Skip to content

Live activity#537

Draft
bjorkert wants to merge 81 commits intodevfrom
live-activity
Draft

Live activity#537
bjorkert wants to merge 81 commits intodevfrom
live-activity

Conversation

@bjorkert
Copy link
Contributor

This PR replaces #534

Work in progress.

MtlPhil and others added 6 commits March 7, 2026 17:05
…f-push)

Implements a lock screen and Dynamic Island Live Activity for LoopFollow displaying real-time glucose data updated via APNs self-push.

## What's included

- Lock screen card: glucose + trend arrow, delta, IOB, COB, projected, last update time, threshold-driven background color (green/orange/red)
- Dynamic Island: compact, expanded, and minimal presentations
- Not Looping overlay: red banner when Loop hasn't reported in 15+ min
- APNs self-push: app sends push to itself for reliable background updates without interference from background audio session
- Single source of truth: all data flows from Storage/Observable
- Source-agnostic: IOB/COB/projected are optional, safe for Dexcom-only users
- Dynamic App Group ID: derived from bundle identifier, no hardcoded team IDs
- APNs key injected via xcconfig/Info.plist — never bundled, never committed

## Files added
- LoopFollow/LiveActivity/: APNSClient, APNSJWTGenerator, AppGroupID, GlucoseLiveActivityAttributes, GlucoseSnapshot, GlucoseSnapshotBuilder, GlucoseSnapshotStore, GlucoseUnitConversion, LAAppGroupSettings, LAThresholdSync, LiveActivityManager, PreferredGlucoseUnit, StorageCurrentGlucoseStateProvider
- LoopFollowLAExtension/: LoopFollowLiveActivity, LoopFollowLABundle
- docs/LiveActivity.md (architecture + APNs setup guide)

## Files modified
- Storage: added lastBgReadingTimeSeconds, lastDeltaMgdl, lastTrendCode, lastIOB, lastCOB, projectedBgMgdl
- Observable: added isNotLooping
- BGData, DeviceStatusLoop, DeviceStatusOpenAPS: write canonical values to Storage
- DeviceStatus: write isNotLooping to Observable
- BackgroundTaskAudio: cleanup
- MainViewController: wired LiveActivityManager.refreshFromCurrentState()
- Info.plist: added APNSKeyID, APNSTeamID, APNSKeyContent build settings
- fastlane/Fastfile: added extension App ID and provisioning profile
- build_LoopFollow.yml: inject APNs key from GitHub secret
- Consolidate JWT generation into JWTManager using CryptoKit with
  multi-slot in-memory cache, removing SwiftJWT and swift-crypto SPM
  dependencies
- Separate APNs keys for LoopFollow (lf) vs remote commands, with
  automatic team-ID routing and a migration step for legacy keys
- Add dedicated APN settings page for LoopFollow's own APNs keys
- Remove hardcoded APNs credentials from CI workflow and Info.plist
  in favor of user-configured keys
- Apply swiftformat to Live Activity files
@bjorkert
Copy link
Contributor Author

Summary of changes in 524b3bb — Replace SwiftJWT with CryptoKit and separate APNs credentials

Dependency removal:

  • Removes the SwiftJWT and swift-crypto SPM packages entirely. JWT signing now uses Apple's built-in CryptoKit (P256/ES256), eliminating two third-party dependencies.

JWT consolidation:

  • Deletes APNSJWTGenerator.swift. All JWT generation logic is now in JWTManager.swift, which uses an in-memory cache (keyed by keyId:teamId, 55-min TTL) instead of persisting JWT tokens to UserDefaults.

APNs credential separation:

  • Previously there was one set of APNs credentials (apnsKey/keyId) shared between remote commands and Live Activity. Now there are two distinct sets:
    • lfApnsKey/lfKeyId — for LoopFollow's own Live Activity pushes
    • remoteApnsKey/remoteKeyId — for remote commands to Loop/Trio
  • Removes the old "Return Notification Settings" section (which appeared when team IDs differed). Instead, the remote credential fields only show when team IDs differ, and LoopFollow credentials are always entered in the new APNSettingsView.

New APNSettingsView:

  • Adds a dedicated settings screen under the Settings menu for entering LoopFollow's own APNs Key ID and Key.

Migration (migrateStep5):

  • Migrates old credential storage keys (apnsKey, keyId, returnApnsKey, returnKeyId) to the new separated keys, handling same-team vs different-team scenarios. Cleans up the legacy keys afterward.

Build/CI updates:

  • Removes the Inject APNs Key Content CI step — credentials are no longer baked into the build via xcconfig/Info.plist. They're entered by the user at runtime.
  • Removes APNSKeyContent, APNSKeyID, APNSTeamID from Info.plist.
  • Updates CI to macos-26 / Xcode_26.2.

APNSClient refactored:

  • Uses JWTManager.shared instead of APNSJWTGenerator. Reads credentials from Storage.shared. Selects sandbox vs production APNs host based on BuildDetails.isTestFlightBuild().

Code style:

  • Standardized file headers, alphabetized imports, added trailing commas, cleaned up whitespace throughout the LiveActivity and Remote modules.

@bjorkert
Copy link
Contributor Author

Consolidated duplicated code in the Live Activity branch:

  • All glucose values now stored in mg/dL — removed the round-trip conversion (mg/dL → mmol/L at snapshot creation, then mmol/L → mg/dL for threshold comparison). Conversion to mmol/L now happens only at display time in LAFormat.
  • Single conversion constant — deleted GlucoseUnitConversion.swift (used 18.0182) and unified on GlucoseConversion.swift (18.01559), with mgDlToMmolL as a computed reciprocal.
  • Deduplicated unit detectionPreferredGlucoseUnit.hkUnit() now delegates to Localizer.getPreferredUnit() instead of duplicating it.
  • Added FortyFiveUp/FortyFiveDown trends — new upSlight/downSlight cases rendering as ↗/↘︎ instead of collapsing to ↑/↓.
  • Fixed locale bugLAFormat now uses NumberFormatter with Locale.current so decimal separators match the main app (e.g. "5,6" for Swedish locale).
  • Deleted dead code — removed LAThresholdSync.swift (never called).
  • Fixed APNs payload — added missing isNotLooping field so push-based updates correctly show the "Not Looping" overlay.

MtlPhil and others added 8 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>
…ension

- Wrap ActivityKit-dependent files (GlucoseLiveActivityAttributes,
  LiveActivityManager, APNSClient) in #if !targetEnvironment(macCatalyst)
- Guard LiveActivityManager call sites in MainViewController, BGData,
  and DeviceStatus with the same compile-time check
- Remove unnecessary @available(iOS 16.1, *) checks (deployment target
  is already 16.6)
- Add platformFilter = ios to the widget extension embed phase and
  target dependency so it is excluded from Mac Catalyst builds
@bjorkert
Copy link
Contributor Author

Mac Catalyst build fix

Problem

ActivityKit is iOS-only — its module exists in the Mac Catalyst SDK but every API is marked @available(macCatalyst, unavailable). #if canImport(ActivityKit) evaluates to true on Mac Catalyst and if #available(iOS 16.1, *) runtime checks also pass, so neither helps. Additionally, the widget extension (LoopFollowLAExtensionExtension.appex) was being embedded unconditionally, causing an "embedded content built for the iOS platform" error.

