Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
1fb0e12
Export confirmed naps to Apple Health as daytime sleep segments
mistral-vibe Nov 7, 2026
28e42c6
Address PR review: row-authoritative nap window, per-day nap re-expor…
mistral-vibe Nov 7, 2026
7cebb76
Make nap export tests clock-relative
mistral-vibe Nov 7, 2026
c3777e9
Fix inverted native seq guard; isolate per-row failures in exportDayNaps
mistral-vibe Nov 7, 2026
025b589
feat: cap naps at 3 hours (manual entries and detected bouts)
mistral-vibe Nov 7, 2026
d1438d3
Pin the nap export bounds test to the shared 3 h cap
mistral-vibe Nov 7, 2026
a49d891
Coordinate nap removal with the daily Health export; 3 h in all nap m…
mistral-vibe Nov 7, 2026
22b9843
Fix analyzer error in HealthNapExporter.synchronized
mistral-vibe Nov 7, 2026
2a23ce3
Drop unused dart:isolate import (Zone/runZoned resolve via dart:async)
mistral-vibe Nov 7, 2026
2956770
Fix tests broken by the 3 h nap cap and by future-dated test windows
mistral-vibe Nov 7, 2026
a33bd35
DST fold test: use a 2 h elapsed bout (00:30->01:30) so the midnight-…
mistral-vibe Nov 8, 2026
02a7677
DST fold test: anchor to UTC instants, not ambiguous wall times
mistral-vibe Nov 8, 2026
1d861e4
Address OpenStrap/edge#677 review findings
mistral-vibe Nov 8, 2026
a386b20
Address second review round on #677: per-window protection, independe…
mistral-vibe Nov 8, 2026
a7c6fc1
chore: refresh star history chart
github-actions[bot] Nov 9, 2026
12cdece
Warn WHOOP users about firmware restrictions on data access
mikenrafter Nov 9, 2026
933630e
Clarify guidance for future users and show the firmware warning
mikenrafter Nov 9, 2026
38a83e9
Merge pull request #680 from mikenrafter/warn/whoop-firmware-access
abdulsaheel Nov 9, 2026
85ecde1
l10n: add report contact strings for es, fr, hi, zh (main's l10n test…
abdulsaheel Nov 10, 2026
31ae237
nap pr: drop coderabbit change, fix indent, accurate delete comment
abdulsaheel Nov 10, 2026
5829102
nap export: clear other-day pending retries under their own day, fix …
abdulsaheel Nov 10, 2026
aa5b160
main is red since #680: ru/th strings for the firmware warning, galle…
abdulsaheel Nov 10, 2026
802b30f
Merge pull request #683 from OpenStrap/fix/l10n-report-contact
abdulsaheel Nov 10, 2026
e086d3e
Merge branch 'main' into vibe/nap-health-export-9b136b
abdulsaheel Nov 10, 2026
f8110a0
Fix CI on #677: use _defaultDayNapRows seam default, regenerate freez…
mistral-vibe Nov 10, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions .coderabbit.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
49 changes: 48 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -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.

<img width="1774" height="887" alt="OpenStrap Edge" src="https://github.com/user-attachments/assets/66653a25-ac97-4f8c-8be1-6c9fceeaf08b" />

A health app for your wearables. No subscription, no fees, private by default.
Expand All @@ -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
Expand Down
6 changes: 3 additions & 3 deletions docs/star-history.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
208 changes: 190 additions & 18 deletions ios/Runner/HealthKitSleepWriter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
23 changes: 19 additions & 4 deletions lib/compute/derivation_engine.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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.
///
Expand Down Expand Up @@ -10082,7 +10087,9 @@ class DerivationEngine {
List<NapEdit> 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;
Expand Down Expand Up @@ -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'] = <String, dynamic>{
'value': merged,
Expand Down
Loading
Loading