From b12928c7f3af6d138a3e0131aa84fb0ee3d0fdfd Mon Sep 17 00:00:00 2001 From: Jason Monk Date: Sat, 18 Apr 2026 12:49:39 -0400 Subject: [PATCH] Fix #243: Always reconnect on FCM wake, never trust stale tunnel state (#245) An FCM wake from the relay proves it needs a fresh WebSocket -- it would not have sent the push if it already had one. The previous WakeAction.Skip path trusted a passing mux-level health check, but a half-open TCP socket can sit in ACTIVE while the relay has already dropped its WebSocket mapping (idle timeout, restart, NAT timeout). Every inbound MCP call then fails until the user force-stops the app. Remove WakeAction.Skip entirely. The decider now always returns Reconnect on FCM wake. The health check ping is still performed for diagnostics: wasStale=true means the tunnel was confirmed dead, false means it looked alive but the relay disagrees. Co-authored-by: Claude Opus 4 (1M context) --- .../tunnel/TunnelClientImplTest.kt | 76 +++++++++++++++++++ .../work/TunnelForegroundService.kt | 13 ++-- .../rousecontext/work/WakeReconnectDecider.kt | 31 +++++--- .../TunnelForegroundServiceLifecycleTest.kt | 17 +++-- .../work/WakeReconnectDeciderTest.kt | 7 +- 5 files changed, 119 insertions(+), 25 deletions(-) diff --git a/core/tunnel/src/jvmTest/kotlin/com/rousecontext/tunnel/TunnelClientImplTest.kt b/core/tunnel/src/jvmTest/kotlin/com/rousecontext/tunnel/TunnelClientImplTest.kt index 718d6008..c4976dbb 100644 --- a/core/tunnel/src/jvmTest/kotlin/com/rousecontext/tunnel/TunnelClientImplTest.kt +++ b/core/tunnel/src/jvmTest/kotlin/com/rousecontext/tunnel/TunnelClientImplTest.kt @@ -688,6 +688,82 @@ class TunnelClientImplTest { } } + @Suppress("LongMethod") + @Test + fun `healthCheck returns false after server silently drops connection`() = runBlocking { + // Simulates a half-open socket: the server stops without sending a + // WebSocket close frame. The device's local TCP socket may still look + // alive until a write or read fails. A mux-level Ping with a short + // timeout must return false, proving the tunnel is dead. See #243. + val port = findFreePort() + val serverSessionRef = CompletableDeferred() + + val server = embeddedServer(CIO, port = port) { + install(ServerWebSockets) + routing { + webSocket("/tunnel") { + serverSessionRef.complete(this) + // Echo Pongs for the first Ping so the tunnel looks alive + // initially. Then the server is killed externally. + for (frame in incoming) { + if (frame is Frame.Binary) { + val muxFrame = MuxCodec.decode(frame.readBytes()) + if (muxFrame is MuxFrame.Ping) { + send( + Frame.Binary( + true, + MuxCodec.encode(MuxFrame.Pong(muxFrame.nonce)) + ) + ) + } + } + } + } + } + } + server.start(wait = false) + + try { + val client = TunnelClientImpl( + scope = this, + webSocketFactory = KtorWebSocketFactory(), + // Disable keepalive so it doesn't interfere with the test. + keepaliveIntervalMillis = 600_000L, + keepaliveTimeoutMillis = 10_000L, + keepaliveMaxMisses = 100 + ) + client.connect("ws://localhost:$port/tunnel") + assertEquals(TunnelState.CONNECTED, client.state.value) + + // Verify the tunnel is initially alive. + val alive = client.healthCheck(kotlin.time.Duration.parse("2s")) + assertTrue(alive, "healthCheck should pass while server is up") + + // Kill the server without sending a close frame — simulates the + // relay dropping the TCP connection after idle timeout or crash. + server.stop(0, 0) + // Brief delay for the TCP RST / FIN to propagate. + delay(500) + + // The tunnel's local state may still be CONNECTED because the + // WebSocket library hasn't noticed the drop yet. A health check + // must detect it. + val stale = client.healthCheck(kotlin.time.Duration.parse("2s")) + assertTrue(!stale, "healthCheck must return false after server drops connection") + + // Clean up: the client should eventually reach DISCONNECTED. + withTimeout(10_000) { + while (client.state.value != TunnelState.DISCONNECTED) { + delay(50) + } + } + + coroutineContext.cancelChildren() + } finally { + server.stop(0, 0) // idempotent + } + } + @Test fun `connection failure emits error on SharedFlow`() = runBlocking { val client = TunnelClientImpl(this, KtorWebSocketFactory()) diff --git a/work/src/main/kotlin/com/rousecontext/work/TunnelForegroundService.kt b/work/src/main/kotlin/com/rousecontext/work/TunnelForegroundService.kt index 5b83c9d2..56f2cc40 100644 --- a/work/src/main/kotlin/com/rousecontext/work/TunnelForegroundService.kt +++ b/work/src/main/kotlin/com/rousecontext/work/TunnelForegroundService.kt @@ -152,17 +152,20 @@ class TunnelForegroundService : LifecycleService() { Log.i(TAG, "Already connecting, skipping") return } - WakeAction.Skip -> { - Log.i(TAG, "Tunnel is active and responsive, skipping reconnect") - return - } is WakeAction.Reconnect -> { val currentState = tunnelClient.state.value if (action.wasStale) { Log.w(TAG, "Tunnel reports ACTIVE but failed health check, reconnecting") + } else if (currentState == TunnelState.ACTIVE) { + // Health check passed but relay sent FCM anyway — relay lost + // its WebSocket mapping (idle timeout, restart, etc.). See #243. + Log.w( + TAG, + "Tunnel health check passed but relay requested wake, reconnecting" + ) } if (currentState == TunnelState.ACTIVE || currentState == TunnelState.CONNECTED) { - if (!action.wasStale) { + if (currentState == TunnelState.CONNECTED) { Log.i(TAG, "Already connected, disconnecting first to refresh") } // Mark intentional so the state observer doesn't trigger reconnect diff --git a/work/src/main/kotlin/com/rousecontext/work/WakeReconnectDecider.kt b/work/src/main/kotlin/com/rousecontext/work/WakeReconnectDecider.kt index a4613460..94bf843a 100644 --- a/work/src/main/kotlin/com/rousecontext/work/WakeReconnectDecider.kt +++ b/work/src/main/kotlin/com/rousecontext/work/WakeReconnectDecider.kt @@ -6,20 +6,24 @@ import kotlin.time.Duration /** * Decides whether a wake-up (FCM, Start command, etc.) should trigger a new - * connect, skip, or force a reconnect because the tunnel is silently dead. + * connect or if one is already in progress. * * Split out from [TunnelForegroundService] for unit testing -- the service * itself is awkward to instantiate in a JVM test. * - * See issue #179: the previous implementation trusted - * `TunnelClient.state == ACTIVE` as "already connected, skip". Under a - * half-open socket that flag stays ACTIVE forever and every FCM wake is - * dropped. We now actively probe with a bounded-deadline Ping before - * trusting the state. + * History: + * - #179: stopped trusting `state == ACTIVE` as "already connected, skip" and + * introduced a mux-level Ping probe before skipping. + * - #243: removed the Skip path entirely. An FCM wake means the relay needs a + * fresh WebSocket — it would not have sent the push if it already had one. + * Even when the device's health check Ping/Pong succeeds (the TCP socket is + * alive), the relay's routing table no longer maps this device to that + * WebSocket. Skipping reconnect leaves the relay stuck waiting, and every + * inbound MCP call fails. The health check is still performed for + * diagnostics: [WakeAction.Reconnect.wasStale] == true means the tunnel was + * confirmed dead, false means it looked alive but the relay disagrees. */ sealed class WakeAction { - /** Tunnel is healthy; do not reconnect. */ - object Skip : WakeAction() /** * Tear down the current tunnel (if any) and establish a fresh one. @@ -35,9 +39,12 @@ sealed class WakeAction { object WakeReconnectDecider { /** - * Inspect the tunnel and decide what to do. On ACTIVE, actively probes - * via [TunnelClient.healthCheck] with the given timeout before trusting - * the state flag. + * Inspect the tunnel and decide what to do. + * + * Always returns [WakeAction.Reconnect] unless a connect is already in + * flight. When the tunnel is ACTIVE, a health check Ping is still sent so + * [WakeAction.Reconnect.wasStale] can distinguish "confirmed dead" from + * "looked alive but relay lost the connection" in logs. */ suspend fun decide(tunnelClient: TunnelClient, healthCheckTimeout: Duration): WakeAction = when (tunnelClient.state.value) { @@ -48,7 +55,7 @@ object WakeReconnectDecider { } catch (_: Exception) { false } - if (live) WakeAction.Skip else WakeAction.Reconnect(wasStale = true) + WakeAction.Reconnect(wasStale = !live) } TunnelState.CONNECTED, TunnelState.DISCONNECTED, diff --git a/work/src/test/kotlin/com/rousecontext/work/TunnelForegroundServiceLifecycleTest.kt b/work/src/test/kotlin/com/rousecontext/work/TunnelForegroundServiceLifecycleTest.kt index 53736689..f0f6365b 100644 --- a/work/src/test/kotlin/com/rousecontext/work/TunnelForegroundServiceLifecycleTest.kt +++ b/work/src/test/kotlin/com/rousecontext/work/TunnelForegroundServiceLifecycleTest.kt @@ -133,11 +133,13 @@ class TunnelForegroundServiceLifecycleTest { ) } - // -- Test 2: FCM wake when ACTIVE with healthy probe skips reconnect -- + // -- Test 2: FCM wake when ACTIVE with healthy probe forces reconnect (#243) -- @Test - fun `FCM wake when ACTIVE with healthy probe skips reconnect`() { - // Start in ACTIVE state with a healthy probe + fun `FCM wake when ACTIVE with healthy probe forces reconnect`() { + // Start in ACTIVE state with a healthy probe. + // Issue #243: an FCM wake means the relay needs a fresh connection, + // even if the health check passes. The decider must return Reconnect. fakeTunnelClient.stateFlow.value = TunnelState.ACTIVE fakeTunnelClient.healthCheckResult = true @@ -151,11 +153,14 @@ class TunnelForegroundServiceLifecycleTest { controller.startCommand(0, 1) drainMain() - // WakeReconnectDecider returns Skip for ACTIVE + healthy probe assertTrue("healthCheck should have been called", fakeTunnelClient.healthCheckCalled) assertTrue( - "Should not call connect when probe is healthy", - fakeTunnelClient.connectCount == connectsBefore + "disconnect should have been called to tear down stale tunnel", + fakeTunnelClient.disconnectCalled + ) + assertTrue( + "Should call connect after FCM wake, even when probe is healthy", + fakeTunnelClient.connectCount > connectsBefore ) } diff --git a/work/src/test/kotlin/com/rousecontext/work/WakeReconnectDeciderTest.kt b/work/src/test/kotlin/com/rousecontext/work/WakeReconnectDeciderTest.kt index 519dbfe8..f486cc2c 100644 --- a/work/src/test/kotlin/com/rousecontext/work/WakeReconnectDeciderTest.kt +++ b/work/src/test/kotlin/com/rousecontext/work/WakeReconnectDeciderTest.kt @@ -40,10 +40,13 @@ class WakeReconnectDeciderTest { } @Test - fun `ACTIVE with healthy probe triggers Skip`() = runBlocking { + fun `ACTIVE with healthy probe triggers Reconnect with wasStale=false`() = runBlocking { + // Issue #243: FCM wake always reconnects. A passing health check only + // means the TCP socket is alive — the relay may have lost its mapping. val client = fakeClient(TunnelState.ACTIVE, healthy = true) val action = WakeReconnectDecider.decide(client, 2.seconds) - assertEquals(WakeAction.Skip, action) + assertTrue(action is WakeAction.Reconnect) + assertEquals(false, (action as WakeAction.Reconnect).wasStale) coVerify(exactly = 1) { client.healthCheck(any()) } }