Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

desktop(web): terminals take a WebRTC data channel to the machine

Dev jacobb103a7bae04f
diff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.md
index 687e22407..a29971f7f 100644
--- a/desktop/CLAUDE.md
+++ b/desktop/CLAUDE.md
@@ -138,6 +138,11 @@ PKCE transaction; conditional adapters handle storage and native-only services.
`platform_auth_web.dart` serializes shared login/refresh/logout with Web Locks
and reloads other tabs when the account changes. Auth and E2EE keys persist in
origin-local storage; only the OAuth transaction is in session storage.
+Each relay connection also negotiates a WebRTC data channel to the machine
+(`web/p2p/`, the phone's `../mobile/lib/p2p` on the browser's own
+`RTCPeerConnection` — no `flutter_webrtc`, so native builds gain no plugin);
+terminal frames take it when it is up and fall back to the relay. Keep
+`terminal_p2p_{plugin,link,policy}.dart` in step with the phone's copies.
Shared sessions use `ObserverRelayCodec` and `/api/observer-ws`, verifying the
owner and permitting only observation and authenticated comments. `/s/:id#key=…`
opens `SharedAgentPage` without restoring the visitor's workspace. Public links
diff --git a/desktop/lib/desktop_workspace.dart b/desktop/lib/desktop_workspace.dart
index 8320c2502..1a019ee6f 100644
--- a/desktop/lib/desktop_workspace.dart
+++ b/desktop/lib/desktop_workspace.dart
@@ -2,6 +2,7 @@ import 'package:flutter/widgets.dart';
import 'screens/swarm_screen.dart';
import 'state/app_state.dart';
+import 'ws/terminal_transport_plugin.dart';
/// The signed-in screen of a native build. A browser build compiles
/// `web/web_entry.dart` in its place (the conditional import in `main.dart`),
@@ -10,3 +11,7 @@ Widget authenticatedWorkspace(AppNotifier app) => SwarmScreen(notifier: app);
/// A native build draws nothing around its screens.
Widget appFrame(Widget app) => app;
+
+/// A native build reaches machines through the local CLI, which carries its
+/// own P2P transport (`remoteRelay.ts`): nothing to plug in here.
+const TerminalTransportPluginFactory? terminalTransportPlugins = null;
diff --git a/desktop/lib/main.dart b/desktop/lib/main.dart
index 74ced9675..8e0dc46d0 100644
--- a/desktop/lib/main.dart
+++ b/desktop/lib/main.dart
@@ -15,5 +15,6 @@ Future<void> main() {
return startHarness(
authenticatedScreen: authenticatedWorkspace,
frame: appFrame,
+ transportPlugins: terminalTransportPlugins,
);
}
diff --git a/desktop/lib/web/p2p/browser_rtc_stats.dart b/desktop/lib/web/p2p/browser_rtc_stats.dart
new file mode 100644
index 000000000..e7722e006
--- /dev/null
+++ b/desktop/lib/web/p2p/browser_rtc_stats.dart
@@ -0,0 +1,58 @@
+import 'dart:js_interop';
+import 'dart:js_interop_unsafe';
+
+import 'package:web/web.dart';
+
+import 'terminal_p2p_link.dart';
+
+/// Which path ICE nominated, read from the browser's stats: the transport's
+/// `selectedCandidatePairId` (Chrome, Safari), else the nominated pair that
+/// succeeded (Firefox reports no transport). Null when there is no pair yet.
+Future<TerminalP2pTransport?> nominatedTransport(RTCPeerConnection pc) async {
+ final byId = <String, JSObject>{};
+ final report = await pc.getStats().toDart;
+ report.callMethod<JSAny?>(
+ 'forEach'.toJS,
+ ((JSObject value, JSString key) {
+ byId[key.toDart] = value;
+ }).toJS,
+ );
+ final pair = _selectedPair(byId) ?? _nominatedPair(byId);
+ if (pair == null) return null;
+ String? typeOf(String? id) =>
+ id == null ? null : _string(byId[id], 'candidateType');
+ return isRelayedPair(
+ typeOf(_string(pair, 'localCandidateId')),
+ typeOf(_string(pair, 'remoteCandidateId')),
+ )
+ ? TerminalP2pTransport.relay
+ : TerminalP2pTransport.direct;
+}
+
+JSObject? _selectedPair(Map<String, JSObject> byId) {
+ for (final stats in byId.values) {
+ if (_string(stats, 'type') != 'transport') continue;
+ final selected = _string(stats, 'selectedCandidatePairId');
+ if (selected != null && byId[selected] != null) return byId[selected];
+ }
+ return null;
+}
+
+JSObject? _nominatedPair(Map<String, JSObject> byId) {
+ for (final stats in byId.values) {
+ if (_string(stats, 'type') != 'candidate-pair') continue;
+ final state = _string(stats, 'state');
+ if (stats.getProperty<JSAny?>('nominated'.toJS).dartify() == true &&
+ (state == 'succeeded' || state == 'in-progress')) {
+ return stats;
+ }
+ }
+ return null;
+}
+
+String? _string(JSObject? stats, String key) {
+ final value = stats?.getProperty<JSAny?>(key.toJS);
+ return value != null && value.isA<JSString>()
+ ? (value as JSString).toDart
+ : null;
+}
diff --git a/desktop/lib/web/p2p/browser_terminal_p2p_link.dart b/desktop/lib/web/p2p/browser_terminal_p2p_link.dart
new file mode 100644
index 000000000..26a2821b4
--- /dev/null
+++ b/desktop/lib/web/p2p/browser_terminal_p2p_link.dart
@@ -0,0 +1,485 @@
+import 'dart:async';
+import 'dart:js_interop';
+
+import 'package:harness/logging/app_log.dart';
+import 'package:web/web.dart';
+
+import 'browser_rtc_stats.dart';
+import 'p2p_sdp.dart';
+import 'terminal_p2p_link.dart';
+import 'terminal_p2p_policy.dart';
+
+/// Diagnostic only, as on the phone: `--dart-define=HARNESS_P2P_FORCE_RELAY=true`
+/// drops host and srflx so nothing but a TURN allocation can be nominated. An
+/// upgrade trial is left alone, which is how the cutover gets exercised at all.
+const kForceP2pRelay = bool.fromEnvironment('HARNESS_P2P_FORCE_RELAY');
+
+/// The browser reports `complete` only once every server answered or timed out
+/// — with a dozen STUN/TURN urls, routinely the whole budget. The offer goes
+/// out once a server-reflexive (or relay) candidate is in plus a moment for the
+/// other interfaces, and at the cap regardless; the rest trickles.
+const _gatherCap = Duration(seconds: 3);
+const _gatherSettleAfterReflexive = Duration(milliseconds: 500);
+
+class BrowserTerminalP2pLinkFactory implements TerminalP2pLinkFactory {
+ const BrowserTerminalP2pLinkFactory();
+
+ @override
+ TerminalP2pLink create({
+ required TerminalP2pPolicy policy,
+ required TerminalP2pSignalSink sendSignal,
+ required TerminalP2pDataSink onData,
+ TerminalP2pStateSink? onState,
+ void Function(String reason)? onUnavailable,
+ void Function(String step, Duration elapsed)? onStep,
+ bool upgrade = false,
+ }) => BrowserTerminalP2pLink(
+ policy: policy,
+ sendSignal: sendSignal,
+ onData: onData,
+ onState: onState,
+ onUnavailable: onUnavailable,
+ onStep: onStep,
+ upgrade: upgrade,
+ );
+}
+
+/// The offerer side of one `terminal-v1` data channel, on the browser's own
+/// `RTCPeerConnection`. The phone's `WebRtcTerminalP2pLink` with the platform
+/// swapped: the same signals, timings and fallbacks, so the responder on the
+/// machine (the CLI's `terminalP2p.ts`) cannot tell the two apart. Without it a
+/// browser's every keystroke and every byte of output rode the relay twice —
+/// out to the backend and back — even with the machine on the same network.
+class BrowserTerminalP2pLink implements TerminalP2pLink {
+ BrowserTerminalP2pLink({
+ required this.policy,
+ required this.sendSignal,
+ required this.onData,
+ this.onState,
+ this.onUnavailable,
+ this.onStep,
+ this.upgrade = false,
+ });
+
+ final TerminalP2pPolicy policy;
+ final bool upgrade;
+ final TerminalP2pSignalSink sendSignal;
+ final TerminalP2pDataSink onData;
+ final TerminalP2pStateSink? onState;
+ final void Function(String reason)? onUnavailable;
+ final void Function(String step, Duration elapsed)? onStep;
+
+ @override
+ final String sessionId = p2pSessionId();
+
+ final Stopwatch _clock = Stopwatch()..start();
+ RTCPeerConnection? _pc;
+ RTCDataChannel? _channel;
+ bool _ready = false;
+ bool _starting = false;
+ bool _finished = false;
+ bool _sawAnswer = false;
+ Timer? _timeout;
+ Timer? _disconnectGrace;
+ TerminalP2pTransport? _transport;
+ final _waiters = <Completer<bool>>[];
+ Completer<void>? _gathered;
+ Completer<void>? _reflexive;
+ Completer<void>? _drained;
+
+ /// Candidates not carried by the offer, held until the answer is in: the
+ /// responder only adds a candidate to an entry that already has a remote
+ /// description. What the offer's SDP turns out to carry is dropped again.
+ final _lateCandidates = <RTCIceCandidate>[];
+ String _offeredSdp = '';
+
+ Duration get _elapsed => _clock.elapsed;
+
+ void _step(String label) => onStep?.call(label, _elapsed);
+
+ @override
+ bool get isReady => _ready && _channelCanSend;
+
+ bool get _channelCanSend {
+ final channel = _channel;
+ return channel != null &&
+ channel.readyState == 'open' &&
+ channel.bufferedAmount < terminalP2pMaxBufferedBytes;
+ }
+
+ @override
+ TerminalP2pTransport? get transport => _ready ? _transport : null;
+
+ @override
+ void start() {
+ if (_starting || _pc != null || _finished) return;
+ _starting = true;
+ _timeout = Timer(
+ terminalP2pNegotiationTimeout,
+ () => _fail('negotiation_timeout'),
+ );
+ onState?.call(TerminalP2pLinkState.connecting, Duration.zero, null);
+ unawaited(_begin());
+ }
+
+ Future<void> _begin() async {
+ try {
+ final pc = RTCPeerConnection(_configuration());
+ if (_finished) {
+ pc.close();
+ return;
+ }
+ _pc = pc;
+ _gathered = Completer<void>();
+ _reflexive = Completer<void>();
+ _wirePeer(pc);
+ final channel = pc.createDataChannel(
+ terminalP2pChannel,
+ RTCDataChannelInit(ordered: true),
+ )..binaryType = 'arraybuffer';
+ _channel = channel;
+ _wireChannel(channel);
+ await _createOffer(pc);
+ } catch (error) {
+ appLog.warn('p2p', 'peer connection setup failed', error: error);
+ _fail('offer_failed');
+ }
+ }
+
+ RTCConfiguration _configuration() {
+ final turn = policy.turn;
+ final servers = <RTCIceServer>[
+ if (policy.stunUrls.isNotEmpty) RTCIceServer(urls: _urls(policy.stunUrls)),
+ if (turn != null)
+ RTCIceServer(
+ urls: _urls(turn.urls),
+ username: turn.username,
+ credential: turn.credential,
+ ),
+ ].toJS;
+ // 'all' unless forced, as the CLI does: host and srflx pairs win by
+ // priority, and a TURN pair is nominated only once every direct one failed.
+ return kForceP2pRelay && !upgrade
+ ? RTCConfiguration(iceServers: servers, iceTransportPolicy: 'relay')
+ : RTCConfiguration(iceServers: servers);
+ }
+
+ static JSArray<JSString> _urls(List<String> urls) =>
+ [for (final url in urls) url.toJS].toJS;
+
+ Future<void> _createOffer(RTCPeerConnection pc) async {
+ final offer = await pc.createOffer().toDart;
+ await pc
+ .setLocalDescription(
+ RTCLocalSessionDescriptionInit(
+ type: 'offer',
+ sdp: raiseMaxMessageSize(offer?.sdp ?? ''),
+ ),
+ )
+ .toDart;
+ if (_pc != pc || _finished) return;
+ _step('offer-created');
+ // Gather-then-signal, like the CLI, but not to completion: the answer
+ // needs nothing more than what is in the SDP.
+ final how = await Future.any<String>([
+ _gathered!.future.then((_) => 'gathered'),
+ _reflexive!.future
+ .then((_) => Future<void>.delayed(_gatherSettleAfterReflexive))
+ .then((_) => 'gathered-enough'),
+ ]).timeout(_gatherCap, onTimeout: () => 'gather-capped');
+ if (_pc != pc || _finished) return;
+ _step(how);
+ final sdp = pc.localDescription?.sdp;
+ if (sdp == null || sdp.isEmpty) {
+ throw StateError('local_description_missing');
+ }
+ _offeredSdp = sdp;
+ _lateCandidates.removeWhere((c) => sdp.contains(c.candidate));
+ sendSignal('p2p_offer', {
+ 'sessionId': sessionId,
+ 'protocolVersion': terminalP2pProtocolVersion,
+ 'sdp': sdp,
+ // The RAW policy list: the responder runs its own gather against it.
+ 'stunUrls': policy.stunUrls,
+ if (policy.turn != null) 'turn': policy.turn!.toJson(),
+ if (upgrade) 'upgrade': true,
+ });
+ _step('offer-sent');
+ }
+
+ @override
+ Future<bool> handleSignal(String type, Map<String, dynamic> payload) async {
+ if (!terminalP2pSignalTypes.contains(type)) return false;
+ if (payload['sessionId'] != sessionId ||
+ payload['protocolVersion'] != terminalP2pProtocolVersion ||
+ _finished) {
+ return true;
+ }
+ final pc = _pc;
+ if (pc == null) return true;
+ try {
+ switch (type) {
+ case 'p2p_answer':
+ final sdp = payload['sdp'];
+ if (sdp is! String) return true;
+ _sawAnswer = true;
+ _step('answer-in');
+ await pc
+ .setRemoteDescription(
+ RTCSessionDescriptionInit(type: 'answer', sdp: sdp),
+ )
+ .toDart;
+ _flushLateCandidates();
+ case 'p2p_ice_candidate':
+ await _addCandidate(pc, payload['candidate']);
+ case 'p2p_abort':
+ final reason = payload['reason'];
+ // The peer's word for it, bounded before it reaches a log line.
+ _fail(
+ reason is String && reason.isNotEmpty
+ ? (reason.length > 64 ? reason.substring(0, 64) : reason)
+ : 'peer_aborted',
+ );
+ }
+ } catch (error) {
+ appLog.warn('p2p', 'signal $type failed', error: error);
+ _fail('signal_invalid');
+ }
+ return true;
+ }
+
+ Future<void> _addCandidate(RTCPeerConnection pc, Object? candidate) async {
+ if (candidate is! Map) return;
+ final line = candidate['candidate'];
+ if (line is! String) return;
+ await pc
+ .addIceCandidate(
+ RTCIceCandidateInit(
+ candidate: line,
+ sdpMid: candidate['sdpMid'] as String?,
+ sdpMLineIndex: (candidate['sdpMLineIndex'] as num?)?.toInt(),
+ ),
+ )
+ .toDart;
+ }
+
+ void _flushLateCandidates() {
+ final pending = List<RTCIceCandidate>.of(_lateCandidates);
+ _lateCandidates.clear();
+ pending.forEach(_trickle);
+ }
+
+ void _trickle(RTCIceCandidate candidate) {
+ if (candidate.candidate.isEmpty) return;
+ sendSignal('p2p_ice_candidate', {
+ 'sessionId': sessionId,
+ 'protocolVersion': terminalP2pProtocolVersion,
+ 'candidate': {
+ 'candidate': candidate.candidate,
+ 'sdpMid': candidate.sdpMid,
+ 'sdpMLineIndex': candidate.sdpMLineIndex,
+ },
+ });
+ }
+
+ @override
+ bool send(Object data) {
+ final channel = _channel;
+ if (!isReady || channel == null) return false;
+ try {
+ // Synchronous here, unlike the phone's plugin: a frame the browser
+ // refuses goes back to the caller, and so onto the relay.
+ channel.send(data is String ? data.toJS : asBytes(data).toJS);
+ return true;
+ } catch (error) {
+ appLog.warn('p2p', 'data channel send failed', error: error);
+ scheduleMicrotask(() => _fail('send_failed'));
+ return false;
+ }
+ }
+
+ @override
+ Future<bool> sendWithBackpressureRetry(
+ Object data, {
+ Duration drain = const Duration(seconds: 5),
+ }) async {
+ if (send(data)) return true;
+ final channel = _channel;
+ if (channel == null || channel.readyState != 'open') return false;
+ if (!await _waitForBufferedAmountLow(channel, drain)) return false;
+ return send(data);
+ }
+
+ Future<bool> _waitForBufferedAmountLow(
+ RTCDataChannel channel,
+ Duration timeout,
+ ) async {
+ if (channel.bufferedAmount < terminalP2pMaxBufferedBytes) return true;
+ final drained = _drained ??= Completer<void>();
+ try {
+ await drained.future.timeout(timeout);
+ } on TimeoutException {
+ return false;
+ }
+ return _channelCanSend;
+ }
+
+ @override
+ Future<bool> waitUntilReady(Duration timeout) {
+ if (isReady) return Future.value(true);
+ if (_finished || timeout <= Duration.zero) return Future.value(false);
+ final waiter = Completer<bool>();
+ _waiters.add(waiter);
+ final timer = Timer(timeout, () {
+ _waiters.remove(waiter);
+ if (!waiter.isCompleted) waiter.complete(false);
+ });
+ return waiter.future.whenComplete(timer.cancel);
+ }
+
+ void _settleWaiters(bool ready) {
+ final waiters = List<Completer<bool>>.of(_waiters);
+ _waiters.clear();
+ for (final waiter in waiters) {
+ if (!waiter.isCompleted) waiter.complete(ready);
+ }
+ }
+
+ @override
+ Future<void> stop({String reason = 'closed', bool notifyPeer = true}) async {
+ if (_finished) return;
+ _finished = true;
+ _ready = false;
+ _timeout?.cancel();
+ _timeout = null;
+ _clearDisconnectGrace();
+ _settleWaiters(false);
+ _lateCandidates.clear();
+ final drained = _drained;
+ _drained = null;
+ if (drained != null && !drained.isCompleted) drained.complete();
+ if (notifyPeer) {
+ sendSignal('p2p_abort', {
+ 'sessionId': sessionId,
+ 'protocolVersion': terminalP2pProtocolVersion,
+ 'reason': reason,
+ });
+ }
+ final channel = _channel;
+ final pc = _pc;
+ _channel = null;
+ _pc = null;
+ channel?.close();
+ pc?.close();
+ onState?.call(TerminalP2pLinkState.closed, _elapsed, reason);
+ }
+
+ void _wirePeer(RTCPeerConnection pc) {
+ pc.onicegatheringstatechange = ((Event _) {
+ if (_pc == pc && pc.iceGatheringState == 'complete') {
+ _complete(_gathered);
+ }
+ }).toJS;
+ pc.onicecandidate = ((RTCPeerConnectionIceEvent event) {
+ if (_pc != pc || _finished) return;
+ final candidate = event.candidate;
+ // A null candidate is the end of gathering.
+ if (candidate == null) return _complete(_gathered);
+ final line = candidate.candidate;
+ if (line.isEmpty) return;
+ if (reflexiveCandidate.hasMatch(line)) _complete(_reflexive);
+ // Everything gathered before the offer left is already inside its SDP.
+ if (_offeredSdp.isNotEmpty && _offeredSdp.contains(line)) return;
+ if (_sawAnswer) {
+ _trickle(candidate);
+ } else {
+ _lateCandidates.add(candidate);
+ }
+ }).toJS;
+ pc.onconnectionstatechange = ((Event _) {
+ if (_pc != pc || _finished) return;
+ final state = pc.connectionState;
+ _step('ice-$state');
+ switch (state) {
+ case 'failed':
+ _clearDisconnectGrace();
+ _fail('peer_failed');
+ case 'disconnected':
+ // "Checks failing but still trying": it heals after a wifi blip.
+ _disconnectGrace ??= Timer(terminalP2pDisconnectGrace, () {
+ _disconnectGrace = null;
+ if (_pc == pc && !_finished) _fail('peer_disconnected_timeout');
+ });
+ default:
+ _clearDisconnectGrace();
+ }
+ }).toJS;
+ }
+
+ void _wireChannel(RTCDataChannel channel) {
+ channel.bufferedAmountLowThreshold = terminalP2pBufferedLowThreshold;
+ channel.onbufferedamountlow = ((Event _) {
+ final drained = _drained;
+ _drained = null;
+ _complete(drained);
+ }).toJS;
+ channel.onopen = ((Event _) {
+ if (_channel == channel && !_finished) unawaited(_opened());
+ }).toJS;
+ channel.onclose = ((Event _) {
+ if (_channel == channel && !_finished && _ready) {
+ _fail('channel_closed');
+ }
+ }).toJS;
+ channel.onmessage = ((MessageEvent event) {
+ if (_channel != channel || _finished) return;
+ final data = event.data;
+ if (data.isA<JSString>()) {
+ onData((data as JSString).toDart);
+ } else if (data.isA<JSArrayBuffer>()) {
+ onData((data as JSArrayBuffer).toDart.asUint8List());
+ }
+ }).toJS;
+ }
+
+ Future<void> _opened() async {
+ // Read the pair BEFORE reporting open, so `transport` answers synchronously
+ // to whoever acts on the state change.
+ _transport = await _readTransport();
+ if (_finished) return;
+ _ready = true;
+ _timeout?.cancel();
+ _timeout = null;
+ _settleWaiters(true);
+ onState?.call(TerminalP2pLinkState.open, _elapsed, null);
+ }
+
+ Future<TerminalP2pTransport?> _readTransport() async {
+ final pc = _pc;
+ if (pc == null) return null;
+ try {
+ return await nominatedTransport(pc);
+ } catch (error) {
+ appLog.warn('p2p', 'getStats failed', error: error);
+ return null;
+ }
+ }
+
+ static void _complete(Completer<void>? completer) {
+ if (completer != null && !completer.isCompleted) completer.complete();
+ }
+
+ void _clearDisconnectGrace() {
+ _disconnectGrace?.cancel();
+ _disconnectGrace = null;
+ }
+
+ void _fail(String reason) {
+ if (_finished) return;
+ final wasReady = _ready;
+ _ready = false;
+ onState?.call(TerminalP2pLinkState.failed, _elapsed, reason);
+ if (wasReady) onUnavailable?.call(reason);
+ unawaited(stop(reason: reason));
+ }
+}
diff --git a/desktop/lib/web/p2p/p2p_resume_retry.dart b/desktop/lib/web/p2p/p2p_resume_retry.dart
new file mode 100644
index 000000000..7430da621
--- /dev/null
+++ b/desktop/lib/web/p2p/p2p_resume_retry.dart
@@ -0,0 +1,37 @@
+import 'package:flutter/widgets.dart';
+
+import 'terminal_p2p_plugin.dart';
+
+/// Coming back to the tab usually means the network changed, which is exactly
+/// when a waiting P2P retry should fire and a TURN link may now go direct —
+/// what the phone does on returning to the foreground.
+class P2pResumeRetry extends StatefulWidget {
+ const P2pResumeRetry({super.key, required this.plugins, required this.child});
+
+ final TerminalP2pPlugins plugins;
+ final Widget child;
+
+ @override
+ State<P2pResumeRetry> createState() => _P2pResumeRetryState();
+}
+
+class _P2pResumeRetryState extends State<P2pResumeRetry> {
+ late final AppLifecycleListener _lifecycle;
+
+ @override
+ void initState() {
+ super.initState();
+ _lifecycle = AppLifecycleListener(
+ onResume: () => widget.plugins.kickRetry(),
+ );
+ }
+
+ @override
+ void dispose() {
+ _lifecycle.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) => widget.child;
+}
diff --git a/desktop/lib/web/p2p/p2p_sdp.dart b/desktop/lib/web/p2p/p2p_sdp.dart
new file mode 100644
index 000000000..77108244a
--- /dev/null
+++ b/desktop/lib/web/p2p/p2p_sdp.dart
@@ -0,0 +1,44 @@
+import 'dart:math';
+import 'dart:typed_data';
+
+/// What this side advertises as `a=max-message-size`. The browser's default is
+/// 256 KiB and werift (the machine's WebRTC stack) enforces the PEER's advertised
+/// ceiling on every send — a terminal keyframe runs to ~480 KiB, so the default
+/// would make the responder's very first keyframe fail and demote the channel.
+/// The CLI and the phone set the same 512 KiB.
+const p2pMaxMessageSize = 512 * 1024;
+
+/// `a=max-message-size` raised to [p2pMaxMessageSize]; added after the
+/// `a=sctp-port` line when the browser left it out, since werift then assumes
+/// 64 KiB. Only the number is touched: a description whose line endings do not
+/// all match is rejected, so the `\r\n` around it stays put.
+String raiseMaxMessageSize(String sdp) {
+ final line = RegExp(r'^(a=max-message-size:)\d+', multiLine: true);
+ if (line.hasMatch(sdp)) {
+ return sdp.replaceAllMapped(
+ line,
+ (match) => '${match[1]}$p2pMaxMessageSize',
+ );
+ }
+ final sctp = RegExp(r'^a=sctp-port:\d+(\r?\n)', multiLine: true);
+ return sdp.replaceFirstMapped(
+ sctp,
+ (match) => '${match[0]}a=max-message-size:$p2pMaxMessageSize${match[1]}',
+ );
+}
+
+/// A lower-case uuid v4: the negotiation's `sessionId`.
+String p2pSessionId([Random? random]) {
+ final source = random ?? Random.secure();
+ final bytes = Uint8List.fromList(
+ List.generate(16, (_) => source.nextInt(256)),
+ );
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
+ final hex = bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
+ return '${hex.substring(0, 8)}-${hex.substring(8, 12)}-'
+ '${hex.substring(12, 16)}-${hex.substring(16, 20)}-${hex.substring(20)}';
+}
+
+/// A candidate line that proves a server answered: server-reflexive or relay.
+final reflexiveCandidate = RegExp(r'\btyp (srflx|relay)\b');
diff --git a/desktop/lib/web/p2p/terminal_p2p_link.dart b/desktop/lib/web/p2p/terminal_p2p_link.dart
new file mode 100644
index 000000000..068028f1f
--- /dev/null
+++ b/desktop/lib/web/p2p/terminal_p2p_link.dart
@@ -0,0 +1,123 @@
+import 'dart:typed_data';
+
+import 'terminal_p2p_policy.dart';
+
+/// The WebRTC half of the phone's P2P terminal transport, kept behind an
+/// interface so the routing above it (`TerminalP2pPlugin`) can be tested with a
+/// scripted link and no native peer connection. Mirrors `TerminalP2pInitiator`
+/// in the harness CLI's `terminalP2p.ts`, whose constants these are.
+
+const terminalP2pChannel = 'terminal-v1';
+
+/// Covers BOTH peers' gathering plus a TURN allocation — see the CLI's own note on
+/// why 10s was too tight. A terminal opened before the channel is ready falls back
+/// to the relay after `openWaitMs` regardless, so a long budget costs nothing visible.
+const terminalP2pNegotiationTimeout = Duration(seconds: 25);
+const terminalP2pMaxBufferedBytes = 2 * 1024 * 1024;
+const terminalP2pBufferedLowThreshold = 256 * 1024;
+
+/// ICE `disconnected` is "checks failing but still trying" and self-heals after a
+/// wifi blip or NAT rebind; only after this does it count as a real failure.
+const terminalP2pDisconnectGrace = Duration(seconds: 5);
+
+/// The signaling frames both peers exchange, E2EE-sealed, through the relay socket.
+/// `p2p_promote`/`p2p_promote_ack` belong to the TURN-to-direct upgrade orchestration
+/// in the plugin, not to a link's own protocol — they just ride the same channel.
+const terminalP2pSignalTypes = {
+ 'p2p_offer',
+ 'p2p_answer',
+ 'p2p_ice_candidate',
+ 'p2p_abort',
+ 'p2p_promote',
+ 'p2p_promote_ack',
+};
+
+/// JSON frame types the machine may send down the data channel — anything else that
+/// arrives there is dropped, as the CLI's `TERMINAL_P2P_UP_TYPES` does.
+const terminalP2pUpTypes = {
+ 'terminal_capabilities_result',
+ 'terminal_ready',
+ 'terminal_keyframe',
+ 'terminal_output',
+ 'terminal_closed',
+ 'terminal_error',
+ 'terminal_chunked_upload_begin_result',
+ 'terminal_chunked_upload_progress',
+ 'terminal_paste_image_result',
+ 'terminal_paste_file_result',
+};
+
+enum TerminalP2pLinkState { connecting, open, failed, closed }
+
+/// Which path ICE nominated once the channel is open. `relay` means the bytes go
+/// through TURN — still WebRTC, still end-to-end encrypted, but billed per GB.
+enum TerminalP2pTransport { direct, relay }
+
+typedef TerminalP2pSignalSink = void Function(
+ String type,
+ Map<String, dynamic> payload,
+);
+typedef TerminalP2pDataSink = void Function(Object data);
+typedef TerminalP2pStateSink = void Function(
+ TerminalP2pLinkState state,
+ Duration setup,
+ String? reason,
+);
+
+abstract interface class TerminalP2pLink {
+ /// Lower-case uuid v4; every signal for this negotiation carries it.
+ String get sessionId;
+
+ /// Open and under the send-buffer ceiling.
+ bool get isReady;
+
+ /// Null while negotiating, or when no candidate pair could be read.
+ TerminalP2pTransport? get transport;
+
+ void start();
+
+ /// False when [type] is not a signal at all; true once handled — including a
+ /// signal for some other session, which is swallowed rather than acted on.
+ Future<bool> handleSignal(String type, Map<String, dynamic> payload);
+
+ /// [data] is a `String` (a sealed JSON frame) or a `Uint8List` (a sealed HTRM
+ /// frame). False means the caller must put the frame on the relay instead.
+ bool send(Object data);
+
+ /// [send], but a failure caused purely by backpressure gets one bounded chance to
+ /// drain first — a burst of upload chunks can cross the ceiling well before the
+ /// network has moved any of it.
+ Future<bool> sendWithBackpressureRetry(
+ Object data, {
+ Duration drain = const Duration(seconds: 5),
+ });
+
+ Future<bool> waitUntilReady(Duration timeout);
+
+ Future<void> stop({String reason = 'closed', bool notifyPeer = true});
+}
+
+abstract interface class TerminalP2pLinkFactory {
+ TerminalP2pLink create({
+ required TerminalP2pPolicy policy,
+ required TerminalP2pSignalSink sendSignal,
+ required TerminalP2pDataSink onData,
+ TerminalP2pStateSink? onState,
+ void Function(String reason)? onUnavailable,
+ void Function(String step, Duration elapsed)? onStep,
+ bool upgrade = false,
+ });
+}
+
+/// Does the nominated pair send its bytes through a TURN allocation? BOTH ends
+/// decide this: one relay candidate is enough for ICE to connect, so a pair of our
+/// srflx with the peer's relay is fully relayed.
+bool isRelayedPair(String? localType, String? remoteType) =>
+ localType == 'relay' || remoteType == 'relay';
+
+/// A `Uint8List` view of whatever binary the data channel handed over.
+Uint8List asBytes(Object data) => data is Uint8List
+ ? data
+ : data is List<int>
+ ? Uint8List.fromList(data)
+ : Uint8List(0);
diff --git a/desktop/lib/web/p2p/terminal_p2p_plugin.dart b/desktop/lib/web/p2p/terminal_p2p_plugin.dart
new file mode 100644
index 000000000..8f99bc572
--- /dev/null
+++ b/desktop/lib/web/p2p/terminal_p2p_plugin.dart
@@ -0,0 +1,868 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:typed_data';
+
+import 'package:harness/logging/app_log.dart';
+import 'package:harness/terminal/terminal_binary.dart';
+import 'package:harness/ws/terminal_transport_plugin.dart';
+
+import 'terminal_p2p_link.dart';
+import 'terminal_p2p_policy.dart';
+
+/// The phone's port of the harness CLI's `RemoteRelayPool` P2P orchestration
+/// (`remoteRelay.ts`): where the desktop lets its local daemon decide which wire
+/// each terminal stream rides, a viewer build decides here, per relay connection.
+///
+/// Three paths a stream can be on, reported to the app as `terminal_link_mode`:
+/// 'p2p' — a data channel, ICE nominated a direct pair.
+/// 'turn' — a data channel, but only a Cloudflare TURN pair would connect. Still
+/// end-to-end encrypted, but billed per GB — hence the upgrade attempts.
+/// 'relay' — no data channel; the bytes ride the backend WebSocket.
+///
+/// Every constant and every rule here is the CLI's, and the comments there say why.
+
+// Retry every 60s, capped at 10 attempts within any trailing hour — a ROLLING window,
+// deliberately: the reason p2p cannot be reached right now is usually transient at the
+// scale of hours (a changed IP, a router reboot, a NAT binding that thawed).
+const _retryDelay = Duration(seconds: 60);
+const _retryWindow = Duration(hours: 1);
+const _retryHourlyCap = 10;
+
+// How long a stream may sit mid-migration before the sweep gives up on it and the
+// ordinary demote-on-mismatch rule applies to it again.
+const _migrationTtl = Duration(seconds: 30);
+const _migrationSweepEvery = Duration(seconds: 20);
+
+// A connection that reached 'direct' only through a TURN pair still costs per GB —
+// and, what a person actually notices, a relay round trip on every keystroke. Worth
+// periodically trying for a truly direct one; the trial never touches the live
+// connection until a replacement has already proven itself. The CLI gives up for
+// good after three tries; a phone's relay socket can live in the foreground for
+// hours, so after those three it keeps trying at a slow pace instead — and again
+// at once when the app comes back, since that usually means the network changed.
+const _upgradeQuickAttempts = 3;
+const _upgradeRetryDelay = Duration(seconds: 60);
+const _upgradeSlowRetryDelay = Duration(minutes: 15);
+const _upgradeAttemptTimeout = Duration(seconds: 15);
+const _upgradeDrainTimeout = Duration(seconds: 5);
+const _promoteAckTimeout = Duration(seconds: 5);
+
+enum _Wire { relay, p2p }
+
+/// The plugins alive right now, so the phone's lifecycle can reach them: a retry
+/// still waiting out its 60s when the app comes back to the foreground is fired
+/// at once instead (its budget still applies).
+class TerminalP2pPlugins {
+ TerminalP2pPlugins({required this.links, DateTime Function()? now})
+ : _now = now ?? DateTime.now;
+
+ final TerminalP2pLinkFactory links;
+ final DateTime Function() _now;
+ final _live = <TerminalP2pPlugin>{};
+
+ TerminalTransportPlugin create(TerminalTransportHost host, String machineId) {
+ final plugin = TerminalP2pPlugin(
+ host: host,
+ machineId: machineId,
+ links: links,
+ now: _now,
+ onDisposed: _live.remove,
+ );
+ _live.add(plugin);
+ return plugin;
+ }
+
+ void kickRetry() {
+ for (final plugin in List.of(_live)) {
+ plugin.kickRetry();
+ }
+ }
+
+ int get liveCount => _live.length;
+}
+
+class TerminalP2pPlugin implements TerminalTransportPlugin {
+ TerminalP2pPlugin({
+ required this.host,
+ required this.machineId,
+ required this.links,
+ DateTime Function()? now,
+ this.onDisposed,
+ }) : _now = now ?? DateTime.now {
+ _sweep = Timer.periodic(_migrationSweepEvery, (_) => _sweepMigrations());
+ }
+
+ final TerminalTransportHost host;
+ final String machineId;
+ final TerminalP2pLinkFactory links;
+ final DateTime Function() _now;
+ final void Function(TerminalP2pPlugin plugin)? onDisposed;
+
+ TerminalP2pPolicy? _policy;
+ TerminalP2pLink? _link;
+ bool _disposed = false;
+
+ /// Streams whose frames ride the data channel.
+ final _p2pStreams = <String>{};
+
+ /// Every stream open on this connection, whatever the wire — what
+ /// [_promoteOpenStreams] walks for migration candidates.
+ final _streams = <String>{};
+
+ /// `terminal_open` requestIds that went out over the data channel; their
+ /// `terminal_ready` decides whether the stream lands in [_p2pStreams].
+ final _pendingOpens = <String>{};
+
+ /// streamId → when its migration to p2p started.
+ final _migrating = <String, DateTime>{};
+
+ final _retryTimestamps = <DateTime>[];
+ Timer? _retryTimer;
+ late final Timer _sweep;
+
+ int _upgradeAttempts = 0;
+ Timer? _upgradeTimer;
+ TerminalP2pLink? _upgradeShadow;
+
+ /// streamId → when its drain-barrier resync went out, right before a cutover.
+ /// Distinct from [_migrating]: that one is WS→p2p, this is turn→direct, and the
+ /// confirmation for each arrives over a different wire.
+ final _upgradeDraining = <String, DateTime>{};
+ void Function()? _upgradeWaitResolve;
+ TerminalP2pLink? _upgradeOrphan;
+ DateTime? _lastUpgradeAttemptAt;
+
+ /// Set only once a cutover succeeded — there is nothing left to upgrade to. A
+ /// demotion resets it along with the attempt count: the next link is its own.
+ bool _upgradeDone = false;
+
+ String get _sid =>
+ machineId.length > 8 ? machineId.substring(0, 8) : machineId;
+
+ void _log(String message) => appLog.info('p2p', '$message · machine=$_sid');
+
+ // ── Lifecycle ──────────────────────────────────────────────────────────────
+
+ @override
+ void onConnectedAck(Map<String, dynamic> payload) {
+ _policy = TerminalP2pPolicy.parse(payload['p2p']);
+ final policy = _policy;
+ if (policy != null) {
+ // Names only, never the credential itself.
+ _log(
+ 'policy stun=${policy.stunUrls.length}'
+ ' turn=${policy.turn == null ? 'NONE' : '${policy.turn!.urls.length} urls'}'
+ ' openWait=${policy.openWaitMs}ms',
+ );
+ }
+ }
+
+ @override
+ void onSessionReady() {
+ if (_disposed) return;
+ // Three ways p2p never even starts, all of which used to look identical from
+ // outside. The peer-version case is the important one: a machine whose CLI
+ // predates p2p answers no offer, so no amount of STUN or TURN can help it.
+ final policy = _policy;
+ if (policy == null) {
+ _log('off · backend sent no policy (rollout or kill switch)');
+ } else if (host.codec.terminalP2pVersion != terminalP2pProtocolVersion) {
+ _log(
+ 'off · peer speaks p2p v${host.codec.terminalP2pVersion}, we speak'
+ ' v$terminalP2pProtocolVersion — no data channel is possible, ws relay only',
+ );
+ } else {
+ _startP2p();
+ }
+ }
+
+ @override
+ void dispose({bool notifyPeer = false}) {
+ if (_disposed) return;
+ _disposed = true;
+ _retryTimer?.cancel();
+ _retryTimer = null;
+ _upgradeTimer?.cancel();
+ _upgradeTimer = null;
+ _sweep.cancel();
+ final shadow = _upgradeShadow;
+ final orphan = _upgradeOrphan;
+ final link = _link;
+ _upgradeShadow = null;
+ _upgradeOrphan = null;
+ _link = null;
+ _upgradeDraining.clear();
+ _upgradeWaitResolve = null;
+ _p2pStreams.clear();
+ _pendingOpens.clear();
+ _streams.clear();
+ _migrating.clear();
+ unawaited(shadow?.stop(reason: 'relay_closed', notifyPeer: notifyPeer));
+ unawaited(orphan?.stop(reason: 'relay_closed', notifyPeer: notifyPeer));
+ unawaited(link?.stop(reason: 'relay_closed', notifyPeer: notifyPeer));
+ onDisposed?.call(this);
+ }
+
+ /// The app came back to the foreground: a retry waiting out its delay fires now,
+ /// and a link sitting on TURN gets an upgrade trial at once — coming back usually
+ /// means the network changed, which is exactly when a direct pair may have
+ /// become possible.
+ void kickRetry() {
+ if (_disposed) return;
+ final timer = _retryTimer;
+ if (timer != null) {
+ timer.cancel();
+ _retryTimer = null;
+ _log('retry kicked · app resumed');
+ if (_link == null) _startP2p();
+ return;
+ }
+ if (_link?.transport == TerminalP2pTransport.relay &&
+ _upgradeShadow == null &&
+ !_upgradeDone) {
+ _upgradeTimer?.cancel();
+ _upgradeTimer = null;
+ _log('upgrade kicked · app resumed');
+ _attemptUpgrade();
+ }
+ }
+
+ // ── Negotiation ───────────────────────────────────────────────────────────
+
+ void _startP2p() {
+ final policy = _policy;
+ if (policy == null || _link != null || _disposed) return;
+ var wasDirect = false;
+ late final TerminalP2pLink link;
+ link = links.create(
+ policy: policy,
+ sendSignal: _sendSignal,
+ onData: _handleP2pData,
+ onStep: (step, elapsed) =>
+ _log('step · $step +${elapsed.inMilliseconds}ms'),
+ onState: (state, setup, reason) {
+ if (_disposed) return;
+ switch (state) {
+ case TerminalP2pLinkState.open:
+ wasDirect = true;
+ final relayed = link.transport == TerminalP2pTransport.relay;
+ _log(
+ 'connected · via=${relayed ? 'turn' : 'direct'}'
+ ' setup=${setup.inMilliseconds}ms',
+ );
+ _reportP2pResult(
+ 'direct',
+ setup: setup,
+ reason: relayed ? 'relayed' : null,
+ );
+ _promoteOpenStreams();
+ if (relayed && !_upgradeDone) _scheduleUpgradeAttempt();
+ case TerminalP2pLinkState.failed:
+ if (wasDirect || _link != link) return;
+ _log(
+ 'gave up · reason=${reason ?? 'unknown'} after=${setup.inMilliseconds}ms'
+ ' — terminals stay on the ws relay',
+ );
+ _reportP2pResult(
+ reason == 'negotiation_timeout' ? 'timeout' : 'failed',
+ setup: setup,
+ reason: reason,
+ );
+ // Without this the plugin is stuck: `_link` still points at a finished
+ // instance and `_startP2p`'s own guard blocks every future attempt.
+ _link = null;
+ _scheduleRetry();
+ case TerminalP2pLinkState.connecting:
+ case TerminalP2pLinkState.closed:
+ break;
+ }
+ },
+ onUnavailable: (reason) {
+ if (_link == link) _demote(reason);
+ },
+ );
+ _link = link;
+ link.start();
+ }
+
+ void _sendSignal(String type, Map<String, dynamic> payload) {
+ // Sealed by the codec on the way out: every p2p_* type is in encryptedDownTypes.
+ unawaited(
+ host.send({'type': type, 'payload': payload}, force: TransportVia.ws),
+ );
+ }
+
+ void _scheduleRetry() {
+ if (_disposed) return;
+ if (_retryTimer != null) {
+ _log('retry already pending');
+ return;
+ }
+ final now = _now();
+ final windowStart = now.subtract(_retryWindow);
+ _retryTimestamps.removeWhere((at) => !at.isAfter(windowStart));
+ var delay = _retryDelay;
+ if (_retryTimestamps.length >= _retryHourlyCap) {
+ // The CLI stops here and leaves the streams on the relay until the socket
+ // itself redials. The window is rolling, though, and nothing else on a phone
+ // would ever ask again — so wait for the oldest attempt to age out instead.
+ delay =
+ _retryTimestamps.first.add(_retryWindow).difference(now) +
+ _retryDelay;
+ _log(
+ 'retry budget exhausted · (${_retryTimestamps.length}/$_retryHourlyCap in the'
+ ' last hour) — deferred ${delay.inSeconds}s until it frees',
+ );
+ } else {
+ _retryTimestamps.add(now);
+ _log(
+ 'retry scheduled · in ${delay.inSeconds}s'
+ ' (${_retryTimestamps.length}/$_retryHourlyCap this hour)',
+ );
+ }
+ _retryTimer = Timer(delay, () {
+ _retryTimer = null;
+ if (!_disposed && _link == null) _startP2p();
+ });
+ }
+
+ // ── Inbound ───────────────────────────────────────────────────────────────
+
+ @override
+ bool consumesInbound(String type) => terminalP2pSignalTypes.contains(type);
+
+ @override
+ Future<void> handleInbound(String type, Map<String, dynamic> payload) async {
+ if (_disposed) return;
+ final sessionId = payload['sessionId'];
+ // p2p_promote_ack belongs to the upgrade orchestration, not to a link's protocol.
+ if (type == 'p2p_promote_ack') {
+ if (sessionId is String && sessionId == _link?.sessionId) {
+ _upgradeWaitResolve?.call();
+ }
+ return;
+ }
+ // A shadow trial negotiates its OWN session beside the live primary — route by
+ // sessionId so its answer reaches it instead of being dropped by the primary.
+ final shadow = _upgradeShadow;
+ if (shadow != null &&
+ sessionId is String &&
+ sessionId == shadow.sessionId) {
+ await shadow.handleSignal(type, payload);
+ } else {
+ await _link?.handleSignal(type, payload);
+ }
+ }
+
+ @override
+ Future<void> observeWsFrame(Map<String, dynamic> plain) =>
+ _noteTerminalResponse(plain, _Wire.relay);
+
+ @override
+ Future<void> observeWsBinary(Uint8List localFrame) async {
+ if (_disposed) return;
+ final header = peekTerminalLocal(localFrame);
+ if (header == null) return;
+ final streamId = header.streamId;
+ if (header.kind == TerminalBinaryKind.keyframe &&
+ _migrating.containsKey(streamId) &&
+ !_p2pStreams.contains(streamId)) {
+ // Phase 1 of a live migration completing: the responder's reply to our WS-side
+ // resync proves it has drained this stream as of now — safe to trigger phase 2.
+ await _commitMigration(streamId);
+ } else if (_p2pStreams.contains(streamId) &&
+ !_migrating.containsKey(streamId)) {
+ // Suppressed while migrating: during phase 2 the responder may still emit
+ // relay-routed output until ITS flip lands, and that is not p2p breaking.
+ await _demote('relay_binary_received');
+ }
+ }
+
+ void _handleP2pData(Object data) {
+ host.enqueueInbound(() async {
+ if (_disposed) return;
+ if (data is String) {
+ if (data.length > 512 * 1024) return;
+ final Map<String, dynamic> wrapped;
+ try {
+ wrapped = jsonDecode(data) as Map<String, dynamic>;
+ } catch (_) {
+ return;
+ }
+ final type = wrapped['type'];
+ if (type is! String || !terminalP2pUpTypes.contains(type)) return;
+ final clear = host.codec.decodeFrame(wrapped);
+ if (clear == null) return;
+ final plain = <String, dynamic>{
+ ...clear,
+ 'payload': (clear['payload'] as Map<String, dynamic>?) ?? {},
+ };
+ // The real frame first — `terminal_ready` is where the session learns its
+ // streamId, and the derived link-mode frame must land after it.
+ await host.dispatch(plain);
+ await _noteTerminalResponse(plain, _Wire.p2p);
+ return;
+ }
+ final bytes = asBytes(data);
+ if (bytes.length > 512 * 1024) return;
+ final local = host.codec.decodeBinary(bytes);
+ if (local == null) return;
+ final header = peekTerminalLocal(local);
+ if (header == null) return;
+ switch (header.kind) {
+ case TerminalBinaryKind.output:
+ case TerminalBinaryKind.keyframe:
+ case TerminalBinaryKind.sync:
+ break;
+ default:
+ return;
+ }
+ final streamId = header.streamId;
+ // Phase 2 of a live migration confirmed: this stream's bytes are genuinely
+ // arriving over p2p — re-arm the ordinary demote-on-mismatch rule for it.
+ _migrating.remove(streamId);
+ // Drain-barrier confirmation for an upgrade in flight: the OLD connection's
+ // answer to the resync it sent itself, proving everything before is accounted for.
+ if (_upgradeDraining.remove(streamId) != null &&
+ _upgradeDraining.isEmpty) {
+ _upgradeWaitResolve?.call();
+ }
+ await host.deliverBinary(local);
+ });
+ }
+
+ Future<void> _noteTerminalResponse(
+ Map<String, dynamic> plain,
+ _Wire wire,
+ ) async {
+ if (_disposed) return;
+ final type = plain['type'];
+ final payload = (plain['payload'] as Map<String, dynamic>?) ?? const {};
+ final streamId = payload['streamId'] is String
+ ? payload['streamId'] as String
+ : '';
+ final requestId = payload['requestId'] is String
+ ? payload['requestId'] as String
+ : '';
+ // Any p2p-delivered frame for a stream still migrating is itself proof the
+ // responder committed its flip.
+ if (wire == _Wire.p2p && streamId.isNotEmpty) _migrating.remove(streamId);
+ if (type == 'terminal_ready' &&
+ requestId.isNotEmpty &&
+ streamId.isNotEmpty) {
+ _streams.add(streamId);
+ if (_pendingOpens.remove(requestId) && wire == _Wire.p2p) {
+ _p2pStreams.add(streamId);
+ }
+ // Derived from the routing table's own membership, not an echo of `wire`, so
+ // a stale terminal_ready can never report a mode that is not actually routing.
+ await _dispatchLinkMode(streamId, linkModeFor(streamId));
+ } else if (type == 'terminal_error' && requestId.isNotEmpty) {
+ _pendingOpens.remove(requestId);
+ } else if (type == 'terminal_closed' && streamId.isNotEmpty) {
+ _p2pStreams.remove(streamId);
+ _streams.remove(streamId);
+ _migrating.remove(streamId);
+ }
+ // A frame for a stream still marked p2p but physically delivered over the relay:
+ // a quieter, single-stream demotion than [_demote] — still worth telling the app.
+ if (wire == _Wire.relay &&
+ streamId.isNotEmpty &&
+ !_migrating.containsKey(streamId) &&
+ _p2pStreams.remove(streamId)) {
+ await _dispatchLinkMode(streamId, 'relay');
+ }
+ }
+
+ Future<void> _dispatchLinkMode(String streamId, String mode) =>
+ host.dispatch({
+ 'type': 'terminal_link_mode',
+ 'payload': {'streamId': streamId, 'mode': mode},
+ });
+
+ /// Which of the three paths this stream's bytes are on.
+ String linkModeFor(String streamId) {
+ if (!_p2pStreams.contains(streamId)) return 'relay';
+ return _link?.transport == TerminalP2pTransport.relay ? 'turn' : 'p2p';
+ }
+
+ // ── Outbound ──────────────────────────────────────────────────────────────
+
+ @override
+ Future<bool> prepareOpen(String requestId) async {
+ final link = _link;
+ final policy = _policy;
+ if (link == null || policy == null || _disposed) return false;
+ final ready = link.isReady || await link.waitUntilReady(policy.openWait);
+ if (_disposed) return false;
+ if (ready) {
+ _pendingOpens.add(requestId);
+ } else {
+ _reportP2pResult('relay', reason: 'open_wait_elapsed');
+ }
+ return ready;
+ }
+
+ @override
+ bool sendJson(
+ String type,
+ Map<String, dynamic> payload,
+ String sealedJson, {
+ required bool openViaPlugin,
+ TransportVia? force,
+ }) {
+ if (_disposed) return false;
+ final streamId = payload['streamId'] is String
+ ? payload['streamId'] as String
+ : '';
+ final closing = type == 'terminal_close' && streamId.isNotEmpty
+ ? streamId
+ : null;
+ if (force == TransportVia.plugin) {
+ // Phase 2 of a migration: a failure here abandons THIS stream's migration only,
+ // never the whole connection — and the frame must not fall back to the relay.
+ final link = _link;
+ if (link != null && link.isReady && link.send(sealedJson)) {
+ if (streamId.isNotEmpty && _migrating.containsKey(streamId)) {
+ _p2pStreams.add(streamId);
+ }
+ } else if (streamId.isNotEmpty) {
+ _migrating.remove(streamId);
+ }
+ return true;
+ }
+ var useP2p =
+ force != TransportVia.ws &&
+ (_p2pStreams.contains(streamId) ||
+ (type == 'terminal_open' && openViaPlugin));
+ if (useP2p && _link?.send(sealedJson) == true) {
+ if (closing != null) {
+ _p2pStreams.remove(closing);
+ _streams.remove(closing);
+ _migrating.remove(closing);
+ }
+ return true;
+ }
+ if (useP2p) {
+ // The relay carries this frame; the demotion's resyncs follow it in the FIFO.
+ unawaited(_demote('send_failed'));
+ }
+ if (closing != null) {
+ _streams.remove(closing);
+ _migrating.remove(closing);
+ }
+ return false;
+ }
+
+ @override
+ Future<bool> sendBinary(Uint8List localFrame, Uint8List sealedFrame) async {
+ if (_disposed) return false;
+ final header = peekTerminalLocal(localFrame);
+ if (header == null || !_p2pStreams.contains(header.streamId)) return false;
+ final link = _link;
+ if (link == null) return false;
+ // A burst of large frames (a chunked upload) can push the send buffer over the
+ // ceiling well before the network drained it — one bounded chance to clear
+ // before this reads a busy channel as a dead one.
+ final startedAt = _now();
+ final sent = await link.sendWithBackpressureRetry(sealedFrame);
+ final waited = _now().difference(startedAt);
+ if (waited.inMilliseconds >= 50) {
+ _log(
+ 'backpressure · drained=${sent ? 'yes' : 'no'} after=${waited.inMilliseconds}ms',
+ );
+ }
+ if (sent) return true;
+ unawaited(_demote('send_failed'));
+ return false;
+ }
+
+ // ── Demotion, migration ───────────────────────────────────────────────────
+
+ Future<void> _demote(String reason) async {
+ // Two causes can race (a refused send and relay-delivered output, say); the
+ // second finds nothing left to demote.
+ if (_disposed || (_link == null && _p2pStreams.isEmpty)) return;
+ // The ONE place every demotion converges, so none can fall through silently.
+ _log('demoted · reason=$reason streams=${_p2pStreams.length}');
+ _upgradeTimer?.cancel();
+ _upgradeTimer = null;
+ _upgradeAttempts = 0;
+ _upgradeDone = false;
+ final shadow = _upgradeShadow;
+ _upgradeShadow = null;
+ if (shadow != null) unawaited(shadow.stop(reason: 'primary_demoted'));
+ // An orphan from an unanswered promote was only worth keeping beside the
+ // primary it was cut over from; with that gone it is just a TURN allocation.
+ final orphan = _upgradeOrphan;
+ _upgradeOrphan = null;
+ if (orphan != null) unawaited(orphan.stop(reason: 'primary_demoted'));
+ _upgradeDraining.clear();
+ _upgradeWaitResolve = null;
+ final link = _link;
+ _link = null;
+ final streamIds = List.of(_p2pStreams);
+ _p2pStreams.clear();
+ _pendingOpens.clear();
+ for (final streamId in streamIds) {
+ _migrating.remove(streamId);
+ unawaited(
+ host.send({
+ 'type': 'terminal_resync',
+ 'payload': {'streamId': streamId},
+ }, force: TransportVia.ws),
+ );
+ await _dispatchLinkMode(streamId, 'relay');
+ }
+ if (streamIds.isNotEmpty) _reportP2pResult('dropped', reason: reason);
+ unawaited(link?.stop(reason: reason));
+ _scheduleRetry();
+ }
+
+ /// Migrate every stream already open on this connection onto p2p, in two phases
+ /// that both reuse `terminal_resync`: (1) here, over the wire the stream is on now
+ /// (the relay) — a drain barrier the responder answers with a fresh keyframe over
+ /// that same path; (2) [_commitMigration], once that keyframe arrives, a second
+ /// resync over p2p, which is what makes the responder flip its routing too.
+ void _promoteOpenStreams() {
+ for (final streamId in _streams) {
+ if (_p2pStreams.contains(streamId) || _migrating.containsKey(streamId)) {
+ continue;
+ }
+ _migrating[streamId] = _now();
+ unawaited(
+ host.send({
+ 'type': 'terminal_resync',
+ 'payload': {'streamId': streamId},
+ }),
+ );
+ }
+ }
+
+ Future<void> _commitMigration(String streamId) async {
+ final link = _link;
+ if (link == null || !link.isReady) {
+ _migrating.remove(streamId);
+ return;
+ }
+ // [_migrating] is deliberately NOT cleared here — only once a p2p-delivered frame
+ // for this stream actually arrives, the real proof the responder flipped.
+ await host.send({
+ 'type': 'terminal_resync',
+ 'payload': {'streamId': streamId},
+ }, force: TransportVia.plugin);
+ }
+
+ void _sweepMigrations() {
+ if (_migrating.isEmpty) return;
+ final cutoff = _now().subtract(_migrationTtl);
+ _migrating.removeWhere((_, startedAt) => startedAt.isBefore(cutoff));
+ }
+
+ // ── TURN → direct upgrade ─────────────────────────────────────────────────
+
+ void _scheduleUpgradeAttempt() {
+ if (_upgradeTimer != null || _upgradeShadow != null || _upgradeDone) return;
+ final delay = _upgradeAttempts < _upgradeQuickAttempts
+ ? _upgradeRetryDelay
+ : _upgradeSlowRetryDelay;
+ _upgradeTimer = Timer(delay, () {
+ _upgradeTimer = null;
+ if (!_disposed) _attemptUpgrade();
+ });
+ }
+
+ /// One trial: a brand-new (shadow) connection, entirely independent of the live
+ /// primary, to see whether IT lands on a direct pair. Nothing here touches the
+ /// routing until [_promoteToDirect] has already proven success.
+ void _attemptUpgrade() {
+ final policy = _policy;
+ final primary = _link;
+ if (_upgradeDone ||
+ primary == null ||
+ !primary.isReady ||
+ primary.transport != TerminalP2pTransport.relay ||
+ policy == null) {
+ return;
+ }
+ // A resume can ask at any moment; one full negotiation a minute is plenty.
+ final now = _now();
+ final last = _lastUpgradeAttemptAt;
+ if (last != null && now.difference(last) < _upgradeRetryDelay) return;
+ _lastUpgradeAttemptAt = now;
+ _upgradeAttempts++;
+ final attempt = _upgradeAttempts;
+ late final TerminalP2pLink shadow;
+ shadow = links.create(
+ policy: policy,
+ upgrade: true,
+ sendSignal: _sendSignal,
+ // Identical to the primary's wiring — nothing routes real data here before
+ // promotion, and after it this IS the primary.
+ onData: _handleP2pData,
+ onStep: (step, elapsed) => _log(
+ 'upgrade step · attempt=$attempt $step +${elapsed.inMilliseconds}ms',
+ ),
+ onState: (state, setup, reason) => _log(
+ 'upgrade ${state.name} · attempt=$attempt +${setup.inMilliseconds}ms'
+ '${reason == null ? '' : ' reason=$reason'}',
+ ),
+ onUnavailable: (reason) {
+ if (_link == shadow) {
+ // Already promoted and now failing for real — an ordinary primary failure.
+ unawaited(_demote(reason));
+ } else if (_upgradeShadow == shadow) {
+ // Died as a trial, before cutover — the primary was never touched.
+ _upgradeShadow = null;
+ _upgradeDraining.clear();
+ _upgradeWaitResolve = null;
+ _finishUpgradeAttempt();
+ }
+ },
+ );
+ _upgradeShadow = shadow;
+ shadow.start();
+ unawaited(_runUpgradeAttempt(shadow));
+ }
+
+ Future<void> _runUpgradeAttempt(TerminalP2pLink shadow) async {
+ final ok = await shadow.waitUntilReady(_upgradeAttemptTimeout);
+ if (_upgradeShadow != shadow || _disposed) return;
+ if (!ok || shadow.transport == TerminalP2pTransport.relay) {
+ _upgradeShadow = null;
+ unawaited(shadow.stop(reason: 'upgrade_no_gain'));
+ _finishUpgradeAttempt();
+ return;
+ }
+ await _promoteToDirect(shadow);
+ }
+
+ void _finishUpgradeAttempt() {
+ if (_upgradeAttempts == _upgradeQuickAttempts) {
+ _log(
+ 'upgrade slowing down · still on turn after $_upgradeAttempts attempts,'
+ ' retrying every ${_upgradeSlowRetryDelay.inMinutes}min',
+ );
+ }
+ _scheduleUpgradeAttempt();
+ }
+
+ /// Cuts the primary over to [shadow], which has already proven itself a true
+ /// direct pair. Every bail-out before the actual swap leaves the primary untouched.
+ Future<void> _promoteToDirect(TerminalP2pLink shadow) async {
+ final old = _link;
+ if (old == null || _upgradeShadow != shadow || _disposed) {
+ unawaited(shadow.stop(reason: 'upgrade_stale'));
+ if (_upgradeShadow == shadow) _upgradeShadow = null;
+ _finishUpgradeAttempt();
+ return;
+ }
+ final streamIds = List.of(_p2pStreams);
+ if (streamIds.isNotEmpty) {
+ // Phase 1 — drain barrier over the OLD (still-primary, still live) connection.
+ final drained = await _waitForUpgradeMilestone(() {
+ final at = _now();
+ for (final streamId in streamIds) {
+ _upgradeDraining[streamId] = at;
+ }
+ for (final streamId in streamIds) {
+ unawaited(
+ host.send({
+ 'type': 'terminal_resync',
+ 'payload': {'streamId': streamId},
+ }),
+ );
+ }
+ }, _upgradeDrainTimeout);
+ if (_upgradeShadow != shadow || _disposed) {
+ _upgradeDraining.clear();
+ unawaited(shadow.stop(reason: 'upgrade_stale'));
+ return;
+ }
+ if (!drained) {
+ // Timed out — the old connection is still completely untouched.
+ _upgradeDraining.clear();
+ _upgradeShadow = null;
+ unawaited(shadow.stop(reason: 'upgrade_drain_timeout'));
+ _finishUpgradeAttempt();
+ return;
+ }
+ }
+ // Phase 2 — the cutover. [_p2pStreams] is untouched: every stream in it was p2p
+ // and stays p2p; only the link behind them changes.
+ _link = shadow;
+ _upgradeShadow = null;
+ final acked = await _waitForUpgradeMilestone(() {
+ for (final streamId in streamIds) {
+ unawaited(
+ host.send({
+ 'type': 'terminal_resync',
+ 'payload': {'streamId': streamId},
+ }),
+ );
+ }
+ _sendSignal('p2p_promote', {
+ 'sessionId': shadow.sessionId,
+ 'protocolVersion': terminalP2pProtocolVersion,
+ });
+ }, _promoteAckTimeout);
+ if (acked) {
+ _upgradeDone = true; // nothing left to upgrade to
+ unawaited(old.stop(reason: 'upgraded', notifyPeer: false));
+ _log('upgrade promoted · attempt=$_upgradeAttempts');
+ // The streams did not change wire from their own point of view, but the
+ // badge they carry did — the CLI leaves it stale at 'turn' here.
+ for (final streamId in streamIds) {
+ if (_p2pStreams.contains(streamId)) {
+ await _dispatchLinkMode(streamId, linkModeFor(streamId));
+ }
+ }
+ } else {
+ // Keep the old connection alive rather than guess it is safe to close; it is
+ // closed when the plugin itself is disposed. The cutover itself stands, so
+ // this link is direct now and there is nothing more to try.
+ _upgradeDone = true;
+ _upgradeOrphan = old;
+ _log('upgrade promote ack timeout · keeping the old connection open');
+ }
+ }
+
+ /// One waiter for [_promoteToDirect]'s two sequential phases. [start] runs AFTER
+ /// the timeout and resolver are armed, so a same-tick resolve cannot race past.
+ Future<bool> _waitForUpgradeMilestone(
+ void Function() start,
+ Duration timeout,
+ ) {
+ final done = Completer<bool>();
+ late final Timer timer;
+ void settle(bool ok) {
+ if (done.isCompleted) return;
+ timer.cancel();
+ _upgradeWaitResolve = null;
+ done.complete(ok);
+ }
+
+ timer = Timer(timeout, () => settle(false));
+ _upgradeWaitResolve = () => settle(true);
+ start();
+ return done.future;
+ }
+
+ // ── Diagnostics ───────────────────────────────────────────────────────────
+
+ /// Sent in the clear (its type is not sealed) so the backend can log outcomes; it
+ /// never carries anything about the session but a word and a duration.
+ void _reportP2pResult(String outcome, {Duration? setup, String? reason}) {
+ unawaited(
+ host.send({
+ 'type': 'p2p_result',
+ 'payload': {
+ 'outcome': outcome,
+ if (setup != null) 'setupMs': setup.inMilliseconds.clamp(0, 1 << 31),
+ if (reason != null && reason.isNotEmpty)
+ 'reason': reason.length > 64 ? reason.substring(0, 64) : reason,
+ },
+ }, force: TransportVia.ws),
+ );
+ }
+}
diff --git a/desktop/lib/web/p2p/terminal_p2p_policy.dart b/desktop/lib/web/p2p/terminal_p2p_policy.dart
new file mode 100644
index 000000000..ab0d4ee60
--- /dev/null
+++ b/desktop/lib/web/p2p/terminal_p2p_policy.dart
@@ -0,0 +1,115 @@
+/// The backend's terminal-P2P policy for one machine, as it arrives on the relay's
+/// `connected` ack — a port of `p2pPolicy()` in the harness CLI's `remoteRelay.ts`
+/// and `readTurn()` in its `terminalP2p.ts`. Same clamps, same reasons: the list
+/// caps match what the backend is configured to send, and a malformed TURN block
+/// degrades to STUN-only rather than to no P2P at all.
+library;
+
+const terminalP2pProtocolVersion = 1;
+
+const _maxStunUrls = 10;
+const _maxTurnUrls = 8;
+const _maxTurnSecretChars = 512;
+const _defaultOpenWaitMs = 1500;
+const _maxOpenWaitMs = 5000;
+
+/// Cloudflare hands out one credential covering several urls. The CLI keeps only
+/// one (werift's limit); libwebrtc takes the whole list, so the phone passes it all.
+class TerminalP2pTurn {
+ const TerminalP2pTurn({
+ required this.urls,
+ required this.username,
+ required this.credential,
+ });
+
+ final List<String> urls;
+ final String username;
+ final String credential;
+
+ /// Shared by both peers in the CLI: same validation, same reason.
+ static TerminalP2pTurn? parse(Object? raw) {
+ if (raw is! Map) return null;
+ final username = raw['username'];
+ final credential = raw['credential'];
+ if (username is! String ||
+ username.isEmpty ||
+ username.length > _maxTurnSecretChars) {
+ return null;
+ }
+ if (credential is! String ||
+ credential.isEmpty ||
+ credential.length > _maxTurnSecretChars) {
+ return null;
+ }
+ final urlsRaw = raw['urls'];
+ final urls = urlsRaw is List
+ ? urlsRaw
+ .whereType<String>()
+ .where(
+ (url) =>
+ RegExp(r'^turns?:', caseSensitive: false).hasMatch(url),
+ )
+ .take(_maxTurnUrls)
+ .toList(growable: false)
+ : const <String>[];
+ if (urls.isEmpty) return null;
+ return TerminalP2pTurn(
+ urls: urls,
+ username: username,
+ credential: credential,
+ );
+ }
+
+ /// As the offer carries it to the responder — the only way the credential can
+ /// reach it, since the backend never sends the responder a policy of its own.
+ Map<String, dynamic> toJson() => {
+ 'urls': urls,
+ 'username': username,
+ 'credential': credential,
+ };
+}
+
+class TerminalP2pPolicy {
+ const TerminalP2pPolicy({
+ required this.stunUrls,
+ required this.openWaitMs,
+ this.turn,
+ });
+
+ /// `stun:`/`stuns:` urls, in the backend's order.
+ final List<String> stunUrls;
+
+ /// How long a `terminal_open` waits for the data channel before riding the relay.
+ final int openWaitMs;
+ final TerminalP2pTurn? turn;
+
+ Duration get openWait => Duration(milliseconds: openWaitMs);
+
+ /// Null unless the backend enabled P2P for this user+machine at the protocol this
+ /// build speaks — either is the same "ws relay only" answer.
+ static TerminalP2pPolicy? parse(Object? raw) {
+ if (raw is! Map) return null;
+ if (raw['enabled'] != true) return null;
+ if (raw['protocolVersion'] != terminalP2pProtocolVersion) return null;
+ final stunRaw = raw['stunUrls'];
+ final stunUrls = stunRaw is List
+ ? stunRaw
+ .whereType<String>()
+ .where(
+ (url) =>
+ RegExp(r'^stuns?:', caseSensitive: false).hasMatch(url),
+ )
+ .take(_maxStunUrls)
+ .toList(growable: false)
+ : const <String>[];
+ final waitRaw = raw['openWaitMs'];
+ final openWaitMs = waitRaw is num && waitRaw.isFinite
+ ? waitRaw.round().clamp(0, _maxOpenWaitMs)
+ : _defaultOpenWaitMs;
+ return TerminalP2pPolicy(
+ stunUrls: stunUrls,
+ openWaitMs: openWaitMs,
+ turn: TerminalP2pTurn.parse(raw['turn']),
+ );
+ }
+}
diff --git a/desktop/lib/web/p2p/web_terminal_p2p.dart b/desktop/lib/web/p2p/web_terminal_p2p.dart
new file mode 100644
index 000000000..95973ca07
--- /dev/null
+++ b/desktop/lib/web/p2p/web_terminal_p2p.dart
@@ -0,0 +1,10 @@
+import 'browser_terminal_p2p_link.dart';
+import 'terminal_p2p_plugin.dart';
+
+/// The browser's one set of P2P terminal plugins, the phone's
+/// `phoneTerminalP2p` on the browser's own WebRTC: each relay connection to a
+/// machine gets a data channel beside it, and terminal traffic takes whichever
+/// wire is up.
+final webTerminalP2p = TerminalP2pPlugins(
+ links: const BrowserTerminalP2pLinkFactory(),
+);
diff --git a/desktop/lib/web/web_entry.dart b/desktop/lib/web/web_entry.dart
index ffe37c873..65b76400e 100644
--- a/desktop/lib/web/web_entry.dart
+++ b/desktop/lib/web/web_entry.dart
@@ -1,14 +1,25 @@
import 'package:flutter/widgets.dart';
import '../state/app_state.dart';
+import '../ws/terminal_transport_plugin.dart';
+import 'p2p/p2p_resume_retry.dart';
+import 'p2p/web_terminal_p2p.dart';
import 'shell/web_store_banner.dart';
import 'shell/web_workspace.dart';
/// The signed-in screen of a browser build, chosen over
/// `desktop_workspace.dart` by the conditional import in `main.dart`: the
/// shared workspace, composed for a mouse.
-Widget authenticatedWorkspace(AppNotifier app) => WebWorkspace(app: app);
+Widget authenticatedWorkspace(AppNotifier app) => P2pResumeRetry(
+ plugins: webTerminalP2p,
+ child: WebWorkspace(app: app),
+);
/// What a browser build draws around every screen: on a phone, the bar that
/// sends it to the Harness app in its store.
Widget appFrame(Widget app) => WebStoreFrame(child: app);
+
+/// A browser reaches a machine through the relay, so each connection gets a
+/// WebRTC data channel beside it (`p2p/`); the relay stays the fallback.
+final TerminalTransportPluginFactory terminalTransportPlugins =
+ webTerminalP2p.create;
diff --git a/desktop/pubspec.lock b/desktop/pubspec.lock
index 363684103..9c7088864 100644
--- a/desktop/pubspec.lock
+++ b/desktop/pubspec.lock
@@ -138,7 +138,7 @@ packages:
source: hosted
version: "2.1.0"
fake_async:
- dependency: transitive
+ dependency: "direct dev"
description:
name: fake_async
sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44"
diff --git a/desktop/pubspec.yaml b/desktop/pubspec.yaml
index 822cd3b1f..d2d6ca096 100644
--- a/desktop/pubspec.yaml
+++ b/desktop/pubspec.yaml
@@ -107,6 +107,7 @@ dev_dependencies:
# package. See that file for information about deactivating specific lint
# rules and activating additional ones.
flutter_lints: ^6.0.0
+ fake_async: ^1.3.3
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
diff --git a/desktop/test/p2p/fakes.dart b/desktop/test/p2p/fakes.dart
new file mode 100644
index 000000000..a81ba682f
--- /dev/null
+++ b/desktop/test/p2p/fakes.dart
@@ -0,0 +1,362 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:typed_data';
+
+import 'package:fake_async/fake_async.dart';
+
+import 'package:harness/terminal/terminal_binary.dart';
+import 'package:harness/ws/relay_codec.dart';
+import 'package:harness/ws/terminal_transport_plugin.dart';
+import 'package:harness/web/p2p/terminal_p2p_link.dart';
+import 'package:harness/web/p2p/terminal_p2p_plugin.dart';
+import 'package:harness/web/p2p/terminal_p2p_policy.dart';
+
+const streamA = '11111111-1111-4111-8111-111111111111';
+const streamB = '22222222-2222-4222-8222-222222222222';
+
+const enabledPolicy = {
+ 'enabled': true,
+ 'protocolVersion': 1,
+ 'stunUrls': ['stun:stun.example:3478'],
+ 'openWaitMs': 1500,
+};
+
+/// A scripted data channel: the test opens, fails or drops it, and sees every
+/// frame the plugin put on it.
+class FakeTerminalP2pLink implements TerminalP2pLink {
+ FakeTerminalP2pLink({
+ required this.policy,
+ required this.sendSignal,
+ required this.onData,
+ this.onState,
+ this.onUnavailable,
+ this.upgrade = false,
+ required this.sessionId,
+ });
+
+ final TerminalP2pPolicy policy;
+ final TerminalP2pSignalSink sendSignal;
+ final TerminalP2pDataSink onData;
+ final TerminalP2pStateSink? onState;
+ final void Function(String reason)? onUnavailable;
+ final bool upgrade;
+
+ @override
+ final String sessionId;
+
+ bool started = false;
+ bool ready = false;
+ bool acceptSends = true;
+ bool stopped = false;
+ String? stopReason;
+ bool? stopNotifiedPeer;
+ TerminalP2pTransport? _transport;
+ final sent = <Object>[];
+ final signals = <(String, Map<String, dynamic>)>[];
+ final _waiters = <Completer<bool>>[];
+
+ @override
+ bool get isReady => ready && acceptSends;
+
+ @override
+ TerminalP2pTransport? get transport => ready ? _transport : null;
+
+ @override
+ void start() {
+ started = true;
+ onState?.call(TerminalP2pLinkState.connecting, Duration.zero, null);
+ }
+
+ void open({TerminalP2pTransport transport = TerminalP2pTransport.direct}) {
+ ready = true;
+ _transport = transport;
+ for (final waiter in _waiters.toList()) {
+ if (!waiter.isCompleted) waiter.complete(true);
+ }
+ _waiters.clear();
+ onState?.call(
+ TerminalP2pLinkState.open,
+ const Duration(milliseconds: 420),
+ null,
+ );
+ }
+
+ /// Never reached open.
+ void failNegotiation(String reason) {
+ onState?.call(
+ TerminalP2pLinkState.failed,
+ const Duration(seconds: 25),
+ reason,
+ );
+ unawaited(stop(reason: reason));
+ }
+
+ /// Was open, and then the wire went away.
+ void drop(String reason) {
+ final wasReady = ready;
+ ready = false;
+ onState?.call(
+ TerminalP2pLinkState.failed,
+ const Duration(seconds: 90),
+ reason,
+ );
+ if (wasReady) onUnavailable?.call(reason);
+ unawaited(stop(reason: reason));
+ }
+
+ /// Something arrived over the channel.
+ void receive(Object data) => onData(data);
+
+ @override
+ Future<bool> handleSignal(String type, Map<String, dynamic> payload) async {
+ if (!terminalP2pSignalTypes.contains(type)) return false;
+ signals.add((type, payload));
+ return true;
+ }
+
+ @override
+ bool send(Object data) {
+ if (!isReady) return false;
+ sent.add(data);
+ return true;
+ }
+
+ @override
+ Future<bool> sendWithBackpressureRetry(
+ Object data, {
+ Duration drain = const Duration(seconds: 5),
+ }) async => send(data);
+
+ @override
+ Future<bool> waitUntilReady(Duration timeout) {
+ if (isReady) return Future.value(true);
+ if (stopped || timeout <= Duration.zero) return Future.value(false);
+ final waiter = Completer<bool>();
+ _waiters.add(waiter);
+ Timer(timeout, () {
+ _waiters.remove(waiter);
+ if (!waiter.isCompleted) waiter.complete(false);
+ });
+ return waiter.future;
+ }
+
+ @override
+ Future<void> stop({String reason = 'closed', bool notifyPeer = true}) async {
+ if (stopped) return;
+ stopped = true;
+ ready = false;
+ stopReason = reason;
+ stopNotifiedPeer = notifyPeer;
+ for (final waiter in _waiters.toList()) {
+ if (!waiter.isCompleted) waiter.complete(false);
+ }
+ _waiters.clear();
+ if (notifyPeer) {
+ sendSignal('p2p_abort', {
+ 'sessionId': sessionId,
+ 'protocolVersion': 1,
+ 'reason': reason,
+ });
+ }
+ onState?.call(TerminalP2pLinkState.closed, Duration.zero, reason);
+ }
+}
+
+class FakeLinkFactory implements TerminalP2pLinkFactory {
+ final created = <FakeTerminalP2pLink>[];
+
+ FakeTerminalP2pLink get last => created.last;
+ FakeTerminalP2pLink get first => created.first;
+
+ @override
+ TerminalP2pLink create({
+ required TerminalP2pPolicy policy,
+ required TerminalP2pSignalSink sendSignal,
+ required TerminalP2pDataSink onData,
+ TerminalP2pStateSink? onState,
+ void Function(String reason)? onUnavailable,
+ void Function(String step, Duration elapsed)? onStep,
+ bool upgrade = false,
+ }) {
+ final link = FakeTerminalP2pLink(
+ policy: policy,
+ sendSignal: sendSignal,
+ onData: onData,
+ onState: onState,
+ onUnavailable: onUnavailable,
+ upgrade: upgrade,
+ sessionId: 'session-${created.length + 1}',
+ );
+ created.add(link);
+ return link;
+ }
+}
+
+class FakeCodec implements RelayCodec {
+ FakeCodec({this.terminalP2pVersion = 1});
+
+ @override
+ final int terminalP2pVersion;
+
+ @override
+ Map<String, dynamic> helloFrame() => {'type': 'e2e_hello', 'payload': {}};
+
+ @override
+ Future<bool> handleWelcome(Map<String, dynamic> payload) async => true;
+
+ @override
+ bool handleRekey(Map<String, dynamic> payload) => true;
+
+ @override
+ Map<String, dynamic>? encodeFrame(Map<String, dynamic> frame) => frame;
+
+ @override
+ Map<String, dynamic>? decodeFrame(Map<String, dynamic> frame) => frame;
+
+ @override
+ Uint8List? encodeBinary(Uint8List localFrame) => localFrame;
+
+ @override
+ Uint8List? decodeBinary(Uint8List wireFrame) => wireFrame;
+}
+
+/// The connection as the plugin sees it, with the same routing rule `WsConn`
+/// applies: a frame the plugin does not take goes to the socket.
+class FakeHost implements TerminalTransportHost {
+ FakeHost({FakeCodec? codec}) : codec = codec ?? FakeCodec();
+
+ @override
+ final FakeCodec codec;
+ late TerminalP2pPlugin plugin;
+
+ /// Frames that reached the socket.
+ final wsFrames = <Map<String, dynamic>>[];
+
+ /// Every frame the plugin asked the host to send, with its forced wire.
+ final sends = <(Map<String, dynamic>, TransportVia?)>[];
+ final dispatched = <Map<String, dynamic>>[];
+ final delivered = <Uint8List>[];
+ Future<void> _inbound = Future.value();
+
+ @override
+ Future<bool> send(Map<String, dynamic> frame, {TransportVia? force}) async {
+ sends.add((frame, force));
+ // `WsConn` queues this behind whatever the outbound FIFO is sending right now.
+ await Future<void>.microtask(() {});
+ final type = frame['type'] as String;
+ final payload = (frame['payload'] as Map<String, dynamic>?) ?? {};
+ final taken = plugin.sendJson(
+ type,
+ payload,
+ jsonEncode(frame),
+ openViaPlugin: false,
+ force: force,
+ );
+ // Diagnostics ride the socket too, but no test is about where they went.
+ if (!taken && type != 'p2p_result') wsFrames.add(frame);
+ return true;
+ }
+
+ /// What `WsConn` does for a terminal frame from the app: ask before an open,
+ /// then offer the sealed frame inside the FIFO.
+ Future<bool> sendTerminalFrame(
+ String type,
+ Map<String, dynamic> payload,
+ ) async {
+ var openViaPlugin = false;
+ if (type == 'terminal_open' && payload['requestId'] is String) {
+ openViaPlugin = await plugin.prepareOpen(payload['requestId'] as String);
+ }
+ final frame = {'type': type, 'payload': payload};
+ final taken = plugin.sendJson(
+ type,
+ payload,
+ jsonEncode(frame),
+ openViaPlugin: openViaPlugin,
+ );
+ if (!taken) wsFrames.add(frame);
+ return true;
+ }
+
+ Future<bool> sendTerminalBinary(Uint8List local) async {
+ final taken = await plugin.sendBinary(local, local);
+ if (!taken) wsBinary.add(local);
+ return true;
+ }
+
+ final wsBinary = <Uint8List>[];
+
+ @override
+ void enqueueInbound(Future<void> Function() task) {
+ _inbound = _inbound.then((_) => task());
+ }
+
+ Future<void> get inboundIdle => _inbound;
+
+ @override
+ Future<void> dispatch(Map<String, dynamic> plain) async =>
+ dispatched.add(plain);
+
+ @override
+ Future<void> deliverBinary(Uint8List localFrame) async =>
+ delivered.add(localFrame);
+
+ /// A frame arrived over the socket: dispatched to the app, then observed.
+ Future<void> receiveWs(Map<String, dynamic> plain) async {
+ dispatched.add(plain);
+ await plugin.observeWsFrame(plain);
+ }
+
+ Future<void> receiveWsBinary(Uint8List local) async {
+ await plugin.observeWsBinary(local);
+ delivered.add(local);
+ }
+
+ Iterable<String> get dispatchedTypes =>
+ dispatched.map((f) => f['type'] as String);
+ Iterable<String> get wsTypes => wsFrames.map((f) => f['type'] as String);
+}
+
+Uint8List htrl(TerminalBinaryKind kind, String streamId, {int seq = 1}) =>
+ encodeTerminalLocal(
+ TerminalBinaryFrame(
+ kind: kind,
+ streamId: streamId,
+ seq: seq,
+ bytes: kind == TerminalBinaryKind.sync
+ ? Uint8List(0)
+ : Uint8List.fromList([1, 2, 3]),
+ compressed: false,
+ cols: kind == TerminalBinaryKind.keyframe ? 80 : null,
+ rows: kind == TerminalBinaryKind.keyframe ? 24 : null,
+ ),
+ )!;
+
+Map<String, dynamic> linkMode(String streamId, String mode) => {
+ 'type': 'terminal_link_mode',
+ 'payload': {'streamId': streamId, 'mode': mode},
+};
+
+/// A plugin with its host and link factory, session already up on the given policy.
+///
+/// Under [async], the plugin's clock is the fake one — `DateTime.now()` is not
+/// faked on its own, and the retry budget and migration sweep read the clock.
+({TerminalP2pPlugin plugin, FakeHost host, FakeLinkFactory links}) bootPlugin({
+ Map<String, dynamic>? policy = enabledPolicy,
+ int peerVersion = 1,
+ FakeAsync? async,
+}) {
+ final host = FakeHost(codec: FakeCodec(terminalP2pVersion: peerVersion));
+ final links = FakeLinkFactory();
+ final epoch = DateTime(2026, 9, 14);
+ final plugin = TerminalP2pPlugin(
+ host: host,
+ machineId: 'machine-1234567890',
+ links: links,
+ now: async == null ? null : () => async.getClock(epoch).now(),
+ );
+ host.plugin = plugin;
+ plugin.onConnectedAck({'machineId': 'machine-1234567890', 'p2p': policy});
+ plugin.onSessionReady();
+ return (plugin: plugin, host: host, links: links);
+}
diff --git a/desktop/test/p2p/p2p_sdp_test.dart b/desktop/test/p2p/p2p_sdp_test.dart
new file mode 100644
index 000000000..9adc59945
--- /dev/null
+++ b/desktop/test/p2p/p2p_sdp_test.dart
@@ -0,0 +1,39 @@
+import 'dart:math';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/web/p2p/p2p_sdp.dart';
+
+void main() {
+ test('raises max-message-size in place, line endings untouched', () {
+ const sdp =
+ 'v=0\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\n'
+ 'a=sctp-port:5000\r\na=max-message-size:262144\r\na=mid:0\r\n';
+ expect(
+ raiseMaxMessageSize(sdp),
+ 'v=0\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\n'
+ 'a=sctp-port:5000\r\na=max-message-size:524288\r\na=mid:0\r\n',
+ );
+ });
+
+ test('adds the line after sctp-port when the browser left it out', () {
+ const sdp = 'v=0\r\na=sctp-port:5000\r\na=mid:0\r\n';
+ expect(
+ raiseMaxMessageSize(sdp),
+ 'v=0\r\na=sctp-port:5000\r\na=max-message-size:524288\r\na=mid:0\r\n',
+ );
+ });
+
+ test('session ids are lower-case uuid v4', () {
+ final id = p2pSessionId(Random(7));
+ expect(
+ id,
+ matches(RegExp(r'^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$')),
+ );
+ });
+
+ test('only server-answered candidates count as reflexive', () {
+ expect(reflexiveCandidate.hasMatch('candidate:1 1 udp 1 1.2.3.4 9 typ srflx'), isTrue);
+ expect(reflexiveCandidate.hasMatch('candidate:1 1 udp 1 1.2.3.4 9 typ relay'), isTrue);
+ expect(reflexiveCandidate.hasMatch('candidate:1 1 udp 1 x.local 9 typ host'), isFalse);
+ });
+}
diff --git a/desktop/test/p2p/terminal_p2p_plugin_edges_test.dart b/desktop/test/p2p/terminal_p2p_plugin_edges_test.dart
new file mode 100644
index 000000000..57b763bf8
--- /dev/null
+++ b/desktop/test/p2p/terminal_p2p_plugin_edges_test.dart
@@ -0,0 +1,350 @@
+import 'dart:convert';
+import 'dart:typed_data';
+
+import 'package:fake_async/fake_async.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/web/p2p/terminal_p2p_link.dart';
+import 'package:harness/web/p2p/terminal_p2p_plugin.dart';
+import 'package:harness/web/p2p/terminal_p2p_policy.dart';
+import 'package:harness/terminal/terminal_binary.dart';
+import 'package:harness/ws/terminal_transport_plugin.dart';
+
+import 'fakes.dart';
+
+void flush(FakeAsync async) => async.flushMicrotasks();
+
+Map<String, dynamic> ready(String streamId, String requestId) => {
+ 'type': 'terminal_ready',
+ 'payload': {'streamId': streamId, 'requestId': requestId, 'agentId': 'a'},
+};
+
+/// A link whose send buffer is full: a binary send waits out [drain] and then fails.
+class _BackedUpLink extends FakeTerminalP2pLink {
+ _BackedUpLink({
+ required super.policy,
+ required super.sendSignal,
+ required super.onData,
+ super.onState,
+ super.onUnavailable,
+ super.upgrade,
+ required super.sessionId,
+ });
+
+ @override
+ Future<bool> sendWithBackpressureRetry(
+ Object data, {
+ Duration drain = const Duration(seconds: 5),
+ }) => Future<bool>.delayed(const Duration(milliseconds: 80), () => false);
+}
+
+/// [FakeLinkFactory], but its links report their negotiation steps, and can be backed up.
+class _Links extends FakeLinkFactory {
+ bool backedUp = false;
+ final steps = <String>[];
+
+ @override
+ TerminalP2pLink create({
+ required TerminalP2pPolicy policy,
+ required TerminalP2pSignalSink sendSignal,
+ required TerminalP2pDataSink onData,
+ TerminalP2pStateSink? onState,
+ void Function(String reason)? onUnavailable,
+ void Function(String step, Duration elapsed)? onStep,
+ bool upgrade = false,
+ }) {
+ onStep?.call('offer-created', const Duration(milliseconds: 5));
+ steps.add(upgrade ? 'upgrade' : 'primary');
+ if (!backedUp) {
+ return super.create(
+ policy: policy,
+ sendSignal: sendSignal,
+ onData: onData,
+ onState: onState,
+ onUnavailable: onUnavailable,
+ onStep: onStep,
+ upgrade: upgrade,
+ );
+ }
+ final link = _BackedUpLink(
+ policy: policy,
+ sendSignal: sendSignal,
+ onData: onData,
+ onState: onState,
+ onUnavailable: onUnavailable,
+ upgrade: upgrade,
+ sessionId: 'backed-up-${created.length + 1}',
+ );
+ created.add(link);
+ return link;
+ }
+}
+
+({TerminalP2pPlugin plugin, FakeHost host, _Links links}) boot(
+ FakeAsync async,
+) {
+ final host = FakeHost();
+ final links = _Links();
+ final epoch = DateTime(2026, 9, 14);
+ final plugin = TerminalP2pPlugin(
+ host: host,
+ machineId: 'machine-1',
+ links: links,
+ now: () => async.getClock(epoch).now(),
+ );
+ host.plugin = plugin;
+ plugin.onConnectedAck({'machineId': 'machine-1', 'p2p': enabledPolicy});
+ plugin.onSessionReady();
+ return (plugin: plugin, host: host, links: links);
+}
+
+/// A stream open over the channel on [link].
+void openOverP2p(
+ FakeAsync async,
+ FakeHost host,
+ FakeTerminalP2pLink link, {
+ String stream = streamA,
+ String requestId = 'r1',
+}) {
+ host.sendTerminalFrame('terminal_open', {'requestId': requestId});
+ flush(async);
+ link.receive(jsonEncode(ready(stream, requestId)));
+ flush(async);
+}
+
+void main() {
+ group('the set of live plugins', () {
+ test('holds each plugin until it is disposed, and kicks them all', () {
+ fakeAsync((async) {
+ final links = FakeLinkFactory();
+ final plugins = TerminalP2pPlugins(links: links);
+ final hostA = FakeHost(), hostB = FakeHost();
+ final a = plugins.create(hostA, 'a') as TerminalP2pPlugin;
+ final b = plugins.create(hostB, 'b') as TerminalP2pPlugin;
+ hostA.plugin = a;
+ hostB.plugin = b;
+ expect(plugins.liveCount, 2);
+
+ for (final plugin in [a, b]) {
+ plugin.onConnectedAck({'p2p': enabledPolicy});
+ plugin.onSessionReady();
+ }
+ // Both fail to negotiate; both wait out a retry.
+ links.created[0].failNegotiation('peer_failed');
+ links.created[1].failNegotiation('peer_failed');
+ flush(async);
+ expect(links.created, hasLength(2));
+ plugins.kickRetry();
+ expect(
+ links.created,
+ hasLength(4),
+ reason: 'every live plugin retried at once',
+ );
+
+ a.dispose();
+ expect(plugins.liveCount, 1);
+ b.dispose();
+ expect(plugins.liveCount, 0);
+ plugins.kickRetry();
+ expect(links.created, hasLength(4));
+ });
+ });
+ });
+
+ group('stream bookkeeping', () {
+ test('an open that errors is no longer waiting on the channel', () {
+ fakeAsync((async) {
+ final b = boot(async);
+ b.links.last.open();
+ flush(async);
+ b.host.sendTerminalFrame('terminal_open', {'requestId': 'r1'});
+ flush(async);
+ b.links.last.receive(
+ jsonEncode({
+ 'type': 'terminal_error',
+ 'payload': {'requestId': 'r1', 'error': 'NO_AGENT'},
+ }),
+ );
+ flush(async);
+ // A late ready for the same request is not taken as a p2p stream.
+ b.host.receiveWs(ready(streamA, 'r1'));
+ flush(async);
+ expect(b.plugin.linkModeFor(streamA), 'relay');
+ b.plugin.dispose();
+ });
+ });
+
+ test('a stream the machine closed over the channel is forgotten', () {
+ fakeAsync((async) {
+ final b = boot(async);
+ b.links.last.open();
+ flush(async);
+ openOverP2p(async, b.host, b.links.last);
+ expect(b.plugin.linkModeFor(streamA), 'p2p');
+ b.links.last.receive(
+ jsonEncode({
+ 'type': 'terminal_closed',
+ 'payload': {'streamId': streamA},
+ }),
+ );
+ flush(async);
+ expect(b.plugin.linkModeFor(streamA), 'relay');
+ b.plugin.dispose();
+ });
+ });
+
+ test(
+ 'closing a stream the channel refused falls to the socket and forgets it',
+ () {
+ fakeAsync((async) {
+ final b = boot(async);
+ b.links.last.open();
+ flush(async);
+ openOverP2p(async, b.host, b.links.last);
+ b.links.last.acceptSends = false;
+ b.host.sendTerminalFrame('terminal_close', {'streamId': streamA});
+ flush(async);
+ expect(b.host.wsTypes, contains('terminal_close'));
+ expect(b.plugin.linkModeFor(streamA), 'relay');
+ b.plugin.dispose();
+ });
+ },
+ );
+
+ test(
+ 'a forced channel send with no channel abandons only that migration',
+ () {
+ fakeAsync((async) {
+ final b = boot(async);
+ // No channel is up: a forced send is still the plugin's, and dropped.
+ expect(
+ b.plugin.sendJson(
+ 'terminal_resync',
+ {'streamId': streamA},
+ '{}',
+ openViaPlugin: false,
+ force: TransportVia.plugin,
+ ),
+ isTrue,
+ );
+ expect(b.plugin.linkModeFor(streamA), 'relay');
+ b.plugin.dispose();
+ });
+ },
+ );
+ });
+
+ group('backpressure', () {
+ test('a channel that stays backed up demotes the stream to the socket', () {
+ fakeAsync((async) {
+ final host = FakeHost();
+ final links = _Links()..backedUp = true;
+ final epoch = DateTime(2026, 9, 14);
+ final plugin = TerminalP2pPlugin(
+ host: host,
+ machineId: 'm',
+ links: links,
+ now: () => async.getClock(epoch).now(),
+ );
+ host.plugin = plugin;
+ plugin.onConnectedAck({'p2p': enabledPolicy});
+ plugin.onSessionReady();
+ final link = links.last;
+ link.open();
+ flush(async);
+ openOverP2p(async, host, link);
+ expect(plugin.linkModeFor(streamA), 'p2p');
+
+ bool? sent;
+ plugin
+ .sendBinary(htrl(TerminalBinaryKind.input, streamA), Uint8List(4))
+ .then((value) => sent = value);
+ async.elapse(const Duration(milliseconds: 100));
+ flush(async);
+ expect(sent, isFalse, reason: 'the socket carries it instead');
+ expect(plugin.linkModeFor(streamA), 'relay');
+ expect(host.dispatched.last, linkMode(streamA, 'relay'));
+ plugin.dispose();
+ });
+ });
+ });
+
+ group('an upgrade trial', () {
+ ({FakeHost host, _Links links, TerminalP2pPlugin plugin}) onTurn(
+ FakeAsync async,
+ ) {
+ final b = boot(async);
+ b.links.last.open(transport: TerminalP2pTransport.relay);
+ flush(async);
+ openOverP2p(async, b.host, b.links.last);
+ b.host.sends.clear();
+ return (host: b.host, links: b.links, plugin: b.plugin);
+ }
+
+ test('signals for the trial reach the trial, not the live link', () {
+ fakeAsync((async) {
+ final b = onTurn(async);
+ async.elapse(const Duration(seconds: 60));
+ final shadow = b.links.last;
+ expect(shadow.upgrade, isTrue);
+ b.plugin.handleInbound('p2p_answer', {
+ 'sessionId': shadow.sessionId,
+ 'sdp': 'v=0',
+ });
+ b.plugin.handleInbound('p2p_answer', {
+ 'sessionId': b.links.first.sessionId,
+ 'sdp': 'v=0',
+ });
+ flush(async);
+ expect(shadow.signals.single.$2['sessionId'], shadow.sessionId);
+ expect(
+ b.links.first.signals.single.$2['sessionId'],
+ b.links.first.sessionId,
+ );
+ // A promote ack for anything but the live link is nobody's.
+ b.plugin.handleInbound('p2p_promote_ack', {'sessionId': 'stranger'});
+ flush(async);
+ expect(b.links.steps, ['primary', 'upgrade']);
+ b.plugin.dispose();
+ });
+ });
+
+ test('a trial the old link never drains for is dropped, the live link untouched', () {
+ fakeAsync((async) {
+ final b = onTurn(async);
+ final primary = b.links.first;
+ async.elapse(const Duration(seconds: 60));
+ final shadow = b.links.last;
+ shadow.open();
+ flush(async);
+ // The drain resync went out; no keyframe comes back.
+ async.elapse(const Duration(seconds: 6));
+ flush(async);
+ expect(shadow.stopReason, 'upgrade_drain_timeout');
+ expect(primary.stopped, isFalse);
+ expect(b.plugin.linkModeFor(streamA), 'turn');
+ // And the next trial is scheduled as usual.
+ async.elapse(const Duration(seconds: 60));
+ expect(b.links.created, hasLength(3));
+ b.plugin.dispose();
+ });
+ });
+
+ test('a trial that dies mid-drain is let go of, and the drain with it', () {
+ fakeAsync((async) {
+ final b = onTurn(async);
+ final primary = b.links.first;
+ async.elapse(const Duration(seconds: 60));
+ final shadow = b.links.last;
+ shadow.open();
+ flush(async);
+ shadow.drop('peer_failed');
+ flush(async);
+ async.elapse(const Duration(seconds: 6));
+ flush(async);
+ expect(primary.stopped, isFalse);
+ expect(b.plugin.linkModeFor(streamA), 'turn');
+ b.plugin.dispose();
+ });
+ });
+ });
+}
diff --git a/desktop/test/p2p/terminal_p2p_plugin_test.dart b/desktop/test/p2p/terminal_p2p_plugin_test.dart
new file mode 100644
index 000000000..112178865
--- /dev/null
+++ b/desktop/test/p2p/terminal_p2p_plugin_test.dart
@@ -0,0 +1,589 @@
+import 'dart:convert';
+
+import 'package:fake_async/fake_async.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/terminal/terminal_binary.dart';
+import 'package:harness/ws/terminal_transport_plugin.dart';
+import 'package:harness/web/p2p/terminal_p2p_link.dart';
+
+import 'fakes.dart';
+
+/// Every await in the plugin is over already-completed futures under a fake
+/// host, so one flush of the microtask queue settles it.
+void flush(FakeAsync async) => async.flushMicrotasks();
+
+Map<String, dynamic> ready(String streamId, String requestId) => {
+ 'type': 'terminal_ready',
+ 'payload': {'streamId': streamId, 'requestId': requestId, 'agentId': 'a'},
+};
+
+Iterable<Map<String, dynamic>> p2pResults(FakeHost host) => host.sends
+ .where((s) => s.$1['type'] == 'p2p_result')
+ .map((s) => s.$1['payload'] as Map<String, dynamic>);
+
+void main() {
+ group('negotiation start', () {
+ test('starts only with a policy and a peer that speaks v1', () {
+ expect(bootPlugin(policy: null).links.created, isEmpty);
+ expect(bootPlugin(peerVersion: 0).links.created, isEmpty);
+ final b = bootPlugin();
+ expect(b.links.created, hasLength(1));
+ expect(b.links.last.started, isTrue);
+ b.plugin.dispose();
+ });
+
+ test(
+ 'signals go out sealed over the socket, answers reach the link',
+ () async {
+ final b = bootPlugin();
+ b.links.last.sendSignal('p2p_offer', {
+ 'sessionId': b.links.last.sessionId,
+ });
+ await Future<void>.delayed(Duration.zero);
+ expect(b.host.sends.single.$2, TransportVia.ws);
+ expect(b.host.wsTypes, ['p2p_offer']);
+ expect(b.plugin.consumesInbound('p2p_answer'), isTrue);
+ expect(b.plugin.consumesInbound('terminal_ready'), isFalse);
+ await b.plugin.handleInbound('p2p_answer', {
+ 'sessionId': b.links.last.sessionId,
+ 'sdp': 'v=0',
+ });
+ expect(b.links.last.signals.single.$1, 'p2p_answer');
+ b.plugin.dispose();
+ },
+ );
+
+ test(
+ 'a failed negotiation reports, clears the link and retries after 60s',
+ () {
+ fakeAsync((async) {
+ final b = bootPlugin(async: async);
+ b.links.last.failNegotiation('negotiation_timeout');
+ flush(async);
+ expect(p2pResults(b.host).single['outcome'], 'timeout');
+ expect(b.links.created, hasLength(1));
+ async.elapse(const Duration(seconds: 60));
+ expect(b.links.created, hasLength(2));
+ expect(b.links.last.started, isTrue);
+ b.links.last.failNegotiation('peer_failed');
+ flush(async);
+ expect(p2pResults(b.host).last['outcome'], 'failed');
+ b.plugin.dispose();
+ });
+ },
+ );
+
+ test('the retry budget is ten per rolling hour', () {
+ fakeAsync((async) {
+ final b = bootPlugin(async: async);
+ for (var i = 0; i < 10; i++) {
+ b.links.last.failNegotiation('peer_failed');
+ flush(async);
+ async.elapse(const Duration(seconds: 60));
+ }
+ expect(b.links.created, hasLength(11));
+ b.links.last.failNegotiation('peer_failed');
+ flush(async);
+ async.elapse(const Duration(minutes: 49));
+ expect(b.links.created, hasLength(11), reason: 'budget spent');
+ // The window rolls: an hour after the first attempt a slot frees up, and
+ // the deferred retry takes it a minute later.
+ async.elapse(const Duration(minutes: 2));
+ expect(b.links.created, hasLength(12));
+ b.plugin.dispose();
+ });
+ });
+
+ test('kickRetry fires a pending retry at once', () {
+ fakeAsync((async) {
+ final b = bootPlugin(async: async);
+ b.links.last.failNegotiation('peer_failed');
+ flush(async);
+ async.elapse(const Duration(seconds: 5));
+ expect(b.links.created, hasLength(1));
+ b.plugin.kickRetry();
+ expect(b.links.created, hasLength(2));
+ b.plugin.dispose();
+ });
+ });
+ });
+
+ group('opening a stream', () {
+ test('rides the channel when it is ready', () {
+ fakeAsync((async) {
+ final b = bootPlugin(async: async);
+ b.links.last.open();
+ flush(async);
+ b.host.sendTerminalFrame('terminal_open', {'requestId': 'r1'});
+ flush(async);
+ expect(b.links.last.sent, hasLength(1));
+ expect(b.host.wsFrames, isEmpty);
+ b.host.receiveWs(
+ ready(streamA, 'r1'),
+ ); // ready came back over the socket…
+ flush(async);
+ // …so the stream is NOT p2p, and the app is told relay.
+ expect(b.host.dispatched.last, linkMode(streamA, 'relay'));
+ expect(b.plugin.linkModeFor(streamA), 'relay');
+ b.plugin.dispose();
+ });
+ });
+
+ test('waits openWaitMs, then falls back to the socket', () {
+ fakeAsync((async) {
+ final b = bootPlugin(async: async);
+ var done = false;
+ b.host
+ .sendTerminalFrame('terminal_open', {'requestId': 'r1'})
+ .then((_) => done = true);
+ flush(async);
+ expect(b.host.wsFrames, isEmpty, reason: 'still waiting');
+ async.elapse(const Duration(milliseconds: 1500));
+ flush(async);
+ expect(done, isTrue);
+ expect(b.host.wsTypes, ['terminal_open']);
+ final result = p2pResults(b.host).single;
+ expect(result['outcome'], 'relay');
+ expect(result['reason'], 'open_wait_elapsed');
+ b.plugin.dispose();
+ });
+ });
+
+ test(
+ 'a ready over the channel marks the stream p2p, mode after the frame',
+ () {
+ fakeAsync((async) {
+ final b = bootPlugin(async: async);
+ b.links.last.open();
+ flush(async);
+ b.host.sendTerminalFrame('terminal_open', {'requestId': 'r1'});
+ flush(async);
+ b.links.last.receive(jsonEncode(ready(streamA, 'r1')));
+ flush(async);
+ expect(b.host.dispatched, [
+ ready(streamA, 'r1'),
+ linkMode(streamA, 'p2p'),
+ ]);
+ expect(b.plugin.linkModeFor(streamA), 'p2p');
+ // From here the stream's frames ride the channel.
+ b.host.sendTerminalFrame('terminal_alive', {'streamId': streamA});
+ b.host.sendTerminalBinary(htrl(TerminalBinaryKind.input, streamA));
+ flush(async);
+ expect(b.links.last.sent, hasLength(3));
+ expect(b.host.wsFrames, isEmpty);
+ expect(b.host.wsBinary, isEmpty);
+ // Another stream's frames do not.
+ b.host.sendTerminalFrame('terminal_alive', {'streamId': streamB});
+ flush(async);
+ expect(b.host.wsTypes, ['terminal_alive']);
+ b.plugin.dispose();
+ });
+ },
+ );
+
+ test('a TURN pair reports as turn', () {
+ fakeAsync((async) {
+ final b = bootPlugin(async: async);
+ b.links.last.open(transport: TerminalP2pTransport.relay);
+ flush(async);
+ expect(p2pResults(b.host).single, {
+ 'outcome': 'direct',
+ 'setupMs': 420,
+ 'reason': 'relayed',
+ });
+ b.host.sendTerminalFrame('terminal_open', {'requestId': 'r1'});
+ flush(async);
+ b.links.last.receive(jsonEncode(ready(streamA, 'r1')));
+ flush(async);
+ expect(b.host.dispatched.last, linkMode(streamA, 'turn'));
+ b.plugin.dispose();
+ });
+ });
+
+ test('closing a stream forgets it', () {
+ fakeAsync((async) {
+ final b = bootPlugin(async: async);
+ b.links.last.open();
+ flush(async);
+ b.host.sendTerminalFrame('terminal_open', {'requestId': 'r1'});
+ flush(async);
+ b.links.last.receive(jsonEncode(ready(streamA, 'r1')));
+ flush(async);
+ b.host.sendTerminalFrame('terminal_close', {'streamId': streamA});
+ flush(async);
+ expect(b.plugin.linkModeFor(streamA), 'relay');
+ b.plugin.dispose();
+ });
+ });
+
+ test('channel frames of unexpected shape are dropped', () {
+ fakeAsync((async) {
+ final b = bootPlugin(async: async);
+ b.links.last.open();
+ flush(async);
+ b.links.last.receive('not json');
+ b.links.last.receive(
+ jsonEncode({'type': 'agent_synced', 'payload': {}}),
+ );
+ b.links.last.receive(htrl(TerminalBinaryKind.input, streamA));
+ b.links.last.receive(htrl(TerminalBinaryKind.output, streamA));
+ flush(async);
+ expect(b.host.dispatched, isEmpty);
+ expect(b.host.delivered, hasLength(1));
+ b.plugin.dispose();
+ });
+ });
+ });
+
+ group('demotion', () {
+ ({FakeHost host, FakeLinkFactory links, dynamic plugin}) upWithStream(
+ FakeAsync async,
+ ) {
+ final b = bootPlugin(async: async);
+ b.links.last.open();
+ flush(async);
+ b.host.sendTerminalFrame('terminal_open', {'requestId': 'r1'});
+ flush(async);
+ b.links.last.receive(jsonEncode(ready(streamA, 'r1')));
+ flush(async);
+ b.host.dispatched.clear();
+ b.host.sends.clear();
+ return (host: b.host, links: b.links, plugin: b.plugin);
+ }
+
+ test('the wire going away resyncs every stream over the socket', () {
+ fakeAsync((async) {
+ final b = upWithStream(async);
+ b.links.last.drop('peer_disconnected_timeout');
+ flush(async);
+ expect(b.host.dispatched, [linkMode(streamA, 'relay')]);
+ final resync = b.host.sends.firstWhere(
+ (s) => s.$1['type'] == 'terminal_resync',
+ );
+ expect(resync.$2, TransportVia.ws);
+ expect(b.host.wsTypes, contains('terminal_resync'));
+ expect(p2pResults(b.host).single, {
+ 'outcome': 'dropped',
+ 'reason': 'peer_disconnected_timeout',
+ });
+ expect(b.plugin.linkModeFor(streamA), 'relay');
+ // The retry comes a minute later.
+ async.elapse(const Duration(seconds: 60));
+ expect(b.links.created, hasLength(2));
+ b.plugin.dispose();
+ });
+ });
+
+ test('a send the channel refuses falls to the socket and demotes', () {
+ fakeAsync((async) {
+ final b = upWithStream(async);
+ b.links.last.acceptSends = false;
+ b.host.sendTerminalFrame('terminal_alive', {'streamId': streamA});
+ flush(async);
+ expect(b.host.wsTypes.first, 'terminal_alive');
+ expect(b.links.last.stopReason, 'send_failed');
+ expect(b.host.dispatched, [linkMode(streamA, 'relay')]);
+ b.plugin.dispose();
+ });
+ });
+
+ test('output for a p2p stream arriving over the socket demotes', () {
+ fakeAsync((async) {
+ final b = upWithStream(async);
+ b.host.receiveWsBinary(htrl(TerminalBinaryKind.output, streamA));
+ flush(async);
+ expect(b.links.last.stopReason, 'relay_binary_received');
+ expect(b.host.delivered, hasLength(1), reason: 'still delivered');
+ b.plugin.dispose();
+ });
+ });
+
+ test(
+ 'a json frame for a p2p stream over the socket demotes that stream only',
+ () {
+ fakeAsync((async) {
+ final b = upWithStream(async);
+ b.host.receiveWs({
+ 'type': 'terminal_error',
+ 'payload': {'streamId': streamA, 'code': 'X'},
+ });
+ flush(async);
+ expect(b.host.dispatched.last, linkMode(streamA, 'relay'));
+ expect(
+ b.links.last.stopped,
+ isFalse,
+ reason: 'the channel itself lives on',
+ );
+ b.plugin.dispose();
+ });
+ },
+ );
+ });
+
+ group('live migration', () {
+ test(
+ 'a stream opened on the socket moves to the channel in two phases',
+ () {
+ fakeAsync((async) {
+ final b = bootPlugin(async: async);
+ // Open before the channel is ready → socket.
+ b.host.sendTerminalFrame('terminal_open', {'requestId': 'r1'});
+ async.elapse(const Duration(milliseconds: 1500));
+ flush(async);
+ b.host.receiveWs(ready(streamA, 'r1'));
+ flush(async);
+ expect(b.host.dispatched.last, linkMode(streamA, 'relay'));
+ b.host.sends.clear();
+ b.host.wsFrames.clear();
+
+ // Phase 1: the channel opens → a resync over the socket.
+ b.links.last.open();
+ flush(async);
+ expect(b.host.wsTypes, ['terminal_resync']);
+ expect(b.links.last.sent, isEmpty);
+ // Meanwhile relay output for it is NOT read as a broken channel.
+ b.host.receiveWsBinary(htrl(TerminalBinaryKind.output, streamA));
+ flush(async);
+ expect(b.links.last.stopped, isFalse);
+
+ // Phase 2: the keyframe answering it → a resync over the channel.
+ b.host.receiveWsBinary(htrl(TerminalBinaryKind.keyframe, streamA));
+ flush(async);
+ expect(b.links.last.sent, hasLength(1));
+ expect(
+ jsonDecode(b.links.last.sent.single as String)['type'],
+ 'terminal_resync',
+ );
+ expect(b.plugin.linkModeFor(streamA), 'p2p');
+ // Still suppressed until a channel-delivered frame proves the flip…
+ b.host.receiveWsBinary(htrl(TerminalBinaryKind.output, streamA));
+ flush(async);
+ expect(b.links.last.stopped, isFalse);
+ // …which re-arms the ordinary rule.
+ b.links.last.receive(htrl(TerminalBinaryKind.output, streamA));
+ flush(async);
+ b.host.receiveWsBinary(htrl(TerminalBinaryKind.output, streamA));
+ flush(async);
+ expect(b.links.last.stopReason, 'relay_binary_received');
+ b.plugin.dispose();
+ });
+ },
+ );
+
+ test('a migration nobody answers is swept after 30s', () {
+ fakeAsync((async) {
+ final b = bootPlugin(async: async);
+ b.host.sendTerminalFrame('terminal_open', {'requestId': 'r1'});
+ async.elapse(const Duration(milliseconds: 1500));
+ flush(async);
+ b.host.receiveWs(ready(streamA, 'r1'));
+ flush(async);
+ b.links.last.open();
+ flush(async);
+ async.elapse(const Duration(seconds: 41));
+ // No longer migrating: the keyframe now is just a keyframe.
+ b.links.last.sent.clear();
+ b.host.receiveWsBinary(htrl(TerminalBinaryKind.keyframe, streamA));
+ flush(async);
+ expect(b.links.last.sent, isEmpty);
+ b.plugin.dispose();
+ });
+ });
+
+ test('phase 2 failing abandons only that stream', () {
+ fakeAsync((async) {
+ final b = bootPlugin(async: async);
+ b.host.sendTerminalFrame('terminal_open', {'requestId': 'r1'});
+ async.elapse(const Duration(milliseconds: 1500));
+ flush(async);
+ b.host.receiveWs(ready(streamA, 'r1'));
+ flush(async);
+ b.links.last.open();
+ flush(async);
+ b.links.last.acceptSends = false;
+ b.host.wsFrames.clear();
+ b.host.receiveWsBinary(htrl(TerminalBinaryKind.keyframe, streamA));
+ flush(async);
+ expect(
+ b.host.wsFrames,
+ isEmpty,
+ reason: 'never falls back to the socket',
+ );
+ expect(b.links.last.stopped, isFalse);
+ expect(b.plugin.linkModeFor(streamA), 'relay');
+ b.plugin.dispose();
+ });
+ });
+ });
+
+ group('turn → direct upgrade', () {
+ ({FakeHost host, FakeLinkFactory links, dynamic plugin}) onTurn(
+ FakeAsync async,
+ ) {
+ final b = bootPlugin(async: async);
+ b.links.last.open(transport: TerminalP2pTransport.relay);
+ flush(async);
+ b.host.sendTerminalFrame('terminal_open', {'requestId': 'r1'});
+ flush(async);
+ b.links.last.receive(jsonEncode(ready(streamA, 'r1')));
+ flush(async);
+ b.host.sends.clear();
+ b.host.dispatched.clear();
+ return (host: b.host, links: b.links, plugin: b.plugin);
+ }
+
+ test('a shadow that lands direct is promoted after a drain and an ack', () {
+ fakeAsync((async) {
+ final b = onTurn(async);
+ final primary = b.links.last;
+ async.elapse(const Duration(seconds: 60));
+ expect(b.links.created, hasLength(2));
+ final shadow = b.links.last;
+ expect(shadow.upgrade, isTrue);
+ expect(shadow.started, isTrue);
+ shadow.open();
+ flush(async);
+ // Phase 1: a drain resync over the OLD connection; nothing routes yet.
+ expect(
+ jsonDecode(primary.sent.last as String)['type'],
+ 'terminal_resync',
+ );
+ expect(shadow.sent, isEmpty);
+ primary.receive(htrl(TerminalBinaryKind.keyframe, streamA));
+ flush(async);
+ // Phase 2: the cutover — resync and promote go out, the ack closes the old.
+ expect(
+ jsonDecode(shadow.sent.single as String)['type'],
+ 'terminal_resync',
+ );
+ final promote = b.host.sends.firstWhere(
+ (s) => s.$1['type'] == 'p2p_promote',
+ );
+ expect((promote.$1['payload'] as Map)['sessionId'], shadow.sessionId);
+ expect(primary.stopped, isFalse);
+ b.plugin.handleInbound('p2p_promote_ack', {
+ 'sessionId': shadow.sessionId,
+ });
+ flush(async);
+ expect(primary.stopReason, 'upgraded');
+ expect(primary.stopNotifiedPeer, isFalse);
+ expect(b.plugin.linkModeFor(streamA), 'p2p');
+ expect(b.host.dispatched.last, linkMode(streamA, 'p2p'));
+ // Traffic now rides the shadow.
+ b.host.sendTerminalFrame('terminal_alive', {'streamId': streamA});
+ flush(async);
+ expect(shadow.sent, hasLength(2));
+ b.plugin.dispose();
+ });
+ });
+
+ test('a shadow that also lands on turn is abandoned; three quick tries, then slow', () {
+ fakeAsync((async) {
+ final b = onTurn(async);
+ for (var attempt = 1; attempt <= 3; attempt++) {
+ async.elapse(const Duration(seconds: 60));
+ expect(b.links.created, hasLength(1 + attempt));
+ b.links.last.open(transport: TerminalP2pTransport.relay);
+ flush(async);
+ expect(b.links.last.stopReason, 'upgrade_no_gain');
+ }
+ async.elapse(const Duration(minutes: 5));
+ expect(b.links.created, hasLength(4), reason: 'slowed down, not yet');
+ async.elapse(const Duration(minutes: 10));
+ expect(b.links.created, hasLength(5), reason: 'every 15 min from now');
+ expect(b.links.last.upgrade, isTrue);
+ expect(b.links.first.stopped, isFalse);
+ b.plugin.dispose();
+ });
+ });
+
+ test('a demotion gives the next link a fresh upgrade budget', () {
+ fakeAsync((async) {
+ final b = onTurn(async);
+ for (var attempt = 1; attempt <= 3; attempt++) {
+ async.elapse(const Duration(seconds: 60));
+ b.links.last.open(transport: TerminalP2pTransport.relay);
+ flush(async);
+ }
+ // The primary dies; the retry lands on TURN again.
+ b.links.first.drop('peer_failed');
+ flush(async);
+ async.elapse(const Duration(seconds: 60));
+ final second = b.links.last;
+ expect(second.upgrade, isFalse);
+ second.open(transport: TerminalP2pTransport.relay);
+ flush(async);
+ // Quick attempts again, not the slow pace.
+ async.elapse(const Duration(seconds: 60));
+ expect(b.links.last.upgrade, isTrue);
+ expect(b.links.last, isNot(second));
+ b.plugin.dispose();
+ });
+ });
+
+ test('coming back to the foreground on turn tries an upgrade at once', () {
+ fakeAsync((async) {
+ final b = onTurn(async);
+ async.elapse(const Duration(seconds: 5));
+ expect(b.links.created, hasLength(1));
+ b.plugin.kickRetry();
+ expect(b.links.created, hasLength(2));
+ expect(b.links.last.upgrade, isTrue);
+ // Not twice while that trial is still running.
+ b.plugin.kickRetry();
+ expect(b.links.created, hasLength(2));
+ b.plugin.dispose();
+ });
+ });
+
+ test(
+ 'an unanswered promote keeps the old connection open as an orphan',
+ () {
+ fakeAsync((async) {
+ final b = onTurn(async);
+ final primary = b.links.last;
+ async.elapse(const Duration(seconds: 60));
+ final shadow = b.links.last;
+ shadow.open();
+ flush(async);
+ primary.receive(htrl(TerminalBinaryKind.keyframe, streamA));
+ flush(async);
+ async.elapse(const Duration(seconds: 5));
+ expect(primary.stopped, isFalse);
+ // The promoted shadow dying takes the orphan with it.
+ shadow.drop('peer_failed');
+ flush(async);
+ expect(primary.stopReason, 'primary_demoted');
+ b.plugin.dispose();
+ expect(shadow.stopped, isTrue);
+ });
+ },
+ );
+
+ test('a primary demotion cancels the trial', () {
+ fakeAsync((async) {
+ final b = onTurn(async);
+ async.elapse(const Duration(seconds: 60));
+ final shadow = b.links.last;
+ b.links.first.drop('peer_failed');
+ flush(async);
+ expect(shadow.stopReason, 'primary_demoted');
+ b.plugin.dispose();
+ });
+ });
+ });
+
+ test('dispose stops everything without telling the peer', () {
+ fakeAsync((async) {
+ final b = bootPlugin(async: async);
+ b.links.last.open();
+ flush(async);
+ b.plugin.dispose();
+ expect(b.links.last.stopNotifiedPeer, isFalse);
+ expect(b.links.last.stopReason, 'relay_closed');
+ // Nothing fires afterwards.
+ async.elapse(const Duration(hours: 1));
+ expect(b.links.created, hasLength(1));
+ });
+ });
+}
diff --git a/desktop/test/p2p/terminal_p2p_policy_test.dart b/desktop/test/p2p/terminal_p2p_policy_test.dart
new file mode 100644
index 000000000..1030f7bda
--- /dev/null
+++ b/desktop/test/p2p/terminal_p2p_policy_test.dart
@@ -0,0 +1,100 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/web/p2p/terminal_p2p_policy.dart';
+
+void main() {
+ test('null unless enabled at this protocol version', () {
+ expect(TerminalP2pPolicy.parse(null), isNull);
+ expect(
+ TerminalP2pPolicy.parse({'enabled': false, 'protocolVersion': 1}),
+ isNull,
+ );
+ expect(
+ TerminalP2pPolicy.parse({'enabled': true, 'protocolVersion': 2}),
+ isNull,
+ );
+ expect(
+ TerminalP2pPolicy.parse({'enabled': true, 'protocolVersion': 1}),
+ isNotNull,
+ );
+ });
+
+ test('keeps only stun urls, at most ten, in order', () {
+ final policy = TerminalP2pPolicy.parse({
+ 'enabled': true,
+ 'protocolVersion': 1,
+ 'stunUrls': [
+ 'stun:a',
+ 'turn:b',
+ 7,
+ 'STUNS:c',
+ for (var i = 0; i < 12; i++) 'stun:many$i',
+ ],
+ })!;
+ expect(policy.stunUrls.length, 10);
+ expect(policy.stunUrls.take(2), ['stun:a', 'STUNS:c']);
+ });
+
+ test('openWaitMs defaults to 1500 and clamps to 0..5000', () {
+ TerminalP2pPolicy parse(Object? wait) => TerminalP2pPolicy.parse({
+ 'enabled': true,
+ 'protocolVersion': 1,
+ 'openWaitMs': wait,
+ })!;
+ expect(parse(null).openWaitMs, 1500);
+ expect(parse('x').openWaitMs, 1500);
+ expect(parse(-5).openWaitMs, 0);
+ expect(parse(9000).openWaitMs, 5000);
+ expect(parse(2500.4).openWaitMs, 2500);
+ });
+
+ test('a malformed turn block degrades to stun-only', () {
+ TerminalP2pTurn? turn(Object? raw) => TerminalP2pPolicy.parse({
+ 'enabled': true,
+ 'protocolVersion': 1,
+ 'turn': raw,
+ })!.turn;
+ expect(turn(null), isNull);
+ expect(
+ turn({
+ 'urls': ['turn:x'],
+ 'username': '',
+ 'credential': 'c',
+ }),
+ isNull,
+ );
+ expect(
+ turn({
+ 'urls': ['turn:x'],
+ 'username': 'u',
+ }),
+ isNull,
+ );
+ expect(
+ turn({
+ 'urls': ['stun:x'],
+ 'username': 'u',
+ 'credential': 'c',
+ }),
+ isNull,
+ );
+ expect(
+ turn({
+ 'urls': ['turn:x'],
+ 'username': 'u' * 513,
+ 'credential': 'c',
+ }),
+ isNull,
+ );
+ final ok = turn({
+ 'urls': ['turn:x?transport=udp', 'turns:y:443', 'stun:z', 'turn:9'],
+ 'username': 'u',
+ 'credential': 'c',
+ })!;
+ expect(ok.urls, ['turn:x?transport=udp', 'turns:y:443', 'turn:9']);
+ expect(ok.toJson(), {
+ 'urls': ['turn:x?transport=udp', 'turns:y:443', 'turn:9'],
+ 'username': 'u',
+ 'credential': 'c',
+ });
+ });
+}
diff --git a/desktop/test/web/browser_terminal_p2p_link_test.dart b/desktop/test/web/browser_terminal_p2p_link_test.dart
new file mode 100644
index 000000000..f72d7c744
--- /dev/null
+++ b/desktop/test/web/browser_terminal_p2p_link_test.dart
@@ -0,0 +1,193 @@
+@TestOn('browser')
+library;
+
+import 'dart:async';
+import 'dart:js_interop';
+import 'dart:typed_data';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/web/p2p/browser_terminal_p2p_link.dart';
+import 'package:harness/web/p2p/p2p_sdp.dart';
+import 'package:harness/web/p2p/terminal_p2p_link.dart';
+import 'package:harness/web/p2p/terminal_p2p_policy.dart';
+import 'package:harness/web/p2p/web_terminal_p2p.dart';
+import 'package:web/web.dart';
+
+/// A second peer connection in the same page answers the link the way the
+/// machine's responder (`terminalP2p.ts`) does: the offer and ICE arrive as
+/// signals, the answer and its candidates go back through `handleSignal`.
+class _Responder {
+ _Responder() {
+ pc.ondatachannel = ((RTCDataChannelEvent event) {
+ channel.complete(event.channel..binaryType = 'arraybuffer');
+ }).toJS;
+ pc.onicecandidate = ((RTCPeerConnectionIceEvent event) {
+ final candidate = event.candidate;
+ if (candidate == null) return;
+ final signal = {
+ 'candidate': candidate.candidate,
+ 'sdpMid': candidate.sdpMid,
+ 'sdpMLineIndex': candidate.sdpMLineIndex,
+ };
+ // The responder only trickles once its answer is out.
+ answered ? _toLink(signal) : _pending.add(signal);
+ }).toJS;
+ }
+
+ final pc = RTCPeerConnection();
+ final channel = Completer<RTCDataChannel>();
+ final offers = <String>[];
+ final aborts = <String>[];
+ final _pending = <Map<String, Object?>>[];
+ late BrowserTerminalP2pLink link;
+ bool answered = false;
+
+ Map<String, Object?> _envelope(Map<String, Object?> body) => {
+ 'sessionId': link.sessionId,
+ 'protocolVersion': terminalP2pProtocolVersion,
+ ...body,
+ };
+
+ void _toLink(Map<String, Object?> candidate) => unawaited(
+ link.handleSignal(
+ 'p2p_ice_candidate',
+ _envelope({'candidate': candidate}),
+ ),
+ );
+
+ Future<void> signal(String type, Map<String, dynamic> payload) async {
+ switch (type) {
+ case 'p2p_offer':
+ final sdp = payload['sdp'] as String;
+ offers.add(sdp);
+ await pc
+ .setRemoteDescription(
+ RTCSessionDescriptionInit(type: 'offer', sdp: sdp),
+ )
+ .toDart;
+ // werift sends up to what the offer allows; a browser as the stand-in
+ // only does once its own description allows as much.
+ final answer = raiseMaxMessageSize(
+ (await pc.createAnswer().toDart)!.sdp,
+ );
+ await pc
+ .setLocalDescription(
+ RTCLocalSessionDescriptionInit(type: 'answer', sdp: answer),
+ )
+ .toDart;
+ await link.handleSignal('p2p_answer', _envelope({'sdp': answer}));
+ answered = true;
+ _pending.forEach(_toLink);
+ _pending.clear();
+ case 'p2p_ice_candidate':
+ final candidate = payload['candidate'] as Map;
+ await pc
+ .addIceCandidate(
+ RTCIceCandidateInit(
+ candidate: candidate['candidate'] as String,
+ sdpMid: candidate['sdpMid'] as String?,
+ sdpMLineIndex: candidate['sdpMLineIndex'] as int?,
+ ),
+ )
+ .toDart;
+ case 'p2p_abort':
+ aborts.add(payload['reason'] as String);
+ }
+ }
+
+ void close() => pc.close();
+}
+
+void main() {
+ late _Responder responder;
+ late List<Object> received;
+ late List<TerminalP2pLinkState> states;
+
+ setUp(() {
+ responder = _Responder();
+ received = [];
+ states = [];
+ responder.link = BrowserTerminalP2pLink(
+ policy: const TerminalP2pPolicy(stunUrls: [], openWaitMs: 2500),
+ sendSignal: (type, payload) => unawaited(responder.signal(type, payload)),
+ onData: received.add,
+ onState: (state, _, _) => states.add(state),
+ );
+ });
+
+ tearDown(() async {
+ await responder.link.stop(notifyPeer: false);
+ responder.close();
+ });
+
+ Future<RTCDataChannel> open() async {
+ responder.link.start();
+ expect(
+ await responder.link.waitUntilReady(const Duration(seconds: 15)),
+ isTrue,
+ );
+ return responder.channel.future.timeout(const Duration(seconds: 5));
+ }
+
+ Future<void> until(bool Function() done) async {
+ final deadline = DateTime.now().add(const Duration(seconds: 5));
+ while (!done() && DateTime.now().isBefore(deadline)) {
+ await Future<void>.delayed(const Duration(milliseconds: 20));
+ }
+ }
+
+ test('opens a direct channel the machine can read', () async {
+ final machine = await open();
+
+ expect(states, [TerminalP2pLinkState.connecting, TerminalP2pLinkState.open]);
+ expect(responder.link.transport, TerminalP2pTransport.direct);
+ // A keyframe outgrows the default 256 KiB; the offer must ask for more.
+ expect(responder.offers.single, contains('a=max-message-size:524288'));
+
+ final upstream = <Object?>[];
+ machine.onmessage = ((MessageEvent event) {
+ final data = event.data;
+ upstream.add(
+ data.isA<JSString>()
+ ? (data as JSString).toDart
+ : (data as JSArrayBuffer).toDart.asUint8List().toList(),
+ );
+ }).toJS;
+ expect(responder.link.send('{"type":"terminal_input"}'), isTrue);
+ expect(responder.link.send(Uint8List.fromList([1, 2, 3])), isTrue);
+ await until(() => upstream.length == 2);
+
+ expect(upstream, [
+ '{"type":"terminal_input"}',
+ [1, 2, 3],
+ ]);
+ });
+
+ test('takes a keyframe larger than the browser default', () async {
+ final machine = await open();
+ final keyframe = Uint8List(480 * 1024)..fillRange(0, 480 * 1024, 7);
+
+ machine.send(keyframe.toJS);
+ machine.send('{"type":"terminal_output"}'.toJS);
+ await until(() => received.length == 2);
+
+ expect((received.first as Uint8List).length, keyframe.length);
+ expect(received.last, '{"type":"terminal_output"}');
+ });
+
+ test('stopping tells the machine and refuses further frames', () async {
+ await open();
+
+ await responder.link.stop(reason: 'relay_closed');
+
+ expect(responder.aborts, ['relay_closed']);
+ expect(states.last, TerminalP2pLinkState.closed);
+ expect(responder.link.isReady, isFalse);
+ expect(responder.link.send('late'), isFalse);
+ });
+
+ test('the browser build plugs in its own WebRTC links', () {
+ expect(webTerminalP2p.links, isA<BrowserTerminalP2pLinkFactory>());
+ expect(webTerminalP2p.liveCount, 0);
+ });
+}