Skip to content

Graceful server-down handling: reachability monitor, fast timeouts, stale-content indicator, pre-play gating - #51

Merged
Quick104 merged 3 commits into
mainfrom
claude/modest-proskuriakova-14f155
Jul 3, 2026
Merged

Quick104 merged 3 commits into
mainfrom
claude/modest-proskuriakova-14f155

Conversation

@Quick104

@Quick104 Quick104 commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Problem

When the server is down, the app still looks fully functional: screens hydrate from the in-memory ResponseCache and swallow failed refreshes silently, so pull-to-refresh shows no error. Tapping an item to play opens the player, spins for up to ~60s (no URLSession timeout was ever configured), then hits a full-screen error wall.

Offline downloads were never the problem — OfflinePlayback already plays local copies with zero server round-trips (airplane-mode safe). The gap was detection and honest degradation, and this PR intentionally leaves the downloads subsystem untouched.

What changed

  • Networking/ConnectionMonitor.swift (new) — app-wide connection state. NWPathMonitor tracks device connectivity; server reachability is learned passively from every HTTPClient request outcome (any HTTP response — even 4xx/5xx — proves the server is alive; transport failures, excluding cancellations, mark it unreachable). While unreachable it re-probes GET /api/v1/health every 15s so the UI self-heals as soon as the server returns. Optimistic by design: an unknown state never blocks a request.
  • HTTPClient — timeoutIntervalForRequest = 15 so a dead-but-routable server fails in seconds instead of a minute (this is the max quiet gap between bytes, not a total budget, so slow-but-alive responses are unaffected). perform() feeds request outcomes to the monitor.
  • Components/ServerUnreachablePill.swift (new) — "Can't reach server — showing cached content" pill, shown in the same overlay slot as RefreshStatusPill on Home, the Browse grid, and library Recommended whenever cached content is painted while unreachable. Disappears automatically on the first successful response.
  • ItemDetailView pre-play gate — if the server is unreachable and the item has a playable download, the local copy plays directly (the "Downloaded vs Stream" choice is skipped since streaming can't start). With no download, a "Can't Reach Server" alert appears before the player is presented, with a "Try Anyway" escape hatch in case the reachability state is stale.
  • MainTabView offline landing (Android parity) — launching with no network and playable local downloads lands on the Downloads tab instead of a Home screen that can't load.

Reviewer notes

  • Reachability is never actively polled while healthy — zero extra traffic in the normal case; the probe loop only runs while a failure has actually been observed.
  • tvOS gets the monitor and fast timeouts via shared code; the pill and pre-play gate live in the iOS/macOS surfaces (tvOS has its own detail views — candidate follow-up).
  • The cast (SiloControl) play branch is not gated: the Apple TV target does its own streaming and reports its own failures.
  • Verified: iOS, tvOS, and macOS schemes build; full test suite passes. Not yet validated against a live server being killed mid-session — that's the recommended manual check (stop the server, confirm the pill appears and Play degrades as described).

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added clearer offline/server reachability pills across Home and Browse, including messaging when cached content is shown.
    • Improved “server unreachable” handling on the detail screen with a “Can’t Reach Server” alert and “Try Anyway” retry.
    • Enhanced offline startup behavior to route users to Downloads when playable offline content exists.
  • Bug Fixes

    • Kept the mini control bar visible during reconnecting/remote-control scenarios.
    • Improved network detection and recovery to distinguish device-offline vs server-unreachable.
    • Extended timeouts for slower subtitle and playback/transcode operations to reduce premature failures.

Quick104 and others added 2 commits July 2, 2026 23:19
Dismissing the remote sheet flipped isShowingRemoteControl, which
re-attached the tabViewBottomAccessory and triggered the system's
accessory slide-in — a second animation on top of the sheet dismissal.
Keep the bar visible (covered by the sheet) so dismissal just reveals it.

Co-Authored-By: Claude Fable 5 <[email protected]>
…tale-content pill, pre-play gating

When the server was down the app silently served the in-memory cache
(refresh showed no error) and a Play tap opened the player, hung up to
60s on the default URLSession timeout, then error-walled. Offline
downloads already play with zero server calls; the gap was detection
and honest degradation, not capability.

- New ConnectionMonitor: NWPathMonitor device state plus passive server
  reachability fed from every HTTPClient request outcome (any HTTP
  response = reachable; transport failure minus cancellation =
  unreachable), with a 15s GET /api/v1/health re-probe loop while
  unreachable so state self-heals.
- HTTPClient: 15s timeoutIntervalForRequest so a dead server fails in
  seconds; perform() reports outcomes to the monitor.
- ServerUnreachablePill ("Can't reach server — showing cached content")
  in the RefreshStatusPill slot on Home, Browse grid, and library
  Recommended whenever cached content is painted while unreachable.
- ItemDetailView pre-play gate: unreachable + playable download plays
  the local copy directly (skips the source-choice alert); unreachable
  with no download shows a "Can't Reach Server" alert with a Try
  Anyway escape hatch instead of presenting a doomed player.
- MainTabView offline landing (Android parity): device offline at
  launch + playable downloads lands on the Downloads tab.

Co-Authored-By: Claude Fable 5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 3, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: cae032ff-2dc7-4e5d-ab3b-f7247fa28eaf

📥 Commits

Reviewing files that changed from the base of the PR and between 98149c0 and fe6a1f4.

📒 Files selected for processing (4)
  • iosApp/iosApp/ContentView.swift
  • iosApp/iosApp/Networking/ContinuumAI.swift
  • iosApp/iosApp/Networking/ContinuumAPI.swift
  • iosApp/iosApp/Networking/HTTPClient.swift
🚧 Files skipped from review as they are similar to previous changes (1)
  • iosApp/iosApp/ContentView.swift

📝 Walkthrough

Walkthrough

Adds reachability tracking through ConnectionMonitor, threads it into HTTPClient, shows a new offline pill across several screens, adjusts detail playback for unreachable servers, adds an offline startup destination check, and changes mini-bar visibility to ignore the remote-control sheet state.

Changes

Server Reachability Monitoring and Offline UI

Layer / File(s) Summary
ConnectionMonitor core implementation
iosApp/iosApp/Networking/ConnectionMonitor.swift
Adds the ConnectionMonitor singleton with device/server state tracking, NWPathMonitor wiring, passive/active reachability signaling, and reprobe loop lifecycle.
HTTPClient timeout and reachability wiring
iosApp/iosApp/Networking/HTTPClient.swift
Adds standard and extended request sessions, threads timeout selection through request sending, and reports successful responses and transport failures to ConnectionMonitor.
ServerUnreachablePill component
iosApp/iosApp/Components/ServerUnreachablePill.swift
Adds the pill view with conditional icon/text, styling, and accessibility label.
Offline pill wiring in Browse/Home screens
iosApp/iosApp/Screens/Browse/BrowseView.swift, iosApp/iosApp/Screens/Home/HomeView.swift
Displays ServerUnreachablePill in browse and home overlays when offline with cached content, and updates related animations.
Detail view unreachable-server playback handling
iosApp/iosApp/Screens/Detail/ItemDetailView.swift
Adds unreachable-play request state, a “Can’t Reach Server” alert, and reachability guards for offline and streaming playback paths.
Initial offline start-destination check
iosApp/iosApp/ContentView.swift
Adds a startup task that waits for initial path state and selects the downloads tab when offline and playable offline content exists.
Mini-bar visibility logic changes
iosApp/iosApp/Control/iOS/NowPlayingShelf.swift, iosApp/iosApp/Control/iOS/SiloControlMiniBar.swift
Removes the remote-control-sheet visibility gate and changes the animation trigger to reconnect state.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant NWPathMonitor
  participant ConnectionMonitor
  participant HTTPClient
  participant ItemDetailView
  participant ServerUnreachablePill

  NWPathMonitor->>ConnectionMonitor: path update (online/offline)
  HTTPClient->>ConnectionMonitor: noteServerUnreachable() / noteServerResponded()
  ConnectionMonitor->>ConnectionMonitor: update isDeviceOnline / serverStatus
  ConnectionMonitor-->>ServerUnreachablePill: isOffline / isDeviceOnline
  ItemDetailView->>ConnectionMonitor: isServerReachable check
  ConnectionMonitor-->>ItemDetailView: reachable / unreachable
  ItemDetailView->>ItemDetailView: present offline player or unreachable alert
  ItemDetailView->>ConnectionMonitor: probeServer() (Try Anyway)
  ConnectionMonitor->>HTTPClient: health request
  HTTPClient-->>ConnectionMonitor: success/failure
  ConnectionMonitor-->>ItemDetailView: probe result
  ItemDetailView->>ItemDetailView: present streaming player
Loading

Possibly related PRs

  • Silo-Server/silo-apple#41: Both PRs modify the same offline playback decision flow in ItemDetailView.swift, with this PR adding server-unreachable handling on top of cached-offline playback.
  • Silo-Server/silo-apple#45: Both PRs touch ContinuumAI.swift timeout behavior for subtitle provider calls, and this PR extends the same HTTPClient timeout path those methods use.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main changes: reachability monitoring, timeouts, stale-content UI, and pre-play gating.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/modest-proskuriakova-14f155

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 98149c00a8

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

// leaves a dead-but-routable server spinning for a minute before the
// user sees anything. 15s is the max quiet gap between bytes, not a
// total budget, so slow-but-alive responses are unaffected.
config.timeoutIntervalForRequest = 15

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Avoid timing out legitimate subtitle searches

When a subtitle-provider search takes the documented 20–30 seconds before the server sends a response (ContinuumAI.searchSubtitles notes this is expected), this global 15-second timeoutIntervalForRequest makes HTTPClient throw URLError.timedOut and also marks the healthy server unreachable. The shorter fail-fast timeout needs to be scoped away from endpoints that legitimately wait on upstream providers, or those searches will fail for users with slower providers.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in fe6a1f4. Added an HTTPTimeout class (.standard/.extended) backed by a second URLSession with a 90s idle timeout — a separate session rather than per-request timeoutInterval so the effective timeout is unambiguous. searchSubtitles, downloadSubtitle (also a synchronous upstream fetch), startPlayback, and startTranscode are marked .extended. cancelInFlightRequests() cancels both sessions so a server switch can't leak a long-wait response.

Comment thread iosApp/iosApp/ContentView.swift Outdated
Comment on lines +600 to +601
DownloadManager.shared.downloadsEnabled,
DownloadManager.shared.records.contains(where: { $0.isPlayableOffline })

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Load downloads before the offline tab check

On a cold authenticated launch, DownloadManager starts with an empty in-memory file and is only hydrated later by DownloadManager.shared.onAppActive() in the parent auth-state task after several awaited network refreshes; this MainTabView task only waits for the initial network path and then checks downloadsEnabled/records once. In the offline launch case this will usually see downloadsEnabled == false and empty records, return, and never rerun when the persisted playable downloads are loaded, so the new offline start-destination does not take effect.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in fe6a1f4. The task now calls DownloadManager.shared.activateScopeIfNeeded() directly before the check — it's disk-only (loads the persisted registry, which also derives downloadsEnabled from the persisted capability via the file didSet) and idempotent, so the later onAppActive() skips the reload.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 2

🧹 Nitpick comments (2)
iosApp/iosApp/Screens/Browse/BrowseView.swift (1)

425-438: 📐 Maintainability & Code Quality | 🔵 Trivial

Duplicated offline-pill overlay pattern across three views.

The same isRefreshing ? RefreshStatusPill : (isOffline && !empty ? ServerUnreachablePill : nil) shape, plus matching padding/transition/zIndex/animation, is repeated verbatim here, in HomeView, and (per the PR summary) presumably similar overlay logic exists elsewhere. Consider extracting a small reusable ViewModifier or helper view (e.g. statusPillOverlay(isRefreshing:isOffline:hasContent:topPadding:)) to keep the three call sites in sync as this logic evolves.

♻️ Sketch of a reusable modifier
struct StatusPillOverlay: ViewModifier {
    let isRefreshing: Bool
    let isOffline: Bool
    let hasContent: Bool
    let topPadding: CGFloat

    func body(content: Content) -> some View {
        content.overlay(alignment: .top) {
            if isRefreshing {
                RefreshStatusPill()
                    .padding(.top, topPadding)
                    .transition(.move(edge: .top).combined(with: .opacity))
                    .zIndex(2)
            } else if isOffline, hasContent {
                ServerUnreachablePill()
                    .padding(.top, topPadding)
                    .transition(.move(edge: .top).combined(with: .opacity))
                    .zIndex(2)
            }
        }
        .animation(.easeInOut(duration: 0.18), value: isRefreshing)
        .animation(.easeInOut(duration: 0.18), value: isOffline)
    }
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@iosApp/iosApp/Screens/Browse/BrowseView.swift` around lines 425 - 438, The
status-pill overlay logic in BrowseView is duplicated and should be centralized
to keep behavior consistent with HomeView and other similar screens. Extract the
repeated conditional overlay, padding, transition, zIndex, and animation into a
reusable helper such as a ViewModifier or small view (for example, a
statusPillOverlay or StatusPillOverlay) that takes isRefreshing, isOffline,
hasContent, and topPadding. Then replace the inline blocks in BrowseView and the
matching call sites so RefreshStatusPill and ServerUnreachablePill are rendered
through the shared abstraction.
iosApp/iosApp/Control/iOS/NowPlayingShelf.swift (1)

27-28: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Visibility predicate duplicated with SiloControlMiniBar.isVisible.

This expression (hasActiveSession && !isAutoResuming) || isReconnecting is now byte-identical to SiloControlMiniBar.isVisible (SiloControlMiniBar.swift Lines 21-22). Since the parent gate and the child's own guard must stay in lock-step, consider a single source of truth (e.g., have SiloControlMiniBar.isVisible reference NowPlayingShelf.controlBarVisible(controller)) so a future change to one doesn't silently diverge.

♻️ One option
// In SiloControlMiniBar
private var isVisible: Bool { NowPlayingShelf.controlBarVisible(controller) }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@iosApp/iosApp/Control/iOS/NowPlayingShelf.swift` around lines 27 - 28,
`NowPlayingShelf.controlBarVisible(_:)` duplicates the same visibility predicate
used by `SiloControlMiniBar.isVisible`, so make the logic a single source of
truth. Keep the predicate in `NowPlayingShelf.controlBarVisible(_:)` and update
`SiloControlMiniBar.isVisible` to call that helper instead of re-implementing
`(hasActiveSession && !isAutoResuming) || isReconnecting`. This keeps
`SiloControlClient` visibility rules in sync and prevents future divergence.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@iosApp/iosApp/ContentView.swift`:
- Around line 593-605: The startup routing task in ContentView’s .task block can
overwrite a tab choice made during launch, so only apply the offline default
route when no navigation has happened yet. In the selectedTab = .downloads path,
add a guard against changing tabs unless selectedTab is still the initial .home
value (and/or otherwise ensure router.requestedTab has not already set a
destination) after waitForInitialPath() completes. Keep the logic localized to
the startup routing block so it only initializes the tab once.

In `@iosApp/iosApp/Networking/HTTPClient.swift`:
- Around line 389-406: performRefresh bypasses the shared reachability tracking
in perform, so refresh failures and successes never update ConnectionMonitor.
Update performRefresh to mirror perform’s server-state handling by marking the
server unreachable on non-cancelled transport errors and marking it responded on
any valid HTTPURLResponse, reusing
ConnectionMonitor.shared.noteServerUnreachable() and noteServerResponded() so
refresh traffic feeds the same logic.

---

Nitpick comments:
In `@iosApp/iosApp/Control/iOS/NowPlayingShelf.swift`:
- Around line 27-28: `NowPlayingShelf.controlBarVisible(_:)` duplicates the same
visibility predicate used by `SiloControlMiniBar.isVisible`, so make the logic a
single source of truth. Keep the predicate in
`NowPlayingShelf.controlBarVisible(_:)` and update
`SiloControlMiniBar.isVisible` to call that helper instead of re-implementing
`(hasActiveSession && !isAutoResuming) || isReconnecting`. This keeps
`SiloControlClient` visibility rules in sync and prevents future divergence.

In `@iosApp/iosApp/Screens/Browse/BrowseView.swift`:
- Around line 425-438: The status-pill overlay logic in BrowseView is duplicated
and should be centralized to keep behavior consistent with HomeView and other
similar screens. Extract the repeated conditional overlay, padding, transition,
zIndex, and animation into a reusable helper such as a ViewModifier or small
view (for example, a statusPillOverlay or StatusPillOverlay) that takes
isRefreshing, isOffline, hasContent, and topPadding. Then replace the inline
blocks in BrowseView and the matching call sites so RefreshStatusPill and
ServerUnreachablePill are rendered through the shared abstraction.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: fb1d7b1a-349b-4204-b074-8451feb35968

📥 Commits

Reviewing files that changed from the base of the PR and between 5e0b745 and 98149c0.

📒 Files selected for processing (9)
  • iosApp/iosApp/Components/ServerUnreachablePill.swift
  • iosApp/iosApp/ContentView.swift
  • iosApp/iosApp/Control/iOS/NowPlayingShelf.swift
  • iosApp/iosApp/Control/iOS/SiloControlMiniBar.swift
  • iosApp/iosApp/Networking/ConnectionMonitor.swift
  • iosApp/iosApp/Networking/HTTPClient.swift
  • iosApp/iosApp/Screens/Browse/BrowseView.swift
  • iosApp/iosApp/Screens/Detail/ItemDetailView.swift
  • iosApp/iosApp/Screens/Home/HomeView.swift

Comment thread iosApp/iosApp/ContentView.swift Resolved
…porting, offline-landing fixes

- Codex P1: the global 15s idle timeout would kill legitimately slow
  endpoints. Add HTTPTimeout (.standard/.extended) backed by a second
  90s URLSession — deterministic, unlike per-request timeoutInterval
  precedence — and mark subtitle search/download and playback
  start/transcode-start as .extended. cancelInFlightRequests() now
  cancels both sessions so a server switch can't leak a long-wait
  response.
- Codex P2: the offline start-destination check raced DownloadManager
  hydration (onAppActive runs after several awaited network refreshes
  in the auth task). Hydrate the scope from disk directly before the
  check — activateScopeIfNeeded() is disk-only and idempotent.
- CodeRabbit: only apply the offline landing when nothing has
  navigated yet (selectedTab still .home, no pending requestedTab).
- CodeRabbit: performRefresh bypasses perform(), so feed
  ConnectionMonitor from the refresh path too.

Co-Authored-By: Claude Fable 5 <[email protected]>
@Quick104
Quick104 merged commit 21bafb1 into main Jul 3, 2026
1 check was pending
@Quick104
Quick104 deleted the claude/modest-proskuriakova-14f155 branch July 3, 2026 05:45
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.

1 participant