Repository navigation
refactor(ipc): split ssh.ts into focused modules - #16394
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 (22)
💤 Files with no reviewable changes (1)
🚧 Files skipped from review as they are similar to previous changes (20)
Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review. 📝 WalkthroughWalkthroughThe monolithic SSH IPC module was split into modules for shared context, connection attempts, lifecycle queues, relay sessions, renderer broadcasts, port forwards, target handlers, teardown, and shutdown. Connection and relay flows now use shared registries and state callbacks. IPC registration delegates to focused handler modules. Shutdown uses a bounded drain sequence. Callers and tests import relocated APIs, and the SSH file no longer has a max-lines exemption. Merge Risk: ⚪ Minimal · up to This refactor splits the SSH IPC implementation into focused modules without changing its behavior, and the reported checks and tests pass; no actionable merge-blocking risk remains beyond normal review. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description provides detailed change scope, rationale, architecture, behavior-preservation evidence, and test results. However, it omits most required template sections, including ELI5, explicit Why, Visual Proof or Resolution Add the missing template sections. State the rationale under ✨ 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 |
# Conflicts: # config/max-lines-baseline.txt
|
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. |
(cherry picked from commit 1f39c93)
Four conflicts, all against module splits main landed on top of the previous merge (d456549). src/shared/runtime-types.ts Main's #16197 dissolved this into a re-export shell over five contract modules. Took the shell; our three additions moved to src/shared/runtime-session-contracts.ts, where the types now live: RuntimeMobileSessionBrowserTab's browserProfileId/executionHostKey/ placement, UNPUBLISHED_WORKTREE_PUBLICATION_EPOCH ('none', unchanged — the merge base already sends it), and RuntimeMobileSessionTabsResult.clientHostedPagesUnreconciled. The shell re-exports the epoch as a value so existing importers keep working. src/shared/remote-runtime-client.ts Main split the file into a handshake module, a request/response router and a subscription transport. Took main's shape and relocated our delta: the clientCapabilities threading stayed on the request path, and the subscription-side machinery moved into the transport. Two further splits were forced by the max-lines ratchet, which main shrank past both files when it split them and which may not grow again: sendRemoteRuntimeRequestOnSocket moved to remote-runtime-request-socket.ts, and the transport's outbound queues and nested-request machinery became remote-runtime-subscription-outbound.ts and remote-runtime-subscription-request-channel.ts. Behaviour is unchanged; remote-runtime-subscription-request.test.ts (out-of-order routing, capacity bound, reject-on-close, exactly-once memory release) passes untouched against the rewrite. src/main/ipc/ssh.ts Main's #16394 split it into focused modules. The browser-partition teardown followed removeRegisteredSshTarget into src/main/ipc/ssh-session-teardown.ts, ordering intact: release, clear, a 500ms delayed second pass for the prepare-racing-removal window, all inside the same target-lifecycle callback. The connection-manager resolver wiring stayed in registerSshHandlers, and getSshConnectionManager is re-exported from ssh-target-registry rather than defined here, so the browser network route can read it without pulling in ipcMain. src/shared/child-process/__fixtures__/child-process-import-allowlist.txt Comment-block union; both sides' entries had already merged cleanly. runtime-client-export-parity.test.ts pins the public surface, so it records the widened signatures and the new value export. No wire changes: every field added is optional and no opcode moved.
Part of replacing #16161 (346 files, too large to audit). Scope is deliberately narrow:
src/main/ipc/ssh.tsand only its direct consequences. No neighbouring oversized file is touched.What moved
src/main/ipc/ssh.tswent from 1807 raw lines / 1524 counted lines (with anoxlint-disable max-linesheader and aconfig/max-lines-baseline.txtentry) to 270 raw / 222 counted, under the 300-line cap with no suppression. The baseline entry and the disable header are removed; no new suppression is added anywhere.New flat siblings under
src/main/ipc/(chosen over assh/subfolder so every../ssh/...,./pty,../providers/...relative import — and therefore everyvi.mock()path in the existing SSH test suite — stays byte-identical, and so./sshnever becomes ambiguous betweenssh.tsandssh/):ssh-ipc-context.tsconnectionManager,portForwardManager,persistedStore, the main-window getter, the runtime service — exported as live bindings plus settersssh-active-relay-sessions.tsactiveSessionsmap and thesetSshActiveMultiplexerResolverinstallssh-target-lifecycle-queue.tsrunTargetLifecycle,awaitTargetLifecycle)ssh-relay-lost-backoff.tsssh-renderer-broadcast.tsbroadcastSshState, relay state overrides,getPublicSshState, port-forward / detected-port broadcast and enrichmentssh-connect-attempt-registry.tsssh-session-teardown.tsdisconnectRegisteredSshTarget,removeRegisteredSshTarget, transport/session teardown, abandoning failed and cancelled attemptsssh-port-forward-persistence.tsssh-advertised-url-refresh.tsssh-host-sleep-reconnect.tsssh-connection-state-callbacks.tsSshConnectionCallbacksfor the transport: credential requests and the transport state-change state machinessh-relay-session-callbacks.tsSshRelaySessioncallbacks: terminal relay error, relay-lost backoff scheduling, on-readyssh-target-crud-handlers.tsssh:listTargets/addTarget/updateTarget/removeTarget/importConfig/ config-host handlers + repo re-adoptionssh-connect-flow.tsconnectTargetadmission anddoConnectssh-connection-handlers.tsssh:connect/disconnect/terminateSessions/resetRelay/getState/needsPassphrasePrompt/testConnectionanddoResetRelayssh-port-forward-handlers.tsssh:*PortForward*/listDetectedPortshandlersssh-shutdown-drain.tsbeginSshShutdown, the phased drain, andSSH_SHUTDOWN_BUDGET_MS/ shutdown typesssh.tskeeps the IPC channel list, the AI-vault session accessors,registerSshHandlers,getSshConnectionManager/getSshConnectionStore,resetSshHandlerStateForTests, and the pre-existingssh-target-registryre-export block.No new re-export barrel was added. Consumers of moved symbols were repointed at the real modules instead:
src/main/index.tsandsrc/main/ipc/ssh-app-shutdown.test.ts→./ipc/ssh-shutdown-drainforbeginSshShutdown/SSH_SHUTDOWN_BUDGET_MS/SshShutdownResultsrc/main/ephemeral-vm-runtime-ssh.ts→./ipc/ssh-session-teardownfordisconnectRegisteredSshTarget/removeRegisteredSshTargetEverything else still imports from
./sshexactly as before, so novi.mock('./ssh')/vi.mock('../ipc/ssh')factory in the suite needed touching.This is behavior-preserving
Function bodies were moved verbatim. The only permitted edits were adding
export, adding imports, and the formatter's reflow. Shared module-levelletstate is exported as live bindings fromssh-ipc-context.tsprecisely so read sites (connectionManager!.getConnection(...),persistedStore,currentRuntime?.…) stay character-for-character identical; only the handful of write sites became setter calls. The new module graph is acyclic (verified).How it was verified
1. Move-check (logic-line diff of
origin/main..HEAD, normalized for whitespace /export/ imports / comments): 29 vanished, 103 appeared. Every one adjudicated:Vanished (29):
ssh.tsfor the module that now uses them, plus the reshaped import inephemeral-vm-runtime-ssh.ts.oxfmtonceexportpushed them past 100 columns (runTargetLifecycle,abandonFailedSshSession,relayGracePeriodForTarget,broadcastPortForwards). Bodies unchanged.letassignments (connectionManager = …,persistedStore = store,currentRuntime = runtime, thenullresets,portForwardManager ??= new SshPortForwardManager()) that became setter calls intossh-ipc-context.ts.??=becamesetPortForwardManager(portForwardManager ?? new SshPortForwardManager())— the right operand still only evaluates when the left is nullish.onStateChange: (targetId, state) => {andcallbacks.onStateChange(targetId, {— the inline arrow was lifted to a named module-levelhandleSshConnectionStateChangewith a byte-identical body (verified by diff), andcreateSshConnectionCallbacksnow returnsonStateChange: handleSshConnectionStateChange. The arrow captured no locals, so the two callers are the same function.portForwardManager.setCallbacks({→portForwardManager!.setCallbacks({(type assertion only) and thereturn { connectionManager, sshStore: … }line reflowed with a!(the narrowing TS did across theif/elseis not available on an imported binding).Appeared (103): import-specifier lines for the new module edges, the multi-line halves of the reflowed signatures listed above, the new
setConnectionManager/setPortForwardManager/setPersistedStore/setCurrentGetMainWindow/setCurrentRuntime/unregisterAdvertisedUrlRefresh/unregisterPowerMonitorReconnect/resetSshShutdownDrainone-line wrappers and their call sites, the threeregisterSsh*Handlers()wrapper declarations and their calls, andhandleSshConnectionStateChange. No new guard, early return,&&/||clause,?./??, error message, timeout, retry count, or literal appears anywhere.Spot-diffs (whitespace-insensitive) confirming verbatim moves of the largest blocks:
doConnect(only thecallbacks.onStateChange→handleSshConnectionStateChangeline differs),connectTarget,doResetRelay,configureRelaySessionCallbacks,refreshActiveRelaySessions, thessh:terminateSessionsbody,ssh:resetRelay…ssh:testConnection, and all five port-forward handlers — identical.2.
pnpm run typecheck— pass.3.
node config/scripts/check-max-lines-ratchet.mjs— pass (144 grandfathered suppressions, one fewer than before, no new bypass).4.
node config/scripts/check-changed-code-quality.mjs origin/main— pass, 0 new findings across 21 changed files (code quality, type-aware, React Doctor).5. Tests (
--config config/vitest.config.ts):sshfilter — 262 files / 2943 tests passed, 2 files / 14 tests skipped. Coversssh.test.ts,ssh-app-shutdown,ssh-handler-reregistration,ssh-disconnect-cancellation,ssh-state-broadcast-fanout,ssh-terminate-sessions,ssh-relay-reset-resume,ssh-target-registry,ssh-browse, allssh-pty-*,worktrees-ssh-*,ephemeral-vm-runtime-ssh-cleanup,runtime/rpc/methods/ssh, and thesrc/main/ssh/**unit tests.worktrees-ssh,repos-remote,preflight-remote-ssh,runtime/rpc/methods/ssh,ipc/pty) — 75 files / 715 passed.ai-vault,ai-vault-scan-coalescing,ai-vault/ssh-session-list,filesystem-import-ssh*,precheck-runner,remote-workspace*— 32 files / 304 passed.check-max-lines-ratchet,app-shutdown,quit-teardown— 4 files / 27 passed.Cross-platform (Windows/WSL/SSH) branches and remote-wire payloads are untouched — no publish shape, opcode, or RPC param changed.