Skip to content

refactor(ipc): split main-process IPC modules under the max-lines budget - #14703

Merged
nwparker merged 1 commit into
mainfrom
nwparker/downsize-03-main-ipc
Aug 16, 2026
Merged

nwparker merged 1 commit into
mainfrom
nwparker/downsize-03-main-ipc

Conversation

@nwparker

@nwparker nwparker commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 40 +100 −57 +43
Prod 57 +2975 −2711 +264

What

Splits the six oversized src/main/ipc modules into focused modules, removes their eslint-disable max-lines suppressions, and prunes the six corresponding entries from the max-lines ratchet baseline (341 → 335).

No behavior change.

Why

Each file carried a file-level max-lines suppression and ran 427–671 counted lines against a 300-line budget. Per AGENTS.md → "Do Not Disable Max Lines", the fix is to split, not suppress; config/max-lines-baseline.txt is a shrink-only ratchet.

How it was split

Target Was Now Extracted
filesystem-mutations.ts 671 265 import-result types, SSH import, local import, path guards
notifications.ts 599 189 notification-sound-selection, notification-sound-ipc, native-notification-lifecycle, notification-permission-probe, notification-system-settings-link, notification-burst-cooldown, native-notification-delivery
crash-reporting.ts 551 110 crash-reporting-renderer-error-report, crash-reporting-renderer-breadcrumbs, crash-reporting-sender, diagnostics copy
filesystem-auth.ts 463 193 filesystem-path-containment, filesystem-allowed-roots, registered-worktree-roots-cache
remote-workspace.ts 437 171 remote-workspace-snapshot-normalization, -relay-sync, -connected-clients, -snapshot-cache, -patch-queue, -client-identity
pet.ts 427 157 pet-image-formats, pet-storage-paths, pet-import-size-limits, pet-symlink-safe-copy, pet-bundle-manifest-schema, pet-bundle-spritesheet-source, pet-bundle-sprite-metadata, pet-bundle-import

filesystem-auth.ts is a security boundary, so its split preserves a strictly acyclic layering — containment primitives → config-derived allow-list → git-registered root cache → path-resolution orchestration — with no layer gaining a back-edge.

No barrel exports; every new module owns real logic and importers point at the owner.

Verification

  • npx oxlint (whole repo) — clean
  • pnpm check:max-lines-ratchet — passes; baseline 341 → 335
  • pnpm typecheck (node + cli + web) — clean
  • pnpm test — full suite green; the one remaining failure is a pre-existing load-induced timeout in a file this branch does not touch, verified passing when re-run serially
  • No new runtime import cycles among 617 modules (type-only edges excluded — erased at compile time)
  • No eslint/oxlint-disable directive added anywhere, confirmed by diff grep

IPC surface proved intact. Comparing (method, channel) multisets between HEAD and the split gives 49 registrations across 49 distinct channels on both sides — nothing added, dropped, duplicated, or switched between handle/on/removeHandler. The comparison is deliberately multi-line tolerant: oxfmt reflows ipcMain.handle('x', …) across lines once a handler body moves out, so a line-anchored grep reports false positives.

Independent adversarial review of all six splits, each instructed to refute the "pure move" claim — checking for duplicated module state, reordered import-time side effects, circular imports, hoisting and this-binding changes, and ??/|| drift. All clean.

One real issue was caught and fixed during review: the filesystem-auth split had added a vi.mock block that pushed clipboard-ipc-handlers.test.ts from 798 to 801 counted lines, breaking the 800-line test budget. Rather than suppress it, the redundant mock was dropped — its isENOENT stub was byte-identical to the real implementation — and realpath: vi.fn() added to the existing node:fs/promises mock. Net 797, assertions unchanged, all 24 tests still pass.

filesystem-auth has the largest blast radius here: 32 importers updated, all import-path-only.

Pre-existing issues found and deliberately NOT changed

  • pet.ts: pet:import copies the picked image with plain copyFile and skips the isSymlink probe, unlike the bundle path which uses copyFileNoFollow.
  • pet.ts: the legacy-image branch of resolvePetFile does a case-sensitive startsWith prefix check with no win32 lowercase normalization, unlike the bundle-escape check.
  • remote-workspace-relay-sync.ts: in requestPatch's catch, both the -32601 branch and the generic branch produce reason: 'unavailable' and differ only in message, so the ternary is effectively dead structure.
  • remote-workspace.ts: _resetRemoteWorkspaceCachesForTests does not reset mainWindowGetter or unregisterRemoteWorkspaceNotifications, so a test that registers handlers leaks the window getter across cases.
  • notifications.ts: probeNotificationDelivery sets the session-prompted flag before constructing the probe, so a throwing constructor still marks the session prompted; and re-calling registerNotificationHandlers nulls deliveryProbeInFlight while a probe may still be in flight, orphaning its finally.

@coderabbitai

coderabbitai Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3e45b834-4f61-4725-b713-5f927359547c

📥 Commits

Reviewing files that changed from the base of the PR and between c8fe5fc and 03b93ce.

