Skip to content

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.

Keep the link when a stats read is slow; pause stats during changes

jesse-agent-362dd2fe7b36ae4
diff --git a/adb/src/main/kotlin/app/tellyscope/adb/DeviceLink.kt b/adb/src/main/kotlin/app/tellyscope/adb/DeviceLink.kt
index 6a16d99..cecd943 100644
--- a/adb/src/main/kotlin/app/tellyscope/adb/DeviceLink.kt
+++ b/adb/src/main/kotlin/app/tellyscope/adb/DeviceLink.kt
@@ -26,7 +26,7 @@ class DeviceLink(
val port: Int,
private val scope: CoroutineScope,
private val retryEvery: Duration = 5.seconds,
- private val monitorFor: (AdbShell) -> MonitorSource = { DeviceMonitor(it) },
+ private val monitorFor: (AdbShell, StatsGate) -> MonitorSource = { s, gate -> DeviceMonitor(s, gate = gate) },
private val open: suspend (String, Int) -> ConnectResult = { h, p -> Connector.connect(h, p) },
private val knownGood: Boolean = false,
private val notAllowedLimit: Int = 3,
@@ -38,6 +38,9 @@ class DeviceLink(
private val _stats = MutableStateFlow<Stats?>(null)
val stats: StateFlow<Stats?> = _stats.asStateFlow()
+ /** Pauses the stats while a change runs on this TV, and turns the process list on and off. */
+ val gate = StatsGate()
+
@Volatile var session: AdbSession? = null
private set
@Volatile var lastSeenMillis: Long? = null
@@ -88,7 +91,7 @@ class DeviceLink(
session = s
_state.value = _state.value.on(DeviceEvent.Authorized)
try {
- monitorFor(s).stats().collect {
+ monitorFor(s, gate).stats().collect {
_stats.value = it
lastSeenMillis = System.currentTimeMillis()
}
diff --git a/adb/src/main/kotlin/app/tellyscope/adb/DeviceMonitor.kt b/adb/src/main/kotlin/app/tellyscope/adb/DeviceMonitor.kt
index f0ee0c0..427373a 100644
--- a/adb/src/main/kotlin/app/tellyscope/adb/DeviceMonitor.kt
+++ b/adb/src/main/kotlin/app/tellyscope/adb/DeviceMonitor.kt
@@ -3,13 +3,17 @@ package app.tellyscope.adb
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flow
+import kotlinx.coroutines.flow.update
import kotlinx.coroutines.withTimeoutOrNull
import java.io.IOException
import java.time.YearMonth
import kotlin.time.ComparableTimeMark
import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds
+import kotlin.time.TimeMark
import kotlin.time.TimeSource
/** One reading for the stat strip. Null fields mean "this TV doesn't report it". */
@@ -43,11 +47,39 @@ fun interface MonitorSource {
}
/**
- * Live stats on three tiers: CPU/RAM/network speed every [fast], processes and screen state every [medium],
- * identity/storage/uptime/temperature/packages every [slow].
+ * What the app tells one TV's stats loop. [during] pauses it while a change runs, so a slow read
+ * never competes with `pm`, an install or a Home switch; [processes] says whether a screen shows
+ * the process list.
+ */
+class StatsGate {
+ private val running = MutableStateFlow(0)
+
+ /** False skips `top` and `dumpsys power`, the heavy read; the last list is kept. */
+ val processes = MutableStateFlow(true)
+
+ val busy: Boolean get() = running.value > 0
+
+ suspend fun <T> during(block: suspend () -> T): T {
+ running.update { it + 1 }
+ try {
+ return block()
+ } finally {
+ running.update { it - 1 }
+ }
+ }
+
+ internal suspend fun awaitIdle() {
+ running.first { it == 0 }
+ }
+}
+
+/**
+ * Live stats on three tiers: CPU/RAM/network speed every [fast], processes and screen state every [medium]
+ * while [StatsGate.processes] is on, identity/storage/uptime/temperature/packages every [slow].
* The first emission comes after one fast interval, since CPU % needs two samples.
- * Shell failures and reads slower than [readTimeout] throw [IOException], so the caller can mark
- * the device offline instead of waiting out the socket timeout.
+ * A read slower than [readTimeout] skips that sample. Shell failures throw, and so does a slow read
+ * the TV then doesn't follow with an `echo` answer within [pingTimeout], so the caller can mark it
+ * offline instead of waiting out the socket timeout.
*/
class DeviceMonitor(
private val shell: AdbShell,
@@ -55,49 +87,69 @@ class DeviceMonitor(
private val medium: Duration = 10.seconds,
private val slow: Duration = 60.seconds,
private val readTimeout: Duration = 10.seconds,
+ private val pingTimeout: Duration = 10.seconds,
+ private val gate: StatsGate = StatsGate(),
/** Times network speed; tests pass the test scheduler's clock. */
private val clock: TimeSource.WithComparableMarks = TimeSource.Monotonic,
) : MonitorSource {
override fun stats(): Flow<Stats> = flow {
- var slowStats = readSlow()
- var lastSlow = TimeSource.Monotonic.markNow()
- var mediumStats = readMedium(slowStats.packages)
- var lastMedium = TimeSource.Monotonic.markNow()
- var prev = readFast()
+ var slowStats = Stats(cpuPercent = null, memory = null)
+ var lastSlow: TimeMark? = null
+ var mediumStats: Pair<List<AppProcess>, Boolean?> = emptyList<AppProcess>() to null
+ var lastMedium: TimeMark? = null
+ var prev: Fast? = null
while (true) {
- delay(fast)
- if (lastSlow.elapsedNow() >= slow) {
- slowStats = readSlow()
+ // A skipped tier waits its whole interval again, so a TV that is always slow isn't asked every 2 s.
+ if (lastSlow.due(slow)) {
+ readSlow()?.let { slowStats = it }
lastSlow = TimeSource.Monotonic.markNow()
}
- if (lastMedium.elapsedNow() >= medium) {
- mediumStats = readMedium(slowStats.packages)
+ if (gate.processes.value && lastMedium.due(medium)) {
+ readMedium(slowStats.packages)?.let { mediumStats = it }
lastMedium = TimeSource.Monotonic.markNow()
}
val now = readFast()
- val pct = if (prev.cpu != null && now.cpu != null) Parsers.cpuPercent(prev.cpu, now.cpu) else null
- emit(
- slowStats.copy(
- cpuPercent = pct,
- memory = now.memory,
- processes = mediumStats.first,
- screenOn = mediumStats.second,
- netBytesPerSec = rate(prev, now),
- ),
- )
- prev = now
+ val last = prev
+ if (now != null && last != null) {
+ val pct = if (last.cpu != null && now.cpu != null) Parsers.cpuPercent(last.cpu, now.cpu) else null
+ emit(
+ slowStats.copy(
+ cpuPercent = pct,
+ memory = now.memory,
+ processes = mediumStats.first,
+ screenOn = mediumStats.second,
+ netBytesPerSec = rate(last, now),
+ ),
+ )
+ }
+ if (now != null) prev = now
+ delay(fast)
}
}
- private suspend fun run(command: String): String =
- withTimeoutOrNull(readTimeout) { shell.shell(command).output }
- ?: throw IOException("no answer in $readTimeout")
+ private fun TimeMark?.due(every: Duration) = this == null || elapsedNow() >= every
+
+ /**
+ * Null skips the sample: the read ran past [readTimeout] while a change was running, or the TV
+ * still answered `echo` after it. While a change runs nothing is read, but the TV is pinged
+ * every [medium], so one that dies mid-change still ends the change instead of hanging it.
+ */
+ private suspend fun run(command: String): String? {
+ while (withTimeoutOrNull(medium) { gate.awaitIdle() } == null) ping()
+ withTimeoutOrNull(readTimeout) { shell.shell(command).output }?.let { return it }
+ if (!gate.busy) ping()
+ return null
+ }
+
+ private suspend fun ping() {
+ withTimeoutOrNull(pingTimeout) { shell.shell("echo") } ?: throw IOException("no answer to echo in $pingTimeout")
+ }
private class Fast(val cpu: Parsers.CpuTimes?, val memory: Parsers.Memory?, val netBytes: Long?, val at: ComparableTimeMark)
- private suspend fun readFast(): Fast {
- val (stat, meminfo, netDev) = Commands.split(run(Commands.FAST), 3)
+ private suspend fun readFast(): Fast? {
+ val (stat, meminfo, netDev) = Commands.split(run(Commands.FAST) ?: return null, 3)
return Fast(Parsers.cpuTimes(stat), Parsers.memory(meminfo), Parsers.netBytes(netDev), clock.markNow())
}
@@ -108,8 +160,8 @@ class DeviceMonitor(
return if (bytes < 0 || ms <= 0) null else bytes * 1000 / ms
}
- private suspend fun readMedium(packages: Map<Int, List<String>>): Pair<List<AppProcess>, Boolean?> {
- val (top, power) = Commands.split(run(Commands.MEDIUM), 2)
+ private suspend fun readMedium(packages: Map<Int, List<String>>): Pair<List<AppProcess>, Boolean?>? {
+ val (top, power) = Commands.split(run(Commands.MEDIUM) ?: return null, 2)
val known = packages.values.flatten().toSet()
val procs = Parsers.processes(top).map { p ->
AppProcess(p.pid, p.name, Parsers.owner(p, packages, known), p.cpuPercent, p.rssKb)
@@ -117,8 +169,8 @@ class DeviceMonitor(
return procs to Parsers.screenOn(power)
}
- private suspend fun readSlow(): Stats {
- val (getprop, df, uptime, thermal, pm) = Commands.split(run(Commands.SLOW), 5)
+ private suspend fun readSlow(): Stats? {
+ val (getprop, df, uptime, thermal, pm) = Commands.split(run(Commands.SLOW) ?: return null, 5)
val props = Parsers.props(getprop)
return Stats(
cpuPercent = null,
diff --git a/adb/src/test/kotlin/app/tellyscope/adb/DeviceLinkTest.kt b/adb/src/test/kotlin/app/tellyscope/adb/DeviceLinkTest.kt
index 5ff68d8..2bd8867 100644
--- a/adb/src/test/kotlin/app/tellyscope/adb/DeviceLinkTest.kt
+++ b/adb/src/test/kotlin/app/tellyscope/adb/DeviceLinkTest.kt
@@ -55,7 +55,7 @@ class DeviceLinkTest {
var failNext = true
val link = DeviceLink(
"tv", 5555, backgroundScope,
- monitorFor = { fakeMonitor(failFirst = failNext.also { failNext = false }) },
+ monitorFor = { _, _ -> fakeMonitor(failFirst = failNext.also { failNext = false }) },
open = { _, _ ->
if (reachable) ConnectResult.Online(FakeShell().also { sessions += it }) else ConnectResult.Unreachable("no route")
},
@@ -90,7 +90,7 @@ class DeviceLinkTest {
var calls = 0
val link = DeviceLink(
"tv", 5555, backgroundScope,
- monitorFor = { fakeMonitor(failFirst = true) },
+ monitorFor = { _, _ -> fakeMonitor(failFirst = true) },
open = { _, _ -> if (calls++ == 0) ConnectResult.Online(FakeShell()) else ConnectResult.NotAllowed },
)
link.connect(); runCurrent()
@@ -101,7 +101,7 @@ class DeviceLinkTest {
@Test fun disconnectClosesSessionAndResets() = runTest {
val shell = FakeShell()
- val link = DeviceLink("tv", 5555, backgroundScope, monitorFor = { fakeMonitor(failFirst = false) },
+ val link = DeviceLink("tv", 5555, backgroundScope, monitorFor = { _, _ -> fakeMonitor(failFirst = false) },
open = { _, _ -> ConnectResult.Online(shell) })
link.connect(); runCurrent()
assertEquals(DeviceState.ONLINE, link.state.value)
diff --git a/adb/src/test/kotlin/app/tellyscope/adb/DeviceMonitorTest.kt b/adb/src/test/kotlin/app/tellyscope/adb/DeviceMonitorTest.kt
index 2576a90..19b89ea 100644
--- a/adb/src/test/kotlin/app/tellyscope/adb/DeviceMonitorTest.kt
+++ b/adb/src/test/kotlin/app/tellyscope/adb/DeviceMonitorTest.kt
@@ -1,15 +1,23 @@
// SPDX-License-Identifier: GPL-3.0-only
package app.tellyscope.adb
+import kotlinx.coroutines.CompletableDeferred
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.take
import kotlinx.coroutines.flow.toList
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.test.advanceTimeBy
+import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import java.io.IOException
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
+import kotlin.test.assertTrue
+@OptIn(ExperimentalCoroutinesApi::class)
class DeviceMonitorTest {
private val sep = "\n@@tellyscope@@\n"
@@ -86,4 +94,67 @@ class DeviceMonitorTest {
assertEquals(false, s.screenOn)
assertEquals(mapOf(10087 to listOf("com.google.android.youtube.tv")), s.packages)
}
+
+ /** Answers the fast read and `echo`, logs every command, and hangs on `top` until cancelled. */
+ private class SlowTop(val onTop: () -> Unit = {}) : AdbShell {
+ val ran = mutableListOf<String>()
+
+ override suspend fun shell(command: String): ShellResult {
+ ran += command
+ if (command.startsWith("top")) { onTop(); awaitCancellation() }
+ return if (command.startsWith("cat /proc/stat")) ok("cpu 25 0 0 75 0 0 0 0\n@@tellyscope@@\nMemTotal: 2000 kB\n") else ok("")
+ }
+ }
+
+ @Test fun aSlowReadOnlySkipsItsSample() = runTest {
+ // A TV busy changing Home: `top` runs past the timeout, but the TV still answers, so it isn't lost.
+ val tv = SlowTop()
+ val readings = DeviceMonitor(tv).stats().take(2).toList()
+ assertEquals(2, readings.size)
+ assertEquals(emptyList<AppProcess>(), readings.last().processes)
+ assertTrue("echo" in tv.ran)
+ }
+
+ @Test fun statsWaitWhileAChangeRuns() = runTest {
+ val gate = StatsGate()
+ val topStarted = CompletableDeferred<Unit>()
+ val tv = SlowTop { topStarted.complete(Unit) }
+ val readings = mutableListOf<Stats>()
+ val collecting = backgroundScope.launch { DeviceMonitor(tv, gate = gate).stats().collect { readings += it } }
+ topStarted.await()
+
+ // A change starts while the process read is still out, as in the reported capture.
+ val done = CompletableDeferred<Unit>()
+ launch { gate.during { done.await() } }
+ runCurrent()
+ val before = tv.ran.size
+ advanceTimeBy(60_000)
+ val during = tv.ran.drop(before)
+ assertTrue(during.isNotEmpty() && during.all { it == "echo" }, "ran during the change: $during")
+ assertTrue(collecting.isActive)
+ assertEquals(emptyList<Stats>(), readings)
+
+ done.complete(Unit)
+ advanceTimeBy(5_000)
+ assertTrue(readings.isNotEmpty())
+ }
+
+ @Test fun aTvThatDiesMidChangeIsStillLost() = runTest {
+ val gate = StatsGate()
+ val ran = mutableListOf<String>()
+ val dead = AdbShell { cmd -> ran += cmd; awaitCancellation() }
+ backgroundScope.launch { gate.during { awaitCancellation() } }
+ runCurrent()
+ assertFailsWith<IOException> { DeviceMonitor(dead, gate = gate).stats().first() }
+ assertEquals(listOf("echo"), ran)
+ }
+
+ @Test fun processesOffSkipsTheHeavyRead() = runTest {
+ val gate = StatsGate().apply { processes.value = false }
+ val tv = SlowTop()
+ val s = DeviceMonitor(tv, gate = gate).stats().first()
+ assertEquals(emptyList<AppProcess>(), s.processes)
+ assertTrue(tv.ran.none { it.startsWith("top") }, "ran: ${tv.ran}")
+ assertTrue("echo" !in tv.ran)
+ }
}
diff --git a/app/src/main/java/app/tellyscope/MainActivity.kt b/app/src/main/java/app/tellyscope/MainActivity.kt
index d605645..d49fcf3 100644
--- a/app/src/main/java/app/tellyscope/MainActivity.kt
+++ b/app/src/main/java/app/tellyscope/MainActivity.kt
@@ -19,6 +19,7 @@ import androidx.compose.material3.SnackbarDuration
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.SnackbarResult
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
@@ -209,6 +210,10 @@ fun TellyscopeApp(vm: TellyscopeViewModel) {
)
} else if (advanced) {
BackHandler { advanced = false }
+ DisposableEffect(Unit) {
+ vm.showProcesses(true)
+ onDispose { vm.showProcesses(false) }
+ }
AdvancedScreen(state, back = { advanced = false }, snackbar = snackbar)
} else if (settings) {
BackHandler { settings = false }
@@ -272,6 +277,7 @@ fun TellyscopeApp(vm: TellyscopeViewModel) {
answerRequest = vm::answerRequest,
dismissRequest = vm::dismissRequest,
foldSystem = vm::foldSystem,
+ showProcesses = vm::showProcesses,
),
)
}
diff --git a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt
index 16770e3..b6af002 100644
--- a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt
+++ b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt
@@ -70,6 +70,7 @@ class AdbDeviceSource(context: Context) : DeviceSource {
private val appContext = context.applicationContext
private val scope = CoroutineScope(SupervisorJob())
private val links = ConcurrentHashMap<String, DeviceLink>()
+ @Volatile private var processesFor: String? = null
private val hits = ConcurrentHashMap<String, ScanHit>()
private val store = DeviceStore(File(appContext.filesDir, "devices.tsv"))
private val saved = ConcurrentHashMap<String, SavedDevice>()
@@ -111,6 +112,7 @@ class AdbDeviceSource(context: Context) : DeviceSource {
val link = DeviceLink(host, port, scope, knownGood = knownGood, open = { h, p ->
pending?.also { pending = null } ?: Connector.connect(h, p)
})
+ link.gate.processes.value = host == processesFor
links.put(host, link)?.disconnect()
watchers.put(host, scope.launch {
// Save a fresh reading only when what's kept of it changed, not every 2 s.
@@ -303,6 +305,15 @@ class AdbDeviceSource(context: Context) : DeviceSource {
}
}
+ override fun showProcesses(deviceId: String?) {
+ processesFor = deviceId
+ links.forEach { (host, link) -> link.gate.processes.value = host == deviceId }
+ }
+
+ /** Runs a change with that TV's stats paused, so a slow stats read can't compete with it or cut it off. */
+ private suspend fun <T> busy(deviceId: String, block: suspend () -> T): T =
+ links[deviceId]?.gate?.during(block) ?: block()
+
override suspend fun apps(deviceId: String): List<AppInfo> {
val shell = session(deviceId)
val home = Actions(shell).homePackages()
@@ -381,7 +392,10 @@ class AdbDeviceSource(context: Context) : DeviceSource {
return labels[pkg] ?: AppNames.fallback(pkg)
}
- override suspend fun act(deviceId: String, action: Action, packageName: String, undoing: Long?): HistoryEntry {
+ override suspend fun act(deviceId: String, action: Action, packageName: String, undoing: Long?): HistoryEntry =
+ busy(deviceId) { actNow(deviceId, action, packageName, undoing) }
+
+ private suspend fun actNow(deviceId: String, action: Action, packageName: String, undoing: Long?): HistoryEntry {
val shell = session(deviceId)
// Before the first change on a TV, note what was already off: Restore must leave those alone.
val key = key(deviceId)
@@ -534,9 +548,9 @@ class AdbDeviceSource(context: Context) : DeviceSource {
return Resolved(index, match, list, out.getOrNull(MATCH_KEYS.size)?.toIntOrNull())
}
- override suspend fun press(deviceId: String, key: RemoteKey) = Remote(session(deviceId)).press(key)
+ override suspend fun press(deviceId: String, key: RemoteKey) = busy(deviceId) { Remote(session(deviceId)).press(key) }
- override suspend fun type(deviceId: String, text: String) = Remote(session(deviceId)).type(text)
+ override suspend fun type(deviceId: String, text: String) = busy(deviceId) { Remote(session(deviceId)).type(text) }
override suspend fun reboot(deviceId: String) = Remote(session(deviceId)).reboot()
@@ -549,7 +563,10 @@ class AdbDeviceSource(context: Context) : DeviceSource {
private suspend fun sdk(deviceId: String) = session(deviceId).shell("getprop ro.build.version.sdk").output.trim().toIntOrNull()
- override suspend fun change(deviceId: String, tweak: Tweak, values: Map<String, String?>, undoing: Long?): HistoryEntry {
+ override suspend fun change(deviceId: String, tweak: Tweak, values: Map<String, String?>, undoing: Long?): HistoryEntry =
+ busy(deviceId) { changeNow(deviceId, tweak, values, undoing) }
+
+ private suspend fun changeNow(deviceId: String, tweak: Tweak, values: Map<String, String?>, undoing: Long?): HistoryEntry {
val t = Tweaks(session(deviceId))
val strictDns = tweak == Tweak.PRIVATE_DNS && values["private_dns_mode"] == "hostname"
if (strictDns && (sdk(deviceId) ?: TvSettings.DNS_SDK) < TvSettings.DNS_SDK) throw IllegalStateException(TvSettings.DNS_TOO_OLD)
@@ -568,7 +585,7 @@ class AdbDeviceSource(context: Context) : DeviceSource {
}
override suspend fun clearCaches(deviceId: String): Long? {
- val freed = Tweaks(session(deviceId)).clearCaches()
+ val freed = busy(deviceId) { Tweaks(session(deviceId)).clearCaches() }
book.record(key(deviceId), System.currentTimeMillis(), Action.ClearCaches, "", TvSettings.CACHES, undo = null)
return freed
}
@@ -616,15 +633,15 @@ class AdbDeviceSource(context: Context) : DeviceSource {
apk: ApkInfo,
allowDowngrade: Boolean,
onProgress: (Progress) -> Unit,
- ): InstallResult = Sideload(session(deviceId)).install(apks, apk, allowDowngrade, onProgress)
+ ): InstallResult = busy(deviceId) { Sideload(session(deviceId)).install(apks, apk, allowDowngrade, onProgress) }
override suspend fun files(deviceId: String, folder: TvFolder) = Files(session(deviceId)).list(folder)
override suspend fun push(deviceId: String, folder: TvFolder, name: String, size: Long?, source: Source, onProgress: (Progress) -> Unit) =
- Files(session(deviceId)).push(source, size, name, folder, onProgress)
+ busy(deviceId) { Files(session(deviceId)).push(source, size, name, folder, onProgress) }
override suspend fun pull(deviceId: String, folder: TvFolder, file: TvFile, sink: Sink, onProgress: (Progress) -> Unit) =
- Files(session(deviceId)).pull(folder, file, sink, onProgress)
+ busy(deviceId) { Files(session(deviceId)).pull(folder, file, sink, onProgress) }
private fun session(deviceId: String) =
links[deviceId]?.session ?: throw IllegalStateException("$deviceId is offline")
diff --git a/app/src/main/java/app/tellyscope/data/DeviceSource.kt b/app/src/main/java/app/tellyscope/data/DeviceSource.kt
index 9177863..014c841 100644
--- a/app/src/main/java/app/tellyscope/data/DeviceSource.kt
+++ b/app/src/main/java/app/tellyscope/data/DeviceSource.kt
@@ -51,6 +51,9 @@ interface DeviceSource {
/** Fast-tier stats. Completes when the device goes offline. */
fun live(deviceId: String): Flow<Snapshot>
+ /** Reads the process list only for [deviceId], while a screen shows it; null for none. */
+ fun showProcesses(deviceId: String?) {}
+
suspend fun apps(deviceId: String): List<AppInfo>
suspend fun network(deviceId: String): NetworkInfo
diff --git a/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt b/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt
index 8fcf353..5e5fd3f 100644
--- a/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt
+++ b/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt
@@ -109,6 +109,8 @@ data class DeviceActions(
val dismissRequest: () -> Unit = {},
/** Folds an Apps tab's System section away, or opens it; remembered across restarts. */
val foldSystem: (AppsTab, Boolean) -> Unit = { _, _ -> },
+ /** Whether the open tab shows the process list; only then does the TV's process read run. */
+ val showProcesses: (Boolean) -> Unit = {},
)
/** Off while the remote is made faster: the device page hides its Remote button. */
diff --git a/app/src/main/java/app/tellyscope/ui/DeviceTabs.kt b/app/src/main/java/app/tellyscope/ui/DeviceTabs.kt
index e86b332..4638963 100644
--- a/app/src/main/java/app/tellyscope/ui/DeviceTabs.kt
+++ b/app/src/main/java/app/tellyscope/ui/DeviceTabs.kt
@@ -65,6 +65,7 @@ import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.toShape
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
@@ -173,6 +174,11 @@ fun DeviceTabsScreen(
// "See changes" lands on Tweaks scrolled to Recent changes, the list's third item, after the hero.
var toChanges by remember { mutableStateOf(false) }
var shown by rememberSaveable { mutableStateOf(tab) }
+ // Overview and Apps (Running, RAM per app) show processes; Files and Tweaks don't need the read.
+ DisposableEffect(tab, device.id) {
+ actions.showProcesses(tab == TvTab.Overview || tab == TvTab.Apps)
+ onDispose { actions.showProcesses(false) }
+ }
LaunchedEffect(tab) {
if (tab == shown) return@LaunchedEffect
shown = tab
diff --git a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt
index 5999010..4e64adb 100644
--- a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt
+++ b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt
@@ -333,6 +333,9 @@ class TellyscopeViewModel(
if (transferJobs[_state.value.selectedId]?.isActive != true) select(device.id)
}
+ /** Only the TV on screen reads its process list, and only while the screen shows it. */
+ fun showProcesses(on: Boolean) = source.showProcesses(if (on) _state.value.selectedId else null)
+
fun select(id: String?) {
liveJob?.cancel()
mediumJob?.cancel()