From 54be32bb1b107887460e7c942c80d62b979109a7 Mon Sep 17 00:00:00 2001 From: Thomas Kroll Date: Fri, 13 Nov 2026 20:49:38 +0100 Subject: [PATCH 01/11] fix: resume a paused container with unpause instead of start The Resume button on a paused container sent the start mutation, which Docker refuses ("cannot start a paused container, try unpause instead"), so the container stayed paused. A paused container now gets the existing UnpauseContainer mutation (docker.unpause, available since API 4.29.0, so on every supported server and without a capability floor); a stopped container still gets start. The choice is made once, in UnraidRepository.startContainer(client, id, paused), the same seam as restartContainer. The Docker tab row and the container sheet both go through MainViewModel.startContainer(Container). The demo follows the repository surface: UnraidGateway.startContainer takes the same flag, and the demo model refuses start on a paused container like Docker does, so the demo no longer hides the bug. Closes #345 Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 5 ++++ .../nofuturekid/nova/data/demo/DemoState.kt | 11 +++++++-- .../nofuturekid/nova/data/demo/DemoUnraid.kt | 3 ++- .../nova/data/repository/UnraidGateway.kt | 4 +++- .../nova/data/repository/UnraidRepository.kt | 16 ++++++++++++- .../nova/ui/screens/main/MainScreen.kt | 4 ++-- .../nova/ui/screens/main/MainViewModel.kt | 6 ++++- .../nova/data/demo/DemoStateTest.kt | 19 +++++++++++++++ .../data/repository/ActionResponseTest.kt | 24 +++++++++++++++++++ .../nova/data/repository/UnraidGatewayTest.kt | 7 ++++-- 10 files changed, 89 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c3199ea..203ae27 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -56,6 +56,11 @@ release version + date and opens a fresh `[Unreleased]`. ### Fixed +- **Resume on a paused container now works** — the Resume button in the Docker tab asked the + server to start the container, which Docker refuses for a paused one, so the container stayed + paused and the app showed an error. Resume now sends the "unpause" action; Start on a stopped + container is unchanged (#345). + - **A turned-off service no longer makes the whole server look offline** — with VMs or Docker switched off, the pill at the top used to read "Offline" even though the server answered. Now only a server that really cannot be reached diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/data/demo/DemoState.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/data/demo/DemoState.kt index 28b106a..4d8a794 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/data/demo/DemoState.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/data/demo/DemoState.kt @@ -104,11 +104,18 @@ data class DemoState( private fun withContainer(id: String, f: (Container) -> Container) = copy(containers = containers.map { if (it.id == id) f(it) else it }) - fun startContainer(id: String) = withContainer(id) { it.copy(status = ContainerStatus.Running) } + /** Docker refuses `start` for a paused container; it needs [unpauseContainer] (#345). */ + fun startContainer(id: String) = withContainer(id) { + if (it.status == ContainerStatus.Paused) it else it.copy(status = ContainerStatus.Running) + } + + fun unpauseContainer(id: String) = withContainer(id) { + if (it.status == ContainerStatus.Paused) it.copy(status = ContainerStatus.Running) else it + } fun stopContainer(id: String) = withContainer(id) { it.copy(status = ContainerStatus.Exited) } /** Restart ends running, also for a container that was stopped. */ - fun restartContainer(id: String) = startContainer(id) + fun restartContainer(id: String) = withContainer(id) { it.copy(status = ContainerStatus.Running) } fun pauseContainer(id: String) = withContainer(id) { if (it.status == ContainerStatus.Running) it.copy(status = ContainerStatus.Paused) else it diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/data/demo/DemoUnraid.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/data/demo/DemoUnraid.kt index 801c6fb..2953cbd 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/data/demo/DemoUnraid.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/data/demo/DemoUnraid.kt @@ -156,7 +156,8 @@ class DemoUnraid internal constructor( fun startArray() = act { it.startArray() } fun stopArray() = act { it.stopArray() } - fun startContainer(id: String) = act { it.startContainer(id) } + fun startContainer(id: String, paused: Boolean) = + act { if (paused) it.unpauseContainer(id) else it.startContainer(id) } fun stopContainer(id: String) = act { it.stopContainer(id) } fun restartContainer(id: String) = act { it.restartContainer(id) } fun pauseContainer(id: String) = act { it.pauseContainer(id) } diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/UnraidGateway.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/UnraidGateway.kt index 56a93da..c500498 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/UnraidGateway.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/UnraidGateway.kt @@ -104,7 +104,9 @@ class UnraidGateway @Inject constructor( suspend fun startArray() = action({ real.startArray() }, { demo.startArray() }) suspend fun stopArray() = action({ real.stopArray() }, { demo.stopArray() }) - suspend fun startContainer(id: String) = action({ real.startContainer(id) }, { demo.startContainer(id) }) + /** [paused] picks `unpause` over `start` (#345); the demo resumes or starts the container in its model. */ + suspend fun startContainer(id: String, paused: Boolean) = + action({ real.startContainer(id, paused) }, { demo.startContainer(id, paused) }) suspend fun stopContainer(id: String) = action({ real.stopContainer(id) }, { demo.stopContainer(id) }) /** [atomic] is the real server's choice (#346); the demo restarts the container in its model either way. */ suspend fun restartContainer(id: String, atomic: Boolean) = diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/UnraidRepository.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/UnraidRepository.kt index 81df2ed..90ab4c4 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/UnraidRepository.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/UnraidRepository.kt @@ -109,6 +109,7 @@ import io.github.nofuturekid.nova.graphql.StartParityCheckMutation import io.github.nofuturekid.nova.graphql.StartVmMutation import io.github.nofuturekid.nova.graphql.StopArrayMutation import io.github.nofuturekid.nova.graphql.StopContainerMutation +import io.github.nofuturekid.nova.graphql.UnpauseContainerMutation import io.github.nofuturekid.nova.graphql.UpdateAllContainersMutation import io.github.nofuturekid.nova.graphql.UpdateContainerMutation import io.github.nofuturekid.nova.graphql.StopVmMutation @@ -287,6 +288,16 @@ class UnraidRepository @Inject constructor( } } + /** + * Starts a container, or resumes it when it is [paused]. Docker refuses `start` for a paused + * container ("cannot start a paused container, try unpause instead"), so a paused one gets + * `unpause` and never `start` (#345). + */ + internal suspend fun startContainer(client: ApolloClient, id: String, paused: Boolean) { + if (paused) client.runAction(UnpauseContainerMutation(id)) + else client.runAction(StartContainerMutation(id)) + } + /** The logs query behind [containerLogs]; `null` = the request failed. */ internal suspend fun fetchContainerLogs(client: ApolloClient, id: String, tail: Int): List? { val resp = try { @@ -1158,7 +1169,10 @@ class UnraidRepository @Inject constructor( suspend fun startArray() { activeClient()?.runAction(StartArrayMutation()) } suspend fun stopArray() { activeClient()?.runAction(StopArrayMutation()) } - suspend fun startContainer(id: String) { activeClient()?.runAction(StartContainerMutation(id)) } + /** [paused]: resume the container with `unpause`; `start` is only for a stopped one (#345). */ + suspend fun startContainer(id: String, paused: Boolean) { + activeClient()?.let { startContainer(it, id, paused) } + } suspend fun stopContainer(id: String) { activeClient()?.runAction(StopContainerMutation(id)) } /** [atomic]: use the server's own `docker.restart` (API 4.36.0+), else stop + start. */ suspend fun restartContainer(id: String, atomic: Boolean) { diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/main/MainScreen.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/main/MainScreen.kt index 2cf2c30..47dc52e 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/main/MainScreen.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/main/MainScreen.kt @@ -307,7 +307,7 @@ fun MainScreen( onAddServer = onAddServer, stats = dockerLiveStats, onOpenContainer = { setOpenContainer(it) }, - onStart = { c -> vm.startContainer(c.id) }, + onStart = { c -> vm.startContainer(c) }, onRestart = { c -> confirm = ConfirmRequest( title = "Restart ${c.name}?", @@ -382,7 +382,7 @@ fun MainScreen( onFetchLogs = { id -> vm.containerLogs(id) }, onRefresh = { vm.refresh() }, onDismiss = { setOpenContainer(null) }, - onStart = { vm.startContainer(it.id); setOpenContainer(null) }, + onStart = { vm.startContainer(it); setOpenContainer(null) }, onRestart = { c -> confirm = ConfirmRequest( title = "Restart ${c.name}?", diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/main/MainViewModel.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/main/MainViewModel.kt index 5091202..e75b2f0 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/main/MainViewModel.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/main/MainViewModel.kt @@ -40,6 +40,7 @@ import io.github.nofuturekid.nova.data.model.DisplayThresholds import io.github.nofuturekid.nova.data.model.NotifType import io.github.nofuturekid.nova.data.model.Container import io.github.nofuturekid.nova.data.model.ContainerLiveStats +import io.github.nofuturekid.nova.data.model.ContainerStatus import io.github.nofuturekid.nova.data.model.LiveMetrics import io.github.nofuturekid.nova.data.model.NetworkThroughput import io.github.nofuturekid.nova.data.model.Notifications @@ -399,7 +400,10 @@ class MainViewModel @Inject constructor( fun startArray() = launchAction { unraid.startArray() } fun stopArray() = launchAction { unraid.stopArray() } - fun startContainer(id: String) = launchAction { unraid.startContainer(id) } + /** Start for a stopped container, resume (`unpause`) for a paused one (#345). */ + fun startContainer(c: Container) = launchAction { + unraid.startContainer(c.id, paused = c.status == ContainerStatus.Paused) + } fun stopContainer(id: String) = launchAction { unraid.stopContainer(id) } fun restartContainer(id: String) = launchAction { // Unknown API version stays on stop + start: only a known 4.36.0+ server gets `docker.restart`. diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/data/demo/DemoStateTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/data/demo/DemoStateTest.kt index 6524ff4..0c432ba 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/data/demo/DemoStateTest.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/data/demo/DemoStateTest.kt @@ -41,6 +41,25 @@ class DemoStateTest { assertEquals(ContainerStatus.Running, start.stopContainer("plex").restartContainer("plex").container("plex").status) } + // WHY (#345): Docker answers `start` on a paused container with "try unpause instead". The demo must + // not hide the bug the real server shows: only unpause resumes a paused container. + @Test fun aPausedContainerResumesWithUnpauseNotStart() { + val paused = start.pauseContainer("plex") + assertEquals(ContainerStatus.Paused, paused.startContainer("plex").container("plex").status) + assertEquals(ContainerStatus.Running, paused.unpauseContainer("plex").container("plex").status) + } + + // WHY: unpause answers only a paused container; it must not start a stopped one by the back door. + @Test fun unpauseLeavesAStoppedOrRunningContainerAlone() { + assertEquals(ContainerStatus.Exited, start.unpauseContainer("jellyfin").container("jellyfin").status) + assertEquals(ContainerStatus.Running, start.unpauseContainer("plex").container("plex").status) + } + + // WHY: restart is stop + start (or one step) on the server and works on a paused container too. + @Test fun restartEndsRunningAlsoForAPausedContainer() { + assertEquals(ContainerStatus.Running, start.pauseContainer("plex").restartContainer("plex").container("plex").status) + } + @Test fun pauseOnlyPausesARunningContainer() { assertEquals(ContainerStatus.Paused, start.pauseContainer("plex").container("plex").status) assertEquals(ContainerStatus.Exited, start.pauseContainer("jellyfin").container("jellyfin").status) diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ActionResponseTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ActionResponseTest.kt index 4886c78..50cd24e 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ActionResponseTest.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ActionResponseTest.kt @@ -121,6 +121,30 @@ class ActionResponseTest { assertTrue(uses.single().contains("mutation(m).execute().orThrow()")) } + private val unpaused = json("""{"data":{"docker":{"unpause":{"id":"c1","state":"RUNNING"}}}}""") + + // WHY (#345): Docker refuses `start` for a paused container ("try unpause instead"), so Resume + // must send unpause and never start. + @Test fun resumingAPausedContainer_sendsUnpause_neverStart() = runTest { + val engine = ScriptedEngine(listOf(unpaused, started)) + UnraidRepository.startContainer(client(engine), "c1", paused = true) + assertEquals(listOf("UnpauseContainer"), engine.operationNames()) + } + + // WHY: the fix must not turn every Start into unpause: a stopped container still gets start. + @Test fun startingAStoppedContainer_sendsStart_neverUnpause() = runTest { + val engine = ScriptedEngine(listOf(started, unpaused)) + UnraidRepository.startContainer(client(engine), "c1", paused = false) + assertEquals(listOf("StartContainer"), engine.operationNames()) + } + + // WHY: a refused resume (no permission) must reach the user with the server's text, like any action. + @Test fun refusedResume_failsTheActionWithServerText() = runTest { + val e = failureOf { UnraidRepository.startContainer(client(ScriptedEngine(listOf(forbidden))), "c1", paused = true) } + assertNotNull("a refused unpause must fail the action", e) + assertTrue(e!!.message, e.message!!.contains("API key lacks DOCKER:UPDATE_ANY")) + } + @Test fun restart_onSuccess_sendsStopThenStart() = runTest { val engine = ScriptedEngine(listOf(stopped, started)) UnraidRepository.restartContainer(client(engine), "c1", atomic = false) diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/UnraidGatewayTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/UnraidGatewayTest.kt index b690d34..f8d3fcb 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/UnraidGatewayTest.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/UnraidGatewayTest.kt @@ -122,14 +122,17 @@ class UnraidGatewayTest { fun vm(id: String) = demo.current.vms.first { it.id == id } gateway.stopContainer("plex"); assertEquals(ContainerStatus.Exited, container("plex").status) - gateway.startContainer("plex"); assertEquals(ContainerStatus.Running, container("plex").status) + gateway.startContainer("plex", paused = false); assertEquals(ContainerStatus.Running, container("plex").status) // The demo restarts the container in its model whichever way the real server would be asked. gateway.stopContainer("plex"); gateway.restartContainer("plex", atomic = true) assertEquals(ContainerStatus.Running, container("plex").status) gateway.stopContainer("plex"); gateway.restartContainer("plex", atomic = false) assertEquals(ContainerStatus.Running, container("plex").status) gateway.pauseContainer("plex"); assertEquals(ContainerStatus.Paused, container("plex").status) - gateway.startContainer("jellyfin"); assertEquals(ContainerStatus.Running, container("jellyfin").status) + // Resume is `unpause`, and Docker refuses `start` for a paused container: the demo's model does the same (#345). + gateway.startContainer("plex", paused = false); assertEquals(ContainerStatus.Paused, container("plex").status) + gateway.startContainer("plex", paused = true); assertEquals(ContainerStatus.Running, container("plex").status) + gateway.startContainer("jellyfin", paused = false); assertEquals(ContainerStatus.Running, container("jellyfin").status) gateway.updateContainer("grafana") assertEquals(ContainerUpdateStatus.UpToDate, container("grafana").updateStatus) assertEquals(ContainerUpdateStatus.UpdateAvailable, container("nextcloud").updateStatus) From a6e20ae840a03e15849b5957811fcca8f0900b95 Mon Sep 17 00:00:00 2001 From: Thomas Kroll Date: Fri, 13 Nov 2026 21:28:13 +0100 Subject: [PATCH 02/11] fix: never send the API key along a redirect to another host or to plain http The foreground clients followed redirects, and OkHttp keeps the x-api-key header when it does, so a 3xx answer moved the key to whatever Location named: another host, or http after the user entered https. For the WebSocket the handshake was followed and the key then went out in connection_init to the new host. No client that carries the key follows a redirect any more (ADR-0051). A redirect is reported as the new reason Redirected, naming the target origin ("The server redirects to https://... Edit the server and enter that address."), in the tabs, in the Add server sheet's Test and in the action message. It is no connection problem, so the pill does not say Offline. Unraid answers http requests with 302 when SSL is Yes or Strict. Closes #354 Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 8 + README.md | 2 +- .../nova/data/api/ApolloClientFactory.kt | 25 ++- .../nova/data/repository/DomainState.kt | 7 + .../data/repository/ResponseClassifier.kt | 41 +++- .../nova/ui/screens/SnapshotStates.kt | 5 +- .../data/api/BackgroundClientRedirectTest.kt | 15 +- .../nova/data/api/KeyedClientRedirectTest.kt | 199 ++++++++++++++++++ .../nova/data/repository/ErrorReasonTest.kt | 20 ++ .../data/repository/ResponseClassifierTest.kt | 78 +++++++ .../ui/screens/TabFailureRenderingTest.kt | 1 + .../ui/screens/main/ConnectionLabelTest.kt | 5 +- .../0051-no-redirects-for-keyed-requests.md | 47 +++++ docs/adr/README.md | 1 + 14 files changed, 432 insertions(+), 22 deletions(-) create mode 100644 app/src/test/kotlin/io/github/nofuturekid/nova/data/api/KeyedClientRedirectTest.kt create mode 100644 docs/adr/0051-no-redirects-for-keyed-requests.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 203ae27..befdd8c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -73,6 +73,14 @@ release version + date and opens a fresh `[Unreleased]`. every time you open it or come back to it, so the notice is on the first screen. +- **NOVA no longer sends your API key along when a server redirects it** — it + used to follow a redirect and take the key with it, to another address or from + https down to plain http. Now a redirect is not followed: the tab, **Test** + and the action message say "The server redirects to …" and name the address, + and you enter that address in the server's settings. This is what Unraid does + when you type an `http` address while its SSL setting is Yes or Strict: it + points to the `https` address, which is the one to enter (#354). + ## [0.1.48] - 2026-11-13 The Overview now tells you when something on your server needs you, and the Docker tab can search and group containers by Compose project. A new "Needs attention" card at the top of the Overview lists what needs you, most urgent first; on a healthy server it is not there, so a quiet Overview is normal. The Docker tab has a search field with a clear button, and a new "Compose" option for the Docker view (Settings, Layout) groups containers by their Compose project. The 0.1.48 beta confirmed the search, the Compose option and the quiet Overview on a real phone. Some groundwork in this release has no visible change yet (detecting the server's API version and what the API key may do, and the rules for later opt-in alerts). As in 0.1.47, NOVA does not install updates itself: "Download" opens the release file in your browser. diff --git a/README.md b/README.md index 0f5eb66..d253191 100644 --- a/README.md +++ b/README.md @@ -82,7 +82,7 @@ A few things bend to taste in **Settings**: 2. On your Unraid server, generate an **API key**: web UI → _Settings → Management Access → API / Connect_ (which rights it needs: [API key permissions](#api-key-permissions)). 3. Open the app → **Add server** and fill in: - **Server name** — a label, e.g. `Tower` - - **Local host** — its address on your home network, e.g. `192.168.1.10`. Flip **Use SSL (HTTPS)** if the server uses HTTPS; for a self-signed certificate also enable **Trust self-signed certificate** and confirm it once + - **Local host** — its address on your home network, e.g. `192.168.1.10`. Flip **Use SSL (HTTPS)** if the server uses HTTPS; for a self-signed certificate also enable **Trust self-signed certificate** and confirm it once. If your server's _Use SSL/TLS_ setting is _Yes_ or _Strict_, it answers a plain `http` request with a redirect to `https`; NOVA does not follow redirects (the API key would travel with it), so enter the address it names, with **Use SSL (HTTPS)** on. A tab or **Test** shows it as "The server redirects to …" - **Remote host (Unraid Connect)** — optional, e.g. `your-server.unraid.net`, for when you're away (with its own **Use SSL (HTTPS)** switch) - **API Key** — the one you just generated 4. Tap **Test** (next to the local and/or remote connection), then **Save**. The pill in the top bar flips between **Local** and **Remote**. diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/data/api/ApolloClientFactory.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/data/api/ApolloClientFactory.kt index e48ce76..5160d54 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/data/api/ApolloClientFactory.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/data/api/ApolloClientFactory.kt @@ -14,7 +14,11 @@ import javax.inject.Inject import javax.inject.Singleton /** - * Builds per-server [ApolloClient] instances. Four variants: + * Builds per-server [ApolloClient] instances. Four variants. None of them follows a redirect + * (ADR-0051): every client here sends the API key, and OkHttp would send it on to whatever a 3xx + * answer's `Location` names, another host or plain http. A redirect comes back as the response + * (an `ApolloHttpException` with the status and the `Location` header) and is reported as + * [io.github.nofuturekid.nova.data.repository.ErrorReason.Redirected]. * * - [build] — short timeouts (8 s connect, 15 s read/write). Used for * polling queries and short-lived mutations (start/stop/pause/etc.). @@ -28,9 +32,9 @@ import javax.inject.Singleton * Per ADR-0016 these get their own client so the polling timeout * doesn't have to be relaxed globally. * - * - [buildBackground] — the polling client for the background alert check: no redirect is - * followed and no cleartext connection is made, so the API key stays on the https address it - * was sent to. Only the background check uses it; the foreground is unchanged. + * - [buildBackground] — the polling client for the background alert check: like the others it + * follows no redirect, and on top of that no cleartext connection is made, so the API key stays + * on the https address it was sent to. Only the background check uses it. * * - [buildWs] — WebSocket-only client for GraphQL subscriptions. Reuses * the existing self-signed TLS pin (ADR-0041) via [applyTrust]. Uses @@ -50,7 +54,7 @@ open class ApolloClientFactory @Inject constructor() { const val WS_PING_INTERVAL_S = 15L } - private val baseHttpClient: OkHttpClient by lazy { + internal val baseHttpClient: OkHttpClient by lazy { val logging = HttpLoggingInterceptor().apply { level = if (io.github.nofuturekid.nova.BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BASIC @@ -62,10 +66,12 @@ open class ApolloClientFactory @Inject constructor() { .readTimeout(15, TimeUnit.SECONDS) .writeTimeout(15, TimeUnit.SECONDS) .addInterceptor(logging) + .followRedirects(false) + .followSslRedirects(false) .build() } - private val longRunningHttpClient: OkHttpClient by lazy { + internal val longRunningHttpClient: OkHttpClient by lazy { val logging = HttpLoggingInterceptor().apply { level = if (io.github.nofuturekid.nova.BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BASIC @@ -77,6 +83,8 @@ open class ApolloClientFactory @Inject constructor() { .readTimeout(10, TimeUnit.MINUTES) .writeTimeout(10, TimeUnit.MINUTES) .addInterceptor(logging) + .followRedirects(false) + .followSslRedirects(false) .build() } @@ -115,8 +123,9 @@ open class ApolloClientFactory @Inject constructor() { open fun build(baseUrl: String, apiKey: String, trust: TlsTrust = TlsTrust.Default): ApolloClient = cached("short", baseHttpClient, baseUrl, apiKey, trust) - /** Same as [build] but for the background alert check ([backgroundHttpClient]): https only, - * no redirect is followed. The foreground variants are not affected. */ + /** Same as [build] but for the background alert check ([backgroundHttpClient]): https only. + * Like every client here it follows no redirect; the background client states that itself + * so it does not depend on the base client. */ fun buildBackground(baseUrl: String, apiKey: String, trust: TlsTrust = TlsTrust.Default): ApolloClient = cached("bg", backgroundHttpClient, baseUrl, apiKey, trust) diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/DomainState.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/DomainState.kt index 985f659..3070f1b 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/DomainState.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/DomainState.kt @@ -64,6 +64,13 @@ enum class ErrorReason { /** The server is fine but the service behind this domain (Docker, VM manager) is turned off. */ ServiceOff, + /** + * The server answered with a redirect (3xx). The app does not follow it, because the API key + * would go with it (ADR-0051); the message names where it points so the user can enter that + * address. The server is reachable, so this is not a [isConnectionProblem]. + */ + Redirected, + /** Any other error the server reported; its own text is shown. */ ServerError, ; diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/ResponseClassifier.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/ResponseClassifier.kt index d8c4a9a..c0294a3 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/ResponseClassifier.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/ResponseClassifier.kt @@ -8,6 +8,7 @@ import com.apollographql.apollo.exception.ApolloHttpException import com.apollographql.apollo.exception.ApolloNetworkException import io.github.nofuturekid.nova.data.api.CertIssue import io.github.nofuturekid.nova.data.api.certIssue +import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import java.io.InterruptedIOException import java.net.SocketException import java.net.UnknownHostException @@ -42,7 +43,8 @@ fun classifyResponse( ): RespClass = when { exception != null -> { val issue = exception.certIssue() - if (issue != null) RespClass.Cert(issue) else RespClass.Failed(exception.failureMessage("Network error")) + if (issue != null) RespClass.Cert(issue) + else RespClass.Failed(exception.redirectMessage() ?: exception.failureMessage("Network error")) } hasErrors -> RespClass.Failed(errorMessage ?: "Unknown GraphQL error") dataIsNull -> RespClass.Empty @@ -52,7 +54,8 @@ fun classifyResponse( /** * Why a domain query failed, by the response it got. The first matching rule wins * (the bodies behind them were recorded from Unraid 7.4.0, API 4.37.11): - * 1. a transport exception: [ErrorReason.Unreachable]; + * 1. a transport exception: [ErrorReason.Unreachable], or [ErrorReason.Redirected] when the + * server answered with a redirect, which the clients do not follow (ADR-0051); * 2. `UNAUTHENTICATED`: [ErrorReason.KeyRejected]; * 3. `GRAPHQL_VALIDATION_FAILED` or "Cannot query field": [ErrorReason.ApiTooOld]; * 4. `FORBIDDEN`: [ErrorReason.Forbidden]; @@ -62,7 +65,9 @@ fun classifyResponse( * cannot disagree about what an `errors` array means. */ fun classifyErrorReason(exception: ApolloException?, errors: List?): ErrorReason { - if (exception != null) return ErrorReason.Unreachable + if (exception != null) { + return if (exception.redirectMessage() != null) ErrorReason.Redirected else ErrorReason.Unreachable + } val list = errors.orEmpty() return when (classifyErrors(list)) { ErrorClass.KeyRejected -> ErrorReason.KeyRejected @@ -92,6 +97,30 @@ fun graphQlError(message: String, errors: List?): DomainState.Error { /** What Unraid's resolvers throw when the service behind a domain is off (Docker: missing socket; VMs: no hypervisor). */ private val SERVICE_OFF_MARKERS = listOf("Docker socket unavailable", "VMs are not available") +/** The statuses OkHttp follows by default; the clients here follow none of them (ADR-0051). */ +private val REDIRECT_STATUSES = setOf(300, 301, 302, 303, 307, 308) + +/** + * The sentence for a server that answered with a redirect, or null when this failure is not one. + * The clients do not follow redirects (the API key would go with them, ADR-0051), so a 3xx + * arrives here as an [ApolloHttpException] with its `Location` header. The target is shown as + * `scheme://host[:port]` only: the path says nothing the user can act on, a query may carry + * tokens, and `user:password@` must never be echoed. A missing, relative or unparsable + * `Location` gets the same advice without a target. + */ +fun ApolloException.redirectMessage(): String? { + if (this !is ApolloHttpException || statusCode !in REDIRECT_STATUSES) return null + val location = headers.firstOrNull { it.name.equals("Location", ignoreCase = true) }?.value + val target = location?.trim()?.toHttpUrlOrNull()?.newBuilder() + ?.username("")?.password("")?.encodedPath("/")?.query(null)?.fragment(null) + ?.build()?.toString()?.removeSuffix("/") + return if (target != null) { + "The server redirects to $target. Edit the server and enter that address." + } else { + "The server redirects to another address, but doesn't say which. Check the address in this server's settings." + } +} + /** * The text to show for a failed request: the exception's own message plus its * innermost cause. Apollo reports any parsing failure as "Error while reading @@ -145,6 +174,9 @@ private const val MAX_CAUSE_DEPTH = 10 */ fun Throwable.toQueryError(fallback: String): DomainState.Error { val text = failureMessage(fallback) + (this as? ApolloException)?.redirectMessage()?.let { + return DomainState.Error(it, detail = text, reason = ErrorReason.Redirected) + } return if (isServerUnreachable()) DomainState.Error(UNREACHABLE_MESSAGE, detail = text) else DomainState.Error(text) } @@ -167,7 +199,8 @@ fun checkActionResponse(exception: ApolloException?, hasErrors: Boolean, errorMe is RespClass.Failed -> throw ActionFailedException( when (exception) { // Plain wording for the snackbar; the technical cause stays on the exception. - is ApolloHttpException -> "the server answered HTTP ${exception.statusCode}" + is ApolloHttpException -> exception.redirectMessage()?.replaceFirstChar { it.lowercase() } + ?: "the server answered HTTP ${exception.statusCode}" is ApolloNetworkException -> "can't reach the server" else -> c.message }, diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/SnapshotStates.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/SnapshotStates.kt index 4534944..b13de89 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/SnapshotStates.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/SnapshotStates.kt @@ -60,7 +60,8 @@ data class ErrorTexts(val title: String, val body: String) /** * The texts for [reason]. Pure, so a test can pin every wording. [message] is the * server's own text and the body only for [ErrorReason.Unreachable] and - * [ErrorReason.ServerError]; the other reasons explain what to do instead. + * [ErrorReason.ServerError] (for [ErrorReason.Redirected] it is the app's own sentence naming the + * target); the other reasons explain what to do instead. * [subject] is null where a screen has none (generic wording). */ fun errorTexts(reason: ErrorReason, subject: ErrorSubject?, message: String): ErrorTexts = when (reason) { @@ -90,6 +91,8 @@ fun errorTexts(reason: ErrorReason, subject: ErrorSubject?, message: String): Er // Only Docker and VMs can be switched off; anything else is the server's own error. else -> ErrorTexts("The server couldn't load ${subject?.noun ?: "this"}", message) } + // [message] names the target ("The server redirects to https://...") and is already the advice. + ErrorReason.Redirected -> ErrorTexts("The address needs to change", message) ErrorReason.ServerError -> ErrorTexts("The server couldn't load ${subject?.noun ?: "this"}", message) } diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/data/api/BackgroundClientRedirectTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/data/api/BackgroundClientRedirectTest.kt index 15d3771..b9e6fbd 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/data/api/BackgroundClientRedirectTest.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/data/api/BackgroundClientRedirectTest.kt @@ -19,8 +19,9 @@ import java.util.concurrent.CopyOnWriteArrayList * WHY: OkHttp follows redirects by default and strips only `Authorization` on the way, so a 3xx * answer would send the `x-api-key` header, and on 307/308 the POST body too, to whatever * `Location` says: another host, or http. In the background nobody is looking, so a verified - * https peer, or a proxy in front of it, must not be able to move the key anywhere. The - * foreground client is deliberately left as it is; a guard test pins that down. + * https peer, or a proxy in front of it, must not be able to move the key anywhere. The foreground + * clients follow no redirect either since ADR-0051 ([KeyedClientRedirectTest]); the background + * client states it itself, so these tests pin it independently of the base client. */ class BackgroundClientRedirectTest { private val servers = mutableListOf() @@ -93,15 +94,15 @@ class BackgroundClientRedirectTest { assertEquals("nothing reached the http server", emptyList(), plain.seenKeys.toList()) } - @Test fun the_foreground_client_still_follows_redirects() { - // WHY: the foreground behaviour of the app is deliberately unchanged; this guard fails if - // the redirect and cleartext settings ever leak from the background variant into build(). + @Test fun the_foreground_client_does_not_follow_redirects_either_but_keeps_cleartext() { + // WHY: ADR-0051 stopped the foreground redirects; what must stay is the background-only cleartext + // block: a user with an http-only server (SSL off) still connects in the foreground. val elsewhere = peer(200) val redirecting = peer(307, location = "${elsewhere.url}/graphql") exception(ApolloClientFactory().build(redirecting.url, "secret")) - assertEquals(listOf("secret"), redirecting.seenKeys.toList()) - assertEquals("the foreground follows the redirect, as before", listOf("secret"), elsewhere.seenKeys.toList()) + assertEquals("http is still allowed in the foreground", listOf("secret"), redirecting.seenKeys.toList()) + assertEquals("no redirect is followed", emptyList(), elsewhere.seenKeys.toList()) } } diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/data/api/KeyedClientRedirectTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/data/api/KeyedClientRedirectTest.kt new file mode 100644 index 0000000..e92db7e --- /dev/null +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/data/api/KeyedClientRedirectTest.kt @@ -0,0 +1,199 @@ +package io.github.nofuturekid.nova.data.api + +import com.apollographql.apollo.ApolloClient +import com.apollographql.apollo.exception.ApolloHttpException +import com.sun.net.httpserver.HttpServer +import io.github.nofuturekid.nova.data.repository.ErrorReason +import io.github.nofuturekid.nova.data.repository.toQueryError +import io.github.nofuturekid.nova.graphql.DockerContainerStatsSubscription +import io.github.nofuturekid.nova.graphql.GetArrayQuery +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeoutOrNull +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import java.io.IOException +import java.net.InetAddress +import java.net.InetSocketAddress +import java.net.ServerSocket +import java.net.Socket +import java.security.MessageDigest +import java.util.Base64 +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.atomic.AtomicInteger +import kotlin.concurrent.thread + +/** + * WHY (ADR-0051): every client that carries the API key must keep it on the address the user + * entered. OkHttp follows redirects by default and strips only `Authorization`, so a 3xx answer + * (from a server, or a proxy or hijacked DNS in front of it) used to move the `x-api-key` header to + * whatever `Location` named: another host, or plain http. The WebSocket client is the same case in + * a worse form: after a followed handshake the key goes out in `connection_init` to the new host. + * Unraid itself answers http requests with `302` when SSL is Yes or Strict, so the redirect must + * also arrive as a reason the user can act on, not as a silent failure. + */ +class KeyedClientRedirectTest { + private val servers = mutableListOf() + private val wsPeers = mutableListOf() + + @After fun stop() { + servers.forEach { it.stop(0) } + wsPeers.forEach { it.close() } + } + + /** Records the x-api-key header of every request it gets; answers with [status] and [location]. */ + private class Peer(val server: HttpServer, val seenKeys: CopyOnWriteArrayList) { + val url get() = "http://127.0.0.1:${server.address.port}" + } + + private fun peer(status: Int, location: String? = null): Peer { + val seen = CopyOnWriteArrayList() + val http = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0) + http.createContext("/graphql") { exchange -> + seen += exchange.requestHeaders.getFirst("x-api-key") ?: "(none)" + exchange.requestBody.readBytes() + location?.let { exchange.responseHeaders.add("Location", it) } + val body = if (status == 200) """{"data":null}""".toByteArray() else ByteArray(0) + exchange.responseHeaders.add("Content-Type", "application/json") + exchange.sendResponseHeaders(status, if (body.isEmpty()) -1 else body.size.toLong()) + exchange.responseBody.use { it.write(body) } + } + http.start() + servers += http + return Peer(http, seen) + } + + /** + * A minimal WebSocket server: accepts the upgrade and records the text frames the client sends + * (the `graphql-ws` `connection_init` carries the API key). It answers nothing else. + */ + private class WsPeer : AutoCloseable { + private val socket = ServerSocket(0, 10, InetAddress.getByName("127.0.0.1")) + val port get() = socket.localPort + val connections = AtomicInteger() + val frames = CopyOnWriteArrayList() + + init { + thread(isDaemon = true) { + try { + while (true) { + val client = socket.accept() + connections.incrementAndGet() + thread(isDaemon = true) { serve(client) } + } + } catch (_: IOException) { /* closed */ } + } + } + + private fun serve(client: Socket) = try { + client.use { + it.soTimeout = 5_000 + val input = it.getInputStream().buffered() + val head = StringBuilder() + while (!head.endsWith("\r\n\r\n")) { + val b = input.read() + if (b < 0) return@use + head.append(b.toChar()) + } + val key = Regex("(?im)^Sec-WebSocket-Key: (.+)$").find(head)?.groupValues?.get(1)?.trim() ?: return@use + val protocol = Regex("(?im)^Sec-WebSocket-Protocol: (.+)$").find(head)?.groupValues?.get(1)?.trim() + val accept = Base64.getEncoder().encodeToString( + MessageDigest.getInstance("SHA-1").digest((key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").toByteArray()), + ) + val reply = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" + + "Sec-WebSocket-Accept: $accept\r\n" + + (protocol?.let { p -> "Sec-WebSocket-Protocol: ${p.substringBefore(',').trim()}\r\n" } ?: "") + "\r\n" + it.getOutputStream().apply { write(reply.toByteArray()); flush() } + while (true) { + val b0 = input.read() + if (b0 < 0) break + var len = input.read() and 0x7f + if (len == 126) len = (input.read() shl 8) or input.read() + val mask = ByteArray(4).also { m -> input.readNBytes(m, 0, 4) } + val payload = ByteArray(len).also { p -> input.readNBytes(p, 0, len) } + for (i in payload.indices) payload[i] = (payload[i].toInt() xor mask[i % 4].toInt()).toByte() + if (b0 and 0x0f == 1) frames += String(payload) + } + } + } catch (_: IOException) { /* peer went away or timed out */ } + + override fun close() = socket.close() + } + + private val variants: Map ApolloClient> = mapOf( + "build" to { factory, url -> factory.build(url, "secret") }, + "buildLongRunning" to { factory, url -> factory.buildLongRunning(url, "secret") }, + ) + + private fun failure(client: ApolloClient) = runBlocking { client.query(GetArrayQuery()).execute().exception } + + @Test fun the_key_never_reaches_a_second_host_through_a_redirect() { + // 302 is what Unraid's nginx sends; 303/307/308 are the other statuses OkHttp would follow. + for ((name, build) in variants) for (status in listOf(301, 302, 303, 307, 308)) { + val elsewhere = peer(200) + val redirecting = peer(status, location = "${elsewhere.url}/graphql") + + val failure = failure(build(ApolloClientFactory(), redirecting.url)) + + assertEquals("$name $status: the address the user entered was asked", listOf("secret"), redirecting.seenKeys.toList()) + assertEquals("$name $status: nothing reached the redirect target", emptyList(), elsewhere.seenKeys.toList()) + assertTrue("$name $status: a 3xx is a failure, got $failure", failure is ApolloHttpException && failure.statusCode == status) + } + } + + // WHY: a redirect that is not followed is the answer the tab gets; it must reach the user as its own + // reason that names the target. It is no outage: the pill must not say Offline (isConnectionProblem). + @Test fun a_redirect_reaches_the_user_as_its_own_reason_with_the_target() { + val elsewhere = peer(200) + val redirecting = peer(302, location = "${elsewhere.url}/graphql") + + val error = failure(ApolloClientFactory().build(redirecting.url, "secret"))!!.toQueryError("Network error") + + assertEquals(ErrorReason.Redirected, error.reason) + assertTrue(error.message, error.message.contains("The server redirects to ${elsewhere.url}.")) + assertFalse(error.reason.isConnectionProblem) + } + + // WHY: nothing may change for the many servers that do not redirect. + @Test fun a_server_that_does_not_redirect_is_used_as_before() { + for ((name, build) in variants) { + val plain = peer(200) + + val failure = failure(build(ApolloClientFactory(), plain.url)) + + assertEquals(name, listOf("secret"), plain.seenKeys.toList()) + assertFalse("$name: an answer is no failure of the transport, got $failure", failure is ApolloHttpException) + } + } + + // WHY: the downgrade from https to http cannot be staged without a TLS peer; the two switches that + // forbid it (followRedirects covers every redirect, followSslRedirects the scheme change) are pinned. + @Test fun the_clients_are_configured_to_follow_no_redirect_at_all() { + val factory = ApolloClientFactory() + for ((name, client) in listOf("short" to factory.baseHttpClient, "long" to factory.longRunningHttpClient, "background" to factory.backgroundHttpClient)) { + assertFalse("$name followRedirects", client.followRedirects) + assertFalse("$name followSslRedirects", client.followSslRedirects) + } + } + + // WHY: the WebSocket sends the key in `connection_init` AFTER the handshake. A followed handshake + // redirect would complete on the second host and hand it the key; not following ends it at the 302. + @Test fun the_websocket_handshake_does_not_follow_a_redirect() { + val elsewhere = WsPeer().also { wsPeers += it } + val redirecting = peer(302, location = "http://127.0.0.1:${elsewhere.port}/graphql") + + val client = ApolloClientFactory().buildWs(redirecting.url, "secret") + runBlocking { + withTimeoutOrNull(4_000) { + try { client.subscription(DockerContainerStatsSubscription()).toFlow().first() } catch (_: Exception) { null } + } + } + + assertTrue("the address the user entered was asked", redirecting.seenKeys.isNotEmpty()) + assertEquals("no connection to the redirect target", 0, elsewhere.connections.get()) + assertEquals("the key was not sent there", emptyList(), elsewhere.frames.toList()) + } +} diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ErrorReasonTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ErrorReasonTest.kt index b95ff7d..4939b1e 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ErrorReasonTest.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ErrorReasonTest.kt @@ -56,6 +56,9 @@ class ErrorReasonTest { """{"errors":[{"message":"boom","extensions":{"code":"INTERNAL_SERVER_ERROR"}}],"data":{"docker":null}}""", ) private val unreachable: () -> HttpResponse = { throw IOException("connection refused") } + private fun redirect(status: Int, location: String?): () -> HttpResponse = { + HttpResponse.Builder(status).apply { if (location != null) addHeader("Location", location) }.build() + } /** Runs the VMs query like the poll does and classifies what comes back. */ private suspend fun reasonOf(server: () -> HttpResponse): ErrorReason { @@ -99,6 +102,23 @@ class ErrorReasonTest { assertEquals(ErrorReason.Unreachable, reasonOf(unreachable)) } + // WHY: the clients no longer follow a redirect (ADR-0051), so a 3xx is the answer the tab gets. It must + // not read as an outage ("Can't reach the server" and an Offline pill): the server answered, and the fix + // is the address in the server's settings. Unraid answers http requests with 302 when SSL is Yes or Strict. + @Test fun redirect_isRedirected_notUnreachable() = runTest { + listOf(301, 302, 303, 307, 308).forEach { status -> + assertEquals("$status", ErrorReason.Redirected, reasonOf(redirect(status, "https://tower.example.net/graphql"))) + } + assertEquals("no Location header", ErrorReason.Redirected, reasonOf(redirect(302, null))) + } + + // WHY: 304 and 4xx/5xx are no redirects; only a status the client would have followed gets the reason. + @Test fun otherHttpStatuses_areNotRedirected() = runTest { + listOf(304, 404, 500).forEach { status -> + assertEquals("$status", ErrorReason.Unreachable, reasonOf(redirect(status, "https://tower.example.net/"))) + } + } + // WHY: rule order. A response that carries both a key refusal and a service message is about the key. @Test fun firstMatchingRuleWins() { val both = listOf( diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ResponseClassifierTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ResponseClassifierTest.kt index 15acdde..ed8bea3 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ResponseClassifierTest.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ResponseClassifierTest.kt @@ -1,5 +1,6 @@ package io.github.nofuturekid.nova.data.repository +import com.apollographql.apollo.api.http.HttpHeader import com.apollographql.apollo.exception.ApolloHttpException import com.apollographql.apollo.exception.ApolloNetworkException import io.github.nofuturekid.nova.data.api.CertIssue @@ -7,6 +8,9 @@ import io.github.nofuturekid.nova.data.api.CertificateChangedException import io.github.nofuturekid.nova.data.api.CertificateUntrustedException import org.junit.Assert.assertEquals import org.junit.Assert.assertNull +import org.junit.Assert.assertFalse +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue import org.junit.Test import java.io.IOException @@ -158,4 +162,78 @@ class ResponseClassifierTest { assertEquals("Error while reading JSON response (EOFException: End of input at path $.data)", err.message) assertNull(err.detail) } + + private fun redirect(status: Int, location: String?, name: String = "Location") = ApolloHttpException( + status, listOfNotNull(location?.let { HttpHeader(name, it) }), null, "HTTP error $status", null, + ) + + // WHY: a redirect is what Unraid sends to an http request when SSL is Yes or Strict (nginx `return 302`). + // The user must be told where it points, as the address to enter; the message names the target and + // the advice, and stays out of the "Offline" class of failures. + @Test fun redirect_namesTheTargetAndTheAdvice() { + val err = redirect(302, "https://192-168-1-100.abc123.myunraid.net:8443/graphql?x=1").toQueryError("Network error") + assertEquals(ErrorReason.Redirected, err.reason) + assertEquals( + "The server redirects to https://192-168-1-100.abc123.myunraid.net:8443. Edit the server and enter that address.", + err.message, + ) + assertEquals("the raw text stays behind Show details", "HTTP error 302", err.detail) + assertFalse("a redirect must not turn the pill to Offline", err.reason.isConnectionProblem) + } + + // WHY: only the origin is shown. A path says nothing the user can act on, a query can carry tokens, and a + // Location with user:password@ must never be echoed onto the screen. + @Test fun redirect_showsOnlySchemeHostAndNonDefaultPort() { + assertEquals( + "The server redirects to https://tower.example.net. Edit the server and enter that address.", + redirect(302, "https://tower.example.net:443/graphql").redirectMessage(), + ) + assertEquals( + "The server redirects to http://[::1]:8080. Edit the server and enter that address.", + redirect(307, "http://[::1]:8080/a?token=secret#frag").redirectMessage(), + ) + val withCredentials = redirect(308, "https://admin:hunter2@tower.example.net/graphql").redirectMessage()!! + assertTrue(withCredentials, !withCredentials.contains("hunter2") && !withCredentials.contains("admin")) + assertTrue(withCredentials, withCredentials.contains("https://tower.example.net.")) + } + + // WHY: a redirect without a usable target still must be a redirect (not "HTTP error 302"), and the text + // must not invent a host. The header name is case-insensitive in HTTP. + @Test fun redirect_withoutUsableTarget_saysSoWithoutInventingOne() { + val unknown = "The server redirects to another address, but doesn't say which. Check the address in this server's settings." + assertEquals(unknown, redirect(302, null).redirectMessage()) + assertEquals("relative", unknown, redirect(302, "/login").redirectMessage()) + assertEquals("not http", unknown, redirect(302, "javascript:alert(1)").redirectMessage()) + assertEquals( + "The server redirects to https://tower.example.net. Edit the server and enter that address.", + redirect(302, "https://tower.example.net/", name = "location").redirectMessage(), + ) + } + + // WHY: only the statuses OkHttp used to follow are redirects; a 304 or an error is not. + @Test fun otherStatuses_areNotRedirects() { + listOf(200, 304, 400, 401, 404, 500).forEach { + assertNull("$it", redirect(it, "https://tower.example.net/").redirectMessage()) + } + assertNull(ApolloNetworkException("down").redirectMessage()) + assertEquals(ErrorReason.Unreachable, redirect(404, null).toQueryError("Network error").reason) + } + + // WHY: the Add server sheet's Test shows the classifier's message, so Test and the tabs say the same. + @Test fun redirect_isTheTestConnectionMessage() { + val c = classifyResponse(redirect(302, "https://tower.example.net/"), hasErrors = false, errorMessage = null, dataIsNull = true) + assertEquals( + RespClass.Failed("The server redirects to https://tower.example.net. Edit the server and enter that address."), + c, + ) + } + + // WHY: an action (start a container) that meets a redirect did not run; the snackbar says why instead of + // "the server answered HTTP 302". + @Test fun redirect_failsAnAction_withTheTarget() { + val e = assertThrows(ActionFailedException::class.java) { + checkActionResponse(redirect(307, "https://tower.example.net/graphql"), hasErrors = false, errorMessage = null) + } + assertEquals("the server redirects to https://tower.example.net. Edit the server and enter that address.", e.message) + } } diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/TabFailureRenderingTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/TabFailureRenderingTest.kt index ee6460f..0f5339d 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/TabFailureRenderingTest.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/TabFailureRenderingTest.kt @@ -82,6 +82,7 @@ class TabFailureRenderingTest { ErrorReason.Forbidden to "This API key can't read containers", ErrorReason.ApiTooOld to "This server's Unraid API is too old", ErrorReason.ServiceOff to "Docker is turned off", + ErrorReason.Redirected to "The address needs to change", ErrorReason.ServerError to "The server couldn't load containers", ) assertTrue("one case per reason", titles.keys == ErrorReason.entries.toSet()) diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/main/ConnectionLabelTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/main/ConnectionLabelTest.kt index d6b1cc4..e484047 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/main/ConnectionLabelTest.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/main/ConnectionLabelTest.kt @@ -41,8 +41,11 @@ class ConnectionLabelTest { } // WHY: the same holds when nothing else has loaded yet, and for every reason that is not about the connection. + // A redirect is one of them: the server answered, so "Offline" would send the user to the network. @Test fun failuresThatAreNotTheConnection_leaveThePillAlone() { - listOf(ErrorReason.Forbidden, ErrorReason.ApiTooOld, ErrorReason.ServiceOff, ErrorReason.ServerError).forEach { + listOf( + ErrorReason.Forbidden, ErrorReason.ApiTooOld, ErrorReason.ServiceOff, ErrorReason.Redirected, ErrorReason.ServerError, + ).forEach { assertEquals("$it", "Local", connectionLabel(DomainState.Error("x", reason = it), ConnectionMode.Local)) } } diff --git a/docs/adr/0051-no-redirects-for-keyed-requests.md b/docs/adr/0051-no-redirects-for-keyed-requests.md new file mode 100644 index 0000000..58564bf --- /dev/null +++ b/docs/adr/0051-no-redirects-for-keyed-requests.md @@ -0,0 +1,47 @@ +# ADR-0051: Never follow a redirect with the API key + +- **Status**: Accepted (2026-11-13) +- **Date**: 2026-11-13 +- **Tags**: security, data, ui + +## Context + +Every request NOVA sends to an Unraid server carries the API key: the `x-api-key` header of the HTTP clients (`ApolloClientFactory.build` and `buildLongRunning`, added by an application interceptor) and the `connection_init` payload of the WebSocket client (`buildWs`), which is sent after the handshake. The background client (`buildBackground`, ADR-0048) already follows no redirect. The three foreground clients kept OkHttp's defaults (`followRedirects` and `followSslRedirects` both true). OkHttp strips only `Authorization` when it follows a redirect to another host, so a 3xx answer re-sent the key to whatever `Location` named: another host, or plain http after the user entered https. For the WebSocket the handshake itself was followed, so the second host completed it and then received the key. `KeyedClientRedirectTest` shows this on the unchanged clients: the key reaches a second server and the WebSocket peer gets a connection (four of its five tests fail without the change). + +What real Unraid servers send (read from `unraid/webgui`, `etc/rc.d/rc.nginx` at commit `99e39027fb` of 2026-11-13; the same lines are in the fixture of `unraid/api`): + +- SSL setting **No**: no redirect. +- SSL **Yes**: a server block on the http port answers every request with `return 302 https://$host:$PORTSSL$request_uri;` (`redirect host`). Same host name, https, port always spelled out. +- SSL **Strict** (`USE_SSL=auto`, with a myunraid.net certificate): `return 302 https://$(fqdn $ADDR)$PORTSSL_URL$request_uri;` (`redirect fqdn`), the host name being `lan-ip.hash.myunraid.net`. A different host name from the one the user typed, even for `http://192.168.1.100` or `http://tower.local`. A Tailscale name gets the same kind of `302` to its own https name. +- All of these are `302`, at server level, so they answer `POST /graphql` too. The `location /graphql` block itself has no redirect; the API answers on a unix socket behind nginx. +- OkHttp turns a followed `301`/`302`/`303` POST into a GET without a body (`RetryAndFollowUpInterceptor`; read from its documented behaviour, not run here), so following Unraid's own redirect could never have produced a working query: the user got a failure on the redirected GET, with no explanation. + +So the realistic case is a user who typed an http address or a bare IP; the redirect is the server telling them the address to use. + +## Decision + +**No client that carries the API key follows a redirect. A redirect becomes a failure reason of its own that names the target.** + +1. **Rule.** The key is never sent to a host other than the one the user entered, and never over http when the user entered https. The simplest way to guarantee both is that no redirect is followed at all: `followRedirects(false)` and `followSslRedirects(false)` on the base and the long-running client; the WebSocket client is derived from the base client and inherits them, which ends the handshake at the 3xx. The background client keeps its own explicit settings. +2. **Not "follow same-host http-to-https upgrades".** That was the alternative. It would not help: the first request already sent the key over http, to the host the user entered, before the redirect; Unraid's redirect is a 302 that OkHttp would turn into a body-less GET; and following needs a custom interceptor that re-sends the POST and compares hosts, which is more code to get wrong in the code path that guards the key. Telling the user the address to enter costs one sentence and fixes the next request too. +3. **Reason.** `ErrorReason.Redirected` (not a connection problem, so the top-bar pill does not say Offline: the server answered). `ApolloException.redirectMessage()` in `ResponseClassifier.kt` recognises the statuses OkHttp followed (300, 301, 302, 303, 307, 308) and builds `The server redirects to . Edit the server and enter that address.` from the `Location` header. Only the origin is shown: the path is of no use to the user, a query can carry tokens, and `user:password@` is dropped. A missing, relative or non-http `Location` gets the same advice without a target. Tabs show it as "The address needs to change" with that sentence; `DomainState.Error.detail` keeps the raw text. +4. **One text everywhere.** `classifyResponse` returns the sentence for a redirect, so the Add server sheet's **Test** (`testConnection`) shows it without a change of its own, and `checkActionResponse` gives it (lower-cased) to the snackbar of a failed action. `classifyErrorReason` and `toQueryError` give tabs the reason. The WebSocket streams keep their generic error text; the polling tabs and **Test** carry the reason. +5. **Unchanged.** A server that does not redirect, http-only servers (SSL No) and the background check behave as before; certificate handling is not touched. + +## Consequences + +- **Positive.** The key cannot be moved by a redirect, whoever sends it (a misconfigured proxy, a changed DNS answer, a captive portal). A user who typed the wrong scheme is told the address instead of seeing an unexplained failure. +- **Negative / trade-offs.** A setup that relied on NOVA following a redirect (a reverse proxy that redirects `/graphql` to another path or host) now fails with the new message and has to be entered at its final address. Unraid's own redirects never worked for POST queries, so no working setup of that kind is known. An http-to-https redirect cannot be followed even when it is harmless; the user enters the https address once. +- **Not covered.** The https-to-http direction cannot be staged in a unit test without a TLS peer; a test pins the two OkHttp switches instead. Certificate handling and the first request over plain http (the user's own choice) are unchanged. +- **Trigger to revisit.** If a real, common Unraid or proxy setup answers the GraphQL POST with a redirect that must be followed (for example a `308` from a documented proxy), follow only a same-host, same-or-upgrading-scheme `307`/`308` in an interceptor that drops the key for any other target. + +## Alternatives considered + +- **Follow only same-host http-to-https upgrades.** Rejected in decision 2. +- **Keep following and strip `x-api-key` on a host or scheme change** (an OkHttp network interceptor). It keeps OkHttp's redirect logic and drops the key, but the follow-up request then fails as unauthenticated with a misleading "key rejected", and the first hop still leaked. +- **Do nothing for the WebSocket.** Rejected: the handshake redirect is the worse leak because the key follows in the payload. + +## References + +- Issue hellwand/nova#354; ADR-0048 (the background client that started this), ADR-0041 (host and SSL entry), ADR-0042 (WebSocket transport), ADR-0047. +- Upstream: `unraid/webgui` `etc/rc.d/rc.nginx` (`redirect()` at the top, the `USE_SSL` branches in `build_servers`, `location /graphql` in `build_locations`). diff --git a/docs/adr/README.md b/docs/adr/README.md index 150491f..a65f1de 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -85,3 +85,4 @@ ADRs live under `docs/` so the CI docs-only bypass applies — pure-ADR PRs comp | [0048](./0048-opt-in-background-alert-checks.md) | Opt-in background alert checks (amends ADR-0017) | Accepted | | [0049](./0049-google-play-third-distribution-channel.md) | Google Play as a third distribution channel | Accepted | | [0050](./0050-demo-mode.md) | A demo mode with fictional data | Proposed | +| [0051](./0051-no-redirects-for-keyed-requests.md) | Never follow a redirect with the API key | Accepted | From 48952d13684332b042612f16ee98e46f8e60bb2f Mon Sep 17 00:00:00 2001 From: Thomas Kroll Date: Fri, 13 Nov 2026 20:57:16 +0100 Subject: [PATCH 03/11] feat: hide controls the API key cannot use A key without the permission for an action no longer gets the button for it. The Docker, VMs and Array tabs and the container, VM and notification sheets hide Start, Stop, Restart, Update, parity, Archive and Delete controls when the capability probe says the key lacks DOCKER, VMS, ARRAY or NOTIFICATIONS UPDATE_ANY / DELETE_ANY, and show one "View only" note that names the missing permission, with a link to the README table. Unknown access keeps every button as before, and a refused action now says which permission it needed instead of "Forbidden resource". The Add server Test button now uses the capability probe instead of Ping, which the server answers for any key: a rejected key fails the test, and an accepted one reports the Unraid and API version and what the key can do. The API Key field gets a hint and a "Which permissions?" link. The Overview shows the failure reason of a total failure like the tabs do, and only a connection problem (unreachable server, rejected key) marks it offline and hides the needs-attention card. Closes #315 Closes #316 Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 23 ++ HANDOFF.md | 2 +- README.md | 4 +- .../github/nofuturekid/nova/queries.graphql | 4 - .../nova/data/repository/CapabilityProbe.kt | 25 +- .../data/repository/ResponseClassifier.kt | 169 +++++++- .../nova/data/repository/UnraidRepository.kt | 29 +- .../nova/ui/components/ViewOnlyNote.kt | 102 +++++ .../nova/ui/screens/array/ArrayTab.kt | 19 +- .../screens/container/ContainerDetailSheet.kt | 8 + .../nova/ui/screens/docker/DockerTab.kt | 51 ++- .../nova/ui/screens/main/MainScreen.kt | 14 + .../notifications/NotificationsSheet.kt | 31 +- .../nova/ui/screens/overview/OverviewTab.kt | 32 +- .../ui/screens/server/AddEditServerSheet.kt | 36 +- .../nova/ui/screens/vms/VmDetailSheet.kt | 13 +- .../nofuturekid/nova/ui/screens/vms/VmsTab.kt | 22 +- .../nova/data/repository/ActionRefusalTest.kt | 121 ++++++ .../repository/TestConnectionOutcomeTest.kt | 133 +++++++ .../nova/ui/screens/ViewOnlyControlsTest.kt | 364 ++++++++++++++++++ .../screens/overview/OverviewFailureTest.kt | 152 ++++++++ 21 files changed, 1247 insertions(+), 107 deletions(-) create mode 100644 app/src/main/kotlin/io/github/nofuturekid/nova/ui/components/ViewOnlyNote.kt create mode 100644 app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ActionRefusalTest.kt create mode 100644 app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/TestConnectionOutcomeTest.kt create mode 100644 app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/ViewOnlyControlsTest.kt create mode 100644 app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewFailureTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index befdd8c..1cbfbce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,6 +39,23 @@ release version + date and opens a fresh `[Unreleased]`. demo entry exists, and removing it (the bin icon in the server list) throws everything away. Adding a real server while in the demo switches to it. +- **NOVA hides the buttons your API key cannot use** — with a read-only key (the + VIEWER role), the Docker, VMs and Array tabs and the container, VM and + notification sheets no longer show Start, Stop, Restart, Update, parity check, + Archive or Delete buttons. One note in their place says "View only" and which + permission the key would need, for example DOCKER:UPDATE_ANY, with a link to + the list of permissions. A key with only some permissions keeps exactly the + buttons it may use. If NOVA cannot find out what the key may do, it shows the + buttons as before. And if the server still refuses an action, the message now + names the missing permission instead of "Forbidden resource" (#315, #316). + +- **"Test" in the Add server sheet now checks the key** — it used to report + "Connected" for any key, even a wrong one. Now a key the server does not accept + fails the test, and a working key shows the Unraid and API version and whether it + is "View only" or can control Docker, VMs and so on. The API Key field has a + hint and a "Which permissions?" link to the table of what each feature needs + (#315, #316). + ### Changed - **Restarting a container is one step on newer servers** — on Unraid API 4.36.0 @@ -81,6 +98,12 @@ release version + date and opens a fresh `[Unreleased]`. when you type an `http` address while its SSL setting is Yes or Strict: it points to the `https` address, which is the one to enter (#354). +- **The Overview explains why it could not load and keeps its attention card** — + when every part of the Overview failed, it always said "Can't reach the server". + It now gives the same reason as the tabs, for example that the server did not + accept the key. And with Docker or VMs switched off, the "Needs attention" card + stays, because the server itself is still reachable (#217). + ## [0.1.48] - 2026-11-13 The Overview now tells you when something on your server needs you, and the Docker tab can search and group containers by Compose project. A new "Needs attention" card at the top of the Overview lists what needs you, most urgent first; on a healthy server it is not there, so a quiet Overview is normal. The Docker tab has a search field with a clear button, and a new "Compose" option for the Docker view (Settings, Layout) groups containers by their Compose project. The 0.1.48 beta confirmed the search, the Compose option and the quiet Overview on a real phone. Some groundwork in this release has no visible change yet (detecting the server's API version and what the API key may do, and the rules for later opt-in alerts). As in 0.1.47, NOVA does not install updates itself: "Download" opens the release file in your browser. diff --git a/HANDOFF.md b/HANDOFF.md index 8c29d28..9313af5 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -111,7 +111,7 @@ _Toolchain raised in the 0.1.28 cycle — see ADR-0023 (AGP-9) / ADR-0024 app/src/main/ ├── graphql/io/github/nofuturekid/nova/ │ ├── schema.graphqls hand-written subset of the unraid/api generated-schema.graphql -│ ├── queries.graphql Ping, GetServerInfo/Metrics/NetworkThroughput/Display/Array/DockerContainers/Vms, +│ ├── queries.graphql GetServerInfo/Metrics/NetworkThroughput/Display/Array/DockerContainers/Vms, │ │ notifications (overview + list), plugins, plugin ops, installed .plg, NetworkInterfaces, FetchContainerLogs │ ├── mutations.graphql Array, Docker (start/stop/pause/unpause/update/updateAll), Vm (start/stop/pause/resume/ │ │ forceStop/reboot/reset), parityCheck, notification actions diff --git a/README.md b/README.md index d253191..0cbad41 100644 --- a/README.md +++ b/README.md @@ -109,7 +109,7 @@ Requires an Unraid 7.x server with the API/Connect plugin enabled. All app featu NOVA talks to your server with one API key per server. **NOVA never needs the ADMIN role or any permission to manage API keys.** Pick whichever of these suits you: -- **Simplest, read-only: a key with the VIEWER role.** It can see everything NOVA shows and cannot change anything, except that servers older than Unraid API 4.37.4 let every key archive and delete notifications [^4]. Buttons that need more rights are refused by the server. +- **Simplest, read-only: a key with the VIEWER role.** It can see everything NOVA shows and cannot change anything, except that servers older than Unraid API 4.37.4 let every key archive and delete notifications [^4]. NOVA hides the buttons that need more rights. - **Simplest, full control: a key with the ADMIN role.** It can do everything NOVA offers. It can also do much more, which NOVA never uses. - **Least privilege: the VIEWER role plus only the controls you want.** See the table below. @@ -155,7 +155,7 @@ The command shape, with the VIEWER role and `DOCKER:UPDATE_ANY`, was run live an ### When a permission is missing -The server decides, not NOVA. An action the key may not do is refused with the message **"Forbidden resource"** and nothing changes on the server (confirmed live for container actions with a VIEWER key). A read the key may not do is refused the same way, so that screen fails to load. A key the server does not accept at all is answered with "API key validation failed". A later version of NOVA will hide the controls a key cannot use instead of showing buttons that are refused. +The server decides, not NOVA. An action the key may not do is refused with the message **"Forbidden resource"** and nothing changes on the server (confirmed live for container actions with a VIEWER key). A read the key may not do is refused the same way, so that screen fails to load. A key the server does not accept at all is answered with "API key validation failed". NOVA asks the server what the key may do and hides the controls it cannot use, with one "View only" note in their place that names the permission. If NOVA cannot find that out, it shows the buttons, and a refused action then says which permission is missing. ### Which Unraid API version you need diff --git a/app/src/main/graphql/io/github/nofuturekid/nova/queries.graphql b/app/src/main/graphql/io/github/nofuturekid/nova/queries.graphql index b9b792d..f5bae79 100644 --- a/app/src/main/graphql/io/github/nofuturekid/nova/queries.graphql +++ b/app/src/main/graphql/io/github/nofuturekid/nova/queries.graphql @@ -1,7 +1,3 @@ -query Ping { - __typename -} - query FetchContainerLogs($id: PrefixedID!, $tail: Int) { docker { logs(id: $id, tail: $tail) { diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/CapabilityProbe.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/CapabilityProbe.kt index f20ed07..038b870 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/CapabilityProbe.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/CapabilityProbe.kt @@ -30,6 +30,10 @@ data class ProbeOutcome( /** The version query failed validation: the API is older than 4.15.0. */ val versionFieldMissing: Boolean = false, val access: KeyAccess = KeyAccess.Unknown, + /** Set with [Detection.Failed]: the transport exception (a certificate problem is told apart by the caller). */ + val cause: Throwable? = null, + /** Set with [Detection.Failed] when the server answered with an error NOVA does not classify: its own text. */ + val failureText: String? = null, ) { fun toCapabilities(target: CapabilityTarget?) = ServerCapabilities( target = target, @@ -54,21 +58,21 @@ internal fun classifyErrors(errors: List): ErrorClass = when { else -> ErrorClass.Other } -private fun Error.code(): Any? = extensions?.get("code") +internal fun Error.code(): Any? = extensions?.get("code") private sealed interface VersionStep { data class Got(val unraid: String?, val apiText: String?) : VersionStep data object Missing : VersionStep data object Unknown : VersionStep data object Rejected : VersionStep - data object Failed : VersionStep + data class Failed(val cause: Throwable? = null, val text: String? = null) : VersionStep } private sealed interface AccessStep { data class Got(val access: KeyAccess.Known) : AccessStep data object Unknown : AccessStep data object Rejected : AccessStep - data object TransportFailed : AccessStep + data class TransportFailed(val cause: Throwable? = null) : AccessStep } /** @@ -80,7 +84,7 @@ internal suspend fun probeCapabilities(client: ApolloClient): ProbeOutcome { val version = probeVersion(client) when (version) { VersionStep.Rejected -> return ProbeOutcome(Detection.KeyRejected) - VersionStep.Failed -> return ProbeOutcome(Detection.Failed) + is VersionStep.Failed -> return ProbeOutcome(Detection.Failed, cause = version.cause, failureText = version.text) else -> Unit } val versionKnown = version is VersionStep.Got || version == VersionStep.Missing @@ -98,7 +102,8 @@ internal suspend fun probeCapabilities(client: ApolloClient): ProbeOutcome { is AccessStep.Got -> base.copy(access = access.access) AccessStep.Unknown -> base AccessStep.Rejected -> ProbeOutcome(Detection.KeyRejected) - AccessStep.TransportFailed -> if (versionKnown) base else ProbeOutcome(Detection.Failed) + is AccessStep.TransportFailed -> + if (versionKnown) base else ProbeOutcome(Detection.Failed, cause = access.cause) } } @@ -112,15 +117,15 @@ private suspend fun probeVersion(client: ApolloClient): VersionStep = try { ErrorClass.KeyRejected -> VersionStep.Rejected ErrorClass.ValidationFailed -> VersionStep.Missing ErrorClass.Forbidden -> VersionStep.Unknown - ErrorClass.Other -> VersionStep.Failed + ErrorClass.Other -> VersionStep.Failed(text = errors.first().message) } // Transport failure, or a body without data and without errors. - else -> VersionStep.Failed + else -> VersionStep.Failed(cause = resp.exception) } } catch (e: CancellationException) { throw e } catch (e: Exception) { - VersionStep.Failed + VersionStep.Failed(cause = e) } private suspend fun probeAccess(client: ApolloClient): AccessStep = try { @@ -141,10 +146,10 @@ private suspend fun probeAccess(client: ApolloClient): AccessStep = try { // FORBIDDEN (a key without ME:READ_ANY), validation and any other error: fail open. else -> AccessStep.Unknown } - else -> AccessStep.TransportFailed + else -> AccessStep.TransportFailed(resp.exception) } } catch (e: CancellationException) { throw e } catch (e: Exception) { - AccessStep.TransportFailed + AccessStep.TransportFailed(e) } diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/ResponseClassifier.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/ResponseClassifier.kt index c0294a3..6ac5cfa 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/ResponseClassifier.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/ResponseClassifier.kt @@ -8,6 +8,11 @@ import com.apollographql.apollo.exception.ApolloHttpException import com.apollographql.apollo.exception.ApolloNetworkException import io.github.nofuturekid.nova.data.api.CertIssue import io.github.nofuturekid.nova.data.api.certIssue +import io.github.nofuturekid.nova.data.model.Access +import io.github.nofuturekid.nova.data.model.ApiVersion +import io.github.nofuturekid.nova.data.model.KeyAction +import io.github.nofuturekid.nova.data.model.Detection +import io.github.nofuturekid.nova.data.model.ServerCapabilities import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import java.io.InterruptedIOException import java.net.SocketException @@ -185,7 +190,31 @@ fun Throwable.toQueryError(fallback: String): DomainState.Error { * is the honest, cause-carrying text ([failureMessage] for transport errors, * the joined GraphQL error messages otherwise) and is what the user sees. */ -class ActionFailedException(message: String, cause: Throwable? = null) : Exception(message, cause) +class ActionFailedException( + message: String, + cause: Throwable? = null, + /** The server's own wording when [message] replaces it with plain words (a refused permission); else null. */ + val detail: String? = null, +) : Exception(message, cause) + +/** + * The plain sentence for an action the server refused because of the key (#315, ADR-0047), or + * null for any other failure. `FORBIDDEN` names the permission the control needs when + * [operationName] is one of NOVA's mutations ([KeyAction.forOperation]); `UNAUTHENTICATED` says + * the key was not accepted. This is the fallback path: while the key's access is unknown the + * buttons are shown, and the server's refusal is explained here instead of "Forbidden resource". + */ +fun actionRefusalMessage(errors: List?, operationName: String?): String? { + val list = errors.orEmpty() + return when { + list.any { it.code() == "UNAUTHENTICATED" } -> "the server didn't accept the API key" + list.any { it.code() == "FORBIDDEN" } -> { + val needs = operationName?.let { KeyAction.forOperation(it) }?.permission + "your API key isn't allowed to do this" + (needs?.let { " (it needs $it)" } ?: "") + } + else -> null + } +} /** * Throws [ActionFailedException] for a failed action response, using the same @@ -193,33 +222,145 @@ class ActionFailedException(message: String, cause: Throwable? = null) : Excepti * `execute()` never throws for transport or GraphQL errors, so a caller that * does not look at the response sees every failure as success (ADR-0037). */ -fun checkActionResponse(exception: ApolloException?, hasErrors: Boolean, errorMessage: String?) { +fun checkActionResponse( + exception: ApolloException?, + hasErrors: Boolean, + errorMessage: String?, + errors: List? = null, + operationName: String? = null, +) { when (val c = classifyResponse(exception, hasErrors, errorMessage, dataIsNull = false)) { is RespClass.Cert -> throw ActionFailedException(exception!!.failureMessage("Network error"), exception) - is RespClass.Failed -> throw ActionFailedException( - when (exception) { - // Plain wording for the snackbar; the technical cause stays on the exception. - is ApolloHttpException -> exception.redirectMessage()?.replaceFirstChar { it.lowercase() } - ?: "the server answered HTTP ${exception.statusCode}" - is ApolloNetworkException -> "can't reach the server" - else -> c.message - }, - exception, - ) + is RespClass.Failed -> { + val refusal = if (exception == null) actionRefusalMessage(errors, operationName) else null + throw ActionFailedException( + refusal ?: when (exception) { + // Plain wording for the snackbar; the technical cause stays on the exception. + is ApolloHttpException -> exception.redirectMessage()?.replaceFirstChar { it.lowercase() } + ?: "the server answered HTTP ${exception.statusCode}" + is ApolloNetworkException -> "can't reach the server" + else -> c.message + }, + exception, + detail = if (refusal != null) c.message else null, + ) + } RespClass.Empty, RespClass.Ok -> Unit } } /** Returns this response, or throws [ActionFailedException] if it carries a transport or GraphQL error. */ fun ApolloResponse.orThrow(): ApolloResponse { - checkActionResponse(exception, hasErrors(), errors?.joinToString { it.message }) + checkActionResponse(exception, hasErrors(), errors?.joinToString { it.message }, errors, operation.name()) return this } +/** What the tested key may do, in the words of the Add server sheet. [text] is null when it is not known. */ +sealed interface TestControl { + val text: String? + + data object Unknown : TestControl { override val text: String? = null } + + data object ViewOnly : TestControl { override val text = "View only key: NOVA will hide controls" } + + data object Full : TestControl { override val text = "Full control" } + + /** Some controls: [areas] are the ones the key may use, e.g. "Docker", "VMs". */ + data class Some(val areas: List) : TestControl { + override val text = "Can control: ${areas.joinToString(", ")}" + } + + companion object { + /** + * The summary of [caps]. Unknown as soon as one control's access is unknown: a half-known + * key is not described, because a wrong "view only" would be worse than saying nothing. + */ + fun of(caps: ServerCapabilities): TestControl { + val all = KeyAction.entries.associateWith { caps.access(it) } + return when { + all.values.any { it == Access.Unknown } -> Unknown + all.values.all { it == Access.Denied } -> ViewOnly + all.values.all { it == Access.Allowed } -> Full + else -> { + fun ok(a: KeyAction) = all[a] == Access.Allowed + Some( + listOfNotNull( + "Array".takeIf { ok(KeyAction.ControlArray) }, + "Docker".takeIf { ok(KeyAction.ControlDocker) }, + "VMs".takeIf { ok(KeyAction.ControlVms) }, + when { + ok(KeyAction.UpdateNotifications) && ok(KeyAction.DeleteNotifications) -> "Notifications" + ok(KeyAction.UpdateNotifications) -> "Archive notifications" + ok(KeyAction.DeleteNotifications) -> "Delete notifications" + else -> null + }, + ), + ) + } + } + } + } +} + /** Structured result of a connection test (consumed by the Add/Edit sheet). */ sealed interface TestOutcome { - data object Ok : TestOutcome + /** + * The server answered and accepted the key (or could not say it did not). Carries what the + * capability probe learned, so the Add server sheet can say what the key can do (#315). + */ + data class Ok( + val unraidVersion: String? = null, + val apiVersionText: String? = null, + val apiTooOld: Boolean = false, + val control: TestControl = TestControl.Unknown, + ) : TestOutcome { + /** "Connected · Unraid 7.4.0 · API 4.37.11"; the parts that are not known are left out. */ + val title: String + get() = listOfNotNull( + "Connected", + unraidVersion?.takeIf { it.isNotBlank() }?.let { "Unraid $it" }, + apiVersionText?.takeIf { it.isNotBlank() }?.let { "API ${ApiVersion.parse(it) ?: it}" }, + ).joinToString(" · ") + + /** The second line: the API warning if the server is too old, else what the key can do, else a plain "ready". */ + val detail: String + get() = when { + apiTooOld -> + "Connected, but this server's Unraid API is too old. NOVA needs 4.30.0 or newer (Unraid 7.2.5 or newer)." + else -> control.text ?: "Server responded · ready to save" + } + } data class Failed(val message: String) : TestOutcome data class CertUntrusted(val sha256: String) : TestOutcome data class CertChanged(val pinned: String, val presented: String) : TestOutcome } + +/** + * The connection-test result for a capability probe (ADR-0047). A rejected key fails the test with + * the server's own wording; a transport failure keeps its certificate handling (an untrusted or + * changed certificate opens the trust dialog, anything else is the exception's message); a server + * that answered with an error NOVA does not classify shows that error's text. + */ +internal fun testOutcomeOf(probe: ProbeOutcome): TestOutcome = when (probe.detection) { + Detection.KeyRejected -> TestOutcome.Failed("The server didn't accept this API key") + Detection.Failed -> { + val cause = probe.cause + when (val issue = cause?.certIssue()) { + is CertIssue.Untrusted -> TestOutcome.CertUntrusted(issue.sha256) + is CertIssue.Changed -> TestOutcome.CertChanged(issue.pinned, issue.presented) + null -> TestOutcome.Failed( + cause?.failureMessage("Network error") ?: probe.failureText ?: "No response from server", + ) + } + } + // Idle and Detecting are never returned by a probe; treat them as an answer without information. + Detection.Done, Detection.Idle, Detection.Detecting -> { + val caps = probe.toCapabilities(target = null) + TestOutcome.Ok( + unraidVersion = probe.unraidVersion, + apiVersionText = probe.apiVersionText, + apiTooOld = caps.apiTooOld, + control = TestControl.of(caps), + ) + } +} diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/UnraidRepository.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/UnraidRepository.kt index 90ab4c4..f8be29e 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/UnraidRepository.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/UnraidRepository.kt @@ -97,7 +97,6 @@ import io.github.nofuturekid.nova.graphql.GetVmsQuery import io.github.nofuturekid.nova.graphql.PauseContainerMutation import io.github.nofuturekid.nova.graphql.PauseParityCheckMutation import io.github.nofuturekid.nova.graphql.PauseVmMutation -import io.github.nofuturekid.nova.graphql.PingQuery import io.github.nofuturekid.nova.graphql.RebootVmMutation import io.github.nofuturekid.nova.graphql.ResetVmMutation import io.github.nofuturekid.nova.graphql.RestartContainerMutation @@ -1271,6 +1270,10 @@ class UnraidRepository @Inject constructor( * the already-confirmed [pinnedSha256] (null on the first probe): the first * probe surfaces [TestOutcome.CertUntrusted] so the sheet can show the * fingerprint dialog; after the user confirms, a re-probe with the pin matches. + * + * The probe is the capability detection (ADR-0047: version and `me`), not `Ping`: the server + * answers a bare `__typename` for any key, so Ping passed with a wrong key (#315). Here a + * rejected key fails the test, and an accepted one reports what it can do. */ suspend fun testConnection( baseUrl: String, @@ -1283,27 +1286,9 @@ class UnraidRepository @Inject constructor( } else { TlsTrust.Default } - val resp = apolloFactory.build(baseUrl, apiKey, trust).query(PingQuery()).execute() - when (val c = classifyResponse( - exception = resp.exception, - hasErrors = resp.hasErrors(), - errorMessage = resp.errors?.firstOrNull()?.message, - dataIsNull = resp.data == null, - )) { - is RespClass.Cert -> when (val i = c.issue) { - is CertIssue.Untrusted -> TestOutcome.CertUntrusted(i.sha256) - is CertIssue.Changed -> TestOutcome.CertChanged(i.pinned, i.presented) - } - is RespClass.Failed -> TestOutcome.Failed(c.message) - RespClass.Empty -> TestOutcome.Failed("No response from server") - RespClass.Ok -> TestOutcome.Ok - } - } catch (e: ApolloException) { - when (val i = e.certIssue()) { - is CertIssue.Untrusted -> TestOutcome.CertUntrusted(i.sha256) - is CertIssue.Changed -> TestOutcome.CertChanged(i.pinned, i.presented) - null -> TestOutcome.Failed(e.failureMessage("Network error")) - } + testOutcomeOf(probeCapabilities(apolloFactory.build(baseUrl, apiKey, trust))) + } catch (e: CancellationException) { + throw e } catch (e: Exception) { TestOutcome.Failed(e.message ?: "Unknown error") } diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/components/ViewOnlyNote.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/components/ViewOnlyNote.kt new file mode 100644 index 0000000..b84b815 --- /dev/null +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/components/ViewOnlyNote.kt @@ -0,0 +1,102 @@ +package io.github.nofuturekid.nova.ui.components + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalUriHandler +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.dp +import io.github.nofuturekid.nova.data.model.Access +import io.github.nofuturekid.nova.data.model.KeyAction +import io.github.nofuturekid.nova.ui.theme.UnraidAlpha +import io.github.nofuturekid.nova.ui.theme.UnraidTheme + +/** The README section that says which permission each feature needs (#316). */ +const val PERMISSIONS_HELP_URL = "https://github.com/hellwand/nova#api-key-permissions" + +/** + * The two lines of a "View only" note (#315): what the key cannot do, and the permission it would + * need. Pure, so a test can pin every wording; the composable below only draws it. + */ +data class ViewOnly(val title: String, val needs: String) { + companion object { + val Containers = ViewOnly( + "View only. This API key can't start, stop or update containers.", + "Needs ${KeyAction.ControlDocker.permission}", + ) + val Vms = ViewOnly( + "View only. This API key can't start or stop virtual machines.", + "Needs ${KeyAction.ControlVms.permission}", + ) + val Array = ViewOnly( + "View only. This API key can't start or stop the array or run parity checks.", + "Needs ${KeyAction.ControlArray.permission}", + ) + + /** + * The note for the notifications sheet, or null when the key may do both. Archiving needs + * `NOTIFICATIONS:UPDATE_ANY`, deleting `NOTIFICATIONS:DELETE_ANY`; only a [Access.Denied] + * counts, so unknown access shows no note and keeps the buttons. + */ + fun notifications(update: Access, delete: Access): ViewOnly? { + val noUpdate = update == Access.Denied + val noDelete = delete == Access.Denied + val upd = KeyAction.UpdateNotifications.permission + val del = KeyAction.DeleteNotifications.permission + return when { + noUpdate && noDelete -> ViewOnly( + "View only. This API key can't archive or delete notifications.", + "Needs $upd and $del", + ) + noDelete -> ViewOnly("This API key can't delete notifications.", "Needs $del") + noUpdate -> ViewOnly("This API key can't archive notifications.", "Needs $upd") + else -> null + } + } + } +} + +/** + * One note per surface where a key's missing permission hides the controls: it sits where they + * were and says why. Both lines are one merged node, so a screen reader reads them together; + * the "Which permissions?" link sits outside that node, so the note itself is not a button. + */ +@Composable +fun ViewOnlyNote(note: ViewOnly, modifier: Modifier = Modifier) { + val t = UnraidTheme.colors + val uriHandler = LocalUriHandler.current + Column(modifier = modifier.fillMaxWidth()) { + Row( + modifier = Modifier + .fillMaxWidth() + .background(t.muted.copy(alpha = UnraidAlpha.softFill), RoundedCornerShape(12.dp)) + .border(1.dp, t.border, RoundedCornerShape(12.dp)) + .padding(horizontal = 14.dp, vertical = 12.dp) + .semantics(mergeDescendants = true) {}, + verticalAlignment = Alignment.Top, + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + UC.Lock(18.dp, t.muted) + Column(modifier = Modifier.weight(1f)) { + Text(note.title, color = t.text, style = MaterialTheme.typography.bodyMedium) + Text(note.needs, color = t.muted, style = MaterialTheme.typography.labelSmall) + } + } + UnraidButton( + onClick = { runCatching { uriHandler.openUri(PERMISSIONS_HELP_URL) } }, + label = "Which permissions?", + variant = BtnVariant.Text, + tone = Tone.Accent, + ) + } +} diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/array/ArrayTab.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/array/ArrayTab.kt index dd422c2..c6fc0e4 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/array/ArrayTab.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/array/ArrayTab.kt @@ -25,6 +25,7 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import io.github.nofuturekid.nova.data.local.LayoutMode +import io.github.nofuturekid.nova.data.model.Access import io.github.nofuturekid.nova.data.model.ArrayInfo import io.github.nofuturekid.nova.data.model.ArrayState import io.github.nofuturekid.nova.data.model.Disk @@ -40,6 +41,8 @@ import io.github.nofuturekid.nova.ui.components.UC import io.github.nofuturekid.nova.ui.components.UnraidButton import io.github.nofuturekid.nova.ui.components.UnraidCard import io.github.nofuturekid.nova.ui.components.UnraidProgress +import io.github.nofuturekid.nova.ui.components.ViewOnly +import io.github.nofuturekid.nova.ui.components.ViewOnlyNote import io.github.nofuturekid.nova.ui.components.onTone import io.github.nofuturekid.nova.ui.screens.ErrorState import io.github.nofuturekid.nova.ui.screens.ErrorSubject @@ -64,6 +67,8 @@ fun ArrayTab( onCancelParity: () -> Unit, globalDiskWarnC: Int? = null, globalDiskCritC: Int? = null, + /** May the key start and stop the array and run parity checks? Only [Access.Denied] hides the buttons (#315). */ + control: Access = Access.Unknown, ) { when (state) { DomainState.Loading -> LoadingState() @@ -75,6 +80,7 @@ fun ArrayTab( state.value, view, onStartArray, onStopArray, onStartParity, onPauseParity, onResumeParity, onCancelParity, globalDiskWarnC, globalDiskCritC, + canControl = control != Access.Denied, ) } } @@ -116,6 +122,7 @@ private fun ArrayContent( onCancelParity: () -> Unit, globalDiskWarnC: Int? = null, globalDiskCritC: Int? = null, + canControl: Boolean = true, ) { val t = UnraidTheme.colors val arrayOn = arr.state != ArrayState.Stopped && arr.state != ArrayState.Offline @@ -135,6 +142,8 @@ private fun ArrayContent( verticalArrangement = Arrangement.spacedBy(d.gap), ) { if (!hasArray) item { NoArrayCard() } + // Without an array there is nothing to control, so the note only belongs to a real array. + if (hasArray && !canControl) item { ViewOnlyNote(ViewOnly.Array) } if (hasArray) item { UnraidCard(padding = UnraidTheme.tokens.padHero) { Column { @@ -162,7 +171,7 @@ private fun ArrayContent( style = MaterialTheme.typography.bodySmall, ) } - if (arrayOn) { + if (canControl && arrayOn) { UnraidButton( onClick = onStop, label = "Stop", @@ -170,7 +179,7 @@ private fun ArrayContent( tone = Tone.Danger, leadingIcon = { UC.Stop(14.dp, t.danger) }, ) - } else { + } else if (canControl) { UnraidButton( onClick = onStart, label = "Start", @@ -212,8 +221,8 @@ private fun ArrayContent( style = MaterialTheme.typography.labelSmall, ) } - Spacer(Modifier.height(10.dp)) - Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { + if (canControl) Spacer(Modifier.height(10.dp)) + if (canControl) Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { if (pc.paused) { UnraidButton( onClick = onResumeParity, @@ -245,7 +254,7 @@ private fun ArrayContent( ) } } - } else if (arrayOn && !parity) { + } else if (canControl && arrayOn && !parity) { Spacer(Modifier.height(12.dp)) UnraidButton( onClick = onStartParity, diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/container/ContainerDetailSheet.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/container/ContainerDetailSheet.kt index 50809f2..be17b2e 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/container/ContainerDetailSheet.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/container/ContainerDetailSheet.kt @@ -47,6 +47,7 @@ import androidx.compose.ui.unit.sp import androidx.compose.ui.platform.LocalContext import android.content.Intent import androidx.core.net.toUri +import io.github.nofuturekid.nova.data.model.Access import io.github.nofuturekid.nova.data.model.Container import io.github.nofuturekid.nova.data.model.ContainerLiveStats import io.github.nofuturekid.nova.data.model.ContainerStatus @@ -59,6 +60,8 @@ import io.github.nofuturekid.nova.ui.components.UC import io.github.nofuturekid.nova.ui.components.UnraidButton import io.github.nofuturekid.nova.ui.components.UnraidCard import io.github.nofuturekid.nova.ui.components.UnraidIconButton +import io.github.nofuturekid.nova.ui.components.ViewOnly +import io.github.nofuturekid.nova.ui.components.ViewOnlyNote import io.github.nofuturekid.nova.ui.components.onTone import io.github.nofuturekid.nova.ui.theme.JetBrainsMono import io.github.nofuturekid.nova.ui.theme.UnraidAlpha @@ -89,6 +92,8 @@ fun ContainerDetailSheet( onRestart: (Container) -> Unit, onStop: (Container) -> Unit, onUpdate: (Container) -> Unit, + /** May the key start, stop, restart and update containers? Only [Access.Denied] hides the buttons (#315). */ + control: Access = Access.Unknown, ) { val t = UnraidTheme.colors val scope = rememberCoroutineScope() @@ -223,6 +228,9 @@ fun ContainerDetailSheet( style = MaterialTheme.typography.labelLarge, ) } + } else if (control == Access.Denied) { + // Logs and the other tabs below are reads and stay; only the actions go. + ViewOnlyNote(ViewOnly.Containers) } else { if (container.updateStatus.hasUpdate()) { UnraidButton( diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/docker/DockerTab.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/docker/DockerTab.kt index b878a8c..659347e 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/docker/DockerTab.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/docker/DockerTab.kt @@ -43,6 +43,7 @@ import androidx.compose.ui.unit.sp import io.github.nofuturekid.nova.data.local.LayoutMode import io.github.nofuturekid.nova.data.model.Container import io.github.nofuturekid.nova.data.model.ContainerLiveStats +import io.github.nofuturekid.nova.data.model.Access import io.github.nofuturekid.nova.data.model.ContainerStatus import io.github.nofuturekid.nova.data.model.hasUpdate import io.github.nofuturekid.nova.data.repository.DomainState @@ -53,6 +54,8 @@ import io.github.nofuturekid.nova.ui.components.Tone import io.github.nofuturekid.nova.ui.components.UC import io.github.nofuturekid.nova.ui.components.UnraidCard import io.github.nofuturekid.nova.ui.components.UnraidIconButton +import io.github.nofuturekid.nova.ui.components.ViewOnly +import io.github.nofuturekid.nova.ui.components.ViewOnlyNote import io.github.nofuturekid.nova.ui.screens.ErrorState import io.github.nofuturekid.nova.ui.screens.ErrorSubject import io.github.nofuturekid.nova.ui.screens.LoadingState @@ -75,6 +78,8 @@ fun DockerTab( onRestart: (Container) -> Unit, onStop: (Container) -> Unit, onUpdateAll: () -> Unit, + /** May the key start, stop, restart and update containers? Only [Access.Denied] hides the controls (#315). */ + control: Access = Access.Unknown, ) { when (state) { DomainState.Loading -> LoadingState() @@ -94,6 +99,7 @@ fun DockerTab( onRestart = onRestart, onStop = onStop, onUpdateAll = onUpdateAll, + control = control, ) } } @@ -135,7 +141,9 @@ private fun DockerContent( onRestart: (Container) -> Unit, onStop: (Container) -> Unit, onUpdateAll: () -> Unit, + control: Access = Access.Unknown, ) { + val canControl = control != Access.Denied val filtered = filterContainers(containers, query) val rows = MainViewModel.joinContainerStats(filtered, stats) val noMatch = filtered.isEmpty() && containers.isNotEmpty() @@ -149,11 +157,12 @@ private fun DockerContent( ), verticalArrangement = Arrangement.spacedBy(d.gap), ) { - if (updateCount > 0) item { UpdateAllBanner(updateCount, onUpdateAll) } + if (!canControl) item { ViewOnlyNote(ViewOnly.Containers) } + if (updateCount > 0) item { UpdateAllBanner(updateCount, onUpdateAll, canControl) } item { SearchBox(query, onQueryChange) } if (noMatch) item { NoMatches(query, containers.size) } items(rows, key = { it.first.id }) { (c, live) -> - ContainerRow(c, serverBaseUrl, live, onOpenContainer, onStart, onRestart, onStop) + ContainerRow(c, serverBaseUrl, live, onOpenContainer, onStart, onRestart, onStop, canControl) } } LayoutMode.Grid -> LazyVerticalGrid( @@ -165,8 +174,9 @@ private fun DockerContent( horizontalArrangement = Arrangement.spacedBy(d.gap), verticalArrangement = Arrangement.spacedBy(d.gap), ) { + if (!canControl) item(span = { GridItemSpan(maxLineSpan) }) { ViewOnlyNote(ViewOnly.Containers) } if (updateCount > 0) item(span = { GridItemSpan(maxLineSpan) }) { - UpdateAllBanner(updateCount, onUpdateAll) + UpdateAllBanner(updateCount, onUpdateAll, canControl) } item(span = { GridItemSpan(maxLineSpan) }) { SearchBox(query, onQueryChange) } if (noMatch) item(span = { GridItemSpan(maxLineSpan) }) { NoMatches(query, containers.size) } @@ -185,25 +195,26 @@ private fun DockerContent( ), verticalArrangement = Arrangement.spacedBy(d.gap), ) { - if (updateCount > 0) item { UpdateAllBanner(updateCount, onUpdateAll) } + if (!canControl) item { ViewOnlyNote(ViewOnly.Containers) } + if (updateCount > 0) item { UpdateAllBanner(updateCount, onUpdateAll, canControl) } item { SearchBox(query, onQueryChange) } if (noMatch) item { NoMatches(query, containers.size) } if (running.isNotEmpty()) { item { SectionLabel("Running · ${running.size}") } items(running, key = { "r-${it.first.id}" }) { (c, live) -> - ContainerRow(c, serverBaseUrl, live, onOpenContainer, onStart, onRestart, onStop) + ContainerRow(c, serverBaseUrl, live, onOpenContainer, onStart, onRestart, onStop, canControl) } } if (paused.isNotEmpty()) { item { SectionLabel("Paused · ${paused.size}") } items(paused, key = { "p-${it.first.id}" }) { (c, live) -> - ContainerRow(c, serverBaseUrl, live, onOpenContainer, onStart, onRestart, onStop) + ContainerRow(c, serverBaseUrl, live, onOpenContainer, onStart, onRestart, onStop, canControl) } } if (exited.isNotEmpty()) { item { SectionLabel("Stopped · ${exited.size}") } items(exited, key = { "x-${it.first.id}" }) { (c, live) -> - ContainerRow(c, serverBaseUrl, live, onOpenContainer, onStart, onRestart, onStop) + ContainerRow(c, serverBaseUrl, live, onOpenContainer, onStart, onRestart, onStop, canControl) } } } @@ -218,7 +229,8 @@ private fun DockerContent( ), verticalArrangement = Arrangement.spacedBy(d.gap), ) { - if (updateCount > 0) item { UpdateAllBanner(updateCount, onUpdateAll) } + if (!canControl) item { ViewOnlyNote(ViewOnly.Containers) } + if (updateCount > 0) item { UpdateAllBanner(updateCount, onUpdateAll, canControl) } item { SearchBox(query, onQueryChange) } if (noMatch) item { NoMatches(query, containers.size) } groups.forEach { group -> @@ -226,7 +238,7 @@ private fun DockerContent( SectionLabel("${group.title} · ${group.containers.size}") } items(group.containers, key = { "c-${it.id}" }) { c -> - ContainerRow(c, serverBaseUrl, liveById[c.id], onOpenContainer, onStart, onRestart, onStop) + ContainerRow(c, serverBaseUrl, liveById[c.id], onOpenContainer, onStart, onRestart, onStop, canControl) } } } @@ -235,7 +247,7 @@ private fun DockerContent( } @Composable -private fun UpdateAllBanner(count: Int, onTap: () -> Unit) { +private fun UpdateAllBanner(count: Int, onTap: () -> Unit, canUpdate: Boolean = true) { val t = UnraidTheme.colors Row( modifier = Modifier @@ -243,7 +255,7 @@ private fun UpdateAllBanner(count: Int, onTap: () -> Unit) { .clip(RoundedCornerShape(12.dp)) .background(t.info.copy(alpha = UnraidAlpha.softFill)) .border(1.dp, t.info.copy(alpha = UnraidAlpha.softBorder), RoundedCornerShape(12.dp)) - .clickable(onClick = onTap) + .then(if (canUpdate) Modifier.clickable(onClick = onTap) else Modifier) .padding(horizontal = 14.dp, vertical = 12.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), @@ -255,13 +267,15 @@ private fun UpdateAllBanner(count: Int, onTap: () -> Unit) { color = t.info, style = MaterialTheme.typography.labelLarge, ) - Text( - text = "Tap to update all", - color = t.info.copy(alpha = 0.75f), - style = MaterialTheme.typography.labelSmall, - ) + if (canUpdate) { + Text( + text = "Tap to update all", + color = t.info.copy(alpha = 0.75f), + style = MaterialTheme.typography.labelSmall, + ) + } } - UC.ChevR(16.dp, t.info) + if (canUpdate) UC.ChevR(16.dp, t.info) } } @@ -339,6 +353,7 @@ private fun ContainerRow( onStart: (Container) -> Unit, onRestart: (Container) -> Unit, onStop: (Container) -> Unit, + canControl: Boolean = true, ) { val t = UnraidTheme.colors val tone = when (c.status) { @@ -389,7 +404,7 @@ private fun ContainerRow( } } } - Row { + if (canControl) Row { when (c.status) { ContainerStatus.Running -> { UnraidIconButton(icon = { UC.Restart(16.dp, t.text) }, onClick = { onRestart(c) }, size = 34.dp, contentDescription = "Restart ${c.name}") diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/main/MainScreen.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/main/MainScreen.kt index 47dc52e..77baed7 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/main/MainScreen.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/main/MainScreen.kt @@ -54,6 +54,7 @@ import io.github.nofuturekid.nova.BuildConfig import io.github.nofuturekid.nova.data.model.ArrayState import io.github.nofuturekid.nova.data.model.AttentionTarget import io.github.nofuturekid.nova.data.model.Container +import io.github.nofuturekid.nova.data.model.KeyAction import io.github.nofuturekid.nova.data.model.ConnectionMode import io.github.nofuturekid.nova.data.model.NotifType import io.github.nofuturekid.nova.data.model.Server @@ -112,6 +113,12 @@ fun MainScreen( val vmsState by vm.vmsState.collectAsStateWithLifecycle() val notificationsState by vm.notificationsState.collectAsStateWithLifecycle() val displayThresholds by vm.displayThresholds.collectAsStateWithLifecycle() + // What the API key may do. Every surface below gets one Access value and hides its controls + // only for Denied; unknown access keeps them, as before (ADR-0047, #315). + val capabilities by vm.capabilities.collectAsStateWithLifecycle() + val dockerAccess = capabilities.access(KeyAction.ControlDocker) + val vmsAccess = capabilities.access(KeyAction.ControlVms) + val arrayAccess = capabilities.access(KeyAction.ControlArray) val scope = rememberCoroutineScope() // Pause polling when app is backgrounded (ADR-0017). Bound to the @@ -298,6 +305,7 @@ fun MainScreen( }, globalDiskWarnC = displayThresholds?.diskWarnC, globalDiskCritC = displayThresholds?.diskCritC, + control = arrayAccess, ) MainTab.Docker -> DockerTab( state = dockerState, @@ -342,6 +350,7 @@ fun MainScreen( onConfirm = { vm.updateAllContainers(); confirm = null }, ) }, + control = dockerAccess, ) MainTab.Vms -> VmsTab( state = vmsState, @@ -351,6 +360,7 @@ fun MainScreen( onResume = { v -> vm.resumeVm(v.id) }, onPause = { v -> vm.pauseVm(v.id) }, onOpenVm = { openVm = it }, + control = vmsAccess, ) } } @@ -413,6 +423,7 @@ fun MainScreen( onConfirm = { vm.updateContainer(c.id); confirm = null }, ) }, + control = dockerAccess, ) } @@ -463,6 +474,7 @@ fun MainScreen( onConfirm = { vm.resetVm(v.id); confirm = null; openVm = null }, ) }, + control = vmsAccess, ) } @@ -491,6 +503,8 @@ fun MainScreen( onConfirm = { vm.deleteNotification(n.id, n.type ?: NotifType.Unread); confirm = null }, ) }, + update = capabilities.access(KeyAction.UpdateNotifications), + delete = capabilities.access(KeyAction.DeleteNotifications), ) } diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/notifications/NotificationsSheet.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/notifications/NotificationsSheet.kt index 1b5303e..af31b25 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/notifications/NotificationsSheet.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/notifications/NotificationsSheet.kt @@ -33,6 +33,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp +import io.github.nofuturekid.nova.data.model.Access import io.github.nofuturekid.nova.data.model.NotifImportance import io.github.nofuturekid.nova.data.model.NotifType import io.github.nofuturekid.nova.data.model.Notifications @@ -43,6 +44,8 @@ import io.github.nofuturekid.nova.ui.components.Tone import io.github.nofuturekid.nova.ui.components.UC import io.github.nofuturekid.nova.ui.components.UnraidButton import io.github.nofuturekid.nova.ui.components.UnraidIconButton +import io.github.nofuturekid.nova.ui.components.ViewOnly +import io.github.nofuturekid.nova.ui.components.ViewOnlyNote import io.github.nofuturekid.nova.ui.theme.UnraidAlpha import io.github.nofuturekid.nova.ui.theme.UnraidTheme import io.github.nofuturekid.nova.ui.util.notificationSummary @@ -73,8 +76,14 @@ fun NotificationsSheet( onArchiveAll: () -> Unit, onDeleteAllArchivedRequest: () -> Unit, onDeleteRequest: (UnraidNotification) -> Unit, + /** May the key archive and unarchive? Only [Access.Denied] hides those buttons (#315). */ + update: Access = Access.Unknown, + /** May the key delete? Only [Access.Denied] hides the delete buttons (#315). */ + delete: Access = Access.Unknown, ) { val t = UnraidTheme.colors + val canUpdate = update != Access.Denied + val canDelete = delete != Access.Denied val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) val data = (state as? DomainState.Content)?.value var tabIndex by remember { mutableIntStateOf(0) } @@ -144,6 +153,10 @@ fun NotificationsSheet( ) } Spacer(Modifier.height(12.dp)) + ViewOnly.notifications(update, delete)?.let { + ViewOnlyNote(it) + Spacer(Modifier.height(12.dp)) + } when { state is DomainState.Loading -> CenterMsg("Loading notifications…", loading = true) @@ -152,7 +165,7 @@ fun NotificationsSheet( state is DomainState.NoServer -> CenterMsg("No server selected.") else -> { val list = if (tabIndex == 0) unread else archived - if (tabIndex == 0 && unread.isNotEmpty()) { + if (canUpdate && tabIndex == 0 && unread.isNotEmpty()) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End, @@ -167,7 +180,7 @@ fun NotificationsSheet( } Spacer(Modifier.height(6.dp)) } - if (tabIndex == 1 && archived.isNotEmpty()) { + if (canDelete && tabIndex == 1 && archived.isNotEmpty()) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End, @@ -199,6 +212,8 @@ fun NotificationsSheet( onArchive = { onArchive(n.id) }, onUnread = { onUnread(n.id) }, onDelete = { onDeleteRequest(n) }, + canUpdate = canUpdate, + canDelete = canDelete, ) } } @@ -235,6 +250,8 @@ private fun NotificationRow( onArchive: () -> Unit, onUnread: () -> Unit, onDelete: () -> Unit, + canUpdate: Boolean = true, + canDelete: Boolean = true, ) { val t = UnraidTheme.colors val accent = when (n.importance) { @@ -279,25 +296,25 @@ private fun NotificationRow( } } } - Spacer(Modifier.height(8.dp)) - Row( + if (canUpdate || canDelete) Spacer(Modifier.height(8.dp)) + if (canUpdate || canDelete) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End, ) { - if (archivedTab) { + if (canUpdate && archivedTab) { UnraidIconButton( icon = { UC.Restart(20.dp, t.text) }, onClick = onUnread, contentDescription = "Unarchive (restore to unread)", ) - } else { + } else if (canUpdate) { UnraidIconButton( icon = { UC.Check(20.dp, t.text) }, onClick = onArchive, contentDescription = "Archive (mark read)", ) } - UnraidIconButton( + if (canDelete) UnraidIconButton( icon = { UC.Trash(20.dp, t.danger) }, onClick = onDelete, contentDescription = "Delete notification", diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewTab.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewTab.kt index 8e29be1..38b5c72 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewTab.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewTab.kt @@ -102,20 +102,16 @@ fun OverviewTab( // Nothing yet → either Loading or surface the first Error. if (info == null && metrics == null && array == null && containers == null && vms == null) { - val err = listOfNotNull( - infoState as? DomainState.Error, - metricsState as? DomainState.Error, - arrayState as? DomainState.Error, - dockerState as? DomainState.Error, - vmsState as? DomainState.Error, - ).firstOrNull() - if (err != null) ErrorState(err.message, detail = err.detail) else LoadingState() + val err = overviewFailure(infoState, metricsState, arrayState, dockerState, vmsState) + // The reason picks the same title and next step as the tabs do (#247, #217). + if (err != null) ErrorState(err.message, detail = err.detail, reason = err.reason) else LoadingState() return } - // Same rule as the top bar's Offline pill: an Error on any of these streams - // means the server is not reachable, so there is nothing trustworthy to flag. - val offline = listOf(infoState, arrayState, dockerState, vmsState).any { it is DomainState.Error } + // Same rule as the top bar's Offline pill: only an Error that says the server cannot be used + // means there is nothing trustworthy to flag. Docker or VMs being switched off, or a key that + // may not read one domain, leaves the server reachable and the card in place (#217). + val offline = isOffline(infoState, arrayState, dockerState, vmsState) val attention = remember(array, notifications, displayThresholds, offline) { if (offline) emptyList() else attentionItems(AttentionSnapshot(array, notifications, displayThresholds)) @@ -127,6 +123,20 @@ fun OverviewTab( ) } +/** + * The error the Overview shows when no domain has loaded: a connection problem (server + * unreachable, key rejected) wins over any other reason, because it is the cause of the rest; + * otherwise the first error in the order given. Null when nothing failed. + */ +internal fun overviewFailure(vararg states: DomainState<*>): DomainState.Error? { + val errors = states.filterIsInstance() + return errors.firstOrNull { it.reason.isConnectionProblem } ?: errors.firstOrNull() +} + +/** True when any state is an Error that says the server itself cannot be used ([ErrorReason.isConnectionProblem]). */ +internal fun isOffline(vararg states: DomainState<*>): Boolean = + states.any { it is DomainState.Error && it.reason.isConnectionProblem } + @Composable private fun OverviewContent( info: ServerInfo?, diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/server/AddEditServerSheet.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/server/AddEditServerSheet.kt index 131bf09..2e28a05 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/server/AddEditServerSheet.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/server/AddEditServerSheet.kt @@ -26,6 +26,7 @@ import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalUriHandler import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel @@ -46,6 +47,7 @@ import io.github.nofuturekid.nova.data.repository.UnraidRepository import io.github.nofuturekid.nova.ui.components.BtnVariant import io.github.nofuturekid.nova.ui.components.ConfirmDialog import io.github.nofuturekid.nova.ui.components.ConfirmRequest +import io.github.nofuturekid.nova.ui.components.PERMISSIONS_HELP_URL import io.github.nofuturekid.nova.ui.components.Tone import io.github.nofuturekid.nova.ui.components.UC import io.github.nofuturekid.nova.ui.components.UnraidButton @@ -70,8 +72,11 @@ data class AddEditUiState( val showKey: Boolean = false, val localTest: TestState = TestState.Idle, val localTestMsg: String? = null, + // The first line of a successful test ("Connected · Unraid 7.4.0 · API 4.37.11"); the second is the message. + val localTestTitle: String? = null, val remoteTest: TestState = TestState.Idle, val remoteTestMsg: String? = null, + val remoteTestTitle: String? = null, // Fingerprint captured at Test, pinned on save (null until confirmed). val pendingLocalCertSha256: String? = null, // When non-null, the sheet shows the cert-trust confirm dialog. @@ -150,7 +155,9 @@ class AddEditServerViewModel @Inject constructor( viewModelScope.launch { val allowSelfSigned = s.localSsl && s.trustSelfSignedLocal when (val out = unraid.testConnection(url, s.apiKey, allowSelfSigned, s.pendingLocalCertSha256)) { - TestOutcome.Ok -> _state.value = _state.value.copy(localTest = TestState.Ok, localTestMsg = null) + is TestOutcome.Ok -> _state.value = _state.value.copy( + localTest = TestState.Ok, localTestTitle = out.title, localTestMsg = out.detail, + ) is TestOutcome.Failed -> _state.value = _state.value.copy(localTest = TestState.Fail, localTestMsg = out.message) is TestOutcome.CertUntrusted -> _state.value = _state.value.copy( localTest = TestState.Idle, certDialogSha256 = out.sha256, certDialogPrevious = null, @@ -175,7 +182,9 @@ class AddEditServerViewModel @Inject constructor( // Remote always uses full CA validation (allowSelfSigned = false). A // self-signed remote cert therefore comes back as Failed, never a prompt. when (val out = unraid.testConnection(url, s.apiKey, allowSelfSigned = false)) { - TestOutcome.Ok -> _state.value = _state.value.copy(remoteTest = TestState.Ok, remoteTestMsg = null) + is TestOutcome.Ok -> _state.value = _state.value.copy( + remoteTest = TestState.Ok, remoteTestTitle = out.title, remoteTestMsg = out.detail, + ) is TestOutcome.Failed -> _state.value = _state.value.copy(remoteTest = TestState.Fail, remoteTestMsg = out.message) is TestOutcome.CertUntrusted -> _state.value = _state.value.copy(remoteTest = TestState.Fail, remoteTestMsg = "Certificate not trusted (remote requires a valid certificate)") is TestOutcome.CertChanged -> _state.value = _state.value.copy(remoteTest = TestState.Fail, remoteTestMsg = "Certificate changed") @@ -431,6 +440,14 @@ fun AddEditServerSheet( contentDescription = if (state.showKey) "Hide API key" else "Show API key", ) }, + helper = "A key with the VIEWER role is enough to see everything. Controls need more permissions.", + ) + val uriHandler = LocalUriHandler.current + UnraidButton( + onClick = { runCatching { uriHandler.openUri(PERMISSIONS_HELP_URL) } }, + label = "Which permissions?", + variant = BtnVariant.Text, + tone = Tone.Accent, ) if (state.localHost.isNotBlank()) { @@ -439,6 +456,7 @@ fun AddEditServerSheet( state = state.localTest, onTest = vm::testLocal, message = state.localTestMsg, + okTitle = state.localTestTitle, ) Spacer(Modifier.height(8.dp)) } @@ -448,6 +466,7 @@ fun AddEditServerSheet( state = state.remoteTest, onTest = vm::testRemote, message = state.remoteTestMsg, + okTitle = state.remoteTestTitle, ) } @@ -561,7 +580,14 @@ fun AddEditServerSheet( } @Composable -private fun TestConnectionPanel(title: String, state: TestState, onTest: () -> Unit, message: String?) { +private fun TestConnectionPanel( + title: String, + state: TestState, + onTest: () -> Unit, + message: String?, + /** First line after a successful test: the server's version. */ + okTitle: String? = null, +) { val t = UnraidTheme.colors val bg = when (state) { TestState.Ok -> t.accent.copy(alpha = UnraidAlpha.softFill) @@ -587,7 +613,7 @@ private fun TestConnectionPanel(title: String, state: TestState, onTest: () -> U text = when (state) { TestState.Idle -> title TestState.Testing -> "Connecting…" - TestState.Ok -> "Connected" + TestState.Ok -> okTitle ?: "Connected" TestState.Fail -> "Failed to connect" }, color = t.text, @@ -598,7 +624,7 @@ private fun TestConnectionPanel(title: String, state: TestState, onTest: () -> U text = when (state) { TestState.Idle -> "Verify URL + API key before saving" TestState.Testing -> "Talking to GraphQL endpoint…" - TestState.Ok -> "Server responded · ready to save" + TestState.Ok -> message ?: "Server responded · ready to save" TestState.Fail -> message ?: "Check URL and API key" }, color = t.muted, diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/vms/VmDetailSheet.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/vms/VmDetailSheet.kt index 17f85ca..09642e4 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/vms/VmDetailSheet.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/vms/VmDetailSheet.kt @@ -23,6 +23,7 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.unit.dp +import io.github.nofuturekid.nova.data.model.Access import io.github.nofuturekid.nova.data.model.Vm import io.github.nofuturekid.nova.data.model.VmState import io.github.nofuturekid.nova.ui.components.BtnVariant @@ -31,6 +32,8 @@ import io.github.nofuturekid.nova.ui.components.Tone import io.github.nofuturekid.nova.ui.components.UC import io.github.nofuturekid.nova.ui.components.UnraidButton import io.github.nofuturekid.nova.ui.components.UnraidIconButton +import io.github.nofuturekid.nova.ui.components.ViewOnly +import io.github.nofuturekid.nova.ui.components.ViewOnlyNote import io.github.nofuturekid.nova.ui.components.onTone import io.github.nofuturekid.nova.ui.theme.UnraidAlpha import io.github.nofuturekid.nova.ui.theme.UnraidTheme @@ -56,6 +59,8 @@ fun VmDetailSheet( onForceStop: (Vm) -> Unit = {}, onReboot: (Vm) -> Unit, onReset: (Vm) -> Unit, + /** May the key start, stop and otherwise control VMs? Only [Access.Denied] hides the buttons (#315). */ + control: Access = Access.Unknown, ) { val t = UnraidTheme.colors val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) @@ -102,7 +107,9 @@ fun VmDetailSheet( Spacer(Modifier.height(18.dp)) } - Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { + if (control == Access.Denied) { + ViewOnlyNote(ViewOnly.Vms) + } else Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { when (vm.state) { VmState.Running -> { UnraidButton( @@ -155,7 +162,7 @@ fun VmDetailSheet( } } } - if (vm.state == VmState.Running) { + if (control != Access.Denied && vm.state == VmState.Running) { Spacer(Modifier.height(6.dp)) Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { UnraidButton( @@ -177,7 +184,7 @@ fun VmDetailSheet( ) } } - if (vm.state != VmState.Stopped) { + if (control != Access.Denied && vm.state != VmState.Stopped) { Spacer(Modifier.height(6.dp)) UnraidButton( onClick = { onForceStop(vm) }, diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/vms/VmsTab.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/vms/VmsTab.kt index e87117f..58f9142 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/vms/VmsTab.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/vms/VmsTab.kt @@ -29,6 +29,7 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import io.github.nofuturekid.nova.data.local.LayoutMode +import io.github.nofuturekid.nova.data.model.Access import io.github.nofuturekid.nova.data.model.Vm import io.github.nofuturekid.nova.data.model.VmState import io.github.nofuturekid.nova.data.repository.DomainState @@ -38,6 +39,8 @@ import io.github.nofuturekid.nova.ui.components.SectionLabel import io.github.nofuturekid.nova.ui.components.Tone import io.github.nofuturekid.nova.ui.components.UC import io.github.nofuturekid.nova.ui.components.UnraidCard +import io.github.nofuturekid.nova.ui.components.ViewOnly +import io.github.nofuturekid.nova.ui.components.ViewOnlyNote import io.github.nofuturekid.nova.ui.components.onTone import io.github.nofuturekid.nova.ui.screens.ErrorState import io.github.nofuturekid.nova.ui.screens.ErrorSubject @@ -55,7 +58,10 @@ fun VmsTab( onResume: (Vm) -> Unit, onPause: (Vm) -> Unit, onOpenVm: (Vm) -> Unit, + /** May the key start, stop and pause VMs? Only [Access.Denied] hides the buttons (#315). */ + control: Access = Access.Unknown, ) { + val canControl = control != Access.Denied when (state) { DomainState.Loading -> LoadingState() DomainState.NoServer -> NoServerState(onAdd = onAddServer) @@ -77,8 +83,9 @@ fun VmsTab( contentPadding = pad, verticalArrangement = Arrangement.spacedBy(d.gap), ) { + if (!canControl) item { ViewOnlyNote(ViewOnly.Vms) } items(vms, key = { it.id }) { vm -> - VmCard(vm, onOpenVm, onStart, onResume, onPause) + VmCard(vm, onOpenVm, onStart, onResume, onPause, canControl) } } LayoutMode.Grid -> LazyVerticalGrid( @@ -88,6 +95,9 @@ fun VmsTab( horizontalArrangement = Arrangement.spacedBy(d.gap), verticalArrangement = Arrangement.spacedBy(d.gap), ) { + if (!canControl) item(span = { androidx.compose.foundation.lazy.grid.GridItemSpan(maxLineSpan) }) { + ViewOnlyNote(ViewOnly.Vms) + } gridItems(vms, key = { it.id }) { vm -> VmTile(vm, onOpenVm) } @@ -101,22 +111,23 @@ fun VmsTab( contentPadding = pad, verticalArrangement = Arrangement.spacedBy(d.gap), ) { + if (!canControl) item { ViewOnlyNote(ViewOnly.Vms) } if (running.isNotEmpty()) { item { SectionLabel("Running · ${running.size}") } items(running, key = { "r-${it.id}" }) { vm -> - VmCard(vm, onOpenVm, onStart, onResume, onPause) + VmCard(vm, onOpenVm, onStart, onResume, onPause, canControl) } } if (paused.isNotEmpty()) { item { SectionLabel("Paused · ${paused.size}") } items(paused, key = { "p-${it.id}" }) { vm -> - VmCard(vm, onOpenVm, onStart, onResume, onPause) + VmCard(vm, onOpenVm, onStart, onResume, onPause, canControl) } } if (stopped.isNotEmpty()) { item { SectionLabel("Stopped · ${stopped.size}") } items(stopped, key = { "s-${it.id}" }) { vm -> - VmCard(vm, onOpenVm, onStart, onResume, onPause) + VmCard(vm, onOpenVm, onStart, onResume, onPause, canControl) } } } @@ -205,6 +216,7 @@ private fun VmCard( onStart: (Vm) -> Unit, onResume: (Vm) -> Unit, onPause: (Vm) -> Unit, + canControl: Boolean = true, ) { val t = UnraidTheme.colors val tone = when (vm.state) { @@ -246,7 +258,7 @@ private fun VmCard( } } } - when (vm.state) { + if (canControl) when (vm.state) { VmState.Running -> UnraidIconButton( icon = { UC.Pause(16.dp, t.warn) }, onClick = { onPause(vm) }, diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ActionRefusalTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ActionRefusalTest.kt new file mode 100644 index 0000000..2334254 --- /dev/null +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ActionRefusalTest.kt @@ -0,0 +1,121 @@ +package io.github.nofuturekid.nova.data.repository + +import com.apollographql.apollo.ApolloClient +import com.apollographql.apollo.api.Error +import com.apollographql.apollo.api.http.HttpRequest +import com.apollographql.apollo.api.http.HttpResponse +import com.apollographql.apollo.network.http.HttpEngine +import io.github.nofuturekid.nova.data.model.KeyAction +import io.github.nofuturekid.nova.data.repository.UnraidRepository.Companion.runAction +import io.github.nofuturekid.nova.graphql.StartContainerMutation +import io.github.nofuturekid.nova.graphql.StopVmMutation +import io.github.nofuturekid.nova.ui.screens.main.MainViewModel +import kotlinx.coroutines.test.runTest +import okio.Buffer +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The fallback path of #315: while the key's access is unknown the buttons are shown, and a refused + * action must say WHY instead of "Forbidden resource". The FORBIDDEN body is the answer a real + * Unraid 7.4.0 server (API 4.37.11) gave a VIEWER key for `docker.start` on 2026-11-13 (the id did + * not exist and the guard ran before the resolver, so nothing changed); the VM and UNAUTHENTICATED + * bodies have the same shape with the path adapted. + */ +class ActionRefusalTest { + + private class Engine(private val reply: () -> HttpResponse) : HttpEngine { + override suspend fun execute(request: HttpRequest): HttpResponse = reply() + override fun close() {} + } + + private fun reply(body: String): () -> HttpResponse = { + HttpResponse.Builder(200) + .addHeader("Content-Type", "application/graphql-response+json") + .body(Buffer().writeUtf8(body)) + .build() + } + + private val forbiddenDocker = reply( + """{"errors":[{"message":"Forbidden resource","locations":[{"line":1,"column":21}],"path":["docker","start"],"extensions":{"code":"FORBIDDEN","originalError":{"message":"Forbidden resource","error":"Forbidden","statusCode":403}}}],"data":null}""", + ) + private val forbiddenVm = reply( + """{"errors":[{"message":"Forbidden resource","locations":[{"line":1,"column":15}],"path":["vm","stop"],"extensions":{"code":"FORBIDDEN","originalError":{"message":"Forbidden resource","error":"Forbidden","statusCode":403}}}],"data":null}""", + ) + private val unauthenticated = reply( + """{"errors":[{"message":"API key validation failed","locations":[{"line":1,"column":21}],"path":["docker","start"],"extensions":{"code":"UNAUTHENTICATED","originalError":{"message":"API key validation failed","error":"Unauthorized","statusCode":401}}}],"data":null}""", + ) + + private fun client(engine: HttpEngine) = + ApolloClient.Builder().serverUrl("http://unraid.test/graphql").httpEngine(engine).build() + + private suspend fun failureOf(block: suspend () -> Unit): ActionFailedException? = + try { block(); null } catch (e: ActionFailedException) { e } + + // WHY: #315. A user who presses Restart with a read-only key learns which permission to grant, + // not the server's internal "Forbidden resource". + @Test fun forbiddenActionNamesPermission() = runTest { + val e = failureOf { client(Engine(forbiddenDocker)).runAction(StartContainerMutation("c1")) } + assertNotNull(e) + assertEquals("your API key isn't allowed to do this (it needs DOCKER:UPDATE_ANY)", e!!.message) + assertEquals("the server's own wording stays available for diagnosis", "Forbidden resource", e.detail) + } + + @Test fun forbiddenVmActionNamesTheVmPermission() = runTest { + val e = failureOf { client(Engine(forbiddenVm)).runAction(StopVmMutation("v1")) } + assertEquals("your API key isn't allowed to do this (it needs VMS:UPDATE_ANY)", e!!.message) + } + + // WHY: the snackbar prefix is added by the view model; the sentence must read as one sentence. + @Test fun snackbarReadsAsOneSentence() = runTest { + val messages = mutableListOf() + MainViewModel.runResilientAction(emit = { messages += it }) { + client(Engine(forbiddenDocker)).runAction(StartContainerMutation("c1")) + } + assertEquals( + listOf("Action failed: your API key isn't allowed to do this (it needs DOCKER:UPDATE_ANY)"), + messages, + ) + } + + @Test fun rejectedKeyIsSaidSo() = runTest { + val e = failureOf { client(Engine(unauthenticated)).runAction(StartContainerMutation("c1")) } + assertEquals("the server didn't accept the API key", e!!.message) + } + + // WHY: a refusal for an operation NOVA has no table entry for must still be explained, without + // inventing a permission name. + @Test fun unknownOperationGetsTheGenericRefusal() { + val errors = listOf(Error.Builder("Forbidden resource").extensions(mapOf("code" to "FORBIDDEN")).build()) + assertEquals("your API key isn't allowed to do this", actionRefusalMessage(errors, "SomethingNew")) + assertEquals("your API key isn't allowed to do this", actionRefusalMessage(errors, null)) + } + + // WHY: only a refusal for the key is reworded. Any other server error keeps its own text, or the + // user loses the one clue that explains it. + @Test fun otherErrorsAreNotReworded() { + val errors = listOf(Error.Builder("Failed to start").extensions(mapOf("code" to "INTERNAL_SERVER_ERROR")).build()) + assertNull(actionRefusalMessage(errors, "StartContainer")) + assertNull(actionRefusalMessage(emptyList(), "StartContainer")) + assertNull(actionRefusalMessage(null, "StartContainer")) + } + + // WHY: the permission named in the message must be the one the buttons are hidden by. Every + // mutation NOVA sends names exactly its KeyAction's permission, so the two cannot drift apart. + @Test fun everyOperationNamesItsOwnPermission() { + val errors = listOf(Error.Builder("Forbidden resource").extensions(mapOf("code" to "FORBIDDEN")).build()) + KeyAction.entries.forEach { action -> + action.operations.forEach { op -> + val text = actionRefusalMessage(errors, op)!! + assertTrue("$op: $text", text.endsWith("(it needs ${action.permission})")) + KeyAction.entries.filter { it != action }.forEach { + assertFalse("$op must not name ${it.permission}", text.contains(it.permission)) + } + } + } + } +} diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/TestConnectionOutcomeTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/TestConnectionOutcomeTest.kt new file mode 100644 index 0000000..dd195bc --- /dev/null +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/TestConnectionOutcomeTest.kt @@ -0,0 +1,133 @@ +package io.github.nofuturekid.nova.data.repository + +import com.apollographql.apollo.ApolloClient +import com.apollographql.apollo.api.http.HttpRequest +import com.apollographql.apollo.api.http.HttpResponse +import com.apollographql.apollo.network.http.HttpEngine +import io.github.nofuturekid.nova.data.api.CertificateUntrustedException +import kotlinx.coroutines.test.runTest +import okio.Buffer +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import java.io.IOException + +/** + * What the Add server sheet's Test button reports (#315). The probe is the capability detection + * (version and `me`), not `Ping`: the server answers a bare `__typename` for ANY key, so the old + * Test said "Connected" for a wrong key. Bodies are the verbatim answers of an Unraid 7.4.0 server + * (API 4.37.11) recorded on 2026-11-13, except the explicit-permission one, which is constructed. + * They run on a scripted HTTP engine through the real Apollo response path. + */ +class TestConnectionOutcomeTest { + + private class Engine( + private val version: () -> HttpResponse, + private val access: () -> HttpResponse, + ) : HttpEngine { + override suspend fun execute(request: HttpRequest): HttpResponse { + val body = Buffer().also { request.body?.writeTo(it) }.readUtf8() + return if ("GetApiVersion" in body) version() else access() + } + override fun close() {} + } + + private fun reply(body: String, status: Int = 200, type: String = "application/json"): () -> HttpResponse = { + HttpResponse.Builder(status).addHeader("Content-Type", type).body(Buffer().writeUtf8(body)).build() + } + + private val versionOk = reply("""{"data":{"info":{"versions":{"core":{"unraid":"7.4.0","api":"4.37.11+8e587fe2"}}}}}""") + private val viewerMe = reply("""{"data":{"me":{"roles":["VIEWER"],"permissions":[]}}}""") + private val adminMe = reply("""{"data":{"me":{"roles":["ADMIN"],"permissions":[]}}}""") + private val viewerWithDockerAndVms = reply( + """{"data":{"me":{"roles":["VIEWER"],"permissions":[{"resource":"DOCKER","actions":["UPDATE_ANY"]},{"resource":"VMS","actions":["UPDATE_ANY"]}]}}}""", + ) + private val unauthenticated = reply( + """{"errors":[{"message":"API key validation failed","locations":[{"line":1,"column":3}],"path":["info"],"extensions":{"code":"UNAUTHENTICATED","originalError":{"message":"API key validation failed","error":"Unauthorized","statusCode":401}}}],"data":null}""", + ) + private val forbidden = reply( + """{"errors":[{"message":"Forbidden resource","locations":[{"line":1,"column":3}],"path":["me"],"extensions":{"code":"FORBIDDEN","originalError":{"message":"Forbidden resource","error":"Forbidden","statusCode":403}}}],"data":null}""", + ) + private val validation400 = reply( + """{"errors":[{"message":"Cannot query field \"core\" on type \"InfoVersions\".","locations":[{"line":1,"column":12}],"extensions":{"code":"GRAPHQL_VALIDATION_FAILED"}}]}""", + status = 400, + type = "application/graphql-response+json", + ) + private val serverError = reply( + """{"errors":[{"message":"boom","extensions":{"code":"INTERNAL_SERVER_ERROR"}}],"data":null}""", + ) + + private suspend fun test(version: () -> HttpResponse, access: () -> HttpResponse): TestOutcome = + testOutcomeOf(probeCapabilities(client(Engine(version, access)))) + + private fun client(engine: HttpEngine) = + ApolloClient.Builder().serverUrl("http://unraid.test/graphql").httpEngine(engine).build() + + // WHY: the whole defect. A wrong key used to pass the Test, so the user saved a server that then + // showed nothing; the server's UNAUTHENTICATED must fail it. + @Test fun testConnectionRejectsWrongKey() = runTest { + val out = test(unauthenticated, unauthenticated) + assertEquals(TestOutcome.Failed("The server didn't accept this API key"), out) + } + + // WHY: #315. A read-only key is a valid key, and the user is told up front that NOVA will hide + // the controls, instead of finding that out from missing buttons. + @Test fun testConnectionReportsViewOnly() = runTest { + val out = test(versionOk, viewerMe) as TestOutcome.Ok + assertEquals("Connected · Unraid 7.4.0 · API 4.37.11", out.title) + assertEquals("View only key: NOVA will hide controls", out.detail) + assertFalse(out.apiTooOld) + } + + @Test fun testConnectionReportsFullControl() = runTest { + val out = test(versionOk, adminMe) as TestOutcome.Ok + assertEquals("Full control", out.detail) + } + + // WHY: a least-privilege key (#316) must be described by what it can do, not as "view only". + @Test fun testConnectionNamesWhatAPartialKeyCanControl() = runTest { + val out = test(versionOk, viewerWithDockerAndVms) as TestOutcome.Ok + assertEquals("Can control: Docker, VMs", out.detail) + } + + // WHY: a refused `me` is fail-open everywhere; the Test must not claim "view only" for a key whose + // rights nobody could read. It says nothing about control, and the connection still counts. + @Test fun testConnectionSaysNothingAboutControlWhenAccessIsUnknown() = runTest { + val out = test(versionOk, forbidden) as TestOutcome.Ok + assertEquals(TestControl.Unknown, out.control) + assertEquals("Server responded · ready to save", out.detail) + assertEquals("Connected · Unraid 7.4.0 · API 4.37.11", out.title) + } + + // WHY: #247. The server answers, so the connection is fine; what is wrong is the API version, and + // the user is told what to update before they wonder why screens fail. + @Test fun testConnectionWarnsWhenTheApiIsTooOld() = runTest { + val out = test(validation400, viewerMe) as TestOutcome.Ok + assertTrue(out.apiTooOld) + assertEquals("Connected", out.title) + assertEquals( + "Connected, but this server's Unraid API is too old. NOVA needs 4.30.0 or newer (Unraid 7.2.5 or newer).", + out.detail, + ) + } + + // WHY: an unreachable server must fail the Test with the cause, never read as a working connection. + @Test fun testConnectionFailsWhenTheServerIsUnreachable() = runTest { + val unreachable: () -> HttpResponse = { throw IOException("connection refused") } + val out = test(unreachable, unreachable) + assertTrue(out.toString(), out is TestOutcome.Failed) + } + + // WHY: the self-signed-certificate dialog depends on the Test surfacing the fingerprint. Moving the + // Test off Ping must not swallow the certificate exception into a generic failure. + @Test fun testConnectionStillSurfacesAnUntrustedCertificate() = runTest { + val untrusted: () -> HttpResponse = { throw CertificateUntrustedException("AB:CD") } + assertEquals(TestOutcome.CertUntrusted("AB:CD"), test(untrusted, untrusted)) + } + + // WHY: an error NOVA does not classify is shown with the server's own text, not as a success. + @Test fun testConnectionShowsTheServersOwnErrorText() = runTest { + assertEquals(TestOutcome.Failed("boom"), test(serverError, serverError)) + } +} diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/ViewOnlyControlsTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/ViewOnlyControlsTest.kt new file mode 100644 index 0000000..ef49e08 --- /dev/null +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/ViewOnlyControlsTest.kt @@ -0,0 +1,364 @@ +package io.github.nofuturekid.nova.ui.screens + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.test.junit4.ComposeContentTestRule +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onAllNodesWithContentDescription +import androidx.compose.ui.test.onAllNodesWithText +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.test.ext.junit.runners.AndroidJUnit4 +import io.github.nofuturekid.nova.data.demo.DemoFixtures +import io.github.nofuturekid.nova.data.demo.DemoUnraid +import io.github.nofuturekid.nova.data.local.LayoutMode +import io.github.nofuturekid.nova.data.model.Access +import io.github.nofuturekid.nova.data.model.ArrayInfo +import io.github.nofuturekid.nova.data.model.ArrayState +import io.github.nofuturekid.nova.data.model.Container +import io.github.nofuturekid.nova.data.model.ContainerStatus +import io.github.nofuturekid.nova.data.model.ContainerUpdateStatus +import io.github.nofuturekid.nova.data.model.KeyAction +import io.github.nofuturekid.nova.data.model.ParityCheck +import io.github.nofuturekid.nova.data.model.Vm +import io.github.nofuturekid.nova.data.model.VmState +import io.github.nofuturekid.nova.data.repository.DomainState +import io.github.nofuturekid.nova.ui.components.ViewOnly +import io.github.nofuturekid.nova.ui.screens.array.ArrayTab +import io.github.nofuturekid.nova.ui.screens.container.ContainerDetailSheet +import io.github.nofuturekid.nova.ui.screens.docker.DockerTab +import io.github.nofuturekid.nova.ui.screens.notifications.NotificationsSheet +import io.github.nofuturekid.nova.ui.screens.vms.VmDetailSheet +import io.github.nofuturekid.nova.ui.screens.vms.VmsTab +import io.github.nofuturekid.nova.ui.theme.ThemeMode +import io.github.nofuturekid.nova.ui.theme.UnraidTheme +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.test.TestScope +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode + +/** + * #315: a key that may not control something is not offered the controls, and one note says why. + * Each surface is tested in pairs: with [Access.Denied] the buttons are gone and the note is + * there; with [Access.Unknown] (detection failed, not finished, or a role NOVA does not know) and + * with [Access.Allowed] the very same screen shows its buttons. Without the second half a screen + * that hides everything would pass. Same Robolectric setup as the other tab tests. + */ +@RunWith(AndroidJUnit4::class) +@GraphicsMode(GraphicsMode.Mode.NATIVE) +@Config(sdk = [35], qualifiers = "w432dp-h768dp-night-400dpi") +class ViewOnlyControlsTest { + + @get:Rule + val rule = createComposeRule() + + private fun show(content: @Composable () -> Unit) = + rule.setContent { UnraidTheme(themeMode = ThemeMode.Dark) { content() } } + + private fun ComposeContentTestRule.hasText(text: String) = + onAllNodesWithText(text).fetchSemanticsNodes().isNotEmpty() + + private fun ComposeContentTestRule.hasDescription(text: String) = + onAllNodesWithContentDescription(text).fetchSemanticsNodes().isNotEmpty() + + private fun container(name: String, status: ContainerStatus, update: ContainerUpdateStatus = ContainerUpdateStatus.UpToDate) = + Container( + id = name, name = name, image = "img/$name", status = status, autoStart = false, + iconColorHex = null, iconUrl = null, cpu = 0.0, memMb = 0, ports = emptyList(), volumes = emptyList(), + updateStatus = update, webUiUrl = null, networkIp = null, + ) + + private val running = container("plex", ContainerStatus.Running, ContainerUpdateStatus.UpdateAvailable) + private val stopped = container("sonarr", ContainerStatus.Exited) + private val paused = container("radarr", ContainerStatus.Paused) + + private val dockerNote = ViewOnly.Containers.title + private val vmsNote = ViewOnly.Vms.title + private val arrayNote = ViewOnly.Array.title + + // ── Docker tab ─────────────────────────────────────────────────── + + private fun dockerTab(control: () -> Access, layout: () -> LayoutMode = { LayoutMode.List }) = show { + DockerTab( + state = DomainState.Content(listOf(running, stopped, paused)), view = layout(), query = "", + onQueryChange = {}, onAddServer = {}, onOpenContainer = {}, onStart = {}, onRestart = {}, + onStop = {}, onUpdateAll = {}, control = control(), + ) + } + + // WHY: #315 acceptance. A read-only key is offered no Start, Stop, Restart or Resume, in any + // layout the user may have chosen, and the tab says why once. + @Test fun dockerTab_deniedHidesEveryContainerButton_andShowsOneNote() { + var layout by mutableStateOf(LayoutMode.List) + dockerTab({ Access.Denied }, { layout }) + listOf(LayoutMode.List, LayoutMode.Grouped, LayoutMode.Compose).forEach { l -> + layout = l + rule.waitForIdle() + listOf("Restart plex", "Stop plex", "Start sonarr", "Resume radarr").forEach { + assertFalse("$it in $l", rule.hasDescription(it)) + } + assertEquals("one note in $l", 1, rule.onAllNodesWithText(dockerNote).fetchSemanticsNodes().size) + assertTrue(rule.hasText("Needs DOCKER:UPDATE_ANY")) + } + } + + // WHY: the banner keeps telling the user that updates exist (a read), but no longer offers to run them. + @Test fun dockerTab_denied_keepsTheUpdateNotice_withoutTheAction() { + dockerTab({ Access.Denied }) + assertTrue(rule.hasText("1 container has an update")) + assertFalse(rule.hasText("Tap to update all")) + } + + // WHY: fail open. Unknown access (detection failed or still running) must look exactly as before the feature. + @Test fun dockerTab_unknownAndAllowedKeepTheButtons() { + var access by mutableStateOf(Access.Unknown) + dockerTab({ access }) + listOf(Access.Unknown, Access.Allowed).forEach { a -> + access = a + rule.waitForIdle() + listOf("Restart plex", "Stop plex", "Start sonarr", "Resume radarr").forEach { + assertTrue("$it with $a", rule.hasDescription(it)) + } + assertTrue(rule.hasText("Tap to update all")) + assertFalse(rule.hasText(dockerNote)) + } + } + + // ── Container sheet ────────────────────────────────────────────── + + private fun containerSheet(c: Container, control: Access) = show { + ContainerDetailSheet( + container = c, serverBaseUrl = "", liveStats = null, isUpdating = false, + onFetchLogs = { null }, onRefresh = {}, onDismiss = {}, + onStart = {}, onRestart = {}, onStop = {}, onUpdate = {}, control = control, + ) + } + + @Test fun containerSheet_denied_hasNoActions_butShowsTheNote() { + containerSheet(running, Access.Denied) + listOf("Update container", "Restart", "Stop", "Start").forEach { assertFalse(it, rule.hasText(it)) } + assertTrue(rule.hasText(dockerNote)) + // The container itself is still shown: only the actions are gone. + assertTrue(rule.hasText("plex")) + } + + @Test fun containerSheet_unknown_keepsTheActions() { + containerSheet(running, Access.Unknown) + listOf("Update container", "Restart", "Stop").forEach { assertTrue(it, rule.hasText(it)) } + assertFalse(rule.hasText(dockerNote)) + } + + // ── VMs ────────────────────────────────────────────────────────── + + private val vmRunning = Vm("v1", "Windows 11", VmState.Running, 4, 8, null) + private val vmPaused = Vm("v2", "Debian", VmState.Paused, 2, 4, null) + private val vmStopped = Vm("v3", "macOS", VmState.Stopped, 2, 4, null) + + private fun vmsTab(control: Access) = show { + VmsTab( + state = DomainState.Content(listOf(vmRunning, vmPaused, vmStopped)), view = LayoutMode.List, + onAddServer = {}, onStart = {}, onResume = {}, onPause = {}, onOpenVm = {}, control = control, + ) + } + + @Test fun vmsTab_deniedHidesPauseResumeStart_andShowsOneNote() { + vmsTab(Access.Denied) + listOf("Pause Windows 11", "Resume Debian", "Start macOS").forEach { assertFalse(it, rule.hasDescription(it)) } + assertEquals(1, rule.onAllNodesWithText(vmsNote).fetchSemanticsNodes().size) + assertTrue(rule.hasText("Needs VMS:UPDATE_ANY")) + // The VMs themselves stay listed. + assertTrue(rule.hasText("Windows 11")) + } + + @Test fun vmsTab_unknownKeepsTheButtons() { + vmsTab(Access.Unknown) + listOf("Pause Windows 11", "Resume Debian", "Start macOS").forEach { assertTrue(it, rule.hasDescription(it)) } + assertFalse(rule.hasText(vmsNote)) + } + + private fun vmSheet(vm: Vm, control: Access) = show { + VmDetailSheet( + vm = vm, onDismiss = {}, onStart = {}, onResume = {}, onPause = {}, onStop = {}, + onForceStop = {}, onReboot = {}, onReset = {}, control = control, + ) + } + + // WHY: the VM sheet has the most buttons (Reboot, Reset and Force stop are the dangerous ones); + // a read-only key must see none of them. + @Test fun vmSheet_denied_hidesEveryAction() { + vmSheet(vmRunning, Access.Denied) + listOf("Pause", "Stop", "Reboot", "Reset", "Force stop").forEach { assertFalse(it, rule.hasText(it)) } + assertTrue(rule.hasText(vmsNote)) + assertTrue(rule.hasText("Windows 11")) + } + + @Test fun vmSheet_unknown_keepsEveryAction() { + vmSheet(vmRunning, Access.Unknown) + listOf("Pause", "Stop", "Reboot", "Reset", "Force stop").forEach { assertTrue(it, rule.hasText(it)) } + assertFalse(rule.hasText(vmsNote)) + } + + @Test fun vmSheet_deniedWhileStopped_hidesStart() { + vmSheet(vmStopped, Access.Denied) + assertFalse(rule.hasText("Start")) + assertTrue(rule.hasText(vmsNote)) + } + + // ── Array ──────────────────────────────────────────────────────── + + private fun arrayInfo(state: ArrayState, parity: ParityCheck? = null) = + DemoFixtures.array.copy(state = state, parity = parity) + + private fun arrayTab(info: ArrayInfo, control: Access) = show { + ArrayTab( + state = DomainState.Content(info), view = LayoutMode.List, onAddServer = {}, + onStartArray = {}, onStopArray = {}, onStartParity = {}, onPauseParity = {}, + onResumeParity = {}, onCancelParity = {}, control = control, + ) + } + + // WHY: array start/stop and parity checks are the most consequential controls; a view-only key sees none. + @Test fun arrayTab_denied_hidesStopAndParityCheck() { + arrayTab(arrayInfo(ArrayState.Started), Access.Denied) + listOf("Stop", "Start", "Check parity").forEach { assertFalse(it, rule.hasText(it)) } + assertTrue(rule.hasText(arrayNote)) + assertTrue(rule.hasText("Needs ARRAY:UPDATE_ANY")) + // The disks stay listed. + assertTrue(rule.hasText("disk1")) + } + + @Test fun arrayTab_denied_hidesStartWhenStopped() { + arrayTab(arrayInfo(ArrayState.Stopped), Access.Denied) + assertFalse(rule.hasText("Start")) + assertTrue(rule.hasText(arrayNote)) + } + + @Test fun arrayTab_denied_hidesPauseAndCancelOfARunningCheck_butKeepsItsProgress() { + arrayTab(arrayInfo(ArrayState.Parity, ParityCheck(0.4f, 120.0, paused = false)), Access.Denied) + listOf("Pause", "Cancel", "Resume").forEach { assertFalse(it, rule.hasText(it)) } + assertTrue(rule.hasText("Parity operation in progress")) + assertTrue(rule.hasText("40%")) + } + + @Test fun arrayTab_unknown_keepsEveryControl() { + arrayTab(arrayInfo(ArrayState.Started), Access.Unknown) + listOf("Stop", "Check parity").forEach { assertTrue(it, rule.hasText(it)) } + assertFalse(rule.hasText(arrayNote)) + } + + @Test fun arrayTab_unknown_keepsPauseAndCancel() { + arrayTab(arrayInfo(ArrayState.Parity, ParityCheck(0.4f, 120.0, paused = false)), Access.Unknown) + listOf("Pause", "Cancel").forEach { assertTrue(it, rule.hasText(it)) } + } + + // ── Notifications ──────────────────────────────────────────────── + + private fun notificationsSheet(update: Access, delete: Access) = show { + NotificationsSheet( + state = DomainState.Content(DemoFixtures.notifications), + onDismiss = {}, onArchive = {}, onUnread = {}, onArchiveAll = {}, + onDeleteAllArchivedRequest = {}, onDeleteRequest = {}, update = update, delete = delete, + ) + } + + // WHY: the two permissions are separate on the server (UPDATE_ANY archives, DELETE_ANY deletes), + // so a key that may archive but not delete keeps exactly the archive buttons. + @Test fun notifications_updateAllowedDeleteDenied_hidesOnlyDelete() { + notificationsSheet(Access.Allowed, Access.Denied) + assertTrue(rule.hasText("Archive all")) + assertTrue(rule.hasDescription("Archive (mark read)")) + assertFalse(rule.hasDescription("Delete notification")) + assertTrue(rule.hasText("This API key can't delete notifications.")) + assertTrue(rule.hasText("Needs NOTIFICATIONS:DELETE_ANY")) + // On the archived tab "Delete all archived" is a delete too. + rule.onNodeWithText("Archived (1)").performClick() + rule.waitForIdle() + assertFalse(rule.hasText("Delete all archived")) + assertTrue(rule.hasDescription("Unarchive (restore to unread)")) + } + + @Test fun notifications_bothDenied_hidesEveryActionAndShowsOneNote() { + notificationsSheet(Access.Denied, Access.Denied) + assertFalse(rule.hasText("Archive all")) + assertFalse(rule.hasDescription("Archive (mark read)")) + assertFalse(rule.hasDescription("Delete notification")) + assertEquals(1, rule.onAllNodesWithText("View only. This API key can't archive or delete notifications.").fetchSemanticsNodes().size) + assertTrue(rule.hasText("Needs NOTIFICATIONS:UPDATE_ANY and NOTIFICATIONS:DELETE_ANY")) + // The notifications themselves are still readable. + assertTrue(rule.hasText("Warning [TOWER] - Disk 3 temperature")) + } + + @Test fun notifications_updateDeniedDeleteAllowed_hidesOnlyArchive() { + notificationsSheet(Access.Denied, Access.Allowed) + assertFalse(rule.hasText("Archive all")) + assertFalse(rule.hasDescription("Archive (mark read)")) + assertTrue(rule.hasDescription("Delete notification")) + assertTrue(rule.hasText("This API key can't archive notifications.")) + } + + @Test fun notifications_unknownKeepsEveryButton() { + notificationsSheet(Access.Unknown, Access.Unknown) + assertTrue(rule.hasText("Archive all")) + assertTrue(rule.hasDescription("Archive (mark read)")) + assertTrue(rule.hasDescription("Delete notification")) + assertFalse(rule.hasText("View only. This API key can't archive or delete notifications.")) + } + + // ── The demo ───────────────────────────────────────────────────── + + // WHY: the demo has no key and no server to refuse anything; it must look like an admin server. + // The access values come from what the demo reports to the capability model, exactly as MainScreen + // derives them, and no screen may show a note or lose a button. + @Test fun demo_hidesNoControl() { + val caps = DemoUnraid(TestScope(), MutableStateFlow(true)) { 0L }.capabilities().toCapabilities(null) + KeyAction.entries.forEach { assertEquals(it.name, Access.Allowed, caps.access(it)) } + assertNull(ViewOnly.notifications(caps.access(KeyAction.UpdateNotifications), caps.access(KeyAction.DeleteNotifications))) + + show { + DockerTab( + state = DomainState.Content(DemoFixtures.containers), view = LayoutMode.List, query = "", + onQueryChange = {}, onAddServer = {}, onOpenContainer = {}, onStart = {}, onRestart = {}, + onStop = {}, onUpdateAll = {}, control = caps.access(KeyAction.ControlDocker), + ) + } + assertTrue(rule.hasDescription("Restart plex")) + assertTrue(rule.hasDescription("Start jellyfin")) + assertFalse(rule.hasText(dockerNote)) + } + + @Test fun demo_vmsKeepTheirControls() { + val caps = DemoUnraid(TestScope(), MutableStateFlow(true)) { 0L }.capabilities().toCapabilities(null) + show { + VmsTab( + state = DomainState.Content(DemoFixtures.vms), view = LayoutMode.List, onAddServer = {}, + onStart = {}, onResume = {}, onPause = {}, onOpenVm = {}, + control = caps.access(KeyAction.ControlVms), + ) + } + assertTrue(rule.hasDescription("Pause Windows 11")) + assertFalse(rule.hasText(vmsNote)) + } + + // ── The note's wording ─────────────────────────────────────────── + + // WHY: the permission named in the note is the one the button is hidden by; they must not drift. + @Test fun noteTexts_nameThePermissionOfTheirKeyAction() { + assertEquals("Needs ${KeyAction.ControlDocker.permission}", ViewOnly.Containers.needs) + assertEquals("Needs ${KeyAction.ControlVms.permission}", ViewOnly.Vms.needs) + assertEquals("Needs ${KeyAction.ControlArray.permission}", ViewOnly.Array.needs) + assertEquals("Needs DOCKER:UPDATE_ANY", ViewOnly.Containers.needs) + assertNotNull(ViewOnly.notifications(Access.Denied, Access.Unknown)) + assertNull(ViewOnly.notifications(Access.Unknown, Access.Unknown)) + assertNull(ViewOnly.notifications(Access.Allowed, Access.Allowed)) + } +} diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewFailureTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewFailureTest.kt new file mode 100644 index 0000000..c72e030 --- /dev/null +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewFailureTest.kt @@ -0,0 +1,152 @@ +package io.github.nofuturekid.nova.ui.screens.overview + +import androidx.compose.runtime.Composable +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.junit4.ComposeContentTestRule +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onAllNodesWithText +import androidx.compose.ui.test.onNodeWithText +import androidx.test.ext.junit.runners.AndroidJUnit4 +import io.github.nofuturekid.nova.data.demo.DemoFixtures +import io.github.nofuturekid.nova.data.model.ArrayState +import io.github.nofuturekid.nova.data.repository.DomainState +import io.github.nofuturekid.nova.data.repository.ErrorReason +import io.github.nofuturekid.nova.ui.theme.ThemeMode +import io.github.nofuturekid.nova.ui.theme.UnraidTheme +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode + +/** + * The Overview names why it failed, and a switched-off Docker or VM service does not make the + * server look offline (#217, #247). Before, every cause of a total failure read "Can't reach the + * server", and ANY Error on a domain hid the "Needs attention" card although the server answered. + */ +@RunWith(AndroidJUnit4::class) +@GraphicsMode(GraphicsMode.Mode.NATIVE) +@Config(sdk = [35], qualifiers = "w432dp-h768dp-night-400dpi") +class OverviewFailureTest { + + @get:Rule + val rule = createComposeRule() + + private fun error(reason: ErrorReason, message: String = "server text") = + DomainState.Error(message, detail = null, reason = reason) + + private fun show(content: @Composable () -> Unit) = + rule.setContent { UnraidTheme(themeMode = ThemeMode.Dark) { content() } } + + private fun overview( + info: DomainState, + array: DomainState, + docker: DomainState>, + vms: DomainState>, + metrics: DomainState = DomainState.Loading, + ) = show { + OverviewTab( + infoState = info, metricsState = metrics, arrayState = array, dockerState = docker, vmsState = vms, + server = null, onAddServer = {}, + ) + } + + private fun ComposeContentTestRule.exists(text: String) = + onAllNodesWithText(text).fetchSemanticsNodes().isNotEmpty() + + // WHY: a rejected key sent the user to check the network. The Overview now gives the tab's own title and next step. + @Test fun everyDomainFailed_showsTheReason_notAlwaysCantReach() { + overview( + info = error(ErrorReason.KeyRejected), array = error(ErrorReason.KeyRejected), + docker = error(ErrorReason.KeyRejected), vms = error(ErrorReason.KeyRejected), + metrics = error(ErrorReason.KeyRejected), + ) + rule.onNodeWithText("The server didn't accept the API key").assertIsDisplayed() + assertFalse(rule.exists("Can't reach the server")) + } + + // WHY: the guard above must be able to fail: an unreachable server still reads "Can't reach the server". + @Test fun everyDomainFailed_unreachableStillSaysSo() { + overview( + info = error(ErrorReason.Unreachable, "Check that the server is online"), array = error(ErrorReason.Unreachable), + docker = error(ErrorReason.Unreachable), vms = error(ErrorReason.Unreachable), + metrics = error(ErrorReason.Unreachable), + ) + rule.onNodeWithText("Can't reach the server").assertIsDisplayed() + } + + // WHY: #357. A redirect is not a connection problem: the server answered. The Overview says what the + // tabs say (the address needs to change, and where to) and does not claim the server is unreachable. + @Test fun everyDomainFailed_redirected_namesTheTarget_notCantReach() { + val message = "The server redirects to https://tower.example" + overview( + info = error(ErrorReason.Redirected, message), array = error(ErrorReason.Redirected, message), + docker = error(ErrorReason.Redirected, message), vms = error(ErrorReason.Redirected, message), + metrics = error(ErrorReason.Redirected, message), + ) + rule.onNodeWithText("The address needs to change").assertIsDisplayed() + rule.onNodeWithText(message).assertIsDisplayed() + assertFalse(rule.exists("Can't reach the server")) + } + + // WHY: #217. Docker and VMs switched off, the server answers and the array has a problem: the + // user must still see "Needs attention". A stopped array is the problem here. + @Test fun dockerAndVmsOff_keepsTheNeedsAttentionCard() { + overview( + info = DomainState.Content(DemoFixtures.info), + array = DomainState.Content(DemoFixtures.array.copy(state = ArrayState.Stopped)), + docker = error(ErrorReason.ServiceOff), vms = error(ErrorReason.ServiceOff), + ) + assertTrue(rule.exists("Needs attention")) + assertTrue(rule.exists("Array is not started")) + } + + // WHY: the other half, so the test above cannot pass for a card that is always shown: a server + // that is really unreachable has nothing trustworthy to flag. + @Test fun unreachableDomain_hidesTheNeedsAttentionCard() { + overview( + info = DomainState.Content(DemoFixtures.info), + array = DomainState.Content(DemoFixtures.array.copy(state = ArrayState.Stopped)), + docker = error(ErrorReason.Unreachable), vms = DomainState.Loading, + ) + assertFalse(rule.exists("Needs attention")) + } + + // WHY: a rejected key is a connection problem too (the pill says "Key rejected"): nothing to flag either. + @Test fun rejectedKey_hidesTheNeedsAttentionCard() { + overview( + info = DomainState.Content(DemoFixtures.info), + array = DomainState.Content(DemoFixtures.array.copy(state = ArrayState.Stopped)), + docker = error(ErrorReason.KeyRejected), vms = DomainState.Loading, + ) + assertFalse(rule.exists("Needs attention")) + } + + // WHY: the offline rule is the pure heart of the above; pin it for every reason. + @Test fun offlineIsDecidedByTheReason() { + ErrorReason.entries.forEach { reason -> + assertEquals( + reason.toString(), + reason == ErrorReason.Unreachable || reason == ErrorReason.KeyRejected, + isOffline(DomainState.Content(1), error(reason)), + ) + } + assertFalse("no error, not offline", isOffline(DomainState.Content(1), DomainState.Loading)) + } + + // WHY: when the server is unreachable the other domains fail BECAUSE of it; show that cause, not + // whichever domain happens to come first. + @Test fun failureShown_prefersAConnectionProblem() { + val picked = overviewFailure(error(ErrorReason.ServiceOff), error(ErrorReason.KeyRejected), error(ErrorReason.ServerError)) + assertEquals(ErrorReason.KeyRejected, picked!!.reason) + assertEquals( + ErrorReason.ServiceOff, + overviewFailure(DomainState.Loading, error(ErrorReason.ServiceOff), error(ErrorReason.ServerError))!!.reason, + ) + assertNull(overviewFailure(DomainState.Loading, DomainState.Content(1))) + } +} From 979274075d6703dee7904ea22a32604548efb4a2 Mon Sep 17 00:00:00 2001 From: Thomas Kroll Date: Fri, 13 Nov 2026 22:30:58 +0100 Subject: [PATCH 04/11] fix: show dashes for unknown Docker and VM counts and test the attention card with services off The Containers and Virtual machines cards turned an unknown list (not loaded, turned off, not allowed, offline) into "0 running", "all healthy" and "0 configured". They now show the same dash as the other Overview cards; a real empty list still reads 0. The figures moved into OverviewFigures.kt so they can be unit-tested. Regression tests for #356: the Needs attention card stays with VMs or Docker switched off or forbidden for the key, and the cards render dashes while their data is unknown. ErrorReasonTest now also classifies the Docker-off answer through the real Docker query. Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 9 ++ .../ui/screens/overview/OverviewFigures.kt | 28 ++++++ .../nova/ui/screens/overview/OverviewTab.kt | 25 ++--- .../nova/data/repository/ErrorReasonTest.kt | 18 ++++ .../NeedsAttentionWithServicesOffTest.kt | 96 +++++++++++++++++++ .../screens/overview/OverviewFailureTest.kt | 35 +++++++ .../screens/overview/OverviewFiguresTest.kt | 29 ++++++ 7 files changed, 222 insertions(+), 18 deletions(-) create mode 100644 app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/overview/NeedsAttentionWithServicesOffTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 1cbfbce..6310fe9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -104,6 +104,15 @@ release version + date and opens a fresh `[Unreleased]`. accept the key. And with Docker or VMs switched off, the "Needs attention" card stays, because the server itself is still reachable (#217). +- **The "Needs attention" card also appears when Docker or VMs are off, and unknown + counts show a dash** — the card used to disappear whenever Docker or the VM + manager was switched off on the server, or the API key may not read them, even + though the server answered and the array needed you. It now stays. And the + Containers and Virtual machines cards show "—" instead of "0 running · all + healthy" or "0 configured" while NOVA does not know the numbers yet (not + loaded, turned off, not allowed or not reachable). A server that really has + none still shows 0 (#356). + ## [0.1.48] - 2026-11-13 The Overview now tells you when something on your server needs you, and the Docker tab can search and group containers by Compose project. A new "Needs attention" card at the top of the Overview lists what needs you, most urgent first; on a healthy server it is not there, so a quiet Overview is normal. The Docker tab has a search field with a clear button, and a new "Compose" option for the Docker view (Settings, Layout) groups containers by their Compose project. The 0.1.48 beta confirmed the search, the Compose option and the quiet Overview on a real phone. Some groundwork in this release has no visible change yet (detecting the server's API version and what the API key may do, and the rules for later opt-in alerts). As in 0.1.47, NOVA does not install updates itself: "Download" opens the release file in your browser. diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewFigures.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewFigures.kt index 9e03264..316e350 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewFigures.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewFigures.kt @@ -1,6 +1,10 @@ package io.github.nofuturekid.nova.ui.screens.overview import io.github.nofuturekid.nova.data.model.ArrayInfo +import io.github.nofuturekid.nova.data.model.Container +import io.github.nofuturekid.nova.data.model.ContainerStatus +import io.github.nofuturekid.nova.data.model.Vm +import io.github.nofuturekid.nova.data.model.VmState /** What a card shows for a value that is not known (offline, not loaded yet). Same dash as the Network and Temperature cards. */ internal const val PLACEHOLDER = "—" @@ -43,6 +47,30 @@ internal fun arrayFigures(array: ArrayInfo?): ArrayFigures { ) } +/** + * Headline and sub line of the Containers or Virtual machines card. Unknown ([containers] or + * [vms] null: not loaded yet, turned off, not allowed, offline) shows the placeholder, never + * "0 running · all healthy" (#356); a real empty list stays 0. + */ +internal data class CountFigures(val value: String, val sub: String) + +internal fun containerFigures(containers: List?): CountFigures { + if (containers == null) return CountFigures(PLACEHOLDER, PLACEHOLDER) + val stopped = containers.count { it.status == ContainerStatus.Exited } + val paused = containers.count { it.status == ContainerStatus.Paused } + return CountFigures( + value = "${containers.count { it.status == ContainerStatus.Running }}", + sub = if (stopped == 0 && paused == 0) "all healthy" else listOfNotNull( + if (stopped > 0) "$stopped stopped" else null, + if (paused > 0) "$paused paused" else null, + ).joinToString(" · "), + ) +} + +internal fun vmFigures(vms: List?): CountFigures = + if (vms == null) CountFigures(PLACEHOLDER, PLACEHOLDER) + else CountFigures("${vms.count { it.state == VmState.Running }}", "${vms.size} configured") + /** CPU headline: the load, or the placeholder while it is unknown. */ internal fun cpuValue(cpuPercent: Double?): String = cpuPercent?.let { "%.1f%%".format(it) } ?: PLACEHOLDER diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewTab.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewTab.kt index 38b5c72..db8347a 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewTab.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewTab.kt @@ -32,7 +32,6 @@ import io.github.nofuturekid.nova.data.model.AttentionSnapshot import io.github.nofuturekid.nova.data.model.AttentionTarget import io.github.nofuturekid.nova.data.model.attentionItems import io.github.nofuturekid.nova.data.model.Container -import io.github.nofuturekid.nova.data.model.ContainerStatus import io.github.nofuturekid.nova.data.model.DisplayThresholds import io.github.nofuturekid.nova.data.model.LiveMetrics import io.github.nofuturekid.nova.data.model.NetworkThroughput @@ -42,7 +41,6 @@ import io.github.nofuturekid.nova.data.model.ServerInfo import io.github.nofuturekid.nova.data.model.Temperature import io.github.nofuturekid.nova.data.model.TemperatureUnit import io.github.nofuturekid.nova.data.model.Vm -import io.github.nofuturekid.nova.data.model.VmState import io.github.nofuturekid.nova.data.repository.DomainState import io.github.nofuturekid.nova.ui.components.Pill import io.github.nofuturekid.nova.ui.components.Sparkline @@ -110,7 +108,7 @@ fun OverviewTab( // Same rule as the top bar's Offline pill: only an Error that says the server cannot be used // means there is nothing trustworthy to flag. Docker or VMs being switched off, or a key that - // may not read one domain, leaves the server reachable and the card in place (#217). + // may not read one domain, leaves the server reachable and the card in place (#217, #356). val offline = isOffline(infoState, arrayState, dockerState, vmsState) val attention = remember(array, notifications, displayThresholds, offline) { if (offline) emptyList() @@ -191,11 +189,8 @@ private fun OverviewContent( val arrayFig = arrayFigures(array) val arrState = array?.state ?: ArrayState.Offline - val running = containers?.count { it.status == ContainerStatus.Running } ?: 0 - val stopped = containers?.count { it.status == ContainerStatus.Exited } ?: 0 - val paused = containers?.count { it.status == ContainerStatus.Paused } ?: 0 - val vmRunning = vms?.count { it.state == VmState.Running } ?: 0 - val vmCount = vms?.size ?: 0 + val dockerFig = containerFigures(containers) + val vmFig = vmFigures(vms) val arrTone = when (arrState) { ArrayState.Started -> Tone.Accent @@ -391,18 +386,12 @@ private fun OverviewContent( } Spacer(Modifier.height(8.dp)) Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(6.dp)) { - Text("$running", color = t.text, style = MaterialTheme.typography.headlineMedium) + Text(dockerFig.value, color = t.text, style = MaterialTheme.typography.headlineMedium) Text("running", color = t.muted, style = MaterialTheme.typography.bodySmall) } Spacer(Modifier.height(6.dp)) Text( - text = when { - stopped == 0 && paused == 0 -> "all healthy" - else -> listOfNotNull( - if (stopped > 0) "$stopped stopped" else null, - if (paused > 0) "$paused paused" else null, - ).joinToString(" · ") - }, + text = dockerFig.sub, color = t.muted, style = MaterialTheme.typography.bodySmall, ) @@ -417,11 +406,11 @@ private fun OverviewContent( } Spacer(Modifier.height(8.dp)) Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(6.dp)) { - Text("$vmRunning", color = t.text, style = MaterialTheme.typography.headlineMedium) + Text(vmFig.value, color = t.text, style = MaterialTheme.typography.headlineMedium) Text("running", color = t.muted, style = MaterialTheme.typography.bodySmall) } Spacer(Modifier.height(6.dp)) - Text("$vmCount configured", color = t.muted, style = MaterialTheme.typography.bodySmall) + Text(vmFig.sub, color = t.muted, style = MaterialTheme.typography.bodySmall) } } } diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ErrorReasonTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ErrorReasonTest.kt index 4939b1e..437d8a9 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ErrorReasonTest.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ErrorReasonTest.kt @@ -5,6 +5,7 @@ import com.apollographql.apollo.api.http.HttpRequest import com.apollographql.apollo.api.http.HttpResponse import com.apollographql.apollo.exception.ApolloException import com.apollographql.apollo.network.http.HttpEngine +import io.github.nofuturekid.nova.graphql.GetDockerContainersQuery import io.github.nofuturekid.nova.graphql.GetVmsQuery import kotlinx.coroutines.test.runTest import okio.Buffer @@ -67,6 +68,14 @@ class ErrorReasonTest { return classifyErrorReason(resp.exception, resp.errors) } + /** The same for the Docker query, which the Docker-off answer is really given to. */ + private suspend fun reasonOfDocker(server: () -> HttpResponse): ErrorReason { + val client = ApolloClient.Builder().serverUrl("http://unraid.test/graphql").httpEngine(Engine(server)).build() + val resp = client.query(GetDockerContainersQuery()).execute() + assertNull("the Docker-off body must parse, not fail in transport", resp.exception) + return classifyErrorReason(resp.exception, resp.errors) + } + // WHY: #247. A server whose API is too old answers HTTP 400 with a validation error; the tab must // show the "API too old" hint, not raw validation text. @Test fun validationError_isApiTooOld() = runTest { @@ -88,6 +97,15 @@ class ErrorReasonTest { assertEquals(ErrorReason.ServiceOff, reasonOf(dockerOff)) } + // WHY: #356. The Overview keeps its card only if the real Docker query turns this answer into + // ServiceOff; a transport exception here would fall back to Unreachable and read as offline. + @Test fun dockerSocketUnavailable_onTheDockerQuery_isServiceOff() = runTest { + val body = reply( + """{"errors":[{"message":"Docker socket unavailable.","path":["docker","containers"],"extensions":{"code":"INTERNAL_SERVER_ERROR"}}],"data":{"docker":null}}""", + ) + assertEquals(ErrorReason.ServiceOff, reasonOfDocker(body)) + } + @Test fun vmsNotAvailable_isServiceOff() = runTest { assertEquals(ErrorReason.ServiceOff, reasonOf(vmsOff)) } diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/overview/NeedsAttentionWithServicesOffTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/overview/NeedsAttentionWithServicesOffTest.kt new file mode 100644 index 0000000..d938584 --- /dev/null +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/overview/NeedsAttentionWithServicesOffTest.kt @@ -0,0 +1,96 @@ +package io.github.nofuturekid.nova.ui.screens.overview + +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onNodeWithText +import androidx.test.ext.junit.runners.AndroidJUnit4 +import io.github.nofuturekid.nova.data.model.ArrayInfo +import io.github.nofuturekid.nova.data.model.ArrayState +import io.github.nofuturekid.nova.data.model.Container +import io.github.nofuturekid.nova.data.model.LiveMetrics +import io.github.nofuturekid.nova.data.model.Server +import io.github.nofuturekid.nova.data.model.ServerInfo +import io.github.nofuturekid.nova.data.model.Vm +import io.github.nofuturekid.nova.data.repository.DomainState +import io.github.nofuturekid.nova.data.repository.ErrorReason +import io.github.nofuturekid.nova.ui.theme.ThemeMode +import io.github.nofuturekid.nova.ui.theme.UnraidTheme +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode + +/** + * #356 (reported on 0.1.48): with Docker or the VM manager switched off on the server, or a key + * that may not read them, the Overview never showed the "Needs attention" card, even when the + * array is degraded. The server is reachable in every one of these cases. Cases B and C fail + * on the released tag, because there any Error on a domain hid the card. + */ +@RunWith(AndroidJUnit4::class) +@GraphicsMode(GraphicsMode.Mode.NATIVE) +@Config(sdk = [35], qualifiers = "w432dp-h768dp-night-400dpi") +class NeedsAttentionWithServicesOffTest { + + @get:Rule val rule = createComposeRule() + + private val server = Server("s", "Tower", "tower.example.net", "http://192.0.2.10", "https://tower.example.net") + private val info = ServerInfo("Tower", "1d", "7.2.0", "6.12", "CPU", 4, 8, 4.0, 16.0) + private val degraded = ArrayInfo(ArrayState.Error, totalTb = 8.0, usedTb = 2.0, parity = null, disks = emptyList()) + private val noContainers: DomainState> = DomainState.Content(emptyList()) + private val noVms: DomainState> = DomainState.Content(emptyList()) + + private fun off(reason: ErrorReason, message: String) = DomainState.Error(message, detail = null, reason = reason) + private val vmsOff = off(ErrorReason.ServiceOff, "Failed to retrieve VM domains: VMs are not available") + private val dockerOff = off(ErrorReason.ServiceOff, "Docker socket unavailable.") + + private fun show(docker: DomainState>, vms: DomainState>) { + rule.setContent { + UnraidTheme(themeMode = ThemeMode.Dark) { + OverviewTab( + infoState = DomainState.Content(info), + metricsState = DomainState.Content(LiveMetrics(10.0, 20.0, 5.0, 2.0)), + arrayState = DomainState.Content(degraded), + dockerState = docker, + vmsState = vms, + server = server, + onAddServer = {}, + ) + } + } + } + + private fun assertCardShown() { + rule.onNodeWithText("Needs attention").assertIsDisplayed() + rule.onNodeWithText("Array is degraded").assertIsDisplayed() + } + + // A: control, so B and C cannot pass for a card that never depends on the services. + @Test fun a_degraded_array_shows_the_card_when_every_service_answers() { + show(noContainers, noVms) + assertCardShown() + } + + // B + @Test fun the_card_is_shown_although_VMs_are_off() { + show(noContainers, vmsOff) + assertCardShown() + } + + // C + @Test fun the_card_is_shown_although_Docker_is_off() { + show(dockerOff, noVms) + assertCardShown() + } + + // The "permission the key lacks" half of #356, rendered once for each domain. + @Test fun the_card_is_shown_although_the_key_may_not_read_Docker() { + show(off(ErrorReason.Forbidden, "Forbidden resource"), noVms) + assertCardShown() + } + + @Test fun the_card_is_shown_although_the_key_may_not_read_VMs() { + show(noContainers, off(ErrorReason.Forbidden, "Forbidden resource")) + assertCardShown() + } +} diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewFailureTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewFailureTest.kt index c72e030..bb11b8c 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewFailureTest.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewFailureTest.kt @@ -149,4 +149,39 @@ class OverviewFailureTest { ) assertNull(overviewFailure(DomainState.Loading, DomainState.Content(1))) } + + // WHY: #356. With Docker off and the VMs not loaded yet, the cards must not claim "0 running · all + // healthy" / "0 configured": the app does not know, and says so with the dash. + @Test fun unknownDockerAndVms_showDashes_notZero() { + overview( + info = DomainState.Content(DemoFixtures.info), + array = DomainState.Content(DemoFixtures.array), + docker = error(ErrorReason.ServiceOff), vms = DomainState.Loading, + ) + assertFalse(rule.exists("all healthy")) + assertFalse(rule.exists("0 configured")) + assertTrue(rule.onAllNodesWithText(PLACEHOLDER).fetchSemanticsNodes().size >= 4) + } + + // WHY: the same for a key that may not read the domains: unknown, not zero. + @Test fun forbiddenDockerAndVms_showDashes_notZero() { + overview( + info = DomainState.Content(DemoFixtures.info), + array = DomainState.Content(DemoFixtures.array), + docker = error(ErrorReason.Forbidden), vms = error(ErrorReason.Forbidden), + ) + assertFalse(rule.exists("all healthy")) + assertFalse(rule.exists("0 configured")) + } + + // WHY: the guard above must be able to fail: a server that really answers with nothing keeps "0". + @Test fun emptyDockerAndVms_stillReadZero() { + overview( + info = DomainState.Content(DemoFixtures.info), + array = DomainState.Content(DemoFixtures.array), + docker = DomainState.Content(emptyList()), vms = DomainState.Content(emptyList()), + ) + assertTrue(rule.exists("all healthy")) + assertTrue(rule.exists("0 configured")) + } } diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewFiguresTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewFiguresTest.kt index 9076340..687342a 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewFiguresTest.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewFiguresTest.kt @@ -1,7 +1,10 @@ package io.github.nofuturekid.nova.ui.screens.overview import io.github.nofuturekid.nova.data.model.ArrayInfo +import io.github.nofuturekid.nova.data.demo.DemoFixtures import io.github.nofuturekid.nova.data.model.ArrayState +import io.github.nofuturekid.nova.data.model.ContainerStatus +import io.github.nofuturekid.nova.data.model.VmState import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertNotEquals @@ -140,4 +143,30 @@ class OverviewFiguresTest { assertEquals(0f, next.last()) assertEquals(SERIES_LENGTH, next.size) } + + // ── Containers and Virtual machines cards ─────────────────────── + + // WHY: #356. Unknown is not an empty server: "0 running · all healthy" would tell the user + // everything is fine while the app has no idea. + @Test fun unknown_containers_and_vms_show_the_placeholder() { + assertEquals(CountFigures(PLACEHOLDER, PLACEHOLDER), containerFigures(null)) + assertEquals(CountFigures(PLACEHOLDER, PLACEHOLDER), vmFigures(null)) + } + + // WHY: the other half, so the placeholder cannot pass for "always dash": a real empty list stays a real 0. + @Test fun empty_lists_stay_zero() { + assertEquals(CountFigures("0", "all healthy"), containerFigures(emptyList())) + assertEquals(CountFigures("0", "0 configured"), vmFigures(emptyList())) + } + + // WHY: the counts themselves must survive the move out of the card. + @Test fun counts_follow_the_status() { + fun c(status: ContainerStatus) = DemoFixtures.containers.first().copy(status = status) + assertEquals( + CountFigures("2", "1 stopped · 1 paused"), + containerFigures(listOf(c(ContainerStatus.Running), c(ContainerStatus.Running), c(ContainerStatus.Exited), c(ContainerStatus.Paused))), + ) + fun v(state: VmState) = DemoFixtures.vms.first().copy(state = state) + assertEquals(CountFigures("1", "3 configured"), vmFigures(listOf(v(VmState.Running), v(VmState.Stopped), v(VmState.Paused)))) + } } From 2db71ba8f14982f88014dba838b83b6f459202ec Mon Sep 17 00:00:00 2001 From: Thomas Kroll Date: Fri, 13 Nov 2026 22:12:01 +0100 Subject: [PATCH 05/11] feat: alerts outside the app, switched on in Settings Settings, Notifications gets the switch for the background check that already exists on main (ADR-0048), off by default. - Switching on opens an explanation, then asks for POST_NOTIFICATIONS on Android 13 and later; only a granted answer schedules anything. A denial leaves the switch off and shows that Android blocks notifications for NOVA, with a button to Android's notification settings. The line is re-read when the screen returns to the front. - Interval (15 minutes to 3 hours), level (alerts and warnings, or alerts only) and Wi-Fi only go through AlertScheduler.update, which reschedules the existing work. The screen reads only the settings store and never asks for WorkManager while alerts are off. - "Send test notification" runs the same https-only probe once for the active server and posts its newest unread alert or warning. It never writes the remembered state. - Each server has a last-check line: the outcome and time are now kept in ServerAlertState.lastCheck, set by the check runner after every run and read by the screen only; what is notified does not change. A server with only http addresses reads "not checked in the background because the connection is not encrypted. An https address is needed."; the demo server is named as never checked. - A battery hint and a link to dontkillmyapp.com (opened by the user), and a link to the README recipe for instant alerts with Unraid's own agents. Documents: CHANGELOG, README (feature list and an Alerts section), privacy policy (what is sent in the background, the https rule, the new permissions, the alert state), the project site, the store description, HANDOFF, and an addendum to ADR-0048 for the https and demo rules. Closes #321 Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 16 + HANDOFF.md | 1 + README.md | 28 ++ .../nova/data/alerts/AlertCheckRunner.kt | 6 +- .../nova/data/alerts/AlertState.kt | 25 ++ .../nova/data/local/SettingsStore.kt | 3 + .../data/repository/SettingsRepository.kt | 8 + .../nova/ui/screens/settings/AlertsSection.kt | 330 ++++++++++++++ .../ui/screens/settings/AlertsViewModel.kt | 244 ++++++++++ .../ui/screens/settings/SettingsScreen.kt | 8 +- .../nova/data/alerts/AlertCheckRunnerTest.kt | 44 +- .../screens/settings/AlertsCheckLineTest.kt | 57 +++ .../ui/screens/settings/AlertsSectionTest.kt | 419 ++++++++++++++++++ .../0048-opt-in-background-alert-checks.md | 18 +- docs/privacy/POLICY.md | 9 +- .../android/en-US/full_description.txt | 2 + site/index.html | 24 + 17 files changed, 1232 insertions(+), 10 deletions(-) create mode 100644 app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/settings/AlertsSection.kt create mode 100644 app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/settings/AlertsViewModel.kt create mode 100644 app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/settings/AlertsCheckLineTest.kt create mode 100644 app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/settings/AlertsSectionTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 6310fe9..15de245 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -56,6 +56,22 @@ release version + date and opens a fresh `[Unreleased]`. hint and a "Which permissions?" link to the table of what each feature needs (#315, #316). +- **Alerts outside the app (opt-in)** — Settings → Notifications → "Alerts from + your servers" lets NOVA check your servers in the background and tell you + about new Unraid alerts and warnings, and about an array that is not started + or is degraded. It is off by default; while it is off, NOVA does nothing in + the background. Switching it on asks for permission to show notifications + (Android 13 and later). You choose how often NOVA checks (every 15 minutes to + 3 hours), whether warnings count or only alerts, and whether to check on + Wi-Fi only; "Send test notification" shows that it works, and each server's + last check is listed under the switch. The checks go only to your own + servers, with the API key you saved, and a read-only key is enough. They use + only https addresses with a trusted certificate: a server that has only an + http address is not checked, and the screen says so. The demo server is never + checked. Android decides when a check runs, so an alert can come late, + sometimes by an hour or more while the phone is idle. Phones whose maker stops + background work may need a setting changed; the section links to tips (#321). + ### Changed - **Restarting a container is one step on newer servers** — on Unraid API 4.36.0 diff --git a/HANDOFF.md b/HANDOFF.md index 9313af5..bad68b0 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -260,6 +260,7 @@ JSON-scalar decision rationale (incl. why-not-String): [ADR-0007](docs/adr/0007- - **JSON scalar → kotlin.Any via Apollo's `AnyAdapter`** — the Unraid GraphQL `JSON` scalar serialises as inline JSON values (objects/arrays/primitives), not pre-stringified text. Custom `kotlin.String` adapters crash. We map it to `kotlin.Any` with `com.apollographql.apollo.api.AnyAdapter` (public, built-in). Don't try to write your own with `reader.readAny()` — that's `@ApolloInternal`. - **Update check** lives under `data/update/`: `UpdateRepository` polls `https://api.github.com/repos/hellwand/nova/releases` (installed versions up to 0.1.42 still carry the old `nofuturekid/nova` name and reach it through GitHub's redirect; no auth, 60 req/h rate limit fine for on-start checks), `UpdateDialog` only sends the browser to the release's APK (or the release page when it has no APK) with `ACTION_VIEW`; the app downloads and installs nothing itself and declares no `REQUEST_INSTALL_PACKAGES` in any flavor (ADR-0046). The check is compiled into both flavors and disabled at runtime when `BuildConfig.HAS_UPDATER` is false (`store`). The Settings screen exposes the "Include pre-releases" toggle + manual "Check now". Banner on MainScreen dismisses per-tag via `dismissedUpdateTag` in DataStore. - Cleartext HTTP requires `android:usesCleartextTraffic="true"` in the manifest. LAN access against `http://192.168.x.x` needs this. The base-config in `network_security_config.xml` permits cleartext; the GitHub hosts (`api.github.com`, `github.com`, `objects.githubusercontent.com`) are pinned to HTTPS. +- **Alerts outside the app** (ADR-0048) live under `data/alerts/`: `AlertScheduler` is the only door to WorkManager and does nothing, not even ask for the instance, while the switch is off (WorkManager is initialised on demand, `NovaApp` is its `Configuration.Provider`, the automatic initializer is removed in the manifest); `AlertCheckWorker` runs `AlertCheckRunner`, which probes each checkable server through `ServerProbe` (https addresses with verified trust only, no redirects; a server without one is `NotEncrypted`; the demo entry is skipped by `isBackgroundCheckable()`), decides with the pure `evaluateAlerts` and posts through `AlertNotifier`. The per-server memory and the last-check record are in `ServerAlertState`, stored through `AlertStateStore`. The Settings section is `ui/screens/settings/AlertsSection.kt` with `AlertsViewModel` (permission flow, test notification, last-check lines); it reads only the settings store. Background work exists only while the switch is on; ADR-0017's foreground-only rule still holds for every screen stream. - **Unraid 7.4 refuses oversized requests** (cost 1,000, depth 20, 100 aliases, 5,000 tokens). `GraphqlRequestLimitsTest` fails CI when an operation passes 70 % of any limit; numbers and sources under "Unraid 7.4 request limits (#320)" below. - **CI `test` job (ADR-0036) can transiently fail at Gradle _configuration_** with a plugin-not-resolvable error (e.g. `com.google.devtools.ksp` not found) on a plugin-portal/registry blip — it fetches plugins fresh under PR `cache-read-only`. **Re-run the job; it is not a code defect** (see ADR-0036 "Known consequence — transient plugin-fetch in the `test` job" note; PR #163 2026-05-19). diff --git a/README.md b/README.md index 0cbad41..a715cfd 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,7 @@ It talks to your server through the official Unraid API (the Connect plugin's Gr - **Docker** — every container with status; start / stop / restart / pause, jump straight to a container's Web UI, see which have image updates and update one — or all — in a tap - **VMs** — VM state with start / stop / pause / resume - **Multiple servers** — switch between them; each remembers its own local and remote address +- **Alerts outside the app** — optional, off by default: NOVA checks your servers in the background and notifies you of new Unraid alerts and warnings and of an array that is not started or is degraded ([details](#alerts-outside-the-app)) - **Live network speed** — upload/download on the Overview card (needs Unraid API 4.35.0 or newer); the NIC inventory sits under Settings → Network interfaces (vendor, model and link speed only with a third-party API plugin) - **Stay current** — the GitHub APK checks GitHub for new releases and shows a notice on the Overview; **Download** lets your browser fetch the file, and you open it to install (NOVA does not install updates itself; the F-Droid build is updated by F-Droid) @@ -63,6 +64,32 @@ NOVA surfaces what Unraid's GraphQL API exposes today. A few things commonly ask If something on this list (or off it) matters to you, an issue or a 👍 on an existing one is the best signal. +## Alerts outside the app + +NOVA can tell you about a problem on your server without you opening the app. It is **off by default**: with the switch off NOVA does nothing in the background. You switch it on under **Settings → Notifications → Alerts from your servers**. + +**What is checked.** For each of your servers, NOVA asks for its unread Unraid notifications and for the state of its array, and notifies you of: + +- every **new** unread Unraid notification of importance alert or warning (once per notification, never twice; "Alerts only" leaves out warnings); +- an array that **is not started**, and an array that **is degraded**. Unraid itself does not notify about these. + +Disk temperatures, disk errors, SMART warnings, parity checks and pools reach you through Unraid's own notifications, so they appear as the first kind. The first check after you switch on only notes what is already there and shows nothing. A server that cannot be reached is never an alert; the Settings section lists each server's last check instead. Unraid raises one warning each time a parity check starts, so you will see that one with "Alerts and warnings". + +**How often.** Every 30 minutes by default; you can pick 15 minutes, 1 hour or 3 hours, and "Only on Wi-Fi". Android decides the exact time and may batch checks with other apps' work, so an alert can come late, sometimes by an hour or more while the phone lies still (Doze). On Android 13 and later an app you have not opened for 8 days is limited to about one check a day. + +**What it needs.** + +- Notifications allowed for NOVA. On Android 13 and later NOVA asks when you switch the alerts on; if you refuse, the alerts stay off. +- An **https address** for the server. **A plain-http address is never contacted in the background**, because nobody is looking at the phone and the API key would travel in clear text. A server that has only an http address is not checked, and Settings says "not checked in the background because the connection is not encrypted". The certificate must be one your phone trusts, or the one you pinned for the local address; a changed or untrusted certificate is reported in Settings and never accepted without you. Redirects are not followed in the background. +- An API key that can read notifications and the array: a key with the VIEWER role is enough (from the Unraid API's source code; we have not yet tried the background check with such a key on a real server). Nothing is ever changed on the server. +- Unraid must keep the notification as unread, which it does by default ("Browser" delivery on). If you turned that off for an importance, those notifications do not reach NOVA. + +**What it never does.** No Google services, no push service or relay run by this project, no server plugin, no foreground service, no exact alarms, no request to ignore battery optimisation. The checks go only to your own servers. The demo server is never checked. Switching the alerts off cancels the work and removes what NOVA posted. + +**Phones that stop background work.** Some makers (Huawei, Xiaomi, Samsung and others) stop apps in the background more strictly than Android does, and the checks may then not run at all. Settings has a link to [dontkillmyapp.com](https://dontkillmyapp.com) (opened by your browser, only when you tap it) and, when Android restricts the app, a shortcut to the battery settings. On EMUI, for example, you need Battery → App launch → NOVA → Manage manually. Whether a check ran is visible in the "Last check" lines in Settings. + +**Instant alerts with Unraid's own agents.** If you want alerts the moment they happen, let Unraid send them itself. For example, with the ntfy agent (from Unraid's source, not tried by this project): Settings → Notifications in the Unraid web UI → the ntfy.sh agent with your own ntfy server and a topic → tick "Agents" for warnings and alerts → subscribe to the topic in the ntfy app. The agent adds an icon link to every message, and that image is hosted on GitHub. This needs no NOVA setting. + ## Look & feel A deliberately dark, glassy Material 3 design — dense cards, a single accent color, restrained motion. Tuned for quick checks, not for living in. @@ -173,6 +200,7 @@ Unraid® is a registered trademark of Lime Technology, Inc. NOVA is an independe - **Full policy:** - **Your API key stays on your device.** It's encrypted at rest using Android Keystore via Google's Tink library, and explicitly excluded from cloud backup / device-transfer. - **No analytics, no telemetry, no tracking services.** The app talks to your Unraid server's API; in the GitHub (`direct`) build it also asks GitHub's API for app updates (at app start, when the app returns from the background or you come back to the main screen from Settings or the server list, when you open Settings, or on "Check now"); and it loads container icons from the URLs your own server supplies (often GitHub or a CDN). +- **Background checks only if you switch them on.** With "Alerts from your servers" on, NOVA asks your own servers, in the background and over verified https only, for their unread alerts and warnings and their array state, as often as you chose. Nothing else is contacted for it, and with the switch off nothing runs in the background. See [Alerts outside the app](#alerts-outside-the-app). - **Update downloads** are made by your browser, not by NOVA: the update sheet opens the release's APK on GitHub, shows its SHA-256 so you can compare it with the downloaded file, and the app itself downloads and installs nothing. See [ADR-0046](./docs/adr/0046-update-via-browser-download.md). - **Source is the spec.** Audit, fork, run yourself — GPL v3. diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/data/alerts/AlertCheckRunner.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/data/alerts/AlertCheckRunner.kt index cb64ad8..fab7e09 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/data/alerts/AlertCheckRunner.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/data/alerts/AlertCheckRunner.kt @@ -34,6 +34,7 @@ class AlertCheckRunner internal constructor( private val notifier: AlertNotifier, private val cancelWork: suspend () -> Unit, private val serverTimeoutMs: Long, + private val now: () -> Long = System::currentTimeMillis, ) { @Inject constructor( @@ -70,8 +71,9 @@ class AlertCheckRunner internal constructor( val posted = notifier.post(ref, evaluation) // Not stored when Android refused the post, so the next check tries again. Not stored either // when the server was deleted while the check ran, which would leave state nobody removes. - if (posted && evaluation.nextState != previous && stillSaved(server.id)) { - states.put(server.id, evaluation.nextState) + // The last-check record is for the settings line only; it changes nothing that is posted. + if (posted && stillSaved(server.id)) { + states.put(server.id, evaluation.nextState.copy(lastCheck = CheckRecord(now(), result.toOutcome()))) } return ServerCheck(ref, result, posted = evaluation.toPost.size, folded = evaluation.foldedCount) } diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/data/alerts/AlertState.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/data/alerts/AlertState.kt index dfe0a47..ba85106 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/data/alerts/AlertState.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/data/alerts/AlertState.kt @@ -22,4 +22,29 @@ data class ServerAlertState( val conditionsBaselined: Boolean = false, /** Array conditions that held at the last successful read, a subset of [STATE_ALERT_KEYS]. */ val openConditions: Set = emptySet(), + /** + * How the last check of this server went, for the settings screen's last-check line only. + * It plays no part in what is posted: [evaluateAlerts] leaves it alone and the check runner + * sets it after every run. + */ + val lastCheck: CheckRecord? = null, ) + +/** How one check of one server ended. Mirrors [ProbeResult], without the data. */ +@Serializable +enum class CheckOutcome { Ok, Unreachable, NotEncrypted, CertificateProblem, KeyMissing, KeyUnreadable, Rejected } + +/** When ([atEpochMs]) and how ([outcome]) a server was last checked in the background. */ +@Serializable +data class CheckRecord(val atEpochMs: Long, val outcome: CheckOutcome) + +/** The [CheckOutcome] a probe result is recorded as. */ +fun ProbeResult.toOutcome(): CheckOutcome = when (this) { + is ProbeResult.Ok -> CheckOutcome.Ok + ProbeResult.Unreachable -> CheckOutcome.Unreachable + ProbeResult.NotEncrypted -> CheckOutcome.NotEncrypted + ProbeResult.CertificateProblem -> CheckOutcome.CertificateProblem + ProbeResult.KeyMissing -> CheckOutcome.KeyMissing + ProbeResult.KeyUndecryptable -> CheckOutcome.KeyUnreadable + is ProbeResult.Rejected -> CheckOutcome.Rejected +} diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/data/local/SettingsStore.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/data/local/SettingsStore.kt index 47751a2..0c193b0 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/data/local/SettingsStore.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/data/local/SettingsStore.kt @@ -242,6 +242,9 @@ class SettingsStore @Inject constructor( runCatching { json.decodeFromString>(it) }.getOrDefault(emptyMap()) } ?: emptyMap() + /** Every server's remembered alert state; the settings screen reads the last-check records from it. */ + val alertStates: Flow> = ds.data.map { decodeAlertStates(it) } + suspend fun alertStateFor(serverId: String): ServerAlertState = decodeAlertStates(ds.data.first())[serverId] ?: ServerAlertState() diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/SettingsRepository.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/SettingsRepository.kt index 2286fa4..9bae1ed 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/SettingsRepository.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/SettingsRepository.kt @@ -1,7 +1,10 @@ package io.github.nofuturekid.nova.data.repository import kotlinx.coroutines.flow.Flow +import io.github.nofuturekid.nova.data.alerts.AlertSettings +import io.github.nofuturekid.nova.data.alerts.ServerAlertState import io.github.nofuturekid.nova.data.local.LayoutMode +import io.github.nofuturekid.nova.data.local.ServerSnapshot import io.github.nofuturekid.nova.data.local.SettingsStore import io.github.nofuturekid.nova.data.model.AppSettings import io.github.nofuturekid.nova.ui.theme.Density @@ -21,6 +24,11 @@ class SettingsRepository @Inject constructor( val lastUpdateCheck: Flow = store.lastUpdateCheck val dismissedUpdateTag: Flow = store.dismissedUpdateTag + // Read side of the alerts section. Writing goes through AlertScheduler, which also schedules. + val alertSettings: Flow = store.alertSettings + val alertStates: Flow> = store.alertStates + val serverSnapshot: Flow = store.serverSnapshot + suspend fun setAccent(hex: Long) = store.setAccent(hex) suspend fun setThemeMode(mode: ThemeMode) = store.setThemeMode(mode) suspend fun setDensity(density: Density) = store.setDensity(density) diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/settings/AlertsSection.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/settings/AlertsSection.kt new file mode 100644 index 0000000..33da5bc --- /dev/null +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/settings/AlertsSection.kt @@ -0,0 +1,330 @@ +package io.github.nofuturekid.nova.ui.screens.settings + +import android.Manifest +import android.content.ActivityNotFoundException +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.net.Uri +import android.os.Build +import android.os.PowerManager +import android.provider.Settings +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.core.content.ContextCompat +import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleEventObserver +import androidx.lifecycle.compose.LocalLifecycleOwner +import io.github.nofuturekid.nova.data.alerts.ALERT_INTERVALS_MIN +import io.github.nofuturekid.nova.data.alerts.AlertLevel +import io.github.nofuturekid.nova.ui.components.BtnVariant +import io.github.nofuturekid.nova.ui.components.SectionLabel +import io.github.nofuturekid.nova.ui.components.Tone +import io.github.nofuturekid.nova.ui.components.UnraidButton +import io.github.nofuturekid.nova.ui.components.UnraidCard +import io.github.nofuturekid.nova.ui.theme.UnraidDims +import io.github.nofuturekid.nova.ui.theme.UnraidTheme +import java.time.Instant +import java.time.LocalDate +import java.time.ZoneId +import java.time.format.DateTimeFormatter +import java.time.format.FormatStyle + +private const val TIPS_URL = "https://dontkillmyapp.com" +private const val INSTANT_ALERTS_URL = "https://github.com/hellwand/nova#alerts-outside-the-app" + +/** + * Settings, Notifications: the switch for alerts outside the app (ADR-0048) and its choices. + * Emits its own label and card into the Settings column. + * + * The permission flow lives here because the system's request needs the activity: the switch + * opens an explanation, "Turn on" asks Android for the permission (Android 13 and later, when it + * is not granted yet) and only a granted answer reaches [AlertsViewModel.onPermissionResult] as + * true, which is the one place that schedules anything. A denial leaves the switch off. + */ +@Composable +fun AlertsSection(vm: AlertsViewModel = hiltViewModel()) { + val ui by vm.state.collectAsState() + val ctx = LocalContext.current + var showExplanation by remember { mutableStateOf(false) } + var resumes by remember { mutableIntStateOf(0) } + + val permissionRequest = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> + vm.onPermissionResult(granted) + } + + // Coming back from Android's settings: the notification block or the battery setting may have changed. + val owner = LocalLifecycleOwner.current + DisposableEffect(owner) { + val observer = LifecycleEventObserver { _, event -> + if (event == Lifecycle.Event.ON_RESUME) { + vm.refreshNotificationsAllowed() + resumes++ + } + } + owner.lifecycle.addObserver(observer) + onDispose { owner.lifecycle.removeObserver(observer) } + } + + val t = UnraidTheme.colors + val settings = ui.settings + SectionLabel("Notifications") + UnraidCard(padding = UnraidTheme.tokens.pad) { + Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Column(modifier = Modifier.weight(1f)) { + Text("Alerts from your servers", color = t.text, style = MaterialTheme.typography.labelLarge) + Text( + text = if (settings.enabled) { + "On. NOVA checks your servers about every ${intervalPhrase(settings.intervalMinutes)}." + } else { + "Off. NOVA does nothing in the background." + }, + color = t.muted, + style = MaterialTheme.typography.bodySmall, + ) + } + Toggle(value = settings.enabled, onChange = { on -> if (on) showExplanation = true else vm.turnOff() }) + } + + if (ui.blocked) { + Text( + text = if (settings.enabled) { + "Android blocks notifications for NOVA, so no alert can be shown and the checks are paused. " + + "Allow notifications in Android's settings." + } else { + "Android blocks notifications for NOVA. Allow them in Android's settings, then switch this on." + }, + color = t.warn, + style = MaterialTheme.typography.bodyMedium, + ) + UnraidButton( + onClick = { ctx.open(notificationSettingsIntent(ctx)) }, + label = "Open notification settings", + variant = BtnVariant.Tonal, + ) + } + + if (ui.hasDemoServer) { + Text( + text = "The demo server is never checked. Alerts only cover your own servers.", + color = t.muted, + style = MaterialTheme.typography.bodySmall, + ) + } + + if (settings.enabled) { + Option("Check every", "More often uses a little more battery.") { + Segmented( + value = settings.intervalMinutes, + options = ALERT_INTERVALS_MIN, + label = ::intervalLabel, + onChange = vm::setInterval, + ) + } + Option("Alert me about", "Unraid also sends a warning each time a parity check starts.") { + Segmented( + value = settings.level, + options = listOf(AlertLevel.AlertsAndWarnings, AlertLevel.AlertsOnly), + label = { if (it == AlertLevel.AlertsOnly) "Alerts only" else "Alerts and warnings" }, + onChange = vm::setLevel, + ) + } + Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { + SettingRow(label = "Only on Wi-Fi") { + Toggle(value = settings.unmeteredOnly, onChange = vm::setUnmeteredOnly) + } + Text("Skip checks on mobile data.", color = t.muted, style = MaterialTheme.typography.bodySmall) + } + + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + Text( + text = "Checks the server you are using now and shows its newest unread alert or warning as a test.", + color = t.muted, + style = MaterialTheme.typography.bodySmall, + ) + UnraidButton( + onClick = vm::sendTest, + label = "Send test notification", + variant = BtnVariant.Tonal, + enabled = ui.canTest && !ui.testing && !ui.blocked, + ) + ui.testMessage?.let { + Text(it, color = t.text, style = MaterialTheme.typography.bodyMedium) + } + } + + if (ui.servers.isNotEmpty()) { + Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { + Text("Last check", color = t.muted, style = MaterialTheme.typography.labelLarge) + ui.servers.forEach { line -> + Column { + Text(line.name, color = t.text, style = MaterialTheme.typography.labelLarge) + Text( + text = line.text.replaceFirstChar { it.uppercase() } + + (line.atEpochMs?.let { " · ${formatCheckTime(it)}" } ?: ""), + color = t.muted, + style = MaterialTheme.typography.bodySmall, + ) + } + } + } + } + + val batteryOptimised = remember(resumes) { ctx.isBatteryOptimised() } + Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { + Text( + text = "Android decides when a check runs. When the phone lies still, a check can be an hour or more late." + + if (batteryOptimised) " Battery saving can delay or stop the checks." else "", + color = t.muted, + style = MaterialTheme.typography.bodySmall, + ) + Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) { + if (batteryOptimised) { + TextButton(onClick = { ctx.open(Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS)) }) { + Text("Open battery settings", color = t.accent) + } + } + TextButton(onClick = { ctx.open(Intent(Intent.ACTION_VIEW, Uri.parse(TIPS_URL))) }) { + Text("Tips for your phone", color = t.accent) + } + } + } + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + text = "Unraid can also send alerts itself, for example to your own ntfy server.", + color = t.muted, + style = MaterialTheme.typography.bodySmall, + modifier = Modifier.weight(1f), + ) + TextButton(onClick = { ctx.open(Intent(Intent.ACTION_VIEW, Uri.parse(INSTANT_ALERTS_URL))) }) { + Text("How", color = t.accent) + } + } + } + } + } + + if (showExplanation) { + ExplanationDialog( + intervalMinutes = settings.intervalMinutes, + onTurnOn = { + showExplanation = false + if (needsPermissionRequest(ctx)) { + permissionRequest.launch(Manifest.permission.POST_NOTIFICATIONS) + } else { + vm.onPermissionResult(true) + } + }, + onDismiss = { showExplanation = false }, + ) + } +} + +@Composable +private fun Option(label: String, help: String, control: @Composable () -> Unit) { + val t = UnraidTheme.colors + Column(modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(6.dp)) { + Text(label, color = t.muted, style = MaterialTheme.typography.labelLarge) + control() + Text(help, color = t.muted, style = MaterialTheme.typography.bodySmall) + } +} + +@Composable +private fun ExplanationDialog(intervalMinutes: Int, onTurnOn: () -> Unit, onDismiss: () -> Unit) { + val t = UnraidTheme.colors + AlertDialog( + onDismissRequest = onDismiss, + shape = RoundedCornerShape(UnraidDims.radDialog), + containerColor = t.surface2, + titleContentColor = t.text, + textContentColor = t.muted, + title = { Text("Get alerts outside the app?", style = MaterialTheme.typography.titleLarge) }, + text = { + Text( + text = "While this is on, NOVA asks each of your servers about every ${intervalPhrase(intervalMinutes)} " + + "whether something needs attention: new Unraid alerts and warnings, and an array that is not " + + "started or is degraded. The checks go only to your own servers, with the API key you saved, " + + "and a read-only key is enough. They use only https addresses with a trusted certificate; " + + "a server that has only an http address is not checked. Android decides the exact time, so an " + + "alert can come late, sometimes by an hour or more while the phone is idle. Turn this off at " + + "any time and NOVA stops all background checks.", + style = MaterialTheme.typography.bodyMedium.copy(lineHeight = 21.sp), + ) + }, + confirmButton = { UnraidButton(onClick = onTurnOn, label = "Turn on", variant = BtnVariant.Text) }, + dismissButton = { + UnraidButton( + onClick = onDismiss, + label = "Not now", + variant = BtnVariant.Text, + tone = Tone.Neutral, + ) + }, + ) +} + +/** Android 13 and later need the runtime permission; before that the channel or app setting is all there is. */ +private fun needsPermissionRequest(ctx: Context): Boolean = + Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && + ContextCompat.checkSelfPermission(ctx, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED + +private fun notificationSettingsIntent(ctx: Context): Intent = + Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS).putExtra(Settings.EXTRA_APP_PACKAGE, ctx.packageName) + +private fun Context.isBatteryOptimised(): Boolean = + !getSystemService(PowerManager::class.java).isIgnoringBatteryOptimizations(packageName) + +/** Starts [intent]; a phone without a matching app (no browser, no settings page) is not worth a crash. */ +private fun Context.open(intent: Intent) { + try { + startActivity(intent) + } catch (_: ActivityNotFoundException) { + // Nothing to open it with. + } +} + +private fun intervalLabel(minutes: Int): String = when (minutes) { + 60 -> "1 hour" + 180 -> "3 hours" + else -> "$minutes min" +} + +private fun intervalPhrase(minutes: Int): String = when (minutes) { + 60 -> "hour" + 180 -> "3 hours" + else -> "$minutes minutes" +} + +/** "today 14:05", or the date and time for an older check. */ +private fun formatCheckTime(epochMs: Long): String { + val at = Instant.ofEpochMilli(epochMs).atZone(ZoneId.systemDefault()) + val time = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).format(at) + return if (at.toLocalDate() == LocalDate.now(at.zone)) "today $time" else { + DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).format(at) + " " + time + } +} diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/settings/AlertsViewModel.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/settings/AlertsViewModel.kt new file mode 100644 index 0000000..49d240e --- /dev/null +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/settings/AlertsViewModel.kt @@ -0,0 +1,244 @@ +package io.github.nofuturekid.nova.ui.screens.settings + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import dagger.hilt.android.lifecycle.HiltViewModel +import io.github.nofuturekid.nova.data.alerts.Alert +import io.github.nofuturekid.nova.data.alerts.AlertEvaluation +import io.github.nofuturekid.nova.data.alerts.AlertLevel +import io.github.nofuturekid.nova.data.alerts.AlertNotifier +import io.github.nofuturekid.nova.data.alerts.AlertScheduler +import io.github.nofuturekid.nova.data.alerts.AlertSettings +import io.github.nofuturekid.nova.data.alerts.AlertSource +import io.github.nofuturekid.nova.data.alerts.CheckOutcome +import io.github.nofuturekid.nova.data.alerts.CheckRecord +import io.github.nofuturekid.nova.data.alerts.ProbeResult +import io.github.nofuturekid.nova.data.alerts.ServerAlertState +import io.github.nofuturekid.nova.data.alerts.ServerProbe +import io.github.nofuturekid.nova.data.alerts.ServerRef +import io.github.nofuturekid.nova.data.alerts.hasCleartextOnlyAddresses +import io.github.nofuturekid.nova.data.alerts.isBackgroundCheckable +import io.github.nofuturekid.nova.data.alerts.toOutcome +import io.github.nofuturekid.nova.data.model.AttentionSeverity +import io.github.nofuturekid.nova.data.model.AttentionTarget +import io.github.nofuturekid.nova.data.model.NotifImportance +import io.github.nofuturekid.nova.data.model.Notifications +import io.github.nofuturekid.nova.data.model.Server +import io.github.nofuturekid.nova.data.model.UnraidNotification +import io.github.nofuturekid.nova.data.repository.SettingsRepository +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeoutOrNull +import java.time.OffsetDateTime +import javax.inject.Inject + +/** One saved server in the "last check" list: its name, what to say about it and when it was checked. */ +data class ServerCheckLine(val name: String, val text: String, val atEpochMs: Long?) + +data class AlertsUi( + val settings: AlertSettings = AlertSettings(), + /** Android blocks NOVA's notifications and the user needs to know (switch on, or a request was denied). */ + val blocked: Boolean = false, + val servers: List = emptyList(), + val hasDemoServer: Boolean = false, + /** At least one saved server can be checked, so the test action means something. */ + val canTest: Boolean = false, + val testing: Boolean = false, + val testMessage: String? = null, +) + +/** + * The state and actions behind Settings, Notifications (ADR-0048). The screen never touches + * WorkManager itself: switching and changing choices go through [AlertScheduler], which does + * nothing, and does not even ask for WorkManager, while alerts are off. Everything this class + * reads comes from the settings store, so opening the screen with alerts off starts nothing. + */ +@HiltViewModel +class AlertsViewModel @Inject constructor( + private val repo: SettingsRepository, + private val scheduler: AlertScheduler, + private val notifier: AlertNotifier, + private val probe: ServerProbe, +) : ViewModel() { + private val allowed = MutableStateFlow(notifier.canPost()) + + /** The user said no to the permission request, or the switch could not be turned on. */ + private val denied = MutableStateFlow(false) + private val testing = MutableStateFlow(false) + private val testMessage = MutableStateFlow(null) + + private val servers = combine(repo.serverSnapshot, repo.alertStates) { snapshot, states -> + snapshot.servers to states + } + + private val notificationState = combine(allowed, denied, testing, testMessage) { a, d, t, m -> + NotificationState(a, d, t, m) + } + + val state: StateFlow = combine(repo.alertSettings, servers, notificationState) { settings, (list, states), n -> + AlertsUi( + settings = settings, + blocked = !n.allowed && (settings.enabled || n.denied), + servers = list.map { serverCheckLine(it, states[it.id]?.lastCheck) }, + hasDemoServer = list.any { it.isDemo }, + canTest = list.any { it.isBackgroundCheckable() }, + testing = n.testing, + testMessage = n.testMessage, + ) + }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), AlertsUi(blocked = false)) + + /** Called when the screen comes back to the front: the user may have changed Android's settings meanwhile. */ + fun refreshNotificationsAllowed() { + val now = notifier.canPost() + allowed.value = now + if (now) denied.value = false + } + + /** The answer to the system's permission request, or true when none was needed. */ + fun onPermissionResult(granted: Boolean) { + if (granted) turnOn() else { + allowed.value = notifier.canPost() + denied.value = true + } + } + + private fun turnOn() { + viewModelScope.launch { + val chosen = repo.alertSettings.first() + val ok = scheduler.enable(chosen.intervalMinutes, chosen.level, chosen.unmeteredOnly) + allowed.value = notifier.canPost() + denied.value = !ok + testMessage.value = null + } + } + + fun turnOff() { + viewModelScope.launch { + scheduler.disable() + denied.value = false + testMessage.value = null + } + } + + fun setInterval(minutes: Int) = change { it.copy(intervalMinutes = minutes) } + fun setLevel(level: AlertLevel) = change { it.copy(level = level) } + fun setUnmeteredOnly(value: Boolean) = change { it.copy(unmeteredOnly = value) } + + private fun change(edit: (AlertSettings) -> AlertSettings) { + viewModelScope.launch { + val next = edit(repo.alertSettings.first()) + scheduler.update(next.intervalMinutes, next.level, next.unmeteredOnly) + } + } + + /** + * "Send test notification": checks the active server once, right now, through the same probe + * the background job uses (so the https rule and the certificate rules apply), and posts its + * newest unread alert or warning as a test. It reads and posts; it never writes the remembered + * state, so a test cannot make a real alert disappear or appear twice. + */ + fun sendTest() { + if (testing.value) return + viewModelScope.launch { + testing.value = true + testMessage.value = null + testMessage.value = try { + runTest() + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + "Test failed." + } finally { + testing.value = false + } + } + } + + private suspend fun runTest(): String { + val snapshot = repo.serverSnapshot.first() + val server = snapshot.servers.firstOrNull { it.id == snapshot.activeId && it.isBackgroundCheckable() } + ?: snapshot.servers.firstOrNull { it.isBackgroundCheckable() } + ?: return "Test: there is no server to check. The demo server is never checked." + if (!notifier.canPost()) { + allowed.value = false + return "Test: Android blocks notifications for NOVA." + } + val result = withTimeoutOrNull(TEST_TIMEOUT_MS) { probe.probe(server, snapshot.pins[server.id]) } + ?: ProbeResult.Unreachable + if (result !is ProbeResult.Ok) { + return "Test: ${server.name}: ${outcomeText(result.toOutcome()).trimEnd('.')}." + } + val newest = result.notifications?.newestAlertOrWarning() + if (newest == null) { + return if (result.notifications == null) { + "Test: NOVA reached ${server.name}, but could not read its alerts." + } else { + "Test: NOVA reached ${server.name}. No unread alerts or warnings." + } + } + val subject = newest.subject.ifBlank { newest.title }.ifBlank { "Server notification" } + val ref = ServerRef(server.id, server.name) + val posted = notifier.post(ref, AlertEvaluation(ref, listOf(newest.toTestAlert(subject)), 0, ServerAlertState())) + return if (posted) "Test: $subject" else "Test: Android blocked the notification." + } + + private data class NotificationState( + val allowed: Boolean, + val denied: Boolean, + val testing: Boolean, + val testMessage: String?, + ) + + private companion object { + const val TEST_TIMEOUT_MS = 45_000L + } +} + +/** + * What the last-check line says about one server. The current address configuration wins over an + * old record: a server that has only http addresses is never checked, whatever an earlier check + * said, and a "not encrypted" record of a server that has an https address since is out of date. + */ +fun serverCheckLine(server: Server, record: CheckRecord?): ServerCheckLine = when { + server.isDemo -> ServerCheckLine(server.name, "demo server, never checked", null) + server.hasCleartextOnlyAddresses() -> + ServerCheckLine(server.name, outcomeText(CheckOutcome.NotEncrypted), null) + record == null || record.outcome == CheckOutcome.NotEncrypted -> + ServerCheckLine(server.name, "not run yet", null) + else -> ServerCheckLine(server.name, outcomeText(record.outcome), record.atEpochMs) +} + +/** The words for an outcome, shared by the last-check line and the test action. */ +fun outcomeText(outcome: CheckOutcome): String = when (outcome) { + CheckOutcome.Ok -> "OK" + CheckOutcome.Unreachable -> "could not be reached" + CheckOutcome.NotEncrypted -> + "not checked in the background because the connection is not encrypted. An https address is needed." + CheckOutcome.CertificateProblem -> "certificate problem (changed or not trusted), open NOVA to review it" + CheckOutcome.KeyMissing -> "API key missing" + CheckOutcome.KeyUnreadable -> "API key cannot be read, enter it again" + CheckOutcome.Rejected -> "API key refused or request rejected" +} + +private fun Notifications.newestAlertOrWarning(): UnraidNotification? = + items.filter { it.importance == NotifImportance.Alert || it.importance == NotifImportance.Warning } + .maxByOrNull { epochMillis(it.timestamp) ?: Long.MIN_VALUE } + +private fun epochMillis(iso: String?): Long? = + iso?.let { runCatching { OffsetDateTime.parse(it).toInstant().toEpochMilli() }.getOrNull() } + +private fun UnraidNotification.toTestAlert(subject: String) = Alert( + key = "nova-test", + source = AlertSource.Notification, + severity = AttentionSeverity.Critical, + title = "Test: $subject", + text = description, + timestamp = timestamp, + target = AttentionTarget.Notifications, +) diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/settings/SettingsScreen.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/settings/SettingsScreen.kt index 1b8e841..61f0ea8 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/settings/SettingsScreen.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/settings/SettingsScreen.kt @@ -251,6 +251,8 @@ fun SettingsScreen( } } + AlertsSection() + // Updates section is direct-flavor-only (ADR-0040). The // `store` flavor (F-Droid + Play) hides the section entirely; // the underlying ViewModel methods stay compiled but dormant. @@ -485,7 +487,7 @@ private fun formatRelativeAge(epochMs: Long): String { } @Composable -private fun SettingRow(label: String, content: @Composable () -> Unit) { +internal fun SettingRow(label: String, content: @Composable () -> Unit) { val t = UnraidTheme.colors Row(verticalAlignment = Alignment.CenterVertically) { Text(label, color = t.muted, style = MaterialTheme.typography.labelLarge, modifier = Modifier.weight(1f)) @@ -494,7 +496,7 @@ private fun SettingRow(label: String, content: @Composable () -> Unit) { } @Composable -private fun Toggle(value: Boolean, onChange: (Boolean) -> Unit) { +internal fun Toggle(value: Boolean, onChange: (Boolean) -> Unit) { // M3 Switch (ADR-0030 F3): replaces the bespoke clickable Box thumb. // Brings the M3 look + free `Role.Switch`/toggleable a11y (TalkBack // announces "switch"); colours route through the P1-style helper. @@ -506,7 +508,7 @@ private fun Toggle(value: Boolean, onChange: (Boolean) -> Unit) { } @Composable -private fun Segmented( +internal fun Segmented( value: T, options: List, label: (T) -> String, diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/AlertCheckRunnerTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/AlertCheckRunnerTest.kt index 78aac22..54c4900 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/AlertCheckRunnerTest.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/AlertCheckRunnerTest.kt @@ -67,8 +67,10 @@ class AlertCheckRunnerTest { settings.setServers(emptyList()) } + private var clock = 1_000L + private fun runner(probe: ServerProbe = this.probe, timeoutMs: Long = SERVER_CHECK_TIMEOUT_MS) = - AlertCheckRunner(settings, probe, states, notifier, { workCancelled++ }, timeoutMs) + AlertCheckRunner(settings, probe, states, notifier, { workCancelled++ }, timeoutMs, { clock }) private fun check(probe: ServerProbe = this.probe, timeoutMs: Long = SERVER_CHECK_TIMEOUT_MS) = runBlocking { runner(probe, timeoutMs).run() } @@ -231,10 +233,48 @@ class AlertCheckRunnerTest { val checks = check() assertEquals(0, posted().size) - assertEquals(before, runBlocking { states.get(tower.id) }) + // The last-check record is new; what was reported and what holds is exactly as before. + assertEquals(before.copy(lastCheck = null), runBlocking { states.get(tower.id) }.copy(lastCheck = null)) assertEquals(ProbeResult.Unreachable, checks.single().result) } + @Test fun every_check_records_when_and_how_it_ended_for_the_settings_line() { + // WHY: the settings screen can only tell the user "Tower: could not be reached" if the check + // wrote it down, and an outage must not read as "OK" or as "never ran". + val outcomes = listOf( + ProbeResult.Unreachable to CheckOutcome.Unreachable, + ProbeResult.NotEncrypted to CheckOutcome.NotEncrypted, + ProbeResult.CertificateProblem to CheckOutcome.CertificateProblem, + ProbeResult.KeyMissing to CheckOutcome.KeyMissing, + ProbeResult.KeyUndecryptable to CheckOutcome.KeyUnreadable, + ProbeResult.Rejected("nope") to CheckOutcome.Rejected, + okResult(emptyList()) to CheckOutcome.Ok, + ) + outcomes.forEach { (result, outcome) -> + clock += 60_000 + probe.answer(tower.id, result) + + check() + + assertEquals(CheckRecord(clock, outcome), runBlocking { states.get(tower.id) }.lastCheck) + } + } + + @Test fun recording_the_check_changes_nothing_that_is_posted_or_remembered() { + // WHY: the record is for the settings line only. A new id still posts exactly once, and the + // ids remembered after a check with a record are the same as the rules produce. + baseline("n1") + probe.answer(tower.id, okResult(listOf(unraidNotification("n1"), unraidNotification("n2")))) + + check() + check() + + assertEquals(1, posted().size) + val state = runBlocking { states.get(tower.id) } + assertEquals(listOf("n1", "n2"), state.seenNotificationIds) + assertTrue(state.notificationsBaselined) + } + @Test fun every_failure_kind_posts_nothing() { baseline("n1") val failures = listOf( diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/settings/AlertsCheckLineTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/settings/AlertsCheckLineTest.kt new file mode 100644 index 0000000..ba3888a --- /dev/null +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/settings/AlertsCheckLineTest.kt @@ -0,0 +1,57 @@ +package io.github.nofuturekid.nova.ui.screens.settings + +import io.github.nofuturekid.nova.data.alerts.CheckOutcome +import io.github.nofuturekid.nova.data.alerts.CheckRecord +import io.github.nofuturekid.nova.data.alerts.testServer +import io.github.nofuturekid.nova.data.demo.DemoFixtures +import io.github.nofuturekid.nova.data.model.Server +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * WHY: the last-check line is what tells a user whether alerts really work for each server. It must + * follow the server's current addresses, not only an old record: an http-only server is never + * checked in the background, so no earlier "OK" may make it look covered. + */ +class AlertsCheckLineTest { + private val tower = testServer("srv-tower", "Tower") + private val plain = Server("srv-plain", "Plain", "plain.example", "http://plain.example", "") + + @Test fun every_outcome_has_its_own_words() { + val texts = CheckOutcome.entries.map { outcomeText(it) } + assertEquals("two outcomes must never read the same", texts.size, texts.toSet().size) + } + + @Test fun a_checked_server_shows_the_outcome_and_the_time() { + val line = serverCheckLine(tower, CheckRecord(5_000, CheckOutcome.Unreachable)) + + assertEquals("could not be reached", line.text) + assertEquals(5_000L, line.atEpochMs) + } + + @Test fun a_server_never_checked_says_so() { + assertEquals("not run yet", serverCheckLine(tower, null).text) + } + + @Test fun an_http_only_server_is_not_encrypted_whatever_an_old_record_says() { + val line = serverCheckLine(plain, CheckRecord(5_000, CheckOutcome.Ok)) + + assertTrue(line.text.contains("connection is not encrypted")) + assertTrue("one sentence says what is needed", line.text.contains("An https address is needed.")) + assertNull("it was not checked, so there is no time", line.atEpochMs) + } + + @Test fun a_not_encrypted_record_of_a_server_that_has_https_now_is_out_of_date() { + // The user added an https address after the last check. + assertEquals("not run yet", serverCheckLine(tower, CheckRecord(5_000, CheckOutcome.NotEncrypted)).text) + } + + @Test fun the_demo_server_is_never_checked() { + val line = serverCheckLine(DemoFixtures.server, CheckRecord(5_000, CheckOutcome.Ok)) + + assertEquals("demo server, never checked", line.text) + assertNull(line.atEpochMs) + } +} diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/settings/AlertsSectionTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/settings/AlertsSectionTest.kt new file mode 100644 index 0000000..1c59078 --- /dev/null +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/settings/AlertsSectionTest.kt @@ -0,0 +1,419 @@ +package io.github.nofuturekid.nova.ui.screens.settings + +import android.Manifest +import android.app.Application +import android.app.NotificationManager +import android.content.Context +import android.content.pm.PackageManager +import androidx.activity.ComponentActivity +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.ui.Modifier +import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.test.isToggleable +import androidx.compose.ui.test.junit4.createAndroidComposeRule +import androidx.compose.ui.test.onAllNodesWithText +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.work.NetworkType +import androidx.work.WorkInfo +import androidx.work.WorkManager +import androidx.work.impl.WorkManagerImpl +import androidx.work.testing.WorkManagerTestInitHelper +import io.github.nofuturekid.nova.data.alerts.ALERT_WORK_NAME +import io.github.nofuturekid.nova.data.alerts.AlertLevel +import io.github.nofuturekid.nova.data.alerts.AlertNotifier +import io.github.nofuturekid.nova.data.alerts.AlertScheduler +import io.github.nofuturekid.nova.data.alerts.AlertSettings +import io.github.nofuturekid.nova.data.alerts.CheckOutcome +import io.github.nofuturekid.nova.data.alerts.CheckRecord +import io.github.nofuturekid.nova.data.alerts.FakeServerProbe +import io.github.nofuturekid.nova.data.alerts.InMemoryAlertStateStore +import io.github.nofuturekid.nova.data.alerts.ProbeResult +import io.github.nofuturekid.nova.data.alerts.ServerAlertState +import io.github.nofuturekid.nova.data.alerts.okResult +import io.github.nofuturekid.nova.data.alerts.testServer +import io.github.nofuturekid.nova.data.alerts.unraidNotification +import io.github.nofuturekid.nova.data.demo.DemoFixtures +import io.github.nofuturekid.nova.data.local.SettingsStore +import io.github.nofuturekid.nova.data.model.Server +import io.github.nofuturekid.nova.data.repository.SettingsRepository +import io.github.nofuturekid.nova.ui.theme.ThemeMode +import io.github.nofuturekid.nova.ui.theme.UnraidTheme +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode +import java.util.concurrent.TimeUnit + +/** + * The real Settings, Notifications section on Robolectric, with the real settings store, the real + * notifier and the real WorkManager test driver. + * + * WHY: this section is the only door to background work. These tests would fail if the switch + * scheduled anything before Android granted the permission, if a denial left the switch on or said + * nothing, if switching off left a job or kept talking to WorkManager, if a changed choice did not + * reach the job, if a server without an https address looked checked, or if merely opening the + * screen with alerts off initialised WorkManager. + */ +@RunWith(AndroidJUnit4::class) +@GraphicsMode(GraphicsMode.Mode.NATIVE) +@Config(sdk = [35], qualifiers = "w432dp-h2400dp-night-400dpi") +class AlertsSectionTest { + + @get:Rule + val rule = createAndroidComposeRule() + + private lateinit var ctx: Context + private lateinit var settings: SettingsStore + private lateinit var notifier: AlertNotifier + private lateinit var nm: NotificationManager + private val states = InMemoryAlertStateStore() + private val probe = FakeServerProbe() + private var workManagerAsked = 0 + + private val tower = testServer("srv-tower", "Tower") + private val plain = Server("srv-plain", "Plain", "plain.example", "http://plain.example", "") + + @Before fun setUp() = runBlocking { + ctx = ApplicationProvider.getApplicationContext() + WorkManagerImpl.setDelegate(null) + settings = SettingsStore(ctx) + settings.setAlertSettings(AlertSettings()) + settings.setServers(emptyList()) + settings.clearAllAlertStates() + notifier = AlertNotifier(ctx) + nm = ctx.getSystemService(NotificationManager::class.java) + shadowOf(nm).setNotificationsEnabled(true) + nm.cancelAll() + shadowOf(ctx as Application).denyPermissions(Manifest.permission.POST_NOTIFICATIONS) + } + + /** Settings and the work database outlive a test inside one JVM; the next class must find alerts off. */ + @After fun tearDown() = runBlocking { + settings.setAlertSettings(AlertSettings()) + settings.setServers(emptyList()) + settings.clearAllAlertStates() + WorkManagerImpl.setDelegate(null) + } + + /** A scheduler on the real WorkManager test driver that counts how often WorkManager is asked for. */ + private fun scheduler(): AlertScheduler { + WorkManagerTestInitHelper.initializeTestWorkManager(ctx) + return AlertScheduler(settings, states, notifier) { + workManagerAsked++ + WorkManager.getInstance(ctx) + } + } + + private fun viewModel(scheduler: AlertScheduler) = + AlertsViewModel(SettingsRepository(settings), scheduler, notifier, probe) + + private fun show(vm: AlertsViewModel) = rule.setContent { + UnraidTheme(themeMode = ThemeMode.Dark) { + Column(Modifier.verticalScroll(rememberScrollState())) { AlertsSection(vm) } + } + } + + /** + * Conditions must not block on the settings store: the test thread is the main thread, and a + * store write started by the view model runs its transform on the main thread, so a blocking + * read here deadlocks it. Wait for what the screen shows instead, and read the store only once + * the screen has settled. + */ + private fun waitUntil(condition: () -> Boolean) = rule.waitUntil(timeoutMillis = 10_000) { + // The view model's coroutines run on the main thread, which is this one: let them run between checks. + rule.waitForIdle() + condition() + } + + private fun waitForText(text: String, substring: Boolean = false) = waitUntil { + rule.onAllNodesWithText(text, substring = substring).fetchSemanticsNodes().isNotEmpty() + } + + private fun enabled() = runBlocking { settings.alertSettings.first().enabled } + + private fun works(): List = + WorkManager.getInstance(ctx).getWorkInfosForUniqueWork(ALERT_WORK_NAME).get().filter { !it.state.isFinished } + + /** Alerts on, one server, one scheduled job. Returns the scheduler: a second one would reset the WorkManager driver. */ + private fun switchOnWithOneServer(): AlertScheduler { + val scheduler = scheduler() + runBlocking { + settings.setServers(listOf(tower)) + assertTrue(scheduler.enable()) + } + return scheduler + } + + private fun answerPermissionRequest(granted: Boolean) { + val request = shadowOf(rule.activity).lastRequestedPermission + rule.runOnUiThread { + @Suppress("DEPRECATION") + rule.activity.onRequestPermissionsResult( + request.requestCode, + request.requestedPermissions, + intArrayOf(if (granted) PackageManager.PERMISSION_GRANTED else PackageManager.PERMISSION_DENIED), + ) + } + } + + // WHY: the maintainer's rule is that with the switch off NOVA does nothing in the background, and + // WorkManager is initialised on demand for exactly that reason. Everything the screen reads and every + // action that is a no-op while off must leave WorkManager uninitialised, on the production scheduler. + @Test fun opening_the_section_with_alerts_off_does_not_initialise_workmanager() { + runBlocking { settings.setServers(listOf(tower)) } + val vm = AlertsViewModel(SettingsRepository(settings), AlertScheduler(ctx, settings, states, notifier), notifier, probe) + + show(vm) + waitForText("Off. NOVA does nothing in the background.") + vm.turnOff() + vm.setInterval(60) + vm.setLevel(AlertLevel.AlertsOnly) + vm.setUnmeteredOnly(true) + vm.refreshNotificationsAllowed() + rule.waitForIdle() + + assertFalse("WorkManager must not be initialised", WorkManager.isInitialized()) + rule.onNodeWithText("Check every").assertDoesNotExist() + assertFalse(enabled()) + } + + // WHY: on Android 13 and later notifications are off until the user allows them; a job scheduled + // before that would run and could never be shown. + @Test fun switching_on_without_the_permission_requests_it_and_schedules_nothing_until_granted() { + runBlocking { settings.setServers(listOf(tower)) } + val vm = viewModel(scheduler()) + show(vm) + waitForText("Off. NOVA does nothing in the background.") + + rule.onAllNodes(isToggleable())[0].performClick() + waitForText("Get alerts outside the app?") + rule.onNodeWithText("Turn on").performClick() + rule.waitForIdle() + + val request = shadowOf(rule.activity).lastRequestedPermission + assertEquals(listOf(Manifest.permission.POST_NOTIFICATIONS), request.requestedPermissions.toList()) + assertFalse("the switch stays off until the answer", enabled()) + assertEquals("nothing is scheduled before the permission is granted", 0, workManagerAsked) + + shadowOf(ctx as Application).grantPermissions(Manifest.permission.POST_NOTIFICATIONS) + answerPermissionRequest(granted = true) + waitForText("On. NOVA checks your servers about every 30 minutes.") + waitUntil { works().size == 1 } + assertTrue(enabled()) + } + + // WHY: a user who says no must see why nothing happened and how to fix it, and the switch must not + // claim alerts are on. + @Test fun denying_the_permission_leaves_the_switch_off_and_explains() { + runBlocking { settings.setServers(listOf(tower)) } + shadowOf(nm).setNotificationsEnabled(false) + val vm = viewModel(scheduler()) + show(vm) + waitForText("Off. NOVA does nothing in the background.") + + rule.onAllNodes(isToggleable())[0].performClick() + waitForText("Turn on") + rule.onNodeWithText("Turn on").performClick() + rule.waitForIdle() + answerPermissionRequest(granted = false) + + waitForText("Android blocks notifications for NOVA", substring = true) + rule.onNodeWithText("Open notification settings").assertExists() + rule.onNodeWithText("Off. NOVA does nothing in the background.").assertExists() + assertFalse(enabled()) + assertEquals(0, workManagerAsked) + assertTrue(works().isEmpty()) + } + + @Test fun not_now_in_the_explanation_changes_nothing() { + runBlocking { settings.setServers(listOf(tower)) } + val vm = viewModel(scheduler()) + show(vm) + waitForText("Off. NOVA does nothing in the background.") + + rule.onAllNodes(isToggleable())[0].performClick() + waitForText("Get alerts outside the app?") + rule.onNodeWithText("Not now").performClick() + rule.waitForIdle() + + rule.onNodeWithText("Get alerts outside the app?").assertDoesNotExist() + assertNull(shadowOf(rule.activity).lastRequestedPermission) + assertFalse(enabled()) + assertEquals(0, workManagerAsked) + } + + // WHY: "switch off" has to mean off: no job, nothing left posted, and a screen that does not poke + // WorkManager again (that would create its database and alarm after the user said no background work). + @Test fun switching_off_cancels_the_work_and_the_screen_makes_no_workmanager_call_afterwards() { + val vm = viewModel(switchOnWithOneServer()) + show(vm) + waitForText("Check every") + assertEquals(1, works().size) + + rule.onAllNodes(isToggleable())[0].performClick() + waitForText("Off. NOVA does nothing in the background.") + waitUntil { works().isEmpty() } + val askedWhenOff = workManagerAsked + + vm.turnOff() + vm.setInterval(60) + vm.setUnmeteredOnly(true) + vm.refreshNotificationsAllowed() + rule.waitForIdle() + + assertEquals("no WorkManager call once alerts are off", askedWhenOff, workManagerAsked) + rule.onNodeWithText("Check every").assertDoesNotExist() + assertTrue(works().isEmpty()) + } + + // WHY: a choice that does not reach the job is a lie on screen: "every hour" while Android still + // runs the old period, or "Wi-Fi only" while the job also runs on mobile data. + @Test fun changing_the_interval_or_the_network_reschedules_the_existing_work() { + val vm = viewModel(switchOnWithOneServer()) + show(vm) + waitForText("Check every") + + rule.onNodeWithText("1 hour").performClick() + waitUntil { works().singleOrNull()?.periodicityInfo?.repeatIntervalMillis == TimeUnit.MINUTES.toMillis(60) } + waitForText("On. NOVA checks your servers about every hour.") + + rule.onAllNodes(isToggleable())[1].performClick() + waitUntil { works().singleOrNull()?.constraints?.requiredNetworkType == NetworkType.UNMETERED } + + assertEquals("still one unique job", 1, works().size) + assertEquals(60, runBlocking { settings.alertSettings.first() }.intervalMinutes) + assertTrue(runBlocking { settings.alertSettings.first() }.unmeteredOnly) + } + + // WHY: a server with only an http address is skipped in the background. The user must be told, and told + // what fixes it, instead of reading a silent "OK". + @Test fun a_server_that_is_not_encrypted_says_so_and_what_it_needs() { + runBlocking { + settings.setServers(listOf(plain, tower)) + settings.setAlertSettings(AlertSettings(enabled = true)) + // Even a stale "OK" record must not make an http-only server look checked. + settings.setAlertState(plain.id, ServerAlertState(lastCheck = CheckRecord(1_000, CheckOutcome.Ok))) + } + show(viewModel(scheduler())) + + waitForText("Not checked in the background because the connection is not encrypted.", substring = true) + rule.onNodeWithText("An https address is needed.", substring = true).assertExists() + rule.onNodeWithText("Plain").assertExists() + } + + @Test fun every_failure_outcome_reads_differently_on_the_last_check_line() { + runBlocking { + settings.setServers(listOf(tower)) + settings.setAlertSettings(AlertSettings(enabled = true)) + } + val vm = viewModel(scheduler()) + show(vm) + val expected = mapOf( + CheckOutcome.Unreachable to "Could not be reached", + CheckOutcome.CertificateProblem to "Certificate problem", + CheckOutcome.KeyMissing to "API key missing", + CheckOutcome.KeyUnreadable to "API key cannot be read", + CheckOutcome.Rejected to "API key refused", + CheckOutcome.Ok to "OK", + ) + expected.forEach { (outcome, text) -> + runBlocking { settings.setAlertState(tower.id, ServerAlertState(lastCheck = CheckRecord(1_000, outcome))) } + waitForText(text, substring = true) + } + } + + // WHY: the demo server has fictional data and no address; it is never checked, and the screen must + // not suggest otherwise, with alerts off or on. + @Test fun the_demo_server_is_named_as_never_checked_and_cannot_be_tested() { + runBlocking { settings.setServers(listOf(DemoFixtures.server)) } + val vm = viewModel(scheduler()) + show(vm) + + waitForText("The demo server is never checked.", substring = true) + assertEquals(0, workManagerAsked) + + runBlocking { settings.setAlertSettings(AlertSettings(enabled = true)) } + waitForText("Send test notification") + rule.onNodeWithText("Send test notification").assertIsNotEnabled() + rule.onNodeWithText("Demo server, never checked", substring = true).assertExists() + assertEquals("the demo server is not a server to schedule for", 0, probe.probed.size) + } + + // WHY: the test action proves key, network, channel and tap target on a real server, so it must show + // a real notification; and it must never write the remembered state, or a test could swallow a real + // alert (marked as seen) or repeat one. + @Test fun the_test_action_posts_the_newest_alert_and_does_not_touch_the_remembered_state() { + val remembered = ServerAlertState( + notificationsBaselined = true, seenNotificationIds = listOf("n1"), conditionsBaselined = true, + lastCheck = CheckRecord(1_000, CheckOutcome.Ok), + ) + runBlocking { + settings.setServers(listOf(tower)) + settings.setAlertSettings(AlertSettings(enabled = true)) + settings.setAlertState(tower.id, remembered) + } + probe.answer( + tower.id, + okResult( + listOf( + unraidNotification("n1", subject = "Old alert", timestamp = "2026-11-13T08:00:00.000Z"), + unraidNotification("n2", subject = "Disk 1 is hot", timestamp = "2026-11-13T10:00:00.000Z"), + ), + ), + ) + show(viewModel(scheduler())) + waitForText("Send test notification") + + rule.onNodeWithText("Send test notification").performClick() + + waitForText("Test: Disk 1 is hot") + val posted = nm.activeNotifications.single() + assertEquals(tower.id, posted.tag) + assertEquals(remembered, runBlocking { settings.alertStateFor(tower.id) }) + } + + @Test fun the_test_action_on_a_server_that_cannot_be_reached_says_so_and_posts_nothing() { + runBlocking { + settings.setServers(listOf(tower)) + settings.setAlertSettings(AlertSettings(enabled = true)) + } + probe.answer(tower.id, ProbeResult.Unreachable) + show(viewModel(scheduler())) + waitForText("Send test notification") + + rule.onNodeWithText("Send test notification").performClick() + + waitForText("Test: Tower: could not be reached.") + assertTrue(nm.activeNotifications.isEmpty()) + } + + @Test fun the_test_action_with_no_unread_alerts_says_the_server_was_reached() { + runBlocking { + settings.setServers(listOf(tower)) + settings.setAlertSettings(AlertSettings(enabled = true)) + } + probe.answer(tower.id, okResult(emptyList())) + show(viewModel(scheduler())) + waitForText("Send test notification") + + rule.onNodeWithText("Send test notification").performClick() + + waitForText("Test: NOVA reached Tower. No unread alerts or warnings.") + assertTrue(nm.activeNotifications.isEmpty()) + } +} diff --git a/docs/adr/0048-opt-in-background-alert-checks.md b/docs/adr/0048-opt-in-background-alert-checks.md index 2502841..b9c017c 100644 --- a/docs/adr/0048-opt-in-background-alert-checks.md +++ b/docs/adr/0048-opt-in-background-alert-checks.md @@ -1,6 +1,6 @@ # ADR-0048: Opt-in background alert checks -- **Status**: Accepted (2026-11-13). Amends ADR-0017. The decision logic and its stored state are built first; the background job, the settings screen and the notifications follow in later changes (#321). +- **Status**: Accepted (2026-11-13). Amends ADR-0017. Implemented in full (#321): the decision logic and its stored state, the background job and the notifications, and the Settings section that switches it on. Two rules added after a security check are in the addendum below. - **Date**: 2026-11-13 - **Tags**: data, security, performance, notifications @@ -35,6 +35,22 @@ What is decided here, and what this first change implements: Planned for the following changes, recorded here so the picture is complete: a periodic WorkManager job (every 30 minutes by default, 15 minutes to 3 hours selectable) initialised on demand so that WorkManager is never touched while the switch is off; the two existing read-only queries over one connection; fail-closed certificate trust and no prompts in the background; no foreground service, no exact alarms, no battery-optimisation exemption request; `FOREGROUND_SERVICE` stripped from the merged manifest; `POST_NOTIFICATIONS` asked for only when the user turns the switch on. +## Addendum (2026-11-13): two rules from the security check, and what the screen says + +A security check of the first implementation found two things that the rules above did not settle. Both are decided here and apply to everything that checks a server in the background. + +1. **Only verified https, no redirects.** The background check contacts a server only at an https address with verified trust: the system's certificates, or, for the local address, the certificate the user pinned. A plain-http address is never contacted in the background, because nobody is looking at the phone and the API key would travel in clear text to whatever answers at that name. A server that has no https address is not checked and gets its own outcome, `NotEncrypted`; it is decided before the key is read, a client is built or a request is sent. The background HTTP client follows no redirect and opens no cleartext connection, so an answer that redirects ends the check as rejected instead of moving the key to another host or down to http. The in-app screens are not affected. +2. **The demo server is never checked.** The demo entry (ADR-0050) has no address and no key. It is skipped by the check and does not count as a server for scheduling: with only the demo entry left, no job exists. + +The Settings section states both rules, because a user must be able to tell that alerts do not cover a server: the explanation before the switch says that only https addresses with a trusted certificate are checked, a server with only an http address shows "not checked in the background because the connection is not encrypted. An https address is needed." under its name, and the demo server is named as never checked. + +What the screen adds, without changing what is notified: + +- **Last-check record.** After every check the runner stores, in that server's alert state, the time and the outcome (OK, could not be reached, not encrypted, certificate problem, API key missing, API key cannot be read, refused or rejected). It is read by the Settings screen only; the rules never look at it. It is cleared with the rest of the state when alerts are switched off. +- **Permission flow.** Switching on opens the explanation; "Turn on" asks for `POST_NOTIFICATIONS` on Android 13 and later; only a granted answer schedules anything. A denial leaves the switch off and shows that Android blocks notifications for NOVA, with a button to Android's notification settings. On older Android the same line appears when notifications are blocked for the app. The line is re-evaluated when the screen comes back to the front. +- **Nothing is read from WorkManager.** The screen takes everything from the settings store and changes choices only through `AlertScheduler`, which does not ask for WorkManager while alerts are off; opening Settings with alerts off leaves WorkManager uninitialised. +- **Test notification.** A button runs the same probe once for the active server, foreground and on request, and posts its newest unread alert or warning as a test. It never writes the remembered state. + ## Consequences **Positive** diff --git a/docs/privacy/POLICY.md b/docs/privacy/POLICY.md index 80c158b..9786353 100644 --- a/docs/privacy/POLICY.md +++ b/docs/privacy/POLICY.md @@ -1,6 +1,6 @@ # Privacy Policy — NOVA -**Effective:** 2026-11-10 +**Effective:** 2026-11-13 NOVA is an open-source Android client for Unraid® servers, published under the GPL v3 license. This policy describes what data the app processes, where it goes, and what you can do about it. @@ -12,6 +12,7 @@ NOVA accesses the following on your device: - **Your server's network addresses** (local URL, remote URL, name). Stored locally in per-app DataStore. Used only to reach your server. - **Your theme preferences** (accent colour, density, layout choices). Stored locally in per-app DataStore. - **Pinned certificate fingerprints** (only if you enable "Trust self-signed certificate" for a server's local connection): the SHA-256 fingerprint of that server's certificate, stored per server in per-app DataStore and excluded from cloud backup and device transfer. +- **Alert state** (only while you use "Alerts from your servers"): per server, the ids of the Unraid notifications NOVA has already looked at, which array conditions held at the last check, and the time and result of the last check. Stored locally in per-app DataStore, excluded from cloud backup and device transfer, and deleted when you switch the alerts off. ## Data the app sends @@ -26,6 +27,8 @@ NOVA initiates network requests to: - **Container icon hosts** (both flavors). The Docker tab and container details show each container's icon. The icon URL is supplied by your own Unraid server (from the container's template), and is usually hosted by a third party chosen by the template author — for example `raw.githubusercontent.com`, `cdn.jsdelivr.net` or `github.com`. The app fetches these URLs directly, so those hosts see your IP address and the standard request headers. NOVA never adds credentials or identifiers to these requests, and decides neither which hosts are contacted nor which icons exist: that comes from the templates on your server. +- **Your own Unraid server, in the background, only while you have switched on "Alerts from your servers"** (Settings → Notifications; off by default). About every 15 minutes to 3 hours (your choice; Android decides the exact time), NOVA asks each of your servers, in the background, for its unread alerts and warnings and for the state of its array, with the API key you saved for it. These requests go only to your own servers, and only to their https addresses: an address that is plain http is never contacted in the background, the connection must be verified (a certificate your phone trusts, or the one you pinned for the local address), and redirects are not followed. The demo server is never contacted. NOVA contacts no other host for this, and nothing is sent in the background while the switch is off. + The app does **not** send data to any other service. No analytics, no telemetry, no crash reporting, no advertising SDKs, no third-party authentication providers. ## What's not collected @@ -35,7 +38,7 @@ The app does **not** send data to any other service. No analytics, no telemetry, - No advertising IDs - No location data - No contacts, phone state, or calendar access -- No background tracking of any kind +- No background tracking of any kind. The only background work is the optional server check described under "Data the app sends", and it exists only while you have switched it on ## Backup behaviour @@ -47,6 +50,8 @@ NOVA declares these Android permissions (visible in the app's permission list un - **`INTERNET`** — required to reach your Unraid server, container icon hosts and (`direct` flavor) GitHub - **`ACCESS_NETWORK_STATE`** — lets the app check whether a network is available +- **`POST_NOTIFICATIONS`** — shows the alerts of "Alerts from your servers". On Android 13 and later NOVA asks for it only when you switch the alerts on; if you refuse, the alerts stay off +- **`WAKE_LOCK`** and **`RECEIVE_BOOT_COMPLETED`** — added by Android's WorkManager library, which runs the optional server check. `WAKE_LOCK` keeps the phone awake for the few seconds a check takes; `RECEIVE_BOOT_COMPLETED` lets the schedule resume after a restart. Both are present in every install, but they do something only while the alerts are switched on NOVA does not declare `REQUEST_INSTALL_PACKAGES` in any flavor: it never installs apps itself. Updates of the GitHub APK are downloaded and opened by your browser and Android's installer. (Versions up to 0.1.46 did declare it, in the GitHub APK only.) diff --git a/fastlane/metadata/android/en-US/full_description.txt b/fastlane/metadata/android/en-US/full_description.txt index f319876..9370e6c 100644 --- a/fastlane/metadata/android/en-US/full_description.txt +++ b/fastlane/metadata/android/en-US/full_description.txt @@ -18,6 +18,8 @@ Features: * VMs: state with start/stop/pause/resume * Multiple servers with local/remote address each * Notifications: Unraid notifications with Unread/Archived tabs +* Optional alerts outside the app (off by default): background checks of + your own servers over https, for new alerts and warnings * Server plugins: read-only inventory + install-operation history * Network interfaces: read-only NIC inventory (IPv4/IPv6 + hardware) diff --git a/site/index.html b/site/index.html index d6c448c..1acca32 100644 --- a/site/index.html +++ b/site/index.html @@ -198,6 +198,17 @@

