diff --git a/.github/workflows/zcode-credential-contract.yml b/.github/workflows/zcode-credential-contract.yml index 1386c74b5db..d5374f037c6 100644 --- a/.github/workflows/zcode-credential-contract.yml +++ b/.github/workflows/zcode-credential-contract.yml @@ -4,10 +4,10 @@ on: types: [opened, synchronize, reopened, ready_for_review, converted_to_draft] paths: - 'src/main/zcode/**' - - 'src/shared/node-bounded-file-reader*' + - 'src/shared/file-content/node-bounded-file-reader*' - 'src/main/rate-limits/**' - - 'src/shared/secure-file*' - - 'src/shared/secure-path-windows-acl*' + - 'src/shared/secure-storage/secure-file*' + - 'src/shared/secure-storage/secure-path-windows-acl*' - 'src/shared/windows-security-descriptor*' - '.github/workflows/zcode-account-contract.yml' - '.github/workflows/zcode-credential-contract.yml' @@ -62,14 +62,14 @@ jobs: fi if [ "$diff_status" = 1 ]; then if git diff --quiet --no-renames HEAD^1 HEAD -- \ - src/main/zcode/ ':(glob)src/shared/node-bounded-file-reader*' src/main/rate-limits/ \ + src/main/zcode/ ':(glob)src/shared/file-content/node-bounded-file-reader*' src/main/rate-limits/ \ .github/workflows/zcode-account-contract.yml \ .github/workflows/zcode-credential-contract.yml \ config/scripts/ci/workflow-contracts/zcode-credential-workflow.test.mjs; then account=false fi if git diff --quiet --no-renames HEAD^1 HEAD -- \ - src/main/zcode/ ':(glob)src/shared/secure-file*' ':(glob)src/shared/secure-path-windows-acl*' \ + src/main/zcode/ ':(glob)src/shared/secure-storage/secure-file*' ':(glob)src/shared/secure-storage/secure-path-windows-acl*' \ ':(glob)src/shared/windows-security-descriptor*' \ .github/workflows/zcode-credential-contract.yml \ config/scripts/ci/workflow-contracts/zcode-credential-workflow.test.mjs; then @@ -90,7 +90,7 @@ jobs: no-cache: true - name: Verify read-only credentials and account changes if: ${{ !cancelled() && steps.scope.outputs.account == 'true' && steps.dependencies.outcome == 'success' && steps.bun.outcome == 'success' }} - run: pnpm test src/main/zcode/zcode-v2-plan-credentials.test.ts src/main/zcode/zcode-v2-personal-overlay-raw-json.test.ts src/main/rate-limits/service-zcode-usage.test.ts src/shared/node-bounded-file-reader-sync.test.ts - - name: Verify rollback and native Windows permissions + run: pnpm test src/main/zcode/zcode-v2-plan-credentials.test.ts src/main/zcode/zcode-v2-personal-overlay-raw-json.test.ts src/main/rate-limits/service-zcode-usage.test.ts src/shared/file-content/node-bounded-file-reader-sync.test.ts + - name: Verify rollback and secure storage if: ${{ !cancelled() && steps.scope.outputs.credentials == 'true' && steps.dependencies.outcome == 'success' && steps.bun.outcome == 'success' }} - run: pnpm test src/main/zcode/zcode-plan-api-key-store.test.ts src/main/zcode/zcode-plan-api-key-store-plaintext-rollback.test.ts src/main/zcode/zcode-plan-api-key-store-publication-race.test.ts src/main/zcode/zcode-plan-api-key-store-native-windows.test.ts src/shared/secure-file.test.ts + run: pnpm test src/main/zcode/zcode-plan-api-key-store.test.ts src/main/zcode/zcode-plan-api-key-store-plaintext-rollback.test.ts src/shared/secure-storage/secure-file.test.ts diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 29c1d5a916a..1adeb33cd86 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -309,7 +309,6 @@ 1 test-no-real-time-wait:src/renderer/src/components/terminal-pane/layout/split/resolve-split-cwd.test.ts 1 test-no-real-time-wait:src/renderer/src/components/terminal-pane/viewport/terminal-fit-restore.test.ts 1 test-no-real-time-wait:src/renderer/src/hooks/runtime-project-refresh-scheduler.test.ts -2 test-no-real-time-wait:src/renderer/src/lib/execute-open-editor-path-move.test.ts 1 test-no-real-time-wait:src/renderer/src/lib/agent-session/resume/cli-fork/native-chat-cli-fork-preparation.test.ts 1 test-no-real-time-wait:src/renderer/src/lib/orca-yaml-trust-prompt-slot-eviction.test.ts 2 test-no-real-time-wait:src/renderer/src/store/slices/workspace-cleanup/workspace-cleanup-removal-preflight.test.ts @@ -321,7 +320,6 @@ 1 test-no-real-time-wait:src/shared/git/status/git-branch-line-total-soft-deadline.test.ts 2 test-no-real-time-wait:src/shared/remote-runtime/control/remote-runtime-shared-control-auth-refusal.test.ts 1 test-no-real-time-wait:src/shared/remote-runtime/control/remote-runtime-shared-control-standing-intent.test.ts -1 test-no-real-time-wait:src/shared/secure-path-windows-acl.win32.test.ts 1 test-no-real-time-wait:src/shared/setup-agent-sequencing-codex-no-daemon.test.ts 2 test-no-real-time-wait:src/shared/setup-agent-sequencing.test.ts 2 test-no-real-time-wait:src/shared/startup-command-staging.node-pty.test.ts @@ -964,7 +962,6 @@ 1 test-timeout-needs-reason:tests/e2e/paired-mobile-serve-restart-terminal-tabs.spec.ts 1 test-timeout-needs-reason:tests/e2e/paired-pane-title-desktop-host.spec.ts 1 test-timeout-needs-reason:tests/e2e/paired-preview-address-bar-convergence.spec.ts -2 test-timeout-needs-reason:tests/e2e/paired-quick-open-large-tree.spec.ts 1 test-timeout-needs-reason:tests/e2e/paired-remote-browser-ghost-subscriber-rejoin.spec.ts 1 test-timeout-needs-reason:tests/e2e/paired-remote-browser-link-open-routing.spec.ts 2 test-timeout-needs-reason:tests/e2e/paired-remote-browser-stream-reconnect.spec.ts diff --git a/config/main-sync-spawn-baseline.txt b/config/main-sync-spawn-baseline.txt index 2eeeca72ab7..e18069dc0c4 100644 --- a/config/main-sync-spawn-baseline.txt +++ b/config/main-sync-spawn-baseline.txt @@ -45,4 +45,4 @@ 2 src/main/pty/shell-startup/zsh-startup-hook-pty-harness.ts 1 src/shared/fish-binary-requirement.ts 1 src/shared/openssh-default-shell.ts -1 src/shared/secure-file.ts +1 src/shared/secure-storage/secure-file.ts diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index ce9f07a7aef..1d5fbc03efe 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -4522,20 +4522,19 @@ "oracle": "Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2043: Remove the registration-wait, webview-security, preview-authorization, guest-lifecycle and grant-IPC unit suites and the sibling-directory assertion reference. Runtime and browser capability consumers also lose removed imported examples. Remaining document-policy, file-reader and grant-registry assertions do not replace those alarms. Preserve the 27 independent dated receipts at their original unchanged selectors; reduced prospective unit selectors have no fresh result or equivalent replacement claim. Historical prior account (preserved verbatim): Audit1973: Delete the browser RPC forwarding/schema/scalar suite and its prospective selector. Preserve all27 unrelated dated receipts; no actual browser operation alarm is replaced. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): The complete terminal-file-link-actions suite is removed. Lose supplied local/remote menu-row inventories, browser label/order/download/reveal callback forwarding, platform-copy and source-group pinning examples. No OS reveal/download, real remote preview or browser navigation was exercised; the other real document-preview sources are not equivalent replacements. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1709 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1687 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1421 narrows renderer unit coverage as recorded in coverageNotes. Prior oracle descriptions are historical for the changed suite. The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Retained unchanged-selector receipts are the only current execution evidence. Reduced-source assertions await validation. Historical prior oracle: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): In paired Electron, write an HTML fixture that declares its own title on the host, invoke the Explorer preview action on the client, and require the document text to be readable out of the orca-preview guest before judging any absence. With that presence established, require the client to hold exactly one browser workspace more than its baseline and that workspace to be the document one: page and tab url blank, the document path mirrored onto both, the tab named by the document's title, the chip naming the file, no editor row of the retired preview species anywhere, and the guest URL carrying the orca-preview scheme. Ask the host through its own page registry as well as through the tab snapshot, and in the same run open an ordinary URL browser tab from the same client and require that one to arrive in both — the presence precondition without which “the host gained nothing” is satisfied just as well by an oracle that cannot see browser pages at all. Require the preview to sit in a group other than the source editor's while the active group and tab remain the source editor's. Then click away to the terminal, click the preview tab, require it to reactivate and still render, close it with its own X, and require the document tab to be gone while the host still holds only the URL tab and the source group, source editor and terminal survive. Quit the client with a document tab open and relaunch it on the same profile: require the same workspace row to come back, blank and named by the document, rendering the document again over a grant URL that differs from the one that was quit, with no preview-scheme or document-named page anywhere in what the host holds. Prove the halves are live by flipping one product property at a time and requiring the run to fail: publish document workspaces to the host like ordinary ones, and stop mirroring the document onto the workspace row. Have the fixture document attempt its own egress on every load — an unattended window.open and location.href to an off-machine URL, plus an inline ICE gathering probe — and require the same baseline counts and a candidate count of zero, so the document's own attempts are measured rather than assumed. Then, as a separate phase after the close oracle has already run, bring the client window to the front, press the document's heading with a real mouse event, and require the document to report that the same press drove it to attempt a second window.open and location.href while both browser counts stay at that phase's baseline and nothing routes — the case a recent-input gate cannot distinguish from the press's own effect. Only then press the target=_blank link with a real mouse event and require both a recorded routing call that returned success and a browser count above that baseline, with the preview tab still open. Drive the preload's click policy as a unit oracle over a real document: a dispatched click, a trusted press on an external anchor, an anchor reached through what it wraps, an SVG animated href, a sibling preview link, fragment and percent-encoded fragment targets, a bare hash, and a middle click. Create a browser page located by a workspace document, handing creation a live grant URL, and require its stored url, its mirrored tab url and the written session payload all to be blank with no orca-preview string anywhere in what was written, while an ordinary page created the same way keeps the URL it was given and asks for the address bar the document page never does. Parse the written page and tab through the session schema and require the document to survive both halves. Hydrate them back and require the document page to return blank and still named — including when its page row was salvaged away and only the tab's own copy remains, and when a foreign session carried a grant URL into both rows. Drive the mirror across a page switch out of the document and back, and across a repair in which the document is the only mirrored field that differs. Name a document page from its document and require the tab to take that name, name it with an empty title and require the file, name it with a live grant URL and require the file again with no preview scheme anywhere in the written session, and require an ordinary blank browser tab beside it to still be called New Tab. Dispatch a title update out of a rendered preview's own guest and require it to reach the page state while the identity chip still reads the document's workspace-relative path. Attach a browsing guest and a workspace-document guest through the same method in one run and require the browsing one to take clicked-link routing, popup handling and auth-identity detach tracking while the document guest takes none of them, stays inside the grant it is showing, denies every window it asks for, and is dropped from the page-keyed document registry by the same teardown that frees its id for a later attach. Register a browsing guest and attach a workspace-document guest in one run against the real manager, require the one door to answer each page with the guest of its own half, and require the document page to be absent from the browsing map and from its enumeration. Drive both browsing registration entry points with a page the document half already holds and require them to register nothing, and drive the mint channel with a page the browsing half already holds and require it to refuse; and drive the offscreen one with a guest that is missing and with one already destroyed, requiring the same refusal. Arm a grab on a live preview target, drive the unregister channel at that same target in the window before the queued operation runs, and require the grab to reach the guest anyway — then drive the same sequence for an ordinary browser page and require its grab state to be disposed after all. Hold one viewport-bridge op open, queue a second behind it, swap the page's guest while that second op waits, and require the injection to land in the guest the page has then. Revoke a grant after a tool has run against its page and require that page's grab state to be cancelled and disposed. Ask a tool for a document page whose guest has not attached, require the request to park in the registration wait, attach the guest, and require the same request to arm on it; require a page nothing ever renders to answer not-ready once that wait elapses. With a document open, ask a tool for a browsing page id and require it to be answered by the browsing half or not at all, with the same channel reaching the document guest under the page it really renders. Drive open-externally for a document whose per-file owner is remote while the workspace-scoped owner is unresolved, for a runtime-owned worktree whose preview tab carries no runtime id of its own, and for a worktree that resolves no runtime owner while the tab still carries one, requiring the download route in each; and for an owner that cannot be resolved at all, and for an unknown workspace root while nothing names another host, requiring a refusal that neither opens nor downloads. Drive the headless backend with a page the document half already holds and require it to reject, destroy the window, and unregister nothing — then shut the backend down and require it still to have unregistered nothing. Navigate a bound preview guest at a second grant through both latch events and require it to stay on the grant it bound to. Mount a preview while a renderer drag is already in flight and require its guest to be click-through at the moment it is appended, not a turn later. Render the editor panel shell in each remaining tab mode and require the path header exactly where the surface does not already name itself. Drive the preview action and require a browser tab located by the document rather than an editor tab, require a second open of the same document to activate the tab it is already in, and require closing that tab to revoke its grant while a URL tab closed beside it revokes none. Publish a worktree holding a document tab and a URL tab and require only the URL tab to reach the mobile snapshot. Install the shared partition policies for a preview partition and for an ordinary browsing partition in the same run, fire each one's own will-download listener, and require the preview's to cancel while the browsing one still reaches the download router — then require the preview protocol installer to be what asks for that deny. In the same run, require the cancelled download to raise a reader-facing notice and the routed one to raise none. require the guest registry to name the bound grant for a live preview guest and nothing for a contents that is not one, has committed no document, or is gone. Drive the shell with a refusal and require one fixed sentence, still one row after three more refusals, standing beside an asset failure rather than being counted with it, gone behind the failure panel, and ignored when it names another preview's grant. Drive the main-side report gate directly for a sender that is no preview guest, a guest with no bound or a revoked grant, a genuine press Electron's webview focus flag misreports as unfocused, and non-web URLs; drive the reader-facing confirmation for accept, cancel, and a confirmed tab the browser refuses; and drive will-attach-webview in both preload directions. Run the per-owner reader, grant-containment, scheme-admission, guest-policy, and plan-routing contracts as unit oracles, including a host-reported truncation, an over-cap binary, and an out-of-worktree paired path. Drive the reader-facing component with the payloads the reader can actually produce — the entry document fails only as truncated or unreadable, a subresource additionally as a refused format — and require the asset case to leave the guest mounted. Drive the closed-tab cleanup hook, the window installer, and the grant IPC handlers directly, requiring the grant to be released when the preview tab closes, cleared at window creation and on a cross-document main-frame navigation, and refused to any sender that is not the trusted renderer. For the browser creations this gate still owns, run the unchanged contract oracle for direct create and side-preview callers with absent status, unknown capabilities, and a mixed-version host, requiring the original unsupported error or visible toast, zero RPCs, and no retained new split; hold a real navigation response beyond the 15-second client deadline after host creation and require the first RPC to return the exact host inventory page ID, one host page, and no retry; repeat reconciliation faults against headless serve and retain the separate exact-page reconciliation rollback oracle.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts src/renderer/src/runtime/web-session-tabs-sync/placement/web-session-tabs-sync-browser-tabs.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/document-preview/doc-preview-grant-registry.test.ts src/main/browser/document-preview/doc-preview-file-reader.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts src/main/browser/document-preview/doc-preview-failure-notice.test.ts src/shared/doc-preview-scheme.test.ts src/renderer/src/lib/doc-preview-grants.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.failure-message.test.tsx src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/document-preview/doc-preview-grant-registry.test.ts src/main/browser/document-preview/doc-preview-file-reader.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts src/main/browser/document-preview/doc-preview-failure-notice.test.ts src/shared/document-preview/doc-preview-scheme.test.ts src/renderer/src/lib/doc-preview-grants.test.ts src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/sessions/browser-session-partition-policies.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/sessions/browser-session-partition-policies.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.failure-message.test.tsx", + "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/sessions/browser-session-partition-policies.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx src/shared/doc-preview-scheme.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx src/shared/document-preview/doc-preview-scheme.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-editor-diff-tabs.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.failure-message.test.tsx", - "pnpm exec vitest run --config config/vitest.config.ts src/preload/doc-preview-link-interception.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts src/main/ipc/browser/browser.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/guest-lifecycle/manager/browser-manager-annotation-bridge.test.ts src/shared/doc-preview-scheme.test.ts src/renderer/src/components/browser-pane/workspace-doc/doc-preview-document-actions.test.ts src/renderer/src/components/browser-pane/workspace-doc/use-doc-preview-guest-tools.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx", - "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/guest-lifecycle/manager/browser-manager-annotation-bridge.test.ts src/main/browser/backends/offscreen-browser-backend-lifecycle.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts src/shared/doc-preview-scheme.test.ts src/renderer/src/components/browser-pane/workspace-doc/doc-preview-document-actions.test.ts src/renderer/src/components/browser-pane/workspace-doc/use-doc-preview-guest-tools.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx", + "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/guest-lifecycle/manager/browser-manager-annotation-bridge.test.ts src/shared/document-preview/doc-preview-scheme.test.ts src/renderer/src/components/browser-pane/workspace-doc/doc-preview-document-actions.test.ts src/renderer/src/components/browser-pane/workspace-doc/use-doc-preview-guest-tools.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx", + "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/guest-lifecycle/manager/browser-manager-annotation-bridge.test.ts src/main/browser/backends/offscreen-browser-backend-lifecycle.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts src/shared/document-preview/doc-preview-scheme.test.ts src/renderer/src/components/browser-pane/workspace-doc/doc-preview-document-actions.test.ts src/renderer/src/components/browser-pane/workspace-doc/use-doc-preview-guest-tools.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/link-actions/LinkActionPopover.test.tsx src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-editor-diff-tabs.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/guest-lifecycle/manager/browser-manager-annotation-bridge.test.ts src/main/browser/backends/offscreen-browser-backend-lifecycle.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts src/shared/doc-preview-scheme.test.ts src/renderer/src/components/browser-pane/workspace-doc/use-doc-preview-guest-tools.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx", + "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/guest-lifecycle/manager/browser-manager-annotation-bridge.test.ts src/main/browser/backends/offscreen-browser-backend-lifecycle.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts src/shared/document-preview/doc-preview-scheme.test.ts src/renderer/src/components/browser-pane/workspace-doc/use-doc-preview-guest-tools.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser/pages/browser-page-conversion.test.ts src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-conversion-publish.test.ts src/renderer/src/lib/workspace-doc-address-input.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx", "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-preview-address-bar-convergence.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=list", "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line", @@ -4558,15 +4557,13 @@ "src/main/browser/document-preview/doc-preview-guest-policy.test.ts", "src/main/browser/document-preview/doc-preview-failure-notice.test.ts", "src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts", - "src/preload/doc-preview-link-interception.test.ts", "src/main/browser/guest-lifecycle/manager/browser-manager-annotation-bridge.test.ts", "src/main/browser/backends/offscreen-browser-backend-lifecycle.test.ts", "src/renderer/src/components/browser-pane/workspace-doc/doc-preview-document-actions.test.ts", "src/renderer/src/components/browser-pane/workspace-doc/use-doc-preview-guest-tools.test.ts", "src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx", - "src/shared/doc-preview-scheme.test.ts", + "src/shared/document-preview/doc-preview-scheme.test.ts", "src/renderer/src/lib/doc-preview-grants.test.ts", - "src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.failure-message.test.tsx", "src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts", "src/renderer/src/components/link-actions/LinkActionPopover.test.tsx", "src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-editor-diff-tabs.test.ts", @@ -4630,22 +4627,6 @@ "file": "src/main/browser/document-preview/doc-preview-failure-notice.test.ts", "assertions": ["413 and 415 map to distinct reasons and everything else stays generic"] }, - { - "file": "src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts", - "assertions": [ - "an external preview link shows the reader its exact destination and becomes a browser tab only after confirmation", - "a declined confirmation opens nothing, and a confirmed tab that is refused or fails outright surfaces instead of being dropped" - ] - }, - { - "file": "src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.failure-message.test.tsx", - "assertions": [ - "each entry-document failure reason surfaces its own sentence instead of one generic unavailable panel", - "a refused subresource names itself in a notice, deduplicated per path, while the document stays rendered", - "an entry-document failure replaces the asset notice with the panel", - "a failure for another preview's grant leaves the rendered document alone" - ] - }, { "file": "src/main/browser/document-preview/doc-preview-guest-policy.test.ts", "assertions": [ @@ -4654,17 +4635,7 @@ ] }, { - "file": "src/preload/doc-preview-link-interception.test.ts", - "assertions": [ - "a click the document dispatched itself is not trusted and routes nothing", - "a trusted press on an external anchor reports it once and stops the navigation, including through what the anchor wraps and an SVG animated href", - "a fragment link scrolls in the document, raw or percent-encoded, and a bare hash goes to the top", - "a sibling preview document is left to the guest's own navigation, and a middle click opens nothing whether or not it is trusted", - "an SVG link is resolved against the document, so its relative, rooted and fragment forms behave exactly like the identical HTML anchor" - ] - }, - { - "file": "src/shared/doc-preview-scheme.test.ts", + "file": "src/shared/document-preview/doc-preview-scheme.test.ts", "assertions": [ "malformed grant ids and unsupported schemes are refused", "undecodable percent escapes are refused" @@ -4822,26 +4793,6 @@ "summary": "Candidate with the sole delta that the preview pane does not hand focus to its guest — the tree as it stood before this change — failed at the target=_blank press: six real presses reached the anchor, the embedder had the webview as its active element, and main's own log answered each report with registered true, grant live, focused false. This is the gap the rewrite found: since previews became browser pages they had no chrome to pass focus on, so the one route out of a preview was shut.", "currentCommand": "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line" }, - { - "date": "2026-08-27", - "runner": "local", - "platform": "macos", - "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.failure-message.test.tsx", - "result": "passed", - "durationSeconds": 1.54, - "summary": "14/14 on the reader-facing failure suite at its relocated path. This and the red run below replace the 2026-08-26 pair recorded against the pre-relocation path (10/10 green, 3/10 red), re-measured today so the entry/subresource split keeps a red half rather than only a green one.", - "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.failure-message.test.tsx" - }, - { - "date": "2026-08-27", - "runner": "local", - "platform": "macos", - "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.failure-message.test.tsx", - "result": "failed", - "durationSeconds": 1.27, - "summary": "Candidate with the sole delta that every failure sets the blocking reason, asset or not, failed 4/14 on the asset-notice assertions — the same mutant the retired 2026-08-26 record measured at 3/10, re-run at the relocated path. A refused subresource must name itself over a document that stays mounted; only the entry document may take the page away.", - "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.failure-message.test.tsx" - }, { "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts", "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser-workspace-doc-location.test.ts src/renderer/src/lib/file-preview.test.ts", @@ -5068,7 +5019,10 @@ "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed.", "Audit2061 (sources2059/2060): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec'); await import('./orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec'); await import('./orca-runtime-tests/worktree-removal-execution-host.spec'); await import('./orca-runtime-tests/terminal-spawn-dispatch.spec'). src/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts: replaces a cwd parsed before late WSL context with the provider cwd; keeps a live WSL cwd that arrives during late-context snapshot recovery; infers local reconstructed WSL context from a WSL UNC worktree; clears stale terminal file URI hostnames after empty-host OSC7 cwd updates; serializes SSH headless OSC7 cwd as POSIX when the desktop runtime is on Windows; keeps Windows SSH OSC7 cwd as a drive path when the desktop runtime is POSIX; serializes Windows SSH headless OSC7 cwd as a drive path on POSIX desktops; infers restored SSH connection identity from app-scoped PTY ids. src/main/runtime/orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec.ts: survives the rebuild that closing a saved editor tab forces; keeps its place in the tab order when the host lists the workspace again; lists tabs to phones in the order desktop clients draw after a rebuild; keeps the place a window gave a chat across a graph resend before the chat is restored. src/main/runtime/orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec.ts: lists every persisted terminal of a windowless host after a cold restart; lists every persisted terminal in the all-worktrees inventory after a cold restart; lists persisted editor tabs beside the terminals after a cold restart; restores a persisted split group layout on the cold rebuild; restores the saved active group of a split even when it is not the first group; falls back to the active tab group when the saved active group was not restored; keeps the headless group active when there is no persisted split; keeps phone and CLI creates in the group they joined across a cold restart. src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts: lists the leftover with its error, though Git no longer does; takes the normal delete once Git registers a checkout at the path again; joins a retry another client started while this Delete listed Git; shows the failed row with its error, not the scan cached before the delete. src/main/runtime/orca-runtime-tests/worktree-removal-execution-host.spec.ts: refuses an SSH row whose host is unreachable instead of deleting here; refuses a runtime row with no nested SSH target rather than deleting locally; refuses a runtime row that also names a nested SSH target; retains runtime purge dispatch in a recovery job; uses the runtime helper override before resuming an interrupted removal; uses the runtime helper override before retrying a failed removal; captures the watcher callback and retains its job-host receiver; reads the current runtime removal queue. src/main/runtime/orca-runtime-tests/terminal-spawn-dispatch.spec.ts: reports the spawn request before it leaves for the pty controller; reports it even when the spawn itself then fails; does not report it when the create fails before any spawn request; captures the admission method before reading the incarnation; captures the record method before evaluating its state object; skips database payload serialization when no database exists; skips a throwing database payload when no database exists; keeps the database method and receiver captured before its payload; captures the canonical map method before a binding getter changes it; completes the captured replacement fence without another map lookup. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed.", "Module layout policy correction: retire the remaining program-status-osc.spec.ts event-projection case (production/mock-derived pane-key oracle) and sign-in timeout case (real setTimeout wait with Date-only fake clocks). The runtime test registrar no longer imports that file. No replacement coverage or fresh execution is claimed for these losses; historical receipts retain their original source scope.", - "Module layout policy correction: retire the two remaining worktree-ps-agent-row-dismissal.spec.ts registrations. The remint/dismissal/exit case computed expected snapshotVersion increments from a production snapshot and used real-clock vi.waitFor; the legacy OSC case derived its expected paneKey from the production layout-owner switch. The runtime registrar no longer imports this file. These public projection scenarios have no replacement coverage or fresh execution claimed; all historical receipts and earlier loss notes retain their original source scope." + "Module layout policy correction: retire the two remaining worktree-ps-agent-row-dismissal.spec.ts registrations. The remint/dismissal/exit case computed expected snapshotVersion increments from a production snapshot and used real-clock vi.waitFor; the legacy OSC case derived its expected paneKey from the production layout-owner switch. The runtime registrar no longer imports this file. These public projection scenarios have no replacement coverage or fresh execution claimed; all historical receipts and earlier loss notes retain their original source scope.", + "D01 candidate audit retires this complete dated receipt because a named test source changes in the candidate overlay. It supplies no new execution or equivalent-coverage claim. Original receipt verbatim:\n{\n \"date\": \"2026-08-27\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.failure-message.test.tsx\",\n \"result\": \"failed\",\n \"durationSeconds\": 1.27,\n \"summary\": \"Candidate with the sole delta that every failure sets the blocking reason, asset or not, failed 4/14 on the asset-notice assertions — the same mutant the retired 2026-08-26 record measured at 3/10, re-run at the relocated path. A refused subresource must name itself over a document that stays mounted; only the entry document may take the page away.\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.failure-message.test.tsx\"\n }", + "D01 candidate audit retires this complete dated receipt because a named test source changes in the candidate overlay. It supplies no new execution or equivalent-coverage claim. Original receipt verbatim:\n{\n \"date\": \"2026-08-27\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.failure-message.test.tsx\",\n \"result\": \"passed\",\n \"durationSeconds\": 1.54,\n \"summary\": \"14/14 on the reader-facing failure suite at its relocated path. This and the red run below replace the 2026-08-26 pair recorded against the pre-relocation path (10/10 green, 3/10 red), re-measured today so the entry/subresource split keeps a red half rather than only a green one.\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.failure-message.test.tsx\"\n }", + "D01 final candidate whole-registration policy removes retired module selectors and obsolete assertion descriptions prospectively. Existing unaffected receipts retain their original scope; reduced selectors have no new execution or equivalent replacement claim. Retired named modules: [\"src/preload/doc-preview-link-interception.test.ts\",\"src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.failure-message.test.tsx\"]. Retired compound assertion refs, preserved as historical data: [{\"file\":\"src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts\",\"assertions\":[\"an external preview link shows the reader its exact destination and becomes a browser tab only after confirmation\",\"a declined confirmation opens nothing, and a confirmed tab that is refused or fails outright surfaces instead of being dropped\"]}]" ], "demotionRule": "Demote if a paired HTML preview creates a browser workspace on either side, renders from anything other than the orca-preview scheme, serves a read the host reported as truncated or over-cap, serves a document without the self-only content security policy, lets the preview session carry an off-machine request, reads an SSH path that canonicalizes outside its grant root, steals focus from the source editor when it opens, removes unrelated editor or terminal state on close, hides a document that rendered because one subresource was refused, leaves a grant readable after the tab or renderer that owns it is gone, mints one for a sender that is not the trusted renderer, opens a browser tab for a navigation the document started with no one at the keyboard, or lets the guest gather an ICE candidate; or if a paired browser creation this gate still owns produces duplicate client or host identities or loses its requested split." }, @@ -13482,13 +13436,13 @@ "oracle": "Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts: delivers remote file changes to listeners for the same worktree. src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts\",\n \"assertions\": [\n \"terminal watcher error and setup failure evict the shared entry before retrying callbacks run\",\n \"an old stream end cannot evict the replacement stream, which still delivers to its listener\",\n \"two same-worktree listeners share a synthetic subscription until the final stop unsubscribes and sends unwatch\"\n ]\n } Historical prior account (preserved verbatim): Audit1973: Delete the standalone mocked watcher cleanup suite and its entire sole-file prospective command. Retire the removed file-command transport-abort alias; preserve the independent cancellation suite and final-overflow/error/end cleanup callback, and13 unrelated receipt objects. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial runtime files-watch suite retains controlled Windows close-event waiting, shared-client survival, late physical-exit ownership/deadline cleanup and shutdown joining. Its combined Windows close/deadline/late-exit alias remains backed by unchanged callbacks. Retire native-error-close, pre-publication setup ownership and failed-delete rearm aliases; associated delegation, failure forwarding, removal routing and recovery examples are lost. These tests inject watch/subscription seams and do not observe an actual native watcher or physical process. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Partial runtime watcher-host suite loses mocked option/event/overflow/resubscription forwarding, supplied teardown-error propagation, aborted-signal/no-call and private ten-thousand-waiter-count inventories. Retire the 10,000-caller bound and failed-recovery-subscriber-ending assertion aliases. Keep same-root owner cancellation, pre-ready replacement, held root-close join, stale-generation recovery delivery and initial failed-root ownership mappings backed by retained real-host callbacks with injected subscription/error/physical-exit promises. No actual native watcher, process termination or resource bound was observed. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1683 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Fill the global watcher-child reservation, require native desktop, paired-runtime, and WSL setup to retain typed transient capacity and retry after one serialized release, then cancel pending desktop and paired-client watches and require no retry. Hold one live anchor while aborting 10,000 callers at the capacity, quarantine-assignment, runtime-root, relay-setup, and SSH-registration layers; require exactly one explicit waiter and one base-promise reaction to remain, then zero after settlement. Hold an old relay unsubscribe, queue one same-root setup leader and one anchor, then abort 10,000 joiners; require every cancellation to settle before teardown releases, exactly one anchor waiter, and only one later physical install. Advance the former paired-web callback deadline while capacity remains full, require cancellation ownership to stay live, publish the server token before ready, and require files.unwatch to abort setup before a later slot release can install a native root. Reject the first ready-watch unwatch with a physical-exit promise, resolve that exit later, and require a fresh physical unwatch attempt, registry release, and exactly one stream end. Fill one healthy shared child with multiple roots, map a standard SSH repository's base, Git common directory, and worktree roots to one relay supervisor, then inject IPC disconnect-before-exit, queued and active cancellation, operations during termination, kill-without-exit, repeated unkillable generations, initial and recovery timeouts, and shard failure. During local and SSH deletion, attempt a late terminal spawn whose worktree identity and cwd name different roots, enumerate a non-prefix remote PTY by authoritative worktree ownership, withhold daemon/relay exit callbacks, make attach positively prove a concurrent-shutdown PID dead, and make the provider unavailable; require every acquired admission to roll back on rejection, dead-PID proof to settle physical exit before reaping, timeout to retain ownership, and Git/filesystem deletion never to start. Require bounded watcher process count, physical-exit settlement, healthy-root recovery, stale-generation rejection, overflow plus later events, and fail-closed destructive cleanup. Verify relay build hashes and remote install probes require both relay.js and relay-watcher.js. Launch the built relay with a real PTY and Parcel watch, kill only the watcher child, and require the same relay PID and PTY to answer before a replacement child delivers overflow and a post-crash event.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-unsubscribe-timeout.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-native-capacity.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-registry.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-launch.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-capacity.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/runtime-watcher-pending-assignment.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/file-watcher-host.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/main/runtime/rpc/methods/files/files-watch-cancellation.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/shared/physical-exit-tracker.test.ts src/shared/promise-settlement-waiters.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-native-capacity.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-registry.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-launch.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-capacity.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/file-watcher-host.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/main/runtime/rpc/methods/files/files-watch-cancellation.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/shared/physical-exit-tracker.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/file-watcher-host.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/file-watcher-host.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/file-watcher-host.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/file-watcher-host.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/file-watcher-host.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-native-capacity.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-registry.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-launch.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-capacity.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/runtime-watcher-pending-assignment.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/main/runtime/rpc/methods/files/files-watch-cancellation.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/shared/physical-exit-tracker.test.ts src/shared/promise-settlement-waiters.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-native-capacity.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-registry.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-launch.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-capacity.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/main/runtime/rpc/methods/files/files-watch-cancellation.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/shared/physical-exit-tracker.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts", "pnpm run build:electron-vite", "node config/scripts/diagnostics/runtime-watchers/runtime-file-watcher-resource-probe.mjs", "node config/scripts/diagnostics/runtime-watchers/runtime-file-watcher-fault-harness.mjs", @@ -13519,7 +13473,6 @@ "src/main/daemon/sessions/testing/session.test.ts", "src/main/daemon/terminal-host/testing/terminal-host.test.ts", "src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts", - "src/main/runtime/files/watch/file-watcher-host.test.ts", "src/main/runtime/files/watch/orca-runtime-files-watch.test.ts", "src/main/runtime/workspaces/removal/worktree-teardown.test.ts", "src/main/runtime/construction/orca-runtime.test.ts", @@ -13620,16 +13573,6 @@ "failed local worktree removal restores every live renderer listener and emits overflow" ] }, - { - "file": "src/main/runtime/files/watch/file-watcher-host.test.ts", - "assertions": [ - "same-root clients share one physical watch and one client abort cannot cancel another owner's setup", - "concurrent pre-ready cancellations join one native root release before an immediate replacement subscribes", - "root-scoped destructive cleanup joins an in-progress subscriber teardown", - "shard failure preserves existing subscribers through isolated recovery and rejects stale-generation events", - "initial setup failure remains discoverable by root-scoped destructive cleanup until physical exit" - ] - }, { "file": "src/main/runtime/files/watch/orca-runtime-files-watch.test.ts", "assertions": [ @@ -13891,7 +13834,8 @@ "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts: delivers remote file changes to listeners for the same worktree. src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts\",\n \"assertions\": [\n \"terminal watcher error and setup failure evict the shared entry before retrying callbacks run\",\n \"an old stream end cannot evict the replacement stream, which still delivers to its listener\",\n \"two same-worktree listeners share a synthetic subscription until the final stop unsubscribes and sends unwatch\"\n ]\n }", "Audit2061 (sources2059/2060): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec'); await import('./orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec'); await import('./orca-runtime-tests/worktree-removal-execution-host.spec'); await import('./orca-runtime-tests/terminal-spawn-dispatch.spec'). src/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts: replaces a cwd parsed before late WSL context with the provider cwd; keeps a live WSL cwd that arrives during late-context snapshot recovery; infers local reconstructed WSL context from a WSL UNC worktree; clears stale terminal file URI hostnames after empty-host OSC7 cwd updates; serializes SSH headless OSC7 cwd as POSIX when the desktop runtime is on Windows; keeps Windows SSH OSC7 cwd as a drive path when the desktop runtime is POSIX; serializes Windows SSH headless OSC7 cwd as a drive path on POSIX desktops; infers restored SSH connection identity from app-scoped PTY ids. src/main/runtime/orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec.ts: survives the rebuild that closing a saved editor tab forces; keeps its place in the tab order when the host lists the workspace again; lists tabs to phones in the order desktop clients draw after a rebuild; keeps the place a window gave a chat across a graph resend before the chat is restored. src/main/runtime/orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec.ts: lists every persisted terminal of a windowless host after a cold restart; lists every persisted terminal in the all-worktrees inventory after a cold restart; lists persisted editor tabs beside the terminals after a cold restart; restores a persisted split group layout on the cold rebuild; restores the saved active group of a split even when it is not the first group; falls back to the active tab group when the saved active group was not restored; keeps the headless group active when there is no persisted split; keeps phone and CLI creates in the group they joined across a cold restart. src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts: lists the leftover with its error, though Git no longer does; takes the normal delete once Git registers a checkout at the path again; joins a retry another client started while this Delete listed Git; shows the failed row with its error, not the scan cached before the delete. src/main/runtime/orca-runtime-tests/worktree-removal-execution-host.spec.ts: refuses an SSH row whose host is unreachable instead of deleting here; refuses a runtime row with no nested SSH target rather than deleting locally; refuses a runtime row that also names a nested SSH target; retains runtime purge dispatch in a recovery job; uses the runtime helper override before resuming an interrupted removal; uses the runtime helper override before retrying a failed removal; captures the watcher callback and retains its job-host receiver; reads the current runtime removal queue. src/main/runtime/orca-runtime-tests/terminal-spawn-dispatch.spec.ts: reports the spawn request before it leaves for the pty controller; reports it even when the spawn itself then fails; does not report it when the create fails before any spawn request; captures the admission method before reading the incarnation; captures the record method before evaluating its state object; skips database payload serialization when no database exists; skips a throwing database payload when no database exists; keeps the database method and receiver captured before its payload; captures the canonical map method before a binding getter changes it; completes the captured replacement fence without another map lookup. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed.", "Module layout policy correction: retire the remaining program-status-osc.spec.ts event-projection case (production/mock-derived pane-key oracle) and sign-in timeout case (real setTimeout wait with Date-only fake clocks). The runtime test registrar no longer imports that file. No replacement coverage or fresh execution is claimed for these losses; historical receipts retain their original source scope.", - "Module layout policy correction: retire the two remaining worktree-ps-agent-row-dismissal.spec.ts registrations. The remint/dismissal/exit case computed expected snapshotVersion increments from a production snapshot and used real-clock vi.waitFor; the legacy OSC case derived its expected paneKey from the production layout-owner switch. The runtime registrar no longer imports this file. These public projection scenarios have no replacement coverage or fresh execution claimed; all historical receipts and earlier loss notes retain their original source scope." + "Module layout policy correction: retire the two remaining worktree-ps-agent-row-dismissal.spec.ts registrations. The remint/dismissal/exit case computed expected snapshotVersion increments from a production snapshot and used real-clock vi.waitFor; the legacy OSC case derived its expected paneKey from the production layout-owner switch. The runtime registrar no longer imports this file. These public projection scenarios have no replacement coverage or fresh execution claimed; all historical receipts and earlier loss notes retain their original source scope.", + "D01 final candidate whole-registration policy removes retired module selectors and obsolete assertion descriptions prospectively. Existing unaffected receipts retain their original scope; reduced selectors have no new execution or equivalent replacement claim. Retired named modules: [\"src/main/runtime/files/watch/file-watcher-host.test.ts\"]. Retired compound assertion refs, preserved as historical data: []" ], "demotionRule": "Demote or quarantine if the fault harness flakes without a product or harness bug, if healthy operation exceeds one runtime watcher child, if total physical operation exceeds eight children including retiring generations, if quarantine children outlive their roots or repeat after fusing, if event delivery becomes unbounded, or if metadata/stat work returns to the serve process." }, diff --git a/config/scripts/ci/unit-selection/dependency-graph/ci-unit-input-ownership.json b/config/scripts/ci/unit-selection/dependency-graph/ci-unit-input-ownership.json index 1830a8fd896..7a0fefadf3b 100644 --- a/config/scripts/ci/unit-selection/dependency-graph/ci-unit-input-ownership.json +++ b/config/scripts/ci/unit-selection/dependency-graph/ci-unit-input-ownership.json @@ -73,14 +73,6 @@ "reason": "Reviewed data/URL parsing only; no indirect repository input. Imported source dependencies remain graph edges.", "contextSha256": "747ec5af67a0b60890da900a83fa255d3b96e2fa17d9199f8e483ef5051b213c" }, - { - "file": "src/shared/doc-preview-scheme.ts", - "inputs": [], - "emptyEnv": [], - "reason": "Reviewed URL/data projection only; no indirect repository reads. The entire local source closure and dependency/runtime context are fingerprinted.", - "contextSha256": "747ec5af67a0b60890da900a83fa255d3b96e2fa17d9199f8e483ef5051b213c", - "sourceClosureSha256": "4a3a0dab2fc5b009d4e4e0d6bb5ba49dae08726f3d94fa83c54283f21f8df097" - }, { "file": "src/shared/node-dist-mirror.ts", "inputs": [], diff --git a/config/scripts/performance/renderer-projection/quick-open-exclusion-benchmark.mjs b/config/scripts/performance/renderer-projection/quick-open-exclusion-benchmark.mjs index 987518f0518..f47b34c30f6 100644 --- a/config/scripts/performance/renderer-projection/quick-open-exclusion-benchmark.mjs +++ b/config/scripts/performance/renderer-projection/quick-open-exclusion-benchmark.mjs @@ -3,7 +3,7 @@ import { performance } from 'node:perf_hooks' import { build } from 'esbuild' const bundled = await build({ - entryPoints: ['src/shared/quick-open-filter.ts'], + entryPoints: ['src/shared/quick-open/quick-open-filter.ts'], bundle: true, platform: 'node', format: 'esm', diff --git a/config/scripts/runtime-verification/ephemeral-store/run-ephemeral-vm-runtime-store-rollback-repro.mjs b/config/scripts/runtime-verification/ephemeral-store/run-ephemeral-vm-runtime-store-rollback-repro.mjs index dea39ba327b..d9cfff77026 100644 --- a/config/scripts/runtime-verification/ephemeral-store/run-ephemeral-vm-runtime-store-rollback-repro.mjs +++ b/config/scripts/runtime-verification/ephemeral-store/run-ephemeral-vm-runtime-store-rollback-repro.mjs @@ -1,8 +1,9 @@ -import { mkdtempSync, mkdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' +import { mkdtempSync, mkdirSync, rmSync, symlinkSync } from 'node:fs' import { tmpdir } from 'node:os' import { join, resolve } from 'node:path' import { spawnSync } from 'node:child_process' import process from 'node:process' +import { copyScriptWithLocalModules } from '../../test-fixtures/script-copy-closure/script-module-dependencies.mjs' const BASELINE_COMMIT = 'bf0c77d5bc800e19117084c27fd1441eda9134ad' const AFFECTED_MAIN_COMMIT = '25abb9368d98ad84a174f530e02f4228d2269062' @@ -17,7 +18,7 @@ try { const baselineRoot = extractSource(BASELINE_COMMIT, 'baseline') const affectedRoot = extractSource(AFFECTED_MAIN_COMMIT, 'affected-main') const revertedRoot = extractSource('HEAD', 'candidate-reverted') - restoreAffectedStoreFiles(revertedRoot) + restoreAffectedStoreFiles(revertedRoot, affectedRoot) const baselineData = makeDataDir('baseline-data') runOracle('baseline write', baselineRoot, 'write-legacy', baselineData) @@ -70,15 +71,12 @@ function extractSource(commit, name) { return destination } -function restoreAffectedStoreFiles(destination) { - for (const relativePath of [ - 'src/shared/ephemeral-vm-runtime-store.ts', - 'src/shared/ephemeral-vm-runtimes.ts' - ]) { - const result = run('git', ['show', `${AFFECTED_MAIN_COMMIT}:${relativePath}`], { - encoding: 'utf8' - }) - writeFileSync(join(destination, relativePath), result.stdout) +function restoreAffectedStoreFiles(destination, affectedRoot) { + for (const name of ['ephemeral-vm-runtime-store.ts', 'ephemeral-vm-runtimes.ts']) { + copyScriptWithLocalModules( + join(affectedRoot, 'src/shared', name), + join(destination, 'src/shared') + ) } } diff --git a/config/scripts/static-analysis/process-boundaries/check-main-sync-spawn-ratchet.mjs b/config/scripts/static-analysis/process-boundaries/check-main-sync-spawn-ratchet.mjs index 6c57ea4cee8..92730a85a81 100644 --- a/config/scripts/static-analysis/process-boundaries/check-main-sync-spawn-ratchet.mjs +++ b/config/scripts/static-analysis/process-boundaries/check-main-sync-spawn-ratchet.mjs @@ -25,7 +25,7 @@ const GATED_FAMILIES = [ }, { modules: ['@orca/process-host'], advice: { runProcessSync: PROCESS_ADVICE } }, { - modules: ['src/shared/secure-path-windows-acl'], + modules: ['src/shared/secure-storage/secure-path-windows-acl'], advice: { restrictWindowsPathSync: SECURE_ADVICE } }, { diff --git a/config/scripts/static-analysis/process-boundaries/check-main-sync-spawn-ratchet.test.mjs b/config/scripts/static-analysis/process-boundaries/check-main-sync-spawn-ratchet.test.mjs index ffe3c729204..01fce47e89b 100644 --- a/config/scripts/static-analysis/process-boundaries/check-main-sync-spawn-ratchet.test.mjs +++ b/config/scripts/static-analysis/process-boundaries/check-main-sync-spawn-ratchet.test.mjs @@ -71,7 +71,7 @@ describe('main sync-spawn ratchet', () => { ['getWslHome', 'listWslDistros'] ], [ - "import * as acl from '..\\\\shared\\\\secure-path-windows-acl'\nacl.restrictWindowsPathSync(p, true)", + "import * as acl from '..\\\\shared\\\\secure-storage\\\\secure-path-windows-acl'\nacl.restrictWindowsPathSync(p, true)", 1, ['restrictWindowsPathSync'] ], @@ -148,7 +148,7 @@ describe('main sync-spawn ratchet', () => { it('fails a lowered or stale count until it is pruned, and prune never raises', () => { const write = - "import { restrictWindowsPathSync } from '../shared/secure-path-windows-acl'\nrestrictWindowsPathSync(a, b)\n" + "import { restrictWindowsPathSync } from '../shared/secure-storage/secure-path-windows-acl'\nrestrictWindowsPathSync(a, b)\n" const root = tree({ 'src/main/store.ts': write, 'src/main/clean.ts': 'export const done = true\n', diff --git a/config/scripts/test-fixtures/script-copy-closure/script-module-dependencies.mjs b/config/scripts/test-fixtures/script-copy-closure/script-module-dependencies.mjs index a5726dac4f4..54fa87df199 100644 --- a/config/scripts/test-fixtures/script-copy-closure/script-module-dependencies.mjs +++ b/config/scripts/test-fixtures/script-copy-closure/script-module-dependencies.mjs @@ -1,4 +1,4 @@ -import { copyFileSync, mkdirSync, readFileSync } from 'node:fs' +import { copyFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs' import { dirname, join, relative } from 'node:path' // Walk/copy relative modules instead of maintaining fixture list: omitted dependencies hide target failures behind resolution errors. @@ -22,7 +22,9 @@ function collectScriptModules(scriptPath, seen = new Set()) { /(?:\bfrom|\brequire\s*\(|\bimport\s*\(|\bimport)\s*'(\.\.?\/[^']+)'/g ) for (const [, specifier] of specifiers) { - collectScriptModules(join(dirname(scriptPath), specifier), seen) + const modulePath = join(dirname(scriptPath), specifier) + const resolved = [modulePath, `${modulePath}.ts`].find((file) => existsSync(file)) ?? modulePath + collectScriptModules(resolved, seen) } return seen } diff --git a/config/scripts/test-fixtures/script-copy-closure/script-module-dependencies.test.mjs b/config/scripts/test-fixtures/script-copy-closure/script-module-dependencies.test.mjs index 451062ff41e..7e0a827a2ff 100644 --- a/config/scripts/test-fixtures/script-copy-closure/script-module-dependencies.test.mjs +++ b/config/scripts/test-fixtures/script-copy-closure/script-module-dependencies.test.mjs @@ -33,10 +33,7 @@ describe('copyScriptWithLocalModules', () => { it('preserves parent paths for modules shared with the runtime', () => { const sourceDir = sourceTree({ 'runtime.ts': 'export const value = 42\n' }) mkdirSync(join(sourceDir, 'scripts')) - writeFileSync( - join(sourceDir, 'scripts', 'entry.mjs'), - "export { value } from '../runtime.ts'\n" - ) + writeFileSync(join(sourceDir, 'scripts', 'entry.mjs'), "export { value } from '../runtime'\n") const destinationRoot = mkdtempSync(join(fixtureDir, 'dest-')) copyScriptWithLocalModules( join(sourceDir, 'scripts', 'entry.mjs'), diff --git a/config/scripts/workflow/source-routing/pr-e2e-source-routing.mjs b/config/scripts/workflow/source-routing/pr-e2e-source-routing.mjs index a18599fdc2b..509507aa49f 100644 --- a/config/scripts/workflow/source-routing/pr-e2e-source-routing.mjs +++ b/config/scripts/workflow/source-routing/pr-e2e-source-routing.mjs @@ -431,15 +431,6 @@ export const PR_E2E_SOURCE_ROUTES = [ file ) }, - { - id: 'quick-open.paired-host-path-search', - specs: ['tests/e2e/paired-quick-open-large-tree.spec.ts'], - matches: (file) => - isProductSource(file) && - /^(?:src\/main\/ipc\/filesystem-(?:list-files|search-file-paths)\.ts|src\/main\/ripgrep\/bundled-ripgrep-path\.ts|src\/main\/providers\/(?:filesystem-provider-contract|ssh-filesystem-provider(?:-capabilities)?)\.ts|src\/main\/runtime\/(?:orca-runtime-files|rpc\/methods\/files)\.ts|src\/renderer\/src\/(?:components\/(?:QuickOpen|quick-open-file-list|quick-open-search)\.tsx?|runtime\/(?:files\/search\/runtime-file-search-client|runtime-legacy-quick-open-inventory)\.ts)|src\/shared\/(?:quick-open-(?:install-rg|path-search|transport-budget)|ripgrep-process-availability|bundled-ripgrep)\.ts)$/.test( - file - ) - }, { id: 'terminal-session.host-cold-park-stream-continuity', specs: ['tests/e2e/host-parked-pane-remote-viewer.spec.ts'], diff --git a/config/scripts/workflow/source-routing/pr-editor-preview-e2e-source-routes.mjs b/config/scripts/workflow/source-routing/pr-editor-preview-e2e-source-routes.mjs index 2f161b87edc..20e97e8d2f9 100644 --- a/config/scripts/workflow/source-routing/pr-editor-preview-e2e-source-routes.mjs +++ b/config/scripts/workflow/source-routing/pr-editor-preview-e2e-source-routes.mjs @@ -55,7 +55,7 @@ export const PR_EDITOR_PREVIEW_E2E_SOURCE_ROUTES = [ 'src/preload/api/fs-bridge.ts', 'src/renderer/src/runtime/files/reads/runtime-file-range-preview.ts', 'src/renderer/src/runtime/files/reads/runtime-file-read-client.ts', - 'src/shared/file-preview-kind.ts' + 'src/shared/file-preview/file-preview-kind.ts' ].includes(file)) }, { diff --git a/config/scripts/workflow/source-routing/pr-package-test-paths.mjs b/config/scripts/workflow/source-routing/pr-package-test-paths.mjs index 99a1d873b3b..97827a96536 100644 --- a/config/scripts/workflow/source-routing/pr-package-test-paths.mjs +++ b/config/scripts/workflow/source-routing/pr-package-test-paths.mjs @@ -150,7 +150,6 @@ export function isCloudTestRunnerInput(file) { // The package (windows) job's "Test Windows-specific boundaries" step runs exactly these files. export const WINDOWS_BOUNDARY_TESTS = [ - 'src/main/zcode/zcode-plan-api-key-store-native-windows.test.ts', 'config/scripts/native-build/node-addons/rebuild-native-deps.test.mjs', 'config/scripts/native-build/node-addons/rebuild-native-deps-windows-process-tree.test.mjs', 'config/scripts/native-build/node-addons/rebuild-native-deps-node-pty.test.mjs', @@ -212,8 +211,7 @@ export const WINDOWS_BOUNDARY_TESTS = [ 'src/main/startup/windows-std-handle-inheritance.win32.test.ts', 'src/main/startup/windows-isolated-spawner.win32.test.ts', 'src/main/runtime/workspaces/catalog/worktree-scan-admin-fingerprint-gate.test.ts', - 'src/shared/secure-file-fsync-flags.test.ts', - 'src/shared/secure-path-windows-acl.win32.test.ts', + 'src/shared/secure-storage/secure-path-windows-acl.win32.test.ts', 'src/main/runtime/rpc/server/pairing/unreadable-secret-store-preservation.win32.test.ts', 'src/main/ipc/preflight-provider-command-selection.test.ts', 'src/main/ipc/preflight-runnable-local-cli.test.ts', diff --git a/mobile/src/components/MobileSvgPreview.tsx b/mobile/src/components/MobileSvgPreview.tsx index 86e537d8b93..ae0125ee567 100644 --- a/mobile/src/components/MobileSvgPreview.tsx +++ b/mobile/src/components/MobileSvgPreview.tsx @@ -1,6 +1,9 @@ import { useMemo, useState } from 'react' import { StyleSheet, View } from 'react-native' -import { readSvgIntrinsicSize, svgMarkupDataUri } from '../../../src/shared/svg-document' +import { + readSvgIntrinsicSize, + svgMarkupDataUri +} from '../../../src/shared/file-preview/svg-document' import { useMobileTranslation } from '../i18n/use-mobile-translation' import { MobileLoadErrorState } from './MobileStateView' import { MobilePanZoomImage } from './MobilePanZoomImage' diff --git a/mobile/src/components/pr-sidebar/MermaidDiagram.tsx b/mobile/src/components/pr-sidebar/MermaidDiagram.tsx index cea411848c9..9d6940c4c6c 100644 --- a/mobile/src/components/pr-sidebar/MermaidDiagram.tsx +++ b/mobile/src/components/pr-sidebar/MermaidDiagram.tsx @@ -5,7 +5,10 @@ import { colors, radii, spacing, typography, pressedStyle } from '../../theme/mo import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme' import { themedStyleSheet } from '../../theme/themed-styles' import { readableMermaidFlowchartSvg } from '../../../../src/shared/mermaid-flowchart-contrast' -import { readSvgIntrinsicSize, svgMarkupDataUri } from '../../../../src/shared/svg-document' +import { + readSvgIntrinsicSize, + svgMarkupDataUri +} from '../../../../src/shared/file-preview/svg-document' import { useMobileTranslation } from '../../i18n/use-mobile-translation' import { MobileNativeChatImageViewer } from '../../session/native-chat/visual/MobileNativeChatImageViewer' import { mermaidDiagramConfig } from './mermaid-diagram-config' diff --git a/mobile/src/files/AttachmentTextScrollView.tsx b/mobile/src/files/AttachmentTextScrollView.tsx index 219bed67b23..56c3c1fe92c 100644 --- a/mobile/src/files/AttachmentTextScrollView.tsx +++ b/mobile/src/files/AttachmentTextScrollView.tsx @@ -3,8 +3,8 @@ import { Platform, ScrollView, Text, View } from 'react-native' import type { AttachmentTextSource, AttachmentTextWindow -} from '../../../src/shared/attachment-text-source' -import { AttachmentTextViewport } from '../../../src/shared/attachment-text-viewport' +} from '../../../src/shared/attachment-text/attachment-text-source' +import { AttachmentTextViewport } from '../../../src/shared/attachment-text/attachment-text-viewport' import { chatAttachmentPreviewStyles as styles } from './mobile-file-preview-styles' function scrollElement(view: ScrollView | null): HTMLElement | null { diff --git a/mobile/src/files/MobileChatAttachmentPreview.tsx b/mobile/src/files/MobileChatAttachmentPreview.tsx index 1582a953711..99db4f1cf0d 100644 --- a/mobile/src/files/MobileChatAttachmentPreview.tsx +++ b/mobile/src/files/MobileChatAttachmentPreview.tsx @@ -8,7 +8,7 @@ import { AttachmentTextScrollView } from './AttachmentTextScrollView' import { SafeAreaView } from 'react-native-safe-area-context' import { useWorkspaceRouteHandoff } from '../navigation/workspace-route-handoff' import { useWorkspaceClient } from '../transport/use-workspace-client' -import { createAttachmentTextPreviewHook } from '../../../src/shared/use-attachment-text-preview' +import { createAttachmentTextPreviewHook } from '../../../src/shared/attachment-text/use-attachment-text-preview' import { chatTextAttachmentName } from '../../../src/shared/native-chat-text-attachment-references' import { MOBILE_BRIDGE_MAX_FRAME_BYTES } from '../../../src/shared/mobile-bridge-frame-bytes' import { useClipboardWriter } from '../platform/clipboard' diff --git a/mobile/src/files/MobileChatAttachmentPreview.web.test.tsx b/mobile/src/files/MobileChatAttachmentPreview.web.test.tsx deleted file mode 100644 index 0e486c62a5c..00000000000 --- a/mobile/src/files/MobileChatAttachmentPreview.web.test.tsx +++ /dev/null @@ -1,607 +0,0 @@ -// @vitest-environment happy-dom -import { act, createElement, type ReactNode } from 'react' -import { createRoot } from 'react-dom/client' -import type { RpcResponse } from '../transport/types' -import type * as ReactNative from 'react-native' -import { expect, it, vi } from 'vitest' -import { MobileChatAttachmentPreview } from './MobileChatAttachmentPreview' -import { activateMobileUiLocale } from '../i18n/mobile-i18n' -import { useMobileFileTapHandlers } from '../session/use-mobile-file-tap-handlers' -import { MobileNativeChatComposerAttachments } from '../session/native-chat/composer/MobileNativeChatComposerAttachments' -import { MobileNativeChatOpenFileContext } from '../session/native-chat/mobile-native-chat-open-file-context' -import { normalizeMobileFilePreviewRouteParams } from './mobile-file-preview-route' - -import { AttachmentTextSource } from '../../../src/shared/attachment-text-source' - -vi.mock('react-native', () => vi.importActual('react-native-web')) -vi.mock('react-native-safe-area-context', () => ({ - SafeAreaView: ({ children }: { children: ReactNode }) => createElement('div', null, children) -})) -vi.mock('../theme/use-mobile-color-scheme', () => ({ useMobileColorScheme: () => 'light' })) -const mocks = vi.hoisted(() => ({ send: vi.fn(), back: vi.fn(), write: vi.fn(), push: vi.fn() })) -vi.mock('../navigation/workspace-route-handoff', () => ({ - useWorkspaceRouteHandoff: () => ({ back: mocks.back, push: mocks.push }) -})) -vi.mock('../platform/clipboard', () => ({ useClipboardWriter: () => ({ writeText: mocks.write }) })) -const client = { - sendRequest: (...args: unknown[]) => mocks.send(...args), - getState: () => 'connected' as const, - getLastConnectedAt: () => 1, - getGeneration: () => 1 -} -vi.mock('../transport/use-workspace-client', () => ({ - useWorkspaceClient: () => ({ client, state: 'connected' }) -})) - -// This full RN-web flow awaits sequential real layouts across dense, elastic and UTF-8 sources. -it( - 'opens the phone attachment card, scrolls the actual RN-web list to its tail and copies eligible complete text', - { timeout: 15_000 }, - async () => { - await activateMobileUiLocale('en') - let viewportHeight = 600 - const children = (node: HTMLElement) => - Array.from(node.children).filter( - (child): child is HTMLElement => child instanceof HTMLElement - ) - const flowChildren = (node: HTMLElement) => - children(node).filter((child) => getComputedStyle(child).position !== 'absolute') - const height = (node: HTMLElement): number => { - const style = getComputedStyle(node) - if (node.style.height.endsWith('px')) { - return Number.parseFloat(node.style.height) - } - if ([style.overflowX, style.overflowY].some((value) => ['auto', 'scroll'].includes(value))) { - return viewportHeight - } - const fixed = Number.parseFloat(style.height) - if (Number.isFinite(fixed)) { - return fixed - } - const children = flowChildren(node).map(height) - return Math.max( - Number.parseFloat(style.minHeight) || 0, - children.length - ? style.flexDirection === 'row' - ? Math.max(...children) - : children.reduce((sum, value) => sum + value, 0) - : node.children.length === 0 && node.textContent - ? 19 - : 0 - ) - } - const width = (node: HTMLElement): number => { - if (node.style.opacity === '0') { - return 8 - } - const value = getComputedStyle(node).width - const fixed = Number.parseFloat(value) - const available = node.parentElement ? width(node.parentElement) : 390 - return Number.isFinite(fixed) - ? value.endsWith('%') - ? (available * fixed) / 100 - : fixed - : available - } - const descriptors = new Map() - const descendantBottom = (node: HTMLElement): number => { - const style = getComputedStyle(node) - return [style.overflow, style.overflowY].some((value) => - ['hidden', 'clip', 'auto', 'scroll'].includes(value) - ) - ? height(node) - : Math.max( - height(node), - ...children(node).map((child) => child.offsetTop + descendantBottom(child)) - ) - } - const metrics = { - offsetHeight: height, - clientHeight: height, - offsetWidth: width, - clientWidth: width, - scrollHeight: (node: HTMLElement) => - Math.max( - height(node), - ...children(node).map((child) => child.offsetTop + descendantBottom(child)) - ), - scrollWidth: (node: HTMLElement) => - Math.max(width(node), ...flowChildren(node).map((child) => child.scrollWidth)), - offsetParent: (node: HTMLElement) => node.parentElement, - offsetLeft: (node: HTMLElement) => Number.parseFloat(getComputedStyle(node).left) || 0, - offsetTop: (node: HTMLElement) => { - const style = getComputedStyle(node) - if (style.position === 'absolute') { - return Number.parseFloat(style.top) || 0 - } - const parent = node.parentElement - if (!parent || getComputedStyle(parent).flexDirection === 'row') { - return 0 - } - const siblings = flowChildren(parent) - return siblings - .slice(0, siblings.indexOf(node)) - .reduce((sum, sibling) => sum + height(sibling), 0) - } - } - for (const [name, measure] of Object.entries(metrics)) { - descriptors.set(name, Object.getOwnPropertyDescriptor(HTMLElement.prototype, name)) - Object.defineProperty(HTMLElement.prototype, name, { - configurable: true, - get(this: HTMLElement) { - return measure(this) - } - }) - } - const positions = new WeakMap() - const nativePositions = new WeakMap() - const horizontal = new WeakMap() - let deliverScroll = true - descriptors.set( - 'scrollLeft', - Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'scrollLeft') - ) - Object.defineProperty(HTMLElement.prototype, 'scrollLeft', { - configurable: true, - get(this: HTMLElement) { - const left = Math.min( - horizontal.get(this) || 0, - Math.max(0, this.scrollWidth - this.clientWidth) - ) - horizontal.set(this, left) - return left - }, - set(this: HTMLElement, value: number) { - horizontal.set(this, Math.max(0, Math.min(value, this.scrollWidth - this.clientWidth))) - } - }) - descriptors.set( - 'scrollTop', - Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'scrollTop') - ) - Object.defineProperty(HTMLElement.prototype, 'scrollTop', { - configurable: true, - get(this: HTMLElement) { - return ( - nativePositions.get(this) ?? - Math.min(positions.get(this) || 0, Math.max(0, this.scrollHeight - this.clientHeight)) - ) - }, - set(this: HTMLElement, value: number) { - nativePositions.delete(this) - const top = Math.max(0, Math.min(value, this.scrollHeight - this.clientHeight)) - if (top !== this.scrollTop) { - positions.set(this, top) - if (deliverScroll) { - queueMicrotask(() => this.dispatchEvent(new Event('scroll'))) - } - } - } - }) - const rect = vi - .spyOn(HTMLElement.prototype, 'getBoundingClientRect') - .mockImplementation(function (this: HTMLElement) { - let x = this.offsetLeft, - y = this.offsetTop - for (let parent = this.parentElement; parent; parent = parent.parentElement) { - x += parent.offsetLeft - parent.scrollLeft - y += parent.offsetTop - parent.scrollTop - } - return new DOMRect(x, y, width(this), height(this)) - }) - const NativeResizeObserver = globalThis.ResizeObserver - vi.stubGlobal( - 'ResizeObserver', - class extends NativeResizeObserver { - constructor(private readonly notify: ResizeObserverCallback) { - super(notify) - } - observe(target: Element) { - super.observe(target) - const box = { - inlineSize: target.getBoundingClientRect().width, - blockSize: target.getBoundingClientRect().height - } - this.notify( - [ - { - target, - contentRect: target.getBoundingClientRect(), - borderBoxSize: [box], - contentBoxSize: [box], - devicePixelContentBoxSize: [box] - } - ], - this - ) - } - } - ) - const path = '/host/agent-session-attachments/12345678-1234-1234-1234-123456789abc/report.txt' - let content = Buffer.from(`${'\n'.repeat(25 * 1024 * 1024)}TAIL`) - const sourceBlocks = vi.spyOn(AttachmentTextSource.prototype, 'block') - const reads: { offset: number; length: number }[] = [] - let hold: Promise | undefined - const held = Promise.withResolvers() - const release = Promise.withResolvers() - mocks.send.mockImplementation( - async ( - method: string, - request?: { offset: number; length: number } - ): Promise => { - if (method === 'status.get') { - return { - id: 's', - ok: true, - result: { capabilities: ['native-chat.text-attachment-read.v1'] } - } - } - if (!request) { - throw new Error('Expected actual range') - } - reads.push(request) - if (hold && request.offset > 0) { - held.resolve() - await hold - } - const part = content.subarray(request.offset, request.offset + request.length) - return { - id: 'r', - ok: true, - result: { - snapshot: 'a'.repeat(64), - size: content.length, - bytesRead: part.length, - contentBase64: part.toString('base64'), - eof: request.offset + part.length === content.length - } - } - } - ) - function Card() { - const handlers = useMobileFileTapHandlers({ - client, - hostId: 'owner', - worktreeId: 'folder:work', - worktreeName: 'Work', - nativeChatSessionId: 's', - structuredAttachments: true, - activeHandleRef: { current: null }, - terminalCwdRef: { current: new Map() }, - openBrowser: vi.fn(), - fetchSessionTabs: async () => {}, - getSessionTabs: () => [], - getActiveSessionTabId: () => 'chat', - getActiveSessionTabType: () => 'agent-session', - switchSessionTab: vi.fn(), - scheduleDelayedAction: vi.fn(), - reportChatTapFailure: vi.fn(), - getSendCompletionGeneration: () => 0 - }) - return createElement( - MobileNativeChatOpenFileContext, - { value: handlers.handleNativeChatFileTap }, - createElement(MobileNativeChatComposerAttachments, { - images: [], - files: [ - { id: 'file', name: 'report.txt', mime: 'text/plain', byteLength: content.length, path } - ] - }) - ) - } - const container = document.createElement('div') - document.body.append(container) - const root = createRoot(container) - const button = (name: string) => { - const element = Array.from(container.querySelectorAll('[role="button"]')).find( - (node) => node.textContent === name - ) - if (!(element instanceof HTMLElement)) { - throw new Error(`Missing ${name}`) - } - return element - } - const flush = () => act(async () => {}) - try { - await act(async () => root.render(createElement(Card))) - const card = container.querySelector('[role="button"]') - if (!(card instanceof HTMLElement)) { - throw new Error('Missing real attachment card') - } - act(() => card.click()) - const route = normalizeMobileFilePreviewRouteParams(mocks.push.mock.calls[0][0].params) - if (!route.ok) { - throw new Error('Expected structured attachment route') - } - expect(route.params.absolutePath).toBe(path) - await act(async () => - root.render(createElement(MobileChatAttachmentPreview, { params: route.params })) - ) - // Supply browser layout, not source results or callbacks; the real list owns scrolling and demand. - const scroller = Array.from(container.querySelectorAll('div')).find((node) => - ['auto', 'scroll'].includes(getComputedStyle(node).overflowY) - ) - if (!(scroller instanceof HTMLElement)) { - throw new Error('Expected actual RN-web scroll host') - } - await vi.waitFor(async () => { - await flush() - expect(scroller.offsetHeight).toBe(viewportHeight) - expect(scroller.offsetWidth).toBeGreaterThan(0) - expect(reads.length).toBeGreaterThan(0) - // Visible rows prove the async RN-web onLayout and initial source publication have settled. - expect( - container.querySelectorAll('[data-testid="attachment-text-segment"]').length - ).toBeGreaterThan(Math.floor(viewportHeight / 19)) - }) - expect(button('Copy').getAttribute('aria-disabled')).toBe('true') - expect(button('Save').getAttribute('aria-disabled')).toBe('true') - const source = sourceBlocks.mock.contexts.at(-1) - if (!(source instanceof AttachmentTextSource)) { - throw new Error('Expected actual source identity') - } - const { AttachmentTextViewport } = - await import('../../../src/shared/attachment-text-viewport') - const track = new AttachmentTextViewport(source, 19, scroller.clientHeight) - await act(async () => { - scroller.scrollTop = track.total - scroller.clientHeight - scroller.dispatchEvent(new Event('scroll')) - }) - await vi.waitFor(async () => { - await flush() - expect(container.textContent).toContain('TAIL') - expect(scroller.scrollTop + scroller.clientHeight).toBe(scroller.scrollHeight) - }) - expect(container.querySelectorAll('input')).toHaveLength(0) - expect(reads.every((request) => request.length <= 16 * 1024)).toBe(true) - expect( - container.querySelectorAll('[data-testid="attachment-text-segment"]').length - ).toBeGreaterThan(0) - expect( - container.querySelectorAll('[data-testid="attachment-text-segment"]').length - ).toBeLessThanOrEqual(Math.ceil(viewportHeight / 19) + 4) - // Discover enough real ranges through scrolling to exercise a compressed physical track. - for (let block = 1; block < 32; block++) { - const current = new AttachmentTextViewport(source, 19, scroller.clientHeight) - if (current.scale < 1) { - break - } - await act(async () => { - scroller.scrollTop = current.position({ block, row: 1 }) - scroller.dispatchEvent(new Event('scroll')) - }) - await vi.waitFor(async () => { - await flush() - expect(source.rowKnown(block)).toBe(true) - }) - } - const compressed = new AttachmentTextViewport(source, 19, scroller.clientHeight) - expect(compressed.scale).toBeLessThan(1) - await act(async () => { - scroller.scrollTop = compressed.total - compressed.height - 1 - scroller.dispatchEvent(new Event('scroll')) - }) - await vi.waitFor(async () => { - await flush() - const rows = Array.from( - container.querySelectorAll('[data-testid="attachment-text-segment"]') - ) - const declared = Number.parseFloat(rows[0]!.parentElement!.style.height) - expect(container.textContent).toContain('TAIL') - expect(Math.max(...rows.map((row) => row.offsetTop + row.offsetHeight))).toBeGreaterThan( - declared - ) - expect(scroller.scrollHeight).toBe(Math.max(scroller.clientHeight, declared)) - }) - await act(async () => { - scroller.scrollTop = 0 - scroller.dispatchEvent(new Event('scroll')) - }) - await act(async () => button('Back').click()) - expect(mocks.back).toHaveBeenCalledOnce() - content = Buffer.from('x'.repeat(96 * 1024)) - await act(async () => - root.render( - createElement(MobileChatAttachmentPreview, { key: 'motion', params: route.params }) - ) - ) - await vi.waitFor(async () => { - await flush() - expect( - container.querySelector('[data-testid="attachment-text-segment"]')?.textContent - ).toBe('x'.repeat(256)) - }) - const motion = Array.from(container.querySelectorAll('div')).find((node) => - ['auto', 'scroll'].includes(getComputedStyle(node).overflowY) - ) - if (!(motion instanceof HTMLElement)) { - throw new Error('Missing actual vertical host') - } - let outer = motion.parentElement - while (outer && !['auto', 'scroll'].includes(getComputedStyle(outer).overflowX)) { - outer = outer.parentElement - } - if (!outer) { - throw new Error('Missing actual horizontal host') - } - const hostScroll = vi.spyOn(motion, 'scrollTo') - try { - outer.scrollLeft = 500 - hold = release.promise - await act(async () => { - motion.scrollTop = 3000 - }) - await held.promise - expect(outer.scrollLeft).toBe(500) - deliverScroll = false - motion.scrollTop += 80 - const live = motion.scrollTop - const calls = hostScroll.mock.calls.length - hold = undefined - await act(async () => release.resolve()) - await vi.waitFor(async () => { - await flush() - expect( - container.querySelector('[data-testid="attachment-text-segment"]')?.textContent - ).toBe('x'.repeat(256)) - }) - expect(hostScroll.mock.calls.length).toBe(calls) - expect(motion.scrollTop).toBe(live) - expect(outer.scrollLeft).toBe(500) - deliverScroll = true - await act(async () => { - motion.scrollTop = 0 - motion.dispatchEvent(new Event('scroll')) - }) - await vi.waitFor(async () => { - await flush() - expect(motion.scrollTop).toBe(0) - expect( - container.querySelector('[data-testid="attachment-text-segment"]')?.textContent - ).toBe('x'.repeat(256)) - }) - expect(outer.scrollLeft).toBe(500) - } finally { - release.resolve() - deliverScroll = true - hostScroll.mockRestore() - } - viewportHeight = 645 - const line = 'Original pasted contents 35636; exact Copy and Save.\n' - const header = `COPY35636-START\n indented\tfield value; whitespace35636\n ${line}` - const tail = '\nCOPY35636-END\n' - content = Buffer.from((header + line.repeat(2000)).slice(0, 98304 - tail.length) + tail) - await act(async () => - root.render( - createElement(MobileChatAttachmentPreview, { key: 'elastic', params: route.params }) - ) - ) - await vi.waitFor(async () => { - await flush() - expect(container.textContent).toContain('COPY35636-START') - }) - const elasticSource = sourceBlocks.mock.contexts.at(-1) - const elastic = Array.from(container.querySelectorAll('div')).find((node) => - ['auto', 'scroll'].includes(getComputedStyle(node).overflowY) - ) - if (!(elasticSource instanceof AttachmentTextSource) || !(elastic instanceof HTMLElement)) { - throw new Error('Missing actual literal source/host') - } - await vi.waitFor(async () => { - await flush() - expect(elastic.clientHeight).toBe(645) - }) - for (let block = 1; block < elasticSource.blockCount; block++) { - const current = new AttachmentTextViewport(elasticSource, 19, elastic.clientHeight) - await act(async () => { - elastic.scrollTop = current.position({ block, row: 1 }) - elastic.dispatchEvent(new Event('scroll')) - }) - await vi.waitFor(async () => { - await flush() - expect(elasticSource.rowKnown(block)).toBe(true) - }) - } - const elasticTrack = new AttachmentTextViewport(elasticSource, 19, elastic.clientHeight) - expect(elasticTrack.total).toBe(35283) - const nativeScroll = async (top: number) => - act(async () => { - nativePositions.set(elastic, top) - elastic.dispatchEvent(new Event('scroll')) - }) - const elasticWrites = vi.spyOn(elastic, 'scrollTo') - try { - const writes = elasticWrites.mock.calls.length - for (const top of [35545, 34931]) { - await nativeScroll(top) - await vi.waitFor(async () => { - await flush() - const rows = Array.from( - container.querySelectorAll('[data-testid="attachment-text-segment"]') - ) - expect(rows[0]?.offsetTop).toBe(34637) - expect(rows.at(-1)!.offsetTop + rows.at(-1)!.offsetHeight).toBe(35283) - expect(elastic.scrollHeight).toBe(35283) - }) - } - await nativeScroll(34638 - 645) - await vi.waitFor(async () => { - await flush() - expect( - container.querySelector('[data-testid="attachment-text-segment"]')! - .offsetTop - ).toBeLessThan(34637) - }) - expect(elasticWrites.mock.calls.length).toBe(writes) - } finally { - elasticWrites.mockRestore() - } - viewportHeight = 600 - content = Buffer.from('🙂'.repeat((25 * 1024 * 1024) / 4)) - await act(async () => - root.render( - createElement(MobileChatAttachmentPreview, { key: 'unicode', params: route.params }) - ) - ) - await vi.waitFor(async () => { - await flush() - const rows = container.querySelectorAll('[data-testid="attachment-text-segment"]') - expect(rows.length).toBeGreaterThanOrEqual(Math.ceil(viewportHeight / 19)) - expect(rows.length).toBeLessThanOrEqual(Math.ceil(viewportHeight / 19) + 4) - expect(rows[0]?.textContent).toBe('🙂'.repeat(256)) - }) - const literal = ' indented\tfield value' - content = Buffer.from(`\ufeffcomplete\r\n${literal}\n🙂`) - await act(async () => - root.render( - createElement(MobileChatAttachmentPreview, { key: 'small', params: route.params }) - ) - ) - await vi.waitFor(async () => { - await flush() - expect(button('Copy').getAttribute('aria-disabled')).not.toBe('true') - const row = Array.from( - container.querySelectorAll('[data-testid="attachment-text-segment"]') - ).find((node) => node.textContent === literal) - if (!(row instanceof HTMLElement)) { - throw new Error('Missing literal indented text row') - } - expect(getComputedStyle(row).whiteSpace).toBe('pre') - }) - await act(async () => button('Copy').click()) - expect(mocks.write).toHaveBeenCalledWith(content.toString('utf8')) - content = Buffer.from('"'.repeat(400_000)) - await act(async () => - root.render( - createElement(MobileChatAttachmentPreview, { key: 'escaped', params: route.params }) - ) - ) - await vi.waitFor(async () => { - await flush() - expect(button('Copy').getAttribute('aria-disabled')).not.toBe('true') - }) - await act(async () => button('Copy').click()) - expect(container.textContent).toContain( - 'Full Copy for this attachment needs the upcoming phone update.' - ) - expect(mocks.write).toHaveBeenCalledTimes(1) - } finally { - release.resolve() - try { - await act(async () => root.unmount()) - } finally { - container.remove() - sourceBlocks.mockRestore() - rect.mockRestore() - for (const [name, descriptor] of descriptors) { - if (descriptor) { - Object.defineProperty(HTMLElement.prototype, name, descriptor) - } else { - Reflect.deleteProperty(HTMLElement.prototype, name) - } - } - vi.unstubAllGlobals() - } - } - } -) diff --git a/mobile/src/files/file-tree.ts b/mobile/src/files/file-tree.ts index 61e3bc9b2ca..eeecd29128e 100644 --- a/mobile/src/files/file-tree.ts +++ b/mobile/src/files/file-tree.ts @@ -1,5 +1,5 @@ -import { MEDIA_FILE_MIME_TYPES } from '../../../src/shared/media-file-extensions' -import { compareFileNames } from '../../../src/shared/file-name-sort' +import { MEDIA_FILE_MIME_TYPES } from '../../../src/shared/file-preview/media-mime-types' +import { compareFileNames } from '../../../src/shared/file-listing/file-name-sort' export type MobileDirEntry = { name: string diff --git a/mobile/src/files/mobile-chat-attachment-read.test.ts b/mobile/src/files/mobile-chat-attachment-read.test.ts deleted file mode 100644 index 9a8db373ab0..00000000000 --- a/mobile/src/files/mobile-chat-attachment-read.test.ts +++ /dev/null @@ -1,125 +0,0 @@ -import { expect, it, vi } from 'vitest' -import { createMobileChatAttachmentReader } from './mobile-chat-attachment-read' -import { AttachmentTextSource } from '../../../src/shared/attachment-text-source' -import { AGENT_SESSION_TEXT_ATTACHMENT_READ_CAPABILITY } from '../../../src/shared/agent-session/agent-session-runtime-capabilities' -import { RpcClientRequestTracker } from '../transport/rpc-client-request-tracker' -import { RpcClientConnectionState } from '../transport/rpc-client-connection-state' -import { createStableLogicalRpcClient } from '../transport/stable-logical-rpc-client' -import { scopeRpcClientToExecutionHost } from '../transport/execution-host-scoped-rpc-client' - -import type { SendRequestOptions } from '../transport/rpc-client' -import type { RpcRequestFrame } from '../transport/rpc-envelope-fields' - -function fixture() { - const state = new RpcClientConnectionState({ - endpoint: 'ws://test35636', - getReconnectAttempt: () => 0, - isClosed: () => false - }) - state.publish('connected') - const frames: RpcRequestFrame[] = [] - const control: { - capable: boolean - holdStatus: boolean - holdBody: boolean - atConnected: (() => void) | undefined - body: unknown - } = { - capable: true, - holdStatus: false, - holdBody: false, - atConnected: undefined, - body: { - snapshot: 'a'.repeat(64), - size: 1, - bytesRead: 1, - contentBase64: 'eA==', - eof: true - } - } - let serial = 0 - let currentMethod = '' - const answer = (frame: RpcRequestFrame, runtimeId = 'successor') => - tracker.resolve({ - id: frame.id, - ok: true, - result: - frame.method === 'status.get' - ? { capabilities: control.capable ? [AGENT_SESSION_TEXT_ATTACHMENT_READ_CAPABILITY] : [] } - : control.body, - _meta: { runtimeId } - }) - const tracker = new RpcClientRequestTracker({ - nextId: () => String(++serial), - getState: () => state.get(), - waitForConnected: (timeout) => { - const connected = state.waitForConnected(timeout) - return currentMethod === 'agentSessionAttachment.readTextChunk' && control.atConnected - ? connected.then(control.atConnected) - : connected - }, - sendFrame: (frame) => { - frames.push(frame) - if (!(frame.method === 'status.get' ? control.holdStatus : control.holdBody)) { - queueMicrotask(() => answer(frame)) - } - return true - } - }) - const physical = { - sendRequest: (method: string, params?: unknown, options?: SendRequestOptions) => { - currentMethod = method - return tracker.sendRequest(method, params, options) - }, - getState: () => state.get(), - getLastConnectedAt: () => state.getLastConnectedAt(), - getReconnectAttempt: () => 0, - onStateChange: (listener: Parameters[0]) => - state.addListener(listener), - notifyForeground: () => {}, - close: () => tracker.rejectAll('closed'), - subscribe: () => () => {}, - updateTerminalSubscriptionViewport: () => {} - } - const logical = createStableLogicalRpcClient(physical, 'lan') - const client = scopeRpcClientToExecutionHost(logical, 'runtime:server35636') - const source = (read = createMobileChatAttachmentReader(client)) => - new AttachmentTextSource('/source35636', read) - const bodyCount = () => - frames.filter((frame) => frame.method === 'agentSessionAttachment.readTextChunk').length - return { state, frames, control, answer, tracker, physical, logical, client, source, bodyCount } -} - -it('settles an abandoned status waiter before release and keeps its same-reader successor pinned', async () => { - const count = 1 - const f = fixture() - f.control.holdStatus = true - const readers = Array.from({ length: count }, () => createMobileChatAttachmentReader(f.client)) - const old = readers.map(f.source) - const pending = old.map((source) => source.block(0).catch((error) => error)) - await vi.waitFor(() => expect(f.frames).toHaveLength(count)) - const held = [...f.frames] - old.forEach((source) => source.dispose()) - expect((await Promise.all(pending)).map((error) => error.name)).toEqual( - Array(count).fill('AbortError') - ) - expect(f.tracker.size()).toBe(0) - f.control.holdStatus = false - const successors = readers.map(f.source) - await Promise.all(successors.map((source) => source.block(0))) - expect(f.bodyCount()).toBe(count) - held.forEach((frame) => expect(f.answer(frame, 'disposed')).toBe(false)) - expect(f.bodyCount()).toBe(count) - expect(await Promise.all(successors.map((source) => source.copyText()))).toEqual( - Array(count).fill('x') - ) - expect(f.frames.every((frame) => !('signal' in frame) && !('beforeSend' in frame))).toBe(true) - expect( - f.frames.every( - (frame) => - JSON.stringify(frame.envelope) === JSON.stringify({ executionHost: 'runtime:server35636' }) - ) - ).toBe(true) - successors.forEach((source) => source.dispose()) - f.logical.close() -}) diff --git a/mobile/src/files/mobile-chat-attachment-read.ts b/mobile/src/files/mobile-chat-attachment-read.ts index a1659543ecd..8f28c3914a1 100644 --- a/mobile/src/files/mobile-chat-attachment-read.ts +++ b/mobile/src/files/mobile-chat-attachment-read.ts @@ -6,7 +6,7 @@ import { rpcResultVariant } from '../transport/rpc-operation-result-reader' import { attachmentTextChunkSchema, type AttachmentTextRead -} from '../../../src/shared/attachment-text-source' +} from '../../../src/shared/attachment-text/attachment-text-source' import type { RpcClient } from '../transport/rpc-client' import type { RpcOperationSender } from '../transport/rpc-operation-sender' diff --git a/mobile/src/files/mobile-diff-image-preview.ts b/mobile/src/files/mobile-diff-image-preview.ts index c5971a2bc96..41599515a67 100644 --- a/mobile/src/files/mobile-diff-image-preview.ts +++ b/mobile/src/files/mobile-diff-image-preview.ts @@ -1,4 +1,4 @@ -import { buildImageDataUri } from '../../../src/shared/image-data-uri' +import { buildImageDataUri } from '../../../src/shared/file-preview/image-data-uri' // Only modifiedDeleted proves deletion; read failures can also return empty modifiedContent with modifiedIsBinary false. // Omit kind: the reply reader admits every non-text arm, including unknown host arms. diff --git a/mobile/src/files/mobile-file-explorer-operations.ts b/mobile/src/files/mobile-file-explorer-operations.ts index c47034570ae..7eb0b589252 100644 --- a/mobile/src/files/mobile-file-explorer-operations.ts +++ b/mobile/src/files/mobile-file-explorer-operations.ts @@ -4,8 +4,8 @@ import type { RpcClient } from '../transport/rpc-client' import { isMobileMethodUnavailableError } from '../transport/mobile-method-unavailable' import { bindDeferredRpcOperation, defineRpcOperation } from '../transport/rpc-operation' import { rpcResultVariant, rpcResultVariants } from '../transport/rpc-operation-result-reader' -import { FILE_READ_DIR_MAX_PAGE_ENTRIES } from '../../../src/shared/file-dir-page' -import { compareDirEntries } from '../../../src/shared/file-name-sort' +import { FILE_READ_DIR_MAX_PAGE_ENTRIES } from '../../../src/shared/file-listing/file-dir-page' +import { compareDirEntries } from '../../../src/shared/file-listing/file-name-sort' import { fileDirectoryEntriesSchema, fileDirectoryPageSchema, diff --git a/mobile/src/files/mobile-file-media.ts b/mobile/src/files/mobile-file-media.ts index ac86eb518ec..c6fbeeddb18 100644 --- a/mobile/src/files/mobile-file-media.ts +++ b/mobile/src/files/mobile-file-media.ts @@ -1,4 +1,4 @@ -import { MEDIA_FILE_MIME_TYPES } from '../../../src/shared/media-file-extensions' +import { MEDIA_FILE_MIME_TYPES } from '../../../src/shared/file-preview/media-mime-types' export const PDF_MIME_TYPE = 'application/pdf' diff --git a/mobile/src/files/mobile-file-mutation-ownership.test.ts b/mobile/src/files/mobile-file-mutation-ownership.test.ts index f612d7ab972..2a815f5ca00 100644 --- a/mobile/src/files/mobile-file-mutation-ownership.test.ts +++ b/mobile/src/files/mobile-file-mutation-ownership.test.ts @@ -1,9 +1,6 @@ import { describe, expect, it, vi } from 'vitest' import type { SshConnectionState } from '../../../src/shared/ssh-types' -import { - FILE_MUTATION_OWNERSHIP_RUNTIME_CAPABILITY, - FILE_MUTATION_OWNERSHIP_UPDATE_REQUIRED_MESSAGE -} from '../../../src/shared/protocol-version' +import { FILE_MUTATION_OWNERSHIP_RUNTIME_CAPABILITY } from '../../../src/shared/file-access/files-runtime-capabilities' import type { RpcClient } from '../transport/rpc-client' import type { RpcResponse } from '../transport/types' import { @@ -70,41 +67,6 @@ describe('mobile file mutation ownership', () => { ) }) - it('captures local ownership only after verifying the runtime capability', async () => { - const { client, sendRequest } = clientWithResponses([ - success({ capabilities: [FILE_MUTATION_OWNERSHIP_RUNTIME_CAPABILITY] }), - success({ worktree: { hostId: 'local' } }) - ]) - - await expect(captureMobileFileMutationOwnership(client, 'id:worktree-1')).resolves.toEqual({ - expectedExecutionHostId: 'local' - }) - expect(sendRequest.mock.calls).toEqual([ - ['status.get', undefined, { timeoutMs: 15_000 }], - ['worktree.show', { worktree: 'id:worktree-1' }, { timeoutMs: 15_000 }] - ]) - }) - - it('captures SSH generation from the HUB before building mutation params', async () => { - const state = sshState('target-1', 9) - const { client, sendRequest } = clientWithResponses([ - success({ capabilities: [FILE_MUTATION_OWNERSHIP_RUNTIME_CAPABILITY] }), - success({ worktree: { hostId: 'ssh:target-1' } }), - success({ state }) - ]) - - await expect(captureMobileFileMutationOwnership(client, 'id:worktree-1')).resolves.toEqual({ - expectedExecutionHostId: 'ssh:target-1', - expectedSshTargetId: 'target-1', - expectedSshConnectionGeneration: 9 - }) - expect(sendRequest.mock.calls[2]).toEqual([ - 'ssh.getState', - { targetId: 'target-1' }, - { timeoutMs: 15_000 } - ]) - }) - // Absent hostId captures local; explicit null refuses an unplaceable host instead of sending its write locally. it('captures local ownership for a workspace whose reply records no host', async () => { const { client } = clientWithResponses([ @@ -127,13 +89,4 @@ describe('mobile file mutation ownership', () => { "Couldn't verify the SSH connection" ) }) - - it('refuses older runtimes before reading or mutating workspace files', async () => { - const { client, sendRequest } = clientWithResponses([success({ capabilities: [] })]) - - await expect(captureMobileFileMutationOwnership(client, 'id:worktree-1')).rejects.toThrow( - FILE_MUTATION_OWNERSHIP_UPDATE_REQUIRED_MESSAGE - ) - expect(sendRequest).toHaveBeenCalledTimes(1) - }) }) diff --git a/mobile/src/files/mobile-file-mutation-ownership.ts b/mobile/src/files/mobile-file-mutation-ownership.ts index 5d38fd002f2..31fd49806ec 100644 --- a/mobile/src/files/mobile-file-mutation-ownership.ts +++ b/mobile/src/files/mobile-file-mutation-ownership.ts @@ -1,5 +1,5 @@ import { parseExecutionHostId } from '../../../src/shared/execution-host' -import { assertFileMutationOwnershipCapability } from '../../../src/shared/file-mutation-ownership' +import { assertFileMutationOwnershipCapability } from '../../../src/shared/file-write/file-mutation-ownership' import type { SshConnectionState, SshMutationExpectation } from '../../../src/shared/ssh-types' import { translate } from '../i18n/mobile-i18n' import { diff --git a/mobile/src/files/mobile-file-tab-doc.ts b/mobile/src/files/mobile-file-tab-doc.ts index bf91203d66e..32b315972d7 100644 --- a/mobile/src/files/mobile-file-tab-doc.ts +++ b/mobile/src/files/mobile-file-tab-doc.ts @@ -1,5 +1,5 @@ import { mobileFileMedia, type MobileFileMedia } from './mobile-file-media' -import { buildImageDataUri } from '../../../src/shared/image-data-uri' +import { buildImageDataUri } from '../../../src/shared/file-preview/image-data-uri' import { classifyMobileArtifact } from '../session/mobile-artifact-kind' import { buildMobileDiffLines, type MobileDiffLine } from '../session/mobile-diff-lines' import { mobileDiffImageDataUri } from './mobile-diff-image-preview' diff --git a/mobile/src/files/mobile-markdown-image-source.ts b/mobile/src/files/mobile-markdown-image-source.ts index e868d26aaeb..e6998850b49 100644 --- a/mobile/src/files/mobile-markdown-image-source.ts +++ b/mobile/src/files/mobile-markdown-image-source.ts @@ -7,7 +7,7 @@ import { routeMarkdownHref } from '../components/markdown-href-routing' import type { MobileFilePreviewRpcSender } from './mobile-file-preview-operations' import { loadMobileFilePreview } from './mobile-file-preview-request' import { classifyMobileArtifact } from '../session/mobile-artifact-kind' -import { svgMarkupDataUri } from '../../../src/shared/svg-document' +import { svgMarkupDataUri } from '../../../src/shared/file-preview/svg-document' // Absolute paths leave the workspace; an external-file tab's document has no workspace images. function isOutsideWorkspace(path: string): boolean { diff --git a/mobile/src/files/mobile-terminal-artifact-grant-refresh.ts b/mobile/src/files/mobile-terminal-artifact-grant-refresh.ts index a97a7eba38b..fc17e224266 100644 --- a/mobile/src/files/mobile-terminal-artifact-grant-refresh.ts +++ b/mobile/src/files/mobile-terminal-artifact-grant-refresh.ts @@ -1,4 +1,4 @@ -import type { RuntimeNativeChatFileContext } from '../../../src/shared/runtime-types' +import type { RuntimeNativeChatFileContext } from '../../../src/shared/native-chat/native-chat-file-context' import type { RpcFailure } from '../transport/types' import { terminalArtifactPathResolve, diff --git a/mobile/src/files/use-mobile-file-explorer-paging.ts b/mobile/src/files/use-mobile-file-explorer-paging.ts index dfba0155583..a1ae9c35940 100644 --- a/mobile/src/files/use-mobile-file-explorer-paging.ts +++ b/mobile/src/files/use-mobile-file-explorer-paging.ts @@ -1,6 +1,6 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useQueryClient } from '@tanstack/react-query' -import { FILE_READ_DIR_MAX_PAGE_ENTRIES } from '../../../src/shared/file-dir-page' +import { FILE_READ_DIR_MAX_PAGE_ENTRIES } from '../../../src/shared/file-listing/file-dir-page' import { hostQueryKey, type HostQueryTarget } from '../query/host-query-key' import { hostReadClient } from '../query/host-read-client' import type { RpcClient } from '../transport/rpc-client' diff --git a/mobile/src/mobile-web-shell/bridge/bridge-image-verbs.ts b/mobile/src/mobile-web-shell/bridge/bridge-image-verbs.ts index 2d6265385e6..3e81928fc60 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-image-verbs.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-image-verbs.ts @@ -1,6 +1,6 @@ import * as z from 'zod' import { CLIPBOARD_IMAGE_MAX_SOURCE_BYTES } from '../../../../src/shared/clipboard-image' -import { isKnownRasterImageMimeType } from '../../../../src/shared/raster-image-preview-limits' +import { isKnownRasterImageMimeType } from '../../../../src/shared/file-preview/raster-image-preview-limits' import { MOBILE_CLIPBOARD_IMAGE_UPLOAD_CHUNK_BASE64_CHARS } from '../../session/mobile-clipboard-image-upload-chunk' // The page cannot reach the clipboard, Photos or the share sheet from the WebView, so it hands the image to the shell. diff --git a/mobile/src/platform/image-actions.web.ts b/mobile/src/platform/image-actions.web.ts index d9a1433545a..bb4127adc3c 100644 --- a/mobile/src/platform/image-actions.web.ts +++ b/mobile/src/platform/image-actions.web.ts @@ -3,9 +3,9 @@ import { agentSessionAttachmentAppends, base64DecodedByteLength } from '../../../src/shared/agent-session/agent-session-attachments' -import { readRasterImageDataUri } from '../../../src/shared/image-data-uri' -import { isKnownRasterImageMimeType } from '../../../src/shared/raster-image-preview-limits' -import { isSvgFilePath } from '../../../src/shared/svg-document' +import { readRasterImageDataUri } from '../../../src/shared/file-preview/image-data-uri' +import { isKnownRasterImageMimeType } from '../../../src/shared/file-preview/raster-image-preview-limits' +import { isSvgFilePath } from '../../../src/shared/file-preview/svg-document' import type { BridgeImageOperation, BridgeImageRunParams diff --git a/mobile/src/platform/native-image-actions.ts b/mobile/src/platform/native-image-actions.ts index bda01f76233..b8b3f8d95e6 100644 --- a/mobile/src/platform/native-image-actions.ts +++ b/mobile/src/platform/native-image-actions.ts @@ -8,7 +8,7 @@ import { CLIPBOARD_IMAGE_MAX_SOURCE_BYTES, CLIPBOARD_IMAGE_TOO_LARGE_ERROR } from '../../../src/shared/clipboard-image' -import { isKnownRasterImageMimeType } from '../../../src/shared/raster-image-preview-limits' +import { isKnownRasterImageMimeType } from '../../../src/shared/file-preview/raster-image-preview-limits' import { imageParamsSchema, type BridgeImageRunParams diff --git a/mobile/src/session/mobile-diff-review-queue.ts b/mobile/src/session/mobile-diff-review-queue.ts index 23112d72dac..0753ee9b709 100644 --- a/mobile/src/session/mobile-diff-review-queue.ts +++ b/mobile/src/session/mobile-diff-review-queue.ts @@ -1,4 +1,4 @@ -import { compareFileNames } from '../../../src/shared/file-name-sort' +import { compareFileNames } from '../../../src/shared/file-listing/file-name-sort' import { translate } from '../i18n/mobile-i18n' import type { DiffComment, diff --git a/mobile/src/session/mobile-file-tap-open.ts b/mobile/src/session/mobile-file-tap-open.ts index a7114ba0d60..90407349b52 100644 --- a/mobile/src/session/mobile-file-tap-open.ts +++ b/mobile/src/session/mobile-file-tap-open.ts @@ -1,8 +1,6 @@ import type { ParsedFileLinkLocation } from '../../../src/shared/file-links/file-link-location' -import type { - RuntimeNativeChatFileContext, - RuntimeTerminalPathResolution -} from '../../../src/shared/runtime-types' +import type { RuntimeNativeChatFileContext } from '../../../src/shared/native-chat/native-chat-file-context' +import type { RuntimeTerminalPathResolution } from '../../../src/shared/terminal/runtime-terminal-file-path' import { filesystemPathToFileUri } from '../../../src/shared/file-links/file-uri-path' import { createMobileFilePreviewHref } from '../files/mobile-file-preview-route' import { classifyMobileArtifact } from './mobile-artifact-kind' diff --git a/mobile/src/session/native-chat/composer/use-mobile-native-chat-file-search.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-file-search.ts index 427f5b2a826..7ac8b7ccd27 100644 --- a/mobile/src/session/native-chat/composer/use-mobile-native-chat-file-search.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-file-search.ts @@ -11,7 +11,7 @@ import { import { getPreparedQuickOpenFiles, rankQuickOpenFiles -} from '../../../../../src/shared/quick-open-path-search' +} from '../../../../../src/shared/quick-open/quick-open-path-search' const FILE_SEARCH_DEBOUNCE_MS = 120 const FILE_SEARCH_RESULT_LIMIT = 16 diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatProse.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatProse.tsx index a5a793eea39..69dc694ba84 100644 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatProse.tsx +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatProse.tsx @@ -30,9 +30,9 @@ import { nativeChatHostStatusCopy } from './native-chat-notice-copy' import { pressedStyle } from '../../../theme/mobile-theme' import { routeNativeChatHref } from '../../../../../src/shared/native-chat/native-chat-href-routing' import { isRuntimePathAbsolute } from '../../../../../src/shared/cross-platform-path' -import { isRasterImagePath } from '../../../../../src/shared/file-preview-kind' -import { isKnownRasterImageMimeType } from '../../../../../src/shared/raster-image-preview-limits' -import { isSvgFilePath } from '../../../../../src/shared/svg-document' +import { isRasterImagePath } from '../../../../../src/shared/file-preview/file-preview-kind' +import { isKnownRasterImageMimeType } from '../../../../../src/shared/file-preview/raster-image-preview-limits' +import { isSvgFilePath } from '../../../../../src/shared/file-preview/svg-document' /** Raster https, data and absolute-path images draw on the phone (paths through the chat's host); anything else stays a link. * The shell's CSP refuses plain http, and React Native's Image cannot draw SVG. */ diff --git a/mobile/src/session/native-chat/use-mobile-native-chat-markdown-links.ts b/mobile/src/session/native-chat/use-mobile-native-chat-markdown-links.ts index 6a2652f44d4..4b9530635a6 100644 --- a/mobile/src/session/native-chat/use-mobile-native-chat-markdown-links.ts +++ b/mobile/src/session/native-chat/use-mobile-native-chat-markdown-links.ts @@ -13,7 +13,7 @@ import { import { createPathExistenceBatch, requirePathExistenceResults -} from '../../../../src/shared/path-existence-batch' +} from '../../../../src/shared/file-access/path-existence-batch' import { resolveTerminalFileLink } from '../../../../src/shared/terminal/links/terminal-links' import { getRepoIdFromWorktreeId } from '../../../../src/shared/worktree/id' import { diff --git a/mobile/src/session/native-chat/visual/mobile-native-chat-image-preview.ts b/mobile/src/session/native-chat/visual/mobile-native-chat-image-preview.ts index 2c524b34905..fd55b54f27c 100644 --- a/mobile/src/session/native-chat/visual/mobile-native-chat-image-preview.ts +++ b/mobile/src/session/native-chat/visual/mobile-native-chat-image-preview.ts @@ -1,4 +1,4 @@ -import { buildImageDataUri } from '../../../../../src/shared/image-data-uri' +import { buildImageDataUri } from '../../../../../src/shared/file-preview/image-data-uri' import { isAgentSessionAttachmentStorePath } from '../../../../../src/shared/agent-session/agent-session-attachments' import { PrioritySemaphore } from '../../../../../src/shared/priority-semaphore' import { filePreviewImageSchema } from '../../../files/file-preview-reply-schema' diff --git a/mobile/src/source-control/mobile-branch-compare.ts b/mobile/src/source-control/mobile-branch-compare.ts index 428ff6720d1..4203ec29e4f 100644 --- a/mobile/src/source-control/mobile-branch-compare.ts +++ b/mobile/src/source-control/mobile-branch-compare.ts @@ -1,4 +1,4 @@ -import { compareFileNames } from '../../../src/shared/file-name-sort' +import { compareFileNames } from '../../../src/shared/file-listing/file-name-sort' import { translate } from '../i18n/mobile-i18n' import type { MobileGitBranchChangeEntry, diff --git a/src/cli/artifact-format.ts b/src/cli/artifact-format.ts index bbc13d9f646..ae60711014c 100644 --- a/src/cli/artifact-format.ts +++ b/src/cli/artifact-format.ts @@ -1,4 +1,4 @@ -import type { ArtifactListItem, ArtifactListPage } from '../shared/artifacts' +import type { ArtifactListItem, ArtifactListPage } from '../shared/artifacts/artifacts' export function formatArtifactList(artifacts: readonly ArtifactListItem[]): string { if (artifacts.length === 0) { diff --git a/src/cli/handlers/artifacts.test.ts b/src/cli/handlers/artifacts.test.ts deleted file mode 100644 index deebc13daa1..00000000000 --- a/src/cli/handlers/artifacts.test.ts +++ /dev/null @@ -1,220 +0,0 @@ -import { mkdtemp, open, 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 type { ArtifactListItem } from '../../shared/artifacts' -import { ARTIFACT_HANDLERS } from './artifacts' -import { ARTIFACT_CLI_MAX_RPC_BYTES } from '../../shared/artifacts' -import { - ARTIFACT_SHARING_DISABLED_CODE, - ARTIFACT_SHARING_DISABLED_NEXT_STEPS -} from '../../shared/artifact-sharing-gate' - -const item: ArtifactListItem = { - artifact: { - version: 1, - slug: 'artifact-1', - title: null, - originalFileName: 'report.html', - sourceContentType: 'text/html', - renderedContentType: 'text/html', - createdAt: '2026-08-06T00:00:00.000Z', - updatedAt: '2026-08-06T00:00:00.000Z', - expiresAt: '2026-09-06T00:00:00.000Z', - byteSize: 12, - deletedAt: null - }, - shareUrl: 'https://share.onorca.dev/a/artifact-1' -} - -afterEach(async () => { - vi.restoreAllMocks() - await Promise.all(directories.splice(0).map((path) => rm(path, { recursive: true, force: true }))) -}) - -const directories: string[] = [] -async function artifactDirectory(): Promise { - const path = await mkdtemp(join(tmpdir(), 'orca-artifact-cli-')) - directories.push(path) - return path -} - -describe('artifact CLI handlers', () => { - it('reads a relative HTML file and sends its content to the runtime', async () => { - const cwd = await artifactDirectory() - await writeFile(join(cwd, 'report.html'), '

Hi

', 'utf8') - const call = vi.fn().mockResolvedValue({ - id: 'request-1', - ok: true, - result: { status: 'ok', value: item }, - _meta: { runtimeId: 'runtime-1' } - }) - const log = vi.spyOn(console, 'log').mockImplementation(() => undefined) - - await ARTIFACT_HANDLERS['artifacts share']!({ - client: { call } as never, - cwd, - flags: new Map([['file', 'report.html']]), - json: false - }) - - expect(call).toHaveBeenCalledWith( - 'artifacts.share', - expect.objectContaining({ - sourceKey: join(cwd, 'report.html'), - content: '

Hi

', - contentType: 'text/html', - fileName: 'report.html' - }) - ) - expect(log).toHaveBeenCalledWith(item.shareUrl) - }) - - it('rejects unsupported file extensions before calling the runtime', async () => { - const cwd = await artifactDirectory() - await writeFile(join(cwd, 'report.txt'), 'hello', 'utf8') - const call = vi.fn() - - await expect( - ARTIFACT_HANDLERS['artifacts share']!({ - client: { call } as never, - cwd, - flags: new Map([['file', 'report.txt']]), - json: false - }) - ).rejects.toThrow(/HTML or Markdown/) - expect(call).not.toHaveBeenCalled() - }) - - it('rejects a sparse oversized file before attempting the RPC', async () => { - const cwd = await artifactDirectory() - const handle = await open(join(cwd, 'oversized.html'), 'w') - await handle.truncate(ARTIFACT_CLI_MAX_RPC_BYTES + 1) - await handle.close() - const call = vi.fn().mockResolvedValue({ - id: 'request-1', - ok: true, - result: { settings: { artifactSharingEnabled: true } }, - _meta: { runtimeId: 'runtime-1' } - }) - - await expect( - ARTIFACT_HANDLERS['artifacts share']!({ - client: { call } as never, - cwd, - flags: new Map([['file', 'oversized.html']]), - json: false - }) - ).rejects.toThrow(/too large/) - expect(call).not.toHaveBeenCalledWith('artifacts.share', expect.anything()) - }) - - it('passes an opaque list cursor through and prints the next cursor', async () => { - const call = vi.fn().mockResolvedValue({ - id: 'request-1', - ok: true, - result: { - status: 'ok', - value: { artifacts: [item], nextCursor: 'next opaque page' } - }, - _meta: { runtimeId: 'runtime-1' } - }) - const log = vi.spyOn(console, 'log').mockImplementation(() => undefined) - - await ARTIFACT_HANDLERS['artifacts list']!({ - client: { call } as never, - cwd: '/repo', - flags: new Map([['cursor', 'current opaque page']]), - json: false - }) - - expect(call).toHaveBeenCalledWith('artifacts.list', { cursor: 'current opaque page' }) - expect(log).toHaveBeenCalledWith( - expect.stringContaining('More artifacts: --cursor next opaque page') - ) - }) - - it.each(['artifacts share', 'artifacts update'])( - 'denies `%s` from the capability preflight without reading or shipping the file', - async (command) => { - const cwd = await artifactDirectory() - const call = vi.fn().mockResolvedValue({ - id: 'request-1', - ok: true, - result: { settings: { artifactSharingEnabled: false } }, - _meta: { runtimeId: 'runtime-1' } - }) - - await expect( - ARTIFACT_HANDLERS[command]!({ - client: { call } as never, - cwd, - flags: new Map([['file', 'report.html']]), - json: false - }) - ).rejects.toMatchObject({ - code: ARTIFACT_SHARING_DISABLED_CODE, - data: { nextSteps: [...ARTIFACT_SHARING_DISABLED_NEXT_STEPS] } - }) - - expect(call).toHaveBeenCalledExactlyOnceWith('settings.get') - } - ) - - it.each([ - ['omits the capability field', {}], - ['cannot answer the preflight', null] - ])('still attempts the publish RPC when the host %s', async (_label, settings) => { - const cwd = await artifactDirectory() - await writeFile(join(cwd, 'report.html'), '

Hi

', 'utf8') - const call = vi.fn().mockImplementation((method: string) => { - if (method === 'settings.get') { - if (!settings) { - return Promise.reject(new Error('unsupported_method')) - } - return Promise.resolve({ - id: 'request-1', - ok: true, - result: { settings }, - _meta: { runtimeId: 'runtime-1' } - }) - } - return Promise.resolve({ - id: 'request-2', - ok: true, - result: { status: 'ok', value: item }, - _meta: { runtimeId: 'runtime-1' } - }) - }) - vi.spyOn(console, 'log').mockImplementation(() => undefined) - - await ARTIFACT_HANDLERS['artifacts share']!({ - client: { call } as never, - cwd, - flags: new Map([['file', 'report.html']]), - json: false - }) - - expect(call).toHaveBeenCalledWith( - 'artifacts.share', - expect.objectContaining({ content: '

Hi

' }) - ) - }) - - it.each(['environment', 'pairing-code'])( - 'rejects explicit remote selector --%s', - async (flag) => { - const call = vi.fn() - - await expect( - ARTIFACT_HANDLERS['artifacts list']!({ - client: { call } as never, - cwd: '/repo', - flags: new Map([[flag, 'remote-host']]), - json: false - }) - ).rejects.toThrow(/does not retarget artifact commands/) - expect(call).not.toHaveBeenCalled() - } - ) -}) diff --git a/src/cli/handlers/artifacts.ts b/src/cli/handlers/artifacts.ts index e9c0b811063..173317475fa 100644 --- a/src/cli/handlers/artifacts.ts +++ b/src/cli/handlers/artifacts.ts @@ -5,18 +5,18 @@ import type { ArtifactListPage, ArtifactListItem, ArtifactWriteRequest -} from '../../shared/artifacts' -import { ARTIFACT_CLI_MAX_RPC_BYTES } from '../../shared/artifacts' +} from '../../shared/artifacts/artifacts' +import { ARTIFACT_CLI_MAX_RPC_BYTES } from '../../shared/artifacts/artifacts' import { parseRemoteArtifactInput, REMOTE_ARTIFACT_INPUT_ENV -} from '../../shared/artifact-cli-bridge' -import { readArtifactFileWithinLimit } from '../../shared/artifact-file-read' +} from '../../shared/artifacts/artifact-cli-bridge' +import { readArtifactFileWithinLimit } from '../../shared/artifacts/artifact-file-read' import { ARTIFACT_SHARING_DISABLED_CODE, ARTIFACT_SHARING_DISABLED_MESSAGE, ARTIFACT_SHARING_DISABLED_NEXT_STEPS -} from '../../shared/artifact-sharing-gate' +} from '../../shared/artifacts/artifact-sharing-gate' import type { CommandHandler, HandlerContext } from '../dispatch' import { rejectRemoteSelectionFlags } from '../remote-selection-flag-rejection' import { RuntimeClientError } from '../runtime-client' diff --git a/src/cli/handlers/file-open-call.ts b/src/cli/handlers/file-open-call.ts index d3eaea15743..7eca5572777 100644 --- a/src/cli/handlers/file-open-call.ts +++ b/src/cli/handlers/file-open-call.ts @@ -1,4 +1,4 @@ -import type { RuntimeFileOpenResult } from '../../shared/runtime-types' +import type { RuntimeFileOpenResult } from '../../shared/file-access/runtime-editor-file-open' import type { HandlerContext } from '../dispatch' import { RuntimeClientError, type RuntimeRpcSuccess } from '../runtime-client' diff --git a/src/cli/handlers/file-open-position.ts b/src/cli/handlers/file-open-position.ts index 3b99b3d5f48..9edc09a0717 100644 --- a/src/cli/handlers/file-open-position.ts +++ b/src/cli/handlers/file-open-position.ts @@ -1,4 +1,4 @@ -import type { RuntimeFileOpenPosition } from '../../shared/runtime-file-contracts' +import type { RuntimeFileOpenPosition } from '../../shared/file-access/runtime-editor-file-open' import { getOptionalPositiveIntegerFlag } from '../flags' import { RuntimeClientError } from '../runtime-client' diff --git a/src/cli/handlers/file.ts b/src/cli/handlers/file.ts index e643b577ba2..68aef649b48 100644 --- a/src/cli/handlers/file.ts +++ b/src/cli/handlers/file.ts @@ -1,6 +1,7 @@ import { getFileOpenPosition } from './file-open-position' import type { GitStatusEntry, GitStatusResult } from '../../shared/git/status/git-status-types' -import type { RuntimeFileOpenResult, RuntimeWorktreeRecord } from '../../shared/runtime-types' +import type { RuntimeFileOpenResult } from '../../shared/file-access/runtime-editor-file-open' +import type { RuntimeWorktreeRecord } from '../../shared/runtime-types' import type { RuntimeNavigationTarget } from '../../shared/runtime-navigation' import { isRuntimePathAbsolute, relativePathInsideRoot } from '../../shared/cross-platform-path' import { isWslUncPath, parseWslUncPath, toWindowsWslPath } from '../../shared/wsl-paths' diff --git a/src/main/acp/acp-prompt-content.ts b/src/main/acp/acp-prompt-content.ts index e6ec843e715..b205aa47164 100644 --- a/src/main/acp/acp-prompt-content.ts +++ b/src/main/acp/acp-prompt-content.ts @@ -11,12 +11,12 @@ import { } from '../../shared/agent-session/failures/agent-session-failure-words' import { formatNativeChatFileReference } from '../../shared/agent-image-paste' import type { AgentJournalMessageItem } from '../../shared/agent-session/journal/agent-session-journal-types' -import { IMAGE_FILE_MIME_TYPES } from '../../shared/image-file-extensions' +import { IMAGE_FILE_MIME_TYPES } from '../../shared/file-preview/image-mime-types' import type { NativeChatImageRefBlock } from '../../shared/native-chat/native-chat-types' import { NodeFileReadTooLargeError, readNodeFileWithinLimit -} from '../../shared/node-bounded-file-reader' +} from '../../shared/file-content/node-bounded-file-reader' import type { AcpLaunchSpec } from './acp-launch-specs' import { resolveAcpPeerOptions } from './acp-peer-limits' import { acpAgentName } from './acp-structured-agent-definitions' diff --git a/src/main/agent-launch/trust/execution-host-workspace-trust.ts b/src/main/agent-launch/trust/execution-host-workspace-trust.ts index a7e73b64d0f..04132d61370 100644 --- a/src/main/agent-launch/trust/execution-host-workspace-trust.ts +++ b/src/main/agent-launch/trust/execution-host-workspace-trust.ts @@ -15,7 +15,7 @@ import { type ClaudeTrustConfigTarget, grantClaudeWorkspaceTrust } from '../../claude/claude-folder-trust-file' -import { isTooBroadToPreTrust } from '../../../shared/home-or-filesystem-root' +import { isTooBroadToPreTrust } from '../../../shared/agent-launch/permissions/workspace-pretrust-scope' /** Resolve trust on the agent’s execution host, including WSL guests and SSH relays. */ export type WorkspaceTrustHost = { diff --git a/src/main/ai-vault/scanners/antigravity/antigravity-index-file-admission.test.ts b/src/main/ai-vault/scanners/antigravity/antigravity-index-file-admission.test.ts index 4102f0fafb0..0dcf0d37048 100644 --- a/src/main/ai-vault/scanners/antigravity/antigravity-index-file-admission.test.ts +++ b/src/main/ai-vault/scanners/antigravity/antigravity-index-file-admission.test.ts @@ -1,10 +1,9 @@ import type * as NodeFsPromises from 'node:fs/promises' -import { constants } from 'node:fs' + import { mkdtemp, 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 { runProcess } from '@orca/process-host' const { afterStat } = vi.hoisted(() => { const afterStat: { run: null | (() => Promise) } = { run: null } @@ -21,7 +20,7 @@ vi.mock('node:fs/promises', async (original) => { } } }) -import { readNodeFileWithinLimit } from '../../../../shared/node-bounded-file-reader' +import { readNodeFileWithinLimit } from '../../../../shared/file-content/node-bounded-file-reader' import { readLocalAntigravityHistory } from './session-scanner-antigravity-history' const roots: string[] = [] @@ -30,36 +29,12 @@ async function filePath() { roots.push(root) return join(root, 'projects.json') } -async function fifo(path: string) { - const result = await runProcess({ program: 'mkfifo', args: [path], timeoutMs: 2000 }) - if (result.code !== 0) { - throw new Error('Could not create task-owned FIFO') - } -} afterEach(async () => { afterStat.run = null await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) }) describe('bounded regular metadata reads', () => { - it.skipIf(process.platform === 'win32')( - 'rejects a regular path replaced by a FIFO between stat and open', - async () => { - const file = await filePath() - await writeFile(file, '{}') - afterStat.run = async () => { - afterStat.run = null - await rm(file) - await fifo(file) - } - await expect(readNodeFileWithinLimit(file, 64, { regularFileOnly: true })).rejects.toThrow( - 'regular file' - ) - expect(constants.O_NONBLOCK).toBeGreaterThan(0) - }, - 2000 - ) - it('retains ordinary metadata within the byte bound', async () => { const file = await filePath() await writeFile(file, '{"project":"/workspace"}') diff --git a/src/main/ai-vault/scanners/antigravity/session-scanner-antigravity-history.ts b/src/main/ai-vault/scanners/antigravity/session-scanner-antigravity-history.ts index 98a0b67b831..f1a1ea89f9b 100644 --- a/src/main/ai-vault/scanners/antigravity/session-scanner-antigravity-history.ts +++ b/src/main/ai-vault/scanners/antigravity/session-scanner-antigravity-history.ts @@ -9,7 +9,7 @@ import { openTranscriptReadStream, wslGatedStat } from '../../../native-chat/wsl-transcript-fs-access' -import { readNodeFileWithinLimit } from '../../../../shared/node-bounded-file-reader' +import { readNodeFileWithinLimit } from '../../../../shared/file-content/node-bounded-file-reader' import { isWslUncPath } from '../../../../shared/wsl-paths' import { throwIfAiVaultScanCancelled } from '../../ai-vault-scan-cancellation' import { WslTranscriptFsError } from '../../../native-chat/wsl-transcript-fs-error' diff --git a/src/main/ai-vault/transcripts/session-document-stream.ts b/src/main/ai-vault/transcripts/session-document-stream.ts index 9d0bccc4cbd..4fc710ef6f3 100644 --- a/src/main/ai-vault/transcripts/session-document-stream.ts +++ b/src/main/ai-vault/transcripts/session-document-stream.ts @@ -1,7 +1,7 @@ import { StringDecoder } from 'node:string_decoder' import { FlexAssembler, arrayRule, objectRule } from 'stream-json/core/utils/flex-assembler.js' import { setImmediate as yieldToEventLoop } from 'node:timers/promises' -import { createJsonTokenReader } from '../../../shared/json-token-reader' +import { createJsonTokenReader } from '../../../shared/json-stream/json-token-reader' import { throwIfAiVaultScanCancelled } from '../ai-vault-scan-cancellation' /** Fold one root array while retaining only the root fields the agent parser uses. */ diff --git a/src/main/antigravity/native-account-store.ts b/src/main/antigravity/native-account-store.ts index e401c8849bb..9725a946c7f 100644 --- a/src/main/antigravity/native-account-store.ts +++ b/src/main/antigravity/native-account-store.ts @@ -5,7 +5,7 @@ import { writeCredentialFileAtomic } from '../credentials/integration-credential import type { AntigravityAccountSummary } from '../../shared/antigravity-account-types' import type { ProviderRateLimits, RateLimitRuntimeTarget } from '../../shared/rate-limit-types' import { parseAntigravityNativeCredential } from './native-credential-codec' -import { readPrivateWindowsFile } from '../../shared/secure-path-windows-acl' +import { readPrivateWindowsFile } from '../../shared/secure-storage/secure-path-windows-acl' export type StoredAntigravityUsage = { target: RateLimitRuntimeTarget diff --git a/src/main/antigravity/native-file-credentials.ts b/src/main/antigravity/native-file-credentials.ts index 21bb12ffbc9..37a8ed234eb 100644 --- a/src/main/antigravity/native-file-credentials.ts +++ b/src/main/antigravity/native-file-credentials.ts @@ -1,7 +1,7 @@ import { existsSync, lstatSync, mkdirSync, readFileSync, statSync } from 'node:fs' import { dirname } from 'node:path' import { writeCredentialFileAtomic } from '../credentials/integration-credential-file' -import { readPrivateWindowsFile } from '../../shared/secure-path-windows-acl' +import { readPrivateWindowsFile } from '../../shared/secure-storage/secure-path-windows-acl' import { parseAntigravityNativeCredential } from './native-credential-codec' import type { AntigravityCredentialBackend } from './native-account-service' diff --git a/src/main/artifacts/artifact-cloud-request.ts b/src/main/artifacts/artifact-cloud-request.ts index 4ad4633dac9..8c040049687 100644 --- a/src/main/artifacts/artifact-cloud-request.ts +++ b/src/main/artifacts/artifact-cloud-request.ts @@ -1,4 +1,4 @@ -import type { ArtifactWriteRequest } from '../../shared/artifacts' +import type { ArtifactWriteRequest } from '../../shared/artifacts/artifacts' import { OrcaCloudRequestError } from '../orca-profiles/profile-cloud-client' export type ArtifactWriteBody = { diff --git a/src/main/artifacts/artifact-cloud-service.test.ts b/src/main/artifacts/artifact-cloud-service.test.ts index 05b9922687f..69bd24b2ade 100644 --- a/src/main/artifacts/artifact-cloud-service.test.ts +++ b/src/main/artifacts/artifact-cloud-service.test.ts @@ -15,11 +15,7 @@ import { unlinkOrcaProfileFromCloud } from '../orca-profiles/profile-cloud-index' import { signOutCloudSession } from '../orca-profiles/profile-cloud-session-owner' -import { saveOrcaCloudSession } from '../orca-profiles/profile-cloud-session-store' -import { - ARTIFACT_SHARING_DISABLED_CODE, - ARTIFACT_SHARING_DISABLED_MESSAGE -} from '../../shared/artifact-sharing-gate' + import { ArtifactCloudService } from './artifact-cloud-service' const createdPaths: string[] = [] @@ -105,171 +101,6 @@ afterEach(async () => { }) describe('ArtifactCloudService record authorization', () => { - it('serializes concurrent publishes for the same source', async () => { - const { service } = await setup() - let resolveCreate: ((response: Response) => void) | undefined - const fetchMock = vi - .fn() - .mockImplementationOnce( - () => - new Promise((resolve) => { - resolveCreate = resolve - }) - ) - .mockResolvedValueOnce(createResponse()) - vi.stubGlobal('fetch', fetchMock) - - const first = service.publish(writeRequest) - const second = service.publish(writeRequest) - await vi.waitFor(() => expect(resolveCreate).toBeTypeOf('function')) - expect(fetchMock).toHaveBeenCalledOnce() - resolveCreate?.(createResponse()) - - await expect(Promise.all([first, second])).resolves.toMatchObject([ - { status: 'ok', value: { change: 'created' } }, - { status: 'ok', value: { change: 'updated' } } - ]) - expect(fetchMock).toHaveBeenCalledTimes(2) - expect(fetchMock.mock.calls[1]?.[1]).toMatchObject({ method: 'PUT' }) - }) - - it('serializes manual publish with CLI share for the same source', async () => { - const { service } = await setup() - let resolvePublish: ((response: Response) => void) | undefined - const fetchMock = vi - .fn() - .mockImplementationOnce( - () => - new Promise((resolve) => { - resolvePublish = resolve - }) - ) - .mockResolvedValueOnce(createResponse('artifact-b')) - vi.stubGlobal('fetch', fetchMock) - - const publish = service.publish(writeRequest) - const share = service.share(writeRequest) - await vi.waitFor(() => expect(resolvePublish).toBeTypeOf('function')) - expect(fetchMock).toHaveBeenCalledOnce() - resolvePublish?.(createResponse('artifact-a')) - - await expect(Promise.all([publish, share])).resolves.toMatchObject([ - { status: 'ok', value: { change: 'created' } }, - { status: 'ok', value: { shareUrl: 'https://share.onorca.dev/a/artifact-b' } } - ]) - expect(fetchMock).toHaveBeenCalledTimes(2) - }) - - it('serializes account deletion with a mapped source update', async () => { - const { service } = await setup() - let resolveUpdate: ((response: Response) => void) | undefined - const fetchMock = vi - .fn() - .mockResolvedValueOnce(createResponse()) - .mockImplementationOnce( - () => - new Promise((resolve) => { - resolveUpdate = resolve - }) - ) - .mockResolvedValueOnce(new Response(null, { status: 204 })) - vi.stubGlobal('fetch', fetchMock) - await service.share(writeRequest) - - const update = service.update(writeRequest) - await vi.waitFor(() => expect(resolveUpdate).toBeTypeOf('function')) - const deletion = service.delete('artifact-a', { apiUrl, authToken: 'token-a' }) - expect(fetchMock).toHaveBeenCalledTimes(2) - resolveUpdate?.(createResponse()) - - await expect(Promise.all([update, deletion])).resolves.toMatchObject([ - { status: 'ok' }, - { status: 'ok' } - ]) - await expect( - service.getPublishedLink({ sourceKey: writeRequest.sourceKey, apiUrl, authToken: 'token-a' }) - ).resolves.toEqual({ status: 'ok', value: null }) - expect(fetchMock).toHaveBeenCalledTimes(3) - }) - - it('recreates an artifact when its stored public link was deleted elsewhere', async () => { - const { service } = await setup() - const fetchMock = vi - .fn() - .mockResolvedValueOnce(createResponse('artifact-a')) - .mockResolvedValueOnce(new Response(JSON.stringify({ code: 'not_found' }), { status: 404 })) - .mockResolvedValueOnce(createResponse('artifact-b')) - .mockResolvedValueOnce(createResponse('artifact-b')) - vi.stubGlobal('fetch', fetchMock) - - await service.publish(writeRequest) - await expect(service.publish(writeRequest)).resolves.toMatchObject({ - status: 'ok', - value: { change: 'created', item: { shareUrl: 'https://share.onorca.dev/a/artifact-b' } } - }) - await expect(service.publish(writeRequest)).resolves.toMatchObject({ - status: 'ok', - value: { change: 'updated', item: { shareUrl: 'https://share.onorca.dev/a/artifact-b' } } - }) - - expect(fetchMock.mock.calls.map(([, options]) => options?.method)).toEqual([ - 'POST', - 'PUT', - 'POST', - 'PUT' - ]) - }) - - it('keeps the idempotency key stable across an auth-refresh retry', async () => { - const { service, profileId, userDataPath } = await setup() - vi.stubEnv('ORCA_CLOUD_API_URL', 'http://localhost:4100') - vi.stubEnv('ORCA_CLOUD_CLIENT_ID', 'desktop-client') - saveOrcaCloudSession(profileId, userDataPath, { - accessToken: 'access-old', - refreshToken: 'refresh-old', - expiresAt: Date.now() + 120_000, - capabilities: { flags: {}, refreshedAt: Date.now() } - }) - let artifactAttempts = 0 - const fetchMock = vi.fn().mockImplementation((input: string | URL) => { - const url = String(input) - if (url === `${apiUrl}/v1/artifacts`) { - artifactAttempts += 1 - return Promise.resolve( - artifactAttempts === 1 - ? new Response(JSON.stringify({ code: 'invalid_access_token' }), { status: 401 }) - : createResponse() - ) - } - if (url === 'http://localhost:4100/v1/desktop/auth/refresh') { - return Promise.resolve( - new Response( - JSON.stringify({ - accessToken: 'access-new', - refreshToken: 'refresh-new', - expiresAt: Date.now() + 3_600_000, - cloud: cloudA, - capabilities: { flags: {}, refreshedAt: Date.now() } - }), - { status: 200, headers: { 'content-type': 'application/json' } } - ) - ) - } - throw new Error(`Unexpected URL: ${url}`) - }) - vi.stubGlobal('fetch', fetchMock) - - await expect(service.share({ ...writeRequest, authToken: undefined })).resolves.toMatchObject({ - status: 'ok' - }) - - expect(requestHeader(fetchMock, 0, 'authorization')).toBe('Bearer access-old') - expect(requestHeader(fetchMock, 2, 'authorization')).toBe('Bearer access-new') - expect(requestHeader(fetchMock, 0, 'idempotency-key')).toBe( - requestHeader(fetchMock, 2, 'idempotency-key') - ) - }) - it('refuses account B update and unshare after account A signs out', async () => { const { userDataPath, profileId, service } = await setup() vi.stubGlobal('fetch', vi.fn().mockResolvedValue(createResponse())) @@ -337,77 +168,9 @@ describe('ArtifactCloudService record authorization', () => { await expect(pending).resolves.toMatchObject({ status: 'ok' }) }) - - it('never scopes an explicit token to the profile linked in the UI', async () => { - const { service } = await setup() - const fetchMock = vi.fn().mockResolvedValue(createResponse()) - vi.stubGlobal('fetch', fetchMock) - await service.share(writeRequest) - - await expect(service.update({ ...writeRequest, authToken: 'token-b' })).rejects.toThrow( - /has not been shared/ - ) - expect(fetchMock).toHaveBeenCalledOnce() - }) - - it('keeps update and unshare working after an update extends expiration', async () => { - vi.useFakeTimers({ toFake: ['Date'] }) - vi.setSystemTime('2026-08-07T00:00:00.000Z') - const { service } = await setup() - let resolveUpdate: ((response: Response) => void) | undefined - const fetchMock = vi - .fn() - .mockResolvedValueOnce(createResponse('artifact-a', '2026-09-06T00:00:00.000Z')) - .mockImplementationOnce( - () => - new Promise((resolve) => { - resolveUpdate = resolve - }) - ) - .mockResolvedValueOnce(new Response(null, { status: 204 })) - vi.stubGlobal('fetch', fetchMock) - - await service.share(writeRequest) - vi.setSystemTime('2026-09-05T00:00:00.000Z') - const update = service.update(writeRequest) - await vi.waitFor(() => expect(resolveUpdate).toBeTypeOf('function')) - vi.setSystemTime('2026-09-07T00:00:00.000Z') - resolveUpdate?.(createResponse('artifact-a', '2026-10-06T00:00:00.000Z')) - await update - await expect( - service.unshare({ sourceKey: writeRequest.sourceKey, apiUrl, authToken: 'token-a' }) - ).resolves.toEqual({ status: 'ok', value: undefined }) - expect(fetchMock).toHaveBeenCalledTimes(3) - }) }) describe('ArtifactCloudService publish capability gate', () => { - it.each([ - ['share', (service: ArtifactCloudService) => service.share(writeRequest)], - ['publish', (service: ArtifactCloudService) => service.publish(writeRequest)], - ['update', (service: ArtifactCloudService) => service.update(writeRequest)] - ])('rejects %s without reaching the network when the capability is off', async (_name, call) => { - const { service } = await setup({ value: false }) - const fetchMock = vi.fn().mockResolvedValue(createResponse()) - vi.stubGlobal('fetch', fetchMock) - - await expect(call(service)).rejects.toMatchObject({ - code: ARTIFACT_SHARING_DISABLED_CODE, - data: { nextSteps: expect.arrayContaining([expect.stringContaining('Settings')]) } - }) - expect(fetchMock).not.toHaveBeenCalled() - }) - - it('persists no share record for a denied share, so a later update stays denied', async () => { - const sharing = { value: false } - const { service } = await setup(sharing) - vi.stubGlobal('fetch', vi.fn().mockResolvedValue(createResponse())) - - await expect(service.share(writeRequest)).rejects.toThrow(ARTIFACT_SHARING_DISABLED_MESSAGE) - sharing.value = true - await expect(service.update(writeRequest)).rejects.toThrow(/has not been shared/) - }) - it('keeps list and unshare working so links stay revocable after opting out', async () => { const sharing = { value: true } const { service } = await setup(sharing) @@ -438,27 +201,4 @@ describe('ArtifactCloudService publish capability gate', () => { service.unshare({ sourceKey: writeRequest.sourceKey, apiUrl, authToken: 'token-a' }) ).resolves.toEqual({ status: 'ok', value: undefined }) }) - - it('re-reads the capability per call so revoking it stops the next share', async () => { - const sharing = { value: true } - const { service } = await setup(sharing) - const fetchMock = vi.fn().mockResolvedValue(createResponse()) - vi.stubGlobal('fetch', fetchMock) - - await service.share(writeRequest) - sharing.value = false - await expect(service.share({ ...writeRequest, sourceKey: '/repo/other.html' })).rejects.toThrow( - ARTIFACT_SHARING_DISABLED_MESSAGE - ) - expect(fetchMock).toHaveBeenCalledOnce() - }) }) - -function requestHeader( - fetchMock: ReturnType, - index: number, - name: string -): string | null { - const init = fetchMock.mock.calls[index]?.[1] as RequestInit | undefined - return new Headers(init?.headers).get(name) -} diff --git a/src/main/artifacts/artifact-cloud-service.ts b/src/main/artifacts/artifact-cloud-service.ts index 2883cb020a3..9cff076d1b0 100644 --- a/src/main/artifacts/artifact-cloud-service.ts +++ b/src/main/artifacts/artifact-cloud-service.ts @@ -8,8 +8,8 @@ import type { ArtifactPublishedLink, ArtifactPublishResult, ArtifactWriteRequest -} from '../../shared/artifacts' -import { assertArtifactSharingAllowed } from '../../shared/artifact-sharing-gate' +} from '../../shared/artifacts/artifacts' +import { assertArtifactSharingAllowed } from '../../shared/artifacts/artifact-sharing-gate' import { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store' import { getOrcaCloudAuthConfig } from '../orca-profiles/profile-cloud-auth-config' import { prepareArtifactCloudUse } from '../orca-profiles/profile-artifact-cloud-cleanup' diff --git a/src/main/artifacts/artifact-create-intent-store.test.ts b/src/main/artifacts/artifact-create-intent-store.test.ts index cc0fa083633..cccaec29f16 100644 --- a/src/main/artifacts/artifact-create-intent-store.test.ts +++ b/src/main/artifacts/artifact-create-intent-store.test.ts @@ -1,12 +1,8 @@ -import { mkdtemp, readFile, readdir, rm, stat, truncate, writeFile } from 'node:fs/promises' +import { mkdtemp, readFile, readdir, rm, truncate, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { - ARTIFACT_MAX_CONTENT_BYTES, - ARTIFACT_MAX_REQUEST_BYTES, - artifactWriteRequestByteLength -} from '../../shared/artifacts' +import { ARTIFACT_MAX_CONTENT_BYTES } from '../../shared/artifacts/artifacts' import { MAX_ARTIFACT_CREATE_INTENT_BYTES, MAX_PENDING_ARTIFACT_CREATES, @@ -238,31 +234,6 @@ describe('artifact create intent store', () => { ).toThrow(/unsupported format/) }) - it('persists an escaped artifact within the recovery limit', async () => { - const userDataPath = await createUserDataPath() - const nearLimitBody = { - ...body, - content: '"'.repeat(Math.floor(ARTIFACT_MAX_CONTENT_BYTES / 2)) - } - expect( - artifactWriteRequestByteLength({ sourceKey: '/repo/report.html', ...nearLimitBody }) - ).toBeLessThanOrEqual(ARTIFACT_MAX_REQUEST_BYTES) - - expect(() => - getOrCreateArtifactCreateIntent( - 'local-profile', - userDataPath, - '/repo/report.html', - scope, - 'key-a', - nearLimitBody - ) - ).not.toThrow() - const directory = join(userDataPath, 'profiles', 'local-profile', 'artifact-create-intents') - const [fileName] = await readdir(directory) - expect((await stat(join(directory, fileName))).size).toBeGreaterThan(ARTIFACT_MAX_CONTENT_BYTES) - }) - it('rejects oversized artifact content before creating a recovery record', async () => { const userDataPath = await createUserDataPath() expect(() => @@ -277,26 +248,6 @@ describe('artifact create intent store', () => { ).toThrow(/10 MiB limit/) }) - it('rejects a recovery body whose escaped request exceeds the transport budget', async () => { - const userDataPath = await createUserDataPath() - const content = '\u0000'.repeat(Math.ceil(ARTIFACT_MAX_REQUEST_BYTES / 6)) - expect(content.length).toBeLessThan(ARTIFACT_MAX_CONTENT_BYTES) - expect( - artifactWriteRequestByteLength({ sourceKey: '/repo/report.html', ...body, content }) - ).toBeGreaterThan(ARTIFACT_MAX_REQUEST_BYTES) - - expect(() => - getOrCreateArtifactCreateIntent( - 'local-profile', - userDataPath, - '/repo/report.html', - scope, - 'key-a', - { ...body, content } - ) - ).toThrow(/supported size/) - }) - it('rejects an oversized recovery record before reading it', async () => { const userDataPath = await createUserDataPath() const directory = join(userDataPath, 'profiles', 'local-profile', 'artifact-create-intents') diff --git a/src/main/artifacts/artifact-create-intent-store.ts b/src/main/artifacts/artifact-create-intent-store.ts index e04ad9b078f..eb2aee86f06 100644 --- a/src/main/artifacts/artifact-create-intent-store.ts +++ b/src/main/artifacts/artifact-create-intent-store.ts @@ -6,8 +6,11 @@ import { ARTIFACT_MAX_REQUEST_BYTES, artifactContentByteLength, artifactWriteRequestByteLength -} from '../../shared/artifacts' -import { bestEffortFsyncDirectorySync, writeSecureFile } from '../../shared/secure-file' +} from '../../shared/artifacts/artifacts' +import { + bestEffortFsyncDirectorySync, + writeSecureFile +} from '../../shared/secure-storage/secure-file' import { getOrcaProfileDirectory } from '../orca-profiles/profile-storage-paths' import type { ArtifactWriteBody } from './artifact-cloud-request' import type { ArtifactShareScope } from './artifact-share-record-store' diff --git a/src/main/artifacts/artifact-publisher.ts b/src/main/artifacts/artifact-publisher.ts index d70958e6b6f..ad86a866cfb 100644 --- a/src/main/artifacts/artifact-publisher.ts +++ b/src/main/artifacts/artifact-publisher.ts @@ -2,7 +2,7 @@ import type { ArtifactListItem, ArtifactPublishResult, ArtifactWriteRequest -} from '../../shared/artifacts' +} from '../../shared/artifacts/artifacts' import { OrcaCloudRequestError } from '../orca-profiles/profile-cloud-client' import { artifactRequest, diff --git a/src/main/artifacts/artifact-recovery-directory-fsync.test.ts b/src/main/artifacts/artifact-recovery-directory-fsync.test.ts index c815d91560d..8dd3810e3db 100644 --- a/src/main/artifacts/artifact-recovery-directory-fsync.test.ts +++ b/src/main/artifacts/artifact-recovery-directory-fsync.test.ts @@ -33,7 +33,10 @@ vi.mock('node:fs', async () => { } }) -import { bestEffortFsyncDirectorySync, writeDurableSecureJsonFile } from '../../shared/secure-file' +import { + bestEffortFsyncDirectorySync, + writeDurableSecureJsonFile +} from '../../shared/secure-storage/secure-file' import { clearArtifactCreateIntents, getOrCreateArtifactCreateIntent diff --git a/src/main/artifacts/artifact-share-record-store.ts b/src/main/artifacts/artifact-share-record-store.ts index ac448fbc564..a4bbff3e626 100644 --- a/src/main/artifacts/artifact-share-record-store.ts +++ b/src/main/artifacts/artifact-share-record-store.ts @@ -1,7 +1,10 @@ import { randomUUID } from 'node:crypto' import { existsSync, readFileSync } from 'node:fs' import { join } from 'node:path' -import { writeDurableSecureJsonFile, writeSecureJsonFile } from '../../shared/secure-file' +import { + writeDurableSecureJsonFile, + writeSecureJsonFile +} from '../../shared/secure-storage/secure-file' import { getOrcaProfileDirectory } from '../orca-profiles/profile-storage-paths' export type ArtifactShareScope = { diff --git a/src/main/bitbucket/credential-store.test.ts b/src/main/bitbucket/credential-store.test.ts index 03976511452..34d1d09424f 100644 --- a/src/main/bitbucket/credential-store.test.ts +++ b/src/main/bitbucket/credential-store.test.ts @@ -2,7 +2,7 @@ import { existsSync, mkdtempSync, readdirSync, statSync } from 'node:fs' import type * as Fs from 'node:fs' import { tmpdir } from 'node:os' import type * as Os from 'node:os' -import type * as WindowsAcl from '../../shared/secure-path-windows-acl' +import type * as WindowsAcl from '../../shared/secure-storage/secure-path-windows-acl' import { join } from 'node:path' import { beforeEach, describe, expect, it, vi } from 'vitest' @@ -19,7 +19,7 @@ async function loadStore( vi.resetModules() // resetModules leaves doMock registrations behind. vi.doUnmock('node:fs') - vi.doUnmock('../../shared/secure-path-windows-acl') + vi.doUnmock('../../shared/secure-storage/secure-path-windows-acl') const { setSecretStore } = await import('../../shared/secret-store') setSecretStore({ isEncryptionAvailable: () => true, @@ -53,7 +53,7 @@ async function loadStore( } }) // Windows writes use the ACL helper. - vi.doMock('../../shared/secure-path-windows-acl', async (importOriginal) => ({ + vi.doMock('../../shared/secure-storage/secure-path-windows-acl', async (importOriginal) => ({ ...(await importOriginal()), writeRestrictedWindowsFile: () => { throw error @@ -105,36 +105,6 @@ describe('Bitbucket credential store', () => { } }) - it('does not decrypt for metadata/status reads — only on a forced secret load', async () => { - const store = await loadStore() - store.saveBitbucketCredential({ - authMode: 'token', - email: null, - baseUrl: 'https://api.bitbucket.org/2.0', - account: 'dev', - accessToken: 'access-secret', - apiToken: null - }) - - store._resetBitbucketCredentialCache() - - expect(store.getStoredBitbucketMetadata()?.account).toBe('dev') - expect(store.hasStoredBitbucketCredential()).toBe(true) - expect(decryptStringMock).not.toHaveBeenCalled() - - expect(store.loadStoredBitbucketSecret()).toBeNull() - expect(decryptStringMock).not.toHaveBeenCalled() - - expect(store.loadStoredBitbucketSecret({ force: true })).toMatchObject({ - accessToken: 'access-secret', - apiToken: null, - authMode: 'token' - }) - expect(decryptStringMock).toHaveBeenCalledTimes(1) - expect(store.loadStoredBitbucketSecret()).not.toBeNull() - expect(decryptStringMock).toHaveBeenCalledTimes(1) - }) - it('rejects non-string fields from hand-edited metadata and secret files', async () => { const store = await loadStore() const { writeFileSync } = await import('node:fs') diff --git a/src/main/browser-passwords/browser-password-vault-file.ts b/src/main/browser-passwords/browser-password-vault-file.ts index ca352f57db5..4ff487f0e16 100644 --- a/src/main/browser-passwords/browser-password-vault-file.ts +++ b/src/main/browser-passwords/browser-password-vault-file.ts @@ -1,7 +1,7 @@ import { readFileSync, rmSync } from 'node:fs' import type { BrowserPasswordEntrySummary } from '../../shared/browser-passwords-types' import { getSecretStore, hasSecretStore } from '../../shared/secret-store' -import { writeSecureFile } from '../../shared/secure-file' +import { writeSecureFile } from '../../shared/secure-storage/secure-file' /** * On-disk vault: usernames and sites sit in one sealed index; each password is sealed on its own diff --git a/src/main/browser/agent-browser/agent-browser-bridge-capture-commands.ts b/src/main/browser/agent-browser/agent-browser-bridge-capture-commands.ts index a23b9e62cef..b62d85b9f58 100644 --- a/src/main/browser/agent-browser/agent-browser-bridge-capture-commands.ts +++ b/src/main/browser/agent-browser/agent-browser-bridge-capture-commands.ts @@ -15,7 +15,7 @@ import { agentBrowserScreenshotArgs, readAgentBrowserScreenshot } from './agent-browser-screenshot-arguments' -import { readRasterImageDimensions } from '../../../shared/raster-image-dimensions' +import { readRasterImageDimensions } from '../../../shared/file-preview/raster-image-dimensions' import { acquireElectronDebugger } from '../cdp/debugger/electron-debugger-lease' import { sendGuestCdpCommand } from '../cdp/debugger/guest-cdp-command' import { AgentBrowserBridgeUtilityCommands } from './agent-browser-bridge-page-commands' diff --git a/src/main/browser/document-preview/doc-preview-failure-notice.ts b/src/main/browser/document-preview/doc-preview-failure-notice.ts index d5ad965418d..1cb3c4c31ae 100644 --- a/src/main/browser/document-preview/doc-preview-failure-notice.ts +++ b/src/main/browser/document-preview/doc-preview-failure-notice.ts @@ -1,7 +1,7 @@ import { DOC_PREVIEW_LOAD_FAILURE_CHANNEL, type DocPreviewFailure -} from '../../../shared/doc-preview-scheme' +} from '../../../shared/document-preview/doc-preview-scheme' type DocPreviewFailureSink = { send: (channel: string, payload: DocPreviewFailure) => void diff --git a/src/main/browser/document-preview/doc-preview-file-reader.ts b/src/main/browser/document-preview/doc-preview-file-reader.ts index dd1def460d7..457b19e8eef 100644 --- a/src/main/browser/document-preview/doc-preview-file-reader.ts +++ b/src/main/browser/document-preview/doc-preview-file-reader.ts @@ -1,12 +1,12 @@ import { extname } from 'node:path' -import type { RuntimeFilePreviewResult } from '../../../shared/runtime-file-contracts' -import type { DocPreviewFileFailureReason } from '../../../shared/doc-preview-scheme' -import { FONT_FILE_MIME_TYPES } from '../../../shared/font-file-extensions' -import { isBinaryBuffer } from '../../../shared/binary-buffer' +import type { RuntimeFilePreviewResult } from '../../../shared/file-content/runtime-file-read' +import type { DocPreviewFileFailureReason } from '../../../shared/document-preview/doc-preview-scheme' +import { FONT_FILE_MIME_TYPES } from '../../../shared/file-preview/font-file-extensions' +import { isBinaryBuffer } from '../../../shared/file-preview/binary-buffer' import { DOC_PREVIEW_FILE_CHANGED_MESSAGE, type DocPreviewFileChunk -} from '../../../shared/doc-preview-file-access' +} from '../../../shared/document-preview/doc-preview-file-access' import { callRuntimeEnvironment } from '../../ipc/runtime-environments/runtime-environment-transport-routing' import { SSH_HOST_NOT_SERVED_MESSAGE } from '../../providers/ssh-host-not-served-error' import { diff --git a/src/main/browser/document-preview/doc-preview-grant-registry.ts b/src/main/browser/document-preview/doc-preview-grant-registry.ts index b4b0ac58f21..133f477cccf 100644 --- a/src/main/browser/document-preview/doc-preview-grant-registry.ts +++ b/src/main/browser/document-preview/doc-preview-grant-registry.ts @@ -1,7 +1,7 @@ import { randomBytes } from 'node:crypto' import { posix, win32 } from 'node:path' import { isWindowsAbsolutePathLike } from '../../../shared/cross-platform-path' -import { parseDocPreviewUrl } from '../../../shared/doc-preview-scheme' +import { parseDocPreviewUrl } from '../../../shared/document-preview/doc-preview-scheme' export type DocPreviewOwner = | { kind: 'ssh'; connectionId: string } diff --git a/src/main/browser/document-preview/doc-preview-guest-policy.test.ts b/src/main/browser/document-preview/doc-preview-guest-policy.test.ts index d3255e83b89..c88a3ebef6e 100644 --- a/src/main/browser/document-preview/doc-preview-guest-policy.test.ts +++ b/src/main/browser/document-preview/doc-preview-guest-policy.test.ts @@ -4,7 +4,7 @@ import { installDocPreviewGuestPolicy, readDocPreviewGuestDocumentUrl } from './doc-preview-guest-policy' -import { buildDocPreviewUrl } from '../../../shared/doc-preview-scheme' +import { buildDocPreviewUrl } from '../../../shared/document-preview/doc-preview-scheme' import { mintDocPreviewGrant, revokeAllDocPreviewGrants } from './doc-preview-grant-registry' type GuestHandlers = Record void> diff --git a/src/main/browser/document-preview/doc-preview-guest-policy.ts b/src/main/browser/document-preview/doc-preview-guest-policy.ts index 9e7a43f1135..fb6ff0a71f0 100644 --- a/src/main/browser/document-preview/doc-preview-guest-policy.ts +++ b/src/main/browser/document-preview/doc-preview-guest-policy.ts @@ -2,7 +2,7 @@ import { DOC_PREVIEW_EXTERNAL_LINK_CHANNEL, parseDocPreviewUrl, type DocPreviewExternalLink -} from '../../../shared/doc-preview-scheme' +} from '../../../shared/document-preview/doc-preview-scheme' import { normalizeExternalBrowserUrl } from '../../../shared/browser-url' import { enforceBrowserRouteWebRtcPolicy } from '../network/egress/browser-route-webrtc-policy' import { getDocPreviewGrant } from './doc-preview-grant-registry' diff --git a/src/main/browser/document-preview/doc-preview-protocol.ts b/src/main/browser/document-preview/doc-preview-protocol.ts index 872ea223302..f57b7089bbd 100644 --- a/src/main/browser/document-preview/doc-preview-protocol.ts +++ b/src/main/browser/document-preview/doc-preview-protocol.ts @@ -3,7 +3,7 @@ import { DOC_PREVIEW_PARTITION, DOC_PREVIEW_SCHEME, parseDocPreviewUrl -} from '../../../shared/doc-preview-scheme' +} from '../../../shared/document-preview/doc-preview-scheme' import { installBrowserSessionPartitionPolicies } from '../sessions/browser-session-partition-policies' import { readDocPreviewFile } from './doc-preview-file-reader' import { publishDocPreviewFailure } from './doc-preview-failure-notice' diff --git a/src/main/browser/document-preview/doc-preview-response-allocation.test.ts b/src/main/browser/document-preview/doc-preview-response-allocation.test.ts deleted file mode 100644 index ec5bca116af..00000000000 --- a/src/main/browser/document-preview/doc-preview-response-allocation.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { Buffer } from 'node:buffer' -import { createHash } from 'node:crypto' -import { types } from 'node:util' -import { runInNewContext } from 'node:vm' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const mocks = vi.hoisted(() => ({ readDocPreviewFile: vi.fn() })) -vi.mock('electron', () => ({ protocol: {}, session: {} })) -vi.mock('./doc-preview-file-reader', () => ({ readDocPreviewFile: mocks.readDocPreviewFile })) -vi.mock('../sessions/browser-session-partition-policies', () => ({ - installBrowserSessionPartitionPolicies: vi.fn() -})) - -import { buildDocPreviewUrl } from '../../../shared/doc-preview-scheme' -import { setDocPreviewFailureSink } from './doc-preview-failure-notice' -import { mintDocPreviewGrant, revokeAllDocPreviewGrants } from './doc-preview-grant-registry' -import { handleDocPreviewRequest } from './doc-preview-protocol' - -function digest(bytes: Uint8Array): string { - return createHash('sha256').update(bytes).digest('hex') -} - -async function serve(bytes: Buffer, contentType = 'text/html; charset=utf-8'): Promise { - const grant = mintDocPreviewGrant({ - owner: { kind: 'ssh', connectionId: 'ssh-1' }, - root: '/home/alice/docs', - entryRelativePath: 'index.html', - browserPageId: 'page-1' - }) - mocks.readDocPreviewFile.mockResolvedValueOnce({ ok: true, bytes, contentType }) - return handleDocPreviewRequest(new Request(buildDocPreviewUrl(grant.id, 'index.html'))) -} - -beforeEach(() => { - vi.clearAllMocks() - revokeAllDocPreviewGrants() - setDocPreviewFailureSink(null) -}) - -afterEach(() => { - revokeAllDocPreviewGrants() -}) - -describe('document preview response allocation', () => { - it('keeps only the requested range and snapshots pooled, offset, shared and cross-realm bytes', async () => { - const payload = Buffer.from('

π😀\u0000 independent bytes

', 'utf8') - const expectedDigest = digest(payload) - const pooled = Buffer.from(payload) - expect(pooled.buffer.byteLength).toBeGreaterThan(pooled.byteLength) - - const backing = new ArrayBuffer(payload.byteLength + 4096) - new Uint8Array(backing).fill(0xa5) - const offset = Buffer.from(backing, 127, payload.byteLength) - offset.set(payload) - expect(offset.byteOffset).toBe(127) - - const sharedBacking = new SharedArrayBuffer(payload.byteLength + 4096) - const shared = Buffer.from(sharedBacking, 127, payload.byteLength) - shared.set(payload) - - const foreignBacking: unknown = runInNewContext('new ArrayBuffer(4096)') - if (!types.isAnyArrayBuffer(foreignBacking)) { - throw new Error('Expected a cross-realm byte backing') - } - expect(foreignBacking instanceof ArrayBuffer).toBe(false) - const foreign = Buffer.from(foreignBacking, 127, payload.byteLength) - foreign.set(payload) - - for (const source of [pooled, offset, shared, foreign]) { - const response = await serve(source) - source.fill(0x7f) - const clone = response.clone() - for (const body of [response, clone]) { - const bytes = Buffer.from(await body.arrayBuffer()) - expect(bytes.byteLength).toBe(payload.byteLength) - expect(digest(bytes)).toBe(expectedDigest) - expect(body.bodyUsed).toBe(true) - await expect(body.arrayBuffer()).rejects.toThrow() - expect(() => body.clone()).toThrow() - } - } - }) -}) diff --git a/src/main/browser/document-preview/doc-preview-terminal-file-reader.ts b/src/main/browser/document-preview/doc-preview-terminal-file-reader.ts index be98c3bd396..47862cf864f 100644 --- a/src/main/browser/document-preview/doc-preview-terminal-file-reader.ts +++ b/src/main/browser/document-preview/doc-preview-terminal-file-reader.ts @@ -1,4 +1,4 @@ -import type { RuntimeFilePreviewResult } from '../../../shared/runtime-file-contracts' +import type { RuntimeFilePreviewResult } from '../../../shared/file-content/runtime-file-read' import { callRuntimeEnvironment } from '../../ipc/runtime-environments/runtime-environment-transport-routing' import { getRuntimeEnvironmentRegistryRoot } from '../../ipc/runtime-environments/runtime-environment-registry-root' import { diff --git a/src/main/browser/element-grab/browser-grab-payload.test.ts b/src/main/browser/element-grab/browser-grab-payload.test.ts index e08471d719b..9cdf9c951e1 100644 --- a/src/main/browser/element-grab/browser-grab-payload.test.ts +++ b/src/main/browser/element-grab/browser-grab-payload.test.ts @@ -4,7 +4,7 @@ import { mintDocPreviewGrant, revokeDocPreviewGrant } from '../document-preview/doc-preview-grant-registry' -import { buildDocPreviewUrl } from '../../../shared/doc-preview-scheme' +import { buildDocPreviewUrl } from '../../../shared/document-preview/doc-preview-scheme' function makeRawPayload(overrides: Record = {}) { return { diff --git a/src/main/browser/guest-lifecycle/prompts/browser-external-app-launch.ts b/src/main/browser/guest-lifecycle/prompts/browser-external-app-launch.ts index 68a4a868359..eccdc1916f7 100644 --- a/src/main/browser/guest-lifecycle/prompts/browser-external-app-launch.ts +++ b/src/main/browser/guest-lifecycle/prompts/browser-external-app-launch.ts @@ -1,6 +1,6 @@ import { app, shell } from 'electron' -import { DOC_PREVIEW_SCHEME } from '../../../../shared/doc-preview-scheme' +import { DOC_PREVIEW_SCHEME } from '../../../../shared/document-preview/doc-preview-scheme' import { BROWSER_EXTENSION_API_SCHEME } from '../../../../shared/browser/extensions/browser-extension-worker-api' import { browserPagePromptOrigin, diff --git a/src/main/claude/claude-control-responses.ts b/src/main/claude/claude-control-responses.ts index 498fde83c30..0a5b6da70f9 100644 --- a/src/main/claude/claude-control-responses.ts +++ b/src/main/claude/claude-control-responses.ts @@ -1,4 +1,4 @@ -import { assertJsonTextStructureWithinLimits } from '../../shared/json-text-structure-limit' +import { assertJsonTextStructureWithinLimits } from '../../shared/json-stream/json-text-structure-limit' const CONTROL_JSON_LIMITS = { structuralTokens: 64 * 1024, nestingDepth: 16 } as const diff --git a/src/main/codex-accounts/fs-utils.ts b/src/main/codex-accounts/fs-utils.ts index 3f96309d25a..a4da92ceecf 100644 --- a/src/main/codex-accounts/fs-utils.ts +++ b/src/main/codex-accounts/fs-utils.ts @@ -3,7 +3,7 @@ import { existsSync, linkSync, rmSync, writeFileSync } from 'node:fs' import { dirname } from 'node:path' import { grantDirAcl } from '../windows/windows-directory-acl' import { isPermissionError } from '../filesystem/permission-errors' -import { nodeFileContentsEqualSync } from '../../shared/node-file-content-equality' +import { nodeFileContentsEqualSync } from '../../shared/file-content/node-file-content-equality' import { copyFileWithWindowsRetry, renameFileWithWindowsRetry, diff --git a/src/main/codex/configuration/agent-state-file-reader.test.ts b/src/main/codex/configuration/agent-state-file-reader.test.ts index eeb2be01f62..ea6a7f97edf 100644 --- a/src/main/codex/configuration/agent-state-file-reader.test.ts +++ b/src/main/codex/configuration/agent-state-file-reader.test.ts @@ -2,7 +2,7 @@ import { mkdtempSync, rmSync, truncateSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' -import { NodeFileReadTooLargeError } from '../../../shared/node-bounded-file-reader' +import { NodeFileReadTooLargeError } from '../../../shared/file-content/node-bounded-file-reader' import { MAX_AGENT_STATE_FILE_BYTES, MAX_AGENT_STATE_JSON_NESTING_DEPTH, @@ -34,17 +34,6 @@ describe('readAgentStateFileSync', () => { expect(readAgentStateFileSync(filePath)).toBe(contents) }) - it('reads a sparse file at the exact 4 MiB boundary', () => { - const filePath = tempFile('snapshot.json') - writeFileSync(filePath, '') - truncateSync(filePath, MAX_AGENT_STATE_FILE_BYTES) - - const contents = readAgentStateFileSync(filePath) - - expect(contents).toHaveLength(MAX_AGENT_STATE_FILE_BYTES) - expect(contents.charCodeAt(MAX_AGENT_STATE_FILE_BYTES - 1)).toBe(0) - }) - it('rejects a sparse file one byte over the boundary before reading its payload', () => { const filePath = tempFile('oversized.json') writeFileSync(filePath, '') diff --git a/src/main/codex/configuration/agent-state-file-reader.ts b/src/main/codex/configuration/agent-state-file-reader.ts index 6289c6aedb6..d715485234e 100644 --- a/src/main/codex/configuration/agent-state-file-reader.ts +++ b/src/main/codex/configuration/agent-state-file-reader.ts @@ -1,5 +1,5 @@ -import { readNodeFileSyncWithinLimit } from '../../../shared/node-bounded-file-reader' -import { assertJsonTextStructureWithinLimits } from '../../../shared/json-text-structure-limit' +import { readNodeFileSyncWithinLimit } from '../../../shared/file-content/node-bounded-file-reader' +import { assertJsonTextStructureWithinLimits } from '../../../shared/json-stream/json-text-structure-limit' export const MAX_AGENT_STATE_FILE_BYTES = 4 * 1024 * 1024 export const MAX_AGENT_STATE_JSON_STRUCTURAL_TOKENS = 1_000_000 diff --git a/src/main/codex/configuration/settings/config-settings-baseline.ts b/src/main/codex/configuration/settings/config-settings-baseline.ts index 2ffb57a9886..a0ad11afd18 100644 --- a/src/main/codex/configuration/settings/config-settings-baseline.ts +++ b/src/main/codex/configuration/settings/config-settings-baseline.ts @@ -1,7 +1,7 @@ import { writeFileSync } from 'node:fs' import { isDefinitiveAbsence } from '../../../../shared/definitive-filesystem-absence' -import { JsonTextStructureCapacityError } from '../../../../shared/json-text-structure-limit' -import { NodeFileReadTooLargeError } from '../../../../shared/node-bounded-file-reader' +import { JsonTextStructureCapacityError } from '../../../../shared/json-stream/json-text-structure-limit' +import { NodeFileReadTooLargeError } from '../../../../shared/file-content/node-bounded-file-reader' import { join } from 'node:path' import { readAgentStateFileSync, readAgentStateJsonFileSync } from '../agent-state-file-reader' diff --git a/src/main/codex/structured/items/codex-image-item-translation.ts b/src/main/codex/structured/items/codex-image-item-translation.ts index c1aa9bed42b..abbc6ae5308 100644 --- a/src/main/codex/structured/items/codex-image-item-translation.ts +++ b/src/main/codex/structured/items/codex-image-item-translation.ts @@ -1,6 +1,6 @@ import type { AgentJournalMessageItem } from '../../../../shared/agent-session/journal/agent-session-journal-types' import type { NativeChatBlock } from '../../../../shared/native-chat/native-chat-types' -import { buildImageDataUri } from '../../../../shared/image-data-uri' +import { buildImageDataUri } from '../../../../shared/file-preview/image-data-uri' import { readString } from '../../app-server/codex-item-field-readers' import type { CodexThreadItem } from './codex-thread-item-identity' diff --git a/src/main/connector-cloud/connector-turn-events.ts b/src/main/connector-cloud/connector-turn-events.ts index 5645a203e7c..ec2ef1a2794 100644 --- a/src/main/connector-cloud/connector-turn-events.ts +++ b/src/main/connector-cloud/connector-turn-events.ts @@ -8,7 +8,7 @@ import { ConnectorConversation, type ConnectorEvent } from '../../shared/connector-cloud-contract' -import { writeSecureJsonFile } from '../../shared/secure-file' +import { writeSecureJsonFile } from '../../shared/secure-storage/secure-file' import type { ConversationEvent, ConversationSnapshot diff --git a/src/main/credentials/encrypted-api-key-file-store.ts b/src/main/credentials/encrypted-api-key-file-store.ts index 0278c17a60c..a81706ae908 100644 --- a/src/main/credentials/encrypted-api-key-file-store.ts +++ b/src/main/credentials/encrypted-api-key-file-store.ts @@ -6,7 +6,7 @@ import { hardenExistingSecureFile, isUnreadableError, writeSecureFile -} from '../../shared/secure-file' +} from '../../shared/secure-storage/secure-file' import type { SecretAtRestProtection } from '../../shared/secret-at-rest-protection' import { ApiKeyFileUnreadableError } from './api-key-file-unreadable-error' diff --git a/src/main/credentials/integration-credential-file.ts b/src/main/credentials/integration-credential-file.ts index 56c3755cc90..4068bb9aadd 100644 --- a/src/main/credentials/integration-credential-file.ts +++ b/src/main/credentials/integration-credential-file.ts @@ -10,8 +10,8 @@ import { writeSync } from 'node:fs' import { getSecretStore } from '../../shared/secret-store' -import { fsyncFileSync } from '../../shared/secure-file' -import { writeRestrictedWindowsFile } from '../../shared/secure-path-windows-acl' +import { fsyncFileSync } from '../../shared/secure-storage/secure-file' +import { writeRestrictedWindowsFile } from '../../shared/secure-storage/secure-path-windows-acl' import { credentialDecryptionMessage, type IntegrationCredentialService diff --git a/src/main/daemon/admission/host-terminal-policy.ts b/src/main/daemon/admission/host-terminal-policy.ts index 3d1384b882e..56dc83fda02 100644 --- a/src/main/daemon/admission/host-terminal-policy.ts +++ b/src/main/daemon/admission/host-terminal-policy.ts @@ -2,7 +2,7 @@ import { createHash, randomUUID } from 'node:crypto' import { lstat, mkdir, rm, writeFile } from 'node:fs/promises' import { homedir } from 'node:os' import { dirname, join } from 'node:path' -import { readNodeFileWithinLimit } from '../../../shared/node-bounded-file-reader' +import { readNodeFileWithinLimit } from '../../../shared/file-content/node-bounded-file-reader' import { renameFileWithWindowsRetryAsync } from '../../../shared/windows-retry-file-operations' import { isConfiguredTerminalLimit, diff --git a/src/main/daemon/admission/system-pty-limit.ts b/src/main/daemon/admission/system-pty-limit.ts index 9dcbb348ab9..5617899d95b 100644 --- a/src/main/daemon/admission/system-pty-limit.ts +++ b/src/main/daemon/admission/system-pty-limit.ts @@ -1,5 +1,5 @@ import { runProcess } from '@orca/process-host' -import { readNodeFileWithinLimit } from '../../../shared/node-bounded-file-reader' +import { readNodeFileWithinLimit } from '../../../shared/file-content/node-bounded-file-reader' import { InFlightPromiseDedupe } from '../../../shared/in-flight-promise-dedupe' import { awaitDaemonValueWithinCallerDeadline } from '../launch/daemon-request-deadline' diff --git a/src/main/daemon/history/storage/terminal-history-file-reader.ts b/src/main/daemon/history/storage/terminal-history-file-reader.ts index dc1afac9c23..fff0c0244e0 100644 --- a/src/main/daemon/history/storage/terminal-history-file-reader.ts +++ b/src/main/daemon/history/storage/terminal-history-file-reader.ts @@ -1,7 +1,7 @@ import { readNodeFileSyncWithinLimit, readNodeFileWithinLimit -} from '../../../../shared/node-bounded-file-reader' +} from '../../../../shared/file-content/node-bounded-file-reader' export function readTerminalHistoryBuffer(filePath: string, maxBytes: number): Buffer { return readNodeFileSyncWithinLimit(filePath, maxBytes).buffer diff --git a/src/main/filesystem/destination-serialized-local-rename.ts b/src/main/filesystem/destination-serialized-local-rename.ts index 8ecd9b345ec..07b1f7144e0 100644 --- a/src/main/filesystem/destination-serialized-local-rename.ts +++ b/src/main/filesystem/destination-serialized-local-rename.ts @@ -1,6 +1,6 @@ import { realpath, rename } from 'node:fs/promises' import { dirname, normalize } from 'node:path' -import { assertNoClobberRenameDestinationAvailable } from '../../shared/filesystem-rename-collision' +import { assertNoClobberRenameDestinationAvailable } from '../../shared/file-write/filesystem-rename-collision' import { windowsFsPath } from '../wsl/filesystem/wsl-unc-drive-fs-path' // Parent-scoped serialization covers Unicode aliases without guessing filesystem collation. diff --git a/src/main/git/source-control/diff-result.ts b/src/main/git/source-control/diff-result.ts index 837e5188a2c..99a7a758e8d 100644 --- a/src/main/git/source-control/diff-result.ts +++ b/src/main/git/source-control/diff-result.ts @@ -3,7 +3,7 @@ import { getLargeDiffRenderLimit } from '../../../shared/large-diff-render-limit import { IMAGE_AND_PDF_PREVIEW_MIME_TYPES, filePreviewExtension -} from '../../../shared/file-preview-kind' +} from '../../../shared/file-preview/file-preview-kind' export function buildDiffResult( originalContent: string, diff --git a/src/main/git/source-control/git-blob-read.ts b/src/main/git/source-control/git-blob-read.ts index f7d329f4d44..f0916ae90a7 100644 --- a/src/main/git/source-control/git-blob-read.ts +++ b/src/main/git/source-control/git-blob-read.ts @@ -1,5 +1,5 @@ import { readFile, stat } from 'node:fs/promises' -import { isBinaryBuffer } from '../../../shared/binary-buffer' +import { isBinaryBuffer } from '../../../shared/file-preview/binary-buffer' import { isMissingGitBlobPath } from '../../../shared/git/diff/git-blob-absence' import { readGitCommandFailureStderr } from '../../../shared/git/commands/git-command-failure-text' import type { GitRuntimeOptions } from '../git-runtime-options' diff --git a/src/main/git/source-control/status-branch-compare.test.ts b/src/main/git/source-control/status-branch-compare.test.ts deleted file mode 100644 index d4a2486c006..00000000000 --- a/src/main/git/source-control/status-branch-compare.test.ts +++ /dev/null @@ -1,184 +0,0 @@ -import type * as RunnerModule from '../runner' -import type * as GitExecFileModule from '../command-runner/git-exec-file' -import type * as GitStreamStdoutModule from '../command-runner/git-stream-stdout' -import type * as GitProcessEnvModule from '../command-runner/git-process-env' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as BoundedFileReader from '../../../shared/node-bounded-file-reader' -import { - createBoundedFileReaderModuleMock, - createFsPromisesModuleMock, - createGitRunnerModuleMock -} from './status-test-harness' - -const { - gitExecFileAsyncMock, - gitExecFileAsyncBufferMock, - gitStreamOptionsMock, - lstatMock, - realpathMock, - readFileMock, - statMock, - rmMock, - existsSyncMock -} = vi.hoisted(() => ({ - gitExecFileAsyncMock: vi.fn(), - gitExecFileAsyncBufferMock: vi.fn(), - gitStreamOptionsMock: vi.fn(), - lstatMock: vi.fn(), - realpathMock: vi.fn(), - readFileMock: vi.fn(), - statMock: vi.fn(), - rmMock: vi.fn(), - existsSyncMock: vi.fn() -})) - -vi.mock('../runner', () => - createGitRunnerModuleMock({ - gitExecFileAsyncMock, - gitExecFileAsyncBufferMock, - gitStreamOptionsMock - }) -) - -vi.mock('../command-runner/git-exec-file', async (importOriginal) => { - const runnerMocks = await vi.importMock('../runner') - return { - ...(await importOriginal()), - gitExecFileAsync: runnerMocks.gitExecFileAsync, - gitExecFileAsyncBuffer: runnerMocks.gitExecFileAsyncBuffer - } -}) - -vi.mock('../command-runner/git-stream-stdout', async (importOriginal) => { - const runnerMocks = await vi.importMock('../runner') - return { - ...(await importOriginal()), - gitStreamStdout: runnerMocks.gitStreamStdout - } -}) - -vi.mock('../command-runner/git-process-env', async (importOriginal) => { - const runnerMocks = await vi.importMock('../runner') - return { - ...(await importOriginal()), - gitOptionalLocksDisabledEnv: runnerMocks.gitOptionalLocksDisabledEnv - } -}) - -vi.mock('fs/promises', () => - createFsPromisesModuleMock({ lstatMock, realpathMock, readFileMock, statMock, rmMock }) -) - -vi.mock('fs', () => ({ - existsSync: existsSyncMock -})) - -vi.mock('../../../shared/node-bounded-file-reader', async (importOriginal) => - createBoundedFileReaderModuleMock(await importOriginal(), { - readFileMock, - statMock - }) -) - -import { getBranchCompare } from './branch-compare' - -describe('getBranchCompare', () => { - beforeEach(() => { - gitExecFileAsyncMock.mockReset() - gitExecFileAsyncBufferMock.mockReset() - readFileMock.mockReset() - }) - - // Route by argv so independent concurrent reads can reorder safely. - type BranchCompareGitResponses = { - branch?: string | Error - probe?: Record - headOid?: string | Error - baseOid?: string | Error - mergeBase?: string | Error - onMergeBase?: () => void - nameStatus?: string | Error - numstat?: string | Error - revList?: string | Error - } - - function mockBranchCompareGit(responses: BranchCompareGitResponses): void { - const reply = ( - value: string | Error | undefined, - label: string - ): Promise<{ stdout: string }> => { - if (value === undefined) { - throw new Error(`unexpected git call: ${label}`) - } - return value instanceof Error ? Promise.reject(value) : Promise.resolve({ stdout: value }) - } - gitExecFileAsyncMock.mockImplementation((args: string[]) => { - if (args[0] === 'branch') { - return reply(responses.branch, 'branch --show-current') - } - if (args[0] === 'rev-parse' && args.includes('--quiet')) { - const probed = args.find((arg) => arg.endsWith('^{commit}')) ?? '' - return reply(responses.probe?.[probed], `probe ${probed}`) - } - if (args[0] === 'rev-parse' && args.includes('HEAD')) { - return reply(responses.headOid, 'rev-parse HEAD') - } - if (args[0] === 'rev-parse') { - return reply(responses.baseOid, `rev-parse ${args.at(-1)}`) - } - if (args[0] === 'merge-base') { - responses.onMergeBase?.() - return reply(responses.mergeBase, 'merge-base') - } - if (args.includes('--raw')) { - const raw = - typeof responses.nameStatus === 'string' - ? responses.nameStatus - .split(/\r?\n/) - .filter(Boolean) - .map((line) => { - const [status, ...paths] = line.split('\t') - return `:100644 100644 a b ${status}\0${paths.join('\0')}\0` - }) - .join('') - : responses.nameStatus - if (raw instanceof Error) { - return reply(raw, 'diff') - } - if (responses.numstat instanceof Error) { - return reply(responses.numstat, 'diff') - } - return reply((raw ?? '') + (responses.numstat ?? ''), 'diff') - } - if (args[0] === 'rev-list') { - return reply(responses.revList, 'rev-list') - } - throw new Error(`unexpected git args: ${args.join(' ')}`) - }) - } - - it('keeps cancellation effective when equal-tip validation settles', async () => { - const oid = 'a'.repeat(40) - const controller = new AbortController() - mockBranchCompareGit({ - branch: 'feature\n', - probe: { 'refs/remotes/origin/main^{commit}': `${oid}\n` }, - headOid: `${oid}\n`, - baseOid: `${oid}\n`, - mergeBase: `${oid}\n`, - onMergeBase: () => controller.abort(new Error('compare canceled')) - }) - - await expect( - getBranchCompare('/repo', 'origin/main', { signal: controller.signal }) - ).resolves.toMatchObject({ - summary: { status: 'error', errorMessage: 'compare canceled' }, - entries: [] - }) - expect( - gitExecFileAsyncMock.mock.calls.some(([args]) => ['diff', 'rev-list'].includes(args[0])) - ).toBe(false) - }) - - // Keep distinct probe results to catch accidental reuse of the losing ref's OID. -}) diff --git a/src/main/git/source-control/status-diff.test.ts b/src/main/git/source-control/status-diff.test.ts index 65b025fc2f0..6efb87276ca 100644 --- a/src/main/git/source-control/status-diff.test.ts +++ b/src/main/git/source-control/status-diff.test.ts @@ -3,9 +3,9 @@ import type * as GitExecFileModule from '../command-runner/git-exec-file' import type * as GitStreamStdoutModule from '../command-runner/git-stream-stdout' import type * as GitProcessEnvModule from '../command-runner/git-process-env' import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as BoundedFileReader from '../../../shared/node-bounded-file-reader' +import type * as BoundedFileReader from '../../../shared/file-content/node-bounded-file-reader' import path from 'node:path' -import { MAX_RENDERED_DIFF_COMBINED_CHARACTERS } from '../../../shared/large-diff-render-limit' + import { createBoundedFileReaderModuleMock, createFsPromisesModuleMock, @@ -75,7 +75,7 @@ vi.mock('fs', () => ({ existsSync: existsSyncMock })) -vi.mock('../../../shared/node-bounded-file-reader', async (importOriginal) => +vi.mock('../../../shared/file-content/node-bounded-file-reader', async (importOriginal) => createBoundedFileReaderModuleMock(await importOriginal(), { readFileMock, statMock @@ -96,51 +96,6 @@ describe('getDiff', () => { }) }) - it('does not read oversized working-tree files into memory', async () => { - const workingTreePath = path.join('/repo', 'dist/large.log') - gitExecFileAsyncBufferMock.mockResolvedValueOnce({ stdout: Buffer.from('index-content\n') }) - // Route stats by path so stamp reads cannot consume the oversized-file response. - statMock.mockImplementation(async (target: string) => - target === workingTreePath - ? { isFile: () => true, size: 10 * 1024 * 1024 + 1 } - : { isFile: () => true, size: 12 } - ) - - const result = await getDiff('/repo', 'dist/large.log', false) - - expect(readFileMock).not.toHaveBeenCalledWith(workingTreePath) - expect(result.kind).toBe('binary') - expect(result.modifiedIsBinary).toBe(true) - expect(result.modifiedContent).toBe('') - }) - - it('omits over-limit text bodies before returning the diff payload', async () => { - const oversizedText = 'a'.repeat(MAX_RENDERED_DIFF_COMBINED_CHARACTERS + 1) - gitExecFileAsyncBufferMock.mockResolvedValueOnce({ stdout: Buffer.from('index-content\n') }) - statMock.mockResolvedValueOnce({ - isFile: () => true, - size: oversizedText.length - }) - readFileMock.mockResolvedValue(Buffer.from(oversizedText)) - - const result = await getDiff('/repo', 'dist/large.log', false) - - expect(result.kind).toBe('text') - if (result.kind !== 'text') { - throw new Error('expected text diff result') - } - expect(result.originalContent).toBe('') - expect(result.modifiedContent).toBe('') - expect(result.largeDiffRenderLimit?.limited).toBe(true) - if (result.largeDiffRenderLimit?.limited !== true) { - throw new Error('expected large diff render limit') - } - expect(result.largeDiffRenderLimit.reason).toBe('character-count') - expect(result.largeDiffRenderLimit.characterCount).toBe( - oversizedText.length + 'index-content\n'.length - ) - }) - it('does not treat an unreadable working-tree image as a deletion', async () => { const pngBuffer = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x00]) const workingTreePath = path.join('/repo', 'assets/unreadable.png') diff --git a/src/main/git/source-control/status-discard-and-bulk-staging.test.ts b/src/main/git/source-control/status-discard-and-bulk-staging.test.ts deleted file mode 100644 index 47d781c68e8..00000000000 --- a/src/main/git/source-control/status-discard-and-bulk-staging.test.ts +++ /dev/null @@ -1,153 +0,0 @@ -import type * as RunnerModule from '../runner' -import type * as GitExecFileModule from '../command-runner/git-exec-file' -import type * as GitStreamStdoutModule from '../command-runner/git-stream-stdout' -import type * as GitProcessEnvModule from '../command-runner/git-process-env' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as BoundedFileReader from '../../../shared/node-bounded-file-reader' -import path from 'node:path' -import { - createBoundedFileReaderModuleMock, - createFsPromisesModuleMock, - createGitRunnerModuleMock -} from './status-test-harness' - -const { - gitExecFileAsyncMock, - gitExecFileAsyncBufferMock, - gitStreamOptionsMock, - lstatMock, - realpathMock, - readFileMock, - statMock, - rmMock, - existsSyncMock -} = vi.hoisted(() => ({ - gitExecFileAsyncMock: vi.fn(), - gitExecFileAsyncBufferMock: vi.fn(), - gitStreamOptionsMock: vi.fn(), - lstatMock: vi.fn(), - realpathMock: vi.fn(), - readFileMock: vi.fn(), - statMock: vi.fn(), - rmMock: vi.fn(), - existsSyncMock: vi.fn() -})) - -vi.mock('../runner', () => - createGitRunnerModuleMock({ - gitExecFileAsyncMock, - gitExecFileAsyncBufferMock, - gitStreamOptionsMock - }) -) - -vi.mock('../command-runner/git-exec-file', async (importOriginal) => { - const runnerMocks = await vi.importMock('../runner') - return { - ...(await importOriginal()), - gitExecFileAsync: runnerMocks.gitExecFileAsync, - gitExecFileAsyncBuffer: runnerMocks.gitExecFileAsyncBuffer - } -}) - -vi.mock('../command-runner/git-stream-stdout', async (importOriginal) => { - const runnerMocks = await vi.importMock('../runner') - return { - ...(await importOriginal()), - gitStreamStdout: runnerMocks.gitStreamStdout - } -}) - -vi.mock('../command-runner/git-process-env', async (importOriginal) => { - const runnerMocks = await vi.importMock('../runner') - return { - ...(await importOriginal()), - gitOptionalLocksDisabledEnv: runnerMocks.gitOptionalLocksDisabledEnv - } -}) - -vi.mock('fs/promises', () => - createFsPromisesModuleMock({ lstatMock, realpathMock, readFileMock, statMock, rmMock }) -) - -vi.mock('fs', () => ({ - existsSync: existsSyncMock -})) - -vi.mock('../../../shared/node-bounded-file-reader', async (importOriginal) => - createBoundedFileReaderModuleMock(await importOriginal(), { - readFileMock, - statMock - }) -) - -import { bulkDiscardChanges, discardChanges } from './discard-changes' -import { bulkStageFiles, bulkUnstageFiles } from './staging' - -describe('discardChanges', () => { - beforeEach(() => { - gitExecFileAsyncMock.mockReset() - gitExecFileAsyncBufferMock.mockReset() - lstatMock.mockReset() - realpathMock.mockReset() - readFileMock.mockReset() - rmMock.mockReset() - lstatMock.mockRejectedValue(Object.assign(new Error('missing'), { code: 'ENOENT' })) - realpathMock.mockImplementation(async (targetPath: string) => path.resolve(targetPath)) - }) - - it('rejects paths that traverse outside the worktree', async () => { - await expect(discardChanges('/repo', '../../etc/passwd')).rejects.toThrow( - 'resolves outside the worktree' - ) - - expect(gitExecFileAsyncMock).not.toHaveBeenCalled() - expect(rmMock).not.toHaveBeenCalled() - }) -}) - -describe('bulk git helpers', () => { - beforeEach(() => { - gitExecFileAsyncMock.mockReset() - lstatMock.mockReset() - realpathMock.mockReset() - rmMock.mockReset() - lstatMock.mockRejectedValue(Object.assign(new Error('missing'), { code: 'ENOENT' })) - realpathMock.mockImplementation(async (targetPath: string) => path.resolve(targetPath)) - }) - - it('preserves bulk discard action selection and original path order for path edges', async () => { - const filePaths = ['new', 'docs\\', '[ab].txt', 'docs///', 'new', 'src/file', 'docs\\'] - gitExecFileAsyncMock - .mockResolvedValueOnce({ stdout: 'docs/readme\0src/file-extra\0[ab].txt\0' }) - .mockResolvedValue({ stdout: '' }) - - await bulkDiscardChanges('/repo', filePaths) - - expect(gitExecFileAsyncMock.mock.calls.map(([args]) => args)).toEqual([ - ['ls-files', '-z', '--', ...filePaths.map((filePath) => `:(literal)${filePath}`)], - ['restore', '--worktree', '--pathspec-from-file=-', '--pathspec-file-nul'], - ['clean', '-ffdx', '--', ':(literal)new', ':(literal)new', ':(literal)src/file'] - ]) - expect(gitExecFileAsyncMock.mock.calls[1][1].stdin).toBe( - ':(literal)docs\\\0:(literal)[ab].txt\0:(literal)docs///\0:(literal)docs\\\0' - ) - expect(rmMock).not.toHaveBeenCalled() - }) - - it('rejects bulk discard paths that traverse outside the worktree', async () => { - await expect(bulkDiscardChanges('/repo', ['src/file.ts', '../outside.txt'])).rejects.toThrow( - 'resolves outside the worktree' - ) - - expect(gitExecFileAsyncMock).not.toHaveBeenCalled() - expect(rmMock).not.toHaveBeenCalled() - }) - - it('rejects embedded NUL before staging or unstaging another path', async () => { - await expect(bulkStageFiles('/repo', ['one\0two'])).rejects.toThrow('NUL') - await expect(bulkUnstageFiles('/repo', ['one\0two'])).rejects.toThrow('NUL') - - expect(gitExecFileAsyncMock).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/git/source-control/status-line-stats-host-paths.test.ts b/src/main/git/source-control/status-line-stats-host-paths.test.ts index 854934b4009..1f2981b56c2 100644 --- a/src/main/git/source-control/status-line-stats-host-paths.test.ts +++ b/src/main/git/source-control/status-line-stats-host-paths.test.ts @@ -2,7 +2,7 @@ import * as path from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type * as FsPromises from 'node:fs/promises' -import type * as BoundedFileReader from '../../../shared/node-bounded-file-reader' +import type * as BoundedFileReader from '../../../shared/file-content/node-bounded-file-reader' import type { GitStatusEntry } from '../../../shared/git/status/git-status-types' import { invalidateGitBranchLineTotalInFlight } from '../../../shared/git/status/git-branch-line-total' @@ -33,7 +33,7 @@ vi.mock('node:fs/promises', async (importOriginal) => { } }) -vi.mock('../../../shared/node-bounded-file-reader', async (importOriginal) => { +vi.mock('../../../shared/file-content/node-bounded-file-reader', async (importOriginal) => { const actual = await importOriginal() return { ...actual, diff --git a/src/main/git/source-control/status-read-coalescing.test.ts b/src/main/git/source-control/status-read-coalescing.test.ts deleted file mode 100644 index 9ffa37bf184..00000000000 --- a/src/main/git/source-control/status-read-coalescing.test.ts +++ /dev/null @@ -1,167 +0,0 @@ -import type * as RunnerModule from '../runner' -import type * as GitExecFileModule from '../command-runner/git-exec-file' -import type * as GitStreamStdoutModule from '../command-runner/git-stream-stdout' -import type * as GitProcessEnvModule from '../command-runner/git-process-env' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as BoundedFileReader from '../../../shared/node-bounded-file-reader' -import { - createBoundedFileReaderModuleMock, - createFsPromisesModuleMock, - createGitRunnerModuleMock -} from './status-test-harness' - -const { - gitExecFileAsyncMock, - gitExecFileAsyncBufferMock, - gitStreamOptionsMock, - lstatMock, - realpathMock, - readFileMock, - statMock, - rmMock, - existsSyncMock -} = vi.hoisted(() => ({ - gitExecFileAsyncMock: vi.fn(), - gitExecFileAsyncBufferMock: vi.fn(), - gitStreamOptionsMock: vi.fn(), - lstatMock: vi.fn(), - realpathMock: vi.fn(), - readFileMock: vi.fn(), - statMock: vi.fn(), - rmMock: vi.fn(), - existsSyncMock: vi.fn() -})) - -vi.mock('../runner', () => - createGitRunnerModuleMock({ - gitExecFileAsyncMock, - gitExecFileAsyncBufferMock, - gitStreamOptionsMock - }) -) - -vi.mock('../command-runner/git-exec-file', async (importOriginal) => { - const runnerMocks = await vi.importMock('../runner') - return { - ...(await importOriginal()), - gitExecFileAsync: runnerMocks.gitExecFileAsync, - gitExecFileAsyncBuffer: runnerMocks.gitExecFileAsyncBuffer - } -}) - -vi.mock('../command-runner/git-stream-stdout', async (importOriginal) => { - const runnerMocks = await vi.importMock('../runner') - return { - ...(await importOriginal()), - gitStreamStdout: runnerMocks.gitStreamStdout - } -}) - -vi.mock('../command-runner/git-process-env', async (importOriginal) => { - const runnerMocks = await vi.importMock('../runner') - return { - ...(await importOriginal()), - gitOptionalLocksDisabledEnv: runnerMocks.gitOptionalLocksDisabledEnv - } -}) - -vi.mock('fs/promises', () => - createFsPromisesModuleMock({ lstatMock, realpathMock, readFileMock, statMock, rmMock }) -) - -vi.mock('fs', () => ({ - existsSync: existsSyncMock -})) - -vi.mock('../../../shared/node-bounded-file-reader', async (importOriginal) => - createBoundedFileReaderModuleMock(await importOriginal(), { - readFileMock, - statMock - }) -) - -import { clearEffectiveUpstreamStatusCacheForTests } from './effective-upstream-status-cache' -import { getStatus } from './status-read' - -describe('getStatus', () => { - beforeEach(() => { - clearEffectiveUpstreamStatusCacheForTests() - gitExecFileAsyncMock.mockReset() - gitExecFileAsyncBufferMock.mockReset() - gitStreamOptionsMock.mockReset() - lstatMock.mockReset() - readFileMock.mockReset() - existsSyncMock.mockReset() - // Supply empty numstat results after tests' one-shot status responses. - gitExecFileAsyncMock.mockResolvedValue({ stdout: '' }) - }) - - it('shares one physical status read across distinct caller signals', async () => { - readFileMock.mockResolvedValue('gitdir: /repo/.git/worktrees/feature\n') - existsSyncMock.mockReturnValue(false) - let releaseStatus!: () => void - let statusCommandCalls = 0 - gitExecFileAsyncMock.mockImplementation((args: string[]) => { - if (args.includes('status')) { - statusCommandCalls += 1 - return new Promise<{ stdout: string }>((resolve) => { - releaseStatus = () => resolve({ stdout: '' }) - }) - } - return Promise.resolve({ stdout: '' }) - }) - const firstController = new AbortController() - const secondController = new AbortController() - const firstError = new Error('first caller cancelled') - const first = getStatus('/repo', { signal: firstController.signal }) - const second = getStatus('/repo', { signal: secondController.signal }) - - await vi.waitFor(() => expect(statusCommandCalls).toBe(1)) - const underlyingSignal = gitStreamOptionsMock.mock.calls[0]?.[0].signal as AbortSignal - firstController.abort(firstError) - await expect(first).rejects.toBe(firstError) - expect(underlyingSignal?.aborted).toBe(false) - - releaseStatus() - await expect(second).resolves.toMatchObject({ entries: [] }) - expect(statusCommandCalls).toBe(1) - }) - - it('aborts physical status work after its last live caller cancels', async () => { - readFileMock.mockResolvedValue('gitdir: /repo/.git/worktrees/feature\n') - existsSyncMock.mockReturnValue(false) - let statusCommandCalls = 0 - let rejectStatus!: (error: unknown) => void - gitExecFileAsyncMock.mockImplementation((args: string[]) => { - if (!args.includes('status')) { - return Promise.resolve({ stdout: '' }) - } - statusCommandCalls += 1 - if (statusCommandCalls > 1) { - return Promise.resolve({ stdout: '' }) - } - return new Promise<{ stdout: string }>((_resolve, reject) => { - rejectStatus = reject - }) - }) - const firstController = new AbortController() - const secondController = new AbortController() - const first = getStatus('/repo', { signal: firstController.signal }) - const second = getStatus('/repo', { signal: secondController.signal }) - - await vi.waitFor(() => expect(statusCommandCalls).toBe(1)) - const underlyingSignal = gitStreamOptionsMock.mock.calls[0]?.[0].signal as AbortSignal - underlyingSignal.addEventListener('abort', () => rejectStatus(underlyingSignal.reason), { - once: true - }) - firstController.abort(new Error('first cancelled')) - await expect(first).rejects.toThrow('first cancelled') - expect(underlyingSignal.aborted).toBe(false) - secondController.abort(new Error('second cancelled')) - await expect(second).rejects.toThrow('second cancelled') - expect(underlyingSignal.aborted).toBe(true) - - await expect(getStatus('/repo')).resolves.toMatchObject({ entries: [] }) - expect(statusCommandCalls).toBe(2) - }) -}) diff --git a/src/main/git/source-control/status-submodule.test.ts b/src/main/git/source-control/status-submodule.test.ts index 92e960ff7eb..c7f8f15790a 100644 --- a/src/main/git/source-control/status-submodule.test.ts +++ b/src/main/git/source-control/status-submodule.test.ts @@ -3,7 +3,7 @@ import type * as GitExecFileModule from '../command-runner/git-exec-file' import type * as GitStreamStdoutModule from '../command-runner/git-stream-stdout' import type * as GitProcessEnvModule from '../command-runner/git-process-env' import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as BoundedFileReader from '../../../shared/node-bounded-file-reader' +import type * as BoundedFileReader from '../../../shared/file-content/node-bounded-file-reader' import path from 'node:path' import { createBoundedFileReaderModuleMock, @@ -74,13 +74,13 @@ vi.mock('fs', () => ({ existsSync: existsSyncMock })) -vi.mock('../../../shared/node-bounded-file-reader', async (importOriginal) => +vi.mock('../../../shared/file-content/node-bounded-file-reader', async (importOriginal) => createBoundedFileReaderModuleMock(await importOriginal(), { readFileMock, statMock }) ) -import { clearSubmodulePathsCacheForTests, listSubmodulePaths } from './submodule-paths' +import { clearSubmodulePathsCacheForTests } from './submodule-paths' import { getDiff } from './file-diff' describe('submodule diff routing', () => { @@ -143,30 +143,3 @@ describe('submodule diff routing', () => { await expect(getDiff(PARENT, '../evil', false)).rejects.toThrow('Access denied') }) }) - -describe('listSubmodulePaths', () => { - beforeEach(() => { - clearSubmodulePathsCacheForTests() - gitExecFileAsyncMock.mockReset() - }) - - it('keeps cached .gitmodules paths separate per WSL distro', async () => { - gitExecFileAsyncMock.mockImplementation((_args: string[], options?: { wslDistro?: string }) => - Promise.resolve({ - stdout: - options?.wslDistro === 'debian' - ? 'submodule.lib.path\ndebian-lib\0' - : 'submodule.lib.path\nubuntu-lib\0' - }) - ) - - await expect(listSubmodulePaths('/repo', { wslDistro: 'ubuntu' })).resolves.toEqual([ - 'ubuntu-lib' - ]) - await expect(listSubmodulePaths('/repo', { wslDistro: 'debian' })).resolves.toEqual([ - 'debian-lib' - ]) - - expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(2) - }) -}) diff --git a/src/main/git/source-control/status-test-harness.ts b/src/main/git/source-control/status-test-harness.ts index 0db2d777f20..0ceb169a149 100644 --- a/src/main/git/source-control/status-test-harness.ts +++ b/src/main/git/source-control/status-test-harness.ts @@ -1,5 +1,5 @@ import type { Mock } from 'vitest' -import type * as BoundedFileReader from '../../../shared/node-bounded-file-reader' +import type * as BoundedFileReader from '../../../shared/file-content/node-bounded-file-reader' type MockFn = Mock diff --git a/src/main/git/source-control/textconv-driver.ts b/src/main/git/source-control/textconv-driver.ts index 42f2aacbfd1..3f1136d7f98 100644 --- a/src/main/git/source-control/textconv-driver.ts +++ b/src/main/git/source-control/textconv-driver.ts @@ -1,7 +1,7 @@ import { IMAGE_AND_PDF_PREVIEW_MIME_TYPES, filePreviewExtension -} from '../../../shared/file-preview-kind' +} from '../../../shared/file-preview/file-preview-kind' import type { GitRuntimeOptions } from '../git-runtime-options' import { gitReadOptionsForWorktree } from '../git-runtime-options' import { gitExecFileAsync } from '../runner' diff --git a/src/main/ipc/app.ts b/src/main/ipc/app.ts index 75686db022e..d44b677b5ca 100644 --- a/src/main/ipc/app.ts +++ b/src/main/ipc/app.ts @@ -6,7 +6,7 @@ import path from 'node:path' import { pathToFileURL } from 'node:url' import { app, BrowserWindow, dialog, ipcMain, type IpcMainInvokeEvent } from 'electron' import type { AppIdentity } from '../../shared/app-identity' -import type { MarkdownDocument } from '../../shared/filesystem-entry-types' +import type { MarkdownDocument } from '../../shared/file-listing/file-document' import type { FloatingTerminalCwdRequest } from '../../shared/ui-chrome-types' import { relaunchApp, runBeforeRelaunchCleanup } from '../startup/quit/app-relaunch' import { setWindowMaterialSuppressed } from '../window/window-material-suppression' @@ -29,7 +29,7 @@ import { import { isMarkdownDocumentName, markdownDocumentFromFilePath -} from '../../shared/markdown-document-paths' +} from '../../shared/file-listing/markdown-document-paths' import { registerMacSymbolicHotkeysProbeHandler } from './macos-symbolic-hotkeys-probe' import { registerRendererShutdownCheckpointHandler, diff --git a/src/main/ipc/doc-preview-grant-ipc.ts b/src/main/ipc/doc-preview-grant-ipc.ts index 2ba025c7b24..063ad916545 100644 --- a/src/main/ipc/doc-preview-grant-ipc.ts +++ b/src/main/ipc/doc-preview-grant-ipc.ts @@ -5,7 +5,7 @@ import { DOC_PREVIEW_LINK_CLICK_CHANNEL, DOC_PREVIEW_MINT_GRANT_CHANNEL, DOC_PREVIEW_REVOKE_GRANT_CHANNEL -} from '../../shared/doc-preview-scheme' +} from '../../shared/document-preview/doc-preview-scheme' import { browserManager } from '../browser/browser-manager' import { reportDocPreviewLinkClick } from '../browser/document-preview/doc-preview-guest-policy' import { diff --git a/src/main/ipc/filesystem/access/filesystem-auth.ts b/src/main/ipc/filesystem/access/filesystem-auth.ts index 2ee958b318b..66c955c01fe 100644 --- a/src/main/ipc/filesystem/access/filesystem-auth.ts +++ b/src/main/ipc/filesystem/access/filesystem-auth.ts @@ -5,7 +5,7 @@ import { realpathAcrossWslDriveMount, windowsFsPath } from '../../../wsl/filesystem/wsl-unc-drive-fs-path' -import { PATH_OUTSIDE_ALLOWED_DIRECTORIES } from '../../../../shared/local-file-access' +import { PATH_OUTSIDE_ALLOWED_DIRECTORIES } from '../../../../shared/file-access/local-file-access' import { getAllowedRoots } from './filesystem-allowed-roots' import { isDescendantOrEqual, isENOENT, normalizeExistingPath } from './filesystem-path-containment' import { diff --git a/src/main/ipc/filesystem/access/local-file-access-resolution.ts b/src/main/ipc/filesystem/access/local-file-access-resolution.ts index e5cf20c10bf..de15278abfe 100644 --- a/src/main/ipc/filesystem/access/local-file-access-resolution.ts +++ b/src/main/ipc/filesystem/access/local-file-access-resolution.ts @@ -1,14 +1,14 @@ import { dirname, isAbsolute, resolve } from 'node:path' import { stat } from 'node:fs/promises' import type { RuntimeStore } from '../../../runtime/construction/runtime-store-contract' -import type { LocalFileAccess } from '../../../../shared/local-file-access' +import type { LocalFileAccess } from '../../../../shared/file-access/local-file-access' import { PATH_ACCESS_DENIED_MESSAGE, resolveAuthorizedPath, type ResolveAuthorizedPathOptions } from './filesystem-auth' import { isDescendantOrEqual } from './filesystem-path-containment' -import { filePreviewForPath } from '../../../../shared/file-preview-kind' +import { filePreviewForPath } from '../../../../shared/file-preview/file-preview-kind' import { getDefaultFloatingWorkspacePath } from '../../floating-workspace-directory' import { isDeviceNamespacePath, diff --git a/src/main/ipc/filesystem/filesystem-chunk-read-handler.ts b/src/main/ipc/filesystem/filesystem-chunk-read-handler.ts index 37836f662d2..5ecf9b9baa8 100644 --- a/src/main/ipc/filesystem/filesystem-chunk-read-handler.ts +++ b/src/main/ipc/filesystem/filesystem-chunk-read-handler.ts @@ -1,9 +1,9 @@ import { ipcMain } from 'electron' import { readLocalFileRange } from './local-file-range-read' -import { validateFileRangeRequest } from '../../../shared/file-range-read' +import { validateFileRangeRequest } from '../../../shared/file-content/file-range-read' import { SshHostNotServedError } from '../../providers/ssh-host-not-served-error' import { resolveLocalFileRequestPath } from './access/local-file-access-resolution' -import type { LocalFileAccess } from '../../../shared/local-file-access' +import type { LocalFileAccess } from '../../../shared/file-access/local-file-access' import type { FilesystemHandlerContext } from './filesystem-handler-context' import { guardWslUncPathAccess } from '../../wsl/filesystem/wsl-unc-access-gate' diff --git a/src/main/ipc/filesystem/filesystem-content-search-handler.ts b/src/main/ipc/filesystem/filesystem-content-search-handler.ts index a4881059bbf..8e7f6d83f67 100644 --- a/src/main/ipc/filesystem/filesystem-content-search-handler.ts +++ b/src/main/ipc/filesystem/filesystem-content-search-handler.ts @@ -1,5 +1,5 @@ import { ipcMain } from 'electron' -import type { SearchOptions, SearchResult } from '../../../shared/code-search-types' +import type { SearchOptions, SearchResult } from '../../../shared/file-search/code-search-types' import { throwIfSignalAborted, waitForPromiseWithSignal } from '../../../shared/abort-signal-reason' import { resolveBundledRipgrepWslRouting } from '../../ripgrep/bundled-ripgrep-wsl-routing' import { SshHostNotServedError } from '../../providers/ssh-host-not-served-error' diff --git a/src/main/ipc/filesystem/filesystem-file-content-inspection.ts b/src/main/ipc/filesystem/filesystem-file-content-inspection.ts index 910adce424a..6a4634255f4 100644 --- a/src/main/ipc/filesystem/filesystem-file-content-inspection.ts +++ b/src/main/ipc/filesystem/filesystem-file-content-inspection.ts @@ -1,9 +1,9 @@ import { IMAGE_AND_PDF_PREVIEW_MIME_TYPES, filePreviewExtension -} from '../../../shared/file-preview-kind' +} from '../../../shared/file-preview/file-preview-kind' import { localLogFileIdentity } from '../../ai-vault/transcripts/local-log-tail-reader' -import { BINARY_PROBE_BYTES, isBinaryBuffer } from '../../../shared/binary-buffer' +import { BINARY_PROBE_BYTES, isBinaryBuffer } from '../../../shared/file-preview/binary-buffer' import { fileTooLargeError, openLocalRegularFile, diff --git a/src/main/ipc/filesystem/filesystem-import-local.ts b/src/main/ipc/filesystem/filesystem-import-local.ts index c240ae408d7..b47ab2b76dd 100644 --- a/src/main/ipc/filesystem/filesystem-import-local.ts +++ b/src/main/ipc/filesystem/filesystem-import-local.ts @@ -3,7 +3,7 @@ import { basename, join, resolve } from 'node:path' import { isENOENT } from './access/filesystem-path-containment' import { classifyImportSource } from './filesystem-import-source-stat' import { deconflictCopyName } from '../../../shared/import-copy-name' -import type { ImportItemResult } from '../../../shared/filesystem-import-result-types' +import type { ImportItemResult } from '../../../shared/file-import/filesystem-import-result' import { copyLocalFileNoFollow, preScanForSymlinks, diff --git a/src/main/ipc/filesystem/filesystem-import-source-stat.ts b/src/main/ipc/filesystem/filesystem-import-source-stat.ts index 3375d3c0938..0c37fb9b834 100644 --- a/src/main/ipc/filesystem/filesystem-import-source-stat.ts +++ b/src/main/ipc/filesystem/filesystem-import-source-stat.ts @@ -1,6 +1,6 @@ import type { Stats } from 'node:fs' import { lstat } from 'node:fs/promises' -import type { ImportSkipReason } from '../../../shared/filesystem-import-result-types' +import type { ImportSkipReason } from '../../../shared/file-import/filesystem-import-result' import { errorMessage } from '../../../shared/error-message' import { isPermissionError } from '../../filesystem/permission-errors' import { isENOENT } from './access/filesystem-path-containment' diff --git a/src/main/ipc/filesystem/filesystem-list-files-name-filter.test.ts b/src/main/ipc/filesystem/filesystem-list-files-name-filter.test.ts index d8f1968fe96..d4a46b12f95 100644 --- a/src/main/ipc/filesystem/filesystem-list-files-name-filter.test.ts +++ b/src/main/ipc/filesystem/filesystem-list-files-name-filter.test.ts @@ -5,7 +5,7 @@ import type * as GitRunner from '../../git/command-runner/wsl-aware-spawn' import { pathMatchesFileNameFilterTokens, splitFileNameFilterTokens -} from '../../../shared/file-name-filter-tokens' +} from '../../../shared/file-listing/file-name-filter-tokens' const { wslAwareSpawnMock } = vi.hoisted(() => ({ wslAwareSpawnMock: vi.fn() diff --git a/src/main/ipc/filesystem/filesystem-list-files.test.ts b/src/main/ipc/filesystem/filesystem-list-files.test.ts index e62f7ddba6a..eddfda8ec9a 100644 --- a/src/main/ipc/filesystem/filesystem-list-files.test.ts +++ b/src/main/ipc/filesystem/filesystem-list-files.test.ts @@ -37,7 +37,6 @@ import { listQuickOpenFiles } from './filesystem-list-files' import { EventEmitter } from 'node:events' import type { Store } from '../../persistence/loading-store/store' import type { ChildProcess } from 'node:child_process' -import { FileListingCancelledError } from '../../../shared/file-listing-cancellation' const BUNDLED_RG = '/bundled/rg' @@ -58,16 +57,6 @@ function createMockProcess(): ChildProcess { return p } -async function flushMicrotasks(): Promise { - for (let index = 0; index < 12; index++) { - await Promise.resolve() - } -} - -function isIgnoredRgPass(args: string[]): boolean { - return args.includes('--no-ignore-vcs') -} - describe('filesystem-list-files', () => { beforeEach(() => { vi.clearAllMocks() @@ -96,90 +85,4 @@ describe('filesystem-list-files', () => { // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: authorization and workspace lookup are mocked above. await expect(listQuickOpenFiles('/repo', {} as Store)).rejects.toThrow('EMFILE') }) - - // WSL cd failure is 97; classify it before generic unavailable checks for codes above rg's 0/1/2. - - it('keeps source files first when only a serialized byte budget is provided', async () => { - const source = createMockProcess() - const broad = createMockProcess() - spawnMock.mockImplementation((_command, args: string[]) => - isIgnoredRgPass(args) ? broad : source - ) - const listing = listQuickOpenFiles( - '/mock/root', - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: authorization and workspace lookup are mocked above. - {} as Store, - undefined, - undefined, - undefined, - 20 - ) - await flushMicrotasks() - expect(spawnMock).toHaveBeenCalledTimes(1) - expect(spawnMock.mock.calls[0]?.[1]).not.toContain('--no-ignore-vcs') - source.stdout?.emit('data', 'source.ts\0') - source.emit('close', 0, null) - await flushMicrotasks() - expect(spawnMock).toHaveBeenCalledTimes(2) - expect(spawnMock.mock.calls[1]?.[1]).toContain('--no-ignore-vcs') - broad.stdout?.emit('data', 'ignored-file.ts\0') - await expect(listing).resolves.toEqual(['source.ts']) - expect(broad.kill).toHaveBeenCalledOnce() - }) - - it('settles and detaches rg scans that ignore timeout kills', async () => { - vi.useFakeTimers() - - try { - const p1 = createMockProcess() - - spawnMock.mockReturnValue(p1) - - const storeMock = {} as unknown as Store - const promise = listQuickOpenFiles('/mock/root', storeMock) - - await Promise.resolve() - await Promise.resolve() - await Promise.resolve() - - p1.stdout?.emit('data', 'src/index.ts\0partial') - const rejection = expect(promise).rejects.toThrow('rg list timed out') - - await vi.advanceTimersByTimeAsync(10000) - - await rejection - expect(p1.kill).toHaveBeenCalled() - expect((p1.stdout as unknown as EventEmitter).listenerCount('data')).toBe(0) - expect((p1.stderr as unknown as EventEmitter).listenerCount('data')).toBe(0) - expect(p1.listenerCount('error')).toBe(0) - expect(p1.listenerCount('close')).toBe(0) - } finally { - vi.useRealTimers() - } - }) - - it('lets cancellation win a native-unavailable race', async () => { - const first = createMockProcess() - Object.defineProperty(first, 'pid', { value: undefined }) - spawnMock.mockReturnValue(first) - const controller = new AbortController() - const cancellation = new FileListingCancelledError('superseded') - - const promise = listQuickOpenFiles( - '/mock/root', - {} as unknown as Store, - undefined, - controller.signal - ) - await flushMicrotasks() - controller.abort(cancellation) - first.emit('close', -2, null) - - await expect(promise).rejects.toBe(cancellation) - expect(spawnMock).toHaveBeenCalledTimes(1) - expect(spawnMock.mock.calls.some((call) => call[0] === 'git')).toBe(false) - const error = Object.assign(new Error('spawn rg ENOENT'), { code: 'ENOENT' }) - expect(() => first.emit('error', error)).not.toThrow() - expect(first.listenerCount('error')).toBe(0) - }) }) diff --git a/src/main/ipc/filesystem/filesystem-list-files.ts b/src/main/ipc/filesystem/filesystem-list-files.ts index 476b6a7e9ae..d0c221caf7b 100644 --- a/src/main/ipc/filesystem/filesystem-list-files.ts +++ b/src/main/ipc/filesystem/filesystem-list-files.ts @@ -1,13 +1,13 @@ import { FileInventoryBudget, FileInventoryCapacityError -} from '../../../shared/file-inventory-budget' -import { quickOpenListingPathFilter } from '../../../shared/quick-open-listing-path-filter' -import { getQuickOpenRgOutputMode } from '../../../shared/quick-open-ripgrep-output-mode' +} from '../../../shared/file-listing/file-inventory-budget' +import { quickOpenListingPathFilter } from '../../../shared/quick-open/quick-open-listing-path-filter' +import { getQuickOpenRgOutputMode } from '../../../shared/quick-open/quick-open-ripgrep-output-mode' import { RipgrepFilenameDecoder, RipgrepFilenameError -} from '../../../shared/ripgrep-filename-decoder' +} from '../../../shared/ripgrep/ripgrep-filename-decoder' import { sep } from 'node:path' import type { RuntimeStore as Store } from '../../runtime/construction/runtime-store-contract' import { resolveAuthorizedPath } from './access/filesystem-auth' @@ -18,11 +18,11 @@ import { buildExcludePathPrefixes, buildRgArgsForQuickOpen, normalizeQuickOpenRgLine -} from '../../../shared/quick-open-filter' +} from '../../../shared/quick-open/quick-open-filter' import { limitQuickOpenFilesBySerializedBytes, serializedQuickOpenPathBytes -} from '../../../shared/quick-open-transport-budget' +} from '../../../shared/quick-open/quick-open-transport-budget' import { bundledRipgrepUnavailableError } from '../../ripgrep/bundled-ripgrep-path' import { spawnBundledRipgrep } from '../../ripgrep/bundled-ripgrep-spawn' import { @@ -35,8 +35,8 @@ import { killSpawnedRipgrepProcess, ripgrepMissingCwdError, RipgrepUnavailableError -} from '../../../shared/ripgrep-process-availability' -import * as listingCancellation from '../../../shared/file-listing-cancellation' +} from '../../../shared/ripgrep/ripgrep-process-availability' +import * as listingCancellation from '../../../shared/file-listing/file-listing-cancellation' import { finishFilesystemListingProcesses, type FilesystemListingProcess diff --git a/src/main/ipc/filesystem/filesystem-listing-cancel-admission.test.ts b/src/main/ipc/filesystem/filesystem-listing-cancel-admission.test.ts deleted file mode 100644 index a74c5f304b9..00000000000 --- a/src/main/ipc/filesystem/filesystem-listing-cancel-admission.test.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { createFakePipedChild } from '../../../shared/__fixtures__/fake-spawned-child' -import { FileListingCancelledError } from '../../../shared/file-listing-cancellation' -import type { RuntimeStore } from '../../runtime/construction/runtime-store-contract' - -const { authorize, spawn } = vi.hoisted(() => ({ authorize: vi.fn(), spawn: vi.fn() })) - -vi.mock('./access/filesystem-auth', () => ({ resolveAuthorizedPath: authorize })) -vi.mock('../../ripgrep/bundled-ripgrep-spawn', () => ({ spawnBundledRipgrep: spawn })) -vi.mock('../local-worktree-runtime-options', () => ({ - getLocalGitOptionsForRegisteredWorktree: () => ({}) -})) - -import { listQuickOpenFiles } from './filesystem-list-files' - -const store: RuntimeStore = Object.create(null) - -function childProcess() { - return Object.assign(createFakePipedChild(), { exitCode: null, signalCode: null }) -} - -describe('file listing cancellation before native admission', () => { - beforeEach(() => { - vi.resetAllMocks() - authorize.mockImplementation(async (path: string) => path) - spawn.mockImplementation(childProcess) - }) - - it('does not authorize or launch an already canceled listing', async () => { - const controller = new AbortController() - const reason = new FileListingCancelledError('superseded') - controller.abort(reason) - - await expect(listQuickOpenFiles('/repo', store, undefined, controller.signal)).rejects.toBe( - reason - ) - expect(authorize).not.toHaveBeenCalled() - expect(spawn).not.toHaveBeenCalled() - }) - - it('admits no obsolete scan after a pending authorization', async () => { - const held = Promise.withResolvers() - authorize.mockReturnValue(held.promise) - const reason = new FileListingCancelledError('workspace switched') - const controller = new AbortController() - const pending = expect( - listQuickOpenFiles('/repo', store, undefined, controller.signal) - ).rejects.toBe(reason) - controller.abort(reason) - held.resolve('/repo') - await pending - expect(spawn).not.toHaveBeenCalled() - }) - - it('does not start the ignored pass when canceled after the primary pass closes', async () => { - const primary = childProcess() - spawn.mockReturnValue(primary) - const controller = new AbortController() - const reason = new FileListingCancelledError('closed') - const listing = listQuickOpenFiles('/repo', store, undefined, controller.signal, 10) - const rejected = expect(listing).rejects.toBe(reason) - await vi.waitFor(() => expect(spawn).toHaveBeenCalledTimes(1)) - primary.once('close', () => controller.abort(reason)) - primary.stdout.emit('data', 'src/primary.ts\0') - primary.emit('close', 0, null) - - await rejected - expect(spawn).toHaveBeenCalledTimes(1) - expect(primary.kill).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/ipc/filesystem/filesystem-listing-process-cleanup.ts b/src/main/ipc/filesystem/filesystem-listing-process-cleanup.ts index 34ca37bbd7c..c752933a5bc 100644 --- a/src/main/ipc/filesystem/filesystem-listing-process-cleanup.ts +++ b/src/main/ipc/filesystem/filesystem-listing-process-cleanup.ts @@ -1,5 +1,5 @@ import type { ChildProcessHandle } from '@orca/process-host/process-spec' -import { killSpawnedRipgrepProcess } from '../../../shared/ripgrep-process-availability' +import { killSpawnedRipgrepProcess } from '../../../shared/ripgrep/ripgrep-process-availability' export type FilesystemListingProcess = { child: ChildProcessHandle diff --git a/src/main/ipc/filesystem/filesystem-mutations.ts b/src/main/ipc/filesystem/filesystem-mutations.ts index b800a064a44..70994692913 100644 --- a/src/main/ipc/filesystem/filesystem-mutations.ts +++ b/src/main/ipc/filesystem/filesystem-mutations.ts @@ -8,7 +8,7 @@ import { resolveLocalRenamePaths, resolveLocalRequestPath } from './access/local-file-access-resolution' -import type { LocalFileAccess } from '../../../shared/local-file-access' +import type { LocalFileAccess } from '../../../shared/file-access/local-file-access' import { SshHostNotServedError } from '../../providers/ssh-host-not-served-error' import { resolveLocalDroppedPathsForAgent } from '../dropped-path-resolution' import type { SshMutationExpectation } from '../../../shared/ssh-types' @@ -17,9 +17,12 @@ import { renameLocalPathSerializedByDestination } from '../../filesystem/destina import { assertNotExists, rethrowWithUserMessage } from './filesystem-create-path-guards' import type { ImportItemResult, - ResolveDroppedPathsResult, - StagedExternalImportSource -} from '../../../shared/filesystem-import-result-types' + ResolveDroppedPathsResult +} from '../../../shared/file-import/filesystem-import-result' +import type { + StagedRuntimeUploadSource as StagedExternalImportSource, + RuntimeUploadFileStreamRequest +} from '../../../shared/file-import/runtime-upload-staging-contract' import { importOneSource } from './filesystem-import-local' import { stagedRuntimeUploadByteLength, @@ -28,7 +31,6 @@ import { import { streamExternalFileToRuntime } from '../runtime-upload-file-stream' import { abortWhenRendererGone } from '../renderer-lifetime-abort' import { sweepAbandonedRuntimeUploadTempPath } from '../runtime-upload-temp-sweep' -import type { RuntimeUploadFileStreamRequest } from '../../../shared/runtime-upload-staging-contract' import { resolveEnvironment } from '../../../shared/remote-runtime/host-store/runtime-environment-store' import { windowsFsPath } from '../../wsl/filesystem/wsl-unc-drive-fs-path' diff --git a/src/main/ipc/filesystem/filesystem-read-handlers.ts b/src/main/ipc/filesystem/filesystem-read-handlers.ts index b841e9f62e3..1ae71c73ec1 100644 --- a/src/main/ipc/filesystem/filesystem-read-handlers.ts +++ b/src/main/ipc/filesystem/filesystem-read-handlers.ts @@ -1,17 +1,18 @@ import { classifyFilesystemDirectoryEntries } from './filesystem-symlink-directory-entries' -import { markdownDocumentsFromRelativePaths } from '../../../shared/markdown-document-paths' +import { markdownDocumentsFromRelativePaths } from '../../../shared/file-listing/markdown-document-paths' import { capturePathExistence, validatePathExistenceBatch, type PathExistenceResult -} from '../../../shared/path-existence-batch' +} from '../../../shared/file-access/path-existence-batch' import { ipcMain } from 'electron' import { readdir, stat } from 'node:fs/promises' -import type { DirEntry, MarkdownDocument } from '../../../shared/filesystem-entry-types' -import { sortDirEntries } from '../../../shared/file-name-sort' +import type { DirEntry } from '../../../shared/file-listing/directory-entry' +import type { MarkdownDocument } from '../../../shared/file-listing/file-document' +import { sortDirEntries } from '../../../shared/file-listing/file-name-sort' import { SshHostNotServedError } from '../../providers/ssh-host-not-served-error' import { resolveRegisteredWorktreePath } from '../worktrees/removal/registered-worktree-roots-cache' -import type { LocalFileAccess } from '../../../shared/local-file-access' +import type { LocalFileAccess } from '../../../shared/file-access/local-file-access' import { resolveDesktopAuthorizedPath, resolveLocalFileRequestPath, @@ -31,7 +32,7 @@ import { assertWslUncPathRunning, guardWslUncPathAccess } from '../../wsl/filesystem/wsl-unc-access-gate' -import { parseRemoteFilePreviewAddress } from '../../../shared/remote-file-preview-address' +import { parseRemoteFilePreviewAddress } from '../../../shared/file-preview/remote-file-preview-address' import { readLocalFileContent, readLocalLogSnapshot, diff --git a/src/main/ipc/filesystem/filesystem-runtime-upload-staging.ts b/src/main/ipc/filesystem/filesystem-runtime-upload-staging.ts index f47106a3a77..cb8ef6369e7 100644 --- a/src/main/ipc/filesystem/filesystem-runtime-upload-staging.ts +++ b/src/main/ipc/filesystem/filesystem-runtime-upload-staging.ts @@ -9,9 +9,9 @@ import { basename, extname, isAbsolute, join, relative, resolve, sep } from 'nod import { classifyImportSource } from './filesystem-import-source-stat' import { detectImageFileSignature, IMAGE_SIGNATURE_BYTES } from '../../media/image-file-signature' import type { - StagedExternalImportEntry, - StagedExternalImportSource -} from '../../../shared/filesystem-import-result-types' + StagedRuntimeUploadEntry as StagedExternalImportEntry, + StagedRuntimeUploadSource as StagedExternalImportSource +} from '../../../shared/file-import/runtime-upload-staging-contract' class RuntimeUploadSymlinkError extends Error {} diff --git a/src/main/ipc/filesystem/filesystem-search-file-paths.ts b/src/main/ipc/filesystem/filesystem-search-file-paths.ts index 25fb40f5c98..c4d7c8e5e5a 100644 --- a/src/main/ipc/filesystem/filesystem-search-file-paths.ts +++ b/src/main/ipc/filesystem/filesystem-search-file-paths.ts @@ -1,19 +1,19 @@ -import { getQuickOpenRgOutputMode } from '../../../shared/quick-open-ripgrep-output-mode' -import { RipgrepFilenameDecoder } from '../../../shared/ripgrep-filename-decoder' +import { getQuickOpenRgOutputMode } from '../../../shared/quick-open/quick-open-ripgrep-output-mode' +import { RipgrepFilenameDecoder } from '../../../shared/ripgrep/ripgrep-filename-decoder' import { sep } from 'node:path' import type { RuntimeStore } from '../../runtime/construction/runtime-store-contract' -import { fileListingCancellationError } from '../../../shared/file-listing-cancellation' +import { fileListingCancellationError } from '../../../shared/file-listing/file-listing-cancellation' import { buildExcludePathPrefixes, buildRgArgsForQuickOpen, normalizeQuickOpenRgLine, shouldExcludeQuickOpenRelPath, shouldIncludeQuickOpenPath -} from '../../../shared/quick-open-filter' +} from '../../../shared/quick-open/quick-open-filter' import { isQuickOpenQueryTooLarge, QuickOpenPathRanker -} from '../../../shared/quick-open-path-search' +} from '../../../shared/quick-open/quick-open-path-search' import { absorbPendingRipgrepSpawnError, isRipgrepUnavailableExit, @@ -25,12 +25,12 @@ import { ripgrepMissingCwdError, RipgrepLaunchFailureError, RipgrepUnavailableError -} from '../../../shared/ripgrep-process-availability' +} from '../../../shared/ripgrep/ripgrep-process-availability' import { toWindowsWslPath } from '../../../shared/wsl-paths' import { resolveBundledRipgrepWslRouting } from '../../ripgrep/bundled-ripgrep-wsl-routing' import { resolveAuthorizedPath } from './access/filesystem-auth' import { getLocalGitOptionsForRegisteredWorktree } from '../local-worktree-runtime-options' -import { QuickOpenSubprocessPathAccumulator } from '../../../shared/quick-open-subprocess-path-accumulator' +import { QuickOpenSubprocessPathAccumulator } from '../../../shared/quick-open/quick-open-subprocess-path-accumulator' import { bundledRipgrepUnavailableError } from '../../ripgrep/bundled-ripgrep-path' import { spawnBundledRipgrep } from '../../ripgrep/bundled-ripgrep-spawn' diff --git a/src/main/ipc/filesystem/filesystem-search-handlers.ts b/src/main/ipc/filesystem/filesystem-search-handlers.ts index 56d552b851e..a0a853b218b 100644 --- a/src/main/ipc/filesystem/filesystem-search-handlers.ts +++ b/src/main/ipc/filesystem/filesystem-search-handlers.ts @@ -4,7 +4,7 @@ import { isFileNameFilterQueryTooLarge, pathMatchesFileNameFilterTokens, splitFileNameFilterTokens -} from '../../../shared/file-name-filter-tokens' +} from '../../../shared/file-listing/file-name-filter-tokens' import type { FilesystemHandlerContext } from './filesystem-handler-context' import { registerFilesystemContentSearchHandler } from './filesystem-content-search-handler' diff --git a/src/main/ipc/filesystem/filesystem-symlink-directory-entries.ts b/src/main/ipc/filesystem/filesystem-symlink-directory-entries.ts index 7a77f355072..916dbd96dae 100644 --- a/src/main/ipc/filesystem/filesystem-symlink-directory-entries.ts +++ b/src/main/ipc/filesystem/filesystem-symlink-directory-entries.ts @@ -1,7 +1,7 @@ import type { Dirent } from 'node:fs' import { stat } from 'node:fs/promises' import { join } from 'node:path' -import type { DirEntry } from '../../../shared/filesystem-entry-types' +import type { DirEntry } from '../../../shared/file-listing/directory-entry' import { mapWithConcurrency } from '../../../shared/map-with-concurrency' import { windowsFsPath } from '../../wsl/filesystem/wsl-unc-drive-fs-path' diff --git a/src/main/ipc/filesystem/filesystem-write-handlers.ts b/src/main/ipc/filesystem/filesystem-write-handlers.ts index 467306a67b1..8d3ca40b258 100644 --- a/src/main/ipc/filesystem/filesystem-write-handlers.ts +++ b/src/main/ipc/filesystem/filesystem-write-handlers.ts @@ -4,7 +4,7 @@ import type { SshMutationExpectation } from '../../../shared/ssh-types' import { assertSshMutationExpectation } from '../../ssh/connection/ssh-connection-generation' import { SshHostNotServedError } from '../../providers/ssh-host-not-served-error' import { tryDeleteWslUncPath } from '../../wsl/filesystem/wsl-unc-delete' -import type { LocalFileAccess } from '../../../shared/local-file-access' +import type { LocalFileAccess } from '../../../shared/file-access/local-file-access' import { resolveDesktopAuthorizedPath, resolveLocalWriteRequestPath @@ -16,10 +16,10 @@ import type { FilesystemHandlerContext } from './filesystem-handler-context' import type { FileWriteDiskPrecondition, FileWriteResult -} from '../../../shared/file-write-disk-precondition' +} from '../../../shared/file-write/file-write-disk-precondition' import { writeLocalTextFileWithDiskPrecondition } from './local-disk-write-precondition' import { replaceLocalFileBytesIfUnchanged } from './local-disk-bytes-replace' -import type { FileBytesWritePrecondition } from '../../../shared/file-bytes-write' +import type { FileBytesWritePrecondition } from '../../../shared/file-write/file-bytes-write' import { windowsFsPath } from '../../wsl/filesystem/wsl-unc-drive-fs-path' import { TRASH_DELETE_FAILED_MESSAGE } from '../../../shared/trash-delete-failure' diff --git a/src/main/ipc/filesystem/filesystem-write-identical.test.ts b/src/main/ipc/filesystem/filesystem-write-identical.test.ts index 1d407905a37..c1594da207e 100644 --- a/src/main/ipc/filesystem/filesystem-write-identical.test.ts +++ b/src/main/ipc/filesystem/filesystem-write-identical.test.ts @@ -2,8 +2,8 @@ import { chmod, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { getDiskBaselineSignature } from '../../../shared/disk-baseline-signature' -import { NOT_A_REGULAR_FILE_MESSAGE } from './local-regular-file-read' +import { getDiskBaselineSignature } from '../../../shared/file-write/disk-baseline-signature' + import { registerFilesystemWriteHandlers } from './filesystem-write-handlers' import type { FilesystemHandlerContext } from './filesystem-handler-context' @@ -51,14 +51,3 @@ it('accepts identical content on a readable, non-writable file through IPC', asy await chmod(filePath, 0o644) } }) - -it - .skipIf(process.platform === 'win32') - .each([undefined, { expectedSignature: getDiskBaselineSignature('') }])( - 'still refuses non-regular files through IPC (%j)', - async (diskPrecondition) => { - await expect( - handlers.get('fs:writeFile')!(null, { filePath: '/dev/null', content: '', diskPrecondition }) - ).rejects.toThrow(NOT_A_REGULAR_FILE_MESSAGE) - } -) diff --git a/src/main/ipc/filesystem/local-disk-bytes-replace.ts b/src/main/ipc/filesystem/local-disk-bytes-replace.ts index 85674a9057b..21aa7362b2d 100644 --- a/src/main/ipc/filesystem/local-disk-bytes-replace.ts +++ b/src/main/ipc/filesystem/local-disk-bytes-replace.ts @@ -2,8 +2,11 @@ import { createHash, randomUUID } from 'node:crypto' import { createReadStream } from 'node:fs' import { chmod, realpath, rm, stat } from 'node:fs/promises' import { basename, dirname, join } from 'node:path' -import type { FileBytesWritePrecondition } from '../../../shared/file-bytes-write' -import { FILE_WRITE_OK, type FileWriteResult } from '../../../shared/file-write-disk-precondition' +import type { FileBytesWritePrecondition } from '../../../shared/file-write/file-bytes-write' +import { + FILE_WRITE_OK, + type FileWriteResult +} from '../../../shared/file-write/file-write-disk-precondition' import { renameFileWithWindowsRetryAsync } from '../../../shared/windows-retry-file-operations' import { windowsFsPath } from '../../wsl/filesystem/wsl-unc-drive-fs-path' import { isENOENT } from './access/filesystem-path-containment' diff --git a/src/main/ipc/filesystem/local-disk-write-precondition.test.ts b/src/main/ipc/filesystem/local-disk-write-precondition.test.ts index 27fde74884f..54018c902cc 100644 --- a/src/main/ipc/filesystem/local-disk-write-precondition.test.ts +++ b/src/main/ipc/filesystem/local-disk-write-precondition.test.ts @@ -2,7 +2,7 @@ import { link, mkdir, mkdtemp, readFile, realpath, rm, symlink, writeFile } from import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { getDiskBaselineSignature } from '../../../shared/disk-baseline-signature' +import { getDiskBaselineSignature } from '../../../shared/file-write/disk-baseline-signature' import type { RuntimeStore } from '../../runtime/construction/runtime-store-contract' import { createLocalFilesystemProvider } from '../../providers/local-filesystem-provider' import type * as LocalRegularFileRead from './local-regular-file-read' @@ -132,21 +132,6 @@ describe('local provider guarded write', () => { ).resolves.toEqual({ ok: true, unchanged: true }) }) - it('lets only one of two concurrent saves from the same baseline write', async () => { - const filePath = join(base, 'a.ts') - await writeFile(filePath, 'original') - const fromBaseline = { expectedSignature: getDiskBaselineSignature('original') } - - const results = await Promise.all([ - provider().writeFileWithDiskPrecondition(filePath, 'client one', fromBaseline), - provider().writeFileWithDiskPrecondition(filePath, 'client two', fromBaseline) - ]) - - const winner = results.findIndex((result) => result.ok) - expect(results[1 - winner]).toEqual({ ok: false, diskConflict: 'changed' }) - expect(await readFile(filePath, 'utf8')).toBe(winner === 0 ? 'client one' : 'client two') - }) - // Windows symlink creation requires elevated rights or Developer Mode. it.skipIf(process.platform === 'win32').each([ ['a symlink', (target: string, alias: string) => symlink(target, alias)], diff --git a/src/main/ipc/filesystem/local-disk-write-precondition.ts b/src/main/ipc/filesystem/local-disk-write-precondition.ts index 72f34f607d2..e54f3f099e9 100644 --- a/src/main/ipc/filesystem/local-disk-write-precondition.ts +++ b/src/main/ipc/filesystem/local-disk-write-precondition.ts @@ -5,7 +5,7 @@ import { getDiskBaselineSignature, diskBaselineSignatureLength, utf8ByteSizeCanDecodeToLength -} from '../../../shared/disk-baseline-signature' +} from '../../../shared/file-write/disk-baseline-signature' import { compareDiskWritePrecondition, FILE_WRITE_OK, @@ -13,7 +13,7 @@ import { type FileWriteDiskComparison, type FileWriteDiskPrecondition, type FileWriteResult -} from '../../../shared/file-write-disk-precondition' +} from '../../../shared/file-write/file-write-disk-precondition' import { readlink, realpath, stat, writeFile } from 'node:fs/promises' import { basename, dirname, join, normalize, resolve } from 'node:path' import { runKeyedSerializedOperation } from '../../cli/keyed-promise-queue' diff --git a/src/main/ipc/filesystem/local-file-range-read.ts b/src/main/ipc/filesystem/local-file-range-read.ts index 1b147c4bca5..c1b7286e8f7 100644 --- a/src/main/ipc/filesystem/local-file-range-read.ts +++ b/src/main/ipc/filesystem/local-file-range-read.ts @@ -1,5 +1,5 @@ import type { FileHandle } from 'node:fs/promises' -import type { RuntimeFileReadChunkResult } from '../../../shared/runtime-types' +import type { RuntimeFileReadChunkResult } from '../../../shared/file-content/runtime-file-read' import { openLocalRegularFile } from './local-regular-file-read' export async function readLocalFileRange( diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-cancellation-tracker.ts b/src/main/ipc/filesystem/watcher-process/parcel-watcher-cancellation-tracker.ts index a3f73fe5a04..65d7cfcb136 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-cancellation-tracker.ts +++ b/src/main/ipc/filesystem/watcher-process/parcel-watcher-cancellation-tracker.ts @@ -1,5 +1,5 @@ import type { ChildProcess } from 'node:child_process' -import { RUNTIME_FILE_WATCH_CANCEL_TIMEOUT_MS } from '../../../../shared/runtime-file-watch-limits' +import { RUNTIME_FILE_WATCH_CANCEL_TIMEOUT_MS } from '../../../../shared/file-watch/runtime-file-watch-limits' type CancelledSubscribe = { child: ChildProcess diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-child-termination.ts b/src/main/ipc/filesystem/watcher-process/parcel-watcher-child-termination.ts index bac94574d81..297635c960b 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-child-termination.ts +++ b/src/main/ipc/filesystem/watcher-process/parcel-watcher-child-termination.ts @@ -4,7 +4,7 @@ import { resolvePendingWatcherUnsubscribes } from './parcel-watcher-host-subscriptions' import { WatcherProcessFailure } from './parcel-watcher-process-failure' -import { RUNTIME_FILE_WATCH_EXIT_DEADLINE_MS } from '../../../../shared/runtime-file-watch-limits' +import { RUNTIME_FILE_WATCH_EXIT_DEADLINE_MS } from '../../../../shared/file-watch/runtime-file-watch-limits' export const WATCHER_PROCESS_HARD_KILL_DELAY_MS = 5_000 export const WATCHER_PROCESS_EXIT_DEADLINE_MS = RUNTIME_FILE_WATCH_EXIT_DEADLINE_MS diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-host-subscriptions.ts b/src/main/ipc/filesystem/watcher-process/parcel-watcher-host-subscriptions.ts index 05b9b2d3634..577f3ee1b9f 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-host-subscriptions.ts +++ b/src/main/ipc/filesystem/watcher-process/parcel-watcher-host-subscriptions.ts @@ -9,7 +9,7 @@ import type { WatcherProcessSubscription, WatcherProcessSubscriptionRecord } from './parcel-watcher-process-subscription' -import { RUNTIME_FILE_WATCH_CANCEL_TIMEOUT_MS } from '../../../../shared/runtime-file-watch-limits' +import { RUNTIME_FILE_WATCH_CANCEL_TIMEOUT_MS } from '../../../../shared/file-watch/runtime-file-watch-limits' export type PendingWatcherUnsubscribe = (error?: Error) => void diff --git a/src/main/ipc/filesystem/watchers/filesystem-watcher-event-batch.ts b/src/main/ipc/filesystem/watchers/filesystem-watcher-event-batch.ts index 68f97fbedb8..d0ecf6e2cb5 100644 --- a/src/main/ipc/filesystem/watchers/filesystem-watcher-event-batch.ts +++ b/src/main/ipc/filesystem/watchers/filesystem-watcher-event-batch.ts @@ -1,5 +1,5 @@ import type { Event as WatcherEvent } from '@parcel/watcher' -import { MAX_BUFFERED_FILE_WATCH_EVENTS } from '../../../../shared/filesystem-watch-event-buffer' +import { MAX_BUFFERED_FILE_WATCH_EVENTS } from '../../../../shared/file-watch/filesystem-watch-event-buffer' export const MAX_BATCHED_WATCHER_EVENTS = MAX_BUFFERED_FILE_WATCH_EVENTS diff --git a/src/main/ipc/filesystem/watchers/filesystem-watcher-large-batch.test.ts b/src/main/ipc/filesystem/watchers/filesystem-watcher-large-batch.test.ts deleted file mode 100644 index 3b8f2b08994..00000000000 --- a/src/main/ipc/filesystem/watchers/filesystem-watcher-large-batch.test.ts +++ /dev/null @@ -1,141 +0,0 @@ -import { createWatcherSender } from './filesystem-watcher-test-sender' -import { join, resolve } from 'node:path' -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { handleMock } = vi.hoisted(() => ({ - handleMock: vi.fn() -})) - -vi.mock('electron', () => ({ - ipcMain: { - handle: handleMock - } -})) - -vi.mock('fs/promises', () => ({ - stat: vi.fn() -})) - -vi.mock('@parcel/watcher', () => ({ - subscribe: vi.fn() -})) - -vi.mock('./filesystem-watcher-wsl', () => ({ - createWslWatcher: vi.fn() -})) - -import { closeAllWatchers } from './filesystem-watcher-shutdown' -import { registerFilesystemWatcherHandlers } from './filesystem-watcher-handlers' -import { stat } from 'node:fs/promises' -import { subscribe as subscribeParcelWatcher } from '@parcel/watcher' -import type { Event as WatcherEvent } from '@parcel/watcher' -import { - WATCH_BATCH_INTERVAL_MS, - WATCH_BATCH_LEADING_MS -} from '../../../../shared/filesystem-watch-batch-window' - -type HandlerMap = Record unknown> - -describe('local filesystem watcher large batches', () => { - const handlers: HandlerMap = {} - - beforeEach(async () => { - vi.useRealTimers() - handleMock.mockReset() - vi.mocked(stat).mockReset() - vi.mocked(subscribeParcelWatcher).mockReset() - for (const key of Object.keys(handlers)) { - delete handlers[key] - } - handleMock.mockImplementation((channel, handler) => { - handlers[channel] = handler - }) - registerFilesystemWatcherHandlers() - await closeAllWatchers() - }) - - it('emits one overflow event for oversized native watcher batches', async () => { - vi.useFakeTimers() - vi.mocked(stat).mockResolvedValue({ isDirectory: () => true } as never) - let watcherCallback: ((err: Error | null, events: WatcherEvent[]) => void) | undefined - vi.mocked(subscribeParcelWatcher).mockImplementation(async (_root, callback) => { - watcherCallback = callback as typeof watcherCallback - return { unsubscribe: vi.fn() } as never - }) - const worktreePath = resolve('/tmp/repo') - const sender = createWatcherSender(1) - - await handlers['fs:watchWorktree']({ sender }, { worktreePath }) - watcherCallback?.( - null, - Array.from({ length: 5_001 }, (_, index): WatcherEvent => ({ - type: 'update', - path: join(worktreePath, `file-${index}.txt`) - })) - ) - - await vi.advanceTimersByTimeAsync(150) - - expect(stat).toHaveBeenCalledTimes(1) - expect(sender.send).toHaveBeenCalledWith('fs:changed', { - worktreePath, - events: [{ kind: 'overflow', absolutePath: worktreePath }] - }) - await closeAllWatchers() - vi.useRealTimers() - }) - - it('still coalesces a local burst on the shared leading window', async () => { - vi.useFakeTimers() - vi.mocked(stat).mockResolvedValue({ isDirectory: () => true } as never) - let watcherCallback: ((err: Error | null, events: WatcherEvent[]) => void) | undefined - vi.mocked(subscribeParcelWatcher).mockImplementation(async (_root, callback) => { - watcherCallback = callback as typeof watcherCallback - return { unsubscribe: vi.fn() } as never - }) - const worktreePath = resolve('/tmp/repo') - const filePath = join(worktreePath, 'a.ts') - const sender = createWatcherSender(1) - - await handlers['fs:watchWorktree']({ sender }, { worktreePath }) - watcherCallback?.(null, [{ type: 'update', path: filePath }]) - watcherCallback?.(null, [{ type: 'update', path: filePath }]) - - await vi.advanceTimersByTimeAsync(WATCH_BATCH_LEADING_MS - 1) - expect(sender.send).not.toHaveBeenCalled() - - await vi.advanceTimersByTimeAsync(1) - expect(sender.send).toHaveBeenCalledTimes(1) - expect(sender.send).toHaveBeenCalledWith('fs:changed', { - worktreePath, - events: [{ kind: 'update', absolutePath: filePath, isDirectory: true }] - }) - await closeAllWatchers() - vi.useRealTimers() - }) - - it('flushes a sustained local stream every interval instead of starving it', async () => { - vi.useFakeTimers() - vi.mocked(stat).mockResolvedValue({ isDirectory: () => true } as never) - let watcherCallback: ((err: Error | null, events: WatcherEvent[]) => void) | undefined - vi.mocked(subscribeParcelWatcher).mockImplementation(async (_root, callback) => { - watcherCallback = callback as typeof watcherCallback - return { unsubscribe: vi.fn() } as never - }) - const worktreePath = resolve('/tmp/repo') - const sender = createWatcherSender(1) - - await handlers['fs:watchWorktree']({ sender }, { worktreePath }) - const step = 10 - for (let elapsed = 0; elapsed < 1_000; elapsed += step) { - watcherCallback?.(null, [{ type: 'update', path: join(worktreePath, `f-${elapsed}.ts`) }]) - await vi.advanceTimersByTimeAsync(step) - } - - const sends = sender.send.mock.calls.length - expect(sends).toBeGreaterThanOrEqual(1_000 / WATCH_BATCH_INTERVAL_MS - 1) - expect(sends).toBeLessThanOrEqual(1_000 / WATCH_BATCH_INTERVAL_MS + 1) - await closeAllWatchers() - vi.useRealTimers() - }) -}) diff --git a/src/main/ipc/filesystem/watchers/filesystem-watcher-local-capacity.ts b/src/main/ipc/filesystem/watchers/filesystem-watcher-local-capacity.ts index 95bfacb4670..a68fbf58bf4 100644 --- a/src/main/ipc/filesystem/watchers/filesystem-watcher-local-capacity.ts +++ b/src/main/ipc/filesystem/watchers/filesystem-watcher-local-capacity.ts @@ -10,7 +10,7 @@ import { registerWatcherSenderCleanup } from './filesystem-watcher-listener-lifecycle' import { isWatcherRemovalInProgressError } from '../../../workspaces/removal/watcher-removal-gate' -import type { FsChangedPayload } from '../../../../shared/filesystem-entry-types' +import type { FsChangedPayload } from '../../../../shared/file-watch/filesystem-change-event' export type SubscribeLocalWatcher = (worktreePath: string, sender: WebContents) => Promise /** Calls `retry` when installing may succeed again; returns a cancel. */ diff --git a/src/main/ipc/filesystem/watchers/filesystem-watcher-local-events.ts b/src/main/ipc/filesystem/watchers/filesystem-watcher-local-events.ts index 49ce3f4d2fc..7a82c964b04 100644 --- a/src/main/ipc/filesystem/watchers/filesystem-watcher-local-events.ts +++ b/src/main/ipc/filesystem/watchers/filesystem-watcher-local-events.ts @@ -1,7 +1,10 @@ import { stat } from 'node:fs/promises' import type { Event as WatcherEvent } from '@parcel/watcher' -import type { FsChangeEvent, FsChangedPayload } from '../../../../shared/filesystem-entry-types' -import { watchBatchFlushDelayMs } from '../../../../shared/filesystem-watch-batch-window' +import type { + FsChangeEvent, + FsChangedPayload +} from '../../../../shared/file-watch/filesystem-change-event' +import { watchBatchFlushDelayMs } from '../../../../shared/file-watch/filesystem-watch-batch-window' import { MAX_BATCHED_WATCHER_EVENTS, queueWatcherEvents } from './filesystem-watcher-event-batch' // Filter high-churn events at source; Explorer display filters only hide rows. import { WATCHER_IGNORE_DIRS, buildParcelWatcherIgnoreOptions } from './filesystem-watcher-ignore' diff --git a/src/main/ipc/filesystem/watchers/filesystem-watcher-local-removal.ts b/src/main/ipc/filesystem/watchers/filesystem-watcher-local-removal.ts index a8874bcff51..ecbfe4362d1 100644 --- a/src/main/ipc/filesystem/watchers/filesystem-watcher-local-removal.ts +++ b/src/main/ipc/filesystem/watchers/filesystem-watcher-local-removal.ts @@ -1,6 +1,6 @@ import { isCurrentWatcherSender } from './filesystem-watcher-sender-lifetime' import type { WebContents } from 'electron' -import type { FsChangedPayload } from '../../../../shared/filesystem-entry-types' +import type { FsChangedPayload } from '../../../../shared/file-watch/filesystem-change-event' import { createWatcherRemovalDeadline, drainBeforeWatcherRemoval, diff --git a/src/main/ipc/filesystem/watchers/filesystem-watcher-stat-lifecycle.test.ts b/src/main/ipc/filesystem/watchers/filesystem-watcher-stat-lifecycle.test.ts deleted file mode 100644 index 5b813431228..00000000000 --- a/src/main/ipc/filesystem/watchers/filesystem-watcher-stat-lifecycle.test.ts +++ /dev/null @@ -1,128 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { join, resolve } from 'node:path' -import type { Event as WatcherEvent } from '@parcel/watcher' -import type { FsChangedPayload } from '../../../../shared/filesystem-entry-types' -import { WATCH_BATCH_INTERVAL_MS } from '../../../../shared/filesystem-watch-batch-window' - -const { statMock, subscribeMock } = vi.hoisted(() => ({ - statMock: vi.fn(), - subscribeMock: vi.fn() -})) -vi.mock('node:fs/promises', () => ({ stat: statMock })) -vi.mock('../watcher-process/parcel-watcher-process', () => ({ - subscribeViaWatcherProcess: subscribeMock, - disposeWatcherProcess: vi.fn() -})) - -import { - subscribeLocalWatcher, - unsubscribeLocalWatcher -} from './filesystem-watcher-local-subscription' -import { - closeLocalWatcherForWorktreePath, - restoreLocalWatcherAfterFailedRemoval -} from './filesystem-watcher-local-removal' -import { watcherLifecycleState } from './filesystem-watcher-lifecycle-state' -import { getLocalWatcherRoot } from './filesystem-watcher-paths' -import { closeAllWatchers } from './filesystem-watcher-shutdown' -import { createWatcherSender, fireWatcherSenderEvent } from './filesystem-watcher-test-sender' - -describe('watcher stat lifecycle across reuse and failed removal', () => { - const worktreePath = resolve('stat-lifecycle') - const { key } = getLocalWatcherRoot(worktreePath) - let callback: (error: Error | null, events: WatcherEvent[]) => void - const pendingStat = () => Promise.withResolvers<{ isDirectory: () => boolean }>() - let firstStat: ReturnType - - function emit(name: string): void { - callback(null, [{ type: 'update', path: join(worktreePath, name) }]) - } - - beforeEach(() => { - vi.useFakeTimers() - watcherLifecycleState.localWatchersClosed = false - firstStat = pendingStat() - statMock.mockReset().mockResolvedValue({ isDirectory: () => true }) - subscribeMock.mockReset().mockImplementation(async (_path, nextCallback) => { - callback = nextCallback - return { unsubscribe: vi.fn(async () => {}) } - }) - }) - - afterEach(async () => { - await closeAllWatchers() - firstStat.resolve({ isDirectory: () => false }) - await vi.advanceTimersByTimeAsync(0) - vi.restoreAllMocks() - vi.useRealTimers() - }) - - it('drains an expired queued flush after unwatch clears a newer timer and rewatch reuses the root', async () => { - const send = vi.fn<(channel: string, payload: FsChangedPayload) => void>() - const sender = createWatcherSender(1, send) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: watcher lifetimes and delivery use only id, isDestroyed, on, removeListener and send from the sender double. - await subscribeLocalWatcher(worktreePath, sender as never) - const root = watcherLifecycleState.watchedRoots.get(key)! - statMock.mockReturnValueOnce(firstStat.promise) - emit('first.ts') - await vi.advanceTimersByTimeAsync(WATCH_BATCH_INTERVAL_MS) - expect(root.batch.flushInFlight).toBe(true) - - emit('queued.ts') - await vi.advanceTimersByTimeAsync(WATCH_BATCH_INTERVAL_MS) - expect(root.batch.flushQueued).toBe(true) - emit('tail.ts') - expect(root.batch.timer).not.toBeNull() - unsubscribeLocalWatcher(worktreePath, sender.id) - expect(root.batch.timer).toBeNull() - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: rewatch uses the same sender double's lifetime and delivery methods. - await subscribeLocalWatcher(worktreePath, sender as never) - expect(watcherLifecycleState.watchedRoots.get(key)).toBe(root) - - firstStat.resolve({ isDirectory: () => false }) - await vi.advanceTimersByTimeAsync(0) - expect(sender.send).toHaveBeenCalledTimes(2) - const payloads = send.mock.calls.map(([, payload]) => payload) - expect(payloads.map(({ events }) => events.map(({ absolutePath }) => absolutePath))).toEqual([ - [join(worktreePath, 'first.ts')], - [join(worktreePath, 'queued.ts'), join(worktreePath, 'tail.ts')] - ]) - expect(root.batch.flushInFlight).toBe(false) - expect(root.batch.statAbortController.signal.aborted).toBe(false) - }) - - it('keeps a replacement root live when an earlier independent unsubscribe rejects during close', async () => { - vi.spyOn(console, 'error').mockImplementation(() => {}) - const oldUnsubscribe = Promise.withResolvers() - const first = createWatcherSender(1) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: watcher lifetimes and delivery use only id, isDestroyed, on, removeListener and send from the sender double. - await subscribeLocalWatcher(worktreePath, first as never) - watcherLifecycleState.watchedRoots.get(key)!.subscription.unsubscribe = () => - oldUnsubscribe.promise - fireWatcherSenderEvent(first, 'destroyed') - await vi.advanceTimersByTimeAsync(0) - expect(watcherLifecycleState.pendingLocalUnsubscribesByRoot.get(key)?.size).toBe(1) - - const replacement = createWatcherSender(2) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the replacement sender supplies the same lifetime and delivery methods as the original. - await subscribeLocalWatcher(worktreePath, replacement as never) - const root = watcherLifecycleState.watchedRoots.get(key)! - const close = closeLocalWatcherForWorktreePath(worktreePath) - const rejectedClose = expect(close).rejects.toThrow('old unsubscribe failed') - await vi.advanceTimersByTimeAsync(0) - oldUnsubscribe.reject(new Error('old unsubscribe failed')) - await rejectedClose - await restoreLocalWatcherAfterFailedRemoval(worktreePath) - expect(watcherLifecycleState.watchedRoots.get(key)).toBe(root) - expect(subscribeMock).toHaveBeenCalledTimes(2) - expect(root.batch.cancelled).toBe(false) - expect(root.batch.statAbortController.signal.aborted).toBe(false) - - emit('after-restore.ts') - await vi.advanceTimersByTimeAsync(WATCH_BATCH_INTERVAL_MS) - expect(replacement.send).toHaveBeenCalledTimes(2) - expect(replacement.send.mock.calls[1][1]).toMatchObject({ - events: [{ kind: 'update', absolutePath: join(worktreePath, 'after-restore.ts') }] - }) - }) -}) diff --git a/src/main/ipc/filesystem/watchers/filesystem-watcher-wsl-stat-stop.test.ts b/src/main/ipc/filesystem/watchers/filesystem-watcher-wsl-stat-stop.test.ts deleted file mode 100644 index 4dfbdb58fc9..00000000000 --- a/src/main/ipc/filesystem/watchers/filesystem-watcher-wsl-stat-stop.test.ts +++ /dev/null @@ -1,151 +0,0 @@ -import { EventEmitter } from 'node:events' -import { join, resolve } from 'node:path' -import { PassThrough } from 'node:stream' -import type { Event as WatcherEvent } from '@parcel/watcher' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import type { FsChangedPayload } from '../../../../shared/filesystem-entry-types' -import { WATCH_BATCH_INTERVAL_MS } from '../../../../shared/filesystem-watch-batch-window' - -const { statMock, subscribeMock, spawnMock } = vi.hoisted(() => ({ - statMock: vi.fn(), - subscribeMock: vi.fn(), - spawnMock: vi.fn() -})) - -vi.mock('node:fs/promises', () => ({ stat: statMock })) -vi.mock('../watcher-process/parcel-watcher-process', () => ({ - subscribeViaWatcherProcess: subscribeMock -})) -vi.mock('./wsl-watcher-spawn', () => ({ spawnWslWatcherProcess: spawnMock })) - -import { cancelLocalBatchFlush } from './filesystem-watcher-batch-control' -import { createLocalWatcher, scheduleLocalBatchFlush } from './filesystem-watcher-local-events' -import { createWatcherSender } from './filesystem-watcher-test-sender' -import { createWslWatcher, type WatchedRoot } from './filesystem-watcher-wsl' - -class SnapshotChild extends EventEmitter { - stdin = new PassThrough() - stdout = new PassThrough() - stderr = new PassThrough() - kill = vi.fn(() => { - this.emit('close', null, 'SIGTERM') - return true - }) -} - -function snapshotFrame(mtime: string): string { - return `\0\x1e\0f\t${mtime}\t/home/me/repo/README.md\0\0\x1f\0` -} - -function listen(root: WatchedRoot, id: number) { - const send = vi.fn<(channel: string, payload: FsChangedPayload) => void>() - const sender = createWatcherSender(id, send) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: batch delivery only calls the fake sender's isDestroyed and send methods. - root.listeners.set(id, sender as never) - return send -} - -type StatResult = { isDirectory: () => boolean } -const roots: WatchedRoot[] = [] -const pendingStats: ReturnType>[] = [] - -beforeEach(() => { - vi.useFakeTimers() - statMock.mockReset().mockImplementation(() => { - const deferred = Promise.withResolvers() - pendingStats.push(deferred) - return deferred.promise - }) - subscribeMock.mockReset() - spawnMock.mockReset() -}) - -afterEach(async () => { - for (const root of roots.splice(0)) { - cancelLocalBatchFlush(root) - await root.subscription.unsubscribe() - } - for (const deferred of pendingStats.splice(0)) { - deferred.resolve({ isDirectory: () => false }) - } - await vi.advanceTimersByTimeAsync(0) - vi.useRealTimers() -}) - -it('delivers overflow after a spontaneous WSL stop without starting queued metadata stats', async () => { - let onLocalEvents: (error: Error | null, events: WatcherEvent[]) => void = () => { - throw new Error('Local watcher has not subscribed') - } - subscribeMock.mockImplementation(async (_path, callback) => { - onLocalEvents = callback - return { unsubscribe: vi.fn(async () => {}) } - }) - const localPath = resolve('busy-local-root') - const local = await createLocalWatcher(localPath, localPath) - roots.push(local) - const localSend = listen(local, 1) - - const child = new SnapshotChild() - spawnMock.mockReturnValueOnce(child) - const wslPath = '\\\\wsl.localhost\\Ubuntu\\home\\me\\repo' - const watchedRoots = new Map() - const onUnexpectedStop = vi.fn() - const starting = createWslWatcher(wslPath, wslPath, { - ignoreDirs: [], - scheduleBatchFlush: scheduleLocalBatchFlush, - watchedRoots, - onUnexpectedStop - }) - child.stdout.write(snapshotFrame('1')) - const wsl = await starting - roots.push(wsl) - watchedRoots.set(wslPath, wsl) - const wslSend = listen(wsl, 2) - - onLocalEvents( - null, - Array.from({ length: 8 }, (_, index) => ({ - type: 'update', - path: join(localPath, `file-${index}.ts`) - })) - ) - await vi.advanceTimersByTimeAsync(WATCH_BATCH_INTERVAL_MS) - expect(statMock).toHaveBeenCalledTimes(8) - - child.stdout.write(snapshotFrame('2')) - await vi.advanceTimersByTimeAsync(WATCH_BATCH_INTERVAL_MS) - expect(wsl.batch.flushInFlight).toBe(true) - expect(wsl.batch.events).toEqual([]) - expect(statMock).toHaveBeenCalledTimes(8) - expect(wslSend).not.toHaveBeenCalled() - - child.emit('close', null, 'SIGTERM') - expect(onUnexpectedStop).toHaveBeenCalledExactlyOnceWith(wsl, 'Ubuntu') - expect(watchedRoots.has(wslPath)).toBe(false) - expect(wsl.batch.statAbortController.signal.aborted).toBe(true) - await vi.advanceTimersByTimeAsync(WATCH_BATCH_INTERVAL_MS) - expect(wsl.batch.flushInFlight).toBe(false) - expect( - wslSend.mock.calls.filter(([, payload]) => - payload.events.some((event) => event.kind === 'overflow') - ) - ).toEqual([ - ['fs:changed', { worktreePath: wslPath, events: [{ kind: 'overflow', absolutePath: wslPath }] }] - ]) - expect(statMock).toHaveBeenCalledTimes(8) - - for (const deferred of pendingStats.splice(0)) { - deferred.resolve({ isDirectory: () => false }) - } - await vi.advanceTimersByTimeAsync(WATCH_BATCH_INTERVAL_MS) - - expect(statMock).toHaveBeenCalledTimes(8) - expect(localSend).toHaveBeenCalledOnce() - const overflowCalls = wslSend.mock.calls.filter(([, payload]) => - payload.events.some((event) => event.kind === 'overflow') - ) - expect(overflowCalls).toEqual([ - ['fs:changed', { worktreePath: wslPath, events: [{ kind: 'overflow', absolutePath: wslPath }] }] - ]) - expect(wsl.batch.flushInFlight).toBe(false) -}) diff --git a/src/main/ipc/markdown-documents.ts b/src/main/ipc/markdown-documents.ts index 7d44836c42f..c9ecb58367a 100644 --- a/src/main/ipc/markdown-documents.ts +++ b/src/main/ipc/markdown-documents.ts @@ -4,8 +4,8 @@ import { resolveBundledRipgrepWslRouting } from '../ripgrep/bundled-ripgrep-wsl- import { collectMarkdownDocuments, MARKDOWN_DOCUMENT_LISTING_ARGS -} from '../../shared/node-markdown-document-listing' -import type { MarkdownDocument } from '../../shared/filesystem-entry-types' +} from '../../shared/file-listing/node-markdown-document-listing' +import type { MarkdownDocument } from '../../shared/file-listing/file-document' export async function listMarkdownDocuments( rootPath: string, diff --git a/src/main/ipc/runtime-upload-file-stream.test.ts b/src/main/ipc/runtime-upload-file-stream.test.ts index 90cd9b3c718..459f3f2f58c 100644 --- a/src/main/ipc/runtime-upload-file-stream.test.ts +++ b/src/main/ipc/runtime-upload-file-stream.test.ts @@ -2,7 +2,7 @@ import { lstat, mkdtemp, rm, utimes, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { StagedRuntimeUploadFileIdentity } from '../../shared/runtime-upload-staging-contract' +import type { StagedRuntimeUploadFileIdentity } from '../../shared/file-import/runtime-upload-staging-contract' import type * as RuntimeImportLimits from './runtime-import-limits' type RuntimeImportLimitsModule = typeof RuntimeImportLimits diff --git a/src/main/ipc/runtime-upload-file-stream.ts b/src/main/ipc/runtime-upload-file-stream.ts index 5c7b95c3de9..0569cb502c4 100644 --- a/src/main/ipc/runtime-upload-file-stream.ts +++ b/src/main/ipc/runtime-upload-file-stream.ts @@ -4,7 +4,7 @@ import { basename, isAbsolute, join, relative, resolve, sep } from 'node:path' import type { RuntimeUploadFileStreamRequest, StagedRuntimeUploadFileIdentity -} from '../../shared/runtime-upload-staging-contract' +} from '../../shared/file-import/runtime-upload-staging-contract' import { formatByteCeiling, REMOTE_IMPORT_MAX_FILE_BYTES } from './runtime-import-limits' import { isRuntimeEnvironmentManuallyDisconnected, diff --git a/src/main/ipc/runtime-upload-temp-sweep.ts b/src/main/ipc/runtime-upload-temp-sweep.ts index 58bc6324e28..5637740fbda 100644 --- a/src/main/ipc/runtime-upload-temp-sweep.ts +++ b/src/main/ipc/runtime-upload-temp-sweep.ts @@ -1,5 +1,5 @@ import { setTimeout } from 'node:timers/promises' -import type { RuntimeUploadFileStreamRequest } from '../../shared/runtime-upload-staging-contract' +import type { RuntimeUploadFileStreamRequest } from '../../shared/file-import/runtime-upload-staging-contract' import { callRuntimeEnvironment } from './runtime-environments/runtime-environment-transport-routing' const RUNTIME_UPLOAD_SWEEP_ATTEMPTS = 2 diff --git a/src/main/ipc/shell-path-existence-handlers.ts b/src/main/ipc/shell-path-existence-handlers.ts index 8aeffca51f0..4bb31318ae1 100644 --- a/src/main/ipc/shell-path-existence-handlers.ts +++ b/src/main/ipc/shell-path-existence-handlers.ts @@ -2,7 +2,7 @@ import { ipcMain } from 'electron' import { validatePathExistenceBatch, type ShellPathExistence -} from '../../shared/path-existence-batch' +} from '../../shared/file-access/path-existence-batch' import { pathExists } from './shell-owned-path-target' import { guardWslUncPathAccess, WslDistroStoppedError } from '../wsl/filesystem/wsl-unc-access-gate' diff --git a/src/main/managed-data-accounts/credential-capture.ts b/src/main/managed-data-accounts/credential-capture.ts index 7acdae090e6..cf5357f7992 100644 --- a/src/main/managed-data-accounts/credential-capture.ts +++ b/src/main/managed-data-accounts/credential-capture.ts @@ -4,7 +4,7 @@ import { z } from 'zod' import { parse } from 'smol-toml' import SyncDatabase from '../sqlite/sync-database' import { tableExists } from '../opencode-usage/schema-helpers' -import { writeSecureFile } from '../../shared/secure-file' +import { writeSecureFile } from '../../shared/secure-storage/secure-file' import type { ManagedDataAccountProvider } from '../../shared/managed-account-types' const credential = z.discriminatedUnion('type', [ diff --git a/src/main/managed-data-accounts/profile-removal-recovery.test.ts b/src/main/managed-data-accounts/profile-removal-recovery.test.ts index c8bbb2bcb35..a283fc6a297 100644 --- a/src/main/managed-data-accounts/profile-removal-recovery.test.ts +++ b/src/main/managed-data-accounts/profile-removal-recovery.test.ts @@ -13,7 +13,7 @@ import { import { tmpdir } from 'node:os' import { join } from 'node:path' import type { ManagedDataAccountProvider } from '../../shared/managed-account-types' -import { writeSecureFile } from '../../shared/secure-file' +import { writeSecureFile } from '../../shared/secure-storage/secure-file' import { ManagedDataAccountService } from './service' vi.mock('node:fs', async (importOriginal) => ({ diff --git a/src/main/managed-data-accounts/profile-removal.ts b/src/main/managed-data-accounts/profile-removal.ts index 65778d1d8b1..fcbba714a91 100644 --- a/src/main/managed-data-accounts/profile-removal.ts +++ b/src/main/managed-data-accounts/profile-removal.ts @@ -7,7 +7,7 @@ import type { ManagedDataAccountProvider, ManagedDataAccountsState } from '../../shared/managed-account-types' -import { writeSecureFile } from '../../shared/secure-file' +import { writeSecureFile } from '../../shared/secure-storage/secure-file' export class ManagedDataAccountProfileRemoval { constructor( diff --git a/src/main/managed-data-accounts/service-enrollment-persistence.test.ts b/src/main/managed-data-accounts/service-enrollment-persistence.test.ts index e7d981a463b..9e92d330577 100644 --- a/src/main/managed-data-accounts/service-enrollment-persistence.test.ts +++ b/src/main/managed-data-accounts/service-enrollment-persistence.test.ts @@ -4,7 +4,7 @@ import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync import { tmpdir } from 'node:os' import { join } from 'node:path' import SyncDatabase from '../sqlite/sync-database' -import * as secureFile from '../../shared/secure-file' +import * as secureFile from '../../shared/secure-storage/secure-file' import { ManagedDataAccountService } from './service' vi.mock('node:fs', async (importOriginal) => { diff --git a/src/main/managed-data-accounts/service.ts b/src/main/managed-data-accounts/service.ts index ffac0f2bf37..ac1fa22b1e6 100644 --- a/src/main/managed-data-accounts/service.ts +++ b/src/main/managed-data-accounts/service.ts @@ -3,7 +3,7 @@ import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, rmSync } import { join, resolve, sep } from 'node:path' import { z } from 'zod' import { getAppEnvironment } from '../../shared/app-environment' -import { writeSecureFile } from '../../shared/secure-file' +import { writeSecureFile } from '../../shared/secure-storage/secure-file' import type { ManagedDataAccountProvider, ManagedDataAccountsState diff --git a/src/main/media/local-preview-grant-file.ts b/src/main/media/local-preview-grant-file.ts index d4ef6d1ff88..3a9386f3fb6 100644 --- a/src/main/media/local-preview-grant-file.ts +++ b/src/main/media/local-preview-grant-file.ts @@ -1,5 +1,5 @@ import type { Store } from '../persistence/loading-store/store' -import { filePreviewForPath, isDocumentPreview } from '../../shared/file-preview-kind' +import { filePreviewForPath, isDocumentPreview } from '../../shared/file-preview/file-preview-kind' import { resolveLocalFileRequestPath } from '../ipc/filesystem/access/local-file-access-resolution' import { openLocalRegularFile } from '../ipc/filesystem/local-regular-file-read' import { guardWslUncPathAccess } from '../wsl/filesystem/wsl-unc-access-gate' diff --git a/src/main/media/media-preview-protocol-granted.test.ts b/src/main/media/media-preview-protocol-granted.test.ts deleted file mode 100644 index 7800006bb15..00000000000 --- a/src/main/media/media-preview-protocol-granted.test.ts +++ /dev/null @@ -1,192 +0,0 @@ -import { EventEmitter } from 'node:events' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { Store } from '../persistence/loading-store/store' -import type { RemoteFilePreviewAddress } from '../../shared/remote-file-preview-address' - -vi.mock('electron', () => ({ - protocol: { handle: vi.fn(), registerSchemesAsPrivileged: vi.fn() } -})) -vi.mock('../ipc/runtime-environments/runtime-environment-registry-root', () => ({ - readRegisteredPairingRevision: vi.fn(() => 9) -})) -vi.mock('./remote-file-preview-reader', async (importOriginal) => ({ - ...(await importOriginal()), - statRemotePreviewFile: vi.fn(), - readRemotePreviewChunk: vi.fn(), - readRemotePreviewRange: vi.fn(), - assertRemoteChunkReadsSupported: vi.fn(), - renewRemotePreviewGrant: vi.fn() -})) - -import { grantRemoteFilePreview, handleMediaPreviewRequest } from './media-preview-protocol' -import { - RemotePreviewGrantLapsedError, - assertRemoteChunkReadsSupported, - renewRemotePreviewGrant, - readRemotePreviewChunk, - readRemotePreviewRange, - statRemotePreviewFile -} from './remote-file-preview-reader' -import type * as RemoteFilePreviewReader from './remote-file-preview-reader' -import { readPreviewGrantRange } from './preview-grant-range-read' - -// #35968: a viewer of a host file outside every workspace outlives the grant that serves it. -describe('a granted remote preview', () => { - const emitter = new EventEmitter() - const event = { - sender: { - id: 24860, - on: vi.fn().mockImplementation((name, callback) => emitter.on(name, callback)), - removeListener: vi - .fn() - .mockImplementation((name, callback) => emitter.removeListener(name, callback)) - } - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: remote previews never read Store members. - const store = {} as Store - const range = (url: string, header = 'bytes=2-4') => - handleMediaPreviewRequest(new Request(url, { headers: { range: header } })) - let now = 1_000_000 - beforeEach(() => { - vi.spyOn(Date, 'now').mockImplementation(() => now) - vi.mocked(statRemotePreviewFile).mockReset().mockResolvedValue({ size: 6, mtime: 1 }) - vi.mocked(readRemotePreviewChunk) - .mockReset() - .mockResolvedValue(Uint8Array.from([2, 3, 4])) - vi.mocked(assertRemoteChunkReadsSupported).mockReset().mockResolvedValue(undefined) - }) - afterEach(() => { - vi.mocked(Date.now).mockRestore() - emitter.emit('destroyed') - }) - - it('renews a lapsed host grant once for a burst, then streams on through the new grant', async () => { - const granted: RemoteFilePreviewAddress = { - environmentId: 'env-1', - worktree: 'id:wt-1', - grantId: 'g-1', - absolutePath: '/tmp/clip.webm', - expectedEnvironmentPairingRevision: 3 - } - const minted = await grantRemoteFilePreview(event, granted, store) - if (!minted) { - throw new Error('Missing preview') - } - now += 1_500 - vi.mocked(statRemotePreviewFile).mockImplementation(async (address) => - address.grantId === 'g-1' - ? Promise.reject(new RemotePreviewGrantLapsedError('terminal_file_grant_expired')) - : { size: 6, mtime: 1 } - ) - vi.mocked(renewRemotePreviewGrant).mockResolvedValue({ ...granted, grantId: 'g-2' }) - - const burst = await Promise.all([range(minted.mediaUrl), range(minted.mediaUrl, 'bytes=0-1')]) - - expect(burst.map((response) => response.status)).toEqual([206, 206]) - expect(renewRemotePreviewGrant).toHaveBeenCalledTimes(1) - expect(readRemotePreviewChunk).toHaveBeenCalledWith( - { ...granted, grantId: 'g-2' }, - 2, - 3, - expect.any(AbortSignal) - ) - vi.mocked(renewRemotePreviewGrant).mockRejectedValue(new Error('gone')) - vi.mocked(statRemotePreviewFile).mockRejectedValue( - new RemotePreviewGrantLapsedError('terminal_file_grant_expired') - ) - now += 1_500 - expect((await range(minted.mediaUrl)).status).toBe(502) - }) - - const lapsedGrant: RemoteFilePreviewAddress = { - environmentId: 'env-1', - worktree: 'id:wt-1', - grantId: 'g-1', - absolutePath: '/tmp/clip.webm', - expectedEnvironmentPairingRevision: 3 - } - const lapsedFor = (address: RemoteFilePreviewAddress) => - address.grantId === 'g-1' - ? new RemotePreviewGrantLapsedError('terminal_file_grant_expired') - : null - - // Why: the body streams after the response returns, so a chunk can find the grant lapsed while its stat is cached. - it('renews a grant that lapses under a streamed chunk read', async () => { - const minted = await grantRemoteFilePreview(event, lapsedGrant, store) - if (!minted) { - throw new Error('Missing preview') - } - vi.mocked(renewRemotePreviewGrant) - .mockReset() - .mockResolvedValue({ ...lapsedGrant, grantId: 'g-2' }) - vi.mocked(readRemotePreviewChunk).mockImplementation(async (address) => { - const lapsed = lapsedFor(address) - if (lapsed) { - throw lapsed - } - return Uint8Array.from([2, 3, 4]) - }) - - const response = await range(minted.mediaUrl) - - expect(response.status).toBe(206) - expect([...new Uint8Array(await response.arrayBuffer())]).toEqual([2, 3, 4]) - expect(renewRemotePreviewGrant).toHaveBeenCalledTimes(1) - }) - - it('never finishes a stream from a grant renewed onto a rewritten file', async () => { - const minted = await grantRemoteFilePreview(event, lapsedGrant, store) - if (!minted) { - throw new Error('Missing preview') - } - vi.mocked(renewRemotePreviewGrant) - .mockReset() - .mockResolvedValue({ ...lapsedGrant, grantId: 'g-2' }) - vi.mocked(statRemotePreviewFile).mockImplementation(async (address) => - address.grantId === 'g-2' ? { size: 6, mtime: 2 } : { size: 6, mtime: 1 } - ) - vi.mocked(readRemotePreviewChunk).mockImplementation(async (address) => { - const lapsed = lapsedFor(address) - if (lapsed) { - throw lapsed - } - return Uint8Array.from([9, 9, 9]) - }) - - const response = await range(minted.mediaUrl) - - await expect(response.arrayBuffer()).rejects.toThrow() - expect(readRemotePreviewChunk).not.toHaveBeenCalledWith( - expect.objectContaining({ grantId: 'g-2' }), - expect.anything(), - expect.anything(), - expect.anything() - ) - }) - - // Why: pdf.js reads ranges over IPC, not orca-media, and a paused reader outlives its grant too. - it('renews a lapsed grant for a PDF range read over IPC', async () => { - const pdf = { ...lapsedGrant, absolutePath: '/tmp/report.pdf' } - vi.mocked(readRemotePreviewRange).mockResolvedValue(new TextEncoder().encode('%PDF-1.7')) - const minted = await grantRemoteFilePreview(event, pdf, store) - if (!minted) { - throw new Error('Missing preview') - } - now += 1_500 - vi.mocked(renewRemotePreviewGrant) - .mockReset() - .mockResolvedValue({ ...pdf, grantId: 'g-2' }) - vi.mocked(readRemotePreviewRange).mockImplementation(async (address) => { - const lapsed = lapsedFor(address) - if (lapsed) { - throw lapsed - } - return new TextEncoder().encode('PDF') - }) - - const bytes = await readPreviewGrantRange(event.sender, minted.mediaUrl, 1, 3) - - expect(new TextDecoder().decode(bytes)).toBe('PDF') - expect(renewRemotePreviewGrant).toHaveBeenCalledTimes(1) - }) -}) diff --git a/src/main/media/media-preview-protocol.ts b/src/main/media/media-preview-protocol.ts index 256c853aa67..b1d7e9a57b6 100644 --- a/src/main/media/media-preview-protocol.ts +++ b/src/main/media/media-preview-protocol.ts @@ -1,12 +1,12 @@ import { protocol } from 'electron' import type { Store } from '../persistence/loading-store/store' -import { MEDIA_PREVIEW_SCHEME } from '../../shared/media-file-extensions' +import { MEDIA_PREVIEW_SCHEME } from '../../shared/file-preview/media-preview-scheme' import { filePreviewForPath, isDocumentPreview, streamsPreviewByRange, type FilePreview -} from '../../shared/file-preview-kind' +} from '../../shared/file-preview/file-preview-kind' import { assertLocalPreviewRasterHeader, assertPreviewableRasterHeader, @@ -18,8 +18,8 @@ import { prefixFitsDocumentPreview } from './preview-document-signature' import { openLocalPreviewGrantFile } from './local-preview-grant-file' -import type { RemoteFilePreviewAddress } from '../../shared/remote-file-preview-address' -import { remoteFilePath } from '../../shared/remote-file-locator' +import type { RemoteFilePreviewAddress } from '../../shared/file-preview/remote-file-preview-address' +import { remoteFilePath } from '../../shared/file-access/remote-file-locator' import { resolveLocalFileRequestPath } from '../ipc/filesystem/access/local-file-access-resolution' import { openLocalRegularFile } from '../ipc/filesystem/local-regular-file-read' import { abortWhenRendererGone } from '../ipc/renderer-lifetime-abort' diff --git a/src/main/media/media-range-response.ts b/src/main/media/media-range-response.ts index 784485d69d9..98f7aa73f6b 100644 --- a/src/main/media/media-range-response.ts +++ b/src/main/media/media-range-response.ts @@ -1,4 +1,4 @@ -import { MAX_FILE_RANGE_READ_BYTES } from '../../shared/file-range-read' +import { MAX_FILE_RANGE_READ_BYTES } from '../../shared/file-content/file-range-read' type MediaReader = { size: number diff --git a/src/main/media/preview-document-signature.ts b/src/main/media/preview-document-signature.ts index 0fad3e2408e..c983147ca5c 100644 --- a/src/main/media/preview-document-signature.ts +++ b/src/main/media/preview-document-signature.ts @@ -1,4 +1,4 @@ -import type { FilePreview } from '../../shared/file-preview-kind' +import type { FilePreview } from '../../shared/file-preview/file-preview-kind' /** pdf.js accepts a PDF header anywhere in the first 1 KiB. */ export const DOCUMENT_SIGNATURE_PROBE_BYTES = 1024 diff --git a/src/main/media/preview-grant-registry.ts b/src/main/media/preview-grant-registry.ts index 9bd0aed1f83..db3fb55a028 100644 --- a/src/main/media/preview-grant-registry.ts +++ b/src/main/media/preview-grant-registry.ts @@ -1,10 +1,10 @@ import { randomUUID } from 'node:crypto' import type { WebContents } from 'electron' import type { Store } from '../persistence/loading-store/store' -import type { LocalFileAccess } from '../../shared/local-file-access' -import { MEDIA_PREVIEW_SCHEME } from '../../shared/media-file-extensions' -import { isDocumentPreview, type FilePreview } from '../../shared/file-preview-kind' -import type { RemoteFilePreviewAddress } from '../../shared/remote-file-preview-address' +import type { LocalFileAccess } from '../../shared/file-access/local-file-access' +import { MEDIA_PREVIEW_SCHEME } from '../../shared/file-preview/media-preview-scheme' +import { isDocumentPreview, type FilePreview } from '../../shared/file-preview/file-preview-kind' +import type { RemoteFilePreviewAddress } from '../../shared/file-preview/remote-file-preview-address' import { abortWhenRendererGone } from '../ipc/renderer-lifetime-abort' import { RemotePreviewGrantLapsedError, diff --git a/src/main/media/preview-raster-header-check.ts b/src/main/media/preview-raster-header-check.ts index c71a8d1bb16..b29d8acdc66 100644 --- a/src/main/media/preview-raster-header-check.ts +++ b/src/main/media/preview-raster-header-check.ts @@ -1,10 +1,10 @@ import type { FileHandle } from 'node:fs/promises' -import type { FilePreview } from '../../shared/file-preview-kind' -import { rasterImageExceedsPreviewLimits } from '../../shared/raster-image-prefix-limits' -import { RASTER_IMAGE_PREVIEW_TOO_LARGE_ERROR } from '../../shared/raster-image-preview-limits' +import type { FilePreview } from '../../shared/file-preview/file-preview-kind' +import { rasterImageExceedsPreviewLimits } from '../../shared/file-preview/raster-image-prefix-limits' +import { RASTER_IMAGE_PREVIEW_TOO_LARGE_ERROR } from '../../shared/file-preview/raster-image-preview-limits' import { MAX_PREVIEWABLE_BINARY_SIZE } from '../ipc/filesystem/filesystem-file-content-inspection' import { fileTooLargeError } from '../ipc/filesystem/local-regular-file-read' -import type { RemoteFilePreviewAddress } from '../../shared/remote-file-preview-address' +import type { RemoteFilePreviewAddress } from '../../shared/file-preview/remote-file-preview-address' import { readRemotePreviewRange } from './remote-file-preview-reader' /** A URL preview keeps the base64 path's guard: an image whose header proves it oversized never reaches the decoder. */ diff --git a/src/main/media/remote-file-preview-reader.ts b/src/main/media/remote-file-preview-reader.ts index 9441232c73e..25602eff652 100644 --- a/src/main/media/remote-file-preview-reader.ts +++ b/src/main/media/remote-file-preview-reader.ts @@ -1,8 +1,8 @@ -import { MAX_FILE_RANGE_READ_BYTES } from '../../shared/file-range-read' -import type { RemoteFilePreviewAddress } from '../../shared/remote-file-preview-address' -import { remoteFileRequest } from '../../shared/remote-file-locator' -import { isRenewableTerminalFileGrantRefusal } from '../../shared/terminal-file-grant-refusal' -import type { RuntimeFileReadChunkResult } from '../../shared/runtime-file-contracts' +import { MAX_FILE_RANGE_READ_BYTES } from '../../shared/file-content/file-range-read' +import type { RemoteFilePreviewAddress } from '../../shared/file-preview/remote-file-preview-address' +import { remoteFileRequest } from '../../shared/file-access/remote-file-locator' +import { isRenewableTerminalFileGrantRefusal } from '../../shared/file-access/terminal-file-grant-refusal' +import type { RuntimeFileReadChunkResult } from '../../shared/file-content/runtime-file-read' import { callRuntimeEnvironment } from '../ipc/runtime-environments/runtime-environment-transport-routing' import { getRuntimeEnvironmentRegistryRoot } from '../ipc/runtime-environments/runtime-environment-registry-root' diff --git a/src/main/minimax/minimax-cookie-store.ts b/src/main/minimax/minimax-cookie-store.ts index bf0e2cc42f7..357d6e7d2d3 100644 --- a/src/main/minimax/minimax-cookie-store.ts +++ b/src/main/minimax/minimax-cookie-store.ts @@ -2,7 +2,7 @@ import { getSecretStore } from '../../shared/secret-store' import { existsSync, readFileSync, rmSync } from 'node:fs' import { homedir } from 'node:os' import { join } from 'node:path' -import { hardenExistingSecureFile, writeSecureFile } from '../../shared/secure-file' +import { hardenExistingSecureFile, writeSecureFile } from '../../shared/secure-storage/secure-file' import type { SecretAtRestProtection } from '../../shared/secret-at-rest-protection' const MINIMAX_COOKIE_FILE = 'minimax-session-cookie.enc' diff --git a/src/main/native-chat/agent-session-attachments/agent-session-attachment-store.ts b/src/main/native-chat/agent-session-attachments/agent-session-attachment-store.ts index 0cd398ce5d1..7803e1ef9d9 100644 --- a/src/main/native-chat/agent-session-attachments/agent-session-attachment-store.ts +++ b/src/main/native-chat/agent-session-attachments/agent-session-attachment-store.ts @@ -1,7 +1,7 @@ // Per-upload directories preserve original filenames without collisions; atomic commit hides partial bytes. import { readAttachmentTextChunk } from './agent-session-attachment-text-read' -import type { AttachmentTextRequest } from '../../../shared/attachment-text-source' +import type { AttachmentTextRequest } from '../../../shared/attachment-text/attachment-text-source' import { randomUUID } from 'node:crypto' import { appendFile, mkdir, rm, writeFile } from 'node:fs/promises' import { extname, join } from 'node:path' @@ -9,10 +9,10 @@ import { sanitizeAgentSessionAttachmentName, type AgentSessionAttachmentUploadCommitResult } from '../../../shared/agent-session/agent-session-attachments' -import type { RuntimeFilePreviewResult } from '../../../shared/runtime-types' -import { readAuthorizedDocPreviewFile } from '../../../shared/doc-preview-file-access' +import type { RuntimeFilePreviewResult } from '../../../shared/file-content/runtime-file-read' +import { readAuthorizedDocPreviewFile } from '../../../shared/document-preview/doc-preview-file-access' import { renameFileWithWindowsRetryAsync } from '../../../shared/windows-retry-file-operations' -import { IMAGE_FILE_MIME_TYPES } from '../../../shared/image-file-extensions' +import { IMAGE_FILE_MIME_TYPES } from '../../../shared/file-preview/image-mime-types' import { LOCAL_PREVIEWABLE_BINARY_MAX_BYTES, assertPreviewWithinTransportBudget, diff --git a/src/main/native-chat/agent-session-attachments/agent-session-attachment-text-read.ts b/src/main/native-chat/agent-session-attachments/agent-session-attachment-text-read.ts index b897bd0a7bf..7e16162e8cb 100644 --- a/src/main/native-chat/agent-session-attachments/agent-session-attachment-text-read.ts +++ b/src/main/native-chat/agent-session-attachments/agent-session-attachment-text-read.ts @@ -1,13 +1,13 @@ import { createHash } from 'node:crypto' import { stat, realpath } from 'node:fs/promises' -import { openAuthorizedDocPreviewTarget } from '../../../shared/doc-preview-file-access' -import { validateFileRangeRequest } from '../../../shared/file-range-read' +import { openAuthorizedDocPreviewTarget } from '../../../shared/document-preview/doc-preview-file-access' +import { validateFileRangeRequest } from '../../../shared/file-content/file-range-read' import { remoteRpcResultExceedsContentBudget } from '../../../shared/remote-rpc-content-budget' import { AGENT_SESSION_ATTACHMENT_MAX_BYTES } from '../../../shared/agent-session/agent-session-attachments' import type { AttachmentTextChunk, AttachmentTextRequest -} from '../../../shared/attachment-text-source' +} from '../../../shared/attachment-text/attachment-text-source' import { parseAgentSessionAttachmentStorePath } from './agent-session-attachment-references' export async function readAttachmentTextChunk( diff --git a/src/main/native-chat/agent-session-journal/history-import/adopted-transcript-source.ts b/src/main/native-chat/agent-session-journal/history-import/adopted-transcript-source.ts index 97648f31231..48d03063648 100644 --- a/src/main/native-chat/agent-session-journal/history-import/adopted-transcript-source.ts +++ b/src/main/native-chat/agent-session-journal/history-import/adopted-transcript-source.ts @@ -2,7 +2,7 @@ import { dirname, join } from 'node:path' import { sessionIdFromFileName } from '../../../ai-vault/session-scanner-accumulator' import type { AgentType } from '../../../../shared/agent-status/contracts/agent-status-types' import { normalizeRuntimePathForComparison } from '../../../../shared/cross-platform-path' -import { readNodeFileWithinLimit } from '../../../../shared/node-bounded-file-reader' +import { readNodeFileWithinLimit } from '../../../../shared/file-content/node-bounded-file-reader' import { extractString, parseJsonObject } from '../../../ai-vault/session-scanner-values' import { asRecord } from '../../../ai-vault/session-scanner-record-value' diff --git a/src/main/native-chat/native-chat-media-path.ts b/src/main/native-chat/native-chat-media-path.ts index b3b3f479933..90c9a763bb9 100644 --- a/src/main/native-chat/native-chat-media-path.ts +++ b/src/main/native-chat/native-chat-media-path.ts @@ -5,7 +5,7 @@ import type { AgentSessionConversationView } from '../../shared/agent-session/li import { isLegacyAgentSessionAccountHome } from '../../shared/agent-session/lifecycle/agent-session-account-home' import { MAX_AGENT_SESSION_PROVIDER_HANDLE_LINKS } from '../../shared/agent-session/lifecycle/agent-session-provider-handle' import { structuredAgentSessionTabId } from '../../shared/agent-session/view/structured-agent-session-projection' -import type { RuntimeNativeChatFileContext } from '../../shared/runtime-types' +import type { RuntimeNativeChatFileContext } from '../../shared/native-chat/native-chat-file-context' import type { ExecutionHostId } from '../../shared/execution-host' import { parsePaneKey } from '../../shared/workspace-layout/stable-pane-id' import { @@ -15,7 +15,7 @@ import { isSafeGrokSessionId, resolveGrokSessionsDir } from '../../shared/grok-session-paths' -import { readNodeFileWithinLimit } from '../../shared/node-bounded-file-reader' +import { readNodeFileWithinLimit } from '../../shared/file-content/node-bounded-file-reader' import { isENOENT } from '../ipc/filesystem/access/filesystem-path-containment' import { needsWslHostResolution } from './host-readable-transcript-path' import { parseWslPath } from '../wsl/filesystem/unc-path-access' diff --git a/src/main/native-chat/native-chat-visual-guest-location.ts b/src/main/native-chat/native-chat-visual-guest-location.ts index 4f000fb7cfc..11e97d17162 100644 --- a/src/main/native-chat/native-chat-visual-guest-location.ts +++ b/src/main/native-chat/native-chat-visual-guest-location.ts @@ -1,7 +1,7 @@ import { basename, dirname } from 'node:path' import { fileURLToPath } from 'node:url' import { isNativeChatVisualFileName } from '../../shared/native-chat/native-chat-visual-directive' -import { parseDocPreviewUrl } from '../../shared/doc-preview-scheme' +import { parseDocPreviewUrl } from '../../shared/document-preview/doc-preview-scheme' import { getDocPreviewGrant } from '../browser/document-preview/doc-preview-grant-registry' /** Presentation identity only; existing file/grant policies still own every read. */ diff --git a/src/main/native-chat/transcript-line-decoders-omp.ts b/src/main/native-chat/transcript-line-decoders-omp.ts index ce6903a8587..dcd3a555bb6 100644 --- a/src/main/native-chat/transcript-line-decoders-omp.ts +++ b/src/main/native-chat/transcript-line-decoders-omp.ts @@ -7,7 +7,7 @@ import { type NativeChatMessage } from '../../shared/native-chat/native-chat-types' import type { AgentSessionTokenUsage } from '../../shared/agent-session/agent-session-context-usage' -import { buildImageDataUri } from '../../shared/image-data-uri' +import { buildImageDataUri } from '../../shared/file-preview/image-data-uri' import { asRecord, extractString, diff --git a/src/main/observability/index.ts b/src/main/observability/index.ts index 7db1241036f..008a82a0156 100644 --- a/src/main/observability/index.ts +++ b/src/main/observability/index.ts @@ -23,7 +23,7 @@ import { type UploadBundleResult } from './diagnostic-bundle-upload' import { setActiveSink, startSpan } from './tracer' -import { setSecurePathHardeningReporter } from '../../shared/secure-path-hardening-report' +import { setSecurePathHardeningReporter } from '../../shared/secure-storage/secure-path-hardening-report' import { withTimeout } from '../../shared/promise-timeout-fallback' const CI_ENV_VARS = [ diff --git a/src/main/opencode/opencode-model-catalog-listing.ts b/src/main/opencode/opencode-model-catalog-listing.ts index fa8dafd98a5..d67d1e5297c 100644 --- a/src/main/opencode/opencode-model-catalog-listing.ts +++ b/src/main/opencode/opencode-model-catalog-listing.ts @@ -2,7 +2,7 @@ import { z } from 'zod' import type { AgentSessionModelOption } from '../../shared/agent-session/agent-session-wire' -import { assertJsonTextStructureWithinLimits } from '../../shared/json-text-structure-limit' +import { assertJsonTextStructureWithinLimits } from '../../shared/json-stream/json-text-structure-limit' export const OPENCODE_MODEL_LISTING_ARGS = ['models', '--verbose'] as const diff --git a/src/main/orca-profiles/profile-artifact-cloud-cleanup.ts b/src/main/orca-profiles/profile-artifact-cloud-cleanup.ts index 88e90471914..be71a725984 100644 --- a/src/main/orca-profiles/profile-artifact-cloud-cleanup.ts +++ b/src/main/orca-profiles/profile-artifact-cloud-cleanup.ts @@ -1,7 +1,10 @@ import { existsSync, readFileSync, rmSync } from 'node:fs' import { join } from 'node:path' import type { OrcaProfileCloudSummary, OrcaProfileSummary } from '../../shared/orca-profiles' -import { bestEffortFsyncDirectorySync, writeDurableSecureJsonFile } from '../../shared/secure-file' +import { + bestEffortFsyncDirectorySync, + writeDurableSecureJsonFile +} from '../../shared/secure-storage/secure-file' import { clearArtifactCreateIntents } from '../artifacts/artifact-create-intent-store' import { clearArtifactShareRecords } from '../artifacts/artifact-share-record-store' import { getOrcaProfileDirectory } from './profile-storage-paths' diff --git a/src/main/orca-profiles/profile-cloud-session-refresh-rotation.test.ts b/src/main/orca-profiles/profile-cloud-session-refresh-rotation.test.ts index 7b77999ea9c..b0bd81ffeb4 100644 --- a/src/main/orca-profiles/profile-cloud-session-refresh-rotation.test.ts +++ b/src/main/orca-profiles/profile-cloud-session-refresh-rotation.test.ts @@ -3,7 +3,7 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import type * as ProfileCloudClient from './profile-cloud-client' -import type * as SecureFile from '../../shared/secure-file' +import type * as SecureFile from '../../shared/secure-storage/secure-file' import type * as Fs from 'node:fs' import type * as ProfileIndexStore from './profile-index-store' @@ -47,7 +47,7 @@ vi.mock('electron', () => ({ } })) -vi.mock('../../shared/secure-file', async (importOriginal) => { +vi.mock('../../shared/secure-storage/secure-file', async (importOriginal) => { const original = await importOriginal() return { ...original, diff --git a/src/main/orca-profiles/profile-cloud-session-store.ts b/src/main/orca-profiles/profile-cloud-session-store.ts index 79afe2ce14b..00d26cd9446 100644 --- a/src/main/orca-profiles/profile-cloud-session-store.ts +++ b/src/main/orca-profiles/profile-cloud-session-store.ts @@ -1,7 +1,7 @@ import { existsSync, readFileSync, rmSync } from 'node:fs' import { join } from 'node:path' import { guardedSafeStorage as safeStorage } from '../host/safe-storage-availability' -import { isUnreadableError, writeSecureJsonFile } from '../../shared/secure-file' +import { isUnreadableError, writeSecureJsonFile } from '../../shared/secure-storage/secure-file' import type { OrcaCloudCapabilities, OrcaCloudOrgSummary, diff --git a/src/main/orca-profiles/profile-index-store.ts b/src/main/orca-profiles/profile-index-store.ts index 5372d3abb30..2c082b9a624 100644 --- a/src/main/orca-profiles/profile-index-store.ts +++ b/src/main/orca-profiles/profile-index-store.ts @@ -8,7 +8,10 @@ import { } from 'node:fs' import { randomUUID } from 'node:crypto' import { dirname } from 'node:path' -import { bestEffortFsyncDirectorySync, fsyncFileSync } from '../../shared/secure-file' +import { + bestEffortFsyncDirectorySync, + fsyncFileSync +} from '../../shared/secure-storage/secure-file' import { createDefaultLocalOrcaProfile, DEFAULT_LOCAL_ORCA_PROFILE_ID, diff --git a/src/main/orca-profiles/profile-project-move-intent.ts b/src/main/orca-profiles/profile-project-move-intent.ts index 51fd796e5ff..cdbd089f1ea 100644 --- a/src/main/orca-profiles/profile-project-move-intent.ts +++ b/src/main/orca-profiles/profile-project-move-intent.ts @@ -1,6 +1,9 @@ import { randomUUID } from 'node:crypto' import { mkdirSync, renameSync, rmSync, writeFileSync } from 'node:fs' -import { bestEffortFsyncDirectorySync, fsyncFileSync } from '../../shared/secure-file' +import { + bestEffortFsyncDirectorySync, + fsyncFileSync +} from '../../shared/secure-storage/secure-file' import { hashProfileStateJson } from '../persistence/profile-state/profile-state-documents' import { readProfileStateWithRevision, diff --git a/src/main/orcad/orcad-cli-launcher.ts b/src/main/orcad/orcad-cli-launcher.ts index 5f8987750d5..844ce159f33 100644 --- a/src/main/orcad/orcad-cli-launcher.ts +++ b/src/main/orcad/orcad-cli-launcher.ts @@ -6,7 +6,7 @@ import { ORCAD_CLI_ENTRY_FILENAME, ORCAD_WINDOWS_CLI_LAUNCHER_FILENAME } from '../../shared/orcad-artifacts' -import { nodeFileContentsEqual } from '../../shared/node-file-content-equality' +import { nodeFileContentsEqual } from '../../shared/file-content/node-file-content-equality' import { buildUnixCliLauncher } from '../cli/cli-dev-launcher' import { writeFileAtomically } from '../codex-accounts/fs-utils' import { resolveOrcadInstallRoot, resolveUserDataPath } from './orcad-app-paths' diff --git a/src/main/orcad/orcad-completed-stop-receipt.ts b/src/main/orcad/orcad-completed-stop-receipt.ts index db71fd7589e..8114ddddcbe 100644 --- a/src/main/orcad/orcad-completed-stop-receipt.ts +++ b/src/main/orcad/orcad-completed-stop-receipt.ts @@ -1,8 +1,8 @@ import { lstatSync } from 'node:fs' import { dirname, join } from 'node:path' import type { z } from 'zod' -import { readNodeFileSyncWithinLimit } from '../../shared/node-bounded-file-reader' -import { writeDurableSecureJsonFile } from '../../shared/secure-file' +import { readNodeFileSyncWithinLimit } from '../../shared/file-content/node-bounded-file-reader' +import { writeDurableSecureJsonFile } from '../../shared/secure-storage/secure-file' import { hasErrorCode } from '../daemon/endpoint/identity/daemon-process-inspection' import { ORCAD_STOP_RECEIPTS_DIRNAME, diff --git a/src/main/orcad/orcad-data-root-privacy.ts b/src/main/orcad/orcad-data-root-privacy.ts index 6679cfe7dd5..f32688b0a59 100644 --- a/src/main/orcad/orcad-data-root-privacy.ts +++ b/src/main/orcad/orcad-data-root-privacy.ts @@ -1,6 +1,6 @@ import { chmodSync, statSync } from 'node:fs' import process from 'node:process' -import { restrictWindowsPathSync } from '../../shared/secure-path-windows-acl' +import { restrictWindowsPathSync } from '../../shared/secure-storage/secure-path-windows-acl' type OrcadInstanceLockCode = | 'orcad_data_root_unusable' diff --git a/src/main/orcad/orcad-exit-code.ts b/src/main/orcad/orcad-exit-code.ts index 18eb47a37db..685b142feac 100644 --- a/src/main/orcad/orcad-exit-code.ts +++ b/src/main/orcad/orcad-exit-code.ts @@ -1,7 +1,7 @@ import { OrcadBindAddressError } from '../../shared/orcad-bind-address' import { OrcadBundledRuntimeError } from './orcad-bundled-runtime' import { OrcadInstanceLockError } from './orcad-data-root-privacy' -import { ProfileStateAccessError } from '../persistence/profile-state/profile-state-access' +import { ProfileStateAccessError } from '../persistence/profile-state/profile-state-access-error' import { ORCAD_EXIT_CONFIGURATION } from './orcad-configuration-exit' import { SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE } from '../../shared/single-instance-exit-code' import { ORCAD_EXIT_TERMINALS_NOT_DURABLE } from '../../shared/serve-supervised-terminal-durability' diff --git a/src/main/orcad/orcad-idle-stop-record.ts b/src/main/orcad/orcad-idle-stop-record.ts index 453962a9aa8..30c8d3fd7e8 100644 --- a/src/main/orcad/orcad-idle-stop-record.ts +++ b/src/main/orcad/orcad-idle-stop-record.ts @@ -1,8 +1,8 @@ // Consume clean idle-stop evidence once; discard failed stops so later crashes cannot inherit it. import { rmSync } from 'node:fs' import { join } from 'node:path' -import { readNodeFileSyncWithinLimit } from '../../shared/node-bounded-file-reader' -import { writeDurableSecureJsonFile } from '../../shared/secure-file' +import { readNodeFileSyncWithinLimit } from '../../shared/file-content/node-bounded-file-reader' +import { writeDurableSecureJsonFile } from '../../shared/secure-storage/secure-file' import { ORCAD_IDLE_STOP_RECORD_FILENAME, OrcadIdleStopRecordSchema, diff --git a/src/main/orcad/orcad-instance-lock-reclaim.ts b/src/main/orcad/orcad-instance-lock-reclaim.ts index ec48871d898..e8444b6804a 100644 --- a/src/main/orcad/orcad-instance-lock-reclaim.ts +++ b/src/main/orcad/orcad-instance-lock-reclaim.ts @@ -13,7 +13,7 @@ import { import { basename, dirname, join } from 'node:path' import process from 'node:process' import { OrcadInstanceLockError } from './orcad-data-root-privacy' -import { readNodeFileSyncWithinLimit } from '../../shared/node-bounded-file-reader' +import { readNodeFileSyncWithinLimit } from '../../shared/file-content/node-bounded-file-reader' import { hasErrorCode } from '../daemon/endpoint/identity/daemon-process-inspection' export const MAX_ORCAD_LOCK_BYTES = 64 * 1024 diff --git a/src/main/orcad/orcad-managed-stop-cancellation.test.ts b/src/main/orcad/orcad-managed-stop-cancellation.test.ts index 1fc7f219f67..5e8a906c7a1 100644 --- a/src/main/orcad/orcad-managed-stop-cancellation.test.ts +++ b/src/main/orcad/orcad-managed-stop-cancellation.test.ts @@ -3,7 +3,7 @@ import { rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import type * as WindowsAcl from '../../shared/secure-path-windows-acl' +import type * as WindowsAcl from '../../shared/secure-storage/secure-path-windows-acl' import type { OrcadManagedStopRequest } from '../../shared/orcad-stop-request' import { acquireOrcadInstanceLock } from './orcad-instance-lock' @@ -13,7 +13,7 @@ import { claimOrcadManagedStopDecision } from './orcad-managed-stop-decision' const hardening = vi.hoisted(() => ({ pending: new Set>() })) -vi.mock('../../shared/secure-path-windows-acl', async (importOriginal) => { +vi.mock('../../shared/secure-storage/secure-path-windows-acl', async (importOriginal) => { const acl = await importOriginal() return { ...acl, diff --git a/src/main/orcad/orcad-managed-stop-completion.ts b/src/main/orcad/orcad-managed-stop-completion.ts index 6ab989b0919..839372a972c 100644 --- a/src/main/orcad/orcad-managed-stop-completion.ts +++ b/src/main/orcad/orcad-managed-stop-completion.ts @@ -1,6 +1,6 @@ // Request shutdown without signaling; only kernel identity, owner change or PID absence proves exit. import { setTimeout as delay } from 'node:timers/promises' -import { writeDurableSecureJsonFile } from '../../shared/secure-file' +import { writeDurableSecureJsonFile } from '../../shared/secure-storage/secure-file' import { OrcadManagedStopRequestSchema, orcadManagedStopRequestKey, diff --git a/src/main/orcad/orcad-managed-stop-decision.ts b/src/main/orcad/orcad-managed-stop-decision.ts index 94e722003a1..8684361d2ed 100644 --- a/src/main/orcad/orcad-managed-stop-decision.ts +++ b/src/main/orcad/orcad-managed-stop-decision.ts @@ -1,7 +1,7 @@ // Exclusive hard links arbitrate stop versus cancel; cancel cannot succeed once dispatch wins. import { linkSync, rmSync } from 'node:fs' import { randomUUID } from 'node:crypto' -import { writeDurableSecureJsonFile } from '../../shared/secure-file' +import { writeDurableSecureJsonFile } from '../../shared/secure-storage/secure-file' import { OrcadManagedStopDecisionSchema, OrcadManagedStopRequestSchema, diff --git a/src/main/orcad/orcad-managed-stop-request.ts b/src/main/orcad/orcad-managed-stop-request.ts index 4aa272233a5..4a75f130bf7 100644 --- a/src/main/orcad/orcad-managed-stop-request.ts +++ b/src/main/orcad/orcad-managed-stop-request.ts @@ -1,7 +1,7 @@ import { createHash } from 'node:crypto' import { lstatSync } from 'node:fs' import { dirname, join, resolve } from 'node:path' -import { readNodeFileSyncWithinLimit } from '../../shared/node-bounded-file-reader' +import { readNodeFileSyncWithinLimit } from '../../shared/file-content/node-bounded-file-reader' import { ORCAD_MANAGED_STOP_REQUEST_MAX_BYTES, ORCAD_MANAGED_STOP_REQUEST_PREFIX, diff --git a/src/main/orcad/orcad-managed-stop.test.ts b/src/main/orcad/orcad-managed-stop.test.ts index 578126e13b1..51a2ed944f1 100644 --- a/src/main/orcad/orcad-managed-stop.test.ts +++ b/src/main/orcad/orcad-managed-stop.test.ts @@ -2,7 +2,7 @@ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'no import { tmpdir } from 'node:os' import { basename, dirname, join, sep } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import type * as WindowsAcl from '../../shared/secure-path-windows-acl' +import type * as WindowsAcl from '../../shared/secure-storage/secure-path-windows-acl' import type { OrcadManagedStopRequest } from '../../shared/orcad-stop-request' import { acquireOrcadInstanceLock, type OrcadInstanceLock } from './orcad-instance-lock' import { @@ -18,7 +18,7 @@ import { runOrcadManagedStopCommand } from './orcad-managed-stop-command' const hardening = vi.hoisted(() => ({ pending: new Set>() })) -vi.mock('../../shared/secure-path-windows-acl', async (importOriginal) => { +vi.mock('../../shared/secure-storage/secure-path-windows-acl', async (importOriginal) => { const acl = await importOriginal() return { ...acl, diff --git a/src/main/orcad/orcad-plaintext-credential-migration.ts b/src/main/orcad/orcad-plaintext-credential-migration.ts index 7a3e6067f08..f93b8cc0441 100644 --- a/src/main/orcad/orcad-plaintext-credential-migration.ts +++ b/src/main/orcad/orcad-plaintext-credential-migration.ts @@ -4,7 +4,7 @@ import { homedir } from 'node:os' import { join } from 'node:path' import type { SecretStore } from '../../shared/secret-store' import { classifyUnenvelopedCredential } from '../../shared/secret-at-rest-protection' -import { hardenExistingSecureFile, writeSecureFile } from '../../shared/secure-file' +import { hardenExistingSecureFile, writeSecureFile } from '../../shared/secure-storage/secure-file' import { writeCredentialFileAtomic } from '../credentials/integration-credential-file' import { getWorkspaceTokenDir, diff --git a/src/main/orcad/orcad-secret-key-record.ts b/src/main/orcad/orcad-secret-key-record.ts index 5ad97213c64..680d1384fe0 100644 --- a/src/main/orcad/orcad-secret-key-record.ts +++ b/src/main/orcad/orcad-secret-key-record.ts @@ -16,8 +16,8 @@ import { bestEffortFsyncDirectorySync, hardenExistingSecureFile, writeSecureFile -} from '../../shared/secure-file' -import { restrictWindowsFile } from '../../shared/secure-path-windows-acl' +} from '../../shared/secure-storage/secure-file' +import { restrictWindowsFile } from '../../shared/secure-storage/secure-path-windows-acl' import { ORCAD_MASTER_KEY_BYTES } from './orcad-secret-sealing' import { hasErrorCode, isProcessAlive } from '../daemon/endpoint/identity/daemon-process-inspection' import { errorMessage } from '../../shared/error-message' diff --git a/src/main/orcad/orcad-serve-cleanup-diagnostics.test-fixture.ts b/src/main/orcad/orcad-serve-cleanup-diagnostics.test-fixture.ts index 950b46c9c30..8ba0ac26d1b 100644 --- a/src/main/orcad/orcad-serve-cleanup-diagnostics.test-fixture.ts +++ b/src/main/orcad/orcad-serve-cleanup-diagnostics.test-fixture.ts @@ -1,7 +1,7 @@ import { existsSync, readdirSync } from 'node:fs' import { join } from 'node:path' import type { spawnProcess } from '@orca/process-host' -import { readNodeFileSyncWithinLimit } from '../../shared/node-bounded-file-reader' +import { readNodeFileSyncWithinLimit } from '../../shared/file-content/node-bounded-file-reader' import { buildProcessTableIndex, collectDescendantsFromIndex diff --git a/src/main/orcad/orcad-wsl-holder-release.ts b/src/main/orcad/orcad-wsl-holder-release.ts index ba7fbc4371d..942c21abf82 100644 --- a/src/main/orcad/orcad-wsl-holder-release.ts +++ b/src/main/orcad/orcad-wsl-holder-release.ts @@ -5,7 +5,7 @@ import { rmSync } from 'node:fs' import { join } from 'node:path' import { ORCAD_WSL_HOLDER_RELEASE_FILENAME } from '../../shared/orcad-idle-exit' -import { writeSecureFile } from '../../shared/secure-file' +import { writeSecureFile } from '../../shared/secure-storage/secure-file' import { ORCAD_WSL_HOST_ENV } from '../ipc/wsl-guest-windows-drive-path' import type { OrcadDaemonRetirement } from './orcad-daemon-retirement' diff --git a/src/main/persistence/applying-settings/ui-state-read.ts b/src/main/persistence/applying-settings/ui-state-read.ts index 7d91463a475..238f6ab67b3 100644 --- a/src/main/persistence/applying-settings/ui-state-read.ts +++ b/src/main/persistence/applying-settings/ui-state-read.ts @@ -1,5 +1,5 @@ import { normalizeGitGraphFilters } from '../../../shared/git/history/git-graph-filters' -import { normalizeExplorerDisplayRootByWorktree } from '../../../shared/file-explorer-display-root' +import { normalizeExplorerDisplayRootByWorktree } from '../../../shared/file-listing/file-explorer-display-root' import type { PersistedState } from '../../../shared/persisted-state-types' import { getDefaultUIState, diff --git a/src/main/persistence/applying-settings/ui-state-update.ts b/src/main/persistence/applying-settings/ui-state-update.ts index b294f577524..5d954d8ff2e 100644 --- a/src/main/persistence/applying-settings/ui-state-update.ts +++ b/src/main/persistence/applying-settings/ui-state-update.ts @@ -1,5 +1,5 @@ import { normalizeGitGraphFilters } from '../../../shared/git/history/git-graph-filters' -import { normalizeExplorerDisplayRootByWorktree } from '../../../shared/file-explorer-display-root' +import { normalizeExplorerDisplayRootByWorktree } from '../../../shared/file-listing/file-explorer-display-root' import type { PersistedState } from '../../../shared/persisted-state-types' import { getDefaultUIState, diff --git a/src/main/persistence/loading-store/normalize-loaded-ui-state.ts b/src/main/persistence/loading-store/normalize-loaded-ui-state.ts index edc2fda00e4..d3bcd2767c6 100644 --- a/src/main/persistence/loading-store/normalize-loaded-ui-state.ts +++ b/src/main/persistence/loading-store/normalize-loaded-ui-state.ts @@ -1,6 +1,6 @@ import { normalizeGitGraphFilters } from '../../../shared/git/history/git-graph-filters' import { resolveStatusBarCompactChangeNoticeDismissed } from '../../../shared/status-bar-compact-change-notice' -import { migrateExplorerDisplayRoots } from '../../../shared/file-explorer-display-root' +import { migrateExplorerDisplayRoots } from '../../../shared/file-listing/file-explorer-display-root' import { getWorktreeCardModeProperties, isCurrentCompactWorktreeCardProperties, diff --git a/src/main/persistence/loading-store/user-data-path.ts b/src/main/persistence/loading-store/user-data-path.ts index 2f623ee10c6..470d611f49b 100644 --- a/src/main/persistence/loading-store/user-data-path.ts +++ b/src/main/persistence/loading-store/user-data-path.ts @@ -2,7 +2,7 @@ import { getAppEnvironment } from '../../../shared/app-environment' import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs' import { dirname, join, resolve } from 'node:path' import type { PersistedState } from '../../../shared/persisted-state-types' -import { hardenExistingSecureFile } from '../../../shared/secure-file' +import { hardenExistingSecureFile } from '../../../shared/secure-storage/secure-file' import { MOBILE_PAIRING_USERDATA_FILES } from '../../runtime/rpc/server/pairing/mobile-pairing-files' // Capture after dev redirection but before app.setName changes path casing and loses case-sensitive data. diff --git a/src/main/persistence/migrating-orcad-catalog/migration-journal-directory.ts b/src/main/persistence/migrating-orcad-catalog/migration-journal-directory.ts index 4743ef1c27e..91e59e93a38 100644 --- a/src/main/persistence/migrating-orcad-catalog/migration-journal-directory.ts +++ b/src/main/persistence/migrating-orcad-catalog/migration-journal-directory.ts @@ -1,9 +1,9 @@ // Unreadable journals fail closed; source-specific directories preserve older-build compatibility. import { existsSync, mkdirSync, readdirSync, rmSync, statSync } from 'node:fs' import { join } from 'node:path' -import { writeSecureJsonFileWithinLimit } from '../../../shared/bounded-secure-json-file' +import { writeSecureJsonFileWithinLimit } from '../../../shared/secure-storage/bounded-secure-json-file' import { errorMessage } from '../../../shared/error-message' -import { readNodeFileSyncWithinLimit } from '../../../shared/node-bounded-file-reader' +import { readNodeFileSyncWithinLimit } from '../../../shared/file-content/node-bounded-file-reader' import { syncDirectoryDurablySync } from '../../filesystem/durable-file-write' const JOURNAL_FILE = /^[A-Za-z0-9_-]{1,128}\.json$/ diff --git a/src/main/persistence/moving-wsl-projects/wsl-move-orchestrator-store.ts b/src/main/persistence/moving-wsl-projects/wsl-move-orchestrator-store.ts index 50d59e7f265..5931a5580d2 100644 --- a/src/main/persistence/moving-wsl-projects/wsl-move-orchestrator-store.ts +++ b/src/main/persistence/moving-wsl-projects/wsl-move-orchestrator-store.ts @@ -6,7 +6,7 @@ import { readFileSync } from 'node:fs' import { join } from 'node:path' import { z } from 'zod' -import { writeDurableSecureJsonFile } from '../../../shared/secure-file' +import { writeDurableSecureJsonFile } from '../../../shared/secure-storage/secure-file' import { wslMoveJournalKey } from '../../../shared/wsl-move/wsl-move-cutover' import type { WslMoveOrchestratorRecord } from '../../../shared/wsl-move/wsl-move-orchestrator-types' diff --git a/src/main/persistence/profile-state/legacy-json/profile-state-recovery.ts b/src/main/persistence/profile-state/legacy-json/profile-state-recovery.ts index d913fedf5c3..ecb123c765a 100644 --- a/src/main/persistence/profile-state/legacy-json/profile-state-recovery.ts +++ b/src/main/persistence/profile-state/legacy-json/profile-state-recovery.ts @@ -3,7 +3,7 @@ import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs' import { dirname } from 'node:path' import { parseProfileStateRoot } from '../profile-state-document-validation' import { durableWriteTempPath, writeFileDurableSync } from '../../../filesystem/durable-file-write' -import { bestEffortFsyncDirectorySync } from '../../../../shared/secure-file' +import { bestEffortFsyncDirectorySync } from '../../../../shared/secure-storage/secure-file' import { quarantineProfileStateDatabase, type ProfileStateDatabaseQuarantine diff --git a/src/main/persistence/profile-state/legacy-json/profile-state-versioned-export.ts b/src/main/persistence/profile-state/legacy-json/profile-state-versioned-export.ts index 9aa5f051cbc..d5f5069a6ec 100644 --- a/src/main/persistence/profile-state/legacy-json/profile-state-versioned-export.ts +++ b/src/main/persistence/profile-state/legacy-json/profile-state-versioned-export.ts @@ -1,6 +1,9 @@ import { lstatSync, mkdirSync, readFileSync, rmSync } from 'node:fs' import { dirname } from 'node:path' -import { bestEffortFsyncDirectorySync, fsyncFileSync } from '../../../../shared/secure-file' +import { + bestEffortFsyncDirectorySync, + fsyncFileSync +} from '../../../../shared/secure-storage/secure-file' import { durableWriteTempPath, publishFileDurableSync diff --git a/src/main/persistence/profile-state/profile-state-access-error.ts b/src/main/persistence/profile-state/profile-state-access-error.ts new file mode 100644 index 00000000000..86c8e4bd0ea --- /dev/null +++ b/src/main/persistence/profile-state/profile-state-access-error.ts @@ -0,0 +1,8 @@ +export class ProfileStateAccessError extends Error { + readonly code = 'profile-state-access-refused' as const + + constructor(message: string) { + super(message) + this.name = 'ProfileStateAccessError' + } +} diff --git a/src/main/persistence/profile-state/profile-state-access-owner.ts b/src/main/persistence/profile-state/profile-state-access-owner.ts index 3b4c4393e09..7bef78abf13 100644 --- a/src/main/persistence/profile-state/profile-state-access-owner.ts +++ b/src/main/persistence/profile-state/profile-state-access-owner.ts @@ -12,7 +12,11 @@ import { } from 'node:fs' import { hostname } from 'node:os' import { dirname, join } from 'node:path' -import { bestEffortFsyncDirectorySync, fsyncFileSync } from '../../../shared/secure-file' +import { ProfileStateAccessError } from './profile-state-access-error' +import { + bestEffortFsyncDirectorySync, + fsyncFileSync +} from '../../../shared/secure-storage/secure-file' import { renameFileWithWindowsRetry } from '../../codex-accounts/fs-utils' import { START_TIME_TOLERANCE_MS, @@ -25,15 +29,6 @@ import { profileStateAccessWrittenThisBoot } from './profile-state-access-identity' -export class ProfileStateAccessError extends Error { - readonly code = 'profile-state-access-refused' as const - - constructor(message: string) { - super(message) - this.name = 'ProfileStateAccessError' - } -} - export type ProfileStateAccessPaths = ReturnType export function profileStateAccessPaths(userDataPath: string) { diff --git a/src/main/persistence/profile-state/profile-state-access.ts b/src/main/persistence/profile-state/profile-state-access.ts index 724549dc7de..ce06f88689c 100644 --- a/src/main/persistence/profile-state/profile-state-access.ts +++ b/src/main/persistence/profile-state/profile-state-access.ts @@ -1,13 +1,12 @@ import { lstatSync, readdirSync, realpathSync } from 'node:fs' import { basename, dirname, join } from 'node:path' import { - ProfileStateAccessError, hasCode, profileStateAccessPaths, publishAccessOwner, reclaimExitedOwner } from './profile-state-access-owner' -export { ProfileStateAccessError } from './profile-state-access-owner' +import { ProfileStateAccessError } from './profile-state-access-error' export type ProfileStateRuntimeAdmission = { assertActive(): void diff --git a/src/main/persistence/profile-state/profile-state-database-quarantine.ts b/src/main/persistence/profile-state/profile-state-database-quarantine.ts index 985cb4e9114..6cc127a4384 100644 --- a/src/main/persistence/profile-state/profile-state-database-quarantine.ts +++ b/src/main/persistence/profile-state/profile-state-database-quarantine.ts @@ -2,7 +2,10 @@ import { profileStateDatabaseFiles } from './profile-state-storage-classificatio import { randomUUID } from 'node:crypto' import { existsSync, mkdirSync, rmSync } from 'node:fs' import { basename, dirname, join } from 'node:path' -import { bestEffortFsyncDirectorySync, fsyncFileSync } from '../../../shared/secure-file' +import { + bestEffortFsyncDirectorySync, + fsyncFileSync +} from '../../../shared/secure-storage/secure-file' import { durableWriteTempPath, writeFileDurableSync } from '../../filesystem/durable-file-write' import { hardenSqliteDatabaseFiles } from '../../sqlite/harden-database-files' import { copyProfileStateRecoveryFiles } from './profile-state-recovery-copy' diff --git a/src/main/persistence/profile-state/profile-state-database-recovery.ts b/src/main/persistence/profile-state/profile-state-database-recovery.ts index 9a5ec67b392..f7aadf972f6 100644 --- a/src/main/persistence/profile-state/profile-state-database-recovery.ts +++ b/src/main/persistence/profile-state/profile-state-database-recovery.ts @@ -3,7 +3,10 @@ import { existsSync, lstatSync, mkdirSync, rmSync } from 'node:fs' import { dirname } from 'node:path' import { durableWriteTempPath, renameDurableSync } from '../../filesystem/durable-file-write' import { hardenSqliteDatabaseFiles } from '../../sqlite/harden-database-files' -import { bestEffortFsyncDirectorySync, fsyncFileSync } from '../../../shared/secure-file' +import { + bestEffortFsyncDirectorySync, + fsyncFileSync +} from '../../../shared/secure-storage/secure-file' import { openProfileStateDatabaseReadOnly } from './profile-state-database' import { validateProfileStateSnapshot } from './profile-state-documents' import { copyProfileStateRecoveryFile } from './profile-state-recovery-copy' diff --git a/src/main/plugins/appearance/plugin-appearance-service.ts b/src/main/plugins/appearance/plugin-appearance-service.ts index 1355250bff0..e07c2abe55d 100644 --- a/src/main/plugins/appearance/plugin-appearance-service.ts +++ b/src/main/plugins/appearance/plugin-appearance-service.ts @@ -3,7 +3,7 @@ import { existsSync, readFileSync, statSync } from 'node:fs' import { join } from 'node:path' import { z } from 'zod' import type { GlobalSettings } from '../../../shared/global-settings-types' -import { writeSecureFile } from '../../../shared/secure-file' +import { writeSecureFile } from '../../../shared/secure-storage/secure-file' import type { PluginThemeRegistration } from '../../../shared/plugins/artifacts/plugin-theme-artifact' import type { PluginTerminalThemeRegistration } from '../../../shared/plugins/artifacts/plugin-terminal-theme-artifact' import type { diff --git a/src/main/plugins/plugin-secrets-store.ts b/src/main/plugins/plugin-secrets-store.ts index 728ea27db71..928c7fa19f5 100644 --- a/src/main/plugins/plugin-secrets-store.ts +++ b/src/main/plugins/plugin-secrets-store.ts @@ -5,7 +5,7 @@ import { assessSecretProtection, type SecretProtectionAssessment } from '../host/electron-secret-store' -import { isUnreadableError, writeSecureFile } from '../../shared/secure-file' +import { isUnreadableError, writeSecureFile } from '../../shared/secure-storage/secure-file' import { PLUGIN_STORAGE_KEY_LIMIT, PLUGIN_STORAGE_TOTAL_MAX_BYTES diff --git a/src/main/plugins/plugin-storage-store.ts b/src/main/plugins/plugin-storage-store.ts index 87cd72a413b..784ca099f83 100644 --- a/src/main/plugins/plugin-storage-store.ts +++ b/src/main/plugins/plugin-storage-store.ts @@ -1,6 +1,6 @@ import { existsSync, readFileSync, statSync } from 'node:fs' import { join } from 'node:path' -import { isUnreadableError, writeSecureFile } from '../../shared/secure-file' +import { isUnreadableError, writeSecureFile } from '../../shared/secure-storage/secure-file' import { isQualifiedPluginKey } from '../../shared/plugins/manifest/plugin-manifest' import { PLUGIN_STORAGE_KEY_LIMIT, diff --git a/src/main/providers/filesystem-markdown-listing.ts b/src/main/providers/filesystem-markdown-listing.ts index 2e66b68029d..7985c29f839 100644 --- a/src/main/providers/filesystem-markdown-listing.ts +++ b/src/main/providers/filesystem-markdown-listing.ts @@ -1,6 +1,6 @@ import type { IFilesystemProvider } from './filesystem-provider-contract' -import { markdownDocumentsFromRelativePaths } from '../../shared/markdown-document-paths' -import { FileInventoryBudget } from '../../shared/file-inventory-budget' +import { markdownDocumentsFromRelativePaths } from '../../shared/file-listing/markdown-document-paths' +import { FileInventoryBudget } from '../../shared/file-listing/file-inventory-budget' type MarkdownListingProvider = | Required> diff --git a/src/main/providers/filesystem-provider-contract.ts b/src/main/providers/filesystem-provider-contract.ts index 179c322510e..4f2c392f68e 100644 --- a/src/main/providers/filesystem-provider-contract.ts +++ b/src/main/providers/filesystem-provider-contract.ts @@ -1,12 +1,14 @@ -import type { PathExistenceResult } from '../../shared/path-existence-batch' -import type { SearchOptions, SearchResult } from '../../shared/code-search-types' +import type { PathExistenceResult } from '../../shared/file-access/path-existence-batch' +import type { SearchOptions, SearchResult } from '../../shared/file-search/code-search-types' import type { DocPreviewFileAccessRequest, DocPreviewFileAccessResult, DocPreviewFileChunk, DocPreviewFileTarget -} from '../../shared/doc-preview-file-access' -import type { DirEntry, FsChangeEvent, MarkdownDocument } from '../../shared/filesystem-entry-types' +} from '../../shared/document-preview/doc-preview-file-access' +import type { DirEntry } from '../../shared/file-listing/directory-entry' +import type { FsChangeEvent } from '../../shared/file-watch/filesystem-change-event' +import type { MarkdownDocument } from '../../shared/file-listing/file-document' import type { WorkspaceSpaceDirectoryScanResult } from '../../shared/workspace-disk-space/workspace-space-types' export type FileStat = { diff --git a/src/main/providers/local-filesystem-provider.ts b/src/main/providers/local-filesystem-provider.ts index 10402f1a7ce..6847fcf5085 100644 --- a/src/main/providers/local-filesystem-provider.ts +++ b/src/main/providers/local-filesystem-provider.ts @@ -4,7 +4,7 @@ import { throwIfSignalAborted, waitForPromiseWithSignal } from '../../shared/abo import { readAuthorizedDocPreviewFile, readAuthorizedDocPreviewFileChunk -} from '../../shared/doc-preview-file-access' +} from '../../shared/document-preview/doc-preview-file-access' import { renameLocalPathSerializedByDestination } from '../filesystem/destination-serialized-local-rename' import type { resolveAuthorizedPath as ResolveAuthorizedPath } from '../ipc/filesystem/access/filesystem-auth' import { isENOENT } from '../ipc/filesystem/access/filesystem-path-containment' @@ -22,7 +22,7 @@ import type { IFilesystemProvider } from './filesystem-provider-contract' import type { FileWriteDiskPrecondition, FileWriteResult -} from '../../shared/file-write-disk-precondition' +} from '../../shared/file-write/file-write-disk-precondition' import { writeLocalTextFileWithDiskPrecondition } from '../ipc/filesystem/local-disk-write-precondition' import { windowsFsPath } from '../wsl/filesystem/wsl-unc-drive-fs-path' diff --git a/src/main/repository-icons/repo-icon-file-detection.ts b/src/main/repository-icons/repo-icon-file-detection.ts index 2dbadbb9efe..1a60db840f2 100644 --- a/src/main/repository-icons/repo-icon-file-detection.ts +++ b/src/main/repository-icons/repo-icon-file-detection.ts @@ -1,5 +1,5 @@ import { readFile, stat } from 'node:fs/promises' -import { buildImageDataUri } from '../../shared/image-data-uri' +import { buildImageDataUri } from '../../shared/file-preview/image-data-uri' import { MAX_REPO_ICON_UPLOAD_BYTES, type RepoIcon } from '../../shared/repo-icon' import type { ExecutionHostFilesystemRoute } from '../providers/execution-host-provider-dispatch' import { detectImageFileSignature } from '../media/image-file-signature' diff --git a/src/main/ripgrep/bundled-ripgrep-path.ts b/src/main/ripgrep/bundled-ripgrep-path.ts index 17ece377aab..4525f739737 100644 --- a/src/main/ripgrep/bundled-ripgrep-path.ts +++ b/src/main/ripgrep/bundled-ripgrep-path.ts @@ -9,7 +9,7 @@ import { bundledRipgrepBinaryName, toBundledRipgrepPlatform, type BundledRipgrepPlatform -} from '../../shared/bundled-ripgrep' +} from '../../shared/ripgrep/bundled-ripgrep' /** Only unpackaged dev/test hosts may fall back to this; see bundledRipgrepCommand. */ const PATH_RIPGREP_COMMAND = 'rg' diff --git a/src/main/ripgrep/bundled-ripgrep-real.test.ts b/src/main/ripgrep/bundled-ripgrep-real.test.ts index b24f5ff5588..8b08f9ad6fa 100644 --- a/src/main/ripgrep/bundled-ripgrep-real.test.ts +++ b/src/main/ripgrep/bundled-ripgrep-real.test.ts @@ -3,7 +3,7 @@ import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { getAppEnvironment, setAppEnvironment } from '../../shared/app-environment' -import { bundledRipgrepBinaryName } from '../../shared/bundled-ripgrep' +import { bundledRipgrepBinaryName } from '../../shared/ripgrep/bundled-ripgrep' import { bundledRipgrepCommand, resetBundledRipgrepPathCacheForTests } from './bundled-ripgrep-path' import { spawnBundledRipgrep } from './bundled-ripgrep-spawn' diff --git a/src/main/ripgrep/bundled-ripgrep-spawn.ts b/src/main/ripgrep/bundled-ripgrep-spawn.ts index de2d3aaa992..a3e069dabeb 100644 --- a/src/main/ripgrep/bundled-ripgrep-spawn.ts +++ b/src/main/ripgrep/bundled-ripgrep-spawn.ts @@ -1,6 +1,6 @@ import { wslAwareSpawn } from '../git/runner' import { bundledRipgrepCommand, bundledRipgrepWslSpawnOptions } from './bundled-ripgrep-path' -import { RIPGREP_MISSING_CWD_EXIT_CODE } from '../../shared/ripgrep-process-availability' +import { RIPGREP_MISSING_CWD_EXIT_CODE } from '../../shared/ripgrep/ripgrep-process-availability' type WslAwareSpawnOptions = Parameters[2] diff --git a/src/main/ripgrep/bundled-ripgrep-stop.ts b/src/main/ripgrep/bundled-ripgrep-stop.ts index f3cdb6df963..1f1166c7d74 100644 --- a/src/main/ripgrep/bundled-ripgrep-stop.ts +++ b/src/main/ripgrep/bundled-ripgrep-stop.ts @@ -1,5 +1,5 @@ import { signalProcessTree } from '@orca/process-host/process-tree-termination' -import { killSpawnedRipgrepProcess } from '../../shared/ripgrep-process-availability' +import { killSpawnedRipgrepProcess } from '../../shared/ripgrep/ripgrep-process-availability' import type { ChildProcessHandle } from '@orca/process-host/process-spec' const stoppingChildren = new WeakSet() diff --git a/src/main/ripgrep/bundled-ripgrep-text-search.ts b/src/main/ripgrep/bundled-ripgrep-text-search.ts index c2560be6845..b4cd60b9809 100644 --- a/src/main/ripgrep/bundled-ripgrep-text-search.ts +++ b/src/main/ripgrep/bundled-ripgrep-text-search.ts @@ -1,6 +1,6 @@ import type { ChildProcessHandle } from '@orca/process-host/process-spec' -import type { SearchOptions, SearchResult } from '../../shared/code-search-types' -import { RipgrepSearchDiagnostics } from '../../shared/ripgrep-search-diagnostics' +import type { SearchOptions, SearchResult } from '../../shared/file-search/code-search-types' +import { RipgrepSearchDiagnostics } from '../../shared/ripgrep/ripgrep-search-diagnostics' import { SearchSubprocessLineAccumulator } from '../../shared/search-subprocess-lines' import { throwIfSignalAborted, abortSignalReason } from '../../shared/abort-signal-reason' import { @@ -10,7 +10,7 @@ import { finalize, ingestRgJsonLine, SEARCH_TIMEOUT_MS -} from '../../shared/text-search' +} from '../../shared/file-search/text-search' import { absorbPendingRipgrepSpawnError, classifySynchronousRipgrepSpawnFailure, @@ -19,7 +19,7 @@ import { isRipgrepUnavailableExit, isTransientRipgrepSpawnError, ripgrepMissingCwdError -} from '../../shared/ripgrep-process-availability' +} from '../../shared/ripgrep/ripgrep-process-availability' import { toWindowsWslPath } from '../../shared/wsl-paths' import { bundledRipgrepUnavailableError } from './bundled-ripgrep-path' import { spawnBundledRipgrep } from './bundled-ripgrep-spawn' diff --git a/src/main/ripgrep/ripgrep-filename-identity-real.test.ts b/src/main/ripgrep/ripgrep-filename-identity-real.test.ts deleted file mode 100644 index 51a549a6b43..00000000000 --- a/src/main/ripgrep/ripgrep-filename-identity-real.test.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' -import { spawnBundledRipgrep } from './bundled-ripgrep-spawn' -import { buildRgArgsForQuickOpen, normalizeQuickOpenRgLine } from '../../shared/quick-open-filter' -import { buildRgArgs, createAccumulator, ingestRgJsonLine } from '../../shared/text-search' -import { joinWorktreeRelativePath } from '../runtime/files/paths/runtime-relative-paths' - -async function capture(root: string, args: string[]): Promise { - const child = spawnBundledRipgrep(args, { cwd: root, stdio: ['ignore', 'pipe', 'pipe'] }) - let output = '' - child.stdout?.setEncoding('utf8').on('data', (chunk: string) => { - output += chunk - }) - child.stderr?.resume() - await new Promise((resolve, reject) => { - child.once('error', reject) - child.once('close', (code) => (code === 0 ? resolve() : reject(new Error(`rg exit ${code}`)))) - }) - return output -} - -describe.skipIf(process.platform === 'win32')('real ripgrep POSIX filename identities', () => { - it('lists, searches, and opens literal-backslash and nested names independently', async () => { - const parent = await mkdtemp(join(tmpdir(), 'orca-rg-identity-')) - const root = join(parent, 'repo\\root') - try { - await mkdir(join(root, 'a'), { recursive: true }) - await writeFile(join(root, 'a\\b.txt'), 'needle literal') - await writeFile(join(root, 'a/b.txt'), 'needle nested') - const args = buildRgArgsForQuickOpen({ - searchRoot: '.', - excludePathPrefixes: [], - forceSlashSeparator: false - }) - const listing = await capture(root, args.primary) - const names = listing - .split('\0') - .filter(Boolean) - .map((line) => normalizeQuickOpenRgLine(line, { kind: 'cwd-relative' })) - expect(names.sort()).toEqual(['a/b.txt', 'a\\b.txt'].sort()) - for (const name of names) { - expect(name).not.toBeNull() - if (name === null) { - throw new Error('invalid name') - } - expect(await readFile(joinWorktreeRelativePath(root, name), 'utf8')).toBe( - name === 'a\\b.txt' ? 'needle literal' : 'needle nested' - ) - } - const acc = createAccumulator() - for (const line of (await capture(root, buildRgArgs('needle', '.', {}))).split('\n')) { - ingestRgJsonLine(line, root, acc, 10) - } - expect([...acc.fileMap.values()].map((file) => file.relativePath).sort()).toEqual(names) - expect(acc.truncated).toBe(false) - } finally { - await rm(parent, { recursive: true, force: true }) - } - }) -}) diff --git a/src/main/ripgrep/synchronous-spawn-failure.test.ts b/src/main/ripgrep/synchronous-spawn-failure.test.ts index 291d1a3a7d9..f69606ec97d 100644 --- a/src/main/ripgrep/synchronous-spawn-failure.test.ts +++ b/src/main/ripgrep/synchronous-spawn-failure.test.ts @@ -3,7 +3,7 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' -import { classifySynchronousRipgrepSpawnFailure } from '../../shared/ripgrep-process-availability' +import { classifySynchronousRipgrepSpawnFailure } from '../../shared/ripgrep/ripgrep-process-availability' const dirs: string[] = [] diff --git a/src/main/ripgrep/text-search-unicode-real.test.ts b/src/main/ripgrep/text-search-unicode-real.test.ts deleted file mode 100644 index b2cc22c1aeb..00000000000 --- a/src/main/ripgrep/text-search-unicode-real.test.ts +++ /dev/null @@ -1,134 +0,0 @@ -import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { spawnBundledRipgrep } from './bundled-ripgrep-spawn' -import { - buildRgArgs, - createAccumulator, - finalize, - ingestRgJsonLine -} from '../../shared/text-search' - -describe('ripgrep Unicode match coordinates', () => { - let root: string - beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-rg-unicode-')) - }) - afterEach(async () => { - vi.unstubAllEnvs() - await rm(root, { recursive: true, force: true }) - }) - - async function search( - query: string, - useRegex = false, - includePattern?: string, - excludePattern?: string - ) { - const child = spawnBundledRipgrep( - buildRgArgs(query, '.', { useRegex, includePattern, excludePattern }), - { - cwd: root, - stdio: ['ignore', 'pipe', 'pipe'] - } - ) - let output = '' - child.stdout?.setEncoding('utf8').on('data', (chunk: string) => { - output += chunk - }) - child.stderr?.resume() - await new Promise((resolve, reject) => { - child.once('error', reject) - child.once('close', (code) => - code === 0 || code === 1 ? resolve() : reject(new Error(`rg exit ${code}`)) - ) - }) - const acc = createAccumulator() - for (const line of output.split('\n')) { - ingestRgJsonLine(line, root, acc, 2000) - } - return finalize(acc) - } - - it('uses UTF16 columns and lengths for multibyte prefixes and astral matches', async () => { - await writeFile(join(root, 'example.txt'), '😀 café 日本 needle 😀 needle\r\n') - const result = await search('needle|😀', true) - expect( - result.files[0]?.matches.map(({ column, matchLength }) => [column, matchLength]) - ).toEqual([ - [1, 2], - [12, 6], - [19, 2], - [22, 6] - ]) - }) - - it.each(['src/**', '/src/**'])('honors root-relative include glob %s', async (includePattern) => { - await mkdir(join(root, 'src')) - await mkdir(join(root, 'other')) - await writeFile(join(root, 'src', 'match.txt'), 'needle') - await writeFile(join(root, 'src', 'skip.txt'), 'needle') - await writeFile(join(root, 'other', 'match.txt'), 'needle') - const result = await search('needle', false, includePattern, '/src/skip.txt') - expect(result.files.map((file) => [file.filePath, file.relativePath])).toEqual([ - [join(root, 'src', 'match.txt'), 'src/match.txt'] - ]) - }) - - it('keeps navigation and clamped display coordinates aligned', async () => { - const prefix = '日本😀'.repeat(200) - await writeFile(join(root, 'long.txt'), `${prefix}needle`) - const match = (await search('needle')).files[0]?.matches[0] - expect(match?.column).toBe(prefix.length + 1) - expect( - match?.lineContent.slice( - (match.displayColumn ?? 1) - 1, - (match.displayColumn ?? 1) - 1 + match.matchLength - ) - ).toBe('needle') - }) - - it('decodes malformed UTF8 context and maps matches using the original bytes', async () => { - const bytes = Buffer.concat([ - Buffer.from('😀 '), - Buffer.from([0xe2, 0x82, 0xff]), - Buffer.from(' needle é needle\r\n') - ]) - await writeFile(join(root, 'malformed.txt'), bytes) - const content = bytes.toString('utf8').replace(/\n$/, '') - const result = await search('needle') - expect(result.totalMatches).toBe(2) - expect( - result.files[0]?.matches.map((match) => [match.column, match.matchLength, match.lineContent]) - ).toEqual([ - [content.indexOf('needle') + 1, 6, content], - [content.lastIndexOf('needle') + 1, 6, content] - ]) - expect(result.truncated).toBe(false) - }) - - it('keeps clipped emoji context intact around a real match', async () => { - const prefix = '😀'.repeat(300) - await writeFile(join(root, 'emoji.txt'), `${prefix}x${prefix}\n`) - const match = (await search('x')).files[0]?.matches[0] - expect(match?.column).toBe(601) - expect(match?.matchLength).toBe(1) - expect(match?.lineContent.isWellFormed()).toBe(true) - expect(match?.lineContent.length).toBeLessThanOrEqual(502) - expect(match?.lineContent.slice((match.displayColumn ?? 1) - 1, match.displayColumn)).toBe('x') - }) - - it('ignores external rg config while retaining workspace ignore files', async () => { - const config = join(root, 'config') - await writeFile(config, '--invert-match\n') - vi.stubEnv('RIPGREP_CONFIG_PATH', config) - await writeFile(join(root, '.ignore'), 'ignored.txt\n') - await writeFile(join(root, 'ignored.txt'), 'needle\n') - await mkdir(join(root, 'docs')) - await writeFile(join(root, 'docs', 'visible.txt'), 'needle\nother\n') - const result = await search('needle') - expect(result.files.map((file) => file.relativePath)).toEqual(['docs/visible.txt']) - expect(result.files[0]?.matches[0]?.lineContent).toBe('needle') - }) -}) diff --git a/src/main/runtime/agent-session/records/agent-session-recovery-capsule.ts b/src/main/runtime/agent-session/records/agent-session-recovery-capsule.ts index ad565f79c77..19d5b2f31a5 100644 --- a/src/main/runtime/agent-session/records/agent-session-recovery-capsule.ts +++ b/src/main/runtime/agent-session/records/agent-session-recovery-capsule.ts @@ -1,8 +1,8 @@ import { rm } from 'node:fs/promises' import { join } from 'node:path' import type { AgentSessionResumeMarker } from '../../../../shared/agent-session/lifecycle/agent-session-resume-marker' -import { readNodeFileWithinLimit } from '../../../../shared/node-bounded-file-reader' -import { stringifyJsonWithinByteLimit } from '../../../../shared/node-bounded-json-stringify' +import { readNodeFileWithinLimit } from '../../../../shared/file-content/node-bounded-file-reader' +import { stringifyJsonWithinByteLimit } from '../../../../shared/json-stream/node-bounded-json-stringify' import { durableWriteTempPath, removeStaleDurableWriteTempFiles, diff --git a/src/main/runtime/agent-session/records/agent-session-runtime-end-record.ts b/src/main/runtime/agent-session/records/agent-session-runtime-end-record.ts index f1f993a98fd..302ccb2ec69 100644 --- a/src/main/runtime/agent-session/records/agent-session-runtime-end-record.ts +++ b/src/main/runtime/agent-session/records/agent-session-runtime-end-record.ts @@ -4,7 +4,7 @@ import { mkdirSync, readdirSync, rmSync, statSync } from 'node:fs' import { join } from 'node:path' import { durableWriteTempPath, writeFileDurableSync } from '../../../filesystem/durable-file-write' -import { readNodeFileSyncWithinLimit } from '../../../../shared/node-bounded-file-reader' +import { readNodeFileSyncWithinLimit } from '../../../../shared/file-content/node-bounded-file-reader' import type { AgentSessionOrcaStopCause } from '../../../../shared/agent-session/lifecycle/agent-session-orca-stop' import { AGENT_SESSION_RESUME_TRIGGERS, diff --git a/src/main/runtime/artifacts/runtime-artifact-controller.ts b/src/main/runtime/artifacts/runtime-artifact-controller.ts index 9e525e1a01a..3c9ddadd68c 100644 --- a/src/main/runtime/artifacts/runtime-artifact-controller.ts +++ b/src/main/runtime/artifacts/runtime-artifact-controller.ts @@ -7,7 +7,7 @@ import type { ArtifactPublishedLink, ArtifactPublishResult, ArtifactWriteRequest -} from '../../../shared/artifacts' +} from '../../../shared/artifacts/artifacts' import { SharingUnavailableOnHostError } from '../../../shared/sharing-unavailable-on-host' import type { ArtifactCloudService } from '../../artifacts/artifact-cloud-service' diff --git a/src/main/runtime/artifacts/runtime-artifact-operations.ts b/src/main/runtime/artifacts/runtime-artifact-operations.ts index b01492234cb..b989e1db153 100644 --- a/src/main/runtime/artifacts/runtime-artifact-operations.ts +++ b/src/main/runtime/artifacts/runtime-artifact-operations.ts @@ -8,7 +8,7 @@ import type { ArtifactPublishResult, ArtifactPublishedLink, ArtifactWriteRequest -} from '../../../shared/artifacts' +} from '../../../shared/artifacts/artifacts' import { LegacyWorkerTerminalSurface } from '../orchestration/terminal-authority/legacy-worker-terminal-surface' export abstract class RuntimeArtifactOperations extends LegacyWorkerTerminalSurface { diff --git a/src/main/runtime/client/events/runtime-notifier-contract.ts b/src/main/runtime/client/events/runtime-notifier-contract.ts index ec4b28ac0f9..910e00ed84a 100644 --- a/src/main/runtime/client/events/runtime-notifier-contract.ts +++ b/src/main/runtime/client/events/runtime-notifier-contract.ts @@ -1,7 +1,7 @@ import type { RuntimeEditorTabReveal, RuntimeFileOpenPosition -} from '../../../../shared/runtime-file-contracts' +} from '../../../../shared/file-access/runtime-editor-file-open' import type { ClaudeAccountSelectionChange } from '../../../../shared/managed-account-types' import type { AgentLaunchPaneVerdictEvent } from '../../../../shared/agent-launch/contracts/agent-launch-pane-verdict' import type { SleepingAgentLaunchConfig } from '../../../../shared/agent-session/lifecycle/agent-session-resume' diff --git a/src/main/runtime/client/settings/runtime-client-settings.ts b/src/main/runtime/client/settings/runtime-client-settings.ts index ac94abe6787..e4c3907b72e 100644 --- a/src/main/runtime/client/settings/runtime-client-settings.ts +++ b/src/main/runtime/client/settings/runtime-client-settings.ts @@ -1,7 +1,7 @@ import { publishedLegacyChatPermissionMode } from '../../../../shared/agent-launch/permissions/agent-chat-permission-mode' import { getClaudeAgentViewService } from '../../../claude/agent-view/agent-view-service' import { getAppEnvironment } from '../../../../shared/app-environment' -import { isArtifactSharingEnabled } from '../../../../shared/artifact-sharing-gate' +import { isArtifactSharingEnabled } from '../../../../shared/artifacts/artifact-sharing-gate' import { isAgentSkillSharingEnabled } from '../../../../shared/agent-skill-sharing-gate' import { applyPRBotAuthorOverride } from '../../../../shared/source-control/review-comments/pr-bot-author-overrides' import { TASK_PROVIDERS } from '../../../../shared/task-providers' diff --git a/src/main/runtime/files/editor-open-through-layout-owner.ts b/src/main/runtime/files/editor-open-through-layout-owner.ts index 16c0b672c2c..4f85b522746 100644 --- a/src/main/runtime/files/editor-open-through-layout-owner.ts +++ b/src/main/runtime/files/editor-open-through-layout-owner.ts @@ -6,7 +6,7 @@ import type { LayoutApplyReply } from '../../../shared/workspace-layout/workspac import type { RuntimeEditorFileOpen, RuntimeEditorTabReveal -} from '../../../shared/runtime-file-contracts' +} from '../../../shared/file-access/runtime-editor-file-open' import type { WindowLayoutCommand } from '../terminal/layout/runtime-layout-apply' import type { RuntimeNotifier } from '../client/events/runtime-notifier-contract' import type { RuntimeFileCommandHost } from './file-command-host' diff --git a/src/main/runtime/files/file-access.ts b/src/main/runtime/files/file-access.ts index 73821e677d2..1ec963b2319 100644 --- a/src/main/runtime/files/file-access.ts +++ b/src/main/runtime/files/file-access.ts @@ -1,13 +1,13 @@ import type { RuntimeFileOpenPosition, RuntimeFileOpenResult -} from '../../../shared/runtime-file-contracts' +} from '../../../shared/file-access/runtime-editor-file-open' import { listFilesystemMarkdownDocuments } from '../../providers/filesystem-markdown-listing' -import type { MarkdownDocument } from '../../../shared/filesystem-entry-types' +import type { MarkdownDocument } from '../../../shared/file-listing/file-document' import { validatePathExistenceBatch, type PathExistenceResult -} from '../../../shared/path-existence-batch' +} from '../../../shared/file-access/path-existence-batch' import { readRuntimeFilePathExistence } from './file-path-existence' import { isMobileBinaryPath, diff --git a/src/main/runtime/files/file-command-host.ts b/src/main/runtime/files/file-command-host.ts index e7bd12e0452..9fe85b417a3 100644 --- a/src/main/runtime/files/file-command-host.ts +++ b/src/main/runtime/files/file-command-host.ts @@ -2,7 +2,7 @@ import type { RuntimeStore } from '../construction/runtime-store-contract' import type { ResolvedRuntimeFileTarget, ResolvedRuntimeFileWorktree } from './file-target' import type { ExecutionHostId } from '../../../shared/execution-host' import type { RuntimeNavigationTarget } from '../../../shared/runtime-navigation' -import type { RuntimeFileOpenPosition } from '../../../shared/runtime-file-contracts' +import type { RuntimeFileOpenPosition } from '../../../shared/file-access/runtime-editor-file-open' import type { NativeChatMediaPathRequest, NativeChatMediaPathResolution diff --git a/src/main/runtime/files/file-mutations.ts b/src/main/runtime/files/file-mutations.ts index 64b19cf8a55..0037ca70fb3 100644 --- a/src/main/runtime/files/file-mutations.ts +++ b/src/main/runtime/files/file-mutations.ts @@ -11,12 +11,12 @@ import type { RuntimeFileCommandHost } from './file-command-host' import { resolveRuntimeAuthorizedPath } from './chat-scratch-file-root' import { constants, copyFile, mkdir, rm } from 'node:fs/promises' import { dirname } from 'node:path' -import type { FileBytesWritePrecondition } from '../../../shared/file-bytes-write' +import type { FileBytesWritePrecondition } from '../../../shared/file-write/file-bytes-write' import { replaceLocalFileBytesIfUnchanged } from '../../ipc/filesystem/local-disk-bytes-replace' import type { FileWriteDiskPrecondition, FileWriteResult -} from '../../../shared/file-write-disk-precondition' +} from '../../../shared/file-write/file-write-disk-precondition' type RuntimeFileMutationHost = Pick< RuntimeFileCommandHost, diff --git a/src/main/runtime/files/file-path-existence.ts b/src/main/runtime/files/file-path-existence.ts index 88a029a423c..349e8c6758c 100644 --- a/src/main/runtime/files/file-path-existence.ts +++ b/src/main/runtime/files/file-path-existence.ts @@ -1,7 +1,7 @@ import { capturePathExistence, type PathExistenceResult -} from '../../../shared/path-existence-batch' +} from '../../../shared/file-access/path-existence-batch' import { isPathAbsentError } from '../../ipc/filesystem/access/filesystem-path-containment' import { requireRuntimeFileProvider, diff --git a/src/main/runtime/files/file-preview-budget.ts b/src/main/runtime/files/file-preview-budget.ts index 8c8f80f2c4e..f58c3535334 100644 --- a/src/main/runtime/files/file-preview-budget.ts +++ b/src/main/runtime/files/file-preview-budget.ts @@ -1,5 +1,5 @@ -import { IMAGE_AND_PDF_PREVIEW_MIME_TYPES } from '../../../shared/file-preview-kind' -import type { RuntimeFilePreviewResult } from '../../../shared/runtime-file-contracts' +import { IMAGE_AND_PDF_PREVIEW_MIME_TYPES } from '../../../shared/file-preview/file-preview-kind' +import type { RuntimeFilePreviewResult } from '../../../shared/file-content/runtime-file-read' import { REMOTE_RPC_MAX_CONTENT_BYTES, remoteRpcResultExceedsContentBudget diff --git a/src/main/runtime/files/file-reads.ts b/src/main/runtime/files/file-reads.ts index fe6f072722e..f84056c724b 100644 --- a/src/main/runtime/files/file-reads.ts +++ b/src/main/runtime/files/file-reads.ts @@ -6,7 +6,7 @@ import type { RuntimeFileReadResult, RuntimeFilePreviewResult, RuntimeFileReadChunkResult -} from '../../../shared/runtime-file-contracts' +} from '../../../shared/file-content/runtime-file-read' import { isMobileBinaryPath, isSafeMobileRelativePath } from './mobile-file-kind' import { joinWorktreeRelativePath } from './paths/runtime-relative-paths' import { truncateMobileFilePreview } from '../terminal/artifacts/artifact-integrity' @@ -27,19 +27,19 @@ import { readLocalFileRange } from '../../ipc/filesystem/local-file-range-read' import { windowsFsPath } from '../../wsl/filesystem/wsl-unc-drive-fs-path' import { guardWslUncPathAccess } from '../../wsl/filesystem/wsl-unc-access-gate' import { resolveLocalFileRequestPath } from '../../ipc/filesystem/access/local-file-access-resolution' -import type { LocalFileAccess } from '../../../shared/local-file-access' -import { filePreviewForPath } from '../../../shared/file-preview-kind' +import type { LocalFileAccess } from '../../../shared/file-access/local-file-access' +import { filePreviewForPath } from '../../../shared/file-preview/file-preview-kind' import { resolveRuntimeAuthorizedPath } from './chat-scratch-file-root' import { NodeFileReadTooLargeError, readNodeFileWithinLimit -} from '../../../shared/node-bounded-file-reader' -import { isBinaryBuffer } from '../../../shared/binary-buffer' +} from '../../../shared/file-content/node-bounded-file-reader' +import { isBinaryBuffer } from '../../../shared/file-preview/binary-buffer' import type { DocPreviewFileAccessResult, DocPreviewFileChunk, DocPreviewFileTarget -} from '../../../shared/doc-preview-file-access' +} from '../../../shared/document-preview/doc-preview-file-access' import type { LocalFilesystemProvider } from '../../providers/local-filesystem-provider' const CHAT_IMAGE_ACCESS: LocalFileAccess = { kind: 'chat-image' } diff --git a/src/main/runtime/files/paths/markdown-tab-disk-documents.ts b/src/main/runtime/files/paths/markdown-tab-disk-documents.ts index f3ae5135c38..cd89726ca40 100644 --- a/src/main/runtime/files/paths/markdown-tab-disk-documents.ts +++ b/src/main/runtime/files/paths/markdown-tab-disk-documents.ts @@ -13,8 +13,8 @@ import type { RuntimeMobileSessionMarkdownTab } from '../../../../shared/runtime import type { FileWriteDiskPrecondition, FileWriteResult -} from '../../../../shared/file-write-disk-precondition' -import { getDiskBaselineSignature } from '../../../../shared/disk-baseline-signature' +} from '../../../../shared/file-write/file-write-disk-precondition' +import { getDiskBaselineSignature } from '../../../../shared/file-write/disk-baseline-signature' import type { PersistedOpenFile, WorkspaceSessionState diff --git a/src/main/runtime/files/paths/markdown-tab-disk-host.ts b/src/main/runtime/files/paths/markdown-tab-disk-host.ts index c2bcb413c93..b281ea08361 100644 --- a/src/main/runtime/files/paths/markdown-tab-disk-host.ts +++ b/src/main/runtime/files/paths/markdown-tab-disk-host.ts @@ -1,6 +1,6 @@ /** Local workspaces use local disk; runtime environments use their server's file RPCs/compare-write. * Raw SSH routes remain unsupported instead of falling back to client paths. */ -import { isBinaryBuffer } from '../../../../shared/binary-buffer' +import { isBinaryBuffer } from '../../../../shared/file-preview/binary-buffer' import { parseExecutionHostId } from '../../../../shared/execution-host' import { compareDiskWritePrecondition, @@ -13,10 +13,10 @@ import { type FileWriteDiskComparison, type FileWriteDiskPrecondition, type FileWriteResult -} from '../../../../shared/file-write-disk-precondition' +} from '../../../../shared/file-write/file-write-disk-precondition' import { utf8ByteLength } from '../../../../shared/mobile-markdown-document' import { RemoteRuntimeClientError } from '../../../../shared/remote-runtime/remote-runtime-client-error' -import { assertFileMutationOwnershipCapability } from '../../../../shared/file-mutation-ownership' +import { assertFileMutationOwnershipCapability } from '../../../../shared/file-write/file-mutation-ownership' import type { PersistedOpenFile } from '../../../../shared/workspace-session/workspace-session-state-types' import { readLocalRuntimeFilePrefix } from '../file-reads' import { diff --git a/src/main/runtime/files/paths/ripgrep-filename-identity.test.ts b/src/main/runtime/files/paths/ripgrep-filename-identity.test.ts index 34e5913cbeb..120322ec3cd 100644 --- a/src/main/runtime/files/paths/ripgrep-filename-identity.test.ts +++ b/src/main/runtime/files/paths/ripgrep-filename-identity.test.ts @@ -3,7 +3,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it } from 'vitest' import { joinWorktreeRelativePath, normalizeRuntimeRelativePath } from './runtime-relative-paths' -import { normalizeQuickOpenRgLine } from '../../../../shared/quick-open-filter' +import { normalizeQuickOpenRgLine } from '../../../../shared/quick-open/quick-open-filter' describe.skipIf(process.platform === 'win32')('real POSIX filename collision', () => { it('opens both literal-backslash and nested files without changing identity', async () => { diff --git a/src/main/runtime/files/search/file-search.ts b/src/main/runtime/files/search/file-search.ts index a077dd3846a..4294f9a478a 100644 --- a/src/main/runtime/files/search/file-search.ts +++ b/src/main/runtime/files/search/file-search.ts @@ -2,9 +2,9 @@ import { QUICK_OPEN_SEARCH_VERSION, QuickOpenPathRanker, isQuickOpenQueryTooLarge -} from '../../../../shared/quick-open-path-search' -import type { RuntimeFileListResult } from '../../../../shared/runtime-file-contracts' -import type { SearchOptions, SearchResult } from '../../../../shared/code-search-types' +} from '../../../../shared/quick-open/quick-open-path-search' +import type { RuntimeFileListResult } from '../../../../shared/file-listing/runtime-file-list' +import type { SearchOptions, SearchResult } from '../../../../shared/file-search/code-search-types' import { throwIfSignalAborted, waitForPromiseWithSignal diff --git a/src/main/runtime/files/search/orca-runtime-files-search.test.ts b/src/main/runtime/files/search/orca-runtime-files-search.test.ts deleted file mode 100644 index f2bf7cd6df0..00000000000 --- a/src/main/runtime/files/search/orca-runtime-files-search.test.ts +++ /dev/null @@ -1,181 +0,0 @@ -import { RuntimeFileSearch } from './file-search' -import { describe, expect, it, vi } from 'vitest' -import { EventEmitter } from 'node:events' -import { - bundledRipgrepCommandMock, - resolveAuthorizedPathMock, - wslAwareSpawnMock -} from '../runtime-file-command-mock-registry' -import { - createRuntimeFileHost, - useRuntimeFileHostLifecycle -} from '../runtime-file-host.test-fixture' -import { SEARCH_TIMEOUT_MS } from '../../../../shared/text-search' - -vi.mock('fs', async () => (await import('../runtime-file-command-mock-registry')).fsModuleMock()) -vi.mock('fs/promises', async () => - (await import('../runtime-file-command-mock-registry')).fsPromisesModuleMock() -) -vi.mock( - '../watch/file-watcher-host', - async () => (await import('../runtime-file-command-mock-registry')).fileWatcherHostMock -) -vi.mock('../../../ipc/filesystem/access/filesystem-auth', async () => - (await import('../runtime-file-command-mock-registry')).filesystemAuthModuleMock() -) -vi.mock('../../../git/runner', async () => - (await import('../runtime-file-command-mock-registry')).gitRunnerModuleMock() -) -vi.mock( - '../../../ipc/local-worktree-runtime-options', - async () => - (await import('../runtime-file-command-mock-registry')).localWorktreeRuntimeOptionsMock -) -vi.mock('../../../ripgrep/bundled-ripgrep-path', async () => - (await import('../runtime-file-command-mock-registry')).bundledRipgrepPathModuleMock() -) - -type MockRuntimeSearchChild = EventEmitter & { - stdout: EventEmitter & { setEncoding: ReturnType } - stderr: EventEmitter - kill: ReturnType -} - -function createRuntimeSearchChild(): MockRuntimeSearchChild { - const child = new EventEmitter() as MockRuntimeSearchChild - child.stdout = new EventEmitter() as MockRuntimeSearchChild['stdout'] - child.stdout.setEncoding = vi.fn() - child.stderr = new EventEmitter() - child.kill = vi.fn() - return child -} - -async function flushRuntimeSearchMicrotasks(): Promise { - for (let index = 0; index < 8; index++) { - await Promise.resolve() - } -} - -describe('RuntimeFileSearch', () => { - useRuntimeFileHostLifecycle() - - it('keeps concurrent runtime clients on the same root independent during cancellation', async () => { - const { commands } = createFileSearch() - const firstChild = createRuntimeSearchChild() - const secondChild = createRuntimeSearchChild() - resolveAuthorizedPathMock.mockResolvedValue('/repo') - wslAwareSpawnMock.mockImplementation((_command, args: string[]) => - args.includes('first') ? firstChild : secondChild - ) - const controller = new AbortController() - const first = commands.searchRuntimeFiles( - 'id:wt-1', - { query: 'first' }, - { signal: controller.signal } - ) - const firstRejected = expect(first).rejects.toMatchObject({ name: 'AbortError' }) - const second = commands.searchRuntimeFiles('id:wt-1', { query: 'second' }) - await vi.waitFor(() => expect(wslAwareSpawnMock).toHaveBeenCalledTimes(2)) - expect(firstChild.kill).not.toHaveBeenCalled() - controller.abort() - await firstRejected - expect(firstChild.kill).toHaveBeenCalledOnce() - expect(secondChild.kill).not.toHaveBeenCalled() - secondChild.emit('close', 1, null) - await expect(second).resolves.toMatchObject({ totalMatches: 0, truncated: false }) - }) - - it('settles and detaches runtime rg searches when timeout kill is ignored', async () => { - const resolveRuntimeFileTarget = vi.fn(async () => ({ - worktree: { - id: 'wt-1', - repoId: 'repo-1', - path: '/repo' - }, - executionHostId: 'local' - })) - const { commands } = createFileSearch({ resolveRuntimeFileTarget }) - const child = createRuntimeSearchChild() - resolveAuthorizedPathMock.mockResolvedValue('/repo') - wslAwareSpawnMock.mockReturnValue(child) - - const resultPromise = commands.searchRuntimeFiles('id:wt-1', { - query: 'needle', - maxResults: 10 - }) - await vi.advanceTimersByTimeAsync(SEARCH_TIMEOUT_MS) - - await expect(resultPromise).resolves.toMatchObject({ - files: [], - totalMatches: 0, - truncated: true - }) - expect(child.kill).toHaveBeenCalledTimes(1) - expect(child.stdout.listenerCount('data')).toBe(0) - expect(child.stderr.listenerCount('data')).toBe(0) - expect(child.listenerCount('error')).toBe(0) - expect(child.listenerCount('close')).toBe(0) - expect(bundledRipgrepCommandMock).toHaveBeenCalledWith({ wsl: false }) - expect(wslAwareSpawnMock).toHaveBeenCalledWith( - '/bundled/rg', - expect.any(Array), - expect.objectContaining({ cwd: '/repo' }) - ) - }) - - it.each(['ignored', 'erroring'] as const)( - 'publishes capped results and detaches when termination is %s', - async (termination) => { - const { commands } = createFileSearch() - const child = createRuntimeSearchChild() - if (termination === 'erroring') { - child.kill.mockImplementation(() => { - child.emit('error', Object.assign(new Error('kill EPERM'), { code: 'EPERM' })) - return false - }) - } - resolveAuthorizedPathMock.mockResolvedValue('/repo') - wslAwareSpawnMock.mockReturnValue(child) - const resultPromise = commands.searchRuntimeFiles('id:wt-1', { - query: 'needle', - maxResults: 2 - }) - let settled = false - void resultPromise.then(() => { - settled = true - }) - await flushRuntimeSearchMicrotasks() - const record = JSON.stringify({ - type: 'match', - data: { - path: { text: './example.txt' }, - lines: { text: 'needle needle\n' }, - line_number: 1, - submatches: [ - { start: 0, end: 6 }, - { start: 7, end: 13 } - ] - } - }) - expect(() => child.stdout.emit('data', `${record}\n{"type":"match"`)).not.toThrow() - await flushRuntimeSearchMicrotasks() - - expect(settled).toBe(true) - await expect(resultPromise).resolves.toMatchObject({ - totalMatches: 2, - truncated: true, - files: [{ matches: [{ column: 1 }, { column: 8 }] }] - }) - expect(child.kill).toHaveBeenCalledOnce() - expect(child.stdout.listenerCount('data')).toBe(0) - expect(child.stderr.listenerCount('data')).toBe(0) - expect(child.listenerCount('close')).toBe(0) - expect(vi.getTimerCount()).toBe(0) - } - ) -}) - -function createFileSearch(options?: Parameters[0]) { - const { host, store } = createRuntimeFileHost(options) - return { commands: new RuntimeFileSearch(host), store } -} diff --git a/src/main/runtime/files/server-browse/runtime-server-environment-commands.ts b/src/main/runtime/files/server-browse/runtime-server-environment-commands.ts index 6a4c21cb8ad..f0b5a0ffac5 100644 --- a/src/main/runtime/files/server-browse/runtime-server-environment-commands.ts +++ b/src/main/runtime/files/server-browse/runtime-server-environment-commands.ts @@ -2,8 +2,9 @@ import { readdir, stat } from 'node:fs/promises' import { homedir } from 'node:os' import type { Dirent } from 'node:fs' import { isAbsolute, join, resolve } from 'node:path' -import type { DirEntry, FilesystemPathFlavor } from '../../../../shared/filesystem-entry-types' -import { sortDirEntries } from '../../../../shared/file-name-sort' +import type { DirEntry } from '../../../../shared/file-listing/directory-entry' +import type { FilesystemPathFlavor } from '../../../../shared/file-access/filesystem-path-flavor' +import { sortDirEntries } from '../../../../shared/file-listing/file-name-sort' import { probeGitAvailability } from '../../../git/git-availability' import { gitExecFileAsync } from '../../../git/command-runner/git-exec-file' import { isServerDriveListRequest, listWindowsDrives } from './windows-drive-listing' diff --git a/src/main/runtime/files/server-browse/windows-drive-listing.ts b/src/main/runtime/files/server-browse/windows-drive-listing.ts index 2e626d53491..fe576ecaa86 100644 --- a/src/main/runtime/files/server-browse/windows-drive-listing.ts +++ b/src/main/runtime/files/server-browse/windows-drive-listing.ts @@ -1,6 +1,6 @@ import { stat } from 'node:fs/promises' import type { Stats } from 'node:fs' -import type { FilesystemPathFlavor } from '../../../../shared/filesystem-entry-types' +import type { FilesystemPathFlavor } from '../../../../shared/file-access/filesystem-path-flavor' export type DriveListing = { resolvedPath: string diff --git a/src/main/runtime/files/staged-file-save-commands.ts b/src/main/runtime/files/staged-file-save-commands.ts index faeafb16db3..ea6013f2778 100644 --- a/src/main/runtime/files/staged-file-save-commands.ts +++ b/src/main/runtime/files/staged-file-save-commands.ts @@ -2,7 +2,7 @@ import { join } from 'node:path' import type { FileWriteDiskPrecondition, FileWriteResult -} from '../../../shared/file-write-disk-precondition' +} from '../../../shared/file-write/file-write-disk-precondition' import { getProfileUserDataPath } from '../../orca-profiles/profile-storage-paths' import { resolveRuntimeAuthorizedPath } from './chat-scratch-file-root' import type { RuntimeFileCommandHost } from './file-command-host' diff --git a/src/main/runtime/files/staged-file-saves.test.ts b/src/main/runtime/files/staged-file-saves.test.ts index b19738010ab..b30a1206f16 100644 --- a/src/main/runtime/files/staged-file-saves.test.ts +++ b/src/main/runtime/files/staged-file-saves.test.ts @@ -14,7 +14,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import type * as FsPromises from 'node:fs/promises' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { STAGED_FILE_SAVE_LIMITS } from '../../../shared/staged-file-save' +import { STAGED_FILE_SAVE_LIMITS } from '../../../shared/file-write/staged-file-save' import { StagedFileSaves } from './staged-file-saves' // An append can be held open to put other ops beside it. diff --git a/src/main/runtime/files/staged-file-saves.ts b/src/main/runtime/files/staged-file-saves.ts index c28de5ba4a5..1e2648ebcb5 100644 --- a/src/main/runtime/files/staged-file-saves.ts +++ b/src/main/runtime/files/staged-file-saves.ts @@ -10,9 +10,9 @@ import { join } from 'node:path' import type { FileWriteDiskPrecondition, FileWriteResult -} from '../../../shared/file-write-disk-precondition' -import { restrictWindowsDirectory } from '../../../shared/secure-path-windows-acl' -import { STAGED_FILE_SAVE_LIMITS } from '../../../shared/staged-file-save' +} from '../../../shared/file-write/file-write-disk-precondition' +import { restrictWindowsDirectory } from '../../../shared/secure-storage/secure-path-windows-acl' +import { STAGED_FILE_SAVE_LIMITS } from '../../../shared/file-write/staged-file-save' import { writeLocalTextFileWithDiskPrecondition } from '../../ipc/filesystem/local-disk-write-precondition' import { inspectProcessLiveness } from '../../daemon/endpoint/identity/daemon-process-inspection' import type { ProcessLivenessVerdict } from '../../daemon/endpoint/identity/daemon-incarnation-evidence-types' diff --git a/src/main/runtime/files/watch/file-watcher-host.test.ts b/src/main/runtime/files/watch/file-watcher-host.test.ts deleted file mode 100644 index d66ec523b44..00000000000 --- a/src/main/runtime/files/watch/file-watcher-host.test.ts +++ /dev/null @@ -1,289 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { FsChangeEvent } from '../../../../shared/filesystem-entry-types' -import type { - WatcherProcessCallback, - WatcherProcessHooks, - WatcherProcessSubscription -} from '../../../ipc/filesystem/watcher-process/parcel-watcher-process-subscription' -import { WatcherProcessFailure } from '../../../ipc/filesystem/watcher-process/parcel-watcher-process-failure' - -const { - forgetRuntimeWatcherProcessRootMock, - resetRuntimeWatcherProcessForTestMock, - subscribeViaRuntimeWatcherProcessMock -} = vi.hoisted(() => ({ - forgetRuntimeWatcherProcessRootMock: vi.fn(), - resetRuntimeWatcherProcessForTestMock: vi.fn(), - subscribeViaRuntimeWatcherProcessMock: vi.fn() -})) - -vi.mock('../../../ipc/filesystem/watcher-process/parcel-watcher-process', () => ({ - forgetRuntimeWatcherProcessRoot: forgetRuntimeWatcherProcessRootMock, - resetRuntimeWatcherProcessForTest: resetRuntimeWatcherProcessForTestMock, - subscribeViaRuntimeWatcherProcess: subscribeViaRuntimeWatcherProcessMock -})) - -import { - closeFileExplorerWatcherInWatcherProcess, - resetRuntimeRootWatchersForTest, - watchFileExplorerInWatcherProcess -} from './file-watcher-host' - -type InstalledWatch = { - callback: WatcherProcessCallback - hooks: WatcherProcessHooks - unsubscribe: ReturnType Promise>> -} - -function installSuccessfulWatch(): InstalledWatch { - let callback: WatcherProcessCallback | undefined - let hooks: WatcherProcessHooks | undefined - const unsubscribe = vi.fn(async () => undefined) - subscribeViaRuntimeWatcherProcessMock.mockImplementationOnce( - async ( - _rootPath: string, - nextCallback: WatcherProcessCallback, - _options: unknown, - nextHooks: WatcherProcessHooks - ): Promise => { - callback = nextCallback - hooks = nextHooks - return { unsubscribe } - } - ) - return { - get callback() { - if (!callback) { - throw new Error('watch callback not installed') - } - return callback - }, - get hooks() { - if (!hooks) { - throw new Error('watch hooks not installed') - } - return hooks - }, - unsubscribe - } -} - -describe('watchFileExplorerInWatcherProcess', () => { - beforeEach(() => { - forgetRuntimeWatcherProcessRootMock.mockReset() - resetRuntimeWatcherProcessForTestMock.mockReset() - subscribeViaRuntimeWatcherProcessMock.mockReset() - }) - - afterEach(() => { - resetRuntimeRootWatchersForTest() - vi.restoreAllMocks() - }) - - it('joins root-scoped cleanup to an in-progress subscriber teardown', async () => { - let resolveUnsubscribe: () => void = () => undefined - const unsubscribe = vi.fn( - () => - new Promise((resolve) => { - resolveUnsubscribe = resolve - }) - ) - subscribeViaRuntimeWatcherProcessMock.mockResolvedValue({ unsubscribe }) - const dispose = await watchFileExplorerInWatcherProcess('/repo', vi.fn()) - - let rootCloseSettled = false - const subscriberClose = dispose() - const rootClose = closeFileExplorerWatcherInWatcherProcess('/repo').then(() => { - rootCloseSettled = true - }) - await Promise.resolve() - expect(rootCloseSettled).toBe(false) - expect(unsubscribe).toHaveBeenCalledTimes(1) - - resolveUnsubscribe() - await Promise.all([subscriberClose, rootClose]) - expect(rootCloseSettled).toBe(true) - }) - - it.each([ - ['native watcher failure', new Error('native subscription stopped')], - [ - 'watcher process failure', - new WatcherProcessFailure('crashed repeatedly', 'supervisor', 'supervisor_crash_fuse') - ] - ])('keeps same-root subscribers alive after a %s', async (_kind, error) => { - const watch = installSuccessfulWatch() - const replacement = installSuccessfulWatch() - const firstEvents = vi.fn<(events: FsChangeEvent[]) => void>() - const secondEvents = vi.fn<(events: FsChangeEvent[]) => void>() - const firstError = vi.fn() - const secondError = vi.fn() - await watchFileExplorerInWatcherProcess('/repo', firstEvents, firstError) - await watchFileExplorerInWatcherProcess('/repo', secondEvents, secondError) - - watch.hooks.onTerminalError?.(error) - await vi.waitFor(() => expect(subscribeViaRuntimeWatcherProcessMock).toHaveBeenCalledTimes(2)) - watch.callback(null, [{ type: 'update', path: '/repo/late.txt' }]) - replacement.callback(null, [{ type: 'update', path: '/repo/recovered.txt' }]) - - expect(firstError).not.toHaveBeenCalled() - expect(secondError).not.toHaveBeenCalled() - expect(firstEvents).toHaveBeenCalledWith([{ kind: 'overflow', absolutePath: '/repo' }]) - expect(firstEvents).toHaveBeenCalledWith([ - { kind: 'update', absolutePath: '/repo/recovered.txt', isDirectory: undefined } - ]) - expect(secondEvents).toHaveBeenCalledTimes(2) - }) - - it('retains an early recovery termination failure until physical exit', async () => { - const watch = installSuccessfulWatch() - let rejectRecovery: ((error: Error) => void) | undefined - subscribeViaRuntimeWatcherProcessMock.mockImplementationOnce( - () => - new Promise((_resolve, reject) => { - rejectRecovery = reject - }) - ) - let resolvePhysicalExit: () => void = () => {} - const physicalExit = new Promise((resolve) => { - resolvePhysicalExit = resolve - }) - const teardownError = new WatcherProcessFailure( - 'file watcher process did not exit after termination deadline', - 'supervisor', - 'process_unavailable', - physicalExit - ) - const dispose = await watchFileExplorerInWatcherProcess('/repo', vi.fn()) - watch.hooks.onTerminalError?.( - new WatcherProcessFailure('crashed repeatedly', 'supervisor', 'supervisor_crash_fuse') - ) - await vi.waitFor(() => expect(rejectRecovery).toBeDefined()) - rejectRecovery?.(teardownError) - await Promise.resolve() - - await expect(dispose()).rejects.toBe(teardownError) - await expect(watchFileExplorerInWatcherProcess('/repo', vi.fn())).rejects.toBe(teardownError) - expect(subscribeViaRuntimeWatcherProcessMock).toHaveBeenCalledTimes(2) - resolvePhysicalExit() - await physicalExit - await vi.waitFor(() => - expect(forgetRuntimeWatcherProcessRootMock).toHaveBeenCalledWith('/repo') - ) - - const replacement = installSuccessfulWatch() - await expect(watchFileExplorerInWatcherProcess('/repo', vi.fn())).resolves.toEqual( - expect.any(Function) - ) - expect(replacement.unsubscribe).not.toHaveBeenCalled() - }) - - it('keeps pre-ready cancellation pending until the root can be replaced', async () => { - let physicalSignal: AbortSignal | undefined - let rejectPhysical: ((error: unknown) => void) | undefined - subscribeViaRuntimeWatcherProcessMock.mockImplementationOnce( - (_rootPath, _callback, _options, hooks: WatcherProcessHooks) => { - physicalSignal = hooks.signal - return new Promise((_resolve, reject) => { - rejectPhysical = reject - }) - } - ) - const controllers = [new AbortController(), new AbortController()] - const pending = controllers.map((controller) => - watchFileExplorerInWatcherProcess('/repo', vi.fn(), vi.fn(), controller.signal) - ) - const settled = [false, false] - pending.forEach((promise, index) => { - void promise.then( - () => { - settled[index] = true - }, - () => { - settled[index] = true - } - ) - }) - - controllers.forEach((controller) => controller.abort()) - await Promise.resolve() - - expect(physicalSignal?.aborted).toBe(true) - expect(settled).toEqual([false, false]) - - rejectPhysical?.( - new WatcherProcessFailure('physical watch aborted', 'subscription', 'subscribe_aborted') - ) - const results = await Promise.allSettled(pending) - expect(results).toEqual([ - expect.objectContaining({ - status: 'rejected', - reason: expect.objectContaining({ message: 'file watcher subscription aborted' }) - }), - expect.objectContaining({ - status: 'rejected', - reason: expect.objectContaining({ message: 'file watcher subscription aborted' }) - }) - ]) - - installSuccessfulWatch() - await expect(watchFileExplorerInWatcherProcess('/repo', vi.fn())).resolves.toEqual( - expect.any(Function) - ) - expect(subscribeViaRuntimeWatcherProcessMock).toHaveBeenCalledTimes(2) - }) - - it('keeps pending setup alive when another same-root client still owns it', async () => { - let physicalSignal: AbortSignal | undefined - let resolvePhysical: ((subscription: WatcherProcessSubscription) => void) | undefined - const unsubscribe = vi.fn(async () => undefined) - subscribeViaRuntimeWatcherProcessMock.mockImplementation( - (_rootPath, _callback, _options, hooks: WatcherProcessHooks) => { - physicalSignal = hooks.signal - return new Promise((resolve) => { - resolvePhysical = resolve - }) - } - ) - const controller = new AbortController() - const first = watchFileExplorerInWatcherProcess('/repo', vi.fn(), vi.fn(), controller.signal) - const second = watchFileExplorerInWatcherProcess('/repo', vi.fn()) - - controller.abort() - await expect(first).rejects.toThrow('aborted') - expect(physicalSignal?.aborted).toBe(false) - - resolvePhysical?.({ unsubscribe }) - await expect(second).resolves.toEqual(expect.any(Function)) - expect(subscribeViaRuntimeWatcherProcessMock).toHaveBeenCalledTimes(1) - }) - - it('retains failed initial root ownership until the exact child physically exits', async () => { - let resolvePhysicalExit: () => void = () => {} - const physicalExit = new Promise((resolve) => { - resolvePhysicalExit = resolve - }) - const teardownError = new WatcherProcessFailure( - 'initial watcher child did not exit', - 'subscription', - 'subscribe_failed', - physicalExit - ) - subscribeViaRuntimeWatcherProcessMock.mockRejectedValueOnce(teardownError) - - await expect(watchFileExplorerInWatcherProcess('/repo', vi.fn())).rejects.toBe(teardownError) - await expect(closeFileExplorerWatcherInWatcherProcess('/repo')).rejects.toBe(teardownError) - await expect(watchFileExplorerInWatcherProcess('/repo', vi.fn())).rejects.toBe(teardownError) - expect(subscribeViaRuntimeWatcherProcessMock).toHaveBeenCalledTimes(1) - expect(forgetRuntimeWatcherProcessRootMock).not.toHaveBeenCalled() - - resolvePhysicalExit() - await physicalExit - const replacement = installSuccessfulWatch() - await expect(watchFileExplorerInWatcherProcess('/repo', vi.fn())).resolves.toEqual( - expect.any(Function) - ) - expect(replacement.unsubscribe).not.toHaveBeenCalled() - await expect(closeFileExplorerWatcherInWatcherProcess('/repo')).resolves.toBeUndefined() - }) -}) diff --git a/src/main/runtime/files/watch/file-watcher-host.ts b/src/main/runtime/files/watch/file-watcher-host.ts index 93b1e7151ff..46f33eb728c 100644 --- a/src/main/runtime/files/watch/file-watcher-host.ts +++ b/src/main/runtime/files/watch/file-watcher-host.ts @@ -1,4 +1,4 @@ -import type { FsChangeEvent } from '../../../../shared/filesystem-entry-types' +import type { FsChangeEvent } from '../../../../shared/file-watch/filesystem-change-event' import { forgetRuntimeWatcherProcessRoot, resetRuntimeWatcherProcessForTest, @@ -19,7 +19,7 @@ import { closeRuntimeRootWatch } from './runtime-root-watch-teardown' import { RUNTIME_FILE_WATCH_CRAWL_TIMEOUT_MS, RUNTIME_FILE_WATCH_MAX_SETUP_ATTEMPTS -} from '../../../../shared/runtime-file-watch-limits' +} from '../../../../shared/file-watch/runtime-file-watch-limits' import { PromiseSettlementWaiters } from '../../../../shared/promise-settlement-waiters' const RUNTIME_FILE_WATCH_IGNORE_OPTIONS = buildParcelWatcherIgnoreOptions(WATCHER_IGNORE_DIRS) diff --git a/src/main/runtime/files/watch/file-watches.ts b/src/main/runtime/files/watch/file-watches.ts index 967195caec0..450e1acef00 100644 --- a/src/main/runtime/files/watch/file-watches.ts +++ b/src/main/runtime/files/watch/file-watches.ts @@ -10,8 +10,9 @@ import { } from '../file-target' import type { RuntimeFileCommandHost } from '../file-command-host' import { stat } from 'node:fs/promises' -import type { DirEntry, FsChangeEvent } from '../../../../shared/filesystem-entry-types' -import { sortDirEntries } from '../../../../shared/file-name-sort' +import type { DirEntry } from '../../../../shared/file-listing/directory-entry' +import type { FsChangeEvent } from '../../../../shared/file-watch/filesystem-change-event' +import { sortDirEntries } from '../../../../shared/file-listing/file-name-sort' import { resolveAuthorizedPath } from '../../../ipc/filesystem/access/filesystem-auth' import { resolveRuntimeAuthorizedPath } from '../chat-scratch-file-root' import { WindowsRuntimeWatchPool } from './windows-runtime-watch-pool' diff --git a/src/main/runtime/files/watch/windows-file-watch.ts b/src/main/runtime/files/watch/windows-file-watch.ts index 3f8916305e2..4c536f238f8 100644 --- a/src/main/runtime/files/watch/windows-file-watch.ts +++ b/src/main/runtime/files/watch/windows-file-watch.ts @@ -1,8 +1,8 @@ -import type { FsChangeEvent } from '../../../../shared/filesystem-entry-types' +import type { FsChangeEvent } from '../../../../shared/file-watch/filesystem-change-event' import { PhysicalExitTracker } from '../../../../shared/physical-exit-tracker' import { watch as watchFs } from 'node:fs' import { WatcherProcessFailure } from '../../../ipc/filesystem/watcher-process/parcel-watcher-process-failure' -import { watchBatchFlushDelayMs } from '../../../../shared/filesystem-watch-batch-window' +import { watchBatchFlushDelayMs } from '../../../../shared/file-watch/filesystem-watch-batch-window' import { WATCHER_IGNORE_DIRS } from '../../../ipc/filesystem/watchers/filesystem-watcher-ignore' const ignoredWatchDirectories = new Set(WATCHER_IGNORE_DIRS) diff --git a/src/main/runtime/files/watch/windows-runtime-watch-pool.ts b/src/main/runtime/files/watch/windows-runtime-watch-pool.ts index 00aaa7a3390..98bfbad43b5 100644 --- a/src/main/runtime/files/watch/windows-runtime-watch-pool.ts +++ b/src/main/runtime/files/watch/windows-runtime-watch-pool.ts @@ -1,4 +1,4 @@ -import type { FsChangeEvent } from '../../../../shared/filesystem-entry-types' +import type { FsChangeEvent } from '../../../../shared/file-watch/filesystem-change-event' import { throwIfSignalAborted, waitForPromiseWithSignal diff --git a/src/main/runtime/mobile-cloud-relay/relay-region-preference.ts b/src/main/runtime/mobile-cloud-relay/relay-region-preference.ts index 66253aaa26e..db5e0205449 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-region-preference.ts +++ b/src/main/runtime/mobile-cloud-relay/relay-region-preference.ts @@ -3,7 +3,10 @@ import { existsSync, readFileSync, rmSync, statSync } from 'node:fs' import { join } from 'node:path' import { performance } from 'node:perf_hooks' import { z } from 'zod' -import { hardenExistingSecureFile, writeSecureJsonFile } from '../../../shared/secure-file' +import { + hardenExistingSecureFile, + writeSecureJsonFile +} from '../../../shared/secure-storage/secure-file' import { fetchRelayRegionCatalog, relayDirectorHost } from './relay-region-catalog-fetch' import type { RelayRegionDecision, RelayRegionWindow } from './relay-region-correction-protocol' import { diff --git a/src/main/runtime/mobile-cloud-relay/relay-revoke-outbox.test.ts b/src/main/runtime/mobile-cloud-relay/relay-revoke-outbox.test.ts index 2ee9e515886..5784b632239 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-revoke-outbox.test.ts +++ b/src/main/runtime/mobile-cloud-relay/relay-revoke-outbox.test.ts @@ -2,12 +2,12 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import type * as SecureFileModule from '../../../shared/secure-file' +import type * as SecureFileModule from '../../../shared/secure-storage/secure-file' import { RelayRevokeOutbox } from './relay-revoke-outbox' const secureFileMocks = vi.hoisted(() => ({ failWrites: false })) -vi.mock('../../../shared/secure-file', async (importOriginal) => { +vi.mock('../../../shared/secure-storage/secure-file', async (importOriginal) => { const actual = await importOriginal() return { ...actual, diff --git a/src/main/runtime/mobile-cloud-relay/relay-revoke-outbox.ts b/src/main/runtime/mobile-cloud-relay/relay-revoke-outbox.ts index f37800c7319..fba0a05ef81 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-revoke-outbox.ts +++ b/src/main/runtime/mobile-cloud-relay/relay-revoke-outbox.ts @@ -5,7 +5,7 @@ import { hardenExistingSecureFile, isUnreadableError, writeSecureJsonFile -} from '../../../shared/secure-file' +} from '../../../shared/secure-storage/secure-file' export type RelayDeviceBinding = { relayHostId: string diff --git a/src/main/runtime/push/notifications/mobile-notification-dismissal-store.ts b/src/main/runtime/push/notifications/mobile-notification-dismissal-store.ts index 17c7c7a48fd..e6e2e69f799 100644 --- a/src/main/runtime/push/notifications/mobile-notification-dismissal-store.ts +++ b/src/main/runtime/push/notifications/mobile-notification-dismissal-store.ts @@ -1,6 +1,6 @@ import { readFileSync } from 'node:fs' import { join } from 'node:path' -import { isUnreadableError } from '../../../../shared/secure-file' +import { isUnreadableError } from '../../../../shared/secure-storage/secure-file' import { AtomicSnapshotWriter } from '../../../persistence/atomic-snapshot-writer' import type { MobileNotificationEvent } from './runtime-mobile-notification-controller' import type { ExecutionHostId } from '../../../../shared/execution-host' diff --git a/src/main/runtime/push/push-unregister-outbox.ts b/src/main/runtime/push/push-unregister-outbox.ts index 12ed19a575e..62420e9d5cf 100644 --- a/src/main/runtime/push/push-unregister-outbox.ts +++ b/src/main/runtime/push/push-unregister-outbox.ts @@ -6,7 +6,7 @@ import { hardenExistingSecureFile, isUnreadableError, writeSecureJsonFile -} from '../../../shared/secure-file' +} from '../../../shared/secure-storage/secure-file' export type PushUnregisterOutboxItem = { reqId: string diff --git a/src/main/runtime/rpc/errors.ts b/src/main/runtime/rpc/errors.ts index d69ab61e649..45ea2865039 100644 --- a/src/main/runtime/rpc/errors.ts +++ b/src/main/runtime/rpc/errors.ts @@ -21,7 +21,7 @@ import { WslHostWindowsDriveRefusalError } from '../../../shared/wsl-host-window import { wslDistroHoldRpcFailure } from '../../../shared/wsl-distro-stopped-hold' import { LINEAR_ERROR_CODES } from '../../../shared/linear/agent-access' import { AGENT_SESSION_RPC_ERROR_CODES } from '../../../shared/agent-session/agent-session-host-authority' -import { ARTIFACT_SHARING_DISABLED_CODE } from '../../../shared/artifact-sharing-gate' +import { ARTIFACT_SHARING_DISABLED_CODE } from '../../../shared/artifacts/artifact-sharing-gate' import { AGENT_SKILL_SHARING_DISABLED_CODE } from '../../../shared/agent-skill-sharing-gate' import { SHARING_UNAVAILABLE_ON_HOST_CODE } from '../../../shared/sharing-unavailable-on-host' import { diff --git a/src/main/runtime/rpc/methods/files/file-watch-event-batcher.test.ts b/src/main/runtime/rpc/methods/files/file-watch-event-batcher.test.ts index ddbdbabf766..59216690faf 100644 --- a/src/main/runtime/rpc/methods/files/file-watch-event-batcher.test.ts +++ b/src/main/runtime/rpc/methods/files/file-watch-event-batcher.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest' -import type { FsChangeEvent } from '../../../../../shared/filesystem-entry-types' -import '../../../../../shared/filesystem-watch-batch-window' +import type { FsChangeEvent } from '../../../../../shared/file-watch/filesystem-change-event' +import '../../../../../shared/file-watch/filesystem-watch-batch-window' import { createFileWatchEventBatcher } from './file-watch-event-batcher' describe('createFileWatchEventBatcher', () => { diff --git a/src/main/runtime/rpc/methods/files/file-watch-event-batcher.ts b/src/main/runtime/rpc/methods/files/file-watch-event-batcher.ts index 2a878e46ac2..6742047593f 100644 --- a/src/main/runtime/rpc/methods/files/file-watch-event-batcher.ts +++ b/src/main/runtime/rpc/methods/files/file-watch-event-batcher.ts @@ -1,6 +1,6 @@ -import { watchBatchFlushDelayMs } from '../../../../../shared/filesystem-watch-batch-window' -import type { FsChangeEvent } from '../../../../../shared/filesystem-entry-types' -import { FileWatchEventBuffer } from '../../../../../shared/filesystem-watch-event-buffer' +import { watchBatchFlushDelayMs } from '../../../../../shared/file-watch/filesystem-watch-batch-window' +import type { FsChangeEvent } from '../../../../../shared/file-watch/filesystem-change-event' +import { FileWatchEventBuffer } from '../../../../../shared/file-watch/filesystem-watch-event-buffer' import type { FileWatchBatchCadence } from '../../../../../shared/rpc-contract/files-target-params' // Older clients discard superseded reads; 100ms batches starve slow links, so preserve their trailing window unless opted in. diff --git a/src/main/runtime/rpc/methods/files/files-mutation-methods.ts b/src/main/runtime/rpc/methods/files/files-mutation-methods.ts index c50d2e16f24..05f23e5b703 100644 --- a/src/main/runtime/rpc/methods/files/files-mutation-methods.ts +++ b/src/main/runtime/rpc/methods/files/files-mutation-methods.ts @@ -1,5 +1,5 @@ import { defineMethod } from '../../core' -import { FILE_REPLACE_WITH_UPLOAD_METHOD } from '../../../../../shared/file-bytes-write' +import { FILE_REPLACE_WITH_UPLOAD_METHOD } from '../../../../../shared/file-write/file-bytes-write' import { FileCommitUpload, FileReplaceWithUpload, diff --git a/src/main/runtime/rpc/methods/files/files-read-dir-page.test.ts b/src/main/runtime/rpc/methods/files/files-read-dir-page.test.ts index d9e22354069..41b60fec247 100644 --- a/src/main/runtime/rpc/methods/files/files-read-dir-page.test.ts +++ b/src/main/runtime/rpc/methods/files/files-read-dir-page.test.ts @@ -1,10 +1,9 @@ import { describe, expect, it, vi } from 'vitest' -import { RpcDispatcher } from '../../dispatcher' -import type { OrcaRuntimeService } from '../../../orca-runtime' -import type { DirEntry } from '../../../../../shared/filesystem-entry-types' -import type { DirEntryCursor } from '../../../../../shared/file-dir-page' -import { FILE_METHODS } from './files' -import { DIR_LISTING_PAGE_CACHE_TTL_MS, DirListingPageCache } from './files-read-dir-page' + +import type { DirEntry } from '../../../../../shared/file-listing/directory-entry' +import type { DirEntryCursor } from '../../../../../shared/file-listing/file-dir-page' + +import { DirListingPageCache } from './files-read-dir-page' const fileNamed = (name: string): DirEntry => ({ name, isDirectory: false, isSymlink: false }) const folder = (count: number, prefix = 'file'): DirEntry[] => @@ -42,37 +41,6 @@ async function readAll( } describe('DirListingPageCache', () => { - it('neither skips nor repeats an entry when one is deleted between pages', async () => { - let entries = folder(6) - const cache = new DirListingPageCache(() => 0) - const list = vi.fn(async () => entries) - const read = await readAll(cache, list, 2, (pageIndex) => { - if (pageIndex === 0) { - // file-000001 was already shown; the watcher drops the listing, so page two re-lists. - entries = entries.filter((entry) => entry.name !== 'file-000001.txt') - cache.forgetWorkspace(REQUEST.worktree) - } - }) - expect(read).toEqual(names(folder(6))) - expect(list).toHaveBeenCalledTimes(2) - }) - - it('stays in order when the listing expires mid-scroll and a file arrives before the cursor', async () => { - let now = 0 - let entries = folder(6) - const cache = new DirListingPageCache(() => now) - const list = vi.fn(async () => entries) - const read = await readAll(cache, list, 2, (pageIndex) => { - if (pageIndex === 0) { - entries = [fileNamed('file-000000-a.txt'), ...entries] - now = DIR_LISTING_PAGE_CACHE_TTL_MS - } - }) - // The new file sorts before the cursor, so it waits for a refresh rather than shifting pages. - expect(read).toEqual(names(folder(6))) - expect(list).toHaveBeenCalledTimes(2) - }) - it('does not serve a file deleted after the cursor once the watcher reports the change', async () => { let entries = folder(6) const cache = new DirListingPageCache(() => 0) @@ -98,89 +66,3 @@ describe('DirListingPageCache', () => { expect(names(page.entries)).toEqual(names(folder(3))) }) }) - -function dispatcherWithListing(entries: DirEntry[]) { - const readFileExplorerDir = vi - .fn() - .mockResolvedValue(entries) - const runtime: Pick = { - getRuntimeId: () => 'test-runtime', - readFileExplorerDir - } - const dispatcher = new RpcDispatcher({ - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: files.readDir uses readFileExplorerDir; its response envelope reads only getRuntimeId. - runtime: runtime as OrcaRuntimeService, - methods: FILE_METHODS - }) - return { dispatcher, readFileExplorerDir } -} - -async function readDir( - dispatcher: RpcDispatcher, - params: Record, - connectionId = 'socket-1' -) { - const replies: unknown[] = [] - await dispatcher.dispatchStreaming( - { id: 'read', authToken: 'tok', method: 'files.readDir', params }, - (reply) => replies.push(JSON.parse(reply)), - { clientKind: 'runtime', connectionId } - ) - return replies[0] -} - -describe('files.readDir pages', () => { - it('pages a folder too large for one remote reply', async () => { - const { dispatcher, readFileExplorerDir } = dispatcherWithListing(folder(80_000, 'paged')) - - const first = await readDir(dispatcher, { ...REQUEST, limit: 1_000 }) - const next = await readDir(dispatcher, { - ...REQUEST, - after: cursorOf(folder(80_000, 'paged')[999]), - limit: 1_000 - }) - - expect(first).toMatchObject({ ok: true, result: { total: 80_000, hasMore: true } }) - expect(next).toMatchObject({ - ok: true, - result: { - total: 80_000, - hasMore: true, - entries: expect.arrayContaining([folder(80_000, 'paged')[1_000]]) - } - }) - expect(readFileExplorerDir).toHaveBeenCalledTimes(1) - }) - - it("drops a cached listing when the host's watcher reports a change in that workspace", async () => { - let entries = folder(6) - let emitChange: ((events: { kind: 'delete'; absolutePath: string }[]) => void) | undefined - const readFileExplorerDir = vi.fn(async () => entries) - const fakeRuntime = { - getRuntimeId: () => 'test-runtime', - readFileExplorerDir, - watchFileExplorer: vi.fn(async (_worktree: string, callback: typeof emitChange) => { - emitChange = callback - return vi.fn() - }), - registerSubscriptionCleanup: vi.fn() - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: files.readDir and files.watch only touch these runtime members. - const runtime = fakeRuntime as unknown as OrcaRuntimeService - const dispatcher = new RpcDispatcher({ runtime, methods: FILE_METHODS }) - void dispatcher.dispatchStreaming( - { id: 'watch', authToken: 'tok', method: 'files.watch', params: { worktree: 'id:wt-1' } }, - () => {}, - { connectionId: 'socket-2' } - ) - await vi.waitFor(() => expect(emitChange).toBeDefined()) - - await readDir(dispatcher, { ...REQUEST, limit: 2 }) - entries = entries.filter((entry) => entry.name !== 'file-000004.txt') - emitChange?.([{ kind: 'delete', absolutePath: '/repo/big/file-000004.txt' }]) - const next = await readDir(dispatcher, { ...REQUEST, after: cursorOf(folder(6)[1]), limit: 5 }) - - expect(readFileExplorerDir).toHaveBeenCalledTimes(2) - expect(next).toMatchObject({ ok: true, result: { total: 5, hasMore: false } }) - }) -}) diff --git a/src/main/runtime/rpc/methods/files/files-read-dir-page.ts b/src/main/runtime/rpc/methods/files/files-read-dir-page.ts index 2a6257af037..d1d5460edaa 100644 --- a/src/main/runtime/rpc/methods/files/files-read-dir-page.ts +++ b/src/main/runtime/rpc/methods/files/files-read-dir-page.ts @@ -1,10 +1,10 @@ -import type { DirEntry } from '../../../../../shared/filesystem-entry-types' +import type { DirEntry } from '../../../../../shared/file-listing/directory-entry' import { dirEntryPageAfter, FILE_READ_DIR_MAX_PAGE_ENTRIES, type DirEntryCursor, type DirEntryPage -} from '../../../../../shared/file-dir-page' +} from '../../../../../shared/file-listing/file-dir-page' /** Long enough to page through a folder as it scrolls; the cursor keeps an older listing correct. */ export const DIR_LISTING_PAGE_CACHE_TTL_MS = 30_000 diff --git a/src/main/runtime/rpc/methods/files/files-read-dir-remote-budget.test.ts b/src/main/runtime/rpc/methods/files/files-read-dir-remote-budget.test.ts deleted file mode 100644 index 915f251872a..00000000000 --- a/src/main/runtime/rpc/methods/files/files-read-dir-remote-budget.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { RpcDispatcher } from '../../dispatcher' -import type { OrcaRuntimeService } from '../../../orca-runtime' -import type { DirEntry } from '../../../../../shared/filesystem-entry-types' -import { FILE_METHODS } from './files' - -const HUGE_LISTING: DirEntry[] = Array.from({ length: 80_000 }, (_, index) => ({ - name: `file-${String(index).padStart(5, '0')}.txt`, - isDirectory: false, - isSymlink: false -})) - -function dispatcherWithListing(entries: DirEntry[]) { - const runtime: Pick = { - getRuntimeId: () => 'test-runtime', - readFileExplorerDir: vi - .fn() - .mockResolvedValue(entries) - } - return new RpcDispatcher({ - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: files.readDir uses readFileExplorerDir; its response envelope reads only getRuntimeId. - runtime: runtime as OrcaRuntimeService, - methods: FILE_METHODS - }) -} - -async function readDir(clientKind: 'runtime' | undefined) { - const replies: unknown[] = [] - await dispatcherWithListing(HUGE_LISTING).dispatchStreaming( - { - id: 'read-flat', - authToken: 'tok', - method: 'files.readDir', - params: { worktree: 'id:wt-1', relativePath: 'flat' } - }, - (reply) => replies.push(JSON.parse(reply)), - { clientKind } - ) - return replies -} - -describe('files.readDir remote reply budget', () => { - it('refuses a listing a remote reply cannot carry, naming the entry count', async () => { - expect(await readDir('runtime')).toEqual([ - expect.objectContaining({ - id: 'read-flat', - ok: false, - error: { - code: 'runtime_error', - message: 'This folder has 80,000 entries, too many to list over a remote connection.' - } - }) - ]) - }) -}) diff --git a/src/main/runtime/rpc/methods/files/files-remote-content-budget.ts b/src/main/runtime/rpc/methods/files/files-remote-content-budget.ts index 818e1f11b50..7a5399e0c73 100644 --- a/src/main/runtime/rpc/methods/files/files-remote-content-budget.ts +++ b/src/main/runtime/rpc/methods/files/files-remote-content-budget.ts @@ -2,8 +2,8 @@ import { remoteRpcContentBudget, remoteRpcResultExceedsContentBudget } from '../../../../../shared/remote-rpc-content-budget' -import type { DirEntry } from '../../../../../shared/filesystem-entry-types' -import { dirListingTooLargeForRemoteMessage } from '../../../../../shared/file-dir-page' +import type { DirEntry } from '../../../../../shared/file-listing/directory-entry' +import { dirListingTooLargeForRemoteMessage } from '../../../../../shared/file-listing/file-dir-page' export function remoteFileContentBudget( clientKind: 'mobile' | 'runtime' | undefined, diff --git a/src/main/runtime/rpc/methods/files/files-staged-save-methods.ts b/src/main/runtime/rpc/methods/files/files-staged-save-methods.ts index fe977418586..88dddbf742a 100644 --- a/src/main/runtime/rpc/methods/files/files-staged-save-methods.ts +++ b/src/main/runtime/rpc/methods/files/files-staged-save-methods.ts @@ -5,7 +5,7 @@ import { FileSaveChunk, FileSaveCommit } from '../../../../../shared/rpc-contract/files-staged-save-params' -import { STAGED_FILE_SAVE_METHODS } from '../../../../../shared/staged-file-save' +import { STAGED_FILE_SAVE_METHODS } from '../../../../../shared/file-write/staged-file-save' // Saves belong to the socket that began them; in-process callers share one owner. const owner = (connectionId: string | undefined) => connectionId ?? 'in-process' diff --git a/src/main/runtime/rpc/methods/files/files.ts b/src/main/runtime/rpc/methods/files/files.ts index 9739e05afbe..56c8c93d755 100644 --- a/src/main/runtime/rpc/methods/files/files.ts +++ b/src/main/runtime/rpc/methods/files/files.ts @@ -7,7 +7,7 @@ import { assertDirListingWithinRemoteBudget, remoteFileContentBudget } from './files-remote-content-budget' -import { limitQuickOpenSearchReplyBySerializedBytes } from '../../../../../shared/quick-open-transport-budget' +import { limitQuickOpenSearchReplyBySerializedBytes } from '../../../../../shared/quick-open/quick-open-transport-budget' import { FileOpen, FileWatch, @@ -31,7 +31,7 @@ import { ResolveTerminalPath, ServerDirectoryBrowse } from '../../../../../shared/rpc-contract/files-params' -import { limitSearchResultToContentBudget } from '../../../../../shared/search-result-transport-budget' +import { limitSearchResultToContentBudget } from '../../../../../shared/file-search/search-result-transport-budget' let filesWatchSubscriptionSeq = 0 diff --git a/src/main/runtime/rpc/methods/structured-sessions/attachments/structured-agent-session-attachments.test.ts b/src/main/runtime/rpc/methods/structured-sessions/attachments/structured-agent-session-attachments.test.ts index 9d0d5043da8..4bcde909d40 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/attachments/structured-agent-session-attachments.test.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/attachments/structured-agent-session-attachments.test.ts @@ -1,19 +1,9 @@ -import * as fs from 'node:fs/promises' import type { RpcResponse } from '../../../core' -import { RUNTIME_CAPABILITIES as runtimeCapabilities } from '../../../../../../shared/protocol-version' -import { AGENT_SESSION_TEXT_ATTACHMENT_READ_CAPABILITY } from '../../../../../../shared/agent-session/agent-session-runtime-capabilities' -import { MOBILE_RPC_METHOD_ALLOWLIST } from '../../../server/runtime-rpc-mobile-method-allowlist' -import { - AttachmentTextSource, - ATTACHMENT_TEXT_BLOCK_BYTES, - type AttachmentTextRequest -} from '../../../../../../shared/attachment-text-source' -import { AttachmentTextViewport } from '../../../../../../shared/attachment-text-viewport' -import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { mkdtemp, readFile, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' import type { OrcaRuntimeService } from '../../../../orca-runtime' import { RpcDispatcher } from '../../../dispatcher' @@ -21,7 +11,7 @@ import { RpcDispatcher } from '../../../dispatcher' import { AgentSessionAttachmentStore } from '../../../../../native-chat/agent-session-attachments/agent-session-attachment-store' import { setAgentSessionAttachmentStore } from '../../../../../native-chat/agent-session-attachments/agent-session-attachment-store-registry' import { STRUCTURED_AGENT_SESSION_ATTACHMENT_METHODS } from './structured-agent-session-attachments' -import { isMobileE2EETextPayloadWithinLimit } from '../../../mobile-e2ee-outbound-admission' + import { clearStructuredHostStub, installStructuredHostStub @@ -29,16 +19,6 @@ import { import { STRUCTURED_CLIENT } from '../protocol/structured-agent-session-rpc-client.test-fixture' -vi.mock('node:fs/promises', async (importOriginal) => { - const original = await importOriginal() - return { - ...original, - open: vi.fn(original.open), - stat: vi.fn(original.stat), - realpath: vi.fn(original.realpath) - } -}) - let root: string let store: AgentSessionAttachmentStore @@ -93,33 +73,6 @@ function result(response: RpcResponse): T { const CLIENT_A = { ...STRUCTURED_CLIENT, clientId: 'client-a' } -async function uploadBytes(name: string, bytes: Buffer): Promise { - const { uploadId } = result<{ uploadId: string }>( - await call( - 'agentSessionAttachment.uploadStart', - { sessionId: 'session-alpha', name, byteLength: bytes.byteLength }, - CLIENT_A - ) - ) - const chunk = 384 * 1024 - for (let offset = 0; offset < bytes.byteLength; offset += chunk) { - result( - await call( - 'agentSessionAttachment.uploadAppend', - { - uploadId, - offset, - contentBase64: bytes.subarray(offset, offset + chunk).toString('base64') - }, - CLIENT_A - ) - ) - } - return result<{ path: string }>( - await call('agentSessionAttachment.uploadCommit', { uploadId }, CLIENT_A) - ).path -} - describe('agentSessionAttachment.*', () => { it('stores an upload for the chat and hands back the server path', async () => { const { uploadId } = result<{ uploadId: string }>( @@ -146,380 +99,4 @@ describe('agentSessionAttachment.*', () => { const preview = await call('agentSessionAttachment.read', { path: stored.path }, CLIENT_A) expect(preview).toMatchObject({ ok: true, result: { isBinary: true, mimeType: 'image/png' } }) }) - - it("keeps one client's upload out of another's reach", async () => { - const { uploadId } = result<{ uploadId: string }>( - await call( - 'agentSessionAttachment.uploadStart', - { sessionId: 'session-alpha', name: 'a.txt', byteLength: 1 }, - CLIENT_A - ) - ) - const response = await call( - 'agentSessionAttachment.uploadCommit', - { uploadId }, - { - ...STRUCTURED_CLIENT, - clientId: 'client-b' - } - ) - expect(response).toMatchObject({ ok: false }) - expect(store.isUploadInFlight(uploadId)).toBe(true) - }) - - it('answers a remote preview of an image over 3 MiB with a small refusal, not an oversized reply', async () => { - const path = await uploadBytes('big.png', Buffer.alloc(3.5 * 1024 * 1024, 7)) - const replies: string[] = [] - const dispatcher = new RpcDispatcher({ - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the attachment methods read only the host-install hook and runtime id. - runtime: { - getRuntimeId: () => 'runtime-1', - ensureStructuredAgentSessionHost: async () => {} - } as unknown as OrcaRuntimeService, - methods: STRUCTURED_AGENT_SESSION_ATTACHMENT_METHODS - }) - await dispatcher.dispatchStreaming( - { - id: 'request-big', - authToken: 'token', - method: 'agentSessionAttachment.read', - params: { path } - }, - (raw) => replies.push(raw), - { ...CLIENT_A, clientKind: 'runtime' } - ) - expect(replies).toHaveLength(1) - expect(isMobileE2EETextPayloadWithinLimit(replies[0] ?? '')).toBe(true) - expect(JSON.parse(replies[0] ?? '{}')).toMatchObject({ - ok: false, - error: { message: expect.stringContaining('file_too_large') } - }) - }) -}) - -it('reads a committed text attachment through the registered mobile RPC and validates its complete snapshot', async () => { - { - const bytes = Buffer.from(`HEAD\n${'\n'.repeat(50 * 1024 * 1024 - 5)}`) - const path = await uploadBytes('tall-track.log', bytes) - const source = new AttachmentTextSource(path, async (request) => - result(await call('agentSessionAttachment.readTextChunk', request, CLIENT_A)) - ) - try { - for (let block = 0; block < 15; block++) { - await source.block(block) - } - const tall = new AttachmentTextViewport(source, 20, 3000) - expect.soft(tall.anchor(0)).toEqual({ block: 0, row: 0 }) - const interior = { block: 7, row: 120.25 } - expect.soft(tall.anchor(tall.position(interior)).block).toBe(interior.block) - expect.soft(tall.anchor(tall.position(interior)).row).toBeCloseTo(interior.row, 6) - await source.block(0) - expect.soft(tall.rows(0)[0]?.text).toBe('HEAD\n') - const resized = new AttachmentTextViewport(source, 23, 700) - expect.soft(resized.anchor(resized.position(interior)).row).toBeCloseTo(interior.row, 6) - expect - .soft(tall.anchor(tall.position(resized.anchor(resized.position(interior)))).row) - .toBeCloseTo(interior.row, 6) - expect - .soft(resized.anchor(resized.restore(tall, tall.position(interior))).row) - .toBeCloseTo(interior.row, 6) - const tailReady = Promise.withResolvers() - source.requestViewport(tall.window(tall.total - tall.height), () => tailReady.resolve()) - await tailReady.promise - const tailLayout = new AttachmentTextViewport(source, 20, 3000) - const tailRows = tailLayout.rows(tailLayout.total - tailLayout.height) - expect(tailRows.length).toBeGreaterThanOrEqual(150) - expect(tailRows.at(-1)!.top + 20).toBeCloseTo(tailLayout.total, 5) - expect(tailLayout.position(tailLayout.anchor(tailLayout.total - 3000))).toBeCloseTo( - tailLayout.total - 3000, - 5 - ) - await source.block(0) - expect(new AttachmentTextViewport(source, 20, 3000).rows(0)[0]?.text).toBe('HEAD\n') - for (let block = 15; block < 100; block++) { - await source.block(block) - } - await source.block(source.blockCount - 1) - const previous = new AttachmentTextViewport(source, 20, 600) - const grown = new AttachmentTextViewport(source, 20, 3000) - const oldEnd = previous.total - previous.height - const back = oldEnd - 2400 - expect(previous.prefixes.at(-1)).toBe(1_735_816) - expect(back).toBe(previous.total - grown.height) - expect(previous.anchor(back).block).toBe(3415) - expect(previous.anchor(back).row).toBeCloseTo(1169.264134908095, 6) - expect - .soft(grown.restore(previous, back)) - .toBeCloseTo(grown.position(previous.anchor(back)), 6) - expect(grown.position(previous.anchor(back))).toBeCloseTo(7_998_151.9358067745, 6) - expect(grown.restore(previous, oldEnd)).toBe(grown.total - grown.height) - const overscan = previous.rows(oldEnd - 1) - expect(overscan.length).toBeGreaterThan(0) - expect(overscan.length).toBeLessThanOrEqual(previous.rowBudget) - expect(overscan.at(-1)!.top + 20).toBeGreaterThan(previous.total) - } finally { - source.dispose() - } - } - { - const bytes = Buffer.from('🙂'.repeat((25 * 1024 * 1024) / 4)) - const path = await uploadBytes('tall-unicode.log', bytes) - const requests: AttachmentTextRequest[] = [] - const source = new AttachmentTextSource(path, async (request) => { - requests.push(request) - return result(await call('agentSessionAttachment.readTextChunk', request, CLIENT_A)) - }) - try { - await source.block(0) - const ready = Promise.withResolvers() - source.requestViewport(new AttachmentTextViewport(source, 20, 3000).window(0), () => - ready.resolve() - ) - await ready.promise - const tall = new AttachmentTextViewport(source, 20, 3000) - const visible = tall.rows(0) - expect.soft(visible.length).toBeGreaterThanOrEqual(150) - expect.soft(visible.length).toBeLessThanOrEqual(Math.ceil(3000 / 20) + 4) - expect.soft(visible.every((row) => Array.from(row.text).length <= 256)).toBe(true) - expect.soft(requests.length).toBeGreaterThan(2) - expect(requests.every((request) => request.length <= 16 * 1024)).toBe(true) - expect(requests.length).toBeLessThanOrEqual(tall.rowBudget + 1) - expect( - Array.from({ length: source.blockCount }, (_, index) => source.cachedBlock(index)).filter( - Boolean - ).length - ).toBeLessThanOrEqual(tall.rowBudget + 1) - expect(visible.at(-1)!.top + 20).toBeGreaterThanOrEqual(3000) - } finally { - source.dispose() - } - } - { - const line = 'Original pasted contents 35636; exact Copy and Save.\n' - const header = `COPY35636-START\n indented\tfield value; whitespace35636\n ${line}` - const tail = '\nCOPY35636-END\n' - const text = (header + line.repeat(2000)).slice(0, 98304 - tail.length) + tail - const bytes = Buffer.from(text) - const path = await uploadBytes('literal-seam.txt', bytes) - const requests: AttachmentTextRequest[] = [] - const source = new AttachmentTextSource(path, async (request) => { - requests.push(request) - return result(await call('agentSessionAttachment.readTextChunk', request, CLIENT_A)) - }) - try { - await source.block(0) - const viewport = new AttachmentTextViewport(source, 19, 600) - expect.soft((viewport.anchor(300).row - viewport.anchor(200).row) * 19).toBeCloseTo(100) - const blocks: string[][] = [] - for (let index = 0; index < source.blockCount; index++) { - blocks.push(await source.block(index)) - } - expect.soft(blocks.flat().join('')).toBe(text) - expect - .soft(blocks.flat().filter((row) => row === line)) - .toHaveLength(text.split('\n').filter((row) => row === line.trimEnd()).length) - for (let index = source.blockCount - 1; index >= 0; index--) { - expect.soft(await source.block(index)).toEqual(blocks[index]) - } - await source.block(source.blockCount - 1) - const elastic = new AttachmentTextViewport(source, 19, 645) - const end = elastic.total - elastic.height - const ending = elastic.rows(end) - expect(elastic.counts).toEqual([291, 290, 289, 290, 289, 290, 118]) - expect(end).toBe(34638) - expect(ending[0]?.top).toBe(34637) - expect(ending.at(-1)!.top + 19).toBe(elastic.total) - expect.soft(elastic.rows(35545)).toEqual(ending) - expect.soft(elastic.rows(34931)).toEqual(ending) - expect(elastic.rows(end - 645)[0]?.key).not.toBe(ending[0]?.key) - await source.block(0) - expect.soft(elastic.rows(-40)).toEqual(elastic.rows(0)) - const fitting = new AttachmentTextViewport(source, 19, 40000) - expect.soft(fitting.rows(80)).toEqual(fitting.rows(0)) - expect.soft(fitting.window(80)).toEqual(fitting.window(0)) - expect(requests.every((request) => request.length <= 16 * 1024)).toBe(true) - expect(await source.copyText()).toBe(text) - const output: Uint8Array[] = [] - for await (const chunk of source.bytes()) { - output.push(chunk) - } - expect(Buffer.concat(output)).toEqual(bytes) - } finally { - source.dispose() - } - } - const prefix = '\ufeffstart\r\nmiddle\rlast\n' - const bytes = Buffer.from( - [ - prefix, - 'a'.repeat(ATTACHMENT_TEXT_BLOCK_BYTES - Buffer.byteLength(prefix) - 1), - '\r\n', - 'é🙂\r\n'.repeat(125_000), - 'end' - ].join('') - ) - const path = await uploadBytes('picked source.log', bytes) - let ranges = 0 - const source = new AttachmentTextSource(path, async (request) => { - ranges++ - const reply = await call('agentSessionAttachment.readTextChunk', request, { - ...CLIENT_A, - clientKind: 'mobile' - }) - expect(isMobileE2EETextPayloadWithinLimit(JSON.stringify(reply))).toBe(true) - return result(reply) - }) - expect(runtimeCapabilities).toContain(AGENT_SESSION_TEXT_ATTACHMENT_READ_CAPABILITY) - expect(MOBILE_RPC_METHOD_ALLOWLIST.has('agentSessionAttachment.readTextChunk')).toBe(true) - await expect(store.readTextChunk({ path, offset: 0, length: 256 * 1024 + 1 })).rejects.toThrow() - await expect( - store.readTextChunk({ path: join(root, 'outside.txt'), offset: 0, length: 10 }) - ).rejects.toThrow() - vi.mocked(fs.open).mockClear() - vi.mocked(fs.stat).mockClear() - vi.mocked(fs.realpath).mockClear() - expect((await source.block(0)).join('')).toMatch(/^\ufeffstart\nmiddle\nlast\n/) - expect((await source.block(1))[0]?.startsWith('é🙂')).toBe(true) - expect(await source.copyText()).toBe(bytes.toString('utf8')) - const saved: Uint8Array[] = [] - for await (const chunk of source.bytes()) { - saved.push(chunk) - } - expect(Buffer.concat(saved)).toEqual(bytes) - expect(ranges).toBe(2 + 2 * Math.ceil(bytes.length / (256 * 1024))) - expect(fs.open).toHaveBeenCalledTimes(ranges) - expect(vi.mocked(fs.stat).mock.calls.length).toBeLessThanOrEqual(4 * ranges) - expect(vi.mocked(fs.realpath).mock.calls.length).toBeLessThanOrEqual(8 * ranges) - const snapshot = source.snapshot - await writeFile(path, Buffer.alloc(bytes.length, 97)) - expect( - await call( - 'agentSessionAttachment.readTextChunk', - { path, offset: 0, length: 10, expectedSnapshot: snapshot }, - CLIENT_A - ) - ).toMatchObject({ ok: false }) - source.dispose() - { - const bytes = Buffer.from( - `\ufeff${'a'.repeat(ATTACHMENT_TEXT_BLOCK_BYTES - 4)}🙂é\r\n${'x'.repeat(25 * 1024 * 1024)}${'\n'.repeat(ATTACHMENT_TEXT_BLOCK_BYTES * 2)}TAIL` - ) - const requests: AttachmentTextRequest[] = [] - let hold: Promise | undefined - let started = Promise.withResolvers() - const path = await uploadBytes('scroll-source.log', bytes) - const source = new AttachmentTextSource(path, async (request) => { - requests.push(request) - started.resolve() - await hold - return result( - await call('agentSessionAttachment.readTextChunk', request, { - ...CLIENT_A, - clientKind: 'mobile' - }) - ) - }) - - const first = await source.block(0) - const pinnedSnapshot = source.snapshot - expect(requests).toHaveLength(1) - const second = await source.block(1) - expect( - (first.join('') + second.join('')).startsWith( - `\ufeff${'a'.repeat(ATTACHMENT_TEXT_BLOCK_BYTES - 4)}🙂é\n` - ) - ).toBe(true) - await source.block(source.blockCount - 2) - await source.block(source.blockCount - 1) - expect(source.cachedBlock(0)).toBeUndefined() - expect(source.cachedBlock(1)).toBeUndefined() - const layout = new AttachmentTextViewport(source, 20, 600) - expect(layout.total).toBeLessThan(8_000_000) - const end = layout.rows(layout.total - 600) - expect(end.length).toBeLessThanOrEqual(layout.rowBudget) - expect(end.at(-1)?.text).toBe('TAIL') - expect(end.every((row) => Array.from(row.text).length <= 256)).toBe(true) - // Evicted ranges remain reachable; viewport storms replace pending work rather than serially enqueuing it. - const release = Promise.withResolvers() - hold = release.promise - started = Promise.withResolvers() - const obsolete: unknown[] = [], - published: unknown[] = [] - source.requestViewport({ block: 3, row: 0, rows: 1 }, (error) => obsolete.push(error)) - await started.promise - const before = requests.length - for (let block = 4; block < 104; block++) { - source.requestViewport({ block, row: 0, rows: 1 }, (error) => obsolete.push(error)) - } - const ready = Promise.withResolvers() - source.requestViewport({ block: 0, row: 0, rows: first.length + second.length }, (error) => { - published.push(error) - ready.resolve() - }) - hold = undefined - release.resolve() - await ready.promise - expect(obsolete).toEqual([]) - expect(published).toEqual([undefined]) - expect(requests.length - before).toBe(2) - expect(source.cachedBlock(0)?.join('')).toBe(first.join('')) - expect(source.cachedBlock(1)?.join('')).toBe(second.join('')) - expect(requests.every((request) => request.length <= 16 * 1024)).toBe(true) - expect(requests.slice(1).every((request) => request.expectedSnapshot === pinnedSnapshot)).toBe( - true - ) - const output: Uint8Array[] = [] - for await (const chunk of source.bytes()) { - output.push(chunk) - } - expect(Buffer.concat(output).equals(bytes)).toBe(true) - await expect(source.copyText()).rejects.toThrow('too large') - started = Promise.withResolvers() - const late = Promise.withResolvers() - hold = late.promise - const dispatched = vi.spyOn(source, 'block') - const afterClose: unknown[] = [] - source.requestViewport({ block: 4, row: 0, rows: 1 }, (error) => afterClose.push(error)) - await started.promise - const pending: unknown = dispatched.mock.results.at(-1)?.value - if (!(pending instanceof Promise)) { - throw new Error('Expected the production demand iteration to dispatch its source read') - } - source.dispose() - late.resolve() - await expect(pending).rejects.toThrow() - expect(source.cachedBlock(4)).toBeUndefined() - expect(afterClose).toEqual([]) - dispatched.mockRestore() - - // A current snapshot failure settles once; a legitimate Retry owns a new source. - await writeFile(path, Buffer.from('RETRY35636')) - const failed = new AttachmentTextSource(path, async (request) => - result( - await call( - 'agentSessionAttachment.readTextChunk', - { ...request, expectedSnapshot: pinnedSnapshot }, - CLIENT_A - ) - ) - ) - const errors: unknown[] = [] - const settled = Promise.withResolvers() - failed.requestViewport({ block: 0, row: 0, rows: 30 }, (error) => { - errors.push(error) - settled.resolve() - }) - await settled.promise - expect(errors).toHaveLength(1) - expect(errors[0]).toBeInstanceOf(Error) - failed.dispose() - const retry = new AttachmentTextSource(path, async (request) => - result(await call('agentSessionAttachment.readTextChunk', request, CLIENT_A)) - ) - const recovered = Promise.withResolvers() - retry.requestViewport({ block: 0, row: 0, rows: 30 }, () => recovered.resolve()) - await recovered.promise - expect(retry.cachedBlock(0)).toEqual(['RETRY35636']) - retry.dispose() - } }) diff --git a/src/main/runtime/rpc/server/network-source-policy-store.ts b/src/main/runtime/rpc/server/network-source-policy-store.ts index 8ee9f97176f..d3ac5ea014b 100644 --- a/src/main/runtime/rpc/server/network-source-policy-store.ts +++ b/src/main/runtime/rpc/server/network-source-policy-store.ts @@ -1,7 +1,7 @@ // Server-level memory of where authenticated direct clients connect from, kept in userData. import { readFileSync } from 'node:fs' import { join } from 'node:path' -import { writeDurableSecureJsonFile } from '../../../../shared/secure-file' +import { writeDurableSecureJsonFile } from '../../../../shared/secure-storage/secure-file' import { isRecord } from '../../../../shared/agent-status/child-work/agent-status-child-work-value-guards' import type { NetworkSourceClass } from '../network-source-class' diff --git a/src/main/runtime/rpc/server/pairing/device-registry-disk-merge.ts b/src/main/runtime/rpc/server/pairing/device-registry-disk-merge.ts index d368e6453c0..eea3b63d7be 100644 --- a/src/main/runtime/rpc/server/pairing/device-registry-disk-merge.ts +++ b/src/main/runtime/rpc/server/pairing/device-registry-disk-merge.ts @@ -1,5 +1,8 @@ import { readFileSync, statSync } from 'node:fs' -import { writeDurableSecureJsonFile, writeSecureJsonFile } from '../../../../../shared/secure-file' +import { + writeDurableSecureJsonFile, + writeSecureJsonFile +} from '../../../../../shared/secure-storage/secure-file' import type { DeviceEntry } from './device-entry' import { isMissingFileError, quarantineCorruptRegistry } from './device-registry-corruption' import { readDeviceRegistryFile, type DeviceRegistryFileRead } from './device-registry-file-read' diff --git a/src/main/runtime/rpc/server/pairing/device-registry-external-edit-auth.test.ts b/src/main/runtime/rpc/server/pairing/device-registry-external-edit-auth.test.ts index d220dafb34e..1cf257111ba 100644 --- a/src/main/runtime/rpc/server/pairing/device-registry-external-edit-auth.test.ts +++ b/src/main/runtime/rpc/server/pairing/device-registry-external-edit-auth.test.ts @@ -3,7 +3,7 @@ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import * as secureFile from '../../../../../shared/secure-file' +import * as secureFile from '../../../../../shared/secure-storage/secure-file' import { DeviceRegistry } from './device-registry' import { DEVICE_REGISTRY_FILENAME } from './mobile-pairing-files' @@ -24,37 +24,7 @@ function registryPath(): string { return join(dir, DEVICE_REGISTRY_FILENAME) } -// Auth checks see another process's edit once the registry's one-second stat window has passed. -function removeOnDisk(deviceId: string, advanceMs = 1000): void { - const rows: { deviceId: string }[] = JSON.parse(readFileSync(registryPath(), 'utf8')) - writeFileSync(registryPath(), JSON.stringify(rows.filter((row) => row.deviceId !== deviceId))) - vi.advanceTimersByTime(advanceMs) -} - -function spyOnSaves() { - return [ - vi.spyOn(secureFile, 'writeSecureJsonFile'), - vi.spyOn(secureFile, 'writeDurableSecureJsonFile') - ] -} - describe('device registry auth checks see edits made on disk', () => { - it('refuses a token removed on disk at the next validate, with no save in between', () => { - const registry = new DeviceRegistry(dir) - const desktop = registry.addDevice('desktop', 'runtime') - const phone = registry.addDevice('phone', 'mobile') - expect(registry.validateToken(desktop.token)?.deviceId).toBe(desktop.deviceId) - const saves = spyOnSaves() - - removeOnDisk(desktop.deviceId) - - expect(registry.validateToken(desktop.token)).toBeNull() - expect(registry.validateToken(phone.token)?.deviceId).toBe(phone.deviceId) - for (const save of saves) { - expect(save).not.toHaveBeenCalled() - } - }) - it('refuses every device once the file is deleted, and keeps working', () => { const registry = new DeviceRegistry(dir) const desktop = registry.addDevice('desktop', 'runtime') diff --git a/src/main/runtime/rpc/server/pairing/device-registry-external-edit.test.ts b/src/main/runtime/rpc/server/pairing/device-registry-external-edit.test.ts index 84960b36b5f..8555209dc9d 100644 --- a/src/main/runtime/rpc/server/pairing/device-registry-external-edit.test.ts +++ b/src/main/runtime/rpc/server/pairing/device-registry-external-edit.test.ts @@ -4,7 +4,7 @@ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import * as secureFile from '../../../../../shared/secure-file' + import { DeviceRegistry } from './device-registry' import { DEVICE_REGISTRY_FILENAME } from './mobile-pairing-files' @@ -85,29 +85,6 @@ describe('device registry saves over an externally edited file', () => { expect(registry.validateToken(desktop.token)).toBeNull() }) - it('never re-adopts a session-only row whose load-time cleanup save failed', () => { - const registry = new DeviceRegistry(dir) - const desktop = registry.addDevice('desktop', 'runtime') - const fork = registry.forkDeviceKey( - desktop.deviceId, - Buffer.alloc(32, 1).toString('base64'), - 'Tab', - { ephemeral: true } - ) - const writes = vi.spyOn(secureFile, 'writeDurableSecureJsonFile').mockImplementationOnce(() => { - throw new Error('disk full') - }) - vi.spyOn(console, 'error').mockImplementation(() => {}) - - const reloaded = new DeviceRegistry(dir) - expect(writes).toHaveBeenCalledOnce() - expect(fileIds()).toContain(fork.deviceId) - reloaded.addDevice('second desktop', 'runtime') - - expect(fileIds()).not.toContain(fork.deviceId) - expect(reloaded.getDevice(fork.deviceId)).toBeNull() - }) - // Review of #35483: a parent must never be handed the token of a child the file had dropped. it.each([ ['unchanged', 'Pixel'], diff --git a/src/main/runtime/rpc/server/pairing/device-registry-file-read.ts b/src/main/runtime/rpc/server/pairing/device-registry-file-read.ts index 8e12d23c71b..e6000cb69c1 100644 --- a/src/main/runtime/rpc/server/pairing/device-registry-file-read.ts +++ b/src/main/runtime/rpc/server/pairing/device-registry-file-read.ts @@ -1,5 +1,8 @@ import { readFileSync } from 'node:fs' -import { hardenExistingSecureFile, isUnreadableError } from '../../../../../shared/secure-file' +import { + hardenExistingSecureFile, + isUnreadableError +} from '../../../../../shared/secure-storage/secure-file' import { corruptRegistryCopyExists, isMissingFileError } from './device-registry-corruption' import type { DeviceEntry } from './device-entry' import { normalizeLoadedDeviceRow } from './device-registry-row-validation' diff --git a/src/main/runtime/rpc/server/pairing/device-registry-own-quarantine.test.ts b/src/main/runtime/rpc/server/pairing/device-registry-own-quarantine.test.ts index 9fb83db14c4..f3d999dd405 100644 --- a/src/main/runtime/rpc/server/pairing/device-registry-own-quarantine.test.ts +++ b/src/main/runtime/rpc/server/pairing/device-registry-own-quarantine.test.ts @@ -4,7 +4,7 @@ import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSy import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import * as secureFile from '../../../../../shared/secure-file' +import * as secureFile from '../../../../../shared/secure-storage/secure-file' import { DeviceRegistry } from './device-registry' import { DEVICE_REGISTRY_FILENAME } from './mobile-pairing-files' diff --git a/src/main/runtime/rpc/server/pairing/e2ee-keypair.ts b/src/main/runtime/rpc/server/pairing/e2ee-keypair.ts index 76d22778842..2a9e7fcf539 100644 --- a/src/main/runtime/rpc/server/pairing/e2ee-keypair.ts +++ b/src/main/runtime/rpc/server/pairing/e2ee-keypair.ts @@ -6,7 +6,7 @@ import { hardenExistingSecureFile, isUnreadableError, writeSecureJsonFile -} from '../../../../../shared/secure-file' +} from '../../../../../shared/secure-storage/secure-file' import { E2EE_KEYPAIR_FILENAME as KEYPAIR_FILENAME, MAX_E2EE_KEYPAIR_FILE_BYTES as MAX_KEYPAIR_FILE_BYTES diff --git a/src/main/runtime/rpc/server/runtime-metadata.ts b/src/main/runtime/rpc/server/runtime-metadata.ts index 2132193cf9e..d5aecee20c0 100644 --- a/src/main/runtime/rpc/server/runtime-metadata.ts +++ b/src/main/runtime/rpc/server/runtime-metadata.ts @@ -1,7 +1,7 @@ import { existsSync, readFileSync, rmSync } from 'node:fs' import { readFile } from 'node:fs/promises' import { getRuntimeMetadataPath, type RuntimeMetadata } from '../../../../shared/runtime-bootstrap' -import { writeSecureJsonFile } from '../../../../shared/secure-file' +import { writeSecureJsonFile } from '../../../../shared/secure-storage/secure-file' export function writeRuntimeMetadata(userDataPath: string, metadata: RuntimeMetadata): void { const metadataPath = getRuntimeMetadataPath(userDataPath) diff --git a/src/main/runtime/session-lifecycle/projection/orca-runtime-mobile-markdown-tab-routes.test.ts b/src/main/runtime/session-lifecycle/projection/orca-runtime-mobile-markdown-tab-routes.test.ts index 31c084579f6..4dcfb65ab89 100644 --- a/src/main/runtime/session-lifecycle/projection/orca-runtime-mobile-markdown-tab-routes.test.ts +++ b/src/main/runtime/session-lifecycle/projection/orca-runtime-mobile-markdown-tab-routes.test.ts @@ -10,12 +10,12 @@ import { hashMarkdownContent } from '../../../../shared/mobile-markdown-document import type { RuntimeMobileSessionMarkdownTab } from '../../../../shared/runtime-mobile-session-tab-contracts' import '../../../../shared/remote-runtime/remote-runtime-client-error' import '../../../../shared/protocol-version' -import { FILE_MUTATION_OWNERSHIP_RUNTIME_CAPABILITY } from '../../../../shared/files-runtime-capabilities' +import { FILE_MUTATION_OWNERSHIP_RUNTIME_CAPABILITY } from '../../../../shared/file-access/files-runtime-capabilities' import { FILE_WRITE_DISK_PRECONDITION_RUNTIME_CAPABILITY, FILE_WRITE_IDENTICAL_RUNTIME_CAPABILITY, FILE_WRITE_IF_UNCHANGED_METHOD -} from '../../../../shared/file-write-disk-precondition' +} from '../../../../shared/file-write/file-write-disk-precondition' import { SshHostNotServedError } from '../../../providers/ssh-host-not-served-error' import { OrchestrationError } from '../../orchestration/orchestration-error' import { RpcDispatcher } from '../../rpc/dispatcher' @@ -162,42 +162,6 @@ async function desktopOnServer( } describe("a phone's Markdown tab on a paired server's workspace", () => { - it('never hops on from a server that does not run the workspace itself', async () => { - const { desktop, serverCalls, serverForwards } = await desktopOnServer('runtime:env-b') - - await expect(desktop.readMobileMarkdownTab(`id:${TEST_WORKTREE_ID}`, readme)).rejects.toThrow( - 'runtime:env-b is not dispatched by this process' - ) - await expect( - desktop.saveMobileMarkdownTab( - `id:${TEST_WORKTREE_ID}`, - readme, - hashMarkdownContent('# Notes\n'), - '# Phone\n' - ) - ).rejects.toThrow() - expect(serverCalls).toEqual(['files.read', 'files.read']) - expect(serverForwards).not.toHaveBeenCalled() - expect(await readFile(readme, 'utf8')).toBe('# Notes\n') - }) - - it('saves through the server, which checks the precondition and writes', async () => { - const { desktop, serverCalls, serverForwards, pins } = await desktopOnServer() - - await expect( - desktop.saveMobileMarkdownTab( - `id:${TEST_WORKTREE_ID}`, - readme, - hashMarkdownContent('# Notes\n'), - '# Phone\n' - ) - ).resolves.toMatchObject({ content: '# Phone\n', isDirty: false }) - expect(await readFile(readme, 'utf8')).toBe('# Phone\n') - expect(serverCalls).toEqual(['files.read', 'status.get', 'files.writeIfUnchanged']) - expect(pins).toEqual([PAIRING_REVISION, PAIRING_REVISION, PAIRING_REVISION]) - expect(serverForwards).not.toHaveBeenCalled() - }) - it("refuses a save the server's disk moved under", async () => { const { desktop, call } = await desktopOnServer() const forward = call.getMockImplementation()! @@ -219,22 +183,6 @@ describe("a phone's Markdown tab on a paired server's workspace", () => { expect(await readFile(readme, 'utf8')).toBe('# Changed on the server\n') }) - it('saves an unchanged file on a server too old to check the disk, comparing here first', async () => { - const { desktop, serverCalls, pins } = await desktopOnServer('local', PRE_DISK_CHECK_SERVER) - - await expect( - desktop.saveMobileMarkdownTab( - `id:${TEST_WORKTREE_ID}`, - readme, - hashMarkdownContent('# Notes\n'), - '# Phone\n' - ) - ).resolves.toMatchObject({ content: '# Phone\n', isDirty: false }) - expect(await readFile(readme, 'utf8')).toBe('# Phone\n') - expect(serverCalls).toEqual(['files.read', 'status.get', 'files.read', 'files.write']) - expect(pins).toEqual([PAIRING_REVISION, PAIRING_REVISION, PAIRING_REVISION, PAIRING_REVISION]) - }) - it('refuses a changed file on a server too old to check the disk, and never writes', async () => { const { desktop, call, serverCalls } = await desktopOnServer('local', PRE_DISK_CHECK_SERVER) const forward = call.getMockImplementation()! @@ -269,33 +217,6 @@ function moveWorkspaceAfterFirstLookup(runtime: Runtime, to: ExecutionHostId): v } describe("a phone's Markdown save whose workspace moves host mid-save", () => { - it('still writes on the server it started on, pinned, never on local disk', async () => { - const { desktop, call, serverCalls, pins } = await desktopOnServer() - const forward = call.getMockImplementation()! - // Server stub never touches shared temp disk; any disk change exposes a local write. - call.mockImplementation(async (environmentId, method, params, timeout, envelope, internal) => { - if (method !== FILE_WRITE_IF_UNCHANGED_METHOD) { - return forward(environmentId, method, params, timeout, envelope, internal) - } - serverCalls.push(method) - pins.push(internal?.expectedEnvironmentPairingRevision) - return { ok: true } - }) - moveWorkspaceAfterFirstLookup(desktop, 'local') - - await expect( - desktop.saveMobileMarkdownTab( - `id:${TEST_WORKTREE_ID}`, - readme, - hashMarkdownContent('# Notes\n'), - '# Phone\n' - ) - ).resolves.toMatchObject({ content: '# Phone\n', isDirty: false }) - expect(serverCalls).toEqual(['files.read', 'status.get', FILE_WRITE_IF_UNCHANGED_METHOD]) - expect(pins).toEqual([PAIRING_REVISION, PAIRING_REVISION, PAIRING_REVISION]) - expect(await readFile(readme, 'utf8')).toBe('# Notes\n') - }) - it('still writes on local disk when it started local, never on a server', async () => { const runtime = await runtimeOnHost('local') const forwards = vi diff --git a/src/main/runtime/session-tabs/headless-editor-tabs.ts b/src/main/runtime/session-tabs/headless-editor-tabs.ts index 9ec5f405778..bac1681d096 100644 --- a/src/main/runtime/session-tabs/headless-editor-tabs.ts +++ b/src/main/runtime/session-tabs/headless-editor-tabs.ts @@ -10,7 +10,7 @@ import type { import type { RuntimeMobileSessionTabsSnapshot } from '../../../shared/runtime-session-contracts' import type { Tab } from '../../../shared/tab-types' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' -import { editorRowHost } from '../../../shared/session-tab-file-host' +import { editorRowHost } from '../../../shared/workspace-session/session-tab-file-host' import { editorTabNamesFile, sameEditorFile diff --git a/src/main/runtime/sidebar-inputs/repo-icon-data-urls.ts b/src/main/runtime/sidebar-inputs/repo-icon-data-urls.ts index 214d5389ffb..3616ca7ddad 100644 --- a/src/main/runtime/sidebar-inputs/repo-icon-data-urls.ts +++ b/src/main/runtime/sidebar-inputs/repo-icon-data-urls.ts @@ -1,7 +1,7 @@ import { createHash } from 'node:crypto' import type { RepoIcon } from '../../../shared/repo-icon' import type { Repo } from '../../../shared/repo-types' -import { readRasterImageDimensions } from '../../../shared/raster-image-dimensions' +import { readRasterImageDimensions } from '../../../shared/file-preview/raster-image-dimensions' import { MAX_REPO_ICON_DATA_URL_BYTES, repoIconFeedKey, diff --git a/src/main/runtime/sidebar-inputs/repo-icon-remote-fetch.ts b/src/main/runtime/sidebar-inputs/repo-icon-remote-fetch.ts index 091359ff5b2..525672eb455 100644 --- a/src/main/runtime/sidebar-inputs/repo-icon-remote-fetch.ts +++ b/src/main/runtime/sidebar-inputs/repo-icon-remote-fetch.ts @@ -1,4 +1,4 @@ -import { isKnownRasterImageMimeType } from '../../../shared/raster-image-preview-limits' +import { isKnownRasterImageMimeType } from '../../../shared/file-preview/raster-image-preview-limits' export const REPO_ICON_FETCH_MAX_BYTES = 64 * 1024 export const REPO_ICON_FETCH_MAX_REDIRECTS = 3 diff --git a/src/main/runtime/terminal/artifacts/artifact-integrity.ts b/src/main/runtime/terminal/artifacts/artifact-integrity.ts index a01aa354bb3..cc1cd6400d6 100644 --- a/src/main/runtime/terminal/artifacts/artifact-integrity.ts +++ b/src/main/runtime/terminal/artifacts/artifact-integrity.ts @@ -6,7 +6,7 @@ import type { TerminalFileContentBlocks, TerminalFileGrant } from './file-grants' -import { isBinaryBuffer } from '../../../../shared/binary-buffer' +import { isBinaryBuffer } from '../../../../shared/file-preview/binary-buffer' import { LOCAL_PREVIEWABLE_BINARY_MAX_BYTES, MOBILE_FILE_READ_MAX_BYTES diff --git a/src/main/runtime/terminal/artifacts/artifact-write.ts b/src/main/runtime/terminal/artifacts/artifact-write.ts index 9fee74d126e..e5429f14094 100644 --- a/src/main/runtime/terminal/artifacts/artifact-write.ts +++ b/src/main/runtime/terminal/artifacts/artifact-write.ts @@ -4,7 +4,7 @@ import { randomUUID } from 'node:crypto' import type { RuntimeTerminalFileGrants } from './file-grants' import { MOBILE_FILE_READ_MAX_BYTES } from '../../files/file-preview-budget' import { isMobileBinaryPath } from '../../files/mobile-file-kind' -import { isBinaryBuffer } from '../../../../shared/binary-buffer' +import { isBinaryBuffer } from '../../../../shared/file-preview/binary-buffer' import { openLocalTerminalArtifactGrant } from './local-artifact-read' import { assertTerminalArtifactContentUnchanged, diff --git a/src/main/runtime/terminal/artifacts/local-artifact-read.ts b/src/main/runtime/terminal/artifacts/local-artifact-read.ts index d3a59f5fbe0..b5cf18d4c65 100644 --- a/src/main/runtime/terminal/artifacts/local-artifact-read.ts +++ b/src/main/runtime/terminal/artifacts/local-artifact-read.ts @@ -15,12 +15,12 @@ import { TERMINAL_ARTIFACT_CONTENT_BLOCK_BYTES, terminalArtifactContentDigest } from './artifact-integrity' -import { BINARY_PROBE_BYTES, isBinaryBuffer } from '../../../../shared/binary-buffer' +import { BINARY_PROBE_BYTES, isBinaryBuffer } from '../../../../shared/file-preview/binary-buffer' import type { RuntimeFilePreviewResult, RuntimeFileReadChunkResult -} from '../../../../shared/runtime-file-contracts' -import { FONT_FILE_MIME_TYPES } from '../../../../shared/font-file-extensions' +} from '../../../../shared/file-content/runtime-file-read' +import { FONT_FILE_MIME_TYPES } from '../../../../shared/file-preview/font-file-extensions' import { assertFileReadRange, fileRangePage, diff --git a/src/main/runtime/terminal/artifacts/terminal-artifacts.ts b/src/main/runtime/terminal/artifacts/terminal-artifacts.ts index 9b2de84c86c..d03a1b784cf 100644 --- a/src/main/runtime/terminal/artifacts/terminal-artifacts.ts +++ b/src/main/runtime/terminal/artifacts/terminal-artifacts.ts @@ -3,9 +3,9 @@ import { RuntimeTerminalFileGrants, type RuntimeTerminalFileGrantHost } from './ import type { RuntimeFilePreviewResult, RuntimeFileReadChunkResult, - RuntimeFileReadResult, - RuntimeTerminalPathResolution -} from '../../../../shared/runtime-file-contracts' + RuntimeFileReadResult +} from '../../../../shared/file-content/runtime-file-read' +import type { RuntimeTerminalPathResolution } from '../../../../shared/terminal/runtime-terminal-file-path' import { assertTerminalFileGrantFresh, canonicalPathForArtifactComparison, diff --git a/src/main/runtime/terminal/output/terminal-kitty-file-read.ts b/src/main/runtime/terminal/output/terminal-kitty-file-read.ts index 26117529314..b7b1e6939c8 100644 --- a/src/main/runtime/terminal/output/terminal-kitty-file-read.ts +++ b/src/main/runtime/terminal/output/terminal-kitty-file-read.ts @@ -8,7 +8,7 @@ import { toWindowsWslPath, toWindowsWslUncPath } from '../../../../shared/wsl-paths' -import { readNodeFileHandleWithinLimit } from '../../../../shared/node-bounded-file-reader' +import { readNodeFileHandleWithinLimit } from '../../../../shared/file-content/node-bounded-file-reader' import { TERMINAL_KITTY_FILE_MAX_BYTES, type TerminalKittyFileRequest, diff --git a/src/main/runtime/terminal/terminal-path-resolver.ts b/src/main/runtime/terminal/terminal-path-resolver.ts index 41516be4485..b6bc4130ca1 100644 --- a/src/main/runtime/terminal/terminal-path-resolver.ts +++ b/src/main/runtime/terminal/terminal-path-resolver.ts @@ -1,7 +1,5 @@ -import type { - RuntimeNativeChatFileContext, - RuntimeTerminalPathResolution -} from '../../../shared/runtime-file-contracts' +import type { RuntimeNativeChatFileContext } from '../../../shared/native-chat/native-chat-file-context' +import type { RuntimeTerminalPathResolution } from '../../../shared/terminal/runtime-terminal-file-path' import { parseWslPath } from '../../wsl/filesystem/unc-path-access' import { relativePathInsideRoot, resolveRuntimePath } from '../../../shared/cross-platform-path' import { homedir } from 'node:os' @@ -11,7 +9,7 @@ import { isSafeMobileRelativePath } from '../files/mobile-file-kind' import { isENOENT } from '../../ipc/filesystem/access/filesystem-path-containment' import type { RuntimeFileCommandHost } from '../files/file-command-host' import type { RuntimeTerminalArtifacts } from './artifacts/terminal-artifacts' -import { SSH_OUTSIDE_WORKSPACE_UNSUPPORTED_MESSAGE } from '../../../shared/runtime-file-contracts' +import { SSH_OUTSIDE_WORKSPACE_UNSUPPORTED_MESSAGE } from '../../../shared/terminal/runtime-terminal-file-path' type RuntimeTerminalPathHost = Pick< RuntimeFileCommandHost, diff --git a/src/main/runtime/workspaces/known-workspace-file-target.ts b/src/main/runtime/workspaces/known-workspace-file-target.ts index 45d2a0fbdd8..eee409a6701 100644 --- a/src/main/runtime/workspaces/known-workspace-file-target.ts +++ b/src/main/runtime/workspaces/known-workspace-file-target.ts @@ -10,7 +10,7 @@ import { } from '../../../shared/execution-host' import type { ResolvedWorktree } from './catalog/runtime-worktree-path-identity' import { resolveWorktreeHostRouting } from './catalog/worktree-launch-host-repo' -import { findRuntimeWorkspaceFileOwner } from '../../../shared/runtime-workspace-file-owner' +import { findRuntimeWorkspaceFileOwner } from '../../../shared/file-access/runtime-workspace-file-owner' import { RuntimePreallocatedTerminalHandles } from '../terminal/identity/preallocated-terminal-handles' export abstract class OrcaRuntimeWithResolveKnownWorkspaceFileTarget extends RuntimePreallocatedTerminalHandles { protected abstract listResolvedWorktrees( diff --git a/src/main/skills/skill-delete/recovery.ts b/src/main/skills/skill-delete/recovery.ts index b5db565291b..6148c12c0e8 100644 --- a/src/main/skills/skill-delete/recovery.ts +++ b/src/main/skills/skill-delete/recovery.ts @@ -1,6 +1,6 @@ import { rm } from 'node:fs/promises' import { join, posix as pathPosix, win32 as pathWin32 } from 'node:path' -import { readNodeFileWithinLimit } from '../../../shared/node-bounded-file-reader' +import { readNodeFileWithinLimit } from '../../../shared/file-content/node-bounded-file-reader' import { SKILL_DELETE_PLACEMENT_KINDS, type SkillDeletePlacementKind diff --git a/src/main/skills/skill-extraction-recovery.ts b/src/main/skills/skill-extraction-recovery.ts index 684d9137e3a..a5b90e85084 100644 --- a/src/main/skills/skill-extraction-recovery.ts +++ b/src/main/skills/skill-extraction-recovery.ts @@ -1,7 +1,7 @@ import { randomUUID } from 'node:crypto' import { readdir, rm } from 'node:fs/promises' import { basename, dirname, join, resolve } from 'node:path' -import { readNodeFileWithinLimit } from '../../shared/node-bounded-file-reader' +import { readNodeFileWithinLimit } from '../../shared/file-content/node-bounded-file-reader' import { writeSkillStateFile } from './skill-install-provenance' import { nativeSkillInstallFilesystem, diff --git a/src/main/skills/skill-install-recovery.ts b/src/main/skills/skill-install-recovery.ts index 8493b293113..437bbffdc96 100644 --- a/src/main/skills/skill-install-recovery.ts +++ b/src/main/skills/skill-install-recovery.ts @@ -1,6 +1,6 @@ import { lstat, rm } from 'node:fs/promises' import { basename, dirname, join, resolve } from 'node:path' -import { readNodeFileWithinLimit } from '../../shared/node-bounded-file-reader' +import { readNodeFileWithinLimit } from '../../shared/file-content/node-bounded-file-reader' import { skillInstallStateKey, writeSkillInstallReceipt, diff --git a/src/main/skills/skill-placement-recovery-journal.ts b/src/main/skills/skill-placement-recovery-journal.ts index fb83973218f..13760a923f5 100644 --- a/src/main/skills/skill-placement-recovery-journal.ts +++ b/src/main/skills/skill-placement-recovery-journal.ts @@ -1,6 +1,6 @@ import { basename, dirname, isAbsolute, join, resolve } from 'node:path' import { isSkillInstallProviderId } from '../../shared/skill-install-providers' -import { readNodeFileWithinLimit } from '../../shared/node-bounded-file-reader' +import { readNodeFileWithinLimit } from '../../shared/file-content/node-bounded-file-reader' import type { SkillInstalledFileMode } from './skill-install-filesystem' import { skillInstallStateKey, type SkillInstallReceiptV1 } from './skill-install-provenance' import { diff --git a/src/main/skills/skill-remove-recovery.ts b/src/main/skills/skill-remove-recovery.ts index 4f4bcf401d0..a6fb8a88ac6 100644 --- a/src/main/skills/skill-remove-recovery.ts +++ b/src/main/skills/skill-remove-recovery.ts @@ -5,7 +5,7 @@ import { normalizedSkillPath, skillPathInside } from '../../shared/skill-path-containment' -import { readNodeFileWithinLimit } from '../../shared/node-bounded-file-reader' +import { readNodeFileWithinLimit } from '../../shared/file-content/node-bounded-file-reader' import type { SkillPlacementResult } from '../../shared/skill-install-contract' import type { SkillInstallFilesystem } from './skill-install-filesystem' import { nativeSkillInstallFilesystem } from './skill-install-filesystem' diff --git a/src/main/skills/skill-transaction-startup-recovery.ts b/src/main/skills/skill-transaction-startup-recovery.ts index 96587865da7..a8c2d15a4ca 100644 --- a/src/main/skills/skill-transaction-startup-recovery.ts +++ b/src/main/skills/skill-transaction-startup-recovery.ts @@ -1,6 +1,6 @@ import { readdir } from 'node:fs/promises' import { dirname, join } from 'node:path' -import { readNodeFileWithinLimit } from '../../shared/node-bounded-file-reader' +import { readNodeFileWithinLimit } from '../../shared/file-content/node-bounded-file-reader' import { acquireSkillInstallLock, reclaimDeadSkillInstallLocks, diff --git a/src/main/ssh/orcad-held-fence-tokens.ts b/src/main/ssh/orcad-held-fence-tokens.ts index f24f4eb3f1a..2abd9920991 100644 --- a/src/main/ssh/orcad-held-fence-tokens.ts +++ b/src/main/ssh/orcad-held-fence-tokens.ts @@ -2,7 +2,7 @@ import { readFileSync } from 'node:fs' import { hostname, uptime } from 'node:os' import { dirname, join } from 'node:path' -import { writeDurableSecureJsonFile } from '../../shared/secure-file' +import { writeDurableSecureJsonFile } from '../../shared/secure-storage/secure-file' export const ORCAD_HELD_FENCE_TOKENS_FILE_NAME = 'orcad-held-fence-tokens.json' // Older entries are leaks from releases never confirmed; the fence went stale long ago anyway. diff --git a/src/main/ssh/ssh-identity-file-read.ts b/src/main/ssh/ssh-identity-file-read.ts index 418bcc3a9fa..18eb7596266 100644 --- a/src/main/ssh/ssh-identity-file-read.ts +++ b/src/main/ssh/ssh-identity-file-read.ts @@ -3,7 +3,7 @@ import { NodeFileReadTooLargeError, readNodeFileSyncWithinLimit, readNodeFileWithinLimit -} from '../../shared/node-bounded-file-reader' +} from '../../shared/file-content/node-bounded-file-reader' import { MAX_SSH_IDENTITY_FILE_BYTES } from './ssh-security-key-identity' /** `problem` is null when the file is simply absent, which is normal for default key paths. */ diff --git a/src/main/ssh/ssh-remote-directory-browse.ts b/src/main/ssh/ssh-remote-directory-browse.ts index 8b377876cf3..08ae3f0de3a 100644 --- a/src/main/ssh/ssh-remote-directory-browse.ts +++ b/src/main/ssh/ssh-remote-directory-browse.ts @@ -3,8 +3,8 @@ import type { SshConnectionManager } from './connection/ssh-connection-manager' import type { SshExecOptions } from './connection/ssh-exec-options' import { powerShellCommand } from './ssh-remote-powershell' import { quotePowerShellLiteral as powerShellLiteral } from '../../shared/powershell-native-argument' -import type { FilesystemPathFlavor } from '../../shared/filesystem-entry-types' -import { sortDirEntries } from '../../shared/file-name-sort' +import type { FilesystemPathFlavor } from '../../shared/file-access/filesystem-path-flavor' +import { sortDirEntries } from '../../shared/file-listing/file-name-sort' import { buildPosixStdoutFence } from '../../shared/posix-stdout-fence' type RemoteDirEntry = { diff --git a/src/main/startup/http1-compatibility-marker.ts b/src/main/startup/http1-compatibility-marker.ts index 2ad797cf3a4..54da41194e9 100644 --- a/src/main/startup/http1-compatibility-marker.ts +++ b/src/main/startup/http1-compatibility-marker.ts @@ -1,7 +1,7 @@ import { readFileSync, rmSync } from 'node:fs' import { join } from 'node:path' import { durableWriteTempPath, writeFileDurableSync } from '../filesystem/durable-file-write' -import { bestEffortFsyncDirectorySync } from '../../shared/secure-file' +import { bestEffortFsyncDirectorySync } from '../../shared/secure-storage/secure-file' /** A tiny profile-scoped marker selects HTTP/2 before the first Electron session without reparsing multi-MB settings before Store startup. Profile identity prevents cross-profile reuse. */ diff --git a/src/main/startup/main-process-runtime-service.ts b/src/main/startup/main-process-runtime-service.ts index ddcc494e8ae..0fdc6b502a9 100644 --- a/src/main/startup/main-process-runtime-service.ts +++ b/src/main/startup/main-process-runtime-service.ts @@ -44,7 +44,7 @@ import { resolveHostAgentBaseEnvironment } from '../runtime/agent-session/enviro import type { RuntimeDesktopWindowStatus } from '../../shared/runtime-types' import { ArtifactCloudService } from '../artifacts/artifact-cloud-service' import { SkillCloudService } from '../skills/skill-cloud-service' -import { isArtifactSharingEnabled } from '../../shared/artifact-sharing-gate' +import { isArtifactSharingEnabled } from '../../shared/artifacts/artifact-sharing-gate' import { AgentStatusObservedPaneIdentities, recordObservedAgentStatusPaneIdentity diff --git a/src/main/startup/os-opened-documents.ts b/src/main/startup/os-opened-documents.ts index 4f3bd4a4f91..1e8287d02a9 100644 --- a/src/main/startup/os-opened-documents.ts +++ b/src/main/startup/os-opened-documents.ts @@ -1,12 +1,12 @@ import { stat } from 'node:fs/promises' import path from 'node:path' import { fileURLToPath } from 'node:url' -import type { FileDocument } from '../../shared/filesystem-entry-types' +import type { FileDocument } from '../../shared/file-listing/file-document' import { ensureDefaultFloatingWorkspacePath } from '../ipc/floating-workspace-directory' import { fileDocumentFromFilePath, isMarkdownDocumentName -} from '../../shared/markdown-document-paths' +} from '../../shared/file-listing/markdown-document-paths' export function isOsOpenedDocumentName(name: string): boolean { const extension = path.extname(name).toLowerCase() diff --git a/src/main/window/checked-drag-temp-source.ts b/src/main/window/checked-drag-temp-source.ts index bdc85ca4e81..79a0a0f049b 100644 --- a/src/main/window/checked-drag-temp-source.ts +++ b/src/main/window/checked-drag-temp-source.ts @@ -3,8 +3,8 @@ import { lstat, mkdtemp, rm, writeFile, type FileHandle } from 'node:fs/promises import { basename, join } from 'node:path' import { pipeline } from 'node:stream/promises' import { AGENT_SESSION_ATTACHMENT_MAX_BYTES } from '../../shared/agent-session/agent-session-attachments' -import type { NativeFileDropCopyFailureReason } from '../../shared/native-file-drop' -import { readNodeFileHandleWithinLimit } from '../../shared/node-bounded-file-reader' +import type { NativeFileDropCopyFailureReason } from '../../shared/file-import/native-file-drop' +import { readNodeFileHandleWithinLimit } from '../../shared/file-content/node-bounded-file-reader' import type { DragTempCopyBatch, DragTempCopyEnvironment, diff --git a/src/main/window/clipboard-native-image.ts b/src/main/window/clipboard-native-image.ts index 47570035afc..b93b8273478 100644 --- a/src/main/window/clipboard-native-image.ts +++ b/src/main/window/clipboard-native-image.ts @@ -3,7 +3,7 @@ import { assertClipboardImageByteLengthWithinLimit, assertClipboardImageDimensionsWithinLimit } from '../../shared/clipboard-image' -import { readRasterImageDimensions } from '../../shared/raster-image-dimensions' +import { readRasterImageDimensions } from '../../shared/file-preview/raster-image-dimensions' export function readClipboardNativeImage(): NativeImage { const image = clipboard.readImage() diff --git a/src/main/window/desktop-integration/custom-app-icon.ts b/src/main/window/desktop-integration/custom-app-icon.ts index 2580b722f71..c6baecb98ed 100644 --- a/src/main/window/desktop-integration/custom-app-icon.ts +++ b/src/main/window/desktop-integration/custom-app-icon.ts @@ -9,7 +9,7 @@ import { type CustomAppIconImportFailureCode, type CustomAppIconImportResult } from '../../../shared/app-icon' -import { readRasterImageDimensions } from '../../../shared/raster-image-dimensions' +import { readRasterImageDimensions } from '../../../shared/file-preview/raster-image-dimensions' import { getCanonicalUserDataPath } from '../../persistence/loading-store/user-data-path' // Why: 1024px covers the largest Dock and taskbar tiles; larger images only cost memory on every apply. diff --git a/src/main/window/dragged-temp-file-copy.ts b/src/main/window/dragged-temp-file-copy.ts index 1047d3bea8d..c21519fb377 100644 --- a/src/main/window/dragged-temp-file-copy.ts +++ b/src/main/window/dragged-temp-file-copy.ts @@ -1,7 +1,7 @@ import { constants, type Stats } from 'node:fs' import { lstat, open, realpath, rm } from 'node:fs/promises' import { basename, resolve } from 'node:path' -import type { NativeFileDropCopyFailureReason } from '../../shared/native-file-drop' +import type { NativeFileDropCopyFailureReason } from '../../shared/file-import/native-file-drop' import { formatByteCeiling, REMOTE_IMPORT_MAX_FILE_BYTES, diff --git a/src/main/window/dropped-path-preparation-ipc.ts b/src/main/window/dropped-path-preparation-ipc.ts index cf7f0ddc9ea..92e5c558c45 100644 --- a/src/main/window/dropped-path-preparation-ipc.ts +++ b/src/main/window/dropped-path-preparation-ipc.ts @@ -2,11 +2,11 @@ import { app, ipcMain, type BrowserWindow } from 'electron' import { createRejectedNativeFileDropPayload, validateNativeFileDropPaths -} from '../../shared/native-file-drop' +} from '../../shared/file-import/native-file-drop' import type { PrepareDroppedPathsRequest, PreparedDroppedPaths -} from '../../shared/native-file-drop-preparation' +} from '../../shared/file-import/native-file-drop-preparation' import { abortWhenRendererGone } from '../ipc/renderer-lifetime-abort' import { getDragTempCopyRoot } from './dragged-temp-file-copy' import { diff --git a/src/main/window/dropped-path-preparation.ts b/src/main/window/dropped-path-preparation.ts index dd67bff123e..2e98806c196 100644 --- a/src/main/window/dropped-path-preparation.ts +++ b/src/main/window/dropped-path-preparation.ts @@ -1,11 +1,11 @@ import { AGENT_SESSION_ATTACHMENT_MAX_BYTES } from '../../shared/agent-session/agent-session-attachments' import { basename } from 'node:path' import type { AgentSessionAttachmentStore } from '../native-chat/agent-session-attachments/agent-session-attachment-store' -import type { NativeFileDropCopyFailureReason } from '../../shared/native-file-drop' +import type { NativeFileDropCopyFailureReason } from '../../shared/file-import/native-file-drop' import type { PrepareDroppedPathsRequest, PreparedDroppedPaths -} from '../../shared/native-file-drop-preparation' +} from '../../shared/file-import/native-file-drop-preparation' import { DragTempCopyBatch, closeDragTempSource, diff --git a/src/main/window/main-window-webview-security.ts b/src/main/window/main-window-webview-security.ts index ac9ddaf0014..7d3ca780af4 100644 --- a/src/main/window/main-window-webview-security.ts +++ b/src/main/window/main-window-webview-security.ts @@ -13,7 +13,10 @@ import { browserRouteWebContentsRegistry } from '../browser/routing/sessions/browser-route-session-runtime' import { ORCA_BROWSER_BLANK_URL } from '../../shared/constants' -import { DOC_PREVIEW_PARTITION, parseDocPreviewUrl } from '../../shared/doc-preview-scheme' +import { + DOC_PREVIEW_PARTITION, + parseDocPreviewUrl +} from '../../shared/document-preview/doc-preview-scheme' import { setDocPreviewFailureSink } from '../browser/document-preview/doc-preview-failure-notice' import { getDocPreviewGrant, diff --git a/src/main/wsl/host-lifecycle/wsl-host-kept-for-peers.ts b/src/main/wsl/host-lifecycle/wsl-host-kept-for-peers.ts index 37797f54597..3d64be5adb7 100644 --- a/src/main/wsl/host-lifecycle/wsl-host-kept-for-peers.ts +++ b/src/main/wsl/host-lifecycle/wsl-host-kept-for-peers.ts @@ -4,8 +4,8 @@ */ import { join } from 'node:path' import { z } from 'zod' -import { writeSecureJsonFileWithinLimit } from '../../../shared/bounded-secure-json-file' -import { readNodeFileSyncWithinLimit } from '../../../shared/node-bounded-file-reader' +import { writeSecureJsonFileWithinLimit } from '../../../shared/secure-storage/bounded-secure-json-file' +import { readNodeFileSyncWithinLimit } from '../../../shared/file-content/node-bounded-file-reader' const KEPT_FILE = 'orca-wsl-hosts-kept-for-peers.json' const MAX_KEPT_FILE_BYTES = 64 * 1024 diff --git a/src/main/wsl/host-lifecycle/wsl-hosts-policy-live-update.ts b/src/main/wsl/host-lifecycle/wsl-hosts-policy-live-update.ts index f09695512bb..b9dea46a8c7 100644 --- a/src/main/wsl/host-lifecycle/wsl-hosts-policy-live-update.ts +++ b/src/main/wsl/host-lifecycle/wsl-hosts-policy-live-update.ts @@ -1,7 +1,7 @@ import { join } from 'node:path' import { getAppEnvironment } from '../../../shared/app-environment' import { readFetchResponseTextWithinLimit } from '../../../shared/fetch-response-body' -import { readNodeFileSyncWithinLimit } from '../../../shared/node-bounded-file-reader' +import { readNodeFileSyncWithinLimit } from '../../../shared/file-content/node-bounded-file-reader' import { getVersionChannel, MAIN_RELEASE_REPO } from '../../../shared/release-channel' import { isWslHostsInternalGateOpen } from '../../../shared/wsl-host-internal-gate' import { diff --git a/src/main/zcode/zcode-plan-api-key-store-native-windows.test.ts b/src/main/zcode/zcode-plan-api-key-store-native-windows.test.ts deleted file mode 100644 index a0b6ac9dab5..00000000000 --- a/src/main/zcode/zcode-plan-api-key-store-native-windows.test.ts +++ /dev/null @@ -1,147 +0,0 @@ -import * as fs from 'node:fs' -import * as os from 'node:os' -import { join } from 'node:path' -import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest' -import { setSecretStore } from '../../shared/secret-store' -import type * as WindowsAcl from '../../shared/secure-path-windows-acl' -import type * as Store from './zcode-plan-api-key-store' - -type NativeCase = { - home: string - fault: 'none' | 'before-restore' | 'after-restore' | 'competing' - reject: boolean - writes: number - renames: number - stages: number - nativeOutcomes: boolean[] - directories: boolean[] -} -const state = vi.hoisted((): NativeCase => ({ - home: '', - fault: 'none', - reject: false, - writes: 0, - renames: 0, - stages: 0, - nativeOutcomes: [], - directories: [] -})) -beforeEach(() => - setSecretStore({ - isEncryptionAvailable: () => false, - encryptString: () => { - throw new Error('unavailable') - }, - decryptString: () => { - throw new Error('unavailable') - }, - describeProtectionGap: () => 'unavailable' - }) -) -vi.mock('node:os', async (original) => ({ - ...(await original()), - homedir: () => state.home -})) -vi.mock('node:fs', async (original) => { - const real = await original() - return { - ...real, - renameSync: (...args: Parameters) => { - real.renameSync(...args) - if (++state.renames === 2 && state.fault === 'after-restore') { - throw new Error('Synthetic failure after restore publication') - } - } - } -}) -vi.mock('../../shared/secure-path-windows-acl', async (original) => { - const real = await original() - const files = await vi.importActual('node:fs') - return { - ...real, - writeRestrictedWindowsFile: (path: string, contents: string) => { - if (++state.writes === 2 && state.fault === 'before-restore') { - throw new Error('Synthetic restore staging failure') - } - const outcome = real.writeRestrictedWindowsFile(path, contents) - state.nativeOutcomes.push(outcome) - if (state.fault === 'competing' && ++state.stages === 2) { - const competing = join(state.home, '.orca', 'competing-key') - expect(real.writeRestrictedWindowsFile(competing, envelope('synthetic-competing'))).toBe( - true - ) - files.renameSync(competing, join(state.home, '.orca', 'zcode-plan-api-key.enc')) - } - return state.reject ? false : outcome - }, - restrictWindowsDirectory: (path: string) => - real.restrictWindowsDirectory(path).then((restricted) => { - state.directories.push(restricted) - return restricted - }) - } -}) - -const envelope = (key: string) => - `orca-zcode-plan-api-key:v1:plaintext:${Buffer.from(key).toString('base64')}` -let store: typeof Store -let keyPath: string - -describe.skipIf(process.platform !== 'win32')('native Windows Coding Plan rollback', () => { - beforeEach(async () => { - state.home = fs.mkdtempSync(join(os.tmpdir(), 'orca-native-plan-')) - state.fault = 'none' - state.reject = false - state.writes = 0 - state.renames = 0 - state.stages = 0 - state.nativeOutcomes = [] - state.directories = [] - keyPath = join(state.home, '.orca', 'zcode-plan-api-key.enc') - vi.spyOn(console, 'warn').mockImplementation(() => undefined) - vi.resetModules() - store = await import('./zcode-plan-api-key-store') - store.saveZcodePlanApiKey('synthetic-previous') - expect(fs.readFileSync(keyPath, 'utf8')).toBe(envelope('synthetic-previous')) - expect(state.nativeOutcomes.length).toBeGreaterThan(0) - expect(state.nativeOutcomes.every(Boolean)).toBe(true) - await vi.waitFor( - () => { - expect(state.directories.length).toBeGreaterThan(0) - expect(state.directories.every(Boolean)).toBe(true) - }, - { timeout: 15_000 } - ) - state.writes = 0 - state.renames = 0 - state.stages = 0 - state.reject = true - }) - - afterEach(() => { - vi.restoreAllMocks() - fs.rmSync(state.home, { recursive: true, force: true }) - }) - - it.each(['before-restore', 'after-restore', 'competing'] as const)( - 'preserves the file contract after %s with real file and directory ACLs', - (fault) => { - state.fault = fault - expect(() => store.saveZcodePlanApiKey('synthetic-rejected')).toThrow( - 'could not be stored securely' - ) - if (fault === 'before-restore') { - expect(fs.existsSync(keyPath)).toBe(false) - } else { - expect(fs.readFileSync(keyPath, 'utf8')).toBe( - envelope(fault === 'competing' ? 'synthetic-competing' : 'synthetic-previous') - ) - } - expect(fs.readdirSync(join(state.home, '.orca')).some((name) => name.endsWith('.tmp'))).toBe( - false - ) - expect(state.nativeOutcomes.every(Boolean)).toBe(true) - }, - 30_000 - ) -}) diff --git a/src/main/zcode/zcode-plan-api-key-store-plaintext-rollback.test.ts b/src/main/zcode/zcode-plan-api-key-store-plaintext-rollback.test.ts index 03e360b2f84..39bbaac7946 100644 --- a/src/main/zcode/zcode-plan-api-key-store-plaintext-rollback.test.ts +++ b/src/main/zcode/zcode-plan-api-key-store-plaintext-rollback.test.ts @@ -3,7 +3,7 @@ import * as os from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { setSecretStore } from '../../shared/secret-store' -import type * as SecureFile from '../../shared/secure-file' +import type * as SecureFile from '../../shared/secure-storage/secure-file' import type * as ZcodePlanApiKeyStore from './zcode-plan-api-key-store' const mocks = vi.hoisted(() => ({ @@ -35,7 +35,7 @@ vi.mock('node:fs', async (original) => ({ renameSync: mocks.rename })) // Stage through mocked writeFile and inject restriction outcome like the born-restricted creator. -vi.mock('../../shared/secure-path-windows-acl', () => ({ +vi.mock('../../shared/secure-storage/secure-path-windows-acl', () => ({ restrictWindowsPathSync: mocks.restrict, writeRestrictedWindowsFile: (path: string, contents: string) => { mocks.write(path, contents, { encoding: 'utf-8', mode: 0o600 }) @@ -63,7 +63,7 @@ beforeEach(async () => { Object.defineProperty(process, 'platform', { value: 'win32', configurable: true }) vi.resetModules() store = await import('./zcode-plan-api-key-store') - writer = await import('../../shared/secure-file') + writer = await import('../../shared/secure-storage/secure-file') }) afterEach(() => { @@ -79,20 +79,6 @@ function rejectReplacement(): void { } describe('plaintext rollback through the secure-file writer', () => { - it('removes only the rejected replacement when rollback fails before publication', () => { - realFs.writeFileSync(keyPath, envelope('previous-key')) - mocks.write.mockImplementationOnce(realFs.writeFileSync).mockImplementationOnce(() => { - throw new Error('Synthetic rollback staging failure') - }) - - rejectReplacement() - - expect(mocks.write).toHaveBeenCalledTimes(2) - expect(realFs.existsSync(keyPath)).toBe(false) - expect(store.readZcodePlanApiKey()).toBeNull() - expect(realFs.readdirSync(join(mocks.home, '.orca'))).toEqual([]) - }) - // Rename preserves staged DACL; later read-time hardening failure must not erase the restored key. it.each(['restriction-false', 'restriction-throws'])( 'keeps the previous envelope if rollback publishes before %s', @@ -116,35 +102,6 @@ describe('plaintext rollback through the secure-file writer', () => { } ) - it.each([ - { phase: 'before-rollback', previous: true }, - { phase: 'before-rollback', previous: false }, - { phase: 'during-rollback', previous: true } - ])( - 'preserves a different envelope written $phase with previous key $previous', - ({ phase, previous }) => { - if (previous) { - realFs.writeFileSync(keyPath, envelope('previous-key')) - } - if (phase === 'before-rollback') { - mocks.rename.mockImplementationOnce((from, to) => { - realFs.renameSync(from, to) - realFs.writeFileSync(keyPath, envelope('other-writer-key')) - }) - } else { - mocks.write.mockImplementationOnce(realFs.writeFileSync).mockImplementationOnce(() => { - realFs.writeFileSync(keyPath, envelope('other-writer-key')) - throw new Error('Synthetic competing rollback writer') - }) - } - - rejectReplacement() - - expect(realFs.readFileSync(keyPath, 'utf8')).toBe(envelope('other-writer-key')) - expect(store.readZcodePlanApiKey()).toBe('other-writer-key') - } - ) - it('retains an identical previous plaintext envelope when retry rollback cannot publish', () => { realFs.writeFileSync(keyPath, envelope('new-key')) mocks.write.mockImplementationOnce(realFs.writeFileSync).mockImplementationOnce(() => { @@ -178,62 +135,6 @@ describe('plaintext rollback through the secure-file writer', () => { }) describe('conditional rollback publication through the real writer', () => { - it.each([false, true])( - 'preserves a competing envelope during rollback staging with restriction %s', - (restricted) => { - realFs.writeFileSync(keyPath, envelope('previous-key')) - mocks.restrict.mockImplementation((path) => { - if (path.endsWith('.tmp') && mocks.write.mock.calls.length === 2) { - realFs.writeFileSync(keyPath, envelope('other-writer-key')) - return restricted - } - return false - }) - - rejectReplacement() - - expect(realFs.readFileSync(keyPath, 'utf8')).toBe(envelope('other-writer-key')) - expect(store.readZcodePlanApiKey()).toBe('other-writer-key') - expect(mocks.rename).toHaveBeenCalledTimes(1) - expect(realFs.readdirSync(join(mocks.home, '.orca'))).toEqual(['zcode-plan-api-key.enc']) - } - ) - - it('keeps the cached previous key when a competing staged rollback cancels publication', () => { - realFs.writeFileSync(keyPath, envelope('previous-key')) - expect(store.readZcodePlanApiKey()).toBe('previous-key') - mocks.restrict.mockImplementation((path) => { - if (path.endsWith('.tmp') && mocks.write.mock.calls.length === 2) { - realFs.writeFileSync(keyPath, envelope('other-writer-key')) - } - return false - }) - - rejectReplacement() - - expect(realFs.readFileSync(keyPath, 'utf8')).toBe(envelope('other-writer-key')) - expect(store.readZcodePlanApiKey()).toBe('previous-key') - expect(mocks.rename).toHaveBeenCalledTimes(1) - }) - - it('preserves an unowned envelope if rollback staging restriction throws', () => { - realFs.writeFileSync(keyPath, envelope('previous-key')) - mocks.restrict.mockImplementation((path) => { - if (path.endsWith('.tmp') && mocks.write.mock.calls.length === 2) { - realFs.writeFileSync(keyPath, envelope('other-writer-key')) - throw new Error('Synthetic staged restriction failure') - } - return false - }) - - rejectReplacement() - - expect(realFs.readFileSync(keyPath, 'utf8')).toBe(envelope('other-writer-key')) - expect(store.readZcodePlanApiKey()).toBe('other-writer-key') - expect(mocks.rename).toHaveBeenCalledTimes(1) - expect(realFs.readdirSync(join(mocks.home, '.orca'))).toEqual(['zcode-plan-api-key.enc']) - }) - it('removes only the owned rejected plaintext when rollback rename fails', () => { realFs.writeFileSync(keyPath, envelope('previous-key')) mocks.rename.mockImplementationOnce(realFs.renameSync).mockImplementationOnce(() => { @@ -247,33 +148,6 @@ describe('conditional rollback publication through the real writer', () => { expect(realFs.readdirSync(join(mocks.home, '.orca'))).toEqual([]) }) - it.each([false, true])( - 'cancels guarded durable publication without changing a previously present target: %s', - (previous) => { - if (previous) { - realFs.writeFileSync(keyPath, envelope('previous-key')) - } - const shouldPublish = vi.fn(() => false) - - expect( - writer.writeSecureFile(keyPath, envelope('candidate-key'), { - durable: true, - shouldPublish - }) - ).toBe(false) - - expect(shouldPublish).toHaveBeenCalledTimes(1) - expect(mocks.rename).not.toHaveBeenCalled() - expect(realFs.existsSync(keyPath)).toBe(previous) - expect(realFs.readdirSync(join(mocks.home, '.orca'))).toEqual( - previous ? ['zcode-plan-api-key.enc'] : [] - ) - if (previous) { - expect(realFs.readFileSync(keyPath, 'utf8')).toBe(envelope('previous-key')) - } - } - ) - it('cleans staged bytes when the publication predicate throws', () => { realFs.writeFileSync(keyPath, envelope('previous-key')) diff --git a/src/main/zcode/zcode-plan-api-key-store-publication-race.test.ts b/src/main/zcode/zcode-plan-api-key-store-publication-race.test.ts deleted file mode 100644 index 73cf2ec53b0..00000000000 --- a/src/main/zcode/zcode-plan-api-key-store-publication-race.test.ts +++ /dev/null @@ -1,164 +0,0 @@ -import { - existsSync, - mkdirSync, - mkdtempSync, - readFileSync, - readdirSync, - renameSync, - rmSync, - writeFileSync -} from 'node:fs' -import { homedir, tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { setSecretStore } from '../../shared/secret-store' -import type * as Fs from 'node:fs' -import type * as SecureFile from '../../shared/secure-file' -import type * as ZcodePlanApiKeyStore from './zcode-plan-api-key-store' - -const restriction = vi.hoisted(() => vi.fn((_path: string, _directory: boolean) => false)) - -beforeEach(() => - setSecretStore({ - isEncryptionAvailable: () => false, - encryptString: () => { - throw new Error('unavailable') - }, - decryptString: () => { - throw new Error('unavailable') - }, - describeProtectionGap: () => 'unavailable' - }) -) -// Stage real bytes and inject the born-restricted creator's restriction outcome. -vi.mock('../../shared/secure-path-windows-acl', async () => { - const { writeFileSync: stage } = await vi.importActual('node:fs') - return { - restrictWindowsPathSync: restriction, - writeRestrictedWindowsFile: (path: string, contents: string) => { - stage(path, contents, { encoding: 'utf-8', mode: 0o600 }) - return restriction(path, false) - }, - restrictWindowsDirectory: () => Promise.resolve(false) - } -}) - -const platformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform')! -const envelope = (key: string): string => - `orca-zcode-plan-api-key:v1:plaintext:${Buffer.from(key).toString('base64')}` -const previousEnvelope = envelope('previous-key') -const competingEnvelope = envelope('competing-key') -let caseHome: string -let keyPath: string -let store: typeof ZcodePlanApiKeyStore -let writer: typeof SecureFile - -beforeEach(async () => { - caseHome = mkdtempSync(join(tmpdir(), 'orca-rollback-publication-')) - vi.stubEnv('HOME', caseHome) - vi.stubEnv('USERPROFILE', caseHome) - keyPath = join(caseHome, '.orca', 'zcode-plan-api-key.enc') - mkdirSync(join(caseHome, '.orca')) - restriction.mockReset().mockReturnValue(false) - vi.spyOn(console, 'warn').mockImplementation(() => undefined) - Object.defineProperty(process, 'platform', { value: 'win32', configurable: true }) - vi.resetModules() - expect(homedir()).toBe(caseHome) - store = await import('./zcode-plan-api-key-store') - writer = await import('../../shared/secure-file') - expect(vi.isMockFunction(writer.writeSecureFile)).toBe(false) - expect(vi.isMockFunction(writeFileSync)).toBe(false) - expect(vi.isMockFunction(renameSync)).toBe(false) -}) - -afterEach(() => { - Object.defineProperty(process, 'platform', platformDescriptor) - vi.unstubAllEnvs() - vi.restoreAllMocks() - rmSync(caseHome, { recursive: true, force: true }) -}) - -function publishDuringRollbackStaging(outcome: boolean | 'throws'): void { - let stagedRestrictions = 0 - restriction.mockImplementation((targetPath) => { - if (targetPath.endsWith('.tmp') && ++stagedRestrictions === 2) { - const competingPath = join(caseHome, '.orca', 'competing-envelope') - writeFileSync(competingPath, competingEnvelope) - renameSync(competingPath, keyPath) - if (outcome === 'throws') { - throw new Error('Synthetic rollback staged ACL failure') - } - return outcome - } - return false - }) -} - -function refuseReplacement(): void { - expect(() => store.saveZcodePlanApiKey('attempted-key')).toThrow( - 'could not be stored securely on this device' - ) -} - -describe('rollback publication with real filesystem writes and renames', () => { - it.each([false, true, 'throws'] as const)( - 'preserves the competing publication when the second staged ACL call returns %s', - (outcome) => { - writeFileSync(keyPath, previousEnvelope) - publishDuringRollbackStaging(outcome) - - refuseReplacement() - - expect(readFileSync(keyPath, 'utf8')).toBe(competingEnvelope) - expect(readFileSync(keyPath, 'utf8')).not.toBe(envelope('attempted-key')) - expect(store.readZcodePlanApiKey()).toBe('competing-key') - expect(readdirSync(join(caseHome, '.orca'))).toEqual(['zcode-plan-api-key.enc']) - } - ) - - it('restores the previous envelope when the attempted publication is still owned', () => { - writeFileSync(keyPath, previousEnvelope) - - refuseReplacement() - - expect(readFileSync(keyPath, 'utf8')).toBe(previousEnvelope) - expect(store.readZcodePlanApiKey()).toBe('previous-key') - expect(readdirSync(join(caseHome, '.orca'))).toEqual(['zcode-plan-api-key.enc']) - }) - - it('removes the owned rejected plaintext when no previous envelope exists', () => { - refuseReplacement() - - expect(existsSync(keyPath)).toBe(false) - expect(store.readZcodePlanApiKey()).toBeNull() - expect(readdirSync(join(caseHome, '.orca'))).toEqual([]) - }) - - it.each([false, true])( - 'retains the prior target state when initial staged hardening throws: previous %s', - (previous) => { - if (previous) { - writeFileSync(keyPath, previousEnvelope) - } - restriction.mockImplementation((targetPath) => { - if (targetPath.endsWith('.tmp')) { - throw new Error('Synthetic initial staged ACL failure') - } - return false - }) - - expect(() => store.saveZcodePlanApiKey('attempted-key')).toThrow( - 'Synthetic initial staged ACL failure' - ) - - expect(existsSync(keyPath)).toBe(previous) - expect(store.readZcodePlanApiKey()).toBe(previous ? 'previous-key' : null) - expect(readdirSync(join(caseHome, '.orca'))).toEqual( - previous ? ['zcode-plan-api-key.enc'] : [] - ) - if (previous) { - expect(readFileSync(keyPath, 'utf8')).toBe(previousEnvelope) - } - } - ) -}) diff --git a/src/main/zcode/zcode-plan-api-key-store.test.ts b/src/main/zcode/zcode-plan-api-key-store.test.ts index 0c5e27bcdec..292854ab658 100644 --- a/src/main/zcode/zcode-plan-api-key-store.test.ts +++ b/src/main/zcode/zcode-plan-api-key-store.test.ts @@ -31,7 +31,7 @@ vi.mock('node:path', () => ({ join: (...parts: string[]) => parts.join('/') })) -vi.mock('../../shared/secure-file', () => ({ +vi.mock('../../shared/secure-storage/secure-file', () => ({ hardenExistingSecureFile: hardenExistingSecureFileMock, writeSecureFile: writeSecureFileMock })) diff --git a/src/main/zcode/zcode-plan-api-key-store.ts b/src/main/zcode/zcode-plan-api-key-store.ts index 62ef14552e8..f839aeb82ac 100644 --- a/src/main/zcode/zcode-plan-api-key-store.ts +++ b/src/main/zcode/zcode-plan-api-key-store.ts @@ -2,7 +2,7 @@ import { getSecretStore } from '../../shared/secret-store' import { existsSync, readFileSync, rmSync } from 'node:fs' import { homedir } from 'node:os' import { join } from 'node:path' -import { hardenExistingSecureFile, writeSecureFile } from '../../shared/secure-file' +import { hardenExistingSecureFile, writeSecureFile } from '../../shared/secure-storage/secure-file' import type { SecretAtRestProtection } from '../../shared/secret-at-rest-protection' const ZCODE_PLAN_API_KEY_FILE = 'zcode-plan-api-key.enc' diff --git a/src/main/zcode/zcode-v2-plan-credentials.ts b/src/main/zcode/zcode-v2-plan-credentials.ts index fa552888ff1..d2b3f890236 100644 --- a/src/main/zcode/zcode-v2-plan-credentials.ts +++ b/src/main/zcode/zcode-v2-plan-credentials.ts @@ -2,7 +2,7 @@ import { createDecipheriv, createHash } from 'node:crypto' import { homedir, platform, userInfo } from 'node:os' import { join, resolve } from 'node:path' import { z } from 'zod' -import { readNodeFileSyncWithinLimit } from '../../shared/node-bounded-file-reader' +import { readNodeFileSyncWithinLimit } from '../../shared/file-content/node-bounded-file-reader' import { ZCODE_PLAN_SITE_BASE_URLS } from '../../shared/zcode-plan-sites' import { readSupportedZcodeV2Selection } from './zcode-v2-personal-overlay' diff --git a/src/preload/api/app-api.ts b/src/preload/api/app-api.ts index d1794fc923a..b82c6a8e054 100644 --- a/src/preload/api/app-api.ts +++ b/src/preload/api/app-api.ts @@ -9,7 +9,7 @@ import type { WriteTerminalRenderDesyncEvidenceResult } from '../../shared/terminal/diagnostics/terminal-render-desync-evidence' import type { MacCapturedDigitRowChord } from '../../shared/macos-symbolic-hotkeys' -import type { MarkdownDocument } from '../../shared/filesystem-entry-types' +import type { MarkdownDocument } from '../../shared/file-listing/file-document' import type { PersistedUIState } from '../../shared/persisted-ui-state-types' import type { FloatingTerminalCwdRequest } from '../../shared/ui-chrome-types' import type { WorkspaceSessionState } from '../../shared/workspace-session/workspace-session-state-types' diff --git a/src/preload/api/app-bridge.ts b/src/preload/api/app-bridge.ts index 113f18603d1..b7d3f3d73bb 100644 --- a/src/preload/api/app-bridge.ts +++ b/src/preload/api/app-bridge.ts @@ -3,7 +3,7 @@ import type { AppIdentity } from '../../shared/app-identity' import type { MacosUpgradeSupport } from '../../shared/macos-upgrade-support' import type { FloatingTerminalCwdRequest } from '../../shared/ui-chrome-types' import type { MacCapturedDigitRowChord } from '../../shared/macos-symbolic-hotkeys' -import type { MarkdownDocument } from '../../shared/filesystem-entry-types' +import type { MarkdownDocument } from '../../shared/file-listing/file-document' import type { WriteTerminalRenderDesyncEvidenceArgs } from '../../shared/terminal/diagnostics/terminal-render-desync-evidence' import { KEYBOARD_LAYOUT_CHANGED_CHANNEL, diff --git a/src/preload/api/doc-preview-api.ts b/src/preload/api/doc-preview-api.ts index 5efd0bcf9bb..63f62f10bb4 100644 --- a/src/preload/api/doc-preview-api.ts +++ b/src/preload/api/doc-preview-api.ts @@ -1,4 +1,7 @@ -import type { DocPreviewExternalLink, DocPreviewFailure } from '../../shared/doc-preview-scheme' +import type { + DocPreviewExternalLink, + DocPreviewFailure +} from '../../shared/document-preview/doc-preview-scheme' export type DocPreviewGrantOwner = | { kind: 'ssh'; connectionId: string } diff --git a/src/preload/api/doc-preview-bridge.ts b/src/preload/api/doc-preview-bridge.ts index 2e106312ded..4dd6ce3598e 100644 --- a/src/preload/api/doc-preview-bridge.ts +++ b/src/preload/api/doc-preview-bridge.ts @@ -7,7 +7,7 @@ import { DOC_PREVIEW_REVOKE_GRANT_CHANNEL, type DocPreviewFailure, type DocPreviewExternalLink -} from '../../shared/doc-preview-scheme' +} from '../../shared/document-preview/doc-preview-scheme' import type { DocPreviewGrantRequest } from '../api/doc-preview-api' import type { PreloadApi } from '../api-types' diff --git a/src/preload/api/filesystem-api.ts b/src/preload/api/filesystem-api.ts index df7c604adb4..8f945c94817 100644 --- a/src/preload/api/filesystem-api.ts +++ b/src/preload/api/filesystem-api.ts @@ -1,17 +1,18 @@ -import type { PathExistenceResult } from '../../shared/path-existence-batch' -import type { RuntimeFileReadChunkResult } from '../../shared/runtime-types' -import type { SearchOptions, SearchResult } from '../../shared/code-search-types' +import type { PathExistenceResult } from '../../shared/file-access/path-existence-batch' +import type { RuntimeFileReadChunkResult } from '../../shared/file-content/runtime-file-read' +import type { SearchOptions, SearchResult } from '../../shared/file-search/code-search-types' import type { PdfExportResult } from '../../shared/pdf-export-failure-copy' -import type { - DirEntry, - FsChangedPayload, - MarkdownDocument -} from '../../shared/filesystem-entry-types' +import type { DirEntry } from '../../shared/file-listing/directory-entry' +import type { FsChangedPayload } from '../../shared/file-watch/filesystem-change-event' +import type { MarkdownDocument } from '../../shared/file-listing/file-document' import type { ImportItemResult, - ResolveDroppedPathsResult, - StagedExternalImportSource -} from '../../shared/filesystem-import-result-types' + ResolveDroppedPathsResult +} from '../../shared/file-import/filesystem-import-result' +import type { + StagedRuntimeUploadSource as StagedExternalImportSource, + RuntimeUploadFileStreamRequest +} from '../../shared/file-import/runtime-upload-staging-contract' import type { LocalLogTailChangedPayload, LocalLogTailReadArgs, @@ -19,13 +20,13 @@ import type { LocalLogTailWatchArgs } from '../../shared/local-log-tail-types' import type { SshMutationExpectation } from '../../shared/ssh-types' -import type { LocalFileAccess } from '../../shared/local-file-access' -import type { RemoteFilePreviewAddress } from '../../shared/remote-file-preview-address' -import type { FileBytesWritePrecondition } from '../../shared/file-bytes-write' +import type { LocalFileAccess } from '../../shared/file-access/local-file-access' +import type { RemoteFilePreviewAddress } from '../../shared/file-preview/remote-file-preview-address' +import type { FileBytesWritePrecondition } from '../../shared/file-write/file-bytes-write' import type { FileWriteDiskPrecondition, FileWriteResult -} from '../../shared/file-write-disk-precondition' +} from '../../shared/file-write/file-write-disk-precondition' import type { CreateVenvResult, KernelFrameEvent, @@ -33,7 +34,6 @@ import type { PythonEnvironment, PythonEnvironments } from '../../shared/notebook-kernel-types' -import type { RuntimeUploadFileStreamRequest } from '../../shared/runtime-upload-staging-contract' import type { AgentSessionAttachmentPathUploadResult, AgentSessionAttachmentUploadTarget @@ -41,7 +41,7 @@ import type { import type { PrepareDroppedPathsRequest, PreparedDroppedPaths -} from '../../shared/native-file-drop-preparation' +} from '../../shared/file-import/native-file-drop-preparation' export type ExportApi = { htmlToPdf: (args: { html: string; title: string }) => Promise diff --git a/src/preload/api/fs-bridge.ts b/src/preload/api/fs-bridge.ts index 686ad4340f6..e33ce61f046 100644 --- a/src/preload/api/fs-bridge.ts +++ b/src/preload/api/fs-bridge.ts @@ -1,29 +1,31 @@ -import type { PathExistenceResult } from '../../shared/path-existence-batch' +import type { PathExistenceResult } from '../../shared/file-access/path-existence-batch' import { ipcRenderer, webUtils } from 'electron' import type { PrepareDroppedPathsRequest, PreparedDroppedPaths -} from '../../shared/native-file-drop-preparation' +} from '../../shared/file-import/native-file-drop-preparation' import type { SshMutationExpectation } from '../../shared/ssh-types' -import type { LocalFileAccess } from '../../shared/local-file-access' -import type { RemoteFilePreviewAddress } from '../../shared/remote-file-preview-address' -import type { FileBytesWritePrecondition } from '../../shared/file-bytes-write' +import type { LocalFileAccess } from '../../shared/file-access/local-file-access' +import type { RemoteFilePreviewAddress } from '../../shared/file-preview/remote-file-preview-address' +import type { FileBytesWritePrecondition } from '../../shared/file-write/file-bytes-write' import type { FileWriteDiskPrecondition, FileWriteResult -} from '../../shared/file-write-disk-precondition' -import type { RuntimeUploadFileStreamRequest } from '../../shared/runtime-upload-staging-contract' +} from '../../shared/file-write/file-write-disk-precondition' +import type { + RuntimeUploadFileStreamRequest, + StagedRuntimeUploadSource as StagedExternalImportSource +} from '../../shared/file-import/runtime-upload-staging-contract' import type { AgentSessionAttachmentPathUploadResult, AgentSessionAttachmentUploadTarget } from '../../shared/agent-session/agent-session-attachments' -import type { SearchResult } from '../../shared/code-search-types' -import type { FsChangedPayload } from '../../shared/filesystem-entry-types' +import type { SearchResult } from '../../shared/file-search/code-search-types' +import type { FsChangedPayload } from '../../shared/file-watch/filesystem-change-event' import type { ImportItemResult, - ResolveDroppedPathsResult, - StagedExternalImportSource -} from '../../shared/filesystem-import-result-types' + ResolveDroppedPathsResult +} from '../../shared/file-import/filesystem-import-result' import type { LocalLogTailChangedPayload, LocalLogTailReadArgs, diff --git a/src/preload/api/shell-api.ts b/src/preload/api/shell-api.ts index 83a4f596524..fe70305cf47 100644 --- a/src/preload/api/shell-api.ts +++ b/src/preload/api/shell-api.ts @@ -1,6 +1,6 @@ import type { RepoIconPickResult } from '../../shared/repo-icon-pick-failure-copy' import type { ExecutionHostId } from '../../shared/execution-host' -import type { ShellPathExistence } from '../../shared/path-existence-batch' +import type { ShellPathExistence } from '../../shared/file-access/path-existence-batch' import type { ShellOpenExternalEditorRequest, ShellOpenExternalEditorResult, diff --git a/src/preload/api/shell-bridge.ts b/src/preload/api/shell-bridge.ts index 6c04245ca50..d638d61dd7a 100644 --- a/src/preload/api/shell-bridge.ts +++ b/src/preload/api/shell-bridge.ts @@ -7,7 +7,7 @@ import type { ShellOpenLocalPathResult } from '../../shared/shell/opening/shell-open-types' import type { ExecutionHostId } from '../../shared/execution-host' -import type { ShellPathExistence } from '../../shared/path-existence-batch' +import type { ShellPathExistence } from '../../shared/file-access/path-existence-batch' import type { PreloadApi } from '../api-types' export const shellApi = { diff --git a/src/preload/api/ssh-api.ts b/src/preload/api/ssh-api.ts index d10247c0355..fcb008740d0 100644 --- a/src/preload/api/ssh-api.ts +++ b/src/preload/api/ssh-api.ts @@ -12,7 +12,7 @@ import type { SshTargetCreateInput, SshTargetUpdateInput } from '../../shared/ssh-types' -import type { FilesystemPathFlavor } from '../../shared/filesystem-entry-types' +import type { FilesystemPathFlavor } from '../../shared/file-access/filesystem-path-flavor' export type SshApi = { listTargets: () => Promise diff --git a/src/preload/api/ssh-bridge.ts b/src/preload/api/ssh-bridge.ts index 9429ff80c80..9e63dddc6ea 100644 --- a/src/preload/api/ssh-bridge.ts +++ b/src/preload/api/ssh-bridge.ts @@ -17,7 +17,7 @@ import { admitSshConnectionStateForAuthorityReconciliation, admitSshDetectedPorts } from '../../shared/ssh-retained-payload-admission' -import type { FilesystemPathFlavor } from '../../shared/filesystem-entry-types' +import type { FilesystemPathFlavor } from '../../shared/file-access/filesystem-path-flavor' import type { PreloadApi } from '../api-types' export const sshApi = { diff --git a/src/preload/api/ui-bridge-state-and-menu-commands.ts b/src/preload/api/ui-bridge-state-and-menu-commands.ts index 3ed7d0c4c78..d565a3d81eb 100644 --- a/src/preload/api/ui-bridge-state-and-menu-commands.ts +++ b/src/preload/api/ui-bridge-state-and-menu-commands.ts @@ -1,4 +1,4 @@ -import type { MarkdownDocument } from '../../shared/filesystem-entry-types' +import type { MarkdownDocument } from '../../shared/file-listing/file-document' import type { BrowserTabCreateRequest } from '../../shared/browser-tab-create-request' import { ipcRenderer } from 'electron' import type { PersistedUIState } from '../../shared/persisted-ui-state-types' diff --git a/src/preload/api/ui-bridge-terminal-and-session-tabs.ts b/src/preload/api/ui-bridge-terminal-and-session-tabs.ts index 277989ee83c..c324db9e5fa 100644 --- a/src/preload/api/ui-bridge-terminal-and-session-tabs.ts +++ b/src/preload/api/ui-bridge-terminal-and-session-tabs.ts @@ -1,7 +1,7 @@ import type { RuntimeEditorTabReveal, RuntimeFileOpenPosition -} from '../../shared/runtime-file-contracts' +} from '../../shared/file-access/runtime-editor-file-open' import { ipcRenderer } from 'electron' import type { TerminalPaneSplitSource } from '../../shared/feature-education-telemetry' import type { TerminalTabCreateReply } from '../../shared/workspace-layout/terminal-reveal-identity' diff --git a/src/preload/api/ui-command-event-api.ts b/src/preload/api/ui-command-event-api.ts index 64e858eba4d..cfb796cc184 100644 --- a/src/preload/api/ui-command-event-api.ts +++ b/src/preload/api/ui-command-event-api.ts @@ -1,14 +1,14 @@ import type { RuntimeEditorTabReveal, RuntimeFileOpenPosition -} from '../../shared/runtime-file-contracts' +} from '../../shared/file-access/runtime-editor-file-open' import type { JiraQuickFilterState } from '../../shared/jira/jira-quick-filters' import type { JiraSavedFilterState, JiraSavedFilterMutation } from '../../shared/jira/jira-saved-filters' import type { BrowserTabCreateRequest } from '../../shared/browser-tab-create-request' -import type { MarkdownDocument } from '../../shared/filesystem-entry-types' +import type { MarkdownDocument } from '../../shared/file-listing/file-document' import type { PersistedUIState } from '../../shared/persisted-ui-state-types' import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' import type { diff --git a/src/preload/doc-preview-link-interception.test.ts b/src/preload/doc-preview-link-interception.test.ts deleted file mode 100644 index 48b98d05334..00000000000 --- a/src/preload/doc-preview-link-interception.test.ts +++ /dev/null @@ -1,243 +0,0 @@ -// @vitest-environment happy-dom -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { DocPreviewLinkModifiers } from '../shared/doc-preview-scheme' -import { - handleDocPreviewLinkAuxClick, - handleDocPreviewLinkClick, - installDocPreviewLinkInterception -} from './doc-preview-link-interception' - -const NO_MODIFIERS = { metaKey: false, ctrlKey: false, shiftKey: false } - -const PREVIEW_GRANT_ID = 'a'.repeat(32) - -let report: ReturnType void>> - -function documentUrl(): string { - return window.location.href -} - -function loadPreviewDocument(body: string): void { - document.body.innerHTML = body - report = vi.fn<(url: string, modifiers: DocPreviewLinkModifiers) => void>() -} - -// happy-dom does not model SVGAnimatedString hrefs. -function loadSvgAnchorDocument(href: string): void { - loadPreviewDocument('
') - const svgNamespace = 'http://www.w3.org/2000/svg' - const anchor = document.createElementNS(svgNamespace, 'a') - anchor.setAttribute('href', href) - Object.defineProperty(anchor, 'href', { value: { baseVal: href } }) - const hit = document.createElementNS(svgNamespace, 'rect') - hit.setAttribute('id', 'svg-hit') - anchor.appendChild(hit) - const svg = document.createElementNS(svgNamespace, 'svg') - svg.appendChild(anchor) - document.getElementById('host')!.appendChild(svg) -} - -function dispatch(selector: string, event: MouseEvent): MouseEvent { - const onClick = (candidate: Event): void => handleDocPreviewLinkClick(candidate, report) - const onAuxClick = (candidate: Event): void => - handleDocPreviewLinkAuxClick(candidate as MouseEvent) - document.addEventListener('click', onClick, true) - document.addEventListener('auxclick', onAuxClick, true) - try { - document.querySelector(selector)!.dispatchEvent(event) - } finally { - document.removeEventListener('click', onClick, true) - document.removeEventListener('auxclick', onAuxClick, true) - } - return event -} - -function pressTrusted(selector: string, init: MouseEventInit = {}): MouseEvent { - const event = new MouseEvent('click', { bubbles: true, cancelable: true, ...init }) - Object.defineProperty(event, 'isTrusted', { configurable: true, value: true }) - return dispatch(selector, event) -} - -beforeEach(() => { - ;(window as never as { happyDOM: { setURL: (url: string) => void } }).happyDOM.setURL( - `orca-preview://${PREVIEW_GRANT_ID}/index.html` - ) - vi.restoreAllMocks() -}) - -describe('doc preview link interception', () => { - it('listens for both press kinds in the capture phase, so the document cannot consume them first', () => { - loadPreviewDocument('go') - const addEventListener = vi.spyOn(document, 'addEventListener') - try { - installDocPreviewLinkInterception(report) - expect(addEventListener.mock.calls.map(([type, , options]) => [type, options])).toEqual([ - ['click', true], - ['auxclick', true] - ]) - const link = document.querySelector('#external')! - const click = new MouseEvent('click', { bubbles: true, cancelable: true }) - Object.defineProperty(click, 'isTrusted', { configurable: true, value: true }) - link.dispatchEvent(click) - expect(report).toHaveBeenCalledExactlyOnceWith('https://example.com/docs', NO_MODIFIERS) - expect(click.defaultPrevented).toBe(true) - - const middleClick = new MouseEvent('auxclick', { bubbles: true, button: 1, cancelable: true }) - Object.defineProperty(middleClick, 'isTrusted', { configurable: true, value: true }) - link.dispatchEvent(middleClick) - expect(middleClick.defaultPrevented).toBe(true) - expect(report).toHaveBeenCalledOnce() - } finally { - for (const [type, listener, options] of addEventListener.mock.calls) { - document.removeEventListener(type, listener, options) - } - } - }) - - it.each([ - { metaKey: true, ctrlKey: false, shiftKey: true }, - { metaKey: false, ctrlKey: true, shiftKey: true } - ])('reports the trusted click modifiers %j without choosing a destination', (modifiers) => { - loadPreviewDocument('go') - - pressTrusted('#external', modifiers) - - expect(report).toHaveBeenCalledExactlyOnceWith('https://example.com/docs', modifiers) - }) - - it('routes nothing for a click the document dispatched itself', () => { - loadPreviewDocument('go') - - const scripted = new MouseEvent('click', { bubbles: true, cancelable: true }) - // happy-dom omits the isTrusted value Chromium sets for synthetic clicks. - Object.defineProperty(scripted, 'isTrusted', { configurable: true, value: false }) - - const event = dispatch('#external', scripted) - - expect(event.isTrusted).toBe(false) - expect(report).not.toHaveBeenCalled() - expect(event.defaultPrevented).toBe(false) - }) - - it('reports the anchor even when the press landed on what it wraps', () => { - loadPreviewDocument('go') - - pressTrusted('#inner') - - expect(report).toHaveBeenCalledExactlyOnceWith('https://example.com/docs', NO_MODIFIERS) - }) - - it('reports an SVG anchor by its animated href', () => { - loadSvgAnchorDocument('https://example.com/chart') - - pressTrusted('#svg-hit') - - expect(report).toHaveBeenCalledExactlyOnceWith('https://example.com/chart', NO_MODIFIERS) - }) - - it('leaves a relative SVG link to the guest, the same as the HTML anchor beside it', () => { - loadSvgAnchorDocument('guide.html') - - const event = pressTrusted('#svg-hit') - - expect(report).not.toHaveBeenCalled() - expect(event.defaultPrevented).toBe(false) - }) - - it('scrolls to an SVG fragment target instead of routing it', () => { - loadSvgAnchorDocument('#section-2') - const target = document.createElement('h2') - target.id = 'section-2' - document.body.appendChild(target) - const scrollIntoView = vi.spyOn(target, 'scrollIntoView') - - const event = pressTrusted('#svg-hit') - - expect(scrollIntoView).toHaveBeenCalledOnce() - expect(report).not.toHaveBeenCalled() - expect(event.defaultPrevented).toBe(true) - }) - - it('keeps a rooted SVG link inside the preview rather than reading it as a filesystem path', () => { - loadSvgAnchorDocument('/assets/a.html') - - const event = pressTrusted('#svg-hit') - - expect(report).not.toHaveBeenCalled() - expect(event.defaultPrevented).toBe(false) - }) - - it('leaves a sibling preview document to the guest, which its policy already permits', () => { - loadPreviewDocument( - `guide` - ) - - const event = pressTrusted('#sibling') - - expect(report).not.toHaveBeenCalled() - expect(event.defaultPrevented).toBe(false) - }) - - it('scrolls to a fragment target in the document instead of routing it', () => { - loadPreviewDocument( - `jump

s

` - ) - const scrollIntoView = vi.spyOn(document.getElementById('section')!, 'scrollIntoView') - - const event = pressTrusted('#jump') - - expect(scrollIntoView).toHaveBeenCalledOnce() - expect(report).not.toHaveBeenCalled() - expect(event.defaultPrevented).toBe(true) - }) - - it('finds a fragment target whose id the href percent-encoded', () => { - loadPreviewDocument(`jump

s

`) - const scrollIntoView = vi.spyOn(document.getElementById('a b')!, 'scrollIntoView') - - pressTrusted('#jump') - - expect(scrollIntoView).toHaveBeenCalledOnce() - expect(report).not.toHaveBeenCalled() - }) - - it('scrolls to the top for a bare # and for #top with nothing carrying that id', () => { - loadPreviewDocument( - `toptop` - ) - const scrollTo = vi.spyOn(window, 'scrollTo').mockImplementation(() => {}) - - pressTrusted('#hash') - pressTrusted('#named') - - expect(scrollTo).toHaveBeenCalledTimes(2) - expect(report).not.toHaveBeenCalled() - }) - - it('routes a fragment href that belongs to another document', () => { - loadPreviewDocument('go') - - pressTrusted('#other') - - expect(report).toHaveBeenCalledExactlyOnceWith('https://example.com/page#section', NO_MODIFIERS) - }) - - it('leaves a middle click the document dispatched itself alone', () => { - loadPreviewDocument('go') - const event = new MouseEvent('auxclick', { bubbles: true, button: 1, cancelable: true }) - Object.defineProperty(event, 'isTrusted', { configurable: true, value: false }) - - dispatch('#external', event) - - expect(event.defaultPrevented).toBe(false) - }) - - it('ignores a press that is not on a link at all', () => { - loadPreviewDocument('

nothing here

') - - const event = pressTrusted('#text') - - expect(report).not.toHaveBeenCalled() - expect(event.defaultPrevented).toBe(false) - }) -}) diff --git a/src/preload/doc-preview-link-interception.ts b/src/preload/doc-preview-link-interception.ts index b6df74d0906..99ea276ccf6 100644 --- a/src/preload/doc-preview-link-interception.ts +++ b/src/preload/doc-preview-link-interception.ts @@ -1,5 +1,5 @@ // Runs in the isolated world so page scripts cannot access the link reporter or its listeners. -import type { DocPreviewLinkModifiers } from '../shared/doc-preview-scheme' +import type { DocPreviewLinkModifiers } from '../shared/document-preview/doc-preview-scheme' export type DocPreviewExternalLinkReporter = ( url: string, diff --git a/src/renderer/src/components/QuickOpen.tsx b/src/renderer/src/components/QuickOpen.tsx index 0b3b5e69989..826c40753fd 100644 --- a/src/renderer/src/components/QuickOpen.tsx +++ b/src/renderer/src/components/QuickOpen.tsx @@ -14,7 +14,7 @@ import { FilePathCursorTooltip, splitTrailingSegment } from '@/components/file-p import { parseQuickOpenQueryTarget, isQuickOpenAbsolutePath -} from '../../../shared/quick-open-query-target' +} from '../../../shared/quick-open/quick-open-query-target' import { openQuickOpenFile } from './quick-open-file-navigation' import { rankQuickOpenFilesWithHistory } from './quick-open-history-ranking' import { useQuickOpenHistory } from '@/lib/quick-open-file-history' diff --git a/src/renderer/src/components/artifacts/ArtifactActions.tsx b/src/renderer/src/components/artifacts/ArtifactActions.tsx index 6529f0325ea..a296372889d 100644 --- a/src/renderer/src/components/artifacts/ArtifactActions.tsx +++ b/src/renderer/src/components/artifacts/ArtifactActions.tsx @@ -1,5 +1,5 @@ import { Copy, ExternalLink, Loader2, MoreHorizontal, Trash2 } from 'lucide-react' -import type { ArtifactListItem } from '../../../../shared/artifacts' +import type { ArtifactListItem } from '../../../../shared/artifacts/artifacts' import { Button } from '@/components/ui/button' import { DropdownMenu, diff --git a/src/renderer/src/components/artifacts/ArtifactCollection.test.tsx b/src/renderer/src/components/artifacts/ArtifactCollection.test.tsx index 0a4bc9a7e39..4b3586a5225 100644 --- a/src/renderer/src/components/artifacts/ArtifactCollection.test.tsx +++ b/src/renderer/src/components/artifacts/ArtifactCollection.test.tsx @@ -5,7 +5,7 @@ import { cleanup, render, screen, within } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { useState } from 'react' import { afterEach, describe, expect, it, vi } from 'vitest' -import type { ArtifactListItem } from '../../../../shared/artifacts' +import type { ArtifactListItem } from '../../../../shared/artifacts/artifacts' vi.mock('./ArtifactPreview', () => ({ ArtifactPreview: ({ shareUrl }: { shareUrl: string }) =>
{`Preview ${shareUrl}`}
@@ -66,44 +66,6 @@ describe('ArtifactCollection', () => { // Restore prototype layout spies or later tests inherit fabricated geometry. afterEach(() => vi.restoreAllMocks()) - function renderCollection( - items: ArtifactListItem[], - selectArtifact = vi.fn(), - hasMore = false - ): { container: HTMLElement; selectArtifact: ReturnType } { - const { container } = render( - - - - ) - return { container, selectArtifact } - } - - it('filters the list by name', async () => { - const items = [artifact('first', 'First artifact'), artifact('second', 'Second artifact')] - renderCollection(items) - - await userEvent.type(screen.getByPlaceholderText('Search...'), 'second') - expect(screen.getByRole('button', { name: /Second artifact/ })).toBeInTheDocument() - expect(screen.queryByRole('button', { name: /First artifact/ })).not.toBeInTheDocument() - - await userEvent.clear(screen.getByPlaceholderText('Search...')) - await userEvent.type(screen.getByPlaceholderText('Search...'), 'nothing') - expect(screen.queryByRole('button', { name: /Second artifact/ })).not.toBeInTheDocument() - expect(screen.getByText('No matches')).toBeInTheDocument() - }) - /** Guard clicks from both descendant triggers and React-bubbling portaled menu items so actions cannot select the row behind them. */ it('runs a row menu action without selecting the artifact behind the menu', async () => { const user = userEvent.setup() diff --git a/src/renderer/src/components/artifacts/ArtifactCollection.tsx b/src/renderer/src/components/artifacts/ArtifactCollection.tsx index 657d4f9f0bc..08663157396 100644 --- a/src/renderer/src/components/artifacts/ArtifactCollection.tsx +++ b/src/renderer/src/components/artifacts/ArtifactCollection.tsx @@ -1,6 +1,6 @@ import { useMemo, useState } from 'react' import { Loader2 } from 'lucide-react' -import type { ArtifactListItem } from '../../../../shared/artifacts' +import type { ArtifactListItem } from '../../../../shared/artifacts/artifacts' import { Button } from '@/components/ui/button' import { useTranslate } from '@/i18n/use-translate' import { cn } from '@/lib/utils' diff --git a/src/renderer/src/components/artifacts/ArtifactDetailDrawer.tsx b/src/renderer/src/components/artifacts/ArtifactDetailDrawer.tsx index 6588b20d1a2..cbdc97f0f0a 100644 --- a/src/renderer/src/components/artifacts/ArtifactDetailDrawer.tsx +++ b/src/renderer/src/components/artifacts/ArtifactDetailDrawer.tsx @@ -1,5 +1,5 @@ import * as VisuallyHidden from 'radix-ui/visually-hidden' -import type { ArtifactListItem } from '../../../../shared/artifacts' +import type { ArtifactListItem } from '../../../../shared/artifacts/artifacts' import { Sheet, SheetContent, SheetDescription, SheetTitle } from '@/components/ui/sheet' import { useTranslate } from '@/i18n/use-translate' import { artifactName } from './artifact-display-labels' diff --git a/src/renderer/src/components/artifacts/ArtifactDetailHeader.tsx b/src/renderer/src/components/artifacts/ArtifactDetailHeader.tsx index 609b2bdbcb5..b532cf40bcb 100644 --- a/src/renderer/src/components/artifacts/ArtifactDetailHeader.tsx +++ b/src/renderer/src/components/artifacts/ArtifactDetailHeader.tsx @@ -1,6 +1,6 @@ import type { ReactNode } from 'react' import { Globe, X } from 'lucide-react' -import type { ArtifactListItem } from '../../../../shared/artifacts' +import type { ArtifactListItem } from '../../../../shared/artifacts/artifacts' import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { useIntlLocale, useTranslate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/artifacts/ArtifactListRow.tsx b/src/renderer/src/components/artifacts/ArtifactListRow.tsx index 6058c98af48..47e63f1b3eb 100644 --- a/src/renderer/src/components/artifacts/ArtifactListRow.tsx +++ b/src/renderer/src/components/artifacts/ArtifactListRow.tsx @@ -1,7 +1,7 @@ import { Fragment } from 'react' import { Copy, ExternalLink, MoreHorizontal, Trash2 } from 'lucide-react' import type { LucideIcon } from 'lucide-react' -import type { ArtifactListItem } from '../../../../shared/artifacts' +import type { ArtifactListItem } from '../../../../shared/artifacts/artifacts' import { Button } from '@/components/ui/button' import { ContextMenu, diff --git a/src/renderer/src/components/artifacts/ArtifactListRows.tsx b/src/renderer/src/components/artifacts/ArtifactListRows.tsx index a5ab824fcf0..edbb7e15efd 100644 --- a/src/renderer/src/components/artifacts/ArtifactListRows.tsx +++ b/src/renderer/src/components/artifacts/ArtifactListRows.tsx @@ -1,5 +1,5 @@ import { VirtualizedList } from '@/components/virtualized-list' -import type { ArtifactListItem } from '../../../../shared/artifacts' +import type { ArtifactListItem } from '../../../../shared/artifacts/artifacts' import { ArtifactListRow } from './ArtifactListRow' import { ARTIFACTS_TABLE_ROW_HEIGHT_PX } from './artifacts-table-layout' diff --git a/src/renderer/src/components/artifacts/ArtifactPublishButton.tsx b/src/renderer/src/components/artifacts/ArtifactPublishButton.tsx index d1e81c98111..d75832498cc 100644 --- a/src/renderer/src/components/artifacts/ArtifactPublishButton.tsx +++ b/src/renderer/src/components/artifacts/ArtifactPublishButton.tsx @@ -1,6 +1,6 @@ import { useEffect, useRef, useState, type RefObject } from 'react' import { ArrowRight, Loader2, Share2 } from 'lucide-react' -import type { ArtifactWriteRequest } from '../../../../shared/artifacts' +import type { ArtifactWriteRequest } from '../../../../shared/artifacts/artifacts' import { Button } from '@/components/ui/button' import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from '@/components/ui/popover' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' diff --git a/src/renderer/src/components/artifacts/ArtifactsPage.tsx b/src/renderer/src/components/artifacts/ArtifactsPage.tsx index d33bffac961..27fd63a96eb 100644 --- a/src/renderer/src/components/artifacts/ArtifactsPage.tsx +++ b/src/renderer/src/components/artifacts/ArtifactsPage.tsx @@ -1,5 +1,8 @@ import { useEffect, useState } from 'react' -import type { ArtifactCloudOperation, ArtifactListItem } from '../../../../shared/artifacts' +import type { + ArtifactCloudOperation, + ArtifactListItem +} from '../../../../shared/artifacts/artifacts' import { useConfirmationDialog } from '@/components/confirmation-dialog-context' import { persistConfirmationSkipPreference } from '@/components/confirmation-skip-preference' import { callRuntimeRpc } from '@/runtime/rpc/calls/runtime-rpc-call' diff --git a/src/renderer/src/components/artifacts/artifact-display-labels.ts b/src/renderer/src/components/artifacts/artifact-display-labels.ts index c7ff3f28d4e..39a0cc39f07 100644 --- a/src/renderer/src/components/artifacts/artifact-display-labels.ts +++ b/src/renderer/src/components/artifacts/artifact-display-labels.ts @@ -1,4 +1,4 @@ -import type { ArtifactListItem } from '../../../../shared/artifacts' +import type { ArtifactListItem } from '../../../../shared/artifacts/artifacts' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' import { formatUiRelativeTime, formatUiRelativeTimeFromDate } from '@/i18n/relative-time-format' diff --git a/src/renderer/src/components/artifacts/artifact-list-search.ts b/src/renderer/src/components/artifacts/artifact-list-search.ts index 6396afda883..8ceda842b6d 100644 --- a/src/renderer/src/components/artifacts/artifact-list-search.ts +++ b/src/renderer/src/components/artifacts/artifact-list-search.ts @@ -1,4 +1,4 @@ -import type { ArtifactListItem } from '../../../../shared/artifacts' +import type { ArtifactListItem } from '../../../../shared/artifacts/artifacts' import { isClipboardTextByteLengthOverLimit } from '../../../../shared/clipboard-text' import { artifactName, artifactTypeLabel } from './artifact-display-labels' import type { Translate } from '../../i18n/use-translate' diff --git a/src/renderer/src/components/artifacts/artifact-publish-flow.test.ts b/src/renderer/src/components/artifacts/artifact-publish-flow.test.ts deleted file mode 100644 index 90f83164389..00000000000 --- a/src/renderer/src/components/artifacts/artifact-publish-flow.test.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { ARTIFACT_MAX_CONTENT_BYTES } from '../../../../shared/artifacts' -import { - ArtifactPublishPreparationError, - publishArtifactFromSurface -} from './artifact-publish-flow' - -const mocks = vi.hoisted(() => ({ - callRuntimeRpc: vi.fn(), - connect: vi.fn(), - toastError: vi.fn(), - toastSuccess: vi.fn(), - state: { - orcaProfileAuthStatus: { state: 'connected' } as { state: string } | null, - connectCurrentOrcaProfile: vi.fn() - } -})) - -vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({ - callRuntimeRpc: mocks.callRuntimeRpc -})) -vi.mock('@/store', () => ({ - useAppStore: { getState: () => mocks.state } -})) -vi.mock('@/i18n/i18n', () => ({ - translate: (_key: string, fallback: string) => fallback -})) -vi.mock('sonner', () => ({ - toast: { error: mocks.toastError, success: mocks.toastSuccess } -})) -const request = { - sourceKey: '/repo/report.html', - content: '

Report

', - contentType: 'text/html' as const, - fileName: 'report.html' -} -const published = { - change: 'created' as const, - item: { - artifact: { slug: 'artifact-a' }, - shareUrl: 'https://share.onorca.dev/a/artifact-a' - } -} - -beforeEach(() => { - vi.clearAllMocks() - mocks.state.orcaProfileAuthStatus = { state: 'connected' } - mocks.state.connectCurrentOrcaProfile = mocks.connect -}) - -describe('artifact publish flow', () => { - // Why: a re-read after sign-in could publish content the user never clicked Share on. - it('publishes the clicked request again after reconnecting, without re-reading', async () => { - mocks.connect.mockResolvedValue({ status: 'connected' }) - mocks.callRuntimeRpc - .mockResolvedValueOnce({ status: 'reconnect-required' }) - .mockResolvedValueOnce({ status: 'ok', value: published }) - const createRequest = vi - .fn() - .mockResolvedValueOnce(request) - .mockResolvedValueOnce({ ...request, content: '

Later

' }) - - await expect(publishArtifactFromSurface(createRequest)).resolves.toBe(published) - expect(mocks.connect).toHaveBeenCalledOnce() - expect(createRequest).toHaveBeenCalledOnce() - expect(mocks.callRuntimeRpc).toHaveBeenCalledTimes(2) - expect(mocks.callRuntimeRpc.mock.calls[1]?.[2]).toBe(request) - }) - - it('surfaces sign-in failures without publishing', async () => { - mocks.state.orcaProfileAuthStatus = { state: 'local' } - mocks.connect.mockRejectedValue(new Error('login failed')) - const createRequest = vi.fn().mockResolvedValue(request) - - await expect(publishArtifactFromSurface(createRequest)).resolves.toBeNull() - expect(mocks.callRuntimeRpc).not.toHaveBeenCalled() - expect(mocks.toastError).toHaveBeenCalledWith('Could not share artifact', undefined) - }) - - it('reports an unreadable file without asking the user to sign in', async () => { - mocks.state.orcaProfileAuthStatus = { state: 'local' } - const createRequest = vi - .fn() - .mockRejectedValue(new ArtifactPublishPreparationError('unreadable')) - - await expect(publishArtifactFromSurface(createRequest)).resolves.toBeNull() - expect(mocks.connect).not.toHaveBeenCalled() - expect(mocks.callRuntimeRpc).not.toHaveBeenCalled() - }) - - it('rejects an oversized request before RPC', async () => { - const createRequest = vi.fn().mockResolvedValue({ - ...request, - content: '"'.repeat(ARTIFACT_MAX_CONTENT_BYTES + 1) - }) - - await expect(publishArtifactFromSurface(createRequest)).resolves.toBeNull() - expect(mocks.callRuntimeRpc).not.toHaveBeenCalled() - expect(mocks.toastError).toHaveBeenCalledWith('Could not share artifact', { - description: 'This artifact is too large to share.' - }) - }) -}) diff --git a/src/renderer/src/components/artifacts/artifact-publish-flow.ts b/src/renderer/src/components/artifacts/artifact-publish-flow.ts index 052b6f86f68..11a32deb485 100644 --- a/src/renderer/src/components/artifacts/artifact-publish-flow.ts +++ b/src/renderer/src/components/artifacts/artifact-publish-flow.ts @@ -3,13 +3,13 @@ import type { ArtifactCloudOperation, ArtifactPublishResult, ArtifactWriteRequest -} from '../../../../shared/artifacts' +} from '../../../../shared/artifacts/artifacts' import { ARTIFACT_MAX_CONTENT_BYTES, ARTIFACT_MAX_REQUEST_BYTES, artifactContentByteLength, artifactWriteRequestByteLength -} from '../../../../shared/artifacts' +} from '../../../../shared/artifacts/artifacts' import { translate } from '@/i18n/i18n' import { callRuntimeRpc } from '@/runtime/rpc/calls/runtime-rpc-call' import { useAppStore } from '@/store' diff --git a/src/renderer/src/components/artifacts/artifact-published-link-client.ts b/src/renderer/src/components/artifacts/artifact-published-link-client.ts index 27a7394ed11..fa64d087448 100644 --- a/src/renderer/src/components/artifacts/artifact-published-link-client.ts +++ b/src/renderer/src/components/artifacts/artifact-published-link-client.ts @@ -1,4 +1,7 @@ -import type { ArtifactCloudOperation, ArtifactPublishedLink } from '../../../../shared/artifacts' +import type { + ArtifactCloudOperation, + ArtifactPublishedLink +} from '../../../../shared/artifacts/artifacts' import { callRuntimeRpc } from '@/runtime/rpc/calls/runtime-rpc-call' const LOCAL_RUNTIME = { kind: 'local' } as const diff --git a/src/renderer/src/components/artifacts/useArtifactPagination.ts b/src/renderer/src/components/artifacts/useArtifactPagination.ts index 0fdc5e1e50d..2e768b877f2 100644 --- a/src/renderer/src/components/artifacts/useArtifactPagination.ts +++ b/src/renderer/src/components/artifacts/useArtifactPagination.ts @@ -3,7 +3,7 @@ import type { ArtifactCloudOperation, ArtifactListItem, ArtifactListPage -} from '../../../../shared/artifacts' +} from '../../../../shared/artifacts/artifacts' import type { OrcaProfileAuthStatus } from '../../../../shared/orca-profiles' import { translate } from '@/i18n/i18n' import { callRuntimeRpc } from '@/runtime/rpc/calls/runtime-rpc-call' diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/ssh-routed-browser-page-gate.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/ssh-routed-browser-page-gate.tsx index db0f45a9ba7..e16f4f3cbbc 100644 --- a/src/renderer/src/components/browser-pane/assemble-chrome/ssh-routed-browser-page-gate.tsx +++ b/src/renderer/src/components/browser-pane/assemble-chrome/ssh-routed-browser-page-gate.tsx @@ -3,7 +3,7 @@ import { Globe } from 'lucide-react' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' import { Button } from '@/components/ui/button' -import { DOC_PREVIEW_PARTITION } from '../../../../../shared/doc-preview-scheme' +import { DOC_PREVIEW_PARTITION } from '../../../../../shared/document-preview/doc-preview-scheme' import { destroyPersistentWebview, webviewRegistry } from '../host-guest/webview-registry' import { useSshWorkspaceBrowserRoute, diff --git a/src/renderer/src/components/browser-pane/describe-page/browser-artifact-upload.test.ts b/src/renderer/src/components/browser-pane/describe-page/browser-artifact-upload.test.ts index 557468a08df..01ed6365ab3 100644 --- a/src/renderer/src/components/browser-pane/describe-page/browser-artifact-upload.test.ts +++ b/src/renderer/src/components/browser-pane/describe-page/browser-artifact-upload.test.ts @@ -1,7 +1,7 @@ // @vitest-environment happy-dom import { beforeEach, describe, expect, it, vi } from 'vitest' -import { ARTIFACT_MAX_CONTENT_BYTES } from '../../../../../shared/artifacts' +import { ARTIFACT_MAX_CONTENT_BYTES } from '../../../../../shared/artifacts/artifacts' import type { ArtifactPublishPreparationError } from '@/components/artifacts/artifact-publish-flow' import { getShareableBrowserArtifactFile, diff --git a/src/renderer/src/components/browser-pane/describe-page/browser-artifact-upload.ts b/src/renderer/src/components/browser-pane/describe-page/browser-artifact-upload.ts index 1720122ef2a..a2b064be052 100644 --- a/src/renderer/src/components/browser-pane/describe-page/browser-artifact-upload.ts +++ b/src/renderer/src/components/browser-pane/describe-page/browser-artifact-upload.ts @@ -1,5 +1,5 @@ -import type { ArtifactWriteRequest } from '../../../../../shared/artifacts' -import { ARTIFACT_MAX_CONTENT_BYTES } from '../../../../../shared/artifacts' +import type { ArtifactWriteRequest } from '../../../../../shared/artifacts/artifacts' +import { ARTIFACT_MAX_CONTENT_BYTES } from '../../../../../shared/artifacts/artifacts' import { getRuntimePathBasename } from '../../../../../shared/cross-platform-path' import { ArtifactPublishPreparationError } from '@/components/artifacts/artifact-publish-flow' import { diff --git a/src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.failure-message.test.tsx b/src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.failure-message.test.tsx deleted file mode 100644 index 267a406b57d..00000000000 --- a/src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.failure-message.test.tsx +++ /dev/null @@ -1,205 +0,0 @@ -// @vitest-environment happy-dom -// Entry failures arrive out-of-band; unsupported formats are subresource failures and must not replace a rendered document. -import { act } from 'react' -import type * as WebviewRegistryModule from '../host-guest/webview-registry' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { ConfirmationDialogContext } from '@/components/confirmation-dialog-context' -import { TooltipProvider } from '@/components/ui/tooltip' -import type { DocPreviewFailure } from '../../../../../shared/doc-preview-scheme' - -const confirmExternalLink = async (): Promise => false - -const GRANT_ID = 'a'.repeat(32) -const REMINTED_GRANT_ID = 'c'.repeat(32) -const ENTRY_RELATIVE_PATH = 'doc.html' - -const grantRuntime = vi.hoisted(() => ({ - mints: 0, - released: [] as string[], - authorizations: [] as { grantId: string; relativePath: string }[] -})) - -vi.mock('@/lib/doc-preview-grants', () => ({ - buildDocPreviewGrantRequest: () => ({ - owner: { - kind: 'runtime' as const, - environmentId: 'env-1', - worktreeSelector: 'id:wt-1', - worktreeRoot: '/repo' - }, - requestBase: '/repo', - root: '/repo/docs', - entryRelativePath: ENTRY_RELATIVE_PATH - }), - ensureDocPreviewGrant: (_previewId: string, location: unknown) => { - grantRuntime.mints += 1 - // Why a fresh id per mint: a re-mint after a reconnect must bind the guest to the new grant. - const grantId = grantRuntime.mints === 1 ? GRANT_ID : REMINTED_GRANT_ID - return Promise.resolve({ - grantId, - url: `orca-preview://${grantId}/${ENTRY_RELATIVE_PATH}`, - location - }) - }, - releaseDocPreviewGrant: (previewId: string) => { - grantRuntime.released.push(previewId) - } -})) - -vi.mock('@/components/browser-pane/host-guest/webview-registry', async (importOriginal) => ({ - ...(await importOriginal()), - moveFocusToRendererBeforeWebviewDetach: () => undefined -})) - -const storeState = { - getKnownWorktreeById: () => ({ path: '/repo' }), - persistedUIReady: true, - settings: {}, - keybindings: {}, - browserAnnotationsByPageId: {} as Record, - activeGroupIdByWorktree: {} as Record, - agentSendPopoverTargetMode: null, - openAgentSendPopoverTargetMode: () => undefined, - closeAgentSendPopoverTargetMode: () => undefined, - addBrowserPageAnnotation: () => undefined, - deleteBrowserPageAnnotation: () => undefined, - clearBrowserPageAnnotations: () => undefined, - recordFeatureInteraction: () => undefined, - recordWorkspaceDocVisit: () => undefined, - workspaceDocHistory: [], - openFile: () => 'file-1' -} - -vi.mock('@/store', () => ({ - useAppStore: Object.assign( - (selector?: (state: typeof storeState) => unknown) => - selector ? selector(storeState) : storeState, - { getState: () => storeState } - ) -})) - -vi.mock('@/lib/execution-host-display-label', () => ({ - selectWorktreeHostDisplayLabel: () => 'Studio Mac mini' -})) - -const failureListeners: ((payload: DocPreviewFailure) => void)[] = [] - -function emitFailure(payload: DocPreviewFailure): void { - for (const listener of failureListeners.slice()) { - listener(payload) - } -} - -async function renderPreview(container: HTMLDivElement, root: Root): Promise { - const { HtmlDocPreview } = await import('./HtmlDocPreview') - await act(async () => { - root.render( - - - - - - ) - }) - expect(container.querySelector('webview')).not.toBeNull() -} - -describe('HtmlDocPreview failure messages', () => { - let container: HTMLDivElement - let root: Root - let mounted = false - - beforeEach(() => { - mounted = true - failureListeners.length = 0 - grantRuntime.mints = 0 - grantRuntime.released = [] - grantRuntime.authorizations = [] - ;(window as unknown as { api: unknown }).api = { - docPreview: { - authorizeDirectory: (grantId: string, relativePath: string) => { - grantRuntime.authorizations.push({ grantId, relativePath }) - return Promise.resolve(true) - }, - onLoadFailure: (callback: (payload: DocPreviewFailure) => void) => { - failureListeners.push(callback) - return () => { - const index = failureListeners.indexOf(callback) - if (index !== -1) { - failureListeners.splice(index, 1) - } - } - } - }, - ui: { writeClipboardText: () => Promise.resolve() }, - browser: { setAnnotationViewportBridge: () => Promise.resolve(true) } - } - container = document.createElement('div') - document.body.append(container) - root = createRoot(container) - }) - - afterEach(() => { - if (mounted) { - act(() => root.unmount()) - mounted = false - } - container.remove() - }) - - it('dismisses every folder the banner named, not just the first', async () => { - await renderPreview(container, root) - - await act(async () => { - emitFailure({ - grantId: GRANT_ID, - relativePath: 'assets/app.js', - reason: 'authorization-required' - }) - emitFailure({ - grantId: GRANT_ID, - relativePath: 'data/rows.json', - reason: 'authorization-required' - }) - }) - const dismissButton = [...container.querySelectorAll('button')].find( - (button) => button.textContent?.trim() === 'Dismiss' - ) - await act(async () => { - dismissButton?.click() - emitFailure({ - grantId: GRANT_ID, - relativePath: 'data/other.json', - reason: 'authorization-required' - }) - }) - - expect(container.textContent).not.toContain('This preview wants to read files in') - expect(grantRuntime.authorizations).toEqual([]) - }) - - // Reconnect changes owner IDs; reloading the old pinned grant would repeat its failure. - it('re-mints the grant when reload is pressed from a failure', async () => { - await renderPreview(container, root) - await act(async () => { - emitFailure({ grantId: GRANT_ID, relativePath: ENTRY_RELATIVE_PATH, reason: 'unreadable' }) - }) - expect(grantRuntime.mints).toBe(1) - - await act(async () => { - container.querySelector('button[aria-label="Reload preview"]')?.click() - }) - - expect(grantRuntime.released).toEqual(['preview-1']) - expect(grantRuntime.mints).toBe(2) - expect(container.querySelector('webview')?.getAttribute('src')).toContain(REMINTED_GRANT_ID) - expect(container.textContent).not.toContain('Preview unavailable') - }) -}) diff --git a/src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.tsx b/src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.tsx index 1dff27ff1fb..e11c2ca3ca6 100644 --- a/src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.tsx +++ b/src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.tsx @@ -3,7 +3,7 @@ import { AlertCircle, Loader2 } from 'lucide-react' import type { DocPreviewFileFailure, DocPreviewFileFailureReason -} from '../../../../../shared/doc-preview-scheme' +} from '../../../../../shared/document-preview/doc-preview-scheme' import type { HtmlDocPreviewProps } from './html-doc-preview-props' import { advanceAcrossBrowserPageConversion, diff --git a/src/renderer/src/components/browser-pane/workspace-doc/doc-preview-artifact-share.tsx b/src/renderer/src/components/browser-pane/workspace-doc/doc-preview-artifact-share.tsx index c7ac29b7ddf..b84b0492ba1 100644 --- a/src/renderer/src/components/browser-pane/workspace-doc/doc-preview-artifact-share.tsx +++ b/src/renderer/src/components/browser-pane/workspace-doc/doc-preview-artifact-share.tsx @@ -1,4 +1,4 @@ -import type { ArtifactWriteRequest } from '../../../../../shared/artifacts' +import type { ArtifactWriteRequest } from '../../../../../shared/artifacts/artifacts' import { getConnectionExecutionHostId, toRuntimeExecutionHostId @@ -18,7 +18,7 @@ import { normalizeRuntimePathForComparison, relativePathInsideRoot } from '../../../../../shared/cross-platform-path' -import type { RuntimeFilePreviewResult } from '../../../../../shared/runtime-types' +import type { RuntimeFilePreviewResult } from '../../../../../shared/file-content/runtime-file-read' import { acquireTerminalArtifactGrant, pinTerminalArtifactGrantTarget, diff --git a/src/renderer/src/components/browser-pane/workspace-doc/doc-preview-directory-access.tsx b/src/renderer/src/components/browser-pane/workspace-doc/doc-preview-directory-access.tsx index 5bca3fad069..8a576c38137 100644 --- a/src/renderer/src/components/browser-pane/workspace-doc/doc-preview-directory-access.tsx +++ b/src/renderer/src/components/browser-pane/workspace-doc/doc-preview-directory-access.tsx @@ -1,7 +1,7 @@ import { useCallback, useRef, useState, type RefObject } from 'react' import { AlertCircle, Loader2 } from 'lucide-react' import { toast } from 'sonner' -import type { DocPreviewFileFailure } from '../../../../../shared/doc-preview-scheme' +import type { DocPreviewFileFailure } from '../../../../../shared/document-preview/doc-preview-scheme' import { Button } from '@/components/ui/button' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts b/src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts index 231fd8fd81d..a62c90e921d 100644 --- a/src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts +++ b/src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts @@ -1,7 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { ConfirmationDialogContextValue } from '@/components/confirmation-dialog-context' -import type { DocPreviewExternalLink } from '../../../../../shared/doc-preview-scheme' +import type { DocPreviewExternalLink } from '../../../../../shared/document-preview/doc-preview-scheme' import type { DocPreviewGrantOwner } from '../../../../../preload/api/doc-preview-api' import { registerHttpLinkStoreAccessor, @@ -93,43 +93,6 @@ afterEach(() => { }) describe('document preview external-link confirmation', () => { - it('confirms the exact URL and captures its source before awaiting the answer', async () => { - let answer: ((confirmed: boolean) => void) | undefined - const confirm = vi.fn( - () => - new Promise((resolve) => { - answer = resolve - }) - ) - const { emit } = installSubscription(confirm) - emit() - expect(confirm).toHaveBeenCalledWith( - expect.objectContaining({ - title: 'Open link to example.com?', - description: 'https://example.com/docs?source=preview' - }) - ) - expect(openBrowser).not.toHaveBeenCalled() - state.unifiedTabsByWorktree['source-workspace'][0].groupId = 'moved-group' - answer?.(true) - await vi.waitFor(() => expect(openBrowser).toHaveBeenCalledOnce()) - expect(openBrowser).toHaveBeenCalledWith( - expect.objectContaining({ - workspaceId: 'source-workspace', - expectedRuntimeEnvironmentId: 'source-server', - allowClientBrowserFallback: true, - linkContext: expect.objectContaining({ - linkIntent: expect.objectContaining({ - sourceTabId: 'source-wrapper', - initialGroupId: 'source-group' - }) - }) - }) - ) - state.unifiedTabsByWorktree['source-workspace'][0].groupId = 'source-group' - expect(openUrl).not.toHaveBeenCalled() - }) - it('opens nothing when the reader cancels or the preview is disposed while confirming', async () => { const cancelled = installSubscription( vi.fn().mockResolvedValue(false) diff --git a/src/renderer/src/components/browser-pane/workspace-doc/doc-preview-failure-messages.ts b/src/renderer/src/components/browser-pane/workspace-doc/doc-preview-failure-messages.ts index dfaa8ac54f8..13676c3f1ac 100644 --- a/src/renderer/src/components/browser-pane/workspace-doc/doc-preview-failure-messages.ts +++ b/src/renderer/src/components/browser-pane/workspace-doc/doc-preview-failure-messages.ts @@ -1,7 +1,7 @@ import type { DocPreviewFileFailure, DocPreviewFileFailureReason -} from '../../../../../shared/doc-preview-scheme' +} from '../../../../../shared/document-preview/doc-preview-scheme' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/browser-pane/workspace-doc/doc-preview-webview-attach.ts b/src/renderer/src/components/browser-pane/workspace-doc/doc-preview-webview-attach.ts index dcef98bfd09..e5bb084cdf4 100644 --- a/src/renderer/src/components/browser-pane/workspace-doc/doc-preview-webview-attach.ts +++ b/src/renderer/src/components/browser-pane/workspace-doc/doc-preview-webview-attach.ts @@ -1,4 +1,4 @@ -import { DOC_PREVIEW_PARTITION } from '../../../../../shared/doc-preview-scheme' +import { DOC_PREVIEW_PARTITION } from '../../../../../shared/document-preview/doc-preview-scheme' import { publishNativeChatVisualGuestTheme } from '@/components/native-chat/media/visuals/NativeChatVisualGuestThemePublisher' import { ORCA_BROWSER_PAGE_GUEST_WEB_PREFERENCES_ATTRIBUTE } from '../../../../../shared/browser-guest-web-preferences' import { diff --git a/src/renderer/src/components/editor/DiagramViewerModal.tsx b/src/renderer/src/components/editor/DiagramViewerModal.tsx index 1a94e87fdbf..7602d1d64a1 100644 --- a/src/renderer/src/components/editor/DiagramViewerModal.tsx +++ b/src/renderer/src/components/editor/DiagramViewerModal.tsx @@ -2,7 +2,7 @@ import React, { useMemo } from 'react' import { useTranslate } from '@/i18n/use-translate' import { useAppStore } from '@/store' import type { PanZoomSize } from '../../../../shared/pan-zoom-view' -import { svgMarkupDataUri } from '../../../../shared/svg-document' +import { svgMarkupDataUri } from '../../../../shared/file-preview/svg-document' import { PanZoomImageDialog } from './PanZoomImageDialog' function readSvgImage(svg: string): { xml: string; size: PanZoomSize } | null { diff --git a/src/renderer/src/components/editor/EditorEditFileSurface.monaco-containment.test.tsx b/src/renderer/src/components/editor/EditorEditFileSurface.monaco-containment.test.tsx deleted file mode 100644 index 3505a66e28f..00000000000 --- a/src/renderer/src/components/editor/EditorEditFileSurface.monaco-containment.test.tsx +++ /dev/null @@ -1,191 +0,0 @@ -// @vitest-environment happy-dom - -// Contain Monaco initialization errors at the editor pane so they cannot unmount the workbench. - -import { act, useEffect, type ReactElement } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -import { RecoverableRenderErrorBoundary } from '../error-boundaries/RecoverableRenderErrorBoundary' -import { EditorEditFileSurface } from './EditorEditFileSurface' -import type { OpenFile } from '@/store/slices/editor/types/open-file' -import type { useMarkdownDocuments } from './markdown/documents/useMarkdownDocuments' -import type { MarkdownDocument } from '../../../../shared/filesystem-entry-types' - -const reportCrashMock = vi.hoisted(() => vi.fn()) -type EditorMountFailure = 'create' | 'on-mount' | null - -const editorMounts = vi.hoisted((): { count: number; failure: EditorMountFailure } => ({ - count: 0, - failure: null -})) - -vi.mock('@/lib/react-error-boundary-reporting', () => ({ - reportReactErrorBoundaryCrash: reportCrashMock -})) - -vi.mock('./editor-lazy-views', () => { - function MonacoEditorStub(): ReactElement { - // Monaco creates the editor and invokes onMount inside its mount effect; exercise both throw paths there. - useEffect(() => { - editorMounts.count += 1 - if (editorMounts.failure === 'create') { - throw new ReferenceError('Cannot access uninitialized variable.') - } - if (editorMounts.failure === 'on-mount') { - const onMount = (): void => { - throw new TypeError('onMount wiring failed') - } - onMount() - } - }, []) - return
- } - const unusedViewer = (): ReactElement =>
- return { - MonacoEditor: MonacoEditorStub, - CsvViewer: unusedViewer, - ImageViewer: unusedViewer, - IpynbViewer: unusedViewer, - MermaidViewer: unusedViewer - } -}) - -globalThis.IS_REACT_ACT_ENVIRONMENT = true - -const PAGE_BOUNDARY_TITLE = 'The page boundary caught it' - -const noMarkdownDocuments: MarkdownDocument[] = [] -const openMarkdownDocument = async (): Promise => {} -const markdownDocumentsStub: ReturnType = { - markdownDocuments: noMarkdownDocuments, - openMarkdownDocument, - onOpenDocLink: () => {}, - previewProps: { markdownDocuments: noMarkdownDocuments, onOpenDocument: openMarkdownDocument }, - mdSave: async () => false -} - -const activeFile: OpenFile = { - id: 'file-1', - filePath: '/repo/src/index.ts', - relativePath: 'src/index.ts', - worktreeId: 'wt-1', - language: 'typescript', - isDirty: false, - mode: 'edit' -} - -function Harness(): ReactElement { - return ( - -
- {}} - markdownAnnotationsEnabled={false} - pendingEditorReveal={null} - markdownDocuments={markdownDocumentsStub} - getConflictNavigation={() => undefined} - getMarkdownSourceLineOffset={() => 0} - handleContentChange={() => {}} - handleDirtyStateHint={() => {}} - handleSave={async () => false} - reloadContent={() => {}} - /> - - ) -} - -describe('Monaco editor failure containment', () => { - let root: Root | null = null - let container: HTMLDivElement | null = null - - beforeEach(() => { - reportCrashMock.mockReset() - editorMounts.count = 0 - editorMounts.failure = null - vi.spyOn(console, 'error').mockImplementation(() => undefined) - container = document.createElement('div') - document.body.appendChild(container) - root = createRoot(container) - }) - - afterEach(() => { - act(() => root?.unmount()) - container?.remove() - root = null - container = null - vi.restoreAllMocks() - }) - - function render(): void { - act(() => { - root?.render() - }) - } - - function retryButton(): HTMLButtonElement { - const button = container?.querySelector('button') - if (!button) { - throw new Error('expected the contained-failure retry button') - } - return button - } - - it.each(['create', 'on-mount'] as const)( - 'contains a %s failure in the editor pane and still reports it', - (failure) => { - editorMounts.failure = failure - render() - - expect(container?.textContent).not.toContain(PAGE_BOUNDARY_TITLE) - expect(container?.querySelector('[data-testid="page-sibling"]')).not.toBeNull() - expect(container?.querySelector('[data-testid="monaco-editor"]')).toBeNull() - expect(container?.querySelector('[role="alert"]')).not.toBeNull() - expect(reportCrashMock).toHaveBeenCalledTimes(1) - expect(reportCrashMock.mock.calls[0]?.[0]).toMatchObject({ - boundaryId: 'editor.monaco', - surface: 'code-editor' - }) - } - ) - - it('remounts the editor when the contained failure is retried', () => { - editorMounts.failure = 'create' - render() - expect(editorMounts.count).toBe(1) - - editorMounts.failure = null - act(() => { - retryButton().click() - }) - - expect(editorMounts.count).toBe(2) - expect(container?.querySelector('[data-testid="monaco-editor"]')).not.toBeNull() - expect(container?.textContent).not.toContain(PAGE_BOUNDARY_TITLE) - }) -}) diff --git a/src/renderer/src/components/editor/EditorFileLoadErrorView.tsx b/src/renderer/src/components/editor/EditorFileLoadErrorView.tsx index f10b704d62b..88632ff7709 100644 --- a/src/renderer/src/components/editor/EditorFileLoadErrorView.tsx +++ b/src/renderer/src/components/editor/EditorFileLoadErrorView.tsx @@ -3,7 +3,7 @@ import { Button } from '@/components/ui/button' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' import { displayIpcErrorMessage } from '@/lib/ipc-error' -import { isFileTooLargeCodeMessage } from '../../../../shared/file-write-disk-precondition' +import { isFileTooLargeCodeMessage } from '../../../../shared/file-write/file-write-disk-precondition' import { WORKTREE_HOST_UNRESOLVED_CODE } from './editor-panel-content-types' import { useStoppedWslHost } from '../wsl-host-stopped/use-stopped-wsl-host' import { WslHostStoppedNotice } from '../wsl-host-stopped/WslHostStoppedNotice' diff --git a/src/renderer/src/components/editor/EditorPanelHeader.tsx b/src/renderer/src/components/editor/EditorPanelHeader.tsx index 19bc9e66fb3..0986d0781a4 100644 --- a/src/renderer/src/components/editor/EditorPanelHeader.tsx +++ b/src/renderer/src/components/editor/EditorPanelHeader.tsx @@ -21,7 +21,7 @@ import { EditorPanelHeaderPath } from './EditorPanelHeaderPath' import { useDiffNavigation } from './diff/review/diff-navigation-context' import { useShortcutKeyDetails } from '@/hooks/useShortcutLabel' import { ShortcutKeyCombo } from '@/components/ShortcutKeyCombo' -import type { ArtifactWriteRequest } from '../../../../shared/artifacts' +import type { ArtifactWriteRequest } from '../../../../shared/artifacts/artifacts' import { ArtifactPublishButton } from '@/components/artifacts/ArtifactPublishButton' import { editorArtifactSourceKey } from './editor-artifact-upload' diff --git a/src/renderer/src/components/editor/EditorPanelShell.tsx b/src/renderer/src/components/editor/EditorPanelShell.tsx index c410a166712..5a35d7ac583 100644 --- a/src/renderer/src/components/editor/EditorPanelShell.tsx +++ b/src/renderer/src/components/editor/EditorPanelShell.tsx @@ -11,7 +11,7 @@ import type { EditorToggleValue } from './view-mode/EditorViewToggle' import { shouldShowEditorPanelHeader } from './editor-header' import { getUntitledFileRoot } from './untitled-file-rename-path' import { useTranslate } from '@/i18n/use-translate' -import type { ArtifactWriteRequest } from '../../../../shared/artifacts' +import type { ArtifactWriteRequest } from '../../../../shared/artifacts/artifacts' import { selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields' type EditorPanelRenderModel = ReturnType diff --git a/src/renderer/src/components/editor/ImageViewer.tsx b/src/renderer/src/components/editor/ImageViewer.tsx index 2a6f8e0df1d..1fbb791e991 100644 --- a/src/renderer/src/components/editor/ImageViewer.tsx +++ b/src/renderer/src/components/editor/ImageViewer.tsx @@ -10,8 +10,8 @@ import { usePanZoomViewport } from './use-pan-zoom-viewport' import { useViewerZoomCommands } from './use-viewer-zoom-commands' import { useSvgObjectUrl } from './use-svg-object-url' import { useTranslate } from '@/i18n/use-translate' -import { buildImageDataUri } from '../../../../shared/image-data-uri' -import { decodeSvgBase64, readSvgIntrinsicSize } from '../../../../shared/svg-document' +import { buildImageDataUri } from '../../../../shared/file-preview/image-data-uri' +import { decodeSvgBase64, readSvgIntrinsicSize } from '../../../../shared/file-preview/svg-document' const FALLBACK_IMAGE_MIME_TYPE = 'image/png' const SVG_MIME_TYPE = 'image/svg+xml' diff --git a/src/renderer/src/components/editor/MonacoEditor.tsx b/src/renderer/src/components/editor/MonacoEditor.tsx index ca5cc6f1fee..4ee504c6c36 100644 --- a/src/renderer/src/components/editor/MonacoEditor.tsx +++ b/src/renderer/src/components/editor/MonacoEditor.tsx @@ -1,7 +1,7 @@ import React, { useRef, useEffect, useLayoutEffect, useMemo, useState } from 'react' import Editor from '@monaco-editor/react' import type { editor, IRange } from 'monaco-editor' -import type { MarkdownDocument } from '../../../../shared/filesystem-entry-types' +import type { MarkdownDocument } from '../../../../shared/file-listing/file-document' import { useAppStore } from '@/store' import '@/lib/monaco-setup' import { monacoTypographyOptions } from '@/lib/editor-typography' diff --git a/src/renderer/src/components/editor/absolute-tab-placement.test.ts b/src/renderer/src/components/editor/absolute-tab-placement.test.ts index 5631a0baa2f..6e0cc02f103 100644 --- a/src/renderer/src/components/editor/absolute-tab-placement.test.ts +++ b/src/renderer/src/components/editor/absolute-tab-placement.test.ts @@ -5,7 +5,7 @@ import { RuntimeRpcCallError } from '@/runtime/rpc/calls/runtime-rpc-result' import { SSH_OUTSIDE_WORKSPACE_UNSUPPORTED_MESSAGE, TERMINAL_ARTIFACT_IN_PLACE_MAX_BYTES -} from '../../../../shared/runtime-file-contracts' +} from '../../../../shared/terminal/runtime-terminal-file-path' const mocks = vi.hoisted(() => ({ findWorkspaceFileRoute: vi.fn(), diff --git a/src/renderer/src/components/editor/autosave/editor-autosave-conflict-flow.test.ts b/src/renderer/src/components/editor/autosave/editor-autosave-conflict-flow.test.ts index 980cd353256..29d6903c91a 100644 --- a/src/renderer/src/components/editor/autosave/editor-autosave-conflict-flow.test.ts +++ b/src/renderer/src/components/editor/autosave/editor-autosave-conflict-flow.test.ts @@ -13,7 +13,7 @@ import { stubEditorWindowWithDisk, withLoadedBaselines } from './editor-autosave-controller-test-fixture' -import { getDiskBaselineSignature } from '../../../../../shared/disk-baseline-signature' +import { getDiskBaselineSignature } from '../../../../../shared/file-write/disk-baseline-signature' const mocks = vi.hoisted(() => ({ getConnectionIdForFile: vi.fn() @@ -76,61 +76,6 @@ describe('editor autosave changed-on-disk conflict flow', () => { } }) - it('suspends autosave while a tab is marked changed-on-disk and resumes when cleared', async () => { - const writeFile = stubEditorWindow() - const store = createEditorStore() - openDirtyFile(store, 'user edit') - store.getState().setExternalMutation('/repo/file.ts', 'changed') - - const cleanup = attachEditorAutosaveController(withLoadedBaselines(store)) - try { - await vi.advanceTimersByTimeAsync(1500) - expect(writeFile).not.toHaveBeenCalled() - - store.getState().setExternalMutation('/repo/file.ts', null) - await vi.advanceTimersByTimeAsync(1500) - expect(writeFile).toHaveBeenCalledWith( - expect.objectContaining({ - filePath: '/repo/file.ts', - content: 'user edit', - connectionId: undefined, - expectedExecutionHostId: 'local' - }) - ) - } finally { - cleanup() - } - }) - - describe('a restored draft autosaves through the guarded write alone', () => { - // Why: hydration restores the draft with the persisted baseline; nothing pauses its autosave. - function restore(disk: string) { - const fakeDisk = stubEditorWindowWithDisk(createFakeEditorDisk({ '/repo/file.ts': disk })) - const store = createEditorStore() - openDirtyFile(store, 'restored draft') - store.getState().setLastKnownDiskSignature('/repo/file.ts', getDiskBaselineSignature('base')) - return { fakeDisk, store, cleanup: attachEditorAutosaveController(store) } - } - - it('is refused with the banner, keeps the draft and stops autosaving when disk changed', async () => { - const { fakeDisk, store, cleanup } = restore('agent write') - try { - await vi.advanceTimersByTimeAsync(1500) - expect(fakeDisk.files.get('/repo/file.ts')).toBe('agent write') - expect(store.getState().openFiles[0]).toMatchObject({ - isDirty: true, - externalMutation: 'changed' - }) - expect(store.getState().editorDrafts['/repo/file.ts']).toBe('restored draft') - - await vi.advanceTimersByTimeAsync(5000) - expect(fakeDisk.fs.writeFile).toHaveBeenCalledTimes(1) - } finally { - cleanup() - } - }) - }) - // A custom editor's Cmd+S reaches this same explicit save after flushing its frame. it('refuses an explicit save while the banner shows, keeping the edits and the disk', async () => { const fakeDisk = stubEditorWindowWithDisk( diff --git a/src/renderer/src/components/editor/autosave/editor-autosave-controller-test-fixture.ts b/src/renderer/src/components/editor/autosave/editor-autosave-controller-test-fixture.ts index 6369a90d343..1329260d818 100644 --- a/src/renderer/src/components/editor/autosave/editor-autosave-controller-test-fixture.ts +++ b/src/renderer/src/components/editor/autosave/editor-autosave-controller-test-fixture.ts @@ -7,11 +7,11 @@ import { withEditorBufferRecords } from '@/store/slices/editor/buffers/editor-bu import type { AppState } from '@/store/types' import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' import { emptyTabLayoutState } from '@/store/slices/editor/editor-slice-test-harness' -import { getDiskBaselineSignature } from '../../../../../shared/disk-baseline-signature' +import { getDiskBaselineSignature } from '../../../../../shared/file-write/disk-baseline-signature' import { compareDiskWritePrecondition, type FileWriteDiskPrecondition -} from '../../../../../shared/file-write-disk-precondition' +} from '../../../../../shared/file-write/file-write-disk-precondition' export type FakeEditorDisk = { files: Map diff --git a/src/renderer/src/components/editor/combined-diff/load-sections/combined-diff-on-demand-load.ts b/src/renderer/src/components/editor/combined-diff/load-sections/combined-diff-on-demand-load.ts index 5eef2bd5042..8e6c68e28a5 100644 --- a/src/renderer/src/components/editor/combined-diff/load-sections/combined-diff-on-demand-load.ts +++ b/src/renderer/src/components/editor/combined-diff/load-sections/combined-diff-on-demand-load.ts @@ -1,4 +1,4 @@ -import { hasBinaryFileExtension } from '../../../../../../shared/binary-file-extensions' +import { hasBinaryFileExtension } from '../../../../../../shared/file-preview/binary-file-extensions' import type { GitBranchChangeEntry } from '../../../../../../shared/git/diff/git-diff-compare-types' import type { GitStatusEntry } from '../../../../../../shared/git/status/git-status-types' diff --git a/src/renderer/src/components/editor/combined-diff/review-controls/use-combined-diff-section-actions.disk-precondition.test.tsx b/src/renderer/src/components/editor/combined-diff/review-controls/use-combined-diff-section-actions.disk-precondition.test.tsx index 44f7530e455..e5fac9b086b 100644 --- a/src/renderer/src/components/editor/combined-diff/review-controls/use-combined-diff-section-actions.disk-precondition.test.tsx +++ b/src/renderer/src/components/editor/combined-diff/review-controls/use-combined-diff-section-actions.disk-precondition.test.tsx @@ -1,8 +1,8 @@ // @vitest-environment happy-dom import { act, cleanup, renderHook } from '@testing-library/react' -import type React from 'react' + import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { getDiskBaselineSignature } from '../../../../../../shared/disk-baseline-signature' + import type { DiffSection } from '../../diff/sections/diff-section-types' import type { OpenFile } from '@/store/slices/editor/types/open-file' import { useCombinedDiffSectionActions } from './use-combined-diff-section-actions' @@ -11,18 +11,8 @@ import { useAppStore } from '@/store' import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' import { TEST_REPO } from '@/store/repos/repo.test-fixture' import { acquireCombinedDiffSectionOperation } from '../load-sections/combined-diff-section-connection' -import { fetchCombinedDiffSection } from '../load-sections/fetch-combined-diff-section' -import { - makeFolderWorkspace, - makeProjectGroup -} from '@/components/sidebar/workspace-creation/folder/folder-workspace-composer-submit-fixtures' -const mocks = vi.hoisted(() => ({ writeRuntimeFile: vi.fn(), diff: vi.fn() })) -vi.mock('@/runtime/source-control/git/runtime-git-diff-client', () => ({ - getRuntimeGitDiff: mocks.diff, - getRuntimeGitBranchDiff: mocks.diff, - getRuntimeGitCommitDiff: mocks.diff -})) +const mocks = vi.hoisted(() => ({ writeRuntimeFile: vi.fn() })) vi.mock('@/runtime/files/mutations/runtime-file-mutation-client', () => ({ writeRuntimeFile: mocks.writeRuntimeFile @@ -41,7 +31,6 @@ beforeEach(() => { afterEach(() => { cleanup() mocks.writeRuntimeFile.mockReset() - mocks.diff.mockReset() }) const file: OpenFile = { @@ -116,219 +105,3 @@ it('refuses to guess a version for a load whose bodies were pruned', async () => expect(mocks.writeRuntimeFile).not.toHaveBeenCalled() expect(setSections.mock.calls[0]?.[0]([pruned])).toEqual([{ ...pruned, saveConflict: true }]) }) - -it('serializes overlapping saves of one section and never clobbers newer edits', async () => { - let resolveFirst: (value: { ok: true }) => void = () => undefined - let resolveSecond: (value: { ok: true }) => void = () => undefined - mocks.writeRuntimeFile - .mockImplementationOnce( - () => - new Promise((resolve) => { - resolveFirst = resolve - }) - ) - .mockImplementationOnce( - () => - new Promise((resolve) => { - resolveSecond = resolve - }) - ) - const sectionsRef: { current: DiffSection[] } = { - current: [{ ...section(), modifiedContent: 'first' }] - } - const setSections = vi.fn((update: React.SetStateAction) => { - sectionsRef.current = typeof update === 'function' ? update(sectionsRef.current) : update - }) - const { result } = renderHook(() => - useCombinedDiffSectionActions({ - activeGroupId: undefined, - branchCompare: null, - canOpenWorkspaceFileBrowserForPath: () => false, - commitCompare: null, - file, - isAllMode: false, - isBranchMode: false, - isCommitMode: false, - sections: sectionsRef.current, - sectionsRef, - setSectionHeights: vi.fn(), - setSections - }) - ) - - const first = result.current.handleSectionSaveRef.current(0) - await act(async () => undefined) - // The user keeps typing while the first write is in flight, then saves again. - sectionsRef.current = [{ ...sectionsRef.current[0], modifiedContent: 'second' }] - const second = result.current.handleSectionSaveRef.current(0) - await act(async () => undefined) - expect(mocks.writeRuntimeFile).toHaveBeenCalledTimes(1) - - resolveFirst({ ok: true }) - await act(() => first) - // The older write moved only the baseline; the newer text stays unsaved. - expect(sectionsRef.current[0]).toMatchObject({ modifiedContent: 'second', dirty: true }) - expect(mocks.writeRuntimeFile).toHaveBeenCalledTimes(2) - - resolveSecond({ ok: true }) - await act(() => second) - expect(mocks.writeRuntimeFile.mock.calls[1]?.[2]).toBe('second') - expect(mocks.writeRuntimeFile.mock.calls[1]?.[4]).toEqual({ - expectedSignature: getDiskBaselineSignature('first'), - allowMissing: false - }) - expect(sectionsRef.current[0]).toMatchObject({ modifiedContent: 'second', dirty: false }) -}) - -it('applies a queued save to the section clicked even after rows are rebuilt', async () => { - let resolveFirst: (value: { ok: true }) => void = () => undefined - mocks.writeRuntimeFile - .mockImplementationOnce( - () => - new Promise((resolve) => { - resolveFirst = resolve - }) - ) - .mockResolvedValue({ ok: true }) - const clicked: DiffSection = { - ...section(), - key: 'b.ts', - path: 'b.ts', - modifiedContent: 'b edit' - } - const sectionsRef: { current: DiffSection[] } = { - current: [{ ...section(), modifiedContent: 'a edit' }, clicked] - } - const { result } = renderHook(() => - useCombinedDiffSectionActions({ - activeGroupId: undefined, - branchCompare: null, - canOpenWorkspaceFileBrowserForPath: () => false, - commitCompare: null, - file, - isAllMode: false, - isBranchMode: false, - isCommitMode: false, - sections: sectionsRef.current, - sectionsRef, - setSectionHeights: vi.fn(), - setSections: vi.fn() - }) - ) - - const first = result.current.handleSectionSaveRef.current(1) - await act(async () => undefined) - const overwrite = result.current.handleSectionSaveRef.current(1, 'overwrite') - // The list is rebuilt while both wait: the clicked section moves to index 0. - sectionsRef.current = [clicked, { ...section(), modifiedContent: 'a edit' }] - resolveFirst({ ok: true }) - await act(() => Promise.all([first, overwrite])) - - const paths = mocks.writeRuntimeFile.mock.calls.map(([, path]) => path) - expect(paths).toEqual(['/repo/b.ts', '/repo/b.ts']) - expect(mocks.writeRuntimeFile.mock.calls[1]?.[4]).toBeUndefined() -}) - -it.each(['worktree', 'branch', 'commit'] as const)( - 'retains a mixed-folder canonical SSH read through %s diff Save and refuses a retarget', - async (mode) => { - const template = section() - const combined = { - ...file, - worktreeId: 'folder:folder-workspace-1', - filePath: '/repo/platform' - } - const local = { - ...TEST_REPO, - id: 'local', - projectGroupId: 'group-1', - path: '/repo/platform/web' - } - const ssh = { - ...TEST_REPO, - id: 'ssh', - projectGroupId: 'group-1', - path: '/repo/platform/api', - executionHostId: 'ssh:box' as const - } - useAppStore.setState({ - openFiles: [combined], - worktreesByRepo: {}, - folderWorkspaces: [makeFolderWorkspace({ folderPath: combined.filePath })], - projectGroups: [makeProjectGroup()], - repos: [local, ssh], - sshConnectionStates: new Map( - ['box', 'other'].map((targetId) => [ - targetId, - { - targetId, - status: 'connected' as const, - error: null, - reconnectAttempt: 0, - connectionGeneration: 7 - } - ]) - ) - }) - mocks.diff.mockResolvedValue(template.diffResult) - const loaded = await fetchCombinedDiffSection({ - file: combined, - entry: { path: 'api/a.ts', status: 'modified', area: 'unstaged' }, - branchCompare: { - baseRef: 'main', - compareRef: 'branch', - baseOid: 'a', - headOid: 'b', - mergeBase: 'c', - compareVersion: '1' - }, - commitCompare: { - baseRef: 'main', - compareRef: 'commit', - commitOid: 'a', - parentOid: 'b', - compareVersion: '1' - }, - isAllMode: false, - isBranchMode: mode === 'branch', - isCommitMode: mode === 'commit' - }) - expect(mocks.diff.mock.calls[0][0]).toMatchObject({ - target: { kind: 'local' }, - connectionId: 'box', - expectedExecutionHostId: 'ssh:box' - }) - const sections = [ - { - ...template, - key: 'api/a.ts', - path: 'api/a.ts', - diffResult: loaded.result, - operation: loaded.operation - } - ] - const sectionsRef = { current: sections } - const { result } = renderHook(() => - useCombinedDiffSectionActions({ - activeGroupId: undefined, - branchCompare: null, - commitCompare: null, - canOpenWorkspaceFileBrowserForPath: () => false, - file: combined, - isAllMode: false, - isBranchMode: false, - isCommitMode: false, - sections, - sectionsRef, - setSectionHeights: vi.fn(), - setSections: vi.fn() - }) - ) - mocks.writeRuntimeFile.mockResolvedValue({ ok: true }) - await act(() => result.current.handleSectionSaveRef.current(0)) - expect(mocks.writeRuntimeFile.mock.calls[0][0]).toMatchObject(mocks.diff.mock.calls[0][0]) - useAppStore.setState({ repos: [local, { ...ssh, executionHostId: 'ssh:other' }] }) - await act(() => result.current.handleSectionSaveRef.current(0)) - expect(mocks.writeRuntimeFile).toHaveBeenCalledOnce() - } -) diff --git a/src/renderer/src/components/editor/combined-diff/review-controls/use-combined-diff-section-save.ts b/src/renderer/src/components/editor/combined-diff/review-controls/use-combined-diff-section-save.ts index c11321922f0..9053fc541e0 100644 --- a/src/renderer/src/components/editor/combined-diff/review-controls/use-combined-diff-section-save.ts +++ b/src/renderer/src/components/editor/combined-diff/review-controls/use-combined-diff-section-save.ts @@ -12,7 +12,7 @@ import { isPrunedTextDiffResult } from '../../diff/large-files/large-diff-section-content' import { removeDiffSectionMeasuredHeight } from '../../diff/sections/diff-section-height-cache' -import { getDiskBaselineSignature } from '../../../../../../shared/disk-baseline-signature' +import { getDiskBaselineSignature } from '../../../../../../shared/file-write/disk-baseline-signature' import { writeEditorSave } from '../../save/queue/editor-save-disk-precondition' import { withEditorFileWriteLock } from '../../save/queue/editor-file-write-lock' import { editorPathHoldKey } from '../../autosave/editor-autosave-holds' diff --git a/src/renderer/src/components/editor/csv/csv-paged-preview.ts b/src/renderer/src/components/editor/csv/csv-paged-preview.ts index 86b0c71f54b..bab64afb80a 100644 --- a/src/renderer/src/components/editor/csv/csv-paged-preview.ts +++ b/src/renderer/src/components/editor/csv/csv-paged-preview.ts @@ -1,4 +1,4 @@ -import { MAX_FILE_RANGE_READ_BYTES } from '../../../../../shared/file-range-read' +import { MAX_FILE_RANGE_READ_BYTES } from '../../../../../shared/file-content/file-range-read' import { readRuntimeFileRange, statRuntimeReadTarget diff --git a/src/renderer/src/components/editor/document-images/local-image-src-reader.ts b/src/renderer/src/components/editor/document-images/local-image-src-reader.ts index 47464318e10..696b661c6d7 100644 --- a/src/renderer/src/components/editor/document-images/local-image-src-reader.ts +++ b/src/renderer/src/components/editor/document-images/local-image-src-reader.ts @@ -1,4 +1,4 @@ -import type { LocalFileAccess } from '../../../../../shared/local-file-access' +import type { LocalFileAccess } from '../../../../../shared/file-access/local-file-access' import type { RuntimeFileOperationArgs } from '@/runtime/files/runtime-file-client-types' import { readRuntimeFilePreview } from '@/runtime/files/reads/runtime-file-read-client' diff --git a/src/renderer/src/components/editor/document-images/useLocalImageSrc.ts b/src/renderer/src/components/editor/document-images/useLocalImageSrc.ts index dfa76433c76..95e36cf2b31 100644 --- a/src/renderer/src/components/editor/document-images/useLocalImageSrc.ts +++ b/src/renderer/src/components/editor/document-images/useLocalImageSrc.ts @@ -2,7 +2,7 @@ import { useEffect, useEffectEvent, useState } from 'react' import { resolveImageAbsolutePath } from '../markdown/link-routing/markdown-preview-links' import type { RuntimeFileOperationArgs } from '@/runtime/files/runtime-file-client-types' import { readLocalImagePreview } from './local-image-src-reader' -import type { LocalFileAccess } from '../../../../../shared/local-file-access' +import type { LocalFileAccess } from '../../../../../shared/file-access/local-file-access' import { blobUrlCache, cacheLocalImageBlob, diff --git a/src/renderer/src/components/editor/editor-artifact-upload.ts b/src/renderer/src/components/editor/editor-artifact-upload.ts index a482378cb44..8cc84e3ed32 100644 --- a/src/renderer/src/components/editor/editor-artifact-upload.ts +++ b/src/renderer/src/components/editor/editor-artifact-upload.ts @@ -1,4 +1,4 @@ -import type { ArtifactWriteRequest } from '../../../../shared/artifacts' +import type { ArtifactWriteRequest } from '../../../../shared/artifacts/artifacts' import { fileArtifactSourceKey, type FileArtifactOwner } from '@/lib/file-artifact-source-key' import { basename } from '@/lib/path' import { useAppStore } from '@/store' diff --git a/src/renderer/src/components/editor/external-changes/ExternalFileChangeBanner.tsx b/src/renderer/src/components/editor/external-changes/ExternalFileChangeBanner.tsx index 61416d831f9..d0a7c7b8f02 100644 --- a/src/renderer/src/components/editor/external-changes/ExternalFileChangeBanner.tsx +++ b/src/renderer/src/components/editor/external-changes/ExternalFileChangeBanner.tsx @@ -11,7 +11,7 @@ import { translate } from '@/i18n/i18n' import { useTranslate } from '@/i18n/use-translate' import type { OpenFile } from '@/store/slices/editor/types/open-file' import { ExternalFileChangeCompareDialog } from './ExternalFileChangeCompareDialog' -import { getDiskBaselineSignature } from '../../../../../shared/disk-baseline-signature' +import { getDiskBaselineSignature } from '../../../../../shared/file-write/disk-baseline-signature' import { trackExternalChangeConflictAction } from './editor-external-change-telemetry' import { attemptEditorFileSave } from '../save/commands/editor-file-save-attempt' import { diff --git a/src/renderer/src/components/editor/external-changes/editor-clean-tab-disk-baseline.ts b/src/renderer/src/components/editor/external-changes/editor-clean-tab-disk-baseline.ts index 9ff0bdd22d5..831934b7727 100644 --- a/src/renderer/src/components/editor/external-changes/editor-clean-tab-disk-baseline.ts +++ b/src/renderer/src/components/editor/external-changes/editor-clean-tab-disk-baseline.ts @@ -2,7 +2,7 @@ import { useAppStore } from '@/store/index' import type { AppState } from '@/store/types' import type { OpenFile } from '@/store/slices/editor/types/open-file' import { isEditorContentUnchanged } from '../model-lifetime/buffer-text/editor-content-dirty-state' -import { getDiskBaselineSignature } from '../../../../../shared/disk-baseline-signature' +import { getDiskBaselineSignature } from '../../../../../shared/file-write/disk-baseline-signature' import type { FileContent } from '../editor-panel-content-types' import { editorModelSiblingTabs, diff --git a/src/renderer/src/components/editor/external-changes/editor-clean-tab-draft-invariant.test.ts b/src/renderer/src/components/editor/external-changes/editor-clean-tab-draft-invariant.test.ts index 46244b09840..5583a882650 100644 --- a/src/renderer/src/components/editor/external-changes/editor-clean-tab-draft-invariant.test.ts +++ b/src/renderer/src/components/editor/external-changes/editor-clean-tab-draft-invariant.test.ts @@ -5,7 +5,7 @@ import { __clearSelfWriteRegistryForTests } from './editor-self-write-registry' import { createEditorStore } from '../autosave/editor-autosave-controller-test-fixture' import { stampCleanTabDiskBaseline } from './editor-clean-tab-disk-baseline' -import { getDiskBaselineSignature } from '../../../../../shared/disk-baseline-signature' +import { getDiskBaselineSignature } from '../../../../../shared/file-write/disk-baseline-signature' import { GUARDED_PATH, stubGuardedDisk } from '../save/queue/editor-save-guarded-disk-fixture' const storeRef = vi.hoisted((): { current: ReturnType | null } => ({ diff --git a/src/renderer/src/components/editor/external-changes/editor-external-watch-path-index.ts b/src/renderer/src/components/editor/external-changes/editor-external-watch-path-index.ts index c980aa3845a..28d52a8b5f2 100644 --- a/src/renderer/src/components/editor/external-changes/editor-external-watch-path-index.ts +++ b/src/renderer/src/components/editor/external-changes/editor-external-watch-path-index.ts @@ -2,7 +2,7 @@ import { joinPath } from '@/lib/path' import '@/components/right-sidebar/file-explorer/watching/useFileExplorerWatch' import { getExternalFileChangeRelativePath } from '@/components/right-sidebar/file-explorer/watching/file-explorer-watch-path' import type { OpenFile } from '@/store/slices/editor/types/open-file' -import type { FsChangedPayload } from '../../../../../shared/filesystem-entry-types' +import type { FsChangedPayload } from '../../../../../shared/file-watch/filesystem-change-event' import { externalChangePathKeyFor } from '@/store/slices/editor/buffers/editor-buffer-identity' import { getLocalWindowsWslPathIdentity, diff --git a/src/renderer/src/components/editor/external-changes/editor-restored-tab-conflict-scan.recheck.test.ts b/src/renderer/src/components/editor/external-changes/editor-restored-tab-conflict-scan.recheck.test.ts index c8ed4ff6188..62b04a4a8b5 100644 --- a/src/renderer/src/components/editor/external-changes/editor-restored-tab-conflict-scan.recheck.test.ts +++ b/src/renderer/src/components/editor/external-changes/editor-restored-tab-conflict-scan.recheck.test.ts @@ -22,7 +22,7 @@ vi.mock('@/lib/file-owner-runtime-target', () => { import { createTestStore } from '@/store/testing/app-store-test-fixture' import { attachRestoredTabConflictScan } from './editor-restored-tab-conflict-scan' -import { getDiskBaselineSignature } from '../../../../../shared/disk-baseline-signature' +import { getDiskBaselineSignature } from '../../../../../shared/file-write/disk-baseline-signature' const FILE = '/repo/a.ts' let store: ReturnType diff --git a/src/renderer/src/components/editor/external-changes/editor-restored-tab-conflict-scan.test.ts b/src/renderer/src/components/editor/external-changes/editor-restored-tab-conflict-scan.test.ts index ca959311527..26a37718b04 100644 --- a/src/renderer/src/components/editor/external-changes/editor-restored-tab-conflict-scan.test.ts +++ b/src/renderer/src/components/editor/external-changes/editor-restored-tab-conflict-scan.test.ts @@ -4,7 +4,7 @@ import { createTestStore } from '@/store/testing/app-store-test-fixture' import type { AppState } from '@/store/types' import { attachRestoredTabConflictScan } from './editor-restored-tab-conflict-scan' -import { getDiskBaselineSignature } from '../../../../../shared/disk-baseline-signature' +import { getDiskBaselineSignature } from '../../../../../shared/file-write/disk-baseline-signature' import { __clearSelfWriteRegistryForTests, recordSelfWrite } from './editor-self-write-registry' const mocks = vi.hoisted(() => ({ @@ -93,118 +93,6 @@ describe('attachRestoredTabConflictScan', () => { } }) - it('does not verify a tab dirtied after the scan attached', async () => { - const store = createTestStore() - const detach = attachRestoredTabConflictScan(store) - store.getState().openFile({ - filePath: '/repo/live.ts', - relativePath: 'live.ts', - worktreeId: 'wt-1', - language: 'typescript', - mode: 'edit' - }) - store.getState().setEditorDraft('/repo/live.ts', 'live edits') - store.getState().markFileDirty('/repo/live.ts', true) - store.getState().setLastKnownDiskSignature('/repo/live.ts', getDiskBaselineSignature('base')) - - try { - await vi.advanceTimersByTimeAsync(10) - // Leave in-session drift to live watchers; polling here would misattribute later conflicts to restoration. - expect(mocks.readRuntimeFileContent).not.toHaveBeenCalled() - } finally { - detach() - } - }) - - it('resolves verification with a deleted mark when the file is definitively gone', async () => { - mocks.readRuntimeFileContent.mockRejectedValue(new Error('ENOENT')) - mocks.pathExists.mockResolvedValue(false) - const store = createTestStore() - openRestoredDirtyTab(store, '/repo/deleted.ts', 'original baseline') - - const detach = attachRestoredTabConflictScan(store) - try { - await vi.advanceTimersByTimeAsync(10) - const tab = store.getState().openFiles[0] - expect(tab?.externalMutation).toBe('deleted') - await vi.advanceTimersByTimeAsync(60_000) - expect(mocks.readRuntimeFileContent).toHaveBeenCalledTimes(1) - } finally { - detach() - } - }) - - it('keeps retrying when the existence probe fails', async () => { - // Why: a transport that is down cannot disprove existence. - mocks.readRuntimeFileContent.mockRejectedValue(new Error('connection not ready')) - mocks.pathExists.mockRejectedValue(new Error('connection not ready')) - const store = createTestStore() - openRestoredDirtyTab(store, '/repo/unreachable.ts', 'original baseline') - - const detach = attachRestoredTabConflictScan(store) - try { - await vi.advanceTimersByTimeAsync(10) - await vi.advanceTimersByTimeAsync(2_100) - const tab = store.getState().openFiles[0] - expect(tab?.externalMutation).toBeUndefined() - expect(mocks.readRuntimeFileContent.mock.calls.length).toBeGreaterThan(1) - } finally { - detach() - } - }) - - it('does not verify an external SSH file through a replacement target', async () => { - const store = createTestStore() - openRestoredDirtyTab(store, '/tmp/external.ts', 'original baseline') - store.setState({ - openFiles: store - .getState() - .openFiles.map((file) => ({ ...file, externalSshTargetId: 'ssh-original' })) - } as never) - mocks.getConnectionIdForFile.mockReturnValue('ssh-replacement') - - const detach = attachRestoredTabConflictScan(store) - try { - await vi.advanceTimersByTimeAsync(10) - expect(mocks.readRuntimeFileContent).not.toHaveBeenCalled() - expect(mocks.pathExists).not.toHaveBeenCalled() - } finally { - detach() - } - }) - - it('caps concurrent verification reads and drains the queue without dropping tabs', async () => { - // Limit restored-tab reads so remote RPCs cannot overwhelm connection recovery; queued tabs must all complete. - const pendingReads: ((value: { content: string; isBinary: boolean }) => void)[] = [] - mocks.readRuntimeFileContent.mockImplementation( - () => - new Promise<{ content: string; isBinary: boolean }>((resolve) => { - pendingReads.push(resolve) - }) - ) - const store = createTestStore() - for (let i = 0; i < 6; i++) { - openRestoredDirtyTab(store, `/repo/file-${i}.ts`, 'original baseline') - } - - const detach = attachRestoredTabConflictScan(store) - try { - expect(mocks.readRuntimeFileContent).toHaveBeenCalledTimes(3) - - pendingReads.shift()!({ content: 'original baseline', isBinary: false }) - await vi.advanceTimersByTimeAsync(10) - expect(mocks.readRuntimeFileContent).toHaveBeenCalledTimes(4) - - while (pendingReads.length > 0) { - pendingReads.shift()!({ content: 'original baseline', isBinary: false }) - await vi.advanceTimersByTimeAsync(10) - } - expect(mocks.readRuntimeFileContent).toHaveBeenCalledTimes(6) - } finally { - detach() - } - }) - it('does not mark a tab that was saved while the read was in flight', async () => { let resolveRead: (value: { content: string; isBinary: boolean }) => void = () => {} mocks.readRuntimeFileContent.mockReturnValue( @@ -225,48 +113,4 @@ describe('attachRestoredTabConflictScan', () => { detach() } }) - - it('verifies a queued tab against its live baseline, not the stale queued snapshot', async () => { - // Queued IDs can be saved or reopened before dispatch; compare current baselines rather than captured OpenFile snapshots. - const pending: { - filePath: string - resolve: (value: { content: string; isBinary: boolean }) => void - }[] = [] - mocks.readRuntimeFileContent.mockImplementation( - ({ filePath }: { filePath: string }) => - new Promise<{ content: string; isBinary: boolean }>((resolve) => { - pending.push({ filePath, resolve }) - }) - ) - const store = createTestStore() - for (let i = 0; i < 4; i++) { - openRestoredDirtyTab(store, `/repo/file-${i}.ts`, 'stale baseline') - } - - const detach = attachRestoredTabConflictScan(store) - try { - expect(mocks.readRuntimeFileContent).toHaveBeenCalledTimes(3) - - store - .getState() - .setLastKnownDiskSignature('/repo/file-3.ts', getDiskBaselineSignature('current disk')) - - for (const filePath of ['/repo/file-0.ts', '/repo/file-1.ts', '/repo/file-2.ts']) { - pending - .find((p) => p.filePath === filePath)! - .resolve({ content: 'stale baseline', isBinary: false }) - await vi.advanceTimersByTimeAsync(10) - } - - pending - .find((p) => p.filePath === '/repo/file-3.ts')! - .resolve({ content: 'current disk', isBinary: false }) - await vi.advanceTimersByTimeAsync(10) - - const tab = store.getState().openFiles.find((f) => f.id === '/repo/file-3.ts') - expect(tab?.externalMutation).toBeUndefined() - } finally { - detach() - } - }) }) diff --git a/src/renderer/src/components/editor/external-changes/editor-restored-tab-conflict-scan.ts b/src/renderer/src/components/editor/external-changes/editor-restored-tab-conflict-scan.ts index 7f2e628eb2d..773167b2108 100644 --- a/src/renderer/src/components/editor/external-changes/editor-restored-tab-conflict-scan.ts +++ b/src/renderer/src/components/editor/external-changes/editor-restored-tab-conflict-scan.ts @@ -10,7 +10,7 @@ import { requireRuntimeTargetForFileOwner } from '@/lib/file-owner-runtime-target' import { canAutoSaveOpenFile } from '../autosave/editor-autosave' -import { getDiskBaselineSignature } from '../../../../../shared/disk-baseline-signature' +import { getDiskBaselineSignature } from '../../../../../shared/file-write/disk-baseline-signature' import { markFileChangedOnDisk } from './editor-changed-on-disk-mark' import { runtimePathsExist } from '@/runtime/files/metadata/runtime-path-existence-batch' import { getRecentSelfWrite } from './editor-self-write-registry' diff --git a/src/renderer/src/components/editor/image-png-export.ts b/src/renderer/src/components/editor/image-png-export.ts index f7e8ca216eb..c9b8ee933e0 100644 --- a/src/renderer/src/components/editor/image-png-export.ts +++ b/src/renderer/src/components/editor/image-png-export.ts @@ -4,7 +4,7 @@ import { assertClipboardImageDimensionsWithinLimit } from '../../../../shared/clipboard-image' import type { PanZoomSize } from '../../../../shared/pan-zoom-view' -import { svgMarkupDataUri } from '../../../../shared/svg-document' +import { svgMarkupDataUri } from '../../../../shared/file-preview/svg-document' import { blobToBase64, convertImageBlobToPng } from '../../lib/image-blob-png' const PREFERRED_PIXEL_RATIO = 2 diff --git a/src/renderer/src/components/editor/markdown-preview/render-tree/markdown-preview-types.ts b/src/renderer/src/components/editor/markdown-preview/render-tree/markdown-preview-types.ts index 04c08473636..42ec4540d41 100644 --- a/src/renderer/src/components/editor/markdown-preview/render-tree/markdown-preview-types.ts +++ b/src/renderer/src/components/editor/markdown-preview/render-tree/markdown-preview-types.ts @@ -1,4 +1,4 @@ -import type { MarkdownDocument } from '../../../../../../shared/filesystem-entry-types' +import type { MarkdownDocument } from '../../../../../../shared/file-listing/file-document' import type { EditorFileOperationProvenance } from '@/lib/editor-file-operation-provenance' export type MarkdownPreviewProps = { diff --git a/src/renderer/src/components/editor/markdown-preview/render-tree/use-markdown-preview-components.tsx b/src/renderer/src/components/editor/markdown-preview/render-tree/use-markdown-preview-components.tsx index 61dc7107cbe..0068f47e6fc 100644 --- a/src/renderer/src/components/editor/markdown-preview/render-tree/use-markdown-preview-components.tsx +++ b/src/renderer/src/components/editor/markdown-preview/render-tree/use-markdown-preview-components.tsx @@ -1,6 +1,6 @@ import React, { useMemo } from 'react' import type { Components } from 'react-markdown' -import type { MarkdownDocument } from '../../../../../../shared/filesystem-entry-types' +import type { MarkdownDocument } from '../../../../../../shared/file-listing/file-document' import CodeBlockCopyButton from '../../CodeBlockCopyButton' import MermaidBlock from '../../MermaidBlock' import { useMermaidDiagramExpand } from '../../use-mermaid-diagram-expand' diff --git a/src/renderer/src/components/editor/markdown-preview/surface/MarkdownPreview.tsx b/src/renderer/src/components/editor/markdown-preview/surface/MarkdownPreview.tsx index 485223896c4..a99f11a1a79 100644 --- a/src/renderer/src/components/editor/markdown-preview/surface/MarkdownPreview.tsx +++ b/src/renderer/src/components/editor/markdown-preview/surface/MarkdownPreview.tsx @@ -1,6 +1,6 @@ import { useCallback, useRef } from 'react' import { VIRTUALIZED_SCROLL_ANCHOR_RECORD_EVENT } from '@/hooks/useVirtualizedScrollAnchor' -import type { MarkdownDocument } from '../../../../../../shared/filesystem-entry-types' +import type { MarkdownDocument } from '../../../../../../shared/file-listing/file-document' import { MarkdownPreviewSurface } from './MarkdownPreviewSurface' import type { MarkdownPreviewProps } from '../render-tree/markdown-preview-types' import { useMarkdownPreviewAnnotationRenderers } from '../review/use-markdown-preview-annotation-renderers' diff --git a/src/renderer/src/components/editor/markdown-preview/surface/use-markdown-preview-foundation.ts b/src/renderer/src/components/editor/markdown-preview/surface/use-markdown-preview-foundation.ts index 19715b7bf72..0dfabf4cd0a 100644 --- a/src/renderer/src/components/editor/markdown-preview/surface/use-markdown-preview-foundation.ts +++ b/src/renderer/src/components/editor/markdown-preview/surface/use-markdown-preview-foundation.ts @@ -6,7 +6,7 @@ import { sortMarkdownReviewNotes, type MarkdownReviewNote } from '@/lib/markdown-review-notes' -import type { MarkdownDocument } from '../../../../../../shared/filesystem-entry-types' +import type { MarkdownDocument } from '../../../../../../shared/file-listing/file-document' import { createMarkdownDocumentIndex } from '../../markdown/documents/markdown-doc-links' import { exceedsMarkdownRichModeSizeLimit } from '../../markdown/render-mode/markdown-rich-size-limit' import { previewHasAnnotationBlockKey } from '../review/markdown-preview-annotation-shortcut' diff --git a/src/renderer/src/components/editor/markdown-source-tools/monaco/monaco-markdown-doc-completions-retention.test.ts b/src/renderer/src/components/editor/markdown-source-tools/monaco/monaco-markdown-doc-completions-retention.test.ts index 7600a408eac..19e746b92fd 100644 --- a/src/renderer/src/components/editor/markdown-source-tools/monaco/monaco-markdown-doc-completions-retention.test.ts +++ b/src/renderer/src/components/editor/markdown-source-tools/monaco/monaco-markdown-doc-completions-retention.test.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { cleanup, render } from '@testing-library/react' import { createElement, useLayoutEffect, useRef } from 'react' -import type { MarkdownDocument } from '../../../../../../shared/filesystem-entry-types' +import type { MarkdownDocument } from '../../../../../../shared/file-listing/file-document' import { useMonacoEditorDecorations } from '../../use-monaco-editor-decorations' import type { editor, languages, Position } from 'monaco-editor' import type { OnMount } from '@monaco-editor/react' diff --git a/src/renderer/src/components/editor/markdown-source-tools/monaco/monaco-markdown-doc-completions.ts b/src/renderer/src/components/editor/markdown-source-tools/monaco/monaco-markdown-doc-completions.ts index 6965bd64327..d31743602fa 100644 --- a/src/renderer/src/components/editor/markdown-source-tools/monaco/monaco-markdown-doc-completions.ts +++ b/src/renderer/src/components/editor/markdown-source-tools/monaco/monaco-markdown-doc-completions.ts @@ -1,6 +1,6 @@ import type { OnMount } from '@monaco-editor/react' import type { IDisposable, editor } from 'monaco-editor' -import type { MarkdownDocument } from '../../../../../../shared/filesystem-entry-types' +import type { MarkdownDocument } from '../../../../../../shared/file-listing/file-document' import { getMarkdownDocCompletionContext, getMarkdownDocCompletionDocuments diff --git a/src/renderer/src/components/editor/markdown/documents/markdown-doc-completions.ts b/src/renderer/src/components/editor/markdown/documents/markdown-doc-completions.ts index eb2ea579559..251a7501525 100644 --- a/src/renderer/src/components/editor/markdown/documents/markdown-doc-completions.ts +++ b/src/renderer/src/components/editor/markdown/documents/markdown-doc-completions.ts @@ -1,4 +1,4 @@ -import type { MarkdownDocument } from '../../../../../../shared/filesystem-entry-types' +import type { MarkdownDocument } from '../../../../../../shared/file-listing/file-document' import { isClipboardTextByteLengthOverLimit } from '../../../../../../shared/clipboard-text' export type MarkdownDocCompletionContext = { diff --git a/src/renderer/src/components/editor/markdown/documents/markdown-doc-links.ts b/src/renderer/src/components/editor/markdown/documents/markdown-doc-links.ts index b582ab6e73a..4b1d76cd6ce 100644 --- a/src/renderer/src/components/editor/markdown/documents/markdown-doc-links.ts +++ b/src/renderer/src/components/editor/markdown/documents/markdown-doc-links.ts @@ -1,4 +1,4 @@ -import type { MarkdownDocument } from '../../../../../../shared/filesystem-entry-types' +import type { MarkdownDocument } from '../../../../../../shared/file-listing/file-document' import { slug as slugMarkdownHeading } from 'github-slugger' export const MARKDOWN_DOC_LINK_PREFIX = '#orca-doc-link=' diff --git a/src/renderer/src/components/editor/markdown/documents/markdown-document-list-request.test.ts b/src/renderer/src/components/editor/markdown/documents/markdown-document-list-request.test.ts deleted file mode 100644 index 6f34323b158..00000000000 --- a/src/renderer/src/components/editor/markdown/documents/markdown-document-list-request.test.ts +++ /dev/null @@ -1,128 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { MarkdownDocument } from '../../../../../../shared/filesystem-entry-types' -import type { RuntimeFileOperationArgs } from '@/runtime/files/runtime-file-client-types' -import { requestSharedMarkdownDocumentList } from './markdown-document-list-request' - -function context(overrides: Partial = {}): RuntimeFileOperationArgs { - return { - target: { kind: 'local' as const }, - worktreeId: 'worktree-1', - worktreePath: '/repo', - ...overrides - } -} - -function deferred(): { - promise: Promise - reject: (error: Error) => void - resolve: (value: T) => void -} { - let resolve!: (value: T) => void - let reject!: (error: Error) => void - const promise = new Promise((resolvePromise, rejectPromise) => { - resolve = resolvePromise - reject = rejectPromise - }) - return { promise, reject, resolve } -} - -describe('shared Markdown document list requests', () => { - it('starts a fresh scan after a mutation instead of joining an older snapshot', async () => { - const stale = deferred() - const fresh = deferred() - const load = vi.fn().mockReturnValueOnce(stale.promise).mockReturnValueOnce(fresh.promise) - - const initialRequest = requestSharedMarkdownDocumentList(context(), '/repo', {}, load) - const mutationRefresh = requestSharedMarkdownDocumentList( - context(), - '/repo', - { requireFresh: true }, - load - ) - - expect(load).toHaveBeenCalledTimes(2) - expect(mutationRefresh).not.toBe(initialRequest) - - const freshDocuments = [{ filePath: '/repo/new.md', relativePath: 'new.md' }] - fresh.resolve(freshDocuments as MarkdownDocument[]) - await expect(mutationRefresh).resolves.toBe(freshDocuments) - - const staleDocuments = [{ filePath: '/repo/old.md', relativePath: 'old.md' }] - stale.resolve(staleDocuments as MarkdownDocument[]) - await expect(initialRequest).resolves.toBe(staleDocuments) - }) - - it('bypasses a pre-change scan but joins a scan started after the same watcher burst', async () => { - const old = deferred() - const fresh = deferred() - const load = vi.fn().mockReturnValueOnce(old.promise).mockReturnValueOnce(fresh.promise) - const now = vi.spyOn(performance, 'now').mockReturnValue(1_000) - try { - const initial = requestSharedMarkdownDocumentList(context(), '/watch-burst', {}, load) - now.mockReturnValue(1_200) - const afterChange = { freshAfter: 1_000 } - const refreshed = requestSharedMarkdownDocumentList( - context(), - '/watch-burst', - afterChange, - load - ) - expect(refreshed).not.toBe(initial) - expect(requestSharedMarkdownDocumentList(context(), '/watch-burst', afterChange, load)).toBe( - refreshed - ) - old.resolve([]) - await initial - expect(requestSharedMarkdownDocumentList(context(), '/watch-burst', afterChange, load)).toBe( - refreshed - ) - expect(load).toHaveBeenCalledTimes(2) - fresh.resolve([]) - await refreshed - } finally { - old.resolve([]) - fresh.resolve([]) - now.mockRestore() - } - }) - - it('allows an ordinary retry after an older scan stops settling', async () => { - const stale = deferred() - const retry = deferred() - const load = vi.fn().mockReturnValueOnce(stale.promise).mockReturnValueOnce(retry.promise) - const now = vi.spyOn(performance, 'now').mockReturnValue(1_000) - - try { - const initialRequest = requestSharedMarkdownDocumentList(context(), '/stuck', {}, load) - now.mockReturnValue(31_001) - const retryRequest = requestSharedMarkdownDocumentList(context(), '/stuck', {}, load) - - expect(load).toHaveBeenCalledTimes(2) - expect(retryRequest).not.toBe(initialRequest) - - retry.resolve([]) - stale.resolve([]) - await expect(retryRequest).resolves.toEqual([]) - await expect(initialRequest).resolves.toEqual([]) - } finally { - now.mockRestore() - } - }) - - it('clears rejected requests so a retry can run', async () => { - const failure = deferred() - const load = vi.fn(() => failure.promise) - const first = requestSharedMarkdownDocumentList(context(), '/retry', {}, load) - const second = requestSharedMarkdownDocumentList(context(), '/retry', {}, load) - - failure.reject(new Error('offline')) - await expect(first).rejects.toThrow('offline') - await expect(second).rejects.toThrow('offline') - - load.mockResolvedValueOnce([]) - await expect(requestSharedMarkdownDocumentList(context(), '/retry', {}, load)).resolves.toEqual( - [] - ) - expect(load).toHaveBeenCalledTimes(2) - }) -}) diff --git a/src/renderer/src/components/editor/markdown/documents/markdown-document-list-request.ts b/src/renderer/src/components/editor/markdown/documents/markdown-document-list-request.ts index c007b2f3c64..852f6f0bc2c 100644 --- a/src/renderer/src/components/editor/markdown/documents/markdown-document-list-request.ts +++ b/src/renderer/src/components/editor/markdown/documents/markdown-document-list-request.ts @@ -1,4 +1,4 @@ -import type { MarkdownDocument } from '../../../../../../shared/filesystem-entry-types' +import type { MarkdownDocument } from '../../../../../../shared/file-listing/file-document' import { listRuntimeMarkdownDocuments } from '@/runtime/files/metadata/runtime-file-metadata-client' import type { RuntimeFileOperationArgs } from '@/runtime/files/runtime-file-client-types' diff --git a/src/renderer/src/components/editor/markdown/documents/use-markdown-document-watch-refresh.ts b/src/renderer/src/components/editor/markdown/documents/use-markdown-document-watch-refresh.ts index ecbdaee4966..e755fcc22d1 100644 --- a/src/renderer/src/components/editor/markdown/documents/use-markdown-document-watch-refresh.ts +++ b/src/renderer/src/components/editor/markdown/documents/use-markdown-document-watch-refresh.ts @@ -1,5 +1,5 @@ import { useEffect } from 'react' -import type { FsChangedPayload } from '../../../../../../shared/filesystem-entry-types' +import type { FsChangedPayload } from '../../../../../../shared/file-watch/filesystem-change-event' import { normalizeRuntimePathForComparison, relativePathInsideRoot diff --git a/src/renderer/src/components/editor/markdown/documents/useMarkdownDocuments.ts b/src/renderer/src/components/editor/markdown/documents/useMarkdownDocuments.ts index da2e97aaf64..366f918a926 100644 --- a/src/renderer/src/components/editor/markdown/documents/useMarkdownDocuments.ts +++ b/src/renderer/src/components/editor/markdown/documents/useMarkdownDocuments.ts @@ -1,6 +1,6 @@ import { toast } from 'sonner' import { useCallback, useEffect, useMemo, useRef, useState } from 'react' -import type { MarkdownDocument } from '../../../../../../shared/filesystem-entry-types' +import type { MarkdownDocument } from '../../../../../../shared/file-listing/file-document' import { useAppStore } from '@/store/index' import { translate } from '@/i18n/i18n' import '@/lib/connection-context' diff --git a/src/renderer/src/components/editor/markdown/documents/useMarkdownDocuments.watch.test.ts b/src/renderer/src/components/editor/markdown/documents/useMarkdownDocuments.watch.test.ts index bc4b32721c5..f3eab1176d8 100644 --- a/src/renderer/src/components/editor/markdown/documents/useMarkdownDocuments.watch.test.ts +++ b/src/renderer/src/components/editor/markdown/documents/useMarkdownDocuments.watch.test.ts @@ -2,10 +2,8 @@ import { act, createElement } from 'react' import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { - FsChangeEvent, - MarkdownDocument -} from '../../../../../../shared/filesystem-entry-types' +import type { FsChangeEvent } from '../../../../../../shared/file-watch/filesystem-change-event' +import type { MarkdownDocument } from '../../../../../../shared/file-listing/file-document' import type { OpenFile } from '@/store/slices/editor/types/open-file' import { ORCA_WORKTREE_FILE_CHANGE_EVENT } from '@/hooks/worktree-file-change-event' import type * as ConnectionOwnerResolution from '@/lib/connection-owner-resolution' @@ -113,18 +111,6 @@ afterEach(() => { }) describe('Markdown metadata from the existing worktree watcher', () => { - it('discovers a created document and removes a deleted document without reopening', async () => { - await render() - runtime.list.mockResolvedValueOnce([target]) - change([{ kind: 'create', absolutePath: target.filePath }]) - await settle() - expect(controllers[0].markdownDocuments).toEqual([target]) - change([{ kind: 'delete', absolutePath: target.filePath }]) - await settle() - expect(controllers[0].markdownDocuments).toEqual([]) - expect(runtime.list).toHaveBeenCalledTimes(3) - }) - it('keeps the last list without a toast when a watcher refresh fails', async () => { runtime.list.mockResolvedValueOnce([target]) await render() @@ -136,93 +122,4 @@ describe('Markdown metadata from the existing worktree watcher', () => { expect(controllers[0].markdownDocuments).toEqual([target]) expect(toastError).not.toHaveBeenCalled() }) - - it('keeps a late pre-change scan from replacing the refreshed document list', async () => { - let resolveOld: (documents: MarkdownDocument[]) => void = () => {} - runtime.list.mockReturnValueOnce( - new Promise((done) => { - resolveOld = done - }) - ) - await render() - runtime.list.mockResolvedValueOnce([target]) - change([{ kind: 'create', absolutePath: target.filePath }]) - await settle() - expect(controllers[0].markdownDocuments).toEqual([target]) - await act(async () => resolveOld([])) - expect(controllers[0].markdownDocuments).toEqual([target]) - expect(runtime.list).toHaveBeenCalledTimes(2) - }) - - it('refreshes a local owner while ignoring an identical remote path', async () => { - await render(null) - change([{ kind: 'create', absolutePath: target.filePath }], 'host-a') - await settle() - expect(runtime.list).toHaveBeenCalledOnce() - runtime.list.mockResolvedValueOnce([target]) - change([{ kind: 'create', absolutePath: target.filePath }], null) - await settle() - expect(controllers[0].markdownDocuments).toEqual([target]) - expect(runtime.list).toHaveBeenLastCalledWith( - expect.objectContaining({ target: { kind: 'local' } }), - '/repo' - ) - }) - - it('coalesces bursts and shares a fresh pending scan across split panes', async () => { - const owner = 'host-split' - await render(owner, 2) - let resolve: (documents: MarkdownDocument[]) => void = () => {} - runtime.list.mockReturnValueOnce( - new Promise((done) => { - resolve = done - }) - ) - change([{ kind: 'create', absolutePath: target.filePath }], owner) - change([{ kind: 'delete', absolutePath: '/repo/old.markdown' }], owner) - await settle() - expect(runtime.list).toHaveBeenCalledTimes(2) - await act(async () => resolve([target])) - expect(controllers.map((controller) => controller.markdownDocuments)).toEqual([ - [target], - [target] - ]) - }) - - it('keeps refreshing while membership changes never stop', async () => { - const owner = 'host-sustained' - await render(owner) - const initialCalls = runtime.list.mock.calls.length - // Watch batches arrive every 100 ms under sustained writes, faster than the 125 ms debounce. - for (let i = 0; i < 10; i++) { - change([{ kind: 'create', absolutePath: `/repo/n${i}.md` }], owner) - await act(async () => { - await vi.advanceTimersByTimeAsync(100) - }) - } - expect(runtime.list.mock.calls.length).toBeGreaterThan(initialCalls) - }) - - it('does not let a remount join a scan that started before the latest change', async () => { - const owner = 'host-remount' - await render(owner) - runtime.list.mockImplementation(() => new Promise(() => {})) - change([{ kind: 'create', absolutePath: target.filePath }], owner) - await settle() - const callsWithScanInFlight = runtime.list.mock.calls.length - // A second change lands while that scan runs; the tab is then switched away and back. - change([{ kind: 'create', absolutePath: '/repo/second.md' }], owner) - await act(async () => root.render(null)) - await render(owner) - expect(runtime.list.mock.calls.length).toBeGreaterThan(callsWithScanInFlight) - }) - - it.each(['unmount', 'owner change'])('cancels scheduled scans on %s', async (reason) => { - await render() - change([{ kind: 'create', absolutePath: target.filePath }]) - await (reason === 'unmount' ? act(async () => root.render(null)) : render('host-b')) - const calls = runtime.list.mock.calls.length - await settle() - expect(runtime.list).toHaveBeenCalledTimes(calls) - }) }) diff --git a/src/renderer/src/components/editor/model-lifetime/buffer-text/editor-buffer-sharing.test.ts b/src/renderer/src/components/editor/model-lifetime/buffer-text/editor-buffer-sharing.test.ts index d3968dee4fc..d1cab149838 100644 --- a/src/renderer/src/components/editor/model-lifetime/buffer-text/editor-buffer-sharing.test.ts +++ b/src/renderer/src/components/editor/model-lifetime/buffer-text/editor-buffer-sharing.test.ts @@ -1,38 +1,21 @@ // @vitest-environment happy-dom // Use real record middleware and save queues for cross-workspace restored drafts, phone writes, rich text and autosave pauses. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { createElement } from 'react' -import { renderToStaticMarkup } from 'react-dom/server' + import * as monaco from 'monaco-editor/esm/vs/editor/editor.api.js' import type { StoreApi } from 'zustand' import type { AppState } from '@/store/types' -import type { OpenFile } from '@/store/slices/editor/types/open-file' -import type { WorkspaceSessionState } from '../../../../../../shared/workspace-session/workspace-session-state-types' -import { - getOpenFilesForExternalFileChange, - ORCA_EDITOR_EXTERNAL_FILE_CHANGE_EVENT, - ORCA_EDITOR_FILE_SAVED_EVENT, - requestEditorFileSave, - type EditorFileSavedDetail -} from '../../autosave/editor-autosave' + +import { requestEditorFileSave } from '../../autosave/editor-autosave' import { attachEditorAutosaveController } from '../../autosave/editor-autosave-controller' import { createEditorStore } from '../../autosave/editor-autosave-controller-test-fixture' import { __clearSelfWriteRegistryForTests } from '../../external-changes/editor-self-write-registry' -import { getDiskBaselineSignature } from '../../../../../../shared/disk-baseline-signature' +import { getDiskBaselineSignature } from '../../../../../../shared/file-write/disk-baseline-signature' import { GUARDED_PATH, stubGuardedDisk } from '../../save/queue/editor-save-guarded-disk-fixture' -import { makeFolderWorkspace } from '@/store/folder-workspaces/folder-workspace.test-fixture' + import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' -import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../../../shared/constants' -import { folderWorkspaceKey } from '../../../../../../shared/workspace-scope' -import { editorTabModelUri } from '../../save/queue/editor-save-disk-precondition' -import { mayPushTabTextIntoModel, isStaleCachedEditorText } from './editor-stale-mount-guard' + import { registerPendingEditorFlush } from '../../save/flush/editor-pending-flush' -import { isDetachedEditorBufferId } from '@/store/slices/editor/buffers/editor-buffer-views' -import { buildHydratedEditorSessionState } from '@/store/slices/editor/hydration/hydrated-editor-session-state' -import { stampCleanTabDiskBaseline } from '../../external-changes/editor-clean-tab-disk-baseline' -import { withRecordDiskText } from './editor-buffer-adapter' -import { ExternalFileChangeBanner } from '../../external-changes/ExternalFileChangeBanner' -import type { FileContent } from '../../editor-panel-content-types' const storeRef = vi.hoisted((): { current: StoreApi | null } => ({ current: null })) @@ -66,72 +49,6 @@ function twoWorkspaceStore(): StoreApi { return store } -function restore( - store: StoreApi, - drafts: [string | undefined, string | undefined], - workspaces = ['wt-1', 'wt-2'] -): [OpenFile, OpenFile] { - const entry = (worktreeId: string, draft: string | undefined) => ({ - filePath: GUARDED_PATH, - relativePath: 'file.ts', - worktreeId, - language: 'typescript', - runtimeEnvironmentId: null, - dirtyDraftContent: draft, - lastKnownDiskSignature: getDiskBaselineSignature(BASE) - }) - const session: WorkspaceSessionState = { - activeRepoId: null, - activeWorktreeId: workspaces[0], - activeTabId: null, - tabsByWorktree: {}, - terminalLayoutsByTabId: {}, - openFilesByWorktree: Object.fromEntries( - workspaces.map((workspace, i) => [workspace, [entry(workspace, drafts[i])]]) - ) - } - store.setState(buildHydratedEditorSessionState(session, new Set(workspaces), workspaces[0]).state) - const [a, b] = store.getState().openFiles - expect([a?.worktreeId, b?.worktreeId]).toEqual(workspaces) - return [a, b] -} - -/** Match mount reconciliation: prefer drafts and never push stale cached text into an already-live model. */ -function mount( - store: StoreApi, - viewId: string, - text = store.getState().editorDrafts[viewId] ?? BASE -): monaco.editor.ITextModel { - const state = store.getState() - const file = state.openFiles.find((tab) => tab.id === viewId)! - const uri = monaco.Uri.parse(editorTabModelUri(state, file)) - const model = monaco.editor.getModel(uri) - if (!model) { - return monaco.editor.createModel(text, 'typescript', uri) - } - if ( - model.getValue() !== text && - !isStaleCachedEditorText(viewId, text) && - mayPushTabTextIntoModel(viewId) - ) { - model.setValue(text) - } - return model -} - -function bannerOf(store: StoreApi, id: string): string | null { - const file = view(store, id)! - return file.externalMutation === 'changed' - ? renderToStaticMarkup( - createElement(ExternalFileChangeBanner, { - file, - currentContent: store.getState().editorDrafts[id] ?? BASE, - reloadContent: () => {} - }) - ) - : null -} - const view = (store: StoreApi, id: string) => store.getState().openFiles.find((tab) => tab.id === id) @@ -148,144 +65,6 @@ afterEach(() => { } }) -describe('restored drafts of one file (scenario 2)', () => { - it.each([ - ['a first', 'wt-2'], - ['b first', 'wt-2'], - ['no mount', 'wt-2'], - ['b first', FLOATING_TERMINAL_WORKTREE_ID] - ] as const)( - 'divergent drafts detach with their own models (%s, %s); the first autosave lands and the other side keeps its draft behind the banner', - async (order, partner) => { - const disk = stubGuardedDisk({ [GUARDED_PATH]: BASE }) - const store = twoWorkspaceStore() - const [a, b] = restore(store, ['abc', 'abcd'], ['wt-1', partner]) - const recordOf = (id: string) => store.getState().editorBufferIdOf[id] - expect(isDetachedEditorBufferId(recordOf(b.id))).toBe(true) - - if (order !== 'no mount') { - const ids = order === 'a first' ? [a.id, b.id] : [b.id, a.id] - const models: monaco.editor.ITextModel[] = [] - for (const id of ids) { - models.push(mount(store, id)) - } - expect(models[0]).not.toBe(models[1]) - expect(mount(store, a.id).getValue()).toBe('abc') - expect(mount(store, b.id).getValue()).toBe('abcd') - } - - const cleanup = attachEditorAutosaveController(store) - try { - await vi.advanceTimersByTimeAsync(5000) - // One write landed; the other was refused against the restored baseline. - const landed = disk.files.get(GUARDED_PATH) - expect(['abc', 'abcd']).toContain(landed) - const kept = landed === 'abc' ? 'abcd' : 'abc' - expect(disk.writeFile).toHaveBeenCalledTimes(2) - // Rejoining preserves the unsaved side’s older baseline and marks every view conflicted. - expect(recordOf(a.id)).toBe(recordOf(b.id)) - for (const id of [a.id, b.id]) { - expect(store.getState().editorDrafts[id]).toBe(kept) - expect(view(store, id)?.isDirty).toBe(true) - expect(view(store, id)?.externalMutation).toBe('changed') - expect(view(store, id)?.lastKnownDiskSignature).toBe(getDiskBaselineSignature(BASE)) - expect(bannerOf(store, id)).toContain('Compare') - expect(bannerOf(store, id)).toContain('Reload from Disk') - expect(bannerOf(store, id)).toContain('Overwrite') - } - } finally { - cleanup() - } - } - ) - - it('identical drafts merge into one record and write once', async () => { - const disk = stubGuardedDisk({ [GUARDED_PATH]: BASE }) - const store = twoWorkspaceStore() - const [a, b] = restore(store, ['same', 'same']) - expect(store.getState().editorBufferIdOf[a.id]).toBe(store.getState().editorBufferIdOf[b.id]) - const cleanup = attachEditorAutosaveController(store) - try { - await vi.advanceTimersByTimeAsync(5000) - expect(disk.writeFile).toHaveBeenCalledTimes(1) - expect(disk.files.get(GUARDED_PATH)).toBe('same') - expect(view(store, a.id)?.isDirty).toBe(false) - expect(view(store, b.id)?.isDirty).toBe(false) - } finally { - cleanup() - } - }) -}) - -describe('restored floating and ordinary views', () => { - it.each([ - ['worktree', false], - ['worktree', true], - ['folder', false], - ['folder', true] - ] as const)( - 'share edits and save both ways after %s restore (late catalog: %s)', - async (kind, late) => { - const disk = stubGuardedDisk({ [GUARDED_PATH]: BASE }) - const store = twoWorkspaceStore() - const workspace = kind === 'folder' ? folderWorkspaceKey('folder') : 'wt-1' - const catalog = - kind === 'folder' - ? { - folderWorkspaces: [ - makeFolderWorkspace({ id: 'folder', folderPath: '/repo', executionHostId: 'local' }) - ] - } - : { worktreesByRepo: store.getState().worktreesByRepo } - store.setState(late ? { worktreesByRepo: {}, folderWorkspaces: [] } : catalog) - const [ordinary, floating] = restore( - store, - [undefined, 'restored draft'], - [workspace, FLOATING_TERMINAL_WORKTREE_ID] - ) - const recordOf = (id: string) => store.getState().editorBufferIdOf[id] - if (late) { - expect(recordOf(ordinary.id)).not.toBe(recordOf(floating.id)) - store.setState(catalog) - } - expect(recordOf(ordinary.id)).toBe(recordOf(floating.id)) - expect(store.getState().editorDrafts[ordinary.id]).toBe('restored draft') - expect(ordinary.operationProvenance).toBeUndefined() - expect(floating.operationProvenance).toBeUndefined() - const model = mount(store, ordinary.id) - expect(mount(store, floating.id)).toBe(model) - store.setState((state) => { - if (!state.settings) { - throw new Error('Editor fixture settings must be initialized') - } - return { settings: { ...state.settings, editorAutoSave: false } } - }) - const cleanup = attachEditorAutosaveController(store) - try { - for (const source of [ordinary, floating]) { - const text = `saved from ${source.worktreeId}` - model.setValue(text) - store.getState().setEditorDraft(source.id, text) - store.getState().markFileDirty(source.id, true) - for (const tab of [ordinary, floating]) { - expect(store.getState().editorDrafts[tab.id]).toBe(text) - } - await requestEditorFileSave({ fileId: source.id }) - expect(disk.files.get(GUARDED_PATH)).toBe(text) - for (const tab of [ordinary, floating]) { - expect(view(store, tab.id)?.isDirty).toBe(false) - expect(store.getState().editorDrafts[tab.id]).toBeUndefined() - expect(mount(store, tab.id, text)).toBe(model) - } - } - expect(disk.writeFile).toHaveBeenCalledTimes(2) - } finally { - cleanup() - } - } - ) -}) - function openShared(disk: string) { const store = twoWorkspaceStore() for (const worktreeId of ['wt-1', 'wt-2']) { @@ -303,97 +82,6 @@ function openShared(disk: string) { } describe('two workspaces on one record', () => { - it('W1 "abc", W2 "d": one write of "abcd"; old W1 text never reaches the model (scenario 1)', async () => { - const disk = stubGuardedDisk({ [GUARDED_PATH]: BASE }) - const { store, a, b } = openShared(BASE) - const model = mount(store, a.id) - expect(mount(store, b.id)).toBe(model) - // Both workspaces edit one model; each editor still publishes its view’s draft. - model.setValue('abc') - store.getState().setEditorDraft(a.id, 'abc') - store.getState().markFileDirty(a.id, true) - model.setValue('abcd') - store.getState().setEditorDraft(b.id, 'abcd') - const cleanup = attachEditorAutosaveController(store) - try { - await vi.advanceTimersByTimeAsync(5000) - expect(disk.writeFile).toHaveBeenCalledTimes(1) - expect(disk.files.get(GUARDED_PATH)).toBe('abcd') - expect(view(store, a.id)?.isDirty).toBe(false) - expect(view(store, b.id)?.isDirty).toBe(false) - expect(mount(store, a.id, 'abc')).toBe(model) - expect(model.getValue()).toBe('abcd') - } finally { - cleanup() - } - }) - - it.each([ - ['dirty', 'banners every view'], - ['clean', 'reloads every view'] - ] as const)('a phone save on a %s record %s (scenario 4)', async (state, _outcome) => { - const disk = stubGuardedDisk({ [GUARDED_PATH]: 'from phone' }) - const { store, a, b } = openShared(BASE) - if (state === 'dirty') { - store.getState().setEditorDraft(a.id, 'desktop edits') - store.getState().markFileDirty(a.id, true) - } - const cleanup = attachEditorAutosaveController(store) - try { - const detail = { worktreeId: 'wt-1', worktreePath: '/repo', relativePath: 'file.ts' } - window.dispatchEvent(new CustomEvent(ORCA_EDITOR_EXTERNAL_FILE_CHANGE_EVENT, { detail })) - for (const id of [a.id, b.id]) { - if (state === 'dirty') { - expect(view(store, id)?.externalMutation).toBe('changed') - expect(store.getState().editorDrafts[id]).toBe('desktop edits') - } else { - expect(view(store, id)?.isDirty).toBe(false) - expect(store.getState().editorDrafts[id]).toBeUndefined() - } - } - if (state === 'clean') { - // Match panel reloads that update both content and clean disk baselines. - const matched = getOpenFilesForExternalFileChange(store.getState().openFiles, { - worktreeId: 'wt-2', - worktreePath: '/repo', - relativePath: 'file.ts' - }).map((file) => file.id) - expect(matched).toContain(b.id) - let contents: Record = {} - for (const id of [a.id, b.id]) { - const loaded = { content: disk.files.get(GUARDED_PATH)!, isBinary: false } - stampCleanTabDiskBaseline(id, loaded) - contents = { ...contents, [id]: loaded } - } - expect(view(store, b.id)?.lastKnownDiskSignature).toBe( - getDiskBaselineSignature('from phone') - ) - - // After a desktop save, the panel must advance the sibling view’s loaded disk text too. - const saved: EditorFileSavedDetail[] = [] - window.addEventListener(ORCA_EDITOR_FILE_SAVED_EVENT, (event) => { - if (event instanceof CustomEvent) { - saved.push(event.detail) - } - }) - store.getState().setEditorDraft(a.id, 'from phone, then desktop') - store.getState().markFileDirty(a.id, true) - await requestEditorFileSave({ fileId: a.id }) - expect(disk.files.get(GUARDED_PATH)).toBe('from phone, then desktop') - const [detail] = saved - contents = withRecordDiskText( - contents, - detail.recordViewIds ?? [], - detail.fileId, - detail.content - ) - expect(contents[b.id]?.content).toBe('from phone, then desktop') - } - } finally { - cleanup() - } - }) - it("a save writes another view's pending rich text; typing during the save stays dirty (scenario 5)", async () => { const disk = stubGuardedDisk({ [GUARDED_PATH]: BASE }) const { store, a, b } = openShared(BASE) diff --git a/src/renderer/src/components/editor/model-lifetime/buffer-text/editor-shared-record-clean-view.test.ts b/src/renderer/src/components/editor/model-lifetime/buffer-text/editor-shared-record-clean-view.test.ts index 852291ab116..43d6c1e6508 100644 --- a/src/renderer/src/components/editor/model-lifetime/buffer-text/editor-shared-record-clean-view.test.ts +++ b/src/renderer/src/components/editor/model-lifetime/buffer-text/editor-shared-record-clean-view.test.ts @@ -13,7 +13,7 @@ import { editorTabModelUri } from '../../save/queue/editor-save-disk-preconditio import { useEditorContentChangeHandler } from './use-editor-content-change-handler' import { useMonacoContentSyncBridge } from '../../use-monaco-content-sync-bridge' import type { FileContent } from '../../editor-panel-content-types' -import { getDiskBaselineSignature } from '../../../../../../shared/disk-baseline-signature' +import { getDiskBaselineSignature } from '../../../../../../shared/file-write/disk-baseline-signature' const storeRef = vi.hoisted((): { current: StoreApi | null } => ({ current: null })) vi.mock('@/store/index', () => { diff --git a/src/renderer/src/components/editor/model-lifetime/buffer-text/editor-stale-mount-guard.ts b/src/renderer/src/components/editor/model-lifetime/buffer-text/editor-stale-mount-guard.ts index 818963756d4..6a832e7ee41 100644 --- a/src/renderer/src/components/editor/model-lifetime/buffer-text/editor-stale-mount-guard.ts +++ b/src/renderer/src/components/editor/model-lifetime/buffer-text/editor-stale-mount-guard.ts @@ -1,5 +1,5 @@ import { useAppStore } from '@/store/index' -import { getDiskBaselineSignature } from '../../../../../../shared/disk-baseline-signature' +import { getDiskBaselineSignature } from '../../../../../../shared/file-write/disk-baseline-signature' import { notifyEditorFileCacheStale } from '../../autosave/editor-autosave' import { isEditorModelDirty } from '../../save/queue/editor-save-disk-precondition' diff --git a/src/renderer/src/components/editor/pdf-js-document-options.ts b/src/renderer/src/components/editor/pdf-js-document-options.ts index f6f10aed68b..c10be27304d 100644 --- a/src/renderer/src/components/editor/pdf-js-document-options.ts +++ b/src/renderer/src/components/editor/pdf-js-document-options.ts @@ -1,5 +1,5 @@ import type { PDFDataRangeTransport } from 'pdfjs-dist' -import { MAX_FILE_RANGE_READ_BYTES } from '../../../../shared/file-range-read' +import { MAX_FILE_RANGE_READ_BYTES } from '../../../../shared/file-content/file-range-read' export function buildPdfJsDocumentOptions( source: { data: Uint8Array } | { range: PDFDataRangeTransport }, diff --git a/src/renderer/src/components/editor/rich-markdown/commands/useRichMarkdownMenuController.ts b/src/renderer/src/components/editor/rich-markdown/commands/useRichMarkdownMenuController.ts index 15fa97cd0f0..4224f3ae15c 100644 --- a/src/renderer/src/components/editor/rich-markdown/commands/useRichMarkdownMenuController.ts +++ b/src/renderer/src/components/editor/rich-markdown/commands/useRichMarkdownMenuController.ts @@ -1,6 +1,6 @@ import { useCallback, useMemo, useRef, useState } from 'react' import type React from 'react' -import type { MarkdownDocument } from '../../../../../../shared/filesystem-entry-types' +import type { MarkdownDocument } from '../../../../../../shared/file-listing/file-document' import { getMarkdownDocCompletionDocuments } from '../../markdown/documents/markdown-doc-completions' import type { DocLinkMenuRow, DocLinkMenuState } from '../doc-links/rich-markdown-commands' import { filterRichMarkdownSlashCommands } from './rich-markdown-slash-command-filter' diff --git a/src/renderer/src/components/editor/rich-markdown/doc-links/rich-markdown-commands.tsx b/src/renderer/src/components/editor/rich-markdown/doc-links/rich-markdown-commands.tsx index 546c092c407..a486d9882e9 100644 --- a/src/renderer/src/components/editor/rich-markdown/doc-links/rich-markdown-commands.tsx +++ b/src/renderer/src/components/editor/rich-markdown/doc-links/rich-markdown-commands.tsx @@ -1,6 +1,6 @@ import type React from 'react' import type { Editor } from '@tiptap/react' -import type { MarkdownDocument } from '../../../../../../shared/filesystem-entry-types' +import type { MarkdownDocument } from '../../../../../../shared/file-listing/file-document' import { stripMarkdownExtension } from '../../markdown/documents/markdown-doc-links' export type DocLinkMenuState = { diff --git a/src/renderer/src/components/editor/rich-markdown/doc-links/rich-markdown-doc-link-storage.ts b/src/renderer/src/components/editor/rich-markdown/doc-links/rich-markdown-doc-link-storage.ts index b4ee203644e..38a10136b46 100644 --- a/src/renderer/src/components/editor/rich-markdown/doc-links/rich-markdown-doc-link-storage.ts +++ b/src/renderer/src/components/editor/rich-markdown/doc-links/rich-markdown-doc-link-storage.ts @@ -1,4 +1,4 @@ -import type { MarkdownDocument } from '../../../../../../shared/filesystem-entry-types' +import type { MarkdownDocument } from '../../../../../../shared/file-listing/file-document' import { createMarkdownDocumentIndex, type MarkdownDocumentIndex diff --git a/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-insert.ts b/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-insert.ts index c7bc61c0f58..472b19a429b 100644 --- a/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-insert.ts +++ b/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-insert.ts @@ -23,7 +23,7 @@ import { selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields' import type { RuntimeFileOperationArgs } from '@/runtime/files/runtime-file-client-types' -import type { LocalFileAccess } from '../../../../../../shared/local-file-access' +import type { LocalFileAccess } from '../../../../../../shared/file-access/local-file-access' export type RichMarkdownImageInsertArgs = { editor: Editor diff --git a/src/renderer/src/components/editor/rich-markdown/instance/rich-markdown-editor-props.ts b/src/renderer/src/components/editor/rich-markdown/instance/rich-markdown-editor-props.ts index 034dd567a1a..f953ad38baa 100644 --- a/src/renderer/src/components/editor/rich-markdown/instance/rich-markdown-editor-props.ts +++ b/src/renderer/src/components/editor/rich-markdown/instance/rich-markdown-editor-props.ts @@ -1,5 +1,5 @@ import type React from 'react' -import type { MarkdownDocument } from '../../../../../../shared/filesystem-entry-types' +import type { MarkdownDocument } from '../../../../../../shared/file-listing/file-document' import type { EditorFileOperationProvenance } from '@/lib/editor-file-operation-provenance' export type RichMarkdownEditorProps = { diff --git a/src/renderer/src/components/editor/rich-markdown/instance/useRichMarkdownProgrammaticSync.ts b/src/renderer/src/components/editor/rich-markdown/instance/useRichMarkdownProgrammaticSync.ts index 78f88d8def6..209081bc07e 100644 --- a/src/renderer/src/components/editor/rich-markdown/instance/useRichMarkdownProgrammaticSync.ts +++ b/src/renderer/src/components/editor/rich-markdown/instance/useRichMarkdownProgrammaticSync.ts @@ -1,7 +1,7 @@ import { useEffect } from 'react' import type { Dispatch, MutableRefObject, SetStateAction } from 'react' import type { Editor } from '@tiptap/react' -import type { MarkdownDocument } from '../../../../../../shared/filesystem-entry-types' +import type { MarkdownDocument } from '../../../../../../shared/file-listing/file-document' import { encodeRawMarkdownHtmlForRichEditor } from '../raw-source/raw-markdown-html' import { syncDocLinkMenu, type DocLinkMenuState } from '../doc-links/rich-markdown-commands' import { normalizeEmptyListItems } from '../schema/rich-markdown-normalize' diff --git a/src/renderer/src/components/editor/save/commands/editor-child-owner-save.test.tsx b/src/renderer/src/components/editor/save/commands/editor-child-owner-save.test.tsx deleted file mode 100644 index edd57ea9c9e..00000000000 --- a/src/renderer/src/components/editor/save/commands/editor-child-owner-save.test.tsx +++ /dev/null @@ -1,188 +0,0 @@ -// @vitest-environment happy-dom -import { act, cleanup, renderHook } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { useAppStore } from '@/store/index' -import { TEST_REPO } from '@/store/repos/repo.test-fixture' -import { - makeFolderWorkspace, - makeProjectGroup -} from '@/components/sidebar/workspace-creation/folder/folder-workspace-composer-submit-fixtures' -import { useEditorPanelFileContentLoader } from '../../useEditorPanelFileContentLoader' -import type { FileContent } from '../../editor-panel-content-types' -import { createEditorSaveQueue } from '../queue/editor-save-queue' -import type { EditorSaveQueue } from '../queue/editor-save-queue-contract' -import type { FileWriteResult } from '../../../../../../shared/file-write-disk-precondition' -import type { readEditorCsvFileContent } from '../../csv/csv-file-content' -import type { writeRuntimeFile } from '@/runtime/files/mutations/runtime-file-mutation-client' -import { getDefaultSettings } from '../../../../../../shared/constants' -import { getDiskBaselineSignature } from '../../../../../../shared/disk-baseline-signature' - -const io = vi.hoisted(() => ({ - read: vi.fn(), - write: vi.fn() -})) -vi.mock('../../csv/csv-file-content', () => ({ readEditorCsvFileContent: io.read })) -vi.mock('@/runtime/files/mutations/runtime-file-mutation-client', () => ({ - writeRuntimeFile: io.write -})) - -const workspaceId = 'folder:mixed' -const filePath = '/root/local/file.ts' -let queue: EditorSaveQueue - -beforeEach(() => { - io.read.mockReset().mockResolvedValue({ content: 'disk content', isBinary: false }) - io.write.mockReset().mockResolvedValue({ ok: true }) - useAppStore.setState(useAppStore.getInitialState(), true) - useAppStore.setState({ - settings: { ...getDefaultSettings('/tmp'), editorAutoSave: true, editorAutoSaveDelayMs: 250 }, - folderWorkspaces: [makeFolderWorkspace({ id: 'mixed', folderPath: '/root' })], - projectGroups: [makeProjectGroup()], - repos: [ - { - ...TEST_REPO, - id: 'child', - path: '/root/local', - projectGroupId: 'group-1', - executionHostId: 'local' - }, - { - ...TEST_REPO, - id: 'remote', - path: '/root/remote', - projectGroupId: 'group-1', - executionHostId: 'ssh:box', - connectionId: 'box' - } - ] - }) - queue = createEditorSaveQueue(useAppStore) -}) - -afterEach(() => { - queue.dispose() - cleanup() -}) - -async function loadChild() { - const id = useAppStore.getState().openFile( - { - worktreeId: workspaceId, - filePath, - relativePath: 'local/file.ts', - mode: 'edit', - language: 'typescript', - runtimeEnvironmentId: null - }, - { suppressActiveRuntimeFallback: true } - ) - let contents: Record = {} - const { result } = renderHook(() => - useEditorPanelFileContentLoader({ - fileLoadRetryAttemptsRef: { current: {} }, - fileReadGenerationCounterRef: { current: 0 }, - fileReadGenerationRef: { current: {} }, - outstandingFileReadsRef: { current: {} }, - openFilesRef: { - get current() { - return useAppStore.getState().openFiles - } - }, - setFileContents: (update) => { - contents = typeof update === 'function' ? update(contents) : update - } - }) - ) - await act(async () => { - await result.current(filePath, id, workspaceId, 'local/file.ts') - }) - expect(contents[id]).toMatchObject({ content: 'disk content', isBinary: false }) - expect(live(id).lastKnownDiskSignature).toBe(getDiskBaselineSignature('disk content')) - expect(live(id).operationProvenance).toMatchObject({ - childRepo: { id: 'child', path: '/root/local' } - }) - return id -} - -function live(id: string) { - const file = useAppStore.getState().openFiles.find((file) => file.id === id) - if (!file) { - throw new Error('Missing loaded tab') - } - return file -} - -function edit(id: string, draft: string) { - useAppStore.getState().setEditorDraft(id, draft) - useAppStore.getState().markFileDirty(id, true) -} - -describe('loaded child-file save ownership', () => { - it('autosaves then drains a queued restart to the acquired child after unrelated sibling removal', async () => { - const id = await loadChild() - let finish!: (result: FileWriteResult) => void - io.write.mockReturnValueOnce( - new Promise((resolve) => { - finish = resolve - }) - ) - edit(id, 'autosave text') - queue.syncAutoSave() - await vi.waitFor(() => expect(io.write).toHaveBeenCalledOnce()) - edit(id, 'restart text') - const pending = queue.queueSave(live(id), 'restart text', 'restart') - useAppStore.setState((state) => ({ repos: state.repos.filter((repo) => repo.id !== 'remote') })) - finish({ ok: true }) - await expect(pending).resolves.toBe('written') - expect(io.write).toHaveBeenCalledTimes(2) - for (const [context, path] of io.write.mock.calls) { - expect(context).toMatchObject({ target: { kind: 'local' }, expectedExecutionHostId: 'local' }) - expect(context.connectionId).toBeUndefined() - expect(path).toBe(filePath) - } - expect(io.write.mock.calls.map((call) => call[2])).toEqual(['autosave text', 'restart text']) - expect(live(id).isDirty).toBe(false) - }) - - it.each(['replaced', 'removed', 'authority'] as const)( - 'refuses a queued restart after the child is %s and retains its draft', - async (change) => { - const id = await loadChild() - const stamp = live(id).operationProvenance - let finish!: (result: FileWriteResult) => void - io.write.mockReturnValueOnce( - new Promise((resolve) => { - finish = resolve - }) - ) - edit(id, 'first text') - const first = queue.queueSave(live(id), 'first text') - await vi.waitFor(() => expect(io.write).toHaveBeenCalledOnce()) - edit(id, 'retained draft') - const restart = queue.queueSave(live(id), 'retained draft', 'restart') - useAppStore.setState((state) => ({ - repos: state.repos.flatMap((repo) => - repo.id !== 'child' - ? [repo] - : change === 'removed' - ? [] - : [ - { - ...repo, - ...(change === 'replaced' - ? { id: 'replacement' } - : { executionHostId: 'ssh:other' as const, connectionId: 'other' }) - } - ] - ) - })) - finish({ ok: true }) - await first - await expect(restart).resolves.toBe('failed') - expect(io.write).toHaveBeenCalledOnce() - expect(live(id).operationProvenance).toBe(stamp) - expect(useAppStore.getState().editorDrafts[id]).toBe('retained draft') - expect(live(id).isDirty).toBe(true) - } - ) -}) diff --git a/src/renderer/src/components/editor/save/commands/editor-file-save-attempt.ts b/src/renderer/src/components/editor/save/commands/editor-file-save-attempt.ts index dcc477864c4..0ebe20e3599 100644 --- a/src/renderer/src/components/editor/save/commands/editor-file-save-attempt.ts +++ b/src/renderer/src/components/editor/save/commands/editor-file-save-attempt.ts @@ -7,7 +7,7 @@ import { EDITOR_NOT_UTF8_SAVE_MESSAGE, EDITOR_STALE_SAVE_MESSAGE } from '../queue/editor-save-disk-precondition' -import { FILE_BYTES_SAVE_UPDATE_REQUIRED_MESSAGE } from '../../../../../../shared/file-bytes-write' +import { FILE_BYTES_SAVE_UPDATE_REQUIRED_MESSAGE } from '../../../../../../shared/file-write/file-bytes-write' import { EditorSaveDeniedByPluginError } from '../transforms/editor-save-plugin-hook' /** Asks before an explicit save rewrites a non-UTF-8 file as UTF-8, which can't be undone. */ diff --git a/src/renderer/src/components/editor/save/commands/editor-untitled-save-lifecycle.test.ts b/src/renderer/src/components/editor/save/commands/editor-untitled-save-lifecycle.test.ts index 310ad251fb4..fb85e094e96 100644 --- a/src/renderer/src/components/editor/save/commands/editor-untitled-save-lifecycle.test.ts +++ b/src/renderer/src/components/editor/save/commands/editor-untitled-save-lifecycle.test.ts @@ -12,7 +12,7 @@ import { } from '../../autosave/editor-autosave-controller-test-fixture' import { discardEditorFileChangesAndClose } from '../flush/discard-editor-file-changes' import { __clearSelfWriteRegistryForTests } from '../../external-changes/editor-self-write-registry' -import { getDiskBaselineSignature } from '../../../../../../shared/disk-baseline-signature' +import { getDiskBaselineSignature } from '../../../../../../shared/file-write/disk-baseline-signature' const storeHolder = vi.hoisted((): { store: StoreApi | null } => ({ store: null })) @@ -127,58 +127,6 @@ describe('untitled note save lifecycle', () => { } }) - it("keeps autosaved content when Don't Save interrupts the in-flight write", async () => { - loadFromDisk(store, '') - let finishWrite: () => void = () => {} - disk.fs.writeFile.mockImplementationOnce( - ({ filePath, content }: { filePath: string; content: string }) => - new Promise((resolve) => { - finishWrite = () => { - disk.files.set(filePath, content) - resolve() - } - }) - ) - const cleanup = attachEditorAutosaveController(withLoadedBaselines(store, disk)) - try { - typeInto(store, 'my note') - await vi.advanceTimersByTimeAsync(1500) - expect(disk.fs.writeFile).toHaveBeenCalledTimes(1) - - const discarded = discardEditorFileChangesAndClose(FILE_ID) - finishWrite() - await discarded - // Why: the superseded save left the tab looking like a placeholder, so only the size check keeps the note. - await vi.advanceTimersByTimeAsync(0) - - expect(store.getState().openFiles).toHaveLength(0) - expect(disk.files.get(FILE_ID)).toBe('my note') - expect(disk.fs.deletePath).not.toHaveBeenCalled() - } finally { - cleanup() - } - }) - - it.each([ - ['while its tab showed the new text', true], - ['while its tab was in the background', false] - ])('keeps a note an agent wrote into %s', async (_when, reloaded) => { - loadFromDisk(store, '') - disk.files.set(FILE_ID, 'agent text') - if (reloaded) { - loadFromDisk(store, 'agent text') - } - - store.getState().closeFile(FILE_ID) - - // Why: a macrotask drains the stat → delete chain before asserting nothing was removed. - await vi.advanceTimersByTimeAsync(0) - expect(disk.files.get(FILE_ID)).toBe('agent text') - expect(disk.fs.deletePath).not.toHaveBeenCalled() - // Why: a background tab never reloaded the write, so only the size check knew it was a real note. - expect(isReopenable(store)).toBe(reloaded) - }) - it("removes a never-saved note's placeholder on Don't Save", async () => { loadFromDisk(store, '') typeInto(store, 'typed but never saved') diff --git a/src/renderer/src/components/editor/save/queue/editor-save-closed-view.test-fixture.ts b/src/renderer/src/components/editor/save/queue/editor-save-closed-view.test-fixture.ts index e2440f2e60a..f642d2b43bf 100644 --- a/src/renderer/src/components/editor/save/queue/editor-save-closed-view.test-fixture.ts +++ b/src/renderer/src/components/editor/save/queue/editor-save-closed-view.test-fixture.ts @@ -1,7 +1,7 @@ import { vi } from 'vitest' import type { OpenFile } from '@/store/slices/editor/types/open-file' import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' -import { getDiskBaselineSignature } from '../../../../../../shared/disk-baseline-signature' +import { getDiskBaselineSignature } from '../../../../../../shared/file-write/disk-baseline-signature' import type { ExecutionHostId } from '../../../../../../shared/execution-host' import { createEditorSaveQueue } from './editor-save-queue' import type { EditorSaveQueue } from './editor-save-queue-contract' diff --git a/src/renderer/src/components/editor/save/queue/editor-save-disk-precondition.races.test.ts b/src/renderer/src/components/editor/save/queue/editor-save-disk-precondition.races.test.ts index 634b96555b5..d31a018accd 100644 --- a/src/renderer/src/components/editor/save/queue/editor-save-disk-precondition.races.test.ts +++ b/src/renderer/src/components/editor/save/queue/editor-save-disk-precondition.races.test.ts @@ -1,10 +1,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { ORCA_EDITOR_FILE_CACHE_STALE_EVENT, - ORCA_EDITOR_FILE_SAVED_EVENT, ORCA_EDITOR_SAVE_AND_CLOSE_EVENT, requestEditorFileSave, - requestEditorSaveQuiesce, type EditorSaveAndCloseDetail } from '../../autosave/editor-autosave' import { attachEditorAutosaveController } from '../../autosave/editor-autosave-controller' @@ -12,10 +10,7 @@ import { __clearSelfWriteRegistryForTests } from '../../external-changes/editor- import { createEditorStore } from '../../autosave/editor-autosave-controller-test-fixture' import { keepTabEditsOverExternalChange } from '../../external-changes/ExternalFileChangeBanner' -import { - getDiskBaselineSignature, - getWrittenContentDiskSignature -} from '../../../../../../shared/disk-baseline-signature' +import { getDiskBaselineSignature } from '../../../../../../shared/file-write/disk-baseline-signature' import { GUARDED_PATH, openGuardedFile, stubGuardedDisk } from './editor-save-guarded-disk-fixture' import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' @@ -55,32 +50,6 @@ describe('guarded editor saves under races', () => { mocks.toastError.mockReset() }) - it('rebaselines to its own write even when a quiesce supersedes the save mid-write', async () => { - const gate = deferred() - const disk = stubGuardedDisk({ [GUARDED_PATH]: 'original' }, () => gate.promise) - const store = createEditorStore() - openGuardedFile(store, { baseline: 'original', draft: 'first' }) - - const cleanup = attachEditorAutosaveController(store) - try { - const save = requestEditorFileSave({ fileId: GUARDED_PATH }) - await vi.advanceTimersByTimeAsync(0) - const quiesce = requestEditorSaveQuiesce({ fileId: GUARDED_PATH }) - gate.resolve() - await save - await quiesce - expect(store.getState().openFiles[0]?.lastKnownDiskSignature).toBe( - getWrittenContentDiskSignature('first') - ) - - store.getState().setEditorDraft(GUARDED_PATH, 'second') - await requestEditorFileSave({ fileId: GUARDED_PATH }) - expect(disk.files.get(GUARDED_PATH)).toBe('second') - } finally { - cleanup() - } - }) - function openSharedModelTabs(disk: string) { const store = createEditorStore() storeRef.current = store @@ -108,49 +77,6 @@ describe('guarded editor saves under races', () => { return { store, a, b } } - it('coalesces saves from two views of one record into one write, ending on the saved text', async () => { - const gate = deferred() - const disk = stubGuardedDisk({ [GUARDED_PATH]: 'A' }, () => gate.promise) - const { store, a, b } = openSharedModelTabs('A') - for (const tab of [a, b]) { - store.getState().setEditorDraft(tab.id, 'X') - store.getState().markFileDirty(tab.id, true) - } - // Mount from per-tab text updated by saved events, matching panel consumers. - const shown = new Map([ - [a.id, 'A'], - [b.id, 'A'] - ]) - const onSaved = (event: Event): void => { - if (event instanceof CustomEvent) { - shown.set(event.detail.fileId, event.detail.content) - } - } - window.addEventListener(ORCA_EDITOR_FILE_SAVED_EVENT, onSaved) - - const cleanup = attachEditorAutosaveController(store) - try { - const saves = Promise.all([ - requestEditorFileSave({ fileId: a.id }), - requestEditorFileSave({ fileId: b.id }) - ]) - gate.resolve() - await saves - - expect(disk.writeFile).toHaveBeenCalledTimes(1) - expect(disk.files.get(GUARDED_PATH)).toBe('X') - expect(shown.get(a.id)).toBe('X') - for (const tab of store.getState().openFiles) { - expect(tab.isDirty).toBe(false) - expect(tab.externalMutation).toBeUndefined() - expect(store.getState().editorDrafts[tab.id]).toBeUndefined() - } - } finally { - cleanup() - window.removeEventListener(ORCA_EDITOR_FILE_SAVED_EVENT, onSaved) - } - }) - it('makes Cmd+S in one tab wait for Keep My Edits in its sibling', async () => { const disk = stubGuardedDisk({ [GUARDED_PATH]: 'B' }) const { store, a, b } = openSharedModelTabs('A') diff --git a/src/renderer/src/components/editor/save/queue/editor-save-disk-precondition.test.ts b/src/renderer/src/components/editor/save/queue/editor-save-disk-precondition.test.ts index 5eed4c00323..4b91bd1f4f6 100644 --- a/src/renderer/src/components/editor/save/queue/editor-save-disk-precondition.test.ts +++ b/src/renderer/src/components/editor/save/queue/editor-save-disk-precondition.test.ts @@ -1,16 +1,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { requestEditorFileSave } from '../../autosave/editor-autosave' import { attachEditorAutosaveController } from '../../autosave/editor-autosave-controller' -import { - __clearSelfWriteRegistryForTests, - hasRecentSelfWrite -} from '../../external-changes/editor-self-write-registry' +import { __clearSelfWriteRegistryForTests } from '../../external-changes/editor-self-write-registry' import { createEditorStore } from '../../autosave/editor-autosave-controller-test-fixture' import { overwriteDiskWithTabEdits } from '../../external-changes/ExternalFileChangeBanner' -import { - getDiskBaselineSignature, - getWrittenContentDiskSignature -} from '../../../../../../shared/disk-baseline-signature' +import { getDiskBaselineSignature } from '../../../../../../shared/file-write/disk-baseline-signature' import { GUARDED_PATH, openGuardedFile, stubGuardedDisk } from './editor-save-guarded-disk-fixture' @@ -53,95 +47,6 @@ describe('editor saves guarded by the disk precondition', () => { __clearSelfWriteRegistryForTests() }) - it('cleans a tab whose disk already holds the edit, without retaining a self-write stamp', async () => { - const disk = stubGuardedDisk({ [PATH]: 'user edit' }) - const store = createEditorStore() - openFile(store, { baseline: 'original', draft: 'user edit' }) - const cleanup = attachEditorAutosaveController(store) - try { - await requestEditorFileSave({ fileId: PATH }) - - await expect(disk.writeFile.mock.results[0]?.value).resolves.toEqual({ - ok: true, - unchanged: true - }) - expect(store.getState().openFiles[0]).toMatchObject({ - isDirty: false, - lastKnownDiskSignature: getWrittenContentDiskSignature('user edit') - }) - expect(store.getState().editorDrafts[PATH]).toBeUndefined() - expect(hasRecentSelfWrite(PATH)).toBe(false) - } finally { - cleanup() - } - }) - - it('blocks an autosave over an unnoticed agent write and raises the banner', async () => { - const disk = stubGuardedDisk({ [PATH]: 'original' }) - const store = createEditorStore() - openFile(store, { baseline: 'original', draft: 'user edit' }) - // Simulate an external write without a watcher notification. - disk.files.set(PATH, 'agent rewrite') - - const cleanup = attachEditorAutosaveController(store) - try { - await vi.advanceTimersByTimeAsync(1500) - - expect(disk.writeFile).toHaveBeenCalledWith( - expect.objectContaining({ - content: 'user edit', - diskPrecondition: { - expectedSignature: getDiskBaselineSignature('original'), - allowMissing: false, - requireLosslessUtf8: true - } - }) - ) - expect(disk.files.get(PATH)).toBe('agent rewrite') - const file = store.getState().openFiles[0] - expect(file?.externalMutation).toBe('changed') - expect(file?.isDirty).toBe(true) - expect(store.getState().editorDrafts[PATH]).toBe('user edit') - - // The banner pauses autosave, so no retry loop follows. - store.getState().setEditorDraft(PATH, 'user edit 2') - await vi.advanceTimersByTimeAsync(1500) - expect(disk.writeFile).toHaveBeenCalledTimes(1) - } finally { - cleanup() - } - }) - - it('keeps refusing explicit saves while the banner shows; only its Overwrite writes', async () => { - const disk = stubGuardedDisk({ [PATH]: 'agent rewrite' }) - const store = createEditorStore() - storeRef.current = store - openFile(store, { baseline: 'original', draft: 'user edit' }) - - const cleanup = attachEditorAutosaveController(store) - try { - await expect(requestEditorFileSave({ fileId: PATH })).rejects.toThrow(/changed on disk/) - expect(disk.files.get(PATH)).toBe('agent rewrite') - expect(store.getState().openFiles[0]?.externalMutation).toBe('changed') - - // Cmd+S again (from the editor or a preview) is not consent. - await expect(requestEditorFileSave({ fileId: PATH })).rejects.toThrow(/changed on disk/) - expect(disk.files.get(PATH)).toBe('agent rewrite') - - expect(await overwriteDiskWithTabEdits(store.getState().openFiles[0])).toBe(true) - expect(disk.writeFile).toHaveBeenLastCalledWith( - expect.not.objectContaining({ diskPrecondition: expect.anything() }) - ) - expect(disk.files.get(PATH)).toBe('user edit') - const file = store.getState().openFiles[0] - expect(file?.externalMutation).toBeUndefined() - expect(file?.isDirty).toBe(false) - expect(file?.lastKnownDiskSignature).toBe(getDiskBaselineSignature('user edit')) - } finally { - cleanup() - } - }) - // Why: a granted host path must never become a write of this computer's same path. it('refuses to save a host-granted tab whose owner resolves to this computer', async () => { const disk = stubGuardedDisk({ [PATH]: 'original' }) diff --git a/src/renderer/src/components/editor/save/queue/editor-save-disk-precondition.ts b/src/renderer/src/components/editor/save/queue/editor-save-disk-precondition.ts index e63e1a52aca..80e0d42067b 100644 --- a/src/renderer/src/components/editor/save/queue/editor-save-disk-precondition.ts +++ b/src/renderer/src/components/editor/save/queue/editor-save-disk-precondition.ts @@ -9,8 +9,8 @@ import { getEditorViewLanguage, getMarkdownViewModes } from '../../view-mode/markdown-preview-controls' -import type { FileWriteResult } from '../../../../../../shared/file-write-disk-precondition' -import type { LocalFileAccess } from '../../../../../../shared/local-file-access' +import type { FileWriteResult } from '../../../../../../shared/file-write/file-write-disk-precondition' +import type { LocalFileAccess } from '../../../../../../shared/file-access/local-file-access' import type { RuntimeFileOperationArgs } from '@/runtime/files/runtime-file-client-types' import { writeRuntimeFile } from '@/runtime/files/mutations/runtime-file-mutation-client' import { writeRuntimeTerminalArtifactFile } from '@/runtime/files/grants/runtime-terminal-artifact-write' diff --git a/src/renderer/src/components/editor/save/queue/editor-save-guarded-disk-fixture.ts b/src/renderer/src/components/editor/save/queue/editor-save-guarded-disk-fixture.ts index 9787347ca59..c4bea14a2df 100644 --- a/src/renderer/src/components/editor/save/queue/editor-save-guarded-disk-fixture.ts +++ b/src/renderer/src/components/editor/save/queue/editor-save-guarded-disk-fixture.ts @@ -2,11 +2,11 @@ import { vi } from 'vitest' import type { StoreApi } from 'zustand' import type { AppState } from '@/store/types' -import { getDiskBaselineSignature } from '../../../../../../shared/disk-baseline-signature' +import { getDiskBaselineSignature } from '../../../../../../shared/file-write/disk-baseline-signature' import { compareDiskWritePrecondition, type FileWriteDiskPrecondition -} from '../../../../../../shared/file-write-disk-precondition' +} from '../../../../../../shared/file-write/file-write-disk-precondition' export const GUARDED_PATH = '/repo/file.ts' diff --git a/src/renderer/src/components/editor/save/queue/editor-save-queue-closed-view-records.test.ts b/src/renderer/src/components/editor/save/queue/editor-save-queue-closed-view-records.test.ts index 55c7cda88bc..4d3fd153072 100644 --- a/src/renderer/src/components/editor/save/queue/editor-save-queue-closed-view-records.test.ts +++ b/src/renderer/src/components/editor/save/queue/editor-save-queue-closed-view-records.test.ts @@ -1,9 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { getDiskBaselineSignature } from '../../../../../../shared/disk-baseline-signature' import { closedViewTab, - closedViewWorktree, createClosedViewHarness, type ClosedViewHarness } from './editor-save-closed-view.test-fixture' @@ -29,142 +27,6 @@ describe('editor save queue: closed saving view, record changes', () => { return { saved } } - it('does not settle a different host after the record is re-keyed mid-write', async () => { - h.type('A', 'edit') - const { saved } = await startHeldSave() - const before = h.recordOf('A') - // Changing both workspace hosts rekeys the record while retaining its views. - h.store.setState({ - worktreesByRepo: { - 'repo-1': [closedViewWorktree('wt-1', 'ssh:box'), closedViewWorktree('wt-2', 'ssh:box')] - } - }) - expect(h.recordOf('B')).not.toBe(before) - expect(h.recordOf('B')).not.toBe(h.recordOf('A')) - h.closeView('A') - h.release() - await expect(saved).resolves.toBe('written') - - expect(h.view('B').isDirty).toBe(true) - expect(h.store.getState().editorDrafts.B).toBe('edit') - expect(h.view('B').lastKnownDiskSignature).toBe(getDiskBaselineSignature('disk')) - }) - - it("moves a detached peer's baseline to the write, keeping its edits", async () => { - h.store.setState({ openFiles: [] }) - h.store.setState({ - openFiles: [ - { ...closedViewTab('A', 'wt-1'), isDirty: true }, - { ...closedViewTab('B', 'wt-2'), isDirty: true } - ], - editorDrafts: { A: 'edit', B: 'theirs' } - }) - expect(h.recordOf('B')).not.toBe(h.recordOf('A')) - const { saved } = await startHeldSave() - h.closeView('A') - h.release() - await expect(saved).resolves.toBe('written') - - expect(h.view('B').lastKnownDiskSignature).toBe(getDiskBaselineSignature('edit')) - expect(h.view('B').isDirty).toBe(true) - expect(h.store.getState().editorDrafts.B).toBe('theirs') - await expect(h.queue.queueSave(h.view('B'), 'theirs')).resolves.toBe('written') - }) - - it.each(['mine, more', 'mine'])( - 'keeps the latest retained detached draft %s until the write settles', - async (draft) => { - h.store.setState({ openFiles: [] }) - h.store.setState({ - openFiles: [ - { ...closedViewTab('A', 'wt-1'), isDirty: true }, - { ...closedViewTab('B', 'wt-2'), isDirty: true } - ], - editorDrafts: { A: 'theirs', B: 'mine' } - }) - const detached = h.recordOf('B') - h.holdNextWrite() - const saved = h.queue.queueSave(h.view('B'), 'mine') - await vi.advanceTimersByTimeAsync(0) - h.type('B', draft) - h.store.setState((state) => ({ - openFiles: state.openFiles.filter((file) => file.id !== 'B'), - editorBufferKeepRequest: { viewIds: new Set(['B']), notice: 2 } - })) - const kept = h.store.getState().editorBufferKept[detached] - expect(kept?.draft).toBe(draft) - expect(kept?.resourceKey).toBeTruthy() - h.release() - await expect(saved).resolves.toBe('written') - if (draft === 'mine') { - expect(h.store.getState().editorBufferKept[detached]).toBeUndefined() - } else { - expect(h.store.getState().editorBufferKept[detached]).toMatchObject({ - notice: 2, - draft, - resourceKey: kept?.resourceKey, - record: { isDirty: true, lastKnownDiskSignature: getDiskBaselineSignature('mine') } - }) - } - expect(h.store.getState().editorDrafts.A).toBe('theirs') - } - ) - - it('does not settle a reused detached record belonging to a different file', async () => { - h.store.setState({ openFiles: [] }) - h.store.setState({ - openFiles: [ - { ...closedViewTab('A', 'wt-1'), isDirty: true }, - { ...closedViewTab('B', 'wt-2'), isDirty: true } - ], - editorDrafts: { A: 'theirs', B: 'mine' } - }) - const detached = h.recordOf('B') - h.holdNextWrite() - const saved = h.queue.queueSave(h.view('B'), 'mine') - await vi.advanceTimersByTimeAsync(0) - h.closeView('B') - const foreign = { - ...closedViewTab('B', 'wt-2'), - filePath: '/repo/foreign.md', - relativePath: 'foreign.md', - isDirty: true - } - h.store.setState((state) => ({ - openFiles: [...state.openFiles, { ...foreign, id: 'C' }, foreign], - editorDrafts: { ...state.editorDrafts, B: 'foreign draft', C: 'foreign peer' } - })) - expect(h.recordOf('B')).toBe(detached) - h.store.setState((state) => ({ - openFiles: state.openFiles.filter((file) => file.id !== 'B'), - editorBufferKeepRequest: { viewIds: new Set(['B']), notice: 3 } - })) - const kept = h.store.getState().editorBufferKept[detached] - expect(kept?.draft).toBe('foreign draft') - h.release() - await expect(saved).resolves.toBe('written') - expect(h.store.getState().editorBufferKept[detached]).toEqual(kept) - expect(h.view('C').lastKnownDiskSignature).toBe(getDiskBaselineSignature('disk')) - expect(h.store.getState().editorDrafts.C).toBe('foreign peer') - }) - - it('joins a retained record when the file reopens before its issued write completes', async () => { - h.type('A', 'edit') - const { saved } = await startHeldSave() - h.store.setState({ - openFiles: [], - editorBufferKeepRequest: { viewIds: new Set(['A', 'B']), notice: 1 } - }) - h.store.setState({ openFiles: [closedViewTab('return', 'wt-2')] }) - expect(h.store.getState().editorDrafts.return).toBe('edit') - h.release() - await expect(saved).resolves.toBe('written') - expect(h.view('return').isDirty).toBe(false) - expect(h.store.getState().editorDrafts.return).toBeUndefined() - expect(h.view('return').lastKnownDiskSignature).toBe(getDiskBaselineSignature('edit')) - expect(h.store.getState().editorBufferKept).toEqual({}) - }) - it('marks the record clean when only a read-only view is left', async () => { h.store.setState({ openFiles: [] }) h.store.setState({ diff --git a/src/renderer/src/components/editor/save/queue/editor-save-queue-closed-view.test.ts b/src/renderer/src/components/editor/save/queue/editor-save-queue-closed-view.test.ts index 442126f90aa..118b3f38780 100644 --- a/src/renderer/src/components/editor/save/queue/editor-save-queue-closed-view.test.ts +++ b/src/renderer/src/components/editor/save/queue/editor-save-queue-closed-view.test.ts @@ -1,10 +1,5 @@ -import { - ORCA_EDITOR_FILE_CACHE_STALE_EVENT, - ORCA_EDITOR_FILE_SAVED_EVENT -} from '../../autosave/editor-autosave' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { getDiskBaselineSignature } from '../../../../../../shared/disk-baseline-signature' import { CLOSED_VIEW_PATH, closedViewTab, @@ -25,91 +20,6 @@ describe('editor save queue: the saving view closes mid-write', () => { afterEach(() => h.dispose()) - it('publishes one settled record before accepting newer subscriber typing', async () => { - h.type('A', 'edit') - h.holdNextWrite() - const saved = h.queue.queueSave(h.view('A'), 'edit') - await vi.advanceTimersByTimeAsync(0) - h.closeView('A') - const unsubscribe = h.store.subscribe((state, previous) => { - if ( - state.openFiles[0]?.lastKnownDiskSignature !== previous.openFiles[0]?.lastKnownDiskSignature - ) { - expect(state.openFiles[0]?.isDirty).toBe(false) - expect(state.editorDrafts.B).toBeUndefined() - h.type('B', 'typed during publication') - } - }) - h.release() - await expect(saved).resolves.toBe('written') - unsubscribe() - expect(h.view('B').isDirty).toBe(true) - expect(h.store.getState().editorDrafts.B).toBe('typed during publication') - expect(h.view('B').lastKnownDiskSignature).toBe(getDiskBaselineSignature('edit')) - }) - - it('does not notify a reused view replaced synchronously during settlement', async () => { - h.type('A', 'edit') - h.holdNextWrite() - const saved = h.queue.queueSave(h.view('A'), 'edit') - await vi.advanceTimersByTimeAsync(0) - h.closeView('A') - let replaced = false - const events = vi.spyOn(window, 'dispatchEvent') - const unsubscribe = h.store.subscribe((state, previous) => { - if ( - !replaced && - state.openFiles[0]?.lastKnownDiskSignature !== previous.openFiles[0]?.lastKnownDiskSignature - ) { - replaced = true - h.closeView('B') - h.store.setState({ - openFiles: [ - { - ...closedViewTab('B', 'wt-2'), - filePath: '/repo/foreign.md', - relativePath: 'foreign.md', - isDirty: true - } - ], - editorDrafts: { B: 'foreign draft' } - }) - } - }) - h.release() - await expect(saved).resolves.toBe('written') - unsubscribe() - expect(replaced).toBe(true) - expect(h.view('B').lastKnownDiskSignature).toBe(getDiskBaselineSignature('disk')) - expect(h.store.getState().editorDrafts.B).toBe('foreign draft') - expect( - events.mock.calls.filter( - ([event]) => - event.type === ORCA_EDITOR_FILE_SAVED_EVENT || - event.type === ORCA_EDITOR_FILE_CACHE_STALE_EVENT - ) - ).toEqual([]) - events.mockRestore() - }) - - it('a save queued behind the running one still writes the record through the view left', async () => { - h.type('A', 'edit') - h.holdNextWrite() - const first = h.queue.queueSave(h.view('A'), 'edit') - await vi.advanceTimersByTimeAsync(0) - h.type('A', 'edit 2') - const second = h.queue.queueSave(h.view('A'), 'edit 2') - h.closeView('A') - h.release() - - await expect(first).resolves.toBe('written') - await expect(second).resolves.toBe('written') - expect(h.disk.files.get(CLOSED_VIEW_PATH)).toBe('edit 2') - expect(h.view('B').isDirty).toBe(false) - expect(h.view('B').lastKnownDiskSignature).toBe(getDiskBaselineSignature('edit 2')) - expect(h.loaded.B?.content).toBe('edit 2') - }) - it('a refused write banners the view left', async () => { h.type('A', 'edit') h.holdNextWrite(true) diff --git a/src/renderer/src/components/editor/save/queue/editor-save-queue-shared-records.test.ts b/src/renderer/src/components/editor/save/queue/editor-save-queue-shared-records.test.ts index 0670a3af7dc..b21e8574f79 100644 --- a/src/renderer/src/components/editor/save/queue/editor-save-queue-shared-records.test.ts +++ b/src/renderer/src/components/editor/save/queue/editor-save-queue-shared-records.test.ts @@ -2,10 +2,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { OpenFile } from '@/store/slices/editor/types/open-file' import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' -import { getDiskBaselineSignature } from '../../../../../../shared/disk-baseline-signature' +import { getDiskBaselineSignature } from '../../../../../../shared/file-write/disk-baseline-signature' import { createEditorSaveQueue } from './editor-save-queue' import type { EditorSaveQueue } from './editor-save-queue-contract' -import { createEditorRestartSaveHandlers } from '../../autosave/editor-restart-save-handlers' + import { __clearSelfWriteRegistryForTests } from '../../external-changes/editor-self-write-registry' import { @@ -18,7 +18,6 @@ import { vi.mock('@/lib/connection-context', () => ({ getConnectionIdForFile: () => undefined })) const PATH = '/repo/a.ts' -const DELAY_MS = 1000 const WORKTREES = { 'repo-1': [ makeWorktree({ id: 'wt-1', repoId: 'repo-1', path: '/repo', hostId: 'local' }), @@ -59,8 +58,6 @@ describe('editor save queue: shared records', () => { } return found } - const recordOf = (id: string): string => store.getState().editorBufferIdOf[id] - const writes = (): string[] => disk.fs.writeFile.mock.calls.map(([args]) => args.content) beforeEach(() => { vi.useFakeTimers() @@ -78,105 +75,7 @@ describe('editor save queue: shared records', () => { vi.restoreAllMocks() }) - describe('a read-only sibling joining a dirty record', () => { - it('mirrors the edits, and autosave writes once through the writable view', async () => { - store.setState({ openFiles: [tab('w1')] }) - type('w1', 'edits') - // Listed first, so a per-tab pick would choose it. - store.setState((s) => ({ openFiles: [tab('log', { readOnly: true }), ...s.openFiles] })) - queue.syncAutoSave() - - expect(recordOf('log')).toBe(recordOf('w1')) - expect(view('log').isDirty).toBe(true) - expect(store.getState().editorDrafts.log).toBe('edits') - await vi.advanceTimersByTimeAsync(DELAY_MS) - - expect(writes()).toEqual(['edits']) - expect(view('log').isDirty).toBe(false) - expect(view('w1').isDirty).toBe(false) - }) - }) - - describe('restart save', () => { - const restart = async (): Promise<{ resolved: boolean; rejected?: string }> => { - const { handleSaveDirtyFiles } = createEditorRestartSaveHandlers({ - store, - queueSave: queue.queueSave, - settleFileSaves: queue.settleFileSaves - }) - const outcome: { resolved: boolean; rejected?: string } = { resolved: false } - const detail = { - claim: () => {}, - resolve: () => { - outcome.resolved = true - }, - reject: (message: string) => { - outcome.rejected = message - } - } - await handleSaveDirtyFiles(new CustomEvent('restart', { detail })) - return outcome - } - - it('writes each record once, whichever workspace holds its views', async () => { - store.setState({ - openFiles: [ - tab('w1'), - tab('w2', { worktreeId: 'wt-2' }), - tab('b1', { filePath: '/repo/b.ts', relativePath: 'b.ts' }), - tab('b2', { filePath: '/repo/b.ts', relativePath: 'b.ts', worktreeId: 'wt-2' }) - ] - }) - disk.files.set('/repo/b.ts', 'disk') - type('w2', 'a edits') - type('b1', 'b edits') - - expect(await restart()).toEqual({ resolved: true }) - expect(disk.fs.writeFile).toHaveBeenCalledTimes(2) - expect(disk.files.get(PATH)).toBe('a edits') - expect(disk.files.get('/repo/b.ts')).toBe('b edits') - expect(store.getState().openFiles.every((file) => !file.isDirty)).toBe(true) - }) - }) - describe('re-keys carry the record', () => { - it('a rename carries a conflict onto the clean record at the new path', async () => { - disk.files.set('/repo/old.ts', 'disk') - store.setState({ - openFiles: [tab('old', { filePath: '/repo/old.ts', relativePath: 'old.ts' }), tab('w2')] - }) - type('old', 'edits') - store.getState().setExternalMutation('old', 'changed') - - const result = store.getState().rekeyOpenFilesForPathChange({ - rekeys: [ - { - oldFileId: 'old', - newFileId: 'renamed', - oldFilePath: '/repo/old.ts', - newFilePath: PATH, - newRelativePath: 'a.ts' - } - ] - }) - queue.syncAutoSave() - - expect(result).toEqual({ ok: true }) - expect(recordOf('renamed')).toBe(recordOf('w2')) - for (const id of ['renamed', 'w2']) { - expect(view(id).externalMutation).toBe('changed') - expect(view(id).isDirty).toBe(true) - expect(store.getState().editorDrafts[id]).toBe('edits') - } - await vi.advanceTimersByTimeAsync(DELAY_MS * 2) - expect(writes()).toEqual([]) - - store.getState().setExternalMutation('w2', null) - queue.syncAutoSave() - await vi.advanceTimersByTimeAsync(DELAY_MS) - expect(writes()).toEqual(['edits']) - }) - it('a stale baseline carried by a rename is refused and bannered on every view', async () => { disk.files.set('/repo/old.ts', 'disk') disk.files.set(PATH, 'someone else') @@ -205,37 +104,5 @@ describe('editor save queue: shared records', () => { expect(view('w2').externalMutation).toBe('changed') expect(view('w2').isDirty).toBe(true) }) - - it('owner resolution re-keys a record by route inputs alone, keeping its conflict', async () => { - store.setState({ worktreesByRepo: {} }) - store.setState({ openFiles: [tab('w1'), tab('w2', { worktreeId: 'wt-2' })] }) - // Unresolved owners never share. - expect(recordOf('w1')).not.toBe(recordOf('w2')) - type('w1', 'edits') - store.getState().setExternalMutation('w1', 'changed') - const openFilesBefore = store.getState().openFiles - - store.setState({ worktreesByRepo: WORKTREES }) - queue.syncAutoSave() - - const state = store.getState() - expect(recordOf('w1')).toBe(recordOf('w2')) - expect(recordOf('w1')).not.toBe('w1') - expect(Object.keys(state.editorBuffers)).toEqual([recordOf('w1')]) - expect(state.openFiles.map((file) => file.id)).toEqual(openFilesBefore.map((f) => f.id)) - expect(view('w1')).toBe(openFilesBefore[0]) - for (const id of ['w1', 'w2']) { - expect(view(id).externalMutation).toBe('changed') - expect(view(id).isDirty).toBe(true) - expect(state.editorDrafts[id]).toBe('edits') - } - await vi.advanceTimersByTimeAsync(DELAY_MS * 2) - expect(writes()).toEqual([]) - - store.getState().setExternalMutation('w2', null) - queue.syncAutoSave() - await vi.advanceTimersByTimeAsync(DELAY_MS) - expect(writes()).toEqual(['edits']) - }) }) }) diff --git a/src/renderer/src/components/editor/save/queue/editor-save-queue.ts b/src/renderer/src/components/editor/save/queue/editor-save-queue.ts index c44d015f585..282f898454b 100644 --- a/src/renderer/src/components/editor/save/queue/editor-save-queue.ts +++ b/src/renderer/src/components/editor/save/queue/editor-save-queue.ts @@ -24,14 +24,14 @@ import { recordSelfWrite, SELF_WRITE_REMOTE_TTL_MS } from '../../external-changes/editor-self-write-registry' -import { getDiskBaselineSignature } from '../../../../../../shared/disk-baseline-signature' +import { getDiskBaselineSignature } from '../../../../../../shared/file-write/disk-baseline-signature' import { markEditorSaveRefusal, settleEditorRecordAfterWrite, setModelExternalMutation, waitForModelBaselineRestamps } from './editor-save-rebaseline' -import type { FileWriteResult } from '../../../../../../shared/file-write-disk-precondition' +import type { FileWriteResult } from '../../../../../../shared/file-write/file-write-disk-precondition' import { editorSavePrecondition, editorSaveGrant, diff --git a/src/renderer/src/components/editor/save/queue/editor-save-rebaseline.ts b/src/renderer/src/components/editor/save/queue/editor-save-rebaseline.ts index 25e6c61db0b..91df332154c 100644 --- a/src/renderer/src/components/editor/save/queue/editor-save-rebaseline.ts +++ b/src/renderer/src/components/editor/save/queue/editor-save-rebaseline.ts @@ -5,8 +5,8 @@ import { writeEditorBuffer } from '@/store/slices/editor/buffers/editor-buffer-r import { editorBufferIdOfView } from '@/store/slices/editor/buffers/editor-buffer-views' import type { AppState } from '@/store/types' import type { OpenFile } from '@/store/slices/editor/types/open-file' -import { getWrittenContentDiskSignature } from '../../../../../../shared/disk-baseline-signature' -import type { FileWriteDiskConflict } from '../../../../../../shared/file-write-disk-precondition' +import { getWrittenContentDiskSignature } from '../../../../../../shared/file-write/disk-baseline-signature' +import type { FileWriteDiskConflict } from '../../../../../../shared/file-write/file-write-disk-precondition' import { notifyEditorFileCacheStale } from '../../autosave/editor-autosave' import { hasPendingEditorBufferChange } from '../flush/editor-pending-flush' import { trackExternalChangeConflictAction } from '../../external-changes/editor-external-change-telemetry' diff --git a/src/renderer/src/components/editor/save/queue/editor-save-shared-model-dirty.test.ts b/src/renderer/src/components/editor/save/queue/editor-save-shared-model-dirty.test.ts index 10ab987d6e9..e2ade6884f9 100644 --- a/src/renderer/src/components/editor/save/queue/editor-save-shared-model-dirty.test.ts +++ b/src/renderer/src/components/editor/save/queue/editor-save-shared-model-dirty.test.ts @@ -1,20 +1,14 @@ // Dirty records must retain every view’s edits and conflict state without per-view reloads. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - ORCA_EDITOR_EXTERNAL_FILE_CHANGE_EVENT, - ORCA_EDITOR_FILE_CACHE_STALE_EVENT, - requestEditorFileSave -} from '../../autosave/editor-autosave' +import { ORCA_EDITOR_FILE_CACHE_STALE_EVENT } from '../../autosave/editor-autosave' import { attachEditorAutosaveController } from '../../autosave/editor-autosave-controller' -import { attachRestoredTabConflictScan } from '../../external-changes/editor-restored-tab-conflict-scan' + import { __clearSelfWriteRegistryForTests } from '../../external-changes/editor-self-write-registry' import { createEditorStore } from '../../autosave/editor-autosave-controller-test-fixture' -import { getDiskBaselineSignature } from '../../../../../../shared/disk-baseline-signature' +import { getDiskBaselineSignature } from '../../../../../../shared/file-write/disk-baseline-signature' import { GUARDED_PATH, stubGuardedDisk } from './editor-save-guarded-disk-fixture' import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' import { overwriteDiskWithTabEdits } from '../../external-changes/ExternalFileChangeBanner' -import { isStaleCachedEditorText } from '../../model-lifetime/buffer-text/editor-stale-mount-guard' -import { stampCleanTabDiskBaseline } from '../../external-changes/editor-clean-tab-disk-baseline' const mocks = vi.hoisted(() => ({ readRuntimeFileContent: vi.fn() })) const storeRef = vi.hoisted((): { current: ReturnType | null } => ({ @@ -86,60 +80,6 @@ describe('a dirty record shown in several workspaces', () => { __clearSelfWriteRegistryForTests() }) - it('gets the banner on an external change, not a lone reload, and no reads loop', async () => { - const { store, a, b, tab } = openSharedTabsWithDirtySibling() - const cleanup = attachEditorAutosaveController(store) - try { - window.dispatchEvent( - new CustomEvent(ORCA_EDITOR_EXTERNAL_FILE_CHANGE_EVENT, { - detail: { worktreeId: 'wt-1', worktreePath: '/repo', relativePath: 'file.ts' } - }) - ) - await vi.advanceTimersByTimeAsync(5_000) - - expect(tab(a.id)?.externalMutation).toBe('changed') - expect(tab(b.id)?.externalMutation).toBe('changed') - // The baseline stays on the version the unsaved text came from; nothing reloads or evicts. - expect(tab(a.id)?.lastKnownDiskSignature).toBe(getDiskBaselineSignature('S0')) - expect(store.getState().editorDrafts[b.id]).toBe('unsaved in B') - expect(mocks.readRuntimeFileContent).not.toHaveBeenCalled() - expect(dropped).toEqual([]) - } finally { - cleanup() - } - }) - - it('after a restart, a file changed while closed banners every tab of the model', async () => { - const { store, a, b, tab } = openSharedTabsWithDirtySibling() - mocks.readRuntimeFileContent.mockResolvedValue({ content: 'E', isBinary: false }) - - const detach = attachRestoredTabConflictScan(store) - try { - await vi.advanceTimersByTimeAsync(5_000) - - expect(tab(b.id)?.externalMutation).toBe('changed') - expect(tab(a.id)?.externalMutation).toBe('changed') - expect(mocks.readRuntimeFileContent).toHaveBeenCalledTimes(1) - expect(dropped).toEqual([]) - } finally { - detach() - } - }) - - it("drops a clean tab's leftover draft when the model moves to a newer load, so it cannot overwrite", async () => { - const { store, a, b, tab } = openSharedTabsWithDirtySibling() - // B undid back to clean but kept a draft equal to the old text; the tab is hidden. - store.getState().markFileDirty(b.id, false) - store.getState().setEditorDraft(b.id, 'S0') - // An agent wrote E; the other workspace's tab loads it while the model is clean. - stampCleanTabDiskBaseline(a.id, { content: 'E', isBinary: false }) - - expect(store.getState().editorDrafts[b.id]).toBeUndefined() - expect(tab(b.id)?.lastKnownDiskSignature).toBe(getDiskBaselineSignature('E')) - expect(dropped).toEqual([b.id]) - expect(isStaleCachedEditorText(b.id, 'S0')).toBe(true) - }) - it("Overwrite from either view writes the record's one draft", async () => { const { store, a } = openSharedTabsWithDirtySibling() const disk = stubGuardedDisk({ [GUARDED_PATH]: 'E' }) @@ -154,55 +94,4 @@ describe('a dirty record shown in several workspaces', () => { cleanup() } }) - - const openThirdView = (store: ReturnType) => { - store.setState({ - worktreesByRepo: { - 'repo-1': [ - ...(store.getState().worktreesByRepo['repo-1'] ?? []), - makeWorktree({ id: 'wt-3', repoId: 'repo-1', path: '/repo', hostId: 'local' }) - ] - } - }) - store.getState().openFile({ - filePath: GUARDED_PATH, - relativePath: 'file.ts', - worktreeId: 'wt-3', - language: 'typescript', - mode: 'edit' - }) - return store.getState().openFiles.find((tab) => tab.worktreeId === 'wt-3')! - } - - it('a view opened later joins the dirty record: its draft, dirty flag and baseline', async () => { - const { store, b } = openSharedTabsWithDirtySibling() - const disk = stubGuardedDisk({ [GUARDED_PATH]: 'S0' }) - const joined = openThirdView(store) - expect(joined.isDirty).toBe(true) - expect(joined.lastKnownDiskSignature).toBe(getDiskBaselineSignature('S0')) - expect(store.getState().editorDrafts[joined.id]).toBe('unsaved in B') - stampCleanTabDiskBaseline(joined.id, { content: 'S0', isBinary: false }) - expect(store.getState().openFiles.every((tab) => tab.externalMutation === undefined)).toBe(true) - - store.getState().setEditorDraft(joined.id, 'from the new tab') - const cleanup = attachEditorAutosaveController(store) - try { - await requestEditorFileSave({ fileId: joined.id }) - expect(disk.files.get(GUARDED_PATH)).toBe('from the new tab') - expect(store.getState().editorDrafts[b.id]).toBeUndefined() - expect(store.getState().openFiles.every((tab) => !tab.isDirty)).toBe(true) - } finally { - cleanup() - } - }) - - it('a view joining a dirty record whose disk moved marks the record changed', () => { - const { store, a, b, tab } = openSharedTabsWithDirtySibling() - const joined = openThirdView(store) - stampCleanTabDiskBaseline(joined.id, { content: 'E', isBinary: false }) - for (const id of [a.id, b.id, joined.id]) { - expect(tab(id)?.lastKnownDiskSignature).toBe(getDiskBaselineSignature('S0')) - expect(tab(id)?.externalMutation).toBe('changed') - } - }) }) diff --git a/src/renderer/src/components/editor/save/queue/editor-save-shared-model.test.ts b/src/renderer/src/components/editor/save/queue/editor-save-shared-model.test.ts index f2420c3d7d3..58b32cf7296 100644 --- a/src/renderer/src/components/editor/save/queue/editor-save-shared-model.test.ts +++ b/src/renderer/src/components/editor/save/queue/editor-save-shared-model.test.ts @@ -4,7 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { __clearSelfWriteRegistryForTests } from '../../external-changes/editor-self-write-registry' import { createEditorStore } from '../../autosave/editor-autosave-controller-test-fixture' import { reloadTabContentFromDisk } from '../../external-changes/ExternalFileChangeBanner' -import { getDiskBaselineSignature } from '../../../../../../shared/disk-baseline-signature' +import { getDiskBaselineSignature } from '../../../../../../shared/file-write/disk-baseline-signature' import { GUARDED_PATH } from './editor-save-guarded-disk-fixture' import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' @@ -117,30 +117,4 @@ describe('two tabs sharing one model', () => { expect(store.getState().editorDrafts[b.id]).toBe('mine') }) - - it.each([ - ['in the other workspace', false], - ['in the other workspace while it shows the Changes view', true] - ])('Undo of Reload yields to typing since %s, on every view', (_name, changesView) => { - const { store, a, b, edit, tab } = openSharedTabs('A') - edit(a.id, 'mine') - const toastMock = vi.mocked(toast) - toastMock.mockClear() - reloadTabContentFromDisk(store.getState().openFiles[0], vi.fn()) - if (changesView) { - // Changes uses the same record, so switching views must not change sharing. - store.getState().setEditorViewMode(b.id, 'changes') - } - edit(b.id, 'typed after reload') - - const undo: unknown = toastMock.mock.calls[0]?.[1]?.action - expect(isClickAction(undo)).toBe(true) - if (isClickAction(undo)) { - undo.onClick() - } - - expect(store.getState().editorDrafts[a.id]).toBe('typed after reload') - expect(store.getState().editorDrafts[b.id]).toBe('typed after reload') - expect(tab(b.id)?.externalMutation).toBeUndefined() - }) }) diff --git a/src/renderer/src/components/editor/save/queue/editor-save-slots.ts b/src/renderer/src/components/editor/save/queue/editor-save-slots.ts index abf6945d9ab..71dbc2f19ae 100644 --- a/src/renderer/src/components/editor/save/queue/editor-save-slots.ts +++ b/src/renderer/src/components/editor/save/queue/editor-save-slots.ts @@ -1,5 +1,5 @@ import type { acquireEditorFileOperation } from '@/lib/editor-file-operation-owner' -import type { LocalFileAccess } from '../../../../../../shared/local-file-access' +import type { LocalFileAccess } from '../../../../../../shared/file-access/local-file-access' import type { EditorSaveResult, EditorSaveTrigger } from './editor-save-disk-precondition' export type EditorSaveAcquisition = diff --git a/src/renderer/src/components/editor/use-custom-editor-outside-merge.test.tsx b/src/renderer/src/components/editor/use-custom-editor-outside-merge.test.tsx deleted file mode 100644 index a345a25c8bd..00000000000 --- a/src/renderer/src/components/editor/use-custom-editor-outside-merge.test.tsx +++ /dev/null @@ -1,88 +0,0 @@ -// @vitest-environment happy-dom - -import { afterEach, describe, expect, it, vi } from 'vitest' -import { useAppStore } from '@/store' -import type { OpenFile } from '@/store/slices/editor/types/open-file' -import { getDiskBaselineSignature } from '../../../../shared/disk-baseline-signature' - -vi.mock('./external-changes/ExternalFileChangeBanner', () => ({ - ExternalFileChangeBanner: () =>
banner
-})) -vi.mock('@/lib/connection-context', () => ({ getConnectionIdForFile: () => null })) - -import { - countCustomEditorMergingView, - mergeOutsideChangeIntoEditor, - recordCustomEditorAncestor, - useCustomEditorOutsideMergeStore -} from './use-custom-editor-outside-merge' - -Reflect.set(globalThis, 'IS_REACT_ACT_ENVIRONMENT', true) - -const initialState = useAppStore.getState() -const FILE_ID = '/repo/board.sketch' - -function openTab(baseline: string): void { - useAppStore.getState().openFile({ - filePath: FILE_ID, - relativePath: 'board.sketch', - worktreeId: 'wt-1', - language: 'plaintext', - mode: 'edit' - }) - useAppStore.getState().markFileDirty(FILE_ID, true) - useAppStore.getState().setLastKnownDiskSignature(FILE_ID, getDiskBaselineSignature(baseline)) - useAppStore.getState().setExternalMutation(FILE_ID, 'changed') -} - -const tab = (): OpenFile | undefined => - useAppStore.getState().openFiles.find((file) => file.id === FILE_ID) - -/** One merging view of a local tab whose edits started from `a`. */ -function ready(): void { - openTab('a') - recordCustomEditorAncestor(FILE_ID, 'a') - countCustomEditorMergingView(FILE_ID, 1) -} - -const afterSaved: (() => void)[] = [] - -afterEach(() => { - afterSaved.splice(0).forEach((stop) => stop()) - useAppStore.setState(initialState, true) - useCustomEditorOutsideMergeStore.setState({ views: {}, busy: {}, ancestors: {} }) -}) - -describe('custom editor outside merge', () => { - it('stamps exactly the disk snapshot the acknowledged merge used, and advances the ancestor', async () => { - ready() - // The tab's saved text moves to the disk text the merge used, as the panel hears after a save. - const saved: unknown[] = [] - const onSaved = (event: Event): void => { - saved.push(event instanceof CustomEvent ? event.detail : null) - } - window.addEventListener('orca:editor-file-saved', onSaved) - afterSaved.push(() => window.removeEventListener('orca:editor-file-saved', onSaved)) - const host = { mergeOutsideChange: vi.fn().mockResolvedValue('a+mine+agent') } - await expect(mergeOutsideChangeIntoEditor(FILE_ID, host, async () => 'a+agent')).resolves.toBe( - true - ) - expect(host.mergeOutsideChange).toHaveBeenCalledWith('a+agent', 'a') - expect(tab()?.externalMutation).toBeUndefined() - expect(tab()?.lastKnownDiskSignature).toBe(getDiskBaselineSignature('a+agent')) - expect(useCustomEditorOutsideMergeStore.getState().ancestors[FILE_ID]?.text).toBe('a+agent') - expect(saved).toEqual([{ fileId: FILE_ID, content: 'a+agent', recordViewIds: [FILE_ID] }]) - }) - - it('puts the conflict back for a write that landed while the merge ran', async () => { - ready() - const reads = ['a+agent', 'a+agent+second'] - const host = { mergeOutsideChange: vi.fn().mockResolvedValue('merged') } - await mergeOutsideChangeIntoEditor(FILE_ID, host, async () => reads.shift() ?? null) - // Only the first write is stamped; the second waits for its own merge. - expect(tab()).toMatchObject({ - externalMutation: 'changed', - lastKnownDiskSignature: getDiskBaselineSignature('a+agent') - }) - }) -}) diff --git a/src/renderer/src/components/editor/use-custom-editor-outside-merge.ts b/src/renderer/src/components/editor/use-custom-editor-outside-merge.ts index 51cd759221c..001f3ad3053 100644 --- a/src/renderer/src/components/editor/use-custom-editor-outside-merge.ts +++ b/src/renderer/src/components/editor/use-custom-editor-outside-merge.ts @@ -6,7 +6,7 @@ import { getRuntimeTargetForFileOwner } from '@/lib/file-owner-runtime-target' import { readRuntimeFileContent } from '@/runtime/files/reads/runtime-file-read-client' import { useAppStore } from '@/store' import type { OpenFile } from '@/store/slices/editor/types/open-file' -import { getDiskBaselineSignature } from '../../../../shared/disk-baseline-signature' +import { getDiskBaselineSignature } from '../../../../shared/file-write/disk-baseline-signature' import { editorModelSiblingTabs, setEditorDiskBaseline diff --git a/src/renderer/src/components/editor/use-monaco-editor-decorations.ts b/src/renderer/src/components/editor/use-monaco-editor-decorations.ts index c54d3bec2d1..d61b033ce05 100644 --- a/src/renderer/src/components/editor/use-monaco-editor-decorations.ts +++ b/src/renderer/src/components/editor/use-monaco-editor-decorations.ts @@ -1,6 +1,6 @@ import { useCallback, useEffect, useRef, type MutableRefObject } from 'react' import type { editor } from 'monaco-editor' -import type { MarkdownDocument } from '../../../../shared/filesystem-entry-types' +import type { MarkdownDocument } from '../../../../shared/file-listing/file-document' import { clearMarkdownDocCompletionDocuments, setMarkdownDocCompletionDocuments diff --git a/src/renderer/src/components/editor/use-monaco-editor-mount.stale-cache.test.tsx b/src/renderer/src/components/editor/use-monaco-editor-mount.stale-cache.test.tsx deleted file mode 100644 index df48dbfdf3d..00000000000 --- a/src/renderer/src/components/editor/use-monaco-editor-mount.stale-cache.test.tsx +++ /dev/null @@ -1,162 +0,0 @@ -// @vitest-environment happy-dom -import { cleanup, renderHook } from '@testing-library/react' -import { afterEach, expect, it, vi } from 'vitest' -import type { editor } from 'monaco-editor' -import type { OnMount } from '@monaco-editor/react' -import { getDiskBaselineSignature } from '../../../../shared/disk-baseline-signature' -import { ORCA_EDITOR_FILE_CACHE_STALE_EVENT } from './autosave/editor-autosave' -import type { MonacoEditorMountParams } from './monaco-editor-mount-params' -import { useMonacoEditorMount } from './use-monaco-editor-mount' - -const filePath = '/repo/file.ts' -const disk = vi.hoisted(() => ({ text: 'B' })) - -vi.mock('@/store', () => ({ - useAppStore: { - getState: () => ({ - pendingEditorReveal: null, - pendingEditorFocusRequest: null, - editorDrafts: {}, - // A sibling wrote 'B' and this tab's baseline moved with it, but its panel cache kept 'A'. - openFiles: [ - { - id: 'tab-b', - filePath: '/repo/file.ts', - mode: 'edit', - lastKnownDiskSignature: getDiskBaselineSignature(disk.text) - } - ] - }) - } -})) -vi.mock('./markdown-source-tools/monaco/monaco-markdown-doc-link-decorations', () => ({ - createMarkdownDocLinkDecorationController: vi.fn() -})) -vi.mock('./markdown-source-tools/monaco/monaco-markdown-doc-completions', () => ({ - ensureMarkdownDocCompletionProvider: vi.fn() -})) -vi.mock('./monaco-e2e-probe', () => ({ installMonacoE2EProbe: () => vi.fn() })) -vi.mock('./monaco-editor-input-bindings', () => ({ - installMonacoEditorInputBindings: () => ({ disposeInputBindings: vi.fn() }) -})) - -afterEach(() => { - cleanup() - disk.text = 'B' -}) - -function setupMount() { - const params: MonacoEditorMountParams = { - fileId: 'tab-b', - filePath, - viewStateKey: 'tab-b-view', - viewStateId: 'tab-b', - worktreeId: 'wt-2', - autoHeight: false, - autoHeightLineHeight: 20, - editorRef: { current: null }, - editorContainerRef: { current: null }, - languageRef: { current: 'typescript' }, - propsRef: { - current: { - relativePath: 'file.ts', - language: 'typescript', - onSave: vi.fn(), - onContentChange: vi.fn() - } - }, - readOnlyRef: { current: false }, - scrollThrottleTimerRef: { current: null }, - unregisterFileSearchSelectionRef: { current: null }, - setMountedEditor: vi.fn(), - setAutoHeightContentHeight: vi.fn(), - setEditorCursorLine: vi.fn(), - setupCopy: vi.fn(), - queueReveal: vi.fn(), - contentSync: { - contentRef: { current: 'A (stale cache)' }, - lastSyncedContentRef: { current: 'A (stale cache)' }, - contentSyncModeRef: { current: 'undoable' }, - isApplyingProgrammaticContentRef: { current: false } - }, - decorations: { - markdownDocLinkDecorationsRef: { current: null }, - conflictDecorationsRef: { current: null }, - updateMarkdownCompletionDocuments: vi.fn() - }, - annotations: { - commentPopoverRef: { current: null }, - shouldShowMarkdownAnnotationsRef: { current: false }, - setCommentPopover: vi.fn(), - setSelectionAnnotationTarget: vi.fn() - }, - gutterMenu: { - setGutterMenuOpen: vi.fn(), - setGutterMenuPoint: vi.fn(), - setGutterMenuLine: vi.fn(), - setGutterMenuSelection: vi.fn() - } - } - const modelText = { value: 'B' } - const model = { - uri: { toString: () => 'file:///repo/file.ts' }, - getValue: () => modelText.value, - getEOL: () => '\n', - pushEditOperations: vi.fn(), - getFullModelRange: vi.fn() - } - const updateOptions = vi.fn() - const executeEdits = vi.fn() - const mockEditor = { - getModel: () => model, - getPosition: () => ({ lineNumber: 1, column: 1 }), - focus: vi.fn(), - updateOptions, - executeEdits, - pushUndoStop: vi.fn(), - onDidChangeCursorPosition: () => ({ dispose: vi.fn() }), - onDidScrollChange: () => ({ dispose: vi.fn() }), - onMouseDown: () => ({ dispose: vi.fn() }), - onDidDispose: vi.fn() - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Mount uses only the editor methods mocked above; decorations/input/probe integrations are mocked. - const editorInstance = mockEditor as unknown as editor.IStandaloneCodeEditor - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The mocked mount integrations do not access Monaco. - const monaco = {} as Parameters[1] - return { params, modelText, model, updateOptions, executeEdits, editorInstance, monaco } -} - -it('reloads the same stale text again once the baseline moves or a fresh mount settles the reload', () => { - const { params, modelText, editorInstance, monaco } = setupMount() - const dropped: string[] = [] - const onStale = (event: Event): void => { - if (event instanceof CustomEvent) { - dropped.push(event.detail.fileId) - } - } - window.addEventListener(ORCA_EDITOR_FILE_CACHE_STALE_EVENT, onStale) - const view = renderHook(() => useMonacoEditorMount(params)) - const mountWith = (text: string): void => { - params.contentSync.contentRef.current = text - modelText.value = text - view.result.current(editorInstance, monaco) - } - try { - mountWith('A2 (stale cache)') - mountWith('A2 (stale cache)') - expect(dropped).toHaveLength(1) - - // Another write moved the baseline: the same stale text must reload again. - disk.text = 'C' - mountWith('A2 (stale cache)') - expect(dropped).toHaveLength(2) - - // The reload landed fresh text; stale text returning later reloads again. - mountWith('C') - expect(dropped).toHaveLength(2) - mountWith('A2 (stale cache)') - expect(dropped).toHaveLength(3) - } finally { - window.removeEventListener(ORCA_EDITOR_FILE_CACHE_STALE_EVENT, onStale) - } -}) diff --git a/src/renderer/src/components/editor/useEditorPanelFileLoadRetry.ts b/src/renderer/src/components/editor/useEditorPanelFileLoadRetry.ts index b81bba9d61b..ce156880bed 100644 --- a/src/renderer/src/components/editor/useEditorPanelFileLoadRetry.ts +++ b/src/renderer/src/components/editor/useEditorPanelFileLoadRetry.ts @@ -3,7 +3,7 @@ import type { OpenFile } from '@/store/slices/editor/types/open-file' import { useWorktreeHostConnection } from '@/lib/workspace/ownership/worktree-host-connection-phase' import { displayIpcErrorMessage } from '@/lib/ipc-error' import { hasRuntimeRpcErrorCode } from '../../../../shared/runtime-rpc-error-code' -import { isFileTooLargeMessage } from '../../../../shared/file-write-disk-precondition' +import { isFileTooLargeMessage } from '../../../../shared/file-write/file-write-disk-precondition' import { WORKTREE_HOST_SELECTOR_NOT_FOUND_CODE, WORKTREE_HOST_UNRESOLVED_CODE, diff --git a/src/renderer/src/components/editor/view-mode/markdown-preview-controls.ts b/src/renderer/src/components/editor/view-mode/markdown-preview-controls.ts index e8c67930f87..f17e3b2675a 100644 --- a/src/renderer/src/components/editor/view-mode/markdown-preview-controls.ts +++ b/src/renderer/src/components/editor/view-mode/markdown-preview-controls.ts @@ -3,7 +3,7 @@ import '../../../../../shared/keybindings' import { keybindingMatchesAction } from '../../../../../shared/keybindings/matching' import type { KeybindingOverrides } from '../../../../../shared/keybindings/types' import type { EditorToggleValue } from './EditorViewToggle' -import { isSvgFilePath } from '../../../../../shared/svg-document' +import { isSvgFilePath } from '../../../../../shared/file-preview/svg-document' import { normalizeMarkdownDefaultViewMode, type MarkdownDefaultViewMode diff --git a/src/renderer/src/components/native-chat/attachments/intake/native-chat-attachment-notices.ts b/src/renderer/src/components/native-chat/attachments/intake/native-chat-attachment-notices.ts index bba90a5e175..1b9e6767bae 100644 --- a/src/renderer/src/components/native-chat/attachments/intake/native-chat-attachment-notices.ts +++ b/src/renderer/src/components/native-chat/attachments/intake/native-chat-attachment-notices.ts @@ -1,5 +1,5 @@ import { translate } from '../../../../i18n/i18n' -import { NATIVE_FILE_DROP_MAX_PATHS } from '../../../../../../shared/native-file-drop' +import { NATIVE_FILE_DROP_MAX_PATHS } from '../../../../../../shared/file-import/native-file-drop' export function nativeChatWorktreeNotReadyNotice(): string { return translate( diff --git a/src/renderer/src/components/native-chat/attachments/intake/native-chat-composer-ime-file-drop.test.tsx b/src/renderer/src/components/native-chat/attachments/intake/native-chat-composer-ime-file-drop.test.tsx deleted file mode 100644 index 9a1e0066abf..00000000000 --- a/src/renderer/src/components/native-chat/attachments/intake/native-chat-composer-ime-file-drop.test.tsx +++ /dev/null @@ -1,381 +0,0 @@ -// @vitest-environment happy-dom - -import type * as AttachmentOwnerModule from '../uploads/native-chat-attachment-owner' -import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' -import { useRef, useState } from 'react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { ExecutionHostId } from '../../../../../../shared/execution-host' - -import type { PreparedDroppedPaths } from '../../../../../../shared/native-file-drop-preparation' -import type { NativeChatStructuredComposerTransport } from '../../composer/submit/native-chat-structured-composer-transport' -import { useNativeChatStructuredComposerSend } from '../../composer/submit/use-native-chat-structured-composer-send' -import type { NativeChatComposerInput } from '../../composer/editor/native-chat-composer-input' -import { NativeChatComposerField } from '../../composer/editor/NativeChatComposerField' -import { useNativeChatComposerAttachments } from '../chips/use-native-chat-composer-attachments' -import { useNativeChatComposerNotice } from '../../composer/controls/use-native-chat-composer-notice' -import { useNativeChatFileDrops } from './use-native-chat-file-drops' -import { NativeChatPaneFileDropSurface } from './NativeChatPaneFileDropSurface' -import { useNativeChatDraft } from '../../drafts/use-native-chat-draft' -import { clearNativeChatComposerDraftsForTests as clearNativeChatDraftCacheForTests } from '../../drafts/native-chat-draft-reset' -import { readNativeChatComposerDraft } from '../../drafts/native-chat-composer-draft-store' -import { - changePrompt, - promptEditor, - promptValue -} from '../../composer/editor/native-chat-prompt-editor.test-support' -import { useImeEnterGestureOwnership } from '@/lib/ime-composition-keyboard-event' -import type * as RemoteRuntimePtyIdModule from '../../../../../../shared/remote-runtime/remote-runtime-pty-id' - -const testState: { - executionHostId: ExecutionHostId - ownerKind: 'local' | 'not-ready' | 'remote' - targetIsRemoteRuntime: boolean - store: { tabsByWorktree: Record } -} = vi.hoisted(() => ({ - executionHostId: 'local', - ownerKind: 'local', - targetIsRemoteRuntime: false, - store: { - tabsByWorktree: { - 'worktree-1': [{ id: 'terminal-tab-1' }] - } - } -})) - -vi.mock('@/components/native-chat/telemetry/native-chat-telemetry', () => ({ - emitNativeChatMessageSent: vi.fn() -})) - -vi.mock('@/store', () => { - const useAppStore = (selector: (state: typeof testState.store) => unknown) => - selector(testState.store) - useAppStore.getState = () => testState.store - return { useAppStore } -}) -vi.mock('@/lib/workspace/ownership/worktree-runtime-owner', () => ({ - getExecutionHostIdForWorktree: () => testState.executionHostId -})) -// Retain production notices and exports so mocks cannot hide stale wording or new behavior. -vi.mock('../uploads/native-chat-attachment-owner', async (importOriginal) => ({ - ...(await importOriginal()), - resolveNativeChatAttachmentHost: () => testState.executionHostId, - resolveNativeChatAttachmentOwnerForWorktree: () => ({ kind: testState.ownerKind }) -})) -vi.mock('@/i18n/i18n', () => ({ - i18n: { language: 'en' }, - translate: (_key: string, fallback: string, values?: Record) => - fallback.replace(/\{\{(\w+)\}\}/g, (_match, name: string) => String(values?.[name])) -})) -vi.mock( - '../../../../../../shared/remote-runtime/remote-runtime-pty-id', - async (importOriginal) => ({ - ...(await importOriginal()), - isRemoteRuntimePtyId: () => testState.targetIsRemoteRuntime - }) -) -vi.mock('../../composer/controls/NativeChatComposerActions', () => ({ - NativeChatComposerActions: () =>
-})) -vi.mock('../../composer/pickers/NativeChatAutocompleteMenus', () => ({ - NativeChatMentionMenu: () => null, - NativeChatPickerMenu: () => null -})) -vi.mock('../chips/NativeChatImageAttachmentPreview', () => ({ - NativeChatImageAttachmentPreview: ({ - attachment - }: { - attachment: { connectionId?: string; path: string } - }) => ( - - {attachment.path} - - ) -})) - -type ProbeProps = { - disabled?: boolean - initialDraft?: string - structured?: boolean - /** Overrides only the structured target, leaving the pane's scope key alone. */ - structuredWorkspaceId?: string - workspaceId?: string - transport?: NativeChatStructuredComposerTransport -} - -const bubbledDrop = vi.fn() - -function ComposerProbe({ - disabled = false, - initialDraft = '', - structured = true, - structuredWorkspaceId, - workspaceId = 'worktree-1', - transport -}: ProbeProps): React.JSX.Element { - const [caret, setCaret] = useState(initialDraft.length) - const { notices, setNotice } = useNativeChatComposerNotice() - const inputRef = useRef(null) - const imeEnterGesture = useImeEnterGestureOwnership() - const { draft, setDraft, flushDraftAppends } = useNativeChatDraft( - `pane:${workspaceId}`, - imeEnterGesture.isComposing - ) - const attachments = useNativeChatComposerAttachments({ - attachmentScopeKey: `pane:${workspaceId}`, - allowWithoutTarget: structured, - imageReferences: structured, - caret, - disabled, - isComposing: imeEnterGesture.isComposing, - resolveTarget: () => - structured ? null : { ptyId: 'pty-1', settings: { activeRuntimeEnvironmentId: null } }, - textareaRef: inputRef, - setCaret, - setDraft, - setNotice - }) - const { pickAttachments } = useNativeChatFileDrops({ - paneKey: `pane:${workspaceId}`, - draftScopeKey: `pane:${workspaceId}`, - targetPtyId: 'pty-1', - terminalTabId: 'terminal-tab-1', - structuredWorktreeId: structured ? (structuredWorkspaceId ?? workspaceId) : undefined, - disabled, - attachResolvedPaths: attachments.attachResolvedPaths, - pendingChips: attachments.pendingChips, - setNotice - }) - - const send = useNativeChatStructuredComposerSend({ - agent: 'codex', - draftScopeKey: `pane:${workspaceId}`, - imageAttachments: attachments.imageAttachments, - structuredTransport: transport, - isComposing: imeEnterGesture.isComposing, - clearSkillOrigin: () => {}, - setDraft, - setCaret - }) - - return ( -
-
- { - setDraft(value) - setCaret(input.selectionStart ?? value.length) - }} - onTextareaSelect={(input) => setCaret(input.selectionStart ?? input.value.length)} - onKeyDown={(event) => { - if (event.key === 'Enter') { - event.preventDefault() - void send(draft) - } - }} - onImeSettled={(input) => { - setDraft(input.value) - flushDraftAppends() - attachments.flushPendingAttachments() - }} - onPaste={() => {}} - pickerListboxId="picker" - onChoosePickerItem={() => {}} - onRetrySkills={() => {}} - onChooseMentionFile={() => {}} - mentionFiles={{ files: [], loading: false, failed: false }} - onRemoveImageAttachment={attachments.removeImageAttachment} - onAttach={() => {}} - onDictationToggle={() => {}} - onDictationHoldStart={() => {}} - onDictationHoldEnd={() => {}} - onSend={() => void send(draft)} - sessionOptionsSurface={null} - sessionOptionsSnapshot={[]} - /> -
- - {draft} -
- ) -} - -const prepare = vi.fn(async ({ paths }: { paths: string[] }): Promise => ({ - paths, - failures: [] -})) -beforeEach(() => { - vi.clearAllMocks() - clearNativeChatDraftCacheForTests() - vi.stubGlobal('api', { - fs: { - getPathForFile: (file: File) => `/drop/${file.name}`, - prepareDroppedPaths: prepare, - stat: vi.fn(async () => ({ isDirectory: false })) - }, - shell: { pickAttachments: vi.fn(async () => ['/picked/browser issues.md']) } - }) -}) -afterEach(() => { - cleanup() - clearNativeChatDraftCacheForTests() - vi.unstubAllGlobals() -}) - -async function osDrop(target: HTMLElement, names = ['notes.txt']) { - const event = new Event('drop', { bubbles: true, cancelable: true, composed: true }) - Object.defineProperty(event, 'isTrusted', { value: true }) - Object.defineProperty(event, 'dataTransfer', { - value: { - types: ['Files'], - files: names.map((name) => new File(['file'], name)) - } - }) - await act(async () => target.dispatchEvent(event)) -} - -describe('OS file drops through the real composing chat field', () => { - it.each(['commit', 'double commit', 'cancel', 'blur', 'blur then commit', 'restart'])( - 'settles one drop exactly once on %s and never replays it in a later composition', - async (ending) => { - render( - - - - ) - const editor = screen.getByRole('textbox') - fireEvent.compositionStart(editor) - changePrompt(editor, 'ni') - await osDrop(editor) - expect(promptValue(editor)).toBe('ni') - if (ending === 'cancel') { - changePrompt(editor, '') - } - if (ending === 'blur' || ending === 'blur then commit') { - fireEvent.blur(editor) - } - if (ending === 'restart') { - fireEvent.compositionStart(editor) - } else if (ending !== 'blur') { - fireEvent.compositionEnd(editor, { data: ending === 'cancel' ? '' : 'ni' }) - } - if (ending === 'double commit') { - fireEvent.compositionEnd(editor, { data: 'ni' }) - } - expect(promptValue(editor).match(/@\/drop\/notes.txt/g)).toHaveLength(1) - expect(prepare).toHaveBeenCalledOnce() - fireEvent.compositionStart(editor) - fireEvent.compositionEnd(editor, { data: 'later' }) - expect(promptValue(editor).match(/@\/drop\/notes.txt/g)).toHaveLength(1) - } - ) - - it('preserves a mixed drop and subsequent question through accepted send', async () => { - const send = vi.fn(() => true) - const transport: NativeChatStructuredComposerTransport = { - capturePresentation: () => () => true, - send, - dispatchCommand: vi.fn(async () => ({ handled: false, accepted: false, error: null })), - optionsSurface: { - getSnapshot: () => [], - setOption: vi.fn(), - invokeAction: vi.fn(), - subscribe: () => () => {} - }, - optionSnapshot: [], - onError: vi.fn(), - runtime: 'local', - sessionId: 'mixed-drop-session', - runtimeEnvironmentId: null - } - prepare.mockImplementationOnce(async ({ paths }) => { - return { - paths: paths.filter((path) => !path.endsWith('/missing.png')), - failures: [ - { - target: 'rejected', - reason: 'temp-copy-failed', - commonReason: 'missing', - pathCount: 2, - byteLength: 0 - } - ] - } - }) - render( - - - - ) - const editor = screen.getByRole('textbox') - const names = ['notes.txt', 'b.png', 'a.png', 'b.png', 'missing.png', 'missing.png'] - await osDrop(editor, names) - expect(prepare.mock.calls[0]?.[0].paths).toEqual(names.map((name) => `/drop/${name}`)) - const assertDraftMatchesDocument = () => { - const saved = readNativeChatComposerDraft('pane:worktree-1') - expect(saved.text).toBe(promptValue(editor)) - expect(saved.document).toEqual(promptEditor(editor).getJSON()) - expect(screen.getByTestId('draft').textContent).toBe(saved.text) - expect( - [...editor.querySelectorAll('[data-native-chat-file-reference]')].map( - (pill) => pill.textContent - ) - ).toEqual(['notes.txt']) - expect( - [...editor.querySelectorAll('[data-native-chat-image-reference]')].map( - (pill) => pill.textContent - ) - ).toEqual(['Image #1', 'Image #2', 'Image #3']) - } - assertDraftMatchesDocument() - // Browser-native End movement is exercised in Electron; here selection uses real editor commands. - act(() => { - promptEditor(editor).commands.selectTextblockEnd() - }) - act(() => { - promptEditor(editor).commands.setTextSelection( - promptEditor(editor).state.doc.content.size - 1 - ) - }) - const question = ' What does notes.txt say, and what is shown in the three images?' - for (const character of question) { - act(() => { - promptEditor(editor).commands.insertContent(character) - }) - } - expect(editor.textContent).toContain(question) - assertDraftMatchesDocument() - const submitted = readNativeChatComposerDraft('pane:worktree-1') - expect(submitted.text).toContain('@/drop/notes.txt') - expect(submitted.text).toContain(question) - await act(async () => fireEvent.keyDown(editor, { key: 'Enter' })) - expect(send).toHaveBeenCalledOnce() - expect(send).toHaveBeenCalledWith( - expect.stringContaining('@/drop/notes.txt'), - expect.arrayContaining([expect.objectContaining({ path: '/drop/b.png' })]) - ) - const [text, images] = send.mock.calls[0] ?? [] - expect(text).toContain(question) - expect(text?.match(/\[Image #\d+\]/g)).toEqual(['[Image #1]', '[Image #2]', '[Image #3]']) - expect(images?.map(({ path }) => path)).toEqual(['/drop/b.png', '/drop/a.png', '/drop/b.png']) - expect(promptValue(editor)).toBe('') - expect(readNativeChatComposerDraft('pane:worktree-1').text).toBe('') - expect(readNativeChatComposerDraft('pane:worktree-1').images).toEqual([]) - }) -}) diff --git a/src/renderer/src/components/native-chat/attachments/intake/native-chat-pane-file-drop.ts b/src/renderer/src/components/native-chat/attachments/intake/native-chat-pane-file-drop.ts index bdab580880b..feacf636506 100644 --- a/src/renderer/src/components/native-chat/attachments/intake/native-chat-pane-file-drop.ts +++ b/src/renderer/src/components/native-chat/attachments/intake/native-chat-pane-file-drop.ts @@ -1,9 +1,9 @@ import { hasWorkspaceFileDragType } from '@/lib/workspace-file-drag' -import { hasNativeFileDragTypes } from '../../../../../../shared/native-file-drop' +import { hasNativeFileDragTypes } from '../../../../../../shared/file-import/native-file-drop' import { type DroppedPathConsumer, OS_FILE_DROP_OWNER_ATTRIBUTE -} from '../../../../../../shared/native-file-drop-preparation' +} from '../../../../../../shared/file-import/native-file-drop-preparation' import type { NativeChatResolvedPathSink } from './use-native-chat-workspace-file-drop' /** Workspace files use composer handlers; OS files use the pane’s native file owner. */ diff --git a/src/renderer/src/components/native-chat/attachments/intake/use-native-chat-external-attachments.ts b/src/renderer/src/components/native-chat/attachments/intake/use-native-chat-external-attachments.ts index 9b54a6cc206..68c352cd8eb 100644 --- a/src/renderer/src/components/native-chat/attachments/intake/use-native-chat-external-attachments.ts +++ b/src/renderer/src/components/native-chat/attachments/intake/use-native-chat-external-attachments.ts @@ -1,7 +1,7 @@ import { captureNativeChatEditDraftDestination } from '../../drafts/native-chat-composer-draft-memory' import { useCallback, useLayoutEffect, useRef } from 'react' import { useAppStore } from '@/store' -import { NATIVE_FILE_DROP_MAX_PATHS } from '../../../../../../shared/native-file-drop' +import { NATIVE_FILE_DROP_MAX_PATHS } from '../../../../../../shared/file-import/native-file-drop' import { isSameComposerWorkspace, nativeChatAttachmentOwnerUnchanged, diff --git a/src/renderer/src/components/native-chat/attachments/intake/use-native-chat-resolved-path-attachments.ts b/src/renderer/src/components/native-chat/attachments/intake/use-native-chat-resolved-path-attachments.ts index a82ce196b38..d6aa89fb617 100644 --- a/src/renderer/src/components/native-chat/attachments/intake/use-native-chat-resolved-path-attachments.ts +++ b/src/renderer/src/components/native-chat/attachments/intake/use-native-chat-resolved-path-attachments.ts @@ -1,6 +1,6 @@ import { useCallback, useEffect, useLayoutEffect, useRef, type RefObject } from 'react' import { translate } from '@/i18n/i18n' -import { NATIVE_FILE_DROP_MAX_PATHS } from '../../../../../../shared/native-file-drop' +import { NATIVE_FILE_DROP_MAX_PATHS } from '../../../../../../shared/file-import/native-file-drop' import { formatNativeChatFileReference } from '../../../../../../shared/agent-image-paste' import type { NativeChatComposerInput } from '../../composer/editor/native-chat-composer-input' import { isImageDropPath } from '../../../../../../shared/image-path-paste' diff --git a/src/renderer/src/components/native-chat/media/images/use-native-chat-media-href.ts b/src/renderer/src/components/native-chat/media/images/use-native-chat-media-href.ts index 823cf87a35a..4c81c5a9438 100644 --- a/src/renderer/src/components/native-chat/media/images/use-native-chat-media-href.ts +++ b/src/renderer/src/components/native-chat/media/images/use-native-chat-media-href.ts @@ -1,5 +1,5 @@ import { useEffect, useState } from 'react' -import type { RuntimeTerminalPathResolution } from '../../../../../../shared/runtime-file-contracts' +import type { RuntimeTerminalPathResolution } from '../../../../../../shared/terminal/runtime-terminal-file-path' import { createNativeChatFileHref, routeNativeChatHref diff --git a/src/renderer/src/components/native-chat/media/text/AttachmentTextScrollView.tsx b/src/renderer/src/components/native-chat/media/text/AttachmentTextScrollView.tsx index 24a1eab6bd9..32119f3b6b3 100644 --- a/src/renderer/src/components/native-chat/media/text/AttachmentTextScrollView.tsx +++ b/src/renderer/src/components/native-chat/media/text/AttachmentTextScrollView.tsx @@ -1,9 +1,9 @@ import { useEffect, useEffectEvent, useLayoutEffect, useRef, useState } from 'react' -import { AttachmentTextViewport } from '../../../../../../shared/attachment-text-viewport' +import { AttachmentTextViewport } from '../../../../../../shared/attachment-text/attachment-text-viewport' import type { AttachmentTextSource, AttachmentTextWindow -} from '../../../../../../shared/attachment-text-source' +} from '../../../../../../shared/attachment-text/attachment-text-source' export function AttachmentTextScrollView(props: { source: AttachmentTextSource diff --git a/src/renderer/src/components/native-chat/media/text/NativeChatTextAttachmentPreview.tsx b/src/renderer/src/components/native-chat/media/text/NativeChatTextAttachmentPreview.tsx index f7ccd97d50f..02631f7a08d 100644 --- a/src/renderer/src/components/native-chat/media/text/NativeChatTextAttachmentPreview.tsx +++ b/src/renderer/src/components/native-chat/media/text/NativeChatTextAttachmentPreview.tsx @@ -12,8 +12,8 @@ import { isWebClientLocation } from '@/lib/web-client-location' import { useIntlLocale, useTranslate } from '@/i18n/use-translate' import { useUiLanguageRevision } from '@/i18n/use-ui-language-revision' import type { RuntimeClientTarget } from '../../../../../../shared/runtime-client-target' -import { createAttachmentTextPreviewHook } from '../../../../../../shared/use-attachment-text-preview' -import { ATTACHMENT_TEXT_COPY_MAX_BYTES } from '../../../../../../shared/attachment-text-source' +import { createAttachmentTextPreviewHook } from '../../../../../../shared/attachment-text/use-attachment-text-preview' +import { ATTACHMENT_TEXT_COPY_MAX_BYTES } from '../../../../../../shared/attachment-text/attachment-text-source' import { AttachmentTextScrollView } from './AttachmentTextScrollView' import { formatAttachmentPreviewError } from './native-chat-text-attachment-error' import { createChatAttachmentReader } from './native-chat-text-attachment-read' diff --git a/src/renderer/src/components/native-chat/media/text/native-chat-text-attachment-admission.test.ts b/src/renderer/src/components/native-chat/media/text/native-chat-text-attachment-admission.test.ts deleted file mode 100644 index c8b7179de83..00000000000 --- a/src/renderer/src/components/native-chat/media/text/native-chat-text-attachment-admission.test.ts +++ /dev/null @@ -1,163 +0,0 @@ -import { afterEach, expect, it, vi } from 'vitest' -import { - generateKeyPair, - deriveSharedKey, - decrypt, - encrypt, - publicKeyToBase64 -} from '../../../../../../shared/remote-runtime/e2ee/node/e2ee-crypto' -import { AttachmentTextSource } from '../../../../../../shared/attachment-text-source' -import { - installBrowserGlobals, - writeStoredRuntimeEnvironment -} from '../../../../web/web-preload-api-test-harness' - -const store = vi.hoisted(() => ({ runtimeEnvironments: [{ id: 'attachment35636' }] })) -vi.mock('@/store', () => ({ useAppStore: { getState: () => store } })) -const path = '/host/agent-session-attachments/12345678-1234-1234-1234-123456789abc/x.txt' -const bytes = Buffer.from('\ufeffcomplete\r\n🙂') -const host = { - runtimeId: 'runtime35636', - protocolVersion: 3, - minCompatibleMobileVersion: 2, - capabilities: ['native-chat.text-attachment-read.v1'] -} -type Frame = { id: string; method: string; params?: { offset: number; length: number } } - -async function fixture() { - vi.resetModules() - const keys = generateKeyPair() - const frames: { socket: Socket; frame: Frame }[] = [] - const sockets: Socket[] = [] - let answer: (socket: Socket, frame: Frame) => void = (socket, frame) => socket.reply(frame) - class Socket { - static CONNECTING = 0 - static OPEN = 1 - readyState = 0 - binaryType = 'arraybuffer' - onopen: (() => void) | null = null - onmessage: ((event: { data: string }) => void) | null = null - onclose: (() => void) | null = null - onerror: (() => void) | null = null - key?: Uint8Array - runtimeId = host.runtimeId - constructor(_url: string) { - sockets.push(this) - queueMicrotask(() => { - if (this.readyState === 0) { - this.readyState = 1 - this.onopen?.() - } - }) - } - send(raw: string) { - if (!this.key) { - const hello = JSON.parse(raw) - this.key = deriveSharedKey(keys.secretKey, Buffer.from(hello.publicKeyB64, 'base64')) - queueMicrotask(() => this.onmessage?.({ data: JSON.stringify({ type: 'e2ee_ready' }) })) - return - } - const frame = JSON.parse(decrypt(raw, this.key)!) - if (frame.type === 'e2ee_auth') { - queueMicrotask(() => this.deliver({ type: 'e2ee_authenticated' })) - } else { - frames.push({ socket: this, frame }) - answer(this, frame) - } - } - deliver(value: unknown) { - if (this.readyState === 1) { - this.onmessage?.({ data: encrypt(JSON.stringify(value), this.key!) }) - } - } - reply(frame: Frame) { - const part = bytes.subarray( - frame.params?.offset ?? 0, - (frame.params?.offset ?? 0) + (frame.params?.length ?? 0) - ) - queueMicrotask(() => - this.deliver({ - id: frame.id, - ok: true, - result: - frame.method === 'status.get' - ? { ...host, runtimeId: this.runtimeId } - : { - snapshot: 'a'.repeat(64), - size: bytes.length, - bytesRead: part.length, - eof: frame.params!.offset + part.length === bytes.length, - contentBase64: part.toString('base64') - }, - _meta: { runtimeId: this.runtimeId } - }) - ) - } - close() { - this.readyState = 3 - } - } - const globals = installBrowserGlobals() - Object.assign(globals.window, { setTimeout, clearTimeout, setInterval, clearInterval }) - vi.stubGlobal('WebSocket', Socket) - writeStoredRuntimeEnvironment(globals.storage, 'attachment35636') - const stored = JSON.parse(globals.storage.getItem('orca.web.runtimeEnvironment.v1')!) - stored.endpoints[0].publicKeyB64 = publicKeyToBase64(keys.publicKey) - globals.storage.setItem('orca.web.runtimeEnvironment.v1', JSON.stringify(stored)) - const { createRuntimeEnvironmentsApi } = - await import('../../../../web/preload-api/web-runtime-environments-api') - const api = createRuntimeEnvironmentsApi() - Object.assign(globals.window, { api: { runtimeEnvironments: api } }) - const session = await import('../../../../web/preload-api/web-runtime-session') - const { createChatAttachmentReader } = await import('./native-chat-text-attachment-read') - const reader = createChatAttachmentReader({ - kind: 'environment', - environmentId: 'attachment35636' - }) - cleanup = () => { - session.closeActiveRuntimeClients() - vi.unstubAllGlobals() - vi.restoreAllMocks() - vi.useRealTimers() - } - return { - reader, - frames, - sockets, - answer: (fn: typeof answer) => { - answer = fn - } - } -} -let cleanup = () => {} -afterEach(() => cleanup()) - -it('cancels a pending real web capability read and completes a same-reader successor', async () => { - const f = await fixture() - const entered = Promise.withResolvers() - let held: { socket: (typeof f.sockets)[number]; frame: Frame } | undefined - f.answer((socket, frame) => { - if (!held && frame.method === 'status.get' && socket !== f.sockets[0]) { - held = { socket, frame } - entered.resolve() - } else { - socket.reply(frame) - } - }) - const old = new AttachmentTextSource(path, f.reader) - const result = old.copyText().catch((error) => error) - await entered.promise - old.dispose() - expect((await result).name).toBe('AbortError') - expect( - f.frames.some(({ frame }) => frame.method === 'agentSessionAttachment.readTextChunk') - ).toBe(false) - const successor = new AttachmentTextSource(path, f.reader) - const copied = successor.copyText() - held!.socket.reply(held!.frame) - expect(await copied).toBe(bytes.toString('utf8')) - expect( - f.frames.filter(({ frame }) => frame.method === 'agentSessionAttachment.readTextChunk') - ).toHaveLength(2) - successor.dispose() -}) diff --git a/src/renderer/src/components/native-chat/media/text/native-chat-text-attachment-read.ts b/src/renderer/src/components/native-chat/media/text/native-chat-text-attachment-read.ts index df2f4b42e02..d29e6be61a5 100644 --- a/src/renderer/src/components/native-chat/media/text/native-chat-text-attachment-read.ts +++ b/src/renderer/src/components/native-chat/media/text/native-chat-text-attachment-read.ts @@ -8,7 +8,7 @@ import { } from '@/runtime/rpc/environment-revisions/runtime-environment-revision' import type { RuntimeClientTarget } from '../../../../../../shared/runtime-client-target' import type { RuntimeStatus } from '../../../../../../shared/runtime-session-contracts' -import type { AttachmentTextRead } from '../../../../../../shared/attachment-text-source' +import type { AttachmentTextRead } from '../../../../../../shared/attachment-text/attachment-text-source' import { AGENT_SESSION_TEXT_ATTACHMENT_READ_CAPABILITY } from '../../../../../../shared/agent-session/agent-session-runtime-capabilities' export function createChatAttachmentReader( diff --git a/src/renderer/src/components/native-chat/media/visuals/NativeChatInlineVisual.tsx b/src/renderer/src/components/native-chat/media/visuals/NativeChatInlineVisual.tsx index c844dd9cceb..1e733282a7d 100644 --- a/src/renderer/src/components/native-chat/media/visuals/NativeChatInlineVisual.tsx +++ b/src/renderer/src/components/native-chat/media/visuals/NativeChatInlineVisual.tsx @@ -4,7 +4,7 @@ import { beginLinkOpenRequest } from '@/lib/link-open-request' import { useContext, useEffect, useRef, useState } from 'react' import { SquareArrowOutUpRight } from 'lucide-react' import { toast } from 'sonner' -import type { ArtifactWriteRequest } from '../../../../../../shared/artifacts' +import type { ArtifactWriteRequest } from '../../../../../../shared/artifacts/artifacts' import { ArtifactPublishButton } from '@/components/artifacts/ArtifactPublishButton' import { ArtifactPublishPreparationError } from '@/components/artifacts/artifact-publish-flow' import { Button } from '@/components/ui/button' diff --git a/src/renderer/src/components/native-chat/paste/native-chat-paste-request.ts b/src/renderer/src/components/native-chat/paste/native-chat-paste-request.ts index 050d0f6729b..f0230adf0ab 100644 --- a/src/renderer/src/components/native-chat/paste/native-chat-paste-request.ts +++ b/src/renderer/src/components/native-chat/paste/native-chat-paste-request.ts @@ -1,5 +1,5 @@ import { translate } from '@/i18n/i18n' -import { OS_FILE_DROP_OWNER_ATTRIBUTE } from '../../../../../shared/native-file-drop-preparation' +import { OS_FILE_DROP_OWNER_ATTRIBUTE } from '../../../../../shared/file-import/native-file-drop-preparation' export const NATIVE_CHAT_PASTE_REQUEST_EVENT = 'orca-native-chat-paste-request' export const NATIVE_CHAT_ROOT_SELECTOR = '[data-native-chat-root="true"]' diff --git a/src/renderer/src/components/plugins/presentation/plugin-custom-editor-takeover.ts b/src/renderer/src/components/plugins/presentation/plugin-custom-editor-takeover.ts index ab4e8e0bf78..5bd6e29b2f1 100644 --- a/src/renderer/src/components/plugins/presentation/plugin-custom-editor-takeover.ts +++ b/src/renderer/src/components/plugins/presentation/plugin-custom-editor-takeover.ts @@ -1,6 +1,6 @@ import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' -import { filePreviewForPath } from '../../../../../shared/file-preview-kind' +import { filePreviewForPath } from '../../../../../shared/file-preview/file-preview-kind' import { fileList } from './plugin-contribution-file-list' /** Says when an editor opens files Orca would otherwise show in its own image, PDF or media viewer. */ diff --git a/src/renderer/src/components/quick-open-file-list-host-name-filter.react.test.tsx b/src/renderer/src/components/quick-open-file-list-host-name-filter.react.test.tsx deleted file mode 100644 index 3671e305873..00000000000 --- a/src/renderer/src/components/quick-open-file-list-host-name-filter.react.test.tsx +++ /dev/null @@ -1,198 +0,0 @@ -// @vitest-environment happy-dom - -import { act, createElement, useEffect } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { FolderWorkspace } from '../../../shared/folder-workspaces/folder-workspace-types' -import type { ProjectGroup } from '../../../shared/project-group-types' -import { folderWorkspaceKey } from '../../../shared/workspace-scope' -import { QUICK_OPEN_LISTING_MAX_RESULTS } from '../../../shared/quick-open-listing-limits' -import { useAppStore } from '@/store' -import { useRuntimeFileListForWorktree, type RuntimeFileListState } from './quick-open-file-list' - -const listRuntimeFilesMock = vi.hoisted(() => vi.fn()) - -vi.mock('@/runtime/files/search/runtime-file-search-client', () => ({ - listRuntimeFiles: listRuntimeFilesMock, - cancelRuntimeFileList: vi.fn(), - searchRuntimeFilePaths: vi.fn() -})) - -const initialAppState = useAppStore.getInitialState() -const roots: Root[] = [] - -function makeProjectGroup(): ProjectGroup { - return { - id: 'group-1', - name: 'Platform', - parentPath: '/srv/platform', - connectionId: null, - parentGroupId: null, - createdFrom: 'folder-scan', - tabOrder: 0, - isCollapsed: false, - color: null, - createdAt: 1, - updatedAt: 1 - } -} - -function makeFolderWorkspace(): FolderWorkspace { - return { - id: 'folder-workspace-1', - projectGroupId: 'group-1', - name: 'Platform workspace', - folderPath: '/srv/platform', - connectionId: null, - linkedTask: null, - comment: '', - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 1, - lastActivityAt: 0, - createdAt: 1, - updatedAt: 1 - } -} - -type ProbeProps = { - enabled: boolean - onState: (state: RuntimeFileListState) => void - query?: string - hostFilterWhenCapped?: boolean - worktreeId: string | null -} - -function HookProbe({ onState, ...args }: ProbeProps): null { - const state = useRuntimeFileListForWorktree(args) - useEffect(() => { - onState(state) - }) - return null -} - -async function flushEffects(): Promise { - await act(async () => { - await Promise.resolve() - await Promise.resolve() - }) -} - -async function renderProbe(args: ProbeProps): Promise { - const container = document.createElement('div') - document.body.appendChild(container) - const root = createRoot(container) - roots.push(root) - await act(async () => { - root.render(createElement(HookProbe, args)) - }) - await flushEffects() - return root -} - -beforeEach(() => { - useAppStore.setState(initialAppState, true) - listRuntimeFilesMock.mockReset().mockResolvedValue(['packages/app/package.json']) -}) - -afterEach(async () => { - for (const root of roots) { - await act(async () => { - root.unmount() - }) - } - roots.length = 0 - useAppStore.setState(initialAppState, true) -}) - -describe('useRuntimeFileListForWorktree host name filter', () => { - it('re-lists a capped local workspace with the name filter applied on the host', async () => { - vi.useFakeTimers() - useAppStore.setState({ - folderWorkspaces: [makeFolderWorkspace()], - projectGroups: [makeProjectGroup()], - repos: [], - worktreesByRepo: {} - }) - listRuntimeFilesMock - .mockResolvedValueOnce( - Array.from({ length: QUICK_OPEN_LISTING_MAX_RESULTS }, (_, i) => `src/file-${i}.ts`) - ) - .mockResolvedValueOnce(['ios/AppDelegate.swift']) - const states: RuntimeFileListState[] = [] - - try { - await renderProbe({ - enabled: true, - onState: (state) => states.push(state), - query: 'AppDelegate', - hostFilterWhenCapped: true, - worktreeId: folderWorkspaceKey('folder-workspace-1') - }) - await flushEffects() - await act(async () => vi.advanceTimersByTimeAsync(120)) - await flushEffects() - - expect(listRuntimeFilesMock).toHaveBeenCalledTimes(2) - expect(listRuntimeFilesMock.mock.calls[0][1]).not.toHaveProperty('nameFilter') - expect(listRuntimeFilesMock.mock.calls[1][1]).toMatchObject({ nameFilter: 'appdelegate' }) - expect(states.at(-1)).toMatchObject({ - files: ['ios/AppDelegate.swift'], - loading: false, - truncated: false - }) - } finally { - vi.useRealTimers() - } - }) - it('falls back to the capped listing and stops re-listing after a host filter failure', async () => { - vi.useFakeTimers() - useAppStore.setState({ - folderWorkspaces: [makeFolderWorkspace()], - projectGroups: [makeProjectGroup()], - repos: [], - worktreesByRepo: {} - }) - const capped = Array.from({ length: QUICK_OPEN_LISTING_MAX_RESULTS }, (_, i) => `f-${i}.ts`) - listRuntimeFilesMock.mockImplementation(async (_context, args: { nameFilter?: string }) => { - if (args.nameFilter) { - throw new Error('rg list timed out') - } - return capped - }) - const states: RuntimeFileListState[] = [] - const workspaceKey = folderWorkspaceKey('folder-workspace-1') - - try { - const root = await renderProbe({ - enabled: true, - onState: (state) => states.push(state), - query: 'f-1', - hostFilterWhenCapped: true, - worktreeId: workspaceKey - }) - await act(async () => vi.advanceTimersByTimeAsync(120)) - await flushEffects() - await act(async () => { - root.render( - createElement(HookProbe, { - enabled: true, - onState: (state: RuntimeFileListState) => states.push(state), - query: 'f-2', - hostFilterWhenCapped: true, - worktreeId: workspaceKey - }) - ) - }) - await act(async () => vi.advanceTimersByTimeAsync(120)) - await flushEffects() - - const nameFilters = listRuntimeFilesMock.mock.calls.map((call) => call[1].nameFilter) - expect(nameFilters.filter(Boolean)).toEqual(['f-1']) - expect(states.at(-1)).toMatchObject({ files: capped, loadError: null, truncated: true }) - } finally { - vi.useRealTimers() - } - }) -}) diff --git a/src/renderer/src/components/quick-open-file-list.react.test.tsx b/src/renderer/src/components/quick-open-file-list.react.test.tsx index 04b01905d1b..64445321d03 100644 --- a/src/renderer/src/components/quick-open-file-list.react.test.tsx +++ b/src/renderer/src/components/quick-open-file-list.react.test.tsx @@ -2,9 +2,9 @@ import { act, createElement } from 'react' import { describe, expect, it, vi } from 'vitest' import { folderWorkspaceKey } from '../../../shared/workspace-scope' -import { QUICK_OPEN_LISTING_MAX_RESULTS } from '../../../shared/quick-open-listing-limits' + import { useAppStore } from '@/store' -import type { AppState } from '@/store/types' + import type { RuntimeFileListState } from './quick-open-file-list' import { @@ -62,125 +62,6 @@ describe('useRuntimeFileListForWorktree', () => { expect(states.at(-1)?.files).toEqual(['example.txt']) }) - it('lists a repo-less SSH folder workspace after folder metadata hydrates', async () => { - const states: RuntimeFileListState[] = [] - const workspaceKey = folderWorkspaceKey('folder-workspace-1') - - useAppStore.setState({ - folderWorkspaces: [], - projectGroups: [], - repos: [], - worktreesByRepo: {} - } as Partial) - - await renderProbe({ - enabled: true, - states, - worktreeId: workspaceKey - }) - - expect(listRuntimeFilesMock).not.toHaveBeenCalled() - - await act(async () => { - useAppStore.setState({ - folderWorkspaces: [makeFolderWorkspace({ connectionId: 'ssh-1' })], - projectGroups: [makeProjectGroup({ connectionId: 'ssh-1' })], - repos: [], - worktreesByRepo: {} - } as Partial) - }) - await waitForListRuntimeFilesCall() - - expect(listRuntimeFilesMock).toHaveBeenCalledWith( - expect.objectContaining({ - worktreeId: workspaceKey, - worktreePath: '/srv/platform', - connectionId: 'ssh-1', - target: { kind: 'local' } - }), - { - includeIgnored: true, - followSymlinks: false, - rootPath: '/srv/platform', - excludePaths: undefined, - requestToken: expect.any(String), - maxResults: QUICK_OPEN_LISTING_MAX_RESULTS, - signal: expect.any(AbortSignal) - } - ) - expect(states.at(-1)?.files).toEqual(['packages/app/package.json']) - expect(states.at(-1)?.truncated).toBe(false) - }) - - // A full capped page is only a prefix; marking it complete would silently hide remaining paths (#12547). - it('reports a capped listing as truncated instead of as the whole workspace', async () => { - const states: RuntimeFileListState[] = [] - const workspaceKey = folderWorkspaceKey('folder-workspace-1') - listRuntimeFilesMock.mockResolvedValue( - Array.from({ length: QUICK_OPEN_LISTING_MAX_RESULTS }, (_, i) => `src/file-${i}.ts`) - ) - - useAppStore.setState({ - folderWorkspaces: [makeFolderWorkspace({ connectionId: 'ssh-1' })], - projectGroups: [makeProjectGroup({ connectionId: 'ssh-1' })], - repos: [], - worktreesByRepo: {} - } as Partial) - - await renderProbe({ - enabled: true, - states, - worktreeId: workspaceKey - }) - await waitForListRuntimeFilesCall() - - expect(states.at(-1)?.files).toHaveLength(QUICK_OPEN_LISTING_MAX_RESULTS) - expect(states.at(-1)?.truncated).toBe(true) - }) - - it('clears settled remote results when the query is cleared', async () => { - vi.useFakeTimers() - seedRemoteWorktree() - const states: RuntimeFileListState[] = [] - searchRuntimeFilePathsMock.mockResolvedValue({ - files: ['src/target.ts'], - truncated: false - }) - - try { - const root = await renderProbe({ - enabled: true, - states, - query: 'target', - worktreeId: 'wt-remote' - }) - await act(async () => vi.advanceTimersByTimeAsync(120)) - await flushEffects() - expect(states.at(-1)?.files).toEqual(['src/target.ts']) - - await act(async () => { - root.render( - createElement(HookProbe, { - enabled: true, - states, - query: '', - worktreeId: 'wt-remote' - }) - ) - }) - await flushEffects() - - expect(searchRuntimeFilePathsMock).toHaveBeenCalledTimes(1) - expect(states.at(-1)).toMatchObject({ - files: ['packages/app/package.json'], - loading: false, - truncated: false - }) - } finally { - vi.useRealTimers() - } - }) - it('aborts superseded runtime queries and ignores stale replies', async () => { vi.useFakeTimers() seedRemoteWorktree() @@ -242,133 +123,6 @@ describe('useRuntimeFileListForWorktree', () => { vi.useRealTimers() } }) - - it('never renders the previous listing once the remote query changes', async () => { - vi.useFakeTimers() - seedRemoteWorktree() - const states: RuntimeFileListState[] = [] - searchRuntimeFilePathsMock.mockResolvedValue({ files: ['src/tar.ts'], truncated: true }) - - try { - const root = await renderProbe({ - enabled: true, - states, - query: 'tar', - worktreeId: 'wt-remote' - }) - await act(async () => vi.advanceTimersByTimeAsync(120)) - await flushEffects() - expect(states.at(-1)).toMatchObject({ files: ['src/tar.ts'], truncated: true }) - - const rendersBeforeChange = states.length - await act(async () => { - root.render( - createElement(HookProbe, { - enabled: true, - states, - query: 'target', - worktreeId: 'wt-remote' - }) - ) - }) - - // Why: the render before the effect restarts the request is the one that can leak. - expect(states.length).toBeGreaterThan(rendersBeforeChange) - for (const state of states.slice(rendersBeforeChange)) { - expect(state).toMatchObject({ files: [], loading: true, truncated: false }) - } - } finally { - vi.useRealTimers() - } - }) - - it('reports the new remote query as loading after the previous one failed', async () => { - vi.useFakeTimers() - seedRemoteWorktree() - const states: RuntimeFileListState[] = [] - searchRuntimeFilePathsMock.mockRejectedValue(new Error('scan failed')) - - try { - const root = await renderProbe({ - enabled: true, - states, - query: 'tar', - worktreeId: 'wt-remote' - }) - await act(async () => vi.advanceTimersByTimeAsync(120)) - await flushEffects() - expect(states.at(-1)).toMatchObject({ files: [], loading: false, loadError: 'scan failed' }) - - const rendersBeforeChange = states.length - await act(async () => { - root.render( - createElement(HookProbe, { - enabled: true, - states, - query: 'target', - worktreeId: 'wt-remote' - }) - ) - }) - - expect(states.length).toBeGreaterThan(rendersBeforeChange) - for (const state of states.slice(rendersBeforeChange)) { - expect(state).toMatchObject({ files: [], loading: true }) - } - } finally { - vi.useRealTimers() - } - }) -}) - -it('merges host-eligible history beyond remote top32 once per palette lifetime', async () => { - vi.useFakeTimers() - try { - seedRemoteWorktree() - const states: RuntimeFileListState[] = [] - searchRuntimeFilePathsMock.mockResolvedValue({ - files: Array.from({ length: 32 }, (_, i) => `src/file${i}.ts`), - truncated: true - }) - listRuntimeFilesMock.mockResolvedValue(['src/file99.ts']) - const args = { - enabled: true, - worktreeId: 'wt-remote', - query: 'file', - recentPaths: ['src/file99.ts', 'src/deleted.ts'], - states - } - const root = await renderProbe(args) - await act(async () => { - await vi.advanceTimersByTimeAsync(400) - }) - expect(states.at(-1)?.files).toContain('src/file99.ts') - expect(states.at(-1)?.files).not.toContain('src/deleted.ts') - expect(listRuntimeFilesMock).toHaveBeenCalledOnce() - expect(listRuntimeFilesMock.mock.calls[0][1]).toMatchObject({ - candidatePaths: args.recentPaths, - maxResults: 2 - }) - await act(async () => { - root.render(createElement(HookProbe, { ...args, query: 'file9' })) - }) - await act(async () => { - await vi.advanceTimersByTimeAsync(400) - }) - expect(listRuntimeFilesMock).toHaveBeenCalledOnce() - await act(async () => { - root.render(createElement(HookProbe, { ...args, enabled: false })) - }) - await act(async () => { - root.render(createElement(HookProbe, args)) - }) - await act(async () => { - await vi.advanceTimersByTimeAsync(400) - }) - expect(listRuntimeFilesMock).toHaveBeenCalledTimes(2) - } finally { - vi.useRealTimers() - } }) it('keeps ordinary remote search available when recent eligibility is unsupported', async () => { diff --git a/src/renderer/src/components/quick-open-file-list.test.ts b/src/renderer/src/components/quick-open-file-list.test.ts index 1ddd92180c0..b072e66ec99 100644 --- a/src/renderer/src/components/quick-open-file-list.test.ts +++ b/src/renderer/src/components/quick-open-file-list.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' import type { Worktree } from '../../../shared/worktree/types' -import { buildExcludePathPrefixes } from '../../../shared/quick-open-filter' +import { buildExcludePathPrefixes } from '../../../shared/quick-open/quick-open-filter' import { getNestedWorktreeExcludeRequest } from './quick-open-file-list-target' import { getNestedWorktreeExcludePaths } from './quick-open-nested-worktrees' diff --git a/src/renderer/src/components/quick-open-file-list.ts b/src/renderer/src/components/quick-open-file-list.ts index e98ab84c03d..6c281099aac 100644 --- a/src/renderer/src/components/quick-open-file-list.ts +++ b/src/renderer/src/components/quick-open-file-list.ts @@ -15,15 +15,15 @@ import { import { useEffect, useMemo, useRef, useState } from 'react' export { isNestedWorktreePath, getNestedWorktreeExcludePaths } from './quick-open-nested-worktrees' import { createNonSecureContextUuid as createBrowserUuid } from '../../../shared/non-secure-context-uuid' -import { isQuickOpenRemoteQueryTooLarge } from '@/components/quick-open-search' -import { QUICK_OPEN_LISTING_MAX_RESULTS } from '../../../shared/quick-open-listing-limits' +import { isQuickOpenRemoteQueryTooLarge } from '../../../shared/quick-open/quick-open-path-search' +import { QUICK_OPEN_LISTING_MAX_RESULTS } from '../../../shared/quick-open/quick-open-listing-limits' import { cancelRuntimeFileList, listRuntimeFiles, searchRuntimeFilePaths } from '@/runtime/files/search/runtime-file-search-client' import { debounceRuntimeFileRequest } from '@/runtime/files/runtime-file-request-debounce' -import { splitFileNameFilterTokens } from '../../../shared/file-name-filter-tokens' +import { splitFileNameFilterTokens } from '../../../shared/file-listing/file-name-filter-tokens' import { nextCappedLocalListing, type CappedLocalListing diff --git a/src/renderer/src/components/quick-open-file-navigation.ts b/src/renderer/src/components/quick-open-file-navigation.ts index 7d8156fe665..e26b4e94141 100644 --- a/src/renderer/src/components/quick-open-file-navigation.ts +++ b/src/renderer/src/components/quick-open-file-navigation.ts @@ -1,4 +1,7 @@ -import { prepareQuickOpenFiles, rankQuickOpenFiles } from '../../../shared/quick-open-path-search' +import { + prepareQuickOpenFiles, + rankQuickOpenFiles +} from '../../../shared/quick-open/quick-open-path-search' import { statUserOpenedPath } from '@/lib/user-opened-local-path' import { detectLanguage } from '@/lib/language-detect' import { joinPath, getRelativePathInsideRoot } from '@/lib/path' @@ -6,12 +9,12 @@ import { useAppStore } from '@/store' import { isMissingRuntimePathError } from '@/runtime/files/metadata/runtime-file-metadata-client' import { callRuntimeRpc } from '@/runtime/rpc/calls/runtime-rpc-call' import { toRuntimeWorktreeSelector } from '@/runtime/rpc/targets/runtime-worktree-selector' -import type { RuntimeTerminalPathResolution } from '../../../shared/runtime-file-contracts' +import type { RuntimeTerminalPathResolution } from '../../../shared/terminal/runtime-terminal-file-path' import { resolveWslRepoWorktreeBasePath } from '../../../shared/wsl-paths' import { isQuickOpenAbsolutePath, type QuickOpenQueryTarget -} from '../../../shared/quick-open-query-target' +} from '../../../shared/quick-open/quick-open-query-target' import { hostAbsentRefusal } from './terminal-pane/host-files/host-file-refusal' import { hostSavesGrantedFiles } from '@/runtime/files/grants/runtime-terminal-artifact-grant' import { scheduleEditorLineReveal } from '@/store/slices/editor/focus/editor-focus-reveal' diff --git a/src/renderer/src/components/quick-open-history-ranking.ts b/src/renderer/src/components/quick-open-history-ranking.ts index dd2ac5b6476..acfbf7bd263 100644 --- a/src/renderer/src/components/quick-open-history-ranking.ts +++ b/src/renderer/src/components/quick-open-history-ranking.ts @@ -2,7 +2,7 @@ import { getPreparedQuickOpenFiles, rankQuickOpenFiles, QUICK_OPEN_RESULT_LIMIT -} from './quick-open-search' +} from '../../../shared/quick-open/quick-open-path-search' // One listing serves every keystroke; rebuilding its membership set per query scanned it all again. const availablePaths = new WeakMap>() diff --git a/src/renderer/src/components/quick-open-recent-validation.ts b/src/renderer/src/components/quick-open-recent-validation.ts index da2fe1b3523..2bff316b597 100644 --- a/src/renderer/src/components/quick-open-recent-validation.ts +++ b/src/renderer/src/components/quick-open-recent-validation.ts @@ -1,6 +1,6 @@ import { debounceRuntimeFileRequest } from '@/runtime/files/runtime-file-request-debounce' import { useEffect, useRef } from 'react' -import { quickOpenRecentCandidateSet } from '../../../shared/quick-open-recent-candidates' +import { quickOpenRecentCandidateSet } from '../../../shared/quick-open/quick-open-recent-candidates' import { cancelRuntimeFileList, listRuntimeFiles diff --git a/src/renderer/src/components/quick-open-search.test.ts b/src/renderer/src/components/quick-open-search.test.ts index 41b4a085a6e..faae670b2c8 100644 --- a/src/renderer/src/components/quick-open-search.test.ts +++ b/src/renderer/src/components/quick-open-search.test.ts @@ -1,5 +1,9 @@ import { describe, expect, it } from 'vitest' -import { QuickOpenPathRanker, prepareQuickOpenFiles, rankQuickOpenFiles } from './quick-open-search' +import { + QuickOpenPathRanker, + prepareQuickOpenFiles, + rankQuickOpenFiles +} from '../../../shared/quick-open/quick-open-path-search' describe('quick-open-search', () => { it('prefers filename substring matches over path-only matches', () => { @@ -95,20 +99,6 @@ it('bridges camel and acronym word boundaries for typed separators without match ) }) -it('evaluates all terms up to the existing byte limit and rejects only oversized input', () => { - const terms = Array.from({ length: 350 }, (_, i) => `t${i}`) - const query = terms.join(' ') - const path = `${terms.join('/')}.ts` - expect(query.length).toBeLessThan(2048) - expect(rankQuickOpenFiles(query, prepareQuickOpenFiles([path])).map((item) => item.path)).toEqual( - [path] - ) - expect(rankQuickOpenFiles(`${query} absent`, prepareQuickOpenFiles([path]))).toEqual([]) - expect(rankQuickOpenFiles(`${query}${' '.repeat(2048)}`, prepareQuickOpenFiles([path]))).toEqual( - [] - ) -}) - it.each([ ['abc-', 'abc.ts'], ['bar-', 'foo-bar.ts'], diff --git a/src/renderer/src/components/quick-open-search.ts b/src/renderer/src/components/quick-open-search.ts deleted file mode 100644 index 3ddd1ce9ce3..00000000000 --- a/src/renderer/src/components/quick-open-search.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '../../../shared/quick-open-path-search' diff --git a/src/renderer/src/components/right-sidebar/FolderWorkspaceSourceControlPanel.watch-coverage.test.tsx b/src/renderer/src/components/right-sidebar/FolderWorkspaceSourceControlPanel.watch-coverage.test.tsx deleted file mode 100644 index 85c70670791..00000000000 --- a/src/renderer/src/components/right-sidebar/FolderWorkspaceSourceControlPanel.watch-coverage.test.tsx +++ /dev/null @@ -1,276 +0,0 @@ -// @vitest-environment happy-dom -import { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import type { Worktree } from '../../../../shared/worktree/types' -import type { FsChangedPayload } from '../../../../shared/filesystem-entry-types' -import type * as WorktreeGitCopy from '@/lib/worktree-git-copy' -import { useAppStore } from '@/store' -import type { AppState } from '@/store/types' -import { TooltipProvider } from '@/components/ui/tooltip' -import { useEditorExternalWatch } from '@/hooks/useEditorExternalWatch' -import FolderWorkspaceSourceControlPanel from './FolderWorkspaceSourceControlPanel' - -const probes = vi.hoisted(() => ({ - status: vi.fn(async (_request: { worktreeId: string }) => {}) -})) -vi.mock('./source-control/sync/git-status-refresh', () => ({ - refreshGitStatusForWorktree: probes.status -})) -vi.mock('./source-control/sync/use-git-status-upstream-ref-watch', () => ({ - useGitStatusUpstreamRefWatch: () => undefined -})) -vi.mock('./source-control/sync/use-refresh-on-host-contact', () => ({ - useRefreshOnHostContact: () => {} -})) -vi.mock('@/lib/worktree-git-copy', async (original) => ({ - ...(await original()), - resolveWorktreeGitCopyNow: (id: string, hostId: string) => ({ - worktreeId: id, - hostId, - transport: { kind: 'local' } - }) -})) -// Body work is covered elsewhere; this contract is about header-tier watch coverage. -vi.mock('./source-control/panel/panel', () => ({ SourceControlPanel: () => null })) - -type RuntimeStream = { - args: { selector: string; method: string; params: { worktree: string } } - callbacks: { onResponse: (response: unknown) => void } - unsubscribe: ReturnType -} -const fsListeners = new Set<(payload: FsChangedPayload) => void>() -let runtimeStreams: RuntimeStream[] = [] -let watchWorktree: ReturnType -let unwatchWorktree: ReturnType -let root: Root -let container: HTMLDivElement - -beforeEach(() => { - vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true) - vi.useFakeTimers() - fsListeners.clear() - runtimeStreams = [] - watchWorktree = vi.fn(async () => {}) - unwatchWorktree = vi.fn(async () => {}) - vi.stubGlobal('api', { - fs: { - watchWorktree, - unwatchWorktree, - onFsChanged: (listener: (payload: FsChangedPayload) => void) => { - fsListeners.add(listener) - return () => fsListeners.delete(listener) - } - }, - runtimeEnvironments: { - subscribe: async ( - args: RuntimeStream['args'], - callbacks: RuntimeStream['callbacks'] - ): Promise<{ unsubscribe: () => void }> => { - const stream = { args, callbacks, unsubscribe: vi.fn() } - runtimeStreams.push(stream) - return { unsubscribe: stream.unsubscribe } - }, - call: async () => ({ ok: true, result: {} }) - }, - worktrees: { - onChanged: () => () => {}, - onGitStatusMetadataChanged: () => () => {} - } - }) - useAppStore.setState(useAppStore.getInitialState(), true) - container = document.createElement('div') - document.body.append(container) - root = createRoot(container) - probes.status.mockClear() -}) -afterEach(async () => { - await act(async () => root.unmount()) - container.remove() - vi.useRealTimers() - vi.unstubAllGlobals() -}) - -function worktreeRow(repoId: string, path: string, index: number, extra: Partial = {}) { - return { - id: `${repoId}::${path}`, - repoId, - path, - branch: `refs/heads/feature-${index}`, - head: 'abc123', - isBare: false, - isMainWorktree: false, - displayName: `Child ${index}`, - comment: '', - linkedIssue: null, - linkedPR: null, - linkedLinearIssue: null, - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: index, - lastActivityAt: 0, - hostId: 'local' as const, - instanceId: `instance-${repoId}-${index}`, - ...extra - } satisfies Worktree -} - -function setup(state: { - children: Worktree[] - others?: Worktree[] - openFiles?: AppState['openFiles'] - lastVisitedAtByWorktreeId?: Record - changed?: ReadonlySet -}) { - const byRepo: Record = {} - for (const row of [...state.children, ...(state.others ?? [])]) { - ;(byRepo[row.repoId] ??= []).push(row) - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: fixture supplies the catalog, lineage and status fields the panel and watch owner read. - useAppStore.setState({ - activeWorktreeId: 'folder:feature', - activeWorkspaceKey: 'folder:feature', - activeWorkspaceExecutionHostId: 'local', - rightSidebarOpen: true, - rightSidebarTab: 'source-control', - repos: [ - { id: 'repo', displayName: 'Child', path: '/repo', kind: 'git' }, - { id: 'other', displayName: 'Other', path: '/other', kind: 'git' }, - { - id: 'rrepo', - displayName: 'Remote', - path: '/remote', - kind: 'git', - executionHostId: 'runtime:env-1' - } - ], - sshConnectionStates: new Map([ - [ - 'nested-ssh', - { targetId: 'nested-ssh', status: 'connected', error: null, reconnectAttempt: 0 } - ] - ]), - worktreesByRepo: byRepo, - folderWorkspaces: [ - { id: 'feature', name: 'Feature', folderPath: '/folder', projectGroupId: 'group' } - ], - workspaceLineageByChildKey: Object.fromEntries( - state.children.map((row, i) => [ - row.id, - { - childWorkspaceKey: `worktree:${row.id}`, - childInstanceId: row.instanceId, - parentWorkspaceKey: 'folder:feature', - parentInstanceId: null, - createdAt: i - } - ]) - ), - // Unchanged sections start collapsed; changed ones expand. - gitStatusByWorktree: Object.fromEntries( - state.children.map((row) => [ - row.id, - state.changed?.has(row.id) ? [{ path: 'a.ts', status: 'modified', area: 'unstaged' }] : [] - ]) - ), - openFiles: state.openFiles ?? [], - lastVisitedAtByWorktreeId: state.lastVisitedAtByWorktreeId ?? {} - } as unknown as Partial) -} - -function WatchOwner() { - useEditorExternalWatch() - return null -} -async function render(panel = true) { - await act(async () => - root.render( - - - {panel && } - - ) - ) - await act(async () => { - await vi.advanceTimersByTimeAsync(0) - }) -} - -async function settleAfter(send: () => void) { - probes.status.mockClear() - await act(async () => { - send() - // Debounce plus the existing 3 s activity floor, well inside the 60 s safety poll. - await vi.advanceTimersByTimeAsync(4000) - }) - return probes.status.mock.calls.map(([request]) => request.worktreeId) -} - -const watchedPaths = (calls: { worktreePath: string }[][]) => - calls.map(([args]) => args!.worktreePath) - -it('wakes only the owning collapsed or expanded section from file events beyond the former three watches', async () => { - const children = Array.from({ length: 30 }, (_, i) => worktreeRow('repo', `/child-${i}`, i)) - setup({ children, changed: new Set([children[5]!.id]) }) - await render() - // Every mounted local section holds a recursive root, collapsed and off-screen ones included. - expect(watchedPaths(watchWorktree.mock.calls).sort()).toEqual( - children.map((row) => row.path).sort() - ) - const local = (path: string, kind: 'create' | 'update' | 'delete', file: string) => () => { - for (const listener of fsListeners) { - listener({ worktreePath: path, events: [{ kind, absolutePath: `${path}/${file}` }] }) - } - } - for (const target of [children[29]!, children[5]!]) { - expect(await settleAfter(local(target.path, 'update', 'src/deep/tracked.ts'))).toEqual([ - target.id - ]) - expect(await settleAfter(local(target.path, 'create', 'untracked.txt'))).toEqual([target.id]) - expect(await settleAfter(local(target.path, 'delete', 'untracked.txt'))).toEqual([target.id]) - } -}) - -it.each(['explicit', 'repository'] as const)( - 'watches an SSH section with %s runtime ownership through files.watch', - async (ownership) => { - const runtimeChild = worktreeRow( - 'rrepo', - '/remote/child', - 0, - ownership === 'explicit' - ? { hostId: 'runtime:env-1', runtimeOwnerEnvironmentId: 'env-1' } - : { hostId: undefined } - ) - setup({ children: [runtimeChild] }) - useAppStore.setState({ - settings: { - ...useAppStore.getState().settings!, - activeRuntimeEnvironmentId: 'selected-elsewhere' - } - }) - await render() - expect(watchWorktree).not.toHaveBeenCalled() - expect(runtimeStreams.map((stream) => [stream.args.selector, stream.args.method])).toEqual([ - ['env-1', 'files.watch'] - ]) - const [stream] = runtimeStreams - await act(async () => - stream!.callbacks.onResponse({ ok: true, result: { type: 'ready', subscriptionId: 'sub-1' } }) - ) - const recipients = await settleAfter(() => - stream!.callbacks.onResponse({ - ok: true, - result: { - type: 'changed', - worktree: runtimeChild.id, - events: [{ kind: 'create', absolutePath: '/remote/child/nested/new.txt' }] - } - }) - ) - expect(recipients).toEqual([runtimeChild.id]) - await render(false) - expect(stream!.unsubscribe).toHaveBeenCalled() - } -) diff --git a/src/renderer/src/components/right-sidebar/file-explorer/content-search/SearchResultItems.tsx b/src/renderer/src/components/right-sidebar/file-explorer/content-search/SearchResultItems.tsx index 32f2952e703..8243bc340bf 100644 --- a/src/renderer/src/components/right-sidebar/file-explorer/content-search/SearchResultItems.tsx +++ b/src/renderer/src/components/right-sidebar/file-explorer/content-search/SearchResultItems.tsx @@ -11,8 +11,11 @@ import { ContextMenuContent, ContextMenuItem } from '@/components/ui/context-menu' -import { normalizeSearchFileMatchCount } from '../../../../../../shared/search-match-count' -import type { SearchFileResult, SearchMatch } from '../../../../../../shared/code-search-types' +import { normalizeSearchFileMatchCount } from '../../../../../../shared/file-search/search-match-count' +import type { + SearchFileResult, + SearchMatch +} from '../../../../../../shared/file-search/code-search-types' import { useTranslate } from '@/i18n/use-translate' export function ToggleButton({ diff --git a/src/renderer/src/components/right-sidebar/file-explorer/content-search/SearchResultsPane.tsx b/src/renderer/src/components/right-sidebar/file-explorer/content-search/SearchResultsPane.tsx index 5f9cfc8798e..d7f1dc2d5a3 100644 --- a/src/renderer/src/components/right-sidebar/file-explorer/content-search/SearchResultsPane.tsx +++ b/src/renderer/src/components/right-sidebar/file-explorer/content-search/SearchResultsPane.tsx @@ -4,7 +4,7 @@ import type { SearchFileResult, SearchMatch, SearchResult -} from '../../../../../../shared/code-search-types' +} from '../../../../../../shared/file-search/code-search-types' import type { SearchRow } from './search-rows' import { FileResultRow, MatchResultRow } from './SearchResultItems' import { translate } from '@/i18n/i18n' diff --git a/src/renderer/src/components/right-sidebar/file-explorer/content-search/file-search-include-pattern.ts b/src/renderer/src/components/right-sidebar/file-explorer/content-search/file-search-include-pattern.ts index e65871f20d4..3e656ba2930 100644 --- a/src/renderer/src/components/right-sidebar/file-explorer/content-search/file-search-include-pattern.ts +++ b/src/renderer/src/components/right-sidebar/file-explorer/content-search/file-search-include-pattern.ts @@ -1,4 +1,4 @@ -import { normalizeRelativePath } from '@/lib/path' +import { normalizeRelativePath } from '../../../../../../shared/cross-platform-path' const SEARCH_GLOB_LITERAL_META = new Set(['\\', '*', '?', '[', ']', '{', '}', '!', ',']) diff --git a/src/renderer/src/components/right-sidebar/file-explorer/content-search/search-match-open.ts b/src/renderer/src/components/right-sidebar/file-explorer/content-search/search-match-open.ts index f4c3cf7fb48..a5c6c7ad4b2 100644 --- a/src/renderer/src/components/right-sidebar/file-explorer/content-search/search-match-open.ts +++ b/src/renderer/src/components/right-sidebar/file-explorer/content-search/search-match-open.ts @@ -1,6 +1,9 @@ import { detectLanguage } from '@/lib/language-detect' import type { FileSearchResultOwner } from '@/lib/file-search-result-owner' -import type { SearchFileResult, SearchMatch } from '../../../../../../shared/code-search-types' +import type { + SearchFileResult, + SearchMatch +} from '../../../../../../shared/file-search/code-search-types' export function cancelRevealFrame(frameRef: React.RefObject): void { if (frameRef.current !== null) { diff --git a/src/renderer/src/components/right-sidebar/file-explorer/content-search/search-rows.ts b/src/renderer/src/components/right-sidebar/file-explorer/content-search/search-rows.ts index 28c66b48c17..d1f996cdae5 100644 --- a/src/renderer/src/components/right-sidebar/file-explorer/content-search/search-rows.ts +++ b/src/renderer/src/components/right-sidebar/file-explorer/content-search/search-rows.ts @@ -2,7 +2,7 @@ import type { SearchFileResult, SearchMatch, SearchResult -} from '../../../../../../shared/code-search-types' +} from '../../../../../../shared/file-search/code-search-types' export type SearchRow = | { diff --git a/src/renderer/src/components/right-sidebar/file-explorer/content-search/useFileSearchPanel.lifecycle.test.tsx b/src/renderer/src/components/right-sidebar/file-explorer/content-search/useFileSearchPanel.lifecycle.test.tsx deleted file mode 100644 index f22b42b94ee..00000000000 --- a/src/renderer/src/components/right-sidebar/file-explorer/content-search/useFileSearchPanel.lifecycle.test.tsx +++ /dev/null @@ -1,117 +0,0 @@ -// @vitest-environment happy-dom -import { act, renderHook } from '@testing-library/react' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { useAppStore } from '@/store/index' -import { makeFolderWorkspace } from '@/store/folder-workspaces/folder-workspace.test-fixture' -import { useFileSearchPanel } from './useFileSearchPanel' -import type { SearchResult } from '../../../../../../shared/code-search-types' - -const { search } = vi.hoisted(() => ({ search: vi.fn() })) -vi.mock('@/runtime/files/search/runtime-file-search-client', () => ({ searchRuntimeFiles: search })) -const initial = useAppStore.getInitialState() - -const empty: SearchResult = { files: [], totalMatches: 0, truncated: false } - -beforeEach(() => { - vi.useFakeTimers() - search.mockReset() - useAppStore.setState( - { - ...initial, - folderWorkspaces: [ - makeFolderWorkspace({ id: 'a', folderPath: '/a' }), - makeFolderWorkspace({ id: 'b', folderPath: '/b' }) - ], - activeWorktreeId: 'folder:a' - }, - true - ) -}) -afterEach(() => { - useAppStore.setState(initial, true) - vi.useRealTimers() -}) - -it('automatically replaces pending root searches and ignores a late old completion', async () => { - const signals: AbortSignal[] = [] - const completions: ((value: SearchResult) => void)[] = [] - search.mockImplementation((_context, _options, signal: AbortSignal) => { - signals.push(signal) - return new Promise((resolve) => completions.push(resolve)) - }) - useAppStore.getState().updateFileSearchState('folder:a', { query: 'needle' }) - const hook = renderHook(() => useFileSearchPanel('search')) - await act(async () => vi.advanceTimersByTimeAsync(300)) - await act(async () => - useAppStore.setState({ - folderWorkspaces: [makeFolderWorkspace({ id: 'a', folderPath: '/replacement' })] - }) - ) - expect(signals[0].aborted).toBe(true) - await act(async () => vi.advanceTimersByTimeAsync(300)) - expect(search).toHaveBeenCalledTimes(2) - await act(async () => completions[1](empty)) - const replacementOwner = useAppStore.getState().fileSearchStateByWorktree['folder:a'].resultOwner - await act(async () => completions[0]({ ...empty, totalMatches: 99 })) - expect(useAppStore.getState().fileSearchStateByWorktree['folder:a'].results?.totalMatches).toBe(0) - expect(useAppStore.getState().fileSearchStateByWorktree['folder:a'].resultOwner).toBe( - replacementOwner - ) - hook.unmount() -}) - -it('retries a saved failure after its root changes without reusing the old error', async () => { - const log = vi.spyOn(console, 'error').mockImplementation(() => {}) - try { - search.mockRejectedValueOnce(new Error('old root unavailable')).mockResolvedValue(empty) - useAppStore.getState().updateFileSearchState('folder:a', { query: 'needle' }) - const hook = renderHook(() => useFileSearchPanel('search')) - await act(async () => vi.advanceTimersByTimeAsync(300)) - expect(useAppStore.getState().fileSearchStateByWorktree['folder:a'].error).toBe( - 'old root unavailable' - ) - await act(async () => - useAppStore.setState({ - folderWorkspaces: [makeFolderWorkspace({ id: 'a', folderPath: '/replacement' })] - }) - ) - await act(async () => vi.advanceTimersByTimeAsync(300)) - expect(search).toHaveBeenCalledTimes(2) - expect(useAppStore.getState().fileSearchStateByWorktree['folder:a'].error).toBeNull() - expect(useAppStore.getState().fileSearchStateByWorktree['folder:a'].results).toEqual(empty) - hook.unmount() - } finally { - log.mockRestore() - } -}) - -it.each(['root', 'owner'] as const)( - 'hides stale errors during %s replacement before effects clear them', - async (change) => { - search.mockRejectedValue(new Error('current failure')) - useAppStore.getState().updateFileSearchState('folder:a', { query: 'needle' }) - const renders: (string | null | undefined)[] = [] - const hook = renderHook(() => { - const panel = useFileSearchPanel('search') - renders.push(panel.resultsProps.error) - return panel - }) - await act(async () => vi.advanceTimersByTimeAsync(300)) - expect(hook.result.current.resultsProps.error).toBe('current failure') - renders.length = 0 - await act(async () => - useAppStore.setState({ - folderWorkspaces: [ - makeFolderWorkspace({ - id: 'a', - folderPath: change === 'root' ? '/replacement' : '/a', - connectionId: change === 'owner' ? 'remote' : null - }) - ] - }) - ) - expect(renders.length).toBeGreaterThan(0) - expect(renders).not.toContain('current failure') - hook.unmount() - } -) diff --git a/src/renderer/src/components/right-sidebar/file-explorer/content-search/useFileSearchPanel.ts b/src/renderer/src/components/right-sidebar/file-explorer/content-search/useFileSearchPanel.ts index 1f50e383b68..1db191b1bc4 100644 --- a/src/renderer/src/components/right-sidebar/file-explorer/content-search/useFileSearchPanel.ts +++ b/src/renderer/src/components/right-sidebar/file-explorer/content-search/useFileSearchPanel.ts @@ -7,7 +7,7 @@ import type { SearchFileResult, SearchMatch, SearchResult -} from '../../../../../../shared/code-search-types' +} from '../../../../../../shared/file-search/code-search-types' import { buildSearchRows } from './search-rows' import { cancelRevealFrame, openMatchResult } from './search-match-open' import type { SearchQueryRowProps } from './SearchQueryRow' diff --git a/src/renderer/src/components/right-sidebar/file-explorer/content-search/useFileSearchRunner.test.tsx b/src/renderer/src/components/right-sidebar/file-explorer/content-search/useFileSearchRunner.test.tsx index 633b6195135..94d7451a4e5 100644 --- a/src/renderer/src/components/right-sidebar/file-explorer/content-search/useFileSearchRunner.test.tsx +++ b/src/renderer/src/components/right-sidebar/file-explorer/content-search/useFileSearchRunner.test.tsx @@ -2,7 +2,7 @@ import { act, renderHook } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { SearchResult } from '../../../../../../shared/code-search-types' +import type { SearchResult } from '../../../../../../shared/file-search/code-search-types' import { useFileSearchRunner } from './useFileSearchRunner' const mocks = vi.hoisted(() => ({ diff --git a/src/renderer/src/components/right-sidebar/file-explorer/content-search/useFileSearchRunner.ts b/src/renderer/src/components/right-sidebar/file-explorer/content-search/useFileSearchRunner.ts index 170cccf1b82..a3aa8facf89 100644 --- a/src/renderer/src/components/right-sidebar/file-explorer/content-search/useFileSearchRunner.ts +++ b/src/renderer/src/components/right-sidebar/file-explorer/content-search/useFileSearchRunner.ts @@ -17,7 +17,7 @@ import { runtimeEnvironmentIdOrLocalUnlessTwin } from '@/lib/workspace/ownership/worktree-runtime-owner' import { isTwinWorkspace } from '@/lib/resolve-owner' -import type { SearchResult } from '../../../../../../shared/code-search-types' +import type { SearchResult } from '../../../../../../shared/file-search/code-search-types' import { runtimeTargetForOwnerEnvironment } from '@/runtime/rpc/targets/runtime-client-target' const SEARCH_DEBOUNCE_MS = 300 diff --git a/src/renderer/src/components/right-sidebar/file-explorer/mutations/file-explorer-delete-undo-precondition.test.tsx b/src/renderer/src/components/right-sidebar/file-explorer/mutations/file-explorer-delete-undo-precondition.test.tsx index 7a8880580ba..aadce4eb438 100644 --- a/src/renderer/src/components/right-sidebar/file-explorer/mutations/file-explorer-delete-undo-precondition.test.tsx +++ b/src/renderer/src/components/right-sidebar/file-explorer/mutations/file-explorer-delete-undo-precondition.test.tsx @@ -4,14 +4,10 @@ import { act, renderHook } from '@testing-library/react' import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { useAppStore } from '@/store/index' import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' -import { - FILE_ALREADY_EXISTS_DIFFERENTLY_MESSAGE, - missingOrIdenticalPrecondition -} from '../../../../../../shared/file-write-disk-precondition' + import { getFileExplorerOperationOwner } from '../navigation/file-explorer-operation-owner' import { clearFileExplorerUndoHistory, - fileExplorerHasRedo, fileExplorerHasUndo, undoFileExplorer } from './fileExplorerUndoRedo' @@ -56,42 +52,6 @@ beforeEach(() => { }) afterEach(() => useAppStore.setState(initialState, true)) -it('undo of a delete never replaces a file recreated at the same path', async () => { - mocks.write.mockResolvedValue({ ok: false, diskConflict: 'changed' }) - const { result } = renderHook(() => - useFileDeletion({ - activeWorktreeId: worktreeId, - openFiles: [], - closeFile: vi.fn(), - refreshDir: vi.fn().mockResolvedValue(undefined), - setSelectedPaths: vi.fn(), - isWindows: false - }) - ) - await act(async () => - result.current.requestDelete({ - name: 'notes.txt', - path: `${root}/notes.txt`, - relativePath: 'notes.txt', - isDirectory: false, - depth: 0, - operationOwner: getFileExplorerOperationOwner(worktreeId) - }) - ) - await vi.waitFor(() => expect(fileExplorerHasUndo()).toBe(true)) - - await expect(undoFileExplorer()).rejects.toThrow(FILE_ALREADY_EXISTS_DIFFERENTLY_MESSAGE) - expect(mocks.write.mock.calls[0]?.[4]).toEqual(missingOrIdenticalPrecondition('deleted body')) - // The refused step stays on the stack, so the user can undo again once the path is clear. - expect(fileExplorerHasUndo()).toBe(true) - expect(fileExplorerHasRedo()).toBe(false) - - mocks.write.mockResolvedValue({ ok: true }) - await expect(undoFileExplorer()).resolves.toBe(true) - expect(fileExplorerHasUndo()).toBe(false) - expect(fileExplorerHasRedo()).toBe(true) -}) - it('drops an undo whose failure may have applied it, as before', async () => { // A timed-out reply may follow a write that landed; replaying could replace a newer file. mocks.write.mockRejectedValue(new Error('Timed out waiting for the remote Orca runtime')) diff --git a/src/renderer/src/components/right-sidebar/file-explorer/mutations/fileExplorerUndoRedo.ts b/src/renderer/src/components/right-sidebar/file-explorer/mutations/fileExplorerUndoRedo.ts index a7373979e25..5b262103638 100644 --- a/src/renderer/src/components/right-sidebar/file-explorer/mutations/fileExplorerUndoRedo.ts +++ b/src/renderer/src/components/right-sidebar/file-explorer/mutations/fileExplorerUndoRedo.ts @@ -1,5 +1,5 @@ /** Keep exact mutation paths/content in memory; OS trash restore has no portable API here. */ -import { FileWriteRefusedError } from '../../../../../../shared/file-write-disk-precondition' +import { FileWriteRefusedError } from '../../../../../../shared/file-write/file-write-disk-precondition' const MAX_STEPS = 50 diff --git a/src/renderer/src/components/right-sidebar/file-explorer/mutations/useFileDeletion.ts b/src/renderer/src/components/right-sidebar/file-explorer/mutations/useFileDeletion.ts index 32011b9d05b..d560593ddae 100644 --- a/src/renderer/src/components/right-sidebar/file-explorer/mutations/useFileDeletion.ts +++ b/src/renderer/src/components/right-sidebar/file-explorer/mutations/useFileDeletion.ts @@ -32,7 +32,7 @@ import { import { assertFileWriteApplied, missingOrIdenticalPrecondition -} from '../../../../../../shared/file-write-disk-precondition' +} from '../../../../../../shared/file-write/file-write-disk-precondition' import { deleteWithPermanentFallback } from './file-explorer-trash-fallback' import { readRuntimeFileContent } from '@/runtime/files/reads/runtime-file-read-client' import { translate } from '@/i18n/i18n' diff --git a/src/renderer/src/components/right-sidebar/file-explorer/mutations/useFileExplorerImport.remote.test.tsx b/src/renderer/src/components/right-sidebar/file-explorer/mutations/useFileExplorerImport.remote.test.tsx index f1ea5e6355b..e5d1acbeb93 100644 --- a/src/renderer/src/components/right-sidebar/file-explorer/mutations/useFileExplorerImport.remote.test.tsx +++ b/src/renderer/src/components/right-sidebar/file-explorer/mutations/useFileExplorerImport.remote.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment happy-dom import { act, cleanup, render, waitFor } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { PreparedDroppedPaths } from '../../../../../../shared/native-file-drop-preparation' +import type { PreparedDroppedPaths } from '../../../../../../shared/file-import/native-file-drop-preparation' import { useAppStore } from '@/store/index' import { seedRemoteDropWorkspaces, diff --git a/src/renderer/src/components/right-sidebar/file-explorer/navigation/FileExplorerRootSelect.tsx b/src/renderer/src/components/right-sidebar/file-explorer/navigation/FileExplorerRootSelect.tsx index 0b32e818354..5d33472ba43 100644 --- a/src/renderer/src/components/right-sidebar/file-explorer/navigation/FileExplorerRootSelect.tsx +++ b/src/renderer/src/components/right-sidebar/file-explorer/navigation/FileExplorerRootSelect.tsx @@ -11,7 +11,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip import { useTranslate } from '@/i18n/use-translate' import './file-explorer-display-root' import type { ExplorerRootOption } from './file-explorer-display-root' -import { FILE_EXPLORER_FULL_ROOT } from '../../../../../../shared/file-explorer-display-root' +import { FILE_EXPLORER_FULL_ROOT } from '../../../../../../shared/file-listing/file-explorer-display-root' export type FileExplorerRootSelectProps = { options: ExplorerRootOption[] diff --git a/src/renderer/src/components/right-sidebar/file-explorer/navigation/file-explorer-display-root.ts b/src/renderer/src/components/right-sidebar/file-explorer/navigation/file-explorer-display-root.ts index 126f71779d7..5b612aae347 100644 --- a/src/renderer/src/components/right-sidebar/file-explorer/navigation/file-explorer-display-root.ts +++ b/src/renderer/src/components/right-sidebar/file-explorer/navigation/file-explorer-display-root.ts @@ -1,7 +1,7 @@ import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' import { getRelativePathInsideRoot, joinPath } from '@/lib/path' -import { FILE_EXPLORER_FULL_ROOT } from '../../../../../../shared/file-explorer-display-root' +import { FILE_EXPLORER_FULL_ROOT } from '../../../../../../shared/file-listing/file-explorer-display-root' import { splitPathSegments } from '../../../../../../shared/cross-platform-path' export type ExplorerRootOption = { value: string; label: string } diff --git a/src/renderer/src/components/right-sidebar/file-explorer/navigation/use-file-explorer-root-navigation.ts b/src/renderer/src/components/right-sidebar/file-explorer/navigation/use-file-explorer-root-navigation.ts index e1c93ac4eb0..4941c6a06f9 100644 --- a/src/renderer/src/components/right-sidebar/file-explorer/navigation/use-file-explorer-root-navigation.ts +++ b/src/renderer/src/components/right-sidebar/file-explorer/navigation/use-file-explorer-root-navigation.ts @@ -2,7 +2,7 @@ import { useCallback, useState } from 'react' import { useAppStore } from '@/store/index' import './file-explorer-display-root' import type { ExplorerRootOption } from './file-explorer-display-root' -import { FILE_EXPLORER_FULL_ROOT } from '../../../../../../shared/file-explorer-display-root' +import { FILE_EXPLORER_FULL_ROOT } from '../../../../../../shared/file-listing/file-explorer-display-root' export function useFileExplorerRootNavigation( worktreeId: string | null, diff --git a/src/renderer/src/components/right-sidebar/file-explorer/navigation/useFileExplorerReveal.ts b/src/renderer/src/components/right-sidebar/file-explorer/navigation/useFileExplorerReveal.ts index 9ba20a55cbf..adcfb2a9332 100644 --- a/src/renderer/src/components/right-sidebar/file-explorer/navigation/useFileExplorerReveal.ts +++ b/src/renderer/src/components/right-sidebar/file-explorer/navigation/useFileExplorerReveal.ts @@ -3,7 +3,7 @@ import type { Dispatch, RefObject, SetStateAction } from 'react' import type { Virtualizer } from '@tanstack/react-virtual' import { getRelativePathInsideRoot } from '@/lib/path' import { getExplorerDisplayDepth } from './file-explorer-display-root' -import { FILE_EXPLORER_FULL_ROOT } from '../../../../../../shared/file-explorer-display-root' +import { FILE_EXPLORER_FULL_ROOT } from '../../../../../../shared/file-listing/file-explorer-display-root' import { useAppStore } from '@/store/index' import { getRevealAncestorDirs } from './file-explorer-paths' import type { DirCache } from '../tree/file-explorer-types' diff --git a/src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-dir-pages.test.ts b/src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-dir-pages.test.ts index 87899c4f7cc..2029d79e160 100644 --- a/src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-dir-pages.test.ts +++ b/src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-dir-pages.test.ts @@ -1,5 +1,5 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { DirEntry } from '../../../../../../shared/filesystem-entry-types' +import type { DirEntry } from '../../../../../../shared/file-listing/directory-entry' const readRuntimeDirectoryPage = vi.fn() const readRuntimeDirectory = vi.fn() diff --git a/src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-dir-pages.ts b/src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-dir-pages.ts index 7600b8bcee2..585f5c2a159 100644 --- a/src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-dir-pages.ts +++ b/src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-dir-pages.ts @@ -1,5 +1,5 @@ import type { Dispatch, SetStateAction } from 'react' -import { sortDirEntries } from '../../../../../../shared/file-name-sort' +import { sortDirEntries } from '../../../../../../shared/file-listing/file-name-sort' import type { DirCache } from './file-explorer-types' import type { FileExplorerDirLoadTracker } from './file-explorer-dir-load-tracker' import { diff --git a/src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-directory-listing.ts b/src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-directory-listing.ts index d9bccf6be37..2b59bb35a76 100644 --- a/src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-directory-listing.ts +++ b/src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-directory-listing.ts @@ -1,7 +1,7 @@ import { useAppStore } from '@/store/index' import { getRelativePathInsideRoot, joinPath } from '@/lib/path' -import type { DirEntry } from '../../../../../../shared/filesystem-entry-types' -import { sortDirEntries } from '../../../../../../shared/file-name-sort' +import type { DirEntry } from '../../../../../../shared/file-listing/directory-entry' +import { sortDirEntries } from '../../../../../../shared/file-listing/file-name-sort' import { readRuntimeDirectoryPage, runtimeDirectoryPagesSupported @@ -11,7 +11,7 @@ import { FILE_READ_DIR_MAX_PAGE_ENTRIES, isDirListingTooLargeForRemoteError, type DirEntryCursor -} from '../../../../../../shared/file-dir-page' +} from '../../../../../../shared/file-listing/file-dir-page' import type { DirCache, FileExplorerDirMore, diff --git a/src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-entries.ts b/src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-entries.ts index 692dde13850..fc40d830218 100644 --- a/src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-entries.ts +++ b/src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-entries.ts @@ -1,4 +1,4 @@ -import type { DirEntry } from '../../../../../../shared/filesystem-entry-types' +import type { DirEntry } from '../../../../../../shared/file-listing/directory-entry' import { splitPathSegments } from '../../../../../../shared/cross-platform-path' export function shouldIncludeFileExplorerEntry(entry: DirEntry): boolean { diff --git a/src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-name-filter-projection.ts b/src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-name-filter-projection.ts index 99a64807a41..1e3842ce898 100644 --- a/src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-name-filter-projection.ts +++ b/src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-name-filter-projection.ts @@ -1,18 +1,21 @@ -import { getRelativePathInsideRoot, joinPath, normalizeRelativePath } from '@/lib/path' -import { compareFileNames } from '../../../../../../shared/file-name-sort' +import { getRelativePathInsideRoot, joinPath } from '@/lib/path' +import { + normalizeRelativePath, + splitPathSegments +} from '../../../../../../shared/cross-platform-path' +import { compareFileNames } from '../../../../../../shared/file-listing/file-name-sort' import { FILE_NAME_FILTER_QUERY_MAX_BYTES, isFileNameFilterQueryTooLarge, pathMatchesFileNameFilterTokens, splitFileNameFilterTokens -} from '../../../../../../shared/file-name-filter-tokens' +} from '../../../../../../shared/file-listing/file-name-filter-tokens' import type { FileExplorerOperationOwner, TreeNode } from './file-explorer-types' import { createFileExplorerRowProjectionFromParts, type FileExplorerRowProjection } from './file-explorer-row-projection' import { isDotfileRelativePath } from './file-explorer-entries' -import { splitPathSegments } from '../../../../../../shared/cross-platform-path' import { isPathIgnored } from '../../../../lib/git-path-decoration' export type FileExplorerNameFilterProjectionSource = { diff --git a/src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-types.ts b/src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-types.ts index 86740a2c6b4..bdac98b58dc 100644 --- a/src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-types.ts +++ b/src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-types.ts @@ -1,5 +1,5 @@ import type { ExecutionHostId } from '../../../../../../shared/execution-host' -import type { DirEntryCursor } from '../../../../../../shared/file-dir-page' +import type { DirEntryCursor } from '../../../../../../shared/file-listing/file-dir-page' export type FileExplorerOperationOwner = | { kind: 'local' } diff --git a/src/renderer/src/components/right-sidebar/file-explorer/tree/useFileExplorerTree.paged-dirs.test.tsx b/src/renderer/src/components/right-sidebar/file-explorer/tree/useFileExplorerTree.paged-dirs.test.tsx index c691ea37bfb..5820cab337d 100644 --- a/src/renderer/src/components/right-sidebar/file-explorer/tree/useFileExplorerTree.paged-dirs.test.tsx +++ b/src/renderer/src/components/right-sidebar/file-explorer/tree/useFileExplorerTree.paged-dirs.test.tsx @@ -2,7 +2,7 @@ import { act, cleanup, renderHook } from '@testing-library/react' import { afterEach, describe, expect, it, vi } from 'vitest' -import type { DirEntry } from '../../../../../../shared/filesystem-entry-types' +import type { DirEntry } from '../../../../../../shared/file-listing/directory-entry' import { useFileExplorerTree } from './useFileExplorerTree' const readDirectoryMock = vi.hoisted(() => vi.fn()) diff --git a/src/renderer/src/components/right-sidebar/file-explorer/watching/file-explorer-expanded-dirs-refresh.test.ts b/src/renderer/src/components/right-sidebar/file-explorer/watching/file-explorer-expanded-dirs-refresh.test.ts deleted file mode 100644 index d95480269a5..00000000000 --- a/src/renderer/src/components/right-sidebar/file-explorer/watching/file-explorer-expanded-dirs-refresh.test.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { SetStateAction } from 'react' -import type { DirEntry } from '../../../../../../shared/filesystem-entry-types' -import type { DirCache } from '../tree/file-explorer-types' -import { createFileExplorerDirLoadTracker } from '../tree/file-explorer-dir-load-tracker' -import { refreshFileExplorerExpandedDirs } from './file-explorer-expanded-dirs-refresh' -import type { FileExplorerLoadingDirsUpdater } from '../tree/file-explorer-dir-load-state' - -type CacheUpdate = SetStateAction> - -function createLoadingDirPathsRecorder(): { - updateLoadingDirPaths: FileExplorerLoadingDirsUpdater - isLoading: (dirPath: string) => boolean -} { - let loadingDirPaths: ReadonlySet = new Set() - return { - updateLoadingDirPaths: (update) => { - loadingDirPaths = update(loadingDirPaths) - }, - isLoading: (dirPath: string) => loadingDirPaths.has(dirPath) - } -} - -function entry(name: string, isDirectory = false): DirEntry { - return { name, isDirectory, isSymlink: false } -} - -describe('refreshFileExplorerExpandedDirs', () => { - it('does not turn a commit callback failure into an empty directory result', async () => { - let cache: Record = {} - const setDirCache = vi.fn((update: CacheUpdate) => { - cache = typeof update === 'function' ? update(cache) : update - }) - const { updateLoadingDirPaths } = createLoadingDirPathsRecorder() - const commitError = new Error('commit failed') - - await expect( - refreshFileExplorerExpandedDirs({ - dirs: [{ dirPath: '/repo/src', depth: 0 }], - worktreePath: '/repo', - dirLoadTracker: createFileExplorerDirLoadTracker(), - setDirCache, - updateLoadingDirPaths, - readDirectory: async () => ({ - entries: [entry('index.ts')], - operationOwner: { kind: 'local' as const } - }), - maxConcurrentReads: 1, - onDirCommitted: () => { - throw commitError - } - }) - ).rejects.toBe(commitError) - - expect(setDirCache).toHaveBeenCalledTimes(2) - expect(cache['/repo/src']).toMatchObject({ children: [{ name: 'index.ts' }] }) - }) - - it('stops later batches after a commit callback throws', async () => { - let cache: Record = {} - const setDirCache = vi.fn((update: CacheUpdate) => { - cache = typeof update === 'function' ? update(cache) : update - }) - const { updateLoadingDirPaths, isLoading } = createLoadingDirPathsRecorder() - const commitError = new Error('commit failed') - const onDirCommitted = vi.fn((dirPath: string) => { - if (dirPath === '/repo/a') { - throw commitError - } - }) - - await expect( - refreshFileExplorerExpandedDirs({ - dirs: ['a', 'b', 'c', 'd'].map((name) => ({ dirPath: `/repo/${name}`, depth: 0 })), - worktreePath: '/repo', - dirLoadTracker: createFileExplorerDirLoadTracker(), - setDirCache, - updateLoadingDirPaths, - readDirectory: async () => ({ - entries: [entry('index.ts')], - operationOwner: { kind: 'local' as const } - }), - // Two dirs per commit batch, so /repo/c and /repo/d belong to a later batch. - maxConcurrentReads: 2, - onDirCommitted - }) - ).rejects.toBe(commitError) - - // Surviving workers must stop after rejection rather than commit later data/staleness writes. - expect(onDirCommitted.mock.calls.map(([dirPath]) => dirPath).sort()).toEqual([ - '/repo/a', - '/repo/b' - ]) - // One up-front placeholder write plus the single failed batch's result write. - expect(setDirCache).toHaveBeenCalledTimes(2) - // Unstarted reads cannot clear spinners later; clear their loading marks now. - expect(isLoading('/repo/c')).toBe(false) - expect(isLoading('/repo/d')).toBe(false) - }) -}) diff --git a/src/renderer/src/components/right-sidebar/file-explorer/watching/file-explorer-linked-recovery.test.tsx b/src/renderer/src/components/right-sidebar/file-explorer/watching/file-explorer-linked-recovery.test.tsx index f899053b38e..1c2346eb1ad 100644 --- a/src/renderer/src/components/right-sidebar/file-explorer/watching/file-explorer-linked-recovery.test.tsx +++ b/src/renderer/src/components/right-sidebar/file-explorer/watching/file-explorer-linked-recovery.test.tsx @@ -2,7 +2,7 @@ import { act, cleanup, renderHook } from '@testing-library/react' import { afterEach, expect, it, vi } from 'vitest' -import type { DirEntry } from '../../../../../../shared/filesystem-entry-types' +import type { DirEntry } from '../../../../../../shared/file-listing/directory-entry' import { useFileExplorerTree } from '../tree/useFileExplorerTree' const readDirectoryMock = vi.hoisted(() => vi.fn()) diff --git a/src/renderer/src/components/right-sidebar/file-explorer/watching/file-explorer-linked-watch.test.ts b/src/renderer/src/components/right-sidebar/file-explorer/watching/file-explorer-linked-watch.test.ts deleted file mode 100644 index 397558d047e..00000000000 --- a/src/renderer/src/components/right-sidebar/file-explorer/watching/file-explorer-linked-watch.test.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { Dispatch, SetStateAction } from 'react' -import type { FsChangeEvent } from '../../../../../../shared/filesystem-entry-types' -import type { DirCache, TreeNode } from '../tree/file-explorer-types' -import { processFileExplorerFsPayload } from './file-explorer-watch-reconcile' -import { createFileExplorerWatchRefreshScheduler } from './file-explorer-watch-refresh-scheduler' -import { joinPath } from '@/lib/path' - -function node(path: string, isDirectory = false, isSymlink = false): TreeNode { - return { path, name: path, relativePath: path, depth: 0, isDirectory, isSymlink } -} - -function fixture(root = '/repo') { - const link = joinPath(root, 'link') - let cache: Record = { - [root]: { children: [node(link, true, true)] }, - [link]: { children: [node(joinPath(link, 'old.ts'))] } - } - let selected: string | null = joinPath(link, 'old.ts') - const setDirCache: Dispatch>> = (value) => { - cache = typeof value === 'function' ? value(cache) : value - } - const setSelectedPath: Dispatch> = (value) => { - selected = typeof value === 'function' ? value(selected) : value - } - const refreshTree = vi.fn() - const refreshDir = vi.fn() - const process = (events: FsChangeEvent[], followSymlinks = true, eventRoot = root) => - processFileExplorerFsPayload({ - payload: { worktreePath: eventRoot, events }, - currentWorktreePath: root, - worktreeId: 'linked-watch', - cache, - expanded: new Set(), - followSymlinks, - setDirCache, - setSelectedPath, - refreshTree, - refreshDir - }) - return { root, link, cache, process, refreshTree, refreshDir, selected: () => selected } -} - -afterEach(() => vi.useRealTimers()) - -describe('linked-directory watcher invalidation', () => { - it('still clears a lexical deleted selection after a prior event requested full refresh', () => { - const f = fixture() - f.process([ - { kind: 'create', absolutePath: '/repo/target/new.ts' }, - { kind: 'delete', absolutePath: '/repo/link/old.ts' } - ]) - expect(f.refreshTree).toHaveBeenCalledOnce() - expect(f.selected()).toBeNull() - }) - - it('coalesces structural bursts and retains a second refresh while the first is in flight', async () => { - vi.useFakeTimers() - const f = fixture() - let complete: () => void = () => undefined - const firstRead = new Promise((resolve) => { - complete = resolve - }) - const refreshTree = vi.fn(async () => { - if (refreshTree.mock.calls.length === 1) { - await firstRead - } - return 'refreshed' as const - }) - const scheduler = createFileExplorerWatchRefreshScheduler({ - refreshTree, - refreshDir: async () => undefined, - isCoveredByFullRefresh: () => true, - dirConcurrency: 4 - }) - f.refreshTree.mockImplementation(scheduler.requestFullRefresh) - for (let i = 0; i < 100; i++) { - f.process([{ kind: 'create', absolutePath: `/repo/target/${i}` }]) - } - await vi.advanceTimersByTimeAsync(0) - expect(refreshTree).toHaveBeenCalledOnce() - f.process([{ kind: 'delete', absolutePath: '/repo/target/after-snapshot' }]) - complete() - await vi.advanceTimersByTimeAsync(1) - expect(refreshTree).toHaveBeenCalledTimes(2) - scheduler.cancel() - }) -}) diff --git a/src/renderer/src/components/right-sidebar/file-explorer/watching/file-explorer-watch-path.ts b/src/renderer/src/components/right-sidebar/file-explorer/watching/file-explorer-watch-path.ts index ca48c1b1050..13b7142df11 100644 --- a/src/renderer/src/components/right-sidebar/file-explorer/watching/file-explorer-watch-path.ts +++ b/src/renderer/src/components/right-sidebar/file-explorer/watching/file-explorer-watch-path.ts @@ -1,5 +1,6 @@ -import { joinPath, dirname, normalizeRelativePath } from '@/lib/path' +import { joinPath, dirname } from '@/lib/path' import { + normalizeRelativePath, isWindowsAbsolutePathLike, normalizeRuntimePathForComparison, relativePathInsideRoot diff --git a/src/renderer/src/components/right-sidebar/file-explorer/watching/file-explorer-watch-reconcile.ts b/src/renderer/src/components/right-sidebar/file-explorer/watching/file-explorer-watch-reconcile.ts index bcf0c64cec4..8284ed08cb0 100644 --- a/src/renderer/src/components/right-sidebar/file-explorer/watching/file-explorer-watch-reconcile.ts +++ b/src/renderer/src/components/right-sidebar/file-explorer/watching/file-explorer-watch-reconcile.ts @@ -1,5 +1,5 @@ import type { Dispatch, SetStateAction } from 'react' -import type { FsChangedPayload } from '../../../../../../shared/filesystem-entry-types' +import type { FsChangedPayload } from '../../../../../../shared/file-watch/filesystem-change-event' import type { DirCache, TreeNode } from '../tree/file-explorer-types' import { isPathInsideOrEqual, diff --git a/src/renderer/src/components/right-sidebar/file-explorer/watching/useFileExplorerTree.stale-dirs.test.tsx b/src/renderer/src/components/right-sidebar/file-explorer/watching/useFileExplorerTree.stale-dirs.test.tsx index 765b161bf7a..28da9498301 100644 --- a/src/renderer/src/components/right-sidebar/file-explorer/watching/useFileExplorerTree.stale-dirs.test.tsx +++ b/src/renderer/src/components/right-sidebar/file-explorer/watching/useFileExplorerTree.stale-dirs.test.tsx @@ -2,7 +2,7 @@ import { act, cleanup, renderHook } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { DirEntry } from '../../../../../../shared/filesystem-entry-types' +import type { DirEntry } from '../../../../../../shared/file-listing/directory-entry' import { useFileExplorerTree } from '../tree/useFileExplorerTree' const readDirectoryMock = vi.hoisted(() => vi.fn()) diff --git a/src/renderer/src/components/right-sidebar/file-explorer/watching/useFileExplorerWatch.ts b/src/renderer/src/components/right-sidebar/file-explorer/watching/useFileExplorerWatch.ts index f3fcd21d9ec..901c130d11c 100644 --- a/src/renderer/src/components/right-sidebar/file-explorer/watching/useFileExplorerWatch.ts +++ b/src/renderer/src/components/right-sidebar/file-explorer/watching/useFileExplorerWatch.ts @@ -2,8 +2,8 @@ import { useEffect, useRef, type Dispatch, type SetStateAction } from 'react' import type { FsChangedPayload, FsChangeEvent -} from '../../../../../../shared/filesystem-entry-types' -import { FileWatchEventBuffer } from '../../../../../../shared/filesystem-watch-event-buffer' +} from '../../../../../../shared/file-watch/filesystem-change-event' +import { FileWatchEventBuffer } from '../../../../../../shared/file-watch/filesystem-watch-event-buffer' import type { DirCache, FileExplorerOperationOwner, diff --git a/src/renderer/src/components/right-sidebar/source-control/listing/use-file-projection.ts b/src/renderer/src/components/right-sidebar/source-control/listing/use-file-projection.ts index e8e85f3a348..08d66e7eafd 100644 --- a/src/renderer/src/components/right-sidebar/source-control/listing/use-file-projection.ts +++ b/src/renderer/src/components/right-sidebar/source-control/listing/use-file-projection.ts @@ -2,7 +2,7 @@ import { useMemo } from 'react' import type { GitBranchChangeEntry } from '../../../../../../shared/git/diff/git-diff-compare-types' import type { GitStatusEntry } from '../../../../../../shared/git/status/git-status-types' import type { SourceControlViewMode } from '../../../../../../shared/ui-chrome-types' -import { compareFileNames } from '../../../../../../shared/file-name-sort' +import { compareFileNames } from '../../../../../../shared/file-listing/file-name-sort' import { filterSourceControlPathEntries, getSourceControlFileFilterState, diff --git a/src/renderer/src/components/right-sidebar/source-control/sync/git-status-file-watch-refresh.ts b/src/renderer/src/components/right-sidebar/source-control/sync/git-status-file-watch-refresh.ts index b00ad9b2982..3e6abeb58d6 100644 --- a/src/renderer/src/components/right-sidebar/source-control/sync/git-status-file-watch-refresh.ts +++ b/src/renderer/src/components/right-sidebar/source-control/sync/git-status-file-watch-refresh.ts @@ -7,7 +7,7 @@ import { normalizeRuntimePathForComparison, relativePathInsideRoot } from '../../../../../../shared/cross-platform-path' -import type { FsChangedPayload } from '../../../../../../shared/filesystem-entry-types' +import type { FsChangedPayload } from '../../../../../../shared/file-watch/filesystem-change-event' import type { ActiveRightSidebarTab, RightSidebarExplorerView diff --git a/src/renderer/src/components/settings/repository/mcp/McpConfigSection.tsx b/src/renderer/src/components/settings/repository/mcp/McpConfigSection.tsx index 173b1ca15bd..63a162c56e9 100644 --- a/src/renderer/src/components/settings/repository/mcp/McpConfigSection.tsx +++ b/src/renderer/src/components/settings/repository/mcp/McpConfigSection.tsx @@ -40,7 +40,7 @@ import { writeRuntimeFile } from '@/runtime/files/mutations/runtime-file-mutatio import { assertFileWriteApplied, missingOrIdenticalPrecondition -} from '../../../../../../shared/file-write-disk-precondition' +} from '../../../../../../shared/file-write/file-write-disk-precondition' import type { RuntimeFileOperationArgs } from '@/runtime/files/runtime-file-client-types' import { runtimeTargetForOwnerEnvironment } from '@/runtime/rpc/targets/runtime-client-target' import { selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields' diff --git a/src/renderer/src/components/sidebar/host-path-browser/RemoteFileBrowser.tsx b/src/renderer/src/components/sidebar/host-path-browser/RemoteFileBrowser.tsx index 6a5f8e4edea..abb8698d017 100644 --- a/src/renderer/src/components/sidebar/host-path-browser/RemoteFileBrowser.tsx +++ b/src/renderer/src/components/sidebar/host-path-browser/RemoteFileBrowser.tsx @@ -18,7 +18,7 @@ import { useRemoteFileBrowserFilterKeyCommands } from './use-remote-file-browser import { useRemoteFileBrowserListing } from './use-remote-file-browser-listing' import { useRemoteFileBrowserPathPreview } from './use-remote-file-browser-path-preview' import { useTranslate } from '@/i18n/use-translate' -import type { FilesystemPathFlavor } from '../../../../../shared/filesystem-entry-types' +import type { FilesystemPathFlavor } from '../../../../../shared/file-access/filesystem-path-flavor' // Both IDs select an SSH host owned and listed by the paired server. type RemoteFileBrowserProps = ( diff --git a/src/renderer/src/components/sidebar/host-path-browser/RemoteFileBrowserBreadcrumbs.tsx b/src/renderer/src/components/sidebar/host-path-browser/RemoteFileBrowserBreadcrumbs.tsx index bdd2d85ae33..46e912b8df2 100644 --- a/src/renderer/src/components/sidebar/host-path-browser/RemoteFileBrowserBreadcrumbs.tsx +++ b/src/renderer/src/components/sidebar/host-path-browser/RemoteFileBrowserBreadcrumbs.tsx @@ -2,7 +2,7 @@ import React, { useCallback } from 'react' import { ChevronRight, ArrowUp, Home } from 'lucide-react' import { cn } from '@/lib/utils' import { driveBreadcrumbPath, splitBrowsePath } from './remote-file-browser-drive-paths' -import type { FilesystemPathFlavor } from '../../../../../shared/filesystem-entry-types' +import type { FilesystemPathFlavor } from '../../../../../shared/file-access/filesystem-path-flavor' type RemoteFileBrowserBreadcrumbsProps = { resolvedPath: string diff --git a/src/renderer/src/components/sidebar/host-path-browser/remote-file-browser-drive-paths.ts b/src/renderer/src/components/sidebar/host-path-browser/remote-file-browser-drive-paths.ts index ae8ac260e04..aaf7a066251 100644 --- a/src/renderer/src/components/sidebar/host-path-browser/remote-file-browser-drive-paths.ts +++ b/src/renderer/src/components/sidebar/host-path-browser/remote-file-browser-drive-paths.ts @@ -59,4 +59,4 @@ export function driveBreadcrumbPath( const kept = segments.slice(0, endIndex + 1) return kept.length === 0 ? driveRoot : `${driveRoot}${kept.join('\\')}` } -import type { FilesystemPathFlavor } from '../../../../../shared/filesystem-entry-types' +import type { FilesystemPathFlavor } from '../../../../../shared/file-access/filesystem-path-flavor' diff --git a/src/renderer/src/components/sidebar/host-path-browser/remote-file-browser-entry-actions.ts b/src/renderer/src/components/sidebar/host-path-browser/remote-file-browser-entry-actions.ts index abee953e39c..7de2cd40d77 100644 --- a/src/renderer/src/components/sidebar/host-path-browser/remote-file-browser-entry-actions.ts +++ b/src/renderer/src/components/sidebar/host-path-browser/remote-file-browser-entry-actions.ts @@ -1,7 +1,7 @@ import { translate } from '@/i18n/i18n' import { shouldHandleTextControlPaste as isRemoteFileBrowserPathResolveTextTooLarge } from '@/lib/text-control-paste' import { isClipboardTextByteLengthOverLimit } from '../../../../../shared/clipboard-text' -import type { FilesystemPathFlavor } from '../../../../../shared/filesystem-entry-types' +import type { FilesystemPathFlavor } from '../../../../../shared/file-access/filesystem-path-flavor' import { driveRootOf, isDrivePath, diff --git a/src/renderer/src/components/sidebar/host-path-browser/remote-file-browser-path-preview-resolver.ts b/src/renderer/src/components/sidebar/host-path-browser/remote-file-browser-path-preview-resolver.ts index 91dcb2fa882..dcb0d16a5b9 100644 --- a/src/renderer/src/components/sidebar/host-path-browser/remote-file-browser-path-preview-resolver.ts +++ b/src/renderer/src/components/sidebar/host-path-browser/remote-file-browser-path-preview-resolver.ts @@ -7,7 +7,7 @@ import { type DirEntry } from './remote-file-browser-entry-actions' import type { FetchListing } from './use-remote-file-browser-listing' -import type { FilesystemPathFlavor } from '../../../../../shared/filesystem-entry-types' +import type { FilesystemPathFlavor } from '../../../../../shared/file-access/filesystem-path-flavor' export type PreviewState = { resolvedPath: string diff --git a/src/renderer/src/components/sidebar/host-path-browser/use-remote-file-browser-filter-key-commands.ts b/src/renderer/src/components/sidebar/host-path-browser/use-remote-file-browser-filter-key-commands.ts index c571fcbc615..95674d7d418 100644 --- a/src/renderer/src/components/sidebar/host-path-browser/use-remote-file-browser-filter-key-commands.ts +++ b/src/renderer/src/components/sidebar/host-path-browser/use-remote-file-browser-filter-key-commands.ts @@ -10,7 +10,7 @@ import { import { stepRemoteFileBrowserHighlight } from './remote-file-browser-highlight' import { isImeOwnedKeyboardEvent } from '@/lib/ime-composition-keyboard-event' import type { PreviewState } from './remote-file-browser-path-preview-resolver' -import type { FilesystemPathFlavor } from '../../../../../shared/filesystem-entry-types' +import type { FilesystemPathFlavor } from '../../../../../shared/file-access/filesystem-path-flavor' export type RemoteFileBrowserFilterKeyCommandsArgs = { loading: boolean diff --git a/src/renderer/src/components/sidebar/host-path-browser/use-remote-file-browser-listing.ts b/src/renderer/src/components/sidebar/host-path-browser/use-remote-file-browser-listing.ts index 198b8bc203e..c5129a75e33 100644 --- a/src/renderer/src/components/sidebar/host-path-browser/use-remote-file-browser-listing.ts +++ b/src/renderer/src/components/sidebar/host-path-browser/use-remote-file-browser-listing.ts @@ -2,7 +2,7 @@ import { useCallback, useRef, type RefObject } from 'react' import { browseRuntimeServerDirectory } from '@/runtime/files/reads/runtime-server-directory-browser' import { browseRuntimeSshDirectory } from '@/runtime/hosts/ssh/runtime-ssh-target-management' import type { DirEntry } from './remote-file-browser-entry-actions' -import type { FilesystemPathFlavor } from '../../../../../shared/filesystem-entry-types' +import type { FilesystemPathFlavor } from '../../../../../shared/file-access/filesystem-path-flavor' export type BrowseResult = { resolvedPath: string diff --git a/src/renderer/src/components/sidebar/host-path-browser/use-remote-file-browser-path-preview.ts b/src/renderer/src/components/sidebar/host-path-browser/use-remote-file-browser-path-preview.ts index ad1b63f1982..451d9c13003 100644 --- a/src/renderer/src/components/sidebar/host-path-browser/use-remote-file-browser-path-preview.ts +++ b/src/renderer/src/components/sidebar/host-path-browser/use-remote-file-browser-path-preview.ts @@ -19,7 +19,7 @@ import { type PreviewState } from './remote-file-browser-path-preview-resolver' import type { FetchListing } from './use-remote-file-browser-listing' -import type { FilesystemPathFlavor } from '../../../../../shared/filesystem-entry-types' +import type { FilesystemPathFlavor } from '../../../../../shared/file-access/filesystem-path-flavor' const PATH_DEBOUNCE_MS = 300 diff --git a/src/renderer/src/components/sidebar/project-admission/drop/useSidebarProjectDrop.ts b/src/renderer/src/components/sidebar/project-admission/drop/useSidebarProjectDrop.ts index 909e981d05c..8f1938609a8 100644 --- a/src/renderer/src/components/sidebar/project-admission/drop/useSidebarProjectDrop.ts +++ b/src/renderer/src/components/sidebar/project-admission/drop/useSidebarProjectDrop.ts @@ -1,6 +1,6 @@ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { toast } from 'sonner' -import { hasNativeFileDragTypes } from '../../../../../../shared/native-file-drop' +import { hasNativeFileDragTypes } from '../../../../../../shared/file-import/native-file-drop' import { createOsFileDropSequence, useOsFileDropOwner } from '@/hooks/use-os-file-drop-owner' import { getNativeFileDropRejectionMessage } from '@/lib/native-file-drop-rejection-message' import { useMountedRef } from '@/hooks/useMountedRef' diff --git a/src/renderer/src/components/sidebar/sidebar-feedback/use-feedback-image-drop.ts b/src/renderer/src/components/sidebar/sidebar-feedback/use-feedback-image-drop.ts index 96db751c8f0..53e4420fda9 100644 --- a/src/renderer/src/components/sidebar/sidebar-feedback/use-feedback-image-drop.ts +++ b/src/renderer/src/components/sidebar/sidebar-feedback/use-feedback-image-drop.ts @@ -1,6 +1,6 @@ import React, { useCallback, useEffect, useRef, useState } from 'react' -import { hasNativeFileDragTypes } from '../../../../../shared/native-file-drop' -import { OS_FILE_DROP_OWNER_ATTRIBUTE } from '../../../../../shared/native-file-drop-preparation' +import { hasNativeFileDragTypes } from '../../../../../shared/file-import/native-file-drop' +import { OS_FILE_DROP_OWNER_ATTRIBUTE } from '../../../../../shared/file-import/native-file-drop-preparation' import { extractImageFilesFromDataTransfer } from '@/lib/feedback-image-attachments' type FeedbackImageDragHandlers = { diff --git a/src/renderer/src/components/sidebar/workspace-actions/deletion/delete-worktree-dirty-change-counts.ts b/src/renderer/src/components/sidebar/workspace-actions/deletion/delete-worktree-dirty-change-counts.ts index 8924db17679..5de76b3bf39 100644 --- a/src/renderer/src/components/sidebar/workspace-actions/deletion/delete-worktree-dirty-change-counts.ts +++ b/src/renderer/src/components/sidebar/workspace-actions/deletion/delete-worktree-dirty-change-counts.ts @@ -6,7 +6,7 @@ import type { import type { Worktree } from '../../../../../../shared/worktree/types' import { getWorktreeHostIdentity } from '../../../../../../shared/worktree/host-qualified-identity' import type { WorktreeDeleteState } from '../../../../store/slices/worktrees/teardown/worktree-delete-state-types' -import { normalizeRelativePath } from '@/lib/path' +import { normalizeRelativePath } from '../../../../../../shared/cross-platform-path' import { buildStatusMap } from '../../../../lib/git-path-decoration' import { isFolderWorkspaceDelete } from './delete-worktree-dialog-copy' import { getDeleteStateForWorktreeHost } from './worktree-delete-state-host-match' diff --git a/src/renderer/src/components/sparse/sparse-directory-browse.ts b/src/renderer/src/components/sparse/sparse-directory-browse.ts index f1ef92aae5b..495d6c7bdcd 100644 --- a/src/renderer/src/components/sparse/sparse-directory-browse.ts +++ b/src/renderer/src/components/sparse/sparse-directory-browse.ts @@ -1,4 +1,4 @@ -import type { DirEntry } from '../../../../shared/filesystem-entry-types' +import type { DirEntry } from '../../../../shared/file-listing/directory-entry' const HIDDEN_BROWSE_DIRECTORIES = new Set(['.git', 'node_modules']) diff --git a/src/renderer/src/components/tab-bar/TabBarCreateEntry.tsx b/src/renderer/src/components/tab-bar/TabBarCreateEntry.tsx index 284a8463b0c..14fe0412324 100644 --- a/src/renderer/src/components/tab-bar/TabBarCreateEntry.tsx +++ b/src/renderer/src/components/tab-bar/TabBarCreateEntry.tsx @@ -29,7 +29,7 @@ import { DEFAULT_SEARCH_ENGINE } from '../../../../shared/browser-url' import { getRendererAppPlatform } from '@/lib/renderer-app-platform' import { useAppStore } from '@/store' import { useFileListWorktree } from '@/store/workspaces/selection/use-selected-worktree' -import { isQuickOpenQueryTooLarge } from '../quick-open-search' +import { isQuickOpenQueryTooLarge } from '../../../../shared/quick-open/quick-open-path-search' import { parseForcedSearchQuery } from './tab-create-entry-forced-search' import { useNetworkSafeTabEntrySelection } from './tab-create-entry-network-selection' import { focusTabEntryMenuItemAtEdge } from './tab-create-entry-keyboard-focus' diff --git a/src/renderer/src/components/tab-bar/open-tab-entry-dedupe.ts b/src/renderer/src/components/tab-bar/open-tab-entry-dedupe.ts index 0df7ddd8fa3..4c9c6b804b7 100644 --- a/src/renderer/src/components/tab-bar/open-tab-entry-dedupe.ts +++ b/src/renderer/src/components/tab-bar/open-tab-entry-dedupe.ts @@ -1,7 +1,9 @@ // Prefer switching to an open editor over reopening its on-disk file. -import { normalizeRelativePath } from '@/lib/path' -import { isCaseInsensitiveRuntimeRoot } from '../../../../shared/cross-platform-path' +import { + normalizeRelativePath, + isCaseInsensitiveRuntimeRoot +} from '../../../../shared/cross-platform-path' import { normalizeBrowserHistoryUrl } from '../../../../shared/workspace-session/workspace-session-browser-history' import type { OpenTabSearchResult } from './open-tab-search' import type { BrowserHistoryOmniboxRow } from './tab-create-entry-active-option' diff --git a/src/renderer/src/components/tab-bar/tab-bar-item-model.ts b/src/renderer/src/components/tab-bar/tab-bar-item-model.ts index 344a774212e..ed1d9f7e076 100644 --- a/src/renderer/src/components/tab-bar/tab-bar-item-model.ts +++ b/src/renderer/src/components/tab-bar/tab-bar-item-model.ts @@ -8,7 +8,7 @@ import type { Tab, WorkspaceVisibleTabType } from '../../../../shared/tab-types' import type { TerminalTab } from '../../../../shared/workspace-layout/terminal-tab-types' import { resolveTerminalTabTitle } from '../../../../shared/tab-title-resolution' import type { OpenFile } from '../../store/slices/editor/types/open-file' -import { normalizeRelativePath } from '@/lib/path' +import { normalizeRelativePath } from '../../../../shared/cross-platform-path' import { isVirtualEditorFile } from '@/store/slices/editor/tabs/editor-tab-content-type' import { tabItemLabel } from './tab-bar-item-label' import type { DropIndicator } from './drop-indicator' diff --git a/src/renderer/src/components/tab-bar/tab-create-entry-classifier.ts b/src/renderer/src/components/tab-bar/tab-create-entry-classifier.ts index e92eed58a1a..eb833edc35a 100644 --- a/src/renderer/src/components/tab-bar/tab-create-entry-classifier.ts +++ b/src/renderer/src/components/tab-bar/tab-create-entry-classifier.ts @@ -1,4 +1,7 @@ -import { getPreparedQuickOpenFiles, isQuickOpenQueryTooLarge } from '../quick-open-search' +import { + getPreparedQuickOpenFiles, + isQuickOpenQueryTooLarge +} from '../../../../shared/quick-open/quick-open-path-search' import type { RuntimeFileListState } from '../quick-open-file-list' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' @@ -17,7 +20,7 @@ import { validateNewTabEntryRelativePath } from './tab-create-entry-path-validation' import { classifyExplicitUrl, classifyHostUrl } from './tab-create-entry-url-classification' -import { htmlFilePathFromUrl } from '../../../../shared/html-file-url' +import { htmlFilePathFromUrl } from '../../../../shared/file-links/html-file-url' export { isTabEntryAbsolutePathLike, diff --git a/src/renderer/src/components/tab-bar/tab-create-entry-file-matches.ts b/src/renderer/src/components/tab-bar/tab-create-entry-file-matches.ts index 3ad562d15a0..984dc5df9b3 100644 --- a/src/renderer/src/components/tab-bar/tab-create-entry-file-matches.ts +++ b/src/renderer/src/components/tab-bar/tab-create-entry-file-matches.ts @@ -2,7 +2,7 @@ import { QuickOpenPathRanker, rankQuickOpenFiles, type QuickOpenIndexedFile -} from '../quick-open-search' +} from '../../../../shared/quick-open/quick-open-path-search' export type ExistingFileMatch = { kind: 'existing-file' diff --git a/src/renderer/src/components/terminal-pane/host-files/host-file-refusal.ts b/src/renderer/src/components/terminal-pane/host-files/host-file-refusal.ts index 34161592317..d13bbbd3c65 100644 --- a/src/renderer/src/components/terminal-pane/host-files/host-file-refusal.ts +++ b/src/renderer/src/components/terminal-pane/host-files/host-file-refusal.ts @@ -2,7 +2,7 @@ import { useAppStore } from '@/store/index' import { getRuntimeEnvironmentDisplayName } from '@/store/repos/owner-routing' import { translate } from '@/i18n/i18n' import { runtimeEnvironmentSupportsCapability } from '@/runtime/rpc/compatibility/runtime-capability-proof' -import { TERMINAL_PATH_ABSOLUTE_FILES_RUNTIME_CAPABILITY } from '../../../../../shared/runtime-file-contracts' +import { TERMINAL_PATH_ABSOLUTE_FILES_RUNTIME_CAPABILITY } from '../../../../../shared/terminal/runtime-terminal-file-path' /** The host answered: it has no file there this client may open. Transport failures stay other errors. */ export class HostFileRefusal extends Error {} diff --git a/src/renderer/src/components/terminal-pane/host-files/terminal-host-workspace-file.ts b/src/renderer/src/components/terminal-pane/host-files/terminal-host-workspace-file.ts index 1af37fbb798..1da0f1033ad 100644 --- a/src/renderer/src/components/terminal-pane/host-files/terminal-host-workspace-file.ts +++ b/src/renderer/src/components/terminal-pane/host-files/terminal-host-workspace-file.ts @@ -19,7 +19,7 @@ import { import { TERMINAL_PATH_CROSS_WORKSPACE_RUNTIME_CAPABILITY, type RuntimeTerminalPathResolution -} from '../../../../../shared/runtime-file-contracts' +} from '../../../../../shared/terminal/runtime-terminal-file-path' import { HostFileRefusal, hostAbsentRefusal } from './host-file-refusal' import { isHtmlFilePath } from '../links/files/local-html-file-destinations' import { diff --git a/src/renderer/src/components/terminal-pane/input/file-drop/terminal-pane-element-file-drop.test.tsx b/src/renderer/src/components/terminal-pane/input/file-drop/terminal-pane-element-file-drop.test.tsx deleted file mode 100644 index 293e2510889..00000000000 --- a/src/renderer/src/components/terminal-pane/input/file-drop/terminal-pane-element-file-drop.test.tsx +++ /dev/null @@ -1,374 +0,0 @@ -// @vitest-environment happy-dom -import { act, cleanup, render } from '@testing-library/react' -import { createPortal } from 'react-dom' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { isTerminalLeafId } from '../../../../../../shared/workspace-layout/stable-pane-id' - -import type { PreparedDroppedPaths } from '../../../../../../shared/native-file-drop-preparation' -import type { PaneManager } from '@/lib/pane-manager/pane-manager' -import type { ManagedPaneInternal } from '@/lib/pane-manager/pane-manager-types' -import { collectPublicPanes, toPublicPane } from '@/lib/pane-manager/pane-public-view' -import type { PtyTransport } from '../../pty-transport/pty-transport-types' -import type { TerminalPaneController } from '../../controller/use-terminal-pane-controller' -import { - NativeChatPaneFileDropSurface, - useNativeChatPaneFileDropClaim -} from '@/components/native-chat/attachments/intake/NativeChatPaneFileDropSurface' -import { TerminalPaneSurface } from '../../controller/TerminalPaneSurface' -import { installOsFileDropCancellationGuard } from '@/lib/os-file-drop-cancellation-guard' - -const mocks = vi.hoisted(() => ({ - state: { - settings: { activeRuntimeEnvironmentId: 'focused-runtime' }, - projects: [], - repos: [], - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Every fixture record has the declared catalog shape. - worktreesByRepo: {} as Record< - string, - { id: string; repoId: string; path: string; hostId: string }[] - >, - detectedWorktreesByRepo: {}, - folderWorkspaces: [], - sshConnectionStates: new Map([['target', { connectionGeneration: 4, remotePlatform: 'linux' }]]) - }, - prepare: vi.fn(), - importPaths: vi.fn(), - resolvePaths: vi.fn(), - chatDrop: vi.fn(), - toastError: vi.fn(), - legacyIpc: vi.fn(), - editorOpen: vi.fn(), - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The portal target starts absent and is assigned only a fixture pane container. - chatPane: null as HTMLElement | null, - chatDisabled: false -})) -vi.mock('electron', () => ({ - ipcRenderer: { on: vi.fn(), send: mocks.legacyIpc, removeListener: vi.fn() }, - webUtils: { getPathForFile: (file: File) => `/client/${file.name}` } -})) -vi.mock('@/store/index', () => ({ - useAppStore: Object.assign( - (selector: (state: typeof mocks.state) => T) => selector(mocks.state), - { getState: () => mocks.state } - ) -})) -vi.mock('@/runtime/files/imports/runtime-file-import-client', () => ({ - importExternalPathsToRuntime: mocks.importPaths -})) -vi.mock('@/lib/new-workspace', () => ({ CLIENT_PLATFORM: 'win32' })) -vi.mock('sonner', () => ({ - toast: { error: mocks.toastError, loading: vi.fn(), dismiss: vi.fn(), message: vi.fn() } -})) -vi.mock('../terminal-input-activity', () => ({ recordTerminalUserInputForLeaf: vi.fn() })) -vi.mock('@/components/ui/tooltip', () => ({ - Tooltip: ({ children }: { children: React.ReactNode }) => children, - TooltipTrigger: ({ children }: { children: React.ReactNode }) => children, - TooltipContent: () => null -})) -vi.mock('@/components/TerminalSearch', () => ({ default: () => null })) -vi.mock('@/components/shared/useDaemonActions', () => ({ DaemonActionDialog: () => null })) -vi.mock('@/components/agent-session-continuation/AgentSessionContinuationDialog', () => ({ - AgentSessionContinuationDialog: () => null -})) -vi.mock('../../layout/close/CloseTerminalDialog', () => ({ default: () => null })) -vi.mock('../../context-menu/TerminalContextMenu', () => ({ default: () => null })) -vi.mock('../../errors/TerminalErrorToast', () => ({ - TerminalErrorToast: () => null -})) -vi.mock('../../render-health/recovery/terminal-pane-recovery', () => ({ - requestTerminalPaneRecovery: vi.fn() -})) -vi.mock('../../layout/persistence/TerminalSessionStateSaveFailureDialog', () => ({ - TerminalSessionStateSaveFailureDialog: () => null -})) -vi.mock('@/components/link-actions/LinkActionPopover', () => ({ LinkActionPopover: () => null })) -vi.mock('../../session-fork/TerminalAgentSessionForkDialog', () => ({ - TerminalAgentSessionForkDialog: () => null -})) -vi.mock('../../session-restore/SessionRestoredBannerPortals', () => ({ - SessionRestoredBannerPortals: () => null -})) -vi.mock('../../../orchestration-crew/TerminalCrewPortals', () => ({ - TerminalCrewPortals: () => null -})) -vi.mock('../../quick-commands/TerminalQuickCommandEditorDialog', () => ({ - TerminalQuickCommandEditorDialog: () => null -})) -vi.mock('../../pty-transport/remote-runtime/recovery/TerminalPaneRecoveryPortals', () => ({ - TerminalPaneRecoveryPortals: () => null -})) -vi.mock('../../controller/TerminalPaneCodexRestartPortals', () => ({ - TerminalPaneCodexRestartPortals: () => null -})) -vi.mock('../../mobile-driver/TerminalPaneMobileDriverPortals', () => ({ - TerminalPaneMobileDriverPortals: () => null -})) -vi.mock('../../process-exit/TerminalPaneProcessExitPortals', () => ({ - TerminalPaneProcessExitPortals: () => null -})) -vi.mock('../../pty-transport/recovery/ssh/TerminalPaneSshReconnectPortals', () => ({ - TerminalPaneSshReconnectPortals: () => null -})) - -function ChatClaim(): null { - useNativeChatPaneFileDropClaim({ - disabled: mocks.chatDisabled, - destinationKey: 'chat-A', - captureExternalDrop: () => mocks.chatDrop, - onDragOverCapture: vi.fn(), - onDropCapture: vi.fn() - }) - return null -} -vi.mock('../../chat/TerminalPaneNativeChatPortal', () => ({ - TerminalPaneNativeChatPortal: () => - mocks.chatPane && - createPortal( - - - - , - mocks.chatPane - ) -})) - -function makePane(id: number): ManagedPaneInternal { - const leafId = `00000000-0000-4000-8000-00000000000${id}` - if (!isTerminalLeafId(leafId)) { - throw new Error('Invalid fixture leaf') - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The surface reads identity, DOM container, and terminal focus; add-ons are mocked out. - return { - id, - leafId, - stablePaneId: leafId, - container: document.createElement('div'), - terminal: { focus: vi.fn() } - } as unknown as ManagedPaneInternal -} - -function mountSurface( - options: { - chat?: boolean - hidden?: 'display' | 'inert' - host?: string - runtime?: string - cwd?: string - worktreeId?: string - } = {} -) { - const internalPanes = [makePane(1), makePane(2)] - const paneRecords = new Map(internalPanes.map((pane) => [pane.id, pane])) - const getPanes = () => collectPublicPanes(paneRecords, paneRecords.size) - const panes = getPanes() - const sends = panes.map(() => vi.fn(() => true)) - const ptyIds = ['pty-A', 'pty-B'] - const transports = new Map() - panes.forEach((pane, index) => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This fixture supplies every transport method used by file drop capture and writes. - transports.set(pane.id, { - sendInput: sends[index], - getPtyId: () => ptyIds[index], - isConnected: () => true, - getExecutionHostId: () => options.host ?? 'local', - getRuntimeEnvironmentId: () => options.runtime ?? null - } as unknown as PtyTransport) - }) - const active = internalPanes[1] - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The surface and drop handlers only enumerate panes and read active identity. - const manager = { getPanes, getActivePane: () => toPublicPane(active) } as unknown as PaneManager - const divider = document.createElement('div') - const activate = vi.fn() - mocks.chatPane = options.chat ? panes[0].container : null - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: All live surface fields are supplied; unrelated dialogs and controller operations are mocked out. - const controller = { - activePane: active, - managedPanes: panes, - managerRef: { current: manager }, - paneTransportsRef: { current: transports }, - tabId: 'tab-1', - worktreeId: options.worktreeId ?? 'wt-1', - cwd: options.cwd, - isActive: true, - terminalContentVisible: true, - hiddenStartupStyle: {}, - terminalContainerStyle: {}, - paneCount: 2, - paneTitles: { 1: 'A', 2: 'B' }, - paneTitleOverlayRects: { - 1: { left: 0, top: 0, width: 200 }, - 2: { left: 220, top: 0, width: 200 } - }, - renamingPaneId: null, - activeAgentId: null, - renameInputRef: { current: null }, - paneTitleBackground: 'transparent', - activatePaneTitleInteraction: activate, - contextMenu: {}, - daemonActions: {}, - sessionRestoredBannerPaneIds: [], - setContainerRef: (root: HTMLElement | null) => - root?.append(panes[0].container, divider, panes[1].container) - } as unknown as TerminalPaneController - const view = render( -
- -
- ) - const titles = view.container.querySelectorAll('.pane-title-bar') - return { - view, - panes, - sends, - manager, - activate, - transports, - ptyIds, - divider, - title: titles[0], - body: panes[0].container, - replacePaneContainer: () => { - paneRecords.set(panes[0].id, { - ...internalPanes[0], - container: document.createElement('div') - }) - } - } -} - -function drop(target: Element, name = 'file.txt') { - const event = new Event('drop', { bubbles: true, cancelable: true, composed: true }) - Object.defineProperty(event, 'isTrusted', { value: true }) - Object.defineProperty(event, 'dataTransfer', { - value: { types: ['Files'], files: [new File([], name)], dropEffect: 'move' } - }) - act(() => { - target.dispatchEvent(event) - }) - return event -} -async function settle(): Promise { - await act(async () => undefined) -} - -let disposeGuard: (() => void) | undefined -beforeEach(() => { - vi.clearAllMocks() - disposeGuard = installOsFileDropCancellationGuard() - mocks.legacyIpc.mockImplementation((_channel: string, payload: { target: string }) => { - if (payload.target === 'editor') { - mocks.editorOpen() - } - }) - mocks.chatPane = null - mocks.chatDisabled = false - mocks.state.worktreesByRepo = { - repo: [{ id: 'wt-1', repoId: 'repo', path: '/owner/workspace', hostId: 'local' }] - } - mocks.prepare.mockImplementation(async ({ paths }: { paths: string[] }) => ({ - paths, - failures: [] - })) - mocks.resolvePaths.mockResolvedValue({ - resolvedPaths: ['/host/file.txt'], - skipped: [], - failed: [] - }) - mocks.importPaths.mockResolvedValue({ - results: [{ status: 'imported', destPath: '/owner/workspace/.orca/drops/file.txt' }] - }) - vi.stubGlobal('api', { - fs: { - getPathForFile: (file: File) => `/client/${file.name}`, - prepareDroppedPaths: mocks.prepare, - resolveDroppedPathsForAgent: mocks.resolvePaths - } - }) -}) -afterEach(() => { - disposeGuard?.() - cleanup() - vi.unstubAllGlobals() -}) - -describe('terminal element file drops', () => { - it.each(['title', 'body'] as const)( - 'refuses delivery from %s when its container is replaced during preparation', - async (root) => { - let finish: ((prepared: PreparedDroppedPaths) => void) | undefined - mocks.prepare.mockImplementationOnce( - () => - new Promise((resolve) => { - finish = resolve - }) - ) - const fixture = mountSurface() - drop(fixture[root]) - expect(mocks.prepare).toHaveBeenCalledOnce() - fixture.replacePaneContainer() - await act(async () => { - finish?.({ paths: ['/client/file.txt'], failures: [] }) - }) - expect(fixture.sends[0]).not.toHaveBeenCalled() - expect(fixture.sends[1]).not.toHaveBeenCalled() - } - ) - it('shares ordering across title and body during delayed preparation', async () => { - let finish: ((prepared: PreparedDroppedPaths) => void) | undefined - mocks.prepare.mockImplementationOnce( - () => - new Promise((resolve) => { - finish = resolve - }) - ) - const fixture = mountSurface() - drop(fixture.title, 'first.txt') - drop(fixture.body, 'second.txt') - await settle() - expect(fixture.sends[0]).not.toHaveBeenCalled() - await act(async () => { - finish?.({ paths: ['/prepared/first.txt'], failures: [] }) - }) - expect(fixture.sends[0].mock.calls).toEqual([ - ['/prepared/first.txt ', 'driving'], - ['/client/second.txt ', 'driving'] - ]) - }) - it.each([false, true])( - 'keeps nested chat drops out of terminal (disabled=%s)', - async (disabled) => { - mocks.chatDisabled = disabled - const fixture = mountSurface({ chat: true }) - drop(fixture.view.getByTestId('chat-target')) - await settle() - expect(mocks.chatDrop).toHaveBeenCalledTimes(disabled ? 0 : 1) - expect(fixture.sends[0]).not.toHaveBeenCalled() - drop(fixture.body) - await settle() - expect(fixture.sends[0]).toHaveBeenCalledExactlyOnceWith('/client/file.txt ', 'driving') - expect(mocks.chatDrop).toHaveBeenCalledTimes(disabled ? 0 : 1) - } - ) - it('captures the PTY before preparation and refuses a replacement', async () => { - let finish: ((prepared: PreparedDroppedPaths) => void) | undefined - mocks.prepare.mockImplementationOnce( - () => - new Promise((resolve) => { - finish = resolve - }) - ) - const fixture = mountSurface() - drop(fixture.title) - fixture.ptyIds[0] = 'replacement' - await act(async () => { - finish?.({ paths: ['/client/file.txt'], failures: [] }) - }) - expect(fixture.sends[0]).not.toHaveBeenCalled() - drop(fixture.body) - await settle() - expect(fixture.sends[0]).toHaveBeenCalledOnce() - }) -}) diff --git a/src/renderer/src/components/terminal-pane/links/files/terminal-link-provider-link-detection.test.ts b/src/renderer/src/components/terminal-pane/links/files/terminal-link-provider-link-detection.test.ts index 9a287aa5808..8f0166502ce 100644 --- a/src/renderer/src/components/terminal-pane/links/files/terminal-link-provider-link-detection.test.ts +++ b/src/renderer/src/components/terminal-pane/links/files/terminal-link-provider-link-detection.test.ts @@ -3,8 +3,7 @@ import { describe, expect, it, vi } from 'vitest' import type { PaneManager } from '@/lib/pane-manager/pane-manager' import { createFilePathLinkProvider } from './terminal-link-handlers' import { getTerminalFileOpenHint } from '../terminal-link-open-hints' -import type { TerminalPathExistsCache } from './terminal-path-exists-cache' -import { RECENT_PATH_ANSWERS_MAX } from '../../../../../../shared/recent-path-answers' + import { getConnectionId } from '@/lib/connection-context' import { createTerminalLinkTestDoubles } from '../terminal-link-handlers-test-fixtures' import { @@ -75,107 +74,6 @@ describe('createFilePathLinkProvider range bounds', () => { await vi.waitFor(() => expect(callback).toHaveBeenCalledTimes(1)) }) - it('bounds the terminal path-exists cache while preserving recent probes', async () => { - const pathExistsCache = makeExistsCache() - for (let index = 0; index < RECENT_PATH_ANSWERS_MAX; index += 1) { - pathExistsCache.set(`active\0/repo/old-${index}.ts`, { - exists: true, - checkedAt: Date.now(), - sequence: 0 - }) - } - const pane = makePane([makeBufferLine('fresh.ts')]) - const managerRef = { - current: { getPanes: () => [pane] } as unknown as PaneManager - } - const provider = createFilePathLinkProvider( - 1, - { - worktreeId: 'wt-1', - worktreePath: '/repo', - startupCwd: '/repo', - managerRef, - linkProviderDisposablesRef: { current: new Map() }, - pathExistsCache - }, - { textContent: '', style: { display: '' } } as unknown as HTMLElement, - getTerminalFileOpenHint() - ) - - const links = await new Promise((resolve) => { - provider.provideLinks(1, (provided) => resolve(provided ?? [])) - }) - - expect(links.map((link) => link.text)).toEqual(['fresh.ts']) - expect(pathExistsCache.size).toBe(RECENT_PATH_ANSWERS_MAX) - expect(pathExistsCache.has('active\0/repo/old-0.ts')).toBe(false) - expect(pathExistsCache.get('active\0/repo/fresh.ts')?.exists).toBe(true) - }) - - it('expires a cached missing path even when the provider scans it repeatedly', async () => { - const now = vi.spyOn(Date, 'now').mockReturnValue(5_000) - const cacheKey = 'active\0/repo/eventually-created.ts' - const pathExistsCache: TerminalPathExistsCache = new Map([ - [cacheKey, { exists: false, checkedAt: 1_000, sequence: 0 }] - ]) - const { provider } = createProviderSetup( - [makeBufferLine('eventually-created.ts')], - pathExistsCache - ) - - const firstLinks = await new Promise((resolve) => { - provider.provideLinks(1, (provided) => resolve(provided ?? [])) - }) - expect(firstLinks).toEqual([]) - expect(window.api.shell.pathExists).not.toHaveBeenCalled() - expect(pathExistsCache.get(cacheKey)?.checkedAt).toBe(1_000) - - now.mockReturnValue(11_000) - const refreshedLinks = await new Promise((resolve) => { - provider.provideLinks(1, (provided) => resolve(provided ?? [])) - }) - - expect(refreshedLinks.map((link) => link.text)).toEqual(['eventually-created.ts']) - expect(window.api.shell.pathExists).toHaveBeenCalledOnce() - expect(pathExistsCache.get(cacheKey)).toMatchObject({ exists: true, checkedAt: 11_000 }) - now.mockRestore() - }) - - it.each([12_000, 11_000])( - 'keeps a newer found result when an older missing probe resolves last (newer starts at %i)', - async (newerStartedAt) => { - const now = vi.spyOn(Date, 'now').mockReturnValue(11_000) - const cacheKey = 'active\0/repo/eventually-created.ts' - const pathExistsCache: TerminalPathExistsCache = new Map() - const { provider } = createProviderSetup( - [makeBufferLine('eventually-created.ts')], - pathExistsCache - ) - const olderProbe = createDeferred() - vi.mocked(window.api.shell.pathExists) - .mockImplementationOnce(() => olderProbe.promise) - .mockResolvedValueOnce(true) - - const olderLinks = new Promise((resolve) => { - provider.provideLinks(1, (provided) => resolve(provided ?? [])) - }) - await flushAsyncWork() - now.mockReturnValue(newerStartedAt) - const newerLinks = await new Promise((resolve) => { - provider.provideLinks(1, (provided) => resolve(provided ?? [])) - }) - olderProbe.resolve(false) - - expect(await olderLinks).toEqual([]) - expect(newerLinks.map((link) => link.text)).toEqual(['eventually-created.ts']) - expect(pathExistsCache.get(cacheKey)).toMatchObject({ - exists: true, - checkedAt: newerStartedAt - }) - now.mockRestore() - } - ) - it('does not reuse SSH path-exists cache entries across connections', async () => { setPlatform('Macintosh') const pathExistsCache = makeExistsCache() @@ -278,71 +176,6 @@ describe('createFilePathLinkProvider range bounds', () => { }) }) - it('returns the same wrapped file link when hovering the continuation row', async () => { - const rows = [ - makeBufferLine('open src/components/'), - makeBufferLine('terminal-link-handlers.ts', { isWrapped: true }) - ] - - const firstRowLinks = await collectLinks(rows, 1) - const continuationLinks = await collectLinks(rows, 2) - const firstRowLink = firstRowLinks.find( - (candidate) => candidate.text === 'src/components/terminal-link-handlers.ts' - ) - const continuationLink = continuationLinks.find( - (candidate) => candidate.text === 'src/components/terminal-link-handlers.ts' - ) - - expect( - continuationLink, - 'wrapped path should be linkified from the continuation row' - ).toBeDefined() - expect(continuationLink!.text).toBe(firstRowLink!.text) - expect(continuationLink!.range).toEqual(firstRowLink!.range) - }) - - it('returns all three sibling links and the same boundary link from either row over SSH', async () => { - const firstPath = 'validation-screenshots/01-before-white-terminal-scrollbar-gutter.png' - const middleStart = 'validation-screenshots/02-after-' - const middleEnd = 'transparent-terminal-scrollbar-gutter.png' - const middlePath = middleStart + middleEnd - const thirdPath = 'validation-screenshots/03-after-light-theme.png' - const rows = [ - makeBufferLine(`${firstPath} · ${middleStart}`), - makeBufferLine(`${middleEnd} · ${thirdPath}`) - ] - const completePaths = new Set([firstPath, middlePath, thirdPath].map((path) => `/repo/${path}`)) - vi.mocked(getConnectionId).mockReturnValue('ssh-wrapped') - fsPathExistsMock.mockImplementation(async ({ filePath }) => completePaths.has(filePath)) - const { provider } = createProviderSetup(rows, new Map()) - const provide = (line: number): Promise => - new Promise((resolve) => provider.provideLinks(line, (links) => resolve(links ?? []))) - - const firstRowLinks = await provide(1) - const secondRowLinks = await provide(2) - const firstMiddle = firstRowLinks.find((link) => link.text === middlePath) - const secondMiddle = secondRowLinks.find((link) => link.text === middlePath) - - expect(firstRowLinks.map((link) => link.text)).toEqual([firstPath, middlePath]) - expect(secondRowLinks.map((link) => link.text)).toEqual([middlePath, thirdPath]) - expect(new Set([...firstRowLinks, ...secondRowLinks].map((link) => link.text))).toEqual( - new Set([firstPath, middlePath, thirdPath]) - ) - expect(firstMiddle?.range).toEqual({ - start: { x: firstPath.length + ' · '.length + 1, y: 1 }, - end: { x: middleEnd.length, y: 2 } - }) - expect(secondMiddle?.range).toEqual(firstMiddle?.range) - expect([...firstRowLinks, ...secondRowLinks].every((link) => !link.text.includes(' · '))).toBe( - true - ) - expect(fsPathExistsMock).toHaveBeenCalledWith({ - filePath: `/repo/${middlePath}`, - connectionId: 'ssh-wrapped' - }) - expect(window.api.shell.pathExists).not.toHaveBeenCalled() - }) - it('maps file link columns through multi-code-unit characters before the path', async () => { const text = 'e\u0301 src/main.ts' const columns = [0, 0, 1] diff --git a/src/renderer/src/components/terminal-pane/links/files/terminal-path-existence-batch.ts b/src/renderer/src/components/terminal-pane/links/files/terminal-path-existence-batch.ts index 10c4ed404c6..05599078f02 100644 --- a/src/renderer/src/components/terminal-pane/links/files/terminal-path-existence-batch.ts +++ b/src/renderer/src/components/terminal-pane/links/files/terminal-path-existence-batch.ts @@ -1,7 +1,7 @@ import { createPathExistenceBatch, type PathExistenceResult -} from '../../../../../../shared/path-existence-batch' +} from '../../../../../../shared/file-access/path-existence-batch' import type { RuntimeFileOperationArgs } from '@/runtime/files/runtime-file-client-types' import { runtimePathsExist } from '@/runtime/files/metadata/runtime-path-existence-batch' import { captureRuntimeEnvironmentRequestRevision } from '@/runtime/rpc/environment-revisions/runtime-environment-revision' diff --git a/src/renderer/src/components/terminal-pane/links/files/terminal-path-exists-cache.test.ts b/src/renderer/src/components/terminal-pane/links/files/terminal-path-exists-cache.test.ts index 478c99a8a93..7a42728f677 100644 --- a/src/renderer/src/components/terminal-pane/links/files/terminal-path-exists-cache.test.ts +++ b/src/renderer/src/components/terminal-pane/links/files/terminal-path-exists-cache.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { RECENT_PATH_ANSWERS_MAX } from '../../../../../../shared/recent-path-answers' + import { readTerminalPathExistence, startTerminalPathExistsProbe, @@ -46,18 +46,4 @@ describe('terminal path-exists cache', () => { writeTerminalPathExistence(cache, 'older-first', true, newer) expect(cache.get('older-first')).toEqual({ exists: true, ...newer }) }) - - it('bounds the cache to the max entry count, evicting the oldest', () => { - const cache: TerminalPathExistsCache = new Map() - for (let i = 0; i < RECENT_PATH_ANSWERS_MAX; i++) { - writeTerminalPathExistence(cache, `k-${i}`, true, startTerminalPathExistsProbe(1)) - } - expect(cache.size).toBe(RECENT_PATH_ANSWERS_MAX) - expect(readTerminalPathExistence(cache, 'k-0', 2)).toBe(true) - writeTerminalPathExistence(cache, 'k-fresh', true, startTerminalPathExistsProbe(2)) - expect(cache.size).toBe(RECENT_PATH_ANSWERS_MAX) - expect(cache.has('k-0')).toBe(true) - expect(cache.has('k-1')).toBe(false) - expect(cache.has('k-fresh')).toBe(true) - }) }) diff --git a/src/renderer/src/components/terminal-pane/links/files/terminal-path-exists-cache.ts b/src/renderer/src/components/terminal-pane/links/files/terminal-path-exists-cache.ts index e66134133c4..b68b7750715 100644 --- a/src/renderer/src/components/terminal-pane/links/files/terminal-path-exists-cache.ts +++ b/src/renderer/src/components/terminal-pane/links/files/terminal-path-exists-cache.ts @@ -1,7 +1,7 @@ import { readRecentPathAnswer, writeRecentPathAnswer -} from '../../../../../../shared/recent-path-answers' +} from '../../../../../../shared/file-links/recent-path-answers' const NEGATIVE_PATH_EXISTS_TTL_MS = 10_000 diff --git a/src/renderer/src/components/terminal-pane/links/terminal-link-paired-click-fallback.test.ts b/src/renderer/src/components/terminal-pane/links/terminal-link-paired-click-fallback.test.ts index beaa83535a2..9b86863cf1a 100644 --- a/src/renderer/src/components/terminal-pane/links/terminal-link-paired-click-fallback.test.ts +++ b/src/renderer/src/components/terminal-pane/links/terminal-link-paired-click-fallback.test.ts @@ -1,4 +1,4 @@ -import type { PathExistenceResult } from '../../../../../shared/path-existence-batch' +import type { PathExistenceResult } from '../../../../../shared/file-access/path-existence-batch' import { describe, expect, it, vi } from 'vitest' import { getConnectionId } from '@/lib/connection-context' import { openFilePathLinkAtBufferPosition } from './files/terminal-file-link-hit-testing' @@ -123,91 +123,6 @@ describe('a modifier-click on a paired-server path followed by more paths', () = expect(onOpenFailure).not.toHaveBeenCalled() }) - it('remembers an older host ENOTDIR answer as missing, so the next click does not re-ask', async () => { - setPlatform('Macintosh') - hostAnswers((path) => (path === 'a.txt' ? { exists: true } : { error: OLD_HOST_ENOTDIR })) - // Why: hovering underlined a.txt, so only the longer joined guesses are unchecked. - const pathExistsCache = makeExistsCache([[runtimeKey('/srv/repo/a.txt'), true]]) - - clickFirstPath(vi.fn(), pathExistsCache) - await flushDoubleRaf() - runtimeEnvironmentCallMock.mockClear() - clickFirstPath(vi.fn(), pathExistsCache) - await flushDoubleRaf() - - expect(runtimeEnvironmentCallMock).not.toHaveBeenCalledWith( - expect.objectContaining({ method: 'files.pathsExist' }) - ) - expect(openFileMock).toHaveBeenCalledTimes(2) - expect(openFileMock).toHaveBeenLastCalledWith( - expect.objectContaining({ filePath: '/srv/repo/a.txt' }), - { forceContentReload: true } - ) - }) - - it('drops a slow ambiguous probe once a later click has opened something else', async () => { - setPlatform('Macintosh') - const firstProbe = createDeferred() - vi.mocked(window.api.shell.pathExists).mockImplementation(async (path: string) => - path === '/repo/a.txt' ? firstProbe.promise : false - ) - const buffer = makeBuffer([ - makeBufferLine('/repo/a.txt'), - makeBufferLine('/repo/b.txt'), - makeBufferLine(''), - makeBufferLine('package.json') - ]) - const deps = { startupCwd: '/repo', worktreeId: 'wt-1', worktreePath: '/repo' } - - openFilePathLinkAtBufferPosition(buffer, { x: 4, y: 1 }, 80, deps) - // Why: a lone candidate opens without probing, and must still cancel the pending probe. - openFilePathLinkAtBufferPosition(buffer, { x: 4, y: 4 }, 80, deps) - firstProbe.resolve(true) - await flushAsyncWork() - - expect(statMock).toHaveBeenCalledTimes(1) - expect(statMock).toHaveBeenCalledWith({ filePath: '/repo/package.json', wakeWslDistro: true }) - }) - - it('checks a longer hard-wrapped name before opening its cached prefix', async () => { - setPlatform('Macintosh') - vi.mocked(window.api.shell.pathExists).mockImplementation( - async (path: string) => path === '/repo/foo.ts.map' - ) - const buffer = makeBuffer([makeBufferLine('/repo/foo.ts'), makeBufferLine('.map')]) - const pathExistsCache = makeExistsCache([ - [getTerminalPathExistsCacheKey({ absolutePath: '/repo/foo.ts' }), true] - ]) - const deps = { startupCwd: '/repo', worktreeId: 'wt-1', worktreePath: '/repo', pathExistsCache } - - openFilePathLinkAtBufferPosition(buffer, { x: 4, y: 1 }, 80, deps) - await flushAsyncWork() - - expect(statMock).toHaveBeenCalledTimes(1) - expect(statMock).toHaveBeenCalledWith({ filePath: '/repo/foo.ts.map', wakeWslDistro: true }) - }) - - it('drops a slow ambiguous probe once any other file open has started', async () => { - setPlatform('Macintosh') - const probe = createDeferred() - vi.mocked(window.api.shell.pathExists).mockImplementation(() => probe.promise) - const deps = { startupCwd: '/repo', worktreeId: 'wt-1', worktreePath: '/repo' } - - openFilePathLinkAtBufferPosition( - makeBuffer([makeBufferLine('/repo/a.txt'), makeBufferLine('/repo/b.txt')]), - { x: 4, y: 1 }, - 80, - deps - ) - // Why: e.g. a chat link or the link popover, which never passes through the click fallback. - openDetectedFilePath('/repo/other.txt', null, null, deps) - probe.resolve(true) - await flushAsyncWork() - - expect(statMock).toHaveBeenCalledTimes(1) - expect(statMock).toHaveBeenCalledWith({ filePath: '/repo/other.txt', wakeWslDistro: true }) - }) - it('supersedes an earlier open still in flight as soon as an ambiguous click starts', async () => { setPlatform('Macintosh') const earlierStat = createDeferred<{ isDirectory: boolean }>() diff --git a/src/renderer/src/hooks/composer-drop-result.ts b/src/renderer/src/hooks/composer-drop-result.ts index dd7334b98db..17b4b7c76bd 100644 --- a/src/renderer/src/hooks/composer-drop-result.ts +++ b/src/renderer/src/hooks/composer-drop-result.ts @@ -1,4 +1,4 @@ -import type { ImportSkipReason } from '../../../shared/filesystem-import-result-types' +import type { ImportSkipReason } from '../../../shared/file-import/filesystem-import-result' export type ComposerDropItemResult = | { diff --git a/src/renderer/src/hooks/composer-state/composer-remote-server-drop.test.tsx b/src/renderer/src/hooks/composer-state/composer-remote-server-drop.test.tsx deleted file mode 100644 index 9e269c1a244..00000000000 --- a/src/renderer/src/hooks/composer-state/composer-remote-server-drop.test.tsx +++ /dev/null @@ -1,221 +0,0 @@ -// @vitest-environment happy-dom - -import { act, renderHook } from '@testing-library/react' -import { createRef } from 'react' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { replaceRuntimeEnvironmentRevisions } from '@/runtime/rpc/environment-revisions/runtime-environment-revision' -import { - clearRuntimeCompatibilityCache as clearRuntimeCompatibilityCacheForTests, - markRuntimeEnvironmentCompatible -} from '@/runtime/rpc/compatibility/runtime-compatibility-cache' -import { - clearRuntimeEnvironmentConnectionGenerations as clearRuntimeEnvironmentConnectionGenerationsForTests, - setRuntimeEnvironmentConnectionGenerationForTests -} from '@/store/slices/runtime-status/runtime-status-connection-generation' -import { - FILE_MUTATION_OWNERSHIP_RUNTIME_CAPABILITY, - MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION, - RUNTIME_PROTOCOL_VERSION -} from '../../../../shared/protocol-version' -import { resolveComposerAttachmentTarget } from './composer-attachment-target' -import { useAttachmentDropState } from './attachment-drop-state' - -const toastError = vi.hoisted(() => vi.fn()) -vi.mock('sonner', () => ({ toast: { error: toastError, message: vi.fn() } })) -vi.mock('@/store', () => ({ - useAppStore: Object.assign(() => undefined, { getState: () => ({}) }) -})) - -const ENVIRONMENT_ID = 'paired-server' -const REPO = { id: 'repo-1', path: '/srv/repo' } -const WORKTREE_SELECTOR = 'id:repo-1::/srv/repo' - -type RuntimeCall = { - selector: string - method: string - params: { worktree?: string; relativePath?: string; finalRelativePath?: string } -} - -/** A paired server that resolves files.* only by a registered worktree id, like the real one. */ -function installPairedServer(options: { onUpload?: () => void } = {}) { - const files = new Set() - const calls: RuntimeCall[] = [] - const meta = { runtimeId: 'server-runtime' } - const call = vi.fn(async (args: RuntimeCall) => { - calls.push(args) - if (args.method === 'status.get') { - return { - id: args.method, - ok: true, - result: { - runtimeId: 'server-runtime', - runtimeProtocolVersion: RUNTIME_PROTOCOL_VERSION, - minCompatibleRuntimeClientVersion: MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION, - capabilities: [FILE_MUTATION_OWNERSHIP_RUNTIME_CAPABILITY] - }, - _meta: meta - } - } - if (args.params.worktree !== WORKTREE_SELECTOR) { - return { - id: args.method, - ok: false, - error: { code: 'selector_not_found', message: 'selector_not_found' }, - _meta: meta - } - } - const relativePath = args.params.relativePath ?? '' - if (args.method === 'files.stat') { - return files.has(relativePath) - ? { id: args.method, ok: true, result: { type: 'file', size: 1, mtime: 0 }, _meta: meta } - : { - id: args.method, - ok: false, - error: { code: 'not_found', message: 'not found' }, - _meta: meta - } - } - if (args.method === 'files.createDir') { - files.add(relativePath) - } - if (args.method === 'files.commitUpload') { - files.add(args.params.finalRelativePath ?? '') - } - return { id: args.method, ok: true, result: { ok: true }, _meta: meta } - }) - const upload = vi.fn(async () => { - options.onUpload?.() - return { byteLength: 1 } - }) - const stage = vi.fn(async ({ sourcePaths }: { sourcePaths: string[] }) => ({ - sources: sourcePaths.map((sourcePath) => ({ - sourcePath, - status: 'staged', - name: sourcePath.slice(sourcePath.lastIndexOf('/') + 1), - kind: 'file', - entries: [ - { relativePath: '', kind: 'file', byteLength: 1, inode: 1, deviceId: 1, modifiedAtMs: 1 } - ] - })) - })) - Object.assign(window, { - api: { - fs: { - importExternalPaths: vi.fn(), - stageExternalPathsForRuntimeUpload: stage, - uploadExternalFileToRuntime: upload - }, - runtimeEnvironments: { call } - } - }) - return { calls, files, upload } -} - -function renderComposerDrop(attached: string[]) { - return renderHook(() => { - const target = resolveComposerAttachmentTarget({ - selectedProjectGroup: null, - selectedRepo: REPO, - selectedRepoPath: REPO.path, - selectedRepoExecutionHostId: `runtime:${ENVIRONMENT_ID}`, - connectionId: null - }) - return useAttachmentDropState({ - agentPromptRef: { current: '' }, - cancelPromptCaretFrame: () => {}, - connectionId: target.connectionId, - promptCaretFrameRef: { current: null }, - promptTextareaRef: createRef(), - selectedRepoPath: target.path ?? undefined, - selectedRepoRuntimeEnvironmentId: target.runtimeEnvironmentId, - selectedWorktreeId: target.worktreeId, - setAgentPrompt: () => {}, - setAttachmentPaths: (next) => { - attached.splice(0, attached.length, ...(typeof next === 'function' ? next([]) : next)) - } - }) - }) -} - -beforeEach(() => { - vi.clearAllMocks() - clearRuntimeCompatibilityCacheForTests() - clearRuntimeEnvironmentConnectionGenerationsForTests() - replaceRuntimeEnvironmentRevisions([{ id: ENVIRONMENT_ID, createdAt: 1, pairingRevision: 3 }]) - setRuntimeEnvironmentConnectionGenerationForTests(ENVIRONMENT_ID, 1) - markRuntimeEnvironmentCompatible(ENVIRONMENT_ID) -}) - -describe('composer drop on a project owned by a paired server (#16558)', () => { - it('uploads into the project drops folder through the repo worktree', async () => { - const server = installPairedServer() - const attached: string[] = [] - const { result } = renderComposerDrop(attached) - - await act(async () => { - await result.current.applyNativeDrop(['/client/shot.png'], () => true) - }) - - expect(toastError).not.toHaveBeenCalled() - expect(attached).toEqual(['/srv/repo/.orca/drops/shot.png']) - expect(server.files.has('.orca/drops/shot.png')).toBe(true) - for (const call of server.calls.filter(({ method }) => method !== 'status.get')) { - expect(call.selector).toBe(ENVIRONMENT_ID) - expect(call.params.worktree).toBe(WORKTREE_SELECTOR) - } - }) - - it('keeps both files when two drops share a basename', async () => { - const server = installPairedServer() - const attached: string[] = [] - const { result } = renderComposerDrop(attached) - - await act(async () => { - await result.current.applyNativeDrop(['/client/a/shot.png'], () => true) - }) - await act(async () => { - await result.current.applyNativeDrop(['/client/b/shot.png'], () => true) - }) - - expect(server.files.has('.orca/drops/shot.png')).toBe(true) - expect(server.files.has('.orca/drops/shot copy.png')).toBe(true) - expect(attached).toContain('/srv/repo/.orca/drops/shot copy.png') - }) - - it('attaches nothing and commits nothing when the server disconnects mid-drop', async () => { - const server = installPairedServer({ - onUpload: () => setRuntimeEnvironmentConnectionGenerationForTests(ENVIRONMENT_ID, 2) - }) - const attached: string[] = [] - const { result } = renderComposerDrop(attached) - - await act(async () => { - await result.current.applyNativeDrop(['/client/shot.png'], () => true) - }) - - expect(server.upload).toHaveBeenCalledOnce() - expect(server.calls.map(({ method }) => method)).not.toContain('files.commitUpload') - expect(attached).toEqual([]) - expect(toastError).toHaveBeenCalledOnce() - }) - - it('never sends temp cleanup to a replacement server after re-pairing', async () => { - const server = installPairedServer({ - onUpload: () => - replaceRuntimeEnvironmentRevisions([ - { id: ENVIRONMENT_ID, createdAt: 1, pairingRevision: 4 } - ]) - }) - const attached: string[] = [] - const { result } = renderComposerDrop(attached) - - await act(async () => { - await result.current.applyNativeDrop(['/client/shot.png'], () => true) - }) - - const afterUpload = server.calls.map(({ method }) => method) - expect(afterUpload).not.toContain('files.commitUpload') - expect(afterUpload).not.toContain('files.delete') - expect(attached).toEqual([]) - }) -}) diff --git a/src/renderer/src/hooks/editor-external-watch-disk-verification.ts b/src/renderer/src/hooks/editor-external-watch-disk-verification.ts index 4d4762dfd3f..80742fec194 100644 --- a/src/renderer/src/hooks/editor-external-watch-disk-verification.ts +++ b/src/renderer/src/hooks/editor-external-watch-disk-verification.ts @@ -6,7 +6,7 @@ import { notifyEditorExternalFileChange } from '@/components/editor/autosave/editor-autosave' import { markFileChangedOnDisk } from '@/components/editor/external-changes/editor-changed-on-disk-mark' -import { getDiskBaselineSignature } from '../../../shared/disk-baseline-signature' +import { getDiskBaselineSignature } from '../../../shared/file-write/disk-baseline-signature' import { clearSelfWrite, getRecentSelfWrite, diff --git a/src/renderer/src/hooks/editor-external-watch-event-reconciliation.ts b/src/renderer/src/hooks/editor-external-watch-event-reconciliation.ts index 61f859d7313..113a4040a0f 100644 --- a/src/renderer/src/hooks/editor-external-watch-event-reconciliation.ts +++ b/src/renderer/src/hooks/editor-external-watch-event-reconciliation.ts @@ -9,7 +9,7 @@ import { isActiveMoveSourcePath } from '@/components/editor/editor-path-move-inflight' import { normalizeRuntimePathForComparison } from '../../../shared/cross-platform-path' -import type { FsChangedPayload } from '../../../shared/filesystem-entry-types' +import type { FsChangedPayload } from '../../../shared/file-watch/filesystem-change-event' import { ORCA_WORKTREE_FILE_CHANGE_EVENT, type WorktreeFileChangeEventDetail @@ -30,7 +30,7 @@ import { reconcileEditorTabsAfterOverflow, supersedeOverflowProbesForBatch } from './editor-external-watch-overflow' -import { WATCH_BATCH_INTERVAL_MS } from '../../../shared/filesystem-watch-batch-window' +import { WATCH_BATCH_INTERVAL_MS } from '../../../shared/file-watch/filesystem-watch-batch-window' function isTargetList( found: EditorExternalWatchTarget | readonly EditorExternalWatchTarget[] | undefined diff --git a/src/renderer/src/hooks/editor-external-watch-overflow.ts b/src/renderer/src/hooks/editor-external-watch-overflow.ts index 19ce5000c82..342745e8716 100644 --- a/src/renderer/src/hooks/editor-external-watch-overflow.ts +++ b/src/renderer/src/hooks/editor-external-watch-overflow.ts @@ -8,7 +8,7 @@ import { runtimePathsExist } from '@/runtime/files/metadata/runtime-path-existen import { PATH_EXISTENCE_BATCH_MAX, type PathExistenceResult -} from '../../../shared/path-existence-batch' +} from '../../../shared/file-access/path-existence-batch' import { getLocalWindowsWslAliasOption, getOpenFileRuntimeOwner, diff --git a/src/renderer/src/hooks/editor-runtime-file-watch.test.ts b/src/renderer/src/hooks/editor-runtime-file-watch.test.ts index f3f49bbec8c..5ead255db73 100644 --- a/src/renderer/src/hooks/editor-runtime-file-watch.test.ts +++ b/src/renderer/src/hooks/editor-runtime-file-watch.test.ts @@ -1,5 +1,5 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { FsChangedPayload } from '../../../shared/filesystem-entry-types' +import type { FsChangedPayload } from '../../../shared/file-watch/filesystem-change-event' import { subscribeEditorRuntimeFileWatch } from './editor-runtime-file-watch' const runtime = vi.hoisted(() => ({ @@ -33,10 +33,6 @@ const target = { connectionId: undefined, runtimeEnvironmentId: 'host-a' } -const change: FsChangedPayload = { - worktreePath: '/repo', - events: [{ kind: 'update', absolutePath: '/repo/README.md' }] -} function pendingSubscription(): { promise: Promise<() => void> resolve: (stop: () => void) => void @@ -86,51 +82,4 @@ describe('editor runtime file watch recovery', () => { stop() expect(stopFresh).toHaveBeenCalledOnce() }) - - it('drops payloads and errors from replaced attempts and unrelated host contact', async () => { - const onPayload = vi.fn() - const onError = vi.fn() - runtime.subscribe.mockImplementation((_context, payload, error) => { - runtime.payloads.push(payload) - runtime.errors.push(error) - return Promise.resolve(vi.fn()) - }) - const stop = subscribeEditorRuntimeFileWatch(target, onPayload, onError) - await settle() - runtime.contact.get('host-b')?.() - expect(runtime.subscribe).toHaveBeenCalledOnce() - runtime.contact.get('host-a')?.() - await settle() - onPayload.mockClear() - runtime.payloads[0](change) - runtime.errors[0](new Error('old transport')) - expect(onPayload).not.toHaveBeenCalled() - expect(onError).not.toHaveBeenCalled() - runtime.payloads[1](change) - expect(onPayload).toHaveBeenCalledOnce() - stop() - runtime.payloads[1](change) - runtime.contact.get('host-a')?.() - expect(onPayload).toHaveBeenCalledOnce() - expect(runtime.subscribe).toHaveBeenCalledTimes(2) - }) - - it('stops on owner retirement so a same-ID replacement cannot revive old work', async () => { - const stopStream = vi.fn() - runtime.subscribe.mockResolvedValue(stopStream) - const stop = subscribeEditorRuntimeFileWatch(target, vi.fn(), vi.fn()) - await settle() - for (const retire of runtime.retire) { - retire(['host-b']) - } - expect(stopStream).not.toHaveBeenCalled() - for (const retire of runtime.retire) { - retire(['host-a']) - } - expect(stopStream).toHaveBeenCalledOnce() - runtime.contact.get('host-a')?.() - expect(runtime.subscribe).toHaveBeenCalledOnce() - stop() - expect(stopStream).toHaveBeenCalledOnce() - }) }) diff --git a/src/renderer/src/hooks/editor-runtime-file-watch.ts b/src/renderer/src/hooks/editor-runtime-file-watch.ts index 463b6fdc1b9..8ea1cf995dc 100644 --- a/src/renderer/src/hooks/editor-runtime-file-watch.ts +++ b/src/renderer/src/hooks/editor-runtime-file-watch.ts @@ -1,4 +1,4 @@ -import type { FsChangedPayload } from '../../../shared/filesystem-entry-types' +import type { FsChangedPayload } from '../../../shared/file-watch/filesystem-change-event' import { subscribeRuntimeFileChanges } from '@/runtime/files/watching/runtime-file-watch-client' import { subscribeRuntimeHostContactRegained } from '@/runtime/hosts/connections/runtime-host-contact-regained' import { onRuntimeEnvironmentsRetired } from '@/runtime/rpc/environment-revisions/runtime-environment-revision' diff --git a/src/renderer/src/hooks/ipc-events/mobile-terminal-close-ipc-bridge-reveal.test.ts b/src/renderer/src/hooks/ipc-events/mobile-terminal-close-ipc-bridge-reveal.test.ts index 62281a1702f..b1985ae1c34 100644 --- a/src/renderer/src/hooks/ipc-events/mobile-terminal-close-ipc-bridge-reveal.test.ts +++ b/src/renderer/src/hooks/ipc-events/mobile-terminal-close-ipc-bridge-reveal.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import type { RuntimeEditorTabReveal } from '../../../../shared/runtime-file-contracts' +import type { RuntimeEditorTabReveal } from '../../../../shared/file-access/runtime-editor-file-open' import { createTestStore, seedStore } from '../../store/testing/app-store-test-fixture' import { makeWorktree } from '../../store/slices/worktrees/worktree.test-fixture' import { createStoreSessionMockApi } from '../../store/testing/app-store-session-api.test-fixture' diff --git a/src/renderer/src/hooks/ipc-events/mobile-terminal-close-ipc-bridge.ts b/src/renderer/src/hooks/ipc-events/mobile-terminal-close-ipc-bridge.ts index 7092f72df4d..a75cb4e9c16 100644 --- a/src/renderer/src/hooks/ipc-events/mobile-terminal-close-ipc-bridge.ts +++ b/src/renderer/src/hooks/ipc-events/mobile-terminal-close-ipc-bridge.ts @@ -15,7 +15,7 @@ import { layoutFramesFlowing } from '@/runtime/workspace-layout/frames/layout-frame-position' import { framesDrawWorkspace } from '@/runtime/workspace-layout/frames/workspace-layout-frame-drawn-workspaces' -import type { RuntimeEditorTabReveal } from '../../../../shared/runtime-file-contracts' +import type { RuntimeEditorTabReveal } from '../../../../shared/file-access/runtime-editor-file-open' import type { AppState } from '../../store/types' import type { EditorTabSelection } from '../../store/slices/editor/types/open-file' import { diff --git a/src/renderer/src/hooks/ipc-events/os-markdown-file-open-bridge.test.ts b/src/renderer/src/hooks/ipc-events/os-markdown-file-open-bridge.test.ts index 6168ba0b8d5..07953fa9902 100644 --- a/src/renderer/src/hooks/ipc-events/os-markdown-file-open-bridge.test.ts +++ b/src/renderer/src/hooks/ipc-events/os-markdown-file-open-bridge.test.ts @@ -1,8 +1,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { TOGGLE_FLOATING_TERMINAL_EVENT } from '@/lib/floating-terminal' + import type { EditorFilesSlice } from '@/store/slices/editor/types/editor-files-slice' -import type { MarkdownDocument } from '../../../../shared/filesystem-entry-types' -import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants' +import type { MarkdownDocument } from '../../../../shared/file-listing/file-document' + import { registerOsMarkdownFileOpenBridge } from './os-markdown-file-open-bridge' const mocks = vi.hoisted(() => ({ @@ -89,54 +89,12 @@ describe('registerOsMarkdownFileOpenBridge', () => { process.on('unhandledRejection', recordUnhandledRejection) }) - it('leaves documents in main until startup restoration has finished', async () => { - storeState.workspaceSessionReady = false - const unsubscribe = vi.fn() - mocks.subscribe.mockReturnValue(unsubscribe) - const consume = vi.fn(async () => [markdownDocument({ relativePath: 'export.csv' })]) - stubPreload({ onOpenMarkdownFiles: () => () => {}, consumePendingMarkdownFileOpens: consume }) - const unsubs: (() => void)[] = [] - registerOsMarkdownFileOpenBridge(unsubs) - await settle() - expect(consume).not.toHaveBeenCalled() - expect(mocks.openFile).not.toHaveBeenCalled() - expect(unsubs).toEqual([unsubscribe]) - - storeState.workspaceSessionReady = true - mocks.subscribe.mock.calls[0][0](storeState) - await settle() - expect(unsubscribe).toHaveBeenCalledOnce() - expect(consume).toHaveBeenCalledOnce() - expect(mocks.openFile.mock.calls[0][0].language).toBe('csv') - }) - afterEach(() => { process.off('unhandledRejection', recordUnhandledRejection) vi.unstubAllGlobals() vi.restoreAllMocks() }) - it('opens every document main queued before the listener attached', async () => { - stubPreload({ - onOpenMarkdownFiles: () => () => {}, - consumePendingMarkdownFileOpens: () => - Promise.resolve([ - markdownDocument(), - markdownDocument({ filePath: '/Users/me/notes/plan.csv', relativePath: 'plan.csv' }) - ]) - }) - - registerOsMarkdownFileOpenBridge([]) - await settle() - - expect(mocks.openFile).toHaveBeenCalledTimes(2) - expect(mocks.openFile.mock.calls.map((call) => call[0].filePath)).toEqual([ - '/Users/me/notes/README.md', - '/Users/me/notes/plan.csv' - ]) - expect(mocks.openFile.mock.calls[0][0].worktreeId).toBe(FLOATING_TERMINAL_WORKTREE_ID) - }) - it('opens documents pushed after startup and hands back the unsubscribe', async () => { const listeners: MarkdownFileOpenListener[] = [] const unsubscribe = vi.fn() @@ -179,124 +137,6 @@ describe('registerOsMarkdownFileOpenBridge', () => { expect(dispatchEvent).toHaveBeenCalledTimes(1) }) - it('leaves settings alone when the floating workspace is already enabled', async () => { - stubPreload({ - onOpenMarkdownFiles: () => () => {}, - consumePendingMarkdownFileOpens: () => Promise.resolve([markdownDocument()]) - }) - - registerOsMarkdownFileOpenBridge([]) - await settle() - - expect(mocks.updateSettings).not.toHaveBeenCalled() - }) - - it('defers the reveal a frame and toggles only while the panel is hidden', async () => { - stubPreload({ - onOpenMarkdownFiles: () => () => {}, - consumePendingMarkdownFileOpens: () => Promise.resolve([markdownDocument()]) - }) - - registerOsMarkdownFileOpenBridge([]) - await settle() - - expect(dispatchEvent).not.toHaveBeenCalled() - runFrames() - - expect(dispatchEvent).toHaveBeenCalledTimes(1) - expect(dispatchEvent.mock.calls[0][0].type).toBe(TOGGLE_FLOATING_TERMINAL_EVENT) - }) - - it('does not toggle when the panel is already visible', async () => { - storeState.floatingWorkspacePanelOpen = true - stubPreload({ - onOpenMarkdownFiles: () => () => {}, - consumePendingMarkdownFileOpens: () => Promise.resolve([markdownDocument()]) - }) - - registerOsMarkdownFileOpenBridge([]) - await settle() - runFrames() - - expect(dispatchEvent).not.toHaveBeenCalled() - }) - - it('ignores an empty batch', async () => { - storeState.settings = { floatingTerminalEnabled: false } - stubPreload({ - onOpenMarkdownFiles: () => () => {}, - consumePendingMarkdownFileOpens: () => Promise.resolve([]) - }) - - registerOsMarkdownFileOpenBridge([]) - await settle() - runFrames() - - expect(mocks.openFile).not.toHaveBeenCalled() - expect(mocks.updateSettings).not.toHaveBeenCalled() - expect(dispatchEvent).not.toHaveBeenCalled() - }) - - it('reports a rejected pending drain without leaking an unhandled rejection', async () => { - stubPreload({ - onOpenMarkdownFiles: () => () => {}, - consumePendingMarkdownFileOpens: () => Promise.reject(new Error('ipc unavailable')) - }) - - registerOsMarkdownFileOpenBridge([]) - await settle() - - expect(mocks.toastError).toHaveBeenCalledWith('Failed to open the file.') - // App classifies registration throws as restore failure; this bridge must contain its own errors. - expect(unhandledRejections).toEqual([]) - }) - - it('reports a throwing openFile without leaking an unhandled rejection', async () => { - mocks.openFile.mockImplementation(() => { - throw new Error('editor slice exploded') - }) - const listeners: MarkdownFileOpenListener[] = [] - stubPreload({ - onOpenMarkdownFiles: (next: MarkdownFileOpenListener) => { - listeners.push(next) - return () => {} - }, - consumePendingMarkdownFileOpens: () => Promise.resolve([]) - }) - - registerOsMarkdownFileOpenBridge([]) - expect(() => listeners[0]([markdownDocument()])).not.toThrow() - await settle() - - expect(mocks.toastError).toHaveBeenCalledWith('Failed to open the file.') - expect(unhandledRejections).toEqual([]) - expect(dispatchEvent).not.toHaveBeenCalled() - }) - - it('keeps opening the rest of a batch when one document fails', async () => { - mocks.openFile.mockImplementationOnce(() => { - throw new Error('first document exploded') - }) - stubPreload({ - onOpenMarkdownFiles: () => () => {}, - consumePendingMarkdownFileOpens: () => - Promise.resolve([ - markdownDocument({ filePath: '/Users/me/notes/bad.md', relativePath: 'bad.md' }), - markdownDocument({ filePath: '/Users/me/notes/good.md', relativePath: 'good.md' }) - ]) - }) - - registerOsMarkdownFileOpenBridge([]) - await settle() - runFrames() - - // Why: a multi-file selection arrives as one batch; one bad file must not cost the rest. - expect(mocks.openFile).toHaveBeenCalledTimes(2) - expect(mocks.toastError).toHaveBeenCalledTimes(1) - expect(dispatchEvent).toHaveBeenCalledTimes(1) - expect(unhandledRejections).toEqual([]) - }) - it('ignores a non-array payload from a mismatched preload', async () => { stubPreload({ onOpenMarkdownFiles: () => () => {}, diff --git a/src/renderer/src/hooks/ipc-events/os-markdown-file-open-bridge.ts b/src/renderer/src/hooks/ipc-events/os-markdown-file-open-bridge.ts index 5fac1cf2488..d6ee9bb878e 100644 --- a/src/renderer/src/hooks/ipc-events/os-markdown-file-open-bridge.ts +++ b/src/renderer/src/hooks/ipc-events/os-markdown-file-open-bridge.ts @@ -1,5 +1,5 @@ import { toast } from 'sonner' -import type { FileDocument } from '../../../../shared/filesystem-entry-types' +import type { FileDocument } from '../../../../shared/file-listing/file-document' import { revealFloatingWorkspacePanel } from '@/lib/floating-workspace-panel-reveal' import { openDocumentInFloatingWorkspace } from '@/lib/open-document-in-floating-workspace' import { translate } from '@/i18n/i18n' diff --git a/src/renderer/src/hooks/ipc-events/runtime-file-position.ts b/src/renderer/src/hooks/ipc-events/runtime-file-position.ts index 83eade1dbe6..27d66ce6af4 100644 --- a/src/renderer/src/hooks/ipc-events/runtime-file-position.ts +++ b/src/renderer/src/hooks/ipc-events/runtime-file-position.ts @@ -1,4 +1,4 @@ -import type { RuntimeFileOpenPosition } from '../../../../shared/runtime-file-contracts' +import type { RuntimeFileOpenPosition } from '../../../../shared/file-access/runtime-editor-file-open' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants' import { scheduleEditorLineReveal } from '@/store/slices/editor/focus/editor-focus-reveal' import { selectFloatingWorkspacePanelVisible } from '@/store/workspaces/floating/floating-workspace-panel-selector' diff --git a/src/renderer/src/hooks/use-os-file-drop-owner.test.tsx b/src/renderer/src/hooks/use-os-file-drop-owner.test.tsx deleted file mode 100644 index b2e04865fd6..00000000000 --- a/src/renderer/src/hooks/use-os-file-drop-owner.test.tsx +++ /dev/null @@ -1,584 +0,0 @@ -// @vitest-environment happy-dom -import { act, cleanup, render } from '@testing-library/react' -import { useRef, useState } from 'react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { ORCA_INTERNAL_FILE_DRAG_TYPE } from '../../../shared/native-file-drop' -import { - WORKSPACE_FILE_DRAG_SOURCE_MIME, - WORKSPACE_FILE_PATHS_MIME -} from '../lib/workspace-file-drag' -import type { - PrepareDroppedPathsRequest, - PreparedDroppedPaths -} from '../../../shared/native-file-drop-preparation' -import { withFallback } from '../web/preload-api/web-fallback-api' -import { takeBrowserAttachmentFile } from '../lib/browser-attachment-files' -import { - createOsFileDropSequence, - useOsFileDropOwner, - type OsFileDropSequence -} from './use-os-file-drop-owner' - -type DropHandler = ( - prepared: PreparedDroppedPaths, - context: { target: EventTarget | null; destination?: Destination } -) => void | Promise - -const uuid = vi.hoisted(() => ({ next: 0 })) - -const mockLaunchUuid = vi.hoisted(() => () => `uuid-${++uuid.next}`) -vi.mock('../../../shared/non-secure-context-uuid', () => ({ - createNonSecureContextUuid: mockLaunchUuid -})) - -const getPathForFile = vi.fn((file: File) => `/dropped/${file.name}`) -const prepareDroppedPaths = vi.fn( - async ({ paths }: PrepareDroppedPathsRequest): Promise => ({ - paths, - failures: [] - }) -) - -function Owner({ - onDrop, - canAccept, - sequence, - captureDestination, - consumer = 'agent', - isDestinationLive, - acceptsBrowserFiles, - children -}: { - onDrop: DropHandler - consumer?: 'agent' | ((destination: Destination | undefined) => 'local-chat' | 'agent') - canAccept?: boolean - sequence?: OsFileDropSequence - captureDestination?: (event: DragEvent) => Destination - isDestinationLive?: (context: { destination?: Destination }) => boolean - acceptsBrowserFiles?: boolean - children?: React.ReactNode -}): React.JSX.Element { - const ownerElementRef = useRef(null) - const [ownSequence] = useState(createOsFileDropSequence) - const options = { - consumer, - onDrop, - canAccept, - sequence: sequence ?? ownSequence, - captureDestination, - isDestinationLive, - acceptsBrowserFiles - } - const ownerRef = useOsFileDropOwner(ownerElementRef, options) - return ( -
- {children} -
- ) -} - -function SiblingOwner({ - onDrop, - titleMounted = true -}: { - onDrop: DropHandler - titleMounted?: boolean -}): React.JSX.Element { - const [sequence] = useState(createOsFileDropSequence) - return ( - <> - {titleMounted && } - - - ) -} - -function drag( - target: Element, - type: 'dragover' | 'drop', - files: File[] = [new File(['a'], 'a.txt')], - options: { trusted?: boolean; types?: string[] } = {} -): { event: Event; transfer: { dropEffect: string } } { - const transfer = { types: options.types ?? ['Files'], files, dropEffect: 'move' } - const event = new Event(type, { bubbles: true, cancelable: true, composed: true }) - Object.defineProperty(event, 'dataTransfer', { value: transfer }) - Object.defineProperty(event, 'isTrusted', { value: options.trusted ?? true }) - act(() => { - target.dispatchEvent(event) - }) - return { event, transfer } -} - -beforeEach(() => { - uuid.next = 0 - vi.stubGlobal('api', { fs: { getPathForFile, prepareDroppedPaths } }) - getPathForFile.mockClear() - prepareDroppedPaths.mockClear() -}) - -afterEach(() => { - cleanup() - vi.unstubAllGlobals() -}) - -describe('useOsFileDropOwner', () => { - it('registers the root with a callback ref and delivers one prepared drop to the nearest owner', async () => { - const outerDrop = vi.fn() - const innerDrop = vi.fn() - const view = render( - - - - - - ) - const roots = view.getAllByTestId('owner') - const target = view.getByTestId('target') - expect(roots.every((root) => root.hasAttribute('data-os-file-drop-owner'))).toBe(true) - - const hover = drag(target, 'dragover') - expect(hover.event.defaultPrevented).toBe(true) - expect(hover.transfer.dropEffect).toBe('copy') - drag(target, 'drop') - await act(async () => undefined) - - expect(prepareDroppedPaths).toHaveBeenCalledExactlyOnceWith({ - paths: ['/dropped/a.txt'], - consumer: 'agent' - }) - expect(innerDrop).toHaveBeenCalledExactlyOnceWith( - { paths: ['/dropped/a.txt'], failures: [] }, - { target } - ) - expect(outerDrop).not.toHaveBeenCalled() - view.unmount() - expect(roots.every((root) => !root.hasAttribute('data-os-file-drop-owner'))).toBe(true) - }) - - it('keeps a disabled nested owner as a refusal barrier', () => { - const outerDrop = vi.fn() - const innerDrop = vi.fn() - const view = render( - - - - - - ) - const target = view.getByTestId('target') - const hover = drag(target, 'dragover') - expect(hover.transfer.dropEffect).toBe('none') - drag(target, 'drop') - expect(outerDrop).not.toHaveBeenCalled() - expect(innerDrop).not.toHaveBeenCalled() - expect(getPathForFile).not.toHaveBeenCalled() - }) - - it('caps the file snapshot before resolving any path and reports the local rejection once', async () => { - const onDrop = vi.fn() - const view = render() - const files = Array.from({ length: 257 }, (_, index) => new File([], `${index}.txt`)) - drag(view.getByTestId('owner'), 'drop', files) - await act(async () => undefined) - expect(getPathForFile).not.toHaveBeenCalled() - expect(prepareDroppedPaths).not.toHaveBeenCalled() - expect(onDrop).toHaveBeenCalledOnce() - expect(onDrop.mock.calls[0][0]).toEqual({ - paths: [], - failures: [{ target: 'rejected', reason: 'too-many-paths', pathCount: 257, byteLength: 0 }] - }) - }) - - it('reports path byte limits and unresolved files without calling preparation', async () => { - const onDrop = vi.fn() - const view = render() - getPathForFile.mockReturnValueOnce('a'.repeat(256 * 1024 + 1)) - drag(view.getByTestId('owner'), 'drop') - await act(async () => undefined) - expect(onDrop.mock.calls[0][0].failures[0].reason).toBe('paths-too-large') - getPathForFile.mockReturnValueOnce('') - drag(view.getByTestId('owner'), 'drop') - await act(async () => undefined) - expect(onDrop.mock.calls[1][0]).toEqual({ - paths: [], - failures: [{ target: 'rejected', reason: 'unresolved-paths', pathCount: 1, byteLength: 0 }] - }) - expect(prepareDroppedPaths).not.toHaveBeenCalled() - }) - - it('ignores internal drags and untrusted drops', () => { - const onDrop = vi.fn() - const view = render() - const root = view.getByTestId('owner') - for (const type of [ - ORCA_INTERNAL_FILE_DRAG_TYPE, - WORKSPACE_FILE_PATHS_MIME, - WORKSPACE_FILE_DRAG_SOURCE_MIME - ]) { - const internal = drag(root, 'drop', undefined, { types: ['Files', type] }) - expect(internal.event.defaultPrevented).toBe(false) - } - drag(root, 'drop', undefined, { trusted: false }) - expect(onDrop).not.toHaveBeenCalled() - expect(prepareDroppedPaths).not.toHaveBeenCalled() - }) - - it.each(['empty', 'throwing'])( - 'keeps resolved paths and reports %s resolutions with preparation failures in order', - async (resolution) => { - const onDrop = vi.fn() - let finishFirst: ((prepared: PreparedDroppedPaths) => void) | undefined - prepareDroppedPaths.mockImplementationOnce( - () => - new Promise((resolve) => { - finishFirst = resolve - }) - ) - getPathForFile - .mockReturnValueOnce('/dropped/notes.txt') - .mockImplementationOnce(() => { - if (resolution === 'throwing') { - throw new Error('virtual file has no path') - } - return '' - }) - .mockReturnValueOnce('') - .mockReturnValueOnce('/dropped/temp.png') - const view = render() - const root = view.getByTestId('owner') - drag( - root, - 'drop', - ['notes.txt', 'virtual.png', 'missing.png', 'temp.png'].map((name) => new File([], name)) - ) - drag(root, 'drop', [new File([], 'later.txt')]) - await act(async () => undefined) - expect(onDrop).not.toHaveBeenCalled() - expect(prepareDroppedPaths.mock.calls[0][0]).toEqual({ - paths: ['/dropped/notes.txt', '/dropped/temp.png'], - consumer: 'agent' - }) - const copyFailure = { - target: 'rejected', - reason: 'temp-copy-failed', - commonReason: 'copy-failed', - pathCount: 1, - byteLength: 0 - } as const - await act(async () => { - finishFirst?.({ paths: ['/dropped/notes.txt'], failures: [copyFailure] }) - }) - expect(onDrop).toHaveBeenCalledTimes(2) - expect(onDrop.mock.calls.map(([prepared]) => prepared)).toEqual([ - { - paths: ['/dropped/notes.txt'], - failures: [ - { target: 'rejected', reason: 'unresolved-paths', pathCount: 2, byteLength: 0 }, - copyFailure - ] - }, - { paths: ['/dropped/later.txt'], failures: [] } - ]) - } - ) - - it('reports a preparation failure once without passing unprepared paths', async () => { - const onDrop = vi.fn() - prepareDroppedPaths.mockRejectedValueOnce(new Error('copy failed')) - const view = render() - drag(view.getByTestId('owner'), 'drop') - await act(async () => undefined) - expect(onDrop).toHaveBeenCalledOnce() - expect(onDrop.mock.calls[0][0]).toEqual({ - paths: [], - failures: [ - { - target: 'rejected', - reason: 'temp-copy-failed', - commonReason: 'copy-failed', - pathCount: 1, - byteLength: '/dropped/a.txt'.length - } - ] - }) - }) - - it('reports a missing web path bridge to the owner despite fallback method synthesis', async () => { - const onDrop = vi.fn() - vi.stubGlobal('api', withFallback({ fs: { prepareDroppedPaths } }, [])) - const view = render() - drag(view.getByTestId('owner'), 'drop') - await act(async () => undefined) - expect(onDrop).toHaveBeenCalledExactlyOnceWith( - { - paths: [], - failures: [{ target: 'rejected', reason: 'unresolved-paths', pathCount: 1, byteLength: 0 }] - }, - { target: view.getByTestId('owner') } - ) - expect(getPathForFile).not.toHaveBeenCalled() - expect(prepareDroppedPaths).not.toHaveBeenCalled() - }) - - it('hands a destination that uploads bytes itself the browser files the web client cannot path', async () => { - const onDrop = vi.fn() - vi.stubGlobal('api', withFallback({ fs: { prepareDroppedPaths } }, [])) - const file = new File(['a'], 'a.txt') - const view = render() - drag(view.getByTestId('owner'), 'drop', [file]) - await act(async () => undefined) - const [prepared] = onDrop.mock.calls[0]! - expect(prepared.failures).toEqual([]) - expect(prepared.paths).toHaveLength(1) - expect(takeBrowserAttachmentFile(prepared.paths[0]!)).toBe(file) - expect(prepareDroppedPaths).not.toHaveBeenCalled() - }) - - it('releases the browser files of a drop its detached owner never delivers', async () => { - vi.stubGlobal('api', withFallback({ fs: { prepareDroppedPaths } }, [])) - let finishFirst: (() => void) | undefined - const onDrop = vi.fn( - () => - new Promise((resolve) => { - finishFirst = resolve - }) - ) - const view = render() - drag(view.getByTestId('owner'), 'drop', [new File(['a'], 'first.txt')]) - await act(async () => undefined) - drag(view.getByTestId('owner'), 'drop', [new File(['b'], 'second.txt')]) - view.unmount() - await act(async () => { - finishFirst?.() - }) - expect(onDrop).toHaveBeenCalledTimes(1) - expect(takeBrowserAttachmentFile('orca-browser-file:uuid-2/second.txt')).toBeNull() - expect(takeBrowserAttachmentFile('orca-browser-file:uuid-1/first.txt')).not.toBeNull() - }) - - it('does not deliver a prepared drop after its owner detaches', async () => { - const onDrop = vi.fn() - let finish: ((prepared: PreparedDroppedPaths) => void) | undefined - prepareDroppedPaths.mockImplementationOnce( - () => - new Promise((resolve) => { - finish = resolve - }) - ) - const view = render() - drag(view.getByTestId('owner'), 'drop') - view.unmount() - await act(async () => { - finish?.({ paths: ['/dropped/a.txt'], failures: [] }) - }) - expect(onDrop).not.toHaveBeenCalled() - }) - - it.each([true, false])( - 'uses destination liveness (%s) after the root detaches and keeps failures', - async (live) => { - const onDrop = vi.fn>() - let finish: ((prepared: PreparedDroppedPaths) => void) | undefined - prepareDroppedPaths.mockImplementationOnce( - () => - new Promise((resolve) => { - finish = resolve - }) - ) - const isDestinationLive = vi.fn(() => live) - const view = render( - 'group-b'} - isDestinationLive={isDestinationLive} - /> - ) - drag(view.getByTestId('owner'), 'drop') - view.unmount() - await act(async () => { - finish?.({ - paths: ['/dropped/a.txt'], - failures: [ - { target: 'rejected', reason: 'unresolved-paths', pathCount: 1, byteLength: 0 } - ] - }) - }) - expect(isDestinationLive).toHaveBeenCalledWith( - expect.objectContaining({ destination: 'group-b' }) - ) - expect(onDrop).toHaveBeenCalledExactlyOnceWith( - { - paths: live ? ['/dropped/a.txt'] : [], - failures: [ - { target: 'rejected', reason: 'unresolved-paths', pathCount: 1, byteLength: 0 } - ] - }, - expect.objectContaining({ destination: 'group-b' }) - ) - } - ) - - it('orders sibling roots through preparation and asynchronous application while independent owners progress', async () => { - let finishPreparation: ((prepared: PreparedDroppedPaths) => void) | undefined - let finishApplication: (() => void) | undefined - prepareDroppedPaths.mockImplementationOnce( - () => - new Promise((resolve) => { - finishPreparation = resolve - }) - ) - const onDrop = vi.fn().mockImplementationOnce( - () => - new Promise((resolve) => { - finishApplication = resolve - }) - ) - const independentDrop = vi.fn() - const view = render( - <> - - - - ) - const [title, content, independent] = view.getAllByTestId('owner') - drag(title, 'drop', [new File([], 'first.txt')]) - drag(content, 'drop', [new File([], 'second.txt')]) - drag(independent, 'drop', [new File([], 'other.txt')]) - await act(async () => undefined) - expect(onDrop).not.toHaveBeenCalled() - expect(independentDrop).toHaveBeenCalledExactlyOnceWith( - { paths: ['/dropped/other.txt'], failures: [] }, - { target: independent } - ) - await act(async () => { - finishPreparation?.({ paths: ['/dropped/first.txt'], failures: [] }) - }) - expect(onDrop).toHaveBeenCalledExactlyOnceWith( - { paths: ['/dropped/first.txt'], failures: [] }, - { target: title } - ) - drag(independent, 'drop', [new File([], 'another.txt')]) - await act(async () => undefined) - expect(independentDrop).toHaveBeenCalledTimes(2) - expect(onDrop).toHaveBeenCalledOnce() - await act(async () => { - finishApplication?.() - }) - expect(onDrop.mock.calls.map(([prepared]) => prepared.paths)).toEqual([ - ['/dropped/first.txt'], - ['/dropped/second.txt'] - ]) - }) - - it('suppresses only the detached sibling root and lets its destination sequence continue', async () => { - let finish: ((prepared: PreparedDroppedPaths) => void) | undefined - prepareDroppedPaths.mockImplementationOnce( - () => - new Promise((resolve) => { - finish = resolve - }) - ) - const onDrop = vi.fn() - const view = render() - const [title, content] = view.getAllByTestId('owner') - drag(title, 'drop', [new File([], 'detached.txt')]) - drag(content, 'drop', [new File([], 'kept.txt')]) - view.rerender() - await act(async () => undefined) - expect(onDrop).not.toHaveBeenCalled() - await act(async () => { - finish?.({ paths: ['/dropped/detached.txt'], failures: [] }) - }) - expect(onDrop).toHaveBeenCalledExactlyOnceWith( - { paths: ['/dropped/kept.txt'], failures: [] }, - { target: content } - ) - }) - - it('captures a destination synchronously before preparation and retains it when the target row recycles', async () => { - let finish: ((prepared: PreparedDroppedPaths) => void) | undefined - const captureDestination = vi.fn((event: DragEvent) => { - expect(prepareDroppedPaths).not.toHaveBeenCalled() - return event.target instanceof HTMLElement ? (event.target.dataset.folder ?? null) : null - }) - prepareDroppedPaths.mockImplementationOnce( - () => - new Promise((resolve) => { - finish = resolve - }) - ) - const onDrop = vi.fn>() - const view = render( - (destination === 'original-folder' ? 'local-chat' : 'agent')} - > - - - ) - const row = view.getByTestId('row') - drag(row, 'drop') - expect(captureDestination).toHaveBeenCalledOnce() - expect(prepareDroppedPaths).toHaveBeenCalledOnce() - expect(prepareDroppedPaths.mock.calls[0][0].consumer).toBe('local-chat') - expect(onDrop).not.toHaveBeenCalled() - row.dataset.folder = 'recycled-folder' - await act(async () => { - finish?.({ paths: ['/dropped/a.txt'], failures: [] }) - }) - expect(captureDestination).toHaveBeenCalledOnce() - expect(onDrop).toHaveBeenCalledExactlyOnceWith( - { paths: ['/dropped/a.txt'], failures: [] }, - { target: row, destination: 'original-folder' } - ) - }) - - it('reports a callback failure and still delivers the next drop', async () => { - const reported = vi.spyOn(console, 'error').mockImplementation(() => undefined) - const onDrop = vi.fn() - onDrop.mockImplementationOnce(() => { - throw new Error('consumer failed') - }) - try { - const view = render() - const root = view.getByTestId('owner') - drag(root, 'drop', [new File([], 'first.txt')]) - drag(root, 'drop', [new File([], 'second.txt')]) - await act(async () => undefined) - expect(onDrop).toHaveBeenCalledTimes(2) - expect(reported).toHaveBeenCalledOnce() - expect(reported.mock.calls[0][1]).toEqual(new Error('consumer failed')) - } finally { - reported.mockRestore() - } - }) -}) - -it('delivers trusted File payloads synchronously to the nearest byte consumer without path preparation', () => { - const received = vi.fn() - const outer = vi.fn() - function ByteOwner() { - const root = useRef(null) - const attach = useOsFileDropOwner(root, { kind: 'files', onFiles: received }) - return ( -
- -
- ) - } - const view = render( - - - - ) - const file = new File(['png'], 'image.png', { type: 'image/png' }) - const target = view.getByTestId('image-target') - drag(target, 'drop', [file]) - expect(received).toHaveBeenCalledExactlyOnceWith([file], { target }) - expect(prepareDroppedPaths).not.toHaveBeenCalled() - expect(outer).not.toHaveBeenCalled() - received.mockClear() - drag(target, 'drop', [file], { trusted: false }) - expect(received).not.toHaveBeenCalled() -}) diff --git a/src/renderer/src/hooks/use-os-file-drop-owner.ts b/src/renderer/src/hooks/use-os-file-drop-owner.ts index 607ccdcf2a6..84d86a3e4b9 100644 --- a/src/renderer/src/hooks/use-os-file-drop-owner.ts +++ b/src/renderer/src/hooks/use-os-file-drop-owner.ts @@ -3,12 +3,12 @@ import { createRejectedNativeFileDropPayload, NATIVE_FILE_DROP_MAX_PATHS, type NativeFileDropRejectedPayload -} from '../../../shared/native-file-drop' +} from '../../../shared/file-import/native-file-drop' import { OS_FILE_DROP_OWNER_ATTRIBUTE, type DroppedPathConsumer, type PreparedDroppedPaths -} from '../../../shared/native-file-drop-preparation' +} from '../../../shared/file-import/native-file-drop-preparation' import { prepareOsFileDropPaths } from '../lib/os-file-drop-preparation' import { hasOsFileDragTypes } from '../lib/os-file-drop-cancellation-guard' import { diff --git a/src/renderer/src/hooks/useEditorExternalWatch-self-move.test.ts b/src/renderer/src/hooks/useEditorExternalWatch-self-move.test.ts index c38a5c4acd3..cf5de59d92a 100644 --- a/src/renderer/src/hooks/useEditorExternalWatch-self-move.test.ts +++ b/src/renderer/src/hooks/useEditorExternalWatch-self-move.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type * as EditorAutosaveModule from '@/components/editor/autosave/editor-autosave' -import type { FsChangedPayload } from '../../../shared/filesystem-entry-types' +import type { FsChangedPayload } from '../../../shared/file-watch/filesystem-change-event' vi.mock('@/store', () => ({ useAppStore: { getState: vi.fn() } @@ -29,7 +29,7 @@ import { beginEditorPathMove, settleEditorPathMove } from '@/components/editor/editor-path-move-inflight' -import { getDiskBaselineSignature } from '../../../shared/disk-baseline-signature' +import { getDiskBaselineSignature } from '../../../shared/file-write/disk-baseline-signature' const findTarget = (worktreePath: string, runtimeEnvironmentId: string | null = null) => worktreePath === '/repo' diff --git a/src/renderer/src/hooks/useEditorExternalWatch-switch-back.test.tsx b/src/renderer/src/hooks/useEditorExternalWatch-switch-back.test.tsx index 24594c940c1..50d305add56 100644 --- a/src/renderer/src/hooks/useEditorExternalWatch-switch-back.test.tsx +++ b/src/renderer/src/hooks/useEditorExternalWatch-switch-back.test.tsx @@ -48,11 +48,8 @@ vi.mock('@/lib/connection-context', () => ({ getConnectionIdForFile: () => undef import { createTestStore } from '@/store/testing/app-store-test-fixture' import { useEditorExternalWatch } from './useEditorExternalWatch' import { attachRestoredTabConflictScan } from '@/components/editor/external-changes/editor-restored-tab-conflict-scan' -import { getDiskBaselineSignature } from '../../../shared/disk-baseline-signature' -import { - isAutosaveSuspendedForFile, - ORCA_EDITOR_EXTERNAL_FILE_CHANGE_EVENT -} from '@/components/editor/autosave/editor-autosave' +import { getDiskBaselineSignature } from '../../../shared/file-write/disk-baseline-signature' +import { ORCA_EDITOR_EXTERNAL_FILE_CHANGE_EVENT } from '@/components/editor/autosave/editor-autosave' import { ORCA_WORKTREE_FILE_CHANGE_EVENT } from './worktree-file-change-event' import { claimCombinedDiffView, @@ -177,17 +174,6 @@ describe('switching back to a workspace that was not watched', () => { await act(async () => vi.advanceTimersByTimeAsync(200)) } - it('reloads clean tabs, flags a changed dirty tab without pausing it, and refreshes git status/Files once', async () => { - harness.readRuntimeFileContent.mockResolvedValue({ content: 'v2 agent write', isBinary: false }) - await switchBack() - - expect(reloads).toEqual(['clean.ts']) - expect(harness.readRuntimeFileContent).toHaveBeenCalledTimes(1) - expect(file(DIRTY)).toMatchObject({ isDirty: true, externalMutation: 'changed' }) - expect(file(CLEAN).externalMutation).toBeFalsy() - expect(fileChangeEvents).toBe(1) - }) - it('marks a clean tab deleted and keeps it when its file was deleted while unwatched', async () => { harness.readRuntimeFileContent.mockResolvedValue({ content: 'v1', isBinary: false }) pathExists.mockImplementation(async ({ filePath }: { filePath: string }) => filePath !== CLEAN) @@ -237,23 +223,4 @@ describe('switching back to a workspace that was not watched', () => { expect(view?.loadedIndices).toEqual([1]) expect(readCombinedDiffViewMemory(viewKey)?.scrollTop).toBe(120) }) - - it('leaves a dirty tab alone when disk still matches what it last read', async () => { - harness.readRuntimeFileContent.mockResolvedValue({ content: 'v1', isBinary: false }) - await switchBack() - - expect(harness.readRuntimeFileContent).toHaveBeenCalledTimes(1) - expect(file(DIRTY).externalMutation).toBeFalsy() - expect(isAutosaveSuspendedForFile(file(DIRTY))).toBe(false) - }) - - it('does not re-read tabs of a workspace that was never dropped', async () => { - await render([active], []) - await render([active, background], []) - await act(async () => settleWatch()) - await act(async () => vi.advanceTimersByTimeAsync(200)) - - expect(reloads).toEqual([]) - expect(harness.readRuntimeFileContent).not.toHaveBeenCalled() - }) }) diff --git a/src/renderer/src/hooks/useEditorExternalWatch.test.ts b/src/renderer/src/hooks/useEditorExternalWatch.test.ts index 52f021beb27..e0a87cb44af 100644 --- a/src/renderer/src/hooks/useEditorExternalWatch.test.ts +++ b/src/renderer/src/hooks/useEditorExternalWatch.test.ts @@ -1,6 +1,6 @@ import { beforeEach, describe, expect, it, vi, afterEach } from 'vitest' import type * as EditorAutosaveModule from '@/components/editor/autosave/editor-autosave' -import type { FsChangedPayload } from '../../../shared/filesystem-entry-types' +import type { FsChangedPayload } from '../../../shared/file-watch/filesystem-change-event' vi.mock('@/store', () => ({ useAppStore: { @@ -490,69 +490,6 @@ describe('createExternalWatchEventHandler tombstone coalescing', () => { dispose() }) - it('shares one echo-verification read across a burst of watcher payloads', async () => { - const dirtyFile = { - ...fileNotes, - isDirty: true - } - vi.mocked(useAppStore.getState).mockReturnValue({ - ...createTestStore().getState(), - openFiles: [dirtyFile], - setExternalMutation - }) - vi.mocked(getOpenFilesForExternalFileChange).mockReturnValue([dirtyFile] as never) - const readFile = vi.fn().mockResolvedValue({ content: 'agent content', isBinary: false }) - vi.stubGlobal('window', { api: { fs: { readFile } } }) - const { handleFsChanged, dispose } = createExternalWatchEventHandler(findTarget) - - recordSelfWrite('/repo/notes.md', 'orca save') - // Burst SSH echo payloads must share full-file reads instead of stacking network round trips. - handleFsChanged(payload([{ kind: 'update', absolutePath: '/repo/notes.md' }])) - handleFsChanged(payload([{ kind: 'update', absolutePath: '/repo/notes.md' }])) - handleFsChanged(payload([{ kind: 'update', absolutePath: '/repo/notes.md' }])) - await vi.advanceTimersByTimeAsync(100) - - expect(readFile).toHaveBeenCalledTimes(1) - expect(setExternalMutation).toHaveBeenCalledWith('file-notes', 'changed') - dispose() - }) - - it('does not let a later write join an echo-verification read that started before it', async () => { - const dirtyFile = { - ...fileNotes, - isDirty: true - } - vi.mocked(useAppStore.getState).mockReturnValue({ - ...createTestStore().getState(), - openFiles: [dirtyFile], - setExternalMutation - }) - vi.mocked(getOpenFilesForExternalFileChange).mockReturnValue([dirtyFile] as never) - let resolveEchoRead: (value: { content: string; isBinary: boolean }) => void = () => {} - const readFile = vi - .fn() - .mockReturnValueOnce( - new Promise((resolve) => { - resolveEchoRead = resolve - }) - ) - .mockResolvedValue({ content: 'agent content', isBinary: false }) - vi.stubGlobal('window', { api: { fs: { readFile } } }) - const { handleFsChanged, dispose } = createExternalWatchEventHandler(findTarget) - - recordSelfWrite('/repo/notes.md', 'orca save') - handleFsChanged(payload([{ kind: 'update', absolutePath: '/repo/notes.md' }])) - await vi.advanceTimersByTimeAsync(50) - handleFsChanged(payload([{ kind: 'update', absolutePath: '/repo/notes.md' }])) - await vi.advanceTimersByTimeAsync(50) - resolveEchoRead({ content: 'orca save', isBinary: false }) - await vi.advanceTimersByTimeAsync(100) - - expect(readFile).toHaveBeenCalledTimes(2) - expect(setExternalMutation).toHaveBeenCalledWith('file-notes', 'changed') - dispose() - }) - it('marks a lone dirty unstaged-diff tab changed-on-disk', () => { const dirtyDiffTab = { id: 'diff-notes', diff --git a/src/renderer/src/hooks/useEditorExternalWatch.ts b/src/renderer/src/hooks/useEditorExternalWatch.ts index 5bdc2463f92..dad4d71db9a 100644 --- a/src/renderer/src/hooks/useEditorExternalWatch.ts +++ b/src/renderer/src/hooks/useEditorExternalWatch.ts @@ -3,7 +3,7 @@ import { useCallback, useEffect, useRef } from 'react' import { useAppStore } from '@/store' import { subscribeEditorRuntimeFileWatch } from './editor-runtime-file-watch' import { normalizeRuntimePathForComparison } from '../../../shared/cross-platform-path' -import type { FsChangedPayload } from '../../../shared/filesystem-entry-types' +import type { FsChangedPayload } from '../../../shared/file-watch/filesystem-change-event' import { getEditorExternalWatchTargetKey, selectEditorExternalWatchTargets, diff --git a/src/renderer/src/hooks/worktree-file-change-event.ts b/src/renderer/src/hooks/worktree-file-change-event.ts index 78c70867825..4a70d44c858 100644 --- a/src/renderer/src/hooks/worktree-file-change-event.ts +++ b/src/renderer/src/hooks/worktree-file-change-event.ts @@ -1,4 +1,4 @@ -import type { FsChangedPayload } from '../../../shared/filesystem-entry-types' +import type { FsChangedPayload } from '../../../shared/file-watch/filesystem-change-event' export const ORCA_WORKTREE_FILE_CHANGE_EVENT = 'orca:worktree-file-change' diff --git a/src/renderer/src/lib/agent-session/resume/history/ai-vault-session-resume-preparation.ts b/src/renderer/src/lib/agent-session/resume/history/ai-vault-session-resume-preparation.ts index 43592445176..8260af2556d 100644 --- a/src/renderer/src/lib/agent-session/resume/history/ai-vault-session-resume-preparation.ts +++ b/src/renderer/src/lib/agent-session/resume/history/ai-vault-session-resume-preparation.ts @@ -20,7 +20,7 @@ import { import { browseRuntimeServerDirectory } from '@/runtime/files/reads/runtime-server-directory-browser' import { RuntimeRpcCallError } from '@/runtime/rpc/calls/runtime-rpc-result' import { getRuntimeEnvironmentRevision } from '@/runtime/rpc/environment-revisions/runtime-environment-revision' -import type { FilesystemPathFlavor } from '../../../../../../shared/filesystem-entry-types' +import type { FilesystemPathFlavor } from '../../../../../../shared/file-access/filesystem-path-flavor' import { isWindowsAbsolutePathLike } from '../../../../../../shared/cross-platform-path' import { readIpcErrorMessage } from '../../../ipc-error' import type { AiVaultResumeCommandSession } from '../../../../../../shared/ai-vault/resume/ai-vault-resume-startup' diff --git a/src/renderer/src/lib/create-untitled-markdown.test.ts b/src/renderer/src/lib/create-untitled-markdown.test.ts index af2c76d0ad4..22b5db8e170 100644 --- a/src/renderer/src/lib/create-untitled-markdown.test.ts +++ b/src/renderer/src/lib/create-untitled-markdown.test.ts @@ -1,12 +1,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { createUntitledMarkdownFile } from './create-untitled-markdown' -import { - createCompatibleRuntimeStatusResponseIfNeeded, - type RuntimeEnvironmentCallRequest -} from '@/runtime/rpc/testing/runtime-compatibility-test-fixture' -import { clearRuntimeCompatibilityCache as clearRuntimeCompatibilityCacheForTests } from '@/runtime/rpc/compatibility/runtime-compatibility-cache' + import type { RuntimeClientTarget } from '../../../shared/runtime-client-target' -import { getDiskBaselineSignature } from '../../../shared/disk-baseline-signature' const LOCAL: RuntimeClientTarget = { kind: 'local' } @@ -22,238 +17,4 @@ describe('createUntitledMarkdownFile', () => { }) ).rejects.toThrow("Couldn't verify which host owns this file") }) - - it('retries with the next untitled name when createFile loses the EEXIST race', async () => { - const pathExists = vi - .fn() - .mockResolvedValueOnce(true) - .mockResolvedValueOnce(false) - .mockResolvedValueOnce(false) - const stat = vi.fn(async (args: { filePath: string }) => { - if (args.filePath.endsWith('untitled.md')) { - return { size: 0, isDirectory: false, mtime: 1 } - } - throw new Error('ENOENT: no such file') - }) - const createFile = vi - .fn() - .mockRejectedValueOnce(new Error('EEXIST: file already exists')) - .mockResolvedValueOnce(undefined) - - vi.stubGlobal('window', { - api: { - shell: { pathExists: vi.fn() }, - fs: { createFile, pathExists, stat } - } - }) - - await expect(createUntitledMarkdownFile('/repo', 'wt-1', undefined, LOCAL)).resolves.toEqual({ - filePath: '/repo/untitled-3.md', - relativePath: 'untitled-3.md', - worktreeId: 'wt-1', - language: 'markdown', - isUntitled: true, - mode: 'edit' - }) - - expect(createFile).toHaveBeenNthCalledWith(1, { - filePath: '/repo/untitled-2.md', - connectionId: undefined, - expectedExecutionHostId: 'local' - }) - expect(createFile).toHaveBeenNthCalledWith(2, { - filePath: '/repo/untitled-3.md', - connectionId: undefined, - expectedExecutionHostId: 'local' - }) - expect(pathExists).toHaveBeenCalledTimes(3) - }) - - it.each(['original text {{title}}', ''])( - 'recovers exact text into a collision-safe new path (%j)', - async (content) => { - const pathExists = vi.fn().mockResolvedValueOnce(true).mockResolvedValue(false) - const createFile = vi - .fn() - .mockRejectedValueOnce(new Error('EEXIST')) - .mockResolvedValue(undefined) - const writeFile = vi.fn().mockResolvedValue(undefined) - vi.stubGlobal('window', { api: { fs: { pathExists, createFile, writeFile } } }) - await expect( - createUntitledMarkdownFile('/active', 'wt', undefined, LOCAL, { - recoveredDocument: { originalPath: 'C:\\removed\\note.ts', content } - }) - ).resolves.toMatchObject({ - filePath: '/active/note (recovered 3).ts', - relativePath: 'note (recovered 3).ts', - language: 'typescript', - isUntitled: true, - deleteUntouchedOnClose: false - }) - expect(writeFile).toHaveBeenCalledTimes(1) - expect(writeFile).toHaveBeenCalledWith( - expect.objectContaining({ - filePath: '/active/note (recovered 3).ts', - content, - diskPrecondition: { expectedSignature: getDiskBaselineSignature('') } - }) - ) - expect(createFile).not.toHaveBeenCalledWith( - expect.objectContaining({ filePath: 'C:\\removed\\note.ts' }) - ) - } - ) - - it('never overwrites or deletes a file another writer filled after the create', async () => { - const createFile = vi.fn().mockResolvedValue(undefined) - const writeFile = vi - .fn() - .mockResolvedValueOnce({ ok: false, diskConflict: 'changed' }) - .mockResolvedValue(undefined) - const deletePath = vi.fn() - vi.stubGlobal('window', { - api: { - fs: { pathExists: vi.fn().mockResolvedValue(false), createFile, writeFile, deletePath } - } - }) - await expect( - createUntitledMarkdownFile('/active', 'wt', undefined, LOCAL, { - recoveredDocument: { originalPath: '/removed/a.md', content: 'text' } - }) - ).resolves.toMatchObject({ filePath: '/active/a (recovered 2).md' }) - expect(writeFile).toHaveBeenCalledTimes(2) - expect(deletePath).not.toHaveBeenCalled() - }) - - it('keeps the created path when a recovered write fails', async () => { - const deletePath = vi.fn() - vi.stubGlobal('window', { - api: { - fs: { - pathExists: vi.fn().mockResolvedValue(false), - createFile: vi.fn().mockResolvedValue(undefined), - writeFile: vi.fn().mockRejectedValue(new Error('disk full')), - deletePath - } - } - }) - await expect( - createUntitledMarkdownFile('/active', 'wt', undefined, LOCAL, { - recoveredDocument: { originalPath: '/removed/a.md', content: 'text' } - }) - ).rejects.toThrow('disk full') - expect(deletePath).not.toHaveBeenCalled() - }) - - it('throws a descriptive error when untitled names are exhausted', async () => { - const pathExists = vi.fn(async () => true) - const stat = vi.fn().mockResolvedValue({ size: 0, isDirectory: false, mtime: 1 }) - const createFile = vi.fn() - - vi.stubGlobal('window', { - api: { - shell: { pathExists: vi.fn() }, - fs: { createFile, pathExists, stat } - } - }) - - await expect(createUntitledMarkdownFile('/repo', 'wt-1', undefined, LOCAL)).rejects.toThrow( - 'Unable to create untitled markdown file after 100 attempts.' - ) - - expect(createFile).not.toHaveBeenCalled() - expect(pathExists).toHaveBeenCalledTimes(100) - }) - - it('passes connectionId to pathExists and createFile for SSH worktrees', async () => { - const pathExists = vi.fn(async () => false) - const stat = vi.fn().mockRejectedValue(new Error('ENOENT: no such file')) - const createFile = vi.fn().mockResolvedValueOnce(undefined) - - vi.stubGlobal('window', { - api: { - shell: { pathExists: vi.fn() }, - fs: { createFile, pathExists, stat } - } - }) - - await expect( - createUntitledMarkdownFile('/repo', 'wt-1', 'conn-1', LOCAL) - ).resolves.toMatchObject({ - filePath: '/repo/untitled.md' - }) - - // Probe through runtime/SSH-aware files API; shell.pathExists only sees main’s local filesystem. - expect(pathExists).toHaveBeenCalledWith({ - filePath: '/repo/untitled.md', - connectionId: 'conn-1' - }) - expect(stat).not.toHaveBeenCalled() - expect(createFile).toHaveBeenCalledWith({ - filePath: '/repo/untitled.md', - connectionId: 'conn-1', - expectedExecutionHostId: 'ssh:conn-1' - }) - }) - - it('creates untitled files through the selected runtime environment', async () => { - clearRuntimeCompatibilityCacheForTests() - const stat = vi.fn() - const createFile = vi.fn() - const runtimeEnvironmentCall = vi - .fn() - .mockResolvedValueOnce({ - id: 'rpc-1', - ok: false, - error: { message: 'ENOENT: no such file' }, - _meta: { runtimeId: 'remote-runtime' } - }) - .mockResolvedValueOnce({ - id: 'rpc-2', - ok: true, - result: { ok: true }, - _meta: { runtimeId: 'remote-runtime' } - }) - const runtimeEnvironmentTransportCall = vi.fn((args: RuntimeEnvironmentCallRequest) => { - return createCompatibleRuntimeStatusResponseIfNeeded(args) ?? runtimeEnvironmentCall(args) - }) - - vi.stubGlobal('window', { - api: { - shell: { pathExists: vi.fn() }, - fs: { createFile, stat }, - runtimeEnvironments: { call: runtimeEnvironmentTransportCall } - } - }) - - await expect( - createUntitledMarkdownFile('/remote/repo', 'wt-1', undefined, { - kind: 'environment', - environmentId: 'env-1' - }) - ).resolves.toMatchObject({ - filePath: '/remote/repo/untitled.md', - relativePath: 'untitled.md' - }) - - expect(runtimeEnvironmentCall).toHaveBeenNthCalledWith(1, { - selector: 'env-1', - method: 'files.stat', - params: { worktree: 'id:wt-1', relativePath: 'untitled.md' }, - timeoutMs: 15_000 - }) - expect(runtimeEnvironmentCall).toHaveBeenNthCalledWith(2, { - selector: 'env-1', - method: 'files.createFile', - expectedEnvironmentPairingRevision: undefined, - params: { - worktree: 'id:wt-1', - relativePath: 'untitled.md', - expectedExecutionHostId: 'local' - }, - timeoutMs: 15_000 - }) - expect(stat).not.toHaveBeenCalled() - expect(createFile).not.toHaveBeenCalled() - }) }) diff --git a/src/renderer/src/lib/create-untitled-markdown.ts b/src/renderer/src/lib/create-untitled-markdown.ts index b367df68e46..7e9dc4f2cc0 100644 --- a/src/renderer/src/lib/create-untitled-markdown.ts +++ b/src/renderer/src/lib/create-untitled-markdown.ts @@ -16,7 +16,7 @@ import { import { requestMarkdownTemplateSelection } from './markdown-template-picker-request' import { basename, joinPath } from './path' import type { EditorFileOperationProvenance } from './editor-file-operation-provenance' -import { getDiskBaselineSignature } from '../../../shared/disk-baseline-signature' +import { getDiskBaselineSignature } from '../../../shared/file-write/disk-baseline-signature' export type UntitledMarkdownFileInfo = { filePath: string diff --git a/src/renderer/src/lib/drop-skip-reason-copy.ts b/src/renderer/src/lib/drop-skip-reason-copy.ts index 98bf3df470b..b9468fd220b 100644 --- a/src/renderer/src/lib/drop-skip-reason-copy.ts +++ b/src/renderer/src/lib/drop-skip-reason-copy.ts @@ -1,5 +1,5 @@ import { translate } from '@/i18n/i18n' -import type { ImportSkipReason } from '../../../shared/filesystem-import-result-types' +import type { ImportSkipReason } from '../../../shared/file-import/filesystem-import-result' const SKIP_REASON_COPY: Record = { missing: { diff --git a/src/renderer/src/lib/drop-temp-copy-failure-copy.ts b/src/renderer/src/lib/drop-temp-copy-failure-copy.ts index 47cc9e5a649..1fbc01e6513 100644 --- a/src/renderer/src/lib/drop-temp-copy-failure-copy.ts +++ b/src/renderer/src/lib/drop-temp-copy-failure-copy.ts @@ -1,5 +1,5 @@ import { translate } from '@/i18n/i18n' -import type { NativeFileDropCopyFailureReason } from '../../../shared/native-file-drop' +import type { NativeFileDropCopyFailureReason } from '../../../shared/file-import/native-file-drop' import { describeDropSkipReason } from './drop-skip-reason-copy' export function describeDropTempCopyFailure( diff --git a/src/renderer/src/lib/editor-file-operation-owner.test.ts b/src/renderer/src/lib/editor-file-operation-owner.test.ts index 18ce94cee4c..064b397f108 100644 --- a/src/renderer/src/lib/editor-file-operation-owner.test.ts +++ b/src/renderer/src/lib/editor-file-operation-owner.test.ts @@ -11,42 +11,12 @@ import { captureEditorFileOperationProvenance } from './editor-file-operation-provenance' import { getEditorFileOperationContext } from './editor-file-operation-owner' -import { applyOpenFileToState } from '@/store/slices/editor/opening/open-file-apply' -import { buildEditorSessionData } from './workspace/persistence/workspace-session' -import { restorableEditorFile } from '@/store/slices/editor/tabs/editor-tab-layout-owner' -import { isSameOwnedDocument } from '@/store/slices/editor/file-ids/same-owned-editor-document' -import { editorMoveOwnerFromContext, isOpenFileOnMoveOwner } from './open-editor-move-owner' -import { getEditorModelOwnerKey } from '@/components/editor/model-lifetime/identity/editor-model-owner' -import { loadWorkspaceLayout } from '../../../shared/workspace-layout/workspace-layout-load' -import { saveWorkspaceLayout } from '../../../shared/workspace-layout/workspace-layout-save' -import { - addWorkspace, - emptySession -} from '../../../shared/workspace-layout/workspace-layout-session.test-fixture' -import { - makeFolderWorkspace, - makeProjectGroup -} from '@/components/sidebar/workspace-creation/folder/folder-workspace-composer-submit-fixtures' -import { ORCA_EDITOR_FILE_SAVED_EVENT } from '@/components/editor/autosave/editor-autosave' -import { createEditorSaveQueue } from '@/components/editor/save/queue/editor-save-queue' -import type * as RuntimeFileMutationClient from '@/runtime/files/mutations/runtime-file-mutation-client' -import type { OpenFile } from '@/store/slices/editor/types/open-file' -import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' -import { TEST_REPO } from '@/store/repos/repo.test-fixture' -import type { FileWriteResult } from '../../../shared/file-write-disk-precondition' - -const { writeRuntimeFile } = vi.hoisted(() => ({ writeRuntimeFile: vi.fn() })) -vi.mock('@/runtime/files/mutations/runtime-file-mutation-client', async (importOriginal) => ({ - ...(await importOriginal()), - writeRuntimeFile -})) vi.mock('../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) const worktreeId = 'repo::/remote/repo' beforeEach(() => { - writeRuntimeFile.mockReset() useAppStore.setState(useAppStore.getInitialState(), true) useAppStore.setState({ repos: [], @@ -62,340 +32,6 @@ beforeEach(() => { }) describe('editor file operation owner', () => { - it.each([true, false])( - 'does not settle an issued write onto a reused view (ok=%s)', - async (ok) => { - const source: OpenFile = { - id: 'reused-view', - worktreeId: 'local-worktree', - filePath: '/repo/source.md', - relativePath: 'source.md', - mode: 'edit', - language: 'markdown', - runtimeEnvironmentId: null, - lastKnownDiskSignature: 'source baseline', - isDirty: true - } - useAppStore.setState({ - repos: [{ ...TEST_REPO, path: '/repo', executionHostId: 'local' }], - worktreesByRepo: { - [TEST_REPO.id]: [ - makeWorktree({ - id: source.worktreeId, - repoId: TEST_REPO.id, - path: '/repo', - hostId: 'local' - }) - ] - }, - openFiles: [source], - editorDrafts: { [source.id]: 'source text' } - }) - let finish!: (result: FileWriteResult) => void - writeRuntimeFile.mockReset().mockReturnValueOnce( - new Promise((resolve) => { - finish = resolve - }) - ) - const events = vi.spyOn(window, 'dispatchEvent') - const queue = createEditorSaveQueue(useAppStore) - const pending = queue.queueSave(source, 'source text') - await vi.waitFor(() => expect(writeRuntimeFile).toHaveBeenCalledOnce()) - const replacement: OpenFile = { - ...source, - filePath: '/repo/other.md', - relativePath: 'other.md', - lastKnownDiskSignature: 'other baseline' - } - useAppStore.getState().closeFile(source.id, { captureRecentlyClosed: false }) - useAppStore.setState({ - openFiles: [replacement], - editorDrafts: { [source.id]: 'other draft' } - }) - finish(ok ? { ok: true } : { ok: false, diskConflict: 'missing' }) - await expect(pending).resolves.toBe(ok ? 'written' : 'blocked-stale') - expect(useAppStore.getState().openFiles[0]).toEqual(replacement) - expect(useAppStore.getState().editorDrafts[source.id]).toBe('other draft') - expect( - events.mock.calls.filter(([event]) => event.type === ORCA_EDITOR_FILE_SAVED_EVENT) - ).toEqual([]) - events.mockRestore() - queue.dispose() - } - ) - it('keeps catalog identity and drafts across capture, saved writers and reload while fencing physical retargets', async () => { - const id = 'folder:physical-owner' - useAppStore.setState({ - activeWorktreeId: id, - activeWorkspaceExecutionHostId: 'runtime:hub-a', - folderWorkspaces: [ - makeFolderWorkspace({ - id: 'physical-owner', - folderPath: '/local', - executionHostId: 'local' - }), - makeFolderWorkspace({ - id: 'physical-owner', - folderPath: '/remote', - projectGroupId: 'physical-group' - }) - ], - projectGroups: [ - { - ...makeProjectGroup(), - id: 'physical-group', - executionHostId: 'runtime:hub-a', - connectionId: 'box' - } - ], - sshStateByEnvironment: new Map([ - [ - 'hub-a', - { - targetsHydrated: true, - targetLabels: new Map([ - ['box', 'box'], - ['other', 'other'] - ]), - targetGenerations: new Map([ - ['box', 7], - ['other', 7] - ]), - removedTargetLabels: new Map(), - connectionStates: new Map( - ['box', 'other'].map((targetId) => [ - targetId, - { - targetId, - status: 'connected' as const, - error: null, - reconnectAttempt: 0, - connectionGeneration: 7 - } - ]) - ) - } - ] - ]) - }) - const initial = useAppStore.getState() - const scratch = { - editorItemFileId: '', - editorItemTargetGroupId: undefined, - editorItemIsPreview: false, - refused: false - } - useAppStore.setState( - applyOpenFileToState( - initial, - { - worktreeId: id, - filePath: '/remote/a.md', - relativePath: 'a.md', - language: 'markdown', - mode: 'edit', - runtimeEnvironmentId: 'hub-a' - }, - { preview: true }, - scratch - ) - ) - const file = useAppStore.getState().openFiles[0] - const provenance = file.operationProvenance! - const incoming = { ...provenance, expectedSshConnectionGeneration: 8 } - const reopened = { - worktreeId: file.worktreeId, - filePath: file.filePath, - relativePath: file.relativePath, - language: file.language, - mode: file.mode, - runtimeEnvironmentId: file.runtimeEnvironmentId, - operationProvenance: incoming - } - useAppStore.setState(applyOpenFileToState(useAppStore.getState(), reopened, undefined, scratch)) - expect(useAppStore.getState().openFiles[0].operationProvenance).toBe(provenance) - const externalRefresh = applyOpenFileToState( - useAppStore.getState(), - { ...reopened, externalSshTargetId: 'box' }, - undefined, - scratch - ) - expect(externalRefresh.openFiles?.[0].operationProvenance).toBe(incoming) - expect(provenance.generation.route).toEqual({ - executionHostId: 'runtime:hub-a', - runtimeEnvironmentId: 'hub-a' - }) - expect(provenance.generation.authority).toEqual({ - endpoint: { kind: 'environment', environmentId: 'hub-a' }, - at: 'ssh:box' - }) - const context = getEditorFileOperationContext(useAppStore.getState(), file, '') - expect(context).toMatchObject({ - target: { kind: 'environment', environmentId: 'hub-a' }, - worktreePath: '/remote', - expectedExecutionHostId: 'ssh:box', - expectedSshConnectionGeneration: 7 - }) - const key = getEditorModelOwnerKey(file, initial) - expect(key).toBe(JSON.stringify(['hub-a', 'ssh:box'])) - const saved = buildEditorSessionData( - [{ ...file, isDirty: true }], - { [file.id]: 'retained draft' }, - {}, - { [id]: file.id }, - { [id]: 'editor' } - ) - const layoutRecord = restorableEditorFile(file) - expect(JSON.stringify([saved, layoutRecord])).not.toContain('authority') - expect(JSON.stringify([saved, layoutRecord])).not.toContain('operationProvenance') - const loaded = loadWorkspaceLayout( - 'local', - { - ...addWorkspace( - emptySession(), - id, - [ - { - id: 'editor-group', - tabs: [{ id: file.id, kind: 'editor', entry: { isPreview: true } }] - } - ], - 'runtime:hub-a' - ), - ...saved - }, - { mintId: () => 'group', mintLeafId: () => '00000000-0000-4000-8000-000000000001' } - ) - const roundTrip = JSON.parse(JSON.stringify(saveWorkspaceLayout(loaded))) - expect(roundTrip.openFilesByWorktree[id][0]).toMatchObject({ - filePath: file.filePath, - runtimeEnvironmentId: 'hub-a', - dirtyDraftContent: 'retained draft', - isPreview: true - }) - useAppStore.getState().hydrateEditorSession(roundTrip) - const restored = useAppStore.getState().openFiles[0] - expect(restored.id).toBe(file.id) - expect(useAppStore.getState().editorDrafts[restored.id]).toBe('retained draft') - expect(getEditorFileOperationContext(useAppStore.getState(), restored, '')).toMatchObject( - context - ) - expect(restored.operationProvenance).toBeUndefined() - expect(getEditorModelOwnerKey(restored, useAppStore.getState())).toBe( - JSON.stringify(['hub-a', 'runtime:hub-a']) - ) - let finishWrite!: (value: { ok: true }) => void - writeRuntimeFile.mockResolvedValue({ ok: true }).mockReturnValueOnce( - new Promise<{ ok: true }>((resolve) => { - finishWrite = resolve - }) - ) - const queue = createEditorSaveQueue(useAppStore) - useAppStore.getState().setLastKnownDiskSignature(restored.id, 'baseline') - useAppStore.getState().markFileDirty(restored.id, true) - const firstSave = queue.queueSave(useAppStore.getState().openFiles[0], 'first') - expect( - getEditorModelOwnerKey(useAppStore.getState().openFiles[0], useAppStore.getState()) - ).toBe(key) - await vi.waitFor(() => expect(writeRuntimeFile).toHaveBeenCalledOnce()) - expect(writeRuntimeFile.mock.calls[0][0]).toMatchObject(context) - useAppStore.getState().setEditorDraft(restored.id, 'queued revised draft') - const secondSave = queue.queueSave(useAppStore.getState().openFiles[0], 'second') - const settlement = secondSave.then( - (result) => ({ result, error: null }), - (error: unknown) => ({ result: null, error }) - ) - useAppStore.setState({ - projectGroups: [ - { - ...makeProjectGroup(), - id: 'physical-group', - executionHostId: 'runtime:hub-a', - connectionId: 'other' - } - ] - }) - finishWrite({ ok: true }) - await expect(firstSave).resolves.toBe('written') - const secondOutcome = await settlement - queue.dispose() - expect(writeRuntimeFile.mock.calls.map(([args]) => args.expectedExecutionHostId)).toEqual([ - 'ssh:box' - ]) - expect(secondOutcome.error).toMatchObject({ - message: expect.stringContaining('Reopen the file') - }) - expect(useAppStore.getState().editorDrafts[restored.id]).toBe('queued revised draft') - expect(() => getEditorFileOperationContext(useAppStore.getState(), file, '')).toThrow( - 'Reopen the file' - ) - const next = captureEditorFileOperationProvenance(useAppStore.getState(), id, 'hub-a', true) - expect(isSameOwnedDocument({ ...file, operationProvenance: next }, file)).toBe(false) - const replacement = { ...file, id: 'other-host', operationProvenance: next, isDirty: false } - useAppStore.setState((state) => ({ openFiles: [...state.openFiles, replacement] })) - expect(useAppStore.getState().editorBufferIdOf[replacement.id]).not.toBe( - useAppStore.getState().editorBufferIdOf[file.id] - ) - expect(useAppStore.getState().editorDrafts[replacement.id]).toBeUndefined() - const other = getEditorFileOperationContext( - useAppStore.getState(), - { ...file, operationProvenance: next }, - '' - ) - expect( - isOpenFileOnMoveOwner(useAppStore.getState(), file, editorMoveOwnerFromContext(other, id)) - ).toBe(false) - expect( - isOpenFileOnMoveOwner(useAppStore.getState(), file, editorMoveOwnerFromContext(context, id)) - ).toBe(true) - useAppStore.setState({ - projectGroups: [ - { - ...makeProjectGroup(), - id: 'physical-group', - executionHostId: 'runtime:hub-a', - connectionId: 'box' - } - ] - }) - useAppStore.setState((state) => ({ - sshStateByEnvironment: new Map([ - [ - 'hub-a', - { - ...state.sshStateByEnvironment.get('hub-a')!, - connectionStates: new Map([ - [ - 'box', - { - targetId: 'box', - status: 'connected' as const, - error: null, - reconnectAttempt: 0, - connectionGeneration: 8 - } - ] - ]) - } - ] - ]) - })) - const reconnected = { - ...file, - id: 'reconnected', - operationProvenance: incoming, - isDirty: false - } - useAppStore.setState((state) => ({ openFiles: [...state.openFiles, reconnected] })) - expect(useAppStore.getState().editorBufferIdOf[reconnected.id]).toBe( - useAppStore.getState().editorBufferIdOf[file.id] - ) - expect(useAppStore.getState().editorDrafts[reconnected.id]).toBe('queued revised draft') - expect(() => assertEditorFileOperationCurrent(useAppStore.getState(), id, provenance)).toThrow( - 'Reopen the file' - ) - }) - it('uses the explicit worktree owner instead of global runtime focus', () => { useAppStore.setState({ worktreesByRepo: { diff --git a/src/renderer/src/lib/execute-open-editor-path-move.test.ts b/src/renderer/src/lib/execute-open-editor-path-move.test.ts index 5a93ad8eee7..44a41122ade 100644 --- a/src/renderer/src/lib/execute-open-editor-path-move.test.ts +++ b/src/renderer/src/lib/execute-open-editor-path-move.test.ts @@ -26,10 +26,9 @@ vi.mock('@/components/editor/autosave/editor-autosave', async (importOriginal) = import { useAppStore } from '@/store' import { executeOpenEditorPathMove } from './execute-open-editor-path-move' -import { __activeEditorPathMoveCountForTests } from '@/components/editor/editor-path-move-inflight' -import { getDiskBaselineSignature } from '../../../shared/disk-baseline-signature' + import { captureWorktreeOperationGenerationSnapshot } from './worktree-operation-generation' -import { buildEditorExternalWatchEventHandler as createExternalWatchEventHandler } from '@/hooks/editor-external-watch-event-reconciliation' + import { drawTabsFromMain, type TabsDrawnFromMain @@ -76,32 +75,6 @@ describe('executeOpenEditorPathMove', () => { vi.unstubAllGlobals() }) - it('renames on disk, retargets the session in place, and installs the verify gate', async () => { - openDirtyTab() - - await executeOpenEditorPathMove({ - context: CONTEXT, - fromPath: '/repo/a.md', - toPath: '/repo/sub/a.md', - worktreeId: 'wt-1', - worktreePath: '/repo' - }) - - expect(mocks.renameRuntimePath).toHaveBeenCalledWith( - CONTEXT, - '/repo/a.md', - '/repo/sub/a.md', - undefined - ) - const moved = useAppStore.getState().openFiles[0]! - expect(moved.filePath).toBe('/repo/sub/a.md') - expect(moved.isDirty).toBe(true) - expect(moved.lastKnownDiskSignature).toBe('sig-a') - expect(useAppStore.getState().editorDrafts['/repo/sub/a.md']).toBe('unsaved work') - expect(moved.pendingSelfMoveEcho?.targetPath).toBe('/repo/sub/a.md') - expect(__activeEditorPathMoveCountForTests()).toBe(0) - }) - it('never retargets the same path open from a same-id workspace on a server', async () => { const localId = openDirtyTab() const state = useAppStore.getState() @@ -190,48 +163,6 @@ describe('executeOpenEditorPathMove', () => { expect(useAppStore.getState().openFiles[0]!.filePath).toBe('/repo/b.md') }) - it('does not raise a false banner when the destination watcher event lands after the move', async () => { - // FSEvents/SSH events may follow fast verification; consuming provenance early would mark our own rename as an external edit. - const DISK_CONTENT = 'the file as it exists on disk\n' - const id = openDirtyTab() - useAppStore.getState().setLastKnownDiskSignature(id, getDiskBaselineSignature(DISK_CONTENT)) - vi.stubGlobal('window', { - api: { - fs: { readFile: vi.fn().mockResolvedValue({ isBinary: false, content: DISK_CONTENT }) } - } - }) - - await executeOpenEditorPathMove({ - context: CONTEXT, - fromPath: '/repo/a.md', - toPath: '/repo/sub/a.md', - worktreeId: 'wt-1', - worktreePath: '/repo' - }) - await new Promise((resolve) => setTimeout(resolve, 20)) - - const { handleFsChanged, dispose } = createExternalWatchEventHandler((worktreePath) => - worktreePath === '/repo' - ? { - worktreeId: 'wt-1', - worktreePath: '/repo', - connectionId: undefined, - runtimeEnvironmentId: null - } - : undefined - ) - handleFsChanged({ - worktreePath: '/repo', - events: [{ kind: 'update', absolutePath: '/repo/sub/a.md' }] - }) - await new Promise((resolve) => setTimeout(resolve, 120)) - - const moved = useAppStore.getState().openFiles[0]! - expect(moved.externalMutation).toBeUndefined() - expect(moved.isDirty).toBe(true) - dispose() - }) - it('undoes the on-disk rename when the editor rekey collides', async () => { openDirtyTab() useAppStore.getState().openFile( @@ -271,54 +202,4 @@ describe('executeOpenEditorPathMove', () => { ) expect(useAppStore.getState().openFiles.map((f) => f.id)).toEqual(before) }) - - it('undoes a document-scoped rename with the renamed file as the document', async () => { - openDirtyTab() - useAppStore.getState().openFile( - { - filePath: '/repo/b.md', - relativePath: 'b.md', - worktreeId: 'wt-1', - runtimeEnvironmentId: null, - language: 'markdown', - mode: 'edit' - }, - { suppressActiveRuntimeFallback: true } - ) - - await expect( - executeOpenEditorPathMove({ - context: CONTEXT, - fromPath: '/repo/a.md', - toPath: '/repo/b.md', - worktreeId: 'wt-1', - worktreePath: '/repo', - documentScoped: true - }) - ).rejects.toThrow(/retarget/) - - expect(mocks.renameRuntimePath).toHaveBeenLastCalledWith(CONTEXT, '/repo/b.md', '/repo/a.md', { - kind: 'document-folder', - documentPath: '/repo/b.md' - }) - }) - - it('leaves the store untouched and settles the transaction when the rename fails', async () => { - openDirtyTab() - const before = useAppStore.getState().openFiles.map((f) => ({ ...f })) - mocks.renameRuntimePath.mockRejectedValue(new Error('EACCES')) - - await expect( - executeOpenEditorPathMove({ - context: CONTEXT, - fromPath: '/repo/a.md', - toPath: '/repo/sub/a.md', - worktreeId: 'wt-1', - worktreePath: '/repo' - }) - ).rejects.toThrow('EACCES') - - expect(useAppStore.getState().openFiles).toEqual(before) - expect(__activeEditorPathMoveCountForTests()).toBe(0) - }) }) diff --git a/src/renderer/src/lib/feedback-image-attachments.ts b/src/renderer/src/lib/feedback-image-attachments.ts index 910ea6f7fb9..f8e8cada69b 100644 --- a/src/renderer/src/lib/feedback-image-attachments.ts +++ b/src/renderer/src/lib/feedback-image-attachments.ts @@ -4,7 +4,7 @@ import { INVALID_RASTER_IMAGE_PREVIEW_ERROR, RASTER_IMAGE_PREVIEW_TOO_LARGE_ERROR, assertRasterImagePreviewWithinLimits -} from '../../../shared/raster-image-preview-limits' +} from '../../../shared/file-preview/raster-image-preview-limits' import { MAX_FEEDBACK_IMAGE_BYTES, MAX_FEEDBACK_IMAGE_COUNT, diff --git a/src/renderer/src/lib/file-artifact-source-key.ts b/src/renderer/src/lib/file-artifact-source-key.ts index 83f6c129c13..fe19731b139 100644 --- a/src/renderer/src/lib/file-artifact-source-key.ts +++ b/src/renderer/src/lib/file-artifact-source-key.ts @@ -1,4 +1,4 @@ -import { sshArtifactSourceKey } from '../../../shared/artifact-cli-bridge' +import { sshArtifactSourceKey } from '../../../shared/artifacts/artifact-cli-bridge' import { parseExecutionHostId, type ExecutionHostId } from '../../../shared/execution-host' /** The host a shared file is read from. */ diff --git a/src/renderer/src/lib/git-path-decoration.ts b/src/renderer/src/lib/git-path-decoration.ts index 4f3f95ef75a..9bcf02d51e8 100644 --- a/src/renderer/src/lib/git-path-decoration.ts +++ b/src/renderer/src/lib/git-path-decoration.ts @@ -1,6 +1,6 @@ import type { GitFileStatus, GitStatusEntry } from '../../../shared/git/status/git-status-types' -import { joinPath, normalizeRelativePath } from '@/lib/path' -import { splitPathSegments } from '../../../shared/cross-platform-path' +import { joinPath } from '@/lib/path' +import { normalizeRelativePath, splitPathSegments } from '../../../shared/cross-platform-path' export const STATUS_COLORS: Record = { modified: 'var(--git-decoration-modified)', diff --git a/src/renderer/src/lib/local-file-access.ts b/src/renderer/src/lib/local-file-access.ts index c09e5fcbacd..00efe036994 100644 --- a/src/renderer/src/lib/local-file-access.ts +++ b/src/renderer/src/lib/local-file-access.ts @@ -1,5 +1,5 @@ import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../shared/constants' -import type { LocalFileAccess } from '../../../shared/local-file-access' +import type { LocalFileAccess } from '../../../shared/file-access/local-file-access' import type { OpenFile } from '@/store/slices/editor/types/open-file' import { getConnectionIdForFile } from './connection-context' import { getRuntimeTargetForFileOwner } from './file-owner-runtime-target' diff --git a/src/renderer/src/lib/markdown-document-templates.ts b/src/renderer/src/lib/markdown-document-templates.ts index 02fbe92032d..d18d0da1ec9 100644 --- a/src/renderer/src/lib/markdown-document-templates.ts +++ b/src/renderer/src/lib/markdown-document-templates.ts @@ -1,4 +1,4 @@ -import type { DirEntry } from '../../../shared/filesystem-entry-types' +import type { DirEntry } from '../../../shared/file-listing/directory-entry' import type { RuntimeClientTarget } from '../../../shared/runtime-client-target' import type { RuntimeFileOperationArgs } from '@/runtime/files/runtime-file-client-types' import { readRuntimeDirectory } from '@/runtime/files/reads/runtime-directory-read' diff --git a/src/renderer/src/lib/native-file-drop-rejection-message.ts b/src/renderer/src/lib/native-file-drop-rejection-message.ts index f604a87907b..a94ff323201 100644 --- a/src/renderer/src/lib/native-file-drop-rejection-message.ts +++ b/src/renderer/src/lib/native-file-drop-rejection-message.ts @@ -2,7 +2,7 @@ import { translate } from '@/i18n/i18n' import { NATIVE_FILE_DROP_MAX_PATHS, type NativeFileDropRejectedPayload -} from '../../../shared/native-file-drop' +} from '../../../shared/file-import/native-file-drop' import { describeDropTempCopyFailure } from './drop-temp-copy-failure-copy' export function getNativeFileDropRejectionMessage(data: NativeFileDropRejectedPayload): { diff --git a/src/renderer/src/lib/open-document-in-floating-workspace.ts b/src/renderer/src/lib/open-document-in-floating-workspace.ts index 47d1069df02..420a0811a34 100644 --- a/src/renderer/src/lib/open-document-in-floating-workspace.ts +++ b/src/renderer/src/lib/open-document-in-floating-workspace.ts @@ -1,4 +1,4 @@ -import type { FileDocument } from '../../../shared/filesystem-entry-types' +import type { FileDocument } from '../../../shared/file-listing/file-document' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../shared/constants' import type { EditorFilesSlice } from '@/store/slices/editor/types/editor-files-slice' import { detectLanguage } from './language-detect' diff --git a/src/renderer/src/lib/os-file-drop-cancellation-guard.ts b/src/renderer/src/lib/os-file-drop-cancellation-guard.ts index cc9b50a7be3..beb4ef99f6e 100644 --- a/src/renderer/src/lib/os-file-drop-cancellation-guard.ts +++ b/src/renderer/src/lib/os-file-drop-cancellation-guard.ts @@ -1,4 +1,4 @@ -import { hasNativeFileDragTypes } from '../../../shared/native-file-drop' +import { hasNativeFileDragTypes } from '../../../shared/file-import/native-file-drop' import { WORKSPACE_FILE_DRAG_SOURCE_MIME, WORKSPACE_FILE_PATHS_MIME } from './workspace-file-drag' let disposeInstalledGuard: (() => void) | null = null diff --git a/src/renderer/src/lib/os-file-drop-preload-integration.test.tsx b/src/renderer/src/lib/os-file-drop-preload-integration.test.tsx index 10e52caf442..79aa99ca7c7 100644 --- a/src/renderer/src/lib/os-file-drop-preload-integration.test.tsx +++ b/src/renderer/src/lib/os-file-drop-preload-integration.test.tsx @@ -2,7 +2,7 @@ import { act, cleanup, render } from '@testing-library/react' import { useRef, useState } from 'react' import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' -import type { PreparedDroppedPaths } from '../../../shared/native-file-drop-preparation' +import type { PreparedDroppedPaths } from '../../../shared/file-import/native-file-drop-preparation' const electron = vi.hoisted(() => ({ on: vi.fn(), diff --git a/src/renderer/src/lib/os-file-drop-preparation.ts b/src/renderer/src/lib/os-file-drop-preparation.ts index 7e21bbd1ee2..7c0eb557254 100644 --- a/src/renderer/src/lib/os-file-drop-preparation.ts +++ b/src/renderer/src/lib/os-file-drop-preparation.ts @@ -1,11 +1,11 @@ import { createRejectedNativeFileDropPayload, validateNativeFileDropPaths -} from '../../../shared/native-file-drop' +} from '../../../shared/file-import/native-file-drop' import type { DroppedPathConsumer, PreparedDroppedPaths -} from '../../../shared/native-file-drop-preparation' +} from '../../../shared/file-import/native-file-drop-preparation' /** Validate OS file paths and let main temp-copy the ones that may vanish before delivery. */ export async function prepareOsFileDropPaths( diff --git a/src/renderer/src/lib/path.ts b/src/renderer/src/lib/path.ts index 6c31648a6bd..afacb9ed9f0 100644 --- a/src/renderer/src/lib/path.ts +++ b/src/renderer/src/lib/path.ts @@ -3,8 +3,6 @@ import { relativePathInsideRoot } from '../../../shared/cross-platform-path' -export { normalizeRelativePath } from '../../../shared/cross-platform-path' - function stripTrailingSeparators(path: string): string { return path.replace(/[\\/]+$/, '') } diff --git a/src/renderer/src/lib/runtime-workspace-file-route.ts b/src/renderer/src/lib/runtime-workspace-file-route.ts index 9d7b52b79e9..cedf680e252 100644 --- a/src/renderer/src/lib/runtime-workspace-file-route.ts +++ b/src/renderer/src/lib/runtime-workspace-file-route.ts @@ -3,7 +3,7 @@ import { toRuntimeExecutionHostId, type ExecutionHostId } from '../../../shared/execution-host' -import { findRuntimeWorkspaceFileOwner } from '../../../shared/runtime-workspace-file-owner' +import { findRuntimeWorkspaceFileOwner } from '../../../shared/file-access/runtime-workspace-file-owner' import { folderWorkspaceKey } from '../../../shared/workspace-scope' import type { AppState } from '@/store/types' import { getIndexedAllWorktrees } from '@/store/slices/worktrees/listing/worktree-catalog-index' diff --git a/src/renderer/src/lib/user-opened-local-path.ts b/src/renderer/src/lib/user-opened-local-path.ts index 796a5a0e163..7b2134cedfb 100644 --- a/src/renderer/src/lib/user-opened-local-path.ts +++ b/src/renderer/src/lib/user-opened-local-path.ts @@ -1,12 +1,12 @@ import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../shared/constants' -import { isPathOutsideAllowedDirectoriesError } from '../../../shared/local-file-access' +import { isPathOutsideAllowedDirectoriesError } from '../../../shared/file-access/local-file-access' import { isRemoteRuntimeFileOperation } from '@/runtime/files/runtime-file-routing' import { statRuntimePath } from '@/runtime/files/metadata/runtime-file-metadata-client' import { readRuntimeDirectory } from '@/runtime/files/reads/runtime-directory-read' import type { RuntimeFileOperationArgs } from '@/runtime/files/runtime-file-client-types' import { projectFolderLinkAccess, userNamedFileAccess } from './local-file-access' import { isPathInsideWorktree } from '../../../shared/terminal/links/terminal-links' -import type { DirEntry } from '../../../shared/filesystem-entry-types' +import type { DirEntry } from '../../../shared/file-listing/directory-entry' export type UserOpenedPathStat = { isDirectory: boolean diff --git a/src/renderer/src/lib/workspace-doc-address-input.ts b/src/renderer/src/lib/workspace-doc-address-input.ts index be2096ce866..bdb37c4632f 100644 --- a/src/renderer/src/lib/workspace-doc-address-input.ts +++ b/src/renderer/src/lib/workspace-doc-address-input.ts @@ -4,7 +4,7 @@ import type { BrowserPageDocLocation } from '../../../shared/browser-workspace-t import { getRelativePathInsideRoot, joinPath } from '@/lib/path' import { getWorkspaceFilePreviewPlan } from '@/lib/file-preview' import type { AppState } from '@/store/types' -import { htmlFilePathFromUrl } from '../../../shared/html-file-url' +import { htmlFilePathFromUrl } from '../../../shared/file-links/html-file-url' import { authorityKey } from '../../../shared/host-authority' import { resolveOwner } from './resolve-owner' import { translate } from '@/i18n/i18n' diff --git a/src/renderer/src/lib/workspace-file-drag.ts b/src/renderer/src/lib/workspace-file-drag.ts index bf8219853f9..4c3686fead4 100644 --- a/src/renderer/src/lib/workspace-file-drag.ts +++ b/src/renderer/src/lib/workspace-file-drag.ts @@ -3,7 +3,7 @@ import { NATIVE_FILE_DROP_MAX_PATH_BYTES, NATIVE_FILE_DROP_MAX_PATHS, validateNativeFileDropPaths -} from '../../../shared/native-file-drop' +} from '../../../shared/file-import/native-file-drop' import { measureClipboardTextByteLength } from '../../../shared/clipboard-text' import { isUnresolvedOwnerHostId, diff --git a/src/renderer/src/runtime/files/grants/runtime-terminal-artifact-grant.ts b/src/renderer/src/runtime/files/grants/runtime-terminal-artifact-grant.ts index 0f519d06f4a..dfb16eb21ee 100644 --- a/src/renderer/src/runtime/files/grants/runtime-terminal-artifact-grant.ts +++ b/src/renderer/src/runtime/files/grants/runtime-terminal-artifact-grant.ts @@ -1,19 +1,19 @@ import type { RuntimeClientTarget } from '../../../../../shared/runtime-client-target' -import { TERMINAL_ARTIFACT_CHUNK_RUNTIME_CAPABILITY } from '../../../../../shared/files-runtime-capabilities' +import { TERMINAL_ARTIFACT_CHUNK_RUNTIME_CAPABILITY } from '../../../../../shared/file-access/files-runtime-capabilities' import { SSH_OUTSIDE_WORKSPACE_UNSUPPORTED_MESSAGE, TERMINAL_ARTIFACT_IN_PLACE_MAX_BYTES, TERMINAL_PATH_ABSOLUTE_FILES_RUNTIME_CAPABILITY, TERMINAL_PATH_IN_PLACE_FILES_RUNTIME_CAPABILITY, type RuntimeTerminalPathResolution -} from '../../../../../shared/runtime-file-contracts' +} from '../../../../../shared/terminal/runtime-terminal-file-path' import { callRuntimeRpc } from '../../rpc/calls/runtime-rpc-call' import { runtimeEnvironmentSupportsCapability } from '../../rpc/compatibility/runtime-capability-proof' import { RuntimeRpcCallError } from '../../rpc/calls/runtime-rpc-result' import { readIpcErrorMessage } from '@/lib/ipc-error' import { toRuntimeWorktreeSelector } from '../../rpc/targets/runtime-worktree-selector' import { captureRuntimeEnvironmentRequestRevision } from '../../rpc/environment-revisions/runtime-environment-revision' -import { isRenewableTerminalFileGrantRefusal } from '../../../../../shared/terminal-file-grant-refusal' +import { isRenewableTerminalFileGrantRefusal } from '../../../../../shared/file-access/terminal-file-grant-refusal' export type TerminalArtifactGrantTarget = { target: RuntimeClientTarget & { kind: 'environment' } diff --git a/src/renderer/src/runtime/files/grants/runtime-terminal-artifact-write.test.ts b/src/renderer/src/runtime/files/grants/runtime-terminal-artifact-write.test.ts index 6e34a69ce88..9ccb4a28537 100644 --- a/src/renderer/src/runtime/files/grants/runtime-terminal-artifact-write.test.ts +++ b/src/renderer/src/runtime/files/grants/runtime-terminal-artifact-write.test.ts @@ -4,30 +4,15 @@ import { runtimeEnvironmentCall, installRuntimeFileClientEnvironment } from '../runtime-file-client-test-harness' -import { getDiskBaselineSignature } from '../../../../../shared/disk-baseline-signature' +import { getDiskBaselineSignature } from '../../../../../shared/file-write/disk-baseline-signature' installRuntimeFileClientEnvironment() const PATH = '/private/tmp/handoff.md' const meta = { runtimeId: 'remote-runtime' } const ok = (result: unknown) => ({ id: 'rpc', ok: true, result, _meta: meta }) -const refused = (message: string) => ({ - id: 'rpc', - ok: false, - error: { code: 'runtime_error', message }, - _meta: meta -}) const read = (content: string) => ok({ worktree: 'wt-1', relativePath: PATH, content, truncated: false, byteLength: 1 }) -const granted = (grantId: string) => - ok({ - worktree: 'wt-1', - relativePath: null, - absolutePath: PATH, - exists: true, - isDirectory: false, - openTarget: { kind: 'absolute-file', provider: 'local', absolutePath: PATH, grantId } - }) function save(content: string, baseline: string, onGrantRenewed?: (grantId: string) => void) { return writeRuntimeTerminalArtifactFile({ @@ -41,31 +26,7 @@ function save(content: string, baseline: string, onGrantRenewed?: (grantId: stri }) } -function grantIdOf(params: unknown): string | undefined { - return typeof params === 'object' && params !== null && 'grantId' in params - ? String(params.grantId) - : undefined -} - describe('saving a granted host file outside every workspace', () => { - // Why: a host change stales the grant; the renewed read must still raise the conflict banner. - it('reports a host-side change behind a stale grant as a conflict', async () => { - runtimeEnvironmentCall.mockImplementation(async ({ method, params }) => { - if (method === 'files.resolveTerminalPath') { - return granted('g-2') - } - if (grantIdOf(params) === 'g-1') { - return refused('terminal_file_grant_stale') - } - return method === 'files.readTerminalArtifact' ? read('# theirs') : ok({ ok: true }) - }) - - await expect(save('# new', '# old')).resolves.toEqual({ ok: false, diskConflict: 'changed' }) - expect(runtimeEnvironmentCall.mock.calls.map(([call]) => call)).not.toContainEqual( - expect.objectContaining({ method: 'files.writeTerminalArtifact' }) - ) - }) - // Why: desktop delivers a lost reply as a runtime_timeout envelope, not a thrown transport error. it('reads back after a desktop timeout envelope and still rejects when the old text remains', async () => { const timedOut = { diff --git a/src/renderer/src/runtime/files/grants/runtime-terminal-artifact-write.ts b/src/renderer/src/runtime/files/grants/runtime-terminal-artifact-write.ts index 41577a9f5b4..a5056f4ba10 100644 --- a/src/renderer/src/runtime/files/grants/runtime-terminal-artifact-write.ts +++ b/src/renderer/src/runtime/files/grants/runtime-terminal-artifact-write.ts @@ -1,4 +1,4 @@ -import type { RuntimeFileReadResult } from '../../../../../shared/runtime-file-contracts' +import type { RuntimeFileReadResult } from '../../../../../shared/file-content/runtime-file-read' import { compareDiskWritePrecondition, isConfirmedFileNotFoundError, @@ -6,7 +6,7 @@ import { FILE_WRITE_UNCHANGED, type FileWriteDiskPrecondition, type FileWriteResult -} from '../../../../../shared/file-write-disk-precondition' +} from '../../../../../shared/file-write/file-write-disk-precondition' import { callRuntimeRpc } from '../../rpc/calls/runtime-rpc-call' import { RuntimeRpcCallError } from '../../rpc/calls/runtime-rpc-result' import { toRuntimeWorktreeSelector } from '../../rpc/targets/runtime-worktree-selector' diff --git a/src/renderer/src/runtime/files/imports/runtime-file-import-client.ts b/src/renderer/src/runtime/files/imports/runtime-file-import-client.ts index 905a74711a9..6d64142af65 100644 --- a/src/renderer/src/runtime/files/imports/runtime-file-import-client.ts +++ b/src/renderer/src/runtime/files/imports/runtime-file-import-client.ts @@ -1,5 +1,5 @@ import { joinPath } from '@/lib/path' -import type { ImportItemResult } from '../../../../../shared/filesystem-import-result-types' +import type { ImportItemResult } from '../../../../../shared/file-import/filesystem-import-result' import { deconflictCopyName } from '../../../../../shared/import-copy-name' import { getRuntimeEnvironmentConnectionGeneration } from '@/store/slices/runtime-status/runtime-status-connection-generation' import type { RuntimeFileOperationArgs } from '../runtime-file-client-types' @@ -23,7 +23,7 @@ import { uploadRuntimeFileWithoutClobber } from './runtime-file-upload-client' import { toRuntimeWorktreeSelector } from '../../rpc/targets/runtime-worktree-selector' -import type { LocalFileAccess } from '../../../../../shared/local-file-access' +import type { LocalFileAccess } from '../../../../../shared/file-access/local-file-access' export async function importExternalPathsToRuntime( context: RuntimeFileOperationArgs, diff --git a/src/renderer/src/runtime/files/imports/runtime-file-import-pairing-revision.test.ts b/src/renderer/src/runtime/files/imports/runtime-file-import-pairing-revision.test.ts index e72d63ae849..83588cb6ce4 100644 --- a/src/renderer/src/runtime/files/imports/runtime-file-import-pairing-revision.test.ts +++ b/src/renderer/src/runtime/files/imports/runtime-file-import-pairing-revision.test.ts @@ -10,7 +10,7 @@ import { setRuntimeEnvironmentConnectionGenerationForTests } from '@/store/slices/runtime-status/runtime-status-connection-generation' -import { FILE_MUTATION_OWNERSHIP_RUNTIME_CAPABILITY } from '../../../../../shared/files-runtime-capabilities' +import { FILE_MUTATION_OWNERSHIP_RUNTIME_CAPABILITY } from '../../../../../shared/file-access/files-runtime-capabilities' import { MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION, RUNTIME_PROTOCOL_VERSION diff --git a/src/renderer/src/runtime/files/imports/runtime-file-upload-client.ts b/src/renderer/src/runtime/files/imports/runtime-file-upload-client.ts index 6652ce41188..2c190ff537c 100644 --- a/src/renderer/src/runtime/files/imports/runtime-file-upload-client.ts +++ b/src/renderer/src/runtime/files/imports/runtime-file-upload-client.ts @@ -1,7 +1,7 @@ import { extractIpcErrorMessage } from '@/lib/ipc-error' import { joinPath } from '@/lib/path' import { normalizeRelativePath } from '../../../../../shared/cross-platform-path' -import type { StagedRuntimeUploadFileIdentity } from '../../../../../shared/runtime-upload-staging-contract' +import type { StagedRuntimeUploadFileIdentity } from '../../../../../shared/file-import/runtime-upload-staging-contract' import { DROP_STAGING_GITIGNORE_CONTENT, DROP_STAGING_RELATIVE_DIR diff --git a/src/renderer/src/runtime/files/metadata/runtime-file-metadata-client.ts b/src/renderer/src/runtime/files/metadata/runtime-file-metadata-client.ts index 896b29a200a..ec158f1013e 100644 --- a/src/renderer/src/runtime/files/metadata/runtime-file-metadata-client.ts +++ b/src/renderer/src/runtime/files/metadata/runtime-file-metadata-client.ts @@ -1,4 +1,4 @@ -import type { MarkdownDocument } from '../../../../../shared/filesystem-entry-types' +import type { MarkdownDocument } from '../../../../../shared/file-listing/file-document' import type { RuntimeFileOperationArgs } from '../runtime-file-client-types' import { assertLocalFilesystemFallbackAllowed, @@ -7,7 +7,7 @@ import { } from '../runtime-file-routing' import { callRuntimeRpc } from '../../rpc/calls/runtime-rpc-call' import { toRuntimeWorktreeSelector } from '../../rpc/targets/runtime-worktree-selector' -import type { LocalFileAccess } from '../../../../../shared/local-file-access' +import type { LocalFileAccess } from '../../../../../shared/file-access/local-file-access' export async function listRuntimeMarkdownDocuments( context: RuntimeFileOperationArgs, diff --git a/src/renderer/src/runtime/files/metadata/runtime-path-existence-batch.ts b/src/renderer/src/runtime/files/metadata/runtime-path-existence-batch.ts index d8522d00e56..ebb3f2fdeb4 100644 --- a/src/renderer/src/runtime/files/metadata/runtime-path-existence-batch.ts +++ b/src/renderer/src/runtime/files/metadata/runtime-path-existence-batch.ts @@ -3,7 +3,7 @@ import { PATH_EXISTENCE_BATCH_CAPABILITY, requirePathExistenceResults, type PathExistenceResult -} from '../../../../../shared/path-existence-batch' +} from '../../../../../shared/file-access/path-existence-batch' import type { RuntimeFileOperationArgs } from '../runtime-file-client-types' import { assertLocalFilesystemFallbackAllowed, getRemoteFileArgs } from '../runtime-file-routing' import { isMissingRuntimePathError, runtimePathExists } from './runtime-file-metadata-client' diff --git a/src/renderer/src/runtime/files/mutations/runtime-file-bytes-write.ts b/src/renderer/src/runtime/files/mutations/runtime-file-bytes-write.ts index d1280dfff59..0d894dc652a 100644 --- a/src/renderer/src/runtime/files/mutations/runtime-file-bytes-write.ts +++ b/src/renderer/src/runtime/files/mutations/runtime-file-bytes-write.ts @@ -6,12 +6,12 @@ import { FILE_REPLACE_WITH_UPLOAD_METHOD, FILE_REPLACE_WITH_UPLOAD_RUNTIME_CAPABILITY, type FileBytesWritePrecondition -} from '../../../../../shared/file-bytes-write' +} from '../../../../../shared/file-write/file-bytes-write' import { parseFileWriteResult, type FileWriteResult -} from '../../../../../shared/file-write-disk-precondition' -import type { LocalFileAccess } from '../../../../../shared/local-file-access' +} from '../../../../../shared/file-write/file-write-disk-precondition' +import type { LocalFileAccess } from '../../../../../shared/file-access/local-file-access' import type { RuntimeFileOperationArgs } from '../runtime-file-client-types' import { callRuntimeFileMutation, diff --git a/src/renderer/src/runtime/files/mutations/runtime-file-client-mutation-ownership.test.ts b/src/renderer/src/runtime/files/mutations/runtime-file-client-mutation-ownership.test.ts deleted file mode 100644 index e59c5adf29b..00000000000 --- a/src/renderer/src/runtime/files/mutations/runtime-file-client-mutation-ownership.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { FILE_MUTATION_OWNERSHIP_RUNTIME_CAPABILITY } from '../../../../../shared/files-runtime-capabilities' -import { deleteRuntimePath, writeRuntimeFile } from './runtime-file-mutation-client' -import { - MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION, - RUNTIME_PROTOCOL_VERSION -} from '../../../../../shared/protocol-version' -import { - runtimeEnvironmentCall, - runtimeEnvironmentTransportCall, - installRuntimeFileClientEnvironment -} from '../runtime-file-client-test-harness' - -installRuntimeFileClientEnvironment() - -describe('runtime file client mutation capability', () => { - it('refuses deletion after a HUB loses mutation support', async () => { - let statusCalls = 0 - runtimeEnvironmentTransportCall.mockImplementation((args: { method: string }) => { - if (args.method === 'status.get') { - statusCalls += 1 - return Promise.resolve({ - id: 'status', - ok: true, - result: { - runtimeProtocolVersion: RUNTIME_PROTOCOL_VERSION, - minCompatibleRuntimeClientVersion: MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION, - capabilities: statusCalls === 1 ? [FILE_MUTATION_OWNERSHIP_RUNTIME_CAPABILITY] : [] - }, - _meta: { runtimeId: statusCalls === 1 ? 'new-hub-runtime' : 'old-hub-runtime' } - }) - } - return runtimeEnvironmentCall(args) - }) - runtimeEnvironmentCall.mockResolvedValue({ - id: 'write', - ok: true, - result: { ok: true }, - _meta: { runtimeId: 'new-hub-runtime' } - }) - const context = { - target: { kind: 'environment' as const, environmentId: 'env-downgraded' }, - worktreeId: 'wt-hub-local', - worktreePath: '/hub/repo', - expectedExecutionHostId: 'local' as const - } - - await writeRuntimeFile(context, '/hub/repo/readme.md', 'first') - await expect(deleteRuntimePath(context, '/hub/repo/readme.md')).rejects.toBeInstanceOf(Error) - - expect(runtimeEnvironmentCall).not.toHaveBeenCalledWith( - expect.objectContaining({ method: 'files.delete' }) - ) - }) -}) diff --git a/src/renderer/src/runtime/files/mutations/runtime-file-mutation-client.ts b/src/renderer/src/runtime/files/mutations/runtime-file-mutation-client.ts index eb684f5963a..09d27e20c93 100644 --- a/src/renderer/src/runtime/files/mutations/runtime-file-mutation-client.ts +++ b/src/renderer/src/runtime/files/mutations/runtime-file-mutation-client.ts @@ -11,14 +11,14 @@ import { } from '../runtime-file-routing' import { callRuntimeFileMutation } from './runtime-file-mutation-rpc' import { toRuntimeWorktreeSelector } from '../../rpc/targets/runtime-worktree-selector' -import type { LocalFileAccess } from '../../../../../shared/local-file-access' +import type { LocalFileAccess } from '../../../../../shared/file-access/local-file-access' import { REMOTE_RUNTIME_MAX_FILE_WRITE_CONTENT_BYTES } from '../../../../../shared/remote-runtime/remote-runtime-memory-limits' import { FILE_WRITE_OK, parseFileWriteResult, type FileWriteDiskPrecondition, type FileWriteResult -} from '../../../../../shared/file-write-disk-precondition' +} from '../../../../../shared/file-write/file-write-disk-precondition' import { writeRemoteFileIfUnchanged } from './runtime-file-write-disk-precondition' import { writeRemoteFileStaged } from './runtime-staged-file-save' diff --git a/src/renderer/src/runtime/files/mutations/runtime-file-mutation-rpc.ts b/src/renderer/src/runtime/files/mutations/runtime-file-mutation-rpc.ts index 2c5e0d9876c..2a385998021 100644 --- a/src/renderer/src/runtime/files/mutations/runtime-file-mutation-rpc.ts +++ b/src/renderer/src/runtime/files/mutations/runtime-file-mutation-rpc.ts @@ -1,6 +1,6 @@ import type { RuntimeStatus } from '../../../../../shared/runtime-session-contracts' import { RUNTIME_CONNECTION_CHANGED_MESSAGE } from '../../../web/web-runtime-request-registry' -import { assertFileMutationOwnershipCapability } from '../../../../../shared/file-mutation-ownership' +import { assertFileMutationOwnershipCapability } from '../../../../../shared/file-write/file-mutation-ownership' import { callRuntimeRpc } from '../../rpc/calls/runtime-rpc-call' import { RuntimeRpcCallError } from '../../rpc/calls/runtime-rpc-result' import { diff --git a/src/renderer/src/runtime/files/mutations/runtime-file-write-disk-precondition.test.ts b/src/renderer/src/runtime/files/mutations/runtime-file-write-disk-precondition.test.ts index 650ebbba8a3..04602942916 100644 --- a/src/renderer/src/runtime/files/mutations/runtime-file-write-disk-precondition.test.ts +++ b/src/renderer/src/runtime/files/mutations/runtime-file-write-disk-precondition.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' import { writeRuntimeFile } from './runtime-file-mutation-client' -import { FILE_MUTATION_OWNERSHIP_RUNTIME_CAPABILITY } from '../../../../../shared/files-runtime-capabilities' +import { FILE_MUTATION_OWNERSHIP_RUNTIME_CAPABILITY } from '../../../../../shared/file-access/files-runtime-capabilities' import { MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION, RUNTIME_PROTOCOL_VERSION @@ -8,8 +8,8 @@ import { import { FILE_WRITE_DISK_PRECONDITION_RUNTIME_CAPABILITY, FILE_WRITE_IDENTICAL_RUNTIME_CAPABILITY -} from '../../../../../shared/file-write-disk-precondition' -import { getDiskBaselineSignature } from '../../../../../shared/disk-baseline-signature' +} from '../../../../../shared/file-write/file-write-disk-precondition' +import { getDiskBaselineSignature } from '../../../../../shared/file-write/disk-baseline-signature' import { advanceRuntimeEnvironmentConnectionGeneration } from '@/store/slices/runtime-status/runtime-status-connection-generation' import { replaceRuntimeEnvironmentRevisions } from '../../rpc/environment-revisions/runtime-environment-revision' import { diff --git a/src/renderer/src/runtime/files/mutations/runtime-file-write-disk-precondition.ts b/src/renderer/src/runtime/files/mutations/runtime-file-write-disk-precondition.ts index 82369ec25db..5ed65d3895d 100644 --- a/src/renderer/src/runtime/files/mutations/runtime-file-write-disk-precondition.ts +++ b/src/renderer/src/runtime/files/mutations/runtime-file-write-disk-precondition.ts @@ -10,11 +10,11 @@ import { type FileWriteDiskComparison, type FileWriteDiskPrecondition, type FileWriteResult -} from '../../../../../shared/file-write-disk-precondition' +} from '../../../../../shared/file-write/file-write-disk-precondition' import { getDiskBaselineSignature, getWrittenContentDiskSignature -} from '../../../../../shared/disk-baseline-signature' +} from '../../../../../shared/file-write/disk-baseline-signature' import { isRecoverableRemoteRuntimeConnectionError, toRemoteRuntimeClientErrorLike diff --git a/src/renderer/src/runtime/files/mutations/runtime-staged-file-save.ts b/src/renderer/src/runtime/files/mutations/runtime-staged-file-save.ts index 950d0a8a686..9b2efba5388 100644 --- a/src/renderer/src/runtime/files/mutations/runtime-staged-file-save.ts +++ b/src/renderer/src/runtime/files/mutations/runtime-staged-file-save.ts @@ -8,12 +8,12 @@ import { parseFileWriteResult, type FileWriteDiskPrecondition, type FileWriteResult -} from '../../../../../shared/file-write-disk-precondition' +} from '../../../../../shared/file-write/file-write-disk-precondition' import { STAGED_FILE_SAVE_CHUNK_BYTES, STAGED_FILE_SAVE_METHODS, STAGED_FILE_SAVE_RUNTIME_CAPABILITY -} from '../../../../../shared/staged-file-save' +} from '../../../../../shared/file-write/staged-file-save' import { getRuntimeEnvironmentConnectionGeneration } from '@/store/slices/runtime-status/runtime-status-connection-generation' import { callRuntimeRpc } from '../../rpc/calls/runtime-rpc-call' import { captureRuntimeEnvironmentRequestRevision } from '../../rpc/environment-revisions/runtime-environment-revision' diff --git a/src/renderer/src/runtime/files/reads/runtime-directory-page-client.test.ts b/src/renderer/src/runtime/files/reads/runtime-directory-page-client.test.ts index 58b1a095518..b62aa57a043 100644 --- a/src/renderer/src/runtime/files/reads/runtime-directory-page-client.test.ts +++ b/src/renderer/src/runtime/files/reads/runtime-directory-page-client.test.ts @@ -1,5 +1,5 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import { FILE_READ_DIR_PAGED_RUNTIME_CAPABILITY } from '../../../../../shared/files-runtime-capabilities' +import { FILE_READ_DIR_PAGED_RUNTIME_CAPABILITY } from '../../../../../shared/file-access/files-runtime-capabilities' const callRuntimeRpc = vi.fn() const readRuntimeDirectory = vi.fn() diff --git a/src/renderer/src/runtime/files/reads/runtime-directory-page-client.ts b/src/renderer/src/runtime/files/reads/runtime-directory-page-client.ts index bc02a08ccae..0d21ddd1678 100644 --- a/src/renderer/src/runtime/files/reads/runtime-directory-page-client.ts +++ b/src/renderer/src/runtime/files/reads/runtime-directory-page-client.ts @@ -1,12 +1,12 @@ import { useAppStore } from '@/store/index' -import type { DirEntry } from '../../../../../shared/filesystem-entry-types' +import type { DirEntry } from '../../../../../shared/file-listing/directory-entry' import { dirEntryPageAfter, type DirEntryCursor, type DirEntryPage -} from '../../../../../shared/file-dir-page' -import { sortDirEntries } from '../../../../../shared/file-name-sort' -import { FILE_READ_DIR_PAGED_RUNTIME_CAPABILITY } from '../../../../../shared/files-runtime-capabilities' +} from '../../../../../shared/file-listing/file-dir-page' +import { sortDirEntries } from '../../../../../shared/file-listing/file-name-sort' +import { FILE_READ_DIR_PAGED_RUNTIME_CAPABILITY } from '../../../../../shared/file-access/files-runtime-capabilities' import { isRuntimeHostContactRevoked, lastVerifiedRuntimeStatus diff --git a/src/renderer/src/runtime/files/reads/runtime-directory-read.ts b/src/renderer/src/runtime/files/reads/runtime-directory-read.ts index 6f6eee08f3a..f2112fbc579 100644 --- a/src/renderer/src/runtime/files/reads/runtime-directory-read.ts +++ b/src/renderer/src/runtime/files/reads/runtime-directory-read.ts @@ -1,5 +1,5 @@ -import type { DirEntry } from '../../../../../shared/filesystem-entry-types' -import type { LocalFileAccess } from '../../../../../shared/local-file-access' +import type { DirEntry } from '../../../../../shared/file-listing/directory-entry' +import type { LocalFileAccess } from '../../../../../shared/file-access/local-file-access' import type { RuntimeFileOperationArgs } from '../runtime-file-client-types' import { assertLocalFilesystemFallbackAllowed, getRemoteFileArgs } from '../runtime-file-routing' import { callRuntimeRpc } from '../../rpc/calls/runtime-rpc-call' diff --git a/src/renderer/src/runtime/files/reads/runtime-file-range-client.ts b/src/renderer/src/runtime/files/reads/runtime-file-range-client.ts index 3112522091f..2e7ec5a3d73 100644 --- a/src/renderer/src/runtime/files/reads/runtime-file-range-client.ts +++ b/src/renderer/src/runtime/files/reads/runtime-file-range-client.ts @@ -1,6 +1,6 @@ -import type { RuntimeFileReadChunkResult } from '../../../../../shared/runtime-file-contracts' +import type { RuntimeFileReadChunkResult } from '../../../../../shared/file-content/runtime-file-read' import type { RuntimeClientTarget } from '../../../../../shared/runtime-client-target' -import { validateFileRangeRequest } from '../../../../../shared/file-range-read' +import { validateFileRangeRequest } from '../../../../../shared/file-content/file-range-read' import type { RuntimeFileReadArgs } from '../runtime-file-client-types' import { assertExternalSshReadOwnership, canReadRelativeRuntimeFile } from '../runtime-file-routing' import { callRuntimeRpc } from '../../rpc/calls/runtime-rpc-call' @@ -10,7 +10,7 @@ import { decodeBase64Bytes } from '@/lib/base64-bytes' import { remoteFileRequest, type RemoteFileLocator -} from '../../../../../shared/remote-file-locator' +} from '../../../../../shared/file-access/remote-file-locator' /** A file on a paired runtime, addressed the way its host's `files.*` methods expect. */ export type RuntimeRemoteFileAddress = { diff --git a/src/renderer/src/runtime/files/reads/runtime-file-range-preview.ts b/src/renderer/src/runtime/files/reads/runtime-file-range-preview.ts index 1367d2dc04b..8a38acd2bb3 100644 --- a/src/renderer/src/runtime/files/reads/runtime-file-range-preview.ts +++ b/src/renderer/src/runtime/files/reads/runtime-file-range-preview.ts @@ -1,5 +1,5 @@ -import { filePreviewForPath } from '../../../../../shared/file-preview-kind' -import { remoteFilePath } from '../../../../../shared/remote-file-locator' +import { filePreviewForPath } from '../../../../../shared/file-preview/file-preview-kind' +import { remoteFilePath } from '../../../../../shared/file-access/remote-file-locator' import type { RuntimeRemoteFileAddress } from './runtime-file-range-client' import type { RuntimeReadableFileContent } from '../runtime-file-client-types' diff --git a/src/renderer/src/runtime/files/reads/runtime-file-read-client.ts b/src/renderer/src/runtime/files/reads/runtime-file-read-client.ts index 7db5e1dc9ff..27077d51563 100644 --- a/src/renderer/src/runtime/files/reads/runtime-file-read-client.ts +++ b/src/renderer/src/runtime/files/reads/runtime-file-read-client.ts @@ -1,4 +1,4 @@ -import type { RuntimeFilePreviewResult } from '../../../../../shared/runtime-file-contracts' +import type { RuntimeFilePreviewResult } from '../../../../../shared/file-content/runtime-file-read' import { callRuntimeRpc } from '../../rpc/calls/runtime-rpc-call' import type { RuntimeFileDownloadResult, @@ -17,8 +17,8 @@ import { toRuntimeWorktreeSelector } from '../../rpc/targets/runtime-worktree-se import { chatScratchFileAddress } from '../addressing/runtime-chat-scratch-file-address' import { readRemoteFileContent } from './runtime-remote-file-content' import { isAgentSessionAttachmentStorePath } from '../../../../../shared/agent-session/agent-session-attachments' -import { decodeSvgBase64, isSvgFilePath } from '../../../../../shared/svg-document' -import type { LocalFileAccess } from '../../../../../shared/local-file-access' +import { decodeSvgBase64, isSvgFilePath } from '../../../../../shared/file-preview/svg-document' +import type { LocalFileAccess } from '../../../../../shared/file-access/local-file-access' import { isHostFileOutsideWorkspaces, readHostFilePreview, diff --git a/src/renderer/src/runtime/files/reads/runtime-paged-file-read.ts b/src/renderer/src/runtime/files/reads/runtime-paged-file-read.ts index 62e82beb84a..418b33cb8d0 100644 --- a/src/renderer/src/runtime/files/reads/runtime-paged-file-read.ts +++ b/src/renderer/src/runtime/files/reads/runtime-paged-file-read.ts @@ -1,12 +1,12 @@ -import { BINARY_PROBE_BYTES } from '../../../../../shared/binary-buffer' +import { BINARY_PROBE_BYTES } from '../../../../../shared/file-preview/binary-buffer' import { IMAGE_AND_PDF_PREVIEW_MIME_TYPES, filePreviewExtension -} from '../../../../../shared/file-preview-kind' +} from '../../../../../shared/file-preview/file-preview-kind' import type { RuntimeFilePreviewResult, RuntimeFileReadChunkResult -} from '../../../../../shared/runtime-file-contracts' +} from '../../../../../shared/file-content/runtime-file-read' import { rangeReadTarget, readRemoteRuntimeFileChunk, @@ -18,9 +18,12 @@ import { import { RuntimeRpcCallError } from '../../rpc/calls/runtime-rpc-result' import { callRuntimeRpc } from '../../rpc/calls/runtime-rpc-call' import { captureRuntimeEnvironmentRequestRevision } from '../../rpc/environment-revisions/runtime-environment-revision' -import { MAX_FILE_RANGE_READ_BYTES } from '../../../../../shared/file-range-read' +import { MAX_FILE_RANGE_READ_BYTES } from '../../../../../shared/file-content/file-range-read' import type { RuntimeFileReadArgs } from '../runtime-file-client-types' -import { remoteFilePath, remoteFileRequest } from '../../../../../shared/remote-file-locator' +import { + remoteFilePath, + remoteFileRequest +} from '../../../../../shared/file-access/remote-file-locator' import { isRenewableGrantError, renewTerminalArtifactGrant diff --git a/src/renderer/src/runtime/files/reads/runtime-remote-file-content.ts b/src/renderer/src/runtime/files/reads/runtime-remote-file-content.ts index 6d6a9c605d7..1d1c9436731 100644 --- a/src/renderer/src/runtime/files/reads/runtime-remote-file-content.ts +++ b/src/renderer/src/runtime/files/reads/runtime-remote-file-content.ts @@ -1,6 +1,6 @@ -import type { RuntimeFileReadResult } from '../../../../../shared/runtime-file-contracts' -import { BINARY_PROBE_BYTES } from '../../../../../shared/binary-buffer' -import { remoteFileRequest } from '../../../../../shared/remote-file-locator' +import type { RuntimeFileReadResult } from '../../../../../shared/file-content/runtime-file-read' +import { BINARY_PROBE_BYTES } from '../../../../../shared/file-preview/binary-buffer' +import { remoteFileRequest } from '../../../../../shared/file-access/remote-file-locator' import type { RuntimeReadableFileContent } from '../runtime-file-client-types' import type { RuntimeRemoteFileAddress } from './runtime-file-range-client' import { readRemoteRangePreview } from './runtime-file-range-preview' diff --git a/src/renderer/src/runtime/files/reads/runtime-remote-file-download.ts b/src/renderer/src/runtime/files/reads/runtime-remote-file-download.ts index b4bf58d679c..1eb2c4a5eaa 100644 --- a/src/renderer/src/runtime/files/reads/runtime-remote-file-download.ts +++ b/src/renderer/src/runtime/files/reads/runtime-remote-file-download.ts @@ -1,7 +1,7 @@ import type { RuntimeFilePreviewResult, RuntimeFileReadChunkResult -} from '../../../../../shared/runtime-file-contracts' +} from '../../../../../shared/file-content/runtime-file-read' import { callRuntimeRpc } from '../../rpc/calls/runtime-rpc-call' import { RuntimeRpcCallError } from '../../rpc/calls/runtime-rpc-result' import type { RuntimeFileDownloadResult } from '../runtime-file-client-types' diff --git a/src/renderer/src/runtime/files/reads/runtime-server-directory-browser.ts b/src/renderer/src/runtime/files/reads/runtime-server-directory-browser.ts index 619d971a2aa..aa1eb408536 100644 --- a/src/renderer/src/runtime/files/reads/runtime-server-directory-browser.ts +++ b/src/renderer/src/runtime/files/reads/runtime-server-directory-browser.ts @@ -1,5 +1,6 @@ -import type { DirEntry, FilesystemPathFlavor } from '../../../../../shared/filesystem-entry-types' -import { sortDirEntries } from '../../../../../shared/file-name-sort' +import type { DirEntry } from '../../../../../shared/file-listing/directory-entry' +import type { FilesystemPathFlavor } from '../../../../../shared/file-access/filesystem-path-flavor' +import { sortDirEntries } from '../../../../../shared/file-listing/file-name-sort' import { callRuntimeRpc } from '../../rpc/calls/runtime-rpc-call' export type RuntimeServerDirectoryListing = { diff --git a/src/renderer/src/runtime/files/runtime-file-client-test-harness.ts b/src/renderer/src/runtime/files/runtime-file-client-test-harness.ts index 519ca4b51ca..7a90a3ac937 100644 --- a/src/renderer/src/runtime/files/runtime-file-client-test-harness.ts +++ b/src/renderer/src/runtime/files/runtime-file-client-test-harness.ts @@ -3,7 +3,7 @@ import type { Mock } from 'vitest' import { clearRuntimeCompatibilityCache as clearRuntimeCompatibilityCacheForTests } from '../rpc/compatibility/runtime-compatibility-cache' import { replaceRuntimeEnvironmentRevisions } from '../rpc/environment-revisions/runtime-environment-revision' import { clearLegacyQuickOpenInventoryCacheForTests } from './search/runtime-legacy-quick-open-inventory' -import { FILE_MUTATION_OWNERSHIP_RUNTIME_CAPABILITY } from '../../../../shared/files-runtime-capabilities' +import { FILE_MUTATION_OWNERSHIP_RUNTIME_CAPABILITY } from '../../../../shared/file-access/files-runtime-capabilities' import { MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION, RUNTIME_PROTOCOL_VERSION diff --git a/src/renderer/src/runtime/files/runtime-file-client-types.ts b/src/renderer/src/runtime/files/runtime-file-client-types.ts index cb6c79fff24..c6ea09c5bb7 100644 --- a/src/renderer/src/runtime/files/runtime-file-client-types.ts +++ b/src/renderer/src/runtime/files/runtime-file-client-types.ts @@ -1,5 +1,5 @@ import type { RuntimeClientTarget } from '../../../../shared/runtime-client-target' -import type { LocalFileAccess } from '../../../../shared/local-file-access' +import type { LocalFileAccess } from '../../../../shared/file-access/local-file-access' export type RuntimeReadableFileContent = { mediaUrl?: string diff --git a/src/renderer/src/runtime/files/runtime-file-routing.ts b/src/renderer/src/runtime/files/runtime-file-routing.ts index cceba08ec1d..d44e6c49f3e 100644 --- a/src/renderer/src/runtime/files/runtime-file-routing.ts +++ b/src/renderer/src/runtime/files/runtime-file-routing.ts @@ -7,7 +7,7 @@ import type { RuntimeClientTarget } from '../../../../shared/runtime-client-targ import { toRuntimeWorktreeSelector } from '../rpc/targets/runtime-worktree-selector' import type { RuntimeFileOperationArgs } from './runtime-file-client-types' import { chatScratchFileAddress } from './addressing/runtime-chat-scratch-file-address' -import type { LocalFileAccess } from '../../../../shared/local-file-access' +import type { LocalFileAccess } from '../../../../shared/file-access/local-file-access' // Why local only: an SSH read is the remote host's to check, and its relay never sees this field. export function localAccess( diff --git a/src/renderer/src/runtime/files/search/runtime-file-search-bounds.ts b/src/renderer/src/runtime/files/search/runtime-file-search-bounds.ts index dd6bf538ff3..c6435b0a174 100644 --- a/src/renderer/src/runtime/files/search/runtime-file-search-bounds.ts +++ b/src/renderer/src/runtime/files/search/runtime-file-search-bounds.ts @@ -1,4 +1,7 @@ -import type { SearchOptions, SearchResult } from '../../../../../shared/code-search-types' +import type { + SearchOptions, + SearchResult +} from '../../../../../shared/file-search/code-search-types' import { isUtf8ByteLengthWithinLimit } from '../../../../../shared/utf8-byte-limits' export const RUNTIME_FILE_SEARCH_TEXT_MAX_BYTES = 8 * 1024 diff --git a/src/renderer/src/runtime/files/search/runtime-file-search-client.ts b/src/renderer/src/runtime/files/search/runtime-file-search-client.ts index 5c9e3ee8ed6..0720290c14f 100644 --- a/src/renderer/src/runtime/files/search/runtime-file-search-client.ts +++ b/src/renderer/src/runtime/files/search/runtime-file-search-client.ts @@ -3,12 +3,15 @@ import { throwIfSignalAborted, waitForPromiseWithSignal } from '../../../../../shared/abort-signal-reason' -import type { SearchOptions, SearchResult } from '../../../../../shared/code-search-types' -import type { RuntimeFileListResult } from '../../../../../shared/runtime-file-contracts' +import type { + SearchOptions, + SearchResult +} from '../../../../../shared/file-search/code-search-types' +import type { RuntimeFileListResult } from '../../../../../shared/file-listing/runtime-file-list' import { buildExcludePathPrefixes, shouldExcludeQuickOpenRelPath -} from '../../../../../shared/quick-open-filter' +} from '../../../../../shared/quick-open/quick-open-filter' import type { RuntimeFileOperationArgs } from '../runtime-file-client-types' import { createEmptyRuntimeFileSearchResult, diff --git a/src/renderer/src/runtime/files/search/runtime-legacy-inventory-budget.ts b/src/renderer/src/runtime/files/search/runtime-legacy-inventory-budget.ts index 660911c3d0e..824608a4598 100644 --- a/src/renderer/src/runtime/files/search/runtime-legacy-inventory-budget.ts +++ b/src/renderer/src/runtime/files/search/runtime-legacy-inventory-budget.ts @@ -1,12 +1,12 @@ import type { RuntimeFileListEntry, RuntimeFileListResult -} from '../../../../../shared/runtime-file-contracts' +} from '../../../../../shared/file-listing/runtime-file-list' import { FILE_INVENTORY_MAX_BYTES, FILE_INVENTORY_MAX_PATH_BYTES, FileInventoryCapacityError -} from '../../../../../shared/file-inventory-budget' +} from '../../../../../shared/file-listing/file-inventory-budget' import { isUtf8ByteLengthWithinLimit } from '../../../../../shared/utf8-byte-limits' export function decodeLegacyQuickOpenInventory( diff --git a/src/renderer/src/runtime/files/search/runtime-legacy-quick-open-inventory.ts b/src/renderer/src/runtime/files/search/runtime-legacy-quick-open-inventory.ts index 45c6aa0cfbb..f2cec102a27 100644 --- a/src/renderer/src/runtime/files/search/runtime-legacy-quick-open-inventory.ts +++ b/src/renderer/src/runtime/files/search/runtime-legacy-quick-open-inventory.ts @@ -2,13 +2,13 @@ import { decodeLegacyQuickOpenInventory, pruneLegacyInventoryCache } from './runtime-legacy-inventory-budget' -import { quickOpenRecentCandidateSet } from '../../../../../shared/quick-open-recent-candidates' -import type { RuntimeFileListResult } from '../../../../../shared/runtime-file-contracts' +import { quickOpenRecentCandidateSet } from '../../../../../shared/quick-open/quick-open-recent-candidates' +import type { RuntimeFileListResult } from '../../../../../shared/file-listing/runtime-file-list' import { buildExcludePathPrefixes, shouldExcludeQuickOpenRelPath -} from '../../../../../shared/quick-open-filter' -import { QuickOpenPathRanker } from '../../../../../shared/quick-open-path-search' +} from '../../../../../shared/quick-open/quick-open-filter' +import { QuickOpenPathRanker } from '../../../../../shared/quick-open/quick-open-path-search' import { callRuntimeRpc } from '../../rpc/calls/runtime-rpc-call' import type { RuntimeClientTarget } from '../../../../../shared/runtime-client-target' import { createRuntimeRpcAbortError } from '../../rpc/calls/abortable-runtime-environment-call' diff --git a/src/renderer/src/runtime/files/watching/runtime-file-watch-client.ts b/src/renderer/src/runtime/files/watching/runtime-file-watch-client.ts index b0cd9e23112..4eb93ac352c 100644 --- a/src/renderer/src/runtime/files/watching/runtime-file-watch-client.ts +++ b/src/renderer/src/runtime/files/watching/runtime-file-watch-client.ts @@ -1,4 +1,4 @@ -import type { FsChangedPayload } from '../../../../../shared/filesystem-entry-types' +import type { FsChangedPayload } from '../../../../../shared/file-watch/filesystem-change-event' import type { RuntimeRpcResponse } from '../../../../../shared/runtime-rpc-envelope' import type { RuntimeFileOperationArgs } from '../runtime-file-client-types' import { callRuntimeRpc } from '../../rpc/calls/runtime-rpc-call' diff --git a/src/renderer/src/runtime/hosts/ssh/runtime-ssh-target-management.ts b/src/renderer/src/runtime/hosts/ssh/runtime-ssh-target-management.ts index 9cbf45d95e7..5cc74d1412a 100644 --- a/src/renderer/src/runtime/hosts/ssh/runtime-ssh-target-management.ts +++ b/src/renderer/src/runtime/hosts/ssh/runtime-ssh-target-management.ts @@ -5,7 +5,7 @@ import { type SshEditableTargetAddResult, type SshEditableTargetInput } from '../../../../../shared/ssh-target-management' -import type { FilesystemPathFlavor } from '../../../../../shared/filesystem-entry-types' +import type { FilesystemPathFlavor } from '../../../../../shared/file-access/filesystem-path-flavor' import { callRuntimeRpc } from '../../rpc/calls/runtime-rpc-call' import { runtimeEnvironmentSupportsCapability } from '../../rpc/compatibility/runtime-capability-proof' diff --git a/src/renderer/src/runtime/sync-runtime-graph/mobile-session-browser-tabs.ts b/src/renderer/src/runtime/sync-runtime-graph/mobile-session-browser-tabs.ts index 734fc87db6e..e2d02ffa0fc 100644 --- a/src/renderer/src/runtime/sync-runtime-graph/mobile-session-browser-tabs.ts +++ b/src/renderer/src/runtime/sync-runtime-graph/mobile-session-browser-tabs.ts @@ -1,7 +1,7 @@ import type { AppState } from '@/store/types' import type { RuntimeMobileSessionBrowserTab } from '../../../../shared/runtime-types' import type { Tab } from '../../../../shared/tab-types' -import { editorRowHost } from '../../../../shared/session-tab-file-host' +import { editorRowHost } from '../../../../shared/workspace-session/session-tab-file-host' import type { MobileSessionWorktreeInputs } from './types' import { isUnifiedTabActiveInActiveGroup } from './mobile-session-surfaces' diff --git a/src/renderer/src/runtime/sync-runtime-graph/mobile-session-editor-tabs.ts b/src/renderer/src/runtime/sync-runtime-graph/mobile-session-editor-tabs.ts index 20b4a0e2462..61986357fb7 100644 --- a/src/renderer/src/runtime/sync-runtime-graph/mobile-session-editor-tabs.ts +++ b/src/renderer/src/runtime/sync-runtime-graph/mobile-session-editor-tabs.ts @@ -4,7 +4,7 @@ import type { RuntimeMobileSessionMarkdownTab } from '../../../../shared/runtime-types' import type { Tab } from '../../../../shared/tab-types' -import { editorRowHost } from '../../../../shared/session-tab-file-host' +import { editorRowHost } from '../../../../shared/workspace-session/session-tab-file-host' import type { MobileSessionWorktreeInputs } from './types' import { getMobileMarkdownSourceFile, diff --git a/src/renderer/src/runtime/workspace-layout/server/server-layout-editor-handover.test.ts b/src/renderer/src/runtime/workspace-layout/server/server-layout-editor-handover.test.ts index 374600c5e61..915c03d77a9 100644 --- a/src/renderer/src/runtime/workspace-layout/server/server-layout-editor-handover.test.ts +++ b/src/renderer/src/runtime/workspace-layout/server/server-layout-editor-handover.test.ts @@ -10,9 +10,9 @@ import type { LayoutApplyReply, LayoutCommand } from '../../../../../shared/workspace-layout/workspace-layout-command-types' -import { ownedEditorFileId } from '../../../../../shared/workspace-session/workspace-session-pane-ownership' + import { toRuntimeExecutionHostId } from '../../../../../shared/execution-host' -import { getDiskBaselineSignature } from '../../../../../shared/disk-baseline-signature' +import { getDiskBaselineSignature } from '../../../../../shared/file-write/disk-baseline-signature' import { TEST_REPO } from '../../../store/repos/repo.test-fixture' import { makeWorktree } from '../../../store/slices/worktrees/worktree.test-fixture' import { createEditorSaveQueue } from '@/components/editor/save/queue/editor-save-queue' @@ -21,7 +21,6 @@ import { _resetLayoutFramePositionForTests } from '../frames/layout-frame-positi import { CAPABLE, ENV, - HOST_GROUP, SERVER_LAYOUT, WT, createFakeLayoutStreams, @@ -128,9 +127,6 @@ const { setServers, mirroredStore, install, uninstallAll } = createServerHarness const FILE_PATH = '/worktree/src/a.ts' const SECOND_PATH = '/worktree/src/b.ts' -/** The id this desktop gives the server's file, before the hand-over and after it. */ -const desktopFileId = (path: string) => ownedEditorFileId(path, WT, ENV) -const serverFileId = (path: string) => ownedEditorFileId(path, WT, undefined) /** Opens a file the way an editor action does; returns its file id and tab id. */ function openDesktopFile( @@ -222,46 +218,6 @@ afterEach(() => { }) describe('a desktop-only editor tab when the server’s frames take its workspace', () => { - it('is handed over under its own id, then drawn from the frames with its draft, once', async () => { - const store = mirroredStore() - const { fileId, tabId } = openDesktopFile(store, FILE_PATH) - expect(fileId).toBe(desktopFileId(FILE_PATH)) - expect(tabId).toBeDefined() - editDraft(store, fileId, 'unsaved') - const server = serverWith() - - const stream = await connect(store, server) - - expect(hoisted.sent.map(({ target, command }) => [target, command])).toEqual([ - [ - { kind: 'environment', environmentId: ENV }, - expect.objectContaining({ - type: 'openEditorTab', - workspace: WT, - tabId, - fileId: serverFileId(FILE_PATH), - groupId: HOST_GROUP, - contentType: 'editor', - file: { filePath: FILE_PATH, relativePath: 'src/a.ts', language: 'typescript' } - }) - ] - ]) - expect(server.layout(WT)?.tabs.map((tab) => tab.id)).toContain(tabId) - expect(isFrameDrawnServerWorkspace(ENV, WT)).toBe(true) - - // The server's next records frame: the tab is the server's now, so it stays. - const renamed = structuredClone(server.layout(WT)!) - renamed.tabs[0]!.customTitle = 'named on the server' - server.change(WT, renamed) - await settle() - - expect(editorTabIds(store)).toEqual([tabId]) - expect(openFileIds(store)).toEqual([fileId]) - expect(store.getState().editorDrafts[fileId]).toBe('unsaved') - expect(store.getState().tabsByWorktree[WT]?.[0]?.customTitle).toBe('named on the server') - expect(stream.closed).toBe(false) - }) - it('keeps the tab and its draft on the mirror for the stream after any other refusal', async () => { const store = mirroredStore() const { fileId, tabId } = openDesktopFile(store, FILE_PATH) @@ -440,28 +396,6 @@ describe('a desktop-only editor tab when the server’s frames take its workspac expect(editorTabIds(store)).toEqual([]) }) - it('routes an open in the gated workspace to the server, whose frames keep the tab', async () => { - const store = mirroredStore() - const server = serverWith() - await connect(store, server) - expect(isFrameDrawnServerWorkspace(ENV, WT)).toBe(true) - - const { fileId } = openDesktopFile(store, FILE_PATH) - editDraft(store, fileId, 'unsaved') - await settle() - await settle() - const [open] = serverOpens() - const renamed = structuredClone(server.layout(WT)!) - renamed.tabs[0]!.customTitle = 'named on the server' - server.change(WT, renamed) - await settle() - - expect(open).toMatchObject({ fileId: serverFileId(FILE_PATH), groupId: HOST_GROUP }) - expect(editorTabIds(store)).toEqual([open!.tabId]) - expect(openFileIds(store)).toEqual([fileId]) - expect(store.getState().editorDrafts[fileId]).toBe('unsaved') - }) - it('saves a handed-over file through the server, never this machine’s disk', async () => { const store = mirroredStore() store.setState({ diff --git a/src/renderer/src/store/slices/browser/pages/browser-page-records.ts b/src/renderer/src/store/slices/browser/pages/browser-page-records.ts index 8b27f585a4c..35620af486a 100644 --- a/src/renderer/src/store/slices/browser/pages/browser-page-records.ts +++ b/src/renderer/src/store/slices/browser/pages/browser-page-records.ts @@ -6,7 +6,7 @@ import type { import { browserPageDocLocationsEqual } from '../../../../../../shared/browser-page-doc-location' import { ORCA_BROWSER_BLANK_URL } from '../../../../../../shared/constants' import { redactKagiSessionToken } from '../../../../../../shared/browser-url' -import { isDocPreviewUrl } from '../../../../../../shared/doc-preview-scheme' +import { isDocPreviewUrl } from '../../../../../../shared/document-preview/doc-preview-scheme' import { basename } from '@/lib/path' import { createNonSecureContextUuid as createBrowserUuid } from '../../../../../../shared/non-secure-context-uuid' import { translate } from '@/i18n/i18n' diff --git a/src/renderer/src/store/slices/editor/opening/open-file-mutations.ts b/src/renderer/src/store/slices/editor/opening/open-file-mutations.ts index d37d4f3485c..f4332e2f925 100644 --- a/src/renderer/src/store/slices/editor/opening/open-file-mutations.ts +++ b/src/renderer/src/store/slices/editor/opening/open-file-mutations.ts @@ -14,7 +14,7 @@ import { updateEditorBuffer, writeEditorBuffer } from '../buffers/editor-buffer-record' -import { getDiskBaselineSignature } from '../../../../../../shared/disk-baseline-signature' +import { getDiskBaselineSignature } from '../../../../../../shared/file-write/disk-baseline-signature' import { captureEditorFileOperationProvenance } from '@/lib/editor-file-operation-provenance' import { isSameEditorFileOperationIdentity } from '@/lib/editor-file-operation-owner' import { editorBufferSiblingViewIds } from '../buffers/editor-buffer-views' diff --git a/src/renderer/src/store/slices/editor/tabs/untitled-file-cleanup.ts b/src/renderer/src/store/slices/editor/tabs/untitled-file-cleanup.ts index 3e91ba1a754..b2d5a28515d 100644 --- a/src/renderer/src/store/slices/editor/tabs/untitled-file-cleanup.ts +++ b/src/renderer/src/store/slices/editor/tabs/untitled-file-cleanup.ts @@ -3,7 +3,7 @@ import type { OpenFile } from '../types/open-file' import { mayShareEditorBackingFile } from '../file-ids/editor-file-ids' import { findFirstIndexedWorktree } from '../../../../lib/workspace/ownership/worktree-runtime-owner-index' import { getEditorFileOperationContext } from '@/lib/editor-file-operation-owner' -import { getDiskBaselineSignature } from '../../../../../../shared/disk-baseline-signature' +import { getDiskBaselineSignature } from '../../../../../../shared/file-write/disk-baseline-signature' import { deleteRuntimePath, deleteRuntimeRelativePath diff --git a/src/renderer/src/store/slices/editor/types/file-search-worktree-state.ts b/src/renderer/src/store/slices/editor/types/file-search-worktree-state.ts index d70c0399ce4..ef4f97d9888 100644 --- a/src/renderer/src/store/slices/editor/types/file-search-worktree-state.ts +++ b/src/renderer/src/store/slices/editor/types/file-search-worktree-state.ts @@ -1,4 +1,4 @@ -import type { SearchResult } from '../../../../../../shared/code-search-types' +import type { SearchResult } from '../../../../../../shared/file-search/code-search-types' import type { FileSearchResultOwner } from '@/lib/file-search-result-owner' export type FileSearchWorktreeState = { diff --git a/src/renderer/src/store/slices/ui/ui-slice-hydration-sanitizers.ts b/src/renderer/src/store/slices/ui/ui-slice-hydration-sanitizers.ts index 1a24f249fac..073ee22a6e8 100644 --- a/src/renderer/src/store/slices/ui/ui-slice-hydration-sanitizers.ts +++ b/src/renderer/src/store/slices/ui/ui-slice-hydration-sanitizers.ts @@ -1,4 +1,4 @@ -import { normalizeExplorerDisplayRootByWorktree } from '../../../../../shared/file-explorer-display-root' +import { normalizeExplorerDisplayRootByWorktree } from '../../../../../shared/file-listing/file-explorer-display-root' import type { AppState } from '../../types' import type { PersistedTrustedOrcaHooks } from '../../../../../shared/orca-yaml-hook-types' import type { PersistedUIState } from '../../../../../shared/persisted-ui-state-types' diff --git a/src/renderer/src/web/preload-api/web-filesystem-api-connection-pin.test.ts b/src/renderer/src/web/preload-api/web-filesystem-api-connection-pin.test.ts deleted file mode 100644 index ccfffb4ca84..00000000000 --- a/src/renderer/src/web/preload-api/web-filesystem-api-connection-pin.test.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { FILE_MUTATION_OWNERSHIP_RUNTIME_CAPABILITY } from '../../../../shared/protocol-version' -import { getDiskBaselineSignature } from '../../../../shared/disk-baseline-signature' - -const session = vi.hoisted(() => { - const client = { connectionEpoch: 1, call: vi.fn() } - const environment = { id: 'env-1', createdAt: 1 } - return { client, environment, state: { activeClient: client } } -}) - -vi.mock('./web-runtime-session', () => ({ - getClientForEnvironment: () => session.client, - requireActiveEnvironment: () => session.environment, - requireActiveEnvironmentOrNull: () => session.environment, - runtimeCallQueuePool: { enqueue: (_id: string, _method: string, run: () => unknown) => run() }, - updateEnvironmentFromResponse: () => undefined, - webRuntimeState: session.state -})) -vi.mock('./web-runtime-worktree-catalog', () => ({ - isMissingPathError: () => false, - resolveRuntimeFilePath: async () => ({ - worktree: { id: 'wt-1', hostId: 'local' }, - relativePath: 'readme.md' - }) -})) - -import { createFileApi } from './web-filesystem-api' - -describe('paired web client writes after the client reconnects during the support probe', () => { - beforeEach(() => { - session.client.connectionEpoch = 1 - session.client.call.mockReset() - session.client.call.mockImplementation(async (method: string) => { - if (method === 'status.get') { - // The same client reconnects while the probe is in flight. - session.client.connectionEpoch += 1 - return { - id: 'rpc', - ok: true, - result: { - capabilities: [ - FILE_MUTATION_OWNERSHIP_RUNTIME_CAPABILITY, - 'files.write.disk-precondition.v1' - ] - } - } - } - return { id: 'rpc', ok: true, result: { ok: true } } - }) - }) - - it('refuses to send a guarded save whose probe answered on another connection', async () => { - await expect( - createFileApi().writeFile({ - filePath: '/hub/readme.md', - content: 'edited', - diskPrecondition: { expectedSignature: getDiskBaselineSignature('original') } - }) - ).rejects.toThrow() - expect(session.client.call).toHaveBeenCalledTimes(1) - }) -}) diff --git a/src/renderer/src/web/preload-api/web-filesystem-api.ts b/src/renderer/src/web/preload-api/web-filesystem-api.ts index 1d2be4041be..deafec9552f 100644 --- a/src/renderer/src/web/preload-api/web-filesystem-api.ts +++ b/src/renderer/src/web/preload-api/web-filesystem-api.ts @@ -1,9 +1,9 @@ import { callAbortableRuntimeEnvironment } from '../../runtime/rpc/calls/abortable-runtime-environment-call' import { unwrapRuntimeRpcResult } from '../../runtime/rpc/calls/runtime-rpc-result' import type { PreloadApi } from '../../../../preload/api-types' -import type { SearchResult } from '../../../../shared/code-search-types' -import { assertFileMutationOwnershipCapability } from '../../../../shared/file-mutation-ownership' -import type { DirEntry } from '../../../../shared/filesystem-entry-types' +import type { SearchResult } from '../../../../shared/file-search/code-search-types' +import { assertFileMutationOwnershipCapability } from '../../../../shared/file-write/file-mutation-ownership' +import type { DirEntry } from '../../../../shared/file-listing/directory-entry' import type { RuntimeRpcResponse } from '../../../../shared/runtime-rpc-envelope' import type { RuntimeStatus } from '../../../../shared/runtime-types' import type { SshConnectionState } from '../../../../shared/ssh-types' diff --git a/src/renderer/src/web/web-file-mutation-methods.ts b/src/renderer/src/web/web-file-mutation-methods.ts index 19312a9f61e..e722ad865d4 100644 --- a/src/renderer/src/web/web-file-mutation-methods.ts +++ b/src/renderer/src/web/web-file-mutation-methods.ts @@ -8,7 +8,7 @@ import { pagedTextFileResult, readFileInChunks } from '../runtime/files/reads/runtime-paged-file-read' -import type { RuntimeFileReadChunkResult } from '../../../shared/runtime-types' +import type { RuntimeFileReadChunkResult } from '../../../shared/file-content/runtime-file-read' import { compareDiskWritePrecondition, diskConflictFromReadFailure, @@ -20,7 +20,7 @@ import { type FileWriteDiskComparison, type FileWriteDiskPrecondition, type FileWriteResult -} from '../../../shared/file-write-disk-precondition' +} from '../../../shared/file-write/file-write-disk-precondition' const SSH_OWNER_CHANGED_MESSAGE = "Couldn't verify the SSH connection. Reconnect the host and try again." diff --git a/src/renderer/src/web/web-file-write-disk-precondition.test.ts b/src/renderer/src/web/web-file-write-disk-precondition.test.ts index 0c4a1d9d41b..fd0e56c5a61 100644 --- a/src/renderer/src/web/web-file-write-disk-precondition.test.ts +++ b/src/renderer/src/web/web-file-write-disk-precondition.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest' -import { getDiskBaselineSignature } from '../../../shared/disk-baseline-signature' -import { FILE_WRITE_DISK_PRECONDITION_RUNTIME_CAPABILITY } from '../../../shared/file-write-disk-precondition' +import { getDiskBaselineSignature } from '../../../shared/file-write/disk-baseline-signature' +import { FILE_WRITE_DISK_PRECONDITION_RUNTIME_CAPABILITY } from '../../../shared/file-write/file-write-disk-precondition' import { createWebFileMutationMethods } from './web-file-mutation-methods' const precondition = { expectedSignature: getDiskBaselineSignature('original') } diff --git a/src/shared/agent-hook-listener/request-body.ts b/src/shared/agent-hook-listener/request-body.ts index 392ec302b9a..80f409fd2b9 100644 --- a/src/shared/agent-hook-listener/request-body.ts +++ b/src/shared/agent-hook-listener/request-body.ts @@ -1,7 +1,7 @@ import type { IncomingMessage } from 'node:http' import { classifyTruncatedHookRequest } from './transport/agent-hook-transport-interference' -import { assertJsonTextStructureWithinLimits } from '../json-text-structure-limit' +import { assertJsonTextStructureWithinLimits } from '../json-stream/json-text-structure-limit' export const HOOK_REQUEST_MAX_BYTES = 1_000_000 const HOOK_REQUEST_INITIAL_BUFFER_BYTES = 4 * 1024 diff --git a/src/shared/home-or-filesystem-root.test.ts b/src/shared/agent-launch/permissions/workspace-pretrust-scope.test.ts similarity index 95% rename from src/shared/home-or-filesystem-root.test.ts rename to src/shared/agent-launch/permissions/workspace-pretrust-scope.test.ts index cb13c1c6bff..d5791f29a3c 100644 --- a/src/shared/home-or-filesystem-root.test.ts +++ b/src/shared/agent-launch/permissions/workspace-pretrust-scope.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { isTooBroadToPreTrust } from './home-or-filesystem-root' +import { isTooBroadToPreTrust } from './workspace-pretrust-scope' describe('isTooBroadToPreTrust', () => { it.each([ diff --git a/src/shared/home-or-filesystem-root.ts b/src/shared/agent-launch/permissions/workspace-pretrust-scope.ts similarity index 90% rename from src/shared/home-or-filesystem-root.ts rename to src/shared/agent-launch/permissions/workspace-pretrust-scope.ts index 3474dc4cc7b..87195fdf83f 100644 --- a/src/shared/home-or-filesystem-root.ts +++ b/src/shared/agent-launch/permissions/workspace-pretrust-scope.ts @@ -1,4 +1,4 @@ -import { normalizeRuntimePathForComparison } from './cross-platform-path' +import { normalizeRuntimePathForComparison } from '../../cross-platform-path' /** Drive, UNC share, WSL distro or POSIX root, as `normalizeRuntimePathForComparison` spells it. */ const FILESYSTEM_ROOT_KEY = /^(?:\/|[a-z]:\/?|\/\/[^/]+(?:\/[^/]+)?)$/i diff --git a/src/shared/agent-session/agent-session-attachments.ts b/src/shared/agent-session/agent-session-attachments.ts index a507745cec2..2834bd11ed2 100644 --- a/src/shared/agent-session/agent-session-attachments.ts +++ b/src/shared/agent-session/agent-session-attachments.ts @@ -1,6 +1,6 @@ // The execution host owns chat attachments; paired clients upload bytes, local pastes write in place, and agents receive only host paths. -import type { ImportSkipReason } from '../filesystem-import-result-types' +import type { ImportSkipReason } from '../file-import/filesystem-import-result' /** Host userData store name; clients recognize stored paths without a round trip. */ export const AGENT_SESSION_ATTACHMENTS_DIR_NAME = 'agent-session-attachments' diff --git a/src/shared/agent-status/contracts/agent-status-run-alias-index.ts b/src/shared/agent-status/contracts/agent-status-run-alias-index.ts index 33ffacc4d6a..c73d94bd219 100644 --- a/src/shared/agent-status/contracts/agent-status-run-alias-index.ts +++ b/src/shared/agent-status/contracts/agent-status-run-alias-index.ts @@ -8,7 +8,7 @@ import { parseAgentStatusExecutionScope, type AgentStatusExecutionScope } from './agent-status-subject' -import { assertJsonTextStructureWithinLimits } from '../../json-text-structure-limit' +import { assertJsonTextStructureWithinLimits } from '../../json-stream/json-text-structure-limit' import { measureUtf8ByteLength } from '../../utf8-byte-limits' const PROVIDER_ALIAS_KEY_PREFIX = 'agent-status-provider-alias-v1:' diff --git a/src/shared/agent-status/contracts/agent-status-transport-envelope.ts b/src/shared/agent-status/contracts/agent-status-transport-envelope.ts index bfda22ae73d..07fc3391af4 100644 --- a/src/shared/agent-status/contracts/agent-status-transport-envelope.ts +++ b/src/shared/agent-status/contracts/agent-status-transport-envelope.ts @@ -7,7 +7,7 @@ import { parseAgentStatusStoreMutation, parseAgentStatusStoreSnapshot } from '../store/agent-status-store-codec' -import { assertJsonTextStructureWithinLimits } from '../../json-text-structure-limit' +import { assertJsonTextStructureWithinLimits } from '../../json-stream/json-text-structure-limit' // Why: the store has no size limit, so only nesting is bounded; any envelope it can serialize must parse. const ENVELOPE_STRUCTURE_LIMITS = { diff --git a/src/shared/agent-status/contracts/agent-status-types.ts b/src/shared/agent-status/contracts/agent-status-types.ts index b151cf9c9b8..797fa72772e 100644 --- a/src/shared/agent-status/contracts/agent-status-types.ts +++ b/src/shared/agent-status/contracts/agent-status-types.ts @@ -19,7 +19,7 @@ import { normalizePromptField, normalizeTurnCompletedAtField } from './agent-status-field-normalization' -import { assertJsonTextStructureWithinLimits } from '../../json-text-structure-limit' +import { assertJsonTextStructureWithinLimits } from '../../json-stream/json-text-structure-limit' import { normalizeAgentSubagentsField, diff --git a/src/shared/agent-status/store/agent-status-store-persistence.ts b/src/shared/agent-status/store/agent-status-store-persistence.ts index 5fc80c454d3..06109b372ff 100644 --- a/src/shared/agent-status/store/agent-status-store-persistence.ts +++ b/src/shared/agent-status/store/agent-status-store-persistence.ts @@ -1,6 +1,6 @@ import type { AgentStatusStoreSnapshot } from './agent-status-store-contract' import { parseAgentStatusStoreSnapshot } from './agent-status-store-codec' -import { assertJsonTextStructureWithinLimits } from '../../json-text-structure-limit' +import { assertJsonTextStructureWithinLimits } from '../../json-stream/json-text-structure-limit' const SNAPSHOT_NESTING_DEPTH = 32 diff --git a/src/shared/agent-status/store/agent-status-store-status-codec.ts b/src/shared/agent-status/store/agent-status-store-status-codec.ts index 450f38bde53..cabd2ceeca7 100644 --- a/src/shared/agent-status/store/agent-status-store-status-codec.ts +++ b/src/shared/agent-status/store/agent-status-store-status-codec.ts @@ -6,7 +6,7 @@ import { parseAgentStatusProviderAlias } from '../contracts/agent-status-run' import { normalizeAgentStatusPayload } from '../contracts/agent-status-types' -import { assertJsonTextStructureWithinLimits } from '../../json-text-structure-limit' +import { assertJsonTextStructureWithinLimits } from '../../json-stream/json-text-structure-limit' import { measureUtf8ByteLength } from '../../utf8-byte-limits' const MAX_STATUS_BYTES = 256 * 1024 diff --git a/src/shared/artifact-cli-bridge.ts b/src/shared/artifacts/artifact-cli-bridge.ts similarity index 100% rename from src/shared/artifact-cli-bridge.ts rename to src/shared/artifacts/artifact-cli-bridge.ts diff --git a/src/shared/artifact-file-read.ts b/src/shared/artifacts/artifact-file-read.ts similarity index 100% rename from src/shared/artifact-file-read.ts rename to src/shared/artifacts/artifact-file-read.ts diff --git a/src/shared/artifact-sharing-gate.ts b/src/shared/artifacts/artifact-sharing-gate.ts similarity index 95% rename from src/shared/artifact-sharing-gate.ts rename to src/shared/artifacts/artifact-sharing-gate.ts index 29e05f03912..3dc47ddb4cc 100644 --- a/src/shared/artifact-sharing-gate.ts +++ b/src/shared/artifacts/artifact-sharing-gate.ts @@ -1,5 +1,5 @@ // Public artifact URLs require a user-granted capability; main/CLI/Settings share this gate. -import type { GlobalSettings } from './global-settings-types' +import type { GlobalSettings } from '../global-settings-types' export const ARTIFACT_SHARING_DISABLED_CODE = 'artifact_sharing_disabled' diff --git a/src/shared/artifacts.ts b/src/shared/artifacts/artifacts.ts similarity index 100% rename from src/shared/artifacts.ts rename to src/shared/artifacts/artifacts.ts diff --git a/src/shared/attachment-text-segments.ts b/src/shared/attachment-text/attachment-text-segments.ts similarity index 100% rename from src/shared/attachment-text-segments.ts rename to src/shared/attachment-text/attachment-text-segments.ts diff --git a/src/shared/attachment-text-source.ts b/src/shared/attachment-text/attachment-text-source.ts similarity index 96% rename from src/shared/attachment-text-source.ts rename to src/shared/attachment-text/attachment-text-source.ts index 188228aeabc..0cfa738a07f 100644 --- a/src/shared/attachment-text-source.ts +++ b/src/shared/attachment-text/attachment-text-source.ts @@ -1,9 +1,12 @@ import * as z from 'zod' import { attachmentTextSegments } from './attachment-text-segments' -export { attachmentTextSegments } from './attachment-text-segments' -import { waitForPromiseWithSignal } from './abort-signal-reason' -import { AGENT_SESSION_ATTACHMENT_MAX_BYTES } from './agent-session/agent-session-attachments' -import { MAX_FILE_RANGE_READ_BYTES, validateFileRangeRequest } from './file-range-read' + +import { waitForPromiseWithSignal } from '../abort-signal-reason' +import { AGENT_SESSION_ATTACHMENT_MAX_BYTES } from '../agent-session/agent-session-attachments' +import { + MAX_FILE_RANGE_READ_BYTES, + validateFileRangeRequest +} from '../file-content/file-range-read' export type AttachmentTextRequest = { path: string diff --git a/src/shared/attachment-text-viewport.ts b/src/shared/attachment-text/attachment-text-viewport.ts similarity index 100% rename from src/shared/attachment-text-viewport.ts rename to src/shared/attachment-text/attachment-text-viewport.ts diff --git a/src/shared/use-attachment-text-preview.ts b/src/shared/attachment-text/use-attachment-text-preview.ts similarity index 100% rename from src/shared/use-attachment-text-preview.ts rename to src/shared/attachment-text/use-attachment-text-preview.ts diff --git a/src/shared/browser-screencast-protocol.ts b/src/shared/browser-screencast-protocol.ts index 1262c8fb3a3..687b39140f3 100644 --- a/src/shared/browser-screencast-protocol.ts +++ b/src/shared/browser-screencast-protocol.ts @@ -1,4 +1,4 @@ -import { assertJsonTextStructureWithinLimits } from './json-text-structure-limit' +import { assertJsonTextStructureWithinLimits } from './json-stream/json-text-structure-limit' const BROWSER_SCREENCAST_KIND = 0x62 const BROWSER_SCREENCAST_VERSION = 1 diff --git a/src/shared/claude-model-list-probe.ts b/src/shared/claude-model-list-probe.ts index 2f3af06a9bf..7afd563ba0c 100644 --- a/src/shared/claude-model-list-probe.ts +++ b/src/shared/claude-model-list-probe.ts @@ -1,5 +1,5 @@ import { claudeBackgroundArgs } from './claude-background-run-isolation' -import { assertJsonTextStructureWithinLimits } from './json-text-structure-limit' +import { assertJsonTextStructureWithinLimits } from './json-stream/json-text-structure-limit' import { labelFromModelId } from './model-id-label' // claude models starts chat; list_models over --print stream-json reads the picker without an API turn. Older CLIs return error with exit 0; keep seed models. diff --git a/src/shared/cross-platform-path.test.ts b/src/shared/cross-platform-path.test.ts index 1cfaa102027..8ed8b13c1f3 100644 --- a/src/shared/cross-platform-path.test.ts +++ b/src/shared/cross-platform-path.test.ts @@ -126,37 +126,4 @@ describe('cross-platform path containment', () => { ) ).toBe('line\nbreak') }) - - it('returns a byte-exact suffix when comparison folding changes length', () => { - // NFC/case folding changes length; slicing raw paths by folded lengths fabricates suffixes callers rejoin on disk. - const nfc = '/Users/ada/프로젝트' - const nfd = nfc.normalize('NFD') - for (const root of [nfc, nfd]) { - for (const candidate of [nfc, nfd]) { - expect(relativePathInsideRoot(root, `${candidate}/src/index.ts`)).toBe('src/index.ts') - } - } - - // Pre-existing over-slice: toLowerCase expands U+0130 to two UTF-16 units. - expect(relativePathInsideRoot('C:\\İş', 'C:\\İş\\src\\a.ts')).toBe('src/a.ts') - - // Kelvin U+212A folds to K; agree on Windows syntax or segment counts desynchronize. - expect(relativePathInsideRoot('\u212A:/a\\b', '\u212A:/a\\b/c')).toBe( - relativePathInsideRoot('K:/a\\b', 'K:/a\\b/c') - ) - - expect(relativePathInsideRoot('/repo/🚀app', '/repo/🚀app/src/🎉file.ts')).toBe('src/🎉file.ts') - - // UNC-shaped paths under / must return relative suffixes without a leading slash. - expect(relativePathInsideRoot('/', '//server/share/x')).toBe('server/share/x') - - // WSL suffixes stay decomposed: Linux treats NFC/NFD as distinct entries. - const decomposed = '프로젝트'.normalize('NFD') - expect( - relativePathInsideRoot( - '\\\\wsl$\\Ubuntu\\home\\ada\\repo', - `\\\\wsl.localhost\\Ubuntu\\home\\ada\\repo\\${decomposed}\\a.ts` - ) - ).toBe(`${decomposed}/a.ts`) - }) }) diff --git a/src/shared/darwin-terminal-names.ts b/src/shared/darwin-terminal-names.ts index 224637a3be5..45bc4d3c32d 100644 --- a/src/shared/darwin-terminal-names.ts +++ b/src/shared/darwin-terminal-names.ts @@ -1,6 +1,6 @@ import { lstat, opendir } from 'node:fs/promises' import { join } from 'node:path' -import { DirectoryListingBudget } from './directory-listing-budget' +import { DirectoryListingBudget } from './file-listing/directory-listing-budget' import { ProcessTableCaptureError } from './process-table-snapshot' type DarwinTerminalNameDeps = { diff --git a/src/shared/doc-preview-file-access.test.ts b/src/shared/doc-preview-file-access.test.ts deleted file mode 100644 index 04af5f1391d..00000000000 --- a/src/shared/doc-preview-file-access.test.ts +++ /dev/null @@ -1,227 +0,0 @@ -import { afterEach, describe, expect, it } from 'vitest' -import { execFile } from 'node:child_process' -import { mkdtemp, mkdir, rm, symlink, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { promisify } from 'node:util' -import { - DOC_PREVIEW_PATH_AUTHORIZATION_ERROR, - readAuthorizedDocPreviewFile, - readAuthorizedDocPreviewFileChunk -} from './doc-preview-file-access' - -const fixtureRoots: string[] = [] - -async function createFixture(): Promise<{ - workspace: string - entry: string - docs: string - assets: string -}> { - const fixture = await mkdtemp(join(tmpdir(), 'orca-doc-preview-access-')) - fixtureRoots.push(fixture) - const workspace = join(fixture, 'workspace') - const docs = join(workspace, 'docs') - const assets = join(workspace, 'assets') - await Promise.all([mkdir(docs, { recursive: true }), mkdir(assets, { recursive: true })]) - const entry = join(docs, 'index.html') - await writeFile(entry, '

entry

') - return { workspace, entry, docs, assets } -} - -afterEach(async () => { - await Promise.all( - fixtureRoots.splice(0).map((root) => rm(root, { recursive: true, force: true })) - ) -}) - -describe('readAuthorizedDocPreviewFile', () => { - it('reads the entry file without granting its containing directory', async () => { - const fixture = await createFixture() - - await expect( - readAuthorizedDocPreviewFile({ - boundaryPath: fixture.workspace, - entryPath: fixture.entry, - implicitRootPath: null, - authorizedRootPaths: [], - targetPath: fixture.entry, - maxTextBytes: 1024, - maxBinaryBytes: 1024 - }) - ).resolves.toEqual({ content: '

entry

', isBinary: false }) - }) - - it('reads a file only after its canonical directory is authorized', async () => { - const fixture = await createFixture() - const asset = join(fixture.assets, 'app.js') - await writeFile(asset, 'console.log(1)') - const request = { - boundaryPath: fixture.workspace, - entryPath: fixture.entry, - implicitRootPath: null, - authorizedRootPaths: [] as string[], - targetPath: asset, - maxTextBytes: 1024, - maxBinaryBytes: 1024 - } - - await expect(readAuthorizedDocPreviewFile(request)).rejects.toThrow( - DOC_PREVIEW_PATH_AUTHORIZATION_ERROR - ) - await expect( - readAuthorizedDocPreviewFile({ ...request, authorizedRootPaths: [fixture.assets] }) - ).resolves.toEqual({ content: 'console.log(1)', isBinary: false }) - }) - - it('rejects an authorized-directory symlink that resolves outside the workspace', async () => { - const fixture = await createFixture() - const outside = join(fixture.workspace, '..', 'outside') - await mkdir(outside) - await writeFile(join(outside, 'secret.txt'), 'secret') - const linked = join(fixture.assets, 'linked') - await symlink(outside, linked, process.platform === 'win32' ? 'junction' : 'dir') - - await expect( - readAuthorizedDocPreviewFile({ - boundaryPath: fixture.workspace, - entryPath: fixture.entry, - implicitRootPath: fixture.docs, - authorizedRootPaths: [fixture.assets], - targetPath: join(linked, 'secret.txt'), - maxTextBytes: 1024, - maxBinaryBytes: 1024 - }) - ).rejects.toThrow(DOC_PREVIEW_PATH_AUTHORIZATION_ERROR) - }) - - it('does not let an implicit nested root canonicalize into whole-workspace authority', async () => { - const fixture = await createFixture() - const rootEntry = join(fixture.workspace, 'index.html') - const secret = join(fixture.workspace, 'secret.txt') - await writeFile(rootEntry, '

entry

') - await writeFile(secret, 'secret') - const linkedRoot = join(fixture.workspace, 'linked-root') - await symlink(fixture.workspace, linkedRoot, process.platform === 'win32' ? 'junction' : 'dir') - - await expect( - readAuthorizedDocPreviewFile({ - boundaryPath: fixture.workspace, - entryPath: join(linkedRoot, 'index.html'), - implicitRootPath: linkedRoot, - authorizedRootPaths: [], - targetPath: secret, - maxTextBytes: 1024, - maxBinaryBytes: 1024 - }) - ).rejects.toThrow(DOC_PREVIEW_PATH_AUTHORIZATION_ERROR) - }) - - // FIFO hazards are POSIX-only; Windows has no mkfifo. - it.skipIf(process.platform === 'win32')( - 'refuses a writer-less FIFO instead of blocking the open forever', - async () => { - const fixture = await createFixture() - const fifo = join(fixture.assets, 'pipe') - await promisify(execFile)('mkfifo', [fifo]) - - // Without O_NONBLOCK this open never returns, so the timeout itself is the regression oracle. - await expect( - readAuthorizedDocPreviewFile({ - boundaryPath: fixture.workspace, - entryPath: fixture.entry, - implicitRootPath: null, - authorizedRootPaths: [fixture.assets], - targetPath: fifo, - maxTextBytes: 1024, - maxBinaryBytes: 1024 - }) - ).rejects.toThrow(DOC_PREVIEW_PATH_AUTHORIZATION_ERROR) - } - ) - - it('returns typed binary bytes and enforces the read cap', async () => { - const fixture = await createFixture() - const image = join(fixture.assets, 'logo.png') - await writeFile(image, Buffer.from([0x89, 0x50, 0x4e, 0x47])) - const request = { - boundaryPath: fixture.workspace, - entryPath: fixture.entry, - implicitRootPath: fixture.docs, - authorizedRootPaths: [fixture.assets], - targetPath: image, - maxTextBytes: 1024, - maxBinaryBytes: 4 - } - - await expect(readAuthorizedDocPreviewFile(request)).resolves.toEqual({ - content: Buffer.from([0x89, 0x50, 0x4e, 0x47]).toString('base64'), - isBinary: true, - mimeType: 'image/png' - }) - await expect(readAuthorizedDocPreviewFile({ ...request, maxBinaryBytes: 3 })).rejects.toThrow( - 'file_too_large' - ) - }) - - it.each([ - { extension: '.woff', mimeType: 'font/woff' }, - { extension: '.WOFF2', mimeType: 'font/woff2' }, - { extension: '.ttf', mimeType: 'font/ttf' }, - { extension: '.otf', mimeType: 'font/otf' } - ])( - 'serves authorized $extension fonts within the binary read cap', - async ({ extension, mimeType }) => { - const fixture = await createFixture() - const font = join(fixture.assets, `typeface${extension}`) - const bytes = Buffer.from([0x77, 0x4f, 0x46, 0x32, 0x00, 0x01, 0x00, 0x00]) - await writeFile(font, bytes) - const request = { - boundaryPath: fixture.workspace, - entryPath: fixture.entry, - implicitRootPath: fixture.docs, - authorizedRootPaths: [fixture.assets], - targetPath: font, - maxTextBytes: 1, - maxBinaryBytes: bytes.length - } - - await expect(readAuthorizedDocPreviewFile(request)).resolves.toEqual({ - content: bytes.toString('base64'), - isBinary: true, - mimeType - }) - await expect( - readAuthorizedDocPreviewFile({ ...request, authorizedRootPaths: [] }) - ).rejects.toThrow(DOC_PREVIEW_PATH_AUTHORIZATION_ERROR) - await expect( - readAuthorizedDocPreviewFile({ ...request, maxBinaryBytes: bytes.length - 1 }) - ).rejects.toThrow('file_too_large') - } - ) -}) - -describe('readAuthorizedDocPreviewFileChunk', () => { - it('reads a range of an authorized file and refuses one outside the grant', async () => { - const fixture = await createFixture() - const asset = join(fixture.assets, 'data.js') - await writeFile(asset, 'abcdefgh') - const target = { - boundaryPath: fixture.workspace, - entryPath: fixture.entry, - implicitRootPath: null, - authorizedRootPaths: [fixture.assets], - targetPath: asset - } - - await expect(readAuthorizedDocPreviewFileChunk(target, 6, 4)).resolves.toMatchObject({ - contentBase64: Buffer.from('gh').toString('base64'), - bytesRead: 2, - eof: true, - size: 8 - }) - await expect( - readAuthorizedDocPreviewFileChunk({ ...target, authorizedRootPaths: [] }, 0, 4) - ).rejects.toThrow(DOC_PREVIEW_PATH_AUTHORIZATION_ERROR) - }) -}) diff --git a/src/shared/document-preview/doc-preview-file-access.test.ts b/src/shared/document-preview/doc-preview-file-access.test.ts new file mode 100644 index 00000000000..76fef15fb2e --- /dev/null +++ b/src/shared/document-preview/doc-preview-file-access.test.ts @@ -0,0 +1,74 @@ +import { afterEach, describe, expect, it } from 'vitest' + +import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +import { readAuthorizedDocPreviewFile } from './doc-preview-file-access' + +const fixtureRoots: string[] = [] + +async function createFixture(): Promise<{ + workspace: string + entry: string + docs: string + assets: string +}> { + const fixture = await mkdtemp(join(tmpdir(), 'orca-doc-preview-access-')) + fixtureRoots.push(fixture) + const workspace = join(fixture, 'workspace') + const docs = join(workspace, 'docs') + const assets = join(workspace, 'assets') + await Promise.all([mkdir(docs, { recursive: true }), mkdir(assets, { recursive: true })]) + const entry = join(docs, 'index.html') + await writeFile(entry, '

entry

') + return { workspace, entry, docs, assets } +} + +afterEach(async () => { + await Promise.all( + fixtureRoots.splice(0).map((root) => rm(root, { recursive: true, force: true })) + ) +}) + +describe('readAuthorizedDocPreviewFile', () => { + it('reads the entry file without granting its containing directory', async () => { + const fixture = await createFixture() + + await expect( + readAuthorizedDocPreviewFile({ + boundaryPath: fixture.workspace, + entryPath: fixture.entry, + implicitRootPath: null, + authorizedRootPaths: [], + targetPath: fixture.entry, + maxTextBytes: 1024, + maxBinaryBytes: 1024 + }) + ).resolves.toEqual({ content: '

entry

', isBinary: false }) + }) + + it('returns typed binary bytes and enforces the read cap', async () => { + const fixture = await createFixture() + const image = join(fixture.assets, 'logo.png') + await writeFile(image, Buffer.from([0x89, 0x50, 0x4e, 0x47])) + const request = { + boundaryPath: fixture.workspace, + entryPath: fixture.entry, + implicitRootPath: fixture.docs, + authorizedRootPaths: [fixture.assets], + targetPath: image, + maxTextBytes: 1024, + maxBinaryBytes: 4 + } + + await expect(readAuthorizedDocPreviewFile(request)).resolves.toEqual({ + content: Buffer.from([0x89, 0x50, 0x4e, 0x47]).toString('base64'), + isBinary: true, + mimeType: 'image/png' + }) + await expect(readAuthorizedDocPreviewFile({ ...request, maxBinaryBytes: 3 })).rejects.toThrow( + 'file_too_large' + ) + }) +}) diff --git a/src/shared/doc-preview-file-access.ts b/src/shared/document-preview/doc-preview-file-access.ts similarity index 94% rename from src/shared/doc-preview-file-access.ts rename to src/shared/document-preview/doc-preview-file-access.ts index 4a2a30d976a..b82d82c1a72 100644 --- a/src/shared/doc-preview-file-access.ts +++ b/src/shared/document-preview/doc-preview-file-access.ts @@ -1,15 +1,15 @@ import { constants, type Stats } from 'node:fs' import { open, realpath, stat, type FileHandle } from 'node:fs/promises' import { extname } from 'node:path' -import { isBinaryBuffer } from './binary-buffer' -import { isPathInsideOrEqual } from './cross-platform-path' -import { IMAGE_FILE_MIME_TYPES } from './image-file-extensions' -import { FONT_FILE_MIME_TYPES } from './font-file-extensions' -import type { RuntimeFileReadChunkResult } from './runtime-file-contracts' +import { isBinaryBuffer } from '../file-preview/binary-buffer' +import { isPathInsideOrEqual } from '../cross-platform-path' +import { IMAGE_FILE_MIME_TYPES } from '../file-preview/image-mime-types' +import { FONT_FILE_MIME_TYPES } from '../file-preview/font-file-extensions' +import type { RuntimeFileReadChunkResult } from '../file-content/runtime-file-read' import { NodeFileReadTooLargeError, readNodeFileHandleWithinLimit -} from './node-bounded-file-reader' +} from '../file-content/node-bounded-file-reader' export const DOC_PREVIEW_PATH_AUTHORIZATION_ERROR = 'doc_preview_path_unauthorized' export const DOC_PREVIEW_FILE_CHANGED_MESSAGE = diff --git a/src/shared/doc-preview-scheme.test.ts b/src/shared/document-preview/doc-preview-scheme.test.ts similarity index 100% rename from src/shared/doc-preview-scheme.test.ts rename to src/shared/document-preview/doc-preview-scheme.test.ts diff --git a/src/shared/doc-preview-scheme.ts b/src/shared/document-preview/doc-preview-scheme.ts similarity index 100% rename from src/shared/doc-preview-scheme.ts rename to src/shared/document-preview/doc-preview-scheme.ts diff --git a/src/shared/ephemeral-vm-recipes.ts b/src/shared/ephemeral-vm-recipes.ts index 021efd4f394..e6561074746 100644 --- a/src/shared/ephemeral-vm-recipes.ts +++ b/src/shared/ephemeral-vm-recipes.ts @@ -1,7 +1,7 @@ import { z } from 'zod' import { parsePairingCode } from './remote-runtime/pairing/pairing' import { MAX_SSH_RELAY_GRACE_PERIOD_SECONDS, MIN_SSH_RELAY_GRACE_PERIOD_SECONDS } from './ssh-types' -import { assertJsonTextStructureWithinLimits } from './json-text-structure-limit' +import { assertJsonTextStructureWithinLimits } from './json-stream/json-text-structure-limit' import { ephemeralVmFailure, type EphemeralVmFailure } from './ephemeral-vm-failure-copy' const JsonValueSchema: z.ZodType = z.lazy(() => diff --git a/src/shared/ephemeral-vm-runtime-feature-store.ts b/src/shared/ephemeral-vm-runtime-feature-store.ts index 9dd049a2958..a811cb0e0c6 100644 --- a/src/shared/ephemeral-vm-runtime-feature-store.ts +++ b/src/shared/ephemeral-vm-runtime-feature-store.ts @@ -1,13 +1,13 @@ import { existsSync } from 'node:fs' import { join } from 'node:path' import { z } from 'zod' -import { readNodeFileSyncWithinLimit } from './node-bounded-file-reader' +import { readNodeFileSyncWithinLimit } from './file-content/node-bounded-file-reader' import { JsonStringifyByteLimitError, stringifyJsonWithinByteLimit -} from './node-bounded-json-stringify' -import { writeSecureJsonFileWithinLimit } from './bounded-secure-json-file' -import { hardenExistingSecureFile } from './secure-file' +} from './json-stream/node-bounded-json-stringify' +import { writeSecureJsonFileWithinLimit } from './secure-storage/bounded-secure-json-file' +import { hardenExistingSecureFile } from './secure-storage/secure-file' import { EphemeralVmRuntimeRecordSchema, type EphemeralVmRuntimeRecord diff --git a/src/shared/ephemeral-vm-runtime-store.ts b/src/shared/ephemeral-vm-runtime-store.ts index a7989206b27..7b99b1ec325 100644 --- a/src/shared/ephemeral-vm-runtime-store.ts +++ b/src/shared/ephemeral-vm-runtime-store.ts @@ -1,9 +1,9 @@ import { existsSync } from 'node:fs' import { join } from 'node:path' -import { JsonStringifyByteLimitError } from './node-bounded-json-stringify' -import { readNodeFileSyncWithinLimit } from './node-bounded-file-reader' -import { writeSecureJsonFileWithinLimit } from './bounded-secure-json-file' -import { hardenExistingSecureFile } from './secure-file' +import { JsonStringifyByteLimitError } from './json-stream/node-bounded-json-stringify' +import { readNodeFileSyncWithinLimit } from './file-content/node-bounded-file-reader' +import { writeSecureJsonFileWithinLimit } from './secure-storage/bounded-secure-json-file' +import { hardenExistingSecureFile } from './secure-storage/secure-file' import { toCleanupLastErrorFields, type EphemeralVmFailure } from './ephemeral-vm-failure-copy' import { featureEntryFromRuntime, diff --git a/src/shared/external-automation-jobs-file.ts b/src/shared/external-automation-jobs-file.ts index c4cf1d9aea9..89d49d1be4a 100644 --- a/src/shared/external-automation-jobs-file.ts +++ b/src/shared/external-automation-jobs-file.ts @@ -1,8 +1,11 @@ -import { NodeFileReadTooLargeError, readNodeFileWithinLimit } from './node-bounded-file-reader' +import { + NodeFileReadTooLargeError, + readNodeFileWithinLimit +} from './file-content/node-bounded-file-reader' import { assertJsonTextStructureWithinLimits, type JsonTextStructureLimits -} from './json-text-structure-limit' +} from './json-stream/json-text-structure-limit' export const EXTERNAL_AUTOMATION_JOBS_FILE_MAX_BYTES = 8 * 1024 * 1024 export const EXTERNAL_AUTOMATION_JOBS_MAX_ENTRIES = 10_000 diff --git a/src/shared/fetch-response-body.ts b/src/shared/fetch-response-body.ts index e9467fd3a2d..ebd03e27f97 100644 --- a/src/shared/fetch-response-body.ts +++ b/src/shared/fetch-response-body.ts @@ -1,7 +1,7 @@ import { assertJsonTextStructureWithinLimits, type JsonTextStructureLimits -} from './json-text-structure-limit' +} from './json-stream/json-text-structure-limit' const INITIAL_RESPONSE_CAPACITY_BYTES = 64 * 1024 diff --git a/src/shared/files-runtime-capabilities.ts b/src/shared/file-access/files-runtime-capabilities.ts similarity index 86% rename from src/shared/files-runtime-capabilities.ts rename to src/shared/file-access/files-runtime-capabilities.ts index 61a5dbf4f9a..318a3a8a3ba 100644 --- a/src/shared/files-runtime-capabilities.ts +++ b/src/shared/file-access/files-runtime-capabilities.ts @@ -1,9 +1,9 @@ import { FILE_WRITE_DISK_PRECONDITION_RUNTIME_CAPABILITY, FILE_WRITE_IDENTICAL_RUNTIME_CAPABILITY -} from './file-write-disk-precondition' -import { STAGED_FILE_SAVE_RUNTIME_CAPABILITY } from './staged-file-save' -import { FILE_REPLACE_WITH_UPLOAD_RUNTIME_CAPABILITY } from './file-bytes-write' +} from '../file-write/file-write-disk-precondition' +import { STAGED_FILE_SAVE_RUNTIME_CAPABILITY } from '../file-write/staged-file-save' +import { FILE_REPLACE_WITH_UPLOAD_RUNTIME_CAPABILITY } from '../file-write/file-bytes-write' // Why: older runtimes strip mutation owner fields, so clients must fence writes before RPC. export const FILE_MUTATION_OWNERSHIP_RUNTIME_CAPABILITY = 'files.mutation-ownership.v1' as const diff --git a/src/shared/file-access/filesystem-path-flavor.ts b/src/shared/file-access/filesystem-path-flavor.ts new file mode 100644 index 00000000000..7041bb339fd --- /dev/null +++ b/src/shared/file-access/filesystem-path-flavor.ts @@ -0,0 +1 @@ +export type FilesystemPathFlavor = 'posix' | 'win32' diff --git a/src/shared/local-file-access.ts b/src/shared/file-access/local-file-access.ts similarity index 100% rename from src/shared/local-file-access.ts rename to src/shared/file-access/local-file-access.ts diff --git a/src/shared/path-existence-batch.ts b/src/shared/file-access/path-existence-batch.ts similarity index 100% rename from src/shared/path-existence-batch.ts rename to src/shared/file-access/path-existence-batch.ts diff --git a/src/shared/remote-file-locator.ts b/src/shared/file-access/remote-file-locator.ts similarity index 100% rename from src/shared/remote-file-locator.ts rename to src/shared/file-access/remote-file-locator.ts diff --git a/src/shared/file-access/runtime-editor-file-open.ts b/src/shared/file-access/runtime-editor-file-open.ts new file mode 100644 index 00000000000..68eb294a520 --- /dev/null +++ b/src/shared/file-access/runtime-editor-file-open.ts @@ -0,0 +1,26 @@ +import type { RuntimeNavigationTarget } from '../runtime-navigation' + +export type RuntimeFileOpenResult = { + worktree: string + relativePath: string + kind: 'markdown' | 'text' | 'binary' | 'image' + opened: boolean +} + +export type RuntimeFileOpenPosition = { + line: number + column?: number +} + +/** A file main opened itself, which a window shows: layout-owner builds, local window only. */ +export type RuntimeEditorFileOpen = { + worktreeId: string + filePath: string + relativePath: string + runtimeEnvironmentId?: string | null + navigation?: RuntimeNavigationTarget + position?: RuntimeFileOpenPosition +} + +/** `frameSeq`: the layout stream position whose frame draws the tab. */ +export type RuntimeEditorTabReveal = RuntimeEditorFileOpen & { tabId: string; frameSeq?: number } diff --git a/src/shared/runtime-workspace-file-owner.test.ts b/src/shared/file-access/runtime-workspace-file-owner.test.ts similarity index 100% rename from src/shared/runtime-workspace-file-owner.test.ts rename to src/shared/file-access/runtime-workspace-file-owner.test.ts diff --git a/src/shared/runtime-workspace-file-owner.ts b/src/shared/file-access/runtime-workspace-file-owner.ts similarity index 92% rename from src/shared/runtime-workspace-file-owner.ts rename to src/shared/file-access/runtime-workspace-file-owner.ts index 1edacb07bbc..ee6fe325122 100644 --- a/src/shared/runtime-workspace-file-owner.ts +++ b/src/shared/file-access/runtime-workspace-file-owner.ts @@ -1,5 +1,5 @@ -import type { ExecutionHostId } from './execution-host' -import { normalizeRuntimePathForComparison, relativePathInsideRoot } from './cross-platform-path' +import type { ExecutionHostId } from '../execution-host' +import { normalizeRuntimePathForComparison, relativePathInsideRoot } from '../cross-platform-path' export type RuntimeWorkspaceFileRoot = { workspaceId: string diff --git a/src/shared/terminal-file-grant-refusal.ts b/src/shared/file-access/terminal-file-grant-refusal.ts similarity index 100% rename from src/shared/terminal-file-grant-refusal.ts rename to src/shared/file-access/terminal-file-grant-refusal.ts diff --git a/src/shared/file-range-read.ts b/src/shared/file-content/file-range-read.ts similarity index 100% rename from src/shared/file-range-read.ts rename to src/shared/file-content/file-range-read.ts diff --git a/src/shared/node-bounded-file-reader-sync.test.ts b/src/shared/file-content/node-bounded-file-reader-sync.test.ts similarity index 100% rename from src/shared/node-bounded-file-reader-sync.test.ts rename to src/shared/file-content/node-bounded-file-reader-sync.test.ts diff --git a/src/shared/node-bounded-file-reader-window.test.ts b/src/shared/file-content/node-bounded-file-reader-window.test.ts similarity index 77% rename from src/shared/node-bounded-file-reader-window.test.ts rename to src/shared/file-content/node-bounded-file-reader-window.test.ts index 5f5b126f411..61f207f4a64 100644 --- a/src/shared/node-bounded-file-reader-window.test.ts +++ b/src/shared/file-content/node-bounded-file-reader-window.test.ts @@ -32,26 +32,6 @@ describe('bounded file read window', () => { }) }) - it.each([ - { offset: -1 }, - { offset: 1.5 }, - { offset: Number.MAX_SAFE_INTEGER + 1 }, - { offset: 0, length: -1 }, - { offset: 0, length: 1.5 }, - { offset: 0, length: 20 }, - { offset: 19, length: 2 }, - { offset: 21 } - ])('rejects invalid or incomplete window %j', async (window) => { - await withFile(async (path) => { - const handle = await open(path, 'r') - try { - await expect(readNodeFileHandleWithinLimit(handle, 19, { window })).rejects.toThrow() - } finally { - await handle.close() - } - }) - }) - it('rejects bytes over the cap and honors cancellation before reading', async () => { await withFile(async (path) => { const handle = await open(path, 'r') diff --git a/src/shared/file-content/node-bounded-file-reader.test.ts b/src/shared/file-content/node-bounded-file-reader.test.ts new file mode 100644 index 00000000000..b4171269341 --- /dev/null +++ b/src/shared/file-content/node-bounded-file-reader.test.ts @@ -0,0 +1,57 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { openMock } = vi.hoisted(() => ({ openMock: vi.fn() })) + +vi.mock('node:fs/promises', () => ({ open: openMock })) + +import { readNodeFileWithinLimit } from './node-bounded-file-reader' + +type FileHandleOptions = { + content: Buffer + initialSize?: number + readError?: Error + statError?: Error + firstReadOnly?: boolean +} + +function createFileHandle({ + content, + initialSize, + readError, + statError, + firstReadOnly +}: FileHandleOptions) { + const close = vi.fn().mockResolvedValue(undefined) + const read = vi.fn(async (target: Buffer, offset: number, length: number, position: number) => { + if (readError) { + throw readError + } + if (firstReadOnly && position > 0) { + return { bytesRead: 0, buffer: target } + } + const bytesRead = Math.min(length, Math.max(0, content.byteLength - position)) + content.copy(target, offset, position, position + bytesRead) + return { bytesRead, buffer: target } + }) + const stat = statError + ? vi.fn().mockRejectedValue(statError) + : vi.fn().mockResolvedValue({ size: initialSize ?? content.byteLength }) + return { close, read, stat } +} + +beforeEach(() => openMock.mockReset()) + +describe('readNodeFileWithinLimit', () => { + it('reads the full sysctl value when later offsets return EOF', async () => { + const handle = createFileHandle({ + content: Buffer.from('4096\n'), + initialSize: 0, + firstReadOnly: true + }) + openMock.mockResolvedValue(handle) + + const result = await readNodeFileWithinLimit('/proc/sys/kernel/pty/max', 1024) + + expect(result.buffer.toString('utf8')).toBe('4096\n') + }) +}) diff --git a/src/shared/node-bounded-file-reader.ts b/src/shared/file-content/node-bounded-file-reader.ts similarity index 100% rename from src/shared/node-bounded-file-reader.ts rename to src/shared/file-content/node-bounded-file-reader.ts diff --git a/src/shared/node-file-content-equality.ts b/src/shared/file-content/node-file-content-equality.ts similarity index 100% rename from src/shared/node-file-content-equality.ts rename to src/shared/file-content/node-file-content-equality.ts diff --git a/src/shared/node-readable-text.test.ts b/src/shared/file-content/node-readable-text.test.ts similarity index 100% rename from src/shared/node-readable-text.test.ts rename to src/shared/file-content/node-readable-text.test.ts diff --git a/src/shared/node-readable-text.ts b/src/shared/file-content/node-readable-text.ts similarity index 100% rename from src/shared/node-readable-text.ts rename to src/shared/file-content/node-readable-text.ts diff --git a/src/shared/node-source-copy-content-equality.test.ts b/src/shared/file-content/node-source-copy-content-equality.test.ts similarity index 100% rename from src/shared/node-source-copy-content-equality.test.ts rename to src/shared/file-content/node-source-copy-content-equality.test.ts diff --git a/src/shared/node-source-copy-content-equality.ts b/src/shared/file-content/node-source-copy-content-equality.ts similarity index 100% rename from src/shared/node-source-copy-content-equality.ts rename to src/shared/file-content/node-source-copy-content-equality.ts diff --git a/src/shared/file-content/runtime-file-read.ts b/src/shared/file-content/runtime-file-read.ts new file mode 100644 index 00000000000..96a31411118 --- /dev/null +++ b/src/shared/file-content/runtime-file-read.ts @@ -0,0 +1,23 @@ +import type { RasterImageDimensions } from '../file-preview/raster-image-dimensions' + +export type RuntimeFileReadResult = { + worktree: string + relativePath: string + content: string + truncated: boolean + byteLength: number +} + +export type RuntimeFilePreviewResult = { + content: string + isBinary: boolean + isImage?: boolean + mimeType?: string + imageDimensions?: RasterImageDimensions +} + +export type RuntimeFileReadChunkResult = { + contentBase64: string + bytesRead: number + eof: boolean +} diff --git a/src/shared/filesystem-import-result-types.ts b/src/shared/file-import/filesystem-import-result.ts similarity index 65% rename from src/shared/filesystem-import-result-types.ts rename to src/shared/file-import/filesystem-import-result.ts index acb0b4c4ad3..6079478a142 100644 --- a/src/shared/filesystem-import-result-types.ts +++ b/src/shared/file-import/filesystem-import-result.ts @@ -1,8 +1,3 @@ -import type { - StagedRuntimeUploadEntry, - StagedRuntimeUploadSource -} from './runtime-upload-staging-contract' - export type ImportSkipReason = 'missing' | 'symlink' | 'permission-denied' | 'unsupported' export type ResolveDroppedPathsResult = { @@ -29,7 +24,3 @@ export type ImportItemResult = status: 'failed' reason: string } - -// Staging crosses IPC into the renderer and back to the streamer; share one shape. -export type StagedExternalImportSource = StagedRuntimeUploadSource -export type StagedExternalImportEntry = StagedRuntimeUploadEntry diff --git a/src/shared/native-file-drop-preparation.ts b/src/shared/file-import/native-file-drop-preparation.ts similarity index 100% rename from src/shared/native-file-drop-preparation.ts rename to src/shared/file-import/native-file-drop-preparation.ts diff --git a/src/shared/native-file-drop.test.ts b/src/shared/file-import/native-file-drop.test.ts similarity index 56% rename from src/shared/native-file-drop.test.ts rename to src/shared/file-import/native-file-drop.test.ts index 7a96b9080aa..d40a9189d3c 100644 --- a/src/shared/native-file-drop.test.ts +++ b/src/shared/file-import/native-file-drop.test.ts @@ -1,7 +1,5 @@ import { describe, expect, it } from 'vitest' import { - NATIVE_FILE_DROP_MAX_PATH_BYTES, - NATIVE_FILE_DROP_MAX_PATHS, ORCA_INTERNAL_FILE_DRAG_TYPE, createRejectedNativeFileDropPayload, hasNativeFileDragTypes, @@ -17,19 +15,6 @@ describe('hasNativeFileDragTypes', () => { }) describe('validateNativeFileDropPaths', () => { - it('rejects native drops by file count before path byte accounting is needed', () => { - const paths = Array.from({ length: NATIVE_FILE_DROP_MAX_PATHS + 1 }, (_value, index) => - ['/tmp/file-', String(index)].join('') - ) - - expect(validateNativeFileDropPaths(paths)).toEqual({ - byteLength: 0, - pathCount: NATIVE_FILE_DROP_MAX_PATHS + 1, - reason: 'too-many-paths', - status: 'rejected' - }) - }) - it('rejects native drops whose path list is too large without exposing paths', () => { const validation = validateNativeFileDropPaths(['C:\\Users\\alice\\secret-token.txt'], { maxPathBytes: 4 @@ -56,22 +41,4 @@ describe('validateNativeFileDropPaths', () => { status: 'rejected' }) }) - - it('enforces file count and byte limits at their boundaries', () => { - expect( - validateNativeFileDropPaths(Array.from({ length: NATIVE_FILE_DROP_MAX_PATHS }, () => '/a')) - .status - ).toBe('accepted') - expect( - validateNativeFileDropPaths( - Array.from({ length: NATIVE_FILE_DROP_MAX_PATHS + 1 }, () => '/a') - ).status - ).toBe('rejected') - expect(validateNativeFileDropPaths(['a'.repeat(NATIVE_FILE_DROP_MAX_PATH_BYTES)]).status).toBe( - 'accepted' - ) - expect( - validateNativeFileDropPaths(['a'.repeat(NATIVE_FILE_DROP_MAX_PATH_BYTES + 1)]).status - ).toBe('rejected') - }) }) diff --git a/src/shared/native-file-drop.ts b/src/shared/file-import/native-file-drop.ts similarity index 98% rename from src/shared/native-file-drop.ts rename to src/shared/file-import/native-file-drop.ts index fb19aa03eaf..604abc64536 100644 --- a/src/shared/native-file-drop.ts +++ b/src/shared/file-import/native-file-drop.ts @@ -1,4 +1,4 @@ -import { measureClipboardTextByteLength } from './clipboard-text' +import { measureClipboardTextByteLength } from '../clipboard-text' export const ORCA_INTERNAL_FILE_DRAG_TYPE = 'text/x-orca-file-path' diff --git a/src/shared/runtime-upload-staging-contract.ts b/src/shared/file-import/runtime-upload-staging-contract.ts similarity index 96% rename from src/shared/runtime-upload-staging-contract.ts rename to src/shared/file-import/runtime-upload-staging-contract.ts index 51f1808ff61..eec61419ae0 100644 --- a/src/shared/runtime-upload-staging-contract.ts +++ b/src/shared/file-import/runtime-upload-staging-contract.ts @@ -1,4 +1,4 @@ -import type { SshMutationExpectation } from './ssh-types' +import type { SshMutationExpectation } from '../ssh-types' export type RuntimeUploadSkipReason = 'missing' | 'symlink' | 'permission-denied' | 'unsupported' diff --git a/src/shared/html-file-url.test.ts b/src/shared/file-links/html-file-url.test.ts similarity index 100% rename from src/shared/html-file-url.test.ts rename to src/shared/file-links/html-file-url.test.ts diff --git a/src/shared/html-file-url.ts b/src/shared/file-links/html-file-url.ts similarity index 88% rename from src/shared/html-file-url.ts rename to src/shared/file-links/html-file-url.ts index 51364f24788..21a5a597cae 100644 --- a/src/shared/html-file-url.ts +++ b/src/shared/file-links/html-file-url.ts @@ -1,4 +1,4 @@ -import { fileUriToFilesystemPath } from './file-links/file-uri-path' +import { fileUriToFilesystemPath } from './file-uri-path' /** File authorities name this machine, never an Orca SSH target. */ export function htmlFilePathFromUrl(input: string): string | null { diff --git a/src/shared/recent-path-answers.ts b/src/shared/file-links/recent-path-answers.ts similarity index 100% rename from src/shared/recent-path-answers.ts rename to src/shared/file-links/recent-path-answers.ts diff --git a/src/shared/file-listing/directory-entry.ts b/src/shared/file-listing/directory-entry.ts new file mode 100644 index 00000000000..c6f43efb109 --- /dev/null +++ b/src/shared/file-listing/directory-entry.ts @@ -0,0 +1,5 @@ +export type DirEntry = { + name: string + isDirectory: boolean + isSymlink: boolean +} diff --git a/src/shared/directory-listing-budget.ts b/src/shared/file-listing/directory-listing-budget.ts similarity index 100% rename from src/shared/directory-listing-budget.ts rename to src/shared/file-listing/directory-listing-budget.ts diff --git a/src/shared/file-dir-page.ts b/src/shared/file-listing/file-dir-page.ts similarity index 97% rename from src/shared/file-dir-page.ts rename to src/shared/file-listing/file-dir-page.ts index 4354264022e..7a59a1ecdd2 100644 --- a/src/shared/file-dir-page.ts +++ b/src/shared/file-listing/file-dir-page.ts @@ -1,4 +1,4 @@ -import type { DirEntry } from './filesystem-entry-types' +import type { DirEntry } from './directory-entry' import { compareDirEntries } from './file-name-sort' /** diff --git a/src/shared/file-listing/file-document.ts b/src/shared/file-listing/file-document.ts new file mode 100644 index 00000000000..34c43bf6943 --- /dev/null +++ b/src/shared/file-listing/file-document.ts @@ -0,0 +1,8 @@ +export type FileDocument = { + filePath: string + relativePath: string + basename: string + name: string +} + +export type MarkdownDocument = FileDocument diff --git a/src/shared/file-explorer-display-root.test.ts b/src/shared/file-listing/file-explorer-display-root.test.ts similarity index 100% rename from src/shared/file-explorer-display-root.test.ts rename to src/shared/file-listing/file-explorer-display-root.test.ts diff --git a/src/shared/file-explorer-display-root.ts b/src/shared/file-listing/file-explorer-display-root.ts similarity index 100% rename from src/shared/file-explorer-display-root.ts rename to src/shared/file-listing/file-explorer-display-root.ts diff --git a/src/shared/file-inventory-budget.test.ts b/src/shared/file-listing/file-inventory-budget.test.ts similarity index 100% rename from src/shared/file-inventory-budget.test.ts rename to src/shared/file-listing/file-inventory-budget.test.ts diff --git a/src/shared/file-inventory-budget.ts b/src/shared/file-listing/file-inventory-budget.ts similarity index 91% rename from src/shared/file-inventory-budget.ts rename to src/shared/file-listing/file-inventory-budget.ts index 3eb1c7786ef..39fe7a61286 100644 --- a/src/shared/file-inventory-budget.ts +++ b/src/shared/file-listing/file-inventory-budget.ts @@ -1,4 +1,4 @@ -import { serializedQuickOpenPathBytes } from './quick-open-transport-budget' +import { serializedQuickOpenPathBytes } from '../quick-open/quick-open-transport-budget' export const FILE_INVENTORY_MAX_BYTES = 64 * 1024 * 1024 export const FILE_INVENTORY_MAX_PATH_BYTES = 64 * 1024 diff --git a/src/shared/file-listing-cancellation.ts b/src/shared/file-listing/file-listing-cancellation.ts similarity index 100% rename from src/shared/file-listing-cancellation.ts rename to src/shared/file-listing/file-listing-cancellation.ts diff --git a/src/shared/file-name-filter-tokens.ts b/src/shared/file-listing/file-name-filter-tokens.ts similarity index 95% rename from src/shared/file-name-filter-tokens.ts rename to src/shared/file-listing/file-name-filter-tokens.ts index badad7006d1..2cfa439b6b2 100644 --- a/src/shared/file-name-filter-tokens.ts +++ b/src/shared/file-listing/file-name-filter-tokens.ts @@ -1,4 +1,4 @@ -import { isClipboardTextByteLengthOverLimit } from './clipboard-text' +import { isClipboardTextByteLengthOverLimit } from '../clipboard-text' /** Explorer name-filter matching, shared so the host can filter a scan exactly like the renderer. */ diff --git a/src/shared/file-name-sort.ts b/src/shared/file-listing/file-name-sort.ts similarity index 100% rename from src/shared/file-name-sort.ts rename to src/shared/file-listing/file-name-sort.ts diff --git a/src/shared/file-listing/markdown-document-listing-limits.test.ts b/src/shared/file-listing/markdown-document-listing-limits.test.ts new file mode 100644 index 00000000000..cd86f20e509 --- /dev/null +++ b/src/shared/file-listing/markdown-document-listing-limits.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from 'vitest' +import type { MarkdownDocument } from './file-document' +import { + assertMarkdownDocumentsWithinLimit, + MarkdownDocumentListingCapacityError +} from './markdown-document-listing-limits' + +function document(path: string): MarkdownDocument { + return { + filePath: `/repo/${path}`, + relativePath: path, + basename: path, + name: path + } +} + +describe('Markdown document listing limits', () => { + it('rejects aggregate metadata overflow', () => { + expect(() => + assertMarkdownDocumentsWithinLimit([document('a'.repeat(100))], { + maxMetadataBytes: 100 + }) + ).toThrow(MarkdownDocumentListingCapacityError) + }) +}) diff --git a/src/shared/markdown-document-listing-limits.ts b/src/shared/file-listing/markdown-document-listing-limits.ts similarity index 96% rename from src/shared/markdown-document-listing-limits.ts rename to src/shared/file-listing/markdown-document-listing-limits.ts index 44ed87005a2..9922990a5df 100644 --- a/src/shared/markdown-document-listing-limits.ts +++ b/src/shared/file-listing/markdown-document-listing-limits.ts @@ -1,5 +1,5 @@ -import type { MarkdownDocument } from './filesystem-entry-types' -import { measureUtf8ByteLength } from './utf8-byte-limits' +import type { MarkdownDocument } from './file-document' +import { measureUtf8ByteLength } from '../utf8-byte-limits' export const MARKDOWN_DOCUMENT_LISTING_MAX_DOCUMENTS = 20_000 export const MARKDOWN_DOCUMENT_LISTING_MAX_METADATA_BYTES = 8 * 1024 * 1024 diff --git a/src/shared/markdown-document-paths-windows-client.test.ts b/src/shared/file-listing/markdown-document-paths-windows-client.test.ts similarity index 69% rename from src/shared/markdown-document-paths-windows-client.test.ts rename to src/shared/file-listing/markdown-document-paths-windows-client.test.ts index 1d5ed71f51b..07c6a33dd5f 100644 --- a/src/shared/markdown-document-paths-windows-client.test.ts +++ b/src/shared/file-listing/markdown-document-paths-windows-client.test.ts @@ -9,19 +9,6 @@ vi.mock('node:path', async (importOriginal) => { import { markdownDocumentFromRelativePath } from './markdown-document-paths' describe('remote Markdown filenames on a Windows client', () => { - it.each(['notes\\.md', 'a\\b.MDX', '..\\a.markdown', 'nested/README.md'])( - 'preserves POSIX filename %s and its extension', - (relativePath) => { - const basename = relativePath.slice(relativePath.lastIndexOf('/') + 1) - expect(markdownDocumentFromRelativePath('/home/repo', relativePath)).toEqual({ - filePath: `/home/repo/${relativePath}`, - relativePath, - basename, - name: basename.slice(0, basename.lastIndexOf('.')) - }) - } - ) - it.each(['notes.md\\', 'nested/.md', '../outside.md'])( 'rejects non-Markdown or escaping POSIX filename %s', (relativePath) => { diff --git a/src/shared/markdown-document-paths.test.ts b/src/shared/file-listing/markdown-document-paths.test.ts similarity index 73% rename from src/shared/markdown-document-paths.test.ts rename to src/shared/file-listing/markdown-document-paths.test.ts index 35feaee5f82..6cd55a654f1 100644 --- a/src/shared/markdown-document-paths.test.ts +++ b/src/shared/file-listing/markdown-document-paths.test.ts @@ -13,17 +13,6 @@ describe('markdownDocumentFromFilePath', () => { }) }) - it('preserves POSIX remote filenames and trailing root backslashes', () => { - for (const name of ['a\\b.md', 'a/b.md', '..\\a.md']) { - expect(markdownDocumentFromRelativePath('/repo\\', name)).toMatchObject({ - filePath: `/repo\\/${name}`, - relativePath: name, - basename: name.slice(name.lastIndexOf('/') + 1) - }) - } - expect(markdownDocumentFromRelativePath('/repo\\', '../a.md')).toBeNull() - }) - it.each(['C:\\repo\\', '\\\\server\\share\\repo\\'])( 'preserves Windows separator handling under %s', (root) => { diff --git a/src/shared/markdown-document-paths.ts b/src/shared/file-listing/markdown-document-paths.ts similarity index 94% rename from src/shared/markdown-document-paths.ts rename to src/shared/file-listing/markdown-document-paths.ts index 426a7f7c4f0..0a5ad584203 100644 --- a/src/shared/markdown-document-paths.ts +++ b/src/shared/file-listing/markdown-document-paths.ts @@ -2,10 +2,10 @@ import { createMarkdownDocumentListingBudget, retainMarkdownDocument } from './markdown-document-listing-limits' -import { isWindowsAbsolutePathLike } from './cross-platform-path' -import { normalizeRelativePath } from './text-search-paths' +import { isWindowsAbsolutePathLike } from '../cross-platform-path' +import { normalizeRelativePath } from '../file-search/text-search-paths' import { basename as pathBasename, extname, isAbsolute, posix, relative, resolve } from 'node:path' -import type { FileDocument, MarkdownDocument } from './filesystem-entry-types' +import type { FileDocument, MarkdownDocument } from './file-document' export function isMarkdownDocumentName(name: string): boolean { return isMarkdownExtension(extname(name)) } diff --git a/src/shared/node-markdown-document-listing.ts b/src/shared/file-listing/node-markdown-document-listing.ts similarity index 93% rename from src/shared/node-markdown-document-listing.ts rename to src/shared/file-listing/node-markdown-document-listing.ts index 3004b1ccc54..26e14e7ecc3 100644 --- a/src/shared/node-markdown-document-listing.ts +++ b/src/shared/file-listing/node-markdown-document-listing.ts @@ -1,10 +1,13 @@ import type { ChildProcessHandle } from '@orca/process-host/process-spec' -import type { MarkdownDocument } from './filesystem-entry-types' -import { RipgrepFilenameDecoder } from './ripgrep-filename-decoder' -import { isRipgrepMissingCwdExit, ripgrepMissingCwdError } from './ripgrep-process-availability' -import { abortSignalReason } from './abort-signal-reason' +import type { MarkdownDocument } from './file-document' +import { RipgrepFilenameDecoder } from '../ripgrep/ripgrep-filename-decoder' +import { + isRipgrepMissingCwdExit, + ripgrepMissingCwdError +} from '../ripgrep/ripgrep-process-availability' +import { abortSignalReason } from '../abort-signal-reason' import { markdownDocumentFromRelativePath, isMarkdownDocumentName } from './markdown-document-paths' -import { joinSearchRoot } from './text-search-paths' +import { joinSearchRoot } from '../file-search/text-search-paths' import { createMarkdownDocumentListingBudget, retainMarkdownDocument, diff --git a/src/shared/file-listing/runtime-file-list.ts b/src/shared/file-listing/runtime-file-list.ts new file mode 100644 index 00000000000..a82a826fce2 --- /dev/null +++ b/src/shared/file-listing/runtime-file-list.ts @@ -0,0 +1,14 @@ +export type RuntimeFileListEntry = { + relativePath: string + basename: string + kind: 'text' | 'binary' +} + +export type RuntimeFileListResult = { + worktree: string + rootPath: string + files: RuntimeFileListEntry[] + totalCount: number + truncated: boolean + quickOpenSearchVersion?: number +} diff --git a/src/shared/binary-buffer.ts b/src/shared/file-preview/binary-buffer.ts similarity index 100% rename from src/shared/binary-buffer.ts rename to src/shared/file-preview/binary-buffer.ts diff --git a/src/shared/binary-file-extensions.ts b/src/shared/file-preview/binary-file-extensions.ts similarity index 91% rename from src/shared/binary-file-extensions.ts rename to src/shared/file-preview/binary-file-extensions.ts index 56ae97845a5..01a0fcf8706 100644 --- a/src/shared/binary-file-extensions.ts +++ b/src/shared/file-preview/binary-file-extensions.ts @@ -1,6 +1,4 @@ -import { IMAGE_FILE_EXTENSIONS } from './media-file-extensions' - -export { IMAGE_FILE_MIME_TYPES, IMAGE_FILE_EXTENSIONS } from './media-file-extensions' +import { IMAGE_FILE_EXTENSIONS } from './image-mime-types' // Keep SVG out of binary extensions because editors open it as source text. const TEXT_IMAGE_EXTENSIONS = new Set(['.svg']) diff --git a/src/shared/file-preview-kind.ts b/src/shared/file-preview/file-preview-kind.ts similarity index 94% rename from src/shared/file-preview-kind.ts rename to src/shared/file-preview/file-preview-kind.ts index 682d3d82706..3fceb3ede10 100644 --- a/src/shared/file-preview-kind.ts +++ b/src/shared/file-preview/file-preview-kind.ts @@ -1,5 +1,5 @@ -import { IMAGE_FILE_MIME_TYPES } from './image-file-extensions' -import { MEDIA_FILE_MIME_TYPES } from './media-file-extensions' +import { IMAGE_FILE_MIME_TYPES } from './image-mime-types' +import { MEDIA_FILE_MIME_TYPES } from './media-mime-types' import { isKnownRasterImageMimeType } from './raster-image-preview-limits' export type FilePreviewKind = 'image' | 'pdf' | 'audio' | 'video' diff --git a/src/shared/font-file-extensions.ts b/src/shared/file-preview/font-file-extensions.ts similarity index 100% rename from src/shared/font-file-extensions.ts rename to src/shared/file-preview/font-file-extensions.ts diff --git a/src/shared/image-data-uri.test.ts b/src/shared/file-preview/image-data-uri.test.ts similarity index 100% rename from src/shared/image-data-uri.test.ts rename to src/shared/file-preview/image-data-uri.test.ts diff --git a/src/shared/image-data-uri.ts b/src/shared/file-preview/image-data-uri.ts similarity index 100% rename from src/shared/image-data-uri.ts rename to src/shared/file-preview/image-data-uri.ts diff --git a/src/shared/file-preview/image-mime-types.ts b/src/shared/file-preview/image-mime-types.ts new file mode 100644 index 00000000000..c80496b40b3 --- /dev/null +++ b/src/shared/file-preview/image-mime-types.ts @@ -0,0 +1,12 @@ +export const IMAGE_FILE_MIME_TYPES: Record = { + '.png': 'image/png', + '.jpg': 'image/jpeg', + '.jpeg': 'image/jpeg', + '.gif': 'image/gif', + '.svg': 'image/svg+xml', + '.webp': 'image/webp', + '.bmp': 'image/bmp', + '.ico': 'image/x-icon' +} + +export const IMAGE_FILE_EXTENSIONS = Object.freeze(Object.keys(IMAGE_FILE_MIME_TYPES)) diff --git a/src/shared/file-preview/media-mime-types.ts b/src/shared/file-preview/media-mime-types.ts new file mode 100644 index 00000000000..28a9557d169 --- /dev/null +++ b/src/shared/file-preview/media-mime-types.ts @@ -0,0 +1,14 @@ +export const MEDIA_FILE_MIME_TYPES: Record = { + '.mp3': 'audio/mpeg', + '.wav': 'audio/wav', + '.m4a': 'audio/mp4', + '.aac': 'audio/aac', + '.ogg': 'audio/ogg', + '.oga': 'audio/ogg', + '.flac': 'audio/flac', + '.opus': 'audio/ogg', + '.mp4': 'video/mp4', + '.m4v': 'video/mp4', + '.mov': 'video/quicktime', + '.webm': 'video/webm' +} diff --git a/src/shared/file-preview/media-preview-scheme.ts b/src/shared/file-preview/media-preview-scheme.ts new file mode 100644 index 00000000000..519a1924050 --- /dev/null +++ b/src/shared/file-preview/media-preview-scheme.ts @@ -0,0 +1 @@ +export const MEDIA_PREVIEW_SCHEME = 'orca-media' diff --git a/src/shared/file-preview/raster-image-base64-preview.test.ts b/src/shared/file-preview/raster-image-base64-preview.test.ts new file mode 100644 index 00000000000..e81ea5e40ad --- /dev/null +++ b/src/shared/file-preview/raster-image-base64-preview.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from 'vitest' +import { exceedsRasterImagePreviewLimits } from './raster-image-base64-preview' + +function pngBytes(totalBytes: number, width: number, height: number): Buffer { + const bytes = Buffer.alloc(Math.max(totalBytes, 24)) + Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).copy(bytes) + bytes.writeUInt32BE(13, 8) + bytes.write('IHDR', 12, 'ascii') + bytes.writeUInt32BE(width, 16) + bytes.writeUInt32BE(height, 20) + for (let index = 24; index < bytes.length; index += 1) { + bytes[index] = (index * 31 + 7) & 0xff + } + return bytes +} + +describe('exceedsRasterImagePreviewLimits', () => { + it('keeps rendering an over-limit header whose payload is not valid base64', () => { + const content = `${pngBytes(70_000, 32_769, 1).toString('base64')}!!!` + expect(exceedsRasterImagePreviewLimits(content, 'image/png')).toBe(false) + }) +}) diff --git a/src/shared/raster-image-base64-preview.ts b/src/shared/file-preview/raster-image-base64-preview.ts similarity index 100% rename from src/shared/raster-image-base64-preview.ts rename to src/shared/file-preview/raster-image-base64-preview.ts diff --git a/src/shared/raster-image-dimensions.test.ts b/src/shared/file-preview/raster-image-dimensions.test.ts similarity index 100% rename from src/shared/raster-image-dimensions.test.ts rename to src/shared/file-preview/raster-image-dimensions.test.ts diff --git a/src/shared/raster-image-dimensions.ts b/src/shared/file-preview/raster-image-dimensions.ts similarity index 100% rename from src/shared/raster-image-dimensions.ts rename to src/shared/file-preview/raster-image-dimensions.ts diff --git a/src/shared/raster-image-prefix-limits.ts b/src/shared/file-preview/raster-image-prefix-limits.ts similarity index 100% rename from src/shared/raster-image-prefix-limits.ts rename to src/shared/file-preview/raster-image-prefix-limits.ts diff --git a/src/shared/raster-image-preview-limits.ts b/src/shared/file-preview/raster-image-preview-limits.ts similarity index 100% rename from src/shared/raster-image-preview-limits.ts rename to src/shared/file-preview/raster-image-preview-limits.ts diff --git a/src/shared/remote-file-preview-address.test.ts b/src/shared/file-preview/remote-file-preview-address.test.ts similarity index 100% rename from src/shared/remote-file-preview-address.test.ts rename to src/shared/file-preview/remote-file-preview-address.test.ts diff --git a/src/shared/remote-file-preview-address.ts b/src/shared/file-preview/remote-file-preview-address.ts similarity index 96% rename from src/shared/remote-file-preview-address.ts rename to src/shared/file-preview/remote-file-preview-address.ts index 822f3b266e9..d95ccb37cf1 100644 --- a/src/shared/remote-file-preview-address.ts +++ b/src/shared/file-preview/remote-file-preview-address.ts @@ -1,4 +1,4 @@ -import type { RemoteFileLocator } from './remote-file-locator' +import type { RemoteFileLocator } from '../file-access/remote-file-locator' /** A file on a paired runtime that the desktop streams to a viewer by byte range. */ export type RemoteFilePreviewAddress = { diff --git a/src/shared/svg-document.test.ts b/src/shared/file-preview/svg-document.test.ts similarity index 100% rename from src/shared/svg-document.test.ts rename to src/shared/file-preview/svg-document.test.ts diff --git a/src/shared/svg-document.ts b/src/shared/file-preview/svg-document.ts similarity index 100% rename from src/shared/svg-document.ts rename to src/shared/file-preview/svg-document.ts diff --git a/src/shared/code-search-types.ts b/src/shared/file-search/code-search-types.ts similarity index 100% rename from src/shared/code-search-types.ts rename to src/shared/file-search/code-search-types.ts diff --git a/src/shared/search-match-count.ts b/src/shared/file-search/search-match-count.ts similarity index 100% rename from src/shared/search-match-count.ts rename to src/shared/file-search/search-match-count.ts diff --git a/src/shared/search-result-transport-budget.ts b/src/shared/file-search/search-result-transport-budget.ts similarity index 92% rename from src/shared/search-result-transport-budget.ts rename to src/shared/file-search/search-result-transport-budget.ts index 8f2d79b69bc..b7085ef74a9 100644 --- a/src/shared/search-result-transport-budget.ts +++ b/src/shared/file-search/search-result-transport-budget.ts @@ -1,5 +1,5 @@ import type { SearchFileResult, SearchResult } from './code-search-types' -import { remoteRpcResultExceedsContentBudget } from './remote-rpc-content-budget' +import { remoteRpcResultExceedsContentBudget } from '../remote-rpc-content-budget' /** * `result` cut to whole files that fit one remote reply, marked truncated: a search past the reply diff --git a/src/shared/file-search/text-search-dense-matches.test.ts b/src/shared/file-search/text-search-dense-matches.test.ts new file mode 100644 index 00000000000..3ff2da508af --- /dev/null +++ b/src/shared/file-search/text-search-dense-matches.test.ts @@ -0,0 +1,34 @@ +import { expect, it } from 'vitest' + +import { createAccumulator, ingestRgJsonLine } from './text-search' + +function denseRecord(count: number): string { + return JSON.stringify({ + type: 'match', + data: { + path: { text: '/root/dense.txt' }, + lines: { text: 'x '.repeat(count) }, + line_number: 1, + submatches: Array.from({ length: count }, (_, index) => ({ + match: { text: 'x' }, + start: index * 2, + end: index * 2 + 1 + })) + } + }) +} + +it.each([ + (record: string) => record.slice(0, -1), + (record: string) => `${record.slice(0, -2)},invalid}`, + (record: string) => `${record.slice(0, -1)},"data":{}}`, + (record: string) => `${record.slice(0, -2)},"submatches":[]}}` +])( + 'rejects invalid tails or duplicate envelope keys without retaining early matches', + (corrupt) => { + const accumulator = createAccumulator() + ingestRgJsonLine(corrupt(denseRecord(10_000)), '/root', accumulator, 2000) + expect(accumulator.totalMatches).toBe(0) + expect(accumulator.truncated).toBe(true) + } +) diff --git a/src/shared/file-search/text-search-glob-patterns.test.ts b/src/shared/file-search/text-search-glob-patterns.test.ts new file mode 100644 index 00000000000..7b4616d4979 --- /dev/null +++ b/src/shared/file-search/text-search-glob-patterns.test.ts @@ -0,0 +1,96 @@ +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { runProcess } from '@orca/process-host' +import { splitSearchGlobPatterns } from './text-search-glob-patterns' +import { buildGitGrepArgs } from './text-search' + +describe('compound search globs', () => { + it.each([ + ['', []], + [' , *.ts,, *.md, ', ['*.ts', '*.md']], + ['}.ts, *.md', ['}.ts', '*.md']], + ['*.{ts,tsx}, *.md', ['*.{ts,tsx}', '*.md']], + ['{src,{lib,test}}/**, *.md', ['{src,{lib,test}}/**', '*.md']], + ['*[a,b].ts, *.md', ['*[a,b].ts', '*.md']], + ['[{},].ts, *.md', ['[{},].ts', '*.md']], + ['[]a,b].ts, *.md', ['[]a,b].ts', '*.md']], + ['[!]a,b].ts, *.md', ['[!]a,b].ts', '*.md']], + ['[^]a,b].ts, *.md', ['[^]a,b].ts', '*.md']], + ['[[:alpha:],].ts, *.md', ['[[:alpha:],].ts', '*.md']], + ['[a\\],b].ts, *.md', ['[a\\],b].ts', '*.md']], + ['foo\\,bar/**, *.ts', ['foo\\,bar/**', '*.ts']], + ['\\{a,b\\}, *.ts', ['\\{a', 'b\\}', '*.ts']], + ['\\[a,b\\], *.ts', ['\\[a', 'b\\]', '*.ts']], + ['src\\', ['src\\']], + ['*.{ts,tsx', ['*.{ts,tsx']], + ['[a,b', ['[a,b']] + ])('preserves grouped and escaped commas in %s', (input, expected) => { + expect(splitSearchGlobPatterns(input, 'git')).toEqual(expected) + }) + + it('preserves 20000 nested groups without expanding alternatives', () => { + const pattern = `${'{'.repeat(20_000)}a,b${'}'.repeat(20_000)}` + expect(splitSearchGlobPatterns(`${pattern}, *.md`)).toEqual([pattern, '*.md']) + }) +}) + +describe('file search with real search engines', () => { + let root: string + + beforeAll(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-search-globs-')) + for (const file of ['a.ts', 'b.tsx', 'c.md', ',.ts']) { + await writeFile(join(root, file), 'needle\n') + } + const initialized = await runProcess({ program: 'git', args: ['init'], cwd: root }) + expect(initialized.code).toBe(0) + }) + + afterAll(async () => { + if (root) { + await rm(root, { recursive: true, force: true }) + } + }) + + it('keeps Git brace syntax literal instead of expanding it', async () => { + const result = await runProcess({ + program: 'git', + args: buildGitGrepArgs('needle', { includePattern: '*.{ts,tsx}' }), + cwd: root + }) + expect(result.code).toBe(1) + expect(result.stdout).toBe('') + expect(result.stderr).toBe('') + }) + + it('preserves character classes in Git exclusions', async () => { + const result = await runProcess({ + program: 'git', + args: buildGitGrepArgs('needle', { excludePattern: '[[:alpha:],].ts' }), + cwd: root + }) + expect(result.code).toBe(0) + expect(result.stdout).toContain('b.tsx\0') + expect(result.stdout).toContain('c.md\0') + expect(result.stdout).not.toContain('a.ts\0') + expect(result.stdout).not.toContain(',.ts\0') + }) + + it.each(['[a,b].ts', '[[:alpha:],].ts'])( + 'preserves %s in the Git fallback too', + async (includePattern) => { + const result = await runProcess({ + program: 'git', + args: buildGitGrepArgs('needle', { includePattern }), + cwd: root + }) + expect(result.code).toBe(0) + expect(result.stdout).toContain('a.ts\0') + expect(result.stdout).toContain(',.ts\0') + expect(result.stdout).not.toContain('b.tsx\0') + expect(result.stdout).not.toContain('c.md\0') + } + ) +}) diff --git a/src/shared/text-search-glob-patterns.ts b/src/shared/file-search/text-search-glob-patterns.ts similarity index 100% rename from src/shared/text-search-glob-patterns.ts rename to src/shared/file-search/text-search-glob-patterns.ts diff --git a/src/shared/text-search-invalid-filename.test.ts b/src/shared/file-search/text-search-invalid-filename.test.ts similarity index 100% rename from src/shared/text-search-invalid-filename.test.ts rename to src/shared/file-search/text-search-invalid-filename.test.ts diff --git a/src/shared/text-search-match-accumulator.ts b/src/shared/file-search/text-search-match-accumulator.ts similarity index 95% rename from src/shared/text-search-match-accumulator.ts rename to src/shared/file-search/text-search-match-accumulator.ts index 391bb2587c9..0c47b21292d 100644 --- a/src/shared/text-search-match-accumulator.ts +++ b/src/shared/file-search/text-search-match-accumulator.ts @@ -1,7 +1,7 @@ import type { SearchFileResult, SearchMatch } from './code-search-types' import type { SearchAccumulator } from './text-search' -import { sliceAtCodeUnitLimit } from './surrogate-safe-text-slice' -import { ownRetainedString } from './own-retained-string' +import { sliceAtCodeUnitLimit } from '../surrogate-safe-text-slice' +import { ownRetainedString } from '../own-retained-string' // Bound repeated context so dense search results fit within the SSH message limit. export const MAX_LINE_CONTENT_LENGTH = 500 diff --git a/src/shared/text-search-paths.test.ts b/src/shared/file-search/text-search-paths.test.ts similarity index 100% rename from src/shared/text-search-paths.test.ts rename to src/shared/file-search/text-search-paths.test.ts diff --git a/src/shared/text-search-paths.ts b/src/shared/file-search/text-search-paths.ts similarity index 93% rename from src/shared/text-search-paths.ts rename to src/shared/file-search/text-search-paths.ts index 4e7cd154158..583abc868a6 100644 --- a/src/shared/text-search-paths.ts +++ b/src/shared/file-search/text-search-paths.ts @@ -1,5 +1,5 @@ import { posix, win32 } from 'node:path' -import { isWindowsAbsolutePathLike } from './cross-platform-path' +import { isWindowsAbsolutePathLike } from '../cross-platform-path' function pathFlavor(rootPath: string): typeof posix | typeof win32 { if (isWindowsAbsolutePathLike(rootPath)) { diff --git a/src/shared/file-search/text-search-snippet-boundaries.test.ts b/src/shared/file-search/text-search-snippet-boundaries.test.ts new file mode 100644 index 00000000000..e2e2496a5d1 --- /dev/null +++ b/src/shared/file-search/text-search-snippet-boundaries.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, it } from 'vitest' +import { createAccumulator, ingestGitGrepLine, ingestRgJsonLine } from './text-search' + +describe('search snippet character boundaries', () => { + it('uses the same character-safe context for the remote git fallback', () => { + const prefix = '😀'.repeat(300) + const accumulator = createAccumulator() + ingestGitGrepLine(`unicode.txt\x001\x00${prefix}xx${prefix}`, '/root', /xx/g, accumulator, 2000) + const match = [...accumulator.fileMap.values()][0].matches[0] + expect(match.lineContent.isWellFormed()).toBe(true) + expect(match.column).toBe(601) + const start = (match.displayColumn ?? match.column) - 1 + expect( + match.lineContent.slice(start, start + (match.displayMatchLength ?? match.matchLength)) + ).toBe('xx') + }) + + it('never returns a negative display length for a zero-width range after the line terminator', () => { + const text = `${'x'.repeat(600)}\n` + const accumulator = createAccumulator() + ingestRgJsonLine( + JSON.stringify({ + type: 'match', + data: { + path: { text: 'line.txt' }, + lines: { text }, + line_number: 1, + submatches: [{ start: text.length, end: text.length }] + } + }), + '/root', + accumulator, + 2000 + ) + const match = [...accumulator.fileMap.values()][0].matches[0] + expect(match.matchLength).toBe(0) + expect(match.displayMatchLength).toBe(0) + }) + + it('excludes truncation markers when a fallback regex begins inside a surrogate pair', () => { + const accumulator = createAccumulator() + ingestGitGrepLine( + `unicode.txt\x001\x00${'😀'.repeat(600)}`, + '/root', + /.{501}/g, + accumulator, + 2000 + ) + const match = [...accumulator.fileMap.values()][0].matches[1] + expect(match.column).toBe(502) + expect(match.matchLength).toBe(501) + expect(match.displayColumn).toBe(2) + expect(match.displayMatchLength).toBe(498) + expect(match.lineContent).toBe(`…${'😀'.repeat(249)}…`) + expect(match.lineContent.slice(1, 499)).toBe('😀'.repeat(249)) + }) +}) diff --git a/src/shared/text-search.test.ts b/src/shared/file-search/text-search.test.ts similarity index 56% rename from src/shared/text-search.test.ts rename to src/shared/file-search/text-search.test.ts index 80929b2afa9..b4a2c6c1469 100644 --- a/src/shared/text-search.test.ts +++ b/src/shared/file-search/text-search.test.ts @@ -1,17 +1,10 @@ -import { describe, expect, it, vi } from 'vitest' -import { execFileSync } from 'node:child_process' -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' +import { describe, expect, it } from 'vitest' + import { - buildGitGrepArgs, buildSubmatchRegex, createAccumulator, - finalize, ingestGitGrepLine, - ingestRgJsonLine, - MAX_LINE_CONTENT_LENGTH, - SEARCH_JSON_STRUCTURE_LIMITS + ingestRgJsonLine } from './text-search' describe('ingestRgJsonLine', () => { @@ -31,22 +24,6 @@ describe('ingestRgJsonLine', () => { } }) - it('rejects excessive nesting before JSON.parse', () => { - const parseSpy = vi.spyOn(JSON, 'parse') - const acc = createAccumulator() - try { - const amplified = `${'['.repeat(SEARCH_JSON_STRUCTURE_LIMITS.nestingDepth + 1)}0${']'.repeat( - SEARCH_JSON_STRUCTURE_LIMITS.nestingDepth + 1 - )}` - - expect(ingestRgJsonLine(amplified, '/root', acc, 100)).toBe('continue') - expect(parseSpy).not.toHaveBeenCalled() - expect(acc.totalMatches).toBe(0) - } finally { - parseSpy.mockRestore() - } - }) - it('creates a navigable fallback match when rg omits submatch ranges', () => { const acc = createAccumulator() const verdict = ingestRgJsonLine(makeMatch('/root/a.ts', 4, [], 'foobar'), '/root', acc, 100) @@ -82,99 +59,9 @@ describe('ingestRgJsonLine', () => { expect(acc.totalMatches).toBe(2) expect(Array.from(acc.fileMap.values())[0].matchCount).toBe(2) }) - - it('clamps huge lineContent around the match to bound payload size', () => { - const acc = createAccumulator() - const huge = `${'x'.repeat(200_000)}NEEDLE${'y'.repeat(200_000)}` - const matchStart = 200_000 - ingestRgJsonLine( - JSON.stringify({ - type: 'match', - data: { - path: { text: '/root/big.js' }, - line_number: 1, - lines: { text: `${huge}\n` }, - submatches: [{ start: matchStart, end: matchStart + 6 }] - } - }), - '/root', - acc, - 100 - ) - const match = Array.from(acc.fileMap.values())[0].matches[0] - expect(match.lineContent.length).toBeLessThanOrEqual(MAX_LINE_CONTENT_LENGTH + 2) - expect(match.column).toBe(matchStart + 1) - expect(match.matchLength).toBe(6) - expect(match.displayColumn).toBeDefined() - expect(match.displayMatchLength).toBe(6) - const displayColumn = match.displayColumn ?? match.column - const displayMatchLength = match.displayMatchLength ?? match.matchLength - const sliced = match.lineContent.slice( - displayColumn - 1, - displayColumn - 1 + displayMatchLength - ) - expect(sliced).toBe('NEEDLE') - }) }) describe('ingestGitGrepLine', () => { - it('parses actual git grep null-delimited output from the current git binary', () => { - const rootPath = mkdtempSync(join(tmpdir(), 'orca-search-git-')) - try { - execFileSync('git', ['init'], { cwd: rootPath, stdio: 'ignore' }) - mkdirSync(join(rootPath, 'src')) - writeFileSync( - join(rootPath, 'src', 'a.ts'), - [ - "reportError(err, { action: 'save' })", - 'reportError(err); reportError(next)', - 'unrelated' - ].join('\n') - ) - - const stdout = execFileSync( - 'git', - buildGitGrepArgs('reportError(', { caseSensitive: false, useRegex: false }), - { cwd: rootPath, encoding: 'utf8' } - ) - const acc = createAccumulator() - const re = buildSubmatchRegex('reportError(', {}) - for (const line of stdout.split('\n')) { - ingestGitGrepLine(line, rootPath, re, acc, 100) - } - - const result = finalize(acc) - expect(result.totalMatches).toBe(3) - expect(result.files).toHaveLength(1) - expect(result.files[0].relativePath).toBe('src/a.ts') - expect(result.files[0].matchCount).toBe(3) - expect(result.files[0].matches.map((match) => [match.line, match.column])).toEqual([ - [1, 1], - [2, 1], - [2, 19] - ]) - } finally { - rmSync(rootPath, { recursive: true, force: true }) - } - }) - - it('does not broaden a separator-only include pattern to the repository', () => { - const rootPath = mkdtempSync(join(tmpdir(), 'orca-search-git-')) - try { - execFileSync('git', ['init'], { cwd: rootPath, stdio: 'ignore' }) - writeFileSync(join(rootPath, 'target.ts'), 'needle\n') - - expect(() => - execFileSync('git', buildGitGrepArgs('needle', { includePattern: '/' }), { - cwd: rootPath, - stdio: 'ignore' - }) - ).toThrow() - } finally { - rmSync(rootPath, { recursive: true, force: true }) - } - }) - it('parses git grep null-delimited line, finds all submatch positions', () => { const acc = createAccumulator() const re = buildSubmatchRegex('foo', {}) @@ -229,14 +116,6 @@ describe('ingestGitGrepLine', () => { expect(acc.totalMatches).toBe(0) }) - it('zero-length regex does not loop', () => { - const acc = createAccumulator() - const re = new RegExp('', 'g') - ingestGitGrepLine('a.ts\x001\x00abc', '/r', re, acc, 5) - expect(acc.totalMatches).toBeGreaterThan(0) - expect(acc.totalMatches).toBeLessThanOrEqual(5) - }) - it('stops at maxResults boundary and sets truncated synchronously', () => { const acc = createAccumulator() const re = buildSubmatchRegex('a', {}) diff --git a/src/shared/text-search.ts b/src/shared/file-search/text-search.ts similarity index 96% rename from src/shared/text-search.ts rename to src/shared/file-search/text-search.ts index c097dfda958..3b1990fb125 100644 --- a/src/shared/text-search.ts +++ b/src/shared/file-search/text-search.ts @@ -1,8 +1,11 @@ /** Share pure rg/git-grep construction and parsing across main/SSH relay so result handling cannot drift (docs/design/share-text-search.md). * Callers own process execution and transport-specific path translation. */ -import { parseRipgrepMatchJson, type RipgrepMatchMessage } from './ripgrep-dense-match-json' +import { + parseRipgrepMatchJson, + type RipgrepMatchMessage +} from '../ripgrep/ripgrep-dense-match-json' import { normalizeSearchResult } from './search-match-count' -import { escapeRegex } from './string-utils' +import { escapeRegex } from '../string-utils' import type { SearchFileResult, SearchOptions, SearchResult } from './code-search-types' import { pushSearchMatch } from './text-search-match-accumulator' import { splitSearchGlobPatterns, toGitGlobPathspecs } from './text-search-glob-patterns' @@ -12,10 +15,8 @@ import { relativeToSearchRoot, resolveSearchResultPath } from './text-search-paths' -import { ripgrepMatchRanges } from './ripgrep-match-offsets' -import { decodeRipgrepLine } from './ripgrep-line-decoding' - -export { MAX_LINE_CONTENT_LENGTH } from './text-search-match-accumulator' +import { ripgrepMatchRanges } from '../ripgrep/ripgrep-match-offsets' +import { decodeRipgrepLine } from '../ripgrep/ripgrep-line-decoding' export type SearchAccumulator = { fileMap: Map diff --git a/src/shared/filesystem-entry-types.ts b/src/shared/file-watch/filesystem-change-event.ts similarity index 65% rename from src/shared/filesystem-entry-types.ts rename to src/shared/file-watch/filesystem-change-event.ts index c1a470f04ab..a6970ffc8a5 100644 --- a/src/shared/filesystem-entry-types.ts +++ b/src/shared/file-watch/filesystem-change-event.ts @@ -1,20 +1,3 @@ -export type FilesystemPathFlavor = 'posix' | 'win32' - -export type DirEntry = { - name: string - isDirectory: boolean - isSymlink: boolean -} - -export type FileDocument = { - filePath: string - relativePath: string - basename: string - name: string -} - -export type MarkdownDocument = FileDocument - export type FsChangeEvent = { kind: 'create' | 'update' | 'delete' | 'rename' | 'overflow' absolutePath: string diff --git a/src/shared/filesystem-watch-batch-window.ts b/src/shared/file-watch/filesystem-watch-batch-window.ts similarity index 100% rename from src/shared/filesystem-watch-batch-window.ts rename to src/shared/file-watch/filesystem-watch-batch-window.ts diff --git a/src/shared/filesystem-watch-event-buffer.ts b/src/shared/file-watch/filesystem-watch-event-buffer.ts similarity index 94% rename from src/shared/filesystem-watch-event-buffer.ts rename to src/shared/file-watch/filesystem-watch-event-buffer.ts index e0643864c83..171167f22cc 100644 --- a/src/shared/filesystem-watch-event-buffer.ts +++ b/src/shared/file-watch/filesystem-watch-event-buffer.ts @@ -1,4 +1,4 @@ -import type { FsChangeEvent } from './filesystem-entry-types' +import type { FsChangeEvent } from './filesystem-change-event' export const MAX_BUFFERED_FILE_WATCH_EVENTS = 5_000 diff --git a/src/shared/runtime-file-watch-limits.ts b/src/shared/file-watch/runtime-file-watch-limits.ts similarity index 100% rename from src/shared/runtime-file-watch-limits.ts rename to src/shared/file-watch/runtime-file-watch-limits.ts diff --git a/src/shared/disk-baseline-signature.ts b/src/shared/file-write/disk-baseline-signature.ts similarity index 100% rename from src/shared/disk-baseline-signature.ts rename to src/shared/file-write/disk-baseline-signature.ts diff --git a/src/shared/file-bytes-write.ts b/src/shared/file-write/file-bytes-write.ts similarity index 100% rename from src/shared/file-bytes-write.ts rename to src/shared/file-write/file-bytes-write.ts diff --git a/src/shared/file-mutation-ownership.ts b/src/shared/file-write/file-mutation-ownership.ts similarity index 78% rename from src/shared/file-mutation-ownership.ts rename to src/shared/file-write/file-mutation-ownership.ts index aec135e5a13..8ce613306ed 100644 --- a/src/shared/file-mutation-ownership.ts +++ b/src/shared/file-write/file-mutation-ownership.ts @@ -1,8 +1,8 @@ import { FILE_MUTATION_OWNERSHIP_RUNTIME_CAPABILITY, FILE_MUTATION_OWNERSHIP_UPDATE_REQUIRED_MESSAGE -} from './protocol-version' -import type { RuntimeStatus } from './runtime-types' +} from '../file-access/files-runtime-capabilities' +import type { RuntimeStatus } from '../runtime-types' export function assertFileMutationOwnershipCapability( status: Pick diff --git a/src/shared/file-write-disk-precondition.test.ts b/src/shared/file-write/file-write-disk-precondition.test.ts similarity index 100% rename from src/shared/file-write-disk-precondition.test.ts rename to src/shared/file-write/file-write-disk-precondition.test.ts diff --git a/src/shared/file-write-disk-precondition.ts b/src/shared/file-write/file-write-disk-precondition.ts similarity index 99% rename from src/shared/file-write-disk-precondition.ts rename to src/shared/file-write/file-write-disk-precondition.ts index 1956ff00e55..c435fcd6829 100644 --- a/src/shared/file-write-disk-precondition.ts +++ b/src/shared/file-write/file-write-disk-precondition.ts @@ -1,5 +1,5 @@ import { getDiskBaselineSignature, getWrittenContentDiskSignature } from './disk-baseline-signature' -import { ERRNO_CODE_PATTERN } from './errno-code' +import { ERRNO_CODE_PATTERN } from '../errno-code' // Why: the host serves `files.writeIfUnchanged`; without it a client compares from its side first. export const FILE_WRITE_DISK_PRECONDITION_RUNTIME_CAPABILITY = diff --git a/src/shared/filesystem-rename-collision.ts b/src/shared/file-write/filesystem-rename-collision.ts similarity index 100% rename from src/shared/filesystem-rename-collision.ts rename to src/shared/file-write/filesystem-rename-collision.ts diff --git a/src/shared/staged-file-save.ts b/src/shared/file-write/staged-file-save.ts similarity index 100% rename from src/shared/staged-file-save.ts rename to src/shared/file-write/staged-file-save.ts diff --git a/src/shared/filesystem-watch-event-buffer.test.ts b/src/shared/filesystem-watch-event-buffer.test.ts deleted file mode 100644 index f0a58d95575..00000000000 --- a/src/shared/filesystem-watch-event-buffer.test.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { FsChangeEvent } from './filesystem-entry-types' -import { FileWatchEventBuffer } from './filesystem-watch-event-buffer' - -describe('FileWatchEventBuffer', () => { - it('retains an explicit overflow until consumed without retaining later paths', () => { - const buffer = new FileWatchEventBuffer() - const overflow: FsChangeEvent = { kind: 'overflow', absolutePath: '/repo' } - buffer.push([{ kind: 'delete', absolutePath: '/repo/deleted.ts' }]) - buffer.push([overflow]) - buffer.push([{ kind: 'update', absolutePath: '/repo/later.ts' }]) - expect(buffer.size).toBe(1) - expect(buffer.take()).toEqual([overflow]) - }) - - it('clears events and overflow debt on owner disposal', () => { - const buffer = new FileWatchEventBuffer() - buffer.push([{ kind: 'overflow', absolutePath: '/repo' }]) - buffer.clear() - expect(buffer.size).toBe(0) - buffer.push([{ kind: 'create', absolutePath: '/new-repo/new.ts' }]) - expect(buffer.take()).toEqual([{ kind: 'create', absolutePath: '/new-repo/new.ts' }]) - }) -}) diff --git a/src/shared/git/compatibility/git-binary-compatibility.test.ts b/src/shared/git/compatibility/git-binary-compatibility.test.ts index 029de7915f5..89c04a174ad 100644 --- a/src/shared/git/compatibility/git-binary-compatibility.test.ts +++ b/src/shared/git/compatibility/git-binary-compatibility.test.ts @@ -1,31 +1,24 @@ -import { mkdir, mkdtemp, realpath, rm, writeFile } from 'node:fs/promises' +import { mkdtemp, realpath, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' -import * as gitRunner from '../../../main/git/command-runner/git-exec-file' -import { getRemoteFileUrl } from '../../../main/git/repo' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' + import { refreshBranchCleanupTargetRefs } from '../branches/git-branch-cleanup-fetch' -import { buildGitGrepArgs } from '../../text-search' -import { parseGitRemoteFetchUrls } from '../remotes/git-remote-url-index' -import { GIT_HISTORY_COMMIT_FORMAT, parseGitHistoryLog } from '../history/git-history-log-parser' + import { GitBinaryTestFixture } from './git-binary.test-fixture' -import { registerGitLocalBaseBranchBinaryCompatibilityCase } from './git-local-base-branch-binary-compatibility.test-cases' + import { registerGitResolutionBinaryCompatibilityCases } from './git-resolution-binary-compatibility.test-cases' -import { registerGitWorktreeBinaryCompatibilityCases } from '../worktrees/git-worktree-binary-compatibility.test-cases' const image = process.env.ORCA_GIT_COMPAT_IMAGE const binary = process.env.ORCA_GIT_COMPAT_BINARY const expectedVersion = process.env.ORCA_GIT_COMPAT_VERSION const describeBinaryCompatibility = image || binary ? describe : describe.skip -const PAIRS_REFS_TEST = - 'pairs published, tracked and default refs with configured repositories, on the selected Git binary' type GitResult = { stdout: string; stderr: string } describeBinaryCompatibility('real Git binary compatibility', () => { let repoPath = '' let fixture: GitBinaryTestFixture - let version = { major: 0, minor: 0 } async function runGit( args: string[], @@ -35,10 +28,6 @@ describeBinaryCompatibility('real Git binary compatibility', () => { return fixture.exec(args, fixture.executionRoot, env, stdin) } - function supports(major: number, minor: number): boolean { - return version.major > major || (version.major === major && version.minor >= minor) - } - beforeAll(async () => { repoPath = await realpath(await mkdtemp(join(tmpdir(), 'orca-git-binary-compat-'))) fixture = new GitBinaryTestFixture(repoPath, '/repo') @@ -47,7 +36,6 @@ describeBinaryCompatibility('real Git binary compatibility', () => { expect(versionOutput.stdout).toContain(`git version ${expectedVersion}`) const match = versionOutput.stdout.match(/git version (\d+)\.(\d+)/) expect(match).not.toBeNull() - version = { major: Number(match![1]), minor: Number(match![2]) } await runGit(['init', '-q']) await runGit(['config', 'user.email', 'compatibility@example.invalid']) @@ -67,186 +55,6 @@ describeBinaryCompatibility('real Git binary compatibility', () => { } }) - // Each Git call is a docker exec: image runs take 22-25 s of a 30 s default, so loaded runners tripped it. - it(PAIRS_REFS_TEST, { timeout: image ? 90_000 : undefined }, async () => { - const root = join(repoPath, 'copy-url') - await mkdir(root) - const cwd = image ? '/repo/copy-url' : root - const git = (...args: string[]) => runGit(['-C', cwd, ...args]) - let overflow = false - const exec = vi - .spyOn(gitRunner, 'gitExecFileAsync') - .mockImplementation(async (args, options) => { - const result = await git(...args) - if (args[0] === 'for-each-ref' && !args.some((arg) => arg.startsWith('--contains='))) { - expect(Buffer.byteLength(result.stdout)).toBeLessThan(1024) - } - if (Buffer.byteLength(result.stdout) > (options?.maxBuffer ?? Infinity)) { - overflow = true - throw new Error('stdout exceeded maxBuffer') - } - return result - }) - try { - const url = (ref: string | null, remote = 'origin', path = root) => - expect(getRemoteFileUrl(path, 'a b.ts', 10, 20)).resolves.toBe( - ref === null - ? null - : `https://github.com/org/${remote}/blob/${encodeURIComponent(ref)}/a%20b.ts#L10-L20` - ) - await url(null) // Non-Git folder. - await git('init', '-q') - await git('symbolic-ref', 'HEAD', 'refs/heads/main') - await git('config', 'user.name', 'Test') - await git('config', 'user.email', 'test@example.invalid') - await git('config', 'core.hooksPath', join(root, 'no-hooks')) - await git('remote', 'add', 'origin', 'https://github.com/org/origin.git') - await url(null) // Unborn. - await git('-c', 'commit.gpgSign=false', 'commit', '--allow-empty', '-qm', 'base') - const base = (await git('rev-parse', 'HEAD')).stdout.trim() - await git('update-ref', 'refs/remotes/origin/main', base) - await git('checkout', '-qb', 'feature/local') - await git('-c', 'commit.gpgSign=false', 'commit', '--allow-empty', '-qm', 'feature') - const head = (await git('rev-parse', 'HEAD')).stdout.trim() - await url('main') - const forkFetchConfig = 'remote.team/fork.x.fetch' - const publicationRef = 'refs/remotes/origin/published' - await git('remote', 'add', 'team/fork.x', 'https://github.com/org/team-fork.git') - for (const [mapping, destination] of [ - ['+refs/heads/review-*:refs/cache/published-*', 'refs/cache/published-feature'], - ['+refs/heads/*:refs/c*end', 'refs/cache/team/feature-end'] - ]) { - await git('config', forkFetchConfig, mapping) - await git('update-ref', destination, head) - await url(head, 'team-fork') - await git('update-ref', '-d', destination) - } - await git('config', forkFetchConfig, '+refs/heads/review/*:refs/hosting-cache/*') - await git('update-ref', 'refs/hosting-cache/topic', base) - await git('config', 'branch.feature/local.remote', 'team/fork.x') - await git('config', 'branch.feature/local.merge', 'refs/heads/review/topic') - await url('review/topic', 'team-fork') - const tree = (await git('rev-parse', 'HEAD^{tree}')).stdout.trim() - const descendant = (await git('commit-tree', tree, '-p', head, '-m', 'later')).stdout.trim() - for (const [destination, tip, remote] of [ - [publicationRef, head, 'origin'], // Publication elsewhere beats an ahead upstream. - ['refs/hosting-cache/topic', head, 'team-fork'], // Upstream wins ties. - ['refs/hosting-cache/topic', descendant, 'team-fork'] // Contains an ancestor. - ]) { - await git('update-ref', destination, tip) - await url(head, remote) - } - await git('remote', 'remove', 'origin') - await git('checkout', '--detach', '-q') - await url(head, 'team-fork') // Detached, no origin, custom destination. - await git('update-ref', 'refs/hosting-cache/topic', base) - await git('symbolic-ref', 'refs/remotes/team/fork.x/HEAD', 'refs/hosting-cache/topic') - await url('review/topic', 'team-fork') // Mapped named default. - await git('remote', 'add', 'origin', 'https://github.com/org/origin.git') - await git('config', 'remote.origin.fetch', '+refs/heads/review/*:refs/remotes/origin/*') - await git('update-ref', 'refs/remotes/origin/main', base) - await git('symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/main') - await url('review/main') // Mapped origin default, never destination suffix. - await git('config', 'remote.origin.fetch', '+refs/heads/*:refs/origin-cache/*') - await git('config', forkFetchConfig, `+refs/heads/published:${publicationRef}`) - await git('update-ref', publicationRef, head) - await url(head, 'team-fork') // Origin-looking destination belongs to fork. - await git('remote', 'add', 'unsupported', '/unhosted.git') - await git('config', 'remote.unsupported.fetch', `+refs/heads/other:${publicationRef}`) - await url(null) // Unsupported owner still makes attribution ambiguous. - await git('remote', 'remove', 'unsupported') - await git('config', '--add', forkFetchConfig, `+refs/heads/other:${publicationRef}`) - await url(null) // Ambiguity inside one remote cannot disappear. - await git('config', '--unset-all', forkFetchConfig) - await git('config', forkFetchConfig, '+refs/heads/review/*:refs/hosting-cache/*') - await git('checkout', '-q', 'feature/local') - await git('update-ref', '-d', 'refs/hosting-cache/topic') - await git('update-ref', 'refs/hosting-cache/topic/descendant', base) - await url(null) // Descendants prove neither upstream nor dangling default target exists. - await git('update-ref', '-d', 'refs/hosting-cache/topic/descendant') - await git('config', 'branch.feature/local.remote', '.') - await git('config', 'branch.feature/local.merge', 'refs/heads/main') - await url(null) - if (supports(2, 29)) { - await git('update-ref', 'refs/hosting-cache/topic', head) - await git('config', '--add', forkFetchConfig, '^refs/heads/review/topic') - await url(null) - } - await git('remote', 'remove', 'team/fork.x') - await git('remote', 'set-url', 'origin', '/unhosted.git') - await url(null) // No supported URL. - await git('remote', 'set-url', 'origin', 'https://github.com/org/origin.git') - await git('config', 'remote.origin.fetch', '+refs/heads/*:refs/remotes/origin/*') - await git('update-ref', 'refs/remotes/origin/main', base) - await git('update-ref', '-d', publicationRef) - for (const tip of [base, head, base]) { - await runGit( - ['-C', cwd, 'update-ref', '--stdin'], - undefined, - Array.from( - { length: 4500 }, - (_, i) => `update refs/remotes/origin/${'x'.repeat(220)}${i} ${tip}\n` - ).join('') - ) - overflow = false - await url('main') - expect(overflow).toBe(tip === head) - } - const counts: number[] = [] - for (const n of [10, 100]) { - for (let i = counts.length ? 10 : 0; i < n; i++) { - await git('remote', 'add', `r${i}`, `https://github.com/org/r${i}.git`) - await git('update-ref', `refs/remotes/r${i}/main`, head) - } - await git('symbolic-ref', 'refs/remotes/r0/HEAD', 'refs/remotes/r0/main') - exec.mockClear() - await url(head, 'r0') - counts.push(exec.mock.calls.length) - } - expect(counts).toEqual([7, 7]) - await mkdir(join(root, 'linked')) - await git('worktree', 'add', '--detach', join(cwd, 'linked'), head) - exec.mockImplementation((args) => runGit(['-C', join(cwd, 'linked'), ...args])) - await url(head, 'r0', join(root, 'linked')) - } finally { - exec.mockRestore() - } - }) - - registerGitWorktreeBinaryCompatibilityCases(runGit) - - // remote -v must match get-url’s insteadOf-expanded first fetch URL across supported Git versions; raw config is insufficient. - it('reports the same fetch URL from remote -v as from remote get-url', async () => { - await runGit(['config', 'url.git@example.invalid:.insteadOf', 'https://example.invalid/']) - await runGit(['remote', 'add', 'compat-single', 'https://example.invalid/a/repo.git']) - await runGit(['remote', 'add', 'compat-multi', 'https://example.invalid/b/repo.git']) - await runGit([ - 'config', - '--add', - 'remote.compat-multi.url', - 'https://example.invalid/b2/repo.git' - ]) - await runGit([ - 'config', - 'remote.compat-multi.pushurl', - 'https://push.example.invalid/b/repo.git' - ]) - try { - const fetchUrls = parseGitRemoteFetchUrls((await runGit(['remote', '-v'])).stdout) - for (const name of ['compat-single', 'compat-multi']) { - const getUrl = (await runGit(['remote', 'get-url', name])).stdout.trim() - expect(fetchUrls.get(name)).toBe(getUrl) - } - expect(fetchUrls.get('compat-single')).toBe('git@example.invalid:a/repo.git') - // A `pushurl` must not displace the fetch URL the scan compares against. - expect(fetchUrls.get('compat-multi')).toBe('git@example.invalid:b/repo.git') - } finally { - await runGit(['remote', 'remove', 'compat-single']) - await runGit(['remote', 'remove', 'compat-multi']) - await runGit(['config', '--unset-all', 'url.git@example.invalid:.insteadOf']) - } - }) - it('refreshes a cleanup base with maintenance disabled and an explicit refspec', async () => { const branch = 'compat-cleanup-source' const remote = 'compat-cleanup' @@ -266,63 +74,5 @@ describeBinaryCompatibility('real Git binary compatibility', () => { } }) - // Unsupported --write-tree may leave crash debris that Git <2.35 cannot prune; create scratch stores only after support is known. - - // Git 2.25–2.49 echoes --end-of-options with --symbolic-full-name but consumes it with --verify; git-history skips the echoed line. - - // Pinned SSH branch diffs require show : to use that commit and reject missing paths; failure represents additions/deletions. - - // Older Git echoes %(decorate:...) with exit 0; %D in the same record must recover badges (#15507). - it('reads commit decorations on both sides of the %(decorate:...) boundary', async () => { - await writeFile(join(repoPath, 'decorated.txt'), 'decorated\n') - await runGit(['add', 'decorated.txt']) - await runGit(['commit', '-qm', 'decorated commit']) - await runGit(['tag', 'compat-decorated']) - const head = (await runGit(['rev-parse', 'HEAD'])).stdout.trim() - - const log = await runGit([ - 'log', - `--format=${GIT_HISTORY_COMMIT_FORMAT}`, - '-z', - '--decorate=full', - '-n1', - head - ]) - - expect(log.stdout.includes('%(decorate')).toBe(!supports(2, 43)) - - const [item] = parseGitHistoryLog(log.stdout) - expect(item?.id).toBe(head) - expect(item?.subject).toBe('decorated commit') - expect(item?.references?.map((ref) => ref.id)).toContain('refs/tags/compat-decorated') - }) - - it('excludes and includes a directory subtree through the generated pathspecs', async () => { - await mkdir(join(repoPath, 'vendored'), { recursive: true }) - await writeFile(join(repoPath, 'vendored', 'inner.txt'), 'pathspecneedle\n') - await writeFile(join(repoPath, 'kept.txt'), 'pathspecneedle\n') - await runGit(['add', '-A']) - await runGit(['commit', '-qm', 'pathspec fixture']) - - const listFiles = async (opts: Parameters[1]): Promise => { - const args = buildGitGrepArgs('pathspecneedle', opts).map((arg) => - arg === '-n' ? '-l' : arg - ) - const { stdout } = await runGit(args) - return stdout.split(/[\0\n]/).filter(Boolean) - } - - const excluded = await listFiles({ excludePattern: 'vendored' }) - expect(excluded).toContain('kept.txt') - expect(excluded.some((file) => file.startsWith('vendored/'))).toBe(false) - - const included = await listFiles({ includePattern: 'vendored' }) - expect(included).toEqual(['vendored/inner.txt']) - }) - - registerGitLocalBaseBranchBinaryCompatibilityCase(runGit, () => repoPath, Boolean(image)) - - registerGitResolutionBinaryCompatibilityCases(runGit, (name) => - image ? `/repo/${name}.git` : join(repoPath, `${name}.git`) - ) + registerGitResolutionBinaryCompatibilityCases(runGit) }) diff --git a/src/shared/git/compatibility/git-local-base-branch-binary-compatibility.test-cases.ts b/src/shared/git/compatibility/git-local-base-branch-binary-compatibility.test-cases.ts deleted file mode 100644 index f951d3fdcbf..00000000000 --- a/src/shared/git/compatibility/git-local-base-branch-binary-compatibility.test-cases.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { mkdir, readFile, rm, writeFile } from 'node:fs/promises' -import { dirname, join } from 'node:path' -import { expect, it } from 'vitest' -import { parseWorktreeList } from '../worktrees/git-worktree-porcelain-parser' -import { fastForwardLocalBaseBranch } from '../../worktree/local-base-branch-fast-forward' - -export function registerGitLocalBaseBranchBinaryCompatibilityCase( - runGit: (args: string[]) => Promise<{ stdout: string; stderr: string }>, - getRepoPath: () => string, - usesContainer: boolean -): void { - // Pin baseline parsing of owner fast-forward flags/config; user branch mergeOptions such as -s ours must not override them. - it('fast-forwards a checked-out base branch with the exact owner arguments', async () => { - const repoPath = getRepoPath() - const worktree = 'compat-ff-wt' - const branch = 'compat-ff-main' - const marker = join(repoPath, worktree, 'compat-ff-hook-ran') - const hookPath = join(repoPath, '.git', 'hooks', 'post-merge') - await runGit(['worktree', 'add', '-q', '-b', branch, worktree]) - const localOid = (await runGit(['-C', worktree, 'rev-parse', 'HEAD'])).stdout.trim() - await writeFile(join(repoPath, worktree, 'compat-ff-added.txt'), 'upstream\n') - await runGit(['-C', worktree, 'add', 'compat-ff-added.txt']) - await runGit(['-C', worktree, 'commit', '-qm', 'upstream']) - const remoteOid = (await runGit(['-C', worktree, 'rev-parse', 'HEAD'])).stdout.trim() - await runGit(['update-ref', `refs/remotes/origin/${branch}`, remoteOid]) - await runGit(['-C', worktree, 'reset', '-q', '--hard', localOid]) - await runGit(['config', `branch.${branch}.mergeOptions`, '-s ours']) - // Why: an uninstalled source-built Git (the CI baseline) has no templates, so no hooks dir. - await mkdir(dirname(hookPath), { recursive: true }) - await writeFile(hookPath, '#!/bin/sh\necho ran > compat-ff-hook-ran\n', { mode: 0o755 }) - const merges: string[][] = [] - // Why `-C`: in the Docker lane, paths Git reports are container paths, not host ones. - const git = { - exec: (args: string[], cwd: string) => { - if (args.includes('merge')) { - merges.push(args) - } - return runGit(['-C', cwd, ...args]) - }, - listWorktrees: async (path: string) => - parseWorktreeList((await runGit(['-C', path, 'worktree', 'list', '--porcelain'])).stdout) - } - - try { - const outcome = await fastForwardLocalBaseBranch(git, { - repoPath: usesContainer ? '/repo' : repoPath, - fullRef: `refs/heads/${branch}`, - remoteTrackingRef: `refs/remotes/origin/${branch}` - }) - - expect(outcome).toMatchObject({ status: 'updated' }) - expect(merges).toHaveLength(1) - await expect( - runGit(['rev-list', '--parents', '-1', `refs/heads/${branch}`]) - ).resolves.toMatchObject({ stdout: `${remoteOid} ${localOid}\n` }) - await expect( - readFile(join(repoPath, worktree, 'compat-ff-added.txt'), 'utf-8') - ).resolves.toBe('upstream\n') - await expect(readFile(marker, 'utf-8')).rejects.toMatchObject({ code: 'ENOENT' }) - - // Control: the hook and the branch setting are both live for a plain fast-forward. - await runGit(['-C', worktree, 'reset', '-q', '--hard', localOid]) - await runGit(['-C', worktree, 'merge', '--ff-only', '-q', remoteOid]) - await expect(readFile(marker, 'utf-8')).resolves.toBe('ran\n') - await expect(runGit(['rev-parse', `refs/heads/${branch}`])).resolves.not.toMatchObject({ - stdout: `${remoteOid}\n` - }) - } finally { - await rm(hookPath, { force: true }) - await runGit(['config', '--unset', `branch.${branch}.mergeOptions`]) - await runGit(['worktree', 'remove', '--force', worktree]) - } - }) -} diff --git a/src/shared/git/compatibility/git-resolution-binary-compatibility.test-cases.ts b/src/shared/git/compatibility/git-resolution-binary-compatibility.test-cases.ts index 3892b1c39ea..537cb534b93 100644 --- a/src/shared/git/compatibility/git-resolution-binary-compatibility.test-cases.ts +++ b/src/shared/git/compatibility/git-resolution-binary-compatibility.test-cases.ts @@ -1,59 +1,13 @@ import { expect, it } from 'vitest' -import { resolveConfiguredGitPushTarget } from '../remotes/git-push-target-resolution' + import { resolveDefaultBaseRefViaExec, resolveRemoteHeadBranchViaExec } from '../refs/git-default-base-ref' export function registerGitResolutionBinaryCompatibilityCases( - runGit: (args: string[]) => Promise<{ stdout: string; stderr: string }>, - resolveRemotePath: (name: string) => string + runGit: (args: string[]) => Promise<{ stdout: string; stderr: string }> ): void { - it('resolves push config from one snapshot and refreshes after a config write', async () => { - const branch = (await runGit(['symbolic-ref', '--quiet', '--short', 'HEAD'])).stdout.trim() - await runGit(['config', `branch.${branch}.remote`, 'fork']) - await runGit(['config', `branch.${branch}.merge`, `refs/heads/${branch}`]) - const calls: string[][] = [] - const exec = async (args: string[]) => { - calls.push(args) - return runGit(args) - } - - await expect(resolveConfiguredGitPushTarget(exec)).resolves.toEqual({ - remote: 'fork', - refspec: `HEAD:${branch}` - }) - await runGit(['config', `branch.${branch}.pushRemote`, 'other-fork']) - await expect(resolveConfiguredGitPushTarget(exec)).resolves.toEqual({ - remote: 'other-fork', - refspec: `HEAD:${branch}` - }) - expect(calls.filter((args) => args[0] === 'config')).toEqual([ - ['config', '--list', '-z'], - ['config', '--list', '-z'] - ]) - for (const name of ['fork', 'other-fork']) { - const remotePath = resolveRemotePath(name) - await runGit(['init', '--bare', '-q', remotePath]) - await runGit(['remote', 'add', name, remotePath]) - } - await runGit(['config', '--unset', `branch.${branch}.merge`]) - await runGit(['config', 'remote.pushDefault', 'fork']) - const firstPush = await resolveConfiguredGitPushTarget(exec) - expect(firstPush).toEqual({ remote: 'other-fork', refspec: 'HEAD' }) - if (!firstPush) { - throw new Error('missing first-publish target') - } - await runGit(['push', '--set-upstream', firstPush.remote, firstPush.refspec]) - const head = (await runGit(['rev-parse', 'HEAD'])).stdout - expect( - (await runGit(['--git-dir=other-fork.git', 'rev-parse', `refs/heads/${branch}`])).stdout - ).toBe(head) - await expect( - runGit(['--git-dir=fork.git', 'show-ref', '--verify', `refs/heads/${branch}`]) - ).rejects.toThrow() - }) - it('resolves default bases from exact refs with symbolic chains and dangling targets', async () => { const head = (await runGit(['rev-parse', 'HEAD'])).stdout.trim() await runGit(['update-ref', '-d', 'refs/remotes/origin/main']) diff --git a/src/shared/git/status/git-status-sort.ts b/src/shared/git/status/git-status-sort.ts index a3d88e5f5a2..462c3d25fba 100644 --- a/src/shared/git/status/git-status-sort.ts +++ b/src/shared/git/status/git-status-sort.ts @@ -1,5 +1,5 @@ import type { GitStatusEntry } from './git-status-types' -import { compareFileNames } from '../../file-name-sort' +import { compareFileNames } from '../../file-listing/file-name-sort' export function compareGitStatusEntries(a: GitStatusEntry, b: GitStatusEntry): number { // Use compareFileNames to break numeric ties (2/02) consistently with File Explorer. diff --git a/src/shared/git/status/git-uncommitted-line-stats.test.ts b/src/shared/git/status/git-uncommitted-line-stats.test.ts index 826cdf39fef..7c37b107c68 100644 --- a/src/shared/git/status/git-uncommitted-line-stats.test.ts +++ b/src/shared/git/status/git-uncommitted-line-stats.test.ts @@ -7,7 +7,7 @@ const { lstatMock, readFileMock } = vi.hoisted(() => ({ vi.mock('fs/promises', () => ({ lstat: lstatMock })) -vi.mock('../../node-bounded-file-reader', () => ({ +vi.mock('../../file-content/node-bounded-file-reader', () => ({ readNodeFileWithinLimit: async (path: string) => ({ buffer: await readFileMock(path), stats: mockFileStat(0) diff --git a/src/shared/git/status/git-uncommitted-line-stats.ts b/src/shared/git/status/git-uncommitted-line-stats.ts index 932584af9ee..283bc3e4447 100644 --- a/src/shared/git/status/git-uncommitted-line-stats.ts +++ b/src/shared/git/status/git-uncommitted-line-stats.ts @@ -1,10 +1,10 @@ import { lstat } from 'node:fs/promises' import * as path from 'node:path' -import { isBinaryBuffer } from '../../binary-buffer' +import { isBinaryBuffer } from '../../file-preview/binary-buffer' import { decodeGitCQuotedPath } from '../paths/git-cquoted-path' import { DEFAULT_GIT_STATUS_LIMIT } from './git-status-limit' import { iterateNulDelimitedFields } from '../../nul-delimited-fields' -import { readNodeFileWithinLimit } from '../../node-bounded-file-reader' +import { readNodeFileWithinLimit } from '../../file-content/node-bounded-file-reader' export type GitLineStats = { added?: number; removed?: number } diff --git a/src/shared/git/worktrees/git-worktree-binary-compatibility.test-cases.ts b/src/shared/git/worktrees/git-worktree-binary-compatibility.test-cases.ts deleted file mode 100644 index c29a546265f..00000000000 --- a/src/shared/git/worktrees/git-worktree-binary-compatibility.test-cases.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { expect, it } from 'vitest' -import { isBranchCheckedOutInWorktreeError } from '../branches/git-branch-delete-refusal' - -export function registerGitWorktreeBinaryCompatibilityCases( - runGit: (args: string[], env?: NodeJS.ProcessEnv) => Promise<{ stdout: string; stderr: string }> -): void { - // Pin stderr refusal recognition across <=2.40 checked-out-at and >=2.43 used-by-worktree-at wording; removal uses it to prune/retry. - it('refuses to delete a branch another worktree holds, on stderr, in a recognized wording', async () => { - await runGit(['worktree', 'add', '-b', 'compat-held', 'held-wt']) - try { - const refusal = await runGit(['branch', '-d', '--', 'compat-held']).then( - () => null, - (error: unknown) => error - ) - expect(refusal).not.toBeNull() - expect(isBranchCheckedOutInWorktreeError(refusal)).toBe(true) - const streams = refusal as { stdout?: string; stderr?: string } - expect(streams.stderr ?? '').toMatch(/delete branch .*compat-held/i) - expect(streams.stdout ?? '').toBe('') - } finally { - await runGit(['worktree', 'remove', '--force', 'held-wt']) - await runGit(['branch', '-D', 'compat-held']) - } - }) - - // The create card consumes worktree add’s unrequested piped checkout meter; pin its format across supported Git. - - // Retarget drift parsing fails closed on shape changes; commit-tree builds fixtures without leaving refs/worktrees. -} diff --git a/src/shared/image-file-extensions.ts b/src/shared/image-file-extensions.ts deleted file mode 100644 index 8253500e498..00000000000 --- a/src/shared/image-file-extensions.ts +++ /dev/null @@ -1 +0,0 @@ -export { IMAGE_FILE_MIME_TYPES, IMAGE_FILE_EXTENSIONS } from './media-file-extensions' diff --git a/src/shared/image-path-paste.ts b/src/shared/image-path-paste.ts index 062f8e34361..7911a420f38 100644 --- a/src/shared/image-path-paste.ts +++ b/src/shared/image-path-paste.ts @@ -1,5 +1,5 @@ import { isWindowsAbsolutePathLike } from './cross-platform-path' -import { IMAGE_FILE_EXTENSIONS } from './image-file-extensions' +import { IMAGE_FILE_EXTENSIONS } from './file-preview/image-mime-types' import { shellEscapePath } from './shell/launch/shell-path-quoting' import { isWslUncPath } from './wsl-paths' diff --git a/src/shared/json-text-structure-limit.test.ts b/src/shared/json-stream/json-text-structure-limit.test.ts similarity index 78% rename from src/shared/json-text-structure-limit.test.ts rename to src/shared/json-stream/json-text-structure-limit.test.ts index c86764a1613..474fd356a0a 100644 --- a/src/shared/json-text-structure-limit.test.ts +++ b/src/shared/json-stream/json-text-structure-limit.test.ts @@ -38,20 +38,6 @@ describe('JSON text structure admission', () => { ).not.toThrow() }) - it.each([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])('handles a quote preceded by %i backslashes', (count) => { - const content = `"${'\\'.repeat(count)}"[[]]` - const check = () => - assertJsonTextStructureWithinLimits(content, { - structuralTokens: 3, - nestingDepth: 2 - }) - if (count % 2 === 0) { - expect(check).toThrowError(new JsonTextStructureCapacityError('structuralTokens', 3)) - } else { - expect(check).not.toThrow() - } - }) - it('resumes counting after escaped quotes and long string values', () => { const content = JSON.stringify({ value: 'ordinary text [{,}] \\" '.repeat(10_000), next: [] }) expect(() => diff --git a/src/shared/json-text-structure-limit.ts b/src/shared/json-stream/json-text-structure-limit.ts similarity index 100% rename from src/shared/json-text-structure-limit.ts rename to src/shared/json-stream/json-text-structure-limit.ts diff --git a/src/shared/json-token-reader.test.ts b/src/shared/json-stream/json-token-reader.test.ts similarity index 54% rename from src/shared/json-token-reader.test.ts rename to src/shared/json-stream/json-token-reader.test.ts index 793b6782507..4c0e88562ce 100644 --- a/src/shared/json-token-reader.test.ts +++ b/src/shared/json-stream/json-token-reader.test.ts @@ -1,22 +1,6 @@ import { expect, it } from 'vitest' -import { FlexAssembler } from 'stream-json/core/utils/flex-assembler.js' -import { createJsonTokenReader } from './json-token-reader' -it.each([1, 7, 64 * 1024, Infinity])('preserves Unicode at chunk size %s', (size) => { - const value = { '\ufeffkey': `\ufeffstart${'\n'.repeat(64 * 1024)}\ufeff😀end` } - const literal = JSON.stringify(value) - for (const text of [literal, literal.replaceAll('\ufeff', '\\uFEFF')]) { - const assembler = new FlexAssembler() - const reader = createJsonTokenReader((token) => { - assembler.consume(token) - }) - for (let offset = 0; offset < text.length; offset += size) { - reader.write(text.slice(offset, offset + size)) - } - reader.end() - expect(assembler.current).toEqual(value) - } -}) +import { createJsonTokenReader } from './json-token-reader' it.each(['', ' ', '{', '{"a":1,}', '{}{}', '[01]', '\ufeff{}'])( 'rejects malformed JSON %j as a syntax error', @@ -46,25 +30,6 @@ it('preserves consumer errors and completes numbers at EOF synchronously', () => expect(() => throwing.write('{}')).toThrow(failure) }) -it.each([1, 7, 65536])('selectively packs complete scalars at chunk size %s', (size) => { - const assembler = new FlexAssembler() - let key = '' - const reader = createJsonTokenReader( - (token) => { - if (token.name === 'keyValue') { - key = token.value - } - assembler.consume(token) - }, - size, - () => key !== 'ignored' - ) - const kept = { text: '😀\n\ufeff\\"', number: -1.25e42, flags: [true, false, null, 0] } - reader.write(JSON.stringify({ ignored: 'discard'.repeat(10000), kept })) - reader.end() - expect(assembler.current).toEqual({ ignored: '', kept }) -}) - it('preserves selective scalar consumer errors and a number ending at EOF', () => { const values: string[] = [] const reader = createJsonTokenReader( diff --git a/src/shared/json-token-reader.ts b/src/shared/json-stream/json-token-reader.ts similarity index 100% rename from src/shared/json-token-reader.ts rename to src/shared/json-stream/json-token-reader.ts diff --git a/src/shared/json-stream/node-bounded-json-stringify.test.ts b/src/shared/json-stream/node-bounded-json-stringify.test.ts new file mode 100644 index 00000000000..453679c290d --- /dev/null +++ b/src/shared/json-stream/node-bounded-json-stringify.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from 'vitest' +import { + JsonStringifyByteLimitError, + stringifyJsonWithinByteLimit +} from './node-bounded-json-stringify' + +describe('stringifyJsonWithinByteLimit', () => { + it('rejects a large root string before materializing escaped JSON', () => { + const value = '\n'.repeat(1024 * 1024) + + expect(() => stringifyJsonWithinByteLimit(value, 1024)).toThrow(JsonStringifyByteLimitError) + }) + + it('measures raw JSON values before native serialization materializes them', () => { + const createRawJson = (JSON as { rawJSON?: (value: string) => unknown }).rawJSON + if (!createRawJson) { + return + } + const value = createRawJson(JSON.stringify('x'.repeat(1024))) + + expect(() => stringifyJsonWithinByteLimit(value, 32)).toThrow(JsonStringifyByteLimitError) + }) +}) diff --git a/src/shared/node-bounded-json-stringify.ts b/src/shared/json-stream/node-bounded-json-stringify.ts similarity index 100% rename from src/shared/node-bounded-json-stringify.ts rename to src/shared/json-stream/node-bounded-json-stringify.ts diff --git a/src/shared/markdown-document-listing-limits.test.ts b/src/shared/markdown-document-listing-limits.test.ts deleted file mode 100644 index d8cbd5719da..00000000000 --- a/src/shared/markdown-document-listing-limits.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { MarkdownDocument } from './filesystem-entry-types' -import { - assertMarkdownDocumentsWithinLimit, - createMarkdownDocumentListingBudget, - MARKDOWN_DOCUMENT_LISTING_ERROR_CODE, - MarkdownDocumentListingCapacityError, - retainMarkdownDocument -} from './markdown-document-listing-limits' - -function document(path: string): MarkdownDocument { - return { - filePath: `/repo/${path}`, - relativePath: path, - basename: path, - name: path - } -} - -describe('Markdown document listing limits', () => { - it('rejects the first document beyond the count limit with a typed error', () => { - const budget = createMarkdownDocumentListingBudget({ maxDocuments: 2 }) - retainMarkdownDocument(budget, document('one.md')) - retainMarkdownDocument(budget, document('two.md')) - - expect(() => retainMarkdownDocument(budget, document('three.md'))).toThrow( - MarkdownDocumentListingCapacityError - ) - expect(() => retainMarkdownDocument(budget, document('three.md'))).toThrow( - expect.objectContaining({ code: MARKDOWN_DOCUMENT_LISTING_ERROR_CODE }) - ) - }) - - it('rejects aggregate metadata overflow', () => { - expect(() => - assertMarkdownDocumentsWithinLimit([document('a'.repeat(100))], { - maxMetadataBytes: 100 - }) - ).toThrow(MarkdownDocumentListingCapacityError) - }) - - it('bounds UTF-8 bytes in both live document paths before retaining metadata', () => { - const budget = createMarkdownDocumentListingBudget({ maxPathBytes: 4 }) - expect(() => retainMarkdownDocument(budget, { ...document('a'), filePath: 'ééé' })).toThrow( - MarkdownDocumentListingCapacityError - ) - expect(() => retainMarkdownDocument(budget, { ...document('ééé'), filePath: 'a' })).toThrow( - MarkdownDocumentListingCapacityError - ) - expect(budget.documents).toBe(0) - expect(budget.metadataBytes).toBe(0) - retainMarkdownDocument(budget, { ...document('éé'), filePath: 'éé' }) - expect(budget.documents).toBe(1) - }) -}) diff --git a/src/shared/media-file-extensions.ts b/src/shared/media-file-extensions.ts deleted file mode 100644 index 94a45fdd96e..00000000000 --- a/src/shared/media-file-extensions.ts +++ /dev/null @@ -1,29 +0,0 @@ -export const IMAGE_FILE_MIME_TYPES: Record = { - '.png': 'image/png', - '.jpg': 'image/jpeg', - '.jpeg': 'image/jpeg', - '.gif': 'image/gif', - '.svg': 'image/svg+xml', - '.webp': 'image/webp', - '.bmp': 'image/bmp', - '.ico': 'image/x-icon' -} - -export const IMAGE_FILE_EXTENSIONS = Object.freeze(Object.keys(IMAGE_FILE_MIME_TYPES)) - -export const MEDIA_FILE_MIME_TYPES: Record = { - '.mp3': 'audio/mpeg', - '.wav': 'audio/wav', - '.m4a': 'audio/mp4', - '.aac': 'audio/aac', - '.ogg': 'audio/ogg', - '.oga': 'audio/ogg', - '.flac': 'audio/flac', - '.opus': 'audio/ogg', - '.mp4': 'video/mp4', - '.m4v': 'video/mp4', - '.mov': 'video/quicktime', - '.webm': 'video/webm' -} - -export const MEDIA_PREVIEW_SCHEME = 'orca-media' diff --git a/src/shared/native-chat-text-attachment-references.ts b/src/shared/native-chat-text-attachment-references.ts index 5297d146200..d1ed7e23bf7 100644 --- a/src/shared/native-chat-text-attachment-references.ts +++ b/src/shared/native-chat-text-attachment-references.ts @@ -1,4 +1,4 @@ -import { hasBinaryFileExtension } from './binary-file-extensions' +import { hasBinaryFileExtension } from './file-preview/binary-file-extensions' import { AGENT_SESSION_ATTACHMENTS_DIR_NAME } from './agent-session/agent-session-attachments' export function isCommittedChatAttachmentCandidate(path: string): boolean { diff --git a/src/shared/native-chat/native-chat-file-context.ts b/src/shared/native-chat/native-chat-file-context.ts new file mode 100644 index 00000000000..59f66baad62 --- /dev/null +++ b/src/shared/native-chat/native-chat-file-context.ts @@ -0,0 +1,4 @@ +export type RuntimeNativeChatFileContext = { + tabId: string + sessionId: string +} diff --git a/src/shared/native-chat/native-chat-file-link-existence.ts b/src/shared/native-chat/native-chat-file-link-existence.ts index 59cbdb37814..d8fd85b01ee 100644 --- a/src/shared/native-chat/native-chat-file-link-existence.ts +++ b/src/shared/native-chat/native-chat-file-link-existence.ts @@ -1,6 +1,6 @@ import type { ParsedTerminalFileLink } from '../terminal/links/terminal-links' import type { FileLinkExists } from './native-chat-file-link-tree' -import { readRecentPathAnswer, writeRecentPathAnswer } from '../recent-path-answers' +import { readRecentPathAnswer, writeRecentPathAnswer } from '../file-links/recent-path-answers' // Why: a host that could not answer is retried a few times, then waits for the next recheck. export const UNVERIFIABLE_RETRY_DELAYS_MS = [2_000, 10_000, 30_000] as const diff --git a/src/shared/native-chat/tools/native-chat-tool-viewed-images.ts b/src/shared/native-chat/tools/native-chat-tool-viewed-images.ts index 35d77e75f1a..4f136e38264 100644 --- a/src/shared/native-chat/tools/native-chat-tool-viewed-images.ts +++ b/src/shared/native-chat/tools/native-chat-tool-viewed-images.ts @@ -1,5 +1,5 @@ import { isRuntimePathAbsolute } from '../../cross-platform-path' -import { isRasterImagePath } from '../../file-preview-kind' +import { isRasterImagePath } from '../../file-preview/file-preview-kind' import { isToolCallBlock, type NativeChatBlock, diff --git a/src/shared/node-bounded-file-reader.test.ts b/src/shared/node-bounded-file-reader.test.ts deleted file mode 100644 index c290983e31a..00000000000 --- a/src/shared/node-bounded-file-reader.test.ts +++ /dev/null @@ -1,115 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { openMock } = vi.hoisted(() => ({ openMock: vi.fn() })) - -vi.mock('node:fs/promises', () => ({ open: openMock })) - -import { NodeFileReadTooLargeError, readNodeFileWithinLimit } from './node-bounded-file-reader' - -type FileHandleOptions = { - content: Buffer - initialSize?: number - readError?: Error - statError?: Error - firstReadOnly?: boolean -} - -function createFileHandle({ - content, - initialSize, - readError, - statError, - firstReadOnly -}: FileHandleOptions) { - const close = vi.fn().mockResolvedValue(undefined) - const read = vi.fn(async (target: Buffer, offset: number, length: number, position: number) => { - if (readError) { - throw readError - } - if (firstReadOnly && position > 0) { - return { bytesRead: 0, buffer: target } - } - const bytesRead = Math.min(length, Math.max(0, content.byteLength - position)) - content.copy(target, offset, position, position + bytesRead) - return { bytesRead, buffer: target } - }) - const stat = statError - ? vi.fn().mockRejectedValue(statError) - : vi.fn().mockResolvedValue({ size: initialSize ?? content.byteLength }) - return { close, read, stat } -} - -beforeEach(() => openMock.mockReset()) - -describe('readNodeFileWithinLimit', () => { - it('rejects an oversized initial size before reading file bytes', async () => { - const handle = createFileHandle({ content: Buffer.alloc(0), initialSize: 65 }) - openMock.mockResolvedValue(handle) - - await expect(readNodeFileWithinLimit('/workspace/oversized.txt', 64)).rejects.toEqual( - new NodeFileReadTooLargeError(65, 64) - ) - expect(handle.read).not.toHaveBeenCalled() - expect(handle.close).toHaveBeenCalledOnce() - }) - - it('includes growth that remains within the read limit', async () => { - const handle = createFileHandle({ content: Buffer.from('grown'), initialSize: 3 }) - openMock.mockResolvedValue(handle) - - const result = await readNodeFileWithinLimit('/workspace/growing.txt', 5) - - expect(result.buffer).toEqual(Buffer.from('grown')) - expect(handle.close).toHaveBeenCalledOnce() - }) - - it('reads proc-style content whose reported file size is zero', async () => { - const handle = createFileHandle({ content: Buffer.from('proc table'), initialSize: 0 }) - openMock.mockResolvedValue(handle) - - const result = await readNodeFileWithinLimit('/proc/net/tcp', 64) - - expect(result.buffer).toEqual(Buffer.from('proc table')) - expect(result.stats.size).toBe(0) - expect(handle.close).toHaveBeenCalledOnce() - }) - - it('reads the full sysctl value when later offsets return EOF', async () => { - const handle = createFileHandle({ - content: Buffer.from('4096\n'), - initialSize: 0, - firstReadOnly: true - }) - openMock.mockResolvedValue(handle) - - const result = await readNodeFileWithinLimit('/proc/sys/kernel/pty/max', 1024) - - expect(result.buffer.toString('utf8')).toBe('4096\n') - }) - - it('rejects growth beyond the limit without allocating the oversized content', async () => { - const handle = createFileHandle({ content: Buffer.from('growth'), initialSize: 3 }) - openMock.mockResolvedValue(handle) - - await expect(readNodeFileWithinLimit('/workspace/growing.txt', 5)).rejects.toEqual( - new NodeFileReadTooLargeError(6, 5) - ) - expect(handle.close).toHaveBeenCalledOnce() - }) - - it.each([ - { label: 'stat', options: { content: Buffer.alloc(0), statError: new Error('stat failed') } }, - { - label: 'read', - options: { content: Buffer.from('data'), readError: new Error('read failed') } - } - ])('closes its descriptor when $label fails', async ({ options }) => { - const handle = createFileHandle(options) - openMock.mockResolvedValue(handle) - - await expect(readNodeFileWithinLimit('/workspace/failing.txt', 64)).rejects.toThrow( - `${options.statError ? 'stat' : 'read'} failed` - ) - expect(handle.close).toHaveBeenCalledOnce() - }) -}) diff --git a/src/shared/node-bounded-json-stringify.test.ts b/src/shared/node-bounded-json-stringify.test.ts deleted file mode 100644 index d2a4154594c..00000000000 --- a/src/shared/node-bounded-json-stringify.test.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - JsonStringifyByteLimitError, - stringifyJsonWithinByteLimit -} from './node-bounded-json-stringify' - -describe('stringifyJsonWithinByteLimit', () => { - it('matches native JSON for nested values, escaping, and omitted fields', () => { - const shared = { label: 'same object' } - const value = { - text: 'quote " slash \\ control\n emoji 🐋 lone \ud800', - nested: [1, undefined, Number.NaN, { omitted: undefined, kept: true }], - repeated: [shared, shared] - } - const native = JSON.stringify(value) - - const result = stringifyJsonWithinByteLimit(value, Buffer.byteLength(native)) - - expect(result.serialized).toBe(native) - expect(result.byteLength).toBe(Buffer.byteLength(native, 'utf8')) - expect(() => stringifyJsonWithinByteLimit(value, result.byteLength - 1)).toThrow( - JsonStringifyByteLimitError - ) - }) - - it('matches native indented JSON and counts whitespace before materializing it', () => { - const value = { nested: [{ quote: '"', unicode: '🐋' }], empty: {} } - const native = JSON.stringify(value, null, 2) - - expect(stringifyJsonWithinByteLimit(value, Buffer.byteLength(native), 2)).toEqual({ - byteLength: Buffer.byteLength(native), - serialized: native - }) - expect(() => stringifyJsonWithinByteLimit(value, Buffer.byteLength(native) - 1, 2)).toThrow( - JsonStringifyByteLimitError - ) - }) - - it('measures values after toJSON without invoking it twice', () => { - let calls = 0 - const value = { - toJSON() { - calls += 1 - return { rendered: 'value' } - } - } - - expect(stringifyJsonWithinByteLimit(value, 100).serialized).toBe('{"rendered":"value"}') - expect(calls).toBe(1) - }) - - it('rejects a large root string before materializing escaped JSON', () => { - const value = '\n'.repeat(1024 * 1024) - - expect(() => stringifyJsonWithinByteLimit(value, 1024)).toThrow(JsonStringifyByteLimitError) - }) - - it('measures raw JSON values before native serialization materializes them', () => { - const createRawJson = (JSON as { rawJSON?: (value: string) => unknown }).rawJSON - if (!createRawJson) { - return - } - const value = createRawJson(JSON.stringify('x'.repeat(1024))) - - expect(() => stringifyJsonWithinByteLimit(value, 32)).toThrow(JsonStringifyByteLimitError) - }) -}) diff --git a/src/shared/opencode-installed-plugin.ts b/src/shared/opencode-installed-plugin.ts index c6f89d7e48b..606fc604885 100644 --- a/src/shared/opencode-installed-plugin.ts +++ b/src/shared/opencode-installed-plugin.ts @@ -1,5 +1,5 @@ import { lstatSync } from 'node:fs' -import { nodeFileContentsEqualSync } from './node-file-content-equality' +import { nodeFileContentsEqualSync } from './file-content/node-file-content-equality' // OpenCode 2 reloads this and subsequent plugins on mtime changes even for identical bytes; skip current writes. // Follow canonical symlinks because OpenCode loads through them. diff --git a/src/shared/protocol-version.ts b/src/shared/protocol-version.ts index 7398a28b817..802f7e75435 100644 --- a/src/shared/protocol-version.ts +++ b/src/shared/protocol-version.ts @@ -16,7 +16,7 @@ import { E2EE_V2_TOKEN_CAPABILITIES_RUNTIME_CAPABILITY } from './remote-runtime/pairing/device-key-capability' import { PAIRING_TICKET_EXCHANGE_RUNTIME_CAPABILITIES } from './remote-runtime/pairing/ticket-exchange-capability' -import { FILES_RUNTIME_CAPABILITIES } from './files-runtime-capabilities' +import { FILES_RUNTIME_CAPABILITIES } from './file-access/files-runtime-capabilities' import { HOST_RUNTIME_CAPABILITIES } from './host-runtime-capabilities' import { MOBILE_RUNTIME_CAPABILITIES } from './mobile-runtime-capabilities' import { ORCAD_RUNTIME_CAPABILITIES } from './orcad-runtime-capabilities' @@ -50,7 +50,7 @@ export const MIN_COMPATIBLE_RUNTIME_SERVER_VERSION = 2 // Why stars: importers keep reading every capability from here while each area owns its module. export * from './browser-runtime-capabilities' -export * from './files-runtime-capabilities' + export * from './host-runtime-capabilities' export * from './mobile-runtime-capabilities' diff --git a/src/shared/quick-open-transport-budget.test.ts b/src/shared/quick-open-transport-budget.test.ts deleted file mode 100644 index 557c7bf2ff4..00000000000 --- a/src/shared/quick-open-transport-budget.test.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { limitQuickOpenFilesBySerializedBytes } from './quick-open-transport-budget' - -describe('Quick Open transport byte budget', () => { - it('returns the largest prefix that fits as a JSON array', () => { - const files = ['src/a.ts', 'data/ignored\nfile.bin', 'src/b.ts'] - const budget = Buffer.byteLength(JSON.stringify(files.slice(0, 2)), 'utf8') - expect(limitQuickOpenFilesBySerializedBytes(files, budget)).toEqual(files.slice(0, 2)) - }) -}) diff --git a/src/shared/quick-open-filter.renderer-safety.test.ts b/src/shared/quick-open/quick-open-filter.renderer-safety.test.ts similarity index 100% rename from src/shared/quick-open-filter.renderer-safety.test.ts rename to src/shared/quick-open/quick-open-filter.renderer-safety.test.ts diff --git a/src/shared/quick-open-filter.test.ts b/src/shared/quick-open/quick-open-filter.test.ts similarity index 100% rename from src/shared/quick-open-filter.test.ts rename to src/shared/quick-open/quick-open-filter.test.ts diff --git a/src/shared/quick-open-filter.ts b/src/shared/quick-open/quick-open-filter.ts similarity index 99% rename from src/shared/quick-open-filter.ts rename to src/shared/quick-open/quick-open-filter.ts index c93f9433c64..b067f719831 100644 --- a/src/shared/quick-open-filter.ts +++ b/src/shared/quick-open/quick-open-filter.ts @@ -1,6 +1,6 @@ /** Pure listing policy shared by main/SSH relay to keep pruning, exclusions and limits aligned; callers own I/O and path translation * (docs/design/share-quick-open-file-listing.md). */ -import { isWindowsAbsolutePathLike, relativePathInsideRoot } from './cross-platform-path' +import { isWindowsAbsolutePathLike, relativePathInsideRoot } from '../cross-platform-path' // Blocklist (not allowlist) keeps novel dotfiles discoverable; entries here are tool-generated // caches/state, never hand-edited. Do NOT add user-authored dotdirs (.config, .ssh, .github) — users open files there. diff --git a/src/shared/quick-open-git-directory-collapse.test.ts b/src/shared/quick-open/quick-open-git-directory-collapse.test.ts similarity index 100% rename from src/shared/quick-open-git-directory-collapse.test.ts rename to src/shared/quick-open/quick-open-git-directory-collapse.test.ts diff --git a/src/shared/quick-open-listing-limits.ts b/src/shared/quick-open/quick-open-listing-limits.ts similarity index 100% rename from src/shared/quick-open-listing-limits.ts rename to src/shared/quick-open/quick-open-listing-limits.ts diff --git a/src/shared/quick-open-listing-path-filter.ts b/src/shared/quick-open/quick-open-listing-path-filter.ts similarity index 100% rename from src/shared/quick-open-listing-path-filter.ts rename to src/shared/quick-open/quick-open-listing-path-filter.ts diff --git a/src/shared/quick-open-path-search.ts b/src/shared/quick-open/quick-open-path-search.ts similarity index 98% rename from src/shared/quick-open-path-search.ts rename to src/shared/quick-open/quick-open-path-search.ts index 5d685621000..4d4bc9296f8 100644 --- a/src/shared/quick-open-path-search.ts +++ b/src/shared/quick-open/quick-open-path-search.ts @@ -2,8 +2,8 @@ import { filenameContainsSeparatorVariant, matchQuickOpenSeparatorAlternatives } from './quick-open-separator-match' -import { isClipboardTextByteLengthOverLimit } from './clipboard-text' -import { compareFileNames } from './file-name-sort' +import { isClipboardTextByteLengthOverLimit } from '../clipboard-text' +import { compareFileNames } from '../file-listing/file-name-sort' export const QUICK_OPEN_RESULT_LIMIT = 50 export const QUICK_OPEN_QUERY_MAX_BYTES = 2 * 1024 diff --git a/src/shared/quick-open-query-target.test.ts b/src/shared/quick-open/quick-open-query-target.test.ts similarity index 100% rename from src/shared/quick-open-query-target.test.ts rename to src/shared/quick-open/quick-open-query-target.test.ts diff --git a/src/shared/quick-open-query-target.ts b/src/shared/quick-open/quick-open-query-target.ts similarity index 94% rename from src/shared/quick-open-query-target.ts rename to src/shared/quick-open/quick-open-query-target.ts index 95658061459..3d7cc92f97c 100644 --- a/src/shared/quick-open-query-target.ts +++ b/src/shared/quick-open/quick-open-query-target.ts @@ -1,4 +1,4 @@ -import { isWindowsAbsolutePathLike } from './cross-platform-path' +import { isWindowsAbsolutePathLike } from '../cross-platform-path' import { isQuickOpenQueryTooLarge } from './quick-open-path-search' export type QuickOpenQueryTarget = { pathQuery: string; line?: number; column?: number } diff --git a/src/shared/quick-open-recent-candidates.test.ts b/src/shared/quick-open/quick-open-recent-candidates.test.ts similarity index 100% rename from src/shared/quick-open-recent-candidates.test.ts rename to src/shared/quick-open/quick-open-recent-candidates.test.ts diff --git a/src/shared/quick-open-recent-candidates.ts b/src/shared/quick-open/quick-open-recent-candidates.ts similarity index 84% rename from src/shared/quick-open-recent-candidates.ts rename to src/shared/quick-open/quick-open-recent-candidates.ts index d27c05cc279..2cd51d9aecb 100644 --- a/src/shared/quick-open-recent-candidates.ts +++ b/src/shared/quick-open/quick-open-recent-candidates.ts @@ -1,5 +1,5 @@ -import { isWindowsAbsolutePathLike } from './cross-platform-path' -import { isClipboardTextByteLengthOverLimit } from './clipboard-text' +import { isWindowsAbsolutePathLike } from '../cross-platform-path' +import { isClipboardTextByteLengthOverLimit } from '../clipboard-text' export const QUICK_OPEN_RECENT_CANDIDATE_LIMIT = 100 const MAX_CANDIDATE_BYTES = 64 * 1024 diff --git a/src/shared/quick-open-ripgrep-output-mode.ts b/src/shared/quick-open/quick-open-ripgrep-output-mode.ts similarity index 100% rename from src/shared/quick-open-ripgrep-output-mode.ts rename to src/shared/quick-open/quick-open-ripgrep-output-mode.ts diff --git a/src/shared/quick-open-separator-match.ts b/src/shared/quick-open/quick-open-separator-match.ts similarity index 100% rename from src/shared/quick-open-separator-match.ts rename to src/shared/quick-open/quick-open-separator-match.ts diff --git a/src/shared/quick-open-subprocess-path-accumulator.test.ts b/src/shared/quick-open/quick-open-subprocess-path-accumulator.test.ts similarity index 50% rename from src/shared/quick-open-subprocess-path-accumulator.test.ts rename to src/shared/quick-open/quick-open-subprocess-path-accumulator.test.ts index 2ade096de30..614450221c4 100644 --- a/src/shared/quick-open-subprocess-path-accumulator.test.ts +++ b/src/shared/quick-open/quick-open-subprocess-path-accumulator.test.ts @@ -1,18 +1,7 @@ -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, it } from 'vitest' import { QuickOpenSubprocessPathAccumulator } from './quick-open-subprocess-path-accumulator' describe('Quick Open subprocess path accumulator', () => { - it('bounds one fragmented subprocess path and recovers after overflow', () => { - const onPath = vi.fn(() => true) - const fields = new QuickOpenSubprocessPathAccumulator(0, 3) - - expect(fields.push(Buffer.from('ab'), onPath)).toBe('continue') - expect(fields.push(Buffer.from('cd'), onPath)).toBe('path-too-large') - expect(fields.push(Buffer.from('ok\0'), onPath)).toBe('continue') - expect(onPath).toHaveBeenCalledTimes(1) - expect(onPath).toHaveBeenCalledWith('ok') - }) - it('stops within a multi-path chunk without visiting later fields', () => { const visited: string[] = [] const fields = new QuickOpenSubprocessPathAccumulator(0, 16) diff --git a/src/shared/quick-open-subprocess-path-accumulator.ts b/src/shared/quick-open/quick-open-subprocess-path-accumulator.ts similarity index 100% rename from src/shared/quick-open-subprocess-path-accumulator.ts rename to src/shared/quick-open/quick-open-subprocess-path-accumulator.ts diff --git a/src/shared/quick-open-transport-budget.ts b/src/shared/quick-open/quick-open-transport-budget.ts similarity index 100% rename from src/shared/quick-open-transport-budget.ts rename to src/shared/quick-open/quick-open-transport-budget.ts diff --git a/src/shared/raster-image-base64-preview.test.ts b/src/shared/raster-image-base64-preview.test.ts deleted file mode 100644 index 0d5130aaf2d..00000000000 --- a/src/shared/raster-image-base64-preview.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { exceedsRasterImagePreviewLimits } from './raster-image-base64-preview' -import type * as RasterImageDimensionsModule from './raster-image-dimensions' -import { RASTER_IMAGE_PREVIEW_HEADER_MAX_BYTES } from './raster-image-preview-limits' - -// Observe decoded bytes handed to dimension reading; output equivalence alone cannot detect wasted full-payload decoding. -const { dimensionReadLengths } = vi.hoisted(() => ({ dimensionReadLengths: [] as number[] })) - -vi.mock('./raster-image-dimensions', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - readRasterImageDimensions: (bytes: Uint8Array) => { - dimensionReadLengths.push(bytes.byteLength) - return actual.readRasterImageDimensions(bytes) - } - } -}) - -function pngBytes(totalBytes: number, width: number, height: number): Buffer { - const bytes = Buffer.alloc(Math.max(totalBytes, 24)) - Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).copy(bytes) - bytes.writeUInt32BE(13, 8) - bytes.write('IHDR', 12, 'ascii') - bytes.writeUInt32BE(width, 16) - bytes.writeUInt32BE(height, 20) - for (let index = 24; index < bytes.length; index += 1) { - bytes[index] = (index * 31 + 7) & 0xff - } - return bytes -} - -/** SOI, `metadataBytes` of APP2 padding (real cameras chain many segments), then SOF0. */ -function jpegBytes( - metadataBytes: number, - width: number, - height: number, - trailingBytes = 4096 -): Buffer { - const parts: Buffer[] = [Buffer.from([0xff, 0xd8])] - for (let written = 0; written < metadataBytes;) { - const size = Math.min(65_533, metadataBytes - written) - const header = Buffer.alloc(4) - header.writeUInt16BE(0xffe2) - header.writeUInt16BE(size + 2, 2) - parts.push(header, Buffer.alloc(size)) - written += size - } - const sof = Buffer.alloc(11) - sof.writeUInt16BE(0xffc0) - sof.writeUInt16BE(8, 2) - sof[4] = 8 - sof.writeUInt16BE(height, 5) - sof.writeUInt16BE(width, 7) - parts.push(sof, Buffer.alloc(trailingBytes)) - return Buffer.concat(parts) -} - -describe('exceedsRasterImagePreviewLimits', () => { - beforeEach(() => { - dimensionReadLengths.length = 0 - }) - - it('widens the probe until a JPEG SOF past its metadata is reachable', () => { - const content = jpegBytes(70_000, 4000, 3000, 3_000_000).toString('base64') - expect(exceedsRasterImagePreviewLimits(content, 'image/jpeg')).toBe(false) - expect(dimensionReadLengths).toEqual([64, 1024, 16_384, 262_144]) - // Far below the ~3 MiB the payload decodes to, and below the 8 MiB fallback cap. - expect(dimensionReadLengths.at(-1)!).toBeLessThan(RASTER_IMAGE_PREVIEW_HEADER_MAX_BYTES) - }) - - it('re-reads the whole payload before suppressing an over-limit image', () => { - const content = pngBytes(70_000, 32_769, 1).toString('base64') - expect(exceedsRasterImagePreviewLimits(content, 'image/png')).toBe(true) - // Before suppression, validate the full payload: later invalid base64 must still mean unmeasurable, not oversized. - expect(dimensionReadLengths).toEqual([64, 70_000]) - }) - - it('keeps rendering an over-limit header whose payload is not valid base64', () => { - const content = `${pngBytes(70_000, 32_769, 1).toString('base64')}!!!` - expect(exceedsRasterImagePreviewLimits(content, 'image/png')).toBe(false) - }) -}) diff --git a/src/shared/raster-image-preview-limits.test.ts b/src/shared/raster-image-preview-limits.test.ts deleted file mode 100644 index 947ca2b9c22..00000000000 --- a/src/shared/raster-image-preview-limits.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - INVALID_RASTER_IMAGE_PREVIEW_ERROR, - MAX_RASTER_IMAGE_PREVIEW_DIMENSION_PX, - RASTER_IMAGE_PREVIEW_TOO_LARGE_ERROR, - assertRasterImagePreviewWithinLimits -} from './raster-image-preview-limits' - -function pngHeader(width: number, height: number): Buffer { - const bytes = Buffer.alloc(24) - Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).copy(bytes) - bytes.writeUInt32BE(13, 8) - bytes.write('IHDR', 12, 'ascii') - bytes.writeUInt32BE(width, 16) - bytes.writeUInt32BE(height, 20) - return bytes -} - -describe('raster image preview limits', () => { - it('rejects oversized edges and total pixel counts before decode', () => { - expect(() => - assertRasterImagePreviewWithinLimits( - pngHeader(MAX_RASTER_IMAGE_PREVIEW_DIMENSION_PX + 1, 1), - 'image/png' - ) - ).toThrow(RASTER_IMAGE_PREVIEW_TOO_LARGE_ERROR) - expect(() => assertRasterImagePreviewWithinLimits(pngHeader(8192, 8192), 'image/png')).toThrow( - RASTER_IMAGE_PREVIEW_TOO_LARGE_ERROR - ) - }) - - it('rejects invalid known raster bytes but leaves SVG and PDF unchanged', () => { - expect(() => assertRasterImagePreviewWithinLimits(new Uint8Array([1]), 'image/gif')).toThrow( - INVALID_RASTER_IMAGE_PREVIEW_ERROR - ) - expect( - assertRasterImagePreviewWithinLimits(new Uint8Array([1]), 'image/svg+xml') - ).toBeUndefined() - expect( - assertRasterImagePreviewWithinLimits(new Uint8Array([1]), 'application/pdf') - ).toBeUndefined() - }) -}) diff --git a/src/shared/relay-version-marker.test.ts b/src/shared/relay-version-marker.test.ts index 36955399518..77ae3efc089 100644 --- a/src/shared/relay-version-marker.test.ts +++ b/src/shared/relay-version-marker.test.ts @@ -2,7 +2,7 @@ import { mkdtempSync, rmSync, truncateSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' -import { NodeFileReadTooLargeError } from './node-bounded-file-reader' +import { NodeFileReadTooLargeError } from './file-content/node-bounded-file-reader' import { RELAY_VERSION_MARKER_MAX_BYTES, readRelayVersionMarkerSync } from './relay-version-marker' const roots: string[] = [] diff --git a/src/shared/relay-version-marker.ts b/src/shared/relay-version-marker.ts index 68be008ff8d..58479029fba 100644 --- a/src/shared/relay-version-marker.ts +++ b/src/shared/relay-version-marker.ts @@ -1,4 +1,4 @@ -import { readNodeFileSyncWithinLimit } from './node-bounded-file-reader' +import { readNodeFileSyncWithinLimit } from './file-content/node-bounded-file-reader' export const RELAY_VERSION_MARKER_MAX_BYTES = 4 * 1024 diff --git a/src/shared/remote-rpc-content-budget.ts b/src/shared/remote-rpc-content-budget.ts index 3ebbf9562f1..b1b270a4966 100644 --- a/src/shared/remote-rpc-content-budget.ts +++ b/src/shared/remote-rpc-content-budget.ts @@ -2,7 +2,7 @@ import { REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES } from './remote-runtime/remote- import { JsonStringifyByteLimitError, stringifyJsonWithinByteLimit -} from './node-bounded-json-stringify' +} from './json-stream/node-bounded-json-stringify' // Reserve fixed/future reply metadata; separately charge arbitrary echoed request IDs. const OUTBOUND_ENVELOPE_RESERVE_BYTES = 4 * 1024 diff --git a/src/shared/remote-runtime/e2ee/node/remote-runtime-e2ee-v2-host-latch.ts b/src/shared/remote-runtime/e2ee/node/remote-runtime-e2ee-v2-host-latch.ts index 36c261280f3..1c6150f16b2 100644 --- a/src/shared/remote-runtime/e2ee/node/remote-runtime-e2ee-v2-host-latch.ts +++ b/src/shared/remote-runtime/e2ee/node/remote-runtime-e2ee-v2-host-latch.ts @@ -1,7 +1,7 @@ import { existsSync } from 'node:fs' import { join } from 'node:path' -import { readNodeFileSyncWithinLimit } from '../../../node-bounded-file-reader' -import { writeSecureJsonFile } from '../../../secure-file' +import { readNodeFileSyncWithinLimit } from '../../../file-content/node-bounded-file-reader' +import { writeSecureJsonFile } from '../../../secure-storage/secure-file' import type { PairedE2EEV2LatchStore } from '../paired-e2ee-framing-policy' export type NodeE2EEV2HostLatchStore = PairedE2EEV2LatchStore & { diff --git a/src/shared/remote-runtime/host-store/runtime-e2ee-keypair-file.ts b/src/shared/remote-runtime/host-store/runtime-e2ee-keypair-file.ts index 38d3c5b1e48..2c1f41f6c42 100644 --- a/src/shared/remote-runtime/host-store/runtime-e2ee-keypair-file.ts +++ b/src/shared/remote-runtime/host-store/runtime-e2ee-keypair-file.ts @@ -1,6 +1,6 @@ import { existsSync } from 'node:fs' import { join } from 'node:path' -import { readNodeFileSyncWithinLimit } from '../../node-bounded-file-reader' +import { readNodeFileSyncWithinLimit } from '../../file-content/node-bounded-file-reader' export const E2EE_KEYPAIR_FILENAME = 'orca-e2ee-keypair.json' export const MAX_E2EE_KEYPAIR_FILE_BYTES = 8 * 1024 diff --git a/src/shared/remote-runtime/host-store/runtime-environment-sidecar.ts b/src/shared/remote-runtime/host-store/runtime-environment-sidecar.ts index 5ca6e3d0c6a..1a7040bd3be 100644 --- a/src/shared/remote-runtime/host-store/runtime-environment-sidecar.ts +++ b/src/shared/remote-runtime/host-store/runtime-environment-sidecar.ts @@ -1,8 +1,8 @@ import { existsSync } from 'node:fs' import { join } from 'node:path' import { z } from 'zod' -import { writeSecureJsonFileWithinLimit } from '../../bounded-secure-json-file' -import { readNodeFileSyncWithinLimit } from '../../node-bounded-file-reader' +import { writeSecureJsonFileWithinLimit } from '../../secure-storage/bounded-secure-json-file' +import { readNodeFileSyncWithinLimit } from '../../file-content/node-bounded-file-reader' import { RuntimeEnvironmentReconciliationRecordSchema } from '../host-catalog/runtime-environment-reconciliation-record' import { readEnvironmentStoreRecords } from './runtime-environment-store-records' import { @@ -15,7 +15,7 @@ import { type KnownRuntimeEnvironment, type PersistedRuntimeEnvironment } from '../host-catalog/runtime-environments' -import { hardenExistingSecureFile } from '../../secure-file' +import { hardenExistingSecureFile } from '../../secure-storage/secure-file' // Shipped builds strip unknown environment fields on routine writes; preserve newer state in this untouched sidecar. const SIDECAR_FILE = 'orca-environment-sidecar.json' diff --git a/src/shared/remote-runtime/host-store/runtime-environment-store-file.ts b/src/shared/remote-runtime/host-store/runtime-environment-store-file.ts index 663279ce23f..0cedbcabf84 100644 --- a/src/shared/remote-runtime/host-store/runtime-environment-store-file.ts +++ b/src/shared/remote-runtime/host-store/runtime-environment-store-file.ts @@ -1,8 +1,8 @@ import { JsonStringifyByteLimitError, stringifyJsonWithinByteLimit -} from '../../node-bounded-json-stringify' -import { writeSecureFile } from '../../secure-file' +} from '../../json-stream/node-bounded-json-stringify' +import { writeSecureFile } from '../../secure-storage/secure-file' import { RuntimeEnvironmentStoreSchema, type KnownRuntimeEnvironment, diff --git a/src/shared/remote-runtime/host-store/runtime-environment-store-read-cache-integration.test.ts b/src/shared/remote-runtime/host-store/runtime-environment-store-read-cache-integration.test.ts index b4e74178112..e567fa52b0c 100644 --- a/src/shared/remote-runtime/host-store/runtime-environment-store-read-cache-integration.test.ts +++ b/src/shared/remote-runtime/host-store/runtime-environment-store-read-cache-integration.test.ts @@ -3,8 +3,8 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { encodePairingOffer } from '../pairing/pairing' -import type * as BoundedReader from '../../node-bounded-file-reader' -import { __resetSecureFileHardenedPathsForTests } from '../../secure-file' +import type * as BoundedReader from '../../file-content/node-bounded-file-reader' +import { __resetSecureFileHardenedPathsForTests } from '../../secure-storage/secure-file' import { addEnvironmentFromPairingCode, listEnvironments } from './runtime-environment-store' import { getEnvironmentStorePath } from './runtime-environment-store-records' @@ -26,7 +26,7 @@ vi.mock('node:fs', async (importOriginal) => { } } }) -vi.mock('../../node-bounded-file-reader', async (importOriginal) => { +vi.mock('../../file-content/node-bounded-file-reader', async (importOriginal) => { const actual = await importOriginal() return { ...actual, diff --git a/src/shared/remote-runtime/host-store/runtime-environment-store-read-cache.ts b/src/shared/remote-runtime/host-store/runtime-environment-store-read-cache.ts index b514557fc55..8680a31cb76 100644 --- a/src/shared/remote-runtime/host-store/runtime-environment-store-read-cache.ts +++ b/src/shared/remote-runtime/host-store/runtime-environment-store-read-cache.ts @@ -1,6 +1,6 @@ import { existsSync, statSync } from 'node:fs' -import { hardenExistingSecureFile } from '../../secure-file' -import { readNodeFileSyncWithinLimit } from '../../node-bounded-file-reader' +import { hardenExistingSecureFile } from '../../secure-storage/secure-file' +import { readNodeFileSyncWithinLimit } from '../../file-content/node-bounded-file-reader' // Why: remote RPC, tunnel and worker-server checks resolve the saved-server registry many times per second; // rechecking, rehardening, reparsing and revalidating unchanged files each time blocked the Electron main thread. diff --git a/src/shared/remote-runtime/host-store/runtime-environment-store-records.ts b/src/shared/remote-runtime/host-store/runtime-environment-store-records.ts index 730d7629ccb..13f83c5e600 100644 --- a/src/shared/remote-runtime/host-store/runtime-environment-store-records.ts +++ b/src/shared/remote-runtime/host-store/runtime-environment-store-records.ts @@ -1,12 +1,12 @@ import { constants, copyFileSync, existsSync } from 'node:fs' import { join } from 'node:path' import { z } from 'zod' -import { readNodeFileSyncWithinLimit } from '../../node-bounded-file-reader' +import { readNodeFileSyncWithinLimit } from '../../file-content/node-bounded-file-reader' import { PersistedRuntimeEnvironmentSchema, type PersistedRuntimeEnvironment } from '../host-catalog/runtime-environments' -import { hardenExistingSecureFile } from '../../secure-file' +import { hardenExistingSecureFile } from '../../secure-storage/secure-file' import { remoteServerPairingFailureText, type RemoteServerPairingFailureCode, diff --git a/src/shared/remote-runtime/host-store/wsl-host-deployment-store.ts b/src/shared/remote-runtime/host-store/wsl-host-deployment-store.ts index 721efc92f09..c08c0c1e235 100644 --- a/src/shared/remote-runtime/host-store/wsl-host-deployment-store.ts +++ b/src/shared/remote-runtime/host-store/wsl-host-deployment-store.ts @@ -1,8 +1,8 @@ import { existsSync } from 'node:fs' import { join } from 'node:path' import { z } from 'zod' -import { writeSecureJsonFileWithinLimit } from '../../bounded-secure-json-file' -import { readNodeFileSyncWithinLimit } from '../../node-bounded-file-reader' +import { writeSecureJsonFileWithinLimit } from '../../secure-storage/bounded-secure-json-file' +import { readNodeFileSyncWithinLimit } from '../../file-content/node-bounded-file-reader' import { warnUnreadableEnvironmentState } from './runtime-environment-store-records' import { getPreferredLoopbackRuntimePort, @@ -10,7 +10,7 @@ import { KnownRuntimeEnvironmentSchema, type KnownRuntimeEnvironment } from '../host-catalog/runtime-environments' -import { hardenExistingSecureFile } from '../../secure-file' +import { hardenExistingSecureFile } from '../../secure-storage/secure-file' import { OrcadWslDeploymentLinkSchema } from '../host-catalog/wsl-host-deployment-link' // Isolate WSL records so older builds cannot reject the entire pairing store. diff --git a/src/shared/remote-runtime/remote-runtime-memory-limits.ts b/src/shared/remote-runtime/remote-runtime-memory-limits.ts index 6560e72f54f..c35e01b1f0a 100644 --- a/src/shared/remote-runtime/remote-runtime-memory-limits.ts +++ b/src/shared/remote-runtime/remote-runtime-memory-limits.ts @@ -1,7 +1,7 @@ import { JsonStringifyByteLimitError, stringifyJsonWithinByteLimit -} from '../node-bounded-json-stringify' +} from '../json-stream/node-bounded-json-stringify' import { RemoteRuntimeClientError } from './remote-runtime-client-error' import type { RuntimeOrchestrationEnvelope } from '../runtime-rpc-envelope' diff --git a/src/shared/remote-runtime/requests/remote-runtime-request-frames.ts b/src/shared/remote-runtime/requests/remote-runtime-request-frames.ts index 66ee8946499..38adb341789 100644 --- a/src/shared/remote-runtime/requests/remote-runtime-request-frames.ts +++ b/src/shared/remote-runtime/requests/remote-runtime-request-frames.ts @@ -4,7 +4,7 @@ import { isKeepaliveFrame } from '../../runtime-rpc-envelope' import { RemoteRuntimeClientError } from '../remote-runtime-client-error' -import { assertJsonTextStructureWithinLimits } from '../../json-text-structure-limit' +import { assertJsonTextStructureWithinLimits } from '../../json-stream/json-text-structure-limit' import type { PairedE2EEAuthReply, PairedE2EEReadyVerdict diff --git a/src/shared/repo-icon.test.ts b/src/shared/repo-icon.test.ts index 1258cd2852d..fcd853d471e 100644 --- a/src/shared/repo-icon.test.ts +++ b/src/shared/repo-icon.test.ts @@ -1,11 +1,11 @@ import { describe, expect, it, vi } from 'vitest' -import type * as ImageDataUriModule from './image-data-uri' +import type * as ImageDataUriModule from './file-preview/image-data-uri' import { githubAvatarIcon, sanitizeRepoIcon } from './repo-icon' // Count leaf data-URI header decodes to measure repeated hydration cost. const { dataUriValidations } = vi.hoisted(() => ({ dataUriValidations: { count: 0 } })) -vi.mock('./image-data-uri', async (importOriginal) => { +vi.mock('./file-preview/image-data-uri', async (importOriginal) => { const actual = await importOriginal() return { ...actual, @@ -106,21 +106,4 @@ describe('repo icon source validation memo', () => { // WebP is a `file` icon only; sharing one cache across sources would accept it as an upload. expect(sanitizeRepoIcon({ type: 'image', src, source: 'upload' })).toBeUndefined() }) - - // Recheck src/source on hits so in-place mutations cannot reuse stale verdicts. - it('re-validates an icon object whose src or source is mutated in place', () => { - const icon = { type: 'image', src: `data:image/png;base64,${pngBase64(7, 1)}`, source: 'file' } - expect(sanitizeRepoIcon(icon)).toEqual(icon) - - icon.src = `data:image/png;base64,${pngBase64(8, 1)}` - dataUriValidations.count = 0 - expect(sanitizeRepoIcon(icon)).toEqual(icon) - expect(dataUriValidations.count).toBe(1) - - // WebP is a `file` icon but not an `upload` icon, so the same object must flip verdicts. - icon.src = `data:image/webp;base64,${WEBP_1X1_BASE64}` - expect(sanitizeRepoIcon(icon)).toEqual(icon) - icon.source = 'upload' - expect(sanitizeRepoIcon(icon)).toBeUndefined() - }) }) diff --git a/src/shared/repo-icon.ts b/src/shared/repo-icon.ts index f62dba86336..da8f1c5fe6f 100644 --- a/src/shared/repo-icon.ts +++ b/src/shared/repo-icon.ts @@ -1,4 +1,4 @@ -import { validateRasterImageDataUri } from './image-data-uri' +import { validateRasterImageDataUri } from './file-preview/image-data-uri' export type RepoIconImageSource = 'upload' | 'file' | 'favicon' | 'github' diff --git a/src/shared/ripgrep-dense-match-json.test.ts b/src/shared/ripgrep-dense-match-json.test.ts deleted file mode 100644 index 9058976321f..00000000000 --- a/src/shared/ripgrep-dense-match-json.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { expect, it } from 'vitest' -import { parseDenseRipgrepMatchJson } from './ripgrep-dense-match-json' - -it.each(['', '\\', '\n', '\n'.repeat(64 * 1024), `${'x'.repeat(64 * 1024)}\n`])( - 'preserves U+FEFF in text and filenames across string-buffer boundaries (%#)', - (prefix) => { - const text = `${prefix}\ufeff😀x` - const source = { - type: 'match', - data: { - path: { text }, - lines: { text }, - line_number: 1, - submatches: [{ start: 0, end: 1 }] - } - } - const record = JSON.stringify(source) - for (const encoded of [record, record.replaceAll('\ufeff', '\\uFEFF')]) { - expect(parseDenseRipgrepMatchJson(encoded, 1, 16)).toEqual(JSON.parse(record)) - } - } -) - -it('retains only exact match fields and the remaining range budget', () => { - const ranges = [ - { start: 0, end: 1 }, - { start: 2, end: 3 } - ] - const source = { - type: 'match', - submatches: [{ start: 99, end: 100 }], - data: { - nested: { submatches: [{ start: 88, end: 89 }] }, - lines: { text: 'a "submatches" b', bytes: 'YQ==' }, - path: { text: '/root/a.ts' }, - line_number: 12, - submatches: ranges - } - } - expect(parseDenseRipgrepMatchJson(JSON.stringify(source), 1, 16)).toEqual({ - type: 'match', - data: { - lines: source.data.lines, - path: source.data.path, - line_number: 12, - submatches: ranges.slice(0, 1) - } - }) -}) - -it('rejects depth overflow and invalid submatch shapes', () => { - const nested = `${'['.repeat(17)}0${']'.repeat(17)}` - expect(() => parseDenseRipgrepMatchJson(nested, 2, 16)).toThrow('rg record nesting exceeds limit') - expect(() => parseDenseRipgrepMatchJson('{"data":{"submatches":[null]}}', 2, 16)).toThrow() -}) - -it('validates submatches after reaching the requested result cap', () => { - const source = JSON.stringify({ - type: 'match', - data: { - submatches: [ - { start: 0, end: 1 }, - { start: null, end: 2 } - ] - } - }) - expect(() => parseDenseRipgrepMatchJson(source, 1, 16)).toThrow('Invalid rg submatch') -}) - -it('rejects duplicate coordinate fields whose final value is not numeric', () => { - const source = '{"data":{"submatches":[{"start":0,"start":{},"end":1}]}}' - expect(() => parseDenseRipgrepMatchJson(source, 1, 16)).toThrow('Invalid rg submatch') -}) - -it.each([16_378, 16_379])('retains the existing per-element token budget at %i values', (count) => { - const source = JSON.stringify({ - data: { submatches: [{ start: 0, end: 1, other: Array(count).fill(0) }] } - }) - const parse = (): unknown => parseDenseRipgrepMatchJson(source, 1, 16) - if (count === 16_378) { - expect(parse()).toMatchObject({ data: { submatches: [{ start: 0, end: 1 }] } }) - } else { - expect(parse).toThrow('rg submatch structure exceeds limit') - } -}) diff --git a/src/shared/ripgrep-line-decoding.test.ts b/src/shared/ripgrep-line-decoding.test.ts deleted file mode 100644 index 3c28d76a37c..00000000000 --- a/src/shared/ripgrep-line-decoding.test.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { decodeRipgrepLine } from './ripgrep-line-decoding' -import { ripgrepMatchRanges } from './ripgrep-match-offsets' - -describe('ripgrep byte line decoding', () => { - it.each([ - [0xff], - [0xc0, 0xaf], - [0xe2, 0x82], - [0xf0, 0x90, 0x80], - [0xed, 0xa0, 0x80], - [0xf4, 0x90, 0x80, 0x80], - [0x80, 0xbf], - [0xe0, 0x80, 0xaf] - ])('maps text after malformed sequence %j like Node UTF8 decoding', (...prefix) => { - const bytes = Buffer.concat([ - Buffer.from('😀é'), - Buffer.from(prefix), - Buffer.from('needle\r\n') - ]) - const decoded = decodeRipgrepLine({ bytes: bytes.toString('base64') }) - expect(decoded.text).toBe(bytes.toString('utf8').replace(/\n$/, '')) - expect(decoded.readOffset(bytes.length - 8)).toBe(decoded.text.indexOf('needle')) - expect(decoded.readOffset(bytes.length - 2)).toBe(decoded.text.indexOf('needle') + 6) - }) - - it('rejects partial replacement boundaries and overlapping ranges without inventing coordinates', () => { - const decoded = decodeRipgrepLine({ - bytes: Buffer.from([0xe2, 0x82, 0x20, 0x78]).toString('base64') - }) - let invalid = 0 - const ranges = [ - ...ripgrepMatchRanges( - decoded.text, - [ - { start: 0, end: 1 }, - { start: 2, end: 3 }, - { start: 2, end: 4 }, - { start: 4, end: 4 } - ], - decoded.readOffset, - () => invalid++ - ) - ] - expect(ranges).toEqual([ - { start: 1, end: 2 }, - { start: 3, end: 3 } - ]) - expect(invalid).toBe(2) - }) - - it('agrees with Node on all two-byte prefixes followed by ASCII', () => { - for (let first = 0; first < 256; first++) { - for (let second = 0; second < 256; second++) { - const bytes = Buffer.from([first, second, 0x78]) - const decoded = decodeRipgrepLine({ bytes: bytes.toString('base64') }) - expect(decoded.readOffset(2)).toBe(bytes.subarray(0, 2).toString('utf8').length) - } - } - }) -}) diff --git a/src/shared/ripgrep-process-availability.test.ts b/src/shared/ripgrep-process-availability.test.ts deleted file mode 100644 index 374435d66ce..00000000000 --- a/src/shared/ripgrep-process-availability.test.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { spawn, ChildProcess } from 'node:child_process' - -import { describe, expect, it, vi } from 'vitest' -import { - absorbPendingRipgrepSpawnError, - killSpawnedRipgrepProcess -} from './ripgrep-process-availability' - -function createChild(pid: number | undefined): ChildProcess { - const child = new ChildProcess() - Object.defineProperty(child, 'pid', { value: pid }) - return child -} - -describe('ripgrep process availability', () => { - it('does not signal a real failed-spawn handle', async () => { - const child = spawn('orca-definitely-missing-rg-admission-test', []) - const error = new Promise((resolve) => child.once('error', () => resolve())) - const close = new Promise((resolve) => child.once('close', () => resolve())) - - const kill = vi.spyOn(child, 'kill') - try { - expect(killSpawnedRipgrepProcess(child)).toBe(false) - expect(kill).not.toHaveBeenCalled() - } finally { - await Promise.all([error, close]) - kill.mockRestore() - } - }) - - it('absorbs a queued spawn error when cleanup wins the race', () => { - const child = createChild(undefined) - absorbPendingRipgrepSpawnError(child, { - errorObserved: false, - unavailableExitObserved: false - }) - - expect(() => child.emit('error', new Error('spawn rg ENOENT'))).not.toThrow() - expect(child.listenerCount('error')).toBe(0) - }) -}) diff --git a/src/shared/bundled-ripgrep.ts b/src/shared/ripgrep/bundled-ripgrep.ts similarity index 97% rename from src/shared/bundled-ripgrep.ts rename to src/shared/ripgrep/bundled-ripgrep.ts index 9fc65807aff..195946dfa23 100644 --- a/src/shared/bundled-ripgrep.ts +++ b/src/shared/ripgrep/bundled-ripgrep.ts @@ -1,4 +1,4 @@ -import { REMOTE_BUNDLE_PLATFORMS, type RemoteBundlePlatform } from './remote-bundle-artifacts' +import { REMOTE_BUNDLE_PLATFORMS, type RemoteBundlePlatform } from '../remote-bundle-artifacts' /** Bundle ripgrep for every relay platform so local/WSL/SSH search never depends on a user-installed rg. */ export const BUNDLED_RIPGREP_PLATFORMS: readonly RemoteBundlePlatform[] = REMOTE_BUNDLE_PLATFORMS diff --git a/src/shared/ripgrep/ripgrep-dense-match-json.test.ts b/src/shared/ripgrep/ripgrep-dense-match-json.test.ts new file mode 100644 index 00000000000..f4f26b0d565 --- /dev/null +++ b/src/shared/ripgrep/ripgrep-dense-match-json.test.ts @@ -0,0 +1,20 @@ +import { expect, it } from 'vitest' +import { parseDenseRipgrepMatchJson } from './ripgrep-dense-match-json' + +it('validates submatches after reaching the requested result cap', () => { + const source = JSON.stringify({ + type: 'match', + data: { + submatches: [ + { start: 0, end: 1 }, + { start: null, end: 2 } + ] + } + }) + expect(() => parseDenseRipgrepMatchJson(source, 1, 16)).toThrow('Invalid rg submatch') +}) + +it('rejects duplicate coordinate fields whose final value is not numeric', () => { + const source = '{"data":{"submatches":[{"start":0,"start":{},"end":1}]}}' + expect(() => parseDenseRipgrepMatchJson(source, 1, 16)).toThrow('Invalid rg submatch') +}) diff --git a/src/shared/ripgrep-dense-match-json.ts b/src/shared/ripgrep/ripgrep-dense-match-json.ts similarity index 97% rename from src/shared/ripgrep-dense-match-json.ts rename to src/shared/ripgrep/ripgrep-dense-match-json.ts index 5b54069fb10..0611f3ee4eb 100644 --- a/src/shared/ripgrep-dense-match-json.ts +++ b/src/shared/ripgrep/ripgrep-dense-match-json.ts @@ -2,8 +2,8 @@ import { assertJsonTextStructureWithinLimits, JsonTextStructureCapacityError, type JsonTextStructureLimits -} from './json-text-structure-limit' -import { createJsonTokenReader } from './json-token-reader' +} from '../json-stream/json-text-structure-limit' +import { createJsonTokenReader } from '../json-stream/json-token-reader' export type RipgrepMatchMessage = { type?: string diff --git a/src/shared/ripgrep-filename-decoder.test.ts b/src/shared/ripgrep/ripgrep-filename-decoder.test.ts similarity index 100% rename from src/shared/ripgrep-filename-decoder.test.ts rename to src/shared/ripgrep/ripgrep-filename-decoder.test.ts diff --git a/src/shared/ripgrep-filename-decoder.ts b/src/shared/ripgrep/ripgrep-filename-decoder.ts similarity index 100% rename from src/shared/ripgrep-filename-decoder.ts rename to src/shared/ripgrep/ripgrep-filename-decoder.ts diff --git a/src/shared/ripgrep-line-decoding.ts b/src/shared/ripgrep/ripgrep-line-decoding.ts similarity index 100% rename from src/shared/ripgrep-line-decoding.ts rename to src/shared/ripgrep/ripgrep-line-decoding.ts diff --git a/src/shared/ripgrep-match-offsets.test.ts b/src/shared/ripgrep/ripgrep-match-offsets.test.ts similarity index 100% rename from src/shared/ripgrep-match-offsets.test.ts rename to src/shared/ripgrep/ripgrep-match-offsets.test.ts diff --git a/src/shared/ripgrep-match-offsets.ts b/src/shared/ripgrep/ripgrep-match-offsets.ts similarity index 100% rename from src/shared/ripgrep-match-offsets.ts rename to src/shared/ripgrep/ripgrep-match-offsets.ts diff --git a/src/shared/ripgrep-process-availability.ts b/src/shared/ripgrep/ripgrep-process-availability.ts similarity index 100% rename from src/shared/ripgrep-process-availability.ts rename to src/shared/ripgrep/ripgrep-process-availability.ts diff --git a/src/shared/ripgrep-search-diagnostics.test.ts b/src/shared/ripgrep/ripgrep-search-diagnostics.test.ts similarity index 84% rename from src/shared/ripgrep-search-diagnostics.test.ts rename to src/shared/ripgrep/ripgrep-search-diagnostics.test.ts index 230ca21f7d7..c8c2fe10642 100644 --- a/src/shared/ripgrep-search-diagnostics.test.ts +++ b/src/shared/ripgrep/ripgrep-search-diagnostics.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { createAccumulator } from './text-search' +import { createAccumulator } from '../file-search/text-search' import { RipgrepSearchDiagnostics } from './ripgrep-search-diagnostics' describe('ripgrep search diagnostics', () => { @@ -11,14 +11,6 @@ describe('ripgrep search diagnostics', () => { ) }) - it('limits retained diagnostics even for large stderr chunks', () => { - const diagnostics = new RipgrepSearchDiagnostics() - diagnostics.append('x'.repeat(100_000)) - diagnostics.append('must not be retained') - const error = diagnostics.failure(2, null, createAccumulator()) - expect(error?.message).toBe(`Search failed (2): ${'x'.repeat(4096)}`) - }) - it('marks permission-error results as incomplete', () => { const acc = createAccumulator() acc.totalMatches = 1 diff --git a/src/shared/ripgrep-search-diagnostics.ts b/src/shared/ripgrep/ripgrep-search-diagnostics.ts similarity index 97% rename from src/shared/ripgrep-search-diagnostics.ts rename to src/shared/ripgrep/ripgrep-search-diagnostics.ts index 05cc8acb5a3..73a7f7984cc 100644 --- a/src/shared/ripgrep-search-diagnostics.ts +++ b/src/shared/ripgrep/ripgrep-search-diagnostics.ts @@ -1,4 +1,4 @@ -import type { SearchAccumulator } from './text-search' +import type { SearchAccumulator } from '../file-search/text-search' const MAX_SEARCH_ERROR_BYTES = 4096 const MAX_STDERR_LINE_CHARS = 64 * 1024 diff --git a/src/shared/rpc-contract/agent-session-attachment-params.ts b/src/shared/rpc-contract/agent-session-attachment-params.ts index 07b5214e596..8ac54c03d00 100644 --- a/src/shared/rpc-contract/agent-session-attachment-params.ts +++ b/src/shared/rpc-contract/agent-session-attachment-params.ts @@ -1,5 +1,5 @@ import { z } from 'zod' -import { MAX_FILE_RANGE_READ_BYTES } from '../file-range-read' +import { MAX_FILE_RANGE_READ_BYTES } from '../file-content/file-range-read' import { AGENT_SESSION_ATTACHMENT_CHUNK_BASE64_CHARS, AGENT_SESSION_ATTACHMENT_MAX_BYTES diff --git a/src/shared/rpc-contract/artifacts-params.ts b/src/shared/rpc-contract/artifacts-params.ts index e5743485892..48b9b5e27ec 100644 --- a/src/shared/rpc-contract/artifacts-params.ts +++ b/src/shared/rpc-contract/artifacts-params.ts @@ -4,7 +4,7 @@ import { ARTIFACT_MAX_REQUEST_BYTES, artifactContentByteLength, artifactWriteRequestByteLength -} from '../artifacts' +} from '../artifacts/artifacts' export const CloudOptions = { apiUrl: z.string().max(2_048).optional(), diff --git a/src/shared/rpc-contract/files-params.ts b/src/shared/rpc-contract/files-params.ts index b0aa8e885c9..95da45fa297 100644 --- a/src/shared/rpc-contract/files-params.ts +++ b/src/shared/rpc-contract/files-params.ts @@ -1,7 +1,7 @@ -import { PATH_EXISTENCE_BATCH_MAX } from '../path-existence-batch' -import { FILE_READ_DIR_MAX_PAGE_ENTRIES } from '../file-dir-page' +import { PATH_EXISTENCE_BATCH_MAX } from '../file-access/path-existence-batch' +import { FILE_READ_DIR_MAX_PAGE_ENTRIES } from '../file-listing/file-dir-page' import { z } from 'zod' -import { QUICK_OPEN_REMOTE_QUERY_MAX_CODE_UNITS } from '../quick-open-path-search' +import { QUICK_OPEN_REMOTE_QUERY_MAX_CODE_UNITS } from '../quick-open/quick-open-path-search' import { RUNTIME_NAVIGATION_TARGETS } from '../runtime-navigation' import { FileOpen, WorktreeSelector } from './files-target-params' diff --git a/src/shared/rpc-contract/files-staged-save-params.ts b/src/shared/rpc-contract/files-staged-save-params.ts index 45294561133..f37850a42ad 100644 --- a/src/shared/rpc-contract/files-staged-save-params.ts +++ b/src/shared/rpc-contract/files-staged-save-params.ts @@ -1,5 +1,5 @@ import { z } from 'zod' -import { STAGED_FILE_SAVE_LIMITS } from '../staged-file-save' +import { STAGED_FILE_SAVE_LIMITS } from '../file-write/staged-file-save' import { FileMutationOpen, FileWriteDiskPreconditionParam, diff --git a/src/shared/runtime-types.ts b/src/shared/runtime-types.ts index a8699e2d38b..88a5808e7b3 100644 --- a/src/shared/runtime-types.ts +++ b/src/shared/runtime-types.ts @@ -82,17 +82,7 @@ export type { BrowserViewportResult, BrowserWaitResult } from './runtime-browser-contracts' -export type { - RuntimeFileListEntry, - RuntimeFileListResult, - RuntimeFileOpenResult, - RuntimeFilePreviewResult, - RuntimeFileReadChunkResult, - RuntimeFileReadResult, - RuntimeNativeChatFileContext, - RuntimeTerminalPathOpenTarget, - RuntimeTerminalPathResolution -} from './runtime-file-contracts' + export { BROWSER_UNAVAILABLE_ERROR_CODE, browserUnavailableMessage, diff --git a/src/shared/search-result-transport-budget.test.ts b/src/shared/search-result-transport-budget.test.ts deleted file mode 100644 index 0330e1ade3a..00000000000 --- a/src/shared/search-result-transport-budget.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { SearchFileResult, SearchResult } from './code-search-types' -import { limitSearchResultToContentBudget } from './search-result-transport-budget' - -function file(index: number, lineBytes: number): SearchFileResult { - return { - filePath: `/repo/src/file-${index}.ts`, - relativePath: `src/file-${index}.ts`, - matches: [{ line: 1, column: 1, matchLength: 3, lineContent: 'x'.repeat(lineBytes) }] - } -} - -function result(files: SearchFileResult[]): SearchResult { - return { files, totalMatches: files.length, truncated: false } -} - -describe('limitSearchResultToContentBudget', () => { - it('keeps whole files that fit the reply and marks the rest truncated', () => { - const large = result(Array.from({ length: 200 }, (_, index) => file(index, 400))) - const maxBytes = 16 * 1024 - const limited = limitSearchResultToContentBudget(large, maxBytes) - - expect(limited.truncated).toBe(true) - expect(limited.files.length).toBeGreaterThan(0) - expect(limited.files.length).toBeLessThan(200) - expect(limited.files).toEqual(large.files.slice(0, limited.files.length)) - expect(limited.totalMatches).toBe(limited.files.length) - expect(Buffer.byteLength(JSON.stringify(limited), 'utf8')).toBeLessThanOrEqual(maxBytes) - }) -}) diff --git a/src/shared/search-subprocess-lines.test.ts b/src/shared/search-subprocess-lines.test.ts index a4175d93e2a..125bc184de8 100644 --- a/src/shared/search-subprocess-lines.test.ts +++ b/src/shared/search-subprocess-lines.test.ts @@ -43,51 +43,12 @@ describe('SearchSubprocessLineAccumulator', () => { expect(lines).toEqual(['', 'a', '']) }) - it('retains a fragmented line until finish and releases its capacity', () => { - const parser = new SearchSubprocessLineAccumulator(256 * 1024) - const byte = Buffer.from('x') - let accepted = true - - for (let index = 0; index < 200_000; index += 1) { - accepted = parser.push(byte, () => {}) && accepted - } - - expect(accepted).toBe(true) - expect(parser.retainedCapacityBytes()).toBeGreaterThanOrEqual(200_000) - expect(parser.finish()).toBe('x'.repeat(200_000)) - expect(parser.retainedCapacityBytes()).toBeNull() - }) - it('rejects invalid byte limits', () => { expect(() => new SearchSubprocessLineAccumulator(-1)).toThrow(RangeError) }) }) describe('oversized search record continuation', () => { - it.each(['string', 'buffer'])('keeps complete lines around an oversized %s record', (kind) => { - const parser = new SearchSubprocessLineAccumulator(4, 'discard') - const lines: string[] = [] - const batch = 'four\noversized\nnext\n' - expect( - parser.push(kind === 'buffer' ? Buffer.from(batch) : batch, (line) => lines.push(line)) - ).toBe(false) - expect(lines).toEqual(['four', 'next']) - expect(parser.retainedCapacityBytes()).toBeNull() - expect(parser.finish()).toBeNull() - }) - - it('discards a fragmented record through its newline before accepting UTF-8 again', () => { - const parser = new SearchSubprocessLineAccumulator(4, 'discard') - const lines: string[] = [] - expect(parser.push(Buffer.from('ab'), (line) => lines.push(line))).toBe(true) - expect(parser.push(Buffer.from('cde'), (line) => lines.push(line))).toBe(false) - expect(parser.retainedCapacityBytes()).toBeNull() - expect(parser.push('suffix', (line) => lines.push(line))).toBe(true) - expect(parser.push('\néé\n', (line) => lines.push(line))).toBe(true) - expect(lines).toEqual(['éé']) - expect(parser.finish()).toBeNull() - }) - it.each(['clear', 'finish'] as const)('resets an unterminated discard on %s', (reset) => { const parser = new SearchSubprocessLineAccumulator(4, 'discard') const lines: string[] = [] @@ -96,12 +57,4 @@ describe('oversized search record continuation', () => { expect(parser.push('four\n', (line) => lines.push(line))).toBe(true) expect(lines).toEqual(['four']) }) - - it('skips adjacent oversized records without changing the byte limit for later records', () => { - const parser = new SearchSubprocessLineAccumulator(4, 'discard') - const lines: string[] = [] - expect(parser.push('five5\nsixsix\n漢é\nfour\n', (line) => lines.push(line))).toBe(false) - expect(lines).toEqual(['four']) - expect(parser.retainedCapacityBytes()).toBeNull() - }) }) diff --git a/src/shared/secure-file-coarse-ctime.test.ts b/src/shared/secure-file-coarse-ctime.test.ts deleted file mode 100644 index daff28255ca..00000000000 --- a/src/shared/secure-file-coarse-ctime.test.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { chmodSyncMock, existsSyncMock, paths, statSyncMock, state } = vi.hoisted(() => ({ - chmodSyncMock: vi.fn(), - existsSyncMock: vi.fn(), - paths: { - dir: '/secure', - file: '/secure/secret.json' - }, - statSyncMock: vi.fn(), - state: { - dirMode: 0o755, - fileMode: 0o600 - } -})) - -vi.mock('fs', () => ({ - chmodSync: chmodSyncMock, - existsSync: existsSyncMock, - mkdirSync: vi.fn(), - renameSync: vi.fn(), - rmSync: vi.fn(), - statSync: statSyncMock, - writeFileSync: vi.fn() -})) - -vi.mock('child_process', () => ({ - execFile: vi.fn(), - execFileSync: vi.fn() -})) - -import { resetWindowsSecurityLoadForTests } from './windows-security-addon' -import { __resetSecureFileHardenedPathsForTests, hardenExistingSecureFile } from './secure-file' - -describe('secure-file coarse-ctime mode drift', () => { - const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') - - beforeEach(() => { - Object.defineProperty(process, 'platform', { configurable: true, value: 'linux' }) - state.dirMode = 0o755 - state.fileMode = 0o600 - existsSyncMock.mockReturnValue(true) - statSyncMock.mockImplementation((targetPath: string) => { - const path = String(targetPath) - if (path === paths.dir) { - return fakeStats(true, state.dirMode) - } - if (path === paths.file) { - return fakeStats(false, state.fileMode) - } - throw new Error(`unexpected stat path ${path}`) - }) - chmodSyncMock.mockImplementation((targetPath: string, mode: number) => { - const path = String(targetPath) - if (path === paths.dir) { - state.dirMode = mode & 0o777 - } else if (path === paths.file) { - state.fileMode = mode & 0o777 - } - }) - resetWindowsSecurityLoadForTests() - __resetSecureFileHardenedPathsForTests() - }) - - afterEach(() => { - chmodSyncMock.mockReset() - existsSyncMock.mockReset() - statSyncMock.mockReset() - resetWindowsSecurityLoadForTests() - __resetSecureFileHardenedPathsForTests() - if (originalPlatform) { - Object.defineProperty(process, 'platform', originalPlatform) - } - }) - - it('re-hardens a directory when only POSIX mode changes under stable timestamps', () => { - hardenExistingSecureFile(paths.file) - expect(chmodSyncMock.mock.calls).toEqual([ - [paths.dir, 0o700], - [paths.file, 0o600] - ]) - - chmodSyncMock.mockClear() - // Coarse-ctime filesystems can report identical timestamps after chmod; only mode changes. - state.dirMode = 0o755 - - hardenExistingSecureFile(paths.file) - - expect(chmodSyncMock.mock.calls).toEqual([[paths.dir, 0o700]]) - }) - - it('re-hardens a file when only POSIX mode changes under stable timestamps', () => { - hardenExistingSecureFile(paths.file) - expect(chmodSyncMock.mock.calls).toEqual([ - [paths.dir, 0o700], - [paths.file, 0o600] - ]) - - chmodSyncMock.mockClear() - // Coarse-ctime filesystems can report identical timestamps after chmod; only mode changes. - state.fileMode = 0o644 - - hardenExistingSecureFile(paths.file) - - expect(chmodSyncMock.mock.calls).toEqual([[paths.file, 0o600]]) - }) -}) - -function fakeStats(isDirectory: boolean, mode: number) { - return { - birthtimeMs: 10, - ctimeMs: 20, - dev: 30, - ino: isDirectory ? 40 : 41, - isDirectory: () => isDirectory, - mode, - mtimeMs: 50, - size: isDirectory ? 0 : 2 - } -} diff --git a/src/shared/secure-file-fsync-flags.test.ts b/src/shared/secure-file-fsync-flags.test.ts deleted file mode 100644 index 9d2bbe7cd9f..00000000000 --- a/src/shared/secure-file-fsync-flags.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { chmodSync, mkdtempSync, statSync, writeFileSync } from 'node:fs' -import { removeTreeSync } from './windows-transient-lock-removal' -import type * as NodeFs from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' - -const openedPaths = vi.hoisted( - () => [] as { path: string; flags: string | number; ownerWritable: boolean }[] -) - -vi.mock('node:fs', async () => { - const actual = await vi.importActual('node:fs') - return { - ...actual, - openSync: (path: NodeFs.PathLike, flags: string | number, mode?: NodeFs.Mode) => { - openedPaths.push({ - path: String(path), - flags, - ownerWritable: Boolean(actual.statSync(path).mode & 0o200) - }) - return actual.openSync(path, flags, mode) - } - } -}) - -import { fsyncFileSync, writeDurableSecureJsonFile } from './secure-file' - -const createdPaths: string[] = [] - -afterEach(() => { - openedPaths.length = 0 - for (const path of createdPaths.splice(0)) { - removeTreeSync(path) - } -}) - -describe('secure file fsync flags', () => { - const windowsIt = process.platform === 'win32' ? it : it.skip - windowsIt('opens files read/write before fsync on Windows', () => { - const directory = mkdtempSync(join(tmpdir(), 'orca-file-fsync-')) - createdPaths.push(directory) - const path = join(directory, 'record.json') - writeFileSync(path, '{}') - - fsyncFileSync(path) - - expect(openedPaths).toMatchObject([{ path, flags: 'r+' }]) - }) - - const posixIt = process.platform === 'win32' ? it.skip : it - posixIt('fsyncs files without owner-write permission', () => { - const directory = mkdtempSync(join(tmpdir(), 'orca-file-fsync-read-only-')) - createdPaths.push(directory) - const path = join(directory, 'record.json') - writeFileSync(path, '{}') - chmodSync(path, 0o400) - - expect(() => fsyncFileSync(path)).not.toThrow() - expect(openedPaths).toEqual([{ path, flags: 'r', ownerWritable: false }]) - }) - - posixIt('durably writes when umask removes owner-write from the temporary file', () => { - const directory = mkdtempSync(join(tmpdir(), 'orca-durable-file-fsync-read-only-')) - createdPaths.push(directory) - const path = join(directory, 'record.json') - const originalUmask = process.umask(0o200) - - try { - expect(() => writeDurableSecureJsonFile(path, { ok: true })).not.toThrow() - } finally { - process.umask(originalUmask) - } - - // chmod precedes fsync; require a read-only fsync handle and published mode exactly 0o600. - expect(openedPaths[0]).toMatchObject({ flags: 'r' }) - expect(openedPaths[0]?.path).toMatch(/record\.json\.\d+\.\d+\.[0-9a-f]+\.tmp$/) - expect(statSync(path).mode & 0o777).toBe(0o600) - }) -}) diff --git a/src/shared/secure-file-windows.test.ts b/src/shared/secure-file-windows.test.ts deleted file mode 100644 index 9744f0ac15f..00000000000 --- a/src/shared/secure-file-windows.test.ts +++ /dev/null @@ -1,283 +0,0 @@ -import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { runProcess, runProcessSync } from '@orca/process-host' -import { - __getSecureFileHardeningCacheStateForTests, - __resetSecureFileHardenedPathsForTests, - hardenExistingSecureFile, - writeSecureFile -} from './secure-file' -import { mayAttemptHardening } from './secure-path-hardening-retry-budget' -import { - setSecurePathHardeningReporter, - type SecurePathHardeningReport -} from './secure-path-hardening-report' -import { - loadWindowsSecurity, - resetWindowsSecurityLoadForTests, - setWindowsSecurityForTests -} from './windows-security-addon' -import { - createFakeWindowsSecurity, - FAKE_USER_SID, - type FakeWindowsSecurity -} from './windows-security-addon.test-fixture' - -vi.mock('@orca/process-host', () => ({ - runProcess: vi.fn(), - runProcessSync: vi.fn() -})) - -const FILE_SDDL = `D:P(A;;FA;;;S-1-5-18)(A;;FA;;;S-1-5-32-544)(A;;FA;;;${FAKE_USER_SID})` -const DIRECTORY_SDDL = `D:P(A;OICI;FA;;;S-1-5-18)(A;OICI;FA;;;S-1-5-32-544)(A;OICI;FA;;;${FAKE_USER_SID})` -/** What the icacls-era hardening left on disk; it must keep verifying with no rewrite. */ -const ICACLS_ERA_FILE_SDDL = `D:PAI(A;;FA;;;BA)(A;;FA;;;SY)(A;;FA;;;${FAKE_USER_SID})` -const ICACLS_ERA_DIRECTORY_SDDL = `D:PAI(A;OICI;FA;;;BA)(A;OICI;FA;;;SY)(A;OICI;FA;;;${FAKE_USER_SID})` - -describe('Windows secure files through the native ACL addon', () => { - const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') - const tempDirs: string[] = [] - let fake: FakeWindowsSecurity - let reports: SecurePathHardeningReport[] - - beforeEach(() => { - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - resetWindowsSecurityLoadForTests() - __resetSecureFileHardenedPathsForTests() - fake = createFakeWindowsSecurity() - setWindowsSecurityForTests(fake) - reports = [] - setSecurePathHardeningReporter((entry) => reports.push(entry)) - vi.mocked(runProcess).mockReset() - vi.mocked(runProcessSync).mockReset() - }) - - afterEach(() => { - // The whole point of #25583 and #26027: no ACL work may start a process. - expect(runProcess).not.toHaveBeenCalled() - expect(runProcessSync).not.toHaveBeenCalled() - setSecurePathHardeningReporter(null) - setWindowsSecurityForTests(null) - resetWindowsSecurityLoadForTests() - __resetSecureFileHardenedPathsForTests() - if (originalPlatform) { - Object.defineProperty(process, 'platform', originalPlatform) - } - for (const dir of tempDirs.splice(0)) { - rmSync(dir, { recursive: true, force: true }) - } - }) - - function tempDir(): string { - const dir = mkdtempSync(join(tmpdir(), 'orca-secure-file-win-')) - tempDirs.push(dir) - return dir - } - - async function settle(): Promise { - for (let i = 0; i < 4; i++) { - await new Promise((resolve) => setTimeout(resolve, 0)) - } - } - - describe('write path', () => { - it('creates the credential already restricted and publishes it without touching its ACL', () => { - const dir = tempDir() - const targetPath = join(dir, 'secret.json') - - expect(writeSecureFile(targetPath, 'contents')).toBe(true) - - const [create] = fake.callsFor('create') - expect(create?.path).toMatch(/secret\.json\.\d+\.\d+\.[0-9a-f]+\.tmp$/) - expect(create && 'sddl' in create ? create.sddl : '').toBe(FILE_SDDL) - expect(readFileSync(targetPath, 'utf-8')).toBe('contents') - // Restricted at creation, so neither temp nor published file needs a later ACL rewrite. - expect(fake.callsFor('set')).toEqual([]) - expect(fake.calls.some((call) => call.path === targetPath)).toBe(false) - }) - - it('reports false but still writes when the addon cannot load, and says so once', () => { - setWindowsSecurityForTests(null) - const dir = tempDir() - - for (const name of ['a.json', 'b.json', 'c.json']) { - expect(writeSecureFile(join(dir, name), name)).toBe(false) - expect(readFileSync(join(dir, name), 'utf-8')).toBe(name) - } - expect(reports.filter((entry) => entry.stage === 'addon')).toHaveLength(1) - }) - - it('throws a failed restricted create and leaves no temp file', () => { - const dir = tempDir() - const targetPath = join(dir, 'secret.json') - writeFileSync(targetPath, 'previous') - fake.createFileWithDacl = () => { - throw new Error('CreateFileW failed with Win32 error 5') - } - - expect(() => writeSecureFile(targetPath, 'contents')).toThrow( - 'CreateFileW failed with Win32 error 5' - ) - - expect(readFileSync(targetPath, 'utf-8')).toBe('previous') - expect(readdirSync(dir).filter((name) => name.endsWith('.tmp'))).toEqual([]) - }) - - it('reports false when the filesystem drops the descriptor (FAT32, some shares)', () => { - const dir = tempDir() - const targetPath = join(dir, 'secret.json') - const realCreate = fake.createFileWithDacl - fake.createFileWithDacl = (path, sddl, data) => { - realCreate(path, sddl, data) - const created = fake.callsFor('create').at(-1)?.path ?? path - fake.dacls.set(created, 'D:NO_ACCESS_CONTROL') - } - - expect(writeSecureFile(targetPath, 'contents')).toBe(false) - - expect(reports).toContainEqual( - expect.objectContaining({ stage: 'verify', detail: expect.stringContaining('NULL DACL') }) - ) - }) - - it('clears the read-path backoff once a write restricts the same path', () => { - const dir = tempDir() - const targetPath = join(dir, 'secret.json') - writeFileSync(targetPath, '{}') - fake.failing.add(targetPath) - let clock = performance.now() - const now = vi.spyOn(performance, 'now').mockImplementation(() => clock) - for (const wait of [0, 61_000, 121_000]) { - clock += wait - hardenExistingSecureFile(targetPath) - } - expect(mayAttemptHardening(targetPath)).toBe(false) - - fake.failing.delete(targetPath) - expect(writeSecureFile(targetPath, 'contents')).toBe(true) - - expect(mayAttemptHardening(targetPath)).toBe(true) - expect(reports).toContainEqual(expect.objectContaining({ targetPath, stage: 'recovered' })) - now.mockRestore() - }) - }) - - describe('directory relock', () => { - it('never rewrites a directory the icacls-era hardening already locked', async () => { - const dir = tempDir() - fake.dacls.set(dir, ICACLS_ERA_DIRECTORY_SDDL) - - writeSecureFile(join(dir, 'secret.json'), 'contents') - await settle() - - expect(fake.callsFor('setAsync')).toEqual([]) - }) - - // Directory relock walks every descendant (~2s for 29k entries); writes cannot wait for it. - it('neither blocks a write nor starts twice while a slow relock is still running', async () => { - fake.holdAsync = true - const dir = tempDir() - - for (let i = 0; i < 3; i++) { - expect(writeSecureFile(join(dir, `secret-${i}.json`), 'contents')).toBe(true) - expect(readFileSync(join(dir, `secret-${i}.json`), 'utf-8')).toBe('contents') - } - await settle() - expect(fake.callsFor('setAsync', dir)).toHaveLength(1) - - fake.releaseAsync() - await settle() - writeSecureFile(join(dir, 'later.json'), 'contents') - await settle() - expect(fake.callsFor('setAsync', dir)).toHaveLength(1) - expect(fake.dacls.get(dir)).toBe(DIRECTORY_SDDL) - }) - - it('retries a failed relock only after its backoff, not on every write', async () => { - const dir = tempDir() - fake.failing.add(dir) - let clock = performance.now() - const now = vi.spyOn(performance, 'now').mockImplementation(() => clock) - - writeSecureFile(join(dir, 'a.json'), 'a') - await settle() - writeSecureFile(join(dir, 'b.json'), 'b') - await settle() - expect(fake.callsFor('setAsync', dir)).toHaveLength(1) - - clock += 61_000 - fake.failing.delete(dir) - writeSecureFile(join(dir, 'c.json'), 'c') - await settle() - expect(fake.callsFor('setAsync', dir)).toHaveLength(2) - expect(reports).toContainEqual(expect.objectContaining({ targetPath: dir, stage: 'apply' })) - now.mockRestore() - }) - }) - - describe('read path', () => { - function existingFile(): { dir: string; targetPath: string } { - const dir = tempDir() - const targetPath = join(dir, 'secret.json') - writeFileSync(targetPath, '{}') - return { dir, targetPath } - } - - it('fixes an inherited-ACL file in-process, synchronously, once while it is unchanged', () => { - const { targetPath } = existingFile() - - for (let i = 0; i < 3; i++) { - hardenExistingSecureFile(targetPath) - } - - expect(fake.callsFor('set', targetPath)).toEqual([ - expect.objectContaining({ op: 'set', path: targetPath, sddl: FILE_SDDL }) - ]) - expect(fake.callsFor('setAsync', targetPath)).toEqual([]) - }) - - it('leaves a file the icacls-era hardening locked exactly as it is', () => { - const { targetPath } = existingFile() - fake.dacls.set(targetPath, ICACLS_ERA_FILE_SDDL) - - hardenExistingSecureFile(targetPath) - - expect(fake.callsFor('set', targetPath)).toEqual([]) - expect(fake.dacls.get(targetPath)).toBe(ICACLS_ERA_FILE_SDDL) - }) - - it('rewrites a protected DACL that grants a stranger', () => { - const { targetPath } = existingFile() - fake.dacls.set(targetPath, 'D:PAI(A;;FA;;;BA)(A;;FA;;;SY)(A;;FA;;;WD)') - - hardenExistingSecureFile(targetPath) - - expect(fake.dacls.get(targetPath)).toBe(FILE_SDDL) - }) - }) - - // Serialize grant merges with relock or a stale broad DACL could be restored. - it('runs async DACL writes to the same path one after another', async () => { - const loaded = loadWindowsSecurity() - if ('error' in loaded) { - throw new Error('fake not installed') - } - fake.holdAsync = true - const order: string[] = [] - const relock = loaded.addon - .setDaclSddlAsync('C:\\Orca', 'D:P(A;OICI;FA;;;SY)') - .then(() => order.push('relock')) - const grant = loaded.addon - .grantAccessAsync('c:\\orca', FAKE_USER_SID, 0x1f01ff, { inheritable: true, replace: true }) - .then(() => order.push('grant')) - await settle() - - // The grant waits for the parked re-lock on the same path, whatever its letter case. - expect(fake.callsFor('grantAsync')).toEqual([]) - fake.releaseAsync() - await Promise.all([relock, grant]) - expect(order).toEqual(['relock', 'grant']) - }) -}) diff --git a/src/shared/secure-path-hardening-retry-budget.test.ts b/src/shared/secure-path-hardening-retry-budget.test.ts deleted file mode 100644 index cf90de30454..00000000000 --- a/src/shared/secure-path-hardening-retry-budget.test.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - configureHardeningRetryBudget, - mayAttemptHardening, - recordHardeningOutcome -} from './secure-path-hardening-retry-budget' -import { - setSecurePathHardeningReporter, - type SecurePathHardeningReport -} from './secure-path-hardening-report' - -const PATH = 'C:\\Users\\me\\.orca\\secret.json' -const OTHER = 'C:\\Users\\me\\.orca\\other.json' -const MINUTE = 60_000 - -describe('secure path hardening retry budget', () => { - /** Elapsed monotonic time, which is what the budget measures. */ - let clock = 0 - /** The wall clock, which it must not measure: it steps backwards on real machines. */ - let wallClock = 0 - let reports: SecurePathHardeningReport[] = [] - - beforeEach(() => { - clock = 1_000_000 - wallClock = Date.parse('2026-01-01T00:00:00Z') - vi.spyOn(performance, 'now').mockImplementation(() => clock) - vi.spyOn(Date, 'now').mockImplementation(() => wallClock) - reports = [] - setSecurePathHardeningReporter((entry) => reports.push(entry)) - configureHardeningRetryBudget({ - maxEntries: 64, - maxKeyBytes: 4096, - maxTotalKeyBytes: 65_536 - }) - }) - - afterEach(() => { - setSecurePathHardeningReporter(null) - vi.restoreAllMocks() - }) - - /** Drives the loop the read path drives: attempt when allowed, record the failure, advance. */ - function pollUntil(elapsedMs: number, stepMs: number, restricted = false): number[] { - const attemptedAt: number[] = [] - const startedAt = clock - while (clock - startedAt <= elapsedMs) { - if (mayAttemptHardening(PATH)) { - attemptedAt.push(clock - startedAt) - recordHardeningOutcome(PATH, restricted) - } - clock += stepMs - wallClock += stepMs - } - return attemptedAt - } - - it('re-probes on the documented curve rather than on every read', () => { - // Six hours of polling every 30s: 720 reads, and only the backoff decides how many run. - const attemptedAt = pollUntil(6 * 60 * MINUTE, 30_000) - - expect(attemptedAt.slice(0, 6).map((ms) => ms / MINUTE)).toEqual([0, 1, 3, 7, 15, 31]) - const trailingGaps = attemptedAt - .slice(-4) - .map((ms, index, all) => (all[index + 1]! - ms) / MINUTE) - expect(trailingGaps.slice(0, -1)).toEqual([30, 30, 30]) - }) - - /** Backwards wall-clock steps previously held paths below retry delay until time caught up; monotonic elapsed time must keep probing. */ - it('re-probes after a backwards clock step rather than waiting for the wall clock', () => { - pollUntil(6 * 60 * MINUTE, 30_000) - - wallClock -= 365 * 24 * 60 * MINUTE - clock += 31 * MINUTE - - expect(mayAttemptHardening(PATH)).toBe(true) - }) - - it('announces recovery when a throttled path hardens again, and resets the curve', () => { - pollUntil(10 * MINUTE, 30_000) - expect(reports.filter((entry) => entry.stage === 'throttled')).toHaveLength(1) - - recordHardeningOutcome(PATH, true) - - expect(reports.filter((entry) => entry.stage === 'recovered')).toMatchObject([ - { targetPath: PATH, stage: 'recovered' } - ]) - // Record cleared: the next failure starts at the floor rather than the ceiling. - expect(mayAttemptHardening(PATH)).toBe(true) - recordHardeningOutcome(PATH, false) - clock += 59_000 - expect(mayAttemptHardening(PATH)).toBe(false) - clock += 2_000 - expect(mayAttemptHardening(PATH)).toBe(true) - }) - - it('budgets each path separately', () => { - recordHardeningOutcome(PATH, false) - - expect(mayAttemptHardening(PATH)).toBe(false) - expect(mayAttemptHardening(OTHER)).toBe(true) - }) - - /** A second importer may have no configuration; throwing there made async hardening crash main. - * Import only the budget so secure-file cannot hide the missing defaults. */ - it('defaults its bounds when nothing configured it', async () => { - vi.resetModules() - const budget = await import('./secure-path-hardening-retry-budget.js') - - expect(budget.mayAttemptHardening(PATH)).toBe(true) - expect(() => budget.recordHardeningOutcome(PATH, false)).not.toThrow() - expect(budget.mayAttemptHardening(PATH)).toBe(false) - expect(budget.mayAttemptHardening(OTHER)).toBe(true) - }) -}) diff --git a/src/shared/secure-path-windows-acl.win32.test.ts b/src/shared/secure-path-windows-acl.win32.test.ts deleted file mode 100644 index 33ad334ad5c..00000000000 --- a/src/shared/secure-path-windows-acl.win32.test.ts +++ /dev/null @@ -1,338 +0,0 @@ -import { - lstatSync, - mkdirSync, - mkdtempSync, - readdirSync, - readFileSync, - writeFileSync -} from 'node:fs' -import { randomBytes } from 'node:crypto' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { Worker } from 'node:worker_threads' -import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest' -import { __resetSecureFileHardenedPathsForTests, writeSecureFile } from './secure-file' -import { - setSecurePathHardeningReporter, - type SecurePathHardeningReport -} from './secure-path-hardening-report' -import { restrictWindowsPathSync } from './secure-path-windows-acl' -import { - loadWindowsSecurity, - resetWindowsSecurityLoadForTests, - setWindowsSecurityForTests, - type WindowsSecurity -} from './windows-security-addon' -import { - CONTAINER_INHERIT_ACE, - findSecureDaclViolation, - OBJECT_INHERIT_ACE -} from './windows-secure-dacl' -import { removeTreeSync } from './windows-transient-lock-removal' - -/** Real NTFS read-back covers what fake addons cannot: relocated C:\ roots inheriting broad Modify access. Windows only. */ -const describeOnWindows = process.platform === 'win32' ? describe : describe.skip - -describeOnWindows('Windows secure paths against a real filesystem', () => { - let addon: WindowsSecurity['addon'] - let sid: string - let root: string - /** A relocated data root: `C:\orca-…` inherits BUILTIN\Users and Authenticated Users from C:\. */ - let relocatedRoot: string - - const daclOf = (path: string) => addon.getDaclAces(path) - const sidsOf = (path: string) => (daclOf(path)?.aces ?? []).map((ace) => ace.sid).sort() - const INHERITABLE = OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE - const INHERITED_ACE = 0x10 - const ORCA_PRINCIPALS = () => ['S-1-5-18', 'S-1-5-32-544', sid].sort() - - beforeAll(() => { - const loaded = loadWindowsSecurity() - if ('error' in loaded) { - throw new Error(`the windows-security addon did not load: ${loaded.error}`) - } - addon = loaded.addon - sid = loaded.userSid - root = mkdtempSync(join(tmpdir(), 'orca-acl-win32-')) - relocatedRoot = join('C:\\', `orca-acl-test-${randomBytes(4).toString('hex')}`) - mkdirSync(relocatedRoot) - }) - - afterEach(() => { - resetWindowsSecurityLoadForTests() - __resetSecureFileHardenedPathsForTests() - setSecurePathHardeningReporter(null) - }) - - afterAll(() => { - // Hostile DACL fixtures may become undeletable if repair regresses; restore this user’s access before cleanup. - for (const tree of [root, relocatedRoot]) { - unlockTree(tree) - removeTreeSync(tree) - } - }) - - function unlockTree(path: string): void { - try { - addon.setDaclSddl(path, `D:P(A;OICI;FA;;;${sid})`) - } catch { - return - } - if (lstatSync(path).isDirectory()) { - for (const name of readdirSync(path)) { - unlockTree(join(path, name)) - } - } - } - - it('restricts a real file, dropping inherited and planted foreign rules', () => { - const file = join(relocatedRoot, 'credential.json') - writeFileSync(file, '{"token":"secret"}') - addon.grantAccess(file, 'S-1-1-0', 0x120089, { inheritable: false, replace: false }) - expect(sidsOf(file)).toContain('S-1-1-0') - - expect(restrictWindowsPathSync(file, false)).toBe(true) - - expect(daclOf(file)?.protected).toBe(true) - expect(sidsOf(file)).toEqual(ORCA_PRINCIPALS()) - }) - - it('gives a directory inheritable rules so files created inside start restricted', () => { - const dir = join(relocatedRoot, 'secure-dir') - mkdirSync(dir) - - expect(restrictWindowsPathSync(dir, true)).toBe(true) - - expect(daclOf(dir)?.aces.every((ace) => ace.flags === INHERITABLE)).toBe(true) - const child = join(dir, 'plain.json') - writeFileSync(child, '{}') - expect(sidsOf(child)).toEqual(ORCA_PRINCIPALS()) - expect(daclOf(child)?.aces.every((ace) => (ace.flags & INHERITED_ACE) !== 0)).toBe(true) - }) - - it.each([ - ['(OI) without (CI), leaving subdirectories unprotected', 'OI'], - ['(OI)(CI)(IO), which grants nobody anything on the directory itself', 'OICIIO'] - ])('repairs a directory whose rules are %s', (_label, flags) => { - const dir = join(root, `wrong-flags-${flags}`) - mkdirSync(dir) - addon.setDaclSddl(dir, `D:P(A;${flags};FA;;;SY)(A;${flags};FA;;;BA)(A;${flags};FA;;;${sid})`) - - expect(restrictWindowsPathSync(dir, true)).toBe(true) - - expect(daclOf(dir)?.aces.every((ace) => ace.flags === INHERITABLE)).toBe(true) - expect(() => writeFileSync(join(dir, 'child.json'), '{}')).not.toThrow() - }) - - it('repairs a protected three-rule DACL that grants the wrong principal', () => { - const file = join(root, 'substituted.json') - writeFileSync(file, '{}') - addon.setDaclSddl(file, 'D:P(A;;FA;;;WD)(A;;FA;;;SY)(A;;FA;;;BA)') - - expect(restrictWindowsPathSync(file, false)).toBe(true) - - expect(sidsOf(file)).toEqual(ORCA_PRINCIPALS()) - }) - - it('never rewrites a path the icacls-era hardening already locked', () => { - const file = join(root, 'icacls-era.json') - writeFileSync(file, '{}') - addon.setDaclSddl(file, `D:PAI(A;;FA;;;BA)(A;;FA;;;SY)(A;;FA;;;${sid})`) - const before = addon.getDaclAces(file) - const writes = countingAddon() - - expect(restrictWindowsPathSync(file, false)).toBe(true) - - expect(writes.count).toBe(0) - expect(addon.getDaclAces(file)).toEqual(before) - }) - - it.each([ - ['spaces', 'a b c'], - ['single quote and dollar', "quo'te $var"], - ['backtick', 'back`tick'], - ['semicolon and ampersand', 'semi;colon & amp'], - ['caret and percent', 'car^et %PATH%'], - ['non-ASCII', 'résumé 資料'] - ])('hardens a path containing %s', (_label, segment) => { - const dir = join(root, segment) - mkdirSync(dir, { recursive: true }) - const file = join(dir, 'secret.json') - writeFileSync(file, '{}') - - expect(restrictWindowsPathSync(file, false)).toBe(true) - expect(sidsOf(file)).toEqual(ORCA_PRINCIPALS()) - }) - - it('hardens a path longer than MAX_PATH', () => { - let dir = join(root, 'long') - while (dir.length < 280) { - dir = join(dir, 'x'.repeat(40)) - } - mkdirSync(dir, { recursive: true }) - const file = join(dir, 'secret.json') - writeFileSync(file, '{}') - - expect(restrictWindowsPathSync(file, false)).toBe(true) - expect(sidsOf(`\\\\?\\${file}`)).toEqual(ORCA_PRINCIPALS()) - }) - - it('reports failure, not success, for a path that does not exist', () => { - const reports: SecurePathHardeningReport[] = [] - setSecurePathHardeningReporter((entry) => reports.push(entry)) - - expect(restrictWindowsPathSync(join(root, 'missing.json'), false)).toBe(false) - expect(reports).toContainEqual(expect.objectContaining({ stage: 'apply' })) - }) - - it('keeps hardening alive when the installed reporter throws', () => { - setSecurePathHardeningReporter(() => { - throw new Error('caller bug') - }) - - expect(restrictWindowsPathSync(join(root, 'missing-reporter.json'), false)).toBe(false) - }) - - it('never exposes a staged or published credential under the relocated root', async () => { - const dir = join(relocatedRoot, 'race') - mkdirSync(dir) - const target = join(dir, 'orca-e2ee-keypair.json') - const observer = observeDacls(dir, 1500) - await observer.ready - - let restricted = 0 - const startedAt = performance.now() - while (performance.now() - startedAt < 1000) { - try { - restricted += writeSecureFile(target, JSON.stringify({ secretKey: 'x'.repeat(64) })) ? 1 : 0 - } catch (error) { - // The observer's own open handle can make a replace-rename fail; that is the racer, not us. - expect(error).toMatchObject({ code: 'EPERM', syscall: 'rename' }) - } - } - const observed = await observer.result - - expect(restricted).toBeGreaterThan(50) - expect(observed.samples).toBeGreaterThan(50) - const broad = Object.keys(observed.distinct).filter( - (dacl) => findSecureDaclViolation(JSON.parse(dacl), sid, false) !== null - ) - console.log( - `[live-acl] ${restricted} writes, ${observed.samples} DACL samples, ` + - `${Object.keys(observed.distinct).length} distinct, ${broad.length} broad` - ) - expect(broad).toEqual([]) - expect(daclOf(target)?.protected).toBe(true) - }) - - // Directory relock must stay off the write path and run once; allow its 60s wait plus 4,000 creates beyond the default timeout. - it('relocks a large relocated directory off the write path, exactly once', async () => { - const dir = join(relocatedRoot, 'large') - mkdirSync(dir) - for (let index = 0; index < 4000; index++) { - writeFileSync(join(dir, `cache-${index}`), 'x') - } - const writes = countingAddon() - - const writeStartedAt = performance.now() - expect(writeSecureFile(join(dir, 'secret.json'), '{}')).toBe(true) - const writeMs = performance.now() - writeStartedAt - writeSecureFile(join(dir, 'second.json'), '{}') - - const relockStartedAt = performance.now() - // The parent turns protected before propagation reaches its children, so wait on both ends. - await vi.waitFor( - () => { - expect(daclOf(dir)?.protected).toBe(true) - expect(sidsOf(join(dir, 'cache-0'))).toEqual(ORCA_PRINCIPALS()) - expect(sidsOf(join(dir, 'cache-3999'))).toEqual(ORCA_PRINCIPALS()) - }, - { timeout: 60_000, interval: 20 } - ) - const relockMs = performance.now() - relockStartedAt + writeMs - console.log( - `[live-acl] write ${writeMs.toFixed(1)}ms while relock of 4000 entries ~${relockMs.toFixed(0)}ms` - ) - - expect(writes.asyncCount).toBe(1) - - // A new process finds the directory already locked and leaves it alone. - __resetSecureFileHardenedPathsForTests() - const nextLaunch = countingAddon() - writeSecureFile(join(dir, 'third.json'), '{}') - await new Promise((resolve) => setTimeout(resolve, 50)) - expect(nextLaunch.asyncCount + nextLaunch.count).toBe(0) - expect(readFileSync(join(dir, 'third.json'), 'utf-8')).toBe('{}') - }, 90_000) - - /** Installs the real addon behind a proxy that counts DACL rewrites. */ - function countingAddon(): { count: number; asyncCount: number } { - const counts = { count: 0, asyncCount: 0 } - setWindowsSecurityForTests({ - ...addon, - currentUserSid: () => sid, - setDaclSddl: (path, sddl) => { - counts.count += 1 - addon.setDaclSddl(path, sddl) - }, - setDaclSddlAsync: (path, sddl) => { - counts.asyncCount += 1 - return addon.setDaclSddlAsync(path, sddl) - } - }) - return counts - } -}) - -type ObservedDacls = { samples: number; distinct: Record } - -function observeDacls( - dir: string, - durationMs: number -): { ready: Promise; result: Promise } { - const worker = new Worker( - ` - const { parentPort, workerData } = require('node:worker_threads') - const { readdirSync } = require('node:fs') - const { join } = require('node:path') - const addon = require(workerData.addonPath) - parentPort.postMessage('ready') - const distinct = {} - let samples = 0 - const deadline = Date.now() + workerData.durationMs - while (Date.now() < deadline) { - let names = [] - try { names = readdirSync(workerData.dir) } catch {} - for (const name of names) { - try { - const sddl = JSON.stringify(addon.getDaclAces(join(workerData.dir, name))) - samples += 1 - distinct[sddl] = (distinct[sddl] || 0) + 1 - } catch {} - } - } - parentPort.postMessage({ samples, distinct }) - `, - { - eval: true, - workerData: { dir, durationMs, addonPath: require.resolve('@orca/windows-security') } - } - ) - let markReady: () => void = () => undefined - const ready = new Promise((resolve) => { - markReady = resolve - }) - const result = new Promise((resolve, reject) => { - worker.on('message', (message: unknown) => { - if (message === 'ready') { - markReady() - return - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the worker above posts exactly this shape after 'ready'. - resolve(message as ObservedDacls) - void worker.terminate() - }) - worker.on('error', reject) - }) - return { ready, result } -} diff --git a/src/shared/bounded-secure-json-file.ts b/src/shared/secure-storage/bounded-secure-json-file.ts similarity index 77% rename from src/shared/bounded-secure-json-file.ts rename to src/shared/secure-storage/bounded-secure-json-file.ts index 75f048b3480..085354ab1d3 100644 --- a/src/shared/bounded-secure-json-file.ts +++ b/src/shared/secure-storage/bounded-secure-json-file.ts @@ -1,4 +1,4 @@ -import { stringifyJsonWithinByteLimit } from './node-bounded-json-stringify' +import { stringifyJsonWithinByteLimit } from '../json-stream/node-bounded-json-stringify' import { writeSecureFile } from './secure-file' export function writeSecureJsonFileWithinLimit( diff --git a/src/shared/secure-storage/secure-file-windows.test.ts b/src/shared/secure-storage/secure-file-windows.test.ts new file mode 100644 index 00000000000..cc527b26088 --- /dev/null +++ b/src/shared/secure-storage/secure-file-windows.test.ts @@ -0,0 +1,65 @@ +import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' + +import { __resetSecureFileHardenedPathsForTests, writeSecureFile } from './secure-file' + +import { + resetWindowsSecurityLoadForTests, + setWindowsSecurityForTests +} from '../windows-security-addon' +import { + createFakeWindowsSecurity, + type FakeWindowsSecurity +} from '../windows-security-addon.test-fixture' + +describe('Windows secure files through the native ACL addon', () => { + const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') + const tempDirs: string[] = [] + let fake: FakeWindowsSecurity + + beforeEach(() => { + Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) + resetWindowsSecurityLoadForTests() + __resetSecureFileHardenedPathsForTests() + fake = createFakeWindowsSecurity() + setWindowsSecurityForTests(fake) + }) + + afterEach(() => { + setWindowsSecurityForTests(null) + resetWindowsSecurityLoadForTests() + __resetSecureFileHardenedPathsForTests() + if (originalPlatform) { + Object.defineProperty(process, 'platform', originalPlatform) + } + for (const dir of tempDirs.splice(0)) { + rmSync(dir, { recursive: true, force: true }) + } + }) + + function tempDir(): string { + const dir = mkdtempSync(join(tmpdir(), 'orca-secure-file-win-')) + tempDirs.push(dir) + return dir + } + + describe('write path', () => { + it('throws a failed restricted create and leaves no temp file', () => { + const dir = tempDir() + const targetPath = join(dir, 'secret.json') + writeFileSync(targetPath, 'previous') + fake.createFileWithDacl = () => { + throw new Error('CreateFileW failed with Win32 error 5') + } + + expect(() => writeSecureFile(targetPath, 'contents')).toThrow( + 'CreateFileW failed with Win32 error 5' + ) + + expect(readFileSync(targetPath, 'utf-8')).toBe('previous') + expect(readdirSync(dir).filter((name) => name.endsWith('.tmp'))).toEqual([]) + }) + }) +}) diff --git a/src/shared/secure-file.test.ts b/src/shared/secure-storage/secure-file.test.ts similarity index 98% rename from src/shared/secure-file.test.ts rename to src/shared/secure-storage/secure-file.test.ts index 9b83d9fc288..f87b1d1546b 100644 --- a/src/shared/secure-file.test.ts +++ b/src/shared/secure-storage/secure-file.test.ts @@ -11,7 +11,7 @@ import { import { setWindowsSecurityForTests, resetWindowsSecurityLoadForTests -} from './windows-security-addon' +} from '../windows-security-addon' const chmodFailure = vi.hoisted((): { code: string | null } => ({ code: null })) diff --git a/src/shared/secure-file.ts b/src/shared/secure-storage/secure-file.ts similarity index 100% rename from src/shared/secure-file.ts rename to src/shared/secure-storage/secure-file.ts diff --git a/src/shared/secure-path-hardening-cache.ts b/src/shared/secure-storage/secure-path-hardening-cache.ts similarity index 100% rename from src/shared/secure-path-hardening-cache.ts rename to src/shared/secure-storage/secure-path-hardening-cache.ts diff --git a/src/shared/secure-path-hardening-report.ts b/src/shared/secure-storage/secure-path-hardening-report.ts similarity index 100% rename from src/shared/secure-path-hardening-report.ts rename to src/shared/secure-storage/secure-path-hardening-report.ts diff --git a/src/shared/secure-storage/secure-path-hardening-retry-budget.test.ts b/src/shared/secure-storage/secure-path-hardening-retry-budget.test.ts new file mode 100644 index 00000000000..2707e397015 --- /dev/null +++ b/src/shared/secure-storage/secure-path-hardening-retry-budget.test.ts @@ -0,0 +1,42 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + configureHardeningRetryBudget, + mayAttemptHardening, + recordHardeningOutcome +} from './secure-path-hardening-retry-budget' + +const PATH = 'C:\\Users\\me\\.orca\\secret.json' +const OTHER = 'C:\\Users\\me\\.orca\\other.json' + +describe('secure path hardening retry budget', () => { + beforeEach(() => { + configureHardeningRetryBudget({ + maxEntries: 64, + maxKeyBytes: 4096, + maxTotalKeyBytes: 65_536 + }) + }) + + afterEach(() => { + vi.restoreAllMocks() + }) + + it('budgets each path separately', () => { + recordHardeningOutcome(PATH, false) + + expect(mayAttemptHardening(PATH)).toBe(false) + expect(mayAttemptHardening(OTHER)).toBe(true) + }) + + /** A second importer may have no configuration; throwing there made async hardening crash main. + * Import only the budget so secure-file cannot hide the missing defaults. */ + it('defaults its bounds when nothing configured it', async () => { + vi.resetModules() + const budget = await import('./secure-path-hardening-retry-budget.js') + + expect(budget.mayAttemptHardening(PATH)).toBe(true) + expect(() => budget.recordHardeningOutcome(PATH, false)).not.toThrow() + expect(budget.mayAttemptHardening(PATH)).toBe(false) + expect(budget.mayAttemptHardening(OTHER)).toBe(true) + }) +}) diff --git a/src/shared/secure-path-hardening-retry-budget.ts b/src/shared/secure-storage/secure-path-hardening-retry-budget.ts similarity index 100% rename from src/shared/secure-path-hardening-retry-budget.ts rename to src/shared/secure-storage/secure-path-hardening-retry-budget.ts diff --git a/src/shared/secure-path-metadata-snapshot.ts b/src/shared/secure-storage/secure-path-metadata-snapshot.ts similarity index 100% rename from src/shared/secure-path-metadata-snapshot.ts rename to src/shared/secure-storage/secure-path-metadata-snapshot.ts diff --git a/src/shared/secure-path-windows-acl.ts b/src/shared/secure-storage/secure-path-windows-acl.ts similarity index 97% rename from src/shared/secure-path-windows-acl.ts rename to src/shared/secure-storage/secure-path-windows-acl.ts index 1962373a1b2..99de032d649 100644 --- a/src/shared/secure-path-windows-acl.ts +++ b/src/shared/secure-storage/secure-path-windows-acl.ts @@ -1,11 +1,11 @@ import { writeFileSync } from 'node:fs' import { reportSecurePathHardening as report } from './secure-path-hardening-report' -import { loadWindowsSecurity, type WindowsSecurity } from './windows-security-addon' +import { loadWindowsSecurity, type WindowsSecurity } from '../windows-security-addon' import { findPrivateDaclViolation, findSecureDaclViolation, hardenedDaclSddl -} from './windows-secure-dacl' +} from '../windows-secure-dacl' /** Restrict directories off-thread because propagation walks all descendants; report failures and resolve false for retry. */ export function restrictWindowsDirectory(dirPath: string): Promise { diff --git a/src/shared/secure-storage/secure-path-windows-acl.win32.test.ts b/src/shared/secure-storage/secure-path-windows-acl.win32.test.ts new file mode 100644 index 00000000000..78dfbab2ad8 --- /dev/null +++ b/src/shared/secure-storage/secure-path-windows-acl.win32.test.ts @@ -0,0 +1,170 @@ +import { lstatSync, mkdirSync, mkdtempSync, readdirSync, writeFileSync } from 'node:fs' +import { randomBytes } from 'node:crypto' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest' +import { __resetSecureFileHardenedPathsForTests } from './secure-file' +import { + setSecurePathHardeningReporter, + type SecurePathHardeningReport +} from './secure-path-hardening-report' +import { restrictWindowsPathSync } from './secure-path-windows-acl' +import { + loadWindowsSecurity, + resetWindowsSecurityLoadForTests, + type WindowsSecurity +} from '../windows-security-addon' +import { CONTAINER_INHERIT_ACE, OBJECT_INHERIT_ACE } from '../windows-secure-dacl' +import { removeTreeSync } from '../windows-transient-lock-removal' + +/** Real NTFS read-back covers what fake addons cannot: relocated C:\ roots inheriting broad Modify access. Windows only. */ +const describeOnWindows = process.platform === 'win32' ? describe : describe.skip + +describeOnWindows('Windows secure paths against a real filesystem', () => { + let addon: WindowsSecurity['addon'] + let sid: string + let root: string + /** A relocated data root: `C:\orca-…` inherits BUILTIN\Users and Authenticated Users from C:\. */ + let relocatedRoot: string + + const daclOf = (path: string) => addon.getDaclAces(path) + const sidsOf = (path: string) => (daclOf(path)?.aces ?? []).map((ace) => ace.sid).sort() + const INHERITABLE = OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE + const INHERITED_ACE = 0x10 + const ORCA_PRINCIPALS = () => ['S-1-5-18', 'S-1-5-32-544', sid].sort() + + beforeAll(() => { + const loaded = loadWindowsSecurity() + if ('error' in loaded) { + throw new Error(`the windows-security addon did not load: ${loaded.error}`) + } + addon = loaded.addon + sid = loaded.userSid + root = mkdtempSync(join(tmpdir(), 'orca-acl-win32-')) + relocatedRoot = join('C:\\', `orca-acl-test-${randomBytes(4).toString('hex')}`) + mkdirSync(relocatedRoot) + }) + + afterEach(() => { + resetWindowsSecurityLoadForTests() + __resetSecureFileHardenedPathsForTests() + setSecurePathHardeningReporter(null) + }) + + afterAll(() => { + // Hostile DACL fixtures may become undeletable if repair regresses; restore this user’s access before cleanup. + for (const tree of [root, relocatedRoot]) { + unlockTree(tree) + removeTreeSync(tree) + } + }) + + function unlockTree(path: string): void { + try { + addon.setDaclSddl(path, `D:P(A;OICI;FA;;;${sid})`) + } catch { + return + } + if (lstatSync(path).isDirectory()) { + for (const name of readdirSync(path)) { + unlockTree(join(path, name)) + } + } + } + + it('restricts a real file, dropping inherited and planted foreign rules', () => { + const file = join(relocatedRoot, 'credential.json') + writeFileSync(file, '{"token":"secret"}') + addon.grantAccess(file, 'S-1-1-0', 0x120089, { inheritable: false, replace: false }) + expect(sidsOf(file)).toContain('S-1-1-0') + + expect(restrictWindowsPathSync(file, false)).toBe(true) + + expect(daclOf(file)?.protected).toBe(true) + expect(sidsOf(file)).toEqual(ORCA_PRINCIPALS()) + }) + + it('gives a directory inheritable rules so files created inside start restricted', () => { + const dir = join(relocatedRoot, 'secure-dir') + mkdirSync(dir) + + expect(restrictWindowsPathSync(dir, true)).toBe(true) + + expect(daclOf(dir)?.aces.every((ace) => ace.flags === INHERITABLE)).toBe(true) + const child = join(dir, 'plain.json') + writeFileSync(child, '{}') + expect(sidsOf(child)).toEqual(ORCA_PRINCIPALS()) + expect(daclOf(child)?.aces.every((ace) => (ace.flags & INHERITED_ACE) !== 0)).toBe(true) + }) + + it.each([ + ['(OI) without (CI), leaving subdirectories unprotected', 'OI'], + ['(OI)(CI)(IO), which grants nobody anything on the directory itself', 'OICIIO'] + ])('repairs a directory whose rules are %s', (_label, flags) => { + const dir = join(root, `wrong-flags-${flags}`) + mkdirSync(dir) + addon.setDaclSddl(dir, `D:P(A;${flags};FA;;;SY)(A;${flags};FA;;;BA)(A;${flags};FA;;;${sid})`) + + expect(restrictWindowsPathSync(dir, true)).toBe(true) + + expect(daclOf(dir)?.aces.every((ace) => ace.flags === INHERITABLE)).toBe(true) + expect(() => writeFileSync(join(dir, 'child.json'), '{}')).not.toThrow() + }) + + it('repairs a protected three-rule DACL that grants the wrong principal', () => { + const file = join(root, 'substituted.json') + writeFileSync(file, '{}') + addon.setDaclSddl(file, 'D:P(A;;FA;;;WD)(A;;FA;;;SY)(A;;FA;;;BA)') + + expect(restrictWindowsPathSync(file, false)).toBe(true) + + expect(sidsOf(file)).toEqual(ORCA_PRINCIPALS()) + }) + + it.each([ + ['spaces', 'a b c'], + ['single quote and dollar', "quo'te $var"], + ['backtick', 'back`tick'], + ['semicolon and ampersand', 'semi;colon & amp'], + ['caret and percent', 'car^et %PATH%'], + ['non-ASCII', 'résumé 資料'] + ])('hardens a path containing %s', (_label, segment) => { + const dir = join(root, segment) + mkdirSync(dir, { recursive: true }) + const file = join(dir, 'secret.json') + writeFileSync(file, '{}') + + expect(restrictWindowsPathSync(file, false)).toBe(true) + expect(sidsOf(file)).toEqual(ORCA_PRINCIPALS()) + }) + + it('hardens a path longer than MAX_PATH', () => { + let dir = join(root, 'long') + while (dir.length < 280) { + dir = join(dir, 'x'.repeat(40)) + } + mkdirSync(dir, { recursive: true }) + const file = join(dir, 'secret.json') + writeFileSync(file, '{}') + + expect(restrictWindowsPathSync(file, false)).toBe(true) + expect(sidsOf(`\\\\?\\${file}`)).toEqual(ORCA_PRINCIPALS()) + }) + + it('reports failure, not success, for a path that does not exist', () => { + const reports: SecurePathHardeningReport[] = [] + setSecurePathHardeningReporter((entry) => reports.push(entry)) + + expect(restrictWindowsPathSync(join(root, 'missing.json'), false)).toBe(false) + expect(reports).toContainEqual(expect.objectContaining({ stage: 'apply' })) + }) + + it('keeps hardening alive when the installed reporter throws', () => { + setSecurePathHardeningReporter(() => { + throw new Error('caller bug') + }) + + expect(restrictWindowsPathSync(join(root, 'missing-reporter.json'), false)).toBe(false) + }) +}) diff --git a/src/shared/source-control/ai/generation/commit-message-model-parsers.ts b/src/shared/source-control/ai/generation/commit-message-model-parsers.ts index 949532c7687..979c7db897c 100644 --- a/src/shared/source-control/ai/generation/commit-message-model-parsers.ts +++ b/src/shared/source-control/ai/generation/commit-message-model-parsers.ts @@ -1,4 +1,4 @@ -import { assertJsonTextStructureWithinLimits } from '../../../json-text-structure-limit' +import { assertJsonTextStructureWithinLimits } from '../../../json-stream/json-text-structure-limit' import { parseClaudeModelList } from '../../../claude-model-list-probe' import { labelFromModelId } from '../../../model-id-label' import type { CommitMessageModel, ThinkingLevel } from './commit-message-agent-spec' diff --git a/src/shared/source-control/ai/generation/pull-request-generation.ts b/src/shared/source-control/ai/generation/pull-request-generation.ts index 3ea4a6164c1..53b3208c673 100644 --- a/src/shared/source-control/ai/generation/pull-request-generation.ts +++ b/src/shared/source-control/ai/generation/pull-request-generation.ts @@ -1,5 +1,5 @@ import { truncateDiffForPrompt } from './commit-message-prompt' -import { assertJsonTextStructureWithinLimits } from '../../../json-text-structure-limit' +import { assertJsonTextStructureWithinLimits } from '../../../json-stream/json-text-structure-limit' import type { HostedReviewProvider } from '../../hosted-review/hosted-review-contracts' export const GENERATED_PULL_REQUEST_JSON_STRUCTURE_LIMITS = { diff --git a/src/shared/source-control/listing/source-control-tree.ts b/src/shared/source-control/listing/source-control-tree.ts index f1d5a35ab7f..5bee4fd8c10 100644 --- a/src/shared/source-control/listing/source-control-tree.ts +++ b/src/shared/source-control/listing/source-control-tree.ts @@ -1,6 +1,6 @@ import { normalizeRelativePath, splitPathSegments } from '../../cross-platform-path' import type { GitStagingArea, GitStatusEntry } from '../../git/status/git-status-types' -import { compareFileNames } from '../../file-name-sort' +import { compareFileNames } from '../../file-listing/file-name-sort' import { compareGitStatusEntries } from '../../git/status/git-status-sort' export type SourceControlTreeArea = Extract diff --git a/src/shared/runtime-file-contracts.ts b/src/shared/terminal/runtime-terminal-file-path.ts similarity index 55% rename from src/shared/runtime-file-contracts.ts rename to src/shared/terminal/runtime-terminal-file-path.ts index 541155a01c1..df7da9d8554 100644 --- a/src/shared/runtime-file-contracts.ts +++ b/src/shared/terminal/runtime-terminal-file-path.ts @@ -1,54 +1,3 @@ -import type { RasterImageDimensions } from './raster-image-dimensions' -import type { RuntimeNavigationTarget } from './runtime-navigation' - -export type RuntimeFileListEntry = { - relativePath: string - basename: string - kind: 'text' | 'binary' -} - -export type RuntimeFileListResult = { - worktree: string - rootPath: string - files: RuntimeFileListEntry[] - totalCount: number - truncated: boolean - quickOpenSearchVersion?: number -} - -export type RuntimeFileOpenResult = { - worktree: string - relativePath: string - kind: 'markdown' | 'text' | 'binary' | 'image' - opened: boolean -} - -export type RuntimeFileOpenPosition = { - line: number - column?: number -} - -/** A file main opened itself, which a window shows: layout-owner builds, local window only. */ -export type RuntimeEditorFileOpen = { - worktreeId: string - filePath: string - relativePath: string - runtimeEnvironmentId?: string | null - navigation?: RuntimeNavigationTarget - position?: RuntimeFileOpenPosition -} - -/** `frameSeq`: the layout stream position whose frame draws the tab. */ -export type RuntimeEditorTabReveal = RuntimeEditorFileOpen & { tabId: string; frameSeq?: number } - -export type RuntimeFileReadResult = { - worktree: string - relativePath: string - content: string - truncated: boolean - byteLength: number -} - export type RuntimeTerminalPathOpenTarget = | { kind: 'worktree-file' @@ -69,11 +18,6 @@ export type RuntimeTerminalPathOpenTarget = } | { kind: 'unsupported'; reason: string } -export type RuntimeNativeChatFileContext = { - tabId: string - sessionId: string -} - // Why: older hosts ignore crossWorkspace, so their refusal is no proof that no host workspace holds the path. export const TERMINAL_PATH_CROSS_WORKSPACE_RUNTIME_CAPABILITY = 'files.resolve-terminal-path.cross-workspace.v1' as const @@ -105,17 +49,3 @@ export type RuntimeTerminalPathResolution = { isDirectory: boolean openTarget?: RuntimeTerminalPathOpenTarget } - -export type RuntimeFilePreviewResult = { - content: string - isBinary: boolean - isImage?: boolean - mimeType?: string - imageDimensions?: RasterImageDimensions -} - -export type RuntimeFileReadChunkResult = { - contentBase64: string - bytesRead: number - eof: boolean -} diff --git a/src/shared/terminal/stream/terminal-stream-protocol.ts b/src/shared/terminal/stream/terminal-stream-protocol.ts index 66833ed13b7..dc4bba54f96 100644 --- a/src/shared/terminal/stream/terminal-stream-protocol.ts +++ b/src/shared/terminal/stream/terminal-stream-protocol.ts @@ -1,4 +1,4 @@ -import { assertJsonTextStructureWithinLimits } from '../../json-text-structure-limit' +import { assertJsonTextStructureWithinLimits } from '../../json-stream/json-text-structure-limit' const TERMINAL_STREAM_KIND = 0x74 const TERMINAL_STREAM_VERSION = 1 diff --git a/src/shared/text-search-dense-matches.test.ts b/src/shared/text-search-dense-matches.test.ts deleted file mode 100644 index 370a348ace8..00000000000 --- a/src/shared/text-search-dense-matches.test.ts +++ /dev/null @@ -1,140 +0,0 @@ -import { mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' -import { runProcess } from '@orca/process-host' -import { buildRgArgs, createAccumulator, ingestRgJsonLine } from './text-search' - -describe('text search match budgets', () => { - it.each(['x', '😀'])( - 'keeps whole Unicode context around dense real rg matches for %s', - async (query) => { - const { rgPath } = await import('@vscode/ripgrep-universal') - const root = await mkdtemp(join(tmpdir(), 'orca-rg-dense-unicode-')) - const filename = join(root, 'unicode.txt') - try { - await writeFile(filename, `a${'😀x'.repeat(10_000)}\n`) - const result = await runProcess({ - program: rgPath, - args: buildRgArgs(query, '.', {}), - cwd: root - }) - expect(result.code).toBe(0) - const accumulator = createAccumulator() - for (const line of result.stdout.split('\n')) { - if (ingestRgJsonLine(line, root, accumulator, 2000) === 'stop') { - break - } - } - expect(accumulator.totalMatches).toBe(2000) - expect(accumulator.truncated).toBe(true) - const matches = accumulator.fileMap.get(filename)?.matches ?? [] - expect(matches).toHaveLength(2000) - for (const [index, match] of matches.entries()) { - expect(match.column).toBe(index * 3 + (query === 'x' ? 4 : 2)) - expect(match.matchLength).toBe(query.length) - expect(match.lineContent.isWellFormed()).toBe(true) - const start = (match.displayColumn ?? match.column) - 1 - const length = match.displayMatchLength ?? match.matchLength - expect(match.lineContent.slice(start, start + length)).toBe(query) - } - } finally { - await rm(root, { recursive: true, force: true }) - } - } - ) - - it('keeps dense-line columns after a leading U+FEFF from real rg', async () => { - const { rgPath } = await import('@vscode/ripgrep-universal') - const root = await mkdtemp(join(tmpdir(), 'orca-rg-dense-bom-')) - const filename = join(root, '\ufeffdense.txt') - try { - await writeFile(filename, `header\n\ufeff${'x '.repeat(10_000)}`) - const result = await runProcess({ - program: rgPath, - args: buildRgArgs('x', '.', {}), - cwd: root - }) - expect(result.code).toBe(0) - const accumulator = createAccumulator() - for (const line of result.stdout.split('\n')) { - if (ingestRgJsonLine(line, root, accumulator, 2000) === 'stop') { - break - } - } - expect(accumulator.totalMatches).toBe(2000) - expect(accumulator.fileMap.get(filename)?.matches[0]).toMatchObject({ - line: 2, - column: 2, - matchLength: 1 - }) - expect(accumulator.fileMap.get(filename)?.matches[1999]?.column).toBe(4000) - } finally { - await rm(root, { recursive: true, force: true }) - } - }) - - it('allows more than 100 matching lines in one file under the global budget', async () => { - const { rgPath } = await import('@vscode/ripgrep-universal') - const root = await mkdtemp(join(tmpdir(), 'orca-rg-lines-')) - try { - await writeFile(join(root, 'many.txt'), 'needle\n'.repeat(150)) - const result = await runProcess({ - program: rgPath, - args: buildRgArgs('needle', root, {}), - cwd: root - }) - expect(result.code).toBe(0) - const accumulator = createAccumulator() - for (const line of result.stdout.split('\n')) { - ingestRgJsonLine(line, root, accumulator, 2000) - } - expect(accumulator.totalMatches).toBe(150) - expect(accumulator.truncated).toBe(false) - } finally { - await rm(root, { recursive: true, force: true }) - } - }) -}) - -function denseRecord(count: number): string { - return JSON.stringify({ - type: 'match', - data: { - path: { text: '/root/dense.txt' }, - lines: { text: 'x '.repeat(count) }, - line_number: 1, - submatches: Array.from({ length: count }, (_, index) => ({ - match: { text: 'x' }, - start: index * 2, - end: index * 2 + 1 - })) - } - }) -} - -it('retains the first 2000 matches from a dense line beyond the normal JSON budget', () => { - const accumulator = createAccumulator() - expect(ingestRgJsonLine(denseRecord(10_000), '/root', accumulator, 2000)).toBe('stop') - expect(accumulator.totalMatches).toBe(2000) - expect(accumulator.truncated).toBe(true) - const matches = accumulator.fileMap.get('/root/dense.txt')?.matches - expect(matches?.map((match) => match.column)).toEqual( - Array.from({ length: 2000 }, (_, index) => index * 2 + 1) - ) -}) - -it.each([ - (record: string) => record.slice(0, -1), - (record: string) => `${record.slice(0, -2)},invalid}`, - (record: string) => `${record.slice(0, -1)},"data":{}}`, - (record: string) => `${record.slice(0, -2)},"submatches":[]}}` -])( - 'rejects invalid tails or duplicate envelope keys without retaining early matches', - (corrupt) => { - const accumulator = createAccumulator() - ingestRgJsonLine(corrupt(denseRecord(10_000)), '/root', accumulator, 2000) - expect(accumulator.totalMatches).toBe(0) - expect(accumulator.truncated).toBe(true) - } -) diff --git a/src/shared/text-search-glob-patterns.test.ts b/src/shared/text-search-glob-patterns.test.ts deleted file mode 100644 index 18c9eae29e1..00000000000 --- a/src/shared/text-search-glob-patterns.test.ts +++ /dev/null @@ -1,205 +0,0 @@ -import { afterAll, beforeAll, describe, expect, it } from 'vitest' -import { mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { runProcess } from '@orca/process-host' -import { splitSearchGlobPatterns } from './text-search-glob-patterns' -import { - buildGitGrepArgs, - buildRgArgs, - createAccumulator, - finalize, - ingestRgJsonLine -} from './text-search' - -describe('compound search globs', () => { - it.each([ - ['', []], - [' , *.ts,, *.md, ', ['*.ts', '*.md']], - ['}.ts, *.md', ['}.ts', '*.md']], - ['*.{ts,tsx}, *.md', ['*.{ts,tsx}', '*.md']], - ['{src,{lib,test}}/**, *.md', ['{src,{lib,test}}/**', '*.md']], - ['*[a,b].ts, *.md', ['*[a,b].ts', '*.md']], - ['[{},].ts, *.md', ['[{},].ts', '*.md']], - ['[]a,b].ts, *.md', ['[]a,b].ts', '*.md']], - ['[!]a,b].ts, *.md', ['[!]a,b].ts', '*.md']], - ['[^]a,b].ts, *.md', ['[^]a,b].ts', '*.md']], - ['[[:alpha:],].ts, *.md', ['[[:alpha:],].ts', '*.md']], - ['[a\\],b].ts, *.md', ['[a\\],b].ts', '*.md']], - ['foo\\,bar/**, *.ts', ['foo\\,bar/**', '*.ts']], - ['\\{a,b\\}, *.ts', ['\\{a', 'b\\}', '*.ts']], - ['\\[a,b\\], *.ts', ['\\[a', 'b\\]', '*.ts']], - ['src\\', ['src\\']], - ['*.{ts,tsx', ['*.{ts,tsx']], - ['[a,b', ['[a,b']] - ])('preserves grouped and escaped commas in %s', (input, expected) => { - expect(splitSearchGlobPatterns(input, 'git')).toEqual(expected) - }) - - it('preserves 20000 nested groups without expanding alternatives', () => { - const pattern = `${'{'.repeat(20_000)}a,b${'}'.repeat(20_000)}` - expect(splitSearchGlobPatterns(`${pattern}, *.md`)).toEqual([pattern, '*.md']) - }) -}) - -describe('file search with real search engines', () => { - let root: string - - beforeAll(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-search-globs-')) - for (const file of ['a.ts', 'b.tsx', 'c.md', ',.ts']) { - await writeFile(join(root, file), 'needle\n') - } - const initialized = await runProcess({ program: 'git', args: ['init'], cwd: root }) - expect(initialized.code).toBe(0) - }) - - afterAll(async () => { - if (root) { - await rm(root, { recursive: true, force: true }) - } - }) - - it.each([ - [{ includePattern: '*.{ts,tsx}' }, [',.ts', 'a.ts', 'b.tsx']], - [{ includePattern: '[a,b].ts, *.md' }, [',.ts', 'a.ts', 'c.md']], - [{ excludePattern: '*.{ts,tsx}' }, ['c.md']], - [{ includePattern: '[]a,b].ts, *.md' }, [',.ts', 'a.ts', 'c.md']], - [{ excludePattern: '[a,b].ts' }, ['b.tsx', 'c.md']], - [{ includePattern: '*.ts, *.tsx', excludePattern: '[a,b].ts' }, ['b.tsx']] - ])('matches files with ripgrep using %j', async (options, expected) => { - const { rgPath } = await import('@vscode/ripgrep-universal') - const result = await runProcess({ - program: rgPath, - args: buildRgArgs('needle', root, options), - cwd: root - }) - expect(result.stderr).toBe('') - expect(result.code).toBe(0) - const accumulator = createAccumulator() - for (const line of result.stdout.split('\n')) { - ingestRgJsonLine(line, root, accumulator, 100) - } - expect( - finalize(accumulator) - .files.map((file) => file.relativePath) - .sort() - ).toEqual(expected) - }) - - it.each(['*.{ts,tsx', '[a,b'])('leaves invalid %s for ripgrep to reject', async (pattern) => { - const { rgPath } = await import('@vscode/ripgrep-universal') - for (const options of [{ includePattern: pattern }, { excludePattern: pattern }]) { - const result = await runProcess({ - program: rgPath, - args: buildRgArgs('needle', root, options), - cwd: root - }) - expect(result.code).toBe(2) - expect(result.stderr).toContain('error parsing glob') - expect(result.stderr).toContain(pattern) - } - }) - - it('keeps Git brace syntax literal instead of expanding it', async () => { - const result = await runProcess({ - program: 'git', - args: buildGitGrepArgs('needle', { includePattern: '*.{ts,tsx}' }), - cwd: root - }) - expect(result.code).toBe(1) - expect(result.stdout).toBe('') - expect(result.stderr).toBe('') - }) - - it('preserves character classes in Git exclusions', async () => { - const result = await runProcess({ - program: 'git', - args: buildGitGrepArgs('needle', { excludePattern: '[[:alpha:],].ts' }), - cwd: root - }) - expect(result.code).toBe(0) - expect(result.stdout).toContain('b.tsx\0') - expect(result.stdout).toContain('c.md\0') - expect(result.stdout).not.toContain('a.ts\0') - expect(result.stdout).not.toContain(',.ts\0') - }) - - it.each(['[a,b].ts', '[[:alpha:],].ts'])( - 'preserves %s in the Git fallback too', - async (includePattern) => { - const result = await runProcess({ - program: 'git', - args: buildGitGrepArgs('needle', { includePattern }), - cwd: root - }) - expect(result.code).toBe(0) - expect(result.stdout).toContain('a.ts\0') - expect(result.stdout).toContain(',.ts\0') - expect(result.stdout).not.toContain('b.tsx\0') - expect(result.stdout).not.toContain('c.md\0') - } - ) -}) - -describe('engine-specific character classes', () => { - let root: string - const files = [',.ts', '[.ts', '].ts', 'a.ts', 'a,b].ts', 'b.tsx', 'c.md'] - - beforeAll(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-search-class-syntax-')) - for (const file of files) { - await writeFile(join(root, file), 'needle\n') - } - expect((await runProcess({ program: 'git', args: ['init'], cwd: root })).code).toBe(0) - }) - - afterAll(async () => { - if (root) { - await rm(root, { recursive: true, force: true }) - } - }) - - it.each([ - ['rg', '[a\\].ts, *.md', ['a.ts', 'c.md']], - ['rg', '[[:].ts, *.md', ['[.ts', 'c.md']], - ['git', '[[:].ts, *.md', ['[.ts', 'c.md']], - ['git', '[a\\],b].ts, *.md', [',.ts', '].ts', 'a.ts', 'c.md']], - ['git', '[[:alpha:],].ts, *.md', [',.ts', 'a.ts', 'c.md']], - ['rg', '[[:alpha:], *.md', ['c.md']] - ] as const)( - 'respects %s syntax in %s for includes and excludes', - async (engine, pattern, matches) => { - const { rgPath } = await import('@vscode/ripgrep-universal') - for (const exclude of [false, true]) { - const options = exclude ? { excludePattern: pattern } : { includePattern: pattern } - const result = await runProcess({ - program: engine === 'rg' ? rgPath : 'git', - args: - engine === 'rg' - ? buildRgArgs('needle', root, options) - : buildGitGrepArgs('needle', options), - cwd: root - }) - expect(result.code).toBe(0) - expect(result.stderr).toBe('') - let actual: string[] - if (engine === 'rg') { - const accumulator = createAccumulator() - for (const line of result.stdout.split('\n')) { - ingestRgJsonLine(line, root, accumulator, 100) - } - actual = finalize(accumulator).files.map((file) => file.relativePath) - } else { - actual = result.stdout - .trim() - .split('\n') - .map((line) => line.split('\0')[0]) - } - const selected = new Set(matches) - const expected = exclude ? files.filter((file) => !selected.has(file)) : [...matches] - expect(actual.sort()).toEqual(expected.sort()) - } - } - ) -}) diff --git a/src/shared/text-search-snippet-boundaries.test.ts b/src/shared/text-search-snippet-boundaries.test.ts deleted file mode 100644 index 57f91f82fea..00000000000 --- a/src/shared/text-search-snippet-boundaries.test.ts +++ /dev/null @@ -1,115 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - createAccumulator, - ingestGitGrepLine, - ingestRgJsonLine, - MAX_LINE_CONTENT_LENGTH -} from './text-search' - -describe('search snippet character boundaries', () => { - it.each([ - ['start', '😀'.repeat(300), 'x', 'a'.repeat(600)], - ['end', 'a'.repeat(600), 'xx', '😀'.repeat(300)], - ['both', '😀'.repeat(300), 'xx', '😀'.repeat(300)], - ['long match', 'a'.repeat(10), `x${'😀'.repeat(300)}`, 'b'.repeat(600)], - ['zero width', '😀'.repeat(300), '', '😀'.repeat(300)], - ['zero width at EOF', `${'😀'.repeat(301)}x`, '', ''], - ['first character', '', '😀', 'a'.repeat(600)], - ['last character', 'a'.repeat(600), '😀', ''], - ['short line', '😀', 'x', '😀'] - ])( - 'keeps the %s boundary whole and retains navigation coordinates', - (_name, prefix, needle, suffix) => { - const text = prefix + needle + suffix - const accumulator = createAccumulator() - ingestRgJsonLine( - JSON.stringify({ - type: 'match', - data: { - path: { text: 'unicode.txt' }, - lines: { text: `${text}\n` }, - line_number: 7, - submatches: [ - { start: Buffer.byteLength(prefix), end: Buffer.byteLength(prefix + needle) } - ] - } - }), - '/root', - accumulator, - 2000 - ) - const match = [...accumulator.fileMap.values()][0].matches[0] - expect(match).toMatchObject({ - line: 7, - column: prefix.length + 1, - matchLength: needle.length - }) - expect(match.lineContent.isWellFormed()).toBe(true) - expect(match.lineContent.length).toBeLessThanOrEqual(MAX_LINE_CONTENT_LENGTH + 2) - const start = (match.displayColumn ?? match.column) - 1 - const length = match.displayMatchLength ?? match.matchLength - const highlighted = match.lineContent.slice(start, start + length) - expect(highlighted.isWellFormed()).toBe(true) - expect(needle.startsWith(highlighted)).toBe(true) - if (needle.length <= MAX_LINE_CONTENT_LENGTH) { - expect(highlighted).toBe(needle) - } else { - expect(length).toBe(MAX_LINE_CONTENT_LENGTH - 1) - expect(highlighted).toBe(`x${'😀'.repeat(249)}`) - } - } - ) - - it('uses the same character-safe context for the remote git fallback', () => { - const prefix = '😀'.repeat(300) - const accumulator = createAccumulator() - ingestGitGrepLine(`unicode.txt\x001\x00${prefix}xx${prefix}`, '/root', /xx/g, accumulator, 2000) - const match = [...accumulator.fileMap.values()][0].matches[0] - expect(match.lineContent.isWellFormed()).toBe(true) - expect(match.column).toBe(601) - const start = (match.displayColumn ?? match.column) - 1 - expect( - match.lineContent.slice(start, start + (match.displayMatchLength ?? match.matchLength)) - ).toBe('xx') - }) - - it('never returns a negative display length for a zero-width range after the line terminator', () => { - const text = `${'x'.repeat(600)}\n` - const accumulator = createAccumulator() - ingestRgJsonLine( - JSON.stringify({ - type: 'match', - data: { - path: { text: 'line.txt' }, - lines: { text }, - line_number: 1, - submatches: [{ start: text.length, end: text.length }] - } - }), - '/root', - accumulator, - 2000 - ) - const match = [...accumulator.fileMap.values()][0].matches[0] - expect(match.matchLength).toBe(0) - expect(match.displayMatchLength).toBe(0) - }) - - it('excludes truncation markers when a fallback regex begins inside a surrogate pair', () => { - const accumulator = createAccumulator() - ingestGitGrepLine( - `unicode.txt\x001\x00${'😀'.repeat(600)}`, - '/root', - /.{501}/g, - accumulator, - 2000 - ) - const match = [...accumulator.fileMap.values()][0].matches[1] - expect(match.column).toBe(502) - expect(match.matchLength).toBe(501) - expect(match.displayColumn).toBe(2) - expect(match.displayMatchLength).toBe(498) - expect(match.lineContent).toBe(`…${'😀'.repeat(249)}…`) - expect(match.lineContent.slice(1, 499)).toBe('😀'.repeat(249)) - }) -}) diff --git a/src/shared/text-search-snippet-retention.test.ts b/src/shared/text-search-snippet-retention.test.ts deleted file mode 100644 index a4a71754e0a..00000000000 --- a/src/shared/text-search-snippet-retention.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { createAccumulator, ingestRgJsonLine } from './text-search' - -function heapAfterCollection(): number { - if (!globalThis.gc) { - throw new Error('This regression requires the test runner to enable --expose-gc') - } - void /reset/.test('reset') - globalThis.gc() - globalThis.gc() - return process.memoryUsage().heapUsed -} - -function collectSnippets() { - const accumulator = createAccumulator() - for (let index = 0; index < 32; index++) { - const prefix = String.fromCharCode(65 + index).repeat(1024 * 1024) - ingestRgJsonLine( - JSON.stringify({ - type: 'match', - data: { - path: { text: `${index}.txt` }, - line_number: 1, - lines: { text: `${prefix}needle` }, - submatches: [{ start: prefix.length, end: prefix.length + 6 }] - } - }), - '/root', - accumulator, - 2000 - ) - } - return accumulator -} - -describe('retained search snippets', () => { - it('releases large source lines while keeping their clipped results alive', () => { - collectSnippets() - const before = heapAfterCollection() - const accumulator = collectSnippets() - const retainedBytes = heapAfterCollection() - before - - expect(accumulator.totalMatches).toBe(32) - for (const file of accumulator.fileMap.values()) { - expect(file.matches[0].lineContent).toHaveLength(501) - expect(file.matches[0].lineContent.endsWith('needle')).toBe(true) - expect(file.matches[0].column).toBe(1024 * 1024 + 1) - } - // Without ownership, 32 tiny snippets retain 32 MiB of source strings. - expect(retainedBytes).toBeLessThan(4 * 1024 * 1024) - }) -}) diff --git a/src/shared/use-attachment-text-preview.test.tsx b/src/shared/use-attachment-text-preview.test.tsx deleted file mode 100644 index 953a1e4adae..00000000000 --- a/src/shared/use-attachment-text-preview.test.tsx +++ /dev/null @@ -1,114 +0,0 @@ -// @vitest-environment happy-dom -import * as React from 'react' -import { act, cleanup, renderHook, waitFor } from '@testing-library/react' -import { afterEach, expect, it, vi } from 'vitest' -import { - AttachmentTextSource, - ATTACHMENT_TEXT_BLOCK_BYTES, - type AttachmentTextRequest -} from './attachment-text-source' -import { AttachmentTextViewport } from './attachment-text-viewport' -import { createAttachmentTextPreviewHook } from './use-attachment-text-preview' - -const usePreview = createAttachmentTextPreviewHook(React) - -function reader(size: number) { - return vi.fn(async ({ offset, length }: AttachmentTextRequest) => { - const bytes = Buffer.alloc(Math.min(length, size - offset), 'x') - return { - snapshot: 'a'.repeat(64), - size, - bytesRead: bytes.length, - contentBase64: bytes.toString('base64'), - eof: offset + bytes.length === size - } - }) -} - -afterEach(() => { - cleanup() - vi.restoreAllMocks() -}) - -it.each([100 * ATTACHMENT_TEXT_BLOCK_BYTES, 1000 * ATTACHMENT_TEXT_BLOCK_BYTES, 50 * 1024 * 1024])( - 'keeps cached scroll work independent of a %i-byte attachment and still loads new rows', - async (size) => { - const read = reader(size) - const counts = vi.spyOn(AttachmentTextSource.prototype, 'rowCount') - const known = vi.spyOn(AttachmentTextSource.prototype, 'rowKnown') - let renders = 0 - const { result } = renderHook(() => { - renders++ - const preview = usePreview('/scroll.txt', read) - const layout = React.useMemo( - () => new AttachmentTextViewport(preview.source, 20, 600, preview.revision), - [preview.source, preview.revision] - ) - return { preview, layout } - }) - await waitFor(() => expect(result.current.preview.source.cachedBlock(0)).toBeDefined()) - const before = result.current - const settledRenders = renders - counts.mockClear() - known.mockClear() - read.mockClear() - for (let pixel = 1; pixel <= 10; pixel++) { - await act(async () => result.current.preview.demand(before.layout.window(pixel))) - } - expect(result.current.preview.revision).toBe(before.preview.revision) - expect(result.current.layout).toBe(before.layout) - expect(renders).toBe(settledRenders) - expect(read).not.toHaveBeenCalled() - expect(known).not.toHaveBeenCalled() - expect(counts.mock.calls.length).toBeLessThanOrEqual(40) - - await act(async () => result.current.preview.demand({ block: 1, row: 0, rows: 1 })) - await waitFor(() => - expect(result.current.preview.revision).toBeGreaterThan(before.preview.revision) - ) - expect(read).toHaveBeenCalledOnce() - expect(result.current.layout).not.toBe(before.layout) - const top = result.current.layout.position({ block: 1, row: 0 }) - expect(result.current.layout.rows(top)[0]?.text).toBe('x'.repeat(256)) - } -) - -it('publishes successful superseded work to a cached window once, including synchronous reentry', async () => { - const read = reader(ATTACHMENT_TEXT_BLOCK_BYTES * 3) - const release = Promise.withResolvers() - const started = Promise.withResolvers() - let held = false - const source = new AttachmentTextSource('/held.txt', async (request) => { - if (held) { - started.resolve() - await release.promise - } - return read(request) - }) - try { - await source.block(0) - held = true - const obsolete = vi.fn() - source.requestViewport({ block: 0, row: 0, rows: source.rowCount(0) + 1 }, obsolete) - await started.promise - const ready = Promise.withResolvers() - const repeated = vi.fn() - const latest = vi.fn(() => { - source.requestViewport({ block: 0, row: 0, rows: 1 }, repeated) - ready.resolve() - }) - source.requestViewport({ block: 0, row: 0, rows: 1 }, latest) - release.resolve() - await ready.promise - expect(obsolete).not.toHaveBeenCalled() - expect(latest).toHaveBeenCalledOnce() - expect(latest).toHaveBeenCalledWith() - expect(repeated).not.toHaveBeenCalled() - expect(source.rowKnown(1)).toBe(true) - expect(source.cachedBlock(0)).toBeDefined() - expect(read).toHaveBeenCalledTimes(2) - } finally { - release.resolve() - source.dispose() - } -}) diff --git a/src/shared/utf8-byte-limits.test.ts b/src/shared/utf8-byte-limits.test.ts index a3f8de26636..ea0830e50be 100644 --- a/src/shared/utf8-byte-limits.test.ts +++ b/src/shared/utf8-byte-limits.test.ts @@ -1,7 +1,6 @@ import { describe, expect, it } from 'vitest' import { clampUtf8TextPrefix, - getUtf8ByteLength, getUtf8ChunkEndIndex, isUtf8ByteLengthWithinLimit, measureUtf8ByteLength, @@ -36,15 +35,6 @@ describe('scanning a prefix slice whose parent continues past the slice', () => expect([...observed]).toEqual([0xd9f6]) }) - it('measures the same byte length as the encoder in every JIT tier', () => { - const expected = Buffer.byteLength(sliced, 'utf8') - const observed = new Set() - for (let iteration = 0; iteration < TIER_UP_ITERATIONS; iteration += 1) { - observed.add(measureUtf8ByteLength(sliced).byteLength) - } - expect([...observed]).toEqual([expected]) - }) - it('does not report an exceeded limit at the true byte length in every JIT tier', () => { const limit = Buffer.byteLength(sliced, 'utf8') const observed = new Set() @@ -109,32 +99,3 @@ describe('isUtf8ByteLengthWithinLimit', () => { expect(isUtf8ByteLengthWithinLimit(text, maxBytes)).toBe(expected) }) }) - -describe('isUtf8ByteLengthWithinLimit native fast path', () => { - // Compare native bounded encoding against the prior scan at boundaries, including lone surrogates. - const samples = [ - '', - 'a', - 'ascii only text', - 'caf\u00e9', - '\u20ac\u20ac\u20ac', - '\ud83d\ude00\ud83d\ude00', - '\ud83d', - '\ude00', - 'mixed \u00e9 \u20ac \ud83d\ude00 tail', - 'x'.repeat(64) - ] - - it('matches the scanning implementation at every limit around the boundary', () => { - for (const text of samples) { - const exactBytes = getUtf8ByteLength(text) - for (let maxBytes = 1; maxBytes <= exactBytes + 2; maxBytes += 1) { - expect({ text, maxBytes, within: isUtf8ByteLengthWithinLimit(text, maxBytes) }).toEqual({ - text, - maxBytes, - within: text.length <= maxBytes && exactBytes <= maxBytes - }) - } - } - }) -}) diff --git a/src/shared/windows-private-credential-file.test.ts b/src/shared/windows-private-credential-file.test.ts index fb63ca1a05a..a92071b0423 100644 --- a/src/shared/windows-private-credential-file.test.ts +++ b/src/shared/windows-private-credential-file.test.ts @@ -7,7 +7,7 @@ import { resetWindowsSecurityLoadForTests, setWindowsSecurityForTests } from './windows-security-addon' -import { readPrivateWindowsFile } from './secure-path-windows-acl' +import { readPrivateWindowsFile } from './secure-storage/secure-path-windows-acl' import { writeCredentialFileAtomic } from '../main/credentials/integration-credential-file' const roots: string[] = [] diff --git a/src/shared/workspace-layout/old-client/old-client-session-editor-rows.ts b/src/shared/workspace-layout/old-client/old-client-session-editor-rows.ts index b360133d5ba..f0ac2881b66 100644 --- a/src/shared/workspace-layout/old-client/old-client-session-editor-rows.ts +++ b/src/shared/workspace-layout/old-client/old-client-session-editor-rows.ts @@ -5,7 +5,7 @@ import type { RuntimeMobileSessionMarkdownTab } from '../../runtime-mobile-session-tab-contracts' import type { LayoutEditorView } from '../layout-editor-view' -import { editorRowHost } from '../../session-tab-file-host' +import { editorRowHost } from '../../workspace-session/session-tab-file-host' import type { DesktopLayoutView } from '../workspace-layout-beside' import { editorFileKey, editorTabFile } from '../workspace-layout-editor-tab-file' import type { LayoutContentTab, LayoutEditorFile, WorkspaceLayout } from '../workspace-layout-model' diff --git a/src/shared/session-tab-file-host.ts b/src/shared/workspace-session/session-tab-file-host.ts similarity index 81% rename from src/shared/session-tab-file-host.ts rename to src/shared/workspace-session/session-tab-file-host.ts index c5fd7801cd5..8f4b46de8a4 100644 --- a/src/shared/session-tab-file-host.ts +++ b/src/shared/workspace-session/session-tab-file-host.ts @@ -1,4 +1,4 @@ -import type { RuntimeMobileSessionFileTab } from './runtime-mobile-session-tab-contracts' +import type { RuntimeMobileSessionFileTab } from '../runtime-mobile-session-tab-contracts' /** Names the paired server a row's file or page lives on, for runtimes to keep from other runtimes (#33424). */ export function editorRowHost(file: { diff --git a/src/shared/workspace-session/workspace-doc-history.ts b/src/shared/workspace-session/workspace-doc-history.ts index 319df961a2d..3856a0502e9 100644 --- a/src/shared/workspace-session/workspace-doc-history.ts +++ b/src/shared/workspace-session/workspace-doc-history.ts @@ -1,5 +1,5 @@ import type { BrowserPageDocLocation } from '../browser-workspace-types' -import { isDocPreviewUrl } from '../doc-preview-scheme' +import { isDocPreviewUrl } from '../document-preview/doc-preview-scheme' /** Persist document identity only; omitting URL gives preview grant URLs no place in history. */ export type WorkspaceDocHistoryEntry = { diff --git a/src/shared/workspace-session/workspace-session-browser-schema.ts b/src/shared/workspace-session/workspace-session-browser-schema.ts index be0bca90c38..4131a510337 100644 --- a/src/shared/workspace-session/workspace-session-browser-schema.ts +++ b/src/shared/workspace-session/workspace-session-browser-schema.ts @@ -2,7 +2,7 @@ import { z } from 'zod' import type { BrowserWorkspace } from '../browser-workspace-types' import { normalizeBrowserHistoryEntries } from './workspace-session-browser-history' import { normalizeWorkspaceDocHistoryEntries } from './workspace-doc-history' -import { isDocPreviewUrl } from '../doc-preview-scheme' +import { isDocPreviewUrl } from '../document-preview/doc-preview-scheme' import { salvagingArray } from '../zod-salvage' const browserLoadErrorSchema = z.object({ diff --git a/tests/e2e/helpers/paired-quick-open-large-tree-fixture.ts b/tests/e2e/helpers/paired-quick-open-large-tree-fixture.ts deleted file mode 100644 index 5455eaa0e3b..00000000000 --- a/tests/e2e/helpers/paired-quick-open-large-tree-fixture.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { execFileSync } from 'node:child_process' -import { - closeSync, - mkdirSync, - mkdtempSync, - openSync, - renameSync, - rmSync, - truncateSync, - writeFileSync -} from 'node:fs' -import os from 'node:os' -import path from 'node:path' - -export const LARGE_TREE_FILE_COUNT = 88_763 -export const LARGE_TREE_IGNORED_FILE_COUNT = 77_792 -export const LARGE_TREE_NOMINAL_IGNORED_BYTES = 22 * 1024 * 1024 * 1024 - -const FILES_PER_DIRECTORY = 256 -const LONG_STEM = 'remote-quick-open-transport-budget-path-'.repeat(2) - -function createFiles(root: string, directoryName: string, count: number, extension: string): void { - for (let start = 0; start < count; start += FILES_PER_DIRECTORY) { - const directory = path.join(root, directoryName, `chunk-${String(start).padStart(6, '0')}`) - mkdirSync(directory, { recursive: true }) - const end = Math.min(start + FILES_PER_DIRECTORY, count) - for (let index = start; index < end; index++) { - closeSync( - openSync( - path.join(directory, `${LONG_STEM}${String(index).padStart(6, '0')}.${extension}`), - 'w' - ) - ) - } - } -} - -export type PairedQuickOpenLargeTreeFixture = { - dispose: () => void - gitIgnoredTargetPath: string - orcaIgnoredTargetPath: string - root: string -} - -export function createPairedQuickOpenLargeTreeFixture(): PairedQuickOpenLargeTreeFixture { - const root = mkdtempSync(path.join(os.tmpdir(), 'orca-paired-quick-open-large-tree-')) - try { - execFileSync('git', ['init'], { cwd: root, stdio: 'pipe' }) - writeFileSync(path.join(root, '.gitignore'), 'data/\n') - writeFileSync(path.join(root, '.orcaignore'), 'orca-ignored/\n') - - const visibleFileCount = LARGE_TREE_FILE_COUNT - LARGE_TREE_IGNORED_FILE_COUNT - 3 - createFiles(root, 'src', visibleFileCount, 'ts') - createFiles(root, 'data', LARGE_TREE_IGNORED_FILE_COUNT, 'bin') - const lastIgnoredIndex = LARGE_TREE_IGNORED_FILE_COUNT - 1 - const lastIgnoredChunk = - Math.floor(lastIgnoredIndex / FILES_PER_DIRECTORY) * FILES_PER_DIRECTORY - const ignoredDirectory = `chunk-${String(lastIgnoredChunk).padStart(6, '0')}` - const gitIgnoredTargetPath = `data/${ignoredDirectory}/sta-4354-gitignored-target.bin` - renameSync( - path.join( - root, - 'data', - ignoredDirectory, - `${LONG_STEM}${String(lastIgnoredIndex).padStart(6, '0')}.bin` - ), - path.join(root, ...gitIgnoredTargetPath.split('/')) - ) - const orcaIgnoredTargetPath = 'orca-ignored/sta-4354-orcaignore-target.ts' - mkdirSync(path.join(root, 'orca-ignored')) - closeSync(openSync(path.join(root, ...orcaIgnoredTargetPath.split('/')), 'w')) - truncateSync( - path.join(root, 'data', 'chunk-000000', `${LONG_STEM}000000.bin`), - LARGE_TREE_NOMINAL_IGNORED_BYTES - ) - - execFileSync('git', ['add', '.gitignore', '.orcaignore'], { cwd: root, stdio: 'pipe' }) - execFileSync( - 'git', - [ - '-c', - 'user.name=Orca E2E', - '-c', - 'user.email=orca-e2e@example.invalid', - 'commit', - '-m', - 'seed large-tree fixture' - ], - { cwd: root, stdio: 'pipe' } - ) - return { - root, - gitIgnoredTargetPath, - orcaIgnoredTargetPath, - dispose: () => rmSync(root, { recursive: true, force: true }) - } - } catch (error) { - rmSync(root, { recursive: true, force: true }) - throw error - } -} diff --git a/tests/e2e/paired-quick-open-large-tree.spec.ts b/tests/e2e/paired-quick-open-large-tree.spec.ts deleted file mode 100644 index e7868b963ba..00000000000 --- a/tests/e2e/paired-quick-open-large-tree.spec.ts +++ /dev/null @@ -1,210 +0,0 @@ -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient, - type PairedElectronClient -} from './helpers/paired-electron-client' -import { createPairedQuickOpenLargeTreeFixture } from './helpers/paired-quick-open-large-tree-fixture' -import type { RuntimeFileListResult } from '../../src/shared/runtime-file-contracts' -import type { RuntimeWorktreeListResult } from '../../src/shared/runtime-worktree-contracts' -import type { PairedQuickOpenLargeTreeFixture } from './helpers/paired-quick-open-large-tree-fixture' -import { waitForSessionReady } from './helpers/store' -import { callPairedRuntime } from './helpers/paired-client-host-session' - -const QUICK_OPEN_SEARCH_DEBOUNCE_MS = 120 - -async function activateWorktree(page: Page, repoPath: string, timeout = 60_000): Promise { - await expect - .poll( - () => - page.evaluate( - (targetPath) => - window.__store - ?.getState() - .allWorktrees() - .find((worktree) => { - const normalize = (value: string): string => - value.startsWith('/private/var/') ? value.slice('/private'.length) : value - return normalize(worktree.path) === normalize(targetPath) - })?.id ?? null, - repoPath - ), - { timeout, message: 'paired client never received the large-tree worktree' } - ) - .not.toBeNull() - return page.evaluate((targetPath) => { - const state = window.__store?.getState() - const worktree = state?.allWorktrees().find((entry) => { - const normalize = (value: string): string => - value.startsWith('/private/var/') ? value.slice('/private'.length) : value - return normalize(entry.path) === normalize(targetPath) - }) - if (!state || !worktree) { - throw new Error('large-tree worktree is unavailable') - } - state.setActiveRepo(worktree.repoId) - state.setActiveWorktree(worktree.id) - return worktree.id - }, repoPath) -} - -async function openQuickOpen(page: Page): Promise { - await page.evaluate(() => window.__store?.getState().openModal('quick-open')) - await expect(page.getByRole('dialog', { name: 'Go to file' })).toBeVisible() -} - -async function expectQuickOpenAndRuntimeHealthy( - client: PairedElectronClient, - worktreeId: string, - fixture: PairedQuickOpenLargeTreeFixture -): Promise { - const dialog = client.page.getByRole('dialog', { name: 'Go to file' }) - const input = dialog.getByPlaceholder('Go to file...') - const loading = dialog.getByText('Loading files...') - await client.page.clock.install() - const queryOracle = async (targetPath: string) => - client.page.evaluate( - async ({ environmentId, worktreeId, targetPath }) => { - const query = targetPath.split('/').at(-1)! - const response = await window.api.runtimeEnvironments.call({ - selector: environmentId, - method: 'files.searchPaths', - params: { worktree: `id:${worktreeId}`, query, limit: 32, mode: 'quick-open' } - }) - if (!response.ok) { - throw new Error(`files.searchPaths oracle failed: ${JSON.stringify(response)}`) - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: runtimeEnvironments.call is untyped at the IPC boundary; files.searchPaths answers RuntimeFileListResult. - const result = response.result as RuntimeFileListResult - const oracle = { - files: result.files.map((file) => file.relativePath), - totalCount: result.totalCount, - truncated: result.truncated - } - const encodedOracle = new TextEncoder().encode(JSON.stringify(oracle)) - const digest = await crypto.subtle.digest('SHA-256', encodedOracle) - return { - ...oracle, - oracleByteLength: encodedOracle.byteLength, - wireByteLength: new TextEncoder().encode(JSON.stringify(response.result)).byteLength, - sha256: Array.from(new Uint8Array(digest), (byte) => - byte.toString(16).padStart(2, '0') - ).join('') - } - }, - { environmentId: client.environmentId, worktreeId, targetPath } - ) - for (const targetPath of [fixture.gitIgnoredTargetPath, fixture.orcaIgnoredTargetPath]) { - const filename = targetPath.split('/').at(-1)! - const stat = await callPairedRuntime<{ size: number; isDirectory: boolean }>( - client.page, - client.environmentId, - 'files.stat', - { worktree: `id:${worktreeId}`, relativePath: targetPath } - ) - expect(stat.isDirectory).toBe(false) - expect(stat.size).toBeGreaterThanOrEqual(0) - - const queryResult = await queryOracle(targetPath) - const repeatedResult = await queryOracle(targetPath) - console.log( - `[STA-5209] query=${targetPath} oracle=${JSON.stringify(queryResult)} repeated=${JSON.stringify(repeatedResult)}` - ) - expect(queryResult).toEqual(repeatedResult) - expect(queryResult.files).toEqual([targetPath]) - expect(queryResult.totalCount).toBe(1) - expect(queryResult.truncated).toBe(false) - expect(queryResult.wireByteLength).toBeLessThan(4_096) - expect(queryResult).toMatchObject( - targetPath === fixture.gitIgnoredTargetPath - ? { - oracleByteLength: 95, - sha256: 'a6259174bf63bccb04ec461aed9b316f8ef78fe0474a6a101d4f11a383414125' - } - : { - oracleByteLength: 89, - sha256: '9e7399e32001d443105e0f612f0eb2eee88fba50902dc75c926c547538e93eb5' - } - ) - - // Why: control only the debounce; RPC deadlines and socket liveness stay on real time. - const pauseAt = await client.page.evaluate(() => Date.now() + 1_000) - await client.page.clock.pauseAt(pauseAt) - await input.fill(filename.slice(0, 8)) - await input.fill(filename.slice(0, 18)) - await input.fill(filename) - await expect(loading).toBeVisible() - await client.page.clock.runFor(QUICK_OPEN_SEARCH_DEBOUNCE_MS) - await client.page.clock.resume() - await expect(dialog.getByRole('option').filter({ hasText: filename })).toHaveCount(1, { - timeout: 60_000 - }) - await expect(loading).toHaveCount(0) - await expect(dialog).not.toContainText('Outbound reply buffer overflow') - await expect(dialog).not.toContainText('Remote Orca runtime closed the connection') - } - - const { worktrees } = await callPairedRuntime( - client.page, - client.environmentId, - 'worktree.list', - { limit: 10_000 } - ) - expect(worktrees.some((worktree) => worktree.id === worktreeId)).toBe(true) -} - -test('finds paths beyond the old prefix on a headed paired runtime @headful', async ({ - orcaPage -}, testInfo) => { - test.setTimeout(240_000) - const fixture = createPairedQuickOpenLargeTreeFixture() - let client: PairedElectronClient | null = null - try { - await waitForSessionReady(orcaPage) - await orcaPage.evaluate(async (repoPath) => { - const store = window.__store - if (!store || !(await store.getState().addRepoPath(repoPath))) { - throw new Error('headed host could not add the large-tree repo') - } - }, fixture.root) - client = await launchPairedElectronClient( - await createRuntimeDesktopPairingOffer(orcaPage), - testInfo, - 'STA-4354 headed host' - ) - const worktreeId = await activateWorktree(client.page, fixture.root) - await openQuickOpen(client.page) - await expectQuickOpenAndRuntimeHealthy(client, worktreeId, fixture) - } finally { - await client?.dispose() - fixture.dispose() - } -}) - -test('finds paths beyond the old prefix on a headless paired runtime', async (// oxlint-disable-next-line no-empty-pattern -- Playwright requires fixture destructuring. -{}, testInfo) => { - test.setTimeout(240_000) - const fixture = createPairedQuickOpenLargeTreeFixture() - const host = await launchHeadlessPairedRuntimeHost() - let client: PairedElectronClient | null = null - try { - const added = await host.client.call<{ repo: { id: string } }>('repo.add', { - path: fixture.root, - kind: 'git' - }) - await host.client.call('repo.update', { - repo: `id:${added.result.repo.id}`, - updates: { externalWorktreeVisibility: 'show' } - }) - client = await launchPairedElectronClient(host.offer, testInfo, 'STA-4354 headless host') - const worktreeId = await activateWorktree(client.page, fixture.root, 180_000) - await openQuickOpen(client.page) - await expectQuickOpenAndRuntimeHealthy(client, worktreeId, fixture) - } finally { - await client?.dispose() - await host.dispose() - fixture.dispose() - } -}) diff --git a/tests/e2e/sidebar-repo-icons.spec.ts b/tests/e2e/sidebar-repo-icons.spec.ts index 1aef15d2641..60d4fb0634e 100644 --- a/tests/e2e/sidebar-repo-icons.spec.ts +++ b/tests/e2e/sidebar-repo-icons.spec.ts @@ -4,7 +4,7 @@ import { test, expect } from './helpers/orca-app' import { SIDEBAR_INPUTS_BUILD } from './helpers/sidebar-inputs-build' import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' import { repoIconId } from '../../src/main/runtime/sidebar-inputs/repo-icon-data-urls' -import { readRasterImageDimensions } from '../../src/shared/raster-image-dimensions' +import { readRasterImageDimensions } from '../../src/shared/file-preview/raster-image-dimensions' test.skip( !SIDEBAR_INPUTS_BUILD,