Skip to content

Agent Mesh

fix(mobile): resolve PR review comments, offload FFI calls to isolates, add thread safety, and fix Firebase init logic

Antonio Ojea7585b94f2c1e
diff --git a/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/SamNodeForegroundService.kt b/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/SamNodeForegroundService.kt
index 1e108267..9e6fac94 100644
--- a/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/SamNodeForegroundService.kt
+++ b/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/SamNodeForegroundService.kt
@@ -71,7 +71,9 @@ class SamNodeForegroundService : Service() {
override fun onDestroy() {
super.onDestroy()
- wakeLock?.release()
+ if (wakeLock?.isHeld == true) {
+ wakeLock?.release()
+ }
Log.d("SAM_SERVICE", "Foreground Service Destroyed")
}
diff --git a/mobile/sam-node-app/lib/main.dart b/mobile/sam-node-app/lib/main.dart
index 9fe121bb..fde679a7 100644
--- a/mobile/sam-node-app/lib/main.dart
+++ b/mobile/sam-node-app/lib/main.dart
@@ -2,6 +2,7 @@ import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math';
+import 'dart:isolate';
import 'package:crypto/crypto.dart';
import 'package:flutter/material.dart';
@@ -143,7 +144,7 @@ class _NodeControlPageState extends State<NodeControlPage> {
try {
final hubUrl = _hubController.text.trim();
debugPrint('DEBUG: Fetching hub info from $hubUrl');
- final infoJson = _samLib.fetchHubInfoJSON(hubUrl);
+ final infoJson = await Isolate.run(() => SamNodeLib().fetchHubInfoJSON(hubUrl));
debugPrint('DEBUG: Hub info JSON: $infoJson');
if (infoJson == null) {
throw Exception('Failed to fetch hub info');
@@ -346,7 +347,7 @@ class _NodeControlPageState extends State<NodeControlPage> {
try {
final hubUrl = _hubController.text.trim();
debugPrint('DEBUG: Device Login: Fetching hub info from $hubUrl');
- final infoJson = _samLib.fetchHubInfoJSON(hubUrl);
+ final infoJson = await Isolate.run(() => SamNodeLib().fetchHubInfoJSON(hubUrl));
if (infoJson == null) throw Exception('Failed to fetch hub info');
final info = jsonDecode(infoJson);
@@ -555,12 +556,16 @@ class _NodeControlPageState extends State<NodeControlPage> {
Future<void> _enroll() async {
final appDir = await getApplicationDocumentsDirectory();
final dataDir = '${appDir.path}/sam_data';
- final err = _samLib.enroll(
- dataDir,
- _hubController.text,
- _jwtController.text,
- true, // allowLoopback
- );
+ final hubText = _hubController.text;
+ final jwtText = _jwtController.text;
+ final err = await Isolate.run(() {
+ return SamNodeLib().enroll(
+ dataDir,
+ hubText,
+ jwtText,
+ true, // allowLoopback
+ );
+ });
setState(() {
if (err != null) {
diff --git a/mobile/sam-node-app/lib/mcp_server.dart b/mobile/sam-node-app/lib/mcp_server.dart
index c3ce0dee..fc6b6d4c 100644
--- a/mobile/sam-node-app/lib/mcp_server.dart
+++ b/mobile/sam-node-app/lib/mcp_server.dart
@@ -152,6 +152,13 @@ class SamDartMcpServer {
// 3. Call Tool
if (method == 'tools/call') {
final params = jsonRpc['params'];
+ if (params is! Map<String, dynamic> || !params.containsKey('name')) {
+ return {
+ 'jsonrpc': '2.0',
+ 'id': id,
+ 'error': {'code': -32602, 'message': 'Invalid params: missing tool name'}
+ };
+ }
final toolName = params['name'];
if (toolName == 'get_battery_status' && isBatteryEnabled()) {
@@ -252,11 +259,11 @@ class SamDartMcpServer {
},
body: jsonEncode({
'service': {
- 'type': 1, // SERVICE_TYPE_MCP
+ 'type': 'SERVICE_TYPE_MCP',
'name': serviceName,
'description': description
},
- 'target_url': targetUrl
+ 'targetUrl': targetUrl
}),
);
diff --git a/mobile/sam-node-ffi/ffi/ffi.go b/mobile/sam-node-ffi/ffi/ffi.go
index 2aa5841a..6266dc70 100644
--- a/mobile/sam-node-ffi/ffi/ffi.go
+++ b/mobile/sam-node-ffi/ffi/ffi.go
@@ -287,11 +287,19 @@ func EnrollNode(dataDir string, hubURL string, jwt string, allowLoopback bool) e
enrollCtx, enrollCancel := context.WithCancel(context.Background())
defer enrollCancel()
+ var listenAddrs []string
+ if allowLoopback {
+ listenAddrs = []string{"/ip4/127.0.0.1/udp/0/quic-v1", "/ip4/127.0.0.1/tcp/0"}
+ } else {
+ listenAddrs = []string{"/ip4/0.0.0.0/udp/0/quic-v1", "/ip4/0.0.0.0/tcp/0"}
+ }
+
meshNode, err := node.NewSamNode(node.Options{
PrivKey: priv,
HubAddrs: initHubAddrs,
Store: store,
AllowLoopback: allowLoopback,
+ ListenAddrs: listenAddrs,
})
if err != nil {
return fmt.Errorf("failed to create node for enrollment: %w", err)
@@ -337,7 +345,10 @@ func FetchHubInfoJSON(hubURL string) string {
// IsEnrolled checks if the node is enrolled (has a valid identity).
func IsEnrolled(dataDir string) byte {
- if activeNode != nil {
+ mu.Lock()
+ running := activeNode != nil
+ mu.Unlock()
+ if running {
return 1 // Running node implies enrolled
}
store, err := node.NewStore(dataDir)
@@ -354,6 +365,9 @@ func IsEnrolled(dataDir string) byte {
// GetMeshInfo returns mesh information as a JSON string.
func GetMeshInfo() string {
+ mu.Lock()
+ defer mu.Unlock()
+
if activeNode == nil {
return `{"error": "node not running"}`
}
@@ -382,10 +396,14 @@ func GetMeshInfo() string {
// CallRemoteTool calls an MCP tool on a remote peer and returns the result as a JSON string.
func CallRemoteTool(peerIDStr string, toolName string, argsJSON string) string {
- if activeNode == nil {
+ mu.Lock()
+ n := activeNode
+ mu.Unlock()
+
+ if n == nil {
return `{"error": "node not running"}`
}
- if activeNode.Host == nil {
+ if n.Host == nil {
return `{"error": "host not initialized"}`
}
@@ -401,7 +419,7 @@ func CallRemoteTool(peerIDStr string, toolName string, argsJSON string) string {
}
}
- res, err := activeNode.CallMCPTool(context.Background(), targetPeer, toolName, params)
+ res, err := n.CallMCPTool(context.Background(), targetPeer, toolName, params)
if err != nil {
return fmt.Sprintf(`{"error": "failed to call tool: %s"}`, err.Error())
}