📒 Files selected for processing (97)
  • config/max-lines-baseline.txt
  • src/main/ai-vault/session-delete.ts
  • src/main/index.ts
  • src/main/ipc/crash-reporting-renderer-breadcrumbs.ts
  • src/main/ipc/crash-reporting-renderer-error-report.ts
  • src/main/ipc/crash-reporting-sendable-reports.ts
  • src/main/ipc/crash-reporting-submission.ts
  • src/main/ipc/crash-reporting.ts
  • src/main/ipc/filesystem-allowed-roots.ts
  • src/main/ipc/filesystem-auth.test.ts
  • src/main/ipc/filesystem-auth.ts
  • src/main/ipc/filesystem-branch-compare-diff.test.ts
  • src/main/ipc/filesystem-commit-message-generation.test.ts
  • src/main/ipc/filesystem-commit-message-model-discovery.test.ts
  • src/main/ipc/filesystem-create-path-guards.ts
  • src/main/ipc/filesystem-download-folder.ts
  • src/main/ipc/filesystem-download-transfers.test.ts
  • src/main/ipc/filesystem-git-commit-dispatch.test.ts
  • src/main/ipc/filesystem-git-status-staging.test.ts
  • src/main/ipc/filesystem-import-local-tree-copy.ts
  • src/main/ipc/filesystem-import-local.ts
  • src/main/ipc/filesystem-import-result-types.ts
  • src/main/ipc/filesystem-import-ssh-path-safety.test.ts
  • src/main/ipc/filesystem-import-ssh.ts
  • src/main/ipc/filesystem-markdown-document-listing.test.ts
  • src/main/ipc/filesystem-mutations.ts
  • src/main/ipc/filesystem-path-containment.ts
  • src/main/ipc/filesystem-pull-request-field-generation.test.ts
  • src/main/ipc/filesystem-runtime-upload-staging.ts
  • src/main/ipc/filesystem-search-rg-timeout.test.ts
  • src/main/ipc/filesystem.test.ts
  • src/main/ipc/filesystem.ts
  • src/main/ipc/folder-repo-git-upgrade.test.ts
  • src/main/ipc/folder-repo-git-upgrade.ts
  • src/main/ipc/git-status-upstream-ref-watch-request.test.ts
  • src/main/ipc/git-status-upstream-ref-watch-request.ts
  • src/main/ipc/hosted-review.test.ts
  • src/main/ipc/hosted-review.ts
  • src/main/ipc/native-notification-delivery.ts
  • src/main/ipc/native-notification-lifecycle.ts
  • src/main/ipc/notification-burst-cooldown.ts
  • src/main/ipc/notification-permission-probe.ts
  • src/main/ipc/notification-sound-ipc.ts
  • src/main/ipc/notification-sound-selection.ts
  • src/main/ipc/notification-system-settings-link.ts
  • src/main/ipc/notifications-permission-onboarding.test.ts
  • src/main/ipc/notifications.ts
  • src/main/ipc/pet-bundle-import.ts
  • src/main/ipc/pet-bundle-manifest-schema.ts
  • src/main/ipc/pet-bundle-sprite-metadata.ts
  • src/main/ipc/pet-bundle-spritesheet-source.ts
  • src/main/ipc/pet-image-formats.ts
  • src/main/ipc/pet-import-size-limits.ts
  • src/main/ipc/pet-storage-paths.ts
  • src/main/ipc/pet-symlink-safe-copy.ts
  • src/main/ipc/pet.ts
  • src/main/ipc/registered-worktree-roots-cache.ts
  • src/main/ipc/remote-workspace-cache.test.ts
  • src/main/ipc/remote-workspace-client-identity.ts
  • src/main/ipc/remote-workspace-connected-clients.ts
  • src/main/ipc/remote-workspace-patch-queue.ts
  • src/main/ipc/remote-workspace-relay-sync.ts
  • src/main/ipc/remote-workspace-snapshot-cache.ts
  • src/main/ipc/remote-workspace-snapshot-normalization.ts
  • src/main/ipc/remote-workspace.test.ts
  • src/main/ipc/remote-workspace.ts
  • src/main/ipc/repos-add-linked-worktree.test.ts
  • src/main/ipc/repos-create.test.ts
  • src/main/ipc/repos-execution-host-catalog.test.ts
  • src/main/ipc/repos-local-add-and-project-setup.test.ts
  • src/main/ipc/repos-local-clone-lifecycle.test.ts
  • src/main/ipc/repos-nested-import.test.ts
  • src/main/ipc/repos-nested-scan.test.ts
  • src/main/ipc/repos-picker.test.ts
  • src/main/ipc/repos-remote-base-ref-queries.test.ts
  • src/main/ipc/repos-remote-client-events.test.ts
  • src/main/ipc/repos-remote-git-username.test.ts
  • src/main/ipc/repos-remote-test-harness.ts
  • src/main/ipc/repos-remote.test.ts
  • src/main/ipc/repos-sparse-presets.test.ts
  • src/main/ipc/repos.ts
  • src/main/ipc/startup-notification-registration.ts
  • src/main/ipc/worktree-remote.ts
  • src/main/ipc/worktrees-detected-scan-cache.test.ts
  • src/main/ipc/worktrees-forget-local.test.ts
  • src/main/ipc/worktrees-local-create-flow.test.ts
  • src/main/ipc/worktrees-test-harness.ts
  • src/main/ipc/worktrees.ts
  • src/main/runtime/fit-override-integration.test.ts
  • src/main/runtime/mobile-presence-lock.test.ts
  • src/main/runtime/mobile-subscribe-integration.test.ts
  • src/main/runtime/orca-runtime-files.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/remote-desktop-driver.test.ts
  • src/main/window/clipboard-ipc-handlers.test.ts
  • src/main/window/clipboard-ipc-handlers.ts

📝 Walkthrough

Walkthrough