Changes

Compile-time guards (#if !targetEnvironment(macCatalyst)):

  • Wrapped entire file contents of GlucoseLiveActivityAttributes.swift, LiveActivityManager.swift, and APNSClient.swift
  • Wrapped call sites in MainViewController.swift, BGData.swift, and DeviceStatus.swift

Removed unnecessary @available(iOS 16.1, *) checks — deployment target is already 16.6, so these were dead code.

Excluded widget extension from Mac Catalyst builds — added platformFilter = ios to both the embed build phase and target dependency for LoopFollowLAExtensionExtension in the Xcode project.

No logic changes — only build configuration and compile-time guards.

MtlPhil and others added 4 commits March 13, 2026 09:54
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>
@MtlPhil
Copy link

MtlPhil commented Mar 13, 2026

Live Activity auto-renewal (8-hour limit workaround)

PR Link

Apple enforces an 8-hour maximum lifetime on Live Activities in the Dynamic Island.

Approach

On every glucose refresh (~5 min), LiveActivityManager checks whether the current LA has passed its renewal deadline. If so, it:

  1. Requests a new LA first (so the user keeps live data if the request fails)
  2. Ends the old LA with .immediate dismissal (removes the lock screen card instantly)
  3. Records a new 7.5-hour deadline in Storage.shared.laRenewBy

If the request fails, laRenewalFailed is set and the existing LA is kept. On next foreground entry, the stale LA is ended and a fresh one is started.

Renewal warning overlay

Starting 20 minutes before the renewal deadline, a gray "Tap to update" overlay is rendered over the lock screen view and all expanded Dynamic Island regions. This prompts the user to bring the app to the foreground, where the LA can be renewed.

The overlay flag (showRenewalOverlay) is computed in GlucoseSnapshotBuilder and included in every APNs push payload so it is delivered reliably in the background.

Robustness

  • New-first renewal order. The new LA is requested before the old one is ended. If Activity.request() throws, the old LA remains intact and laRenewalFailed is set.
  • staleDate tied to renewal deadline. ActivityContent.staleDate is set to laRenewBy so ActivityKit marks the content stale at exactly the renewal moment.
  • Foreground retry awaits end. On foreground retry after a failed renewal, laRenewBy and laRenewalFailed are cleared synchronously, then activity.end() is awaited before startFromCurrentState() is called. This ensures Activity.activities is empty when startIfNeeded() runs, forcing a fresh-request path that writes a new deadline, preventing a stale overlay from appearing on the restarted LA.
  • showRenewalOverlay in APNs payload. The field is included in every push so background deliveries correctly activate and clear the overlay.
  • Orphaned activity cleanup. On app launch, endOrphanedActivities() ends any untracked Live Activities left behind by a previous crash.

Files changed

File: Storage/Storage.swift
Change: Added laRenewBy: TimeInterval and laRenewalFailed: Bool
────────────────────────────────────────
File: LiveActivity/GlucoseSnapshot.swift
Change: Added showRenewalOverlay: Bool field
────────────────────────────────────────
File: LiveActivity/GlucoseSnapshotBuilder.swift
Change: Computes showRenewalOverlay from laRenewBy
────────────────────────────────────────
File: LiveActivity/APNSClient.swift
Change: Includes showRenewalOverlay in APNs push payload
────────────────────────────────────────
File: LiveActivity/LiveActivityManager.swift
Change: Renewal logic: renewIfNeeded(), endOrphanedActivities(), foreground retry, renewalThreshold/renewalWarning constants
────────────────────────────────────────
File: LoopFollowLAExtension/LoopFollowLiveActivity.swift
Change: "Tap to update" overlay on lock screen and Dynamic Island expanded regions

Testing checklist

  • "Tap to update" overlay appears 20 minutes before the renewal deadline
  • LA is replaced cleanly at the renewal deadline (no duplicate cards, no stale overlay on new LA)
  • Foreground retry after a failed renewal starts a fresh LA with showRenewalOverlay = false
  • Orphaned activities from a previous crash are cleaned up on launch

MtlPhil and others added 5 commits March 13, 2026 19:32
* feat: Live Activity auto-renewal to work around 8-hour system limit

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

* test: reduce LA renewal threshold to 20 min for testing

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

* feat: improve LA renewal robustness and stale indicator

- 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>

* feat: renewal warning overlay + restore 7.5h threshold

- 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>

* fix: overlay not appearing + foreground restart not working

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>

* test: set renewalThreshold to 20 min for testing

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

* fix: renewal overlay not clearing after LA is refreshed

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>

* fix: overlay permanently active when warning window equals threshold

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>

* fix: include showRenewalOverlay in APNs payload and clear laRenewBy synchronously

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>

* fix: await LA end before restarting on foreground retry to avoid reuse 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>

* chore: restore production renewal timing (7.5h threshold, 20min warning)

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>
MtlPhil and others added 30 commits March 15, 2026 18:32
buildPayload() was only serializing the base fields (glucose, delta, trend,
updatedAt, unit, iob, cob, projected). All extended fields added with the
configurable grid slots (battery, sageInsertTime, pumpBattery, basalRate,
autosens, tdd, targets, isf, carbRatio, carbsToday, profileName, CAGE, IAGE,
minBg, maxBg, override, recBolus) were missing from the APNs payload, causing
the extension to decode them as nil/0 and display '--' on every push-driven
refresh.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Upstream commits merged:
- fec3f79: PR #547 merged (configurable grid slots + InfoType coverage)
- 83ba7c5: Linting — indentation, struct→enum for LiveActivitySlotDefaults,
  blank line cleanup in Storage.swift and LiveActivitySlotConfig.swift
- a20f3ec: Fix PRODUCT_BUNDLE_IDENTIFIER for Tests

Conflict resolutions: all whitespace/style-only, took upstream version.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Registers the Live Activity for the small activity family via
.supplementalActivityFamilies([.small]), enabling automatic display on:
- CarPlay Dashboard (iOS 26+)
- Apple Watch Smart Stack (watchOS 11+)

The small view is hardcoded to the essentials appropriate for a driving
context: glucose value, trend arrow, delta, and time since last reading.
Background tint matches the existing threshold-based color logic.

The lock screen layout (full grid with configurable slots) is unchanged.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* feat: Live Activity auto-renewal to work around 8-hour system limit

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

* test: reduce LA renewal threshold to 20 min for testing

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

* feat: improve LA renewal robustness and stale indicator

- 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>

* feat: renewal warning overlay + restore 7.5h threshold

- 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>

* fix: overlay not appearing + foreground restart not working

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>

* test: set renewalThreshold to 20 min for testing

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

* fix: renewal overlay not clearing after LA is refreshed

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>

* fix: overlay permanently active when warning window equals threshold

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>

* fix: include showRenewalOverlay in APNs payload and clear laRenewBy synchronously

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>

* fix: await LA end before restarting on foreground retry to avoid reuse 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>

* chore: restore production renewal timing (7.5h threshold, 20min warning)

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

* feat: laEnabled toggle, forceRestart(), and RestartLiveActivityIntent

- 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>

* Added RestartLiveActivityIntent to project

* fix: resolve two build errors in LiveActivityManager and RestartLiveActivityIntent

- 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>

* fix: guard continueInForeground() behind iOS 26 availability check

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>

* fix: use startFromCurrentState in handleDidBecomeActive instead of forceRestart

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>

* feat: LA foreground tab navigation, button feedback, and toggle sync

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>

* fix: flush LA update on willResignActive to ensure lock screen shows 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>

* feat: redesign Dynamic Island compact and expanded views

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>

* fix: match Proj text style to delta; add trailing padding to IOB/COB

- 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>

* feat: separate Live Activity and APN settings into distinct menus

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>

* Added Live Activity menu

* chore: add LiveActivitySettingsView to Xcode project

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

* fix: LA tap navigation, manual dismissal prevention, and toggle start

- 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>

* fix: end Live Activity on app force-quit

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>

* fix: use dismissedByUser flag instead of disabling laEnabled on manual 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>

* fix: dismiss modal (Settings sheet) before tab switch on LA tap

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>

* fix: LA tap navigation timing and LA reappear-after-dismiss

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>

* fix: handle loopfollow://la-tap URL in SceneDelegate, not AppDelegate

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>

* feat: configurable LA grid slots + full InfoType snapshot coverage

Lock screen layout:
- Left column: glucose + trend arrow, delta below (replaces "Last Update:")
- Right grid: 4 configurable slots read from LAAppGroupSettings (defaults: IOB/COB/Proj/empty)
- Footer: centered HH:MM update time at reduced opacity

Slot configuration:
- LiveActivitySlotOption enum with all 22 InfoType-aligned cases
- LAAppGroupSettings.setSlots() / slots() persisted to App Group UserDefaults
- Uniqueness enforced: selecting an option clears it from any other slot
- Settings UI: "Grid slots" section with 4 pickers in LiveActivitySettingsView
- Changes take effect immediately (refreshFromCurrentState called on save)

GlucoseSnapshot extended with 19 new fields covering all InfoType items:
override, recBolus, battery, pumpBattery, basalRate, pumpReservoirU,
autosens, tdd, targetLowMgdl/High, isfMgdlPerU, carbRatio, carbsToday,
profileName, sageInsertTime, cageInsertTime, iageInsertTime, minBgMgdl/Max

Storage.swift: 13 new UserDefaults-backed fields for the above metrics

Controllers updated to write new Storage fields on each data fetch:
Basals, DeviceStatus, DeviceStatusLoop, DeviceStatusOpenAPS,
Carbs, Profile, IAge

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

* fix: label delta and footer on lock screen LA card

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

* docs: add PR description for configurable LA grid slots

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

* Update PR_configurable_slots.md

* chore: remove PR notes from tracking, keep docs/LiveActivity.md only

- Untrack docs/PR_configurable_slots.md (local-only reference doc)
- Add docs/PR_configurable_slots.md and docs/LiveActivityTestPlan.md to .gitignore

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

* fix: include all extended InfoType fields in APNs push payload

buildPayload() was only serializing the base fields (glucose, delta, trend,
updatedAt, unit, iob, cob, projected). All extended fields added with the
configurable grid slots (battery, sageInsertTime, pumpBattery, basalRate,
autosens, tdd, targets, isf, carbRatio, carbsToday, profileName, CAGE, IAGE,
minBg, maxBg, override, recBolus) were missing from the APNs payload, causing
the extension to decode them as nil/0 and display '--' on every push-driven
refresh.

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

* feat: add small family view for CarPlay Dashboard and Watch Smart Stack

Registers the Live Activity for the small activity family via
.supplementalActivityFamilies([.small]), enabling automatic display on:
- CarPlay Dashboard (iOS 26+)
- Apple Watch Smart Stack (watchOS 11+)

The small view is hardcoded to the essentials appropriate for a driving
context: glucose value, trend arrow, delta, and time since last reading.
Background tint matches the existing threshold-based color logic.

The lock screen layout (full grid with configurable slots) is unchanged.

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

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
…rease renewal overlay opacity

- supplementalActivityFamilies and activityFamily require iOS 18.0+;
  restructured into two Widget structs sharing a makeDynamicIsland() helper:
  - LoopFollowLiveActivityWidget (iOS 16.1+): lock screen + Dynamic Island
  - LoopFollowLiveActivityWidgetWithCarPlay (iOS 18.0+): adds .supplementalActivityFamilies([.small])
- Bundle uses if #available(iOS 18.0, *) to select the right variant
- Podfile: set minimum deployment target to 16.6 for all pods
- Increase 'Tap to update' renewal overlay opacity from 60% to 90%

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

@WidgetBundleBuilder does not support if #available { } else { }, but
@WidgetConfigurationBuilder (used by Widget.body) does. Collapsed back to
a single LoopFollowLiveActivityWidget struct with the iOS 18 conditional
inside body — iOS 18+ branch adds .supplementalActivityFamilies([.small])
for CarPlay and Watch Smart Stack; else branch uses the plain lock screen view.

Bundle reverts to the original single if #available(iOS 16.1, *) pattern.

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

@WidgetConfigurationBuilder's buildEither requires both branches to return the
same concrete type, making if/else with supplementalActivityFamilies impossible
(it wraps to a different opaque type). @WidgetBundleBuilder does not support
if #available { } else { } at all.

Solution: two separate single-branch if #available blocks in the bundle —
the pattern that @WidgetBundleBuilder already supported in the original code:
- LoopFollowLiveActivityWidget (iOS 16.1+): primary, lock screen + Dynamic Island
- LoopFollowLiveActivityWidgetWithCarPlay (iOS 18.0+): supplemental, adds
  .supplementalActivityFamilies([.small]) for CarPlay Dashboard + Watch Smart Stack

ActivityKit uses the supplemental widget for small-family surfaces and the
primary widget for lock screen / Dynamic Island, keeping iOS 16.6+ support intact.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…erlay at 90% opacity

Upstream restructured the CarPlay/Watch Smart Stack feature to use a single
widget with .supplementalActivityFamilies([.small]) and @available(iOS 16.1, *)
on all views, removing the need for a second LoopFollowLiveActivityWidgetWithCarPlay
struct. Resolved conflicts by taking the upstream structure while preserving
the 90% opacity on the renewal overlay.

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

* feat: Live Activity auto-renewal to work around 8-hour system limit

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

* test: reduce LA renewal threshold to 20 min for testing

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

* feat: improve LA renewal robustness and stale indicator

- 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>

* feat: renewal warning overlay + restore 7.5h threshold

- 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>

* fix: overlay not appearing + foreground restart not working

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>

* test: set renewalThreshold to 20 min for testing

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

* fix: renewal overlay not clearing after LA is refreshed

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>

* fix: overlay permanently active when warning window equals threshold

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>

* fix: include showRenewalOverlay in APNs payload and clear laRenewBy synchronously

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>

* fix: await LA end before restarting on foreground retry to avoid reuse 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>

* chore: restore production renewal timing (7.5h threshold, 20min warning)

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

* feat: laEnabled toggle, forceRestart(), and RestartLiveActivityIntent

- 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>

* Added RestartLiveActivityIntent to project

* fix: resolve two build errors in LiveActivityManager and RestartLiveActivityIntent

- 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>

* fix: guard continueInForeground() behind iOS 26 availability check

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>

* fix: use startFromCurrentState in handleDidBecomeActive instead of forceRestart

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>

* feat: LA foreground tab navigation, button feedback, and toggle sync

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>

* fix: flush LA update on willResignActive to ensure lock screen shows 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>

* feat: redesign Dynamic Island compact and expanded views

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>

* fix: match Proj text style to delta; add trailing padding to IOB/COB

- 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>

* feat: separate Live Activity and APN settings into distinct menus

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>

* Added Live Activity menu

* chore: add LiveActivitySettingsView to Xcode project

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

* fix: LA tap navigation, manual dismissal prevention, and toggle start

- 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>

* fix: end Live Activity on app force-quit

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>

* fix: use dismissedByUser flag instead of disabling laEnabled on manual 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>

* fix: dismiss modal (Settings sheet) before tab switch on LA tap

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>

* fix: LA tap navigation timing and LA reappear-after-dismiss

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>

* fix: handle loopfollow://la-tap URL in SceneDelegate, not AppDelegate

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>

* feat: configurable LA grid slots + full InfoType snapshot coverage

Lock screen layout:
- Left column: glucose + trend arrow, delta below (replaces "Last Update:")
- Right grid: 4 configurable slots read from LAAppGroupSettings (defaults: IOB/COB/Proj/empty)
- Footer: centered HH:MM update time at reduced opacity

Slot configuration:
- LiveActivitySlotOption enum with all 22 InfoType-aligned cases
- LAAppGroupSettings.setSlots() / slots() persisted to App Group UserDefaults
- Uniqueness enforced: selecting an option clears it from any other slot
- Settings UI: "Grid slots" section with 4 pickers in LiveActivitySettingsView
- Changes take effect immediately (refreshFromCurrentState called on save)

GlucoseSnapshot extended with 19 new fields covering all InfoType items:
override, recBolus, battery, pumpBattery, basalRate, pumpReservoirU,
autosens, tdd, targetLowMgdl/High, isfMgdlPerU, carbRatio, carbsToday,
profileName, sageInsertTime, cageInsertTime, iageInsertTime, minBgMgdl/Max

Storage.swift: 13 new UserDefaults-backed fields for the above metrics

Controllers updated to write new Storage fields on each data fetch:
Basals, DeviceStatus, DeviceStatusLoop, DeviceStatusOpenAPS,
Carbs, Profile, IAge

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

* fix: label delta and footer on lock screen LA card

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

* docs: add PR description for configurable LA grid slots

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

* Update PR_configurable_slots.md

* chore: remove PR notes from tracking, keep docs/LiveActivity.md only

- Untrack docs/PR_configurable_slots.md (local-only reference doc)
- Add docs/PR_configurable_slots.md and docs/LiveActivityTestPlan.md to .gitignore

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

* fix: include all extended InfoType fields in APNs push payload

buildPayload() was only serializing the base fields (glucose, delta, trend,
updatedAt, unit, iob, cob, projected). All extended fields added with the
configurable grid slots (battery, sageInsertTime, pumpBattery, basalRate,
autosens, tdd, targets, isf, carbRatio, carbsToday, profileName, CAGE, IAGE,
minBg, maxBg, override, recBolus) were missing from the APNs payload, causing
the extension to decode them as nil/0 and display '--' on every push-driven
refresh.

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

* feat: add small family view for CarPlay Dashboard and Watch Smart Stack

Registers the Live Activity for the small activity family via
.supplementalActivityFamilies([.small]), enabling automatic display on:
- CarPlay Dashboard (iOS 26+)
- Apple Watch Smart Stack (watchOS 11+)

The small view is hardcoded to the essentials appropriate for a driving
context: glucose value, trend arrow, delta, and time since last reading.
Background tint matches the existing threshold-based color logic.

The lock screen layout (full grid with configurable slots) is unchanged.

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

* fix: guard CarPlay/Watch small family behind iOS 18 availability; increase renewal overlay opacity

- supplementalActivityFamilies and activityFamily require iOS 18.0+;
  restructured into two Widget structs sharing a makeDynamicIsland() helper:
  - LoopFollowLiveActivityWidget (iOS 16.1+): lock screen + Dynamic Island
  - LoopFollowLiveActivityWidgetWithCarPlay (iOS 18.0+): adds .supplementalActivityFamilies([.small])
- Bundle uses if #available(iOS 18.0, *) to select the right variant
- Podfile: set minimum deployment target to 16.6 for all pods
- Increase 'Tap to update' renewal overlay opacity from 60% to 90%

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

* fix: move if #available into Widget.body to avoid WidgetBundleBuilder limitation

@WidgetBundleBuilder does not support if #available { } else { }, but
@WidgetConfigurationBuilder (used by Widget.body) does. Collapsed back to
a single LoopFollowLiveActivityWidget struct with the iOS 18 conditional
inside body — iOS 18+ branch adds .supplementalActivityFamilies([.small])
for CarPlay and Watch Smart Stack; else branch uses the plain lock screen view.

Bundle reverts to the original single if #available(iOS 16.1, *) pattern.

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

* fix: use two separate single-branch if #available in bundle for CarPlay support

@WidgetConfigurationBuilder's buildEither requires both branches to return the
same concrete type, making if/else with supplementalActivityFamilies impossible
(it wraps to a different opaque type). @WidgetBundleBuilder does not support
if #available { } else { } at all.

Solution: two separate single-branch if #available blocks in the bundle —
the pattern that @WidgetBundleBuilder already supported in the original code:
- LoopFollowLiveActivityWidget (iOS 16.1+): primary, lock screen + Dynamic Island
- LoopFollowLiveActivityWidgetWithCarPlay (iOS 18.0+): supplemental, adds
  .supplementalActivityFamilies([.small]) for CarPlay Dashboard + Watch Smart Stack

ActivityKit uses the supplemental widget for small-family surfaces and the
primary widget for lock screen / Dynamic Island, keeping iOS 16.6+ support intact.

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

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
…d activityFamily behind iOS 18

Upstream's single-widget approach placed iOS 18+ APIs (supplementalActivityFamilies,
activityFamily, ActivityFamily) behind @available(iOS 16.1, *), which fails to
compile at the 16.6 deployment target. Restoring the two-widget pattern:

