Debloat your Android TV, install apps, browse and transfer files on it, all from your phone. Just 3 MB, no tracking, no root, no PC.
Run on real TVs through :adb
jesse-agent-23207dfc31d17c9
diff --git a/app/src/main/java/app/tellyscope/MainActivity.kt b/app/src/main/java/app/tellyscope/MainActivity.ktindex 696bdf3..03a017b 100644--- a/app/src/main/java/app/tellyscope/MainActivity.kt+++ b/app/src/main/java/app/tellyscope/MainActivity.kt@@ -2,10 +2,17 @@package app.tellyscope+import android.content.Intent+import android.content.pm.PackageManager+import android.net.Uri+import android.os.Buildimport android.os.Bundle+import android.provider.Settingsimport androidx.activity.ComponentActivityimport androidx.activity.compose.BackHandler+import androidx.activity.compose.rememberLauncherForActivityResultimport androidx.activity.compose.setContent+import androidx.activity.result.contract.ActivityResultContractsimport androidx.activity.enableEdgeToEdgeimport androidx.compose.material3.SnackbarDurationimport androidx.compose.material3.SnackbarHostState@@ -17,14 +24,19 @@ import androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.saveable.rememberSaveableimport androidx.compose.runtime.setValue+import androidx.core.content.ContextCompat+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.compose.LifecycleEventEffectimport androidx.lifecycle.compose.collectAsStateWithLifecycleimport androidx.lifecycle.viewmodel.compose.viewModelimport androidx.lifecycle.viewmodel.initializerimport androidx.lifecycle.viewmodel.viewModelFactory+import app.tellyscope.data.AdbDeviceSourceimport app.tellyscope.data.FakeDeviceSourceimport app.tellyscope.ui.Copyimport app.tellyscope.ui.DeviceActionsimport app.tellyscope.ui.DeviceScreen+import app.tellyscope.ui.PermissionScreenimport app.tellyscope.ui.ScanScreenimport app.tellyscope.ui.TellyscopeViewModelimport app.tellyscope.ui.theme.TellyscopeTheme@@ -33,28 +45,71 @@ class MainActivity : ComponentActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)enableEdgeToEdge()- // Until the :adb module lands, the app runs on the fake source. Launch with- // `--es scenario empty|noallow` to see the guide or the timeout.+ // Real TVs by default. Launch with `--es scenario fake|empty|noallow` to run on+ // made-up data: the full app, the empty-scan guide, or the Allow timeout.val scenario = when (intent.getStringExtra("scenario")) {+ "fake" -> FakeDeviceSource.Scenario.Normal"empty" -> FakeDeviceSource.Scenario.Empty"noallow" -> FakeDeviceSource.Scenario.NoAllow- else -> FakeDeviceSource.Scenario.Normal+ else -> null}setContent {TellyscopeTheme {- val vm: TellyscopeViewModel = viewModel(- factory = viewModelFactory { initializer { TellyscopeViewModel(FakeDeviceSource(scenario)) } },- )- TellyscopeApp(vm)+ LocalNetworkGate(skip = scenario != null) {+ val vm: TellyscopeViewModel = viewModel(+ factory = viewModelFactory {+ initializer {+ TellyscopeViewModel(scenario?.let(::FakeDeviceSource) ?: AdbDeviceSource(applicationContext))+ }+ },+ )+ TellyscopeApp(vm)+ }}}}++ /**+ * Android 17 blocks LAN connections and mDNS for apps targeting 37 until the user grants+ * ACCESS_LOCAL_NETWORK, so nothing scans until then. The view model is created inside+ * [content], which keeps the first scan behind the grant.+ */+ @Composable+ private fun LocalNetworkGate(skip: Boolean, content: @Composable () -> Unit) {+ // Not in Manifest.permission below API 37; the string is the same on every SDK.+ val permission = "android.permission.ACCESS_LOCAL_NETWORK"+ fun granted() = skip || Build.VERSION.SDK_INT < 37 ||+ ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED++ var ok by remember { mutableStateOf(granted()) }+ var denied by rememberSaveable { mutableStateOf(false) }+ val launcher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { yes ->+ ok = yes+ // No rationale after a refusal means Android won't ask again: only Settings can grant it.+ denied = !yes && !shouldShowRequestPermissionRationale(permission)+ }+ // Coming back from Settings.+ LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { ok = granted() }++ if (ok) {+ content()+ } else {+ PermissionScreen(+ denied = denied,+ onAllow = { launcher.launch(permission) },+ onSettings = {+ startActivity(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", packageName, null)))+ },+ )+ }+ }}@Composablefun TellyscopeApp(vm: TellyscopeViewModel) {val state by vm.state.collectAsStateWithLifecycle()val done by vm.done.collectAsStateWithLifecycle()+ val error by vm.error.collectAsStateWithLifecycle()val snackbar = remember { SnackbarHostState() }var adding by rememberSaveable { mutableStateOf(false) }@@ -69,6 +124,12 @@ fun TellyscopeApp(vm: TellyscopeViewModel) {if (result == SnackbarResult.ActionPerformed) vm.undo(entry)}+ LaunchedEffect(error) {+ val message = error ?: return@LaunchedEffect+ vm.errorShown()+ snackbar.showSnackbar(message, duration = SnackbarDuration.Long)+ }+// A newly connected TV becomes the selection; leave the add flow then, not on tap.LaunchedEffect(state.selectedId) { adding = false }diff --git a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.ktnew file mode 100644index 0000000..844a5fb--- /dev/null+++ b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt@@ -0,0 +1,212 @@+// SPDX-License-Identifier: GPL-3.0-only++package app.tellyscope.data++import android.content.Context+import app.tellyscope.adb.ActionResult+import app.tellyscope.adb.Actions+import app.tellyscope.adb.Connector+import app.tellyscope.adb.DeviceLink+import app.tellyscope.adb.LanScanner+import app.tellyscope.adb.Parsers+import app.tellyscope.adb.Protected+import app.tellyscope.adb.ProtectedReason+import com.flyfishxu.kadb.exception.AdbPairAuthException+import com.flyfishxu.kadb.mdns.KadbMdnsAndroid+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.flow+import kotlinx.coroutines.flow.map+import kotlinx.coroutines.flow.transformWhile+import java.io.File+import java.util.concurrent.ConcurrentHashMap+import app.tellyscope.adb.Action as AdbAction+import app.tellyscope.adb.ConnectResult as AdbConnectResult+import app.tellyscope.adb.DeviceState as AdbState+import app.tellyscope.adb.ScanHit as AdbHit++/**+ * [DeviceSource] on real TVs through `:adb`. Device id is the TV's IP. Known devices live for the+ * app process only (persisting them is a later slice), and `procs` / network details beyond the+ * IP are empty for now: slice 1 is scan → connect → live CPU/RAM.+ */+class AdbDeviceSource(context: Context) : DeviceSource {+ private val appContext = context.applicationContext+ private val scope = CoroutineScope(SupervisorJob())+ private val links = ConcurrentHashMap<String, DeviceLink>()+ private val hits = ConcurrentHashMap<String, ScanHit>()+ /** Wireless debugging advertises pairing and connect on different ports. */+ private val pairingPorts = ConcurrentHashMap<String, Int>()+ private var historyId = 0L++ init {+ Connector.init(File(appContext.filesDir, "adbkey.pem"))+ }++ override fun scan(): Flow<ScanEvent> = flow {+ LanScanner(KadbMdnsAndroid(appContext)).scan().collect { h ->+ if (h.kind == AdbHit.Kind.PAIRING) {+ pairingPorts[h.host] = h.port+ if (hits.containsKey(h.host)) return@collect+ }+ val hit = ScanHit(+ ip = h.host,+ port = h.port,+ kind = if (h.kind == AdbHit.Kind.CLASSIC) ScanKind.Classic else ScanKind.Wireless,+ hostname = h.name,+ maker = null, // Android 10+ apps can't read the ARP table+ )+ hits[h.host] = hit+ emit(ScanEvent.Found(hit))+ }+ emit(ScanEvent.Done)+ }++ override suspend fun connect(hit: ScanHit): ConnectResult = when (val r = Connector.connect(hit.ip, hit.port)) {+ is AdbConnectResult.Online -> {+ hits[hit.ip] = hit+ // Hand the open session to a link, which reconnects on its own from here on.+ var first: AdbConnectResult? = r+ val link = DeviceLink(hit.ip, hit.port, scope, open = { h, p ->+ first?.also { first = null } ?: Connector.connect(h, p)+ })+ links.put(hit.ip, link)?.disconnect()+ link.connect()+ ConnectResult.Online(device(hit.ip))+ }+ AdbConnectResult.NotAllowed -> ConnectResult.NotAllowed+ AdbConnectResult.NeedsPairing -> ConnectResult.NeedsPairing+ is AdbConnectResult.Unreachable -> ConnectResult.Unreachable(r.reason)+ }++ override suspend fun pair(hit: ScanHit, code: String): ConnectResult {+ try {+ Connector.pair(hit.ip, pairingPorts[hit.ip] ?: hit.port, code)+ } catch (e: AdbPairAuthException) {+ return ConnectResult.WrongCode(e.message ?: "pairing failed")+ } catch (e: IllegalArgumentException) {+ return ConnectResult.WrongCode(e.message ?: "pairing code must be 6 digits")+ }+ // After pairing, the connect port is the one mDNS advertised, not the pairing port.+ val connectHit = hits[hit.ip]?.takeIf { it.port != pairingPorts[hit.ip] } ?: hit+ return connect(connectHit)+ }++ override suspend fun known(): List<Device> = links.keys.map(::device)++ override fun live(deviceId: String): Flow<Snapshot> {+ val link = links[deviceId] ?: return flow {}+ // Completes once the link drops (offline, not allowed, needs pairing), as the interface promises.+ return combine(link.state, link.stats) { state, stats -> state to stats }+ .transformWhile { (state, stats) ->+ if (state == AdbState.ONLINE && stats != null) emit(stats)+ state in setOf(AdbState.FOUND, AdbState.WAITING, AdbState.ONLINE)+ }+ .map { s ->+ val mem = s.memory+ Snapshot(+ at = System.currentTimeMillis(),+ cpuPercent = s.cpuPercent?.toInt() ?: 0,+ ramUsedMb = mem?.let { ((it.totalKb - it.availableKb) / 1024).toInt() } ?: 0,+ ramTotalMb = mem?.let { (it.totalKb / 1024).toInt() } ?: 0,+ storageUsedGb = s.storage?.let { it.usedKb / 1_048_576.0 },+ storageTotalGb = s.storage?.let { it.totalKb / 1_048_576.0 },+ tempC = s.temperatureC?.toInt(),+ uptimeSeconds = s.uptimeSeconds ?: 0,+ screenOn = null,+ procs = emptyList(),+ )+ }+ }++ override suspend fun apps(deviceId: String): List<AppInfo> {+ val shell = session(deviceId)+ val home = Actions(shell).homePackages()+ val system = Parsers.packages(shell.shell("pm list packages -s").output).map { it.name }.toSet()+ val disabled = Parsers.packages(shell.shell("pm list packages -d").output).map { it.name }.toSet()+ return Parsers.packages(shell.shell("pm list packages").output).map { p ->+ AppInfo(+ packageName = p.name,+ label = humanise(p.name),+ iconColor = null,+ system = p.name in system,+ enabled = p.name !in disabled,+ protectedReason = Protected.reason(p.name, home)?.let(::reasonText),+ version = "",+ )+ }.sortedBy { it.label.lowercase() }+ }++ override suspend fun network(deviceId: String): NetworkInfo {+ val out = session(deviceId).shell("ip -o -4 addr show").output+ val line = out.lineSequence().firstOrNull { "inet " in it && " lo " !in it }+ val f = line?.trim()?.split(Regex("\\s+")).orEmpty()+ return NetworkInfo(+ iface = f.getOrElse(1) { "" },+ ip = f.getOrNull(3)?.substringBefore('/') ?: deviceId,+ mac = null, ssid = null, rssi = null, linkMbps = null,+ sockets = emptyList(), traffic = emptyList(),+ )+ }++ override suspend fun act(deviceId: String, action: Action, packageName: String): HistoryEntry {+ val r = Actions(session(deviceId)).run(AdbAction.valueOf(action.name.uppercase()), packageName)+ return when (r) {+ is ActionResult.Done -> HistoryEntry(+ id = ++historyId,+ deviceId = deviceId,+ at = System.currentTimeMillis(),+ action = action,+ packageName = packageName,+ label = humanise(packageName),+ undo = r.undo?.let { Action.valueOf(it.name.lowercase().replaceFirstChar(Char::uppercase)) },+ undoneAt = null,+ )+ is ActionResult.Refused -> throw IllegalStateException(reasonText(r.reason))+ is ActionResult.Failed -> throw IllegalStateException(r.output.ifEmpty { "the TV refused" })+ }+ }++ private fun session(deviceId: String) =+ links[deviceId]?.session ?: throw IllegalStateException("$deviceId is offline")++ private fun device(id: String): Device {+ val link = links[id]+ val stats = link?.stats?.value+ return Device(+ id = id,+ hit = hits.getValue(id),+ state = when (link?.state?.value) {+ AdbState.WAITING -> DeviceState.Waiting+ AdbState.ONLINE -> DeviceState.Online+ AdbState.OFFLINE -> DeviceState.Offline+ AdbState.NOT_ALLOWED -> DeviceState.NotAllowed+ AdbState.NEEDS_PAIRING -> DeviceState.NeedsPairing+ AdbState.FOUND, null -> DeviceState.Found+ },+ model = stats?.model,+ manufacturer = stats?.manufacturer,+ android = stats?.androidVersion,+ lastSeen = link?.lastSeenMillis,+ )+ }++ /** `com.google.android.youtube.tv` → "Youtube". Real APK labels come with the apps slice. */+ private fun humanise(pkg: String): String {+ val parts = pkg.split('.').filter { it !in setOf("com", "android", "google", "tv", "app", "apps", "org") }+ return (parts.lastOrNull() ?: pkg).replaceFirstChar(Char::uppercase)+ }++ /** Copy from the protected-apps table in the UX copy doc. */+ private fun reasonText(r: ProtectedReason) = when (r) {+ ProtectedReason.HOME_SCREEN -> "this is your home screen"+ ProtectedReason.SYSTEM -> "the TV needs this to work"+ ProtectedReason.SETTINGS -> "you need this to change TV settings"+ ProtectedReason.PLAY_SERVICES -> "most apps stop working without it"+ ProtectedReason.KEYBOARD -> "you'd lose the on-screen keyboard"+ ProtectedReason.TV_INPUTS_REMOTE -> "your remote or HDMI inputs could stop working"+ ProtectedReason.SETUP_WIZARD -> "the TV may get stuck on restart without it"+ }+}diff --git a/app/src/main/java/app/tellyscope/data/FakeDeviceSource.kt b/app/src/main/java/app/tellyscope/data/FakeDeviceSource.ktindex dd3a777..785248f 100644--- a/app/src/main/java/app/tellyscope/data/FakeDeviceSource.kt+++ b/app/src/main/java/app/tellyscope/data/FakeDeviceSource.kt@@ -72,7 +72,7 @@ class FakeDeviceSource(override suspend fun pair(hit: ScanHit, code: String): ConnectResult {delay(800)if (!code.matches(Regex("\\d{6}"))) {- return ConnectResult.WrongCode("that code didn't work. codes change each time the box opens; check the tv and try again.")+ return ConnectResult.WrongCode("that code didn't work. codes change each time the box opens; check the TV and try again.")}return ConnectResult.Online(device(hit))}@@ -179,8 +179,8 @@ class FakeDeviceSource(AppInfo("com.xgimi.assistant", "XGIMI Assistant", null, true, true, null, "2.1.8"),AppInfo("com.xgimi.ota", "XGIMI Updates", null, true, true, null, "1.4.0"),AppInfo("com.google.android.tvrecommendations", "TV Recommendations", null, true, false, null, "1.0"),- AppInfo("com.android.systemui", "System UI", null, true, true, "the tv needs this to draw the screen", "11"),- AppInfo("com.android.tv.settings", "Settings", null, true, true, "you need this to change tv settings", "11"),+ AppInfo("com.android.systemui", "System UI", null, true, true, "the TV needs this to draw the screen", "11"),+ AppInfo("com.android.tv.settings", "Settings", null, true, true, "you need this to change TV settings", "11"),AppInfo("com.google.android.gms", "Google Play services", null, true, true, "most apps stop working without it", "24.38"),AppInfo("com.google.android.inputmethod.latin", "Gboard", null, true, true, "you'd lose the on-screen keyboard", "14.1"),)diff --git a/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt b/app/src/main/java/app/tellyscope/ui/DeviceScreen.ktindex 8689c78..ee46638 100644--- a/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt+++ b/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt@@ -152,7 +152,8 @@ fun DeviceScreen(if (offline) item { OfflineCard(device, state.now, actions.reconnect) }item { StatGrid(ui.snapshot, Modifier.alpha(if (offline) 0.4f else 1f)) }ui.snapshot?.let { snap ->- if (q.isEmpty()) item { UsageCard(snap, ui.apps) }+ // The :adb source has no per-process list yet; no bars beats an empty card.+ if (q.isEmpty() && snap.procs.isNotEmpty()) item { UsageCard(snap, ui.apps) }}section(key = "apps",@@ -313,11 +314,13 @@ private fun Bars(rows: List<Pair<String, Double>>, fmt: (Double) -> String, top:shown.forEach { (name, v) ->val frac by animateFloatAsState((v / max).toFloat(), MaterialTheme.motionScheme.defaultSpatialSpec(), label = "bar")Row(verticalAlignment = Alignment.CenterVertically) {- Text(name, Modifier.width(120.dp), style = MaterialTheme.typography.bodyMedium, maxLines = 1, overflow = TextOverflow.Ellipsis)+ // Long app names wrap to two lines rather than cut off; the value column only needs "1.2 GB".+ Text(name, Modifier.width(148.dp), style = MaterialTheme.typography.bodyMedium, maxLines = 2, overflow = TextOverflow.Ellipsis)+ Spacer(Modifier.width(8.dp))Box(Modifier.weight(1f).height(12.dp).clip(MaterialTheme.shapes.small).background(MaterialTheme.colorScheme.surfaceContainerHigh)) {Box(Modifier.fillMaxHeight().fillMaxWidth(frac).clip(MaterialTheme.shapes.small).background(MaterialTheme.colorScheme.primary))}- Text(fmt(v), Modifier.width(72.dp), style = SmallNumber, textAlign = androidx.compose.ui.text.style.TextAlign.End)+ Text(fmt(v), Modifier.width(60.dp), style = SmallNumber, textAlign = androidx.compose.ui.text.style.TextAlign.End)}}}diff --git a/app/src/main/java/app/tellyscope/ui/PermissionScreen.kt b/app/src/main/java/app/tellyscope/ui/PermissionScreen.ktnew file mode 100644index 0000000..1ff2b2a--- /dev/null+++ b/app/src/main/java/app/tellyscope/ui/PermissionScreen.kt@@ -0,0 +1,47 @@+// SPDX-License-Identifier: GPL-3.0-only++package app.tellyscope.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.material3.Button+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Scaffold+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp++/**+ * Shown before the first scan on Android 17+, where talking to anything on the+ * Wi-Fi needs the "Nearby devices" permission. Once the user has said no twice,+ * Android stops showing its dialog, so the button sends them to Settings instead.+ */+@Composable+fun PermissionScreen(denied: Boolean, onAllow: () -> Unit, onSettings: () -> Unit) {+ Scaffold { pad ->+ Column(+ Modifier.fillMaxSize().padding(pad).padding(24.dp),+ verticalArrangement = Arrangement.spacedBy(16.dp, androidx.compose.ui.Alignment.CenterVertically),+ ) {+ Text("Find TVs on your Wi-Fi", style = MaterialTheme.typography.headlineMedium)+ Text(+ "Android asks before an app talks to other devices on your Wi-Fi. " ++ "Tellyscope only connects to the TVs you pick.",+ style = MaterialTheme.typography.bodyLarge,+ )+ if (denied) {+ Text(+ "Without it, Tellyscope can't see any TV. In Settings, open Permissions → Nearby devices and choose Allow.",+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ Button(onClick = onSettings) { Text("Open Settings") }+ } else {+ Button(onClick = onAllow) { Text("Continue") }+ }+ }+ }+}diff --git a/app/src/main/java/app/tellyscope/ui/ScanScreen.kt b/app/src/main/java/app/tellyscope/ui/ScanScreen.ktindex 70ad8ab..fdfbbaa 100644--- a/app/src/main/java/app/tellyscope/ui/ScanScreen.kt+++ b/app/src/main/java/app/tellyscope/ui/ScanScreen.kt@@ -106,7 +106,7 @@ fun ScanScreen(}}}- if (adding) AddByIpDialog(onDismiss = { adding = false }, onSubmit = { onAddByIp(it).also { e -> if (e == null) adding = false } })+ if (adding) AddByIpDialog(subnet = scan.progress?.subnet, onDismiss = { adding = false }, onSubmit = { onAddByIp(it).also { e -> if (e == null) adding = false } })}@OptIn(ExperimentalMaterial3ExpressiveApi::class)@@ -116,7 +116,7 @@ private fun ScanStatus(scan: ScanUi) {Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {if (scan.scanning) {Text(- "Looking for TVs on ${p?.subnet ?: "your Wi-Fi"}… ${p?.probed ?: 0}/${p?.total ?: 254}",+ "Looking for TVs on your Wi-Fi… ${p?.probed ?: 0}/${p?.total ?: 254}",style = MaterialTheme.typography.labelLarge,)LinearWavyProgressIndicator(@@ -126,7 +126,7 @@ private fun ScanStatus(scan: ScanUi) {} else {val n = scan.hits.sizeText(- if (n == 0) "No TVs found yet" else "Found $n ${if (n == 1) "TV" else "TVs"} on ${p?.subnet ?: "your Wi-Fi"}",+ if (n == 0) "No TVs found yet" else "Found $n ${if (n == 1) "TV" else "TVs"} on your Wi-Fi",style = MaterialTheme.typography.labelLarge,)}@@ -179,7 +179,7 @@ private fun HitCard(Column {Text("Check your TV", style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.primary)Text(- "A box saying \"Allow USB debugging?\" is on screen. Tick \"Always allow from this phone\", then press Allow.",+ "A box saying \"Allow USB debugging?\" is on screen. Tick \"Always allow from this computer\", then press Allow.",style = MaterialTheme.typography.bodyMedium,)Text(@@ -226,7 +226,7 @@ private fun HitCard(}@Composable-private fun AddByIpDialog(onDismiss: () -> Unit, onSubmit: (String) -> String?) {+private fun AddByIpDialog(subnet: String?, onDismiss: () -> Unit, onSubmit: (String) -> String?) {var text by remember { mutableStateOf("") }var error by remember { mutableStateOf<String?>(null) }AlertDialog(@@ -235,6 +235,8 @@ private fun AddByIpDialog(onDismiss: () -> Unit, onSubmit: (String) -> String?)text = {Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {Text("Find it on the TV under Settings → Network → your Wi-Fi.")+ // The scan screen says "your Wi-Fi"; the range is only useful here, while typing.+ if (subnet != null) Text("Your Wi-Fi: $subnet", style = SmallNumber, color = MaterialTheme.colorScheme.onSurfaceVariant)OutlinedTextField(value = text,onValueChange = { text = it; error = null },diff --git a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.ktindex c5ddf2a..502e29b 100644--- a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt+++ b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt@@ -16,6 +16,7 @@ import app.tellyscope.data.ScanEventimport app.tellyscope.data.ScanHitimport app.tellyscope.data.ScanProgressimport app.tellyscope.data.Snapshot+import kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.Jobimport kotlinx.coroutines.delayimport kotlinx.coroutines.flow.MutableStateFlow@@ -75,6 +76,10 @@ class TellyscopeViewModel(private val _done = MutableStateFlow<HistoryEntry?>(null)val done: StateFlow<HistoryEntry?> = _done.asStateFlow()+ /** One-shot failures for the snackbar: the TV refused, or went away mid-action. */+ private val _error = MutableStateFlow<String?>(null)+ val error: StateFlow<String?> = _error.asStateFlow()+private var scanJob: Job? = nullprivate var liveJob: Job? = nullprivate var mediumJob: Job? = null@@ -184,11 +189,18 @@ class TellyscopeViewModel(source.live(id!!).collect { snap -> _state.update { it.copy(device = it.device.copy(snapshot = snap)) } }}mediumJob = viewModelScope.launch {- _state.update { it.copy(device = it.device.copy(apps = source.apps(id!!))) }- while (true) {- val net = source.network(id!!)- _state.update { it.copy(device = it.device.copy(network = net)) }- delay(10_000)+ // A TV that drops mid-read throws; the live flow ends and the offline card takes over.+ try {+ _state.update { it.copy(device = it.device.copy(apps = source.apps(id!!))) }+ while (true) {+ val net = source.network(id!!)+ _state.update { it.copy(device = it.device.copy(network = net)) }+ delay(10_000)+ }+ } catch (e: CancellationException) {+ throw e+ } catch (_: Exception) {+ // Nothing to show: the stats stop and the offline card explains.}}}@@ -217,8 +229,17 @@ class TellyscopeViewModel(val id = _state.value.selectedId ?: return_state.update { it.copy(device = it.device.copy(pending = null, busy = pkg)) }viewModelScope.launch {- val entry = source.act(id, action, pkg)- val apps = source.apps(id)+ // The source throws with the user-facing reason when the TV refuses.+ val (entry, apps) = try {+ source.act(id, action, pkg) to source.apps(id)+ } catch (e: CancellationException) {+ throw e+ } catch (e: Exception) {+ // Anything else (a dropped socket) still must not crash the app.+ _state.update { it.copy(device = it.device.copy(busy = null)) }+ _error.value = e.message?.replaceFirstChar(Char::uppercase) ?: "That didn't work."+ return@launch+ }_state.update { s ->val history = s.device.history.map { if (it.id == undoing) it.copy(undoneAt = entry.at) else it }s.copy(device = s.device.copy(apps = apps, busy = null, history = listOf(entry) + history))@@ -231,6 +252,10 @@ class TellyscopeViewModel(_done.value = null}+ fun errorShown() {+ _error.value = null+ }+private fun setRow(ip: String, row: RowState) =_state.update { it.copy(scan = it.scan.copy(rows = it.scan.rows + (ip to row))) }diff --git a/app/src/test/java/app/tellyscope/ScreenshotTest.kt b/app/src/test/java/app/tellyscope/ScreenshotTest.ktindex a20fdca..2f78185 100644--- a/app/src/test/java/app/tellyscope/ScreenshotTest.kt+++ b/app/src/test/java/app/tellyscope/ScreenshotTest.kt@@ -16,6 +16,7 @@ import app.tellyscope.data.ScanProgressimport app.tellyscope.ui.DeviceActionsimport app.tellyscope.ui.DeviceScreenimport app.tellyscope.ui.DeviceUi+import app.tellyscope.ui.PermissionScreenimport app.tellyscope.ui.RowStateimport app.tellyscope.ui.ScanScreenimport app.tellyscope.ui.ScanUi@@ -134,4 +135,8 @@ class ScreenshotTest {)shot("07_device_history") { DeviceScreen(deviceState { copy(history = history) }, DeviceActions()) }}++ @Test fun permission() = shot("08_permission") { PermissionScreen(denied = false, {}, {}) }++ @Test fun permission_denied() = shot("08_permission_denied") { PermissionScreen(denied = true, {}, {}) }}