The change extracts crash reporting, filesystem authorization and import logic, native notification handling, pet bundle importing, and remote workspace synchronization into dedicated modules. It adds validation, sanitization, caching, deduplication, safe file handling, lifecycle management, and structured IPC results. Existing handlers and tests are updated to use the new module boundaries.solete max-lines baseline entries are removed.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 21.62% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description explains the refactor and verification, but it omits required sections including Linked Issue, Visual Proof, Testing, Review, Checklist, and Author. Add the missing template sections, include the linked issue, state N/A with a reason for Visual Proof, and document testing, review, checklist, and author details.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the main refactor: splitting oversized main-process IPC modules to meet the max-lines budget.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🧹 Nitpick comments (10)
src/main/ipc/crash-reporting-renderer-breadcrumbs.ts (1)

49-69: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Extract the repeated breadcrumb name into a constant.

'terminal_safe_fit_retry_exhausted' appears at Line 54 and Line 69. The other coalesced names already use named constants. A named constant prevents the two sets from drifting.

♻️ Proposed refactor
 const DUPLICATE_TAB_OWNER_BREADCRUMB = 'terminal_tab_id_owned_by_multiple_worktrees'
 const PARK_VERDICT_CHURN_BREADCRUMB = 'terminal_park_verdict_churn'
+const SAFE_FIT_RETRY_EXHAUSTED_BREADCRUMB = 'terminal_safe_fit_retry_exhausted'
 const COALESCED_RENDERER_BREADCRUMB_NAMES = new Set([
   'renderer_error',
   'renderer_unhandled_rejection',
-  'terminal_safe_fit_retry_exhausted',
+  SAFE_FIT_RETRY_EXHAUSTED_BREADCRUMB,
   DUPLICATE_TAB_OWNER_BREADCRUMB,
   PARK_VERDICT_CHURN_BREADCRUMB,
   TERMINAL_WEBGL_DIAGNOSTIC_BREADCRUMB
 ])
@@
-const NAME_ONLY_COALESCED_BREADCRUMB_NAMES = new Set(['terminal_safe_fit_retry_exhausted'])
+const NAME_ONLY_COALESCED_BREADCRUMB_NAMES = new Set([SAFE_FIT_RETRY_EXHAUSTED_BREADCRUMB])
src/main/ipc/crash-reporting-renderer-error-report.ts (1)

65-91: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Compute each optional field once.

Every optional field calls stringField or nullableStringField twice with the same max length. The duplicated length literals can drift between the guard and the assigned value. Bind each result to a local first.

♻️ Proposed refactor (pattern for all optional fields)
+  const errorStack = stringField(record.errorStack, 8_000)
+  const componentStack = stringField(record.componentStack, 8_000)
+  const activeView = stringField(record.activeView, 80)
+  const activeModal = nullableStringField(record.activeModal, 80)
+  const activeTabType = stringField(record.activeTabType, 80)
+  const activeRightSidebarTab = stringField(record.activeRightSidebarTab, 80)
+
   return {
     boundaryId,
     surface: surface as ReactErrorBoundaryReportArgs['surface'],
     errorName,
     errorMessage,
-    ...(stringField(record.errorStack, 8_000)
-      ? { errorStack: stringField(record.errorStack, 8_000) }
-      : {}),
-    ...(stringField(record.componentStack, 8_000)
-      ? { componentStack: stringField(record.componentStack, 8_000) }
-      : {}),
-    ...(stringField(record.activeView, 80)
-      ? { activeView: stringField(record.activeView, 80) }
-      : {}),
-    ...(nullableStringField(record.activeModal, 80) !== undefined
-      ? { activeModal: nullableStringField(record.activeModal, 80) ?? null }
-      : {}),
-    ...(stringField(record.activeTabType, 80)
-      ? { activeTabType: stringField(record.activeTabType, 80) }
-      : {}),
-    ...(stringField(record.activeRightSidebarTab, 80)
-      ? { activeRightSidebarTab: stringField(record.activeRightSidebarTab, 80) }
-      : {}),
+    ...(errorStack ? { errorStack } : {}),
+    ...(componentStack ? { componentStack } : {}),
+    ...(activeView ? { activeView } : {}),
+    ...(activeModal !== undefined ? { activeModal } : {}),
+    ...(activeTabType ? { activeTabType } : {}),
+    ...(activeRightSidebarTab ? { activeRightSidebarTab } : {}),
     ...(typeof record.hasActiveWorktree === 'boolean'
       ? { hasActiveWorktree: record.hasActiveWorktree }
       : {})
   }
src/main/ipc/pet-symlink-safe-copy.ts (1)

7-11: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick win

Check for a symlink in the Windows fallback path.

On Windows, O_NOFOLLOW is absent, so copyFile runs and follows a symlink at src. The function then provides no no-follow guarantee on that platform. Add an lstat check immediately before the copy to narrow the swap window.

As per coding guidelines: "Keep platform-dependent behavior behind runtime checks for macOS, Linux, and Windows."

♻️ Proposed change
   if (noFollow === 0) {
+    // Windows has no O_NOFOLLOW; re-check immediately before the copy.
+    if (await isSymlink(src)) {
+      throw new Error('Refusing to copy a symlink.')
+    }
     await copyFile(src, dest)
     return
   }

Source: Coding guidelines

src/main/ipc/remote-workspace-connected-clients.ts (1)

49-70: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Query presence in parallel per target.

The loop awaits each workspace.presence request in sequence, so total latency is the sum of all target latencies. One slow relay delays every remaining target and the remoteWorkspace:listConnectedClients reply. registerRemoteWorkspaceHandlers in src/main/ipc/remote-workspace.ts Lines 139-149 already fans out per-target work with Promise.all for this reason. The per-target try/catch keeps failures isolated when the requests run concurrently.

♻️ Proposed refactor
-  const results: { targetId: string; clients: RemoteWorkspaceConnectedClient[] }[] = []
-  for (const target of targets) {
-    const mux = getActiveMultiplexer(target.id)
-    if (!mux) {
-      continue
-    }
-    const namespace = getRemoteWorkspaceNamespace(target)
-    try {
-      const raw = await mux.request('workspace.presence', {
-        namespace,
-        clientId: CLIENT_ID,
-        clientName: CLIENT_NAME
-      })
-      results.push({
-        targetId: target.id,
-        clients: normalizeConnectedClients(raw, CLIENT_ID)
-      })
-    } catch {
-      results.push({ targetId: target.id, clients: [] })
-    }
-  }
-  return results
+  const settled = await Promise.all(
+    targets.map(async (target) => {
+      const mux = getActiveMultiplexer(target.id)
+      if (!mux) {
+        return null
+      }
+      const namespace = getRemoteWorkspaceNamespace(target)
+      try {
+        const raw = await mux.request('workspace.presence', {
+          namespace,
+          clientId: CLIENT_ID,
+          clientName: CLIENT_NAME
+        })
+        return { targetId: target.id, clients: normalizeConnectedClients(raw, CLIENT_ID) }
+      } catch {
+        return { targetId: target.id, clients: [] }
+      }
+    })
+  )
+  return settled.filter(
+    (entry): entry is { targetId: string; clients: RemoteWorkspaceConnectedClient[] } =>
+      entry !== null
+  )
src/main/ipc/filesystem-create-path-guards.ts (1)

32-43: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Move the "already exists" throw out of the try block.

The Error created at Line 35 is thrown inside the try, so the local catch receives it. The code works only because isENOENT returns false and rethrows it. A later change to the catch predicate would silently swallow the guard. Use a flag or return-based flow instead.

♻️ Proposed refactor
 export async function assertNotExists(targetPath: string): Promise<void> {
+  let exists = true
   try {
     await lstat(targetPath)
-    throw new Error(
-      `A file or folder named '${basename(targetPath)}' already exists in this location`
-    )
   } catch (error) {
     if (!isENOENT(error)) {
       throw error
     }
+    exists = false
+  }
+  if (exists) {
+    throw new Error(
+      `A file or folder named '${basename(targetPath)}' already exists in this location`
+    )
   }
 }
src/main/ipc/filesystem-runtime-upload-staging.ts (1)

11-12: 🚀 Performance & Scalability | 🔵 Trivial | 🏗️ Heavy lift

The total-byte budget applies per source, not per staging request.

stageDirectoryEntries creates a new totalBytes counter for each source, and stageOneSourceForRuntimeUpload stages one source per call. The caller in src/main/ipc/filesystem-mutations.ts loops over args.sourcePaths and collects every result. A drop of N sources can therefore hold up to N × 100 MiB of file content, plus about 33% more for base64 encoding, in the main process before the IPC reply is serialized.

This behavior is unchanged by the extraction. Consider threading a shared budget across the loop so the cap is per request.

Also applies to: 199-210

src/main/ipc/filesystem-import-local-tree-copy.ts (1)

26-30: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Update the stale JSDoc. The comment states the function uses copyFile for individual files. The implementation calls copyLocalFileNoFollow, which streams from an O_NOFOLLOW handle and never calls copyFile. Describe the actual behavior so the security rationale stays accurate.

📝 Proposed doc fix
 /**
  * Recursively copy a directory and all its contents. Uses copyFile for
- * individual files to leverage native OS copy primitives instead of
- * buffering entire files into memory.
+ * Recursively copy a directory and all its contents. Files are copied by
+ * streaming from an O_NOFOLLOW handle, which pins the validated file
+ * identity and avoids buffering entire files into memory.
  */
src/main/ipc/notification-permission-probe.ts (1)

40-112: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Consider guarding the probe construction and show() against synchronous throws.

Line 46 constructs the Notification outside the promise. Line 106 calls probe.show() inside the promise executor.

Two consequences:

  • If new Notification(...) throws, probeNotificationDelivery throws synchronously. Line 44 already set permissionDialogTriggeredThisSession = true, so notifications.ts never retries the trigger path for the rest of the session.
  • If probe.show() throws, the executor rejects deliveryProbeInFlight. notifications.ts returns that promise directly from the notifications:probeDelivery handler, so the renderer receives an IPC error instead of a NotificationDeliveryProbeResult. The void probeNotificationDelivery() call site also produces an unhandled rejection.

A try/catch that resolves { state: 'blocked', authoritative: false } keeps the contract intact.

♻️ Proposed hardening
     probe.once('show', onShow)
     probe.once('failed', onFailed)
     // Why: don't record 'failed' on timeout — a missing callback is ambiguous, only the 'failed' event is definitive.
     timeoutTimer = setTimeout(() => {
       if (!settled) {
         settled = true
         resolve({ state: 'blocked', authoritative: false })
         releaseProbe()
       }
     }, NOTIFICATION_PROBE_RESULT_TIMEOUT_MS)
     if (typeof timeoutTimer.unref === 'function') {
       timeoutTimer.unref()
     }
 