- LoopFollowLiveActivityWidget (@available iOS 16.1): lock screen + DI, uses
  LockScreenLiveActivityView, no supplementalActivityFamilies
- LoopFollowLiveActivityWidgetWithCarPlay (@available iOS 18.0): adds CarPlay
  Dashboard + Watch Smart Stack via supplementalActivityFamilies([.small]),
  uses LockScreenFamilyAdaptiveView (also @available iOS 18.0)
- SmallFamilyView availability corrected to @available(iOS 18.0, *)
- Bundle registers both via separate if #available blocks

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

- LoopFollowLAExtension MARKETING_VERSION now uses "$(MARKETING_VERSION)" to
  match the parent app version automatically, resolving CFBundleShortVersionString
  mismatch warning
- Remove unnecessary Task/await wrapping of refreshFromCurrentState in
  LiveActivitySettingsView — the method is not async

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
… minor warnings (#550)

* feat: Live Activity auto-renewal to work around 8-hour system limit

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

* test: reduce LA renewal threshold to 20 min for testing

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

* feat: improve LA renewal robustness and stale indicator

- 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>

* feat: renewal warning overlay + restore 7.5h threshold

- 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>

* fix: overlay not appearing + foreground restart not working

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>

* test: set renewalThreshold to 20 min for testing

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

* fix: renewal overlay not clearing after LA is refreshed

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>

* fix: overlay permanently active when warning window equals threshold

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>

* fix: include showRenewalOverlay in APNs payload and clear laRenewBy synchronously

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>

* fix: await LA end before restarting on foreground retry to avoid reuse 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>

* chore: restore production renewal timing (7.5h threshold, 20min warning)

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

* feat: laEnabled toggle, forceRestart(), and RestartLiveActivityIntent

- 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>

* Added RestartLiveActivityIntent to project

* fix: resolve two build errors in LiveActivityManager and RestartLiveActivityIntent

- 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>

* fix: guard continueInForeground() behind iOS 26 availability check

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>

* fix: use startFromCurrentState in handleDidBecomeActive instead of forceRestart

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>

* feat: LA foreground tab navigation, button feedback, and toggle sync

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>

* fix: flush LA update on willResignActive to ensure lock screen shows 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>

* feat: redesign Dynamic Island compact and expanded views

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>

* fix: match Proj text style to delta; add trailing padding to IOB/COB

- 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>

* feat: separate Live Activity and APN settings into distinct menus

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>

* Added Live Activity menu

* chore: add LiveActivitySettingsView to Xcode project

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

* fix: LA tap navigation, manual dismissal prevention, and toggle start

- 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>

* fix: end Live Activity on app force-quit

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>

* fix: use dismissedByUser flag instead of disabling laEnabled on manual 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>

* fix: dismiss modal (Settings sheet) before tab switch on LA tap

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>

* fix: LA tap navigation timing and LA reappear-after-dismiss

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>

* fix: handle loopfollow://la-tap URL in SceneDelegate, not AppDelegate

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>

* feat: configurable LA grid slots + full InfoType snapshot coverage

Lock screen layout:
- Left column: glucose + trend arrow, delta below (replaces "Last Update:")
- Right grid: 4 configurable slots read from LAAppGroupSettings (defaults: IOB/COB/Proj/empty)
- Footer: centered HH:MM update time at reduced opacity

Slot configuration:
- LiveActivitySlotOption enum with all 22 InfoType-aligned cases
- LAAppGroupSettings.setSlots() / slots() persisted to App Group UserDefaults
- Uniqueness enforced: selecting an option clears it from any other slot
- Settings UI: "Grid slots" section with 4 pickers in LiveActivitySettingsView
- Changes take effect immediately (refreshFromCurrentState called on save)

GlucoseSnapshot extended with 19 new fields covering all InfoType items:
override, recBolus, battery, pumpBattery, basalRate, pumpReservoirU,
autosens, tdd, targetLowMgdl/High, isfMgdlPerU, carbRatio, carbsToday,
profileName, sageInsertTime, cageInsertTime, iageInsertTime, minBgMgdl/Max

Storage.swift: 13 new UserDefaults-backed fields for the above metrics

Controllers updated to write new Storage fields on each data fetch:
Basals, DeviceStatus, DeviceStatusLoop, DeviceStatusOpenAPS,
Carbs, Profile, IAge

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

* fix: label delta and footer on lock screen LA card

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

* docs: add PR description for configurable LA grid slots

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

* Update PR_configurable_slots.md

* chore: remove PR notes from tracking, keep docs/LiveActivity.md only

- Untrack docs/PR_configurable_slots.md (local-only reference doc)
- Add docs/PR_configurable_slots.md and docs/LiveActivityTestPlan.md to .gitignore

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

* fix: include all extended InfoType fields in APNs push payload

buildPayload() was only serializing the base fields (glucose, delta, trend,
updatedAt, unit, iob, cob, projected). All extended fields added with the
configurable grid slots (battery, sageInsertTime, pumpBattery, basalRate,
autosens, tdd, targets, isf, carbRatio, carbsToday, profileName, CAGE, IAGE,
minBg, maxBg, override, recBolus) were missing from the APNs payload, causing
the extension to decode them as nil/0 and display '--' on every push-driven
refresh.

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

* feat: add small family view for CarPlay Dashboard and Watch Smart Stack

Registers the Live Activity for the small activity family via
.supplementalActivityFamilies([.small]), enabling automatic display on:
- CarPlay Dashboard (iOS 26+)
- Apple Watch Smart Stack (watchOS 11+)

The small view is hardcoded to the essentials appropriate for a driving
context: glucose value, trend arrow, delta, and time since last reading.
Background tint matches the existing threshold-based color logic.

The lock screen layout (full grid with configurable slots) is unchanged.

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

* fix: guard CarPlay/Watch small family behind iOS 18 availability; increase renewal overlay opacity

- supplementalActivityFamilies and activityFamily require iOS 18.0+;
  restructured into two Widget structs sharing a makeDynamicIsland() helper:
  - LoopFollowLiveActivityWidget (iOS 16.1+): lock screen + Dynamic Island
  - LoopFollowLiveActivityWidgetWithCarPlay (iOS 18.0+): adds .supplementalActivityFamilies([.small])
- Bundle uses if #available(iOS 18.0, *) to select the right variant
- Podfile: set minimum deployment target to 16.6 for all pods
- Increase 'Tap to update' renewal overlay opacity from 60% to 90%

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

* fix: move if #available into Widget.body to avoid WidgetBundleBuilder limitation

@WidgetBundleBuilder does not support if #available { } else { }, but
@WidgetConfigurationBuilder (used by Widget.body) does. Collapsed back to
a single LoopFollowLiveActivityWidget struct with the iOS 18 conditional
inside body — iOS 18+ branch adds .supplementalActivityFamilies([.small])
for CarPlay and Watch Smart Stack; else branch uses the plain lock screen view.

Bundle reverts to the original single if #available(iOS 16.1, *) pattern.

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

* fix: use two separate single-branch if #available in bundle for CarPlay support

@WidgetConfigurationBuilder's buildEither requires both branches to return the
same concrete type, making if/else with supplementalActivityFamilies impossible
(it wraps to a different opaque type). @WidgetBundleBuilder does not support
if #available { } else { } at all.

Solution: two separate single-branch if #available blocks in the bundle —
the pattern that @WidgetBundleBuilder already supported in the original code:
- LoopFollowLiveActivityWidget (iOS 16.1+): primary, lock screen + Dynamic Island
- LoopFollowLiveActivityWidgetWithCarPlay (iOS 18.0+): supplemental, adds
  .supplementalActivityFamilies([.small]) for CarPlay Dashboard + Watch Smart Stack

ActivityKit uses the supplemental widget for small-family surfaces and the
primary widget for lock screen / Dynamic Island, keeping iOS 16.6+ support intact.

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

* fix: restore two-widget bundle; guard supplementalActivityFamilies and activityFamily behind iOS 18

Upstream's single-widget approach placed iOS 18+ APIs (supplementalActivityFamilies,
activityFamily, ActivityFamily) behind @available(iOS 16.1, *), which fails to
compile at the 16.6 deployment target. Restoring the two-widget pattern:

- LoopFollowLiveActivityWidget (@available iOS 16.1): lock screen + DI, uses
  LockScreenLiveActivityView, no supplementalActivityFamilies
- LoopFollowLiveActivityWidgetWithCarPlay (@available iOS 18.0): adds CarPlay
  Dashboard + Watch Smart Stack via supplementalActivityFamilies([.small]),
  uses LockScreenFamilyAdaptiveView (also @available iOS 18.0)
- SmallFamilyView availability corrected to @available(iOS 18.0, *)
- Bundle registers both via separate if #available blocks

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

* fix: extension version inherits from parent; remove spurious await in slot config

- LoopFollowLAExtension MARKETING_VERSION now uses "$(MARKETING_VERSION)" to
  match the parent app version automatically, resolving CFBundleShortVersionString
  mismatch warning
- Remove unnecessary Task/await wrapping of refreshFromCurrentState in
  LiveActivitySettingsView — the method is not async

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

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
At 46pt, a 4-character mmol/L value ("10.5") plus "↑↑" overflowed the 168pt
left column, truncating the glucose reading. Fix: reduce trend arrow to 32pt
and add minimumScaleFactor(0.7) + lineLimit(1) to the glucose text so values
above 10 mmol/L render correctly.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…es (#552)

* feat: Live Activity auto-renewal to work around 8-hour system limit

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

* test: reduce LA renewal threshold to 20 min for testing

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

* feat: improve LA renewal robustness and stale indicator

- 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>

* feat: renewal warning overlay + restore 7.5h threshold

- 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>

* fix: overlay not appearing + foreground restart not working

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>

* test: set renewalThreshold to 20 min for testing

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

* fix: renewal overlay not clearing after LA is refreshed

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>

* fix: overlay permanently active when warning window equals threshold

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>

* fix: include showRenewalOverlay in APNs payload and clear laRenewBy synchronously

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>

* fix: await LA end before restarting on foreground retry to avoid reuse 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>

* chore: restore production renewal timing (7.5h threshold, 20min warning)

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

* feat: laEnabled toggle, forceRestart(), and RestartLiveActivityIntent

- 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>

* Added RestartLiveActivityIntent to project

* fix: resolve two build errors in LiveActivityManager and RestartLiveActivityIntent

- 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>

* fix: guard continueInForeground() behind iOS 26 availability check

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>

* fix: use startFromCurrentState in handleDidBecomeActive instead of forceRestart

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>

* feat: LA foreground tab navigation, button feedback, and toggle sync

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>

* fix: flush LA update on willResignActive to ensure lock screen shows 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>

* feat: redesign Dynamic Island compact and expanded views

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>

* fix: match Proj text style to delta; add trailing padding to IOB/COB

- 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>

* feat: separate Live Activity and APN settings into distinct menus

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>

* Added Live Activity menu

* chore: add LiveActivitySettingsView to Xcode project

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

* fix: LA tap navigation, manual dismissal prevention, and toggle start

- 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>

* fix: end Live Activity on app force-quit

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>

* fix: use dismissedByUser flag instead of disabling laEnabled on manual 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>

* fix: dismiss modal (Settings sheet) before tab switch on LA tap

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>

* fix: LA tap navigation timing and LA reappear-after-dismiss

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>

* fix: handle loopfollow://la-tap URL in SceneDelegate, not AppDelegate

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>

* feat: configurable LA grid slots + full InfoType snapshot coverage

Lock screen layout:
- Left column: glucose + trend arrow, delta below (replaces "Last Update:")
- Right grid: 4 configurable slots read from LAAppGroupSettings (defaults: IOB/COB/Proj/empty)
- Footer: centered HH:MM update time at reduced opacity

Slot configuration:
- LiveActivitySlotOption enum with all 22 InfoType-aligned cases
- LAAppGroupSettings.setSlots() / slots() persisted to App Group UserDefaults
- Uniqueness enforced: selecting an option clears it from any other slot
- Settings UI: "Grid slots" section with 4 pickers in LiveActivitySettingsView
- Changes take effect immediately (refreshFromCurrentState called on save)

GlucoseSnapshot extended with 19 new fields covering all InfoType items:
override, recBolus, battery, pumpBattery, basalRate, pumpReservoirU,
autosens, tdd, targetLowMgdl/High, isfMgdlPerU, carbRatio, carbsToday,
profileName, sageInsertTime, cageInsertTime, iageInsertTime, minBgMgdl/Max

Storage.swift: 13 new UserDefaults-backed fields for the above metrics

Controllers updated to write new Storage fields on each data fetch:
Basals, DeviceStatus, DeviceStatusLoop, DeviceStatusOpenAPS,
Carbs, Profile, IAge

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

* fix: label delta and footer on lock screen LA card

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

* docs: add PR description for configurable LA grid slots

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

* Update PR_configurable_slots.md

* chore: remove PR notes from tracking, keep docs/LiveActivity.md only

- Untrack docs/PR_configurable_slots.md (local-only reference doc)
- Add docs/PR_configurable_slots.md and docs/LiveActivityTestPlan.md to .gitignore

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

* fix: include all extended InfoType fields in APNs push payload

buildPayload() was only serializing the base fields (glucose, delta, trend,
updatedAt, unit, iob, cob, projected). All extended fields added with the
configurable grid slots (battery, sageInsertTime, pumpBattery, basalRate,
autosens, tdd, targets, isf, carbRatio, carbsToday, profileName, CAGE, IAGE,
minBg, maxBg, override, recBolus) were missing from the APNs payload, causing
the extension to decode them as nil/0 and display '--' on every push-driven
refresh.

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

* feat: add small family view for CarPlay Dashboard and Watch Smart Stack

Registers the Live Activity for the small activity family via
.supplementalActivityFamilies([.small]), enabling automatic display on:
- CarPlay Dashboard (iOS 26+)
- Apple Watch Smart Stack (watchOS 11+)

The small view is hardcoded to the essentials appropriate for a driving
context: glucose value, trend arrow, delta, and time since last reading.
Background tint matches the existing threshold-based color logic.

The lock screen layout (full grid with configurable slots) is unchanged.

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

* fix: guard CarPlay/Watch small family behind iOS 18 availability; increase renewal overlay opacity

- supplementalActivityFamilies and activityFamily require iOS 18.0+;
  restructured into two Widget structs sharing a makeDynamicIsland() helper:
  - LoopFollowLiveActivityWidget (iOS 16.1+): lock screen + Dynamic Island
  - LoopFollowLiveActivityWidgetWithCarPlay (iOS 18.0+): adds .supplementalActivityFamilies([.small])
- Bundle uses if #available(iOS 18.0, *) to select the right variant
- Podfile: set minimum deployment target to 16.6 for all pods
- Increase 'Tap to update' renewal overlay opacity from 60% to 90%

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

* fix: move if #available into Widget.body to avoid WidgetBundleBuilder limitation

@WidgetBundleBuilder does not support if #available { } else { }, but
@WidgetConfigurationBuilder (used by Widget.body) does. Collapsed back to
a single LoopFollowLiveActivityWidget struct with the iOS 18 conditional
inside body — iOS 18+ branch adds .supplementalActivityFamilies([.small])
for CarPlay and Watch Smart Stack; else branch uses the plain lock screen view.

Bundle reverts to the original single if #available(iOS 16.1, *) pattern.

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

* fix: use two separate single-branch if #available in bundle for CarPlay support

@WidgetConfigurationBuilder's buildEither requires both branches to return the
same concrete type, making if/else with supplementalActivityFamilies impossible
(it wraps to a different opaque type). @WidgetBundleBuilder does not support
if #available { } else { } at all.

Solution: two separate single-branch if #available blocks in the bundle —
the pattern that @WidgetBundleBuilder already supported in the original code:
- LoopFollowLiveActivityWidget (iOS 16.1+): primary, lock screen + Dynamic Island
- LoopFollowLiveActivityWidgetWithCarPlay (iOS 18.0+): supplemental, adds
  .supplementalActivityFamilies([.small]) for CarPlay Dashboard + Watch Smart Stack

ActivityKit uses the supplemental widget for small-family surfaces and the
primary widget for lock screen / Dynamic Island, keeping iOS 16.6+ support intact.

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

* fix: restore two-widget bundle; guard supplementalActivityFamilies and activityFamily behind iOS 18

Upstream's single-widget approach placed iOS 18+ APIs (supplementalActivityFamilies,
activityFamily, ActivityFamily) behind @available(iOS 16.1, *), which fails to
compile at the 16.6 deployment target. Restoring the two-widget pattern:

- LoopFollowLiveActivityWidget (@available iOS 16.1): lock screen + DI, uses
  LockScreenLiveActivityView, no supplementalActivityFamilies
- LoopFollowLiveActivityWidgetWithCarPlay (@available iOS 18.0): adds CarPlay
  Dashboard + Watch Smart Stack via supplementalActivityFamilies([.small]),
  uses LockScreenFamilyAdaptiveView (also @available iOS 18.0)
- SmallFamilyView availability corrected to @available(iOS 18.0, *)
- Bundle registers both via separate if #available blocks

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

* fix: extension version inherits from parent; remove spurious await in slot config

- LoopFollowLAExtension MARKETING_VERSION now uses "$(MARKETING_VERSION)" to
  match the parent app version automatically, resolving CFBundleShortVersionString
  mismatch warning
- Remove unnecessary Task/await wrapping of refreshFromCurrentState in
  LiveActivitySettingsView — the method is not async

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

* fix: prevent glucose + trend arrow clipping on wide mmol/L values

At 46pt, a 4-character mmol/L value ("10.5") plus "↑↑" overflowed the 168pt
left column, truncating the glucose reading. Fix: reduce trend arrow to 32pt
and add minimumScaleFactor(0.7) + lineLimit(1) to the glucose text so values
above 10 mmol/L render correctly.

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

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
The app's minimum deployment target is iOS 16.6, making all iOS 16.1
availability checks redundant. Removed @available(iOS 16.1, *) annotations
from all types and the if #available(iOS 16.1, *) wrapper in the bundle.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
The app's minimum deployment target is iOS 16.6, making all iOS 16.1
availability checks redundant. Removed @available(iOS 16.1, *) annotations
from all types and the if #available(iOS 16.1, *) wrapper in the bundle.

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

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Previously handleForeground() only restarted the LA when laRenewalFailed=true,
but the renewal overlay also appears as a warning before renewal is attempted
(while laRenewalFailed is still false). Users who foregrounded during the
warning window saw the overlay persist with no restart occurring.

