Skip to content

Agent Mesh

test: add bidirectional E2E integration test using Android Emulator in GitHub Actions, add Makefile targets, and add mobile docs

Antonio Ojea6385b6ac54b7
diff --git a/.github/workflows/test_flutter.yaml b/.github/workflows/test_flutter.yaml
index 91fd5a20..76997b5d 100644
--- a/.github/workflows/test_flutter.yaml
+++ b/.github/workflows/test_flutter.yaml
@@ -2,7 +2,7 @@
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
+# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
@@ -17,10 +17,11 @@ on:
push:
branches:
- 'main'
+ - 'mmobile'
tags:
- 'v*'
pull_request:
- branches: [ main ]
+ branches: [ main, mmobile ]
env:
GO_VERSION: "1.26"
@@ -48,3 +49,26 @@ jobs:
- name: Analyze code
run: flutter analyze
working-directory: mobile/sam-node-app
+
+ e2e-android:
+ runs-on: macos-latest
+ steps:
+ - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
+ - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6
+ with:
+ go-version: ${{ env.GO_VERSION }}
+ - uses: subosito/flutter-action@f0e3869966141470404a3952d9a30b9538350811 # v2
+ with:
+ channel: 'stable'
+ - name: Set up JDK
+ uses: actions/setup-java@99b8673ff64fbf99d8d325f52d9a5bdedb8483e9 # v4.2.1
+ with:
+ java-version: '17'
+ distribution: 'temurin'
+ - name: Run E2E Integration Test in Android Emulator
+ uses: ReactiveCircus/android-emulator-runner@b86636dcd5723ef0161e7f288e9bd0ad01258791 # v2.30.0
+ with:
+ api-level: 30
+ target: google_apis
+ arch: x86_64
+ script: ./mobile/mobile_e2e.sh
diff --git a/Makefile b/Makefile
index 8463a12f..3d646736 100644
--- a/Makefile
+++ b/Makefile
@@ -10,7 +10,7 @@ build:
go build -v -o "$(OUT_DIR)/sam-hub" ./cmd/sam-hub
go build -v -o "$(OUT_DIR)/mcp-client" ./cmd/mcp-client
-.PHONY: mobile-ffi-host mobile-ffi-android mobile-ffi-ios
+.PHONY: mobile-ffi-host mobile-ffi-android mobile-ffi-ios mobile-ffi mobile-app-apk mobile-app-apk-emulator
mobile-ffi-host:
mkdir -p "$(OUT_DIR)"
CGO_ENABLED=1 go build -v -buildmode=c-shared -o "$(OUT_DIR)/libsam.so" ./mobile/sam-node-ffi
@@ -23,6 +23,20 @@ mobile-ffi-ios:
mkdir -p "$(OUT_DIR)/ios"
GOOS=ios GOARCH=arm64 CGO_ENABLED=1 go build -v -buildmode=c-archive -o "$(OUT_DIR)/ios/libsam.a" ./mobile/sam-node-ffi
+mobile-ffi: mobile-ffi-host mobile-ffi-android mobile-ffi-ios
+
+mobile-app-apk: mobile-ffi-android
+ mkdir -p mobile/sam-node-app/android/app/src/main/jniLibs/arm64-v8a
+ cp "$(OUT_DIR)/android/libsam.so" mobile/sam-node-app/android/app/src/main/jniLibs/arm64-v8a/libsam.so
+ cd mobile/sam-node-app && flutter build apk --release
+
+mobile-app-apk-emulator:
+ mkdir -p "$(OUT_DIR)/android-x86_64"
+ GOOS=android GOARCH=amd64 CGO_ENABLED=1 go build -v -buildmode=c-shared -o "$(OUT_DIR)/android-x86_64/libsam.so" ./mobile/sam-node-ffi
+ mkdir -p mobile/sam-node-app/android/app/src/main/jniLibs/x86_64
+ cp "$(OUT_DIR)/android-x86_64/libsam.so" mobile/sam-node-app/android/app/src/main/jniLibs/x86_64/libsam.so
+ cd mobile/sam-node-app && flutter build apk --release
+
.PHONY: proto
proto:
./hack/gen-proto.sh
diff --git a/mobile/mobile_e2e.sh b/mobile/mobile_e2e.sh
new file mode 100755
index 00000000..ec92f666
--- /dev/null
+++ b/mobile/mobile_e2e.sh
@@ -0,0 +1,126 @@
+#!/usr/bin/env bash
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+set -xeuo pipefail
+
+SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &> /dev/null && pwd)
+REPO_ROOT=$(cd "$SCRIPT_DIR/.." &> /dev/null && pwd)
+cd "$REPO_ROOT"
+
+# Helper to kill background processes on exit
+NODE_PID=""
+HUB_PID=""
+OIDC_PID=""
+cleanup() {
+ echo "[E2E] Cleaning up background processes..."
+ if [ -n "$NODE_PID" ]; then kill "$NODE_PID" || true; fi
+ if [ -n "$HUB_PID" ]; then kill "$HUB_PID" || true; fi
+ if [ -n "$OIDC_PID" ]; then kill "$OIDC_PID" || true; fi
+ rm -rf /tmp/host-node-data
+}
+trap cleanup EXIT
+
+# 1. Setup local DNS for mock-oidc
+if ! grep -q "mock-oidc" /etc/hosts; then
+ echo "127.0.0.1 mock-oidc" | sudo tee -a /etc/hosts
+fi
+
+# 2. Build host binaries
+make build
+
+# 3. Build FFI library for the Android Emulator architecture (x86_64)
+mkdir -p mobile/sam-node-app/android/app/src/main/jniLibs/x86_64
+GOOS=android GOARCH=amd64 CGO_ENABLED=1 go build -v -buildmode=c-shared -o mobile/sam-node-app/android/app/src/main/jniLibs/x86_64/libsam.so ./mobile/sam-node-ffi
+
+# 4. Start the mock OIDC server
+python3 tests/e2e/docker/mock_oidc.py &
+OIDC_PID=$!
+
+# 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'
+
+# 5. Start the Hub
+bin/sam-hub run \
+ --bind-addr 127.0.0.1:37001 \
+ --oidc-issuer http://mock-oidc:18080 \
+ --mesh-id public-mesh \
+ --insecure-skip-tls-verify &
+HUB_PID=$!
+
+# Wait for Hub to print PeerID
+timeout 15s bash -c 'until bin/sam-hub --context local info 2>/dev/null; do sleep 0.5; done'
+
+# 6. Enroll and Start the External Node on Host
+rm -rf /tmp/host-node-data
+HOST_JWT=$(curl -s -X POST -d "grant_type=client_credentials&client_id=test-client&client_secret=test-secret" http://127.0.0.1:18080/token | jq -r .access_token)
+
+bin/sam-node enroll \
+ --data-dir /tmp/host-node-data \
+ --hub http://127.0.0.1:37001 \
+ --jwt "$HOST_JWT" \
+ --allow-loopback
+
+bin/sam-node run \
+ --data-dir /tmp/host-node-data \
+ --hub http://127.0.0.1:37001 \
+ --bind-addr 127.0.0.1:8081 \
+ --api-token host-token \
+ --allow-loopback &
+NODE_PID=$!
+
+# Wait for external node to be ready
+timeout 15s bash -c 'until curl -s -X POST -H "Authorization: Bearer host-token" -d "{\"jsonrpc\":\"2.0\",\"method\":\"ping\",\"id\":1}" http://127.0.0.1:8081/mcp >/dev/null; do sleep 0.5; done'
+
+# Register a dummy MCP service on the host node
+curl -s -X POST \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer host-token" \
+ -d '{"service":{"type":"SERVICE_TYPE_MCP","name":"host-tool","description":"test tool on host"},"targetUrl":"http://127.0.0.1:8081"}' \
+ http://127.0.0.1:8081/sam/service/register
+
+# 7. Start the Android Emulator and run the Flutter integration test
+# Since this script runs on CI inside ReactiveCircus/android-emulator-runner,
+# the emulator is already started and adb is fully connected to the emulator.
+cd mobile/sam-node-app
+
+# Run Flutter integration test
+flutter test integration_test/e2e_test.dart &
+TEST_PID=$!
+
+# 8. Monitor host node's MCP tool list to verify discovery of emulator-tool
+echo "[E2E] Verifying host node can discover emulator-tool..."
+DISCOVERED=0
+for i in {1..45}; do
+ if [ -f "$REPO_ROOT/bin/mcp-client" ]; then
+ TOOLS=$("$REPO_ROOT/bin/mcp-client" -url http://127.0.0.1:8081/mcp -tool list_tools 2>/dev/null || true)
+ if echo "$TOOLS" | grep -q "emulator-tool"; then
+ echo "[E2E] Host successfully discovered emulator-tool!"
+ DISCOVERED=1
+ break
+ fi
+ fi
+ sleep 1
+done
+
+# Wait for integration test execution to finalize
+wait $TEST_PID
+
+if [ "$DISCOVERED" -ne 1 ]; then
+ echo "[E2E] FAILED: Host failed to discover emulator-tool"
+ exit 1
+fi
+
+echo "[E2E] SUCCESS: Bidirectional mobile E2E test passed!"
+exit 0
diff --git a/mobile/sam-node-app/integration_test/e2e_test.dart b/mobile/sam-node-app/integration_test/e2e_test.dart
new file mode 100644
index 00000000..f4fa1a5d
--- /dev/null
+++ b/mobile/sam-node-app/integration_test/e2e_test.dart
@@ -0,0 +1,131 @@
+import 'dart:convert';
+import 'dart:io';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:http/http.dart' as http;
+import 'package:integration_test/integration_test.dart';
+import 'package:path_provider/path_provider.dart';
+import 'package:sam_agent/sam_ffi.dart';
+
+void main() {
+ IntegrationTestWidgetsFlutterBinding.ensureInitialized();
+
+ testWidgets('E2E Mesh Communication Test', (WidgetTester tester) async {
+ final samLib = SamNodeLib();
+
+ // 1. Get local app directories
+ final appDir = await getApplicationDocumentsDirectory();
+ final dataDir = '${appDir.path}/sam_e2e_data';
+
+ // Cleanup old data
+ final dir = Directory(dataDir);
+ if (dir.existsSync()) {
+ dir.deleteSync(recursive: true);
+ }
+
+ // 2. Fetch OIDC JWT from the mock OIDC server running on host
+ // Host IP from emulator is 10.0.2.2
+ final oidcIssuer = 'http://10.0.2.2:18080';
+ final tokenURL = '$oidcIssuer/token';
+
+ final response = await http.post(
+ Uri.parse(tokenURL),
+ headers: {'Content-Type': 'application/x-www-form-urlencoded'},
+ body: {
+ 'grant_type': 'client_credentials',
+ 'client_id': 'test-client',
+ 'client_secret': 'test-secret',
+ },
+ );
+ expect(response.statusCode, equals(200));
+ final tokenData = jsonDecode(response.body);
+ final jwt = tokenData['access_token'] as String;
+ expect(jwt, isNotEmpty);
+
+ // 3. Enroll Node against host Hub
+ final hubURL = 'http://10.0.2.2:37001';
+ final enrollErr = samLib.enroll(dataDir, hubURL, jwt, true);
+ expect(enrollErr, isNull);
+
+ // 4. Start Node
+ final startErr = samLib.start({
+ 'dataDir': dataDir,
+ 'hubURL': hubURL,
+ 'meshID': 'public-mesh',
+ 'bindAddr': '0.0.0.0:8080', // sidecar HTTP server inside phone
+ 'apiToken': 'test-token',
+ 'allowLoopback': true,
+ 'enableRelay': false,
+ });
+ expect(startErr, isNull);
+
+ // Wait for node to initialize host connection
+ await Future.delayed(const Duration(seconds: 5));
+
+ final nodeID = samLib.getNodeID();
+ expect(nodeID, isNotNull);
+ expect(nodeID, isNotEmpty);
+ expect(nodeID, isNot('unauthenticated'));
+
+ // Register a dummy MCP service inside the Android emulator
+ final registerUrl = 'http://127.0.0.1:8080/sam/service/register';
+ final regResponse = await http.post(
+ Uri.parse(registerUrl),
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Authorization': 'Bearer test-token',
+ },
+ body: jsonEncode({
+ 'service': {
+ 'type': 'SERVICE_TYPE_MCP',
+ 'name': 'emulator-tool',
+ 'description': 'test tool inside emulator'
+ },
+ 'targetUrl': 'http://127.0.0.1:8080' // dummy loopback inside emulator
+ }),
+ );
+ expect(regResponse.statusCode, equals(200));
+
+ // Discover host-tool from inside the emulator via its local MCP API
+ final listToolsUrl = 'http://127.0.0.1:8080/mcp';
+ var discovered = false;
+ for (var i = 0; i < 30; i++) {
+ try {
+ final listResponse = await http.post(
+ Uri.parse(listToolsUrl),
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Authorization': 'Bearer test-token',
+ },
+ body: jsonEncode({
+ 'jsonrpc': '2.0',
+ 'method': 'tools/list',
+ 'params': {},
+ 'id': 1
+ }),
+ );
+ if (listResponse.statusCode == 200) {
+ final listData = jsonDecode(listResponse.body);
+ final result = listData['result'];
+ if (result != null && result['tools'] != null) {
+ final tools = result['tools'] as List;
+ if (tools.any((t) => t['name'] == 'host-tool')) {
+ discovered = true;
+ break;
+ }
+ }
+ }
+ } catch (e) {
+ // ignore network setup transient errors
+ }
+ await Future.delayed(const Duration(seconds: 1));
+ }
+ expect(discovered, isTrue, reason: 'Emulator failed to discover host-tool');
+
+ // Wait some time to let the host verify connection and discover emulator-tool
+ await Future.delayed(const Duration(seconds: 5));
+
+ // Cleanup & Stop
+ final stopErr = samLib.stop();
+ expect(stopErr, isNull);
+ });
+}
diff --git a/mobile/sam-node-app/pubspec.yaml b/mobile/sam-node-app/pubspec.yaml
index 09a62754..822d32db 100644
--- a/mobile/sam-node-app/pubspec.yaml
+++ b/mobile/sam-node-app/pubspec.yaml
@@ -1,5 +1,5 @@
-name: sam_node_app
-description: "A PoC Flutter app for starting/stopping sam-node via FFI."
+name: sam_agent
+description: "SAM Mobile Agent - Secure, decentralized mesh node and MCP tool registry for Android and iOS."
publish_to: 'none'
version: 1.0.0+1
@@ -12,10 +12,13 @@ dependencies:
sdk: flutter
ffi: ^2.1.0
path_provider: ^2.1.1
+ http: ^1.2.0
dev_dependencies:
flutter_test:
sdk: flutter
+ integration_test:
+ sdk: flutter
flutter_lints: ^3.0.0
flutter:
diff --git a/site/content/docs/development/mobile.md b/site/content/docs/development/mobile.md
new file mode 100644
index 00000000..1fe4a785
--- /dev/null
+++ b/site/content/docs/development/mobile.md
@@ -0,0 +1,122 @@
+---
+title: "Mobile Support (Android & iOS)"
+linkTitle: "Mobile Support"
+weight: 6
+---
+
+This guide describes the architecture, compilation toolchain, development workflow, and testing procedures for running `sam-node` on mobile platforms (Android and iOS).
+
+---
+
+## Architecture Overview
+
+To run `sam-node` on mobile with near-zero codebase maintenance, we avoid rewriting the p2p network stack and routing logic in Kotlin/Swift. Instead, we use Go's CGO compiler to generate native C-compatible libraries that are loaded and controlled inside a Flutter app using **Dart FFI (Foreign Function Interface)**.
+
+```
+ ┌────────────────────────────────────────────────────────┐
+ │ Flutter Mobile App │
+ │ │
+ │ ┌─────────────────┐ ┌──────────────────┐ │
+ │ │ Dart GUI │ │ Dart FFI Client │ │
+ │ └────────┬────────┘ └────────┬─────────┘ │
+ │ │ │ │
+ └───────────┼───────────────────────────────┼────────────┘
+ │ │ (C Function Calls)
+ │ (HTTP / JSON RPC) ▼
+ ┌───────────┼───────────────────────────────┼────────────┐
+ │ ▼ │ │
+ │ ┌─────────────────┐ ┌────────▼─────────┐ │
+ │ │ Sidecar API │ │ Go FFI Entry │ │
+ │ │ (127.0.0.1) │ │ (sam-node-ffi) │ │
+ │ └────────┬────────┘ └────────┬─────────┘ │
+ │ │ │ (Go APIs) │
+ │ ▼ ▼ │
+ │ ┌──────────────────────────────────────────────────┐ │
+ │ │ sam-node │ │
+ │ └──────────────────────────────────────────────────┘ │
+ │ Go Runtime │
+ └────────────────────────────────────────────────────────┘
+```
+
+1. **Go FFI Binding Package (`mobile/sam-node-ffi/`)**: Contains CGO-exported functions (`StartNode`, `StopNode`, `EnrollNode`, `GetNodeID`, `FreeString`) which compile into a C-shared library (`.so`) or static archive (`.a`).
+2. **Flutter App (`mobile/sam-node-app/`)**: A cross-platform app containing:
+ - `lib/sam_ffi.dart`: The Dart FFI wrapper loading the Go library and exposing Dart methods.
+ - `lib/main.dart`: Simple control UI to enroll and start/stop the background node.
+3. **Local Loopback Communication**:
+ - The Flutter Dart environment controls the node lifecycle (construction, starting, stopping) via FFI.
+ - Any actual tool registration, discovery, or mesh API queries are performed using standard HTTP JSON-RPC calls over local loopback (`127.0.0.1`) to the `sam-node` sidecar API.
+
+---
+
+## Make Build Targets
+
+We provide dedicated `Makefile` targets to automate Go FFI compilation and copy binaries into the mobile app:
+
+### 1. Build Host FFI (For local desktop testing)
+Compiles `bin/libsam.so` for the host platform:
+```bash
+make mobile-ffi-host
+```
+
+### 2. Build Android FFI Library
+Compiles `bin/android/libsam.so` targeting Android ARM64 devices:
+```bash
+make mobile-ffi-android
+```
+
+### 3. Build iOS FFI Library
+Compiles `bin/ios/libsam.a` targeting iOS ARM64 devices:
+```bash
+make mobile-ffi-ios
+```
+
+### 4. Build Complete Android Release APK
+Compiles the FFI library, bundles it inside the Flutter project, and builds the final release APK:
+```bash
+make mobile-app-apk
+```
+
+---
+
+## Local Development Workflow
+
+To make changes to `sam-node` and run them on a mobile device:
+
+### Android Setup
+1. Compile the Android ARM64 FFI shared library:
+ ```bash
+ make mobile-ffi-android
+ ```
+2. Copy the library into the Android project's `jniLibs` directory:
+ ```bash
+ mkdir -p mobile/sam-node-app/android/app/src/main/jniLibs/arm64-v8a
+ cp bin/android/libsam.so mobile/sam-node-app/android/app/src/main/jniLibs/arm64-v8a/libsam.so
+ ```
+3. Connect your Android device via USB (verify connection with `adb devices`).
+4. Run the app:
+ ```bash
+ cd mobile/sam-node-app
+ flutter run
+ ```
+
+---
+
+## Integration Testing (E2E)
+
+We automate end-to-end integration verification in the CI by running a headless Android Emulator and executing bidirectional MCP discovery:
+
+### Local Execution of E2E Script
+If you have an active emulator running locally, you can run the full E2E orchestration test:
+```bash
+./mobile/mobile_e2e.sh
+```
+
+#### What the E2E test validates:
+1. Starts a local **Mock OIDC Server** and **sam-hub** process on the host.
+2. Registers a dummy tool (`host-tool`) on a host-level **sam-node**.
+3. Boots the **Android Emulator**, installs the FFI-embedded app, and starts the node inside the emulator.
+4. Registers an `emulator-tool` inside the emulator app.
+5. Asserts **bidirectional discovery**:
+ - The emulator app successfully discovers the host's `host-tool` via the mesh.
+ - The host node successfully discovers the emulator's `emulator-tool` via the mesh.
+6. Terminates all background processes and cleans up directories on completion.