-    probe.show()
+    try {
+      probe.show()
+    } catch {
+      // Why: a presenter that refuses the request is indistinguishable from a denial.
+      settled = true
+      if (timeoutTimer) {
+        clearTimeout(timeoutTimer)
+        timeoutTimer = null
+      }
+      resolve({ state: 'blocked', authoritative: false })
+      releaseProbe()
+    }
   }).finally(() => {
src/main/ipc/notification-sound-ipc.ts (1)

58-60: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Log the read failure before returning 'read-failed'.

The catch discards the error. A missing or unreadable custom sound file then produces no main-process diagnostic, which makes user reports hard to act on. Log the path and error at warn level.

src/main/ipc/notification-system-settings-link.ts (1)

12-18: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

Handle shell.openExternal failures

Attach .catch() to both shell.openExternal calls. void does not handle rejected promises.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 99b078fe-a0ca-4726-b390-2e7e02bfe4de

📥 Commits

Reviewing files that changed from the base of the PR and between 3908978 and 06e4906.

📒 Files selected for processing (76)
  • config/max-lines-baseline.txt
  • src/main/ai-vault/session-delete.ts
  • src/main/index.ts
  • src/main/ipc/crash-reporting-renderer-breadcrumbs.ts
  • src/main/ipc/crash-reporting-renderer-error-report.ts
  • src/main/ipc/crash-reporting-sendable-reports.ts
  • src/main/ipc/crash-reporting-submission.ts
  • src/main/ipc/crash-reporting.ts
  • src/main/ipc/filesystem-allowed-roots.ts
  • src/main/ipc/filesystem-auth.test.ts
  • src/main/ipc/filesystem-auth.ts
  • src/main/ipc/filesystem-create-path-guards.ts
  • src/main/ipc/filesystem-download-folder.ts
  • src/main/ipc/filesystem-import-local-tree-copy.ts
  • src/main/ipc/filesystem-import-local.ts
  • src/main/ipc/filesystem-import-result-types.ts
  • src/main/ipc/filesystem-import-ssh-path-safety.test.ts
  • src/main/ipc/filesystem-import-ssh.ts
  • src/main/ipc/filesystem-mutations.ts
  • src/main/ipc/filesystem-path-containment.ts
  • src/main/ipc/filesystem-runtime-upload-staging.ts
  • src/main/ipc/filesystem-search-rg-timeout.test.ts
  • src/main/ipc/filesystem.test.ts
  • src/main/ipc/filesystem.ts
  • src/main/ipc/git-status-upstream-ref-watch-request.test.ts
  • src/main/ipc/git-status-upstream-ref-watch-request.ts
  • src/main/ipc/hosted-review.test.ts
  • src/main/ipc/hosted-review.ts
  • src/main/ipc/native-notification-delivery.ts
  • src/main/ipc/native-notification-lifecycle.ts
  • src/main/ipc/notification-burst-cooldown.ts
  • src/main/ipc/notification-permission-probe.ts
  • src/main/ipc/notification-sound-ipc.ts
  • src/main/ipc/notification-sound-selection.ts
  • src/main/ipc/notification-system-settings-link.ts
  • src/main/ipc/notifications.test.ts
  • src/main/ipc/notifications.ts
  • src/main/ipc/pet-bundle-import.ts
  • src/main/ipc/pet-bundle-manifest-schema.ts
  • src/main/ipc/pet-bundle-sprite-metadata.ts
  • src/main/ipc/pet-bundle-spritesheet-source.ts
  • src/main/ipc/pet-image-formats.ts
  • src/main/ipc/pet-import-size-limits.ts
  • src/main/ipc/pet-storage-paths.ts
  • src/main/ipc/pet-symlink-safe-copy.ts
  • src/main/ipc/pet.ts
  • src/main/ipc/registered-worktree-roots-cache.ts
  • src/main/ipc/remote-workspace-cache.test.ts
  • src/main/ipc/remote-workspace-client-identity.ts
  • src/main/ipc/remote-workspace-connected-clients.ts
  • src/main/ipc/remote-workspace-patch-queue.ts
  • src/main/ipc/remote-workspace-relay-sync.ts
  • src/main/ipc/remote-workspace-snapshot-cache.ts
  • src/main/ipc/remote-workspace-snapshot-normalization.ts
  • src/main/ipc/remote-workspace.test.ts
  • src/main/ipc/remote-workspace.ts
  • src/main/ipc/repos-add-linked-worktree.test.ts
  • src/main/ipc/repos-create.test.ts
  • src/main/ipc/repos-picker.test.ts
  • src/main/ipc/repos-remote-client-events.test.ts
  • src/main/ipc/repos-remote.test.ts
  • src/main/ipc/repos-sparse-presets.test.ts
  • src/main/ipc/repos.ts
  • src/main/ipc/startup-notification-registration.ts
  • src/main/ipc/worktree-remote.ts
  • src/main/ipc/worktrees.test.ts
  • src/main/ipc/worktrees.ts
  • src/main/runtime/fit-override-integration.test.ts
  • src/main/runtime/mobile-presence-lock.test.ts
  • src/main/runtime/mobile-subscribe-integration.test.ts
  • src/main/runtime/orca-runtime-files.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/remote-desktop-driver.test.ts
  • src/main/window/clipboard-ipc-handlers.test.ts
  • src/main/window/clipboard-ipc-handlers.ts
💤 Files with no reviewable changes (1)
  • config/max-lines-baseline.txt

Comment on lines +90 to +98
} catch (error) {
if (destinationCreated) {
await unlink(dstPath).catch(() => {})
}
throw error
} finally {
await sourceHandle.close().catch(() => {})
await destinationHandle?.close().catch(() => {})
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Close the destination handle before you unlink it. The catch block runs before the finally block. unlink(dstPath) therefore executes while destinationHandle is still open. On Windows, unlinking an open file fails with EPERM/EBUSY, and .catch(() => {}) hides the failure. A single-file import then leaves a partial destination file, because only directory imports are rolled back by rm in src/main/ipc/filesystem-import-local.ts (Line 86).

Close both handles first, then remove the partial destination.

🔧 Proposed fix
-  } catch (error) {
-    if (destinationCreated) {
-      await unlink(dstPath).catch(() => {})
-    }
-    throw error
-  } finally {
-    await sourceHandle.close().catch(() => {})
-    await destinationHandle?.close().catch(() => {})
-  }
+  } catch (error) {
+    // Why: Windows refuses unlink on an open handle, so close before cleanup.
+    await destinationHandle?.close().catch(() => {})
+    destinationHandle = null
+    if (destinationCreated) {
+      await unlink(dstPath).catch(() => {})
+    }
+    throw error
+  } finally {
+    await sourceHandle.close().catch(() => {})
+    await destinationHandle?.close().catch(() => {})
+  }

