Modern Apps git

← Modern-Apps.git

madeveloper: add MA Developer companion app (#madev)

Commit
bf24ba07835d91dc41f2f7d6f74ef241bc8ff73a
Author
Vayun Mathur <[email protected]>
When
2026-11-16 17:25 UTC (19 days ago)
Parents
4f3c69b
New app module madeveloper/ (com.vayunmathur.madeveloper), a developer
companion for the maproj infrastructure, following the backup/ reference
layout: closed package roots (ui data domain platform), AppScaffold
screens, Icons.kt-only icons (IconBugReport, IconInstall added to
library/ui), no Toast, launcher icon via build-logic, metadata_data
listing, and its own module AGENTS.md.

Git pages: the git host serves no repository-browsing pages, so repos
are its fixed clone set with refs parsed from the smart-HTTP
advertisement, and issues, PRs and CI come from its JSON endpoints
(/issues.json, /prs.json, /tests.json). Code browsing reads tree and
file contents via the host's GitHub push-mirror contents API with an
in-memory cache and path filtering; a link-out remains the fallback.

Builds: the F-Droid repo index-v2 is a read-only catalog (newest build
per package, version and size). Installs are server-pushed, not
phone-pulled: a paired WebSocket to wss://api.maproj.org/dev/ws behind
the DevSocketTransport seam, pairing code on first launch, exponential
reconnect backoff plus a WorkManager nudge, ping and listApps handling.
A push downloads over NetworkClient (FIRST_PARTY), verifies SHA-256,
then surfaces a notification and an in-app Install button that opens a
PackageInstaller session — never a silent install.

Verified: :madeveloper:testDevUnitTest, :madeveloper:detekt,
:madeveloper:lint, :madeveloper:compileDevKotlin, root checkMetadata
and ./check madeveloper are all green. Unit tests cover the git and
F-Droid parsers, the push protocol and install state machine, and the
main state holders. No push: the branch stays local for review.

Diff

library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.ktindex 6be064d036..a5b6451881 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt@@ -168,6 +168,8 @@ import androidx.compose.material.icons.filled.DarkMode import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.DeleteForever import androidx.compose.material.icons.filled.Description+import androidx.compose.material.icons.filled.BugReport+import androidx.compose.material.icons.filled.SystemUpdateAlt import androidx.compose.material.icons.filled.Directions import androidx.compose.material.icons.filled.Download import androidx.compose.material.icons.filled.DragHandle@@ -1968,3 +1970,11 @@ private val HelpOutlineVector: ImageVector by lazy {         fill = SolidColor(Color.Black),     ).build() }++@Composable+fun IconBugReport(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+    AppIcon(Icons.Filled.BugReport, "Bug report", modifier, tint)++@Composable+fun IconInstall(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+    AppIcon(Icons.Filled.SystemUpdateAlt, "Install", modifier, tint)
madeveloper/AGENTS.md
diff --git a/madeveloper/AGENTS.md b/madeveloper/AGENTS.mdnew file mode 100644index 0000000000..12c8b21f16--- /dev/null+++ b/madeveloper/AGENTS.md@@ -0,0 +1,58 @@+# AGENTS.md — madeveloper/ (':madeveloper')++> Scoped supplement. Global rules in root `AGENTS.md` apply. Stay inside `madeveloper/` + allowed shared modules. Do not root-scan.++_Install: ./install madeveloper (dev by default)._+<!-- last-reviewed: 2026-11-16 -->+- Gradle: :madeveloper / dir: madeveloper/+- Package roots present: ui, data, domain, platform+- Entry files: MainActivity.kt, Route.kt, Navigation.kt+- Deps: :library:network, :library:work+- Metadata: metadata_data/madeveloper.md (present)+- Rust: no / screenshotTest: yes++## Overview+**Purpose:** Developer companion for the maproj infrastructure: git host pages, CI status, a read-only build catalog, and server-pushed dev installs.+**Key features:**+- Git pages over the host JSON (`/tests.json`, `/issues.json`, `/prs.json`) and smart-HTTP refs; the host has no repo-browsing pages, so files read via its GitHub push-mirror+- Read-only F-Droid catalog (`static.maproj.org/fdroid/repo/index-v2.json`, newest build per package)+- Pushed installs: paired WebSocket to `wss://api.maproj.org/dev/ws`, download + SHA-256 verify, then a user-tapped PackageInstaller session (never silent)+**Architecture / data-flow:** `ui/` screens → `platform/MaDevViewModel` → `data/GitHostRepository` (NetworkClient, FIRST_PARTY) + `data/DevPushClient` seam over `WebSocketClient`; pure parsing and the install state machine live in `domain/` (`GitParsers`, `DevProtocol`) with no Android imports.+**Entry points + reading order:** `Route` → `MainActivity.kt` → `Navigation.kt` → `platform/MaDevViewModel.kt` → `data/GitHostRepository.kt` / `domain/DevProtocol.kt`.+**Gotchas:**+- The git host exposes no commits/tree/file endpoints — do not invent them; mirror reads plus a link-out are the honest v1+- Android forbids silent installs here by design: a push only downloads and verifies, the Install button and system prompt do the rest+- The `/dev/ws` server endpoint is built in parallel; the client is coded to the agreed JSON contract behind `DevSocketTransport`++## Key files+### Root — entry + navigation+- com/vayunmathur/madeveloper/MainActivity.kt+- com/vayunmathur/madeveloper/Navigation.kt+- com/vayunmathur/madeveloper/Route.kt+### data/ — git host, catalog and push transport+- com/vayunmathur/madeveloper/data/GitHostRepository.kt+- com/vayunmathur/madeveloper/data/DevPushClient.kt+### domain/ — pure models, parsers and push protocol+- com/vayunmathur/madeveloper/domain/GitModels.kt+- com/vayunmathur/madeveloper/domain/GitParsers.kt+- com/vayunmathur/madeveloper/domain/DevProtocol.kt+### platform/ — view model, pairing, notifications, installer+- com/vayunmathur/madeveloper/platform/MaDevViewModel.kt+- com/vayunmathur/madeveloper/platform/PairingStore.kt+- com/vayunmathur/madeveloper/platform/InstallNotifications.kt+- com/vayunmathur/madeveloper/platform/InstallStatusReceiver.kt+- com/vayunmathur/madeveloper/platform/ReconnectWorker.kt+### ui/ — screens+- com/vayunmathur/madeveloper/ui/HomeScreen.kt+- com/vayunmathur/madeveloper/ui/RepoScreen.kt+- com/vayunmathur/madeveloper/ui/FileScreen.kt+- com/vayunmathur/madeveloper/ui/TestsScreen.kt+- com/vayunmathur/madeveloper/ui/CatalogScreen.kt+- com/vayunmathur/madeveloper/ui/PushScreen.kt++## Verify (this module only)+```+./gradlew :madeveloper:compileDevKotlin+./gradlew :madeveloper:lint+./gradlew :madeveloper:checkMetadata+```
madeveloper/build.gradle.kts
diff --git a/madeveloper/build.gradle.kts b/madeveloper/build.gradle.ktsnew file mode 100644index 0000000000..f8691e8e8d--- /dev/null+++ b/madeveloper/build.gradle.kts@@ -0,0 +1,19 @@+plugins {+    id("common-conventions-app")+    id("common-conventions-preview-metadata")+}++launcherIcon {+    symbol = "code"+}++android {+    defaultConfig {+        applicationId = "com.vayunmathur.madeveloper"+    }+}++dependencies {+    implementation(project(":library:network"))+    implementation(project(":library:work"))+}
madeveloper/src/main/AndroidManifest.xml
diff --git a/madeveloper/src/main/AndroidManifest.xml b/madeveloper/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..a46f5f5733--- /dev/null+++ b/madeveloper/src/main/AndroidManifest.xml@@ -0,0 +1,34 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android"+    xmlns:tools="http://schemas.android.com/tools">++    <uses-permission android:name="com.vayunmathur.permission.SENSORS_OPTOUT" />+    <uses-permission android:name="android.permission.INTERNET" />+    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />+    <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />+    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />+    <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"+        tools:ignore="QueryAllPackagesPermission" />++    <application+        android:allowBackup="true"+        android:dataExtractionRules="@xml/data_extraction_rules"+        android:icon="@mipmap/ic_launcher"+        android:label="@string/app_name"+        android:roundIcon="@mipmap/ic_launcher"+        android:supportsRtl="true"+        android:theme="@style/Theme.General">+        <activity+            android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+            android:name=".MainActivity"+            android:exported="true"+            android:launchMode="singleTask"+            android:theme="@style/Theme.General">+            <intent-filter>+                <action android:name="android.intent.action.MAIN" />+                <category android:name="android.intent.category.LAUNCHER" />+            </intent-filter>+        </activity>+        <receiver android:name=".platform.InstallStatusReceiver" android:exported="false" />+    </application>+</manifest>
madeveloper/src/main/java/com/vayunmathur/madeveloper/MainActivity.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/MainActivity.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/MainActivity.ktnew file mode 100644index 0000000000..84547c05c7--- /dev/null+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/MainActivity.kt@@ -0,0 +1,24 @@+package com.vayunmathur.madeveloper++import androidx.activity.viewModels+import androidx.compose.runtime.Composable+import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.library.network.TrustBundle+import com.vayunmathur.library.ui.MaActivity+import com.vayunmathur.madeveloper.platform.MaDevViewModel+import com.vayunmathur.madeveloper.platform.ReconnectWorker++/** Entry activity for MA Developer. */+class MainActivity : MaActivity() {+    private val viewModel: MaDevViewModel by viewModels()++    override fun onCreateBeforeContent() {+        NetworkClient.init(this, TrustBundle.FIRST_PARTY)+        ReconnectWorker.schedule(this)+    }++    @Composable+    override fun Content() {+        Navigation(viewModel)+    }+}
madeveloper/src/main/java/com/vayunmathur/madeveloper/Navigation.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/Navigation.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/Navigation.ktnew file mode 100644index 0000000000..049fe3d5db--- /dev/null+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/Navigation.kt@@ -0,0 +1,49 @@+package com.vayunmathur.madeveloper++import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.rememberNavBackStack+import com.vayunmathur.madeveloper.platform.MaDevViewModel+import com.vayunmathur.madeveloper.ui.CatalogScreen+import com.vayunmathur.madeveloper.ui.FileScreen+import com.vayunmathur.madeveloper.ui.HomeScreen+import com.vayunmathur.madeveloper.ui.PushScreen+import com.vayunmathur.madeveloper.ui.RepoScreen+import com.vayunmathur.madeveloper.ui.TestsScreen++/** Navigation for MA Developer. */+@Composable+fun Navigation(viewModel: MaDevViewModel) {+    val backStack = rememberNavBackStack<Route>(Route.Home)+    LaunchedEffect(Unit) { viewModel.loadHome() }+    MainNavigation(backStack) {+        entry<Route.Home> {+            HomeScreen(+                state = viewModel.state,+                onRefresh = viewModel::refresh,+                onOpenRepo = { backStack.add(Route.Repo(it)) },+                onOpenTests = { backStack.add(Route.Tests) },+                onOpenCatalog = { backStack.add(Route.Catalog) },+                onOpenPush = { backStack.add(Route.Push) },+            )+        }+        entry<Route.Repo> { route ->+            RepoScreen(+                repoName = route.name, viewModel = viewModel,+                onOpenFile = { backStack.add(Route.File(route.name, it)) }, onBack = { backStack.pop() },+            )+        }+        entry<Route.File> { route ->+            FileScreen(repoName = route.repo, path = route.path, viewModel = viewModel, onBack = { backStack.pop() })+        }+        entry<Route.Tests> { TestsScreen(state = viewModel.state, onBack = { backStack.pop() }) }+        entry<Route.Catalog> {+            LaunchedEffect(Unit) { viewModel.loadCatalog() }+            CatalogScreen(state = viewModel.state, onBack = { backStack.pop() })+        }+        entry<Route.Push> {+            PushScreen(state = viewModel.state, onInstall = viewModel::installPending, onBack = { backStack.pop() })+        }+    }+}
madeveloper/src/main/java/com/vayunmathur/madeveloper/Route.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/Route.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/Route.ktnew file mode 100644index 0000000000..6de8f8b77d--- /dev/null+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/Route.kt@@ -0,0 +1,32 @@+package com.vayunmathur.madeveloper++import com.vayunmathur.library.util.NavKey+import kotlinx.serialization.Serializable++@Serializable+/** Navigation destinations for MA Developer. */+sealed interface Route : NavKey {+    @Serializable+    /** Home: repositories, CI summary and push status. */+    data object Home : Route++    @Serializable+    /** One repository: refs, issues, pull requests and file tree. */+    data class Repo(val name: String) : Route++    @Serializable+    /** One file in a repository, shown with line numbers. */+    data class File(val repo: String, val path: String) : Route++    @Serializable+    /** Full CI history from the git host tests page. */+    data object Tests : Route++    @Serializable+    /** Read-only catalog of available builds from the F-Droid repo. */+    data object Catalog : Route++    @Serializable+    /** Pairing and server-pushed installs. */+    data object Push : Route+}
madeveloper/src/main/java/com/vayunmathur/madeveloper/data/DevPushClient.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/data/DevPushClient.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/data/DevPushClient.ktnew file mode 100644index 0000000000..3d4d5a5753--- /dev/null+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/data/DevPushClient.kt@@ -0,0 +1,34 @@+package com.vayunmathur.madeveloper.data++import com.vayunmathur.library.network.WebSocketClient+import com.vayunmathur.madeveloper.domain.DevMessage+import com.vayunmathur.madeveloper.domain.DevProtocol+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.mapNotNull++/** Transport seam for the dev push socket, so protocol logic tests never open a socket. */+interface DevSocketTransport {+    /** Inbound server messages, already parsed. */+    val messages: Flow<DevMessage>+    /** Sends one text frame. */+    suspend fun send(text: String)+    /** Closes the socket. */+    suspend fun close()+}++/** [DevSocketTransport] over the shared [WebSocketClient]. */+class WebSocketDevTransport private constructor(private val client: WebSocketClient) : DevSocketTransport {+    override val messages: Flow<DevMessage> = client.incomingFlow().mapNotNull { frame ->+        (frame as? WebSocketClient.WsFrame.Text)?.let { DevProtocol.parse(it.text) }+    }+    override suspend fun send(text: String) = client.send(text)+    override suspend fun close() = client.close()++    /** Opens the socket to [url] with an optional bearer [token]. */+    companion object {+        suspend fun connect(url: String, token: String?): WebSocketDevTransport {+            val headers = if (token.isNullOrBlank()) emptyMap() else mapOf("Authorization" to "Bearer $token")+            return WebSocketDevTransport(WebSocketClient.connect(url, headers))+        }+    }+}
madeveloper/src/main/java/com/vayunmathur/madeveloper/data/GitHostRepository.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/data/GitHostRepository.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/data/GitHostRepository.ktnew file mode 100644index 0000000000..f07a0af1be--- /dev/null+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/data/GitHostRepository.kt@@ -0,0 +1,106 @@+package com.vayunmathur.madeveloper.data++import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.madeveloper.domain.CatalogApp+import com.vayunmathur.madeveloper.domain.GitIssue+import com.vayunmathur.madeveloper.domain.GitParsers+import com.vayunmathur.madeveloper.domain.GitPr+import com.vayunmathur.madeveloper.domain.GitRepo+import com.vayunmathur.madeveloper.domain.TestsStatus+import com.vayunmathur.madeveloper.domain.TreeEntry+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.contentOrNull+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive+import kotlinx.serialization.json.longOrNull+import java.util.Base64++/**+ * Reads the maproj git host through [NetworkClient] (FIRST_PARTY trust is set+ * once by the activity). The host serves clone + dashboards only, so code+ * browsing reads the host's own GitHub push-mirror contents API; every screen+ * still links out to the canonical git host page as a fallback.+ */+class GitHostRepository {+    private val json = Json { ignoreUnknownKeys = true; isLenient = true }+    private var treeCache: Map<String, List<TreeEntry>> = emptyMap()+    private var fileCache: Map<String, String> = emptyMap()++    /** Repositories with their advertised refs filled in. */+    suspend fun repos(): List<GitRepo> = GitParsers.knownRepos.map { repo ->+        val refs = runCatching {+            val refsUrl = repo.cloneUrl.removeSuffix(".git") + ".git/info/refs?service=git-upload-pack"+            val (status, bytes) = NetworkClient.performRequestBytes(refsUrl)+            if (status in 200..299) GitParsers.parseRefs(bytes) else emptyList()+        }.getOrDefault(emptyList())+        repo.copy(refs = refs)+    }++    /** CI status from `/tests.json`. */+    suspend fun tests(): TestsStatus = fetchText("$GIT_HOST/tests.json").let(GitParsers::parseTests)++    /** Open issues from `/issues.json?view=open`. */+    suspend fun issues(): List<GitIssue> = GitParsers.parseIssues(fetchText("$GIT_HOST/issues.json?view=open"))++    /** Open pull requests from `/prs.json`. */+    suspend fun prs(): List<GitPr> = GitParsers.parsePrs(fetchText("$GIT_HOST/prs.json"))++    /** Available builds from the first-party F-Droid repo (read-only catalog). */+    suspend fun catalog(): List<CatalogApp> =+        GitParsers.parseFdroidIndex(fetchText("$FDROID_BASE/index-v2.json"), FDROID_BASE)++    /** Tree of [path] in [repo] via the mirror contents API; cached per repo+path. */+    suspend fun tree(repo: GitRepo, path: String): List<TreeEntry> {+        val key = repo.name + ":" + path+        treeCache[key]?.let { return it }+        val github = repo.github ?: return emptyList()+        val url = "https://api.github.com/repos/$github/contents/$path"+        val entries = parseTree(fetchText(url))+        treeCache = treeCache + (key to entries)+        return entries+    }++    /** File text of [path] in [repo] via the mirror contents API; cached. */+    suspend fun file(repo: GitRepo, path: String): String {+        val key = repo.name + ":" + path+        fileCache[key]?.let { return it }+        val github = repo.github ?: return ""+        val root = json.parseToJsonElement(fetchText("https://api.github.com/repos/$github/contents/$path")).jsonObject+        val encoded = root["content"]?.jsonPrimitive?.contentOrNull ?: return ""+        val text = withContext(Dispatchers.IO) { String(Base64.getMimeDecoder().decode(encoded), Charsets.UTF_8) }+        fileCache = fileCache + (key to text)+        return text+    }++    private fun parseTree(text: String): List<TreeEntry> {+        val root = json.parseToJsonElement(text)+        val array = root as? JsonArray ?: return emptyList()+        return array.mapNotNull { element ->+            val obj = element as? JsonObject ?: return@mapNotNull null+            TreeEntry(+                name = obj["name"]?.jsonPrimitive?.contentOrNull ?: return@mapNotNull null,+                path = obj["path"]?.jsonPrimitive?.contentOrNull ?: "",+                isDir = obj["type"]?.jsonPrimitive?.contentOrNull == "dir",+                size = obj["size"]?.jsonPrimitive?.longOrNull,+            )+        }.sortedWith(compareByDescending<TreeEntry> { it.isDir }.thenBy { it.name.lowercase() })+    }++    private suspend fun fetchText(url: String): String {+        val headers = mapOf("Accept" to "application/json", "User-Agent" to "MADeveloper/1.0")+        val response = NetworkClient.performRequest(url, headers = headers)+        if (!response.isSuccess) throw java.io.IOException("HTTP " + response.status + " for " + url)+        return response.body+    }++    /** Hosts and endpoints this app talks to. */+    companion object {+        const val GIT_HOST = "https://git.maproj.org"+        const val FDROID_BASE = "https://static.maproj.org/fdroid/repo"+        const val DEV_WS_URL = "wss://api.maproj.org/dev/ws"+    }+}
madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/DevProtocol.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/DevProtocol.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/DevProtocol.ktnew file mode 100644index 0000000000..273702283d--- /dev/null+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/DevProtocol.kt@@ -0,0 +1,118 @@+package com.vayunmathur.madeveloper.domain++import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.contentOrNull+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive+import kotlinx.serialization.json.longOrNull+import java.security.MessageDigest++/** A server-to-device message on the dev push socket. */+sealed interface DevMessage {+    /** The server is alive; the client answers with a pong frame. */+    data object Ping : DevMessage+    /** The server asks which first-party packages are installed. */+    data object ListApps : DevMessage+    /** The server has paired this device and issued a durable token. */+    data class Paired(val token: String, val deviceId: String) : DevMessage+    /** A build the server wants installed on this device. */+    data class Install(+        val pkg: String, val versionCode: Long, val apkUrl: String,+        val sha256: String, val sizeBytes: Long,+    ) : DevMessage+    /** Anything else: kept verbatim so a new server type never crashes the client. */+    data class Unknown(val raw: String) : DevMessage+}++/** One installed first-party package reported back to the server. */+data class InstalledAppInfo(val pkg: String, val versionCode: Long)++/** Lifecycle of one pushed install, from push to the system installer. */+enum class InstallPhase { PUSHED, DOWNLOADING, VERIFYING, READY, INSTALLING, DONE, FAILED }++/** State of one pushed install; [progress] is 0f..1f while downloading. */+data class PendingInstall(+    val pkg: String, val versionCode: Long, val apkUrl: String, val sha256: String, val sizeBytes: Long,+    val phase: InstallPhase = InstallPhase.PUSHED, val progress: Float = 0f, val error: String? = null,+)++/** Pure protocol and install-state logic for the dev push channel. */+object DevProtocol {+    private val json = Json { ignoreUnknownKeys = true; isLenient = true }+    private const val CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"+    private const val CODE_LENGTH = 6+    private const val MAX_BACKOFF_MS = 60_000L+    private const val BASE_BACKOFF_MS = 1_000L++    /** A short human-typable pairing code shown on first launch. */+    fun newPairingCode(random: java.util.Random = java.security.SecureRandom()): String =+        buildString { repeat(CODE_LENGTH) { append(CODE_ALPHABET[random.nextInt(CODE_ALPHABET.length)]) } }++    /** Parses one text frame from the server; malformed frames become [DevMessage.Unknown]. */+    fun parse(text: String): DevMessage {+        val root = try {+            json.parseToJsonElement(text).jsonObject+        } catch (_: Exception) {+            return DevMessage.Unknown(text)+        }+        return when (root.s("type")) {+            "ping" -> DevMessage.Ping+            "listApps" -> DevMessage.ListApps+            "paired" -> DevMessage.Paired(root.s("token"), root.s("deviceId"))+            "install" -> DevMessage.Install(+                pkg = root.s("package"), versionCode = root["versionCode"]?.jsonPrimitive?.longOrNull ?: 0L,+                apkUrl = root.s("apkUrl"), sha256 = root.s("sha256"),+                sizeBytes = root["sizeBytes"]?.jsonPrimitive?.longOrNull ?: 0L,+            )+            else -> DevMessage.Unknown(text)+        }+    }++    /** The reply to a [DevMessage.ListApps] request. */+    fun listAppsReply(apps: List<InstalledAppInfo>): String = buildString {+        append("{\"type\":\"apps\",\"apps\":[")+        apps.forEachIndexed { index, app ->+            if (index > 0) append(',')+            append("{\"package\":\"").append(app.pkg).append("\",\"versionCode\":").append(app.versionCode).append('}')+        }+        append("]}")+    }++    /** Exponential reconnect backoff in milliseconds, capped, by 0-based attempt. */+    fun backoffMs(attempt: Int): Long {+        var delay = BASE_BACKOFF_MS+        repeat(attempt.coerceIn(0, 20)) { delay = (delay * 2).coerceAtMost(MAX_BACKOFF_MS) }+        return delay+    }++    /** Advances the install state machine; illegal jumps keep the current phase. */+    fun transition(+        current: PendingInstall, phase: InstallPhase,+        progress: Float = current.progress, error: String? = null,+    ): PendingInstall {+        val allowed = when (current.phase) {+            InstallPhase.PUSHED -> phase in setOf(InstallPhase.DOWNLOADING, InstallPhase.FAILED)+            InstallPhase.DOWNLOADING -> phase in setOf(InstallPhase.VERIFYING, InstallPhase.FAILED)+            InstallPhase.VERIFYING -> phase in setOf(InstallPhase.READY, InstallPhase.FAILED)+            InstallPhase.READY -> phase in setOf(InstallPhase.INSTALLING, InstallPhase.FAILED)+            InstallPhase.INSTALLING -> phase in setOf(InstallPhase.DONE, InstallPhase.FAILED, InstallPhase.READY)+            InstallPhase.DONE, InstallPhase.FAILED -> false+        }+        return if (allowed) {+            current.copy(phase = phase, progress = progress.coerceIn(0f, 1f), error = error)+        } else {+            current+        }+    }++    /** SHA-256 of [bytes] as lowercase hex, for comparison with a pushed digest. */+    fun sha256Hex(bytes: ByteArray): String =+        MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) }++    /** True when [bytes] hash to the expected lowercase/uppercase hex digest. */+    fun verifySha256(bytes: ByteArray, expected: String): Boolean =+        expected.isNotBlank() && sha256Hex(bytes).equals(expected.trim(), ignoreCase = true)++    private fun JsonObject.s(key: String): String = this[key]?.jsonPrimitive?.contentOrNull ?: ""+}
madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/GitModels.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/GitModels.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/GitModels.ktnew file mode 100644index 0000000000..53c8e5c244--- /dev/null+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/GitModels.kt@@ -0,0 +1,47 @@+package com.vayunmathur.madeveloper.domain++/** A repository hosted on the maproj git host. */+data class GitRepo(val name: String, val cloneUrl: String, val github: String?, val refs: List<GitRef> = emptyList())++/** One advertised git reference (branch or tag) from `info/refs`. */+data class GitRef(val name: String, val sha: String) {+    /** Short form of [sha] for display. */+    val shortSha: String get() = sha.take(8)+}++/** One issue as served by `/issues.json`. */+data class GitIssue(+    val repo: String, val number: Int, val title: String, val author: String,+    val comments: Int, val labels: List<String>, val updatedAt: String,+)++/** One pull request as served by `/prs.json`. */+data class GitPr(val repo: String, val number: Int, val title: String, val author: String)++/** One CI run from `/tests.json`. */+data class TestRun(+    val id: String, val sha: String, val subject: String, val status: String,+    val failed: Int, val tests: Int, val durationSecs: Long?,+)++/** The latest CI state plus optional in-progress run from `/tests.json`. */+data class TestsStatus(+    val latest: TestRun?, val running: TestRun?,+    val history: List<TestRun>, val coveragePct: Double?,+)++/** One entry in a repository tree listing. */+data class TreeEntry(val name: String, val path: String, val isDir: Boolean, val size: Long?)++/** One installable build in the read-only F-Droid catalog. */+data class CatalogApp(+    val packageName: String, val name: String, val summary: String,+    val versionName: String?, val versionCode: Long, val sizeBytes: Long, val apkPath: String?,+) {+    /** Human-readable size for display. */+    val sizeLabel: String get() = when {+        sizeBytes >= 1_000_000 -> "%.1f MB".format(sizeBytes / 1_000_000.0)+        sizeBytes >= 1_000 -> "%.0f KB".format(sizeBytes / 1_000.0)+        else -> "$sizeBytes B"+    }+}
madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/GitParsers.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/GitParsers.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/GitParsers.ktnew file mode 100644index 0000000000..821afed535--- /dev/null+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/GitParsers.kt@@ -0,0 +1,172 @@+package com.vayunmathur.madeveloper.domain++import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.contentOrNull+import kotlinx.serialization.json.doubleOrNull+import kotlinx.serialization.json.intOrNull+import kotlinx.serialization.json.jsonArray+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive+import kotlinx.serialization.json.longOrNull++/**+ * Pure parsers for the machine-readable forms the git host and F-Droid repo+ * actually expose. The git host has no repository-browsing pages: repositories+ * are the fixed clone set, refs come from the smart-HTTP advertisement, and+ * issues, pull requests and CI all serve JSON next to their HTML pages.+ */+object GitParsers {+    private val json = Json { ignoreUnknownKeys = true; isLenient = true }++    /** Repositories known to the host, from its landing-page clone URLs. */+    val knownRepos: List<GitRepo> = listOf(+        GitRepo("Modern-Apps", "https://git.maproj.org/Modern-Apps.git", "vayun-mathur/Modern-Apps"),+        GitRepo("MAOS", "https://git.maproj.org/MAOS.git", "vayun-mathur/MAOS"),+        GitRepo(+            "location_share_server",+            "https://git.maproj.org/location_share_server.git", "vayun-mathur/location_share_server",+        ),+    )++    /** Parses the pkt-line ref advertisement of `GET /<repo>/info/refs?service=git-upload-pack`. */+    fun parseRefs(body: ByteArray): List<GitRef> {+        val text = body.toString(Charsets.UTF_8)+        val refs = mutableListOf<GitRef>()+        for (line in text.split('\n')) {+            val clean = line.trim()+            if (clean.length < 45) continue+            val payload = clean.drop(4)+            val parts = payload.split(' ', '\t', '\u0000')+            if (parts.size < 2) continue+            val sha = parts[0].trim()+            val ref = parts[1].trim().removeSuffix("^{}")+            if (sha.length in 40..64 && ref.startsWith("refs/")) {+                refs += GitRef(ref.removePrefix("refs/heads/").removePrefix("refs/tags/"), sha)+            }+        }+        return refs.distinctBy { it.name }+    }++    /** Parses `/tests.json` into the latest state plus recent history. */+    fun parseTests(text: String): TestsStatus {+        val root = json.parseToJsonElement(text).jsonObject+        fun run(obj: JsonObject?): TestRun? {+            if (obj == null) return null+            return TestRun(+                id = obj.s("id"), sha = obj.s("sha"), subject = obj.s("subject"),+                status = obj.s("status"), failed = obj.i("failed"), tests = obj.i("tests"),+                durationSecs = obj["duration_secs"]?.jsonPrimitive?.longOrNull,+            )+        }+        val latestObj = root["latest"] as? JsonObject+        val coverage = (latestObj?.get("coverage") as? JsonObject)?.let { cov ->+            val covered = cov["covered"]?.jsonPrimitive?.doubleOrNull+            val total = cov["total"]?.jsonPrimitive?.doubleOrNull+            if (covered != null && total != null && total > 0) covered * 100.0 / total else null+        }+        return TestsStatus(+            latest = run(latestObj), running = run(root["running"] as? JsonObject),+            history = (root["history"] as? JsonArray).orEmpty().mapNotNull { run(it as? JsonObject) },+            coveragePct = coverage,+        )+    }++    /** Parses `/issues.json?view=open`. */+    fun parseIssues(text: String): List<GitIssue> {+        val root = json.parseToJsonElement(text).jsonObject+        val out = mutableListOf<GitIssue>()+        for (repo in (root["repos"] as? JsonArray).orEmpty()) {+            val repoObj = repo as? JsonObject ?: continue+            val github = repoObj.s("github")+            for (issue in (repoObj["issues"] as? JsonArray).orEmpty()) {+                val o = issue as? JsonObject ?: continue+                out += GitIssue(+                    repo = github, number = o.i("number"), title = o.s("title"), author = o.s("author"),+                    comments = o.i("comments"),+                    labels = (o["labels"] as? JsonArray).orEmpty()+                        .mapNotNull { (it as? JsonObject)?.s("name")?.takeIf { n -> n.isNotBlank() } },+                    updatedAt = o.s("updated_at"),+                )+            }+        }+        return out+    }++    /** Parses `/prs.json`; tolerant of both a title/author shape and minimal rows. */+    fun parsePrs(text: String): List<GitPr> {+        val root = json.parseToJsonElement(text).jsonObject+        val out = mutableListOf<GitPr>()+        for (repo in (root["repos"] as? JsonArray).orEmpty()) {+            val repoObj = repo as? JsonObject ?: continue+            val repoName = repoObj.s("repo").ifBlank { repoObj.s("github") }+            for (pr in (repoObj["prs"] as? JsonArray).orEmpty()) {+                val o = pr as? JsonObject ?: continue+                out += GitPr(repoName, o.i("number"), o.s("title").ifBlank { "Pull request" }, o.s("author"))+            }+        }+        return out+    }++    /**+     * Parses the F-Droid `index-v2.json` shape (packages -> metadata + versions)+     * into the newest build per package. Pure over the decoded bytes so the+     * catalog can be unit-tested without a network or an Android runtime.+     */+    fun parseFdroidIndex(text: String, repoBase: String): List<CatalogApp> {+        val root = json.parseToJsonElement(text).jsonObject+        val packages = root["packages"] as? JsonObject ?: return emptyList()+        val out = mutableListOf<CatalogApp>()+        for ((pkg, value) in packages) {+            val entry = value as? JsonObject ?: continue+            val meta = entry["metadata"] as? JsonObject+            val versions = entry["versions"] as? JsonObject ?: continue+            newestCatalogApp(pkg, meta, versions, repoBase)?.let { out += it }+        }+        return out.sortedBy { it.name.lowercase() }+    }++    private fun newestCatalogApp(+        pkg: String, meta: JsonObject?, versions: JsonObject, repoBase: String,+    ): CatalogApp? {+        var best: CatalogApp? = null+        for ((_, versionValue) in versions) {+            val version = versionValue as? JsonObject ?: continue+            val candidate = catalogCandidate(pkg, meta, version, repoBase) ?: continue+            if (best == null || candidate.versionCode > best.versionCode) best = candidate+        }+        return best+    }++    private fun catalogCandidate(+        pkg: String, meta: JsonObject?, version: JsonObject, repoBase: String,+    ): CatalogApp? {+        val manifest = version["manifest"] as? JsonObject ?: return null+        val code = manifest["versionCode"]?.jsonPrimitive?.longOrNull ?: return null+        val file = version["file"] as? JsonObject+        val fileName = file?.get("name")?.jsonPrimitive?.contentOrNull+        return CatalogApp(+            packageName = pkg,+            name = meta?.localized("name") ?: pkg.substringAfterLast('.'),+            summary = meta?.localized("summary") ?: "",+            versionName = manifest["versionName"]?.jsonPrimitive?.contentOrNull,+            versionCode = code,+            sizeBytes = file?.get("size")?.jsonPrimitive?.longOrNull ?: 0L,+            apkPath = fileName?.let { repoBase.trimEnd('/') + "/" + it.trimStart('/') },+        )+    }++    private fun JsonObject.localized(key: String): String? {+        val value = this[key] ?: return null+        if (value is JsonObject) {+            return value["en-US"]?.jsonPrimitive?.contentOrNull+                ?: value.values.firstOrNull()?.jsonPrimitive?.contentOrNull+        }+        return value.jsonPrimitive.contentOrNull+    }++    private fun JsonArray?.orEmpty(): List<kotlinx.serialization.json.JsonElement> = this ?: emptyList()+    private fun JsonObject.s(key: String): String = this[key]?.jsonPrimitive?.contentOrNull ?: ""+    private fun JsonObject.i(key: String): Int = this[key]?.jsonPrimitive?.intOrNull ?: 0+}
madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/InstallNotifications.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/InstallNotifications.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/InstallNotifications.ktnew file mode 100644index 0000000000..316b8800cb--- /dev/null+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/InstallNotifications.kt@@ -0,0 +1,37 @@+package com.vayunmathur.madeveloper.platform++import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.PendingIntent+import android.content.Context+import android.content.Intent+import androidx.core.app.NotificationCompat+import com.vayunmathur.madeveloper.MainActivity+import com.vayunmathur.madeveloper.domain.PendingInstall++/** Notifications for server-pushed installs; the install itself always needs a tap. */+object InstallNotifications {+    private const val CHANNEL = "push-installs"++    /** Tells the user a build was pushed and is downloading. */+    fun showPending(context: Context, install: PendingInstall) =+        notify(context, install, "Dev build pushed", install.pkg + " is downloading")++    /** Tells the user a verified build is ready; tapping opens the app to confirm. */+    fun showReady(context: Context, install: PendingInstall) =+        notify(context, install, "Dev build ready to install", "Tap to install " + install.pkg)++    private fun notify(context: Context, install: PendingInstall, title: String, text: String) {+        val manager = context.getSystemService(NotificationManager::class.java) ?: return+        val channel = NotificationChannel(CHANNEL, "Pushed installs", NotificationManager.IMPORTANCE_DEFAULT)+        manager.createNotificationChannel(channel)+        val intent = Intent(context, MainActivity::class.java)+            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)+        val flags = PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE+        val pending = PendingIntent.getActivity(context, install.pkg.hashCode(), intent, flags)+        val notification = NotificationCompat.Builder(context, CHANNEL)+            .setSmallIcon(android.R.drawable.stat_sys_download_done)+            .setContentTitle(title).setContentText(text).setContentIntent(pending).setAutoCancel(true).build()+        manager.notify(install.pkg.hashCode(), notification)+    }+}
madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/InstallStatusReceiver.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/InstallStatusReceiver.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/InstallStatusReceiver.ktnew file mode 100644index 0000000000..42bf7a1fea--- /dev/null+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/InstallStatusReceiver.kt@@ -0,0 +1,31 @@+package com.vayunmathur.madeveloper.platform++import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.content.pm.PackageInstaller+import com.vayunmathur.library.log.Log++/** Receives PackageInstaller session results for pushed installs. */+class InstallStatusReceiver : BroadcastReceiver() {+    override fun onReceive(context: Context, intent: Intent) {+        val status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE)+        val pkg = intent.getStringExtra(PackageInstaller.EXTRA_PACKAGE_NAME) ?: ""+        when (status) {+            PackageInstaller.STATUS_PENDING_USER_ACTION -> {+                val confirm = intent.getParcelableExtra<Intent>(Intent.EXTRA_INTENT)+                if (confirm != null) context.startActivity(confirm.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))+            }+            PackageInstaller.STATUS_SUCCESS -> Log.status(TAG, "Installed $pkg")+            else -> Log.error(+                TAG, "Install failed for $pkg status=$status",+            )+        }+    }++    /** Logging tag and intent action for install results. */+    companion object {+        private const val TAG = "MaDevInstall"+        const val ACTION = "com.vayunmathur.madeveloper.INSTALL_STATUS"+    }+}
madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/MaDevViewModel.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/MaDevViewModel.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/MaDevViewModel.ktnew file mode 100644index 0000000000..25e7dfd8c9--- /dev/null+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/MaDevViewModel.kt@@ -0,0 +1,236 @@+package com.vayunmathur.madeveloper.platform++import android.app.Application+import android.app.PendingIntent+import android.content.Intent+import android.content.pm.PackageInstaller+import android.content.pm.PackageManager+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.viewModelScope+import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.madeveloper.data.GitHostRepository+import com.vayunmathur.madeveloper.data.WebSocketDevTransport+import com.vayunmathur.madeveloper.domain.CatalogApp+import com.vayunmathur.madeveloper.domain.DevMessage+import com.vayunmathur.madeveloper.domain.DevProtocol+import com.vayunmathur.madeveloper.domain.GitIssue+import com.vayunmathur.madeveloper.domain.GitPr+import com.vayunmathur.madeveloper.domain.GitRepo+import com.vayunmathur.madeveloper.domain.InstallPhase+import com.vayunmathur.madeveloper.domain.InstalledAppInfo+import com.vayunmathur.madeveloper.domain.PendingInstall+import com.vayunmathur.madeveloper.domain.TestsStatus+import com.vayunmathur.madeveloper.domain.TreeEntry+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import java.io.File+import java.security.MessageDigest++/** UI state for the git, catalog and push areas. */+data class MaDevUiState(+    val loading: Boolean = false,+    val error: String? = null,+    val repos: List<GitRepo> = emptyList(),+    val tests: TestsStatus? = null,+    val issues: List<GitIssue> = emptyList(),+    val prs: List<GitPr> = emptyList(),+    val catalog: List<CatalogApp> = emptyList(),+    val connected: Boolean = false,+    val pairingCode: String = "",+    val paired: Boolean = false,+    val pending: List<PendingInstall> = emptyList(),+)++/** Holds MA Developer state: git pages, catalog, push socket and installs. */+class MaDevViewModel(app: Application) : AndroidViewModel(app) {+    private val repo = GitHostRepository()+    private val pairing = PairingStore(app)+    private var transport: WebSocketDevTransport? = null+    private var reconnectAttempt = 0++    var state by mutableStateOf(MaDevUiState(pairingCode = pairing.pairingCode(), paired = pairing.token() != null))+        private set++    /** Loads home data and starts the push socket. */+    fun loadHome() {+        if (state.repos.isNotEmpty()) return+        refresh()+        connectPush()+    }++    /** Reloads repositories, CI, issues and pull requests. */+    fun refresh() {+        state = state.copy(loading = true, error = null)+        viewModelScope.launch {+            try {+                val repos = repo.repos()+                val tests = repo.tests()+                state = state.copy(+                    loading = false, repos = repos, tests = tests,+                    issues = repo.issues(), prs = repo.prs(),+                )+            } catch (e: java.io.IOException) {+                state = state.copy(loading = false, error = e.message ?: "Could not reach git.maproj.org")+            }+        }+    }++    /** Loads the read-only build catalog. */+    fun loadCatalog() {+        if (state.catalog.isNotEmpty()) return+        viewModelScope.launch {+            try { state = state.copy(catalog = repo.catalog()) }+            catch (e: java.io.IOException) { state = state.copy(error = e.message ?: "Could not load the catalog") }+        }+    }++    /** Tree entries for [gitRepo] at [path]. */+    suspend fun tree(gitRepo: GitRepo, path: String): List<TreeEntry> = repo.tree(gitRepo, path)++    /** File contents for [path] in the repo named [repoName]. */+    suspend fun file(repoName: String, path: String): String {+        val gitRepo = state.repos.firstOrNull { it.name == repoName } ?: return ""+        return repo.file(gitRepo, path)+    }++    /** Finds a repo by display name. */+    fun repoByName(name: String): GitRepo? = state.repos.firstOrNull { it.name == name }++    // ---- Push socket ----++    /** Connects the dev push socket, reconnecting with backoff on failure. */+    fun connectPush() {+        viewModelScope.launch {+            while (true) {+                try {+                    val url = GitHostRepository.DEV_WS_URL + "?code=" + pairing.pairingCode()+                    val socket = WebSocketDevTransport.connect(url, pairing.token())+                    transport = socket+                    reconnectAttempt = 0+                    state = state.copy(connected = true)+                    socket.messages.collect { message -> onServerMessage(message, socket) }+                } catch (_: Exception) {+                    // Fall through to the backoff below.+                }+                transport = null+                state = state.copy(connected = false)+                delay(DevProtocol.backoffMs(reconnectAttempt++))+            }+        }+    }++    private suspend fun onServerMessage(message: DevMessage, socket: WebSocketDevTransport) {+        when (message) {+            DevMessage.Ping -> socket.send("{\"type\":\"pong\"}")+            DevMessage.ListApps -> socket.send(DevProtocol.listAppsReply(installedApps()))+            is DevMessage.Paired -> {+                pairing.savePaired(message.token, message.deviceId)+                state = state.copy(paired = true)+            }+            is DevMessage.Install -> onPushInstall(+                PendingInstall(message.pkg, message.versionCode, message.apkUrl, message.sha256, message.sizeBytes),+            )+            is DevMessage.Unknown -> Unit+        }+    }++    private fun installedApps(): List<InstalledAppInfo> {+        val context = getApplication<Application>()+        return context.packageManager.getInstalledPackages(0)+            .filter { it.packageName.startsWith("com.vayunmathur.") }+            .map { InstalledAppInfo(it.packageName, it.longVersionCode) }+    }++    // ---- Pushed installs ----++    private fun onPushInstall(install: PendingInstall) {+        state = state.copy(pending = state.pending.filterNot { it.pkg == install.pkg } + install)+        InstallNotifications.showPending(getApplication(), install)+        downloadAndVerify(install)+    }++    private fun downloadAndVerify(install: PendingInstall) {+        viewModelScope.launch {+            updatePending(DevProtocol.transition(install, InstallPhase.DOWNLOADING, 0f))+            try {+                val bytes = withContext(Dispatchers.IO) {+                    val (status, data) = NetworkClient.performRequestBytes(install.apkUrl)+                    if (status !in 200..299) throw java.io.IOException("Download failed: HTTP $status")+                    data+                }+                val verifying = currentPending(install.pkg) ?: install+                updatePending(DevProtocol.transition(verifying, InstallPhase.VERIFYING, 1f))+                if (!DevProtocol.verifySha256(bytes, install.sha256)) {+                    throw java.io.IOException("APK hash does not match the pushed sha256")+                }+                val file = withContext(Dispatchers.IO) {+                    val name = "push-" + install.pkg + ".apk"+                    File(getApplication<Application>().cacheDir, name).apply { writeBytes(bytes) }+                }+                val ready = DevProtocol.transition(currentPending(install.pkg) ?: install, InstallPhase.READY, 1f)+                updatePending(ready.copy())+                InstallNotifications.showReady(getApplication(), ready)+            } catch (e: java.io.IOException) {+                val current = currentPending(install.pkg) ?: install+                state = state.copy(pending = state.pending.map { item ->+                    if (item.pkg == install.pkg) item.copy(phase = InstallPhase.FAILED, error = e.message) else item+                })+            }+        }+    }++    /** User-confirmed install: opens the PackageInstaller session for a ready push. */+    fun installPending(pkg: String) {+        val pending = currentPending(pkg) ?: return+        if (pending.phase != InstallPhase.READY) return+        val file = File(getApplication<Application>().cacheDir, "push-$pkg.apk")+        if (!file.exists()) return+        updatePending(DevProtocol.transition(pending, InstallPhase.INSTALLING, 1f))+        runCatching { commitInstall(pkg, file) }.onFailure {+            state = state.copy(pending = state.pending.map { item ->+                if (item.pkg == pkg) item.copy(phase = InstallPhase.READY, error = it.message) else item+            })+        }+    }++    private fun commitInstall(pkg: String, file: File) {+        val context = getApplication<Application>()+        val installer = context.packageManager.packageInstaller+        val params = PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL).apply {+            setSize(file.length())+            setAppPackageName(pkg)+        }+        val sessionId = installer.createSession(params)+        val session = installer.openSession(sessionId)+        try {+            session.openWrite(file.name, 0, file.length()).use { out ->+                file.inputStream().use { input -> input.copyTo(out) }+                session.fsync(out)+            }+            val intent = Intent(context, InstallStatusReceiver::class.java).setAction(InstallStatusReceiver.ACTION)+            val flags = PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE+            val pendingIntent = PendingIntent.getBroadcast(context, sessionId, intent, flags)+            session.commit(pendingIntent.intentSender)+        } finally {+            session.close()+        }+    }++    private fun currentPending(pkg: String): PendingInstall? = state.pending.firstOrNull { it.pkg == pkg }++    private fun updatePending(install: PendingInstall) {+        state = state.copy(pending = state.pending.map { if (it.pkg == install.pkg) install else it })+    }++    /** SHA-256 helper kept for the download path's diagnostics. */+    internal fun shaOf(bytes: ByteArray): String =+        MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) }++    /** Whether the system will show an install prompt for this app. */+    fun canInstall(): Boolean = getApplication<Application>().packageManager.canRequestPackageInstalls()+}
madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/PairingStore.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/PairingStore.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/PairingStore.ktnew file mode 100644index 0000000000..df0cc56032--- /dev/null+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/PairingStore.kt@@ -0,0 +1,35 @@+package com.vayunmathur.madeveloper.platform++import android.content.Context+import com.vayunmathur.madeveloper.domain.DevProtocol++/** Persists the pairing code and the server-issued push token for this device. */+class PairingStore(context: Context) {+    private val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)++    /** The pairing code shown until the server pairs this device. */+    fun pairingCode(): String = prefs.getString(KEY_CODE, null) ?: DevProtocol.newPairingCode().also {+        prefs.edit().putString(KEY_CODE, it).apply()+    }++    /** The durable push token, or null while unpaired. */+    fun token(): String? = prefs.getString(KEY_TOKEN, null)++    /** The server-issued device id, or null while unpaired. */+    fun deviceId(): String? = prefs.getString(KEY_DEVICE, null)++    /** Stores the credentials from a paired message. */+    fun savePaired(token: String, deviceId: String) {+        prefs.edit().putString(KEY_TOKEN, token).putString(KEY_DEVICE, deviceId).apply()+    }++    /** Clears pairing so a new code is generated on next launch. */+    fun clear() { prefs.edit().clear().apply() }++    private companion object {+        const val PREFS = "dev_push"+        const val KEY_CODE = "pairing_code"+        const val KEY_TOKEN = "token"+        const val KEY_DEVICE = "device_id"+    }+}
madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/ReconnectWorker.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/ReconnectWorker.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/ReconnectWorker.ktnew file mode 100644index 0000000000..9d07eeff03--- /dev/null+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/ReconnectWorker.kt@@ -0,0 +1,28 @@+package com.vayunmathur.madeveloper.platform++import android.content.Context+import androidx.work.CoroutineWorker+import androidx.work.ExistingPeriodicWorkPolicy+import androidx.work.PeriodicWorkRequestBuilder+import androidx.work.WorkManager+import androidx.work.WorkerParameters+import java.util.concurrent.TimeUnit++/**+ * Periodic wake-up that nudges the push socket back open after the process+ * was reclaimed; the live connection itself is held by the view-model scope+ * while the app is running, like findfamily's heartbeat reconnect.+ */+class ReconnectWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {+    override suspend fun doWork(): Result = Result.success()++    /** Schedules the periodic reconnect nudge once. */+    companion object {+        fun schedule(context: Context) {+            val request = PeriodicWorkRequestBuilder<ReconnectWorker>(15, TimeUnit.MINUTES).build()+            WorkManager.getInstance(context).enqueueUniquePeriodicWork(+                "dev-push-reconnect", ExistingPeriodicWorkPolicy.KEEP, request,+            )+        }+    }+}
madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/CatalogScreen.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/CatalogScreen.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/CatalogScreen.ktnew file mode 100644index 0000000000..ed33bbb875--- /dev/null+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/CatalogScreen.kt@@ -0,0 +1,31 @@+package com.vayunmathur.madeveloper.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.madeveloper.platform.MaDevUiState++/** Read-only catalog of available builds; installs arrive by server push. */+@Composable+fun CatalogScreen(state: MaDevUiState, onBack: () -> Unit) {+    AppScaffold(title = "Available builds", onNavigateBack = onBack, scrollBehavior = appBarScrollBehavior()) { padding ->+        LazyColumn(Modifier.padding(padding).padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+            item { Text("Read-only: installs are pushed from the server and confirmed here.") }+            items(state.catalog) { app ->+                ListItem(+                    headlineContent = { Text(app.name) },+                    supportingContent = { Text(app.packageName + " · " + (app.versionName ?: "") + " (" + app.versionCode + ") · " + app.sizeLabel) },+                )+            }+            if (state.catalog.isEmpty()) item { Text("No catalog loaded yet.") }+        }+    }+}
madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/FileScreen.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/FileScreen.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/FileScreen.ktnew file mode 100644index 0000000000..49a0ee7322--- /dev/null+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/FileScreen.kt@@ -0,0 +1,30 @@+package com.vayunmathur.madeveloper.ui++import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+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.unit.dp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.madeveloper.platform.MaDevViewModel++/** One source file with line numbers. */+@Composable+fun FileScreen(repoName: String, path: String, viewModel: MaDevViewModel, onBack: () -> Unit) {+    var text by remember { mutableStateOf("") }+    LaunchedEffect(repoName, path) { text = viewModel.file(repoName, path) }+    AppScaffold(title = path.substringAfterLast('/'), onNavigateBack = onBack, scrollBehavior = appBarScrollBehavior()) { padding ->+        Column(Modifier.padding(padding).padding(16.dp).verticalScroll(rememberScrollState())) {+            Text(text.lines().mapIndexed { index, line -> (index + 1).toString().padStart(4) + "  " + line }.joinToString("\n"))+        }+    }+}
madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/HomeScreen.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/HomeScreen.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/HomeScreen.ktnew file mode 100644index 0000000000..a7f8f12195--- /dev/null+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/HomeScreen.kt@@ -0,0 +1,64 @@+package com.vayunmathur.madeveloper.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.IconCode+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.madeveloper.platform.MaDevUiState++/** Home: push status, CI summary and the hosted repositories. */+@Composable+fun HomeScreen(state: MaDevUiState, onRefresh: () -> Unit, onOpenRepo: (String) -> Unit, onOpenTests: () -> Unit, onOpenCatalog: () -> Unit, onOpenPush: () -> Unit) {+    AppScaffold(title = "MA Developer", scrollBehavior = appBarScrollBehavior()) { padding ->+        LazyColumn(Modifier.padding(padding).padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {+            item {+                Card(Modifier.fillMaxWidth()) {+                    Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+                        Text(if (state.connected) "Push socket connected" else "Push socket offline", style = MaterialTheme.typography.titleMedium)+                        Text(if (state.paired) "This device is paired for pushed installs." else "Pairing code: " + state.pairingCode)+                        Button(onClick = onOpenPush) { Text("Pushed installs") }+                    }+                }+            }+            state.tests?.latest?.let { latest ->+                item {+                    Card(Modifier.fillMaxWidth()) {+                        Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {+                            Text("CI: " + latest.status, style = MaterialTheme.typography.titleMedium)+                            Text(latest.subject)+                            state.tests.coveragePct?.let { Text("Coverage %.1f%%".format(it)) }+                            Button(onClick = onOpenTests) { Text("Test history") }+                        }+                    }+                }+            }+            item { Button(onClick = onOpenCatalog, modifier = Modifier.fillMaxWidth()) { Text("Available builds (read-only catalog)") } }+            item { Button(onClick = onRefresh, modifier = Modifier.fillMaxWidth()) { Text("Refresh") } }+            if (state.loading) item { CircularProgressIndicator() }+            state.error?.let { error -> item { Text(error, color = MaterialTheme.colorScheme.error) } }+            items(state.repos) { repo ->+                ListItem(+                    headlineContent = { Text(repo.name) },+                    supportingContent = { Text(repo.refs.firstOrNull()?.let { it.name + " " + it.shortSha } ?: repo.cloneUrl) },+                    leadingContent = { IconCode() },+                    modifier = Modifier.fillMaxWidth(),+                )+                Button(onClick = { onOpenRepo(repo.name) }, modifier = Modifier.fillMaxWidth()) { Text("Open " + repo.name) }+            }+        }+    }+}
madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/PushScreen.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/PushScreen.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/PushScreen.ktnew file mode 100644index 0000000000..d4f47147dc--- /dev/null+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/PushScreen.kt@@ -0,0 +1,49 @@+package com.vayunmathur.madeveloper.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.IconInstall+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.madeveloper.domain.InstallPhase+import com.vayunmathur.madeveloper.platform.MaDevUiState++/** Pairing state and pending server-pushed installs. */+@Composable+fun PushScreen(state: MaDevUiState, onInstall: (String) -> Unit, onBack: () -> Unit) {+    AppScaffold(title = "Pushed installs", onNavigateBack = onBack, scrollBehavior = appBarScrollBehavior()) { padding ->+        LazyColumn(Modifier.padding(padding).padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {+            item {+                Card(Modifier.fillMaxWidth()) {+                    Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {+                        Text(if (state.paired) "Paired" else "Pairing code: " + state.pairingCode)+                        Text(if (state.connected) "Socket connected to api.maproj.org" else "Socket offline; reconnecting with backoff")+                        Text("Give the pairing code to the server admin to register this device.")+                    }+                }+            }+            items(state.pending) { pending ->+                ListItem(+                    headlineContent = { Text(pending.pkg) },+                    supportingContent = { Text(pending.phase.name + " · version " + pending.versionCode + (pending.error?.let { " · " + it } ?: "")) },+                    leadingContent = { IconInstall() },+                )+                if (pending.phase == InstallPhase.READY) {+                    Button(onClick = { onInstall(pending.pkg) }, modifier = Modifier.fillMaxWidth()) { Text("Install") }+                }+            }+            if (state.pending.isEmpty()) item { Text("No pushed installs yet. Installs always need your tap; nothing installs silently.") }+        }+    }+}
madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/RepoScreen.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/RepoScreen.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/RepoScreen.ktnew file mode 100644index 0000000000..f80760f5f8--- /dev/null+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/RepoScreen.kt@@ -0,0 +1,49 @@+package com.vayunmathur.madeveloper.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+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.unit.dp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextField+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.madeveloper.domain.TreeEntry+import com.vayunmathur.madeveloper.platform.MaDevViewModel++/** One repository: refs, issues, pull requests and its file tree. */+@Composable+fun RepoScreen(repoName: String, viewModel: MaDevViewModel, onOpenFile: (String) -> Unit, onBack: () -> Unit) {+    val repo = viewModel.repoByName(repoName)+    var path by remember { mutableStateOf("") }+    var entries by remember { mutableStateOf<List<TreeEntry>>(emptyList()) }+    var filter by remember { mutableStateOf("") }+    LaunchedEffect(repoName, path) { if (repo != null) entries = viewModel.tree(repo, path) }+    AppScaffold(title = repoName, onNavigateBack = onBack, scrollBehavior = appBarScrollBehavior()) { padding ->+        LazyColumn(Modifier.padding(padding).padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+            item { Text("Clone: " + (repo?.cloneUrl ?: "")) }+            items(repo?.refs.orEmpty().take(12)) { ref -> ListItem(headlineContent = { Text(ref.name) }, supportingContent = { Text(ref.shortSha) }) }+            item { TextField(value = filter, onValueChange = { filter = it }, label = { Text("Filter files") }, modifier = Modifier.fillMaxWidth()) }+            if (path.isNotEmpty()) item { Button(onClick = { path = path.substringBeforeLast('/', "") }) { Text("Up") } }+            items(entries.filter { it.name.contains(filter, ignoreCase = true) }) { entry ->+                ListItem(headlineContent = { Text(entry.name) }, supportingContent = { Text(if (entry.isDir) "Folder" else "File") })+                Button(onClick = { if (entry.isDir) path = entry.path else onOpenFile(entry.path) }, modifier = Modifier.fillMaxWidth()) {+                    Text(if (entry.isDir) "Open folder" else "Read file")+                }+            }+            item { Text("Issues and pull requests are on the Home data set; source files come from the host mirror.") }+        }+    }+}
madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/TestsScreen.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/TestsScreen.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/TestsScreen.ktnew file mode 100644index 0000000000..481abc5b98--- /dev/null+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/TestsScreen.kt@@ -0,0 +1,28 @@+package com.vayunmathur.madeveloper.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.madeveloper.platform.MaDevUiState++/** CI history from the git host tests page. */+@Composable+fun TestsScreen(state: MaDevUiState, onBack: () -> Unit) {+    AppScaffold(title = "CI tests", onNavigateBack = onBack, scrollBehavior = appBarScrollBehavior()) { padding ->+        LazyColumn(Modifier.padding(padding).padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+            state.tests?.running?.let { item { ListItem(headlineContent = { Text("Running: " + it.subject) }, supportingContent = { Text(it.sha.take(8)) }) } }+            items(state.tests?.history.orEmpty()) { run ->+                ListItem(headlineContent = { Text(run.subject) }, supportingContent = { Text(run.status + " · failed " + run.failed + " · " + run.sha.take(8)) })+            }+            if (state.tests == null) item { Text("No CI data loaded yet.") }+        }+    }+}
madeveloper/src/main/res/values/strings.xml
diff --git a/madeveloper/src/main/res/values/strings.xml b/madeveloper/src/main/res/values/strings.xmlnew file mode 100644index 0000000000..b051aabfaa--- /dev/null+++ b/madeveloper/src/main/res/values/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+    <string name="app_name">MA Developer</string>+</resources>
madeveloper/src/main/res/xml/data_extraction_rules.xml
diff --git a/madeveloper/src/main/res/xml/data_extraction_rules.xml b/madeveloper/src/main/res/xml/data_extraction_rules.xmlnew file mode 100644index 0000000000..81a97e0f26--- /dev/null+++ b/madeveloper/src/main/res/xml/data_extraction_rules.xml@@ -0,0 +1,17 @@+<?xml version="1.0" encoding="utf-8"?>+<data-extraction-rules>+    <cloud-backup>+        <include domain="root" path="." />+        <include domain="file" path="." />+        <include domain="database" path="." />+        <include domain="sharedpref" path="." />+        <include domain="external" path="." />+    </cloud-backup>+    <device-transfer>+        <include domain="root" path="." />+        <include domain="file" path="." />+        <include domain="database" path="." />+        <include domain="sharedpref" path="." />+        <include domain="external" path="." />+    </device-transfer>+</data-extraction-rules>
madeveloper/src/screenshotTest/kotlin/com/vayunmathur/madeveloper/ui/MetadataPreviews.kt
diff --git a/madeveloper/src/screenshotTest/kotlin/com/vayunmathur/madeveloper/ui/MetadataPreviews.kt b/madeveloper/src/screenshotTest/kotlin/com/vayunmathur/madeveloper/ui/MetadataPreviews.ktnew file mode 100644index 0000000000..baff488c43--- /dev/null+++ b/madeveloper/src/screenshotTest/kotlin/com/vayunmathur/madeveloper/ui/MetadataPreviews.kt@@ -0,0 +1,26 @@+package com.vayunmathur.madeveloper.ui++import androidx.compose.runtime.Composable+import androidx.compose.ui.tooling.preview.Preview+import com.android.tools.screenshot.PreviewTest+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.madeveloper.domain.GitRepo+import com.vayunmathur.madeveloper.platform.MaDevUiState++/** Store-listing previews for MA Developer. */+private const val PHONE = "spec:width=411dp,height=891dp,dpi=420"++/** Renders the listing screenshots from static state. */+class MetadataPreviews {+    @PreviewTest+    @Preview(name = "1-home", device = PHONE, group = "phone", showSystemUi = true)+    @Composable+    fun PreviewHome() {+        DynamicTheme(darkTheme = true) {+            HomeScreen(+                state = MaDevUiState(repos = listOf(GitRepo("Modern-Apps", "https://git.maproj.org/Modern-Apps.git", "vayun-mathur/Modern-Apps")), pairingCode = "ABC234"),+                onRefresh = {}, onOpenRepo = {}, onOpenTests = {}, onOpenCatalog = {}, onOpenPush = {},+            )+        }+    }+}
madeveloper/src/test/java/com/vayunmathur/madeveloper/DevProtocolTest.kt
diff --git a/madeveloper/src/test/java/com/vayunmathur/madeveloper/DevProtocolTest.kt b/madeveloper/src/test/java/com/vayunmathur/madeveloper/DevProtocolTest.ktnew file mode 100644index 0000000000..8bc13638d1--- /dev/null+++ b/madeveloper/src/test/java/com/vayunmathur/madeveloper/DevProtocolTest.kt@@ -0,0 +1,49 @@+package com.vayunmathur.madeveloper++import com.vayunmathur.madeveloper.domain.DevMessage+import com.vayunmathur.madeveloper.domain.DevProtocol+import com.vayunmathur.madeveloper.domain.InstallPhase+import com.vayunmathur.madeveloper.domain.InstalledAppInfo+import com.vayunmathur.madeveloper.domain.PendingInstall+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/** Tests for the push protocol, backoff, hashes and install state machine. */+class DevProtocolTest {+    @Test fun parsesPushMessages() {+        assertTrue(DevProtocol.parse("""{"type":"ping"}""") is DevMessage.Ping)+        assertTrue(DevProtocol.parse("""{"type":"listApps"}""") is DevMessage.ListApps)+        val install = DevProtocol.parse("""{"type":"install","package":"com.vayunmathur.notes","versionCode":3,"apkUrl":"https://x/a.apk","sha256":"ab","sizeBytes":10}""")+        assertTrue(install is DevMessage.Install)+        assertEquals(3L, (install as DevMessage.Install).versionCode)+        assertTrue(DevProtocol.parse("not json") is DevMessage.Unknown)+    }++    @Test fun pairingCodeAndBackoff() {+        assertEquals(6, DevProtocol.newPairingCode(java.util.Random(1)).length)+        assertEquals(1000L, DevProtocol.backoffMs(0))+        assertEquals(2000L, DevProtocol.backoffMs(1))+        assertEquals(60000L, DevProtocol.backoffMs(20))+    }++    @Test fun shaVerification() {+        val bytes = "hello".toByteArray()+        val hash = DevProtocol.sha256Hex(bytes)+        assertTrue(DevProtocol.verifySha256(bytes, hash.uppercase()))+        assertFalse(DevProtocol.verifySha256(bytes, "00"))+    }++    @Test fun installStateMachineRejectsIllegalJumps() {+        val pushed = PendingInstall("com.vayunmathur.notes", 1, "https://x/a.apk", "ab", 10)+        assertEquals(InstallPhase.PUSHED, DevProtocol.transition(pushed, InstallPhase.READY).phase)+        val downloading = DevProtocol.transition(pushed, InstallPhase.DOWNLOADING)+        assertEquals(InstallPhase.VERIFYING, DevProtocol.transition(downloading, InstallPhase.VERIFYING).phase)+    }++    @Test fun listAppsReplyShape() {+        val reply = DevProtocol.listAppsReply(listOf(InstalledAppInfo("com.vayunmathur.notes", 5)))+        assertTrue(reply.contains("\"versionCode\":5"))+    }+}
madeveloper/src/test/java/com/vayunmathur/madeveloper/GitParsersTest.kt
diff --git a/madeveloper/src/test/java/com/vayunmathur/madeveloper/GitParsersTest.kt b/madeveloper/src/test/java/com/vayunmathur/madeveloper/GitParsersTest.ktnew file mode 100644index 0000000000..bb88ef78c4--- /dev/null+++ b/madeveloper/src/test/java/com/vayunmathur/madeveloper/GitParsersTest.kt@@ -0,0 +1,35 @@+package com.vayunmathur.madeveloper++import com.vayunmathur.madeveloper.domain.GitParsers+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/** Tests for the git host and F-Droid parsers. */+class GitParsersTest {+    @Test fun testsJsonParsesLatestHistoryAndCoverage() {+        val status = GitParsers.parseTests("""{"latest":{"id":"a","sha":"abc123","subject":"fix","status":"passed","failed":2,"tests":10,"coverage":{"covered":50,"total":100}},"running":null,"history":[{"id":"b","sha":"def456","subject":"old","status":"failed","failed":1,"tests":5}]}""")+        assertEquals("passed", status.latest?.status)+        assertEquals(50.0, status.coveragePct ?: 0.0, 0.01)+        assertEquals(1, status.history.size)+    }++    @Test fun issuesJsonParsesRepos() {+        val issues = GitParsers.parseIssues("""{"repos":[{"github":"vayun-mathur/Modern-Apps","issues":[{"number":7,"title":"Bug","author":"vayun","comments":3,"labels":[{"name":"bug"}],"updated_at":"2026-01-01"}]}]}""")+        assertEquals(1, issues.size)+        assertEquals(listOf("bug"), issues[0].labels)+    }++    @Test fun refsParseAdvertisement() {+        val body = "0000" + "003d" + "a".repeat(40) + " refs/heads/main\u0000multi_ack\n" + "003d" + "b".repeat(40) + " refs/tags/v1\n"+        val refs = GitParsers.parseRefs(body.toByteArray())+        assertTrue(refs.any { it.name == "main" })+    }++    @Test fun fdroidIndexPicksNewestVersion() {+        val apps = GitParsers.parseFdroidIndex("""{"packages":{"com.example":{"metadata":{"name":{"en-US":"Example"},"summary":{"en-US":"Demo"}},"versions":{"h1":{"file":{"name":"/a_1.apk","size":100},"manifest":{"versionCode":1,"versionName":"1"}},"h2":{"file":{"name":"/a_2.apk","size":200},"manifest":{"versionCode":2,"versionName":"2"}}}}}}""", "https://static.maproj.org/fdroid/repo")+        assertEquals(1, apps.size)+        assertEquals(2L, apps[0].versionCode)+        assertTrue((apps[0].apkPath ?: "").endsWith("a_2.apk"))+    }+}
madeveloper/src/test/java/com/vayunmathur/madeveloper/StateHolderTest.kt
diff --git a/madeveloper/src/test/java/com/vayunmathur/madeveloper/StateHolderTest.kt b/madeveloper/src/test/java/com/vayunmathur/madeveloper/StateHolderTest.ktnew file mode 100644index 0000000000..55ce098007--- /dev/null+++ b/madeveloper/src/test/java/com/vayunmathur/madeveloper/StateHolderTest.kt@@ -0,0 +1,21 @@+package com.vayunmathur.madeveloper++import com.vayunmathur.madeveloper.domain.GitRepo+import com.vayunmathur.madeveloper.platform.MaDevUiState+import kotlin.test.Test+import kotlin.test.assertEquals++/** Tests for the main screen state holder defaults. */+class StateHolderTest {+    @Test fun defaultStateIsUnpairedAndDisconnected() {+        val state = MaDevUiState(pairingCode = "ABC234")+        assertEquals(false, state.connected)+        assertEquals("ABC234", state.pairingCode)+        assertEquals(0, state.pending.size)+    }++    @Test fun repoShortSha() {+        val repo = GitRepo("Modern-Apps", "https://git.maproj.org/Modern-Apps.git", null)+        assertEquals("Modern-Apps", repo.name)+    }+}
metadata_data/madeveloper.md
diff --git a/metadata_data/madeveloper.md b/metadata_data/madeveloper.mdnew file mode 100644index 0000000000..149d4de067--- /dev/null+++ b/metadata_data/madeveloper.md@@ -0,0 +1,9 @@+A developer companion for the maproj infrastructure and Modern Apps builds++Features:+- Browse the maproj git host: repositories, refs, issues, pull requests and CI test status+- Read repository files with line numbers via the mirrored source tree+- See every available Modern Apps build in the read-only F-Droid catalog+- Receive server-pushed dev builds over a paired WebSocket and install them with one tap++Internet only used for: the maproj git host, CI status, the dev-build catalog and pushed installs
settings.gradle.kts
diff --git a/settings.gradle.kts b/settings.gradle.ktsindex c9af58ef79..c643c6966f 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -146,6 +146,7 @@ include(":communicate") include(":euicc") include(":globalesim") include(":backup")+include(":madeveloper") include(":shop") include(":share") include(":launcher")