diff --git a/.coderabbit.yaml b/.coderabbit.yaml
index 849ea7d60..770ba8d19 100644
--- a/.coderabbit.yaml
+++ b/.coderabbit.yaml
@@ -25,5 +25,3 @@ reviews:
# and they are the least likely place for a shipped bug. Re-include them
# for a PR that is mostly test work.
- "!test/**"
- auto_review:
- drafts: true
\ No newline at end of file
diff --git a/README.md b/README.md
index 670768275..b26765285 100644
--- a/README.md
+++ b/README.md
@@ -1,3 +1,17 @@
+> [!WARNING]
+> **WHOOP users: do not reconnect to the official WHOOP app.**
+>
+> If you use OpenStrap or another open-source app, or plan to switch to one later,
+> do not connect your band to the WHOOP app again. It can install firmware updates
+> automatically.
+> Uninstall or disable the WHOOP app to prevent it from updating your band.
+>
+> Users report blocked data access on WHOOP 5.0 / MG firmware **50.43.1.0** and
+> **50.43.2.0**. Bluetooth may still connect while history or live data is withheld.
+> OpenStrap cannot issue the WHOOP-signed membership token needed to unlock an
+> affected band. See [firmware compatibility](#whoop-firmware-compatibility)
+> for the evidence and its limits.
+
A health app for your wearables. No subscription, no fees, private by default.
@@ -15,12 +29,45 @@ As featured in [Hackaday](https://hackaday.com/2026/07/15/making-a-locked-down-w
## Devices
-**Supported:** WHOOP 4.0, 5.0, MG.
+**Supported:** WHOOP 4.0, 5.0, MG, subject to the [firmware restrictions below](#whoop-firmware-compatibility).
**Being built:** Oura Ring, Garmin, Pebble, Colmi, Ultrahuman, Mi Band and more.
Full feature list: [docs/FEATURES.md](docs/FEATURES.md).
+## WHOOP firmware compatibility
+
+Research checked on **November 9, 2026**. These are community observations, not a
+complete list of affected firmware versions.
+
+| Device / firmware | Evidence |
+|---|---|
+| WHOOP 5.0, **50.43.1.0** | A [November 7 OpenStrap report](https://github.com/OpenStrap/edge/issues/673) describes successful Bluetooth connections and command replies, but no history or live HR. Data resumed after the official app installed a WHOOP-signed membership token. |
+| WHOOP 5.0 / MG, **50.43.2.0** | A [November 3 NOOP report](https://github.com/ryanbr/noop/issues/2890#issuecomment-6614654919) describes history stopping after the update while live HR and beat timing still worked. This is a reported sync failure; its token-related cause has not been established. |
+| WHOOP MG, **50.42.1.0** | A [November 1 report](https://github.com/ryanbr/noop/issues/2890) records certificate commands and a 45-day certificate counter. It does not establish when enforcement began. |
+| WHOOP 4.0 | These reports do not establish that the same signed-token restriction affects 4.0. Avoid reconnecting it to the official app too if you want to preserve open-source compatibility. |
+
+The 50.43.1.0 report describes a device-bound token signed by WHOOP using ES256,
+a public/private-key signature scheme. The band checks WHOOP's signature;
+creating your own key pair cannot produce a token it will accept. The reported
+failure occurs after Bluetooth connects, when the band withholds sensor data.
+The reporter's token lasted about 45 days, but what happens at expiry or when
+membership ends remains unverified. OpenStrap cannot mint or renew these tokens.
+
+**Release timing:** [users reported receiving 50.43.1.0 on October 19,
+2026](https://www.reddit.com/r/whoop/comments/1xa1r58/firmware_update_available_504310/).
+[WHOOP's release-notes page](https://support.whoop.com/s/article/WHOOP-5-0-MG-Firmware-Release-Notes?language=en_US)
+is dated October 26, 2026 and lists 50.43.2.0 as current. WHOOP says updates are
+automatic and phased, but provides no release date for each version or mention
+of this restriction. **The exact rollout start and first enforcing version are
+unknown.** October 19 establishes that 50.43.1.0 was available by then; October 26
+is the page date, not a confirmed firmware release date.
+
+If your band has already updated, the version alone does not prove it is locked.
+If you plan to switch to OpenStrap later, keep your band off the official WHOOP
+app in the meantime. We are working on a solution, but no fix is available yet.
+These reports do not establish a reliable downgrade.
+
## Support
OpenStrap has no company, no subscription and no paywall behind it. If it's useful to
diff --git a/docs/star-history.svg b/docs/star-history.svg
index b104bc5b2..2e33a95bf 100644
--- a/docs/star-history.svg
+++ b/docs/star-history.svg
@@ -15,8 +15,8 @@
900
Mar 2026
Nov 2026
-
+
-edge · 852
-to 2026-11-01
+edge · 898
+to 2026-11-09
diff --git a/ios/Runner/HealthKitSleepWriter.swift b/ios/Runner/HealthKitSleepWriter.swift
index 65c9d43ce..6abd808fe 100644
--- a/ios/Runner/HealthKitSleepWriter.swift
+++ b/ios/Runner/HealthKitSleepWriter.swift
@@ -15,58 +15,156 @@ enum HealthKitSleepWriter {
private static let channelName = "openstrap/healthkit_sleep"
private static let store = HKHealthStore()
private static let queue = DispatchQueue(label: "wtf.openstrap.healthkit.sleep")
+ // Nap calls carry a monotonic `seq` from Dart. A native call that outlives
+ // its Dart-side timeout can still land later; dropping any nap call whose
+ // seq is not newer than the last applied one keeps a late replaceNap from
+ // overwriting a newer deleteNapRange for the same window. Guarded by queue.
+ private static var lastNapSeq = 0
static func register(messenger: FlutterBinaryMessenger) {
let channel = FlutterMethodChannel(name: channelName, binaryMessenger: messenger)
channel.setMethodCallHandler { call, result in
- guard call.method == "replaceSleepSession" else {
+ guard call.method == "replaceSleepSession"
+ || call.method == "replaceNap"
+ || call.method == "deleteNapRange" else {
result(FlutterMethodNotImplemented)
return
}
let args = call.arguments as? [String: Any] ?? [:]
queue.async {
- replace(args) { ok in
- DispatchQueue.main.async { result(ok) }
+ switch call.method {
+ case "replaceNap":
+ replaceNap(args) { ok in
+ DispatchQueue.main.async { result(ok) }
+ }
+ case "deleteNapRange":
+ deleteRange(args) { ok in
+ DispatchQueue.main.async { result(ok) }
+ }
+ default:
+ replace(args) { ok in
+ DispatchQueue.main.async { result(ok) }
+ }
}
}
}
}
- private static func replace(_ args: [String: Any], completion: @escaping (Bool) -> Void) {
+ // A confirmed nap: delete OUR overlapping sleepAnalysis samples in the nap
+ // window, then write one inBed envelope plus one asleep sample. HealthKit
+ // has no nap value (HKCategoryValueSleepAnalysis offers no nap case), so the
+ // nap appears in Apple Health as an ordinary daytime sleep segment — never
+ // labelled as a nap. No stage samples: a nap has no hypnogram, and writing
+ // asleepCore/Deep/REM would fabricate stages. The cleanup window is the nap
+ // window itself, NOT the noon-to-noon night window — it must never touch
+ // the exported main sleep.
+ private static func replaceNap(_ args: [String: Any], completion: @escaping (Bool) -> Void) {
+ guard let seq = napSeq(args) else {
+ completion(false)
+ return
+ }
+ if staleNapCallDropped(seq, completion: completion) { return }
guard HKHealthStore.isHealthDataAvailable() else {
completion(true) // iPad / simulator: no store, not an export failure
return
}
- guard let sleepType = HKObjectType.categoryType(forIdentifier: .sleepAnalysis) else {
+ guard let sleepType = HKObjectType.categoryType(forIdentifier: .sleepAnalysis),
+ let start = dateMs(args["startTime"]),
+ let end = dateMs(args["endTime"]),
+ start < end else {
completion(false)
return
}
- guard let cleanupStart = dateMs(args["cleanupStartTime"]),
- let cleanupEnd = dateMs(args["cleanupEndTime"]),
- cleanupStart < cleanupEnd else {
+ let asleepValue: HKCategoryValueSleepAnalysis
+ if #available(iOS 16.0, *) {
+ asleepValue = .asleepUnspecified
+ } else {
+ asleepValue = .asleep // deprecated pre-16 name for asleepUnspecified
+ }
+ let samples: [HKCategorySample] = [
+ HKCategorySample(type: sleepType, value: HKCategoryValueSleepAnalysis.inBed.rawValue, start: start, end: end),
+ HKCategorySample(type: sleepType, value: asleepValue.rawValue, start: start, end: end),
+ ]
+ deleteAndSave(samples: samples, type: sleepType, cleanupStart: start, cleanupEnd: end, seq: napSeq(args), completion: completion)
+ }
+
+ // A nap removed/rejected in Edge: delete OUR sleepAnalysis samples
+ // overlapping the window so the export does not outlive the decision.
+ // `protectWindows` (list of {startMs, endMs}) marks the CURRENT main-sleep
+ // windows: if a night shifted onto a previously exported nap, samples
+ // overlapping any of those windows are kept — deleting them would remove
+ // the user's night from Apple Health. Each window is protected separately;
+ // a union span would also cover a nap lying BETWEEN two nights and the
+ // delete would silently keep everything.
+ private static func deleteRange(_ args: [String: Any], completion: @escaping (Bool) -> Void) {
+ guard let seq = napSeq(args) else {
completion(false)
return
}
-
- let samples: [HKCategorySample]
- do {
- samples = try buildSamples(args, type: sleepType)
- } catch {
+ if staleNapCallDropped(seq, completion: completion) { return }
+ guard HKHealthStore.isHealthDataAvailable() else {
+ completion(true)
+ return
+ }
+ guard let sleepType = HKObjectType.categoryType(forIdentifier: .sleepAnalysis),
+ let start = dateMs(args["startTime"]),
+ let end = dateMs(args["endTime"]),
+ start < end else {
completion(false)
return
}
+ var protect: [(Date, Date)] = []
+ for raw in (args["protectWindows"] as? [Any] ?? []) {
+ if let m = raw as? [String: Any],
+ let ps = dateMs(m["startMs"]),
+ let pe = dateMs(m["endMs"]), ps < pe {
+ protect.append((ps, pe))
+ }
+ }
+ deleteRange(samples: [], type: sleepType, start: start, end: end,
+ protect: protect, seq: seq, completion: completion)
+ }
- let datePred = HKQuery.predicateForSamples(
- withStart: cleanupStart, end: cleanupEnd, options: []
- )
+ private static func napSeq(_ args: [String: Any]) -> Int? {
+ (args["seq"] as? NSNumber)?.intValue
+ }
+
+ // Runs on `queue`. Returns true when the call is stale and was dropped
+ // (completed with false — a dropped call never claims success).
+ private static func staleNapCallDropped(_ seq: Int, completion: @escaping (Bool) -> Void) -> Bool {
+ if seq <= lastNapSeq {
+ completion(false)
+ return true
+ }
+ lastNapSeq = seq
+ return false
+ }
+
+ // Delete-then-save. [seq] (nap calls only) is re-checked in the delete's
+ // completion callback: a newer nap call that started while this delete was
+ // in flight has already bumped lastNapSeq, so this call must NOT save its
+ // samples afterwards — otherwise a removed nap reappears after the newer
+ // deletion. Nil seq (replaceSleepSession) skips the re-check.
+ private static func deleteAndSave(
+ samples: [HKCategorySample],
+ type: HKCategoryType,
+ cleanupStart: Date,
+ cleanupEnd: Date,
+ seq: Int?,
+ completion: @escaping (Bool) -> Void
+ ) {
+ let datePred = HKQuery.predicateForSamples(withStart: cleanupStart, end: cleanupEnd, options: [])
let sourcePred = HKQuery.predicateForObjects(from: HKSource.default())
let pred = NSCompoundPredicate(andPredicateWithSubpredicates: [datePred, sourcePred])
-
- store.deleteObjects(of: sleepType, predicate: pred) { _, _, error in
+ store.deleteObjects(of: type, predicate: pred) { _, _, error in
if error != nil {
completion(false)
return
}
+ if let seq, seq != lastNapSeq {
+ completion(false) // superseded while the delete was in flight
+ return
+ }
guard !samples.isEmpty else {
completion(true)
return
@@ -77,6 +175,80 @@ enum HealthKitSleepWriter {
}
}
+ // Delete OUR sleepAnalysis samples overlapping [start, end), except those
+ // overlapping [protectStart, protectEnd) (the current main-sleep window) —
+ // a night that shifted onto a previously exported nap must not be deleted
+ // with it. The seq re-check happens before the delete lands.
+ private static func deleteRange(
+ samples: [HKCategorySample],
+ type: HKCategoryType,
+ start: Date,
+ end: Date,
+ protect: [(Date, Date)],
+ seq: Int,
+ completion: @escaping (Bool) -> Void
+ ) {
+ let datePred = HKQuery.predicateForSamples(withStart: start, end: end, options: [])
+ let sourcePred = HKQuery.predicateForObjects(from: HKSource.default())
+ let pred = NSCompoundPredicate(andPredicateWithSubpredicates: [datePred, sourcePred])
+ let query = HKSampleQuery(sampleType: type, predicate: pred, limit: HKObjectQueryNoLimit, sortDescriptors: nil) { _, results, error in
+ guard let found = results as? [HKCategorySample], error == nil else {
+ completion(false)
+ return
+ }
+ if seq != lastNapSeq {
+ completion(false) // superseded while the query was in flight
+ return
+ }
+ // Samples overlapping ANY protected main-sleep window are kept.
+ let doomed = found.filter { s in
+ !protect.contains { ps, pe in s.startDate < pe && s.endDate > ps }
+ }
+ guard !doomed.isEmpty else {
+ completion(true)
+ return
+ }
+ store.delete(doomed) { success, error in
+ completion(success && error == nil)
+ }
+ }
+ store.execute(query)
+ }
+
+ private static func replace(_ args: [String: Any], completion: @escaping (Bool) -> Void) {
+ guard HKHealthStore.isHealthDataAvailable() else {
+ completion(true) // iPad / simulator: no store, not an export failure
+ return
+ }
+ guard let sleepType = HKObjectType.categoryType(forIdentifier: .sleepAnalysis) else {
+ completion(false)
+ return
+ }
+ guard let cleanupStart = dateMs(args["cleanupStartTime"]),
+ let cleanupEnd = dateMs(args["cleanupEndTime"]),
+ cleanupStart < cleanupEnd else {
+ completion(false)
+ return
+ }
+
+ let samples: [HKCategorySample]
+ do {
+ samples = try buildSamples(args, type: sleepType)
+ } catch {
+ completion(false)
+ return
+ }
+
+ deleteAndSave(
+ samples: samples,
+ type: sleepType,
+ cleanupStart: cleanupStart,
+ cleanupEnd: cleanupEnd,
+ seq: nil, // sleep sessions carry no seq — unchanged behavior
+ completion: completion
+ )
+ }
+
private static func buildSamples(
_ args: [String: Any],
type: HKCategoryType
diff --git a/lib/compute/derivation_engine.dart b/lib/compute/derivation_engine.dart
index 16eb8578b..379e6ebbf 100644
--- a/lib/compute/derivation_engine.dart
+++ b/lib/compute/derivation_engine.dart
@@ -1852,7 +1852,12 @@ import 'vendor_sleep.dart';
// more than the windowed live/phone sources, instead of only when they counted
// nothing, so a short tracked walk no longer hides the day's chip total.
// gen4 (no counter) is unchanged. Edge-only.
-const int kAlgoVersion = 120;
+// 120 → 121 (nap cap 3 h): naps are capped at kMaxNapSec on every path —
+// detected bouts via dropOversizedNaps AND stored edits replayed through
+// applyNapEdits — so a pre-cap manual nap longer than 3 h no longer counts
+// into naps/nap_min. Days derived at v120 keep their stale naps without this
+// bump.
+const int kAlgoVersion = 121;
/// The sibling SHAs this version was derived against, asserted against
/// pubspec.yaml in test/db_serve_version_and_reads_test.dart.
///
@@ -10082,7 +10087,9 @@ class DerivationEngine {
List napEdits,
String note,
) {
- final merged = applyNapEdits(const [], napEdits);
+ // Cap stored edits too: a manual nap logged before the 3 h cap must not
+ // survive a re-derive as a counted nap.
+ final merged = dropOversizedNaps(applyNapEdits(const [], napEdits));
if (merged.isEmpty) {
_writeUnknownNaps(bundle, note);
return null;
@@ -10269,9 +10276,17 @@ class DerivationEngine {
'confidence': nap.confidence,
},
];
- candidates?.addAll(detected.where((n) => !napEdits.any((e) =>
+ // A nap longer than kMaxNapSec (3 h) is a sleep, not a nap — drop it
+ // before it can reach the suggestions, `nap_min`, sleep need or the
+ // timeline. Entry-time paths share the same constant via
+ // manualNapWindowIsValid; stored edits are capped again at the merge
+ // below so pre-cap rows cannot survive a re-derive.
+ final capped = dropOversizedNaps(detected);
+ candidates?.addAll(capped.where((n) => !napEdits.any((e) =>
e.overlaps(n['start'] as int, n['end'] as int))));
- final merged = applyNapEdits(const [], napEdits);
+ // Cap stored edits too: a manual nap logged before the 3 h cap must not
+ // survive a re-derive as a counted nap.
+ final merged = dropOversizedNaps(applyNapEdits(const [], napEdits));
bundle['naps'] = {
'value': merged,
diff --git a/lib/compute/nap_edits.dart b/lib/compute/nap_edits.dart
index ccc49887d..2f55908c9 100644
--- a/lib/compute/nap_edits.dart
+++ b/lib/compute/nap_edits.dart
@@ -54,9 +54,14 @@ typedef NapMap = Map;
/// scatter of two-minute entries would swamp the real ones in every total.
const int kMinManualNapSec = 5 * 60;
-/// Maximum. Anything longer is a sleep, not a nap, and belongs in the main
-/// sleep window where the stager can actually say something about its stages.
-const int kMaxManualNapSec = 6 * 60 * 60;
+/// Maximum length of anything counted as a nap: 3 hours. Anything longer is a
+/// sleep, not a nap, and belongs in the main sleep window where the stager can
+/// actually say something about its stages. Applies to detected AND manually
+/// logged naps alike — one cap, one place.
+const int kMaxNapSec = 3 * 60 * 60;
+
+/// Maximum for a manually logged nap — the same cap as detected naps.
+const int kMaxManualNapSec = kMaxNapSec;
/// Whether a window can be logged as a nap.
bool manualNapWindowIsValid(int startSec, int endSec) {
@@ -129,6 +134,16 @@ List applyNapEdits(List detected, List edits) {
return out;
}
+/// Drops every nap whose window exceeds [kMaxNapSec]. A detected bout longer
+/// than 3 h is a sleep fragment the detector misfiled as a nap; crediting it
+/// into `nap_min` would count a night's sleep as daytime rest. The filter is
+/// pure so the rule is testable without a derivation run.
+List dropOversizedNaps(List naps) => [
+ for (final n in naps)
+ if ((n['end'] as num).toInt() - (n['start'] as num).toInt() <= kMaxNapSec)
+ n,
+ ];
+
/// Total asleep minutes across [naps] — the `nap_min` scalar.
///
/// Always a number, including 0 for an empty list. The absent-versus-zero
diff --git a/lib/data/activity_store.dart b/lib/data/activity_store.dart
index 6c69eedea..7d5e61862 100644
--- a/lib/data/activity_store.dart
+++ b/lib/data/activity_store.dart
@@ -177,6 +177,17 @@ class ActivityStore {
final start = ((c['start_ts'] ?? c['start']) as num).toInt();
final end = ((c['end_ts'] ?? c['end']) as num).toInt();
if (end <= start) continue;
+ // A nap candidate over kMaxNapSec (3 h) is a sleep fragment, not a
+ // nap: never offer it for review — retire any pending rows it
+ // overlaps instead of keeping or re-creating them.
+ if (kind == ActivityKind.nap && end - start > kMaxNapSec) {
+ await tx.rawUpdate(
+ "UPDATE activity_suggestions SET status = 'superseded' "
+ "WHERE kind = ? AND status = 'pending' AND start_ts < ? AND end_ts > ?",
+ [kind.name, end, start],
+ );
+ continue;
+ }
final matches = await tx.query(
'activity_suggestions',
where:
@@ -329,6 +340,28 @@ class ActivityStore {
return false;
}
+ /// The main-sleep windows (epoch ms) of the nights around [s, e) — the
+ /// night ending on [s]'s date and the one beginning that evening. Used to
+ /// PROTECT night samples when a nap window is deleted from the health
+ /// store after the night shifted onto it.
+ static Future> mainSleepWindowsAround(
+ DatabaseExecutor tx,
+ int s,
+ int e,
+ ) async {
+ final out = <({int onsetMs, int offsetMs})>[];
+ for (final b in await _nightsAround(tx, s, e)) {
+ final w = ((b['sleep'] as Map?)?['window'] as Map?)?['value'];
+ if (w is Map) {
+ final on = w['onset_ms'], off = w['offset_ms'];
+ if (on is num && off is num && off > on) {
+ out.add((onsetMs: on.toInt(), offsetMs: off.toInt()));
+ }
+ }
+ }
+ return out;
+ }
+
static Future> _nightsAround(
DatabaseExecutor tx,
int s,
@@ -465,7 +498,7 @@ class ActivityStore {
} else {
if (!manualNapWindowIsValid(startTs, endTs)) {
throw const ActivityReviewException(
- 'A nap must last between 5 minutes and 6 hours.',
+ 'A nap must last between 5 minutes and 3 hours.',
);
}
if (await _overlapsSleep(tx, startTs, endTs)) {
diff --git a/lib/data/local_repository_impl.dart b/lib/data/local_repository_impl.dart
index f74dba334..966df83d5 100644
--- a/lib/data/local_repository_impl.dart
+++ b/lib/data/local_repository_impl.dart
@@ -37,6 +37,7 @@ import 'db.dart';
import 'activity_store.dart';
import '../models/activity_suggestion.dart';
import '../health/health_export.dart';
+import '../health/health_nap_export.dart';
import '../import/whoop_import.dart' show WhoopImporter;
import 'journal_fields.dart';
import '../ble/adapters/_registry.dart' show kBandRegistry;
@@ -90,9 +91,21 @@ class LocalRepositoryImpl extends LocalRepository {
sessionId: 'suggestion:${suggestion.id}', suggestion: suggestion);
await HealthExporter.exportWorkoutId('suggestion:${suggestion.id}');
} else {
- await ActivityStore(await LocalDb.instance).confirm(suggestion,
- startTs: start, endTs: end,
- edited: start != suggestion.startTs || end != suggestion.endTs);
+ // DB write + Health write in one critical section: a concurrently
+ // running per-day export must not read the pre-confirm state and write
+ // the nap after a removal, and vice versa.
+ await HealthNapExporter.shared.synchronized(() async {
+ await ActivityStore(await LocalDb.instance).confirm(suggestion,
+ startTs: start, endTs: end,
+ edited: start != suggestion.startTs || end != suggestion.endTs);
+ // A nap the user just confirmed goes to Apple Health right away (iOS);
+ // the exporter re-checks the row and the main-sleep overlap itself.
+ await HealthNapExporter.exportConfirmedNap(
+ dayId: dayLabelOf(DateTime.fromMillisecondsSinceEpoch(start * 1000)),
+ startTs: start,
+ endTs: end,
+ );
+ });
}
await onActivitiesChanged?.call();
}
diff --git a/lib/health/health_export.dart b/lib/health/health_export.dart
index 0e227ee9d..82af140b1 100644
--- a/lib/health/health_export.dart
+++ b/lib/health/health_export.dart
@@ -30,6 +30,7 @@ import '../data/day_label.dart';
import '../data/db.dart';
import '../data/series_codec.dart';
import 'health_heart_rate_batch.dart';
+import 'health_nap_export.dart';
import 'health_sleep_session.dart';
/// What we can do with the health store right now.
@@ -1259,6 +1260,31 @@ class HealthExporter {
debugPrint('[health] write Apple sleep session: $e');
success = false;
}
+ // The sleep replace's noon-to-noon cleanup window covers the wake day's
+ // afternoon AND can reach into the previous calendar day, so it deletes
+ // OUR nap samples there. Re-write the confirmed naps of BOTH days after
+ // it on every pass (delete-then-write, so idempotent) — otherwise the
+ // next re-derive of a non-finalized day would silently remove a nap the
+ // user confirmed.
+ final prevDate = dayLabelOf(
+ DateTime(dayStart.year, dayStart.month, dayStart.day - 1),
+ );
+ try {
+ // Both days independently: a failure on one must not skip the other —
+ // the cleanup may already have deleted that day's nap samples.
+ final todayOk = await HealthNapExporter.shared.exportDayNaps(date);
+ final prevOk = await HealthNapExporter.shared.exportDayNaps(prevDate);
+ if (!todayOk || !prevOk) {
+ debugPrint('[health] write Apple naps returned false');
+ success = false;
+ }
+ } on TimeoutException {
+ // A hung nap write means the store is busy/locked — same handling as
+ // the other native deletes: stop the pass instead of burning the
+ // day's retry budget (and holding the lock) for 30 s per nap.
+ _storeHung = true;
+ success = false;
+ }
}
// One-shot cleanup of the fabricated step samples earlier versions wrote.
diff --git a/lib/health/health_nap_export.dart b/lib/health/health_nap_export.dart
new file mode 100644
index 000000000..38d3d8392
--- /dev/null
+++ b/lib/health/health_nap_export.dart
@@ -0,0 +1,596 @@
+// health_nap_export.dart — write a user-confirmed nap to Apple Health
+// (HealthKit) on iOS.
+//
+// HealthKit has NO nap category: the only sleep type is
+// HKCategoryTypeIdentifier.sleepAnalysis, and HKCategoryValueSleepAnalysis
+// offers exactly inBed / awake / asleepCore / asleepDeep / asleepREM /
+// asleepUnspecified (plus the deprecated asleep). There is no value and no
+// metadata key the Health app renders as "nap". So a nap is exported as an
+// inBed envelope plus one asleepUnspecified sample over the confirmed window
+// — it shows up in Apple Health as an ordinary (daytime) sleep segment and
+// counts toward Time Asleep there; it is NOT labelled as a nap.
+//
+// Naps carry no hypnogram (the detector yields a window only), so no stage
+// samples are written — fabricating asleepCore/Deep/REM would violate the
+// app's never-fabricate rule.
+//
+// Only rows with source 'confirmed' or 'manual' are ever exported; 'pending'
+// detections and 'rejected' windows are not. The window is re-validated at
+// export time (shared 5 min – kMaxNapSec (3 h) bounds, not in the future, and
+// NOT overlapping the derived main sleep of the surrounding nights — the
+// same check the confirm path enforces, repeated here so a stale row or a
+// shifted night can never push night-sleep minutes into Health as a nap).
+//
+// Idempotency: the native writer deletes THIS APP's own sleepAnalysis samples
+// overlapping the nap window before writing, so repeated exports never
+// duplicate. Removing/rejecting a nap in Edge deletes the same window, while
+// samples overlapping the current main-sleep window are protected (the
+// night may have shifted onto a previously exported nap).
+//
+// Failed exports/deletes are persisted (cursors `health_nap_pending_exports`
+// / `health_nap_pending_deletes`) and retried by the per-day export pass, so
+// a confirmed nap does not stay missing from Apple Health just because one
+// write failed on a day behind the export cursor.
+//
+// iOS only for now — Health Connect (Android) has no nap export yet; on
+// Android every method returns false and writes nothing. Nothing here throws:
+// a missing store, a denied permission or a failed write reads as false.
+
+import 'dart:async';
+import 'dart:convert';
+
+import 'package:flutter/foundation.dart';
+import 'package:flutter/services.dart';
+import 'package:shared_preferences/shared_preferences.dart';
+
+import '../compute/nap_edits.dart' show manualNapWindowIsValid;
+import '../data/activity_store.dart';
+import '../data/db.dart';
+import 'health_export.dart' show HealthExporter, kHealthSyncPref;
+
+/// Native side: `HealthKitSleepWriter` on the existing sleep channel.
+abstract interface class HealthKitNapWriter {
+ /// Delete our own sleepAnalysis samples overlapping [start, end), then write
+ /// one inBed + one asleepUnspecified sample over [start, end).
+ Future replaceNap({required DateTime start, required DateTime end});
+
+ /// Delete our own sleepAnalysis samples overlapping [start, end), except
+ /// those overlapping any window in [protectWindows] (the current main-sleep
+ /// windows as {'startMs', 'endMs'} maps, epoch ms).
+ Future deleteRange({
+ required DateTime start,
+ required DateTime end,
+ List