Keep platform-dependent behavior behind runtime checks for macOS, Linux, and Windows. As per coding guidelines.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
} catch (error) {
if (destinationCreated) {
await unlink(dstPath).catch(() => {})
}
throw error
} finally {
await sourceHandle.close().catch(() => {})
await destinationHandle?.close().catch(() => {})
}
} catch (error) {
// Why: Windows refuses unlink on an open handle, so close before cleanup.
await destinationHandle?.close().catch(() => {})
destinationHandle = null
if (destinationCreated) {
await unlink(dstPath).catch(() => {})
}
throw error
} finally {
await sourceHandle.close().catch(() => {})
await destinationHandle?.close().catch(() => {})
}

Source: Coding guidelines

Comment on lines +34 to +36
if (await isSymlink(sheetSrc)) {
throw new Error('spritesheet must not be a symlink.')
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win

Add a realpath containment check for intermediate directory symlinks.

isSymlink inspects the final component only. copyFileNoFollow also applies O_NOFOLLOW to the final component only. If spritesheetPath traverses a symlinked directory inside the bundle, for example link/sheet.png where <bundleDir>/link points outside the bundle, the lexical prefix check on Line 31 still passes and the file is copied from outside the bundle.

Resolve both paths and repeat the containment check.

🛡️ Proposed fix
-import { stat } from 'node:fs/promises'
+import { realpath, stat } from 'node:fs/promises'
+  // Why: O_NOFOLLOW and lstat only guard the leaf — resolve to catch symlinked parent directories.
+  const realSheetSrc = await realpath(sheetSrc).catch(() => null)
+  const realBundle = await realpath(bundleResolved).catch(() => null)
+  if (!realSheetSrc || !realBundle || !cmp(realSheetSrc + sep).startsWith(cmp(realBundle + sep))) {
+    throw new Error('spritesheetPath escapes the bundle.')
+  }
   if (await isSymlink(sheetSrc)) {
     throw new Error('spritesheet must not be a symlink.')
   }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (await isSymlink(sheetSrc)) {
throw new Error('spritesheet must not be a symlink.')
}
// Resolve parent symlinks before copying.
const realSheetSrc = await realpath(sheetSrc).catch(() => null)
const realBundle = await realpath(bundleResolved).catch(() => null)
if (!realSheetSrc || !realBundle || !cmp(realSheetSrc + sep).startsWith(cmp(realBundle + sep))) {
throw new Error('spritesheetPath escapes the bundle.')
}
if (await isSymlink(sheetSrc)) {
throw new Error('spritesheet must not be a symlink.')
}

Comment on lines +33 to +67
function normalizeRemoteSession(raw: unknown): RemoteWorkspaceSession {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
return emptyRemoteSession()
}
const input = raw as Partial<RemoteWorkspaceSession>
return {
activeWorktreePath:
typeof input.activeWorktreePath === 'string' ? input.activeWorktreePath : null,
activeTabId: typeof input.activeTabId === 'string' ? input.activeTabId : null,
tabsByWorktreePath:
input.tabsByWorktreePath &&
typeof input.tabsByWorktreePath === 'object' &&
!Array.isArray(input.tabsByWorktreePath)
? input.tabsByWorktreePath
: {},
terminalLayoutsByTabId:
input.terminalLayoutsByTabId &&
typeof input.terminalLayoutsByTabId === 'object' &&
!Array.isArray(input.terminalLayoutsByTabId)
? input.terminalLayoutsByTabId
: {},
activeWorktreePathsOnShutdown: normalizeOptionalStringArray(
input.activeWorktreePathsOnShutdown
),
activeTabIdByWorktreePath: normalizeOptionalRecord<Record<string, string | null>>(
input.activeTabIdByWorktreePath
),
remoteSessionIdsByTabId: normalizeOptionalRecord<Record<string, string>>(
input.remoteSessionIdsByTabId
),
lastVisitedAtByWorktreePath: normalizeOptionalRecord<Record<string, number>>(
input.lastVisitedAtByWorktreePath
)
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Confirm the session field contract and any intentional exclusion.
rg -n 'defaultTerminalTabsAppliedByWorktreePath' --type=ts -C3
rg -n 'exportRemoteWorkspaceSession' --type=ts -C5

Repository: stablyai/orca

Length of output: 151


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- candidate files ---'
fd -i 'remote-workspace' .
printf '%s\n' '--- field references ---'
rg -n -C3 'defaultTerminalTabsAppliedByWorktreePath|RemoteWorkspaceSession|normalizeRemoteSession|normalizeSnapshot|remoteWorkspaceSessionMatchesSnapshot|patchRemoteWorkspaceSession' .

Repository: stablyai/orca

Length of output: 36339


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- normalization ---'
cat -n src/main/ipc/remote-workspace-snapshot-normalization.ts
printf '%s\n' '--- projection ---'
sed -n '32,190p' src/shared/remote-workspace-session-projection.ts
printf '%s\n' '--- patch path ---'
sed -n '40,115p' src/main/ipc/remote-workspace-relay-sync.ts
printf '%s\n' '--- related tests ---'
sed -n '70,165p' src/main/ipc/remote-workspace.test.ts

Repository: stablyai/orca

Length of output: 15302


🏁 Script executed:

#!/bin/bash
set -e
python3 - <<'PY'
from pathlib import Path
import re

types = Path("src/shared/remote-workspace-types.ts").read_text()
normalizer = Path("src/main/ipc/remote-workspace-snapshot-normalization.ts").read_text()
projection = Path("src/shared/remote-workspace-session-projection.ts").read_text()

field = "defaultTerminalTabsAppliedByWorktreePath"
assert re.search(rf"\b{field}\s*\?:\s*Record<string,\s*true>", types)
returned = normalizer[normalizer.index("return {", normalizer.index("function normalizeRemoteSession")):
                    normalizer.index("\n  }\n}", normalizer.index("function normalizeRemoteSession"))]
print("declared_in_remote_session_type:", True)
print("copied_by_normalize_remote_session:", bool(re.search(rf"\b{field}\s*:", returned)))
print("exported_by_projection:", bool(re.search(rf"\b{field}\s*$", projection, re.MULTILINE)))
print("imported_by_projection:", bool(re.search(rf"\b{field}\b", projection[projection.index("export function importRemoteWorkspaceSession"):])))

assert not re.search(rf"\b{field}\s*:", returned)
assert re.search(rf"\b{field}\s*$", projection, re.MULTILINE)
PY

Repository: stablyai/orca

Length of output: 289


🏁 Script executed:

#!/bin/bash
set -e
python3 - <<'PY'
from pathlib import Path
import re

types = Path("src/shared/remote-workspace-types.ts").read_text()
normalizer = Path("src/main/ipc/remote-workspace-snapshot-normalization.ts").read_text()
projection = Path("src/shared/remote-workspace-session-projection.ts").read_text()

field = "defaultTerminalTabsAppliedByWorktreePath"
assert re.search(rf"\b{field}\s*\?:\s*Record<string,\s*true>", types)
start = normalizer.index("function normalizeRemoteSession")
returned = normalizer.index("return {", start)
end = normalizer.index("\n  }\n}", returned)
body = normalizer[returned:end]

print("declared_in_remote_session_type:", True)
print("copied_by_normalize_remote_session:", bool(re.search(rf"\b{field}\s*:", body)))
print("exported_by_projection:", bool(re.search(rf"\b{field}\s*$", projection, re.MULTILINE)))
print("imported_by_projection:", bool(re.search(
    rf"\b{field}\b",
    projection[projection.index("export function importRemoteWorkspaceSession"):]
)))

assert not re.search(rf"\b{field}\s*:", body)
assert re.search(rf"\b{field}\s*$", projection, re.MULTILINE)
PY

Repository: stablyai/orca

Length of output: 289


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- flag consumers ---'
rg -n -C4 'defaultTerminalTabsAppliedByWorktreeId|defaultTerminalTabsAppliedByWorktreePath' src
printf '%s\n' '--- normalizer behavior probe ---'
python3 - <<'PY'
from pathlib import Path
import re

source = Path("src/main/ipc/remote-workspace-snapshot-normalization.ts").read_text()
field = "defaultTerminalTabsAppliedByWorktreePath"
start = source.index("function normalizeRemoteSession")
end = source.index("\n}\n\nexport function normalizeSnapshot", start)
body = source[start:end]
print("normalizer_has_field:", bool(re.search(rf"\b{field}\s*:", body)))
print("normalizer_return_keys:",
      re.findall(r"^\s{4}([A-Za-z0-9_]+):", body, re.MULTILINE))

relay = Path("src/main/ipc/remote-workspace-relay-sync.ts").read_text()
print("patch_uses_normalized_equality:",
      "remoteWorkspaceSessionMatchesSnapshot(current, session)" in relay)
print("patch_payload_is_full_session:",
      "patch: { kind: 'replace-session', session }" in relay)
PY

Repository: stablyai/orca

Length of output: 50369


Preserve defaultTerminalTabsAppliedByWorktreePath in normalizeRemoteSession.

The field is exported, imported, and used to prevent duplicate default terminal tabs. The normalizer drops it from snapshots, and marker-only changes compare equal and skip the relay patch. Add the field to the normalizer.

Comment on lines +84 to +91
// Fallback in case macOS doesn't fire the 'show' event (e.g. user denies).
fallbackTimer = setTimeout(cleanup, 10_000)
if (typeof fallbackTimer.unref === 'function') {
fallbackTimer.unref()
}

notification.show()
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Wrap notification.show() so a startup throw cannot escape.

src/main/index.ts calls triggerStartupNotificationRegistration during app startup. Line 90 calls notification.show() without a guard. If show() throws, the exception propagates into the startup path, and line 21 has already persisted notificationPermissionRequested: true, so the prompt is never retried on this install.

Catch the throw and run cleanup().

🛡️ Proposed fix
-  notification.show()
+  try {
+    notification.show()
+  } catch {
+    logNativeNotificationFailure('startup registration')
+    cleanup()
+  }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Fallback in case macOS doesn't fire the 'show' event (e.g. user denies).
fallbackTimer = setTimeout(cleanup, 10_000)
if (typeof fallbackTimer.unref === 'function') {
fallbackTimer.unref()
}
notification.show()
}
// Fallback in case macOS doesn't fire the 'show' event (e.g. user denies).
fallbackTimer = setTimeout(cleanup, 10_000)
if (typeof fallbackTimer.unref === 'function') {
fallbackTimer.unref()
}
try {
notification.show()
} catch {
logNativeNotificationFailure('startup registration')
cleanup()
}
}

