Repository navigation
iOS offline downloads: monitoring, background refresh, push-triggered auto-download - #41
Conversation
…ded badges Iterates on the download feature: BGAppRefreshTask keeps series monitoring alive while backgrounded, local notifications announce queued/completed downloads, size estimates surface in the options sheet, downloaded badges appear on media cards, and offline playback, grouping, and manager views get follow-up fixes. Co-Authored-By: Claude Fable 5 <[email protected]>
The push relay already sends content-available on every APNs push, so iOS wakes the app for ~30s on each new-episode notification — the wake just only ran the inbox sync. Run DownloadManager.onAppActive() in parallel with it (the same path as the BG refresh task), so a monitored episode is enqueued into the background URLSession and downloads while the app stays closed. Retarget TokenStore before both syncs so a cold background launch authenticates, and widen the deadline to 20s since the monitoring chain ends with the pipeline kick that does the enqueue. Co-Authored-By: Claude Fable 5 <[email protected]>
📝 WalkthroughWalkthroughAdds offline downloads across iOS and macOS: persistence, API endpoints, background transfer, a central manager, UI, offline playback, and routing. It also adds a downloads Live Activity widget and embeds it in the iOS app target. ChangesOffline Downloads Feature
Estimated code review effort: 5 (Critical) | ~120 minutes 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 692a989aa7
ℹ️ 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".
| // Same capability-gated path as a foreground activation: | ||
| // activate scope → refresh capability → reconcile → | ||
| // monitoring/progress sync (which also kicks the pipeline). | ||
| await DownloadManager.shared.onAppActive() |
There was a problem hiding this comment.
Retarget TokenStore before background refresh sync
When the app is launched directly by BGTaskScheduler rather than from the foreground, ContentView.checkInitialState() may not have retargeted TokenStore yet. This handler goes straight into DownloadManager.onAppActive(), whose capability/reconcile calls authenticate through HTTPClient; with TokenStore still on the empty active server, those requests go out without the stored token and the 4-hour monitoring fallback silently does no work. The push wake path already performs this retarget before running the same sync, so the refresh handler should do the same.
Useful? React with 👍 / 👎.
| guard let seriesId = record.seriesId, | ||
| let subscription = subscription(forSeriesId: seriesId), | ||
| subscription.maxStorageBytes > 0 else { |
There was a problem hiding this comment.
Resolve monitored episodes before cap checks
For episodes registered by subscription sync, the row is added locally before the manifest hydrates seriesId; in that state the code uses contentId as the series id elsewhere, but this guard returns false whenever record.seriesId is nil. A monitored series with maxStorageBytes therefore starts newly queued episodes without applying its storage cap until after the pipeline has already begun. Use the episode row's contentId as the series id fallback before looking up the subscription.
Useful? React with 👍 / 👎.
| let used = file.records.values | ||
| .filter { $0.seriesId == seriesId && $0.localStatus == .completed } |
There was a problem hiding this comment.
Count in-flight bytes against subscription caps
When a subscription queues multiple episodes at once, processQueue() calls this check for each queued record before any of the earlier starts have completed. Because used only includes .completed records, every queued item sees the same free capacity and up to the concurrency limit can start, overshooting maxStorageBytes as soon as those transfers finish. Include active/reserved bytes for the series, or reserve the current record's size as records are started.
Useful? React with 👍 / 👎.
| case .allEventsDelivered: | ||
| sessionDelegate.backgroundCompletionHandler?() | ||
| sessionDelegate.backgroundCompletionHandler = nil |
There was a problem hiding this comment.
Flush the store before ending background events
When iOS relaunches the app for a background URLSession, prior .finished/.failed handlers only enqueue disk writes through persist()'s asynchronous saveChain. Calling the system completion handler immediately on .allEventsDelivered lets iOS suspend the process before the completed/failed record is written, leaving the store with a stale downloading task that can be requeued or orphan the moved media on the next launch. Await the outstanding save chain before invoking the background completion handler.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Actionable comments posted: 8
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
iosApp/iosApp/Notifications/SiloAppDelegate+Push.swift (1)
112-136: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy liftMake the deadline race return when the timer wins.
withTaskGroupwaits for both children to unwind, so a sleeping timer does not letsyncWithDeadlineexit untilrefreshFromRemoteNotification()/onAppActive()finish. Use a cancellation-aware unstructured race, or add cancellation checks between the sync phases.🤖 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/Notifications/SiloAppDelegate`+Push.swift around lines 112 - 136, The race in syncWithDeadline is still blocked by withTaskGroup waiting for both child tasks to unwind, so the timeout path cannot return immediately when the timer wins. Update the logic around syncWithDeadline in SiloAppDelegate+Push so the timer can end the operation promptly, either by using a cancellation-aware unstructured race or by adding explicit cancellation checks between the refreshFromRemoteNotification and onAppActive phases. Keep the existing retry/retarget flow intact, but make sure the timeout branch can exit without waiting for the sync work to finish.iosApp/iosApp/Screens/Player/PlayerViewModel.swift (1)
2724-2739: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winFinalize the prior server session before entering offline playback.
The offline branch never starts a replacement server session, but cleanup still calls
sessionBridge.stopSession(...). If the bridge is still holding the previous online session, offline teardown can report the offline position against that stale server session. Treat offline loads as finalizing the current server session up front, then skip the server stop during offline cleanup.Proposed fix
- let shouldFinalizeCurrentSession = finalizeCurrentSession + let shouldFinalizeCurrentSession = finalizeCurrentSession || request.offlineDownloadId != nil- if let offline = offlinePlaybackContext { + let offline = offlinePlaybackContext + let shouldStopServerSessionOnCleanup = offline == nil + if let offline { let finalOfflinePosition = completionProgressPositionForCurrentItem() let endedNaturally = hasReachedEndOfFile || showNextUpScreen // Strong capture on purpose: this is the last write of the // resume point and must not be dropped because the VM was // released between dismiss and the hop to the MainActor. @@ if let unavailabilityToken { await realtimeClient.removeUnavailabilityObserver(unavailabilityToken) } await realtimeClient.unbind() - await sessionBridge.stopSession(position: finalPosition, isPaused: true) + if shouldStopServerSessionOnCleanup { + await sessionBridge.stopSession(position: finalPosition, isPaused: true) + } }Also applies to: 2762-2792, 4677-4719
🤖 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/Player/PlayerViewModel.swift` around lines 2724 - 2739, Treat offline playback loads as finalizing the existing server session before the offline branch proceeds, instead of leaving cleanup to call sessionBridge.stopSession later. Update the fresh load flow in PlayerViewModel so the offline path sets the finalize flag up front and the subsequent teardown skips stopping the stale server session, while preserving the existing reportProgress behavior for non-finalizing loads. Check the freshLoadTask block and the related offline branches in PlayerViewModel to keep the sessionBridge calls aligned with the current playback mode.
🧹 Nitpick comments (4)
iosApp/iosApp/Components/EpisodeThumbCard.swift (1)
169-180: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract the duplicated "Downloaded indicator" overlay into a shared helper.
This block (condition +
DownloadedBadge()+ padding/frame + explanatory comment) is duplicated almost verbatim inMediaCard.swift(Lines 193-204). A sharedViewextension/modifier (e.g.,.downloadedBadgeOverlay(contentId:)) would keep both placements in sync as the badge logic evolves.♻️ Proposed shared helper
extension View { /// Bottom-trailing "downloaded" badge overlay, gated by capability-aware /// lookup so nothing renders on servers without downloads. `@ViewBuilder` func downloadedBadgeOverlay(contentId: String?, padding: CGFloat) -> some View { `#if` !os(tvOS) overlay(alignment: .bottomTrailing) { if let contentId, DownloadManager.shared.isDownloaded(contentId: contentId) { DownloadedBadge().padding(padding) } } `#else` self `#endif` } }🤖 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/Components/EpisodeThumbCard.swift` around lines 169 - 180, The “Downloaded indicator” overlay logic is duplicated between EpisodeThumbCard and MediaCard, so extract the condition plus DownloadedBadge placement into a shared View helper/modifier such as downloadedBadgeOverlay(contentId:padding:). Put the capability-aware DownloadManager.shared.isDownloaded lookup and the bottom-trailing overlay alignment inside that helper, then replace both inline blocks with the shared helper to keep badge behavior and comments in sync.iosApp/iosApp/Downloads/DownloadsSettingsView.swift (1)
87-91: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winPrefer bulk delete over per-record loop.
Looping
manager.deleteDownload(id:)per record re-runspersist(),refreshStorageUsage(), and an individual server delete request for every item.DownloadManager.deleteDownloads(ids:)(used elsewhere inDownloadsView.swift) batches these side effects into a single pass.♻️ Suggested fix
Button("Remove All", role: .destructive) { - for record in manager.records { - manager.deleteDownload(id: record.id) - } + manager.deleteDownloads(ids: manager.records.map(\.id)) }🤖 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/Downloads/DownloadsSettingsView.swift` around lines 87 - 91, The “Remove All” action in DownloadsSettingsView is deleting each record one by one via manager.deleteDownload(id:), which repeats persistence, storage refresh, and server deletes unnecessarily. Update the Button action to collect all current manager.records ids and call the bulk DeleteDownloadManager.deleteDownloads(ids:) path instead, matching the batching pattern already used in DownloadsView.swift and avoiding the per-record loop.iosApp/iosApp/Downloads/DownloadsView.swift (1)
159-167: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winDestructive multi-item deletes have no confirmation.
Multi-select bottom-bar delete and per-row "Delete All Episodes"/"Delete Download" context-menu actions call
manager.deleteDownloads/manager.deleteDownloadimmediately on tap, with no confirmation step — unlikeDownloadsSettingsView's "Remove All Downloads", which is gated behind aconfirmationDialog. Given downloads can represent large amounts of storage and re-fetching requires re-downloading, an accidental tap here is costly and irreversible without a re-download.Also applies to: 179-187, 278-301
🤖 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/Downloads/DownloadsView.swift` around lines 159 - 167, The destructive download deletion actions in DownloadsView are firing immediately without user confirmation. Update the multi-select bottom-bar delete path and the per-row context-menu actions in DownloadsView (including the delete helpers that call manager.deleteDownloads and manager.deleteDownload) to present a confirmationDialog before deleting, matching the pattern already used in DownloadsSettingsView. Keep the delete logic in the existing action methods, but gate invocation behind a confirm step so accidental taps do not remove downloads immediately.iosApp/iosApp/Downloads/SeriesDownloadControls.swift (1)
52-58: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winFragile fixed-delay sheet chaining.
Dismissing then re-presenting a sheet via a hard-coded 300ms
Task.sleepis fragile — if the dismiss animation takes longer (slower device, accessibility settings, low-power mode), the second sheet may be requested to present before SwiftUI has finished tearing down the first, silently failing to appear. Prefer thesheet(item:onDismiss:content:)overload and trigger the follow-up sheet from theonDismissclosure instead of guessing a delay.♻️ Suggested approach
- .sheet(item: $activeSheet) { sheet in + .sheet(item: $activeSheet, onDismiss: { + if pendingMonitorSheet { + pendingMonitorSheet = false + activeSheet = .monitor + } + }) { sheet in switch sheet { case .downloadOptions: SeriesDownloadOptionsSheet( ... - onMonitor: openMonitorSheet + onMonitor: { pendingMonitorSheet = true } )🤖 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/Downloads/SeriesDownloadControls.swift` around lines 52 - 58, The openMonitorSheet flow in SeriesDownloadControls currently relies on a hard-coded Task.sleep to chain sheets, which is fragile. Remove the fixed 300ms delay and instead use SwiftUI’s sheet(item:onDismiss:content:) pattern so the follow-up monitor sheet is triggered from the dismissal callback after the first sheet fully closes. Update the activeSheet handling in openMonitorSheet and the related sheet presentation logic to use the dismissal lifecycle rather than guessing timing.
🤖 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 210-224: The `handleDeepLink(_:)` branch for host `"downloads"`
should also respect `downloadsEnabled`, since it currently switches to
`.downloads` even when that tab is not available. Update the `ContentView`
deep-link handling to gate this path the same way as the other downloads entry
points, and only call `router.switchTab(to: .downloads)` when downloads are
enabled; otherwise ignore or fall back before setting `requestedTab` to an
unavailable tab.
In `@iosApp/iosApp/Downloads/DownloadFilePaths.swift`:
- Around line 149-162: The `sanitize(_:)` helper in `DownloadFilePaths` still
allows `.` through, so values like `.` and `..` can survive unchanged and be
used in `downloadDirectory`/`removeDownloadDirectory`. Update `sanitize(_:)` to
reject or replace dot-only and dot-containing traversal components instead of
preserving them, and make sure the resulting path segment cannot be `.` or `..`
even when `downloadId` comes from `ServerDownloadRow.id`. Keep the fix localized
to `sanitize(_:)` so all callers automatically benefit.
In `@iosApp/iosApp/Downloads/DownloadManager.swift`:
- Around line 1015-1018: The 401 handling in DownloadManager’s response switch
can retry forever because scheduleRetry(recordId:resumeData:refreshToken:) is
called without capping or incrementing retryCount, leaving the record stuck in
.downloading. Update the 401 branch to follow the same retry-limit logic used
for other failures: inspect and increment the record’s retryCount before
scheduling, and stop retrying once the maximum is reached. Use the existing
DownloadManager helpers and record.id/retryCount fields to keep the auth-failure
path bounded.
- Around line 1567-1576: The storage-cap check in exceedsStorageCap(for:) only
applies when record.seriesId is already present, so newly synced episode rows
with episodeId but nil seriesId bypass the cap. Update the lookup logic to
resolve the subscription and aggregate used storage for these fresh rows as
well, using the episode-based identity/path available in DownloadManager until
hydration fills in seriesId. Keep the maxStorageBytes enforcement in the same
method, but make sure the guard no longer returns false for newly synced episode
records that should count against the series cap.
- Around line 1-28: The DownloadManager type uses `@Observable` but the file only
imports Foundation and OSLog, so add the missing Observation import at the top
of DownloadManager.swift. Keep the existing DownloadError and DownloadManager
declarations unchanged; this fix is only about making the `@Observable` macro
available so the file compiles.
In `@iosApp/iosApp/Downloads/SeriesDownloadControls.swift`:
- Around line 94-107: The download and subscription actions in
SeriesDownloadControls are swallowing failures, so users get no indication when
`downloadSeason`, `downloadSeries`, or `save()` fail. Update the `optionButton`
actions and the `save()` path to catch errors explicitly instead of using
`try?`/empty `catch`, keep the sheet from dismissing on failure, and surface a
visible user-facing error for the relevant flows using the existing `manager`,
`selectedSeason`, and `save()`/subscription action logic.
In `@iosApp/iosApp/Downloads/Views/DownloadManagerRows.swift`:
- Around line 201-222: The revealButton in DownloadManagerRows should be hidden
from hit testing and accessibility when the swipe action is closed, since
opacity alone still leaves it in the hierarchy. Update the revealButton view so
it uses the same open-state condition as the swipe UI instead of only
.opacity(offset < -8 ? 1 : 0), and ensure the Button and its label are not
reachable by VoiceOver when closed.
In `@iosApp/iosApp/Notifications/SiloAppDelegate`+Push.swift:
- Around line 36-43: Retarget TokenStore before calling
DownloadManager.shared.activateScopeIfNeeded() in the SiloAppDelegate+Push
background completion path, because the current Task on the main actor may
activate downloads before app state is restored. Update the startup flow so the
active profile/scoped token is loaded first, then invoke
setBackgroundCompletionHandler(_:), and only after that call
activateScopeIfNeeded() to avoid releasing background session events against an
empty scope.
---
Outside diff comments:
In `@iosApp/iosApp/Notifications/SiloAppDelegate`+Push.swift:
- Around line 112-136: The race in syncWithDeadline is still blocked by
withTaskGroup waiting for both child tasks to unwind, so the timeout path cannot
return immediately when the timer wins. Update the logic around syncWithDeadline
in SiloAppDelegate+Push so the timer can end the operation promptly, either by
using a cancellation-aware unstructured race or by adding explicit cancellation
checks between the refreshFromRemoteNotification and onAppActive phases. Keep
the existing retry/retarget flow intact, but make sure the timeout branch can
exit without waiting for the sync work to finish.
In `@iosApp/iosApp/Screens/Player/PlayerViewModel.swift`:
- Around line 2724-2739: Treat offline playback loads as finalizing the existing
server session before the offline branch proceeds, instead of leaving cleanup to
call sessionBridge.stopSession later. Update the fresh load flow in
PlayerViewModel so the offline path sets the finalize flag up front and the
subsequent teardown skips stopping the stale server session, while preserving
the existing reportProgress behavior for non-finalizing loads. Check the
freshLoadTask block and the related offline branches in PlayerViewModel to keep
the sessionBridge calls aligned with the current playback mode.
---
Nitpick comments:
In `@iosApp/iosApp/Components/EpisodeThumbCard.swift`:
- Around line 169-180: The “Downloaded indicator” overlay logic is duplicated
between EpisodeThumbCard and MediaCard, so extract the condition plus
DownloadedBadge placement into a shared View helper/modifier such as
downloadedBadgeOverlay(contentId:padding:). Put the capability-aware
DownloadManager.shared.isDownloaded lookup and the bottom-trailing overlay
alignment inside that helper, then replace both inline blocks with the shared
helper to keep badge behavior and comments in sync.
In `@iosApp/iosApp/Downloads/DownloadsSettingsView.swift`:
- Around line 87-91: The “Remove All” action in DownloadsSettingsView is
deleting each record one by one via manager.deleteDownload(id:), which repeats
persistence, storage refresh, and server deletes unnecessarily. Update the
Button action to collect all current manager.records ids and call the bulk
DeleteDownloadManager.deleteDownloads(ids:) path instead, matching the batching
pattern already used in DownloadsView.swift and avoiding the per-record loop.
In `@iosApp/iosApp/Downloads/DownloadsView.swift`:
- Around line 159-167: The destructive download deletion actions in
DownloadsView are firing immediately without user confirmation. Update the
multi-select bottom-bar delete path and the per-row context-menu actions in
DownloadsView (including the delete helpers that call manager.deleteDownloads
and manager.deleteDownload) to present a confirmationDialog before deleting,
matching the pattern already used in DownloadsSettingsView. Keep the delete
logic in the existing action methods, but gate invocation behind a confirm step
so accidental taps do not remove downloads immediately.
In `@iosApp/iosApp/Downloads/SeriesDownloadControls.swift`:
- Around line 52-58: The openMonitorSheet flow in SeriesDownloadControls
currently relies on a hard-coded Task.sleep to chain sheets, which is fragile.
Remove the fixed 300ms delay and instead use SwiftUI’s
sheet(item:onDismiss:content:) pattern so the follow-up monitor sheet is
triggered from the dismissal callback after the first sheet fully closes. Update
the activeSheet handling in openMonitorSheet and the related sheet presentation
logic to use the dismissal lifecycle rather than guessing timing.
🪄 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: 8be09ca5-40b4-42e2-970f-8c8a724a7452
📒 Files selected for processing (46)
iosApp/Tests/DownloadGroupingTests.swiftiosApp/iosApp/Components/DownloadedBadge.swiftiosApp/iosApp/Components/EpisodeThumbCard.swiftiosApp/iosApp/Components/MediaCard.swiftiosApp/iosApp/ContentView.swiftiosApp/iosApp/Downloads/DownloadAPI.swiftiosApp/iosApp/Downloads/DownloadActionButton.swiftiosApp/iosApp/Downloads/DownloadBackgroundRefresh.swiftiosApp/iosApp/Downloads/DownloadFilePaths.swiftiosApp/iosApp/Downloads/DownloadGrouping.swiftiosApp/iosApp/Downloads/DownloadManager.swiftiosApp/iosApp/Downloads/DownloadModels.swiftiosApp/iosApp/Downloads/DownloadNotifications.swiftiosApp/iosApp/Downloads/DownloadOptionsSheet.swiftiosApp/iosApp/Downloads/DownloadSessionDelegate.swiftiosApp/iosApp/Downloads/DownloadSettings.swiftiosApp/iosApp/Downloads/DownloadSizeEstimate.swiftiosApp/iosApp/Downloads/DownloadStore.swiftiosApp/iosApp/Downloads/DownloadsSettingsView.swiftiosApp/iosApp/Downloads/DownloadsView.swiftiosApp/iosApp/Downloads/OfflinePlayback.swiftiosApp/iosApp/Downloads/SeriesDownloadControls.swiftiosApp/iosApp/Downloads/Views/DownloadManagerRows.swiftiosApp/iosApp/Downloads/Views/DownloadReclaimSheet.swiftiosApp/iosApp/Downloads/Views/DownloadsManagerComponents.swiftiosApp/iosApp/Downloads/Views/OfflineBrowse.swiftiosApp/iosApp/Info.plistiosApp/iosApp/Navigation/AppRouter.swiftiosApp/iosApp/Navigation/Route.swiftiosApp/iosApp/Navigation/TabRouter.swiftiosApp/iosApp/Networking/ContinuumAPI.swiftiosApp/iosApp/Networking/HTTPClient.swiftiosApp/iosApp/Networking/Models.swiftiosApp/iosApp/Notifications/SiloAppDelegate+Push.swiftiosApp/iosApp/Screens/Browse/FilterView.swiftiosApp/iosApp/Screens/Detail/ItemDetailViewModel.swiftiosApp/iosApp/Screens/Detail/MovieDetailContent.swiftiosApp/iosApp/Screens/Detail/Phone/PhoneEpisodeRail.swiftiosApp/iosApp/Screens/Detail/SeasonDetailContent.swiftiosApp/iosApp/Screens/Detail/SeriesDetailContent.swiftiosApp/iosApp/Screens/Personal/FavoritesView.swiftiosApp/iosApp/Screens/Personal/WatchlistView.swiftiosApp/iosApp/Screens/Player/PlayerView.swiftiosApp/iosApp/Screens/Player/PlayerViewModel.swiftiosApp/iosApp/Screens/Settings/SettingsView.swiftiosApp/iosApp/macOS/PlayerView.swift
Add a SiloDownloadsActivity WidgetKit extension rendering active downloads as a Live Activity (lock screen card + Dynamic Island): current item, item-weighted queue progress, bytes and transfer rate, deep-linking to the Downloads tab. The app owns the lifecycle via DownloadLiveActivityController, fed from DownloadManager.file's didSet at the existing 1s publish cadence; content states carry a 90s stale date so the widget flips to "Continuing in background…" once the app is suspended and background-session progress callbacks stop. Co-Authored-By: Claude Fable 5 <[email protected]>
- Add downloaded playback choice, safer delete confirmations, and shared badge overlay - Bound retry/progress behavior and flush background download state before completion - Fix offline session teardown, storage cap accounting, and path sanitization
e12369c to
f5589bc
Compare
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
iosApp/iosApp/Downloads/SeriesDownloadControls.swift (1)
130-139: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winStop swallowing subscription-delete failures.
DownloadManager.deleteSubscription(id:)removes the local subscription and then usestry?for the API call, so offline/auth failures leave the server-side subscription active while the sheet is already dismissed. Make this path surface errors or defer dismissing until the delete succeeds.🤖 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/Downloads/SeriesDownloadControls.swift` around lines 130 - 139, The stop-monitoring flow in SeriesDownloadControls and DownloadManager.deleteSubscription(id:) is hiding API failures by using try? and dismissing the sheet immediately. Update the delete path so the deleteSubscription call surfaces errors and only dismisses after a successful server-side delete, or otherwise presents the failure to the user instead of swallowing it.
🧹 Nitpick comments (2)
iosApp/DownloadsActivity/DownloadsLiveActivity.swift (1)
24-76: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDynamic Island keeps showing progress after completion, unlike the lock-screen view.
Lock screen hides percent/progress once
phase == .completed, but the Dynamic Island's expanded/compact/minimal presentations don't apply the samephase != .completedgating, so they'll keep rendering a full progress ring/100% during the linger period. Likely intentional but worth confirming it matches design intent.🤖 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/DownloadsActivity/DownloadsLiveActivity.swift` around lines 24 - 76, The Dynamic Island presentations in DownloadsLiveActivity are still rendering progress after completion, unlike the lock-screen view. Update the DynamicIsland expanded, compactTrailing, and minimal sections to use the same phase gating as the lock-screen UI in the activity state so percent/progress are hidden when context.state.phase is .completed and only the non-progress completion UI remains during the linger period.iosApp/iosApp/Downloads/DownloadLiveActivity.swift (1)
44-65: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low valueRapid finish→restart could momentarily create a duplicate Activity.
finishActivity()clearsself.activitysynchronously but ends the old one asynchronously viaactivityChain;startActivity()isn't routed through that same chain, so async()call with new active records arriving before the queuedend()finishes can callActivity.request()while the previous activity is still winding down. Not crash-prone (iOS allows multiple concurrent activities of the same type), but could show a stray duplicate card until the queuedend()fires;adoptExistingActivityIfNeeded()only self-heals on next app launch, not mid-session.Consider routing
startActivitythroughactivityChainas well so starts/updates/ends are strictly serialized.Also applies to: 69-84, 99-133
🤖 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/Downloads/DownloadLiveActivity.swift` around lines 44 - 65, The sync flow can start a new DownloadLiveActivity before the previous one has finished ending because finishActivity() is serialized on activityChain but startActivity() is not. Update DownloadLiveActivity.sync and the startActivity path so activity creation is also routed through activityChain, keeping starts, updates, and ends strictly serialized. Use the existing activityChain, finishActivity(), and startActivity() symbols to ensure a new Activity.request() cannot run while a prior activity is still winding down.
🤖 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.
Outside diff comments:
In `@iosApp/iosApp/Downloads/SeriesDownloadControls.swift`:
- Around line 130-139: The stop-monitoring flow in SeriesDownloadControls and
DownloadManager.deleteSubscription(id:) is hiding API failures by using try? and
dismissing the sheet immediately. Update the delete path so the
deleteSubscription call surfaces errors and only dismisses after a successful
server-side delete, or otherwise presents the failure to the user instead of
swallowing it.
---
Nitpick comments:
In `@iosApp/DownloadsActivity/DownloadsLiveActivity.swift`:
- Around line 24-76: The Dynamic Island presentations in DownloadsLiveActivity
are still rendering progress after completion, unlike the lock-screen view.
Update the DynamicIsland expanded, compactTrailing, and minimal sections to use
the same phase gating as the lock-screen UI in the activity state so
percent/progress are hidden when context.state.phase is .completed and only the
non-progress completion UI remains during the linger period.
In `@iosApp/iosApp/Downloads/DownloadLiveActivity.swift`:
- Around line 44-65: The sync flow can start a new DownloadLiveActivity before
the previous one has finished ending because finishActivity() is serialized on
activityChain but startActivity() is not. Update DownloadLiveActivity.sync and
the startActivity path so activity creation is also routed through
activityChain, keeping starts, updates, and ends strictly serialized. Use the
existing activityChain, finishActivity(), and startActivity() symbols to ensure
a new Activity.request() cannot run while a prior activity is still winding
down.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: e2083534-904b-4d19-99d8-35bf5533fca1
📒 Files selected for processing (24)
iosApp/DownloadsActivity/DownloadsLiveActivity.swiftiosApp/DownloadsActivity/Info.plistiosApp/Signing/Local.xcconfig.sampleiosApp/Signing/SiloDownloadsActivity.xcconfigiosApp/iosApp/Components/DownloadedBadge.swiftiosApp/iosApp/Components/EpisodeThumbCard.swiftiosApp/iosApp/Components/MediaCard.swiftiosApp/iosApp/ContentView.swiftiosApp/iosApp/Downloads/DownloadActivityAttributes.swiftiosApp/iosApp/Downloads/DownloadBackgroundRefresh.swiftiosApp/iosApp/Downloads/DownloadFilePaths.swiftiosApp/iosApp/Downloads/DownloadLiveActivity.swiftiosApp/iosApp/Downloads/DownloadManager.swiftiosApp/iosApp/Downloads/DownloadsSettingsView.swiftiosApp/iosApp/Downloads/DownloadsView.swiftiosApp/iosApp/Downloads/SeriesDownloadControls.swiftiosApp/iosApp/Downloads/Views/DownloadManagerRows.swiftiosApp/iosApp/Info.plistiosApp/iosApp/Navigation/AppRouter.swiftiosApp/iosApp/Navigation/Route.swiftiosApp/iosApp/Notifications/SiloAppDelegate+Push.swiftiosApp/iosApp/Screens/Detail/ItemDetailView.swiftiosApp/iosApp/Screens/Player/PlayerViewModel.swiftiosApp/project.yml
✅ Files skipped from review due to trivial changes (1)
- iosApp/Signing/Local.xcconfig.sample
🚧 Files skipped from review as they are similar to previous changes (11)
- iosApp/iosApp/Components/EpisodeThumbCard.swift
- iosApp/iosApp/Downloads/DownloadBackgroundRefresh.swift
- iosApp/iosApp/Navigation/AppRouter.swift
- iosApp/iosApp/Downloads/DownloadsSettingsView.swift
- iosApp/iosApp/Downloads/Views/DownloadManagerRows.swift
- iosApp/iosApp/Downloads/DownloadFilePaths.swift
- iosApp/iosApp/Notifications/SiloAppDelegate+Push.swift
- iosApp/iosApp/ContentView.swift
- iosApp/iosApp/Downloads/DownloadsView.swift
- iosApp/iosApp/Downloads/DownloadManager.swift
- iosApp/iosApp/Screens/Player/PlayerViewModel.swift
…nsions The push-notification (#40) and offline-downloads (#41) PRs added two embedded app extensions, but the beta_ios lane still fetched only the main app's profile and forced it onto every target via a global PROVISIONING_PROFILE_SPECIFIER xcarg, failing the archive step with a bundle-ID mismatch. - match now syncs profiles for the app and both extensions - per-target signing via update_code_signing_settings + export_options provisioningProfiles mapping (same pattern as the tvOS Top Shelf lane) - Matchfile identifier list includes both extension IDs - new sync_signing lane for read-write local profile generation Co-Authored-By: Claude Fable 5 <[email protected]>
What changed
Adds the iOS offline download feature and its follow-up iteration:
iosApp/iosApp/Downloads/): backgroundURLSessiontransfers, per-scope persistence, series monitoring/subscriptions, offline playback, downloads manager UI, and settings.BGAppRefreshTask(DownloadBackgroundRefresh) runs the subscription/progress sync every few hours so "auto-download new episodes" works without opening the app.DownloadNotifications): announce newly queued episodes and completed downloads.SiloAppDelegate+Push): the push relay already sendscontent-available: 1on every APNs push, so iOS wakes the app for ~30s when a new-episode notification arrives. That wake now also runsDownloadManager.onAppActive()(in parallel with the notification-inbox sync, under the existing deadline race), which registers monitored episodes and enqueues them into the backgroundURLSession— the download starts and completes while the app stays closed.TokenStoreis retargeted before both syncs so a cold background launch authenticates, and the wake deadline is widened from 15s to 20s because the monitoring chain ends with the pipeline kick that performs the enqueue.Why
Lets users keep media available offline, and makes series monitoring hands-off: a monitored show's new episode starts downloading the moment the push arrives, with the 4-hour BG refresh task as the fallback for throttled or missed pushes.
Reviewer notes
content-availablewas already on every push.Siloscheme, iPhone 17 Pro simulator,CODE_SIGNING_ALLOWED=NO).🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Bug Fixes