Now triggers a restart whenever the overlay is showing (within the warning
window before the deadline) OR renewal previously failed.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
When AVAudioSession.setActive() fails (e.g. another app holds the session
exclusively), the app loses its background keep-alive with no recovery path.
Two bugs fixed and recovery logic added:

1. interruptedAudio handler was calling playAudio() on interruption *began*
   (intValue == 1) instead of *ended* — corrected to restart on .ended only.

2. playAudio() catch block now retries up to 3 times (2s apart). After all
   retries are exhausted it posts a BackgroundAudioFailed notification.

3. LiveActivityManager observes BackgroundAudioFailed and immediately sets
   laRenewBy to now (making showRenewalOverlay = true) then pushes a refresh
   so the lock screen overlay tells the user to foreground the app.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
… layout fixes, cleanup (#554)

* feat: Live Activity auto-renewal to work around 8-hour system limit

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

* test: reduce LA renewal threshold to 20 min for testing

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

* feat: improve LA renewal robustness and stale indicator

- 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>

* feat: renewal warning overlay + restore 7.5h threshold

- 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>

* fix: overlay not appearing + foreground restart not working

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>

* test: set renewalThreshold to 20 min for testing

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

* fix: renewal overlay not clearing after LA is refreshed

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>

* fix: overlay permanently active when warning window equals threshold

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>

* fix: include showRenewalOverlay in APNs payload and clear laRenewBy synchronously

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>

* fix: await LA end before restarting on foreground retry to avoid reuse 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>

* chore: restore production renewal timing (7.5h threshold, 20min warning)

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

* feat: laEnabled toggle, forceRestart(), and RestartLiveActivityIntent

- 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>

* Added RestartLiveActivityIntent to project

* fix: resolve two build errors in LiveActivityManager and RestartLiveActivityIntent

- 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>

* fix: guard continueInForeground() behind iOS 26 availability check

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>

* fix: use startFromCurrentState in handleDidBecomeActive instead of forceRestart

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>

* feat: LA foreground tab navigation, button feedback, and toggle sync

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>

* fix: flush LA update on willResignActive to ensure lock screen shows 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>

* feat: redesign Dynamic Island compact and expanded views

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>

* fix: match Proj text style to delta; add trailing padding to IOB/COB

- 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>

* feat: separate Live Activity and APN settings into distinct menus

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>

* Added Live Activity menu

* chore: add LiveActivitySettingsView to Xcode project

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

* fix: LA tap navigation, manual dismissal prevention, and toggle start

- 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>

* fix: end Live Activity on app force-quit

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>

* fix: use dismissedByUser flag instead of disabling laEnabled on manual 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>

* fix: dismiss modal (Settings sheet) before tab switch on LA tap

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>

* fix: LA tap navigation timing and LA reappear-after-dismiss

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>

* fix: handle loopfollow://la-tap URL in SceneDelegate, not AppDelegate

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>

* feat: configurable LA grid slots + full InfoType snapshot coverage

Lock screen layout:
- Left column: glucose + trend arrow, delta below (replaces "Last Update:")
- Right grid: 4 configurable slots read from LAAppGroupSettings (defaults: IOB/COB/Proj/empty)
- Footer: centered HH:MM update time at reduced opacity

Slot configuration:
- LiveActivitySlotOption enum with all 22 InfoType-aligned cases
- LAAppGroupSettings.setSlots() / slots() persisted to App Group UserDefaults
- Uniqueness enforced: selecting an option clears it from any other slot
- Settings UI: "Grid slots" section with 4 pickers in LiveActivitySettingsView
- Changes take effect immediately (refreshFromCurrentState called on save)

GlucoseSnapshot extended with 19 new fields covering all InfoType items:
override, recBolus, battery, pumpBattery, basalRate, pumpReservoirU,
autosens, tdd, targetLowMgdl/High, isfMgdlPerU, carbRatio, carbsToday,
profileName, sageInsertTime, cageInsertTime, iageInsertTime, minBgMgdl/Max

Storage.swift: 13 new UserDefaults-backed fields for the above metrics

Controllers updated to write new Storage fields on each data fetch:
Basals, DeviceStatus, DeviceStatusLoop, DeviceStatusOpenAPS,
Carbs, Profile, IAge

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

* fix: label delta and footer on lock screen LA card

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

* docs: add PR description for configurable LA grid slots

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

* Update PR_configurable_slots.md

* chore: remove PR notes from tracking, keep docs/LiveActivity.md only

- Untrack docs/PR_configurable_slots.md (local-only reference doc)
- Add docs/PR_configurable_slots.md and docs/LiveActivityTestPlan.md to .gitignore

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

* fix: include all extended InfoType fields in APNs push payload

buildPayload() was only serializing the base fields (glucose, delta, trend,
updatedAt, unit, iob, cob, projected). All extended fields added with the
configurable grid slots (battery, sageInsertTime, pumpBattery, basalRate,
autosens, tdd, targets, isf, carbRatio, carbsToday, profileName, CAGE, IAGE,
minBg, maxBg, override, recBolus) were missing from the APNs payload, causing
the extension to decode them as nil/0 and display '--' on every push-driven
refresh.

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

* feat: add small family view for CarPlay Dashboard and Watch Smart Stack

Registers the Live Activity for the small activity family via
.supplementalActivityFamilies([.small]), enabling automatic display on:
- CarPlay Dashboard (iOS 26+)
- Apple Watch Smart Stack (watchOS 11+)

The small view is hardcoded to the essentials appropriate for a driving
context: glucose value, trend arrow, delta, and time since last reading.
Background tint matches the existing threshold-based color logic.

The lock screen layout (full grid with configurable slots) is unchanged.

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

* fix: guard CarPlay/Watch small family behind iOS 18 availability; increase renewal overlay opacity

- supplementalActivityFamilies and activityFamily require iOS 18.0+;
  restructured into two Widget structs sharing a makeDynamicIsland() helper:
  - LoopFollowLiveActivityWidget (iOS 16.1+): lock screen + Dynamic Island
  - LoopFollowLiveActivityWidgetWithCarPlay (iOS 18.0+): adds .supplementalActivityFamilies([.small])
- Bundle uses if #available(iOS 18.0, *) to select the right variant
- Podfile: set minimum deployment target to 16.6 for all pods
- Increase 'Tap to update' renewal overlay opacity from 60% to 90%

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

* fix: move if #available into Widget.body to avoid WidgetBundleBuilder limitation

@WidgetBundleBuilder does not support if #available { } else { }, but
@WidgetConfigurationBuilder (used by Widget.body) does. Collapsed back to
a single LoopFollowLiveActivityWidget struct with the iOS 18 conditional
inside body — iOS 18+ branch adds .supplementalActivityFamilies([.small])
for CarPlay and Watch Smart Stack; else branch uses the plain lock screen view.

Bundle reverts to the original single if #available(iOS 16.1, *) pattern.

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

* fix: use two separate single-branch if #available in bundle for CarPlay support

@WidgetConfigurationBuilder's buildEither requires both branches to return the
same concrete type, making if/else with supplementalActivityFamilies impossible
(it wraps to a different opaque type). @WidgetBundleBuilder does not support
if #available { } else { } at all.

Solution: two separate single-branch if #available blocks in the bundle —
the pattern that @WidgetBundleBuilder already supported in the original code:
- LoopFollowLiveActivityWidget (iOS 16.1+): primary, lock screen + Dynamic Island
- LoopFollowLiveActivityWidgetWithCarPlay (iOS 18.0+): supplemental, adds
  .supplementalActivityFamilies([.small]) for CarPlay Dashboard + Watch Smart Stack

ActivityKit uses the supplemental widget for small-family surfaces and the
primary widget for lock screen / Dynamic Island, keeping iOS 16.6+ support intact.

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

* fix: restore two-widget bundle; guard supplementalActivityFamilies and activityFamily behind iOS 18

Upstream's single-widget approach placed iOS 18+ APIs (supplementalActivityFamilies,
activityFamily, ActivityFamily) behind @available(iOS 16.1, *), which fails to
compile at the 16.6 deployment target. Restoring the two-widget pattern:

- LoopFollowLiveActivityWidget (@available iOS 16.1): lock screen + DI, uses
  LockScreenLiveActivityView, no supplementalActivityFamilies
- LoopFollowLiveActivityWidgetWithCarPlay (@available iOS 18.0): adds CarPlay
  Dashboard + Watch Smart Stack via supplementalActivityFamilies([.small]),
  uses LockScreenFamilyAdaptiveView (also @available iOS 18.0)
- SmallFamilyView availability corrected to @available(iOS 18.0, *)
- Bundle registers both via separate if #available blocks

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

* fix: extension version inherits from parent; remove spurious await in slot config

- LoopFollowLAExtension MARKETING_VERSION now uses "$(MARKETING_VERSION)" to
  match the parent app version automatically, resolving CFBundleShortVersionString
  mismatch warning
- Remove unnecessary Task/await wrapping of refreshFromCurrentState in
  LiveActivitySettingsView — the method is not async

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

* fix: prevent glucose + trend arrow clipping on wide mmol/L values

At 46pt, a 4-character mmol/L value ("10.5") plus "↑↑" overflowed the 168pt
left column, truncating the glucose reading. Fix: reduce trend arrow to 32pt
and add minimumScaleFactor(0.7) + lineLimit(1) to the glucose text so values
above 10 mmol/L render correctly.

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