@nwparker
nwparker force-pushed the nwparker/downsize-03-main-ipc branch 2 times, most recently from 5316a2a to 2f8c021 Compare August 15, 2026 10:31
The six oversized src/main/ipc modules each carried a file-level
`eslint-disable max-lines` and ran 427-671 counted lines against a 300-line
budget. AGENTS.md calls for splitting rather than suppressing, and
config/max-lines-baseline.txt is a shrink-only ratchet, so this removes all six
suppressions and prunes their entries (341 -> 335).

Pure move, no behavior change. Each file is cut along the seams it already had:
pet splits into format allowlist / storage paths / symlink-safe copy / bundle
manifest + import; filesystem-auth into path-containment primitives, the
config-derived allow-list, and the git-registered root cache; notifications into
sound selection, native lifecycle, permission probe, and burst cooldown;
crash-reporting into renderer error reports, breadcrumbs, and sender.

The IPC surface is proved intact rather than assumed: comparing (method,
channel) multisets between HEAD and the split gives 49 registrations across 49
distinct channels on both sides. filesystem-auth's security boundary keeps its
acyclic layering -- containment primitives, then allow-list, then root cache,
then path-resolution orchestration -- with no layer gaining a back-edge.

Also keeps clipboard-ipc-handlers.test.ts under the 800-line test budget. The
split had briefly added a redundant vi.mock for isENOENT (byte-identical to the
real implementation) that pushed it to 801; the mock is dropped in favor of the
real function, with realpath added to the existing node:fs/promises mock.

