Repository navigation
refactor(ipc): split main-process IPC modules under the max-lines budget - #14703
Conversation
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (97)
📝 WalkthroughWalkthroughThe 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)
✅ Passed checks (3 passed)
✨ Finishing Touches📝 Generate docstrings
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 6
🧹 Nitpick comments (10)
src/main/ipc/crash-reporting-renderer-breadcrumbs.ts (1)
49-69: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueExtract 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 winCompute each optional field once.
Every optional field calls
stringFieldornullableStringFieldtwice 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 winCheck for a symlink in the Windows fallback path.
On Windows,
O_NOFOLLOWis absent, socopyFileruns and follows a symlink atsrc. The function then provides no no-follow guarantee on that platform. Add anlstatcheck 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 winQuery presence in parallel per target.
The loop awaits each
workspace.presencerequest in sequence, so total latency is the sum of all target latencies. One slow relay delays every remaining target and theremoteWorkspace:listConnectedClientsreply.registerRemoteWorkspaceHandlersinsrc/main/ipc/remote-workspace.tsLines 139-149 already fans out per-target work withPromise.allfor this reason. The per-targettry/catchkeeps 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 winMove the "already exists" throw out of the
tryblock.The
Errorcreated at Line 35 is thrown inside thetry, so the localcatchreceives it. The code works only becauseisENOENTreturnsfalseand rethrows it. A later change to thecatchpredicate 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 liftThe total-byte budget applies per source, not per staging request.
stageDirectoryEntriescreates a newtotalBytescounter for each source, andstageOneSourceForRuntimeUploadstages one source per call. The caller insrc/main/ipc/filesystem-mutations.tsloops overargs.sourcePathsand 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 winUpdate the stale JSDoc. The comment states the function uses
copyFilefor individual files. The implementation callscopyLocalFileNoFollow, which streams from anO_NOFOLLOWhandle and never callscopyFile. 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 winConsider guarding the probe construction and
show()against synchronous throws.Line 46 constructs the
Notificationoutside the promise. Line 106 callsprobe.show()inside the promise executor.Two consequences:
- If
new Notification(...)throws,probeNotificationDeliverythrows synchronously. Line 44 already setpermissionDialogTriggeredThisSession = true, sonotifications.tsnever retries the trigger path for the rest of the session.- If
probe.show()throws, the executor rejectsdeliveryProbeInFlight.notifications.tsreturns that promise directly from thenotifications:probeDeliveryhandler, so the renderer receives an IPC error instead of aNotificationDeliveryProbeResult. Thevoid probeNotificationDelivery()call site also produces an unhandled rejection.A
try/catchthat 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 valueLog 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
warnlevel.src/main/ipc/notification-system-settings-link.ts (1)
12-18: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low valueHandle
shell.openExternalfailuresAttach
.catch()to bothshell.openExternalcalls.voiddoes 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
📒 Files selected for processing (76)
config/max-lines-baseline.txtsrc/main/ai-vault/session-delete.tssrc/main/index.tssrc/main/ipc/crash-reporting-renderer-breadcrumbs.tssrc/main/ipc/crash-reporting-renderer-error-report.tssrc/main/ipc/crash-reporting-sendable-reports.tssrc/main/ipc/crash-reporting-submission.tssrc/main/ipc/crash-reporting.tssrc/main/ipc/filesystem-allowed-roots.tssrc/main/ipc/filesystem-auth.test.tssrc/main/ipc/filesystem-auth.tssrc/main/ipc/filesystem-create-path-guards.tssrc/main/ipc/filesystem-download-folder.tssrc/main/ipc/filesystem-import-local-tree-copy.tssrc/main/ipc/filesystem-import-local.tssrc/main/ipc/filesystem-import-result-types.tssrc/main/ipc/filesystem-import-ssh-path-safety.test.tssrc/main/ipc/filesystem-import-ssh.tssrc/main/ipc/filesystem-mutations.tssrc/main/ipc/filesystem-path-containment.tssrc/main/ipc/filesystem-runtime-upload-staging.tssrc/main/ipc/filesystem-search-rg-timeout.test.tssrc/main/ipc/filesystem.test.tssrc/main/ipc/filesystem.tssrc/main/ipc/git-status-upstream-ref-watch-request.test.tssrc/main/ipc/git-status-upstream-ref-watch-request.tssrc/main/ipc/hosted-review.test.tssrc/main/ipc/hosted-review.tssrc/main/ipc/native-notification-delivery.tssrc/main/ipc/native-notification-lifecycle.tssrc/main/ipc/notification-burst-cooldown.tssrc/main/ipc/notification-permission-probe.tssrc/main/ipc/notification-sound-ipc.tssrc/main/ipc/notification-sound-selection.tssrc/main/ipc/notification-system-settings-link.tssrc/main/ipc/notifications.test.tssrc/main/ipc/notifications.tssrc/main/ipc/pet-bundle-import.tssrc/main/ipc/pet-bundle-manifest-schema.tssrc/main/ipc/pet-bundle-sprite-metadata.tssrc/main/ipc/pet-bundle-spritesheet-source.tssrc/main/ipc/pet-image-formats.tssrc/main/ipc/pet-import-size-limits.tssrc/main/ipc/pet-storage-paths.tssrc/main/ipc/pet-symlink-safe-copy.tssrc/main/ipc/pet.tssrc/main/ipc/registered-worktree-roots-cache.tssrc/main/ipc/remote-workspace-cache.test.tssrc/main/ipc/remote-workspace-client-identity.tssrc/main/ipc/remote-workspace-connected-clients.tssrc/main/ipc/remote-workspace-patch-queue.tssrc/main/ipc/remote-workspace-relay-sync.tssrc/main/ipc/remote-workspace-snapshot-cache.tssrc/main/ipc/remote-workspace-snapshot-normalization.tssrc/main/ipc/remote-workspace.test.tssrc/main/ipc/remote-workspace.tssrc/main/ipc/repos-add-linked-worktree.test.tssrc/main/ipc/repos-create.test.tssrc/main/ipc/repos-picker.test.tssrc/main/ipc/repos-remote-client-events.test.tssrc/main/ipc/repos-remote.test.tssrc/main/ipc/repos-sparse-presets.test.tssrc/main/ipc/repos.tssrc/main/ipc/startup-notification-registration.tssrc/main/ipc/worktree-remote.tssrc/main/ipc/worktrees.test.tssrc/main/ipc/worktrees.tssrc/main/runtime/fit-override-integration.test.tssrc/main/runtime/mobile-presence-lock.test.tssrc/main/runtime/mobile-subscribe-integration.test.tssrc/main/runtime/orca-runtime-files.tssrc/main/runtime/orca-runtime.test.tssrc/main/runtime/orca-runtime.tssrc/main/runtime/remote-desktop-driver.test.tssrc/main/window/clipboard-ipc-handlers.test.tssrc/main/window/clipboard-ipc-handlers.ts
💤 Files with no reviewable changes (1)
- config/max-lines-baseline.txt
| } catch (error) { | ||
| if (destinationCreated) { | ||
| await unlink(dstPath).catch(() => {}) | ||
| } | ||
| throw error | ||
| } finally { | ||
| await sourceHandle.close().catch(() => {}) | ||
| await destinationHandle?.close().catch(() => {}) | ||
| } |
There was a problem hiding this comment.
🩺 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.
| } 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
| if (await isSymlink(sheetSrc)) { | ||
| throw new Error('spritesheet must not be a symlink.') | ||
| } |
There was a problem hiding this comment.
🔒 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.
| 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.') | |
| } |
| 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 | ||
| ) | ||
| } | ||
| } |
There was a problem hiding this comment.
🗄️ 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 -C5Repository: 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.tsRepository: 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)
PYRepository: 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)
PYRepository: 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)
PYRepository: 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.
| // 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() | ||
| } |
There was a problem hiding this comment.
🩺 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.
| // 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() | |
| } | |
| } |
5316a2a to
2f8c021
Compare
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.
2f8c021 to
03b93ce
Compare
|
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. |
…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.
…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.
What
Splits the six oversized
src/main/ipcmodules into focused modules, removes theireslint-disable max-linessuppressions, and prunes the six corresponding entries from themax-linesratchet baseline (341 → 335).No behavior change.
Why
Each file carried a file-level
max-linessuppression and ran 427–671 counted lines against a 300-line budget. PerAGENTS.md→ "Do Not Disable Max Lines", the fix is to split, not suppress;config/max-lines-baseline.txtis a shrink-only ratchet.How it was split
filesystem-mutations.tsnotifications.tsnotification-sound-selection,notification-sound-ipc,native-notification-lifecycle,notification-permission-probe,notification-system-settings-link,notification-burst-cooldown,native-notification-deliverycrash-reporting.tscrash-reporting-renderer-error-report,crash-reporting-renderer-breadcrumbs,crash-reporting-sender, diagnostics copyfilesystem-auth.tsfilesystem-path-containment,filesystem-allowed-roots,registered-worktree-roots-cacheremote-workspace.tsremote-workspace-snapshot-normalization,-relay-sync,-connected-clients,-snapshot-cache,-patch-queue,-client-identitypet.tspet-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-importfilesystem-auth.tsis 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) — cleanpnpm check:max-lines-ratchet— passes; baseline 341 → 335pnpm typecheck(node + cli + web) — cleanpnpm 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 seriallyeslint/oxlint-disabledirective added anywhere, confirmed by diff grepIPC surface proved intact. Comparing
(method, channel)multisets betweenHEADand the split gives 49 registrations across 49 distinct channels on both sides — nothing added, dropped, duplicated, or switched betweenhandle/on/removeHandler. The comparison is deliberately multi-line tolerant: oxfmt reflowsipcMain.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-authsplit had added avi.mockblock that pushedclipboard-ipc-handlers.test.tsfrom 798 to 801 counted lines, breaking the 800-line test budget. Rather than suppress it, the redundant mock was dropped — itsisENOENTstub was byte-identical to the real implementation — andrealpath: vi.fn()added to the existingnode:fs/promisesmock. Net 797, assertions unchanged, all 24 tests still pass.filesystem-authhas the largest blast radius here: 32 importers updated, all import-path-only.Pre-existing issues found and deliberately NOT changed
pet.ts:pet:importcopies the picked image with plaincopyFileand skips theisSymlinkprobe, unlike the bundle path which usescopyFileNoFollow.pet.ts: the legacy-image branch ofresolvePetFiledoes a case-sensitivestartsWithprefix check with no win32 lowercase normalization, unlike the bundle-escape check.remote-workspace-relay-sync.ts: inrequestPatch's catch, both the-32601branch and the generic branch producereason: 'unavailable'and differ only inmessage, so the ternary is effectively dead structure.remote-workspace.ts:_resetRemoteWorkspaceCachesForTestsdoes not resetmainWindowGetterorunregisterRemoteWorkspaceNotifications, so a test that registers handlers leaks the window getter across cases.notifications.ts:probeNotificationDeliverysets the session-prompted flag before constructing the probe, so a throwing constructor still marks the session prompted; and re-callingregisterNotificationHandlersnullsdeliveryProbeInFlightwhile a probe may still be in flight, orphaning itsfinally.