Repository navigation
refactor(browser): split browser and browser-IPC modules under the max-lines budget - #14697
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (48)
💤 Files with no reviewable changes (2)
🚧 Files skipped from review as they are similar to previous changes (45)
📝 WalkthroughWalkthroughThe change decomposes browser functionality into dedicated modules. Guest input, screencast processing, session persistence, CDP proxy handling, snapshot generation, and browser IPC now use focused services and handlers. Existing orchestration modules delegate to these components. Tests, imports, cleanup paths, and line-count baselines were updated for the new structure. Merge Risk: 🟡 Moderate · up to The refactor preserves the existing browser behavior but still carries two unresolved risks: some accessibility references may target ID 0, and deleting a profile may leave staged cookie database files on disk. These bounded correctness and cleanup issues should be fixed or explicitly accepted before merging. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches 💡 1📝 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: 1
🧹 Nitpick comments (7)
src/main/browser/snapshot-cursor-interactive-elements.ts (1)
4-7: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueShorten or remove the implementation comments.
These comments restate visible behavior. Keep only a short comment for non-obvious policy or constraints.
As per coding guidelines, comments must be concise, non-obvious, and brief.
Also applies to: 16-17, 92-92
Source: Coding guidelines
src/main/browser/browser-session-meta-store.ts (1)
57-62: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winResolve the metadata path once per write.
persistBrowserSessionMetacallsresolveMetadataPath()four times in one write. The resolver readsmetadataPathOverrideandapp.getPath('userData')at call time. If the resolved value changes between calls, the temporary file and the rename target can point to different directories, and the rename is no longer atomic. A single local value also removes the repeated lookups.♻️ Proposed refactor
try { const existing = loadBrowserSessionMeta(resolveMetadataPath, defaultPartition) - const tmpPath = `${resolveMetadataPath()}.tmp` - mkdirSync(dirname(resolveMetadataPath()), { recursive: true }) + const metadataPath = resolveMetadataPath() + const tmpPath = `${metadataPath}.tmp` + mkdirSync(dirname(metadataPath), { recursive: true }) writeFileSync(tmpPath, JSON.stringify({ ...existing, ...updates })) - renameSync(tmpPath, resolveMetadataPath()) + renameSync(tmpPath, metadataPath) } catch {src/main/browser/browser-session-partition-policies.ts (1)
25-38: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider one shared helper for clean user-agent application.
Lines 28 and 34-38 duplicate the logic in
applyBrowserSessionUserAgentModesat lines 112-121: set the user-agent mode, clean the Electron user agent, then install the client-hints override. The two copies can drift, and only the copy ininstallBrowserSessionPartitionPoliciesguardstypeof sess.getUserAgent === 'function'. Extract a singleapplyUserAgentModeToSession(sess, profile)helper and call it from both places.Also applies to: 106-126
src/main/browser/browser-session-persisted-profile-validation.ts (1)
4-5: 🔒 Security & Privacy | 🔵 Trivial | 💤 Low valueTighten the profile-ID pattern.
Each group in
BROWSER_SESSION_PROFILE_ID_REallows-as a member character, so strings such as------------------------------------pass. The deterministic partition comparison inisProfileOwnedSessionPartitionstill confines the derived partition, so this is a strictness gap and not an exploitable path. Use[\da-f]in each group to make the check a real UUID match.♻️ Proposed refactor
-const BROWSER_SESSION_PROFILE_ID_RE = - /^[\da-f-]{8}-[\da-f-]{4}-[\da-f-]{4}-[\da-f-]{4}-[\da-f-]{12}$/ +const BROWSER_SESSION_PROFILE_ID_RE = + /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/src/main/browser/browser-session-registry.ts (1)
236-242: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick winReuse
clearPendingCookieImportindeleteProfile.
deleteProfileremoves the pending entry from the metadata map only.clearPendingBrowserCookieImportinsrc/main/browser/browser-session-cookie-staging.tsalso unlinks the staged database and its-wal/-shmsidecars. As written, the staged cookie database for a deleted profile stays on disk, so user cookie data survives profile deletion. This behavior predates the refactor, but the extracted helper now makes the fix a one-line delegation.♻️ Proposed change
this.profiles.delete(profileId) this.persistProfiles() - const meta = this.loadPersistedMeta() - const pendingCookieImports = { ...meta.pendingCookieImports } - delete pendingCookieImports[profile.partition] - this.persistMeta({ - pendingCookieImports, - pendingCookieDbPath: pendingCookieImports[this.defaultPartition] ?? null - }) + this.clearPendingCookieImport(profile.partition)src/main/browser/cdp-synthetic-session-registry.ts (1)
49-54: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueOptional: simplify the synthetic-session guard.
The expression repeats the
msgSessionIdtruthiness check three times. A single early return states the same rule.♻️ Proposed simplification
resolveDebuggerSessionId(msgSessionId?: string): string | undefined { - const syntheticSession = - (msgSessionId && this.clientSessionIds.has(msgSessionId)) || - (msgSessionId && this.clientBrowserSessionIds.has(msgSessionId)) - return msgSessionId && !syntheticSession ? msgSessionId : undefined + if (!msgSessionId) { + return undefined + } + const synthetic = + this.clientSessionIds.has(msgSessionId) || this.clientBrowserSessionIds.has(msgSessionId) + return synthetic ? undefined : msgSessionId }src/main/browser/cdp-target-discovery.ts (1)
26-28: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueOptional: hoist the Chrome version fallback to one place.
Lines 28 and 90 duplicate
process.versions.chrome ?? '134.0.0.0'. A module constant keeps the two identity responses in sync.♻️ Proposed extraction
+const CHROME_VERSION = process.versions.chrome ?? '134.0.0.0' + export class CdpTargetDiscovery {Then use
CHROME_VERSIONin bothhandleHttpRequestand theBrowser.getVersionbranch.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 1487f71b-1b32-4c96-9251-808967c98c3c
📒 Files selected for processing (48)
config/max-lines-baseline.txtsrc/main/browser/browser-guest-context-menu.tssrc/main/browser/browser-guest-grab-shortcuts.tssrc/main/browser/browser-guest-renderer-target.tssrc/main/browser/browser-guest-shortcut-dispatch.tssrc/main/browser/browser-guest-shortcut-forwarding.test.tssrc/main/browser/browser-guest-shortcut-forwarding.tssrc/main/browser/browser-guest-ui.tssrc/main/browser/browser-guest-wheel-zoom.tssrc/main/browser/browser-manager.tssrc/main/browser/browser-screencast-cdp-events.tssrc/main/browser/browser-screencast-debugger-command.tssrc/main/browser/browser-screencast-device-metrics.tssrc/main/browser/browser-screencast-frame-metadata.tssrc/main/browser/browser-screencast-frame-pacer.tssrc/main/browser/browser-screencast-snapshot-capture.tssrc/main/browser/browser-screencast-stream-types.tssrc/main/browser/browser-screencast-stream.tssrc/main/browser/browser-screencast-viewport-fit.tssrc/main/browser/browser-session-cookie-staging.tssrc/main/browser/browser-session-meta-store.tssrc/main/browser/browser-session-partition-policies.tssrc/main/browser/browser-session-persisted-profile-validation.tssrc/main/browser/browser-session-registry.tssrc/main/browser/cdp-client-response-writer.tssrc/main/browser/cdp-debugger-channel.tssrc/main/browser/cdp-dom-focus-replay.tssrc/main/browser/cdp-page-capture-commands.tssrc/main/browser/cdp-page-navigation-commands.tssrc/main/browser/cdp-synthetic-session-registry.tssrc/main/browser/cdp-target-discovery.tssrc/main/browser/cdp-ws-proxy.test.tssrc/main/browser/cdp-ws-proxy.tssrc/main/browser/snapshot-ax-tree-walk.tssrc/main/browser/snapshot-cursor-interactive-elements.tssrc/main/browser/snapshot-engine.tssrc/main/ipc/browser-grab-ipc.tssrc/main/ipc/browser-guest-view-ipc.tssrc/main/ipc/browser-renderer-trust.tssrc/main/ipc/browser-session-profile-ipc.test.tssrc/main/ipc/browser-session-profile-ipc.tssrc/main/ipc/browser-tab-registration-wait.tssrc/main/ipc/browser.test.tssrc/main/ipc/browser.tssrc/main/ipc/register-core-handlers.test.tssrc/main/ipc/register-core-handlers.tssrc/main/runtime/orca-runtime-browser.test.tssrc/main/runtime/orca-runtime-browser.ts
💤 Files with no reviewable changes (2)
- src/main/browser/browser-guest-ui.ts
- config/max-lines-baseline.txt
| if (isInteractive && (hasFocusable || node.backendDOMNodeId)) { | ||
| const ref = `@e${nextRef()}` | ||
| entries.push({ | ||
| ref, | ||
| role: formatInteractiveRole(role), | ||
| name: name || '(unlabeled)', | ||
| backendDOMNodeId: node.backendDOMNodeId ?? 0, |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Require a backend DOM ID before creating an @e reference.
Line 124 accepts a focusable node without backendDOMNodeId. Line 130 then stores 0. This creates a reference with no usable DOM target.
Proposed fix
- if (isInteractive && (hasFocusable || node.backendDOMNodeId)) {
+ if (isInteractive && hasFocusable && node.backendDOMNodeId !== undefined) {
const ref = `@e${nextRef()}`
entries.push({
ref,
role: formatInteractiveRole(role),
name: name || '(unlabeled)',
- backendDOMNodeId: node.backendDOMNodeId ?? 0,
+ backendDOMNodeId: node.backendDOMNodeId,
depth
})bd298cb to
83e905b
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. |
…x-lines budget The five oversized src/main/browser modules and src/main/ipc/browser.ts each carried a file-level `eslint-disable max-lines` and ran 377-654 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. cdp-ws-proxy is decomposed into collaborating objects rather than free functions because its state is genuinely per-connection: every collaborator is a private readonly instance field built in the constructor with live closures over `this`, so per-connection state stays per-connection. Likewise the screencast pacer's isClosed/isStopping and snapshot capture's getSeq are live thunks, not values captured at wiring time, so guards inside already-armed timers still observe a later stop(). browser-guest-ui.ts is renamed to browser-guest-shortcut-forwarding.ts: after the split it exports exactly one function, setupGuestShortcutForwarding, so the old name no longer described its contents. Also restores a single `webContents.debugger` read in the screencast path. The extraction had left three reads where the original had one; the accessor is stable today, so this is not a behavior fix but it removes a latent divergence. Verified: oxlint clean, ratchet passes, typecheck clean, full unit suite green (remaining failures are pre-existing load flakes in untouched files, each green when re-run serially), no new runtime import cycles, and the IPC channel set diffed identical before/after with all 23 handlers still trust-gated.
83e905b to
c577e13
Compare
Resolves conflicts with #14697, which split the browser and browser-IPC modules under the max-lines budget. This branch's additions are relocated rather than re-applied in place: - browser-session-registry.ts: took main's restructured file and re-added only hasProfileNonTransplantableCookies / clearProfileNonTransplantableCookies plus the two imports they need. The import block this branch had touched was removed upstream because its consumers moved out. - ipc/browser.ts: the session-profile handlers now live in browser-session-profile-ipc.ts, so the hasGoogleCookies / clearGoogleCookies handlers moved there beside their siblings instead of staying behind. - browser.test.ts: main extracted the api mock into createBrowserMockApi, so the two new session mocks were added to the shared harness rather than inlined in one test file.
Resolves a conflict with #14697, which split the browser IPC modules under the max-lines budget and slimmed ipc/browser.ts's import block. Took main's reorganized imports and re-added only the two this branch still needs: cancelBrowserWebAuthnAccountRequests / respondToBrowserWebAuthnAccountRequest and the BrowserWebAuthnAccountResponse type. The call sites stay put — the browser:unregisterGuest handler that cancels pending pickers on tab close remained in ipc/browser.ts rather than moving to one of the new modules.
…x-lines budget (#14697) The five oversized src/main/browser modules and src/main/ipc/browser.ts each carried a file-level `eslint-disable max-lines` and ran 377-654 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. cdp-ws-proxy is decomposed into collaborating objects rather than free functions because its state is genuinely per-connection: every collaborator is a private readonly instance field built in the constructor with live closures over `this`, so per-connection state stays per-connection. Likewise the screencast pacer's isClosed/isStopping and snapshot capture's getSeq are live thunks, not values captured at wiring time, so guards inside already-armed timers still observe a later stop(). browser-guest-ui.ts is renamed to browser-guest-shortcut-forwarding.ts: after the split it exports exactly one function, setupGuestShortcutForwarding, so the old name no longer described its contents. Also restores a single `webContents.debugger` read in the screencast path. The extraction had left three reads where the original had one; the accessor is stable today, so this is not a behavior fix but it removes a latent divergence. Verified: oxlint clean, ratchet passes, typecheck clean, full unit suite green (remaining failures are pre-existing load flakes in untouched files, each green when re-run serially), no new runtime import cycles, and the IPC channel set diffed identical before/after with all 23 handlers still trust-gated.
…x-lines budget (stablyai#14697) The five oversized src/main/browser modules and src/main/ipc/browser.ts each carried a file-level `eslint-disable max-lines` and ran 377-654 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. cdp-ws-proxy is decomposed into collaborating objects rather than free functions because its state is genuinely per-connection: every collaborator is a private readonly instance field built in the constructor with live closures over `this`, so per-connection state stays per-connection. Likewise the screencast pacer's isClosed/isStopping and snapshot capture's getSeq are live thunks, not values captured at wiring time, so guards inside already-armed timers still observe a later stop(). browser-guest-ui.ts is renamed to browser-guest-shortcut-forwarding.ts: after the split it exports exactly one function, setupGuestShortcutForwarding, so the old name no longer described its contents. Also restores a single `webContents.debugger` read in the screencast path. The extraction had left three reads where the original had one; the accessor is stable today, so this is not a behavior fix but it removes a latent divergence. Verified: oxlint clean, ratchet passes, typecheck clean, full unit suite green (remaining failures are pre-existing load flakes in untouched files, each green when re-run serially), no new runtime import cycles, and the IPC channel set diffed identical before/after with all 23 handlers still trust-gated.
What
Splits the five oversized
src/main/browsermodules andsrc/main/ipc/browser.tsinto focused modules, removes theireslint-disable max-linessuppressions, and prunes the six corresponding entries from themax-linesratchet baseline (341 → 335).No behavior change.
Why
Each of these six files carried a file-level
max-linessuppression and had grown to 377–654 counted lines against a 300-line budget. PerAGENTS.md→ "Do Not Disable Max Lines", the fix is to split, not to suppress;config/max-lines-baseline.txtis a shrink-only ratchet.How it was split
ipc/browser.tsbrowser-grab-ipc,browser-guest-view-ipc,browser-renderer-trust,browser-session-profile-ipc,browser-tab-registration-waitbrowser/cdp-ws-proxy.tscdp-client-response-writer,cdp-debugger-channel,cdp-dom-focus-replay,cdp-page-capture-commands,cdp-page-navigation-commands,cdp-synthetic-session-registry,cdp-target-discoverybrowser/browser-screencast-stream.ts…-stream-types,…-debugger-command,…-frame-metadata,…-cdp-events,…-device-metrics,…-frame-pacer,…-snapshot-capture,…-viewport-fitbrowser/browser-guest-ui.tsbrowser-guest-renderer-target,browser-guest-context-menu,browser-guest-grab-shortcuts,browser-guest-wheel-zoom,browser-guest-shortcut-dispatchbrowser/browser-session-registry.tsbrowser-session-meta-store,browser-session-persisted-profile-validation,browser-session-cookie-staging,browser-session-partition-policiesbrowser/snapshot-engine.tssnapshot-ax-tree-walk,snapshot-cursor-interactive-elementscdp-ws-proxy.tsis decomposed into collaborating objects rather than free functions, because its state is genuinely per-connection. Every collaborator is aprivate readonlyinstance field built in the constructor with live closures overthis(() => this.client,() => this.port,() => this.stop()), so per-connection state stays per-connection.browser-guest-ui.tswas renamed tobrowser-guest-shortcut-forwarding.ts: after the split it exports exactly one function,setupGuestShortcutForwarding, so the old name no longer described its contents (AGENTS.md→ "name files after what they actually contain").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 only failures are pre-existing load-induced timeouts in files this branch does not touch, each verified passing when re-run seriallyeslint/oxlint-disabledirective was added anywheresrc/main/browsersuite: 40 files / 637 tests green, zero skipsIPC surface proved intact. The channel registration set was extracted from the original and from the new modules and diffed: identical sets and identical per-channel counts. All 23 registered handlers remain trust-gated (22 → 22
isTrustedBrowserRenderercall sites), andtrustedBrowserRendererWebContentsIdremains a single module singleton — the split did not fork the trust state.Independent adversarial review of every file, each instructed to refute the "pure move" claim. Beyond reading, reviewers ran a multiset diff of every string/numeric literal and every comparison/logical operator (
??,?.,===,!==,&&,||, …) between the original and the union of the new modules — confirming no??silently became||, no bound or error string changed.Specific invariants confirmed rather than assumed:
CONTROL_MODIFIERS,MAC_COMMAND_MODIFIERS,WHEEL_ZOOM_BLOCKING_MODIFIERS,recentGuestWheelZoomByGuest) were already module-level in the original.isSnapshotStalereadsgetSeq(), a live closure, not a captured number — hadseqbeen passed by value across the new module boundary, the initial-snapshot fallback would have raced every live frame.isClosed/isStoppingare live thunks, so guards inside already-armedsetTimeoutcallbacks still observe astop()that happened after the timer was armed.removeListenerstill receives the same reference.ackPending = falsedefault (finish()must not ack,stop()must).preventDefaulton the keydown branch are unchanged.configuredPartitionsmoved from aprivate readonlyinstance field to a module-levelconst. The owning class is unexported with a single construction site, and two existing tests pin both halves of the semantics — one proves it still dedupes within a module instance, a later test reusing the same partition string proves state is still fresh between tests. Both pass.Pre-existing issues found and deliberately NOT changed
browser-guest-wheel-zoom.ts:consumeRecentGuestWheelZoomreturnsfalseon a direction mismatch without deleting the stale WeakMap entry, so a zoom-in-then-zoom-out inside the 250 ms window leaves the old entry to expire on its own.snapshot-cursor-interactive-elements.ts: in the injected page script, the trailingif (found.length >= 50) returnis a no-op (last statement in the function); the cap is actually enforced by the twoforEachguards at the call sites.snapshot-ax-tree-walk.ts:ordinal()computess[(v - 20) % 10], which indexes negatively forv < 20and silently relies on the|| s[v] || s[0]fallback chain.browser-session-cookie-staging.ts:clearPendingBrowserCookieImportunlinksstagedPath + suffixafter deleting the key, so a non-string persisted value would build a garbage path.ipc/browser.ts:browser:acceptDownloadisremoveHandler'd but never registered (preserved verbatim inbrowser-guest-view-ipc.ts).