Verified: oxlint clean, ratchet passes, typecheck clean, full unit suite green
(the one remaining failure is a pre-existing load flake in an untouched file,
green when re-run serially), no new runtime import cycles among 617 modules,
and no lint suppression added anywhere.
@nwparker
nwparker force-pushed the nwparker/downsize-03-main-ipc branch from 2f8c021 to 03b93ce Compare August 16, 2026 01:04
@coderabbitai

coderabbitai Bot commented Aug 16, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@nwparker
nwparker merged commit 15e1ba3 into main Aug 16, 2026
45 checks passed
AmethystLiang pushed a commit that referenced this pull request Aug 17, 2026
…get (#14703)

The six oversized src/main/ipc modules each carried a file-level
`eslint-disable max-lines` and ran 427-671 counted lines against a 300-line
budget. AGENTS.md calls for splitting rather than suppressing, and
config/max-lines-baseline.txt is a shrink-only ratchet, so this removes all six
suppressions and prunes their entries (341 -> 335).

Pure move, no behavior change. Each file is cut along the seams it already had:
pet splits into format allowlist / storage paths / symlink-safe copy / bundle
manifest + import; filesystem-auth into path-containment primitives, the
config-derived allow-list, and the git-registered root cache; notifications into
sound selection, native lifecycle, permission probe, and burst cooldown;
crash-reporting into renderer error reports, breadcrumbs, and sender.

The IPC surface is proved intact rather than assumed: comparing (method,
channel) multisets between HEAD and the split gives 49 registrations across 49
distinct channels on both sides. filesystem-auth's security boundary keeps its
acyclic layering -- containment primitives, then allow-list, then root cache,
then path-resolution orchestration -- with no layer gaining a back-edge.

Also keeps clipboard-ipc-handlers.test.ts under the 800-line test budget. The
split had briefly added a redundant vi.mock for isENOENT (byte-identical to the
real implementation) that pushed it to 801; the mock is dropped in favor of the
real function, with realpath added to the existing node:fs/promises mock.

Verified: oxlint clean, ratchet passes, typecheck clean, full unit suite green
(the one remaining failure is a pre-existing load flake in an untouched file,
green when re-run serially), no new runtime import cycles among 617 modules,
and no lint suppression added anywhere.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…get (stablyai#14703)

The six oversized src/main/ipc modules each carried a file-level
`eslint-disable max-lines` and ran 427-671 counted lines against a 300-line
budget. AGENTS.md calls for splitting rather than suppressing, and
config/max-lines-baseline.txt is a shrink-only ratchet, so this removes all six
suppressions and prunes their entries (341 -> 335).

Pure move, no behavior change. Each file is cut along the seams it already had:
pet splits into format allowlist / storage paths / symlink-safe copy / bundle
manifest + import; filesystem-auth into path-containment primitives, the
config-derived allow-list, and the git-registered root cache; notifications into
sound selection, native lifecycle, permission probe, and burst cooldown;
crash-reporting into renderer error reports, breadcrumbs, and sender.

The IPC surface is proved intact rather than assumed: comparing (method,
channel) multisets between HEAD and the split gives 49 registrations across 49
distinct channels on both sides. filesystem-auth's security boundary keeps its
acyclic layering -- containment primitives, then allow-list, then root cache,
then path-resolution orchestration -- with no layer gaining a back-edge.

Also keeps clipboard-ipc-handlers.test.ts under the 800-line test budget. The
split had briefly added a redundant vi.mock for isENOENT (byte-identical to the
real implementation) that pushed it to 801; the mock is dropped in favor of the
real function, with realpath added to the existing node:fs/promises mock.

Verified: oxlint clean, ratchet passes, typecheck clean, full unit suite green
(the one remaining failure is a pre-existing load flake in an untouched file,
green when re-run serially), no new runtime import cycles among 617 modules,
and no lint suppression added anywhere.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant