Skip to content

feat(runtime): loopback port-forward transport for paired clients - #21822

Closed
mmarabel wants to merge 5 commits into
stablyai:mainfrom
mmarabel:feat/remote-port-forward-transport
Closed

mmarabel wants to merge 5 commits into
stablyai:mainfrom
mmarabel:feat/remote-port-forward-transport

Conversation

@mmarabel

@mmarabel mmarabel commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Part 3 of 3 — the transport half. Independent of #21807 and #21821: no shared files, based directly on main.

This ships no user-visible behaviour on its own, deliberately. See Why land this before its consumer below — the short version is that hosts and clients update separately, so the host half is the piece that benefits from going first.

ELI5

Some dev servers only accept connections from the machine they run on. When that machine is a remote Orca server, there is no address your laptop can use — not a tunnel address, not a VPN address, none. The only fix is to carry the connection.

This adds the pipe that carries it. Nothing uses the pipe yet.

What Changed

A dev server bound to 0.0.0.0 on a remote host can be reached by rewriting the URL, which is #21807. A dev server bound to 127.0.0.1 cannot be reached at any address, because the kernel refuses packets arriving on a non-loopback interface. That case needs a forward, and this is the machinery for it.

Host — network.portForward. A streaming RPC method that accepts tunnel frames and connects them to loopback ports.

Client — three pieces. PortForwardListener binds 127.0.0.1 on the client and opens one tunnel stream per inbound connection. PortForwardTransport owns one subscription and the tunnel client riding it. PortForwardManager keeps one subscription per environment and one listener per remote port.

The stream framing is reused verbatim. The browser tunnel's wire format is already a general-purpose TCP multiplexer — Open { host, port } plus flow control — so a forward is one stream per connection. No new opcode, no codec change, no change to BrowserNetworkTunnelSession, which already takes an injectable connect. Per docs/reference/remote-wire-compatibility.md a new opcode would have needed negotiation; none is introduced.

Why

The authorization is deliberately not reused. network.browserTunnel accepts any destination, which is safe there because a browser-host lease scopes it. A forward has no such scope, so the destination itself becomes the boundary: loopback only, enforced at connect time, with the rejection reported as destination_connect_failed so the target is never echoed back.

The loopback check is purpose-built rather than borrowed. classifyRemotePairingHostname looks like the obvious helper, but its loopback test is normalized.startsWith('127.') — a string comparison that also admits 127.evil.example.com. Fine for labelling a pairing endpoint, a hole for deciding which socket a paired client may reach. The new check is a strict allowlist over localhost, 127.0.0.0/8, ::1 and IPv4-mapped forms, and refuses subdomains of localhost because RFC 6761 notwithstanding, resolver behaviour varies and a wrong answer here opens a hole rather than merely failing.

The check returns the address to dial, rather than approving a string someone else dials. A boolean leaves a gap between what was validated and what the socket reaches: getaddrinfo treats 127.0.0.08 and [127.0.0.1] as hostnames, so a wildcard resolver or a search domain could answer them off-host after the check said loopback. resolveLoopbackForwardHost hands back a numeric literal instead, and that literal is what gets connected — net.connect skips the resolver for a literal, so the resolver is not in the path at all. Leading-zero octets are refused outright rather than read as decimal, since a decimal reading would disagree with the octal one the OS performs.

Why land this before its consumer. Hosts and clients update independently — remote-wire-compatibility.md opens by saying mixed versions are the normal state. If the host half lands first, hosts in the wild already advertise network.portForward.v1 by the time the client half ships, and the feature works for people who have not updated their server. If both halves land together, every user needs both sides updated before anything works. #14440 landed contracts-only for the same reason. Happy to hold this until the consumer is ready if maintainers would rather see them together.

Same-port preference. The listener asks for the host's own port number first and reports exact: false when it cannot have it. A remapped port breaks anything carrying the original number — hot-reload sockets, OAuth redirect URIs, absolute asset paths — so callers must surface that rather than quietly hand over a different URL.

A forward is shared, not per-consumer. Two surfaces asking for the same remote port get the same local port; handing out two would double the listeners and give the user two URLs for one dev server. Concurrent requests collapse through an in-flight map, without which each binds its own listener and the loser leaks.

Linked Issue

Refs #21806 — Branch B.

Visual Proof

N/A — no user-visible surface. Nothing constructs these classes yet; the method is registered but no shipped client calls it.

Testing

  • pnpm lint — full suite, clean. Worth noting check:dead-classes scans src/renderer only, so it does not flag these main-process classes; that is a gap in the gate, not evidence the code is wired up.
  • pnpm tc — clean.
  • pnpm test — 41 tests.

Coverage worth calling out:

  • The destination boundary is tested against the cases that matter, not just the happy path: 127.evil.example.com, localhost.evil.example.com, app.localhost, 169.254.169.254, 0.0.0.0, the leading-zero forms (127.0.0.08, 127.000.000.001, 0177.0.0.1), and the full 127.0.0.0/8 range. A dial-site test proves the resolved literal is what reaches a real listener, not the string the caller sent.

  • The transport's teardown asserts a lost tunnel is reported once, a deliberate close is not reported as a loss, and a close that lands before readiness still settles the attach rather than leaving it pending.

  • The listener is exercised against real sockets end to end — byte carriage, same-port preference, fallback reporting exact: false, several concurrent connections, and an open failure dropping the connection rather than hanging it.

  • The manager covers sharing, concurrent collapse, per-environment isolation, teardown when a tunnel is lost, and dropping the subscription once the last forward is released.

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

AI Disclosure

Claude Opus 5, used for investigation, implementation, and tests.

Review

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Security. This is the part most worth a close read. The method requires an authenticated paired binary client and the negotiated capability, and admits loopback destinations only — deliberately stricter than the browser tunnel it borrows framing from. It grants no reach a paired client does not already have through a terminal on that host, but it is a new door and should be judged as one.
  • Backwards compatibility. Capability-gated: a host running this code reports network.portForward.v1 in getStatus(), and one that predates it does not, so a newer client simply does not offer the feature against an older host. No opcode, no codec change, no change to existing methods.
  • Cross-platform. No paths or shells. IPv6 loopback forms and IPv4-mapped addresses are covered.
  • Resource bounds. The session's existing stream, open-rate and memory budgets apply unchanged; the outbound queue caps mirror the browser tunnel, which carries the same shape of traffic.
  • What is missing. The UI wiring, which needs an IPC channel because the manager lives in main and the ports UI is in the renderer. That is the follow-up, and it is what will make a loopback-bound remote port openable.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

A dev server bound to 127.0.0.1 on a remote host cannot be reached from the
client at any address, so no URL rewrite helps it; only a forward does. This
adds the host half.

network.portForward reuses the browser tunnel's stream framing verbatim — it is
already a general-purpose TCP multiplexer, so a forward is one stream per
inbound connection and needs no new opcode or codec change. What it does not
reuse is that method's authorization: the browser tunnel accepts any
destination because a browser-host lease scopes it, which would be far too
broad here. This method instead makes the destination itself the boundary and
admits loopback only.

The destination check is a strict allowlist rather than the existing
classifyRemotePairingHostname, whose string-prefix test for '127.' would also
admit 127.evil.example.com.

Gated behind network.portForward.v1, so a host that predates it never
advertises the method and clients keep today's behaviour.
… host

Client half, part one: a 127.0.0.1-bound listener that opens one tunnel stream
per inbound connection and pipes it to the remote port.

It prefers the host's own port number and reports exact:false when it cannot get
it, because a remapped port breaks everything that carries the original number —
hot-reload sockets, OAuth redirect URIs, absolute asset paths. Callers must
surface that rather than silently hand over a different URL.

Bound to loopback only: the forward exists to make a remote port reachable on
this machine, never to republish it to the network.
Client half, part two.

PortForwardTransport carries one network.portForward subscription and the
tunnel client riding it. It is separate from the browser tunnel's transport
because that one is scoped by a browser-host lease and carries execution-host
routing; a forward needs neither.

PortForwardManager owns one subscription per environment and one listener per
remote port. A forward is shared rather than per-consumer: two surfaces asking
for the same remote port get the same local port, because handing out two would
double the listeners and give the user two URLs for one dev server. Concurrent
requests for the same port collapse through an in-flight map, without which each
would bind its own listener and the loser would leak.
@coderabbitai

coderabbitai Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: cf34583b-6a71-42fc-ad35-8e3f86a337c1

📥 Commits

Reviewing files that changed from the base of the PR and between 0a501c3 and 1c56ed4.

📒 Files selected for processing (2)
  • src/main/port-forward/port-forward-transport.test.ts
  • src/main/port-forward/port-forward-transport.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/port-forward/port-forward-transport.ts
  • src/main/port-forward/port-forward-transport.test.ts

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


