Skip to content

refactor(ipc): split ssh.ts into focused modules - #16394

Merged
nwparker merged 2 commits into
mainfrom
refactor-split-ipc-ssh
Aug 25, 2026
Merged

nwparker merged 2 commits into
mainfrom
refactor-split-ipc-ssh

Conversation

@nwparker

@nwparker nwparker commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2 $\color{#cf222e}{\Huge{\mathbf{−}}}$​2 0
Prod 21 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1901 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1629 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​272

Part of replacing #16161 (346 files, too large to audit). Scope is deliberately narrow: src/main/ipc/ssh.ts and only its direct consequences. No neighbouring oversized file is touched.

What moved

src/main/ipc/ssh.ts went from 1807 raw lines / 1524 counted lines (with an oxlint-disable max-lines header and a config/max-lines-baseline.txt entry) 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 a ssh/ subfolder so every ../ssh/..., ./pty, ../providers/... relative import — and therefore every vi.mock() path in the existing SSH test suite — stays byte-identical, and so ./ssh never becomes ambiguous between ssh.ts and ssh/):

Module Counted lines Owns
ssh-ipc-context.ts 28 The process-wide singletons the SSH IPC layer binds to: connectionManager, portForwardManager, persistedStore, the main-window getter, the runtime service — exported as live bindings plus setters
ssh-active-relay-sessions.ts 6 The activeSessions map and the setSshActiveMultiplexerResolver install
ssh-target-lifecycle-queue.ts 30 Per-target serialization of disconnect/remove/terminate/reset (runTargetLifecycle, awaitTargetLifecycle)
ssh-relay-lost-backoff.ts 27 Relay-lost backoff state, its constants, and the terminal-transport status set
ssh-renderer-broadcast.ts 129 Everything the SSH layer pushes at the renderer: broadcastSshState, relay state overrides, getPublicSshState, port-forward / detected-port broadcast and enrichment
ssh-connect-attempt-registry.ts 30 In-flight connect attempts, pending transport reconnects, reset/test bookkeeping, credential-requested tracking, the shutdown fence assert
ssh-session-teardown.ts 123 disconnectRegisteredSshTarget, removeRegisteredSshTarget, transport/session teardown, abandoning failed and cancelled attempts
ssh-port-forward-persistence.ts 71 Persisting forwards (with and without unrestored entries) and restoring them on ready
ssh-advertised-url-refresh.ts 32 The advertised-URL watcher subscription
ssh-host-sleep-reconnect.ts 63 powerMonitor suspend/resume wiring and the post-resume liveness probe
ssh-connection-state-callbacks.ts 107 SshConnectionCallbacks for the transport: credential requests and the transport state-change state machine
ssh-relay-session-callbacks.ts 176 SshRelaySession callbacks: terminal relay error, relay-lost backoff scheduling, on-ready
ssh-target-crud-handlers.ts 66 ssh:listTargets / addTarget / updateTarget / removeTarget / importConfig / config-host handlers + repo re-adoption
ssh-connect-flow.ts 226 connectTarget admission and doConnect
ssh-connection-handlers.ts 225 ssh:connect / disconnect / terminateSessions / resetRelay / getState / needsPassphrasePrompt / testConnection and doResetRelay
ssh-port-forward-handlers.ts 101 The five ssh:*PortForward* / listDetectedPorts handlers
ssh-shutdown-drain.ts 125 beginSshShutdown, the phased drain, and SSH_SHUTDOWN_BUDGET_MS / shutdown types

ssh.ts keeps the IPC channel list, the AI-vault session accessors, registerSshHandlers, getSshConnectionManager / getSshConnectionStore, resetSshHandlerStateForTests, and the pre-existing ssh-target-registry re-export block.

No new re-export barrel was added. Consumers of moved symbols were repointed at the real modules instead:

  • src/main/index.ts and src/main/ipc/ssh-app-shutdown.test.ts → ./ipc/ssh-shutdown-drain for beginSshShutdown / SSH_SHUTDOWN_BUDGET_MS / SshShutdownResult
  • src/main/ephemeral-vm-runtime-ssh.ts → ./ipc/ssh-session-teardown for disconnectRegisteredSshTarget / removeRegisteredSshTarget

