Skip to content

fix(android): keep the foreground service through reconnects - #33

Merged
HarryCordewener merged 1 commit into
masterfrom
claude/project-thread-630v1g
Nov 26, 2026
Merged

HarryCordewener merged 1 commit into
masterfrom
claude/project-thread-630v1g

Conversation

@HarryCordewener

@HarryCordewener HarryCordewener commented Nov 26, 2026 •

Copy link
Copy Markdown
Member

Requested by Grave · project thread

Symptom

On Android, locking the screen loses or closes telnet connections again.

Root cause

ConnectionKeepAliveCoordinator halted the foreground service whenever no session was Connected. That includes Reconnecting, and the brief Disconnected that ForceReconnectAsync passes through after a network change (it calls ConnectAsync, which disconnects first).

Android 12+ refuses StartForegroundService while the app is in the background. So once a session blipped with the screen locked:

  1. the service stopped, releasing the partial wake lock;
  2. on reconnect, Start threw inside TelnetConnection.SetState(Connected), because the coordinator is a synchronous StateChanged subscriber;
  3. on the network-change path that failed ConnectAsync, leaving the session in Error with no retry. In the backoff loop it was swallowed as a failed attempt, the next attempt tore down the socket that had just connected, and the auto-login was skipped because Session.OnStateChanged raises StateChanged before it sends the login;
  4. with no service and no wake lock, the process was frozen until the phone was unlocked.

The Android code and toolchain did not change between v1.6 and v2.0: both release builds use SDK 10.0.300 and MAUI 10.0.20, and v2.0 used Android workload 36.1.69 (API 36). This failure mode has been there since the keep-alive was added. I could not find what makes the first drop happen more often now, and a device log would show it.

Fix

  • The coordinator moves to Core (SharpClient.Core.Connection) so it can be tested.
  • Connecting and Reconnecting count as active. The service halts only after 15 s with nothing active, which covers the transient Disconnected.
  • A Start/Halt failure is logged (it reaches the diagnostics log) and never reaches the connection. The next state change tries again.
  • Start is called only when the notification text changes. Once the service runs, AndroidConnectionKeepAlive re-posts the notification instead of calling StartForegroundService again.
  • The network-change signal is wired in MauiProgram to ReconnectAll, which logs a failed reconnect instead of dropping it unobserved.

Verification

  • New ConnectionKeepAliveCoordinatorTests (7): start on connect, no halt through Reconnecting or through Disconnected → Connecting → Connected, halt after the grace period, no restart for an unchanged status, a throwing Start contained and retried, ReconnectAll reaching every session.
  • CI on bba8463: Core 322/322, UI 96/96, Data 19/19 passed; Android head Release build passed.
  • Not run on a device yet.

Out of scope

  • An app in Error after a long outage still cannot start the service from the background. That would need a battery-optimisation exemption.
  • TelnetConnection.SetState still lets any subscriber exception fail a connect.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Rqqt7WhTrKwT2PgaSu4HcZ

Summary by CodeRabbit

  • New Features
    • Connection keep-alive now reflects active and reconnecting sessions, including the number of active connections.
    • Brief interruptions no longer immediately stop keep-alive; it remains active for a short grace period.
    • Network changes trigger reconnection attempts for active sessions.
  • Bug Fixes
    • Android keep-alive notifications retain their current status when network connectivity changes.
    • Repeated start requests no longer restart an already-running Android service.

The keep-alive coordinator halted the foreground service whenever no
session was Connected, which includes Reconnecting and the brief
Disconnected that a network-change reconnect passes through. Android 12+
refuses to start a foreground service while the app is in the
background, so with the screen locked the service could not come back:
the start threw inside the connection's state change, the reconnect that
raised it failed (or, in the backoff loop, skipped the auto-login), and
without the wake lock the process was frozen.

- Count Connecting and Reconnecting as active, and halt only after a
  15 s grace period with nothing active.
- Never let a keep-alive failure escape into the connection; log it.
- Once the service runs, change its notification text in place instead
  of calling StartForegroundService again.
- Move the coordinator into Core so it has tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Rqqt7WhTrKwT2PgaSu4HcZ
@coderabbitai

coderabbitai Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Explain Change →

Caution

Review failed

The pull request is closed.

Walkthrough

The connection keep-alive coordinator moves to Core and manages session activity, reconnect requests, and delayed halts. MauiProgram routes network changes to the coordinator. Android retains the current notification status when the network changes.

Changes

Connection keep-alive

Layer / File(s) Summary
Core session ownership and reconnect wiring
src/SharpClient.Core/Connection/ConnectionKeepAliveCoordinator.cs, src/SharpClient.App/Services/ConnectionKeepAliveCoordinator.cs, src/SharpClient.App/MauiProgram.cs, src/SharpClient.App/Services/NetworkChangeSignal.cs, src/SharpClient.Core/Connection/IConnectionKeepAlive.cs, tests/SharpClient.Tests/Connection/ConnectionKeepAliveCoordinatorTests.cs, tests/SharpClient.Tests/Sessions/FakeSession.cs
The Core coordinator tracks sessions and reconnects them. MauiProgram routes network-change events to ReconnectAll. The former App coordinator is removed. Tests cover reconnect requests, including session failures.
Keep-alive status and delayed halt
src/SharpClient.Core/Connection/ConnectionKeepAliveCoordinator.cs, tests/SharpClient.Tests/Connection/ConnectionKeepAliveCoordinatorTests.cs
The coordinator updates keep-alive status as sessions connect or reconnects occur. It schedules a halt after a 15-second grace period when no session is active. Tests cover status changes, delayed halts, and start failures.
Android service and notification status
src/SharpClient.App/Platforms/Android/AndroidConnectionKeepAlive.cs, src/SharpClient.App/Platforms/Android/ConnectionKeepAliveService.cs
On Android API 26 or later, repeated starts update the running service status instead of starting the service again. The service retains and posts that status across network changes.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant MauiProgram
  participant NetworkChangeSignal
  participant ConnectionKeepAliveCoordinator
  participant Session
  MauiProgram->>NetworkChangeSignal: Subscribe ReconnectAll to Changed
  NetworkChangeSignal->>ConnectionKeepAliveCoordinator: Changed invokes ReconnectAll
  ConnectionKeepAliveCoordinator->>Session: ForceReconnectAsync
Loading
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

@HarryCordewener HarryCordewener self-assigned this Nov 26, 2026
@HarryCordewener
HarryCordewener marked this pull request as ready for review November 26, 2026 21:16
Copilot AI balanced review requested due to automatic review settings November 26, 2026 21:16

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing. Review the Copilot code review billing settings.

Copy link
Copy Markdown
Member Author

The copilot-pull-request-reviewer failure is not caused by this PR. The reviewer stopped with SessionModelError: You have exceeded your monthly quota (HTTP 402) before it looked at the diff. CI is green on bba8463: unit tests (322/96/19) and the Android head Release build.


Generated by Claude Code

@HarryCordewener
HarryCordewener merged commit f4b7862 into master Nov 26, 2026
2 of 4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants