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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat: add P2P WebRTC terminal transport support for mobile and desktop clients
0xken1509ae2ac29a61
diff --git a/backend/src/lib/p2pSignaling.test.ts b/backend/src/lib/p2pSignaling.test.tsindex a18392928..e86172226 100644--- a/backend/src/lib/p2pSignaling.test.ts+++ b/backend/src/lib/p2pSignaling.test.ts@@ -1,12 +1,19 @@import { describe, expect, it } from 'vitest'import {isEncryptedP2pFrame,+ P2P_DOWN_TYPES,P2P_SIGNAL_MAX_FRAMES_PER_MINUTE,+ P2P_UP_TYPES,p2pFrameBytes,P2pSignalRateGuard,} from './p2pSignaling.js'describe('P2P signaling relay guard', () => {+ it('routes the whole exchange, the TURN-to-direct cutover included', () => {+ expect([...P2P_DOWN_TYPES].sort()).toEqual(['p2p_abort', 'p2p_ice_candidate', 'p2p_offer', 'p2p_promote'])+ expect([...P2P_UP_TYPES].sort()).toEqual(['p2p_abort', 'p2p_answer', 'p2p_ice_candidate', 'p2p_promote_ack'])+ })+it('accepts only opaque pairwise E2EE envelopes', () => {const encrypted = {type: 'p2p_offer',diff --git a/backend/src/lib/p2pSignaling.ts b/backend/src/lib/p2pSignaling.tsindex 5cd86abdb..167d64729 100644--- a/backend/src/lib/p2pSignaling.ts+++ b/backend/src/lib/p2pSignaling.ts@@ -8,8 +8,12 @@ export const P2P_SIGNAL_MAX_BYTES = 128 * 1024export const P2P_SIGNAL_MAX_FRAMES_PER_MINUTE = 240export const P2P_SIGNAL_MAX_BYTES_PER_MINUTE = 4 * 1024 * 1024-export const P2P_DOWN_TYPES = new Set(['p2p_offer', 'p2p_ice_candidate', 'p2p_abort'])-export const P2P_UP_TYPES = new Set(['p2p_answer', 'p2p_ice_candidate', 'p2p_abort'])+// p2p_promote / p2p_promote_ack: the client's TURN-to-direct upgrade cutting a live session over to a+// shadow one it negotiated beside it (the CLI's remoteRelay.ts promoteToDirect(), and the phone's port of+// it). They ride the same sealed signaling channel as the offer/answer they follow; without them here+// the cutover's promote was rejected as P2P_TYPE_REJECTED and every upgrade timed out on its ack.+export const P2P_DOWN_TYPES = new Set(['p2p_offer', 'p2p_ice_candidate', 'p2p_abort', 'p2p_promote'])+export const P2P_UP_TYPES = new Set(['p2p_answer', 'p2p_ice_candidate', 'p2p_abort', 'p2p_promote_ack'])export function p2pFrameBytes(frame: Frame): number {return Buffer.byteLength(JSON.stringify(frame), 'utf8')diff --git a/cli/src/lib/e2ee/core.test.ts b/cli/src/lib/e2ee/core.test.tsindex 3450c5cc8..634c4fb52 100644--- a/cli/src/lib/e2ee/core.test.ts+++ b/cli/src/lib/e2ee/core.test.ts@@ -135,6 +135,10 @@ describe('e2ee core — codes + fingerprint + classification', () => {// A machine's account usage names what the person spends and on whose subscription. Missing from// either list the request would not fail — it would time out, which is harder to find.expect(C.isEncryptedDownType('usage_read')).toBe(true)+ // The whole p2p signaling exchange, cutover included — see the set's own comment.+ for (const type of ['p2p_offer', 'p2p_answer', 'p2p_ice_candidate', 'p2p_abort', 'p2p_promote']) {+ expect(C.isEncryptedDownType(type)).toBe(true)+ }expect(C.isEncryptedRpcResultType('usage_read_result')).toBe(true)expect(C.ENCRYPTED_RPC_RESULT_TYPES.has('session_get_result')).toBe(true)expect(C.ENCRYPTED_RPC_RESULT_TYPES.has('agents_list_result')).toBe(true)@@ -201,6 +205,6 @@ describe('e2ee core — interop keystone', () => {it('core.ts still hashes to the pinned value shared with the other implementations', () => {const here = dirname(fileURLToPath(import.meta.url))const actual = createHash('sha256').update(readFileSync(join(here, 'core.ts'))).digest('hex')- expect(actual).toBe('76b0171f0dd53a1a00e5e321f376ae956faacf3db85cd95b644ef3dd9f91e78c')+ expect(actual).toBe('ea9395d253a6c1896f264509d18eef1a8e6072b5f5a55ed2e7dea69944d06776')})})diff --git a/cli/src/lib/e2ee/core.ts b/cli/src/lib/e2ee/core.tsindex b333ed27c..dc3b86b35 100644--- a/cli/src/lib/e2ee/core.ts+++ b/cli/src/lib/e2ee/core.ts@@ -387,8 +387,10 @@ export const ENCRYPTED_DOWN_TYPES = new Set<string>([// it outright as TERMINAL_FRAME_REJECTED — indistinguishable from a real protocol violation.'terminal_chunked_upload_begin', 'terminal_chunked_upload_cancel',// WebRTC signaling reveals both peers' network candidates. Keep it inside the already-authenticated- // pairwise session; the backend needs only the outer type + connId to route it.- 'p2p_offer', 'p2p_answer', 'p2p_ice_candidate', 'p2p_abort',+ // pairwise session; the backend needs only the outer type + connId to route it. p2p_promote is the+ // TURN-to-direct cutover (remoteRelay.ts promoteToDirect()) — missing here it went out in the clear+ // and the backend's isEncryptedP2pFrame() rejected it, so no upgrade ever got its ack.+ 'p2p_offer', 'p2p_answer', 'p2p_ice_candidate', 'p2p_abort', 'p2p_promote',])export function isEncryptedUpType(t: string): boolean { return ENCRYPTED_UP_TYPES.has(t) }export function isEncryptedRpcResultType(t: string): boolean { return ENCRYPTED_RPC_RESULT_TYPES.has(t) }diff --git a/desktop/lib/app_shell.dart b/desktop/lib/app_shell.dartindex 001469504..504bc7222 100644--- a/desktop/lib/app_shell.dart+++ b/desktop/lib/app_shell.dart@@ -10,6 +10,8 @@ import 'core/crash_log.dart';import 'core/desktop_window.dart';import 'screens/login_screen.dart';import 'state/app_state.dart';+import 'viewer/viewer_services.dart';+import 'ws/terminal_transport_plugin.dart';import 'shared/theme/app_theme.dart' as grid;import 'shared/theme/appearance_prefs_store.dart';import 'terminal/terminal_font_store.dart';@@ -41,8 +43,12 @@ typedef AuthenticatedScreenBuilder = Widget Function(AppNotifier app);/// stranded from the desktop it shared a codebase with.Future<void> startHarness({required AuthenticatedScreenBuilder authenticatedScreen,+ /// A viewer build's second wire to each machine (see+ /// [TerminalTransportPlugin]); the desktop passes none.+ TerminalTransportPluginFactory? transportPlugins,}) async {WidgetsFlutterBinding.ensureInitialized();+ harnessTransportPlugins = transportPlugins;// Before anything else can fail. The file sinks come first so CrashLog's own// install has somewhere to mirror to — see CrashLog.record.installFileLogs();diff --git a/desktop/lib/e2ee/envelope.dart b/desktop/lib/e2ee/envelope.dartindex a5aa61097..7ea7196f7 100644--- a/desktop/lib/e2ee/envelope.dart+++ b/desktop/lib/e2ee/envelope.dart@@ -49,6 +49,7 @@ const Set<String> encryptedDownTypes = {'p2p_answer','p2p_ice_candidate','p2p_abort',+ 'p2p_promote',};Uint8List _aad(int v, String type, String dbSessionId, String k, String epoch) =>diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 257abd14e..bb833c923 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -2258,6 +2258,7 @@ class AppNotifier extends ChangeNotifier {);},relayCodecs: viewer?.relayCodecs,+ transportPlugins: viewer?.transportPlugins,onAuthFailure: _signedOutAtRuntime,onLocalFailure: _onLocalFailure,onEvent: _handleEvent,diff --git a/desktop/lib/terminal/terminal_binary.dart b/desktop/lib/terminal/terminal_binary.dartindex ed51258f1..e9b21c37b 100644--- a/desktop/lib/terminal/terminal_binary.dart+++ b/desktop/lib/terminal/terminal_binary.dart@@ -202,6 +202,30 @@ Uint8List? encodeTerminalLocal(TerminalBinaryFrame frame) {return Uint8List.fromList([...header, ...payload]);}+/// Kind and stream of a loopback (HTRL) frame from its headers alone — enough to+/// route it without inflating or copying the payload. Null when the frame does+/// not carry a plain body [decodeTerminalLocal] would accept either.+({TerminalBinaryKind kind, String streamId})? peekTerminalLocal(+ Uint8List bytes,+) {+ if (bytes.length < terminalLocalHeaderBytes + 16) return null;+ for (var index = 0; index < _localMagic.length; index++) {+ if (bytes[index] != _localMagic[index]) return null;+ }+ final kind = TerminalBinaryKind.fromCode(bytes[5]);+ if (bytes[4] != terminalLocalVersion || kind == null) return null;+ return (+ kind: kind,+ streamId: _uuidString(+ Uint8List.sublistView(+ bytes,+ terminalLocalHeaderBytes,+ terminalLocalHeaderBytes + 16,+ ),+ ),+ );+}+TerminalBinaryFrame? decodeTerminalLocal(List<int> raw) {final bytes = Uint8List.fromList(raw);if (bytes.length < terminalLocalHeaderBytes) return null;diff --git a/desktop/lib/viewer/e2ee_relay_codec.dart b/desktop/lib/viewer/e2ee_relay_codec.dartindex 1635162ff..2d4057a95 100644--- a/desktop/lib/viewer/e2ee_relay_codec.dart+++ b/desktop/lib/viewer/e2ee_relay_codec.dart@@ -24,6 +24,9 @@ class E2eeRelayCodec implements RelayCodec {bool handleRekey(Map<String, dynamic> payload) =>_session.handleRekey(payload);+ @override+ int get terminalP2pVersion => _session.terminalP2pVersion;+@overrideMap<String, dynamic>? encodeFrame(Map<String, dynamic> frame) {final type = frame['type'];diff --git a/desktop/lib/viewer/viewer_services.dart b/desktop/lib/viewer/viewer_services.dartindex 1c6fb7968..fec09acd3 100644--- a/desktop/lib/viewer/viewer_services.dart+++ b/desktop/lib/viewer/viewer_services.dart@@ -1,6 +1,7 @@import '../auth/auth_session.dart';import '../core/config.dart';import '../ws/relay_codec.dart';+import '../ws/terminal_transport_plugin.dart';import 'direct_auth.dart';import 'direct_auth_api.dart';import 'direct_link.dart';@@ -8,6 +9,13 @@ import 'direct_login.dart';import 'e2ee_relay_codec.dart';import 'viewer_key_store.dart';+/// The second wire a viewer build offers its relay connections — the phone's WebRTC+/// data channel to the machine. Set once, from that app's `main()` through+/// `startHarness`, before the first frame; a mutable global for the same reason+/// `harnessAssetPackage` is one. Null — the desktop, or a viewer without one —+/// leaves every terminal frame on the relay socket.+TerminalTransportPluginFactory? harnessTransportPlugins;+/// Everything a viewer build uses in place of the harness CLI, built once and handed to/// `AppNotifier`: the SSO session, signing in, the machines this device has linked and the E2EE/// sessions to them. A desktop build has none — and where it is null, nothing in the app behaves@@ -19,21 +27,27 @@ class ViewerServices {required this.login,required this.links,required this.relayCodecs,+ required this.transportPlugins,});factory ViewerServices({required AppConfig config,required AuthSession session,ViewerKeyStore? keys,+ TerminalTransportPluginFactory? transportPlugins,}) {final store = keys ?? ViewerKeyStore();- final auth = DirectAuth(session: session, api: DirectAuthApi(config: config));+ final auth = DirectAuth(+ session: session,+ api: DirectAuthApi(config: config),+ );return ViewerServices._(keys: store,auth: auth,login: DirectLogin(auth: auth),links: DirectLink(keys: store, auth: auth, config: config),relayCodecs: viewerRelayCodecs(store),+ transportPlugins: transportPlugins ?? harnessTransportPlugins,);}@@ -42,4 +56,5 @@ class ViewerServices {final DirectLogin login;final DirectLink links;final RelayCodecFactory relayCodecs;+ final TerminalTransportPluginFactory? transportPlugins;}diff --git a/desktop/lib/ws/relay_codec.dart b/desktop/lib/ws/relay_codec.dartindex 900b45f49..9dd854449 100644--- a/desktop/lib/ws/relay_codec.dart+++ b/desktop/lib/ws/relay_codec.dart@@ -15,6 +15,10 @@ abstract interface class RelayCodec {bool handleRekey(Map<String, dynamic> payload);+ /// The machine's `features.terminalP2p` from its welcome — 0 when it offers no+ /// P2P terminal channel (or before the welcome).+ int get terminalP2pVersion;+/// The frame as it may cross the relay. Null when it must travel sealed and the session is not/// up yet — it must then not go at all: sent in the clear it leaks, and a terminal frame is/// rejected by the relay outright.diff --git a/desktop/lib/ws/terminal_transport_plugin.dart b/desktop/lib/ws/terminal_transport_plugin.dartnew file mode 100644index 000000000..0f1fac35c--- /dev/null+++ b/desktop/lib/ws/terminal_transport_plugin.dart@@ -0,0 +1,91 @@+import 'dart:typed_data';++import 'relay_codec.dart';++/// Which wire a frame is forced onto, when the plugin asks for one rather than+/// leaving the choice to its own routing table.+enum TransportVia { ws, plugin }++/// What a [TerminalTransportPlugin] needs from the relay [WsConn] it rides on.+///+/// Every method here lands the plugin's traffic on the SAME FIFOs the socket's own+/// frames use — the outbound one so the E2EE counters are taken in send order+/// whichever wire carries a frame, and the inbound one so replay-window commits and+/// `onEvent` ordering stay serial with what arrives over the WebSocket.+abstract interface class TerminalTransportHost {+ /// The connection's E2EE session, minted per connect.+ RelayCodec get codec;++ /// A plain `{type, payload}` frame of the plugin's own, sealed by the codec where+ /// its type requires it and queued on the outbound FIFO like any other. Without+ /// [force] it is routed the ordinary way (offered back to [TerminalTransportPlugin.sendJson]);+ /// with one, that wire is used. False when it could not go at all.+ Future<bool> send(Map<String, dynamic> frame, {TransportVia? force});++ /// Runs [task] on the inbound FIFO, after everything already queued.+ void enqueueInbound(Future<void> Function() task);++ /// A decoded `{type, payload}` frame, delivered as if it had arrived over the+ /// WebSocket: request/reply matching first, `onEvent` otherwise.+ Future<void> dispatch(Map<String, dynamic> plain);++ /// A loopback (HTRL) binary frame, delivered as if it had arrived over the WebSocket.+ Future<void> deliverBinary(Uint8List localFrame);+}++/// A second wire beside the relay WebSocket — the phone's WebRTC data channel to the+/// machine — that a relay [WsConn] offers every terminal frame to before falling back+/// to the socket. Pure interface: nothing in the shared package knows what the wire+/// is, only where in the socket's life it gets a say.+///+/// The harness CLI plays this role for the desktop (`remoteRelay.ts`); a viewer build+/// that wants the same plugs one of these in through `ViewerServices`.+abstract interface class TerminalTransportPlugin {+ /// The relay's ack to `machine_select` — before the E2EE hello goes out. The+ /// payload carries the backend's transport policy (`p2p`), if any.+ void onConnectedAck(Map<String, dynamic> payload);++ /// The E2EE session is up: `codec.terminalP2pVersion` is now known.+ void onSessionReady();++ /// True for a frame type the plugin owns outright (signaling); such a frame goes+ /// to [handleInbound] and never reaches `onEvent`.+ bool consumesInbound(String type);+ Future<void> handleInbound(String type, Map<String, dynamic> payload);++ /// A decoded WebSocket frame, AFTER it was dispatched to the app. Awaited on the+ /// inbound FIFO, so anything the plugin dispatches from here lands in order.+ Future<void> observeWsFrame(Map<String, dynamic> plain);++ /// A decoded WebSocket binary frame (HTRL), BEFORE it is delivered to the app.+ Future<void> observeWsBinary(Uint8List localFrame);++ /// Called before a `terminal_open` is queued: the plugin may wait (bounded) for its+ /// wire to be ready. True means the open should ride the plugin's wire.+ Future<bool> prepareOpen(String requestId);++ /// Inside the outbound FIFO, once the codec sealed the frame. True: the plugin took+ /// it — sent on its wire, or (a frame [force]d onto a wire that just went away)+ /// deliberately dropped. False: the socket sends it — and the plugin has already+ /// recorded whatever that means for its routing (a stream it thought was its own, say).+ bool sendJson(+ String type,+ Map<String, dynamic> payload,+ String sealedJson, {+ required bool openViaPlugin,+ TransportVia? force,+ });++ /// Inside the outbound FIFO, once the codec sealed the frame. Same contract as+ /// [sendJson]; may wait briefly for backpressure to clear.+ Future<bool> sendBinary(Uint8List localFrame, Uint8List sealedFrame);++ /// The socket is gone (closed, redialing, or refused). Tear the wire down.+ void dispose({bool notifyPeer = false});+}++/// One plugin per relay connection, built once the codec exists.+typedef TerminalTransportPluginFactory = TerminalTransportPlugin Function(+ TerminalTransportHost host,+ String machineId,+);diff --git a/desktop/lib/ws/ws_conn.dart b/desktop/lib/ws/ws_conn.dartindex bdaefb557..e66c38f1a 100644--- a/desktop/lib/ws/ws_conn.dart+++ b/desktop/lib/ws/ws_conn.dart@@ -9,6 +9,7 @@ import '../logging/app_log.dart';import '../logging/redact.dart';import '../core/models.dart';import 'relay_codec.dart';+import 'terminal_transport_plugin.dart';typedef AccessTokenProvider = Future<String> Function(bool forceRefresh,@@ -85,6 +86,11 @@ class WsConn {/// as they are, which is right for the local transport and the dev fixture.final RelayCodecFactory? relayCodecs;+ /// A second wire beside the relay socket (a viewer's WebRTC data channel to the+ /// machine), built per connect once the codec exists. Null — the desktop, the+ /// local transport, the dev fixture — means every frame rides the socket.+ final TerminalTransportPluginFactory? transportPlugins;+Future<Map<String, dynamic>> Function(String type,Map<String, dynamic> payload,@@ -99,6 +105,7 @@ class WsConn {WebSocketChannel? _channel;RelayCodec? _codec;+ TerminalTransportPlugin? _plugin;StreamSubscription? _sub;bool _closing = false;bool _connecting = false;@@ -164,6 +171,7 @@ class WsConn {this.localApiKey,this.localProtocolVersion = 1,this.relayCodecs,+ this.transportPlugins,});Future<void> connect() async {@@ -191,6 +199,10 @@ class WsConn {return;}_codec = codec;+ // A dial that failed past this point left one behind; this connect owns a new one.+ _disposePlugin();+ final plugins = transportPlugins;+ if (plugins != null) _plugin = plugins(_PluginHost(this), machineId);}final Uri uri;if (isLocal) {@@ -247,7 +259,9 @@ class WsConn {_inboundTail = _inboundTail.then((_) async {final local = codec == null ? bytes : codec.decodeBinary(bytes);- if (local != null) await onBinaryFrame?.call(local);+ if (local == null) return;+ await _plugin?.observeWsBinary(local);+ await onBinaryFrame?.call(local);}).catchError((_) {// Binary E2EE/session code owns recovery for bad frames.@@ -313,12 +327,16 @@ class WsConn {// The socket's first `connected` answers the socket itself (it names the user, not a// machine); only the select's own ack starts the handshake.if (payload['machineId'] == machineId) {+ // The policy rides the ack; the plugin must have it before the welcome+ // that decides whether to act on it.+ _plugin?.onConnectedAck(payload);_channel?.sink.add(jsonEncode(codec.helloFrame()));}return;case 'e2e_welcome':if (await codec.handleWelcome(payload)) {_markReady();+ _plugin?.onSessionReady();} else {_refusePeer('E2EE_WELCOME_INVALID');}@@ -332,10 +350,24 @@ class WsConn {}final clear = codec.decodeFrame(message);if (clear == null) return;- await _dispatch({+ final plain = <String, dynamic>{...clear,'payload': (clear['payload'] as Map<String, dynamic>?) ?? {},- });+ };+ final plugin = _plugin;+ final type = plain['type'];+ if (plugin != null && type is String && plugin.consumesInbound(type)) {+ await plugin.handleInbound(+ type,+ plain['payload'] as Map<String, dynamic>,+ );+ return;+ }+ await _dispatch(plain);+ // After, not before: for `terminal_ready` the session learns its streamId from+ // the frame itself, and anything the plugin derives from it (its own+ // `terminal_link_mode`) must land once that has happened.+ await _plugin?.observeWsFrame(plain);}/// The machine is reachable but this device may not talk to it: never linked, the link revoked@@ -345,6 +377,7 @@ class WsConn {void _refusePeer(String reason) {_closing = true;_ready = false;+ _disposePlugin();// needsLink first: AppNotifier's onStatus handler reads machine.needsLink to decide whether a// disconnect should be treated as the node going offline — it has to see it flipped before// onStatus runs, or the very first 4404 for this machine reads as offline for one retry cycle.@@ -457,13 +490,29 @@ class WsConn {/// Terminal input is best-effort: it is never queued across reconnect and/// the caller gets false if the socket stopped being ready before send.- Future<bool> sendTerminalFrame(String type, Map<String, dynamic> payload) =>- _enqueueFrame({'type': type, 'payload': payload}, requireReady: true);+ Future<bool> sendTerminalFrame(+ String type,+ Map<String, dynamic> payload,+ ) async {+ // Outside the FIFO on purpose: the plugin may wait a bounded while for its wire+ // before an open, and that wait must not hold up other panes' input.+ var openViaPlugin = false;+ final plugin = _plugin;+ final requestId = payload['requestId'];+ if (plugin != null && type == 'terminal_open' && requestId is String) {+ openViaPlugin = await plugin.prepareOpen(requestId);+ }+ return _enqueueFrame(+ {'type': type, 'payload': payload},+ requireReady: true,+ openViaPlugin: openViaPlugin,+ );+ }Future<bool> sendTerminalBinary(Uint8List bytes) {final completer = Completer<bool>();_outboundTail = _outboundTail- .then((_) {+ .then((_) async {if (!isReady) {completer.complete(false);return;@@ -481,6 +530,11 @@ class WsConn {completer.complete(false);return;}+ final plugin = _plugin;+ if (plugin != null && await plugin.sendBinary(bytes, wire)) {+ completer.complete(true);+ return;+ }channel.sink.add(wire);completer.complete(true);} catch (_) {@@ -500,6 +554,8 @@ class WsConn {Future<bool> _enqueueFrame(Map<String, dynamic> frame, {bool requireReady = false,+ bool openViaPlugin = false,+ TransportVia? force,void Function(Object error)? onFailure,}) {final completer = Completer<bool>();@@ -510,7 +566,11 @@ class WsConn {return;}try {- await _sendFrameNow(frame);+ await _sendFrameNow(+ frame,+ openViaPlugin: openViaPlugin,+ force: force,+ );completer.complete(true);} catch (error) {onFailure?.call(error);@@ -545,7 +605,11 @@ class WsConn {}}- Future<void> _sendFrameNow(Map<String, dynamic> frame) async {+ Future<void> _sendFrameNow(+ Map<String, dynamic> frame, {+ bool openViaPlugin = false,+ TransportVia? force,+ }) async {final type = frame['type'] as String;var payload = (frame['payload'] as Map<String, dynamic>?) ?? {};if (onOutgoing != null) payload = await onOutgoing!(type, payload);@@ -555,7 +619,24 @@ class WsConn {final codec = _codec;final wire = codec == null ? out : codec.encodeFrame(out);if (wire == null) throw StateError('E2EE session is not ready for $type');- channel.sink.add(jsonEncode(wire));+ final encoded = jsonEncode(wire);+ // Sealed first, then offered: the counter is taken in send order whichever+ // wire ends up carrying the frame, which is what the peer's replay window needs.+ // Only once the session is up: nothing before that (the select, the hello) is+ // the plugin's to route.+ final plugin = _plugin;+ if (plugin != null &&+ _ready &&+ plugin.sendJson(+ type,+ payload,+ encoded,+ openViaPlugin: openViaPlugin,+ force: force,+ )) {+ return;+ }+ channel.sink.add(encoded);}void _flushQueue() {@@ -583,6 +664,7 @@ class WsConn {_channel = null;_sub = null;_codec = null;+ _disposePlugin();_ready = false;_rejectPending('WS disconnected');if (_closing) {@@ -655,6 +737,7 @@ class WsConn {_closing = true;_ready = false;_codec = null;+ _disposePlugin();_reconnectTimer?.cancel();_reconnectTimer = null;_rejectPending('WS closed');@@ -682,6 +765,7 @@ class WsConn {_reconnectTimer?.cancel();_ready = false;_codec = null;+ _disposePlugin();_rejectPending('forcing relay reconnect');final sub = _sub;_sub = null;@@ -712,6 +796,12 @@ class WsConn {await channel.sink.close(4000, 'integration test transport drop');}+ void _disposePlugin() {+ final plugin = _plugin;+ _plugin = null;+ plugin?.dispose();+ }+static String _newRequestId() {final random = Random.secure();final bytes = List<int>.generate(16, (_) => random.nextInt(256));@@ -719,6 +809,41 @@ class WsConn {}}+/// The connection as its plugin sees it — see [TerminalTransportHost].+class _PluginHost implements TerminalTransportHost {+ _PluginHost(this._conn);+ final WsConn _conn;++ @override+ RelayCodec get codec {+ final codec = _conn._codec;+ if (codec == null) throw StateError('relay session is gone');+ return codec;+ }++ @override+ Future<bool> send(Map<String, dynamic> frame, {TransportVia? force}) =>+ _conn._enqueueFrame(frame, requireReady: true, force: force);++ @override+ void enqueueInbound(Future<void> Function() task) {+ _conn._inboundTail = _conn._inboundTail.then((_) => task()).catchError((_) {+ // Keep the FIFO alive, as the socket's own handlers do.+ });+ }++ @override+ Future<void> dispatch(Map<String, dynamic> plain) => _conn._dispatch({+ ...plain,+ 'payload': (plain['payload'] as Map<String, dynamic>?) ?? {},+ });++ @override+ Future<void> deliverBinary(Uint8List localFrame) async {+ await _conn.onBinaryFrame?.call(localFrame);+ }+}+class _PendingRpc {final Completer<Map<String, dynamic>> completer;final Timer timer;diff --git a/desktop/lib/ws/ws_pool.dart b/desktop/lib/ws/ws_pool.dartindex d98c4f210..e45bfde0f 100644--- a/desktop/lib/ws/ws_pool.dart+++ b/desktop/lib/ws/ws_pool.dart@@ -1,5 +1,7 @@import 'dart:async';+import 'relay_codec.dart';+import 'terminal_transport_plugin.dart';import '../core/models.dart';import 'ws_conn.dart';@@ -11,6 +13,10 @@ class WsPool {/// Handed to every relay connection — a viewer build's E2EE sessions (see [RelayCodec]).final RelayCodecFactory? relayCodecs;++ /// Handed to every relay connection beside [relayCodecs] — a viewer build's second+ /// wire to the machine (see [TerminalTransportPlugin]).+ final TerminalTransportPluginFactory? transportPlugins;final AccessTokenProvider accessTokenProvider;final void Function(String message) onAuthFailure;final void Function(String machineId, int code, String reason)?@@ -25,6 +31,7 @@ class WsPool {required this.wsBaseUrl,required this.autonomousEnv,this.relayCodecs,+ this.transportPlugins,required this.accessTokenProvider,required this.onAuthFailure,this.onLocalFailure,@@ -55,6 +62,9 @@ class WsPool {relayCodecs: transportKind == WsTransportKind.cloudE2ee? relayCodecs: null,+ transportPlugins: transportKind == WsTransportKind.cloudE2ee+ ? transportPlugins+ : null,machineId: machineId,accessTokenProvider: accessTokenProvider,onAuthFailure: onAuthFailure,diff --git a/desktop/test/ws_conn_plugin_test.dart b/desktop/test/ws_conn_plugin_test.dartnew file mode 100644index 000000000..ed203e57a--- /dev/null+++ b/desktop/test/ws_conn_plugin_test.dart@@ -0,0 +1,317 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';+import 'dart:typed_data';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/models.dart';+import 'package:harness/ws/relay_codec.dart';+import 'package:harness/ws/terminal_transport_plugin.dart';+import 'package:harness/ws/ws_conn.dart';++/// A relay session that seals nothing — the handshake shape of the real one, with+/// the frames left readable so the test can see what crossed the socket.+class _PassThroughCodec implements RelayCodec {+ bool welcomed = false;++ @override+ Map<String, dynamic> helloFrame() => {'type': 'e2e_hello', 'payload': {}};++ @override+ Future<bool> handleWelcome(Map<String, dynamic> payload) async {+ welcomed = true;+ return true;+ }++ @override+ bool handleRekey(Map<String, dynamic> payload) => true;++ @override+ int get terminalP2pVersion => 1;++ @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;+}++class _RecordingPlugin implements TerminalTransportPlugin {+ _RecordingPlugin(this.host);+ final TerminalTransportHost host;+ final calls = <String>[];+ final sentJson = <Map<String, dynamic>>[];+ bool takeJson = false;+ bool takeBinary = false;+ bool openReady = true;+ bool disposed = false;++ @override+ void onConnectedAck(Map<String, dynamic> payload) =>+ calls.add('ack:${(payload['p2p'] as Map?)?['enabled']}');++ @override+ void onSessionReady() => calls.add('ready');++ @override+ bool consumesInbound(String type) => type.startsWith('p2p_');++ @override+ Future<void> handleInbound(String type, Map<String, dynamic> payload) async =>+ calls.add('inbound:$type');++ @override+ Future<void> observeWsFrame(Map<String, dynamic> plain) async =>+ calls.add('observe:${plain['type']}');++ @override+ Future<void> observeWsBinary(Uint8List localFrame) async =>+ calls.add('observeBinary:${localFrame.length}');++ @override+ Future<bool> prepareOpen(String requestId) async {+ calls.add('prepareOpen:$requestId');+ return openReady;+ }++ @override+ bool sendJson(+ String type,+ Map<String, dynamic> payload,+ String sealedJson, {+ required bool openViaPlugin,+ TransportVia? force,+ }) {+ sentJson.add({+ 'type': type,+ 'openViaPlugin': openViaPlugin,+ 'force': force?.name,+ });+ return takeJson;+ }++ @override+ Future<bool> sendBinary(Uint8List localFrame, Uint8List sealedFrame) async {+ calls.add('sendBinary:${localFrame.length}');+ return takeBinary;+ }++ @override+ void dispose({bool notifyPeer = false}) {+ disposed = true;+ calls.add('dispose');+ }+}++Future<void> _settle() =>+ Future<void>.delayed(const Duration(milliseconds: 40));++void main() {+ late HttpServer server;+ late Completer<WebSocket> socketReady;+ late List<Map<String, dynamic>> received;+ late List<List<int>> receivedBinary;++ setUp(() async {+ server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);+ socketReady = Completer<WebSocket>();+ received = [];+ receivedBinary = [];+ unawaited(+ server.forEach((request) async {+ final socket = await WebSocketTransformer.upgrade(request);+ if (!socketReady.isCompleted) socketReady.complete(socket);+ socket.listen((raw) {+ if (raw is List<int>) {+ receivedBinary.add(raw);+ return;+ }+ final frame = jsonDecode(raw as String) as Map<String, dynamic>;+ received.add(frame);+ if (frame['type'] == 'machine_select') {+ socket.add(+ jsonEncode({+ 'type': 'connected',+ 'payload': {+ 'machineId': 'machine-1',+ 'p2p': {'enabled': true, 'protocolVersion': 1},+ },+ }),+ );+ }+ if (frame['type'] == 'e2e_hello') {+ socket.add(jsonEncode({'type': 'e2e_welcome', 'payload': {}}));+ }+ });+ }),+ );+ });++ tearDown(() async {+ await server.close(force: true);+ });++ Future<(WsConn, _RecordingPlugin, List<Map<String, dynamic>>, List<int>)>+ connect() async {+ final connected = Completer<void>();+ final events = <Map<String, dynamic>>[];+ final binaries = <int>[];+ late _RecordingPlugin plugin;+ final conn = WsConn(+ wsBaseUrl: 'ws://127.0.0.1:${server.port}',+ autonomousEnv: 'prod',+ machineId: 'machine-1',+ accessTokenProvider: (_, _) async => 'test-token',+ onAuthFailure: (_) {},+ relayCodecs: (_) async => _PassThroughCodec(),+ transportPlugins: (host, machineId) {+ expect(machineId, 'machine-1');+ return plugin = _RecordingPlugin(host);+ },+ onStatus: (status) {+ if (status == ConnectionStatus.connected && !connected.isCompleted) {+ connected.complete();+ }+ },+ onEvent: (event) => events.add(event),+ );+ conn.onBinaryFrame = (frame) async => binaries.add(frame.length);+ await conn.connect();+ await connected.future.timeout(const Duration(seconds: 2));+ await _settle();+ return (conn, plugin, events, binaries);+ }++ test(+ 'policy ack precedes the hello, readiness follows the welcome',+ () async {+ final (conn, plugin, _, _) = await connect();+ expect(plugin.calls, ['ack:true', 'ready']);+ final helloAt = received.indexWhere((f) => f['type'] == 'e2e_hello');+ expect(helloAt, greaterThan(0));+ await conn.close();+ },+ );++ test('signaling goes to the plugin and never to onEvent', () async {+ final (conn, plugin, events, _) = await connect();+ final socket = await socketReady.future;+ socket.add(+ jsonEncode({+ 'type': 'p2p_answer',+ 'payload': {'sessionId': 's'},+ }),+ );+ socket.add(+ jsonEncode({+ 'type': 'terminal_ready',+ 'payload': {'streamId': 'st', 'requestId': 'r'},+ }),+ );+ await _settle();+ expect(events.map((e) => e['type']), ['terminal_ready']);+ expect(plugin.calls.skip(2), [+ 'inbound:p2p_answer',+ 'observe:terminal_ready',+ ]);+ await conn.close();+ });++ test(+ 'terminal_open asks the plugin first and the answer rides the FIFO',+ () async {+ final (conn, plugin, _, _) = await connect();+ plugin.takeJson = true;+ expect(+ await conn.sendTerminalFrame('terminal_open', {'requestId': 'dsk_1'}),+ isTrue,+ );+ plugin.openReady = false;+ expect(+ await conn.sendTerminalFrame('terminal_open', {'requestId': 'dsk_2'}),+ isTrue,+ );+ await _settle();+ expect(plugin.calls.where((c) => c.startsWith('prepareOpen')), [+ 'prepareOpen:dsk_1',+ 'prepareOpen:dsk_2',+ ]);+ expect(plugin.sentJson.map((s) => s['openViaPlugin']), [true, false]);+ // The plugin took both: the socket saw neither.+ expect(received.where((f) => f['type'] == 'terminal_open'), isEmpty);++ plugin.takeJson = false;+ await conn.sendTerminalFrame('terminal_alive', {'streamId': 'st'});+ await _settle();+ expect(+ received.where((f) => f['type'] == 'terminal_alive'),+ hasLength(1),+ );+ await conn.close();+ },+ );++ test('the host sends on a forced wire through the same FIFO', () async {+ final (conn, plugin, _, _) = await connect();+ expect(+ await plugin.host.send({+ 'type': 'terminal_resync',+ 'payload': {'streamId': 'st'},+ }, force: TransportVia.ws),+ isTrue,+ );+ await _settle();+ expect(plugin.sentJson.single['force'], 'ws');+ expect(received.where((f) => f['type'] == 'terminal_resync'), hasLength(1));+ await conn.close();+ });++ test(+ 'binary is offered to the plugin outbound and observed inbound first',+ () async {+ final (conn, plugin, _, binaries) = await connect();+ plugin.takeBinary = true;+ expect(await conn.sendTerminalBinary(Uint8List(5)), isTrue);+ await _settle();+ expect(receivedBinary, isEmpty);+ plugin.takeBinary = false;+ expect(await conn.sendTerminalBinary(Uint8List(6)), isTrue);+ await _settle();+ expect(receivedBinary.single.length, 6);++ final socket = await socketReady.future;+ socket.add(Uint8List(7));+ await _settle();+ expect(binaries, [7]);+ expect(plugin.calls.last, 'observeBinary:7');+ await conn.close();+ },+ );++ test(+ 'the host delivers plugin traffic as if it were the socket\'s',+ () async {+ final (conn, plugin, events, binaries) = await connect();+ await plugin.host.dispatch({+ 'type': 'terminal_link_mode',+ 'payload': {'streamId': 'st', 'mode': 'p2p'},+ });+ await plugin.host.deliverBinary(Uint8List(3));+ expect(events.single['type'], 'terminal_link_mode');+ expect(binaries, [3]);+ await conn.close();+ },+ );++ test('closing disposes the plugin', () async {+ final (conn, plugin, _, _) = await connect();+ await conn.close();+ expect(plugin.disposed, isTrue);+ });+}diff --git a/mobile/android/app/src/main/AndroidManifest.xml b/mobile/android/app/src/main/AndroidManifest.xmlindex 87b9eeedb..0d189ce84 100644--- a/mobile/android/app/src/main/AndroidManifest.xml+++ b/mobile/android/app/src/main/AndroidManifest.xml@@ -1,4 +1,7 @@<manifest xmlns:android="http://schemas.android.com/apk/res/android">+ <!-- Lets libwebrtc notice a wifi↔cellular change and restart ICE rather than+ wait out the disconnect grace. Not a runtime permission. -->+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><applicationandroid:label="harness"android:name="${applicationName}"diff --git a/mobile/lib/main.dart b/mobile/lib/main.dartindex b4f383982..8777d2e18 100644--- a/mobile/lib/main.dart+++ b/mobile/lib/main.dart@@ -1,6 +1,7 @@import 'package:harness/app_shell.dart';import 'package:harness/core/asset_owner.dart';+import 'p2p/phone_terminal_p2p.dart';import 'phone/phone_shell.dart';/// Harness for iOS and Android: a viewer onto the machines this device has@@ -17,11 +18,16 @@ import 'phone/phone_shell.dart';/// itself (`kViewerMode`, and `viewer/` in `package:harness`). That is decided/// by the platform, not here — a Mac can run the same path with/// `--dart-define=HARNESS_VIEWER_MODE=true`.+///+/// It also brings its own second wire to each machine: the WebRTC data channel+/// the harness CLI opens on the desktop's behalf (`lib/p2p/`), so a terminal+/// rides p2p or TURN when it can and the relay only when it must.Future<void> main() {// `harness` is a dependency here rather than the root package, so Flutter// registers its assets under `packages/harness/…`. Set before the first frame.harnessAssetPackage = 'harness';return startHarness(authenticatedScreen: (app) => PhoneShell(notifier: app),+ transportPlugins: phoneTerminalP2p.create,);}diff --git a/mobile/lib/p2p/phone_terminal_p2p.dart b/mobile/lib/p2p/phone_terminal_p2p.dartnew file mode 100644index 000000000..1599235b2--- /dev/null+++ b/mobile/lib/p2p/phone_terminal_p2p.dart@@ -0,0 +1,8 @@+import 'terminal_p2p_plugin.dart';+import 'webrtc_terminal_p2p_link.dart';++/// The phone's one set of P2P terminal plugins — handed to `startHarness` by+/// `main()` and reached again by the shell when the app returns to the foreground.+final phoneTerminalP2p = TerminalP2pPlugins(+ links: const WebRtcTerminalP2pLinkFactory(),+);diff --git a/mobile/lib/p2p/terminal_p2p_link.dart b/mobile/lib/p2p/terminal_p2p_link.dartnew file mode 100644index 000000000..068028f1f--- /dev/null+++ b/mobile/lib/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/mobile/lib/p2p/terminal_p2p_plugin.dart b/mobile/lib/p2p/terminal_p2p_plugin.dartnew file mode 100644index 000000000..83426ba88--- /dev/null+++ b/mobile/lib/p2p/terminal_p2p_plugin.dart@@ -0,0 +1,834 @@+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 —+// worth periodically trying for a truly direct one. Never touches the live+// connection until a replacement has already proven itself.+const _upgradeMaxAttempts = 3;+const _upgradeRetryDelay = Duration(seconds: 60);+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;+ 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.+ void kickRetry() {+ final timer = _retryTimer;+ if (timer == null || _disposed) return;+ timer.cancel();+ _retryTimer = null;+ _log('retry kicked · app resumed');+ _link = null;+ _startP2p();+ }++ // ── 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) return;+ _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 {+ if (_disposed) return;+ // The ONE place every demotion converges, so none can fall through silently.+ _log('demoted · reason=$reason streams=${_p2pStreams.length}');+ _upgradeTimer?.cancel();+ _upgradeTimer = null;+ final shadow = _upgradeShadow;+ _upgradeShadow = null;+ if (shadow != null) unawaited(shadow.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;+ if (_upgradeAttempts >= _upgradeMaxAttempts) {+ _upgradeDone = true;+ return;+ }+ _upgradeTimer = Timer(_upgradeRetryDelay, () {+ _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;+ }+ _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 >= _upgradeMaxAttempts) {+ _upgradeDone = true;+ _log(+ 'upgrade giving up · staying on turn after $_upgradeAttempts attempts',+ );+ return;+ }+ _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);+ _upgradeDone = true; // either way, this connection is done trying+ if (acked) {+ 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.+ _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/mobile/lib/p2p/terminal_p2p_policy.dart b/mobile/lib/p2p/terminal_p2p_policy.dartnew file mode 100644index 000000000..ab0d4ee60--- /dev/null+++ b/mobile/lib/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/mobile/lib/p2p/webrtc_terminal_p2p_link.dart b/mobile/lib/p2p/webrtc_terminal_p2p_link.dartnew file mode 100644index 000000000..d8e155038--- /dev/null+++ b/mobile/lib/p2p/webrtc_terminal_p2p_link.dart@@ -0,0 +1,574 @@+import 'dart:async';+import 'dart:math';+import 'dart:typed_data';++import 'package:flutter/foundation.dart' show visibleForTesting;+import 'package:flutter_webrtc/flutter_webrtc.dart';+import 'package:harness/logging/app_log.dart';++import 'terminal_p2p_link.dart';+import 'terminal_p2p_policy.dart';++/// Diagnostic only, the phone's `TERMINAL_P2P_FORCE_RELAY`: drops host and srflx so+/// nothing but a TURN allocation can be nominated. `--dart-define=HARNESS_P2P_FORCE_RELAY=true`.+/// Unlike the CLI's flag it leaves an upgrade trial alone — a primary forced onto+/// TURN with a shadow free to go direct is how the cutover gets exercised at all.+const kForceP2pRelay = bool.fromEnvironment('HARNESS_P2P_FORCE_RELAY');++/// What this side advertises as `a=max-message-size`. libwebrtc'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 whole channel. The CLI sets+/// the same 512 KiB for werift↔werift.+const _maxMessageSize = 512 * 1024;++/// libwebrtc gathers in the background and only reports `complete` once every+/// server answered or timed out — with a dozen STUN/TURN urls that is routinely+/// the whole budget. The offer goes out early instead: once a server-reflexive+/// (or relay) candidate is in, plus a moment for the other interfaces to report,+/// and at the cap regardless. Whatever gathers after that trickles.+const _gatherCap = Duration(seconds: 3);+const _gatherSettleAfterReflexive = Duration(milliseconds: 500);++class WebRtcTerminalP2pLinkFactory implements TerminalP2pLinkFactory {+ const WebRtcTerminalP2pLinkFactory();++ @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,+ }) => WebRtcTerminalP2pLink(+ policy: policy,+ sendSignal: sendSignal,+ onData: onData,+ onState: onState,+ onUnavailable: onUnavailable,+ onStep: onStep,+ upgrade: upgrade,+ );+}++/// The offerer side of one `terminal-v1` data channel, on `flutter_webrtc`. A port+/// of the harness CLI's `TerminalP2pInitiator` (terminalP2p.ts); the responder on+/// the machine is unchanged and this speaks exactly what it expects.+///+/// Where the CLI races its STUN servers and picks one TURN url, this hands+/// libwebrtc the whole list — the race exists for werift's serial gather, and the+/// single url for its "first `turn:` entry only" limit; neither applies here.+class WebRtcTerminalP2pLink implements TerminalP2pLink {+ WebRtcTerminalP2pLink({+ 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 = _uuidV4();++ 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 gathered after the offer left. Held until the answer is in: the+ /// responder only adds a candidate to an entry that already has a remote+ /// description, and one arriving earlier is dropped or tears the session down.+ 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.state == RTCDataChannelState.RTCDataChannelOpen &&+ (channel.bufferedAmount ?? 0) < 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 turn = policy.turn;+ final config = <String, dynamic>{+ 'iceServers': [+ if (policy.stunUrls.isNotEmpty) {'urls': policy.stunUrls},+ if (turn != null)+ {+ 'urls': turn.urls,+ 'username': turn.username,+ 'credential': turn.credential,+ },+ ],+ 'sdpSemantics': 'unified-plan',+ // Left at 'all' deliberately, as the CLI does: host and srflx pairs win by+ // priority, and a TURN pair is nominated only once every direct one failed.+ if (kForceP2pRelay && !upgrade) 'iceTransportPolicy': 'relay',+ };+ final pc = await createPeerConnection(config);+ if (_finished) {+ await pc.dispose();+ return;+ }+ _pc = pc;+ _gathered = Completer<void>();+ _reflexive = Completer<void>();+ _wirePeer(pc);+ final channel = await pc.createDataChannel(+ terminalP2pChannel,+ RTCDataChannelInit()..ordered = true,+ );+ _channel = channel;+ _wireChannel(channel);+ await _createOffer(pc);+ } catch (error) {+ appLog.warn('p2p', 'peer connection setup failed', error: error);+ _fail('offer_failed');+ }+ }++ Future<void> _createOffer(RTCPeerConnection pc) async {+ final offer = await pc.createOffer({});+ final munged = _raiseMaxMessageSize(offer.sdp ?? '');+ await pc.setLocalDescription(RTCSessionDescription(munged, 'offer'));+ if (_pc != pc || _finished) return;+ _step('offer-created');+ // Gather-then-signal, like the CLI, but not to completion: the responder's+ // answer needs nothing more than what is in the SDP, and anything slower+ // trickles after it.+ 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 local = await pc.getLocalDescription();+ final sdp = local?.sdp;+ if (sdp == null || sdp.isEmpty) {+ throw StateError('local_description_missing');+ }+ _offeredSdp = sdp;+ 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(RTCSessionDescription(sdp, 'answer'));+ _flushLateCandidates();+ case 'p2p_ice_candidate':+ final candidate = payload['candidate'];+ if (candidate is Map) {+ final line = candidate['candidate'];+ if (line is String) {+ await pc.addCandidate(+ RTCIceCandidate(+ line,+ candidate['sdpMid'] as String?,+ (candidate['sdpMLineIndex'] as num?)?.toInt(),+ ),+ );+ }+ }+ case 'p2p_abort':+ final reason = payload['reason'];+ _fail(+ reason is String && reason.isNotEmpty ? reason : 'peer_aborted',+ );+ }+ } catch (error) {+ appLog.warn('p2p', 'signal $type failed', error: error);+ _fail('signal_invalid');+ }+ return true;+ }++ void _flushLateCandidates() {+ final pending = List<RTCIceCandidate>.from(_lateCandidates);+ _lateCandidates.clear();+ for (final candidate in pending) {+ _trickle(candidate);+ }+ }++ void _trickle(RTCIceCandidate candidate) {+ final line = candidate.candidate;+ if (line == null || line.isEmpty) return;+ sendSignal('p2p_ice_candidate', {+ 'sessionId': sessionId,+ 'protocolVersion': terminalP2pProtocolVersion,+ 'candidate': {+ 'candidate': line,+ 'sdpMid': candidate.sdpMid,+ 'sdpMLineIndex': candidate.sdpMLineIndex,+ },+ });+ }++ @override+ bool send(Object data) {+ final channel = _channel;+ if (!isReady || channel == null) return false;+ try {+ final message = data is String+ ? RTCDataChannelMessage(data)+ : RTCDataChannelMessage.fromBinary(asBytes(data));+ // The plugin's send is a Future; a rejection is a channel that stopped being+ // usable. Reported on a later turn so the caller's relay fallback for THIS+ // frame goes out before any resync a failure triggers — otherwise the+ // higher-counter resync would arrive first and read as a replay.+ unawaited(+ channel.send(message).catchError((Object error) {+ appLog.warn('p2p', 'data channel send failed', error: error);+ _fail('send_failed');+ }),+ );+ return true;+ } catch (_) {+ 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.state != RTCDataChannelState.RTCDataChannelOpen) {+ return false;+ }+ if (!await _waitForBufferedAmountLow(channel, drain)) return false;+ return send(data);+ }++ Future<bool> _waitForBufferedAmountLow(+ RTCDataChannel channel,+ Duration timeout,+ ) async {+ // The cached figure only moves on a native event; ask for the real one first.+ try {+ if (await channel.getBufferedAmount() < terminalP2pMaxBufferedBytes) {+ return true;+ }+ } catch (_) {+ return false;+ }+ final drained = _drained ??= Completer<void>();+ try {+ await drained.future.timeout(timeout);+ } catch (_) {+ return false;+ }+ return channel.state == RTCDataChannelState.RTCDataChannelOpen &&+ (channel.bufferedAmount ?? 0) < terminalP2pMaxBufferedBytes;+ }++ @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>>.from(_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);+ _drained?.complete();+ _drained = null;+ if (notifyPeer) {+ sendSignal('p2p_abort', {+ 'sessionId': sessionId,+ 'protocolVersion': terminalP2pProtocolVersion,+ 'reason': reason,+ });+ }+ final channel = _channel;+ final pc = _pc;+ _channel = null;+ _pc = null;+ try {+ await channel?.close();+ } catch (_) {+ /* already closed */+ }+ // dispose() alone: natively it IS close, and it cancels the Dart event+ // subscription first — a close() before it removes the native handler that+ // cancel then fails to reach, as an uncaught MissingPluginException.+ if (pc != null) {+ try {+ await pc.dispose();+ } catch (_) {+ /* best effort */+ }+ }+ onState?.call(TerminalP2pLinkState.closed, _elapsed, reason);+ }++ /// Why a negotiation went nowhere, in one line. `answer=no` is the case that+ /// matters: the peer never replied, so no candidate of ours was ever going to be+ /// tried — a peer problem, not a connectivity one.+ String get negotiationDetail =>+ 'answer=${_sawAnswer ? 'yes' : 'no'} ice=${_pc?.connectionState?.name ?? '-'}';++ void _wirePeer(RTCPeerConnection pc) {+ pc.onIceGatheringState = (state) {+ if (_pc != pc) return;+ if (state == RTCIceGatheringState.RTCIceGatheringStateComplete) {+ final gathered = _gathered;+ if (gathered != null && !gathered.isCompleted) gathered.complete();+ }+ };+ pc.onIceCandidate = (candidate) {+ if (_pc != pc || _finished) return;+ final line = candidate.candidate;+ if (line == null || line.isEmpty) return;+ if (RegExp(r'\btyp (srflx|relay)\b').hasMatch(line)) {+ final reflexive = _reflexive;+ if (reflexive != null && !reflexive.isCompleted) reflexive.complete();+ }+ // Everything gathered before the offer left is already inside its SDP.+ if (_offeredSdp.isEmpty || _offeredSdp.contains(line)) return;+ if (_sawAnswer) {+ _trickle(candidate);+ } else {+ _lateCandidates.add(candidate);+ }+ };+ pc.onConnectionState = (state) {+ if (_pc != pc || _finished) return;+ _step('ice-${state.name}');+ switch (state) {+ case RTCPeerConnectionState.RTCPeerConnectionStateFailed:+ _clearDisconnectGrace();+ _fail('peer_failed');+ case RTCPeerConnectionState.RTCPeerConnectionStateDisconnected:+ if (_disconnectGrace != null) return;+ _disconnectGrace = Timer(terminalP2pDisconnectGrace, () {+ _disconnectGrace = null;+ if (_pc == pc && !_finished) _fail('peer_disconnected_timeout');+ });+ default:+ // Back to connected (or connecting through an ICE restart): it healed.+ _clearDisconnectGrace();+ }+ };+ }++ void _wireChannel(RTCDataChannel channel) {+ channel.bufferedAmountLowThreshold = terminalP2pBufferedLowThreshold;+ channel.onBufferedAmountLow = (_) {+ final drained = _drained;+ _drained = null;+ if (drained != null && !drained.isCompleted) drained.complete();+ };+ channel.onDataChannelState = (state) {+ if (_channel != channel || _finished) return;+ switch (state) {+ case RTCDataChannelState.RTCDataChannelOpen:+ unawaited(_opened());+ case RTCDataChannelState.RTCDataChannelClosing:+ case RTCDataChannelState.RTCDataChannelClosed:+ if (_ready) _fail('channel_closed');+ case RTCDataChannelState.RTCDataChannelConnecting:+ break;+ }+ };+ channel.onMessage = (message) {+ if (_channel != channel || _finished) return;+ onData(message.isBinary ? message.binary : message.text);+ };+ }++ 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 {+ final reports = await pc.getStats();+ final byId = {for (final report in reports) report.id: report};+ StatsReport? pair;+ for (final report in reports) {+ if (report.type == 'transport') {+ final selected = report.values['selectedCandidatePairId'];+ if (selected is String && byId[selected] != null) {+ pair = byId[selected];+ break;+ }+ }+ }+ pair ??= reports.cast<StatsReport?>().firstWhere((report) {+ if (report!.type != 'candidate-pair') return false;+ final values = report.values;+ return values['nominated'] == true &&+ (values['state'] == 'succeeded' ||+ values['state'] == 'in-progress');+ }, orElse: () => null);+ if (pair == null) return null;+ String? typeOf(Object? id) {+ final candidate = id is String ? byId[id] : null;+ final type = candidate?.values['candidateType'];+ return type is String ? type : null;+ }++ return isRelayedPair(+ typeOf(pair.values['localCandidateId']),+ typeOf(pair.values['remoteCandidateId']),+ )+ ? TerminalP2pTransport.relay+ : TerminalP2pTransport.direct;+ } catch (error) {+ appLog.warn('p2p', 'getStats failed', error: error);+ return null;+ }+ }++ 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));+ }+}++/// `a=max-message-size` raised to what a keyframe needs — see [_maxMessageSize].+/// Added when libwebrtc left it out, since werift then assumes 64 KiB.+String _raiseMaxMessageSize(String sdp) {+ // Only the number is touched: libwebrtc's parser rejects a description whose+ // line endings do not all match, so the `\r\n` around it must stay put.+ final line = RegExp(r'^(a=max-message-size:)\d+', multiLine: true);+ if (line.hasMatch(sdp)) {+ return sdp.replaceAllMapped(line, (match) => '${match[1]}$_maxMessageSize');+ }+ final sctp = RegExp(r'^a=sctp-port:\d+(\r?\n)', multiLine: true);+ return sdp.replaceFirstMapped(+ sctp,+ (match) => '${match[0]}a=max-message-size:$_maxMessageSize${match[1]}',+ );+}++String _uuidV4() {+ final random = Random.secure();+ final bytes = Uint8List.fromList(+ List.generate(16, (_) => random.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)}';+}++@visibleForTesting+String raiseMaxMessageSizeForTest(String sdp) => _raiseMaxMessageSize(sdp);diff --git a/mobile/lib/phone/phone_shell.dart b/mobile/lib/phone/phone_shell.dartindex 57ce852e6..a57a5f69a 100644--- a/mobile/lib/phone/phone_shell.dart+++ b/mobile/lib/phone/phone_shell.dart@@ -1,6 +1,8 @@import 'package:flutter/material.dart';import 'package:harness/state/app_state.dart';++import '../p2p/phone_terminal_p2p.dart';import 'agent_index.dart';import 'agents_tab.dart';import 'machines_tab.dart';@@ -26,7 +28,7 @@ class PhoneShell extends StatefulWidget {State<PhoneShell> createState() => _PhoneShellState();}-class _PhoneShellState extends State<PhoneShell> {+class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {PhoneTab _tab = PhoneTab.agents;final _navigators = {@@ -38,14 +40,29 @@ class _PhoneShellState extends State<PhoneShell> {for (final tab in PhoneTab.values) tab: HeroController(),};+ @override+ void initState() {+ super.initState();+ WidgetsBinding.instance.addObserver(this);+ }+@overridevoid dispose() {+ WidgetsBinding.instance.removeObserver(this);for (final controller in _heroControllers.values) {controller.dispose();}super.dispose();}+ /// Back in the foreground: a p2p retry waiting out its delay fires now. Going to+ /// the background needs nothing — the OS suspends the socket, and its redial+ /// tears the old wire down and negotiates a fresh one.+ @override+ void didChangeAppLifecycleState(AppLifecycleState state) {+ if (state == AppLifecycleState.resumed) phoneTerminalP2p.kickRetry();+ }+NavigatorState? get _currentNavigator => _navigators[_tab]?.currentState;void _select(PhoneTab tab) {diff --git a/mobile/pubspec.lock b/mobile/pubspec.lockindex 8218464e7..9073e4783 100644--- a/mobile/pubspec.lock+++ b/mobile/pubspec.lock@@ -41,6 +41,14 @@ packages:url: "https://pub.dev"source: hostedversion: "1.1.3"+ code_assets:+ dependency: transitive+ description:+ name: code_assets+ sha256: bf394f466ba9205f1812a0433b392d6af280f155f56651eda7c18cc32ed493b8+ url: "https://pub.dev"+ source: hosted+ version: "1.2.1"collection:dependency: transitivedescription:@@ -89,6 +97,14 @@ packages:url: "https://pub.dev"source: hostedversion: "1.0.9"+ dart_webrtc:+ dependency: transitive+ description:+ name: dart_webrtc+ sha256: "078e3c431500147e5cc52b3c6ea41ed538f30c7720cc2467d2186c9251e62716"+ url: "https://pub.dev"+ source: hosted+ version: "1.8.2"dbus:dependency: transitivedescription:@@ -130,7 +146,7 @@ packages:source: hostedversion: "2.1.0"fake_async:- dependency: transitive+ dependency: "direct dev"description:name: fake_asyncsha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44"@@ -248,6 +264,14 @@ packages:description: fluttersource: sdkversion: "0.0.0"+ flutter_webrtc:+ dependency: "direct main"+ description:+ name: flutter_webrtc+ sha256: "381e05c120caf2f1ee1accd806baad22b33802f36c74d8ea5e43a5800ce6380c"+ url: "https://pub.dev"+ source: hosted+ version: "1.6.2+hotfix.1"go_router:dependency: transitivedescription:@@ -263,6 +287,14 @@ packages:relative: truesource: pathversion: "1.0.0+1"+ hooks:+ dependency: transitive+ description:+ name: hooks+ sha256: "9a62a50b50b769a737bc0a8ff381f333529df3ab746b2f6b02e83760231455ba"+ url: "https://pub.dev"+ source: hosted+ version: "2.0.2"http:dependency: transitivedescription:@@ -279,6 +311,30 @@ packages:url: "https://pub.dev"source: hostedversion: "4.1.2"+ jni:+ dependency: transitive+ description:+ name: jni+ sha256: f038e58b4dc2c9037f50e233175086337e0b305e356d28211bf55f21c504cbd3+ url: "https://pub.dev"+ source: hosted+ version: "1.0.3"+ jni_flutter:+ dependency: transitive+ description:+ name: jni_flutter+ sha256: b2310cdd4c18c65c081ab141a41efa94aa26c65431803703ece51996f174f351+ url: "https://pub.dev"+ source: hosted+ version: "1.0.3"+ jni_util:+ dependency: transitive+ description:+ name: jni_util+ sha256: "1ba86da04a5f2bf18fde2edb235587e70c5b0fc5bd4ba955f46b00942c3fc35f"+ url: "https://pub.dev"+ source: hosted+ version: "1.0.0"json_annotation:dependency: transitivedescription:@@ -319,6 +375,14 @@ packages:url: "https://pub.dev"source: hostedversion: "6.1.0"+ logger:+ dependency: transitive+ description:+ name: logger+ sha256: "2a0dc097e7b01d942475bdd552356db2d0f768b05540bd4b2b53f1840f2239a7"+ url: "https://pub.dev"+ source: hosted+ version: "2.8.0"logging:dependency: transitivedescription:@@ -367,6 +431,22 @@ packages:url: "https://pub.dev"source: hostedversion: "2.1.0"+ objective_c:+ dependency: transitive+ description:+ name: objective_c+ sha256: b7fb95a6d9a4f009edd63dc5ac69f07420b23a16161c6dd8660290b59c602e8e+ url: "https://pub.dev"+ source: hosted+ version: "9.5.0"+ package_config:+ dependency: transitive+ description:+ name: package_config+ sha256: ffcf4cf3d6c0b74ac43708d9f56625506e8a68aa935abe9d267a7330f320eb5d+ url: "https://pub.dev"+ source: hosted+ version: "3.0.0"package_info_plus:dependency: transitivedescription:@@ -391,6 +471,54 @@ packages:url: "https://pub.dev"source: hostedversion: "1.9.1"+ path_provider:+ dependency: transitive+ description:+ name: path_provider+ sha256: a7f4874f987173da295a61c181b8ee71dab59b332a486b391babf26a1b884825+ url: "https://pub.dev"+ source: hosted+ version: "2.1.6"+ path_provider_android:+ dependency: transitive+ description:+ name: path_provider_android+ sha256: "69cbd515a62b94d32a7944f086b2f82b4ac40a1d45bebfc00813a430ab2dabcd"+ url: "https://pub.dev"+ source: hosted+ version: "2.3.1"+ path_provider_foundation:+ dependency: transitive+ description:+ name: path_provider_foundation+ sha256: "2a376b7d6392d80cd3705782d2caa734ca4727776db0b6ec36ef3f1855197699"+ url: "https://pub.dev"+ source: hosted+ version: "2.6.0"+ path_provider_linux:+ dependency: transitive+ description:+ name: path_provider_linux+ sha256: "58c2005f147315b11e9b4a7bc889cd5203e250cba8e3f012dae259b4972b5c16"+ url: "https://pub.dev"+ source: hosted+ version: "2.2.2"+ path_provider_platform_interface:+ dependency: transitive+ description:+ name: path_provider_platform_interface+ sha256: "484838772624c3a4b94f1e44a3e19897fee738f2d5c4ce448443b0417f7c9dda"+ url: "https://pub.dev"+ source: hosted+ version: "2.1.3"+ path_provider_windows:+ dependency: transitive+ description:+ name: path_provider_windows+ sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7+ url: "https://pub.dev"+ source: hosted+ version: "2.3.0"petitparser:dependency: transitivedescription:@@ -399,6 +527,14 @@ packages:url: "https://pub.dev"source: hostedversion: "7.0.2"+ platform:+ dependency: transitive+ description:+ name: platform+ sha256: a36d119c13416516a7b5913fbe8af8531e11633d784c550b2125f76c758524ec+ url: "https://pub.dev"+ source: hosted+ version: "3.2.0"plugin_platform_interface:dependency: transitivedescription:@@ -407,6 +543,14 @@ packages:url: "https://pub.dev"source: hostedversion: "2.1.8"+ pub_semver:+ dependency: transitive+ description:+ name: pub_semver+ sha256: "261236774e8b1d69cfc6b9eabbc96c40f25e7a2d6b171f3385d4f65d5734fb24"+ url: "https://pub.dev"+ source: hosted+ version: "2.2.1"quiver:dependency: transitivedescription:@@ -415,6 +559,14 @@ packages:url: "https://pub.dev"source: hostedversion: "3.2.2"+ record_use:+ dependency: transitive+ description:+ name: record_use+ sha256: "2551bd8eecfe95d14ae75f6021ad0248be5c27f138c2ec12fcb52b500b3ba1ed"+ url: "https://pub.dev"+ source: hosted+ version: "0.6.0"riverpod:dependency: transitivedescription:@@ -516,6 +668,14 @@ packages:url: "https://pub.dev"source: hostedversion: "1.4.1"+ synchronized:+ dependency: transitive+ description:+ name: synchronized+ sha256: "397b146f97613b83d84bdccb439bc8d0f3aebb6c1d14a9641e6f24201c490b2d"+ url: "https://pub.dev"+ source: hosted+ version: "3.4.2"term_glyph:dependency: transitivedescription:@@ -660,6 +820,14 @@ packages:url: "https://pub.dev"source: hostedversion: "3.0.3"+ webrtc_interface:+ dependency: transitive+ description:+ name: webrtc_interface+ sha256: c6f100eac5057d9a817a60473126f9828c796d42884d498af4f339c97b21014f+ url: "https://pub.dev"+ source: hosted+ version: "1.5.1"win32:dependency: transitivedescription:@@ -676,6 +844,14 @@ packages:url: "https://pub.dev"source: hostedversion: "0.5.2"+ xdg_directories:+ dependency: transitive+ description:+ name: xdg_directories+ sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15"+ url: "https://pub.dev"+ source: hosted+ version: "1.1.0"xml:dependency: transitivedescription:@@ -691,6 +867,14 @@ packages:relative: truesource: pathversion: "4.0.0"+ yaml:+ dependency: transitive+ description:+ name: yaml+ sha256: f67cdd8e07d3c6329146aaef1ba043542b3134c12489f553ca9a7435d1068aea+ url: "https://pub.dev"+ source: hosted+ version: "3.1.4"zmodem:dependency: transitivedescription:diff --git a/mobile/pubspec.yaml b/mobile/pubspec.yamlindex 08c6941bb..c93fd1a43 100644--- a/mobile/pubspec.yaml+++ b/mobile/pubspec.yaml@@ -26,10 +26,20 @@ dependencies:flutter_riverpod: ^2.6.1lucide_icons_flutter: ^3.1.15+ # The phone's second wire to a machine: the `terminal-v1` data channel the+ # harness CLI opens with werift on the desktop's behalf (lib/p2p/). Data+ # channels only — no camera or microphone, so no usage strings are needed.+ # Pinned exactly: a native plugin, and libwebrtc's SCTP/SDP behaviour is+ # what the responder's werift has to agree with.+ flutter_webrtc: 1.6.2+hotfix.1+dev_dependencies:flutter_test:sdk: flutterflutter_lints: ^6.0.0+ # The p2p routing is all timers (retry, migration sweep, upgrade) — tests drive+ # them without waiting them out.+ fake_async: ^1.3.1flutter:uses-material-design: truediff --git a/mobile/test/p2p/fakes.dart b/mobile/test/p2p/fakes.dartnew file mode 100644index 000000000..1b98e9647--- /dev/null+++ b/mobile/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_mobile/p2p/terminal_p2p_link.dart';+import 'package:harness_mobile/p2p/terminal_p2p_plugin.dart';+import 'package:harness_mobile/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/mobile/test/p2p/sdp_munge_test.dart b/mobile/test/p2p/sdp_munge_test.dartnew file mode 100644index 000000000..a28ceae2f--- /dev/null+++ b/mobile/test/p2p/sdp_munge_test.dart@@ -0,0 +1,23 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/p2p/webrtc_terminal_p2p_link.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(+ raiseMaxMessageSizeForTest(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 libwebrtc left it out', () {+ const sdp = 'v=0\r\na=sctp-port:5000\r\na=mid:0\r\n';+ expect(+ raiseMaxMessageSizeForTest(sdp),+ 'v=0\r\na=sctp-port:5000\r\na=max-message-size:524288\r\na=mid:0\r\n',+ );+ });+}diff --git a/mobile/test/p2p/terminal_p2p_plugin_test.dart b/mobile/test/p2p/terminal_p2p_plugin_test.dartnew file mode 100644index 000000000..2b0384910--- /dev/null+++ b/mobile/test/p2p/terminal_p2p_plugin_test.dart@@ -0,0 +1,547 @@+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_mobile/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 tries then done',+ () {+ 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: 'gave up');+ expect(b.links.first.stopped, isFalse);+ 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);+ b.plugin.dispose();+ expect(primary.stopped, isTrue);+ 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/mobile/test/p2p/terminal_p2p_policy_test.dart b/mobile/test/p2p/terminal_p2p_policy_test.dartnew file mode 100644index 000000000..64d3f88e4--- /dev/null+++ b/mobile/test/p2p/terminal_p2p_policy_test.dart@@ -0,0 +1,100 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/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',+ });+ });+}