* chore: remove redundant @available(iOS 16.1) guards

The app's minimum deployment target is iOS 16.6, making all iOS 16.1
availability checks redundant. Removed @available(iOS 16.1, *) annotations
from all types and the if #available(iOS 16.1, *) wrapper in the bundle.

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

* Fix Live Activity glucose overflow with flexible layout and tighter grid spacing

* Fix Live Activity glucose overflow with flexible layout and tighter grid spacing

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

* fix: restart LA on foreground when renewal overlay is showing

Previously handleForeground() only restarted the LA when laRenewalFailed=true,
but the renewal overlay also appears as a warning before renewal is attempted
(while laRenewalFailed is still false). Users who foregrounded during the
warning window saw the overlay persist with no restart occurring.

Now triggers a restart whenever the overlay is showing (within the warning
window before the deadline) OR renewal previously failed.

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

* fix: recover from audio session failure and alert user via LA overlay

When AVAudioSession.setActive() fails (e.g. another app holds the session
exclusively), the app loses its background keep-alive with no recovery path.
Two bugs fixed and recovery logic added:

1. interruptedAudio handler was calling playAudio() on interruption *began*
   (intValue == 1) instead of *ended* — corrected to restart on .ended only.

2. playAudio() catch block now retries up to 3 times (2s apart). After all
   retries are exhausted it posts a BackgroundAudioFailed notification.

3. LiveActivityManager observes BackgroundAudioFailed and immediately sets
   laRenewBy to now (making showRenewalOverlay = true) then pushes a refresh
   so the lock screen overlay tells the user to foreground the app.

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

* Update BackgroundTaskAudio.swift

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
# Conflicts:
#	LoopFollow/Helpers/BackgroundTaskAudio.swift
#	LoopFollow/LiveActivity/LiveActivityManager.swift
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.

Live Activities/Dynamic Island for LF

2 participants