Multiple servers

Notifications

Unraid notifications with Unread and Archived tabs.

+
  • +

    Alerts outside the app

    +

    + Optional and off by default. NOVA can check your servers in the + background and notify you of new Unraid alerts and warnings and + of an array that is not started or is degraded. See + the README. +

    +
  • Plugins and network

    @@ -448,6 +459,19 @@

    Your server

    addresses you configured.

  • +
  • +

    Background checks (optional)

    +

    + Only while you have switched on “Alerts from your + servers” (off by default), NOVA asks each of your servers + for its unread alerts and its array state, in the background, + every 15 minutes to 3 hours as you choose. These requests go + only to your own servers, only to https addresses with a + verified certificate, and with no redirect followed. The demo + server is never contacted. With the switch off, nothing runs + in the background. +

    +
  • Container icons

    From 110bddd9b00b91b320b26005c3fd32d44766dd83 Mon Sep 17 00:00:00 2001 From: Thomas Kroll Date: Fri, 13 Nov 2026 22:23:08 +0100 Subject: [PATCH 06/11] address review findings - Settings, Notifications: say so when the user switched off the "Server alerts" or "Server warnings" channel (AlertNotifier.blockedChannel, read only), with the same button to Android's notification settings. - Switching alerts off cancels a running test and a test that finishes after the switch is off posts nothing. - Robolectric tests for both. Co-Authored-By: Claude Sonnet 5.5 --- .../nova/data/alerts/AlertNotifier.kt | 9 ++++ .../nova/ui/screens/settings/AlertsSection.kt | 7 ++- .../ui/screens/settings/AlertsViewModel.kt | 18 +++++-- .../ui/screens/settings/AlertsSectionTest.kt | 52 +++++++++++++++++++ 4 files changed, 81 insertions(+), 5 deletions(-) diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/data/alerts/AlertNotifier.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/data/alerts/AlertNotifier.kt index 0490c48..6ea4a88 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/data/alerts/AlertNotifier.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/data/alerts/AlertNotifier.kt @@ -52,6 +52,15 @@ class AlertNotifier @Inject constructor( /** False when the user (or Android 13+, without the permission) blocks NOVA's notifications. */ fun canPost(): Boolean = compat.areNotificationsEnabled() + /** + * True when the user switched off one of NOVA's two channels in Android's settings. Read-only: + * the worker posts as before, Android just drops what goes into such a channel. A channel that + * does not exist yet is not blocked. + */ + fun blockedChannel(): Boolean = listOf(ALERTS_CHANNEL_ID, WARNINGS_CHANNEL_ID).any { + compat.getNotificationChannel(it)?.importance == NotificationManager.IMPORTANCE_NONE + } + /** Creates the two channels. Safe to call again: an existing channel is left as the user set it. */ fun ensureChannels() { compat.createNotificationChannel( diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/settings/AlertsSection.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/settings/AlertsSection.kt index 33da5bc..de1e0d1 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/settings/AlertsSection.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/settings/AlertsSection.kt @@ -110,9 +110,12 @@ fun AlertsSection(vm: AlertsViewModel = hiltViewModel()) { Toggle(value = settings.enabled, onChange = { on -> if (on) showExplanation = true else vm.turnOff() }) } - if (ui.blocked) { + if (ui.blocked || ui.channelBlocked) { Text( - text = if (settings.enabled) { + text = if (ui.channelBlocked) { + "Android blocks NOVA's \"Server alerts\" or \"Server warnings\" notifications, so those " + + "alerts are not shown. Allow them in Android's settings." + } else if (settings.enabled) { "Android blocks notifications for NOVA, so no alert can be shown and the checks are paused. " + "Allow notifications in Android's settings." } else { diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/settings/AlertsViewModel.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/settings/AlertsViewModel.kt index 49d240e..6c8cfd9 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/settings/AlertsViewModel.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/settings/AlertsViewModel.kt @@ -27,6 +27,7 @@ import io.github.nofuturekid.nova.data.model.Server import io.github.nofuturekid.nova.data.model.UnraidNotification import io.github.nofuturekid.nova.data.repository.SettingsRepository import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow @@ -45,6 +46,8 @@ data class AlertsUi( val settings: AlertSettings = AlertSettings(), /** Android blocks NOVA's notifications and the user needs to know (switch on, or a request was denied). */ val blocked: Boolean = false, + /** Alerts are on and Android allows NOVA, but the user switched off one of its two channels. */ + val channelBlocked: Boolean = false, val servers: List = emptyList(), val hasDemoServer: Boolean = false, /** At least one saved server can be checked, so the test action means something. */ @@ -67,6 +70,8 @@ class AlertsViewModel @Inject constructor( private val probe: ServerProbe, ) : ViewModel() { private val allowed = MutableStateFlow(notifier.canPost()) + private val channelBlocked = MutableStateFlow(notifier.blockedChannel()) + private var testJob: Job? = null /** The user said no to the permission request, or the switch could not be turned on. */ private val denied = MutableStateFlow(false) @@ -77,14 +82,15 @@ class AlertsViewModel @Inject constructor( snapshot.servers to states } - private val notificationState = combine(allowed, denied, testing, testMessage) { a, d, t, m -> - NotificationState(a, d, t, m) + private val notificationState = combine(allowed, channelBlocked, denied, testing, testMessage) { a, c, d, t, m -> + NotificationState(a, c, d, t, m) } val state: StateFlow = combine(repo.alertSettings, servers, notificationState) { settings, (list, states), n -> AlertsUi( settings = settings, blocked = !n.allowed && (settings.enabled || n.denied), + channelBlocked = settings.enabled && n.allowed && n.channelBlocked, servers = list.map { serverCheckLine(it, states[it.id]?.lastCheck) }, hasDemoServer = list.any { it.isDemo }, canTest = list.any { it.isBackgroundCheckable() }, @@ -97,6 +103,7 @@ class AlertsViewModel @Inject constructor( fun refreshNotificationsAllowed() { val now = notifier.canPost() allowed.value = now + channelBlocked.value = notifier.blockedChannel() if (now) denied.value = false } @@ -113,12 +120,15 @@ class AlertsViewModel @Inject constructor( val chosen = repo.alertSettings.first() val ok = scheduler.enable(chosen.intervalMinutes, chosen.level, chosen.unmeteredOnly) allowed.value = notifier.canPost() + channelBlocked.value = notifier.blockedChannel() denied.value = !ok testMessage.value = null } } fun turnOff() { + testJob?.cancel() + testJob = null viewModelScope.launch { scheduler.disable() denied.value = false @@ -145,7 +155,7 @@ class AlertsViewModel @Inject constructor( */ fun sendTest() { if (testing.value) return - viewModelScope.launch { + testJob = viewModelScope.launch { testing.value = true testMessage.value = null testMessage.value = try { @@ -182,6 +192,7 @@ class AlertsViewModel @Inject constructor( "Test: NOVA reached ${server.name}. No unread alerts or warnings." } } + if (!repo.alertSettings.first().enabled) return "Test cancelled: alerts are off." val subject = newest.subject.ifBlank { newest.title }.ifBlank { "Server notification" } val ref = ServerRef(server.id, server.name) val posted = notifier.post(ref, AlertEvaluation(ref, listOf(newest.toTestAlert(subject)), 0, ServerAlertState())) @@ -190,6 +201,7 @@ class AlertsViewModel @Inject constructor( private data class NotificationState( val allowed: Boolean, + val channelBlocked: Boolean, val denied: Boolean, val testing: Boolean, val testMessage: String?, diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/settings/AlertsSectionTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/settings/AlertsSectionTest.kt index 1c59078..06e7308 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/settings/AlertsSectionTest.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/settings/AlertsSectionTest.kt @@ -2,6 +2,7 @@ package io.github.nofuturekid.nova.ui.screens.settings import android.Manifest import android.app.Application +import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.content.pm.PackageManager @@ -23,6 +24,7 @@ import androidx.work.WorkInfo import androidx.work.WorkManager import androidx.work.impl.WorkManagerImpl import androidx.work.testing.WorkManagerTestInitHelper +import io.github.nofuturekid.nova.data.alerts.ALERTS_CHANNEL_ID import io.github.nofuturekid.nova.data.alerts.ALERT_WORK_NAME import io.github.nofuturekid.nova.data.alerts.AlertLevel import io.github.nofuturekid.nova.data.alerts.AlertNotifier @@ -34,6 +36,7 @@ import io.github.nofuturekid.nova.data.alerts.FakeServerProbe import io.github.nofuturekid.nova.data.alerts.InMemoryAlertStateStore import io.github.nofuturekid.nova.data.alerts.ProbeResult import io.github.nofuturekid.nova.data.alerts.ServerAlertState +import io.github.nofuturekid.nova.data.alerts.ServerProbe import io.github.nofuturekid.nova.data.alerts.okResult import io.github.nofuturekid.nova.data.alerts.testServer import io.github.nofuturekid.nova.data.alerts.unraidNotification @@ -43,6 +46,7 @@ import io.github.nofuturekid.nova.data.model.Server import io.github.nofuturekid.nova.data.repository.SettingsRepository import io.github.nofuturekid.nova.ui.theme.ThemeMode import io.github.nofuturekid.nova.ui.theme.UnraidTheme +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking import org.junit.After @@ -387,6 +391,54 @@ class AlertsSectionTest { assertEquals(remembered, runBlocking { settings.alertStateFor(tower.id) }) } + // WHY: with the app-level permission granted, a user who switches off one of NOVA's channels would + // otherwise read "On" while every alert of that channel is silently dropped (and marked as seen). + @Test fun a_blocked_channel_is_named_with_a_way_to_fix_it() { + runBlocking { + settings.setServers(listOf(tower)) + settings.setAlertSettings(AlertSettings(enabled = true)) + } + notifier.ensureChannels() + show(viewModel(scheduler())) + waitForText("Send test notification") + rule.onNodeWithText("Open notification settings").assertDoesNotExist() + + nm.deleteNotificationChannel(ALERTS_CHANNEL_ID) + nm.createNotificationChannel(NotificationChannel(ALERTS_CHANNEL_ID, "Server alerts", NotificationManager.IMPORTANCE_NONE)) + rule.activityRule.scenario.moveToState(androidx.lifecycle.Lifecycle.State.STARTED) + rule.activityRule.scenario.moveToState(androidx.lifecycle.Lifecycle.State.RESUMED) + + waitForText("Android blocks NOVA's \"Server alerts\" or \"Server warnings\" notifications", substring = true) + rule.onNodeWithText("Open notification settings").assertExists() + } + + // WHY: "switching off cancels the work": a test already waiting on a slow server must not post a + // notification after the user said off. + @Test fun switching_off_while_a_test_is_running_posts_nothing() { + val gate = CompletableDeferred() + var entered = false + val slow = object : ServerProbe { + override suspend fun probe(server: Server, pin: String?): ProbeResult { + entered = true + return gate.await() + } + } + val scheduler = switchOnWithOneServer() + val vm = AlertsViewModel(SettingsRepository(settings), scheduler, notifier, slow) + show(vm) + waitForText("Send test notification") + + rule.onNodeWithText("Send test notification").performClick() + waitUntil { entered } + vm.turnOff() + waitForText("Off. NOVA does nothing in the background.") + gate.complete(okResult(listOf(unraidNotification("n2", subject = "Disk 1 is hot", timestamp = "2026-11-13T10:00:00.000Z")))) + rule.waitForIdle() + + assertTrue("no notification after the switch is off", nm.activeNotifications.isEmpty()) + assertFalse(enabled()) + } + @Test fun the_test_action_on_a_server_that_cannot_be_reached_says_so_and_posts_nothing() { runBlocking { settings.setServers(listOf(tower)) From ced6191ce17626c4c0527922984d5ea33ef88f57 Mon Sep 17 00:00:00 2001 From: Thomas Kroll Date: Fri, 13 Nov 2026 22:54:32 +0100 Subject: [PATCH 07/11] fix: Test names the redirect target like the tabs do #358 moved the Add server sheet's Test onto the capability probe, whose failure path never called redirectMessage(): a 3xx answer showed the generic "Http request failed with status code 302" instead of the sentence ADR-0051 documents. testOutcomeOf now prefers the redirect message when the probe's failure carries the HTTP exception. Tests: a 302 with a target and one without go through the real probe; the classifier test no longer claims to cover Test. ADR-0048's last sentence pointed at in-app clients that follow redirects; since ADR-0051 they do not. Co-Authored-By: Claude Sonnet 5.5 --- .../data/repository/ResponseClassifier.kt | 8 ++++-- .../data/repository/ResponseClassifierTest.kt | 5 ++-- .../repository/TestConnectionOutcomeTest.kt | 28 +++++++++++++++++++ .../0048-opt-in-background-alert-checks.md | 2 +- 4 files changed, 38 insertions(+), 5 deletions(-) diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/ResponseClassifier.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/ResponseClassifier.kt index 6ac5cfa..bf0620a 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/ResponseClassifier.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/ResponseClassifier.kt @@ -338,7 +338,7 @@ sealed interface TestOutcome { /** * The connection-test result for a capability probe (ADR-0047). A rejected key fails the test with * the server's own wording; a transport failure keeps its certificate handling (an untrusted or - * changed certificate opens the trust dialog, anything else is the exception's message); a server + * changed certificate opens the trust dialog, a redirect names its target, anything else is the exception's message); a server * that answered with an error NOVA does not classify shows that error's text. */ internal fun testOutcomeOf(probe: ProbeOutcome): TestOutcome = when (probe.detection) { @@ -348,8 +348,12 @@ internal fun testOutcomeOf(probe: ProbeOutcome): TestOutcome = when (probe.detec when (val issue = cause?.certIssue()) { is CertIssue.Untrusted -> TestOutcome.CertUntrusted(issue.sha256) is CertIssue.Changed -> TestOutcome.CertChanged(issue.pinned, issue.presented) + // A redirect gets its own sentence with the target, the same one the tabs show (ADR-0051). null -> TestOutcome.Failed( - cause?.failureMessage("Network error") ?: probe.failureText ?: "No response from server", + (cause as? ApolloException)?.redirectMessage() + ?: cause?.failureMessage("Network error") + ?: probe.failureText + ?: "No response from server", ) } } diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ResponseClassifierTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ResponseClassifierTest.kt index ed8bea3..6ad6f3f 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ResponseClassifierTest.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ResponseClassifierTest.kt @@ -219,8 +219,9 @@ class ResponseClassifierTest { assertEquals(ErrorReason.Unreachable, redirect(404, null).toQueryError("Network error").reason) } - // WHY: the Add server sheet's Test shows the classifier's message, so Test and the tabs say the same. - @Test fun redirect_isTheTestConnectionMessage() { + // WHY: the classifier's redirect text is what the pre-probe Test path showed; the Test button itself now goes + // through the capability probe (TestConnectionOutcomeTest.testConnectionNamesTheRedirectTarget covers it). + @Test fun redirect_classifiesAsFailedWithTheTarget() { val c = classifyResponse(redirect(302, "https://tower.example.net/"), hasErrors = false, errorMessage = null, dataIsNull = true) assertEquals( RespClass.Failed("The server redirects to https://tower.example.net. Edit the server and enter that address."), diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/TestConnectionOutcomeTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/TestConnectionOutcomeTest.kt index dd195bc..91de9e2 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/TestConnectionOutcomeTest.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/TestConnectionOutcomeTest.kt @@ -130,4 +130,32 @@ class TestConnectionOutcomeTest { @Test fun testConnectionShowsTheServersOwnErrorText() = runTest { assertEquals(TestOutcome.Failed("boom"), test(serverError, serverError)) } + + private fun redirectTo(location: String): () -> HttpResponse = { + HttpResponse.Builder(302).addHeader("Location", location).body(Buffer()).build() + } + + // WHY: Unraid answers an http request with a 302 to its https address when SSL is Yes or Strict. A user who + // typed such an address must be told the address to enter, in Test exactly as in the tabs, not "Http request + // failed with status code 302". + @Test fun testConnectionNamesTheRedirectTarget() = runTest { + val moved = redirectTo("https://192-168-1-100.abc123.myunraid.net:8443/graphql?x=1") + assertEquals( + TestOutcome.Failed( + "The server redirects to https://192-168-1-100.abc123.myunraid.net:8443. Edit the server and enter that address.", + ), + test(moved, moved), + ) + } + + // WHY: a redirect without a usable target is still a redirect; Test says so instead of the generic status text. + @Test fun testConnectionSaysARedirectWithoutTargetHasNoTarget() = runTest { + val moved: () -> HttpResponse = { HttpResponse.Builder(302).body(Buffer()).build() } + assertEquals( + TestOutcome.Failed( + "The server redirects to another address, but doesn't say which. Check the address in this server's settings.", + ), + test(moved, moved), + ) + } } diff --git a/docs/adr/0048-opt-in-background-alert-checks.md b/docs/adr/0048-opt-in-background-alert-checks.md index b9c017c..b697eaf 100644 --- a/docs/adr/0048-opt-in-background-alert-checks.md +++ b/docs/adr/0048-opt-in-background-alert-checks.md @@ -39,7 +39,7 @@ Planned for the following changes, recorded here so the picture is complete: a p A security check of the first implementation found two things that the rules above did not settle. Both are decided here and apply to everything that checks a server in the background. -1. **Only verified https, no redirects.** The background check contacts a server only at an https address with verified trust: the system's certificates, or, for the local address, the certificate the user pinned. A plain-http address is never contacted in the background, because nobody is looking at the phone and the API key would travel in clear text to whatever answers at that name. A server that has no https address is not checked and gets its own outcome, `NotEncrypted`; it is decided before the key is read, a client is built or a request is sent. The background HTTP client follows no redirect and opens no cleartext connection, so an answer that redirects ends the check as rejected instead of moving the key to another host or down to http. The in-app screens are not affected. +1. **Only verified https, no redirects.** The background check contacts a server only at an https address with verified trust: the system's certificates, or, for the local address, the certificate the user pinned. A plain-http address is never contacted in the background, because nobody is looking at the phone and the API key would travel in clear text to whatever answers at that name. A server that has no https address is not checked and gets its own outcome, `NotEncrypted`; it is decided before the key is read, a client is built or a request is sent. The background HTTP client follows no redirect and opens no cleartext connection, so an answer that redirects ends the check as rejected instead of moving the key to another host or down to http. Since ADR-0051 the in-app clients follow no redirects either. 2. **The demo server is never checked.** The demo entry (ADR-0050) has no address and no key. It is skipped by the check and does not count as a server for scheduling: with only the demo entry left, no job exists. The Settings section states both rules, because a user must be able to tell that alerts do not cover a server: the explanation before the switch says that only https addresses with a trusted certificate are checked, a server with only an http address shows "not checked in the background because the connection is not encrypted. An https address is needed." under its name, and the demo server is named as never checked. From abc3c08a5d0b4fbfd9e50bf3bdae409158e60974 Mon Sep 17 00:00:00 2001 From: Thomas Kroll Date: Fri, 13 Nov 2026 23:07:07 +0100 Subject: [PATCH 08/11] docs: say where Test gets the redirect sentence ADR-0051, decision 4, said that classifyResponse returns the redirect sentence so the Add server sheet's Test shows it without a change of its own. Test no longer goes through classifyResponse: testConnection runs testOutcomeOf(probeCapabilities(...)), and testOutcomeOf prefers the redirect message of the probe's failure cause. Tabs still get the reason through classifyErrorReason and toQueryError, and the snackbar of a failed action gets the lower-cased sentence from checkActionResponse. Co-Authored-By: Claude Sonnet 5.5 --- docs/adr/0051-no-redirects-for-keyed-requests.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/adr/0051-no-redirects-for-keyed-requests.md b/docs/adr/0051-no-redirects-for-keyed-requests.md index 58564bf..e1bec48 100644 --- a/docs/adr/0051-no-redirects-for-keyed-requests.md +++ b/docs/adr/0051-no-redirects-for-keyed-requests.md @@ -25,7 +25,7 @@ So the realistic case is a user who typed an http address or a bare IP; the redi 1. **Rule.** The key is never sent to a host other than the one the user entered, and never over http when the user entered https. The simplest way to guarantee both is that no redirect is followed at all: `followRedirects(false)` and `followSslRedirects(false)` on the base and the long-running client; the WebSocket client is derived from the base client and inherits them, which ends the handshake at the 3xx. The background client keeps its own explicit settings. 2. **Not "follow same-host http-to-https upgrades".** That was the alternative. It would not help: the first request already sent the key over http, to the host the user entered, before the redirect; Unraid's redirect is a 302 that OkHttp would turn into a body-less GET; and following needs a custom interceptor that re-sends the POST and compares hosts, which is more code to get wrong in the code path that guards the key. Telling the user the address to enter costs one sentence and fixes the next request too. 3. **Reason.** `ErrorReason.Redirected` (not a connection problem, so the top-bar pill does not say Offline: the server answered). `ApolloException.redirectMessage()` in `ResponseClassifier.kt` recognises the statuses OkHttp followed (300, 301, 302, 303, 307, 308) and builds `The server redirects to . Edit the server and enter that address.` from the `Location` header. Only the origin is shown: the path is of no use to the user, a query can carry tokens, and `user:password@` is dropped. A missing, relative or non-http `Location` gets the same advice without a target. Tabs show it as "The address needs to change" with that sentence; `DomainState.Error.detail` keeps the raw text. -4. **One text everywhere.** `classifyResponse` returns the sentence for a redirect, so the Add server sheet's **Test** (`testConnection`) shows it without a change of its own, and `checkActionResponse` gives it (lower-cased) to the snackbar of a failed action. `classifyErrorReason` and `toQueryError` give tabs the reason. The WebSocket streams keep their generic error text; the polling tabs and **Test** carry the reason. +4. **One text everywhere.** `classifyResponse` returns the sentence for a redirect and `checkActionResponse` gives it (lower-cased) to the snackbar of a failed action. `classifyErrorReason` and `toQueryError` give tabs the reason. The Add server sheet's **Test** (`testConnection`) does not go through `classifyResponse`: it runs `testOutcomeOf(probeCapabilities(...))`, and `testOutcomeOf` prefers the redirect message of the probe's failure cause, so Test shows the same sentence. The WebSocket streams keep their generic error text; the polling tabs and **Test** carry the reason. 5. **Unchanged.** A server that does not redirect, http-only servers (SSL No) and the background check behave as before; certificate handling is not touched. ## Consequences From 1c83820477221302180585246c9b089a89b738fb Mon Sep 17 00:00:00 2001 From: Thomas Kroll Date: Fri, 13 Nov 2026 22:07:39 +0100 Subject: [PATCH 09/11] test: make a stalled AlertStateStoreTest fail fast and explain itself One full local run hung for over 34 minutes in AlertStateStoreTest with every thread idle, so the dump could not say which coroutine waited for what. StallWatch writes the thread stacks, the main looper state and the DataStore internals (lock, write actor, in-memory cache) after 60 s and ends the test JVM, so a recurrence fails within a minute with the data needed to decide the cause. Diagnostic only, not a fix for the hang. Refs #359 Co-Authored-By: Claude Sonnet 5.5 --- .../nova/data/alerts/AlertStateStoreTest.kt | 3 + .../nova/data/alerts/StallWatch.kt | 107 ++++++++++++++++++ 2 files changed, 110 insertions(+) create mode 100644 app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/StallWatch.kt diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/AlertStateStoreTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/AlertStateStoreTest.kt index e51a2e4..b320c5b 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/AlertStateStoreTest.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/AlertStateStoreTest.kt @@ -11,6 +11,7 @@ import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking import org.junit.Assert.assertEquals import org.junit.Before +import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.robolectric.annotation.Config @@ -30,6 +31,8 @@ import org.robolectric.annotation.Config @RunWith(AndroidJUnit4::class) @Config(sdk = [35]) class AlertStateStoreTest { + @get:Rule val stallWatch = StallWatch() + private lateinit var ctx: Context @Before fun setUp() = runBlocking { diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/StallWatch.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/StallWatch.kt new file mode 100644 index 0000000..10f7fd1 --- /dev/null +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/StallWatch.kt @@ -0,0 +1,107 @@ +package io.github.nofuturekid.nova.data.alerts + +import android.content.Context +import android.os.Looper +import androidx.test.core.app.ApplicationProvider +import io.github.nofuturekid.nova.data.local.SettingsStore +import org.junit.rules.TestRule +import org.junit.runner.Description +import org.junit.runners.model.Statement +import org.robolectric.Shadows.shadowOf +import java.io.File +import java.lang.management.ManagementFactory +import java.lang.reflect.Modifier +import java.util.concurrent.atomic.AtomicBoolean + +/** + * WHY: on 2026-11-13 one full local run hung for over 30 minutes inside [AlertStateStoreTest] + * (a `runBlocking` on the Robolectric main thread that never returned). The thread dump showed + * every thread idle and no lock held, which says a coroutine is suspended but not where, and the + * run was killed before it said anything else. A test that waits for ever tells nobody anything. + * + * This rule turns such a stall into a fast failure that explains itself: when the test has not + * finished after [limitMs] it writes a dump (JVM uptime, every thread's stack, the main looper, + * the internals of the DataStore the store sits on) to `app/build/stall-dumps/` and to stderr and + * ends the test JVM, so Gradle reports a failed test run within a minute. It ends the JVM instead + * of only failing the test because the DataStore is one object per Robolectric sandbox: after a + * stall every later test that touches it would wait for ever as well. + * + * The limit is a diagnostic, not a fix, and not a retry: it must stay far above any honest run of + * one test (they take well under a second). A JUnit `Timeout` rule is not used on purpose: it runs + * the test on another thread, and a Robolectric test has to stay on its main thread. + */ +class StallWatch(private val limitMs: Long = 60_000) : TestRule { + + override fun apply(base: Statement, description: Description) = object : Statement() { + override fun evaluate() { + val testThread = Thread.currentThread() + val started = System.nanoTime() + val done = Object() + val finished = AtomicBoolean(false) + val watchdog = Thread({ + synchronized(done) { if (!finished.get()) done.wait(limitMs) } + if (!finished.get()) { + val file = runCatching { writeDump(description, testThread, (System.nanoTime() - started) / 1_000_000) } + System.err.println("${description.displayName} stalled for $limitMs ms; dump: $file; ending the test JVM") + System.err.flush() + Runtime.getRuntime().halt(STALL_EXIT_CODE) + } + }, "stall-watch").apply { isDaemon = true; start() } + try { + base.evaluate() + } finally { + synchronized(done) { finished.set(true); done.notifyAll() } + watchdog.join(5_000) + } + } + } + + private fun writeDump(description: Description, testThread: Thread, elapsedMs: Long): File { + val sb = StringBuilder() + sb.append("STALL in ${description.displayName} after $elapsedMs ms\n") + sb.append("JVM uptime ms: ${ManagementFactory.getRuntimeMXBean().uptime}\n") + val mx = ManagementFactory.getThreadMXBean() + sb.append("test thread '${testThread.name}' cpu ms: ${mx.getThreadCpuTime(testThread.id) / 1_000_000}\n") + sb.append("main looper idle: ${runCatching { shadowOf(Looper.getMainLooper()).isIdle }}\n") + sb.append("\n--- threads ---\n") + for ((t, stack) in Thread.getAllStackTraces()) { + sb.append("\"${t.name}\" ${t.state}\n") + stack.take(30).forEach { sb.append(" at $it\n") } + } + sb.append("\n--- DataStore behind SettingsStore ---\n") + runCatching { + val store = SettingsStore(ApplicationProvider.getApplicationContext()) + val ds = SettingsStore::class.java.getDeclaredField("ds").apply { isAccessible = true }.get(store) + dumpObject(sb, ds, 4, "", HashSet()) + }.onFailure { sb.append("could not read it: $it\n") } + + val dir = File(System.getProperty("user.dir"), "build/stall-dumps").apply { mkdirs() } + val file = File(dir, "${description.className}.${description.methodName}.txt") + file.writeText(sb.toString()) + System.err.println(sb) + return file + } + + private fun dumpObject(sb: StringBuilder, o: Any?, depth: Int, indent: String, seen: MutableSet) { + if (o == null || depth < 0 || !seen.add(System.identityHashCode(o))) return + var c: Class<*>? = o.javaClass + while (c != null && c != Any::class.java) { + for (f in c.declaredFields) { + if (Modifier.isStatic(f.modifiers)) continue + runCatching { + f.isAccessible = true + val v = f.get(o) + val plain = v == null || v is String || v is Number || v is Boolean + val shown = if (plain) "$v" else v!!.javaClass.name + " " + runCatching { v.toString() }.getOrDefault("?").take(300) + sb.append(indent).append(c.simpleName).append('.').append(f.name).append(" = ").append(shown).append('\n') + if (!plain && !v!!.javaClass.name.startsWith("java.lang")) dumpObject(sb, v, depth - 1, "$indent ", seen) + } + } + c = c.superclass + } + } + + private companion object { + const val STALL_EXIT_CODE = 70 + } +} From 5de1d3661568b1b807189dc71302391efbe27e1e Mon Sep 17 00:00:00 2001 From: Thomas Kroll Date: Fri, 13 Nov 2026 22:29:13 +0100 Subject: [PATCH 10/11] test: add a coroutine dump to the stall dump and watch every class that uses the DataStore The stall dump of #359 could not tell the two open hypotheses apart: it showed threads, the main looper and DataStore fields, but not which coroutine holds the DataStore mutex or what the test's runBlocking waits on. - StallWatch installs kotlinx-coroutines-debug probes once per JVM and dumps every live coroutine with state, dispatcher, suspension point and creation stack, names the coroutine that passes through SingleProcessCoordinator.lock, lists the edit callers and their dispatchers, shows the main looper's queue and the event loop of each runBlocking, and lists the test classes started in this JVM so far. The probes are installed through the application class loader: Robolectric keeps the Kotlin standard library there, so a sandbox-side install records nothing. - The rule is now on every class that uses the sandbox-wide DataStore (AlertCheckRunnerTest, AlertCheckWorkerTest, AlertSchedulerTest, AlertSettingsStoreTest, SaveServerPinTest, UnraidGatewayTest, UpdateCheckOnForegroundTest, AlertsSectionTest, AlertStateStoreTest), so a coroutine leaked by an earlier class is caught where it bites and its creation stack names its origin. - The dump is also written next to the HTML test report, which CI already uploads when a job fails. - kotlinx-coroutines-debug as test dependency, same version as the coroutines in use. Still no fix and no retry: the 60 s limit only turns a silent hang into a fast failure with evidence. Refs #359 Co-Authored-By: Claude Sonnet 5.5 --- app/build.gradle.kts | 7 + .../nova/data/alerts/AlertCheckRunnerTest.kt | 3 + .../nova/data/alerts/AlertCheckWorkerTest.kt | 3 + .../nova/data/alerts/AlertSchedulerTest.kt | 3 + .../data/alerts/AlertSettingsStoreTest.kt | 3 + .../nova/data/alerts/StallWatch.kt | 187 ++++++++++++++++-- .../nova/data/repository/SaveServerPinTest.kt | 4 + .../nova/data/repository/UnraidGatewayTest.kt | 4 + .../main/UpdateCheckOnForegroundTest.kt | 3 + .../ui/screens/settings/AlertsSectionTest.kt | 2 + gradle/libs.versions.toml | 2 + 11 files changed, 209 insertions(+), 12 deletions(-) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 98b8a77..a154dc8 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -190,6 +190,7 @@ dependencies { testImplementation(libs.junit) testImplementation(libs.kotlinx.coroutines.test) + testImplementation(libs.kotlinx.coroutines.debug) testImplementation(libs.androidx.work.testing) // Store-screenshot rendering (StoreScreenshots.kt) — test scope only, @@ -218,4 +219,10 @@ tasks.withType().configureEach { } else { filter.excludeTestsMatching("*StoreScreenshots") } + // StallWatch (test rule) writes its dump of a stalled test here as well as to build/stall-dumps: + // CI already uploads the HTML report directory, also when the job fails. Set at execution time, + // so the path is not a task input. + doFirst { + systemProperty("nova.stallDumpCopyDir", reports.html.outputLocation.get().asFile.resolve("stall-dumps").path) + } } diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/AlertCheckRunnerTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/AlertCheckRunnerTest.kt index 54c4900..5a1e460 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/AlertCheckRunnerTest.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/AlertCheckRunnerTest.kt @@ -19,6 +19,7 @@ import org.junit.Assert.assertNotNull import org.junit.Assert.assertTrue import org.junit.After import org.junit.Before +import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.robolectric.Shadows.shadowOf @@ -39,6 +40,8 @@ import java.time.Instant @RunWith(AndroidJUnit4::class) @Config(sdk = [35]) class AlertCheckRunnerTest { + @get:Rule val stallWatch = StallWatch() + private lateinit var ctx: Context private lateinit var settings: SettingsStore private lateinit var notifier: AlertNotifier diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/AlertCheckWorkerTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/AlertCheckWorkerTest.kt index d12cdf0..9537fda 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/AlertCheckWorkerTest.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/AlertCheckWorkerTest.kt @@ -15,6 +15,7 @@ import kotlinx.coroutines.runBlocking import org.junit.After import org.junit.Assert.assertEquals import org.junit.Before +import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.robolectric.Shadows.shadowOf @@ -30,6 +31,8 @@ import org.robolectric.annotation.Config @RunWith(AndroidJUnit4::class) @Config(sdk = [35]) class AlertCheckWorkerTest { + @get:Rule val stallWatch = StallWatch() + private lateinit var ctx: Context private lateinit var settings: SettingsStore private lateinit var nm: NotificationManager diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/AlertSchedulerTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/AlertSchedulerTest.kt index 9c504d0..895d5a7 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/AlertSchedulerTest.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/AlertSchedulerTest.kt @@ -18,6 +18,7 @@ import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Before +import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.robolectric.Shadows.shadowOf @@ -38,6 +39,8 @@ import java.util.concurrent.TimeUnit @RunWith(AndroidJUnit4::class) @Config(sdk = [35]) class AlertSchedulerTest { + @get:Rule val stallWatch = StallWatch() + private lateinit var ctx: Context private lateinit var settings: SettingsStore private lateinit var notifier: AlertNotifier diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/AlertSettingsStoreTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/AlertSettingsStoreTest.kt index 7f8c406..e961ea4 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/AlertSettingsStoreTest.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/AlertSettingsStoreTest.kt @@ -9,6 +9,7 @@ import kotlinx.coroutines.runBlocking import org.junit.After import org.junit.Assert.assertEquals import org.junit.Before +import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.robolectric.annotation.Config @@ -22,6 +23,8 @@ import org.robolectric.annotation.Config @RunWith(AndroidJUnit4::class) @Config(sdk = [35]) class AlertSettingsStoreTest { + @get:Rule val stallWatch = StallWatch() + private lateinit var settings: SettingsStore @Before fun setUp() { diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/StallWatch.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/StallWatch.kt index 10f7fd1..9b6faa4 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/StallWatch.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/StallWatch.kt @@ -12,6 +12,8 @@ import java.io.File import java.lang.management.ManagementFactory import java.lang.reflect.Modifier import java.util.concurrent.atomic.AtomicBoolean +import kotlin.coroutines.ContinuationInterceptor +import kotlin.coroutines.CoroutineContext /** * WHY: on 2026-11-13 one full local run hung for over 30 minutes inside [AlertStateStoreTest] @@ -20,11 +22,23 @@ import java.util.concurrent.atomic.AtomicBoolean * run was killed before it said anything else. A test that waits for ever tells nobody anything. * * This rule turns such a stall into a fast failure that explains itself: when the test has not - * finished after [limitMs] it writes a dump (JVM uptime, every thread's stack, the main looper, - * the internals of the DataStore the store sits on) to `app/build/stall-dumps/` and to stderr and - * ends the test JVM, so Gradle reports a failed test run within a minute. It ends the JVM instead - * of only failing the test because the DataStore is one object per Robolectric sandbox: after a - * stall every later test that touches it would wait for ever as well. + * finished after [limitMs] it writes a dump to `build/stall-dumps/` and to stderr and ends the + * test JVM, so Gradle reports a failed test run within a minute. The dump holds the JVM uptime, + * the test classes that have started in this JVM so far (in order), every thread's stack, the main + * looper, the internals of the DataStore the store sits on (is its coordinator mutex locked, what + * is queued for its write actor) and every live coroutine with its state, dispatcher, suspension + * point and creation stack (kotlinx-coroutines-debug). The coroutine part decides between the open + * hypotheses of #359. H1: an edit whose caller dispatcher cannot run keeps the DataStore mutex + * locked; the dump then shows a coroutine that holds the mutex (stack through + * `SingleProcessCoordinator.lock`) suspended in `transformAndWrite`, an edit caller bound to a + * looper dispatcher, and a pending message in the main looper's queue. H2: a resumption into the + * main thread's blocking event loop never arrives; the dump then shows the test's `runBlocking` + * coroutine suspended, an empty event loop queue, and a mutex that nobody holds. + * + * It ends the JVM instead of only failing the test because the DataStore is one object per + * Robolectric sandbox: after a stall every later test that touches it would wait for ever as well. + * Every test class that uses that DataStore carries this rule, so a coroutine leaked by an earlier + * class is caught in the class where it bites, and its creation stack names the class it came from. * * The limit is a diagnostic, not a fix, and not a retry: it must stay far above any honest run of * one test (they take well under a second). A JUnit `Timeout` rule is not used on purpose: it runs @@ -34,6 +48,8 @@ class StallWatch(private val limitMs: Long = 60_000) : TestRule { override fun apply(base: Statement, description: Description) = object : Statement() { override fun evaluate() { + Probes.install() + noteClassStarted(description.className) val testThread = Thread.currentThread() val started = System.nanoTime() val done = Object() @@ -60,14 +76,16 @@ class StallWatch(private val limitMs: Long = 60_000) : TestRule { val sb = StringBuilder() sb.append("STALL in ${description.displayName} after $elapsedMs ms\n") sb.append("JVM uptime ms: ${ManagementFactory.getRuntimeMXBean().uptime}\n") + sb.append("test classes started in this JVM so far, in order (JVM uptime ms when each first reached this rule):\n") + for (entry in startedClasses()) sb.append(" ").append(entry).append('\n') val mx = ManagementFactory.getThreadMXBean() sb.append("test thread '${testThread.name}' cpu ms: ${mx.getThreadCpuTime(testThread.id) / 1_000_000}\n") sb.append("main looper idle: ${runCatching { shadowOf(Looper.getMainLooper()).isIdle }}\n") - sb.append("\n--- threads ---\n") - for ((t, stack) in Thread.getAllStackTraces()) { - sb.append("\"${t.name}\" ${t.state}\n") - stack.take(30).forEach { sb.append(" at $it\n") } - } + sb.append("main looper queue: ${runCatching { looperQueue() }.getOrElse { "not readable: $it" }}\n") + + sb.append("\n--- coroutines (kotlinx-coroutines-debug) ---\n") + runCatching { dumpCoroutines(sb) }.onFailure { sb.append("coroutine dump failed: $it\n") } + sb.append("\n--- DataStore behind SettingsStore ---\n") runCatching { val store = SettingsStore(ApplicationProvider.getApplicationContext()) @@ -75,13 +93,85 @@ class StallWatch(private val limitMs: Long = 60_000) : TestRule { dumpObject(sb, ds, 4, "", HashSet()) }.onFailure { sb.append("could not read it: $it\n") } - val dir = File(System.getProperty("user.dir"), "build/stall-dumps").apply { mkdirs() } - val file = File(dir, "${description.className}.${description.methodName}.txt") + sb.append("\n--- threads ---\n") + for ((t, stack) in Thread.getAllStackTraces()) { + sb.append("\"${t.name}\" ${t.state}\n") + stack.take(30).forEach { sb.append(" at $it\n") } + } + + val name = "${description.className}.${description.methodName}.txt" + val file = File(File(System.getProperty("user.dir"), "build/stall-dumps").apply { mkdirs() }, name) file.writeText(sb.toString()) + // A second copy next to the HTML test report: CI already uploads that directory, also when the job fails. + System.getProperty(COPY_DIR_PROPERTY)?.let { runCatching { File(it).apply { mkdirs() }.resolve(name).writeText(sb.toString()) } } System.err.println(sb) return file } + /** The main looper's pending messages. A message here that is never taken is a looper that is not served. */ + private fun looperQueue(): String { + val out = StringBuilder() + Looper.getMainLooper().dump({ out.append(it).append(" | ") }, "") + return out.toString().ifBlank { "(empty)" } + } + + private fun dumpCoroutines(sb: StringBuilder) { + Probes.failure?.let { + sb.append("DebugProbes could not be installed: $it\n") + return + } + // In creation order (the probes return them sorted by their creation sequence number). + val all = Probes.dump() + fun id(c: Probed) = "#${all.indexOf(c)}" + sb.append("${all.size} live coroutines created since the probes were installed (first watched test class of this JVM).\n") + sb.append("Facts per coroutine: state (CREATED = never started, SUSPENDED = waiting, RUNNING), the dispatcher it\n") + sb.append("is bound to, where it is suspended, where it was created. A CREATED coroutine on a dispatcher that\n") + sb.append("is not served never starts.\n") + if (all.isEmpty()) sb.append("NOTE: nothing was recorded. DebugProbes swallows a failed agent attach, so this can also mean the probes are not active.\n") + sb.append('\n') + + sb.append("SUMMARY\n") + val never = all.filter { it.state == "CREATED" } + sb.append(" never started (CREATED): ${never.size}\n") + never.forEach { sb.append(" ${id(it)} on ${it.dispatcher}\n") } + // DataStore takes its coordinator mutex in SingleProcessCoordinator.lock and runs the transform of an + // edit, on the dispatcher of the edit's caller, inside it. A coroutine whose stack passes through + // that lock holds the mutex; where it is suspended says what it waits for. + val holders = all.filter { c -> c.stack().any { it.className == "androidx.datastore.core.SingleProcessCoordinator" && it.methodName == "lock" } } + sb.append(" holds the DataStore coordinator mutex (stack passes through SingleProcessCoordinator.lock): ${holders.size}\n") + holders.forEach { sb.append(" ${id(it)} ${it.state} on ${it.dispatcher}, suspended at ${it.suspendedAt()}\n") } + val callers = all.filter { c -> c.stack().firstOrNull()?.className?.startsWith("androidx.datastore.core.DataStoreImpl\$updateData") == true } + sb.append(" edits waiting for DataStore's answer (suspended in DataStoreImpl.updateData); the transform of each runs on ITS dispatcher: ${callers.size}\n") + callers.forEach { sb.append(" ${id(it)} on ${it.dispatcher}\n") } + val onMutex = all.filter { c -> c.stack().take(6).any { it.className.startsWith("kotlinx.coroutines.sync.") } } + sb.append(" waiting for a Mutex: ${onMutex.size}\n") + onMutex.forEach { sb.append(" ${id(it)} on ${it.dispatcher}, ${it.suspendedAt()}\n") } + val blocking = all.filter { it.isBlocking } + sb.append(" runBlocking coroutines: ${blocking.size}\n") + blocking.forEach { sb.append(" ${id(it)} ${it.state}, ${it.suspendedAt()}\n") } + sb.append('\n') + + for (c in all.take(MAX_COROUTINES)) { + sb.append("coroutine ${id(c)} state=${c.state} dispatcher=${c.dispatcher}\n") + sb.append(" context: ${c.context}\n") + sb.append(" suspended at: ${c.suspendedAt()}\n") + val st = c.stack() + if (st.isEmpty()) sb.append(" stack: (none; a CREATED coroutine has not run)\n") + else { + sb.append(" stack:\n") + st.take(25).forEach { sb.append(" at $it\n") } + } + sb.append(" created at:\n") + val cr = c.creationStack() + if (cr.isEmpty()) sb.append(" (not recorded)\n") else cr.take(30).forEach { sb.append(" at $it\n") } + if (c.isBlocking) { + sb.append(" event loop of this runBlocking:\n") + dumpObject(sb, c.context[ContinuationInterceptor], 2, " ", HashSet()) + } + } + if (all.size > MAX_COROUTINES) sb.append("... ${all.size - MAX_COROUTINES} more coroutines not listed\n") + } + private fun dumpObject(sb: StringBuilder, o: Any?, depth: Int, indent: String, seen: MutableSet) { if (o == null || depth < 0 || !seen.add(System.identityHashCode(o))) return var c: Class<*>? = o.javaClass @@ -101,7 +191,80 @@ class StallWatch(private val limitMs: Long = 60_000) : TestRule { } } + /** One coroutine as the probes report it. Read by reflection, see [Probes]. */ + private class Probed(private val info: Any) { + private fun call(name: String): T { + @Suppress("UNCHECKED_CAST") + return info.javaClass.getMethod(name).invoke(info) as T + } + + val state: String get() = call("getState").toString() + val context: CoroutineContext get() = call("getContext") + val dispatcher: String get() = context[ContinuationInterceptor]?.toString() ?: "none" + val isBlocking: Boolean get() = dispatcher.contains("BlockingEventLoop") + fun stack(): List = runCatching { call>("lastObservedStackTrace") }.getOrDefault(emptyList()) + fun creationStack(): List = runCatching { call>("getCreationStackTrace") }.getOrDefault(emptyList()) + fun suspendedAt(): String { + val st = stack() + return st.firstOrNull { !it.className.startsWith("kotlinx.coroutines.") && !it.className.startsWith("kotlin.") }?.toString() + ?: st.firstOrNull()?.toString() ?: "(no frame: not started)" + } + } + + /** + * The coroutine probes, installed once per JVM, and only through the application class loader. + * Why not directly: Robolectric loads kotlinx.coroutines into its own sandbox class loader but + * leaves the Kotlin standard library, which holds `DebugProbesKt` (the hook every coroutine + * creation calls), in the application class loader. The hook is rewritten to call the + * `DebugProbesImpl` of the loader that holds it. A `DebugProbes.install()` made from the sandbox + * therefore succeeds and records nothing (0 coroutines). Installed through the application + * class loader the hook reports every coroutine of the sandbox too, and the stack frames are + * plain `StackTraceElement`s and `CoroutineContext`s, which both loaders share. Only the + * coroutines' `Job` is not recognised across the two loaders; the dump does not use it. + * A failure is kept and printed in the dump, it never fails a test. + */ + private object Probes { + @Volatile var failure: String? = null + private var installed = false + private var probes: Any? = null + private var probesClass: Class<*>? = null + + @Synchronized fun install() { + if (installed) return + installed = true + try { + val cls = Class.forName("kotlinx.coroutines.debug.DebugProbes", true, Unit::class.java.classLoader) + val instance = cls.getField("INSTANCE").get(null) + cls.getMethod("setEnableCreationStackTraces", Boolean::class.javaPrimitiveType).invoke(instance, true) + cls.getMethod("install").invoke(instance) + probes = instance + probesClass = cls + } catch (t: Throwable) { + failure = (t.cause ?: t).toString() + } + } + + fun dump(): List = + (probesClass!!.getMethod("dumpCoroutinesInfo").invoke(probes) as List<*>).map { Probed(it!!) } + } + private companion object { const val STALL_EXIT_CODE = 70 + const val MAX_COROUTINES = 150 + + /** Set by Gradle (app/build.gradle.kts): where CI already collects the test report. */ + const val COPY_DIR_PROPERTY = "nova.stallDumpCopyDir" + const val CLASSES_PROPERTY = "nova.stallWatch.startedClasses" + + /** In a system property, not a field: the sandbox class loader can be replaced, the JVM cannot. */ + fun noteClassStarted(className: String) = synchronized(System.getProperties()) { + val now = ManagementFactory.getRuntimeMXBean().uptime + val known = System.getProperty(CLASSES_PROPERTY).orEmpty().split('\n').filter { it.isNotBlank() } + if (known.none { it.substringBefore(" @") == className }) { + System.setProperty(CLASSES_PROPERTY, (known + "$className @ $now ms").joinToString("\n")) + } + } + + fun startedClasses(): List = System.getProperty(CLASSES_PROPERTY).orEmpty().split('\n').filter { it.isNotBlank() } } } diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/SaveServerPinTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/SaveServerPinTest.kt index ad5da4e..df308e1 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/SaveServerPinTest.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/SaveServerPinTest.kt @@ -6,6 +6,7 @@ import androidx.test.ext.junit.runners.AndroidJUnit4 import io.github.nofuturekid.nova.data.alerts.AlertNotifier import io.github.nofuturekid.nova.data.alerts.AlertScheduler import io.github.nofuturekid.nova.data.alerts.SettingsAlertStateStore +import io.github.nofuturekid.nova.data.alerts.StallWatch import io.github.nofuturekid.nova.data.local.ApiKeyStore import io.github.nofuturekid.nova.data.local.SettingsStore import io.github.nofuturekid.nova.data.model.Server @@ -21,6 +22,7 @@ import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Before +import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.robolectric.annotation.Config @@ -48,6 +50,8 @@ import java.util.concurrent.CopyOnWriteArrayList @RunWith(AndroidJUnit4::class) @Config(sdk = [35]) class SaveServerPinTest { + @get:Rule val stallWatch = StallWatch() + private lateinit var repo: ServerRepository private val seen = CopyOnWriteArrayList() diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/UnraidGatewayTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/UnraidGatewayTest.kt index f8d3fcb..bfc6186 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/UnraidGatewayTest.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/UnraidGatewayTest.kt @@ -8,6 +8,7 @@ import io.github.nofuturekid.nova.data.api.ApolloClientFactory import io.github.nofuturekid.nova.data.alerts.AlertNotifier import io.github.nofuturekid.nova.data.alerts.AlertScheduler import io.github.nofuturekid.nova.data.alerts.SettingsAlertStateStore +import io.github.nofuturekid.nova.data.alerts.StallWatch import io.github.nofuturekid.nova.data.api.TlsTrust import io.github.nofuturekid.nova.data.demo.DemoFixtures import io.github.nofuturekid.nova.data.demo.DemoState @@ -36,6 +37,7 @@ import org.junit.Assert.assertFalse import org.junit.Assert.assertNotNull import org.junit.Assert.assertTrue import org.junit.Before +import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.robolectric.annotation.Config @@ -64,6 +66,8 @@ private class ForbiddenFactory : ApolloClientFactory() { @RunWith(AndroidJUnit4::class) @Config(sdk = [35]) class UnraidGatewayTest { + @get:Rule val stallWatch = StallWatch() + private lateinit var servers: ServerRepository private lateinit var factory: ForbiddenFactory private lateinit var demo: DemoUnraid diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/main/UpdateCheckOnForegroundTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/main/UpdateCheckOnForegroundTest.kt index af74d39..7064d10 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/main/UpdateCheckOnForegroundTest.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/main/UpdateCheckOnForegroundTest.kt @@ -8,6 +8,7 @@ import io.github.nofuturekid.nova.data.alerts.AlertNotifier import io.github.nofuturekid.nova.data.alerts.AlertScheduler import io.github.nofuturekid.nova.data.alerts.PendingNavigation import io.github.nofuturekid.nova.data.alerts.SettingsAlertStateStore +import io.github.nofuturekid.nova.data.alerts.StallWatch import io.github.nofuturekid.nova.data.api.ApolloClientFactory import io.github.nofuturekid.nova.data.demo.DemoUnraid import io.github.nofuturekid.nova.data.local.ApiKeyStore @@ -33,6 +34,7 @@ import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Assume.assumeTrue import org.junit.Before +import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.robolectric.annotation.Config @@ -60,6 +62,7 @@ import java.util.concurrent.atomic.AtomicInteger @RunWith(AndroidJUnit4::class) @Config(sdk = [35]) class UpdateCheckOnForegroundTest { + @get:Rule val stallWatch = StallWatch() private val installed = "0.1.48-beta1" private val scope = CoroutineScope(Dispatchers.Default) diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/settings/AlertsSectionTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/settings/AlertsSectionTest.kt index 06e7308..58ae1fb 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/settings/AlertsSectionTest.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/settings/AlertsSectionTest.kt @@ -37,6 +37,7 @@ import io.github.nofuturekid.nova.data.alerts.InMemoryAlertStateStore import io.github.nofuturekid.nova.data.alerts.ProbeResult import io.github.nofuturekid.nova.data.alerts.ServerAlertState import io.github.nofuturekid.nova.data.alerts.ServerProbe +import io.github.nofuturekid.nova.data.alerts.StallWatch import io.github.nofuturekid.nova.data.alerts.okResult import io.github.nofuturekid.nova.data.alerts.testServer import io.github.nofuturekid.nova.data.alerts.unraidNotification @@ -77,6 +78,7 @@ import java.util.concurrent.TimeUnit @GraphicsMode(GraphicsMode.Mode.NATIVE) @Config(sdk = [35], qualifiers = "w432dp-h2400dp-night-400dpi") class AlertsSectionTest { + @get:Rule val stallWatch = StallWatch() @get:Rule val rule = createAndroidComposeRule() diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 45b6c1e..05be6ee 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -81,6 +81,8 @@ roborazzi-compose = { module = "io.github.takahirom.roborazzi:roborazzi-compose" androidx-compose-ui-test-junit4 = { module = "androidx.compose.ui:ui-test-junit4" } androidx-compose-ui-test-manifest = { module = "androidx.compose.ui:ui-test-manifest" } kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "kotlinxCoroutines" } +# Coroutine dump of a stalled test (StallWatch). Test scope only; same version as the coroutines in use. +kotlinx-coroutines-debug = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-debug", version.ref = "kotlinxCoroutines" } androidx-work-testing = { module = "androidx.work:work-testing", version.ref = "work" } aboutlibraries-compose-m3 = { module = "com.mikepenz:aboutlibraries-compose-m3", version.ref = "aboutLibraries" } From deded389c1680fbe784e3115e9ad7bef2ad2c2eb Mon Sep 17 00:00:00 2001 From: Thomas Kroll Date: Fri, 13 Nov 2026 22:54:00 +0100 Subject: [PATCH 11/11] test: print the coroutines at fault in full and attribute each to its test class The coroutine dump listed details for the 150 oldest coroutines only, but the coroutines at fault (mutex holder, edit callers, never-started ones) are the newest. Every coroutine named in the summary is now printed in full; the cap applies to the rest, newest first, with the number left out. Each watched class records the highest coroutine id alive when it starts, and the dump says for every coroutine during which class it was created, so a coroutine leaked by an earlier class is attributable even when its creation stack names no test. The watchdog waits on a deadline loop (no early end on a spurious wakeup), writes the dump on a bounded thread (a blocked read cannot keep the JVM alive) and lists the thread stacks first. The KDoc now states how the dump reads under each hypothesis and what it cannot tell. Refs #359 Co-Authored-By: Claude Sonnet 5.5 --- .../nova/data/alerts/StallWatch.kt | 106 ++++++++++++++---- 1 file changed, 83 insertions(+), 23 deletions(-) diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/StallWatch.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/StallWatch.kt index 9b6faa4..14998fe 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/StallWatch.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/data/alerts/StallWatch.kt @@ -24,21 +24,39 @@ import kotlin.coroutines.CoroutineContext * This rule turns such a stall into a fast failure that explains itself: when the test has not * finished after [limitMs] it writes a dump to `build/stall-dumps/` and to stderr and ends the * test JVM, so Gradle reports a failed test run within a minute. The dump holds the JVM uptime, - * the test classes that have started in this JVM so far (in order), every thread's stack, the main + * the watched test classes that have started in this JVM so far (in order, classes without the rule are not listed), every thread's stack, the main * looper, the internals of the DataStore the store sits on (is its coordinator mutex locked, what * is queued for its write actor) and every live coroutine with its state, dispatcher, suspension - * point and creation stack (kotlinx-coroutines-debug). The coroutine part decides between the open - * hypotheses of #359. H1: an edit whose caller dispatcher cannot run keeps the DataStore mutex - * locked; the dump then shows a coroutine that holds the mutex (stack through - * `SingleProcessCoordinator.lock`) suspended in `transformAndWrite`, an edit caller bound to a - * looper dispatcher, and a pending message in the main looper's queue. H2: a resumption into the - * main thread's blocking event loop never arrives; the dump then shows the test's `runBlocking` - * coroutine suspended, an empty event loop queue, and a mutex that nobody holds. + * point and creation stack (kotlinx-coroutines-debug), each with the test class during which it was + * created. The coroutine part decides between the open hypotheses of #359. H1: an edit whose + * caller dispatcher cannot run keeps the DataStore mutex locked; the dump then shows a coroutine + * that holds the mutex (stack through `SingleProcessCoordinator.lock`) suspended in + * `transformAndWrite`, an edit caller bound to a dispatcher that is not served (for example a + * looper with a pending message in the main looper's queue) and the coordinator mutex locked. + * H1 has a second shape: the transform of the test's own edit is lost on its own `runBlocking`; + * then one holder exists and the only edit caller is on the BlockingEventLoop. H2: a resumption + * into the main thread's blocking event loop never arrives while nothing holds the mutex; the + * dump then shows the test's `runBlocking` coroutine suspended, no holder, an unlocked mutex and + * no edit caller. The event loop queue of the `runBlocking` cannot tell the two apart (it is + * empty in the H1 validation run as well). `AlertStateStoreTest.setUp` ends with an unconditional + * `clear()` edit that did finish in the original hang, so under H1 the blocking edit entered the + * write actor after `setUp`, from a coroutine that was still running then. + * + * What the dump cannot tell: with two or more edit callers on unserved dispatchers it does not say + * which one is in flight (the queued message's caller context is below the depth the object dump + * reaches); it does not show the value of the in-memory data, so within H2 it cannot separate "the + * answer was never completed" from "it was completed but the resumption was lost"; and the probes + * keep coroutines in a weak map, so a coroutine on an abandoned dispatcher that nothing else + * references can be missing from the coroutine list (the mutex state and the actor queue are + * still shown). * * It ends the JVM instead of only failing the test because the DataStore is one object per * Robolectric sandbox: after a stall every later test that touches it would wait for ever as well. * Every test class that uses that DataStore carries this rule, so a coroutine leaked by an earlier - * class is caught in the class where it bites, and its creation stack names the class it came from. + * class is caught in the class where it bites. Its creation stack names the class it came from only + * if the stack passes through test code, which a coroutine started from another coroutine does not; + * so the dump also records, per coroutine, the watched class during which it was created (from the + * coroutine counter noted when each class started). * * The limit is a diagnostic, not a fix, and not a retry: it must stay far above any honest run of * one test (they take well under a second). A JUnit `Timeout` rule is not used on purpose: it runs @@ -49,15 +67,27 @@ class StallWatch(private val limitMs: Long = 60_000) : TestRule { override fun apply(base: Statement, description: Description) = object : Statement() { override fun evaluate() { Probes.install() - noteClassStarted(description.className) + noteClassStarted(description.className, Probes.lastCoroutineId()) val testThread = Thread.currentThread() val started = System.nanoTime() val done = Object() val finished = AtomicBoolean(false) val watchdog = Thread({ - synchronized(done) { if (!finished.get()) done.wait(limitMs) } + synchronized(done) { + // A loop on the deadline: a spurious wakeup must not end the JVM early. + while (!finished.get()) { + val left = limitMs - (System.nanoTime() - started) / 1_000_000 + if (left <= 0) break + done.wait(left) + } + } if (!finished.get()) { - val file = runCatching { writeDump(description, testThread, (System.nanoTime() - started) / 1_000_000) } + // The dump runs on its own thread with a bound: if reading some part of it blocks, the JVM still ends. + var file: Result? = null + val writer = Thread({ file = runCatching { writeDump(description, testThread, (System.nanoTime() - started) / 1_000_000) } }, "stall-watch-dump") + .apply { isDaemon = true; start() } + writer.join(DUMP_BUDGET_MS) + if (writer.isAlive) file = Result.failure(IllegalStateException("dump not finished after $DUMP_BUDGET_MS ms")) System.err.println("${description.displayName} stalled for $limitMs ms; dump: $file; ending the test JVM") System.err.flush() Runtime.getRuntime().halt(STALL_EXIT_CODE) @@ -76,13 +106,19 @@ class StallWatch(private val limitMs: Long = 60_000) : TestRule { val sb = StringBuilder() sb.append("STALL in ${description.displayName} after $elapsedMs ms\n") sb.append("JVM uptime ms: ${ManagementFactory.getRuntimeMXBean().uptime}\n") - sb.append("test classes started in this JVM so far, in order (JVM uptime ms when each first reached this rule):\n") + sb.append("watched test classes started in this JVM so far, in order (JVM uptime ms when each first reached this rule; classes without the rule are not listed; the coroutine id is the highest one alive at that moment):\n") for (entry in startedClasses()) sb.append(" ").append(entry).append('\n') val mx = ManagementFactory.getThreadMXBean() sb.append("test thread '${testThread.name}' cpu ms: ${mx.getThreadCpuTime(testThread.id) / 1_000_000}\n") sb.append("main looper idle: ${runCatching { shadowOf(Looper.getMainLooper()).isIdle }}\n") sb.append("main looper queue: ${runCatching { looperQueue() }.getOrElse { "not readable: $it" }}\n") + sb.append("\n--- threads ---\n") + for ((t, stack) in Thread.getAllStackTraces()) { + sb.append("\"${t.name}\" ${t.state}\n") + stack.take(30).forEach { sb.append(" at $it\n") } + } + sb.append("\n--- coroutines (kotlinx-coroutines-debug) ---\n") runCatching { dumpCoroutines(sb) }.onFailure { sb.append("coroutine dump failed: $it\n") } @@ -93,12 +129,6 @@ class StallWatch(private val limitMs: Long = 60_000) : TestRule { dumpObject(sb, ds, 4, "", HashSet()) }.onFailure { sb.append("could not read it: $it\n") } - sb.append("\n--- threads ---\n") - for ((t, stack) in Thread.getAllStackTraces()) { - sb.append("\"${t.name}\" ${t.state}\n") - stack.take(30).forEach { sb.append(" at $it\n") } - } - val name = "${description.className}.${description.methodName}.txt" val file = File(File(System.getProperty("user.dir"), "build/stall-dumps").apply { mkdirs() }, name) file.writeText(sb.toString()) @@ -151,8 +181,9 @@ class StallWatch(private val limitMs: Long = 60_000) : TestRule { blocking.forEach { sb.append(" ${id(it)} ${it.state}, ${it.suspendedAt()}\n") } sb.append('\n') - for (c in all.take(MAX_COROUTINES)) { + fun detail(c: Probed) { sb.append("coroutine ${id(c)} state=${c.state} dispatcher=${c.dispatcher}\n") + sb.append(" created during: ${createdDuring(c)}\n") sb.append(" context: ${c.context}\n") sb.append(" suspended at: ${c.suspendedAt()}\n") val st = c.stack() @@ -169,7 +200,28 @@ class StallWatch(private val limitMs: Long = 60_000) : TestRule { dumpObject(sb, c.context[ContinuationInterceptor], 2, " ", HashSet()) } } - if (all.size > MAX_COROUTINES) sb.append("... ${all.size - MAX_COROUTINES} more coroutines not listed\n") + // The coroutines named in the summary are the ones at fault, and they are usually the newest: in full, whatever the cap. + val named = (never + holders + callers + onMutex + blocking).toSet() + val namedInOrder = all.filter { it in named } + sb.append("DETAILS of the ${namedInOrder.size} coroutines named in the summary (oldest first)\n\n") + namedInOrder.forEach { detail(it) } + // The rest: newest first, capped, with the number left out. + val rest = all.filter { it !in named }.asReversed() + sb.append("DETAILS of the other coroutines (newest first, at most $MAX_COROUTINES)\n\n") + rest.take(MAX_COROUTINES).forEach { detail(it) } + if (rest.size > MAX_COROUTINES) sb.append("... ${rest.size - MAX_COROUTINES} older coroutines not listed in detail\n") + } + + /** The watched class during which the coroutine was created, from the coroutine counter noted when each class started. */ + private fun createdDuring(c: Probed): String { + val id = c.coroutineId ?: return "unknown (no CoroutineId in its context)" + val started = startedClasses().mapNotNull { e -> + e.substringAfter("after coroutine id ", "").trim().toLongOrNull()?.let { e.substringBefore(" @") to it } + } + if (started.isEmpty()) return "unknown (no class start recorded)" + val owner = started.lastOrNull { id > it.second } + return if (owner == null) "before the first watched class started (${started.first().first}), or in a class without the rule" + else "${owner.first}, or later in a class without the rule before the next watched class started" } private fun dumpObject(sb: StringBuilder, o: Any?, depth: Int, indent: String, seen: MutableSet) { @@ -199,6 +251,8 @@ class StallWatch(private val limitMs: Long = 60_000) : TestRule { } val state: String get() = call("getState").toString() + /** The counter kotlinx.coroutines puts into every context while its debug mode is on (it is under -ea). Increases with creation. */ + val coroutineId: Long? get() = runCatching { COROUTINE_ID.find(context.toString())?.groupValues?.get(1)?.toLong() }.getOrNull() val context: CoroutineContext get() = call("getContext") val dispatcher: String get() = context[ContinuationInterceptor]?.toString() ?: "none" val isBlocking: Boolean get() = dispatcher.contains("BlockingEventLoop") @@ -244,6 +298,10 @@ class StallWatch(private val limitMs: Long = 60_000) : TestRule { } } + /** Highest coroutine id alive now (0 if none): every coroutine created later has a higher one. -1 if the probes are not usable. */ + fun lastCoroutineId(): Long = + if (probesClass == null) -1 else runCatching { dump().maxOfOrNull { it.coroutineId ?: 0L } ?: 0L }.getOrDefault(-1) + fun dump(): List = (probesClass!!.getMethod("dumpCoroutinesInfo").invoke(probes) as List<*>).map { Probed(it!!) } } @@ -251,17 +309,19 @@ class StallWatch(private val limitMs: Long = 60_000) : TestRule { private companion object { const val STALL_EXIT_CODE = 70 const val MAX_COROUTINES = 150 + const val DUMP_BUDGET_MS = 30_000L + val COROUTINE_ID = Regex("""CoroutineId\((\d+)\)""") /** Set by Gradle (app/build.gradle.kts): where CI already collects the test report. */ const val COPY_DIR_PROPERTY = "nova.stallDumpCopyDir" const val CLASSES_PROPERTY = "nova.stallWatch.startedClasses" /** In a system property, not a field: the sandbox class loader can be replaced, the JVM cannot. */ - fun noteClassStarted(className: String) = synchronized(System.getProperties()) { + fun noteClassStarted(className: String, lastCoroutineId: Long) = synchronized(System.getProperties()) { val now = ManagementFactory.getRuntimeMXBean().uptime val known = System.getProperty(CLASSES_PROPERTY).orEmpty().split('\n').filter { it.isNotBlank() } if (known.none { it.substringBefore(" @") == className }) { - System.setProperty(CLASSES_PROPERTY, (known + "$className @ $now ms").joinToString("\n")) + System.setProperty(CLASSES_PROPERTY, (known + "$className @ $now ms, coroutines created after coroutine id $lastCoroutineId").joinToString("\n")) } }