📝 Walkthrough

Walkthrough

Adds loopback port forwarding across the runtime and paired client. Shared schemas and validation restrict destinations to loopback hosts and valid ports. The runtime exposes network.portForward with capability and authentication checks. PortForwardTransport handles tunnel readiness and closure. PortForwardListener forwards local sockets and handles port fallback. PortForwardManager shares forwards, deduplicates concurrent requests, and manages cleanup. Tests cover validation, RPC behavior, byte forwarding, sharing, remapping, and teardown.

Priority: ➖ Normal

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 34.78% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 23 functions across 13 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 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 identifies the main change: adding loopback port-forward transport for paired clients.
Description check ✅ Passed The description follows the required template and covers the change, rationale, linked issue, testing, security, compatibility, platform impact, and deferred UI work. It provides sufficient detail for…
  • Fix all pre-merge checks with AI

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: 2

🧹 Nitpick comments (1)
src/main/port-forward/port-forward-transport.ts (1)

178-185: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Guard fail against re-entry after an intentional close.

PortForwardTransport.close() sets closed and calls BrowserNetworkTunnelClient.close() before clearing tunnelValue. The tunnel client invokes onClosed synchronously, so fail() re-enters while tunnelValue is non-null and emits onLost for an intentional shutdown.

♻️ Proposed guard
   private fail(error: Error, rejectReady: (error: Error) => void): void {
+    if (this.closed) {
+      return
+    }
     const wasReady = this.tunnelValue !== null
     this.close()
     rejectReady(error)
     if (wasReady) {
       this.options.onLost?.(error)

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 0a27a284-287e-48f9-a142-dd9195b097c7

📥 Commits

Reviewing files that changed from the base of the PR and between fa0010e and f0c2f22.

⛔ Files ignored due to path filters (1)
  • src/shared/rpc-contract/rpc-params-catalog.generated.ts is excluded by !**/*.generated.*
📒 Files selected for processing (12)
  • src/main/port-forward/port-forward-listener.test.ts
  • src/main/port-forward/port-forward-listener.ts
  • src/main/port-forward/port-forward-manager.test.ts
  • src/main/port-forward/port-forward-manager.ts
  • src/main/port-forward/port-forward-transport.ts
  • src/main/runtime/rpc/methods/index.ts
  • src/main/runtime/rpc/methods/port-forward.test.ts
  • src/main/runtime/rpc/methods/port-forward.ts
  • src/shared/loopback-forward-destination.test.ts
  • src/shared/loopback-forward-destination.ts
  • src/shared/port-forward-protocol.ts
  • src/shared/protocol-version.ts

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

Comment thread src/shared/protocol-version.ts Resolved

@pullfrog pullfrog 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.

Important

The security boundary and host advertisement both have gaps that need a look before merge: the host never advertises network.portForward.v1, and the loopback predicate classifies some strings as numeric loopback that the OS instead resolves as hostnames. Two lifecycle defects in the client transport/manager round it out.

Reviewed changes — read the complete 13-file diff at f0c2f222ee for review:

  • Host RPC network.portForward — streaming handler admits authenticated paired binary clients that negotiated the capability, then runs BrowserNetworkTunnelSession with a loopback-only connector; rejection surfaces as destination_connect_failed without echoing the target.
  • Destination boundary — new isLoopbackForwardDestination / isForwardablePort shared predicate, purpose-built rather than reusing classifyRemotePairingHostname.
  • Client listener — PortForwardListener binds 127.0.0.1, prefers the host's own port, falls back with exact: false, and opens one tunnel stream per inbound connection.
  • Client transport + manager — PortForwardTransport owns one subscription and the tunnel client; PortForwardManager shares one forward per remote port (in-flight collapse) and tears down on tunnel loss.
  • Registration and wire — method added to ALL_RPC_METHODS and the params catalog, new capability constant, no opcode or codec change.
  • Tests — new suites for the listener (real sockets), manager sharing/concurrency/teardown, RPC admission, and the destination predicate.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Comment thread src/shared/protocol-version.ts Resolved
…literal, and settle teardown once

Advertise network.portForward.v1 in RUNTIME_CAPABILITIES so getStatus reports it;
registration alone left every host looking like one that predates the feature.

Dial the literal the loopback check validated instead of the caller's string.
Normalised forms and leading-zero octets (127.0.0.08) were handed to getaddrinfo,
which resolves them as hostnames and can answer off-host.

Guard PortForwardTransport.fail against the re-entry its own close() causes, so a
lost tunnel reports once and a deliberate close reports not at all.

Re-check environment identity in PortForwardManager.release before closing, as
open() already does, so a release cannot tear down the environment that replaced
the one it observed.

@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: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: b1e43bfc-d7ec-497c-8621-0c173ba1d3af

📥 Commits

Reviewing files that changed from the base of the PR and between f0c2f22 and 0a501c3.

📒 Files selected for processing (9)
  • src/main/port-forward/port-forward-manager.test.ts
  • src/main/port-forward/port-forward-manager.ts
  • src/main/port-forward/port-forward-transport.test.ts
  • src/main/port-forward/port-forward-transport.ts
  • src/main/runtime/rpc/methods/port-forward.test.ts
  • src/main/runtime/rpc/methods/port-forward.ts
  • src/shared/loopback-forward-destination.test.ts
  • src/shared/loopback-forward-destination.ts
  • src/shared/protocol-version.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/port-forward/port-forward-manager.test.ts
  • src/shared/protocol-version.ts

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

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes — incremental review of 0a501c3bcd, the commit that settles the four findings from the prior pullfrog review; the full 14-file diff was re-read for context, and the five port-forward suites pass locally (40/40).

  • Advertised the capability. PORT_FORWARD_RUNTIME_CAPABILITY is now a member of RUNTIME_CAPABILITIES, so getStatus().capabilities reports network.portForward.v1. port-forward.test.ts asserts membership beside the registration assertion, matching the sibling-capability pattern.
  • Removed the validated-vs-dialled gap. isLoopbackForwardDestination became resolveLoopbackForwardHost, which returns the IP literal to dial (or null), and connectLoopbackForwardDestination connects that literal instead of target.host. Leading-zero octets are refused outright rather than read as decimal; localhost is pinned to 127.0.0.1; [::1] and trailing-dot forms normalise to a literal the resolver never sees.
  • Settled transport teardown once. PortForwardTransport.fail now opens with if (this.closed) return, so the synchronous onClosed re-entry from close() no longer double-fires onLost or reports a deliberate close as a loss. New port-forward-transport.test.ts covers both directions.
  • Closed the manager release race. PortForwardManager.release re-checks this.environments.get(environmentId) === environment before closeEnvironment, mirroring open; the regression test holds listener.close() open and swaps the environment under the same id.
  • Test harness. port-forward-manager.test.ts gained an openers capture and a holdClose gate, and the stream-opener assertion now proves the tunnel dials the remote port rather than the local one.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

…first

The re-entry guard added in the previous commit short-circuits fail(), so a
close() between acquiring the subscription and the ready event left nothing to
settle the attach: start() — and the ensure() awaiting it — stayed pending for
the life of the process.

close() now rejects a waiting attach itself, and fail() rejects before tearing
down so a real failure still surfaces its own error rather than the generic
teardown one.

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes — incremental review of 1c56ed47f4, the commit that settles a pending attach when the transport is closed before readiness. The full 14-file diff was re-read for context, and the new test was confirmed to fail when the fix is removed.

  • Settled a pre-readiness close. PortForwardTransport.close() now rejects the pending ready promise (port-forward-transport.ts:208), so start() resolves its rejection instead of hanging for the process lifetime when close lands before the ready frame.
  • Preserved the real failure reason. fail() rejects the attach before calling close() (:194-195), so the caller sees the actual error rather than the generic port_forward_transport_closed that close() would otherwise settle it with.
  • Added real coverage. The new test (port-forward-transport.test.ts:93-107) times out without the fix; the harness gained stubSubscription/settleSubscription so the test can hold a subscription without announcing readiness.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@Em3rald0

Copy link
Copy Markdown

Tested live against a headless orca serve host: works, with 3 things worth fixing before the consumer lands

I run Orca headless (orca serve on Debian 13, behind nginx), with a desktop and a phone paired to it, so a loopback-only dev server is exactly my gap. Nothing calls this code yet, so I ran the host half inside a real build and drove it with this PR's own PortForwardManager / PortForwardTransport, through the real E2EE runtime client.

Build. The PR merged cleanly onto v1.4.209. Its 41/41 tests pass on Arch and on Debian 13, pnpm lint shows 0 errors, and all 4 tsc projects pass. The host is the official v1.4.209 AppImage with only app.asar and app.asar.unpacked replaced by the PR build; the two bundles differ only in this PR's files, plus dev files the app never loads.

Platforms tested: Linux only. The host was Debian 13 (orca serve, headless); the client was Arch Linux, same box and over SSH. I did not test macOS or Windows clients, or the mobile app. The client code is plain net/ws with no paths or shells, but it hasn't been run there.

Same host Desktop → host over a real link
Host advertises network.portForward.v1; a client without it is refused ✅ ✅
Loopback-only dev server reachable via ensure() ✅ (exact: false: port taken on the same box) ✅ exact: true, http://127.0.0.1:5199
8 MiB down + 8 MiB up, sha256 ✅ ✅
WebSocket (HMR-style), 101 frames ✅ ✅
16 off-host / disguised destinations refused; canary listeners on every non-loopback address ✅ 0 hits ✅ 0 hits
release() closes the local port ✅ ✅
Real Vite app page load (139 requests, 25.9 MiB), median of 5 – 2.85 s / 3.15 s vs ssh -L 3.79 s / 3.82 s (two sessions)

image

Worth fixing before the consumer lands:

  1. A forward goes dead silently after 65,536 connections. Stream ids are never reused, and ids are capped at 65,536 per tunnel (browser-network-tunnel-client.ts:88). The browser route replaces an exhausted tunnel (paired-runtime-browser-network-route.ts:212), but the forward path has no equivalent. Reproduced live: exactly 65,536 connections succeeded (91 min at ~12/s, under the host's rate budget). Connection fix: route terminal paste through electron clipboard #65,537 and all 50 after it failed (socket hang up), while onLost never fired and manager.get() still returned the forward. It looks healthy and is dead. A once-a-second health check reaches this in about 18 h.
  2. Refusals are silent. PortForwardListener drops the reason the tunnel already provides (port-forward-listener.ts:96, .catch(() => socket.destroy())). The inherited limits suit a browser but not general forwards. They are 32 streams shared by every forward to a host, 16 pending opens, and 128 opens per 10 s. Clients that open one connection per request just see ECONNRESET. Over a real link, bursts also hit the pending limit: pending_open_limit_exceeded appeared in 1 of 3 raw 40-open probes, and 40 HTTP connections got only 17 through.
  3. Choose the window before v1 ships. Throughput per forwarded connection is capped at window ÷ RTT, and I measured it (details below). At 256 KiB that's about 9 MiB/s at 28 ms and about 2.5 MiB/s at 100 ms. Meanwhile ssh -L reached 11.5 MiB/s on the same link. Because network.portForward.v1 hasn't shipped, forward tunnels could still get a larger or adaptive window with no compatibility cost. After release, the same change needs a new capability. (Don't shrink it: a 64 KiB client made the page load 2.6× slower.)
Destination boundary: full matrix

Every one of these was refused with the generic destination_connect_failed, and the target was never echoed back:

  • Metadata and off-host addresses: 169.254.169.254, 0.0.0.0, docker 172.17.0.1, a WireGuard 10.x, the host's public v4 and v6, ::ffff:172.17.0.1
  • Names: 127.evil.example.com, localhost.evil.example.com, app.localhost, example.com
  • Alternative number forms: 0177.0.0.1, 127.0.0.08, 127.000.000.001, 2130706433, 0x7f000001

Ports 0 and 65536 are rejected client-side. localhost, ::1, [::1], [127.0.0.1] and ::ffff:127.0.0.1 connect; the bracket-stripping dials the literal. 127.1 is refused (fails closed). A refused open doesn't harm the tunnel.

The dev server listened on loopback only, and the same port on every non-loopback address was a canary listener: 0 connections during the probes on both legs. Scope note, consistent with "no reach beyond a terminal": any loopback listener is reachable, e.g. 127.0.0.1:22 connected.

Limits: measurements and a suggested fix
Limit Where Measured
32 concurrent streams client, browser-network-tunnel-client.ts:85; one tunnel per host Locally 40 → 32 opened + 8 stream limit exceeded. With 10 connections held on a forward to :22, a forward to :5199 got exactly 22.
16 pending opens host, browser-network-tunnel-resource-budget.ts Desktop, raw 40-open bursts: 32/32/25 opened; run 3 had 7 × pending_open_limit_exceeded. Through HTTP, 40 → 17 and 32 → 30. Never seen locally.
128 opens / 10 s host, same file; per tunnel session After 116 opens in ~6 s, a burst of 32 got exactly 12. It recovers as the window slides. Refused attempts don't count against it.

Suggested, all client-only, so they work against every host version:

  • Log the refusal reason at listener L96.
  • Queue instead of resetting: at most 16 opens in flight, pace opens under 128 per 10 s, and hold accepted sockets briefly (with a deadline) while the tunnel is full. That turns the WAN bursts above into short waits.
  • Replace a tunnel whose stream ids are exhausted, as the browser route does.
  • Optionally, for updated hosts only: let network.portForward pass its own pending and rate budget to its session.

I'd avoid one tunnel per port: it multiplies the host's per-session budgets and does nothing for one busy port.

Benchmark: method and the window experiment

The host ran a real React + Tailwind Vite app in dev mode, bound to 127.0.0.1. From the desktop, a browser-like loader fetched index.html and then followed the static module graph over 6 keep-alive connections: 139 requests, 25.9 MiB, including a 17.7 MiB dependency chunk. Both paths ran over the same SSH link, alternating round by round, so the difference isolates this transport. Two sessions: 2,850 vs 3,788 ms and 3,149 vs 3,817 ms (forward vs ssh -L, medians of 5). Zero errors throughout. In Firefox through the forward: 163 requests, 31.6 MB, load 5.40 s.

Window experiment. Credit is explicit (every stream starts at sendCredit: 0), and peers reject only credit above 256 KiB (destination-flow.ts:85, client-stream-frames.ts:77). So a client granting less is wire-safe. I confirmed it live: a 64 KiB client against the unmodified host was byte-exact, with no credit errors, and the existing 77 tunnel unit tests pass with the default. But the 17.7 MiB file then moved at a flat 2.2–2.3 MiB/s in every round (64 KiB ÷ ~28 ms), while the SSH control in the same phase swung between 3 and 10 MiB/s. The page load took 8.3 s, 2.6× slower. At 256 KiB, the largest file never exceeded 8.0 MiB/s, while ssh -L (2 MiB channel windows) reached 11.5 MiB/s.

The missing Branch B wiring, from a serve user's side

The call site already exists. openWorkspacePortInBrowser (src/renderer/src/lib/workspace-port-actions.ts) sends a local port to the system browser on Shift/⌘-click (L123). A remote (environment) port always goes to the in-app browser via browser.tabCreate (L141). The consumer is roughly one more branch there:

  1. When the target is an environment host that advertises network.portForward.v1, call an IPC to main → PortForwardManager.ensure() → shell.openUrl(handle.url). Hosts that don't advertise it keep today's behaviour.
  2. Show a notice when exact: false, since a remapped port breaks HMR sockets, OAuth redirects and absolute asset URLs.
  3. Release forwards when the environment disconnects, and show the loss (onLost) in the Ports UI.
  4. In serve mode the right-sidebar Ports item is hidden altogether (sshOnly: true, use-right-sidebar-activity-items.ts:112). Only the status-bar popover works there, so the consumer may want to lift that gate for environments with the capability.

#21807 edits the same function for the 0.0.0.0 case, so doing the two together avoids a second pass.

Notes on the build
  • For the host I reused CI's node-pty. A local Arch build of it needs GLIBC_2.42, and the afterPack glibc gate rightly refused to package it.
  • pnpm typecheck runs 4 tsc processes at once (run-typecheck-projects-in-parallel.mjs only runs them one at a time on single-core hosts). On a 16 GB machine that invoked the OOM killer. It's unrelated to this PR, and I can file it separately.
  • pnpm lint's 2 warnings are in mobile/src/onboarding/*.test.ts, which this PR doesn't touch.

Happy to share the harness, the loader and the window patch, or to rerun all of it against a new revision. Had this problem myself, so happy to help and we'll be waiting for the merge to happen

Testing and analysis were done with Claude Code (Claude Opus 5.5); I reviewed the results and ran the desktop leg myself.

@AmoabaKelvin

Copy link
Copy Markdown
Collaborator

Thank you for this. Your design for the host side, a sibling network.portForward method that reuses the tunnel framing and admits loopback destinations only, is what #47994 builds. The tunnel code has moved a lot since September, so we rebuilt it on current main and wired it into the Ports panel, terminal links and the browser's Open in default browser. You'll be credited as co-author on the merge commit.

@AmoabaKelvin

Copy link
Copy Markdown
Collaborator

Closing since this landed in #47994, which builds on your loopback port-forward transport and credits you as co-author. Thanks for the groundwork!

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.

3 participants