Everything else still imports from ./ssh exactly as before, so no vi.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-level let state is exported as live bindings from ssh-ipc-context.ts precisely 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):

  • 11 are import-specifier lines — type/value specifiers that left ssh.ts for the module that now uses them, plus the reshaped import in ephemeral-vm-runtime-ssh.ts.
  • 4 are single-line signatures reflowed to multi-line by oxfmt once export pushed them past 100 columns (runTargetLifecycle, abandonFailedSshSession, relayGracePeriodForTarget, broadcastPortForwards). Bodies unchanged.
  • 10 are the module-level let assignments (connectionManager = …, persistedStore = store, currentRuntime = runtime, the null resets, portForwardManager ??= new SshPortForwardManager()) that became setter calls into ssh-ipc-context.ts. ??= became setPortForwardManager(portForwardManager ?? new SshPortForwardManager()) — the right operand still only evaluates when the left is nullish.
  • onStateChange: (targetId, state) => { and callbacks.onStateChange(targetId, { — the inline arrow was lifted to a named module-level handleSshConnectionStateChange with a byte-identical body (verified by diff), and createSshConnectionCallbacks now returns onStateChange: handleSshConnectionStateChange. The arrow captured no locals, so the two callers are the same function.
  • portForwardManager.setCallbacks({ → portForwardManager!.setCallbacks({ (type assertion only) and the return { connectionManager, sshStore: … } line reflowed with a ! (the narrowing TS did across the if/else is 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 / resetSshShutdownDrain one-line wrappers and their call sites, the three registerSsh*Handlers() wrapper declarations and their calls, and handleSshConnectionStateChange. 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 the callbacks.onStateChange → handleSshConnectionStateChange line differs), connectTarget, doResetRelay, configureRelaySessionCallbacks, refreshActiveRelaySessions, the ssh:terminateSessions body, 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):

  • ssh filter — 262 files / 2943 tests passed, 2 files / 14 tests skipped. Covers ssh.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, all ssh-pty-*, worktrees-ssh-*, ephemeral-vm-runtime-ssh-cleanup, runtime/rpc/methods/ssh, and the src/main/ssh/** unit tests.
  • consumer sweep (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.

Branch is refactor-split-ipc-ssh, not refactor/split-ipc-ssh: the remote already has a branch literally named refactor, so git rejects any refactor/* ref with a directory/file conflict.

@coderabbitai

coderabbitai Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3a338b1e-4b7f-4e14-90b9-ae39af3f9f39

📥 Commits

Reviewing files that changed from the base of the PR and between 33587fb and b389c36.

📒 Files selected for processing (22)
  • config/max-lines-baseline.txt
  • src/main/ephemeral-vm-runtime-ssh.ts
  • src/main/index.ts
  • src/main/ipc/ssh-active-relay-sessions.ts
  • src/main/ipc/ssh-advertised-url-refresh.ts
  • src/main/ipc/ssh-app-shutdown.test.ts
  • src/main/ipc/ssh-connect-attempt-registry.ts
  • src/main/ipc/ssh-connect-flow.ts
  • src/main/ipc/ssh-connection-handlers.ts
  • src/main/ipc/ssh-connection-state-callbacks.ts
  • src/main/ipc/ssh-host-sleep-reconnect.ts
  • src/main/ipc/ssh-ipc-context.ts
  • src/main/ipc/ssh-port-forward-handlers.ts
  • src/main/ipc/ssh-port-forward-persistence.ts
  • src/main/ipc/ssh-relay-lost-backoff.ts
  • src/main/ipc/ssh-relay-session-callbacks.ts
  • src/main/ipc/ssh-renderer-broadcast.ts
  • src/main/ipc/ssh-session-teardown.ts
  • src/main/ipc/ssh-shutdown-drain.ts
  • src/main/ipc/ssh-target-crud-handlers.ts
  • src/main/ipc/ssh-target-lifecycle-queue.ts
  • src/main/ipc/ssh.ts
💤 Files with no reviewable changes (1)
  • config/max-lines-baseline.txt
🚧 Files skipped from review as they are similar to previous changes (20)
  • src/main/index.ts
  • src/main/ipc/ssh-active-relay-sessions.ts
  • src/main/ipc/ssh-target-crud-handlers.ts
  • src/main/ipc/ssh-app-shutdown.test.ts
  • src/main/ipc/ssh-advertised-url-refresh.ts
  • src/main/ipc/ssh-connect-attempt-registry.ts
  • src/main/ipc/ssh-host-sleep-reconnect.ts
  • src/main/ipc/ssh-relay-session-callbacks.ts
  • src/main/ipc/ssh-port-forward-handlers.ts
  • src/main/ipc/ssh-ipc-context.ts
  • src/main/ipc/ssh-connection-state-callbacks.ts
  • src/main/ipc/ssh-target-lifecycle-queue.ts
  • src/main/ipc/ssh-session-teardown.ts
  • src/main/ipc/ssh-port-forward-persistence.ts
  • src/main/ipc/ssh-relay-lost-backoff.ts
  • src/main/ipc/ssh-renderer-broadcast.ts
  • src/main/ipc/ssh-connection-handlers.ts
  • src/main/ephemeral-vm-runtime-ssh.ts
  • src/main/ipc/ssh-shutdown-drain.ts
  • src/main/ipc/ssh.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.


📝 Walkthrough

Walkthrough

The 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 b389c

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)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description provides detailed change scope, rationale, architecture, behavior-preservation evidence, and test results. However, it omits most required template sections, including ELI5, explicit W… Add the missing template sections. State the rationale under ## Why, identify the linked issue using the required Fixes #... format, add N/A with a reason under ## Visual Proof if there is no UI or interaction change, complete the t…
Docstring Coverage ⚠️ Warning Docstring coverage is 13.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 60 functions across 21 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: splitting ssh.ts into focused modules.
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.
Full details: Description check

Explanation

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 N/A, AI Disclosure, Review, Agent skill boundary, Notes, and Checklist items.

Resolution

Add the missing template sections. State the rationale under ## Why, identify the linked issue using the required Fixes #... format, add N/A with a reason under ## Visual Proof if there is no UI or interaction change, complete the testing checkboxes, provide AI Disclosure details or follow the internal-contributor exception, complete the Agent skill boundary section, Notes, Review, and Checklist.

✨ Finishing Touches 💡 1
📝 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.

# Conflicts:
#	config/max-lines-baseline.txt
@coderabbitai

coderabbitai Bot commented Aug 25, 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 1f39c93 into main Aug 25, 2026
51 checks passed
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 25, 2026
Jinwoo-H added a commit that referenced this pull request Aug 25, 2026
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.
dallascrilley pushed a commit to dallascrilley/orca that referenced this pull request Aug 27, 2026
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
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