Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
feat(mobile): Redesign UI with state-driven UX, OIDC integration, Device Flow, QR codes, and mesh stats polling
Antonio Ojeaa175f4bc0257
diff --git a/mobile/sam-node-app/android/app/src/main/AndroidManifest.xml b/mobile/sam-node-app/android/app/src/main/AndroidManifest.xmlindex 4e6e2cfc..f0f15198 100644--- a/mobile/sam-node-app/android/app/src/main/AndroidManifest.xml+++ b/mobile/sam-node-app/android/app/src/main/AndroidManifest.xml@@ -1,4 +1,5 @@<manifest xmlns:android="http://schemas.android.com/apk/res/android">+ <uses-permission android:name="android.permission.INTERNET"/><applicationandroid:label="sam_agent"android:name="${applicationName}"@@ -37,6 +38,14 @@In particular, this is used by the Flutter engine in io.flutter.plugin.text.ProcessTextPlugin. --><queries>+ <intent>+ <action android:name="android.intent.action.VIEW" />+ <data android:scheme="http" />+ </intent>+ <intent>+ <action android:name="android.intent.action.VIEW" />+ <data android:scheme="https" />+ </intent><intent><action android:name="android.intent.action.PROCESS_TEXT"/><data android:mimeType="text/plain"/>diff --git a/mobile/sam-node-app/lib/main.dart b/mobile/sam-node-app/lib/main.dartindex 7f1f7d8d..a421e7d3 100644--- a/mobile/sam-node-app/lib/main.dart+++ b/mobile/sam-node-app/lib/main.dart@@ -1,5 +1,13 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';+import 'dart:math';import 'package:flutter/material.dart';import 'package:path_provider/path_provider.dart';+import 'package:url_launcher/url_launcher.dart';+import 'package:http/http.dart' as http;+import 'package:crypto/crypto.dart';+import 'package:qr_flutter/qr_flutter.dart';import 'sam_ffi.dart';void main() {@@ -35,14 +43,465 @@ class _NodeControlPageState extends State<NodeControlPage> {final _tokenController = TextEditingController(text: 'secret-token');late SamNodeLib _samLib;+ bool? _isEnrolled; // null = checking, false = show enrollment, true = show dashboardbool _running = false;String _status = 'Disconnected';String _nodeID = '';+ int _connectedPeers = 0;+ int _dhtSize = 0;+ bool _loggingIn = false;+ bool _devicePollingActive = false;+ Timer? _pollingTimer;@overridevoid initState() {super.initState();_samLib = SamNodeLib();+ _checkEnrollment();+ }++ @override+ void dispose() {+ _pollingTimer?.cancel();+ _hubController.dispose();+ _jwtController.dispose();+ _tokenController.dispose();+ super.dispose();+ }++ Future<void> _checkEnrollment() async {+ final appDir = await getApplicationDocumentsDirectory();+ final dataDir = '${appDir.path}/sam_data';+ final enrolled = _samLib.isEnrolled(dataDir);+ setState(() {+ _isEnrolled = enrolled;+ if (enrolled) {+ _status = 'Enrolled';+ // Try to get node ID if running (though might not be started yet)+ _nodeID = _samLib.getNodeID() ?? '';+ }+ });+ }++ String _generateCodeVerifier() {+ final random = Random.secure();+ final values = List<int>.generate(32, (i) => random.nextInt(256));+ return base64UrlEncode(values).replaceAll('=', '');+ }++ String _generateCodeChallenge(String verifier) {+ final bytes = utf8.encode(verifier);+ final digest = sha256.convert(bytes);+ return base64UrlEncode(digest.bytes).replaceAll('=', '');+ }++ Future<void> _loginAndEnroll() async {+ print('DEBUG: _loginAndEnroll started');+ setState(() {+ _loggingIn = true;+ _status = 'Fetching hub info...';+ });++ HttpServer? server;++ try {+ final hubUrl = _hubController.text.trim();+ print('DEBUG: Fetching hub info from $hubUrl');+ final infoJson = _samLib.fetchHubInfoJSON(hubUrl);+ print('DEBUG: Hub info JSON: $infoJson');+ if (infoJson == null) {+ throw Exception('Failed to fetch hub info');+ }++ final info = jsonDecode(infoJson);+ if (info['error'] != null) {+ throw Exception('Hub info error: ${info['error']}');+ }++ final issuer = info['oidcIssuer'];+ final clientId = info['clientId'];+ final audience = info['audience'];++ print('DEBUG: Issuer: $issuer, ClientId: $clientId, Audience: $audience');++ if (issuer == null || clientId == null) {+ throw Exception('Incomplete hub info received');+ }++ setState(() {+ _status = 'Discovering OIDC endpoints...';+ });++ // Simple OIDC discovery+ final discoveryUrl = '$issuer/.well-known/openid-configuration';+ print('DEBUG: Fetching OIDC config from $discoveryUrl');+ final discResponse = await http.get(Uri.parse(discoveryUrl));+ print('DEBUG: OIDC config response status: ${discResponse.statusCode}');+ if (discResponse.statusCode != 200) {+ throw Exception('Failed to discover OIDC endpoints');+ }+ final discData = jsonDecode(discResponse.body);+ final authUrl = discData['authorization_endpoint'];+ final tokenUrl = discData['token_endpoint'];++ print('DEBUG: AuthURL: $authUrl, TokenURL: $tokenUrl');++ if (authUrl == null || tokenUrl == null) {+ throw Exception('Missing endpoints in OIDC discovery');+ }++ // Start local server to capture callback+ int? selectedPort;+ for (final port in [13000, 13001, 13002]) {+ try {+ server = await HttpServer.bind(InternetAddress.anyIPv4, port);+ selectedPort = port;+ print('DEBUG: Bound local server to port $port (any IPv4)');+ break;+ } catch (e) {+ print('DEBUG: Failed to bind to port $port: $e');+ }+ }++ if (server == null || selectedPort == null) {+ throw Exception('Could not bind local callback listener (ports 13000-13002 busy)');+ }++ final verifier = _generateCodeVerifier();+ final challenge = _generateCodeChallenge(verifier);+ final state = base64UrlEncode(List<int>.generate(16, (_) => Random.secure().nextInt(256))).replaceAll('=', '');+ final redirectUri = 'http://127.0.0.1:$selectedPort/callback';++ final queryParams = {+ 'response_type': 'code',+ 'client_id': clientId,+ 'redirect_uri': redirectUri,+ 'scope': 'openid email profile',+ 'state': state,+ 'code_challenge': challenge,+ 'code_challenge_method': 'S256',+ };+ if (audience != null && audience.isNotEmpty) {+ queryParams['audience'] = audience;+ }++ final uri = Uri.parse(authUrl).replace(queryParameters: queryParams);++ print('OIDC Login URL: $uri');+ print('Expecting callback on: $redirectUri');++ setState(() {+ _status = 'Opening browser for login...';+ });++ if (!await launchUrl(uri, mode: LaunchMode.platformDefault)) {+ throw Exception('Could not launch login URL');+ }++ print('Waiting for callback on local server...');++ String? code;+ String? receivedState;++ await for (final request in server) {+ print('DEBUG: Received request: ${request.requestedUri}');++ if (request.requestedUri.path == '/callback') {+ final query = request.requestedUri.queryParameters;+ receivedState = query['state'];+ code = query['code'];++ print('DEBUG: Callback state: $receivedState, code: $code');++ if (receivedState != state) {+ print('DEBUG: State mismatch. Expected $state, got $receivedState');+ request.response.statusCode = 400;+ request.response.write('Invalid state parameter');+ await request.response.close();+ break;+ }++ if (code == null) {+ print('DEBUG: No code in callback');+ request.response.statusCode = 400;+ request.response.write('No code received');+ await request.response.close();+ break;+ }++ request.response.headers.contentType = ContentType.html;+ request.response.write('<html><body><h1>Authorization successful!</h1><p>You can close this window and return to the app.</p></body></html>');+ await request.response.close();+ print('DEBUG: Callback handled successfully');+ break; // Success+ } else {+ print('DEBUG: Ignoring non-callback request: ${request.requestedUri.path}');+ request.response.statusCode = 404;+ await request.response.close();+ }+ }++ await server.close();++ if (receivedState != state) {+ throw Exception('Invalid state parameter received');+ }++ if (code == null) {+ throw Exception('No code received');+ }+++ setState(() {+ _status = 'Exchanging code for token...';+ });++ final tokenResponse = await http.post(+ Uri.parse(tokenUrl),+ headers: {'Content-Type': 'application/x-www-form-urlencoded'},+ body: {+ 'grant_type': 'authorization_code',+ 'client_id': clientId,+ 'code': code,+ 'redirect_uri': redirectUri,+ 'code_verifier': verifier,+ },+ );++ if (tokenResponse.statusCode != 200) {+ throw Exception('Token exchange failed: ${tokenResponse.body}');+ }++ final tokenData = jsonDecode(tokenResponse.body);+ final jwt = tokenData['id_token'] ?? tokenData['access_token'];++ if (jwt == null) {+ throw Exception('No token received');+ }++ setState(() {+ _jwtController.text = jwt;+ _status = 'Token obtained! Enrolling...';+ });++ await _enroll();++ } catch (e) {+ setState(() {+ _status = 'Login/Enrollment failed: $e';+ });+ } finally {+ await server?.close();+ setState(() {+ _loggingIn = false;+ });+ }+ }++ Future<void> _startDeviceLogin() async {+ setState(() {+ _loggingIn = true;+ _status = 'Fetching hub info for device login...';+ });++ try {+ final hubUrl = _hubController.text.trim();+ print('DEBUG: Device Login: Fetching hub info from $hubUrl');+ final infoJson = _samLib.fetchHubInfoJSON(hubUrl);+ if (infoJson == null) throw Exception('Failed to fetch hub info');++ final info = jsonDecode(infoJson);+ if (info['error'] != null) throw Exception('Hub info error: ${info['error']}');++ final issuer = info['oidcIssuer'];+ final clientId = info['clientId'];+ final audience = info['audience'];++ if (issuer == null || clientId == null) {+ throw Exception('Incomplete hub info received');+ }++ // OIDC discovery+ final discoveryUrl = '$issuer/.well-known/openid-configuration';+ final discResponse = await http.get(Uri.parse(discoveryUrl));+ if (discResponse.statusCode != 200) throw Exception('Failed to discover OIDC endpoints');++ final discData = jsonDecode(discResponse.body);+ final deviceAuthUrl = discData['device_authorization_endpoint'];+ final tokenUrl = discData['token_endpoint'];++ if (deviceAuthUrl == null) {+ throw Exception('Device Authorization not supported by Issuer');+ }++ print('DEBUG: Device Auth Endpoint: $deviceAuthUrl');++ // 1. Request Device Code+ final deviceCodeResp = await http.post(+ Uri.parse(deviceAuthUrl),+ headers: {'Content-Type': 'application/x-www-form-urlencoded'},+ body: {+ 'client_id': clientId,+ 'scope': 'openid email profile',+ if (audience != null && audience.isNotEmpty) 'audience': audience,+ },+ );++ if (deviceCodeResp.statusCode != 200) {+ throw Exception('Failed to get device code: ${deviceCodeResp.body}');+ }++ final deviceData = jsonDecode(deviceCodeResp.body);+ final deviceCode = deviceData['device_code'];+ final userCode = deviceData['user_code'];+ final verificationUri = deviceData['verification_uri_complete'] ?? deviceData['verification_uri'];+ int interval = deviceData['interval'] ?? 5; // seconds++ print('DEBUG: User Code: $userCode');+ print('DEBUG: Verification URI: $verificationUri');++ // 2. Show UI+ _devicePollingActive = true;+ _showDeviceCodeDialog(userCode, verificationUri);++ // 3. Start Polling+ _pollForDeviceToken(tokenUrl, clientId, deviceCode, interval);++ } catch (e) {+ setState(() {+ _status = 'Device Login failed: $e';+ _loggingIn = false;+ });+ }+ }++ Future<void> _pollForDeviceToken(String tokenUrl, String clientId, String deviceCode, int interval) async {+ print('DEBUG: Starting device token polling...');+ bool polling = true;+ while (polling && _devicePollingActive) {+ await Future.delayed(Duration(seconds: interval));++ if (!_devicePollingActive) break;++ try {+ final response = await http.post(+ Uri.parse(tokenUrl),+ headers: {'Content-Type': 'application/x-www-form-urlencoded'},+ body: {+ 'grant_type': 'urn:ietf:params:oauth:grant-type:device_code',+ 'device_code': deviceCode,+ 'client_id': clientId,+ },+ );++ if (response.statusCode == 200) {+ final data = jsonDecode(response.body);+ final jwt = data['id_token'] ?? data['access_token'];+ if (jwt != null) {+ setState(() {+ _jwtController.text = jwt;+ _status = 'Token obtained via Device Flow! Enrolling...';+ });+ await _enroll();+ polling = false;+ _devicePollingActive = false;+ if (mounted && Navigator.canPop(context)) {+ Navigator.pop(context);+ }+ }+ } else {+ final errorData = jsonDecode(response.body);+ final error = errorData['error'];++ if (error == 'authorization_pending') {+ print('DEBUG: Authorization pending...');+ } else if (error == 'slow_down') {+ print('DEBUG: Slow down requested');+ interval += 5; // Slow down+ } else {+ throw Exception('Device login error: $error');+ }+ }+ } catch (e) {+ print('DEBUG: Polling error: $e');+ setState(() {+ _status = 'Polling failed: $e';+ });+ polling = false;+ _devicePollingActive = false;+ if (mounted && Navigator.canPop(context)) {+ Navigator.pop(context);+ }+ }+ }++ setState(() {+ _loggingIn = false;+ });+ }++ void _showDeviceCodeDialog(String userCode, String verificationUri) {+ showDialog(+ context: context,+ barrierDismissible: false,+ builder: (BuildContext context) {+ return AlertDialog(+ title: const Text('Device Login'),+ content: SingleChildScrollView(+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ const Text('Scan this QR code or visit the URL below:'),+ const SizedBox(height: 10),+ SizedBox(+ width: 200,+ height: 200,+ child: QrImageView(+ data: verificationUri,+ version: QrVersions.auto,+ backgroundColor: Colors.white,+ ),+ ),+ const SizedBox(height: 20),+ SelectableText(+ verificationUri,+ style: const TextStyle(fontWeight: FontWeight.bold, color: Colors.blue),+ textAlign: TextAlign.center,+ ),+ const SizedBox(height: 20),+ const Text('And enter this code:'),+ SelectableText(+ userCode,+ style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold, letterSpacing: 2),+ ),+ ],+ ),+ ),+ actions: [+ TextButton(+ onPressed: () async {+ final uri = Uri.parse(verificationUri);+ if (await canLaunchUrl(uri)) {+ await launchUrl(uri, mode: LaunchMode.externalApplication);+ }+ },+ child: const Text('Open Browser (This Device)'),+ ),+ TextButton(+ onPressed: () {+ _devicePollingActive = false;+ Navigator.of(context).pop();+ setState(() {+ _loggingIn = false;+ _status = 'Device login cancelled by user';+ });+ },+ child: const Text('Cancel'),+ ),+ ],+ );+ },+ );}Future<void> _enroll() async {@@ -59,9 +518,42 @@ class _NodeControlPageState extends State<NodeControlPage> {if (err != null) {_status = 'Enrollment failed: $err';} else {- _status = 'Enrollment successful! You can now start the node.';+ _status = 'Enrollment successful!';+ _isEnrolled = true; // Switch to Dashboard+ }+ });+ }++ void _startPolling() {+ _pollingTimer?.cancel();+ _pollingTimer = Timer.periodic(const Duration(seconds: 3), (timer) {+ if (!_running) {+ timer.cancel();+ return;}+ _updateMeshInfo();});+ _updateMeshInfo(); // Run once immediately+ }++ void _updateMeshInfo() {+ final infoJson = _samLib.getMeshInfo();+ if (infoJson != null) {+ try {+ final info = jsonDecode(infoJson);+ if (info['error'] == null) {+ setState(() {+ _connectedPeers = info['connected_peers'] ?? 0;+ _dhtSize = info['dht_size'] ?? 0;+ if (info['node_id'] != null) {+ _nodeID = info['node_id'];+ }+ });+ }+ } catch (e) {+ print('DEBUG: Error parsing mesh info: $e');+ }+ }}Future<void> _start() async {@@ -90,9 +582,11 @@ class _NodeControlPageState extends State<NodeControlPage> {_status = 'Running';_nodeID = _samLib.getNodeID() ?? 'unknown';});+ _startPolling();}void _stop() {+ _pollingTimer?.cancel();final err = _samLib.stop();setState(() {if (err != null) {@@ -100,72 +594,270 @@ class _NodeControlPageState extends State<NodeControlPage> {} else {_running = false;_status = 'Stopped';- _nodeID = '';+ _connectedPeers = 0;+ _dhtSize = 0;}});}+ Future<void> _unenroll() async {+ final confirm = await showDialog<bool>(+ context: context,+ builder: (context) => AlertDialog(+ title: const Text('Unenroll Node'),+ content: const Text('Are you sure you want to unenroll? This will delete your local identity and disconnect you from the mesh.'),+ actions: [+ TextButton(onPressed: () => Navigator.pop(context, false), child: const Text('Cancel')),+ TextButton(+ onPressed: () => Navigator.pop(context, true),+ child: const Text('Unenroll', style: TextStyle(color: Colors.red)),+ ),+ ],+ ),+ );++ if (confirm == true) {+ if (_running) {+ _stop();+ }+ final appDir = await getApplicationDocumentsDirectory();+ final dataDir = '${appDir.path}/sam_data';+ try {+ final dir = Directory(dataDir);+ if (await dir.exists()) {+ await dir.delete(recursive: true);+ }+ setState(() {+ _isEnrolled = false;+ _status = 'Unenrolled';+ _nodeID = '';+ });+ } catch (e) {+ setState(() {+ _status = 'Failed to unenroll: $e';+ });+ }+ }+ }+@overrideWidget build(BuildContext context) {return Scaffold(appBar: AppBar(title: const Text('SAM Node Mobile')),- body: SingleChildScrollView(- padding: const EdgeInsets.all(16.0),- child: Column(- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- TextField(- controller: _hubController,- decoration: const InputDecoration(labelText: 'Hub URL / Address'),+ body: _buildBody(),+ );+ }++ Widget _buildBody() {+ if (_isEnrolled == null) {+ return const Center(child: CircularProgressIndicator());+ }+ if (_isEnrolled == false) {+ return _buildEnrollmentView();+ }+ return _buildDashboardView();+ }++ Widget _buildEnrollmentView() {+ return SingleChildScrollView(+ padding: const EdgeInsets.all(16.0),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ const Text('Welcome to SAM', style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold), textAlign: TextAlign.center),+ const SizedBox(height: 20),+ const Text('Please enroll your node to join the mesh.', textAlign: TextAlign.center),+ const SizedBox(height: 30),+ TextField(+ controller: _hubController,+ decoration: const InputDecoration(+ labelText: 'Hub URL',+ border: OutlineInputBorder(),+ hintText: 'https://bananas.sam-mesh.dev',),- TextField(- controller: _jwtController,- decoration: const InputDecoration(labelText: 'Enrollment JWT'),+ ),+ const SizedBox(height: 20),+ ElevatedButton.icon(+ onPressed: _loggingIn ? null : _loginAndEnroll,+ icon: _loggingIn+ ? const SizedBox(height: 20, width: 20, child: CircularProgressIndicator(strokeWidth: 2))+ : const Icon(Icons.login),+ label: const Text('Login & Enroll (Browser)'),+ style: ElevatedButton.styleFrom(padding: const EdgeInsets.symmetric(vertical: 16)),+ ),+ const SizedBox(height: 10),+ ElevatedButton.icon(+ onPressed: _loggingIn ? null : _startDeviceLogin,+ icon: const Icon(Icons.tv),+ label: const Text('Device Login (TV / Other Device)'),+ style: ElevatedButton.styleFrom(padding: const EdgeInsets.symmetric(vertical: 16)),+ ),+ const SizedBox(height: 30),+ if (_status.isNotEmpty && _status != 'Enrolled' && _status != 'Unenrolled')+ Card(+ color: Colors.grey.shade100,+ child: Padding(+ padding: const EdgeInsets.all(16.0),+ child: Text('Status: $_status', style: const TextStyle(fontStyle: FontStyle.italic)),+ ),),- TextField(- controller: _tokenController,- decoration: const InputDecoration(labelText: 'Local API Token'),+ ],+ ),+ );+ }++ Widget _buildDashboardView() {+ final bool isRunning = _running;+ final Color statusColor = isRunning ? Colors.green : Colors.grey;++ return SingleChildScrollView(+ padding: const EdgeInsets.all(16.0),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ // Status Card+ Card(+ elevation: 4,+ child: Padding(+ padding: const EdgeInsets.all(20.0),+ child: Column(+ children: [+ Row(+ mainAxisAlignment: MainAxisAlignment.center,+ children: [+ Container(+ width: 16,+ height: 16,+ decoration: BoxDecoration(+ color: statusColor,+ shape: BoxShape.circle,+ boxShadow: [+ if (isRunning)+ BoxShadow(+ color: Colors.green.withOpacity(0.5),+ spreadRadius: 4,+ blurRadius: 4,+ )+ ],+ ),+ ),+ const SizedBox(width: 10),+ Text(+ isRunning ? 'Node is Running' : 'Node is Stopped',+ style: TextStyle(+ fontSize: 20,+ fontWeight: FontWeight.bold,+ color: isRunning ? Colors.green.shade700 : Colors.grey.shade700,+ ),+ ),+ ],+ ),+ const SizedBox(height: 10),+ Text('Mesh: public-mesh', style: TextStyle(color: Colors.grey.shade600)),+ ],+ ),),- const SizedBox(height: 20),- ElevatedButton(- onPressed: _enroll,- child: const Text('Enroll Node'),+ ),+ const SizedBox(height: 20),++ // Stats Grid+ Row(+ children: [+ Expanded(+ child: _buildStatCard(+ icon: Icons.people,+ title: 'Connected Peers',+ value: '$_connectedPeers',+ color: Colors.blue,+ ),+ ),+ const SizedBox(width: 16),+ Expanded(+ child: _buildStatCard(+ icon: Icons.storage,+ title: 'DHT Size',+ value: '$_dhtSize',+ color: Colors.purple,+ ),+ ),+ ],+ ),+ const SizedBox(height: 20),++ // Node Info+ Card(+ child: Padding(+ padding: const EdgeInsets.all(16.0),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ const Text('Node ID', style: TextStyle(fontWeight: FontWeight.bold)),+ const SizedBox(height: 4),+ SelectableText(+ _nodeID.isEmpty ? 'Unknown (Start node to see ID)' : _nodeID,+ style: const TextStyle(fontFamily: 'monospace', fontSize: 12),+ ),+ ],+ ),),- const SizedBox(height: 10),- Row(- children: [- Expanded(- child: ElevatedButton(- onPressed: _running ? null : _start,- child: const Text('Start Node'),+ ),+ const SizedBox(height: 30),++ // Controls+ Row(+ children: [+ Expanded(+ child: ElevatedButton.icon(+ onPressed: isRunning ? null : _start,+ icon: const Icon(Icons.play_arrow),+ label: const Text('Start'),+ style: ElevatedButton.styleFrom(+ backgroundColor: Colors.green,+ foregroundColor: Colors.white,+ padding: const EdgeInsets.symmetric(vertical: 16),),),- const SizedBox(width: 10),- Expanded(- child: ElevatedButton(- onPressed: _running ? _stop : null,- style: ElevatedButton.styleFrom(- backgroundColor: Colors.red.shade100,- ),- child: const Text('Stop Node'),+ ),+ const SizedBox(width: 16),+ Expanded(+ child: ElevatedButton.icon(+ onPressed: isRunning ? _stop : null,+ icon: const Icon(Icons.stop),+ label: const Text('Stop'),+ style: ElevatedButton.styleFrom(+ backgroundColor: Colors.red,+ foregroundColor: Colors.white,+ padding: const EdgeInsets.symmetric(vertical: 16),),),- ],- ),- const SizedBox(height: 30),- Card(- child: Padding(- padding: const EdgeInsets.all(16.0),- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Text('Status: $_status', style: const TextStyle(fontWeight: FontWeight.bold)),- const SizedBox(height: 10),- Text('Node ID: $_nodeID', style: const TextStyle(fontFamily: 'monospace')),- ],- ),),- ),+ ],+ ),+ const SizedBox(height: 20),++ // Unenroll fallback+ TextButton.icon(+ onPressed: _unenroll,+ icon: const Icon(Icons.logout, color: Colors.red),+ label: const Text('Unenroll / Clear Identity', style: TextStyle(color: Colors.red)),+ ),+ ],+ ),+ );+ }++ Widget _buildStatCard({required IconData icon, required String title, required String value, required Color color}) {+ return Card(+ elevation: 2,+ child: Padding(+ padding: const EdgeInsets.all(16.0),+ child: Column(+ children: [+ Icon(icon, color: color, size: 30),+ const SizedBox(height: 10),+ Text(value, style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold)),+ const SizedBox(height: 5),+ Text(title, style: TextStyle(color: Colors.grey.shade600, fontSize: 12), textAlign: TextAlign.center),],),),diff --git a/mobile/sam-node-app/lib/sam_ffi.dart b/mobile/sam-node-app/lib/sam_ffi.dartindex b16fd084..ced40c8d 100644--- a/mobile/sam-node-app/lib/sam_ffi.dart+++ b/mobile/sam-node-app/lib/sam_ffi.dart@@ -24,6 +24,15 @@ typedef EnrollNodeDart = ffi.Pointer<Utf8> Function(ffi.Pointer<Utf8> jwt,int allowLoopback);+typedef FetchHubInfoJSONC = ffi.Pointer<Utf8> Function(ffi.Pointer<Utf8> hubURL);+typedef FetchHubInfoJSONDart = ffi.Pointer<Utf8> Function(ffi.Pointer<Utf8> hubURL);++typedef IsEnrolledC = ffi.Int8 Function(ffi.Pointer<Utf8> dataDir);+typedef IsEnrolledDart = int Function(ffi.Pointer<Utf8> dataDir);++typedef GetMeshInfoC = ffi.Pointer<Utf8> Function();+typedef GetMeshInfoDart = ffi.Pointer<Utf8> Function();+typedef FreeStringC = ffi.Void Function(ffi.Pointer<Utf8> str);typedef FreeStringDart = void Function(ffi.Pointer<Utf8> str);@@ -33,6 +42,9 @@ class SamNodeLib {late StopNodeDart _stopNode;late GetNodeIDDart _getNodeID;late EnrollNodeDart _enrollNode;+ late FetchHubInfoJSONDart _fetchHubInfoJSON;+ late IsEnrolledDart _isEnrolled;+ late GetMeshInfoDart _getMeshInfo;late FreeStringDart _freeString;SamNodeLib() {@@ -48,6 +60,9 @@ class SamNodeLib {_stopNode = _dylib.lookupFunction<StopNodeC, StopNodeDart>('StopNode');_getNodeID = _dylib.lookupFunction<GetNodeIDC, GetNodeIDDart>('GetNodeID');_enrollNode = _dylib.lookupFunction<EnrollNodeC, EnrollNodeDart>('EnrollNode');+ _fetchHubInfoJSON = _dylib.lookupFunction<FetchHubInfoJSONC, FetchHubInfoJSONDart>('FetchHubInfoJSON');+ _isEnrolled = _dylib.lookupFunction<IsEnrolledC, IsEnrolledDart>('IsEnrolled');+ _getMeshInfo = _dylib.lookupFunction<GetMeshInfoC, GetMeshInfoDart>('GetMeshInfo');_freeString = _dylib.lookupFunction<FreeStringC, FreeStringDart>('FreeString');}@@ -96,4 +111,30 @@ class SamNodeLib {_freeString(cErr);return goErr;}++ String? fetchHubInfoJSON(String hubURL) {+ final cHubURL = hubURL.toNativeUtf8();+ final cResult = _fetchHubInfoJSON(cHubURL);+ calloc.free(cHubURL);++ if (cResult.address == 0) return null;+ final goResult = cResult.toDartString();+ _freeString(cResult);+ return goResult;+ }++ bool isEnrolled(String dataDir) {+ final cDataDir = dataDir.toNativeUtf8();+ final result = _isEnrolled(cDataDir);+ calloc.free(cDataDir);+ return result != 0;+ }++ String? getMeshInfo() {+ final cResult = _getMeshInfo();+ if (cResult.address == 0) return null;+ final goResult = cResult.toDartString();+ _freeString(cResult);+ return goResult;+ }}diff --git a/mobile/sam-node-app/pubspec.lock b/mobile/sam-node-app/pubspec.lockindex f484b628..441e23f1 100644--- a/mobile/sam-node-app/pubspec.lock+++ b/mobile/sam-node-app/pubspec.lock@@ -58,7 +58,7 @@ packages:source: hostedversion: "1.19.1"crypto:- dependency: transitive+ dependency: "direct main"description:name: cryptosha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf@@ -112,6 +112,11 @@ packages:description: fluttersource: sdkversion: "0.0.0"+ flutter_web_plugins:+ dependency: transitive+ description: flutter+ source: sdk+ version: "0.0.0"fuchsia_remote_debug_protocol:dependency: transitivedescription: flutter@@ -330,6 +335,22 @@ packages:url: "https://pub.dev"source: hostedversion: "2.2.0"+ qr:+ dependency: transitive+ description:+ name: qr+ sha256: "5a1d2586170e172b8a8c8470bbbffd5eb0cd38a66c0d77155ea138d3af3a4445"+ url: "https://pub.dev"+ source: hosted+ version: "3.0.2"+ qr_flutter:+ dependency: "direct main"+ description:+ name: qr_flutter+ sha256: "5095f0fc6e3f71d08adef8feccc8cea4f12eec18a2e31c2e8d82cb6019f4b097"+ url: "https://pub.dev"+ source: hosted+ version: "4.1.0"record_use:dependency: transitivedescription:@@ -407,6 +428,70 @@ packages:url: "https://pub.dev"source: hostedversion: "1.4.0"+ url_launcher:+ dependency: "direct main"+ description:+ name: url_launcher+ sha256: f6a7e5c4835bb4e3026a04793a4199ca2d14c739ec378fdfe23fc8075d0439f8+ url: "https://pub.dev"+ source: hosted+ version: "6.3.2"+ url_launcher_android:+ dependency: transitive+ description:+ name: url_launcher_android+ sha256: b413d49b73867ac08dd2f9890efd3cc11f2a0e577618d50843440a1fb3776c32+ url: "https://pub.dev"+ source: hosted+ version: "6.3.32"+ url_launcher_ios:+ dependency: transitive+ description:+ name: url_launcher_ios+ sha256: "580fe5dfb51671ae38191d316e027f6b76272b026370708c2d898799750a02b0"+ url: "https://pub.dev"+ source: hosted+ version: "6.4.1"+ url_launcher_linux:+ dependency: transitive+ description:+ name: url_launcher_linux+ sha256: d5e14138b3bc193a0f63c10a53c94b91d399df0512b1f29b94a043db7482384a+ url: "https://pub.dev"+ source: hosted+ version: "3.2.2"+ url_launcher_macos:+ dependency: transitive+ description:+ name: url_launcher_macos+ sha256: "368adf46f71ad3c21b8f06614adb38346f193f3a59ba8fe9a2fd74133070ba18"+ url: "https://pub.dev"+ source: hosted+ version: "3.2.5"+ url_launcher_platform_interface:+ dependency: transitive+ description:+ name: url_launcher_platform_interface+ sha256: "552f8a1e663569be95a8190206a38187b531910283c3e982193e4f2733f01029"+ url: "https://pub.dev"+ source: hosted+ version: "2.3.2"+ url_launcher_web:+ dependency: transitive+ description:+ name: url_launcher_web+ sha256: "85c81589622fbc87c1c683aaea164d3604a7777495a79d91e39ffcdec39ddb34"+ url: "https://pub.dev"+ source: hosted+ version: "2.4.3"+ url_launcher_windows:+ dependency: transitive+ description:+ name: url_launcher_windows+ sha256: "712c70ab1b99744ff066053cbe3e80c73332b38d46e5e945c98689b2e66fc15f"+ url: "https://pub.dev"+ source: hosted+ version: "3.1.5"vector_math:dependency: transitivedescription:@@ -456,5 +541,5 @@ packages:source: hostedversion: "3.1.3"sdks:- dart: ">=3.10.3 <4.0.0"- flutter: ">=3.38.4"+ dart: ">=3.12.0 <4.0.0"+ flutter: ">=3.44.0"diff --git a/mobile/sam-node-app/pubspec.yaml b/mobile/sam-node-app/pubspec.yamlindex 822d32db..0b5444a0 100644--- a/mobile/sam-node-app/pubspec.yaml+++ b/mobile/sam-node-app/pubspec.yaml@@ -13,6 +13,9 @@ dependencies:ffi: ^2.1.0path_provider: ^2.1.1http: ^1.2.0+ url_launcher: ^6.2.5+ crypto: ^3.0.3+ qr_flutter: ^4.1.0dev_dependencies:flutter_test:diff --git a/mobile/sam-node-ffi/ffi/ffi.go b/mobile/sam-node-ffi/ffi/ffi.goindex 6121203c..91840623 100644--- a/mobile/sam-node-ffi/ffi/ffi.go+++ b/mobile/sam-node-ffi/ffi/ffi.go@@ -30,6 +30,7 @@ import ("github.com/google/sam/internal/node"golog "github.com/ipfs/go-log/v2""github.com/multiformats/go-multiaddr"+ "google.golang.org/protobuf/encoding/protojson")var (@@ -318,3 +319,59 @@ func EnrollNode(dataDir string, hubURL string, jwt string, allowLoopback bool) ereturn nil}++// FetchHubInfoJSON fetches hub info and returns it as a JSON string.+// If an error occurs, it returns a JSON object with an "error" field.+func FetchHubInfoJSON(hubURL string) string {+ info, err := node.FetchHubInfo(context.Background(), hubURL)+ if err != nil {+ return fmt.Sprintf(`{"error": %q}`, err.Error())+ }+ jsonBytes, err := protojson.Marshal(info)+ if err != nil {+ return fmt.Sprintf(`{"error": %q}`, err.Error())+ }+ return string(jsonBytes)+}++// IsEnrolled checks if the node is enrolled (has a valid identity).+func IsEnrolled(dataDir string) byte {+ if activeNode != nil {+ return 1 // Running node implies enrolled+ }+ store, err := node.NewStore(dataDir)+ if err != nil {+ return 0+ }+ defer store.Close()+ token, _ := store.LoadIdentity()+ if len(token) > 0 {+ return 1+ }+ return 0+}++// GetMeshInfo returns mesh information as a JSON string.+func GetMeshInfo() string {+ if activeNode == nil {+ return `{"error": "node not running"}`+ }++ peers := activeNode.Host.Network().Peers()+ dhtSize := 0+ if activeNode.DHT != nil && activeNode.DHT.RoutingTable() != nil {+ dhtSize = activeNode.DHT.RoutingTable().Size()+ }++ resData := map[string]any{+ "connected_peers": len(peers),+ "dht_size": dhtSize,+ "node_id": activeNode.Host.ID().String(),+ }++ jsonBytes, err := json.Marshal(resData)+ if err != nil {+ return fmt.Sprintf(`{"error": %q}`, err.Error())+ }+ return string(jsonBytes)+}diff --git a/mobile/sam-node-ffi/main.go b/mobile/sam-node-ffi/main.goindex 8eafc31d..cec7d1b8 100644--- a/mobile/sam-node-ffi/main.go+++ b/mobile/sam-node-ffi/main.go@@ -68,6 +68,25 @@ func EnrollNode(dataDir *C.char, hubURL *C.char, jwt *C.char, allowLoopback C.chreturn nil}+//export FetchHubInfoJSON+func FetchHubInfoJSON(hubURL *C.char) *C.char {+ goHubURL := C.GoString(hubURL)+ jsonStr := ffi.FetchHubInfoJSON(goHubURL)+ return C.CString(jsonStr)+}++//export IsEnrolled+func IsEnrolled(dataDir *C.char) C.char {+ goDataDir := C.GoString(dataDir)+ return C.char(ffi.IsEnrolled(goDataDir))+}++//export GetMeshInfo+func GetMeshInfo() *C.char {+ jsonStr := ffi.GetMeshInfo()+ return C.CString(jsonStr)+}+//export FreeStringfunc FreeString(str *C.char) {C.free(unsafe.Pointer(str))