Fold network cards and show which peer carries exit traffic

Start the tray and Android overviews with each network folded under its
bold name. Keep the selected exit, its host name and its sent and received
byte totals visible. Put VIP beside Copy secret and Show devices.

Default to bytes and make the unit switch update the desktop traffic
column, totals, rates and plots together. Open the devices window at
1000 points wide and bound the network and per-peer plots. Use both sides
of the phone detail view for transport, latency, version and traffic.

Attach counters to the current network and exit peer. Count off-mesh IP
bytes after carrier acceptance and replies after local interface delivery.
Changing the selection starts new totals. Ordinary mesh traffic to the
same peer and rejected packets stay out of the exit counters.

Advertise the agent release as an optional bounded trailer on an
authenticated control v8 announcement. Older readers can ignore it and
older peers display an unknown version. Release labels live for the
session and do not participate in authentication or wire negotiation.
The new status fields require local IPC v25, so update the daemon, CLI
and tray together. Existing mesh identities and databases need no migration.

On Android, request system interface consent on the first app launch.
Respect an explicit stop or declined consent across launches. Start
Tsunagi Agent re-enables automatic startup.

Checked formatting and strict workspace Clippy on macOS arm64. The full
locked workspace suite passed 588 tests with four opt-in tests ignored.
Built the tray and Android debug APKs. Both instrumentation tests passed
on an Android 37 arm64 emulator, including app startup, stop and restart.
Checked the first-run permission prompt and the rendered phone and desktop
layouts. Native Linux and Windows tests were not run on this host.
This commit is contained in:
Aleksandr Bogomiakov committed 2026-11-25 14:33:50 +02:00
1 parent f9f67f88b1
commit 8c4c2fa34e
39 files changed
+1144 -412

No files matched your search

+2 -2
View File
@@ -16,7 +16,7 @@ cd android
adb install -r app/build/outputs/apk/debug/app-debug.apk
```
Open **tsunagi**, tap **Start VPN**, accept Android’s VPN prompt, then join with the existing network name and secret. Android keeps the established VPN service bound when the activity closes. **About → Stop VPN** disconnects it. The app-private state directory holds the device identity and its saved networks.
Open **tsunagi** to start the agent. On first launch, accept Android’s VPN permission prompt so the agent can create its mesh interface. Join with the existing network name and secret. The service continues when the activity closes. **About → Stop Tsunagi Agent** keeps it stopped across launches. After stopping or declining consent, tap **Start Tsunagi Agent** to enable automatic startup again. The app-private state directory holds the device identity and its saved networks.
The Rust agent owns one interface across the active networks. The Android service establishes the TUN and supplies its descriptor when addresses or exit routes change. Discovery and transport sockets use the selected physical network. TCP health checks bind to the VPN and the address of their own mesh network. The per-network transport selector offers `wg`, `awg`, `wg-quic` and `tcp-tls` in the same default order as the desktop. Each network retains its saved selection and priority. An advertised remote exit can carry the phone’s IPv4 internet traffic.
@@ -26,7 +26,7 @@ Applications using Android’s system resolver can connect to `<member>.<network
The tray and Android use the same egui network tiles, join form, device list, VIP editor and live traffic diagram from `crates/tsunagi-ui`. On Android, the Rust activity view opens each form in the current viewport. Kotlin handles the service, connectivity, rendering surface, input and clipboard.
Open **Exit node…** on a network tile to compare remote gateways by measured data RTT and data path. Tap a row and confirm to route IPv4 internet traffic through it. The selected exit has an ongoing notification, including when the peer is offline. **Disconnect exit node** restores the ordinary internet route and keeps mesh access and DNS active. Mesh-only mode has no persistent app notification. Android controls the system VPN indicator. Android 13 and later request notification permission for the exit notice. Starting with Android 14, an unlocked device allows an individual swipe to dismiss an ongoing VPN notification. [Android notification behavior](https://developer.android.com/about/versions/14/behavior-changes-all#non-dismissable-notifications)
Tap the network name to expand its card, then open **Exit node…** to compare remote gateways by measured data RTT and data path. Tap a row and confirm to route IPv4 internet traffic through it. The selected exit has an ongoing notification, including when the peer is offline. **Disconnect exit node** restores the ordinary internet route and keeps mesh access and DNS active. Mesh-only mode has no persistent app notification. Android controls the system VPN indicator. Android 13 and later request notification permission for the exit notice. Starting with Android 14, an unlocked device allows an individual swipe to dismiss an ongoing VPN notification. [Android notification behavior](https://developer.android.com/about/versions/14/behavior-changes-all#non-dismissable-notifications)
## Check two networks on an emulator
@@ -0,0 +1,51 @@
package cy.hexor.tsunagi
import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.net.VpnService
import android.os.SystemClock
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Test
class AgentStartupTest {
@Suppress("DEPRECATION")
@Test fun launchStartsAgentAndExplicitStopSurvivesReopening() {
val test = InstrumentationRegistry.getInstrumentation()
val context = test.targetContext
check(VpnService.prepare(context) == null) { "Grant VPN consent on the test emulator first" }
val manager = context.getSystemService(ActivityManager::class.java)
fun running() = manager.getRunningServices(Int.MAX_VALUE).any {
it.service.className == MeshVpn::class.java.name && it.started
}
fun awaitRunning(expected: Boolean) {
val deadline = SystemClock.elapsedRealtime() + 5000
while (running() != expected) {
check(SystemClock.elapsedRealtime() < deadline) { "Agent did not reach started=$expected" }
SystemClock.sleep(25)
}
}
fun launch() = test.startActivitySync(Intent(context, MainActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) as MainActivity
val settings = context.getSharedPreferences("agent", Context.MODE_PRIVATE)
val old = settings.getBoolean("auto_start", true)
var activity: MainActivity? = null
try {
settings.edit().remove("auto_start").commit()
activity = launch()
awaitRunning(true)
test.runOnMainSync { activity!!.stopAgent(); activity!!.finish() }
awaitRunning(false)
activity = launch()
test.waitForIdleSync()
check(!running())
test.runOnMainSync { activity!!.requestAgent() }
awaitRunning(true)
} finally {
test.runOnMainSync { activity?.stopAgent(); activity?.finish() }
awaitRunning(false)
settings.edit().putBoolean("auto_start", old).commit()
}
}
}
@@ -9,6 +9,9 @@ import android.view.WindowInsets
import android.widget.FrameLayout
class MainActivity : Activity() {
private val settings by lazy { getSharedPreferences("agent", MODE_PRIVATE) }
private var checkedAutoStart = false
private var consentPending = false
private var askedForNotifications = false
internal fun requestExitNotifications() {
if (Build.VERSION.SDK_INT >= 33 && !askedForNotifications &&
@@ -20,6 +23,7 @@ class MainActivity : Activity() {
private lateinit var surface: MeshSurface
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
consentPending = savedInstanceState?.getBoolean("consent_pending") == true
surface = MeshSurface(this)
val root = FrameLayout(this)
if (Build.VERSION.SDK_INT >= 30) {
@@ -33,17 +37,43 @@ class MainActivity : Activity() {
root.addView(surface)
setContentView(root)
}
internal fun requestVpn() {
override fun onPostResume() {
super.onPostResume()
if (checkedAutoStart) return
checkedAutoStart = true
if (!MeshVpn.started && settings.getBoolean("auto_start", true)) requestAgent()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putBoolean("consent_pending", consentPending)
}
internal fun requestAgent() {
if (consentPending) return
val consent = VpnService.prepare(this)
if (consent == null) startForegroundService(Intent(this, MeshVpn::class.java))
else startActivityForResult(consent, 1)
if (consent == null) startAgent() else {
consentPending = true
startActivityForResult(consent, 1)
}
}
private fun startAgent() {
settings.edit().putBoolean("auto_start", true).apply()
val service = Intent(this, MeshVpn::class.java)
// A retry of an existing service may already have left foreground mode.
if (MeshVpn.started) startService(service) else startForegroundService(service)
}
internal fun stopAgent() {
settings.edit().putBoolean("auto_start", false).apply()
startService(Intent(this, MeshVpn::class.java).setAction(MeshVpn.STOP_VPN))
}
@Deprecated("Platform consent result")
override fun onActivityResult(request: Int, result: Int, data: Intent?) {
super.onActivityResult(request, result, data)
if (request == 1) {
if (result == RESULT_OK) startForegroundService(Intent(this, MeshVpn::class.java))
else surface.input(5, "VPN permission was declined")
consentPending = false
if (result == RESULT_OK) startAgent() else {
settings.edit().putBoolean("auto_start", false).apply()
surface.input(5, "Android VPN permission was declined")
}
}
}
@Deprecated("Forward system Back to the current Rust view")
@@ -34,7 +34,7 @@ class MeshSurface(private val activity: MainActivity) : GLSurfaceView(activity),
override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) = Native.surface()
override fun onSurfaceChanged(gl: GL10?, w: Int, h: Int) { widthPx = w; heightPx = h }
override fun onDrawFrame(gl: GL10?) {
val delay = Native.draw(this, widthPx, heightPx, density)
val delay = Native.draw(this, widthPx, heightPx, density, MeshVpn.started)
removeCallbacks(repaint)
postDelayed(repaint, delay.coerceAtLeast(16))
}
@@ -58,8 +58,8 @@ class MeshSurface(private val activity: MainActivity) : GLSurfaceView(activity),
return true
}
fun startVpn() { post { activity.requestVpn() } }
fun stopVpn() { post { activity.startService(Intent(activity, MeshVpn::class.java).setAction(MeshVpn.STOP_VPN)) } }
fun startAgent() { post { activity.requestAgent() } }
fun stopAgent() { post { activity.stopAgent() } }
fun requestExitNotifications() { post { activity.requestExitNotifications() } }
fun closeScreen() { post { activity.finish() } }
fun openUrl(url: String) { post {
@@ -27,6 +27,8 @@ class MeshVpn : VpnService() {
private const val DISCONNECT_EXIT = "cy.hexor.tsunagi.DISCONNECT_EXIT"
private const val NOTIFICATION_ID = 1
private const val EXIT_CHANNEL = "exit-node"
@Volatile var started = false
private set
}
private val main = Handler(Looper.getMainLooper())
private val notifications by lazy { getSystemService(NotificationManager::class.java) }
@@ -34,7 +36,6 @@ class MeshVpn : VpnService() {
private var closed = false
private val connectivity by lazy { getSystemService(ConnectivityManager::class.java) }
@Volatile private var upstream: Network? = null
private var watching = false
private val changes = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) = useUnderlay(network)
override fun onLinkPropertiesChanged(network: Network, properties: LinkProperties) {
@@ -77,15 +78,15 @@ class MeshVpn : VpnService() {
STOP_VPN -> { shutdown(); stopSelf(startId); return START_NOT_STICKY }
DISCONNECT_EXIT -> {
val ids = intent.data?.pathSegments.orEmpty()
if (watching && ids.size == 2 && intent.getLongExtra("instance", 0) == instance) {
if (started && ids.size == 2 && intent.getLongExtra("instance", 0) == instance) {
if (!Native.disconnectExit(instance, ids[0], ids[1])) {
android.widget.Toast.makeText(this, "Exit node is busy. Try again.", android.widget.Toast.LENGTH_SHORT).show()
}
} else if (!watching) stopSelf(startId)
} else if (!started) stopSelf(startId)
return START_NOT_STICKY
}
}
if (watching) {
if (started) {
if (Native.failed(instance)) {
Native.stop(instance)
instance = 0
@@ -93,12 +94,13 @@ class MeshVpn : VpnService() {
}
return START_NOT_STICKY
}
notifications.createNotificationChannel(NotificationChannel("vpn", "VPN", NotificationManager.IMPORTANCE_LOW))
closed = false
notifications.createNotificationChannel(NotificationChannel("vpn", "Tsunagi Agent", NotificationManager.IMPORTANCE_LOW))
notifications.createNotificationChannel(NotificationChannel(EXIT_CHANNEL, "Exit node", NotificationManager.IMPORTANCE_LOW))
val startup = notification("vpn").setContentTitle("Starting mesh VPN")
val startup = notification("vpn").setContentTitle("Starting Tsunagi Agent")
if (Build.VERSION.SDK_INT >= 31) startup.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_DEFERRED)
startForeground(NOTIFICATION_ID, startup.build())
watching = true
started = true
connectivity.requestNetwork(NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN).build(), changes, Handler(Looper.getMainLooper()))
@@ -189,8 +191,12 @@ class MeshVpn : VpnService() {
@Synchronized private fun shutdown() {
if (closed) return
closed = true
if (watching) connectivity.unregisterNetworkCallback(changes)
if (started) connectivity.unregisterNetworkCallback(changes)
started = false
if (instance != 0L) Native.stop(instance)
instance = 0L
upstream = null
physicalAddresses = ""
connectivity.bindProcessToNetwork(null)
stopForeground(STOP_FOREGROUND_REMOVE)
}
@@ -13,7 +13,7 @@ internal object Native {
external fun networkChanged(instance: Long, addresses: String)
external fun surface()
external fun draw(host: MeshSurface, width: Int, height: Int, density: Float): Long
external fun draw(host: MeshSurface, width: Int, height: Int, density: Float, serviceStarted: Boolean): Long
external fun touch(action: Int, id: Int, x: Float, y: Float)
external fun input(kind: Int, value: String)
external fun key(key: Int)