Skip to content

Live Activity — UX Improvements and Reliability Fixes#540

Merged
bjorkert merged 30 commits intoloopandlearn:live-activityfrom
achkars-org:live-activity
Mar 15, 2026
Merged

Live Activity — UX Improvements and Reliability Fixes#540
bjorkert merged 30 commits intoloopandlearn:live-activityfrom
achkars-org:live-activity

Conversation

@MtlPhil
Copy link

@MtlPhil MtlPhil commented Mar 15, 2026

Building on the auto-renewal foundation merged in #539, this PR adds user-facing controls,
improved navigation, and a set of reliability fixes identified through testing.


New Features

Separate APN and Live Activity Settings Screens

A new Live Activity entry in the Settings menu leads to the new screen with the enable toggle and restart button. The toggle is backed by Storage.shared.laEnabled so the preference survives app restarts.

All entry points into the LA (startFromCurrentState, refreshFromCurrentState, handleDidBecomeActive, handleWillResignActive) are gated on laEnabled`, so disabling the toggle cleanly stops all LA activity with no side effects.

A Restart Live Activity button in the Live Activity settings screen calls forceRestart(), which ends all existing activities and starts a fresh one. The button shows "Live Activity Restarted" for 2 seconds as visual feedback, then resets. Only visible when the toggle is ON.

Siri / Apple Shortcuts Integration (RestartLiveActivityIntent)

An AppIntent named Restart Live Activity allows the user to restart the LA via Siri or the Shortcuts app. If APNs credentials are missing the intent returns a dialog directing the user to Settings. The intent also clears the dismissedByUser flag so the LA resumes from a dismissed state.

Lock Screen and Dynamic Island Tap Navigation

Tapping the lock screen LA card or the expanded Dynamic Island now navigates to the correct tab:

  • Active alarm → Snoozer tab
  • No active alarm → Home tab

Any open modal (e.g. Settings sheet) is dismissed before the tab switch. Implementation uses widgetURL(URL(string: "loopfollow://la-tap")!) on the lock screen view and Link views in the expanded DI regions. The URL is handled in SceneDelegate.scene(_:openURLContexts:).

Dynamic Island Redesign

  • Compact trailing: shows BG delta (was trend arrow)
  • Expanded leading: large BG value with trend arrow · delta · Proj on one row, all same style (size 13, semibold, 0.9 opacity)
  • Expanded trailing: IOB and COB with .padding(.trailing, 6) to prevent decimal clipping

Reliability Fixes

Lock Screen Shows Latest Data When App Backgrounds

A willResignActive observer cancels any pending debounced refresh and immediately pushes the latest snapshot via both direct ActivityKit update and APNs self-push. Without this, data arriving during the 5-second debounce window would not be visible on the lock screen.

LA Ends on App Force-Quit

applicationWillTerminate calls endOnTerminate(), which ends the activity synchronously (blocking up to 3 s via Task.detached + DispatchSemaphore) before the process exits. Stale glucose data no longer persists on the lock screen after force-quit. laEnabled is preserved so the LA restarts on next launch.

Manual Dismissal Does Not Auto-Restart

When the user swipes the LA card away from the lock screen, ActivityKit delivers .dismissed (distinct from .ended). The state observer now sets an in-memory dismissedByUser flag on .dismissed. All auto-restart paths (startFromCurrentState, refreshFromCurrentState, handleDidBecomeActive) are gated on !dismissedByUser, so the LA does not reappear until the user explicitly enables it via:

  • Toggling Enable Live Activity off then on
  • Pressing Restart Live Activity
  • Using the Siri / Shortcuts App Intent

laEnabled is left true — the user's preference is preserved; only the auto-restart is suppressed. dismissedByUser is in-memory only, so a force-quit and relaunch resets it and starts the LA fresh, which is the expected behavior.

refreshFromCurrentState Respects Dismissed State

performRefresh() previously called startIfNeeded() directly, bypassing the dismissedByUser guard in startFromCurrentState(). On every BG reading with laEnabled = true and no current activity, it would silently recreate the LA. refreshFromCurrentState is now also gated on !dismissedByUser.


Files Changed

File Change
LiveActivity/LiveActivityManager.swift laEnabled guards; forceRestart(); handleDidBecomeActive/WillResignActive; dismissedByUser flag;
LiveActivitySettingsView.swift New file — enable toggle, restart button, reactive sync
Settings/SettingsMenuView.swift New "Live Activity" entry; "APN" entry preserved
LiveActivity/RestartLiveActivityIntent.swift New file — AppIntent + AppShortcutsProvider
Application/SceneDelegate.swift scene(_:openURLContexts:) for loopfollow://la-tap; sceneDidBecomeActive for deferred navigation
ViewControllers/MainViewController.swift navigateOnLAForeground() — modal dismissal + tab switch; observer for .liveActivityDidForeground
LoopFollowLAExtension/LoopFollowLiveActivity.swift DI redesign; widgetURL on lock screen; Link in expanded DI regions

MtlPhil and others added 30 commits March 12, 2026 21:40
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- staleDate on every ActivityContent now tracks the renewal deadline,
  so the system shows Apple's built-in stale indicator if renewal fails
- Add laRenewalFailed StorageValue; set on Activity.request() failure,
  cleared on any successful LA start
- Observe willEnterForegroundNotification: retry startIfNeeded() if a
  previous renewal attempt failed
- New-first renewal order: request the replacement LA before ending the
  old one — if the request throws the existing LA stays alive so the
  user keeps live data until the system kills it at the 8-hour mark

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Restore renewalThreshold to 7.5 * 3600 (testing complete)
- Add showRenewalOverlay: Bool to GlucoseSnapshot (Codable, default false)
- GlucoseSnapshotBuilder sets it true when now >= laRenewBy - 1800
  (30 minutes before the renewal deadline)
- Lock screen: 60% gray overlay with "Tap to update" centered in white,
  layered above the existing isNotLooping overlay
- DI expanded: RenewalOverlayView applied to leading/trailing/bottom
  regions; "Tap to update" text shown on the bottom region only
- showRenewalOverlay resets to false automatically on renewal since
  laRenewBy is updated and the next snapshot rebuild clears the flag

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Overlay rendering:
- Replace Group{if condition{ZStack{RoundedRectangle...}}} with a
  permanently-present ZStack toggled via .opacity(). The Group/if
  pattern causes SwiftUI sizing ambiguity when the condition transitions
  from false→true inside an .overlay(), producing a zero-size result.
  The .opacity() approach keeps a stable view hierarchy.
- Same fix applied to RenewalOverlayView used on DI expanded regions.

Foreground restart:
- handleForeground() was calling startIfNeeded(), which finds the
  still-alive (failed-to-renew) LA in Activity.activities and reuses
  it, doing nothing useful. Fixed to manually nil out current, cancel
  all tasks, await activity.end(.immediate), then startFromCurrentState().

Overlay timing:
- Changed warning window from 30 min (1800s) to 20 min (1200s) before
  the renewal deadline, matching the intended test cadence.

Logging:
- handleForeground: log on every foreground event with laRenewalFailed value
- renewIfNeeded: log how many seconds past the deadline when firing
- GlucoseSnapshotBuilder: log when overlay activates with seconds to deadline
- performRefresh: log when sending an update with the overlay visible

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Normal renewal path (renewIfNeeded success):
- Build a fresh snapshot with showRenewalOverlay: false for the new
  LA's initial content — it has a new deadline so the overlay should
  never be visible from the first frame.
- Save that fresh snapshot to GlucoseSnapshotStore so the next
  duplicate check has the correct baseline and doesn't suppress the
  first real BG update.

Foreground restart path (handleForeground):
- Zero laRenewBy before calling startFromCurrentState() so
  GlucoseSnapshotBuilder computes showRenewalOverlay = false for the
  seed snapshot. startIfNeeded() then sets the new deadline after the
  request succeeds.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
With renewalThreshold=20min and the hardcoded 1200s warning window,
renewBy-1200 = start, so showRenewalOverlay is always true from the
moment the LA begins.

Extract a named renewalWarning constant (5 min for testing) so the
warning window is always less than the threshold. The builder now reads
LiveActivityManager.renewalWarning instead of a hardcoded literal.

Production values to restore before merging:
  renewalThreshold = 7.5 * 3600
  renewalWarning   = 20 * 60

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…ynchronously

APNSClient was missing showRenewalOverlay from the push payload, so background
APNs updates never delivered the overlay flag to the extension — only foreground
direct ActivityKit updates did.

In handleForeground, laRenewBy is now zeroed synchronously before spawning the
async end/restart Task. This means any snapshot built between the foreground
notification and the new LA start (e.g. from viewDidAppear's startFromCurrentState)
computes showRenewalOverlay = false rather than reading the stale expired deadline.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…e path

Reset laRenewBy and laRenewalFailed synchronously before tearing down the
failed LA, then await activity.end() before calling startFromCurrentState().

This guarantees Activity.activities is clear when startIfNeeded() runs, so
it takes the fresh-request path and writes a new laRenewBy. startFromCurrentState
rebuilds the snapshot with showRenewalOverlay=false (laRenewBy=0), saves it
to the store, then startIfNeeded uses that clean snapshot as the seed.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- SettingsMenuView: rename "APN" menu entry to "Live Activity"
- Storage: add laEnabled: Bool StorageValue (default false)
- APNSettingsView: on/off toggle bound to laEnabled; APNs key fields and
  Restart button shown only when enabled; disabling immediately ends any
  running LA
- LiveActivityManager:
  - forceRestart() (@mainactor) ends all running activities, resets laRenewBy
    and laRenewalFailed, then calls startFromCurrentState()
  - laEnabled guard added to startFromCurrentState(), refreshFromCurrentState(),
    handleForeground(), and handleDidBecomeActive()
  - didBecomeActiveNotification observer calls forceRestart() on every
    foreground transition when laEnabled is true
- RestartLiveActivityIntent: AppIntent + ForegroundContinuableIntent; sets
  laEnabled, validates credentials, opens settings deep link if missing,
  otherwise calls forceRestart() in foreground; LoopFollowAppShortcuts
  exposes the intent with Siri phrase

Note: RestartLiveActivityIntent.swift must be added to the app target in Xcode.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…ctivityIntent

- LiveActivityManager: handleDidBecomeActive() calls @mainactor forceRestart()
  via Task { @mainactor in ... } to satisfy Swift concurrency isolation
- RestartLiveActivityIntent: drop ForegroundContinuableIntent — continueInForeground()
  was renamed to continueInForeground(_:alwaysConfirm:) in the iOS 26 SDK and
  requires iOS 26+; the didBecomeActiveNotification observer handles restart
  when the app comes to foreground, making explicit continuation unnecessary

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
continueInForeground(_:alwaysConfirm:) is iOS 26+ only. On earlier
versions, forceRestart() runs directly via the existing background
audio session — no foreground continuation needed.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…rceRestart

forceRestart() was killing the LA that the RestartLiveActivityIntent had
just created, because continueInForeground() triggers didBecomeActive.
startFromCurrentState() reuses an existing active LA via startIfNeeded()
and only creates one if none is present — no destructive race.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
APNSettingsView:
- "Restart Live Activity" button shows "Live Activity Restarted" for 2 seconds
  and disables itself during that window to prevent double-taps
- Toggle observes Storage.shared.laEnabled via onReceive so it reflects changes
  made externally (e.g. by the App Intent / Shortcuts)

LiveActivityManager:
- handleDidBecomeActive posts .liveActivityDidForeground after startFromCurrentState
- Notification.Name.liveActivityDidForeground extension defined here

MainViewController:
- Observes .liveActivityDidForeground; navigates to Snoozer tab if an alarm
  is currently active, otherwise navigates to tab 0 (Home)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…latest data

The 5-second debounce on refreshFromCurrentState means a BG update arriving
while the app is foreground won't reach the LA before the user returns to the
lock screen. When the debounce fires in background, isForeground=false so the
direct ActivityKit update is skipped.

Fix: observe willResignActiveNotification, cancel the pending debounce, and
immediately push the latest snapshot via direct ActivityKit update while the
app is still foreground-active. The APNs push is also sent as a backup.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Compact:
- Trailing now shows delta instead of trend arrow (leading already showed BG)

Expanded leading:
- Large BG value at top
- Second row: trend arrow, delta, and "Proj: X" in smaller text below

Expanded trailing:
- IOB and COB (moved from bottom)

Expanded bottom:
- "Updated at: HH:mm" (moved from trailing)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Proj label now uses same size (13), weight (semibold), and opacity (0.9) as
  the delta text beside it
- Added 6pt trailing padding to the expanded DI trailing VStack so the IOB
  decimal is not clipped by the Dynamic Island edge

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Per maintainer preference, the APNs credentials (Key ID and Key) remain in
their own "APN" settings screen. A new separate "Live Activity" settings screen
contains the enable/disable toggle and the Restart Live Activity button.

- APNSettingsView: restored to Key ID + Key only (no toggle or restart button)
- LiveActivitySettingsView: new view with laEnabled toggle and restart button
  (with 2-second confirmation feedback); toggle stays in sync via onReceive
- SettingsMenuView: "APN" entry restored; new "Live Activity" entry added with
  dot.radiowaves icon; Sheet.liveActivity case wired to LiveActivitySettingsView

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…l PR loopandlearn#539)

Resolves conflicts between our branch and upstream commits:
- 32a6dd0: Mac Catalyst build fix (#if !targetEnvironment(macCatalyst) guards)
- e737bce: Live Activity auto-renewal PR (loopandlearn#539)

Our additions are preserved on top:
- laEnabled toggle with Storage backing
- forceRestart() for button and AppIntent
- handleDidBecomeActive / handleWillResignActive observers
- willResignActive flush to ensure lock screen shows latest data
- liveActivityDidForeground notification for tab navigation
- Notification.Name extension

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- widgetURL on lock screen LA → opens app via loopfollow://la-tap
- Link views in expanded DI regions → same URL on tap
- AppDelegate.application(_:open:) handles loopfollow://la-tap and posts
  .liveActivityDidForeground so MainViewController navigates to Snoozer
  (if alarm active) or Home tab — fires only on LA/DI taps, not every foreground
- Notification.Name.liveActivityDidForeground moved outside #if macCatalyst
  so AppDelegate can reference it unconditionally
- handleDidBecomeActive no longer posts .liveActivityDidForeground (was
  firing on every app foreground, not just LA taps)
- attachStateObserver: .dismissed state (user swipe) sets laEnabled = false
  so the LA does not auto-restart when the app foregrounds
- LiveActivitySettingsView: toggling ON calls startFromCurrentState()

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Adds endOnTerminate() to LiveActivityManager — blocks up to 3 s using
Task.detached + DispatchSemaphore so the async activity.end() completes
before the process exits. Called from applicationWillTerminate so the
LA clears from the lock screen immediately on force-quit.

laEnabled is preserved so the LA restarts correctly on next launch.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…l dismiss

- Manual LA swipe-away sets dismissedByUser (in-memory) instead of
  laEnabled = false, preserving the user's preference
- startFromCurrentState() guards on !dismissedByUser so the LA does not
  auto-restart on foreground, BG refresh, or handleDidBecomeActive
- forceRestart() clears dismissedByUser before starting, so the Restart
  button and App Intent both work as the explicit re-enable mechanism
- Toggle ON in settings calls forceRestart() (clears flag + starts) instead
  of startFromCurrentState() which would have been blocked by the flag
- dismissedByUser resets to false on app relaunch (in-memory only), so
  a kill + relaunch starts the LA fresh as expected

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
navigateOnLAForeground now checks tabBarController.presentedViewController
and dismisses it before switching to the target tab, matching the existing
pattern used elsewhere in MainViewController for the same scenario.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Navigation fix:
- loopfollow://la-tap URL can arrive before applicationDidBecomeActive
  while UIKit is still restoring the view hierarchy from background.
  At that moment tabBarController.presentedViewController is nil so the
  Settings modal is never dismissed and the navigation notification fires
  too early.
- Now stores a pendingLATapNavigation flag if app is not yet .active,
  and fires the notification in applicationDidBecomeActive when the full
  view hierarchy (including presented modals) is restored.

LA reappear fix:
- performRefresh() calls startIfNeeded() directly, bypassing the
  dismissedByUser guard that only exists in startFromCurrentState().
  On every BG refresh with laEnabled=true and current==nil (post-dismiss),
  it would recreate the LA.
- Added !dismissedByUser guard to refreshFromCurrentState() so the entire
  refresh pipeline is skipped while dismissed, matching the existing guard
  in startFromCurrentState().

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
With scene-based lifecycle (iOS 13+), widget/LA tap URLs are delivered to
scene(_:openURLContexts:) on UIWindowSceneDelegate — AppDelegate.application
(_:open:url:options:) is never called. Our previous handler was dead code.

SceneDelegate now implements scene(_:openURLContexts:) which posts
.liveActivityDidForeground on the next run loop (via DispatchQueue.main.async)
to let the view hierarchy fully settle before navigateOnLAForeground() runs.
Also handles the edge case where the URL arrives before sceneDidBecomeActive
by storing a pendingLATapNavigation flag.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@MtlPhil MtlPhil mentioned this pull request Mar 15, 2026
@bjorkert bjorkert merged commit 26b244e into loopandlearn:live-activity Mar 15, 2026
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.

2 participants