Modern Apps git

← Modern-Apps.git

share: receive in the background via notifications and a Quick Settings tile

Commit
0522c426bf7e3e026d8cb4ce23905ef2798df494
Author
vayun-mathur <[email protected]>
When
2026-08-20 01:40 UTC (3 months ago)
Parents
b0e7b7d

Diff

share/PROTOCOL_CONTRACT.md
diff --git a/share/PROTOCOL_CONTRACT.md b/share/PROTOCOL_CONTRACT.mdindex e2bb209eb6..3297c96701 100644--- a/share/PROTOCOL_CONTRACT.md+++ b/share/PROTOCOL_CONTRACT.md@@ -144,7 +144,7 @@ Errors are returned as negative `int` codes from the `native* -> int` methods; a | 0 | `Handshaking`     | `CONNECTION_REQUEST`/`RESPONSE`, UKEY2, and the paired-key exchange are in progress; keep pumping bytes. | | 1 | `AwaitingAccept`  | An `INTRODUCTION` decoded; the UI should surface `queryPendingFiles` and prompt Accept/Reject. | | 2 | `Transferring`    | Accepted; payload bytes are flowing (`openFile`/`writeChunk`/`closeFile`). |-| 3 | `Completed`       | Every announced payload arrived. |+| 3 | `Completed`       | Receiving: every announced payload arrived. Sending: every payload the `INTRODUCTION` announced has had its `FLAG_LAST` chunk written. | | 4 | `Failed`          | Protocol failure, peer rejection, or local rejection. |  ## 5. JNI surface (exact signatures)@@ -168,6 +168,8 @@ internal object ShareNative {   external fun nativeCloseFile(handle: Long): Int   external fun nativeDrainReceived(handle: Long): ByteArray?    // one §6 record, null = none   external fun nativeQueryFailureReason(handle: Long): String?  // null = healthy+  external fun nativeQueryPeerName(handle: Long): String?       // null until CONNECTION_REQUEST is read+  external fun nativeQueryTrace(handle: Long): String?          // recent protocol events, one per line   external fun nativeDestroy(handle: Long)                           // void    // Discovery — derived in ble_adv.rs from SHA-256("NearbySharing"). Pure functions.
share/src/main/AndroidManifest.xml
diff --git a/share/src/main/AndroidManifest.xml b/share/src/main/AndroidManifest.xmlindex 1791e5bdc6..0ac7f88516 100644--- a/share/src/main/AndroidManifest.xml+++ b/share/src/main/AndroidManifest.xml@@ -12,29 +12,36 @@          and transfer both depend on it. -->     <uses-permission android:name="android.permission.ACCESS_LOCAL_NETWORK" /> -    <!-- BLE discovery (Nearby Connections uses BLE for advertisement + scan) -->-    <uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />-    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />+    <!-- BLE discovery (Nearby Connections uses BLE for advertisement + scan).+         No BLUETOOTH_CONNECT: the peer's name comes from the endpoint-info blob inside the+         advertisement, falling back to ScanRecord.getDeviceName(), and both are parsed from+         bytes we already have. BluetoothDevice.getName() is the only API here that would need+         CONNECT, and it reports the same advertised local name.+         No location permission either: minSdk is 31, so neverForLocation on BLUETOOTH_SCAN is+         the whole story — the pre-Android-12 classic-scan fallback that used to require+         ACCESS_FINE_LOCATION cannot be reached. -->     <uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />     <uses-permission android:name="android.permission.BLUETOOTH_SCAN" android:usesPermissionFlags="neverForLocation" />-    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />-    <!-- BLE scan is location-free (neverForLocation above), but ACCESS_FINE_LOCATION-         is still needed on Android < 12 when the BLE stack falls back to classic scan. -->-    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />-    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> -    <!-- Stay discoverable/receivable in background -->+    <!-- Stay discoverable/receivable in background. NOT dataSync: Android 15 caps+         dataSync foreground services at 6 cumulative hours per 24h and then calls+         onTimeout() and stops the service, which for an always-on receiver means it+         silently stops being receivable part-way through the day (see :vpn's manifest for+         the same reasoning). connectedDevice is semantically accurate — BLE advertising+         plus a local peer link — is not capped, and is not on Android 13/14's list of+         types a BOOT_COMPLETED receiver may not start. -->     <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />-    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />+    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" />     <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />+    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />      <!-- Nearby Share over Wi-Fi Direct / Hotspot uses nearby-devices on Android 13+ -->     <uses-permission android:name="android.permission.NEARBY_WIFI_DEVICES" android:usesPermissionFlags="neverForLocation" /> -    <!-- Reading files chosen in the send flow -->-    <uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />-    <uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />-    <uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />+    <!-- Deliberately NO storage or media permissions. Files to send are picked with+         ACTION_OPEN_DOCUMENT and files are saved with ACTION_CREATE_DOCUMENT, both of which+         grant access to exactly the URI the user chose. Received files are staged in+         app-private storage and handed out through the FileProvider below. -->      <uses-feature android:name="android.hardware.bluetooth" android:required="false" />     <uses-feature android:name="android.hardware.bluetooth_le" android:required="false" />@@ -71,11 +78,51 @@             </intent-filter>         </activity> +        <!-- Transparent trampoline for the Save action's SAF directory picker: an+             ActivityResultLauncher needs an Activity and there is no receive screen left.+             Deliberately NOT noHistory: that finishes the activity as soon as it stops being+             visible, which is exactly what launching the picker does, so the result callback+             would be dropped. excludeFromRecents gives the invisibility without the hazard. -->+        <activity+            android:name=".platform.receive.ShareSaveActivity"+            android:excludeFromRecents="true"+            android:exported="false"+            android:theme="@android:style/Theme.Translucent.NoTitleBar" />+         <!-- Keep receiving / transferring while backgrounded. -->         <service             android:name=".platform.transfer.ShareTransferService"             android:exported="false"-            android:foregroundServiceType="dataSync" />+            android:foregroundServiceType="connectedDevice" />++        <!-- The only on/off control for receiving. -->+        <service+            android:name=".platform.receive.ShareReceiveTileService"+            android:exported="true"+            android:icon="@drawable/ic_tile_share"+            android:label="@string/share_tile_label"+            android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">+            <intent-filter>+                <action android:name="android.service.quicksettings.action.QS_TILE" />+            </intent-filter>+            <meta-data+                android:name="android.service.quicksettings.ACTIVITY"+                android:value=".MainActivity" />+        </service>++        <!-- Accept / Reject / Cancel from a notification. Explicit component only. -->+        <receiver+            android:name=".platform.receive.ShareNotificationReceiver"+            android:exported="false" />++        <receiver+            android:name=".platform.receive.ShareBootReceiver"+            android:exported="false">+            <intent-filter>+                <action android:name="android.intent.action.BOOT_COMPLETED" />+                <action android:name="android.intent.action.MY_PACKAGE_REPLACED" />+            </intent-filter>+        </receiver>         <!-- Grants read access to a received file when the user taps Share. -->         <provider             android:name="androidx.core.content.FileProvider"
share/src/main/java/com/vayunmathur/share/Navigation.kt
diff --git a/share/src/main/java/com/vayunmathur/share/Navigation.kt b/share/src/main/java/com/vayunmathur/share/Navigation.ktindex e98d8e0224..69a4a96be3 100644--- a/share/src/main/java/com/vayunmathur/share/Navigation.kt+++ b/share/src/main/java/com/vayunmathur/share/Navigation.kt@@ -3,26 +3,14 @@ package com.vayunmathur.share import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable-import androidx.compose.runtime.LaunchedEffect-import androidx.compose.runtime.collectAsState-import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.remember-import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import com.vayunmathur.library.ui.AppScaffold-import com.vayunmathur.library.ui.Tab-import com.vayunmathur.library.ui.TabRow-import com.vayunmathur.library.ui.Text import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.rememberNavBackStack import com.vayunmathur.share.platform.ShareViewModel-import com.vayunmathur.share.ui.ShareReceiveScreen import com.vayunmathur.share.ui.ShareSendScreen -private enum class ShareTab { Receive, Send }- @Composable fun Navigation(viewModel: ShareViewModel) {     val backStack = rememberNavBackStack<Route>(Route.Share)@@ -33,23 +21,18 @@ fun Navigation(viewModel: ShareViewModel) {     } } +/**+ * The whole in-app surface: sending.+ *+ * Receiving has no screen. It is driven by notifications and turned on and off from a Quick+ * Settings tile, so it works when the app has never been opened.+ */ @Composable private fun ShareApp(viewModel: ShareViewModel) {-    var currentTab by remember { mutableStateOf(ShareTab.Receive) }-    val outgoing by viewModel.outgoingUris.collectAsState()-    LaunchedEffect(outgoing) {-        if (outgoing.isNotEmpty()) currentTab = ShareTab.Send-    }     AppScaffold(title = stringResource(R.string.app_name)) { padding ->-        androidx.compose.foundation.layout.Column(modifier = Modifier.fillMaxSize().padding(padding)) {-            TabRow(selectedTabIndex = currentTab.ordinal) {-                Tab(selected = currentTab == ShareTab.Receive, onClick = { currentTab = ShareTab.Receive }, text = { Text(stringResource(R.string.tab_receive)) })-                Tab(selected = currentTab == ShareTab.Send, onClick = { currentTab = ShareTab.Send }, text = { Text(stringResource(R.string.tab_send)) })-            }-            when (currentTab) {-                ShareTab.Receive -> ShareReceiveScreen(viewModel = viewModel, modifier = Modifier.fillMaxSize())-                ShareTab.Send -> ShareSendScreen(viewModel = viewModel, modifier = Modifier.fillMaxSize())-            }-        }+        ShareSendScreen(+            viewModel = viewModel,+            modifier = Modifier.fillMaxSize().padding(padding),+        )     }-}\ No newline at end of file+}
share/src/main/java/com/vayunmathur/share/domain/protocol/ShareSession.kt
diff --git a/share/src/main/java/com/vayunmathur/share/domain/protocol/ShareSession.kt b/share/src/main/java/com/vayunmathur/share/domain/protocol/ShareSession.ktindex 78c2652636..e032f2d345 100644--- a/share/src/main/java/com/vayunmathur/share/domain/protocol/ShareSession.kt+++ b/share/src/main/java/com/vayunmathur/share/domain/protocol/ShareSession.kt@@ -144,6 +144,14 @@ class ShareSession @JvmOverloads constructor(      */     val failureReason: String? get() = ShareNative.nativeQueryFailureReason(handle) +    /**+     * The peer's advertised device name, or null until its `CONNECTION_REQUEST` has been read.+     *+     * This is what a notification should be titled with: `host:port` means nothing to+     * someone deciding whether to accept a transfer.+     */+    val peerName: String? get() = ShareNative.nativeQueryPeerName(handle)+     /**      * Recent protocol events, one per line, for diagnosing a peer that stops responding.      */
share/src/main/java/com/vayunmathur/share/network/transport/TcpTransport.kt
diff --git a/share/src/main/java/com/vayunmathur/share/network/transport/TcpTransport.kt b/share/src/main/java/com/vayunmathur/share/network/transport/TcpTransport.ktindex 81e48899c3..bd7e0a8f7d 100644--- a/share/src/main/java/com/vayunmathur/share/network/transport/TcpTransport.kt+++ b/share/src/main/java/com/vayunmathur/share/network/transport/TcpTransport.kt@@ -17,10 +17,18 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel+import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.flow.flatMapLatest+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.flow.map+import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.withContext@@ -75,6 +83,10 @@ private const val KEEP_ALIVE_EVERY_MS = 5_000L  *  * Each peer gets its own [ShareSession] (handle lifetime owns the Rust session). The  * session's role follows the socket: the side that dialled is the initiator.+ *+ * Connections are keyed by [Connection.sessionHandle], the only identity that survives a+ * `PendingIntent`: a notification action cannot carry a [Connection], which wraps a live+ * socket and a native handle.  */ class TcpTransport(     localName: String,@@ -106,19 +118,35 @@ class TcpTransport(     private val _listenPort = MutableStateFlow<Int?>(null)     val listenPort: StateFlow<Int?> = _listenPort.asStateFlow() -    private val _incomingConnections = MutableStateFlow<List<Connection>>(emptyList())-    val incomingConnections: StateFlow<List<Connection>> = _incomingConnections.asStateFlow()+    private val _connections = MutableStateFlow<List<Connection>>(emptyList())++    /** Every live session, inbound and outbound. */+    val connections: StateFlow<List<Connection>> = _connections.asStateFlow() -    /** Active session pumps, keyed by handle for teardown tracking. */-    private val connections = mutableListOf<Connection>()+    /**+     * Only the sessions a peer dialled *us* on.+     *+     * An outgoing transfer used to appear here too, so sending a file to someone raised an+     * "incoming request" against ourselves.+     */+    val incomingConnections: StateFlow<List<Connection>> = _connections+        .map { conns -> conns.filter { it.incoming } }+        .stateIn(scope, SharingStarted.Eagerly, emptyList())++    /** Active session pumps, keyed by native session handle. */+    private val byHandle = mutableMapOf<Long, Connection>()     private val connectionsLock = Any()      private fun publishConnections() {         synchronized(connectionsLock) {-            _incomingConnections.value = connections.toList()+            _connections.value = byHandle.values.toList()         }     } +    /** The live connection for [handle], or null once its session is gone. */+    fun connectionFor(handle: Long): Connection? =+        synchronized(connectionsLock) { byHandle[handle] }+     // ------------------------------------------------------------------     // Server (Receive)     // ------------------------------------------------------------------@@ -195,7 +223,7 @@ class TcpTransport(             incoming = incoming,             remoteEndpoint = "${socket.inetAddress.hostAddress}:${socket.port}",         )-        synchronized(connectionsLock) { connections += conn }+        synchronized(connectionsLock) { byHandle[session.handle] = conn }         publishConnections()         conn.pumpJob = scope.launch {             pump(conn)@@ -212,9 +240,8 @@ class TcpTransport(         val socket = conn.socket         try {             // Flush any initial outbound (e.g. UKEY2 ClientInit) before the first read.-            drainAll(session, socket.getOutputStream())+            drainAll(conn)             val input = socket.getInputStream()-            val output = socket.getOutputStream()             val buf = ByteArray(8192)             socket.soTimeout = PUMP_READ_TIMEOUT_MS             var lastKeepAlive = System.currentTimeMillis()@@ -222,8 +249,10 @@ class TcpTransport(                 val now = System.currentTimeMillis()                 if (now - lastKeepAlive < KEEP_ALIVE_EVERY_MS) return                 lastKeepAlive = now-                session.sendKeepAlive()-                drainAll(session, output)+                synchronized(conn.writeLock) {+                    session.sendKeepAlive()+                    drainAll(conn)+                }             }             while (isActive && !socket.isClosed) {                 val n: Int = try {@@ -232,9 +261,9 @@ class TcpTransport(                     // Periodic keep-alive: drain outbound even on read timeout so                     // handshake retries / accept responses still flush.                     keepAliveIfDue()-                    drainAll(session, output)+                    drainAll(conn)                     conn.updateStateFromSession()-                    if (conn.state.value == ShareState.Failed || conn.state.value == ShareState.Completed) break+                    if (conn.state.value.isTerminal) break                     continue                 }                 if (n == -1) {@@ -243,8 +272,6 @@ class TcpTransport(                 }                 if (n == 0) continue                 val inbound = buf.copyOf(n)-                Log.d(TAG, "IN  ${hexPrefix(inbound)}")-                conn.bytesReceived.value += n                 val rc = session.feedInbound(inbound)                 if (rc < 0) {                     Log.w(TAG, "feedInbound failed rc=$rc")@@ -253,10 +280,10 @@ class TcpTransport(                     break                 }                 drainReceived(conn)-                drainAll(session, output)+                drainAll(conn)                 keepAliveIfDue()                 conn.updateStateFromSession()-                if (conn.state.value == ShareState.Completed || conn.state.value == ShareState.Failed) break+                if (conn.state.value.isTerminal) break             }         } catch (e: Exception) {             if (isActive) Log.w(TAG, "pump error for ${conn.remoteEndpoint}", e)@@ -269,7 +296,7 @@ class TcpTransport(             // Graceful shutdown: one last drain in each direction.             drainReceived(conn)             try {-                drainAll(session, socket.getOutputStream())+                drainAll(conn)             } catch (_: Exception) {             }             try {@@ -292,6 +319,10 @@ class TcpTransport(         val session = conn.session         while (true) {             val chunk = session.drainReceived() ?: return+            // Decrypted payload bytes, which is the only count comparable to the file sizes the+            // peer announced. Raw socket bytes include the UKEY2 handshake, frame prefixes,+            // encryption overhead and keep-alives, so a percentage built on them overshoots.+            conn.bytesReceived.value += chunk.body.size             val finished = receivedStore.append(session.handle, chunk) ?: continue             val announcedMime = conn.pendingFiles.value                 .firstOrNull { it.name == chunk.name }@@ -307,28 +338,41 @@ class TcpTransport(         }     } -    /** TEMP DIAGNOSTIC: hex of a frame prefix, for comparing our SecureMessage headers to the peer's. */-    private fun hexPrefix(bytes: ByteArray, n: Int = 96): String =-        bytes.take(n).joinToString("") { "%02x".format(it) } +-            if (bytes.size > n) "…(${bytes.size}B)" else "(${bytes.size}B)"--    private fun drainAll(session: ShareSession, out: OutputStream) {-        while (true) {-            val bytes = session.drainOutbound() ?: break-            Log.d(TAG, "OUT ${hexPrefix(bytes)}")-            // Rust already applied the 4-byte big-endian length prefix to each frame and-            // concatenated them; write verbatim per PROTOCOL_CONTRACT.md §6.-            out.write(bytes)-            out.flush()+    /**+     * Write everything Rust has queued, holding [Connection.writeLock] for the whole batch.+     *+     * The lock is the fix for two threads writing one socket: `sendFiles` runs on the+     * caller's coroutine while [pump] runs on this transport's scope, and both drain. Rust's+     * own state is mutex-protected, but two interleaved `OutputStream.write` calls put half+     * of one frame batch inside another, which the peer reads as a corrupt frame.+     *+     * A JVM monitor rather than a `kotlinx` `Mutex` because every caller is already doing+     * blocking socket I/O, and because this must also be callable from [pump]'s `finally`,+     * where suspending after cancellation is not allowed. It is reentrant, so a caller that+     * already holds it (see `keepAliveIfDue`) is safe.+     */+    private fun drainAll(conn: Connection) {+        synchronized(conn.writeLock) {+            val out: OutputStream = conn.socket.getOutputStream()+            while (true) {+                val bytes = conn.session.drainOutbound() ?: break+                // Rust already applied the 4-byte big-endian length prefix to each frame and+                // concatenated them; write verbatim per PROTOCOL_CONTRACT.md §6.+                out.write(bytes)+                out.flush()+            }         }     }      private fun Connection.updateStateFromSession() {         val polled = session.state         state.value = polled+        if (peerName.value == null) session.peerName?.let { peerName.value = it }         // Pending files may become available asynchronously once Introduction decodes.         if (polled == ShareState.AwaitingAccept || polled == ShareState.Transferring) {-            pendingFiles.value = session.pendingFiles+            val files = session.pendingFiles+            pendingFiles.value = files+            if (incoming) expectedTotalBytes.value = files.sumOf { it.sizeBytes }         }         if (polled == ShareState.Failed) {             if (error.value == null) error.value = session.failureReason ?: "Transfer failed"@@ -337,7 +381,22 @@ class TcpTransport(     }      suspend fun disconnect(conn: Connection) {-        conn.pumpJob?.cancel()+        // Joined, not just cancelled: the pump's `finally` still drains and polls the session,+        // so destroying it from under a pump that has not finished unwinding would have those+        // calls operate on a handle that no longer exists.+        conn.pumpJob?.cancelAndJoin()+        retire(conn)+    }++    /**+     * Release everything behind [conn] and drop it from [connections].+     *+     * Safe to call once the pump has stopped. Incoming sessions are retired by+     * `ShareReceiveNotifier` after it posts their terminal notification, because nothing else+     * ever disconnects them and both the `Connection` and its native session would otherwise+     * accumulate for the life of the process.+     */+    fun retire(conn: Connection) {         try {             conn.socket.close()         } catch (_: Exception) {@@ -347,14 +406,49 @@ class TcpTransport(             conn.session.destroy()         } catch (_: Exception) {         }-        synchronized(connectionsLock) { connections.remove(conn) }+        synchronized(connectionsLock) { byHandle.remove(conn.session.handle) }         publishConnections()     } +    fun retire(handle: Long) {+        connectionFor(handle)?.let { retire(it) }+    }++    /**+     * Suspend until no session is still moving bytes.+     *+     * `connections` alone is not enough: it re-emits when a session appears or is retired, not+     * when one goes terminal, so the per-connection `state` flows have to be folded in.+     */+    @Suppress("OPT_IN_USAGE")+    suspend fun awaitIdle() {+        connections+            .flatMapLatest { conns ->+                if (conns.isEmpty()) flowOf(true)+                else combine(conns.map { it.state }) { states -> states.all { it.isTerminal } }+            }+            .first { it }+    }++    /**+     * Tear down the session [handle] identifies, if it is still alive.+     *+     * The handle-keyed entry point for a notification's Cancel action, which cannot carry a+     * [Connection].+     */+    suspend fun cancel(handle: Long) {+        val conn = connectionFor(handle) ?: return+        if (!conn.state.value.isTerminal) {+            conn.error.value = "cancelled"+            conn.state.value = ShareState.Failed+        }+        disconnect(conn)+    }+     fun release() {         stopListening()         synchronized(connectionsLock) {-            connections.forEach { c ->+            byHandle.values.forEach { c ->                 try {                     c.socket.close()                 } catch (_: Exception) {@@ -365,10 +459,10 @@ class TcpTransport(                 }                 c.pumpJob?.cancel()             }-            connections.clear()+            byHandle.clear()         }         receivedStore.closeAll()-        _incomingConnections.value = emptyList()+        _connections.value = emptyList()         scope.cancel()     } @@ -383,18 +477,33 @@ class TcpTransport(      * paired-key exchange finishes), waits for the peer to accept, then streams each      * file. The payload ids the peer sees come from the introduction, so the bytes match      * the metadata it showed the user.+     *+     * At most one `INTRODUCTION` per session: picking more files after connecting used to+     * announce a second one on the same session, which the peer has no way to reconcile+     * with the payload ids it already showed its user.      */     suspend fun sendFiles(conn: Connection, files: List<File>) = withContext(Dispatchers.IO) {+        if (files.isEmpty()) return@withContext+        if (!conn.introductionSent.compareAndSet(false, true)) {+            Log.w(TAG, "already announced files on session ${conn.sessionHandle}; ignoring ${files.size} more")+            return@withContext+        }         val session = conn.session         val staged = files.map {-            PendingFile(name = it.name, sizeBytes = it.length(), mimeType = "")+            PendingFile(+                name = it.name,+                sizeBytes = it.length(),+                // A real type, so the peer shows an image as an image rather than a document.+                mimeType = ReceivedFileStore.mimeTypeOf(it),+            )         }+        conn.expectedTotalBytes.value = staged.sumOf { it.sizeBytes }         if (session.setFilesToSend(staged) < 0 || session.queueIntroduction() < 0) {             conn.error.value = "Failed to announce files"             conn.state.value = ShareState.Failed             return@withContext         }-        drainAll(session, conn.socket.getOutputStream())+        drainAll(conn)         // Wait for the peer to accept before streaming a single chunk. Rust flips to         // Transferring when the Sharing ConnectionResponse arrives; a real device hangs up         // if payload chunks show up for a transfer its user has not accepted yet, and@@ -432,23 +541,29 @@ class TcpTransport(                     }                     conn.bytesSent.value += n                     // Flush after each chunk so the pump's next drain picks it up.-                    drainAll(session, conn.socket.getOutputStream())+                    drainAll(conn)                     conn.updateStateFromSession()                     if (conn.state.value == ShareState.Failed) break                 }             }             session.closeFile()+            drainAll(conn)+            conn.updateStateFromSession()             if (conn.state.value == ShareState.Failed) break         }     }      /**-     * Answer the peer's `INTRODUCTION`.+     * Answer the peer's `INTRODUCTION` on the session [handle] identifies.      *      * Received bytes go to app-private staging via [ReceivedFileStore], so there is no      * destination to choose here; the user picks one later, per file, with Save.+     *+     * Returns -1 when no such session exists, which is the normal outcome for a+     * notification action tapped after the process was killed.      */-    fun acceptIncoming(conn: Connection, accept: Boolean): Int {+    fun acceptIncoming(handle: Long, accept: Boolean): Int {+        val conn = connectionFor(handle) ?: return -1         val rc = conn.session.accept(accept)         if (rc < 0) {             conn.error.value = "accept failed ($rc)"@@ -457,7 +572,7 @@ class TcpTransport(         conn.updateStateFromSession()         // Flush the ACCEPT outbound immediately.         try {-            drainAll(conn.session, conn.socket.getOutputStream())+            drainAll(conn)         } catch (e: Exception) {             Log.w(TAG, "drain after accept failed", e)         }@@ -467,6 +582,10 @@ class TcpTransport(  /**  * A single peer connection + its Rust session pump.+ *+ * [sessionHandle] is the public identity: it is a plain `Long`, so unlike a `Connection` it+ * fits in a `PendingIntent` extra, and it is already the key [ReceivedFileStore] files+ * chunks under.  */ class Connection(     val socket: Socket,@@ -474,13 +593,41 @@ class Connection(     val incoming: Boolean,     val remoteEndpoint: String, ) {+    val sessionHandle: Long get() = session.handle++    /** Serialises every write to [socket]; see `TcpTransport.drainAll`. */+    internal val writeLock = Any()++    /** Guards against announcing a second `INTRODUCTION` on one session. */+    internal val introductionSent = java.util.concurrent.atomic.AtomicBoolean(false)+     var pumpJob: Job? = null     val state: MutableStateFlow<ShareState> = MutableStateFlow(ShareState.Handshaking)     val pendingFiles: MutableStateFlow<List<PendingFile>> = MutableStateFlow(emptyList()) +    /** The peer's advertised device name, once its `CONNECTION_REQUEST` has been read. */+    val peerName: MutableStateFlow<String?> = MutableStateFlow(null)++    /**+     * Total bytes this transfer is expected to move, or 0 while unknown.+     *+     * Announced by the peer's `INTRODUCTION` when receiving and by our own when sending, so+     * a percentage is computable without the caller summing file sizes itself.+     */+    val expectedTotalBytes: MutableStateFlow<Long> = MutableStateFlow(0L)+     /** Files that finished arriving, each staged in app-private storage. */     val receivedFiles: MutableStateFlow<List<ReceivedFile>> = MutableStateFlow(emptyList())     val bytesSent: MutableStateFlow<Long> = MutableStateFlow(0L)++    /** Decrypted payload bytes received, comparable to [expectedTotalBytes]. */     val bytesReceived: MutableStateFlow<Long> = MutableStateFlow(0L)     val error: MutableStateFlow<String?> = MutableStateFlow(null)++    /** A name to show a human: the peer's own, falling back to its address. */+    val displayName: String get() = peerName.value ?: remoteEndpoint }++/** No further frames will flow: the pump can stop and a terminal notification is due. */+val ShareState.isTerminal: Boolean+    get() = this == ShareState.Completed || this == ShareState.Failed
share/src/main/java/com/vayunmathur/share/platform/ReceivedFileStore.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/ReceivedFileStore.kt b/share/src/main/java/com/vayunmathur/share/platform/ReceivedFileStore.ktindex cd30227918..7c58767028 100644--- a/share/src/main/java/com/vayunmathur/share/platform/ReceivedFileStore.kt+++ b/share/src/main/java/com/vayunmathur/share/platform/ReceivedFileStore.kt@@ -92,6 +92,25 @@ class ReceivedFileStore(private val context: Context) {         }     } +    /**+     * Delete staged files older than [maxAgeMillis].+     *+     * Cold-start recovery: nothing else survives process death — sockets, native handles and+     * the open-stream map all go — but the half-written files do, and no [ReceivedFile] was+     * ever published for them, so nothing can reach them again. Age-based rather than+     * delete-everything because a completed file the user has not saved yet is still theirs.+     *+     * Returns how many files were removed.+     */+    fun gcOrphans(maxAgeMillis: Long): Int {+        val cutoff = System.currentTimeMillis() - maxAgeMillis+        val stillOpen = synchronized(lock) { open.values.map { it.file.absolutePath }.toSet() }+        return dir.listFiles()+            ?.filter { it.isFile && it.lastModified() < cutoff && it.absolutePath !in stillOpen }+            ?.count { it.delete() }+            ?: 0+    }+     /**      * A content URI another app can read, granted per-intent.      *@@ -110,9 +129,20 @@ class ReceivedFileStore(private val context: Context) {      companion object {         /** MIME type for [file] from its extension, for the share chooser. */-        fun mimeTypeOf(file: File): String =-            MimeTypeMap.getSingleton().getMimeTypeFromExtension(file.extension.lowercase())+        fun mimeTypeOf(file: File): String = mimeTypeOf(file.name)++        /**+         * MIME type for a file [name] from its extension.+         *+         * The name overload is what the send path needs: it announces types for files it has+         * only staged a copy of, and `""` made every image and video arrive at the peer as a+         * generic document.+         */+        fun mimeTypeOf(name: String): String {+            val ext = name.substringAfterLast('.', "").lowercase()+            return MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext)                 ?: "application/octet-stream"+        }          /** `report.pdf` -> `report_1.pdf` when the name is taken. */         fun uniqueFile(dir: File, name: String): File {
share/src/main/java/com/vayunmathur/share/platform/SharePermissions.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/SharePermissions.kt b/share/src/main/java/com/vayunmathur/share/platform/SharePermissions.ktindex 9fdec5785e..2b735d096f 100644--- a/share/src/main/java/com/vayunmathur/share/platform/SharePermissions.kt+++ b/share/src/main/java/com/vayunmathur/share/platform/SharePermissions.kt@@ -6,14 +6,24 @@ import android.os.Build /**  * Runtime permissions for the Share module (mirrors AndroidManifest.xml).  *- * Grouped so the UI can request just what it needs per flow and so- * [ShareViewModel.requestPermissionsIfNeeded] can reason about grants.+ * Deliberately short. `:share` asks for nothing it can avoid:+ *  - **no storage or media permissions** — files to send are picked with `ACTION_OPEN_DOCUMENT`+ *    and saved with `ACTION_CREATE_DOCUMENT`, each of which grants access to exactly the URI the+ *    user chose; received files live in app-private storage and leave through a `FileProvider`.+ *  - **no location** — `minSdk` is 31, so `neverForLocation` on `BLUETOOTH_SCAN` covers scanning+ *    outright; the pre-Android-12 classic-scan fallback that needed `ACCESS_FINE_LOCATION`+ *    cannot be reached.+ *  - **no `BLUETOOTH_CONNECT`** — the peer's name comes from its advertisement, never from+ *    `BluetoothDevice.getName()`.+ *+ * `POST_NOTIFICATIONS` is not optional for receiving: notifications *are* the receive UI, so+ * [com.vayunmathur.share.platform.receive.ShareReceiveTileService] refuses to turn receiving on+ * without it.  */ object SharePermissions {-    /** Needed to advertise/scan for discovery on Android 12+ (and for Quick Share visibility). */+    /** Needed to advertise for discovery (and so for Quick Share visibility). */     val BLE_ADVERTISE = Manifest.permission.BLUETOOTH_ADVERTISE     val BLE_SCAN = Manifest.permission.BLUETOOTH_SCAN-    val BLE_CONNECT = Manifest.permission.BLUETOOTH_CONNECT      /** Wi-Fi Direct / Hotspot transport (Android 13+ shows a dedicated dialog). */     val NEARBY_WIFI = Manifest.permission.NEARBY_WIFI_DEVICES@@ -27,30 +37,21 @@ object SharePermissions {     val LOCAL_NETWORK =         if (Build.VERSION.SDK_INT >= 36) Manifest.permission.ACCESS_LOCAL_NETWORK else null -    /** Foreground-service notification (Android 13+). */+    /** Foreground-service and transfer notifications (Android 13+). */     val POST_NOTIFICATIONS = if (Build.VERSION.SDK_INT >= 33) Manifest.permission.POST_NOTIFICATIONS else null -    /** BLE scan may still imply location on < S without neverForLocation flag. */-    val FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION-    val COARSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION-+    /** Scanning for peers to send to. Advertising is not needed to send. */     fun sendFlowPermissions(): Array<String> = buildList {         add(BLE_SCAN)-        add(BLE_CONNECT)         add(NEARBY_WIFI)-        add(FINE_LOCATION)-        add(COARSE_LOCATION)         LOCAL_NETWORK?.let { add(it) }         POST_NOTIFICATIONS?.let { add(it) }     }.toTypedArray() +    /** Advertising so peers can find us, plus the notifications that are the receive UI. */     fun receiveFlowPermissions(): Array<String> = buildList {         add(BLE_ADVERTISE)-        add(BLE_SCAN)-        add(BLE_CONNECT)         add(NEARBY_WIFI)-        add(FINE_LOCATION)-        add(COARSE_LOCATION)         LOCAL_NETWORK?.let { add(it) }         POST_NOTIFICATIONS?.let { add(it) }     }.toTypedArray()@@ -58,10 +59,7 @@ object SharePermissions {     fun allSharePermissions(): Array<String> = buildList {         add(BLE_ADVERTISE)         add(BLE_SCAN)-        add(BLE_CONNECT)         add(NEARBY_WIFI)-        add(FINE_LOCATION)-        add(COARSE_LOCATION)         LOCAL_NETWORK?.let { add(it) }         POST_NOTIFICATIONS?.let { add(it) }     }.toTypedArray()
share/src/main/java/com/vayunmathur/share/platform/ShareUiContract.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/ShareUiContract.kt b/share/src/main/java/com/vayunmathur/share/platform/ShareUiContract.ktindex 9c793a1650..52a0bfd5a0 100644--- a/share/src/main/java/com/vayunmathur/share/platform/ShareUiContract.kt+++ b/share/src/main/java/com/vayunmathur/share/platform/ShareUiContract.kt@@ -1,35 +1,27 @@ package com.vayunmathur.share.platform -import android.content.Context import android.net.Uri import com.vayunmathur.share.platform.discovery.NearbyDevice-import com.vayunmathur.share.domain.protocol.PendingFile-import com.vayunmathur.share.domain.protocol.ShareState import com.vayunmathur.share.network.transport.Connection  /**- * UI contract for the Share app (Receive + Send flows).+ * UI contract for the Share app.  *- * Mirrors the per-repo pattern (see FindFamilyUiContract / MapsUiContract):- * data-class UiState + actions interface with a Noop object for @Preview.+ * In-app is the **send** flow only: receiving is entirely notification-driven, controlled by a+ * Quick Settings tile, and owned by+ * [com.vayunmathur.share.platform.receive.ShareReceiveController] so it works with no Activity+ * alive.+ *+ * Mirrors the per-repo pattern (see FindFamilyUiContract / MapsUiContract): data-class UiState+ * + actions interface with a Noop object for @Preview.  */ -data class ReceiveUiState(-    val isVisible: Boolean = false,-    val localName: String = "",-    val listenPort: Int? = null,-    val incomingConnections: List<Connection> = emptyList(),-    val hasPermissions: Boolean = true,-)- data class SendUiState(     val discoveredDevices: List<NearbyDevice> = emptyList(),     val isScanning: Boolean = false,-    val selectedDevice: NearbyDevice? = null,     val outgoingUris: List<Uri> = emptyList(),     val outgoingDisplayNames: List<String> = emptyList(),     val activeConnection: Connection? = null,-    val hasPermissions: Boolean = true, )  /**@@ -45,27 +37,7 @@ data class ReceivedFile(     val uri: Uri, ) -data class TransferProgress(-    val state: ShareState,-    val pendingFiles: List<PendingFile>,-    val receivedFiles: List<ReceivedFile>,-    val bytesSent: Long,-    val bytesReceived: Long,-    val error: String?,-)--fun Connection.toProgress(): TransferProgress = TransferProgress(-    state = state.value,-    pendingFiles = pendingFiles.value,-    receivedFiles = receivedFiles.value,-    bytesSent = bytesSent.value,-    bytesReceived = bytesReceived.value,-    error = error.value,-)- interface ShareActions {-    fun setVisible(visible: Boolean)-    fun acceptIncoming(connection: Connection, accept: Boolean)     fun startScan()     fun stopScan()     fun connectToDevice(device: NearbyDevice)@@ -73,29 +45,14 @@ interface ShareActions {     fun clearOutgoing()     fun disconnect(connection: Connection) -    /**-     * Hand [file] to the system share chooser.-     *-     * Takes a [Context] because launching an Activity needs one that belongs to a task;-     * pass the composable's `LocalContext`, not an application context.-     */-    fun shareReceivedFile(context: Context, file: ReceivedFile)--    /** Copy [file] into [treeUri], a directory the user picked with `OpenDocumentTree`. */-    fun saveReceivedFile(file: ReceivedFile, treeUri: Uri)-     companion object {         val Noop = object : ShareActions {-            override fun setVisible(visible: Boolean) {}-            override fun acceptIncoming(connection: Connection, accept: Boolean) {}             override fun startScan() {}             override fun stopScan() {}             override fun connectToDevice(device: NearbyDevice) {}             override fun setOutgoingUris(uris: List<Uri>) {}             override fun clearOutgoing() {}             override fun disconnect(connection: Connection) {}-            override fun shareReceivedFile(context: Context, file: ReceivedFile) {}-            override fun saveReceivedFile(file: ReceivedFile, treeUri: Uri) {}         }     } }
share/src/main/java/com/vayunmathur/share/platform/ShareViewModel.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/ShareViewModel.kt b/share/src/main/java/com/vayunmathur/share/platform/ShareViewModel.ktindex 3f9cf3e518..4fec04deba 100644--- a/share/src/main/java/com/vayunmathur/share/platform/ShareViewModel.kt+++ b/share/src/main/java/com/vayunmathur/share/platform/ShareViewModel.kt@@ -5,27 +5,19 @@ import android.content.Context import android.content.Intent import android.net.Uri import android.os.Build-import android.provider.DocumentsContract import android.provider.OpenableColumns import android.util.Log import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope-import com.vayunmathur.library.ui.ExternalIntents import com.vayunmathur.library.util.AppMessages-import com.vayunmathur.share.BuildConfig import com.vayunmathur.share.R-import com.vayunmathur.share.platform.discovery.BleDiscoveryManager import com.vayunmathur.share.platform.discovery.DiscoverySource import com.vayunmathur.share.platform.discovery.NearbyDevice-import com.vayunmathur.share.platform.discovery.NsdDiscoveryManager-import com.vayunmathur.share.domain.protocol.PendingFile-import com.vayunmathur.share.domain.protocol.ShareState+import com.vayunmathur.share.platform.receive.ShareReceiveController import com.vayunmathur.share.platform.transfer.ShareTransferService-import com.vayunmathur.share.protocol.ShareNative import com.vayunmathur.share.network.transport.Connection-import com.vayunmathur.share.network.transport.TcpTransport import java.io.File import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job@@ -41,19 +33,17 @@ import kotlinx.coroutines.withContext private const val TAG = "ShareVM"  /**- * Single ViewModel for the Share app (Receive + Send).+ * ViewModel for the Share app's **send** flow.  *  * Everyone-mode only (no Google account, so no contact certificates):- *  - Visibility: `ServerSocket(0)` on WIFI_LAN, its port registered under- *    `_FC9F5ED42C8A._tcp` (the service type derived from `SHA-256("NearbySharing")`),- *    plus a Nearby Connections `BleAdvertisement` under GATT `0xFEF3`.- *  - Discovery: browse `_FC9F5ED42C8A._tcp` (resolves host/port) and scan `0xFEF3`, then- *    merge by endpointId. Connecting needs host/port, which only the mDNS leg supplies.+ *  - Discovery: browse `_FC9F5ED42C8A._tcp` (resolves host/port) and scan `0xFEF3`, then merge+ *    by endpointId. Connecting needs host/port, which only the mDNS leg supplies.  *- * One endpoint id and one endpoint-info blob are shared by the BLE advertisement, the mDNS- * record and `CONNECTION_REQUEST`. A peer matches the request against what it discovered,- * so a device that advertises one identity and dials out under another is hung up on- * (`p000\each.java:2092-2097`).+ * Owns no session state. The `TcpTransport` and the discovery managers come from+ * [ShareReceiveController], which outlives every Activity: one endpoint id and one+ * endpoint-info blob are shared by the BLE advertisement, the mDNS record and+ * `CONNECTION_REQUEST`, and a device that advertises one identity and dials out under another+ * is hung up on (`p000\each.java:2092-2097`).  */ class ShareViewModel(     application: Application,@@ -61,171 +51,13 @@ class ShareViewModel(      private val appContext: Context get() = getApplication() -    // --- Device identity ---+    private val nsd get() = ShareReceiveController.nsd(appContext)+    private val ble get() = ShareReceiveController.ble(appContext)+    private val transport get() = ShareReceiveController.transport(appContext) -    private val _localName = MutableStateFlow(-        Build.MODEL?.takeIf { it.isNotBlank() } ?: "My device"-    )-    val localName: StateFlow<String> = _localName.asStateFlow()+    val localName: String get() = ShareReceiveController.localName -    fun setLocalName(name: String) {-        val trimmed = name.trim().ifBlank { return }-        if (trimmed == _localName.value) return-        _localName.value = trimmed-        // The name is inside the endpoint-info blob, so renaming means re-advertising.-        if (_isVisible.value) setVisible(true)-    }--    // --- Subsystems (lazy so the VM can be constructed in previews / tests-    // without touching the framework) --------------------------------------    private val nsd by lazy { NsdDiscoveryManager(appContext) }-    private val ble by lazy { BleDiscoveryManager(appContext) }-    private val receivedStore by lazy { ReceivedFileStore(appContext) }-    // TcpTransport owns ServerSocket(0) on WIFI_LAN; NsdDiscoveryManager publishes its port.-    private val transport by lazy {-        TcpTransport(-            localName = _localName.value,-            receivedStore = receivedStore,-            localEndpointInfo = endpointInfo() ?: ByteArray(0),-            localEndpointId = localEndpointId,-        )-    }--    /**-     * Endpoint id advertised as the mDNS instance name. Nearby endpoint ids are four-     * characters; a stable random one per process keeps re-advertising idempotent.-     */-    private val localEndpointId: String by lazy {-        val alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"-        (1..4).map { alphabet.random() }.joinToString("")-    }--    /**-     * The endpoint-info blob for the current device name, or null if it cannot be built.-     *-     * PHONE is cosmetic — it picks the icon the peer renders next to our name.-     */-    private fun endpointInfo(): ByteArray? = try {-        ShareNative.nativeBuildEndpointInfo(_localName.value, ShareNative.DEVICE_TYPE_PHONE)-    } catch (e: UnsatisfiedLinkError) {-        Log.e(TAG, "libshare_nearby unavailable — cannot build endpoint info", e)-        null-    }--    // --- Receive: visibility toggle ---------------------------------------    private val _isVisible = MutableStateFlow(false)-    val isVisible: StateFlow<Boolean> = _isVisible.asStateFlow()--    val listenPort: StateFlow<Int?> by lazy {-        transport.listenPort-    }--    val incomingConnections: StateFlow<List<Connection>> by lazy {-        transport.incomingConnections-    }--    val receiveUiState: StateFlow<ReceiveUiState> by lazy {-        combine(-            _isVisible,-            _localName,-            transport.listenPort,-            transport.incomingConnections,-        ) { visible, name, port, conns ->-            ReceiveUiState(-                isVisible = visible,-                localName = name,-                listenPort = port,-                incomingConnections = conns,-            )-        }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ReceiveUiState())-    }--    override fun setVisible(visible: Boolean) {-        if (visible) {-            val endpointInfo = endpointInfo()-            if (endpointInfo == null) {-                Log.w(TAG, "cannot advertise without an endpoint info blob")-                _isVisible.value = false-                return-            }-            _isVisible.value = true-            // Before listen(), so a socket accepted immediately announces the identity we-            // are about to advertise rather than the transport's construction-time one.-            transport.setLocalIdentity(localName.value, endpointInfo, localEndpointId)-            val port = transport.listen()-            // Publish the WIFI_LAN port under _FC9F5ED42C8A._tcp, with the endpoint info in-            // the `n` TXT attribute — the record a Quick Share device lists us from.-            nsd.advertise(localEndpointId, endpointInfo, port)-            // The same blob inside a Nearby Connections BleAdvertisement under 0xFEF3.-            ble.startAdvertising(localEndpointId, endpointInfo)-            ShareTransferService.startReceiveMode(appContext, port)-        } else {-            _isVisible.value = false-            nsd.unadvertise()-            ble.stopAdvertising()-            transport.stopListening()-            ShareTransferService.stop(appContext)-        }-    }--    override fun acceptIncoming(connection: Connection, accept: Boolean) {-        viewModelScope.launch(Dispatchers.IO) {-            val rc = transport.acceptIncoming(connection, accept)-            if (rc < 0) {-                Log.w(TAG, "acceptIncoming failed rc=$rc")-            }-        }-    }--    override fun shareReceivedFile(context: Context, file: ReceivedFile) {-        ExternalIntents.shareFile(-            context = context,-            uri = file.uri,-            mimeType = file.mimeType,-            chooserTitle = context.getString(R.string.share_received_chooser),-        )-    }--    override fun saveReceivedFile(file: ReceivedFile, treeUri: Uri) {-        viewModelScope.launch(Dispatchers.IO) {-            val saved = copyIntoTree(file, treeUri)-            AppMessages.show(-                appContext.getString(-                    if (saved) R.string.share_save_succeeded else R.string.share_save_failed,-                    file.name,-                )-            )-        }-    }--    /**-     * Copy [file] into the SAF tree [treeUri] the user picked.-     *-     * Uses the platform [DocumentsContract] rather than `androidx.documentfile`, which-     * is not a dependency of this repo. `createDocument` may hand back a different-     * display name than requested if one is taken; that is the provider's call, not-     * ours, so nothing here second-guesses it.-     */-    private fun copyIntoTree(file: ReceivedFile, treeUri: Uri): Boolean = try {-        val resolver = appContext.contentResolver-        val parent = DocumentsContract.buildDocumentUriUsingTree(-            treeUri,-            DocumentsContract.getTreeDocumentId(treeUri),-        )-        val target = DocumentsContract.createDocument(resolver, parent, file.mimeType, file.name)-        if (target == null) {-            false-        } else {-            resolver.openInputStream(file.uri)?.use { input ->-                resolver.openOutputStream(target)?.use { output -> input.copyTo(output) }-            } != null-        }-    } catch (e: Exception) {-        Log.w(TAG, "saveReceivedFile failed for ${file.name}", e)-        false-    }+    fun setLocalName(name: String) = ShareReceiveController.setLocalName(appContext, name)      // --- Send: discovery + outgoing URIs -------------------------------- @@ -233,18 +65,18 @@ class ShareViewModel(     val isScanning: StateFlow<Boolean> = _isScanning.asStateFlow()      private val _discoveredDevices = MutableStateFlow<List<NearbyDevice>>(emptyList())-    val discoveredDevices: StateFlow<List<NearbyDevice>> = _discoveredDevices.asStateFlow()      private val _outgoingUris = MutableStateFlow<List<Uri>>(emptyList())     val outgoingUris: StateFlow<List<Uri>> = _outgoingUris.asStateFlow()      private val _outgoingDisplayNames = MutableStateFlow<List<String>>(emptyList())-    val outgoingDisplayNames: StateFlow<List<String>> = _outgoingDisplayNames.asStateFlow()      private val _activeConnection = MutableStateFlow<Connection?>(null)-    val activeConnection: StateFlow<Connection?> = _activeConnection.asStateFlow() -    val sendUiState: StateFlow<SendUiState> by lazy {+    /** Held for the whole dial-and-send, so one transfer cannot be started twice. */+    private val connecting = java.util.concurrent.atomic.AtomicBoolean(false)++    val sendUiState: StateFlow<SendUiState> =         combine(             _discoveredDevices,             _isScanning,@@ -255,13 +87,11 @@ class ShareViewModel(             SendUiState(                 discoveredDevices = devices,                 isScanning = scanning,-                selectedDevice = null,                 outgoingUris = uris,                 outgoingDisplayNames = names,                 activeConnection = active,             )         }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), SendUiState())-    }      private var scanNsdJob: Job? = null     private var scanBleJob: Job? = null@@ -275,9 +105,7 @@ class ShareViewModel(             try {                 // Browse _FC9F5ED42C8A._tcp for WIFI_LAN endpoints (host/port + name).                 nsd.discover().collect { dev ->-                    val current = _discoveredDevices.value-                    val merged = mergeDevice(current, dev)-                    _discoveredDevices.value = merged+                    _discoveredDevices.value = mergeDevice(_discoveredDevices.value, dev)                 }             } catch (e: Exception) {                 Log.w(TAG, "NSD discover error", e)@@ -287,9 +115,7 @@ class ShareViewModel(             try {                 // Scan GATT 0xFEF3 for Nearby Connections BleAdvertisements.                 ble.scan().collect { dev ->-                    val current = _discoveredDevices.value-                    val merged = mergeDevice(current, dev)-                    _discoveredDevices.value = merged+                    _discoveredDevices.value = mergeDevice(_discoveredDevices.value, dev)                 }             } catch (e: Exception) {                 Log.w(TAG, "BLE scan error", e)@@ -340,55 +166,39 @@ class ShareViewModel(             Log.w(TAG, "cannot connect to ${device.endpointName}: no host/port (needs the mDNS browse)")             return         }+        val uris = _outgoingUris.value+        if (uris.isEmpty()) {+            // Connecting with nothing staged streams nothing and idles until the peer's 60 s+            // accept timeout, which reads as a broken app rather than an empty selection.+            AppMessages.show(appContext.getString(R.string.share_nothing_selected))+            return+        }+        // A second tap while the first dial is still in flight would open another socket and+        // another native session, leak the first, and leave the peer with two half-sessions.+        if (!connecting.compareAndSet(false, true)) return+        // A scan competes with the transfer for the same radios, and the device is chosen.+        stopScan()         viewModelScope.launch {             try {-                // A rename while hidden never re-advertised, so refresh the identity the+                // A rename never re-advertised while hidden, so refresh the identity the                 // CONNECTION_REQUEST will carry before dialling.-                endpointInfo()?.let {-                    transport.setLocalIdentity(localName.value, it, localEndpointId)-                }+                ShareReceiveController.refreshLocalIdentity(appContext)                 val conn = transport.connect(host, port)                 _activeConnection.value = conn-                ShareTransferService.startSendMode(appContext, host, port)-                val uris = _outgoingUris.value.ifEmpty { devTestFileUri()?.let(::listOf).orEmpty() }-                if (uris.isNotEmpty()) {-                    sendUrisOver(conn, uris)-                }+                ShareTransferService.startSendMode(appContext)+                sendUrisOver(conn, uris)             } catch (e: Exception) {                 Log.w(TAG, "connect to ${device.endpointName} failed", e)+            } finally {+                connecting.set(false)             }         }     } -    /**-     * A throwaway file to send when nothing is selected, so a transfer can be exercised-     * without going through the file picker. Dev builds only.-     */-    private fun devTestFileUri(): Uri? {-        if (!BuildConfig.DEV_BUILD) return null-        return try {-            // Not under cache/share_send: that is where uriToTempFile copies *into*, and-            // copying a file onto itself deletes it.-            val f = File(appContext.cacheDir, "dev_test/share-test.txt")-            f.parentFile?.mkdirs()-            f.writeText(":share test payload ${System.currentTimeMillis()}\n")-            Log.i(TAG, "no files selected — sending ${f.name} (dev build only)")-            Uri.fromFile(f)-        } catch (e: Exception) {-            Log.w(TAG, "could not stage the dev test file", e)-            null-        }-    }-     override fun setOutgoingUris(uris: List<Uri>) {         _outgoingUris.value = uris         viewModelScope.launch(Dispatchers.IO) {-            val names = uris.map { uri -> resolveDisplayName(appContext, uri) ?: uri.toString() }-            _outgoingDisplayNames.value = names-        }-        val conn = _activeConnection.value-        if (conn != null && uris.isNotEmpty()) {-            viewModelScope.launch { sendUrisOver(conn, uris) }+            _outgoingDisplayNames.value = uris.map { resolveDisplayName(appContext, it) ?: it.toString() }         }     } @@ -434,8 +244,12 @@ class ShareViewModel(      private suspend fun sendUrisOver(conn: Connection, uris: List<Uri>) = withContext(Dispatchers.IO) {         val files = uris.mapNotNull { uri -> uriToTempFile(appContext, uri) }-        if (files.isNotEmpty()) {+        if (files.isEmpty()) return@withContext+        try {             transport.sendFiles(conn, files)+        } finally {+            // The staging copies exist only for the duration of the send.+            files.forEach { it.delete() }         }     } @@ -448,23 +262,15 @@ class ShareViewModel(         viewModelScope.launch {             transport.disconnect(connection)             if (_activeConnection.value === connection) _activeConnection.value = null+            // The send is over; the service stays up only if receiving still wants it.+            ShareTransferService.stop(appContext)         }     }      override fun onCleared() {+        // Only the scan is this ViewModel's to stop: the transport, the discovery managers and+        // every live session belong to ShareReceiveController and must outlive the Activity.         stopScan()-        try {-            nsd.release()-        } catch (_: Exception) {-        }-        try {-            ble.release()-        } catch (_: Exception) {-        }-        try {-            transport.release()-        } catch (_: Exception) {-        }     } } @@ -498,6 +304,8 @@ internal fun uriToTempFile(context: Context, uri: Uri): File? {         if (uri.scheme == "file") {             val src = File(uri.path ?: "")             if (src.exists() && src.isFile) {+                // Copying a file onto itself truncates it, and shared text is staged here.+                if (src.canonicalPath == dest.canonicalPath) return src                 src.copyTo(dest, overwrite = true)                 return dest             }
share/src/main/java/com/vayunmathur/share/platform/discovery/BleDiscoveryManager.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/discovery/BleDiscoveryManager.kt b/share/src/main/java/com/vayunmathur/share/platform/discovery/BleDiscoveryManager.ktindex 942a91193e..98f3300393 100644--- a/share/src/main/java/com/vayunmathur/share/platform/discovery/BleDiscoveryManager.kt+++ b/share/src/main/java/com/vayunmathur/share/platform/discovery/BleDiscoveryManager.kt@@ -439,8 +439,11 @@ class BleDiscoveryManager(private val context: Context) {                 val endpointId = ShareNative.nativeParseBleEndpointId(data) ?: addr                 val dev = NearbyDevice(                     endpointId = endpointId,+                    // Both names come from bytes already in hand: the endpoint-info blob, then+                    // the advertisement's own local name. `BluetoothDevice.getName()` would+                    // report the same thing but needs BLUETOOTH_CONNECT, which this app does+                    // not hold.                     endpointName = fields.deviceName-                        ?: result.device.name                         ?: record.deviceName                         ?: addr,                     host = null,
share/src/main/java/com/vayunmathur/share/platform/receive/PostGate.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/receive/PostGate.kt b/share/src/main/java/com/vayunmathur/share/platform/receive/PostGate.ktnew file mode 100644index 0000000000..89a7cc02ca--- /dev/null+++ b/share/src/main/java/com/vayunmathur/share/platform/receive/PostGate.kt@@ -0,0 +1,39 @@+package com.vayunmathur.share.platform.receive++/** Floor between two progress posts, so the pump is never throttled by the notifier. */+internal const val PROGRESS_MIN_INTERVAL_MS = 500L++/**+ * Decides which of a transfer's state emissions become notification posts.+ *+ * `bytesReceived` advances once per socket read, which for a 3 MB file over Wi-Fi is thousands+ * of emissions. Posting each one would make `notify()` the bottleneck of the transfer, so:+ *+ * - a change of notification *kind* always posts, immediately — those are the four things the+ *   user actually needs to see, and none of them can be dropped;+ * - progress within one kind posts only when the integer percentage changes, and at most once+ *   per [PROGRESS_MIN_INTERVAL_MS].+ *+ * Pure and clock-injected so the gate is testable without Android. `kind` is an ordinal rather+ * than the enum because the enum is private to the notifier.+ */+internal class PostGate {+    private var lastKind = -1+    private var lastPercent = -1+    private var lastPostAt = Long.MIN_VALUE++    /** True if this emission should be posted, recording it as posted when so. */+    fun admit(kind: Int, percent: Int, now: Long): Boolean {+        val due = when {+            kind != lastKind -> true+            percent == lastPercent -> false+            else -> now - lastPostAt >= PROGRESS_MIN_INTERVAL_MS+        }+        if (due) {+            lastKind = kind+            lastPercent = percent+            lastPostAt = now+        }+        return due+    }+}
share/src/main/java/com/vayunmathur/share/platform/receive/ShareBootReceiver.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/receive/ShareBootReceiver.kt b/share/src/main/java/com/vayunmathur/share/platform/receive/ShareBootReceiver.ktnew file mode 100644index 0000000000..888d5b07ff--- /dev/null+++ b/share/src/main/java/com/vayunmathur/share/platform/receive/ShareBootReceiver.kt@@ -0,0 +1,33 @@+package com.vayunmathur.share.platform.receive++import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch++/**+ * Restores receiving after a reboot or an app update, if the tile left it on.+ *+ * The flag is the source of truth, so this only has to reconcile:+ * [ShareReceiveController.syncServiceState] decides whether to start anything.+ */+class ShareBootReceiver : BroadcastReceiver() {+    override fun onReceive(context: Context, intent: Intent) {+        if (intent.action != Intent.ACTION_BOOT_COMPLETED &&+            intent.action != Intent.ACTION_MY_PACKAGE_REPLACED+        ) {+            return+        }+        val pending = goAsync()+        val appContext = context.applicationContext+        CoroutineScope(Dispatchers.IO).launch {+            try {+                ShareReceiveController.syncServiceState(appContext)+            } finally {+                pending.finish()+            }+        }+    }+}
share/src/main/java/com/vayunmathur/share/platform/receive/ShareNotificationReceiver.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/receive/ShareNotificationReceiver.kt b/share/src/main/java/com/vayunmathur/share/platform/receive/ShareNotificationReceiver.ktnew file mode 100644index 0000000000..d43e088789--- /dev/null+++ b/share/src/main/java/com/vayunmathur/share/platform/receive/ShareNotificationReceiver.kt@@ -0,0 +1,51 @@+package com.vayunmathur.share.platform.receive++import android.app.NotificationManager+import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.util.Log+import androidx.core.content.getSystemService+import com.vayunmathur.share.platform.transfer.ShareTransferService++private const val TAG = "ShareNotifRecv"++/**+ * Turns a notification's Accept / Reject / Cancel tap into service work.+ *+ * Forwarded to [ShareTransferService] rather than handled here: a broadcast receiver gets+ * roughly ten seconds and an accept starts a transfer that runs for minutes, so the follow-up+ * needs a foreground service to live in.+ *+ * `exported="false"` with no intent-filter and an explicit component target, following the+ * `email` / `clock` receivers: nothing outside the app can reach it.+ */+class ShareNotificationReceiver : BroadcastReceiver() {++    override fun onReceive(context: Context, intent: Intent) {+        val action = intent.action ?: return+        if (action !in HANDLED) return+        val handle = intent.getLongExtra(ShareTransferService.EXTRA_SESSION_HANDLE, 0L)+        val notifId = intent.getIntExtra(ShareTransferService.EXTRA_NOTIF_ID, -1)+        if (handle == 0L) {+            Log.w(TAG, "$action with no session handle")+            return+        }+        if (ShareReceiveController.connectionFor(context, handle) == null) {+            // The process died between posting the notification and this tap, so the socket+            // and the native session are both gone. Say so instead of silently doing nothing.+            Log.w(TAG, "no live session $handle for $action; clearing notification $notifId")+            if (notifId >= 0) context.getSystemService<NotificationManager>()?.cancel(notifId)+            return+        }+        ShareTransferService.routeSessionAction(context, action, handle, notifId)+    }++    private companion object {+        val HANDLED = setOf(+            ShareTransferService.ACTION_ACCEPT,+            ShareTransferService.ACTION_REJECT,+            ShareTransferService.ACTION_CANCEL,+        )+    }+}
share/src/main/java/com/vayunmathur/share/platform/receive/ShareReceiveController.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/receive/ShareReceiveController.kt b/share/src/main/java/com/vayunmathur/share/platform/receive/ShareReceiveController.ktnew file mode 100644index 0000000000..c06fbdddde--- /dev/null+++ b/share/src/main/java/com/vayunmathur/share/platform/receive/ShareReceiveController.kt@@ -0,0 +1,296 @@+package com.vayunmathur.share.platform.receive++import android.Manifest+import android.content.Context+import android.content.Intent+import android.content.pm.PackageManager+import android.os.Build+import android.util.Log+import androidx.core.content.ContextCompat+import com.vayunmathur.library.util.DataStoreUtils+import com.vayunmathur.share.network.transport.Connection+import com.vayunmathur.share.network.transport.TcpTransport+import com.vayunmathur.share.network.transport.isTerminal+import com.vayunmathur.share.platform.ReceivedFileStore+import com.vayunmathur.share.platform.discovery.BleDiscoveryManager+import com.vayunmathur.share.platform.discovery.NsdDiscoveryManager+import com.vayunmathur.share.platform.transfer.ShareTransferService+import com.vayunmathur.share.protocol.ShareNative+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.withContext++private const val TAG = "ShareReceive"++/**+ * Staged files older than this are unreachable leftovers of a killed process, so a cold start+ * deletes them. A day, not an hour: a completed file the user has not saved yet is still+ * theirs, and only the *partial* ones are truly orphaned.+ */+private const val ORPHAN_MAX_AGE_MS = 24L * 60 * 60 * 1000++/**+ * Single owner of everything the receive path needs, and the only source of truth for whether+ * it should be running.+ *+ * A singleton rather than fields on [ShareTransferService], because the persisted flag is then+ * authoritative: a `START_STICKY` restart with a null Intent just calls [syncServiceState], the+ * Quick Settings tile works whether or not the service is alive, and two overlapping service+ * instances cannot double-post notifications. Structurally the same shape as+ * `LocationServiceController` in `:findfamily`.+ *+ * The transport and the notifier live for the whole process, not for the enabled window:+ * [start] and [stop] only control listening and advertising. That is what lets a transfer+ * already in flight finish, and keep reporting progress, after the tile is switched off.+ */+object ShareReceiveController {++    /** Persisted on/off switch, owned by the Quick Settings tile (default off). */+    const val RECEIVE_ENABLED_KEY = "share_receive_enabled"++    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+    private val lock = Any()++    private class Parts(+        val nsd: NsdDiscoveryManager,+        val ble: BleDiscoveryManager,+        val store: ReceivedFileStore,+        val transport: TcpTransport,+        val notifier: ShareReceiveNotifier,+        val endpointId: String,+    )++    private var parts: Parts? = null++    @Volatile+    private var advertising = false++    /**+     * The device name announced over mDNS, BLE and `CONNECTION_REQUEST`.+     *+     * Held here rather than in `ShareViewModel` because advertising has to work from boot, when+     * no ViewModel exists.+     */+    @Volatile+    var localName: String = Build.MODEL?.takeIf { it.isNotBlank() } ?: "My device"+        private set++    /**+     * Endpoint id advertised as the mDNS instance name. Nearby endpoint ids are four+     * characters; a stable random one per process keeps re-advertising idempotent.+     */+    private fun randomEndpointId(): String {+        val alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"+        return (1..4).map { alphabet.random() }.joinToString("")+    }++    private fun ensure(context: Context): Parts = synchronized(lock) {+        parts ?: run {+            val app = context.applicationContext+            val store = ReceivedFileStore(app)+            val endpointId = randomEndpointId()+            val transport = TcpTransport(+                localName = localName,+                receivedStore = store,+                localEndpointInfo = endpointInfo() ?: ByteArray(0),+                localEndpointId = endpointId,+            )+            val notifier = ShareReceiveNotifier(app, transport)+            notifier.start(scope)+            Parts(+                nsd = NsdDiscoveryManager(app),+                ble = BleDiscoveryManager(app),+                store = store,+                transport = transport,+                notifier = notifier,+                endpointId = endpointId,+            ).also { parts = it }+        }+    }++    /**+     * The one [TcpTransport] in the process.+     *+     * Shared with the send flow so `setLocalIdentity` has exactly one owner: two transports+     * would mean two `ServerSocket`s and two identities for one advertised device.+     */+    fun transport(context: Context): TcpTransport = ensure(context).transport++    fun nsd(context: Context): NsdDiscoveryManager = ensure(context).nsd++    fun ble(context: Context): BleDiscoveryManager = ensure(context).ble++    fun connectionFor(context: Context, handle: Long): Connection? =+        ensure(context).transport.connectionFor(handle)++    /** True while any session is still moving bytes; the service must not die under one. */+    fun hasActiveTransfers(context: Context): Boolean =+        ensure(context).transport.connections.value.any { !it.state.value.isTerminal }++    /**+     * The endpoint-info blob for the current device name, or null if it cannot be built.+     *+     * PHONE is cosmetic — it picks the icon the peer renders next to our name.+     */+    fun endpointInfo(): ByteArray? = try {+        ShareNative.nativeBuildEndpointInfo(localName, ShareNative.DEVICE_TYPE_PHONE)+    } catch (e: UnsatisfiedLinkError) {+        Log.e(TAG, "libshare_nearby unavailable — cannot build endpoint info", e)+        null+    }++    /** Rename the device, re-advertising if we are currently visible. */+    fun setLocalName(context: Context, name: String) {+        val trimmed = name.trim()+        if (trimmed.isBlank() || trimmed == localName) return+        localName = trimmed+        // The name lives inside the endpoint-info blob, so renaming means re-advertising.+        if (advertising) {+            stop(context)+            start(context)+        }+    }++    // ------------------------------------------------------------------+    // Persisted flag + reconciliation+    // ------------------------------------------------------------------++    suspend fun isReceiveEnabled(context: Context): Boolean =+        DataStoreUtils.getInstance(context).getBooleanAwait(RECEIVE_ENABLED_KEY, false)++    suspend fun setReceiveEnabled(context: Context, enabled: Boolean) {+        DataStoreUtils.getInstance(context).setBoolean(RECEIVE_ENABLED_KEY, enabled)+        syncServiceState(context)+    }++    fun hasNotificationPermission(context: Context): Boolean =+        Build.VERSION.SDK_INT < 33 || ContextCompat.checkSelfPermission(+            context,+            Manifest.permission.POST_NOTIFICATIONS,+        ) == PackageManager.PERMISSION_GRANTED++    /**+     * Whether the foreground service should be running: the flag *and* the permission.+     *+     * Both `syncServiceState` and the service's own stop check use this, so they cannot+     * disagree — a service that keeps being started on one condition and refuses to stop on+     * another would run forever without ever receiving anything.+     */+    suspend fun isServiceWanted(context: Context): Boolean {+        val app = context.applicationContext+        return isReceiveEnabled(app) && hasNotificationPermission(app)+    }++    /**+     * Start the service if it is wanted, otherwise ask it to stop. Safe from any context —+     * tile, boot, sticky restart, permission refresh.+     *+     * Stopping goes through the service's own `ACTION_STOP` rather than `stopService`, because+     * only the service knows whether a transfer is still in flight; killing it there and then+     * would drop a live socket.+     */+    suspend fun syncServiceState(context: Context) {+        val app = context.applicationContext+        val wanted = isServiceWanted(app)+        withContext(Dispatchers.Main) {+            if (wanted) {+                try {+                    app.startForegroundService(+                        Intent(app, ShareTransferService::class.java)+                            .setAction(ShareTransferService.ACTION_START_RECEIVE)+                    )+                } catch (_: Exception) {+                }+            } else {+                ShareTransferService.stop(app)+            }+        }+    }++    // ------------------------------------------------------------------+    // Listening + advertising+    // ------------------------------------------------------------------++    /**+     * Begin listening and advertising. Idempotent.+     *+     * Also performs cold-start recovery. Nothing else survives process death — sockets, native+     * handles and partial files all go — but *posted notifications do*, so a stale Request+     * notification would offer an Accept that can never work.+     */+    fun start(context: Context) {+        val app = context.applicationContext+        val p = ensure(app)+        val endpointInfo = endpointInfo()+        if (endpointInfo == null) {+            // A random blob is worse than silence: peers would list us and then fail to connect.+            Log.w(TAG, "refusing to advertise without an endpoint info blob")+            return+        }+        // Under `lock`, not just a volatile check-then-set: `start` runs on the service's main+        // thread and `stop` on Dispatchers.IO, and an interleaving that closed the ServerSocket+        // after listen() had already handed its port to nsd.advertise() would leave the device+        // advertised on a port nothing is accepting on.+        synchronized(lock) {+            if (advertising) return+            advertising = true+            ShareReceiveNotifier.cancelStale(app)+            val swept = p.store.gcOrphans(ORPHAN_MAX_AGE_MS)+            if (swept > 0) Log.i(TAG, "swept $swept orphaned staged file(s)")+            // Before listen(), so a socket accepted immediately announces the identity we are+            // about to advertise rather than the transport's construction-time one.+            p.transport.setLocalIdentity(localName, endpointInfo, p.endpointId)+            val port = p.transport.listen()+            // The WIFI_LAN port under _FC9F5ED42C8A._tcp, endpoint info in the `n` TXT+            // attribute — the record a Quick Share device lists us from.+            p.nsd.advertise(p.endpointId, endpointInfo, port)+            // The same blob inside a Nearby Connections BleAdvertisement under 0xFEF3.+            p.ble.startAdvertising(p.endpointId, endpointInfo)+            Log.i(TAG, "receiving as \"$localName\" on port $port")+        }+    }++    /**+     * Stop listening and advertising. Idempotent.+     *+     * Deliberately leaves live sessions pumping: switching off means "no new transfers", not+     * "drop the one in progress".+     */+    fun stop(context: Context) {+        val p = parts ?: return+        synchronized(lock) {+            if (!advertising) return+            advertising = false+            p.nsd.unadvertise()+            p.ble.stopAdvertising()+            p.transport.stopListening()+        }+        Log.i(TAG, "stopped receiving")+    }++    /** Suspend until no session is still moving bytes. */+    suspend fun awaitIdle(context: Context) {+        ensure(context).transport.awaitIdle()+    }++    /**+     * Push the current name and endpoint id into the transport, for sessions it is about to+     * create.+     *+     * The send flow needs this before dialling out: a rename while not advertising never+     * refreshed the transport, so the `CONNECTION_REQUEST` would carry a stale name.+     */+    fun refreshLocalIdentity(context: Context) {+        val p = ensure(context)+        endpointInfo()?.let { p.transport.setLocalIdentity(localName, it, p.endpointId) }+    }++    /** Answer a peer's `INTRODUCTION` from a notification action. */+    fun acceptIncoming(context: Context, handle: Long, accept: Boolean): Int =+        ensure(context).transport.acceptIncoming(handle, accept)++    suspend fun cancel(context: Context, handle: Long) {+        ensure(context).transport.cancel(handle)+    }+}
share/src/main/java/com/vayunmathur/share/platform/receive/ShareReceiveNotifier.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/receive/ShareReceiveNotifier.kt b/share/src/main/java/com/vayunmathur/share/platform/receive/ShareReceiveNotifier.ktnew file mode 100644index 0000000000..d72737703b--- /dev/null+++ b/share/src/main/java/com/vayunmathur/share/platform/receive/ShareReceiveNotifier.kt@@ -0,0 +1,421 @@+package com.vayunmathur.share.platform.receive++import android.app.NotificationManager+import android.app.PendingIntent+import android.content.Context+import android.content.Intent+import android.net.Uri+import android.os.Build+import android.util.Log+import androidx.core.app.NotificationCompat+import androidx.core.app.NotificationManagerCompat+import androidx.core.content.getSystemService+import androidx.core.net.toUri+import com.vayunmathur.library.util.deleteNotificationChannel+import com.vayunmathur.library.util.ensureNotificationChannel+import com.vayunmathur.share.R+import com.vayunmathur.share.domain.protocol.ShareState+import com.vayunmathur.share.network.transport.Connection+import com.vayunmathur.share.network.transport.TcpTransport+import com.vayunmathur.share.platform.ReceivedFile+import com.vayunmathur.share.platform.transfer.ShareTransferService+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Job+import kotlinx.coroutines.coroutineScope+import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.conflate+import kotlinx.coroutines.launch++private const val TAG = "ShareNotifier"++/**+ * Everything the user is meant to react to — requests, progress, and outcomes.+ *+ * Both `IMPORTANCE_MAX`, so all of them heads-up rather than sitting in the shade. The only+ * quiet notification `:share` posts is the foreground service's own "Ready to receive", which+ * has its own `IMPORTANCE_LOW` channel in [ShareTransferService]; the two are deliberately+ * separate so silencing the always-on status indicator does not silence an incoming transfer.+ *+ * [CHANNEL_REQUESTS] carries a `_v2` suffix because the first cut of it was `IMPORTANCE_HIGH`,+ * and a channel's importance is fixed for good: `createNotificationChannel` refreshes a+ * channel's name and description, but the system ignores any later change to its importance+ * and remembers the settings of deleted channels, so raising it needs a new id.+ */+private const val CHANNEL_REQUESTS = "share_requests_v2"+private const val CHANNEL_TRANSFERS = "share_transfers"++/** The `IMPORTANCE_HIGH` requests channel that [CHANNEL_REQUESTS] replaces. */+private const val CHANNEL_LEGACY_REQUESTS = "share_requests"++/** Concurrent transfers bundle under one summary instead of stacking. */+private const val GROUP_KEY = "com.vayunmathur.share.TRANSFERS"++/**+ * First id handed out per transfer. Above the foreground-service notification's 4101 and+ * allocated from a counter rather than hashed from the session handle: hashing a `Long` into+ * an `Int` invites a silent collision between two concurrent transfers, which would show one+ * peer's files under the other's name.+ */+private const val FIRST_TRANSFER_NOTIF_ID = 4200++/** GMS's measured accept timeout. A prompt that outlives the session is a lie. */+private const val REQUEST_TIMEOUT_MS = 60_000L++/** Android 16 Live Updates; below this a plain determinate bar says the same thing. */+private const val PROGRESS_STYLE_SDK = 36++/**+ * Request codes reserved per notification, so Share and Save cannot collide.+ *+ * Two per notification id: `id * N` for Share and `id * N + 1` for Save.+ */+private const val REQUEST_CODES_PER_NOTIF = 2++/**+ * Turns [TcpTransport] state into notifications, which are the only receive UI there is.+ *+ * Owned by [ShareReceiveController] rather than by [ShareTransferService]: the service can be+ * recreated at any time, and two overlapping instances would double-post.+ *+ * Concurrency shape worth keeping: a **keyed child job per session handle**, not+ * `flatMapLatest { merge(...) }`. The latter tears down and restarts every existing collector+ * whenever a new connection appears, so a second peer arriving would restart the first+ * transfer's observer mid-flight. Each child `conflate()`s, so a notification post can never+ * back-pressure the transfer pump.+ */+class ShareReceiveNotifier(+    context: Context,+    private val transport: TcpTransport,+) {+    private val appContext = context.applicationContext+    private var job: Job? = null++    /** Allocated notification id per handle, and whose terminal post has landed. [idLock]. */+    private val ids = mutableMapOf<Long, Int>()+    private val terminalPosted = mutableSetOf<Long>()+    private var nextId = FIRST_TRANSFER_NOTIF_ID+    private val idLock = Any()++    private enum class Kind { None, Request, Progress, Done, Failed }++    fun start(scope: CoroutineScope) {+        if (job != null) return+        ensureChannels()+        job = scope.launch { watch() }+    }++    fun stop() {+        job?.cancel()+        job = null+    }++    private fun ensureChannels() {+        appContext.deleteNotificationChannel(CHANNEL_LEGACY_REQUESTS)+        appContext.ensureNotificationChannel(+            id = CHANNEL_REQUESTS,+            name = appContext.getString(R.string.share_channel_requests_name),+            importance = NotificationManager.IMPORTANCE_MAX,+            description = appContext.getString(R.string.share_channel_requests_desc),+        )+        appContext.ensureNotificationChannel(+            id = CHANNEL_TRANSFERS,+            name = appContext.getString(R.string.share_channel_transfers_name),+            importance = NotificationManager.IMPORTANCE_MAX,+            description = appContext.getString(R.string.share_channel_transfers_desc),+        )+    }++    private suspend fun watch() {+        coroutineScope {+            val children = mutableMapOf<Long, Job>()+            transport.incomingConnections.collect { conns ->+                val live = conns.associateBy { it.sessionHandle }+                for ((handle, conn) in live) {+                    if (children.containsKey(handle)) continue+                    children[handle] = launch { observe(conn) }+                }+                for (handle in children.keys - live.keys) {+                    children.remove(handle)?.cancel()+                    onGone(handle)+                }+            }+        }+    }++    /**+     * One notification lifecycle for one connection.+     *+     * `peerName` and `expectedTotalBytes` are read at post time rather than combined: both are+     * set once, before the state they matter for, so folding them into the `combine` would only+     * add emissions that change nothing.+     */+    private suspend fun observe(conn: Connection) {+        val gate = PostGate()+        combine(+            conn.state,+            conn.pendingFiles,+            conn.receivedFiles,+            conn.bytesReceived,+        ) { state, pending, received, bytes -> Snapshot(state, pending.size, received, bytes) }+            .conflate()+            .collect { snap ->+                val kind = kindOf(snap.state)+                if (kind == Kind.None) return@collect+                val total = conn.expectedTotalBytes.value+                val percent = if (total > 0) ((snap.bytes * 100) / total).toInt().coerceIn(0, 100) else 0+                if (!gate.admit(kind.ordinal, percent, System.currentTimeMillis())) return@collect+                post(conn, kind, snap, percent)+            }+    }++    private class Snapshot(+        val state: ShareState,+        val fileCount: Int,+        val received: List<ReceivedFile>,+        val bytes: Long,+    )++    private fun kindOf(state: ShareState): Kind = when (state) {+        ShareState.AwaitingAccept -> Kind.Request+        ShareState.Transferring -> Kind.Progress+        ShareState.Completed -> Kind.Done+        ShareState.Failed -> Kind.Failed+        ShareState.Handshaking, ShareState.Unknown -> Kind.None+    }++    /**+     * A connection vanished from the transport.+     *+     * Only reported when the user was already shown something for it: a session that failed+     * during the handshake was never visible, and announcing a failed transfer nobody+     * initiated is noise.+     */+    private fun onGone(handle: Long) {+        val id = synchronized(idLock) {+            val id = ids.remove(handle) ?: return+            if (terminalPosted.remove(handle)) return+            id+        }+        notify(id, failedNotification(appContext.getString(R.string.share_transfer_failed)))+    }++    private fun idFor(handle: Long): Int = synchronized(idLock) {+        ids.getOrPut(handle) { nextId++ }+    }++    private fun post(conn: Connection, kind: Kind, snap: Snapshot, percent: Int) {+        val handle = conn.sessionHandle+        val id = idFor(handle)+        val notification = when (kind) {+            Kind.Request -> requestNotification(conn, id, snap.fileCount)+            Kind.Progress -> progressNotification(conn, id, snap, percent)+            Kind.Done -> doneNotification(conn, id, snap.received)+            Kind.Failed -> failedNotification(conn.error.value ?: appContext.getString(R.string.share_transfer_failed))+            Kind.None -> return+        }+        if (kind == Kind.Done || kind == Kind.Failed) {+            synchronized(idLock) { terminalPosted += handle }+            notify(id, notification)+            // The user has been told the outcome, so the session's `Connection` and native+            // handle have no remaining reader. Nothing else disconnects an incoming session.+            transport.retire(handle)+            return+        }+        notify(id, notification)+    }++    private fun notify(id: Int, notification: android.app.Notification) {+        try {+            NotificationManagerCompat.from(appContext).notify(id, notification)+        } catch (e: SecurityException) {+            // POST_NOTIFICATIONS revoked mid-transfer. Nothing to fall back to — the tile+            // refuses to enable without it — so record it rather than crashing the pump.+            Log.w(TAG, "cannot post notification $id", e)+        }+    }++    private fun base(channel: String) = NotificationCompat.Builder(appContext, channel)+        .setSmallIcon(R.drawable.ic_tile_share)+        .setGroup(GROUP_KEY)++    private fun requestNotification(conn: Connection, id: Int, fileCount: Int) =+        base(CHANNEL_REQUESTS)+            .setContentTitle(conn.displayName)+            .setContentText(appContext.getString(R.string.share_wants_to_send, fileCount))+            .setCategory(NotificationCompat.CATEGORY_SOCIAL)+            .setOngoing(true)+            .setTimeoutAfter(REQUEST_TIMEOUT_MS)+            .addAction(+                R.drawable.ic_tile_share,+                appContext.getString(R.string.share_accept),+                sessionAction(ShareTransferService.ACTION_ACCEPT, conn.sessionHandle, id),+            )+            .addAction(+                R.drawable.ic_tile_share,+                appContext.getString(R.string.share_decline),+                sessionAction(ShareTransferService.ACTION_REJECT, conn.sessionHandle, id),+            )+            .build()++    private fun progressNotification(conn: Connection, id: Int, snap: Snapshot, percent: Int): android.app.Notification {+        val total = conn.expectedTotalBytes.value+        val builder = base(CHANNEL_TRANSFERS)+            .setContentTitle(conn.displayName)+            .setContentText(appContext.getString(R.string.share_receiving))+            .setSubText(+                appContext.getString(R.string.share_progress_kb, snap.bytes / 1024, total / 1024)+            )+            .setCategory(NotificationCompat.CATEGORY_PROGRESS)+            .setOngoing(true)+            .setOnlyAlertOnce(true)+            .addAction(+                R.drawable.ic_tile_share,+                appContext.getString(R.string.share_action_cancel),+                sessionAction(ShareTransferService.ACTION_CANCEL, conn.sessionHandle, id),+            )+        val sizesKb = conn.pendingFiles.value.map { (it.sizeBytes / 1024).toInt().coerceAtLeast(1) }+        if (Build.VERSION.SDK_INT >= PROGRESS_STYLE_SDK && sizesKb.isNotEmpty()) {+            // One segment per announced file, so a multi-file transfer shows which file it is on.+            builder.setStyle(+                NotificationCompat.ProgressStyle()+                    .setProgressSegments(sizesKb.map { NotificationCompat.ProgressStyle.Segment(it) })+                    .setProgress((snap.bytes / 1024).toInt())+            )+            builder.setShortCriticalText("$percent%")+        } else {+            builder.setProgress(100, percent, total <= 0)+        }+        return builder.build()+    }++    private fun doneNotification(conn: Connection, id: Int, received: List<ReceivedFile>): android.app.Notification {+        val builder = base(CHANNEL_TRANSFERS)+            .setContentTitle(conn.displayName)+            .setContentText(appContext.getString(R.string.share_received_count, received.size))+            .setAutoCancel(true)+        if (received.isNotEmpty()) {+            // URIs, not the handle: by the time this is tapped the session is gone.+            val uris = received.map { it.uri }+            val mime = received.map { it.mimeType }.distinct().singleOrNull() ?: "*/*"+            builder.addAction(+                R.drawable.ic_tile_share,+                appContext.getString(R.string.share_action_share),+                sharePendingIntent(uris, mime, id),+            )+            builder.addAction(+                R.drawable.ic_tile_share,+                appContext.getString(R.string.share_action_save),+                savePendingIntent(uris, id),+            )+        }+        return builder.build()+    }++    private fun failedNotification(reason: String) = base(CHANNEL_TRANSFERS)+        .setContentTitle(appContext.getString(R.string.share_transfer_failed))+        .setContentText(reason)+        .setStyle(NotificationCompat.BigTextStyle().bigText(reason))+        .setAutoCancel(true)+        .build()++    /**+     * A broadcast to [ShareNotificationReceiver] for Accept / Reject / Cancel.+     *+     * Both a distinct `requestCode` **and** a distinct [Intent.data] per (handle, action):+     * `Intent` equality ignores extras, so with `FLAG_UPDATE_CURRENT` two handles' Accept+     * intents would collapse onto one `PendingIntent` and deliver whichever handle was+     * registered last.+     */+    private fun sessionAction(action: String, handle: Long, notifId: Int): PendingIntent {+        val intent = Intent(appContext, ShareNotificationReceiver::class.java).apply {+            this.action = action+            data = "share://session/$handle/$action".toUri()+            putExtra(ShareTransferService.EXTRA_SESSION_HANDLE, handle)+            putExtra(ShareTransferService.EXTRA_NOTIF_ID, notifId)+        }+        return PendingIntent.getBroadcast(+            appContext,+            requestCode(handle, action),+            intent,+            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,+        )+    }++    /**+     * The system chooser, launched straight from the notification.+     *+     * `PendingIntent.getActivity` rather than `ExternalIntents.launch`, which calls+     * `startActivity` without `FLAG_ACTIVITY_NEW_TASK` and so cannot run from a service or+     * broadcast context.+     *+     * **Nothing may set `data` on the chooser intent.** `ACTION_CHOOSER` is resolved by the+     * framework's `ChooserActivity`, whose intent-filter declares no data at all, and a filter+     * with no data element does not match an intent that has a URI. Setting one made+     * `startActivity` throw `ActivityNotFoundException` inside the `PendingIntent`, which the+     * system only logs — so Share appeared to do nothing whatsoever.+     *+     * That leaves the `requestCode` carrying the whole burden of keeping two peers' Share+     * intents apart, because `filterEquals` ignores extras and every chooser intent is+     * otherwise identical. [notifId] is safe for that: it comes from a counter, not a hash.+     */+    private fun sharePendingIntent(uris: List<Uri>, mime: String, notifId: Int): PendingIntent {+        val send = if (uris.size == 1) {+            Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_STREAM, uris.first())+        } else {+            Intent(Intent.ACTION_SEND_MULTIPLE).putParcelableArrayListExtra(+                Intent.EXTRA_STREAM,+                ArrayList(uris),+            )+        }+        send.type = mime+        send.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)+        val chooser = Intent.createChooser(+            send,+            appContext.getString(R.string.share_received_chooser),+        ).apply {+            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION)+        }+        return PendingIntent.getActivity(+            appContext,+            notifId * REQUEST_CODES_PER_NOTIF,+            chooser,+            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,+        )+    }++    private fun savePendingIntent(uris: List<Uri>, notifId: Int): PendingIntent {+        val intent = Intent(appContext, ShareSaveActivity::class.java).apply {+            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+            putExtra(ShareSaveActivity.EXTRA_FILE_URIS, ArrayList(uris))+        }+        return PendingIntent.getActivity(+            appContext,+            notifId * REQUEST_CODES_PER_NOTIF + 1,+            intent,+            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,+        )+    }++    private fun requestCode(handle: Long, action: String): Int =+        (handle.hashCode() * 31 + action.hashCode())++    companion object {+        /**+         * Clear every per-transfer notification left over from a previous process.+         *+         * Posted notifications are the one thing that outlives process death: the sockets,+         * native handles and partial files do not, so a Request notification found at startup+         * points at a session that no longer exists and whose Accept can never work.+         */+        fun cancelStale(context: Context) {+            val nm = context.getSystemService<NotificationManager>() ?: return+            try {+                nm.activeNotifications+                    .filter { it.notification.group == GROUP_KEY }+                    .forEach { nm.cancel(it.id) }+            } catch (e: Exception) {+                Log.w(TAG, "could not enumerate active notifications", e)+            }+        }+    }+}
share/src/main/java/com/vayunmathur/share/platform/receive/ShareReceiveTileService.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/receive/ShareReceiveTileService.kt b/share/src/main/java/com/vayunmathur/share/platform/receive/ShareReceiveTileService.ktnew file mode 100644index 0000000000..93db41fc36--- /dev/null+++ b/share/src/main/java/com/vayunmathur/share/platform/receive/ShareReceiveTileService.kt@@ -0,0 +1,84 @@+package com.vayunmathur.share.platform.receive++import android.app.PendingIntent+import android.content.Intent+import android.os.Build+import android.service.quicksettings.Tile+import android.service.quicksettings.TileService+import com.vayunmathur.share.MainActivity+import com.vayunmathur.share.R+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.launch++/**+ * The only control for whether `:share` is receivable.+ *+ * Tapping flips the persisted [ShareReceiveController.RECEIVE_ENABLED_KEY] flag and reconciles+ * the foreground service immediately; boot and a sticky restart honour the same flag through+ * [ShareReceiveController.syncServiceState], so the tile and the service can never disagree.+ *+ * Without `POST_NOTIFICATIONS` the whole feature is invisible — notifications *are* the receive+ * UI — so the tile refuses to enable and sends the user to the app to grant it instead.+ */+class ShareReceiveTileService : TileService() {++    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)++    override fun onStartListening() {+        super.onStartListening()+        refreshTile()+    }++    override fun onTileAdded() {+        super.onTileAdded()+        refreshTile()+    }++    override fun onClick() {+        super.onClick()+        if (!ShareReceiveController.hasNotificationPermission(this)) {+            openApp()+            return+        }+        scope.launch {+            val enabled = ShareReceiveController.isReceiveEnabled(this@ShareReceiveTileService)+            ShareReceiveController.setReceiveEnabled(this@ShareReceiveTileService, !enabled)+            refreshTile()+        }+    }++    private fun refreshTile() {+        scope.launch {+            val tile = qsTile ?: return@launch+            val hasPermission = ShareReceiveController.hasNotificationPermission(this@ShareReceiveTileService)+            val enabled = ShareReceiveController.isReceiveEnabled(this@ShareReceiveTileService)+            tile.state = if (enabled && hasPermission) Tile.STATE_ACTIVE else Tile.STATE_INACTIVE+            tile.subtitle = when {+                !hasPermission -> getString(R.string.share_tile_no_permission)+                enabled -> ShareReceiveController.localName+                else -> getString(R.string.share_tile_off)+            }+            tile.updateTile()+        }+    }++    private fun openApp() {+        val intent = Intent(this, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+        if (Build.VERSION.SDK_INT >= 34) {+            startActivityAndCollapse(+                PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)+            )+        } else {+            @Suppress("DEPRECATION")+            startActivityAndCollapse(intent)+        }+    }++    override fun onDestroy() {+        super.onDestroy()+        scope.cancel()+    }+}
share/src/main/java/com/vayunmathur/share/platform/receive/ShareSaveActivity.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/receive/ShareSaveActivity.kt b/share/src/main/java/com/vayunmathur/share/platform/receive/ShareSaveActivity.ktnew file mode 100644index 0000000000..f35a8f2989--- /dev/null+++ b/share/src/main/java/com/vayunmathur/share/platform/receive/ShareSaveActivity.kt@@ -0,0 +1,135 @@+package com.vayunmathur.share.platform.receive++import android.content.Intent+import android.net.Uri+import android.os.Build+import android.os.Bundle+import android.util.Log+import android.widget.Toast+import androidx.activity.ComponentActivity+import androidx.activity.result.contract.ActivityResultContracts+import androidx.lifecycle.lifecycleScope+import com.vayunmathur.share.R+import com.vayunmathur.share.platform.ReceivedFileStore+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++private const val TAG = "ShareSave"+private const val STATE_INDEX = "index"+private const val STATE_SAVED = "saved"++/**+ * Transparent trampoline hosting the "save a copy" picker for a Done notification's Save.+ *+ * An `ActivityResultLauncher` needs an Activity, and there is no receive screen left to host one,+ * so this exists only to run the picker, copy, and finish. It carries URIs rather than a session+ * handle because by the time Save is tappable the session is gone.+ *+ * Uses `ACTION_CREATE_DOCUMENT`, not `OpenDocumentTree`. Tree access hands the app read/write over+ * a whole directory and its children forever, which is why the system refuses the ones people+ * actually want — Downloads and the storage root both answer "Can't use this folder / To protect+ * your privacy, choose another folder". `ACTION_CREATE_DOCUMENT` grants write access to exactly+ * the one file the user just named, so nothing is blocked and nothing lingering is granted.+ *+ * The cost is one picker per file, so they are run in sequence.+ */+class ShareSaveActivity : ComponentActivity() {++    private var index = 0+    private var saved = 0++    private val creator = registerForActivityResult(+        ActivityResultContracts.StartActivityForResult()+    ) { result ->+        val source = uris().getOrNull(index)+        val destination = result.data?.data+        if (result.resultCode == RESULT_OK && destination != null && source != null) {+            lifecycleScope.launch {+                if (withContext(Dispatchers.IO) { copy(source, destination) }) saved+++                index+++                advance()+            }+        } else {+            // Cancelled for this file. Skipping to the next is friendlier than abandoning the+            // whole batch, and cancelling the first is indistinguishable from changing your mind.+            index+++            advance()+        }+    }++    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)+        index = savedInstanceState?.getInt(STATE_INDEX) ?: 0+        saved = savedInstanceState?.getInt(STATE_SAVED) ?: 0+        if (uris().isEmpty()) {+            Log.w(TAG, "no URIs to save")+            finish()+            return+        }+        // Only on a fresh launch: `registerForActivityResult` restores the pending request across+        // recreation, so launching again would stack a second picker on top of it.+        if (savedInstanceState == null) advance()+    }++    override fun onSaveInstanceState(outState: Bundle) {+        super.onSaveInstanceState(outState)+        outState.putInt(STATE_INDEX, index)+        outState.putInt(STATE_SAVED, saved)+    }++    /** Ask for the next destination, or report and finish once every file has had its turn. */+    private fun advance() {+        val targets = uris()+        val next = targets.getOrNull(index)+        if (next == null) {+            // A Toast, not `AppMessages`: that is collected by the app's scaffold, and this+            // trampoline has no UI and may well be the only thing the user has open.+            Toast.makeText(+                this,+                if (saved == targets.size) getString(R.string.share_save_succeeded, saved)+                else getString(R.string.share_save_failed, targets.size - saved),+                Toast.LENGTH_SHORT,+            ).show()+            finish()+            return+        }+        val name = displayName(next)+        creator.launch(+            Intent(Intent.ACTION_CREATE_DOCUMENT).apply {+                addCategory(Intent.CATEGORY_OPENABLE)+                // Per file, from its own name: a batch can mix a photo and a PDF, and the picker+                // uses the type to choose a default location and a sensible extension.+                type = ReceivedFileStore.mimeTypeOf(name)+                putExtra(Intent.EXTRA_TITLE, name)+            }+        )+    }++    /** The staged file's name. These are our own `FileProvider` URIs, so it is the last segment. */+    private fun displayName(uri: Uri): String =+        uri.lastPathSegment?.substringAfterLast('/').orEmpty().ifBlank { "received_file" }++    private fun uris(): List<Uri> {+        val extras = if (Build.VERSION.SDK_INT >= 33) {+            intent.getParcelableArrayListExtra(EXTRA_FILE_URIS, Uri::class.java)+        } else {+            @Suppress("DEPRECATION")+            intent.getParcelableArrayListExtra<Uri>(EXTRA_FILE_URIS)+        }+        return extras.orEmpty()+    }++    private fun copy(source: Uri, destination: Uri): Boolean = try {+        contentResolver.openInputStream(source)?.use { input ->+            contentResolver.openOutputStream(destination)?.use { output -> input.copyTo(output) }+        } != null+    } catch (e: Exception) {+        Log.w(TAG, "save failed for $source", e)+        false+    }++    companion object {+        const val EXTRA_FILE_URIS = "com.vayunmathur.share.EXTRA_FILE_URIS"+    }+}
share/src/main/java/com/vayunmathur/share/platform/transfer/ShareTransferService.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/transfer/ShareTransferService.kt b/share/src/main/java/com/vayunmathur/share/platform/transfer/ShareTransferService.ktindex 79856e6270..e85503fd5d 100644--- a/share/src/main/java/com/vayunmathur/share/platform/transfer/ShareTransferService.kt+++ b/share/src/main/java/com/vayunmathur/share/platform/transfer/ShareTransferService.kt@@ -9,34 +9,73 @@ import android.content.Intent import android.content.pm.ServiceInfo import android.os.Build import android.os.IBinder+import android.util.Log import androidx.core.app.NotificationCompat import androidx.core.content.getSystemService+import com.vayunmathur.library.util.deleteNotificationChannel import com.vayunmathur.library.util.ensureNotificationChannel import com.vayunmathur.share.MainActivity import com.vayunmathur.share.R+import com.vayunmathur.share.platform.receive.ShareReceiveController+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++private const val TAG = "ShareTransferSvc"++/**+ * The service's own channel, and nothing else's.+ *+ * `IMPORTANCE_LOW` so the always-on "Ready to receive" notification never makes a sound — it is+ * a status indicator, not an event. Every notification the user is meant to *react* to lives on+ * `ShareReceiveNotifier`'s own `IMPORTANCE_MAX` channels, so silencing this one in settings does+ * not silence incoming transfer requests.+ */+private const val CHANNEL_ID = "share_service"++/**+ * The id this channel used to have, when the notifier shared it.+ *+ * Sharing it meant progress and results inherited `IMPORTANCE_LOW` and never left the shade, and+ * that the channel's name flip-flopped depending on which of the two registered it last. Deleted+ * rather than reused, because a channel's importance is fixed at creation.+ */+private const val CHANNEL_LEGACY = "share_transfer" -private const val CHANNEL_ID = "share_transfer" private const val NOTIF_ID = 4101  /**- * Foreground service that keeps Nearby Share transfers alive while the app- * is backgrounded.+ * Foreground service that keeps `:share` receivable while the app is not open.  *- * Pattern follows the per-repo foreground-service convention (see- * library:downloadservice / maps RouteService): a dataSync service that- * posts a low-importance notification while a session pump is active, and- * tears itself down when transfers complete or the user dismisses.+ * A lifecycle host with **zero session state**: [ShareReceiveController] owns the sockets, the+ * native sessions and the notifier, so this can be recreated or restarted at any time without+ * anything being lost. `START_STICKY` plus a null-Intent restart that just reconciles against+ * the persisted flag is what makes that safe.  *- * The ViewModel owns the actual TCP + Rust pumps; this service exists just- * to satisfy the platform's background-execution contract. No session state- * lives here.+ * Foreground-service type is `connectedDevice`, not `dataSync`. `:vpn`'s manifest documents the+ * reason first-hand: Android 15 caps `dataSync` at six cumulative hours per 24 h, then calls+ * [onTimeout] and stops the service — unacceptable for an always-on receiver.+ * `connectedDevice` is semantically accurate (BLE advertising plus a local peer link), is not+ * capped, and is not on Android 13/14's list of types that a `BOOT_COMPLETED` receiver may not+ * start, so [ShareBootReceiver] can bring it up. Its permission prerequisite is satisfied by+ * `CHANGE_WIFI_STATE`, which is a normal permission, so it cannot fail for want of a runtime+ * Bluetooth grant.  */ class ShareTransferService : Service() { +    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++    /** So two overlapping stop requests cannot both sit waiting on [ShareReceiveController.awaitIdle]. */+    private val stopping = java.util.concurrent.atomic.AtomicBoolean(false)+     override fun onBind(intent: Intent?): IBinder? = null      override fun onCreate() {         super.onCreate()+        deleteNotificationChannel(CHANNEL_LEGACY)         ensureNotificationChannel(             CHANNEL_ID,             getString(R.string.share_notification_channel_name),@@ -46,44 +85,120 @@ class ShareTransferService : Service() {     }      override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {-        when (intent?.action) {-            ACTION_START_RECEIVE, ACTION_START_SEND -> {-                val notif = buildNotification(intent.action == ACTION_START_SEND)-                if (Build.VERSION.SDK_INT >= 34) {-                    startForeground(-                        NOTIF_ID,-                        notif,-                        ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC,-                    )-                } else {-                    @Suppress("DEPRECATION")-                    startForeground(NOTIF_ID, notif)+        // Enter the foreground before anything else: this service is normally started with+        // startForegroundService, and the platform kills a process that does not honour that+        // within a few seconds regardless of which action it was handling.+        val action = intent?.action+        enterForeground(isSending = action == ACTION_START_SEND)+        when (action) {+            ACTION_START_SEND -> Unit+            // Everything else touches sockets or DataStore. `onStartCommand` runs on the main+            // thread and `acceptIncoming` flushes the Sharing ACCEPT frame down the socket, so+            // none of this may be done inline.+            ACTION_START_RECEIVE -> scope.launch { ShareReceiveController.start(this@ShareTransferService) }+            ACTION_ACCEPT, ACTION_REJECT -> {+                val handle = intent.getLongExtra(EXTRA_SESSION_HANDLE, 0L)+                val accept = action == ACTION_ACCEPT+                scope.launch {+                    val rc = ShareReceiveController.acceptIncoming(this@ShareTransferService, handle, accept)+                    if (rc < 0) Log.w(TAG, "accept($accept) on $handle failed rc=$rc")+                    if (!accept) stopIfNotNeeded()+                }+            }+            ACTION_CANCEL -> {+                val handle = intent.getLongExtra(EXTRA_SESSION_HANDLE, 0L)+                scope.launch {+                    ShareReceiveController.cancel(this@ShareTransferService, handle)+                    stopIfNotNeeded()                 }             }-            ACTION_STOP -> {+            ACTION_TURN_OFF -> scope.launch {+                // The user's own "Turn off": flip the persisted flag so the Quick Settings tile+                // agrees, and let syncServiceState issue the ACTION_STOP that follows.+                ShareReceiveController.setReceiveEnabled(this@ShareTransferService, false)+            }+            ACTION_STOP -> scope.launch { stopIfNotNeeded() }+            else -> {+                // START_STICKY restart, or a start with no action: the persisted flag decides.+                scope.launch { ShareReceiveController.syncServiceState(this@ShareTransferService) }+            }+        }+        return START_STICKY+    }++    /**+     * Stop, unless receiving is still wanted or a transfer is still running.+     *+     * Two separate reasons to stay up. Receiving being wanted is the obvious one — a finished+     * *send* must not take the receiver down with it. The other is that toggling receiving off+     * mid-transfer must not kill a live socket, so the service outlives the flag and waits for+     * the last session to go terminal rather than returning and never being asked again.+     *+     * "Wanted" is the same condition `syncServiceState` starts on, permission included:+     * gating only on the flag would leave the service running forever after+     * `POST_NOTIFICATIONS` was revoked, since it would keep being started and never stop.+     */+    private suspend fun stopIfNotNeeded() {+        if (!stopping.compareAndSet(false, true)) return+        try {+            if (ShareReceiveController.isServiceWanted(this)) return+            ShareReceiveController.stop(this)+            if (ShareReceiveController.hasActiveTransfers(this)) {+                Log.i(TAG, "deferring stop: a transfer is still in flight")+                ShareReceiveController.awaitIdle(this)+            }+            withContext(Dispatchers.Main) {                 stopForeground(STOP_FOREGROUND_REMOVE)                 stopSelf()             }-            else -> {-                // Service restarted by system; re-enter foreground with a generic notification.-                val notif = buildNotification(isSending = false)-                if (Build.VERSION.SDK_INT >= 34) {-                    startForeground(NOTIF_ID, notif, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)-                } else {-                    @Suppress("DEPRECATION")-                    startForeground(NOTIF_ID, notif)-                }+        } finally {+            stopping.set(false)+        }+    }++    private fun enterForeground(isSending: Boolean) {+        val notif = buildNotification(isSending)+        try {+            if (Build.VERSION.SDK_INT >= 34) {+                startForeground(+                    NOTIF_ID,+                    notif,+                    ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE,+                )+            } else {+                @Suppress("DEPRECATION")+                startForeground(NOTIF_ID, notif)             }+        } catch (e: Exception) {+            // A background start that the platform refuses. Nothing to recover here; the tile+            // and the boot receiver both retry through syncServiceState.+            Log.w(TAG, "could not enter the foreground", e)         }-        return START_NOT_STICKY+    }++    /**+     * Android 15's cumulative-runtime timeout.+     *+     * `connectedDevice` is not capped, so this should never fire; if a future platform version+     * caps it anyway, stopping cleanly beats being killed with a live socket open.+     */+    override fun onTimeout(startId: Int, fgsType: Int) {+        Log.w(TAG, "foreground service timed out (type $fgsType)")+        scope.launch {+            ShareReceiveController.stop(this@ShareTransferService)+            withContext(Dispatchers.Main) {+                stopForeground(STOP_FOREGROUND_REMOVE)+                stopSelf()+            }+        }+    }++    override fun onDestroy() {+        super.onDestroy()+        scope.cancel()     }      private fun buildNotification(isSending: Boolean): Notification {-        val title = getString(-            if (isSending) R.string.share_notification_title_sending-            else R.string.share_notification_title_receiving-        )-        val text = getString(R.string.share_notification_text)         val pendingIntent = PendingIntent.getActivity(             this,             0,@@ -95,63 +210,78 @@ class ShareTransferService : Service() {         val stopIntent = PendingIntent.getService(             this,             1,-            Intent(this, ShareTransferService::class.java).setAction(ACTION_STOP),+            Intent(this, ShareTransferService::class.java).setAction(ACTION_TURN_OFF),             PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,         )-        return NotificationCompat.Builder(this, CHANNEL_ID)-            .setSmallIcon(android.R.drawable.stat_sys_download_done)-            .setContentTitle(title)-            .setContentText(text)+        val builder = NotificationCompat.Builder(this, CHANNEL_ID)+            .setSmallIcon(R.drawable.ic_tile_share)+            .setContentTitle(+                getString(+                    if (isSending) R.string.share_notification_title_sending+                    else R.string.share_notification_title_receiving+                )+            )+            .setContentText(+                getString(+                    if (isSending) R.string.share_notification_text_sending+                    else R.string.share_notification_text+                )+            )             .setOngoing(true)             .setContentIntent(pendingIntent)-            .addAction(-                android.R.drawable.ic_delete,+        // "Turn off" belongs to receiving; offering it beside a send would be a lie.+        if (!isSending) {+            builder.addAction(+                R.drawable.ic_tile_share,                 getString(R.string.share_notification_action_stop),                 stopIntent,             )-            .build()+        }+        return builder.build()     }      companion object {         const val ACTION_START_RECEIVE = "com.vayunmathur.share.action.START_RECEIVE"         const val ACTION_START_SEND = "com.vayunmathur.share.action.START_SEND"++        /** Reconcile and stop if nothing needs this service any more. */         const val ACTION_STOP = "com.vayunmathur.share.action.STOP" -        fun startReceiveMode(context: Context, port: Int) {-            val intent = Intent(context, ShareTransferService::class.java).apply {-                action = ACTION_START_RECEIVE-                putExtra(EXTRA_PORT, port)-            }-            start(context, intent)+        /** The foreground notification's own "Turn off", which also flips the persisted flag. */+        const val ACTION_TURN_OFF = "com.vayunmathur.share.action.TURN_OFF"++        const val ACTION_ACCEPT = "com.vayunmathur.share.action.ACCEPT"+        const val ACTION_REJECT = "com.vayunmathur.share.action.REJECT"+        const val ACTION_CANCEL = "com.vayunmathur.share.action.CANCEL"++        /** The native session handle, the only session identity that fits a `PendingIntent`. */+        const val EXTRA_SESSION_HANDLE = "com.vayunmathur.share.EXTRA_SESSION_HANDLE"++        /** So a consumer never has to recompute the notification id it is answering for. */+        const val EXTRA_NOTIF_ID = "com.vayunmathur.share.EXTRA_NOTIF_ID"++        fun startSendMode(context: Context) {+            start(context, Intent(context, ShareTransferService::class.java).setAction(ACTION_START_SEND))         } -        fun startSendMode(context: Context, host: String, port: Int) {+        fun routeSessionAction(context: Context, action: String, handle: Long, notifId: Int) {             val intent = Intent(context, ShareTransferService::class.java).apply {-                action = ACTION_START_SEND-                putExtra(EXTRA_HOST, host)-                putExtra(EXTRA_PORT, port)+                this.action = action+                putExtra(EXTRA_SESSION_HANDLE, handle)+                putExtra(EXTRA_NOTIF_ID, notifId)             }             start(context, intent)         }          fun stop(context: Context) {-            val intent = Intent(context, ShareTransferService::class.java).setAction(ACTION_STOP)-            try {-                context.startService(intent)-            } catch (_: Exception) {-            }+            // startForegroundService, not startService: a background startService throws on+            // Android 8+, and every branch of onStartCommand enters the foreground anyway.+            start(context, Intent(context, ShareTransferService::class.java).setAction(ACTION_STOP))         } -        private const val EXTRA_PORT = "port"-        private const val EXTRA_HOST = "host"-         private fun start(context: Context, intent: Intent) {             try {-                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {-                    context.startForegroundService(intent)-                } else {-                    context.startService(intent)-                }+                context.startForegroundService(intent)             } catch (_: Exception) {             }         }
share/src/main/java/com/vayunmathur/share/protocol/ShareNative.kt
diff --git a/share/src/main/java/com/vayunmathur/share/protocol/ShareNative.kt b/share/src/main/java/com/vayunmathur/share/protocol/ShareNative.ktindex 0111282b6b..40f12fa042 100644--- a/share/src/main/java/com/vayunmathur/share/protocol/ShareNative.kt+++ b/share/src/main/java/com/vayunmathur/share/protocol/ShareNative.kt@@ -105,6 +105,12 @@ internal object ShareNative {     /** Why the session failed, or null while it is healthy. */     external fun nativeQueryFailureReason(handle: Long): String? +    /**+     * The peer's advertised device name, or null before its `CONNECTION_REQUEST` has been+     * read. Prefers the human-readable name inside `endpoint_info` over `endpoint_name`.+     */+    external fun nativeQueryPeerName(handle: Long): String?+     /** Recent protocol events, one per line — which frames each side actually exchanged. */     external fun nativeQueryTrace(handle: Long): String? 
share/src/main/java/com/vayunmathur/share/ui/ShareReceiveScreen.kt
diff --git a/share/src/main/java/com/vayunmathur/share/ui/ShareReceiveScreen.kt b/share/src/main/java/com/vayunmathur/share/ui/ShareReceiveScreen.ktdeleted file mode 100644index 8a43e409ab..0000000000--- a/share/src/main/java/com/vayunmathur/share/ui/ShareReceiveScreen.kt+++ /dev/null@@ -1,357 +0,0 @@-package com.vayunmathur.share.ui--import androidx.activity.compose.rememberLauncherForActivityResult-import androidx.activity.result.contract.ActivityResultContracts-import androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.Row-import androidx.compose.foundation.layout.Spacer-import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.height-import androidx.compose.foundation.layout.padding-import androidx.compose.foundation.layout.width-import androidx.compose.foundation.lazy.LazyColumn-import androidx.compose.foundation.lazy.items-import androidx.compose.runtime.Composable-import androidx.compose.runtime.collectAsState-import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.remember-import androidx.compose.runtime.setValue-import androidx.compose.ui.Alignment-import androidx.compose.ui.Modifier-import androidx.compose.ui.platform.LocalContext-import androidx.compose.ui.res.stringResource-import androidx.compose.ui.unit.dp-import com.vayunmathur.library.ui.Button-import com.vayunmathur.library.ui.Card-import com.vayunmathur.library.ui.CircularProgressIndicator-import com.vayunmathur.library.ui.LinearProgressIndicator-import com.vayunmathur.library.ui.ListItem-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.OutlinedButton-import com.vayunmathur.library.ui.Switch-import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.TextButton-import com.vayunmathur.share.R-import com.vayunmathur.share.domain.protocol.PendingFile-import com.vayunmathur.share.domain.protocol.ShareState-import com.vayunmathur.share.platform.ReceivedFile-import com.vayunmathur.share.platform.ShareViewModel-import com.vayunmathur.share.platform.ShareActions-import com.vayunmathur.share.platform.ReceiveUiState-import com.vayunmathur.share.platform.TransferProgress-import com.vayunmathur.share.network.transport.Connection--@Composable-fun ShareReceiveScreen(-    viewModel: ShareViewModel,-    modifier: Modifier = Modifier,-) {-    val uiState by viewModel.receiveUiState.collectAsState()-    ShareReceiveContent(-        uiState = uiState,-        actions = viewModel,-        modifier = modifier,-    )-}--@Composable-fun ShareReceiveContent(-    uiState: ReceiveUiState,-    actions: ShareActions,-    modifier: Modifier = Modifier,-) {-    LazyColumn(-        modifier = modifier-            .fillMaxSize()-            .padding(horizontal = 16.dp, vertical = 12.dp),-        verticalArrangement = Arrangement.spacedBy(12.dp),-    ) {-        item {-            VisibilityCard(-                isVisible = uiState.isVisible,-                localName = uiState.localName,-                listenPort = uiState.listenPort,-                onToggle = actions::setVisible,-            )-        }-        item {-            Text(-                stringResource(R.string.share_incoming_title),-                style = MaterialTheme.typography.titleMedium,-                modifier = Modifier.padding(top = 4.dp),-            )-        }-        if (uiState.incomingConnections.isEmpty()) {-            item {-                Card(modifier = Modifier.fillMaxWidth()) {-                    Text(-                        stringResource(-                            if (uiState.isVisible) R.string.share_waiting_for_devices-                            else R.string.share_turn_on_visibility-                        ),-                        modifier = Modifier.padding(16.dp),-                        color = MaterialTheme.colorScheme.outline,-                    )

Diff truncated.