Skip to content

Agent Mesh

comments have been addressed, and validation checks are passing.

Antonio Ojea37193a71bd07
diff --git a/mobile/mobile_e2e.sh b/mobile/mobile_e2e.sh
index d001378c..2b6b6709 100755
--- a/mobile/mobile_e2e.sh
+++ b/mobile/mobile_e2e.sh
@@ -32,6 +32,7 @@ cleanup() {
docker kill host-node sam-hub mock-oidc host-mock-mcp >/dev/null 2>&1 || true
docker network rm sam-net >/dev/null 2>&1 || true
rm -rf /tmp/host-node-data
+ adb reverse --remove-all || true
}
trap cleanup EXIT
@@ -57,6 +58,9 @@ docker run --name mock-oidc \
# Wait for OIDC server to be ready
timeout 15s bash -c 'until curl -s http://127.0.0.1:18080/ >/dev/null; do sleep 0.5; done'
+# Set up adb reverse for OIDC
+adb reverse tcp:18080 tcp:18080
+
# 4. Start the Hub container
docker run --name sam-hub \
--network sam-net \
@@ -67,7 +71,7 @@ docker run --name sam-hub \
sam-hub:local \
--bind-address 0.0.0.0:37001 \
--listen /ip4/0.0.0.0/tcp/37002 \
- --external-multiaddr /ip4/10.0.2.2/tcp/37002,/dns4/sam-hub/tcp/37002 \
+ --external-multiaddr /ip4/10.0.2.2/tcp/37002,/ip4/127.0.0.1/tcp/37002,/dns4/sam-hub/tcp/37002 \
--issuer http://mock-oidc:18080 \
--mesh public-mesh \
--policy-file /policy.yaml \
@@ -75,6 +79,10 @@ docker run --name sam-hub \
--allow-loopback \
--log-level debug
+# Set up adb reverse for Hub
+adb reverse tcp:37001 tcp:37001
+adb reverse tcp:37002 tcp:37002
+
# Wait for Hub to be ready
timeout 15s bash -c 'until curl -s http://127.0.0.1:37001/info >/dev/null; do sleep 0.5; done'
diff --git a/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/MainActivity.kt b/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/MainActivity.kt
index ffa6fc93..ff98cfe7 100644
--- a/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/MainActivity.kt
+++ b/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/MainActivity.kt
@@ -73,9 +73,14 @@ class MainActivity : FlutterActivity() {
return@setMethodCallHandler
}
+ val hasFineLocation = androidx.core.content.ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == android.content.pm.PackageManager.PERMISSION_GRANTED
val locationManager = getSystemService(Context.LOCATION_SERVICE) as android.location.LocationManager
- val location: android.location.Location? = locationManager.getLastKnownLocation(android.location.LocationManager.GPS_PROVIDER)
- ?: locationManager.getLastKnownLocation(android.location.LocationManager.NETWORK_PROVIDER)
+ val location: android.location.Location? = if (hasFineLocation) {
+ locationManager.getLastKnownLocation(android.location.LocationManager.GPS_PROVIDER)
+ ?: locationManager.getLastKnownLocation(android.location.LocationManager.NETWORK_PROVIDER)
+ } else {
+ locationManager.getLastKnownLocation(android.location.LocationManager.NETWORK_PROVIDER)
+ }
if (location != null) {
result.success("{\"latitude\": ${location.latitude}, \"longitude\": ${location.longitude}}")
diff --git a/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/SamApplication.kt b/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/SamApplication.kt
index d48865b3..4642ca3d 100644
--- a/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/SamApplication.kt
+++ b/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/SamApplication.kt
@@ -1,9 +1,9 @@
package com.example.sam_agent
-import io.flutter.app.FlutterApplication
+import android.app.Application
import androidx.appfunctions.service.AppFunctionConfiguration
-class SamApplication : FlutterApplication(), AppFunctionConfiguration.Provider {
+class SamApplication : Application(), AppFunctionConfiguration.Provider {
// Instantiate SamFunctions lazily or eagerly
private val samFunctions by lazy { SamFunctions() }
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 f6eccd3e..1e108267 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
@@ -9,6 +9,10 @@ import android.os.Build
import android.os.IBinder
import android.os.PowerManager
import androidx.core.app.NotificationCompat
+import androidx.core.content.ContextCompat
+import android.content.pm.ServiceInfo
+import android.content.pm.PackageManager
+import android.Manifest
import android.util.Log
class SamNodeForegroundService : Service() {
@@ -31,7 +35,30 @@ class SamNodeForegroundService : Service() {
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val notification = createNotification()
- startForeground(NOTIFICATION_ID, notification)
+
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
+ var type = 0
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
+ type = type or ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE
+ }
+
+ val hasLocationPermission = ContextCompat.checkSelfPermission(
+ this,
+ Manifest.permission.ACCESS_COARSE_LOCATION
+ ) == PackageManager.PERMISSION_GRANTED
+
+ if (hasLocationPermission) {
+ type = type or ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION
+ }
+
+ if (type != 0) {
+ startForeground(NOTIFICATION_ID, notification, type)
+ } else {
+ startForeground(NOTIFICATION_ID, notification)
+ }
+ } else {
+ startForeground(NOTIFICATION_ID, notification)
+ }
Log.d("SAM_SERVICE", "Foreground Service Started")
diff --git a/mobile/sam-node-app/integration_test/e2e_test.dart b/mobile/sam-node-app/integration_test/e2e_test.dart
index 1e90c2b4..448853c5 100644
--- a/mobile/sam-node-app/integration_test/e2e_test.dart
+++ b/mobile/sam-node-app/integration_test/e2e_test.dart
@@ -24,8 +24,8 @@ void main() {
}
// 2. Fetch OIDC JWT from the mock OIDC server running on host
- // Host IP from emulator is 10.0.2.2
- const oidcIssuer = 'http://10.0.2.2:18080';
+ // Use loopback with adb reverse
+ const oidcIssuer = 'http://127.0.0.1:18080';
const tokenURL = '$oidcIssuer/token';
final response = await http.post(
@@ -43,7 +43,7 @@ void main() {
expect(jwt, isNotEmpty);
// 3. Enroll Node against host Hub
- const hubURL = 'http://10.0.2.2:37001';
+ const hubURL = 'http://127.0.0.1:37001';
final enrollErr = samLib.enroll(dataDir, hubURL, jwt, true);
expect(enrollErr, isNull);
diff --git a/mobile/sam-node-app/lib/main.dart b/mobile/sam-node-app/lib/main.dart
index 7dbe6f82..9fe121bb 100644
--- a/mobile/sam-node-app/lib/main.dart
+++ b/mobile/sam-node-app/lib/main.dart
@@ -18,7 +18,11 @@ import 'mcp_server.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
- await Firebase.initializeApp();
+ try {
+ await Firebase.initializeApp();
+ } catch (e) {
+ debugPrint('Failed to initialize Firebase: $e');
+ }
runApp(const MyApp());
}
@@ -186,9 +190,9 @@ class _NodeControlPageState extends State<NodeControlPage> {
int? selectedPort;
for (final port in [13000, 13001, 13002]) {
try {
- server = await HttpServer.bind(InternetAddress.anyIPv4, port);
+ server = await HttpServer.bind(InternetAddress.loopbackIPv4, port);
selectedPort = port;
- debugPrint('DEBUG: Bound local server to port $port (any IPv4)');
+ debugPrint('DEBUG: Bound local server to port $port (loopback)');
break;
} catch (e) {
debugPrint('DEBUG: Failed to bind to port $port: $e');
@@ -586,6 +590,7 @@ class _NodeControlPageState extends State<NodeControlPage> {
try {
final info = jsonDecode(infoJson);
if (info['error'] == null) {
+ if (!mounted) return;
setState(() {
_connectedPeers = info['connected_peers'] ?? 0;
_dhtSize = info['dht_size'] ?? 0;
diff --git a/mobile/sam-node-app/lib/mcp_server.dart b/mobile/sam-node-app/lib/mcp_server.dart
index 4d583df0..c3ce0dee 100644
--- a/mobile/sam-node-app/lib/mcp_server.dart
+++ b/mobile/sam-node-app/lib/mcp_server.dart
@@ -64,6 +64,9 @@ class SamDartMcpServer {
request.response.headers.add('Connection', 'keep-alive');
_sseClients.add(request.response);
+ request.response.done.then((_) {
+ _sseClients.remove(request.response);
+ });
// Initial connection event
request.response.write('event: connected\ndata: {}\n\n');
@@ -238,33 +241,41 @@ class SamDartMcpServer {
}) async {
final url = 'http://127.0.0.1:$goSidecarPort/sam/service/register';
- try {
- final response = await http.post(
- Uri.parse(url),
- headers: {
- 'Authorization': 'Bearer $apiToken',
- 'Content-Type': 'application/json',
- },
- body: jsonEncode({
- 'service': {
- 'type': 1, // SERVICE_TYPE_MCP
- 'name': serviceName,
- 'description': description
+ int retries = 5;
+ while (retries > 0) {
+ try {
+ final response = await http.post(
+ Uri.parse(url),
+ headers: {
+ 'Authorization': 'Bearer $apiToken',
+ 'Content-Type': 'application/json',
},
- 'target_url': targetUrl
- }),
- );
+ body: jsonEncode({
+ 'service': {
+ 'type': 1, // SERVICE_TYPE_MCP
+ 'name': serviceName,
+ 'description': description
+ },
+ 'target_url': targetUrl
+ }),
+ );
- if (response.statusCode == 200) {
- debugPrint('Service "$serviceName" registered successfully with SAM Go Node!');
- return true;
- } else {
- debugPrint('Failed to register service "$serviceName": ${response.statusCode} - ${response.body}');
- return false;
+ if (response.statusCode == 200) {
+ debugPrint('Service "$serviceName" registered successfully with SAM Go Node!');
+ return true;
+ } else {
+ debugPrint('Failed to register service "$serviceName": ${response.statusCode} - ${response.body}');
+ return false;
+ }
+ } catch (e) {
+ retries--;
+ if (retries == 0) {
+ debugPrint('Error registering service "$serviceName": $e');
+ return false;
+ }
+ await Future.delayed(const Duration(milliseconds: 500));
}
- } catch (e) {
- debugPrint('Error registering service "$serviceName": $e');
- return false;
}
+ return false;
}
}
diff --git a/mobile/sam-node-ffi/ffi/ffi.go b/mobile/sam-node-ffi/ffi/ffi.go
index 47af0394..2aa5841a 100644
--- a/mobile/sam-node-ffi/ffi/ffi.go
+++ b/mobile/sam-node-ffi/ffi/ffi.go
@@ -357,6 +357,9 @@ func GetMeshInfo() string {
if activeNode == nil {
return `{"error": "node not running"}`
}
+ if activeNode.Host == nil {
+ return `{"error": "host not initialized"}`
+ }
peers := activeNode.Host.Network().Peers()
dhtSize := 0
@@ -382,6 +385,9 @@ func CallRemoteTool(peerIDStr string, toolName string, argsJSON string) string {
if activeNode == nil {
return `{"error": "node not running"}`
}
+ if activeNode.Host == nil {
+ return `{"error": "host not initialized"}`
+ }
targetPeer, err := peer.Decode(peerIDStr)
if err != nil {