From 41162e89fd9330da5edb8f32794a722e1efee764 Mon Sep 17 00:00:00 2001 From: Ncbudd <209378361+Ncbudd@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:42:21 -0500 Subject: [PATCH 1/2] Wake: hold after the alarm rang; follow an early calendar start --- core/embertide/engine/controller.py | 1 + core/embertide/engine/night.py | 63 +++++++++++++-- core/embertide/models.py | 1 + core/tests/test_scenarios.py | 7 +- core/tests/test_wake_morning.py | 116 ++++++++++++++++++++++++++++ sel.txt | 1 + web/src/screens/SettingsSleep.tsx | 4 +- web/src/types.ts | 2 +- 8 files changed, 183 insertions(+), 12 deletions(-) create mode 100644 core/tests/test_wake_morning.py create mode 100644 sel.txt diff --git a/core/embertide/engine/controller.py b/core/embertide/engine/controller.py index 7d36b67..fb1f2de 100644 --- a/core/embertide/engine/controller.py +++ b/core/embertide/engine/controller.py @@ -751,6 +751,7 @@ async def _tick_person(self, p: Person, now: float, frame, guest_zones: set[str] self._ctx_home[p.id] = home e.busy_until = ctx.busy_until e.follow_alarm(now, ctx.next_alarm, ctx.alarm_reported) # the warm wake lines up with the phone's alarm + e.follow_calendar(now, ctx.early_start) # ... and comes earlier for an early first event except Exception: # noqa: BLE001 log.exception("context failed for %s", p.id) # away for a while (engine/away.py): back when they use their side or the end date passes diff --git a/core/embertide/engine/night.py b/core/embertide/engine/night.py index 5d85780..a6104a4 100644 --- a/core/embertide/engine/night.py +++ b/core/embertide/engine/night.py @@ -70,6 +70,7 @@ class NightState: lie_in: bool = False lie_in_over: bool = False # it ended (got up / cap): getting back in doesn't start another snoozed_until: float | None = None # a later alarm after the followed one rang (a snooze or an extended alarm) + alarms_seen: list = field(default_factory=list) # later alarms the phone showed after the followed one rang, still in bed ended: bool = False # "I'm up": the night was ended by hand (the dial, the app, a watch) # the person's own phone / watch (the "phone:bedside" and "watch:me" votes): ever voted this night, since when # neither has, and whether the pad was empty for a while after that. Used only to end a lie-in (see _lie_in) @@ -222,7 +223,7 @@ def _end_flash(self, now: float, source: str = "app") -> None: # ---------- the phone's alarm ---------- ALARM_EARLIER_S = 4 * 3600 # an alarm up to 4 h before the planned wake moves it earlier - ALARM_LATER_S = 3 * 3600 # and up to 3 h after (a second, later alarm to sleep in) moves it later + ALARM_LATER_S = 3 * 3600 # and up to 3 h after (a later alarm set to sleep in) moves it later, until one rings SNOOZE_S = 30 * 60 # a later alarm this soon after the first one rang = snooze @@ -260,17 +261,65 @@ def follow_alarm(self, now: float, alarm: float | None, reported: bool = False) if self.s.wake_from_alarm == alarm: return False fa = self.s.wake_from_alarm - if fa and fa <= now and fa < alarm <= fa + self.SNOOZE_S: - if self.s.snoozed_until != alarm: - self.s.snoozed_until = alarm - self._ev(now, "alarm_snoozed", until=alarm, alarm=fa) - # the followed alarm already rang and the next one is a few minutes after it: a snooze. The wake holds - # at the time the alarm first rang (a reset alarm well after it is a real change of plan and is followed) + if fa and fa <= now and alarm > fa: + # the followed alarm already rang: the morning has begun and the wake holds at the time it rang. A later + # alarm the phone shows while they're still in bed is a snooze or a backup alarm, never a reason to push + # the wake later: that put the side back into its night phases, so getting up was read as a trip to the + # bathroom and the side kept running (and the phone's next alarm flipped between the snooze and the backup + # alarm, 2026-11-27). Staying in bed is the lie-in's job. Only a NEW alarm set after they got up (the + # night over) means going back to bed, and is followed. + up = self.s.state == "done" or self.s.lie_in_over + if not up or alarm in self.s.alarms_seen: + if not up and alarm not in self.s.alarms_seen: + self.s.alarms_seen = (self.s.alarms_seen + [alarm])[-12:] + if alarm <= fa + self.SNOOZE_S and self.s.snoozed_until != alarm: + self.s.snoozed_until = alarm + self._ev(now, "alarm_snoozed", until=alarm, alarm=fa) + return False + self.s.alarms_seen = [] + if self.s.wake_source == "calendar" and self.s.wake_override is not None and alarm > self.s.wake_override: + self.s.wake_from_alarm = alarm # an early start in the calendar already woke them earlier return False self.s.wake_override, self.s.wake_from_alarm, self.s.wake_source = alarm, alarm, None self._ev(now, "wake_from_alarm", wake=alarm, planned=planned) return True + # ---------- an early start in the calendar ---------- + CALENDAR_LEAD_S = 45 * 60 # warm wake this long before the first event (the app's "Wake up earlier" button) + + def follow_calendar(self, now: float, early_start: float | None) -> bool: + """Move tonight's wake earlier for an early first event tomorrow morning (the phone's or an HA calendar), + Settings: "Wake for early events". Only ever earlier than the wake it would otherwise have (an earlier alarm + wins), at most ALARM_EARLIER_S before the planned wake, and never once that wake has come. A wake set by hand + wins. When the event goes away before the wake, the wake goes back (to the alarm's, if one is followed).""" + if not getattr(self.person.settings, "wake_with_calendar", True) or self.s.wake_by_hand: + return False + s = self.s + cur = s.wake_override if s.wake_source == "calendar" else None + # the wake without the calendar: the followed alarm's, or the planned one + fa = s.wake_from_alarm if s.wake_from_alarm and (cur is not None or s.wake_override == s.wake_from_alarm) else None + from datetime import datetime + d = night_date(datetime.fromtimestamp(now, self.tz)) + rhythm = pick_rhythm(self.person.rhythms, d) + if rhythm is None: + return False + planned = resolve(rhythm, d, self.tz).wake + base = fa or planned + want = early_start - self.CALENDAR_LEAD_S if early_start else None + if want is not None and now < want and planned - self.ALARM_EARLIER_S <= want < base - 60: + if cur is not None and abs(cur - want) < 60: + return False + if cur is None and s.wake_override is not None and s.wake_override <= now: + return False # the morning already began on another wake + s.wake_override, s.wake_source = want, "calendar" + self._ev(now, "wake_from_calendar", wake=want, event=early_start, planned=planned) + return True + if cur is not None and now < cur: # the event went away or moved later before the wake came + s.wake_override, s.wake_source = fa, None + self._ev(now, "wake_calendar_cleared", was=cur) + return True + return False + # ---------- lying in ---------- # the wake target runs on while they're still in bed (getting up ends it: LIE_IN_UP_S), up to this long past the # night's end only as a safety net for a sensor stuck on "occupied" (2026-11-15: a 45-minute cap turned the side off diff --git a/core/embertide/models.py b/core/embertide/models.py index a6aa026..5ce7a49 100644 --- a/core/embertide/models.py +++ b/core/embertide/models.py @@ -230,6 +230,7 @@ class PersonSettings(BaseModel): wearable: str = Field("", max_length=20, pattern=r"^[a-z_]*$") # first-time setup's pick ("oura", "apple", "none"...) setup_steps: list[str] = Field(default_factory=list, max_length=30) # first-time setup steps already done (skipped next time) tone: Literal["calm", "friendly", "cheeky"] = "calm" # how notifications and suggestions are worded (voice.py); alerts stay plain + wake_with_calendar: bool = True # an early first event tomorrow morning (phone or HA calendar) moves the warm wake earlier wake_with_alarm: bool = True # the warm wake lines up with the phone's next alarm (shared from the phone), earlier or a bit later pet_questions: bool = True # ask "was the pet on the bed?" after something lay on your side that didn't look like you # in / out of bed tuning (None = recommended): minutes lying down before the night starts, and minutes out of diff --git a/core/tests/test_scenarios.py b/core/tests/test_scenarios.py index 2a74437..80ff21f 100644 --- a/core/tests/test_scenarios.py +++ b/core/tests/test_scenarios.py @@ -514,7 +514,8 @@ async def test_the_warm_wake_follows_the_phones_alarm(tmp_path): async def test_snoozing_the_alarm_holds_the_wake(tmp_path): """The followed alarm rings and is snoozed: the phone's next alarm is now 9 min later. The wake stays at the - time the alarm first rang; resetting the alarm an hour later (sleeping in on purpose) is still followed.""" + time the alarm first rang. An alarm an hour later doesn't move it either (2026-11-27: a backup alarm moved the wake + back into the night, so getting up was read as a night-time trip); staying in bed is the lie-in's job.""" n = Night(tmp_path, "2026-11-05T22:00") n.present("left", True) await n.until("2026-11-06T03:00") @@ -527,8 +528,8 @@ async def test_snoozing_the_alarm_holds_the_wake(tmp_path): assert not e.follow_alarm(now, alarm + 9 * 60) # snooze assert not e.follow_alarm(now, alarm + 18 * 60) # and again assert abs(e.s.wake_override - alarm) < 1 - assert e.follow_alarm(now, alarm + 3600) # a new alarm an hour later: followed - assert abs(e.s.wake_override - (alarm + 3600)) < 1 + assert not e.follow_alarm(now, alarm + 3600) # a backup alarm an hour later: the wake holds + assert abs(e.s.wake_override - alarm) < 1 def test_a_short_sit_down_hours_before_isnt_getting_into_bed(): diff --git a/core/tests/test_wake_morning.py b/core/tests/test_wake_morning.py new file mode 100644 index 0000000..4acdcd8 --- /dev/null +++ b/core/tests/test_wake_morning.py @@ -0,0 +1,116 @@ +"""The morning after the alarm rang, and an early start in the calendar (2026-11-27: the 6:00 alarm rang, the phone's +next alarm flipped between the snooze and an 8:30 backup alarm, the wake moved to 8:30 and then back to the planned +9:30 on "no alarm", so getting up at 6:46 was read as a night-time trip and the side kept running).""" + +from datetime import datetime + +from embertide.engine import phone_context as PC +from test_scenarios import Night + + +def _at(n, ts: float) -> str: + return datetime.fromtimestamp(ts, n.clock.tz).strftime("%Y-%m-%dT%H:%M") + + +async def _night(tmp_path): + n = Night(tmp_path, "2026-11-05T22:00") + n.present("left", True) + await n.until("2026-11-05T23:00") + e = n.e(n.p1) + return n, e, e.night.wake + + +async def test_backup_alarm_after_the_alarm_rang_keeps_the_wake(tmp_path): + n, e, planned = await _night(tmp_path) + alarm = planned - 3 * 3600 + PC.update(n.store, n.p1.id, {"next_alarm": alarm}, n.clock.now_ts()) + await n.step(2) + assert e.s.wake_override == alarm + await n.until(_at(n, alarm + 60)) + backup = alarm + 150 * 60 # a backup alarm, before the planned wake + for nxt in (backup, alarm + 10 * 60, backup, alarm + 55 * 60, backup, None): # what the phone sent that morning + PC.update(n.store, n.p1.id, {"next_alarm": nxt}, n.clock.now_ts()) + await n.step(2) + assert e.s.wake_override == alarm and abs(e.night.wake - alarm) < 1, nxt + assert not n.events("wake_alarm_cleared") + + +async def test_getting_up_after_the_alarm_ends_the_night(tmp_path): + n, e, planned = await _night(tmp_path) + alarm = planned - 3 * 3600 + PC.update(n.store, n.p1.id, {"next_alarm": alarm}, n.clock.now_ts()) + await n.until(_at(n, alarm + 40 * 60)) + PC.update(n.store, n.p1.id, {"next_alarm": alarm + 150 * 60}, n.clock.now_ts()) # backup alarm still set + await n.step(2) + n.present("left", False) + await n.step(16) # 8 min out of bed + assert e.s.state == "done", e.s.state + assert not n.side("left").on + PC.update(n.store, n.p1.id, {"next_alarm": alarm + 150 * 60}, n.clock.now_ts()) # the same backup alarm: no reopen + await n.step(4) + assert e.s.state == "done" and e.s.wake_override == alarm + + +async def test_alarm_moved_later_before_it_rings_is_still_followed(tmp_path): + n, e, planned = await _night(tmp_path) + alarm = planned - 3600 + PC.update(n.store, n.p1.id, {"next_alarm": alarm}, n.clock.now_ts()) + await n.step(2) + PC.update(n.store, n.p1.id, {"next_alarm": planned + 1800}, n.clock.now_ts()) # set later to sleep in + await n.step(2) + assert e.s.wake_override == planned + 1800 + + +async def test_early_event_moves_the_wake_earlier(tmp_path): + n, e, planned = await _night(tmp_path) + event = planned - 2 * 3600 + PC.update(n.store, n.p1.id, {"early_start": event}, n.clock.now_ts()) + await n.step(2) + assert e.s.wake_override == event - 45 * 60 and e.s.wake_source == "calendar" + assert abs(e.night.wake - (event - 45 * 60)) < 1 + assert n.events("wake_from_calendar") + + +async def test_event_an_hour_after_the_planned_wake_changes_nothing(tmp_path): + n, e, planned = await _night(tmp_path) + PC.update(n.store, n.p1.id, {"early_start": planned + 3600}, n.clock.now_ts()) + await n.step(2) + assert e.s.wake_override is None + + +async def test_earlier_alarm_wins_over_the_calendar(tmp_path): + n, e, planned = await _night(tmp_path) + alarm = planned - 3 * 3600 + PC.update(n.store, n.p1.id, {"next_alarm": alarm, "early_start": planned - 3600}, n.clock.now_ts()) + await n.step(2) + assert e.s.wake_override == alarm and e.s.wake_source is None + + +async def test_calendar_earlier_than_the_alarm_wins_and_the_alarm_does_not_undo_it(tmp_path): + n, e, planned = await _night(tmp_path) + alarm = planned - 3600 + event = planned - 2 * 3600 # warm wake 2 h 45 min early + PC.update(n.store, n.p1.id, {"next_alarm": alarm, "early_start": event}, n.clock.now_ts()) + await n.step(4) + assert e.s.wake_override == event - 45 * 60 and e.s.wake_source == "calendar" + # the event is cancelled: back to the alarm, not the planned wake + PC.update(n.store, n.p1.id, {"early_start": None}, n.clock.now_ts()) + await n.step(2) + assert e.s.wake_override == alarm + assert n.events("wake_calendar_cleared") + + +async def test_wake_set_by_hand_wins_over_the_calendar(tmp_path): + n, e, planned = await _night(tmp_path) + e.s.wake_override, e.s.wake_by_hand, e.s.wake_source = planned - 600, True, "hand" + PC.update(n.store, n.p1.id, {"early_start": planned - 2 * 3600}, n.clock.now_ts()) + await n.step(2) + assert e.s.wake_override == planned - 600 + + +async def test_calendar_setting_off(tmp_path): + n, e, planned = await _night(tmp_path) + n.p1.settings.wake_with_calendar = False + PC.update(n.store, n.p1.id, {"early_start": planned - 2 * 3600}, n.clock.now_ts()) + await n.step(2) + assert e.s.wake_override is None diff --git a/sel.txt b/sel.txt new file mode 100644 index 0000000..90a8622 --- /dev/null +++ b/sel.txt @@ -0,0 +1 @@ +sim_edges.py simnight.py test_ai_settings.py test_alarm_follow.py test_context.py test_end_night.py test_engine.py test_guest_settings.py test_lie_in.py test_night_devices.py test_night_fix.py test_phone_context.py test_restart_night.py test_review_context_words.py test_scenarios.py test_sim_clock_jump.py test_sim_night_away_pet.py test_sim_night_calibration.py test_sim_night_controls.py test_sim_night_dog_identity.py test_sim_night_gaps.py test_sim_night_people.py test_sim_night_sensors.py test_sim_night_sleepsign.py test_sim_night_time.py test_sim_notify_actions.py test_sim_notify_delivery.py test_sim_notify_gaps.py test_sim_notify_more.py test_sim_notify_tones.py test_sim_notify_triggers.py test_sim_wear_clock.py test_sim_wear_cloud.py test_sim_wear_cloud_more.py test_sim_wear_hc.py test_sim_wear_live.py test_sim_wear_open.py test_sim_wear_people.py test_up_during_night.py test_wake_morning.py test_web_engines.py \ No newline at end of file diff --git a/web/src/screens/SettingsSleep.tsx b/web/src/screens/SettingsSleep.tsx index a629371..290d743 100644 --- a/web/src/screens/SettingsSleep.tsx +++ b/web/src/screens/SettingsSleep.tsx @@ -47,8 +47,10 @@ export function SleepDataRows({ s, upd }: { s: PersonSettings; upd: (p: Partial< upd({ autopilot: { ...s.autopilot, trust_more: v } })} /> Used for your in-bed and asleep times, sleep stages, heart rate, your normal range and whether it's you in bed. -
Wake with my phone's alarm
The warm wake moves to match your next alarm, earlier or later (set a second alarm to sleep in). Needs your phone to share its next alarm.
+
Wake with my phone's alarm
The warm wake moves to match your next alarm, earlier or later. Once it rings, snoozes and backup alarms don't move it later. Needs your phone to share its next alarm.
upd({ wake_with_alarm: e.target.checked })} />
+
Wake earlier for early events
When your calendar has an event early tomorrow morning, the warm wake moves to 45 minutes before it. Only ever earlier; an earlier alarm wins. Needs your phone (or Home Assistant) to share your calendar.
+ upd({ wake_with_calendar: e.target.checked })} />
Ask me about the pet
If something on your side for half an hour or more didn't seem like you, you're asked "Was it the dog?". One question a night at most.
upd({ pet_questions: e.target.checked })} />
{(s.pet_questions ?? true) &&
Also as a notification
Only between 8 AM and 9 PM. You can answer right from it.
diff --git a/web/src/types.ts b/web/src/types.ts index ae4317e..73328c1 100644 --- a/web/src/types.ts +++ b/web/src/types.ts @@ -20,7 +20,7 @@ export interface PersonSettings { tone?: "calm" | "friendly" | "cheeky"; show_ask?: boolean; work_days?: number[]; wearable?: string; setup_steps?: string[]; - pet_questions?: boolean; wake_with_alarm?: boolean; in_bed_after_min?: number | null; up_after_min?: number | null; + pet_questions?: boolean; wake_with_alarm?: boolean; wake_with_calendar?: boolean; in_bed_after_min?: number | null; up_after_min?: number | null; } interface NightContext { home: boolean | null; why: string; distance_km: number | null; eta_min: number | null; heading_home: boolean; busy_until: number | null; event_end: number | null; lights_on: boolean | null; early_start?: number | null } interface FlashState { kind: "hot" | "cold"; start: number; end: number; ease_end: number; target_c: number; source: string } From b95d1f5b41961f4e2024fedfffbd0fd06111eec8 Mon Sep 17 00:00:00 2001 From: Ncbudd <209378361+Ncbudd@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:59:51 -0500 Subject: [PATCH 2/2] Wake: review follow-ups (morning begun, deleted alarm, back in bed, noon, settings off) --- core/embertide/engine/night.py | 128 +++++++++++++++++++------------- core/tests/test_wake_morning.py | 51 +++++++++++++ 2 files changed, 128 insertions(+), 51 deletions(-) diff --git a/core/embertide/engine/night.py b/core/embertide/engine/night.py index a6104a4..fea2188 100644 --- a/core/embertide/engine/night.py +++ b/core/embertide/engine/night.py @@ -94,6 +94,7 @@ def __init__(self, person: Person, tz: ZoneInfo) -> None: self.s = NightState() self.night: ResolvedNight | None = None self.busy_until: float | None = None # set by the controller from calendar context + self.last_present: bool | None = None # presence at the last tick self.away = False # away for a while (engine/away.py), set by the controller each tick # settling in (controller._start_gate): False = the bed radar / phone don't back this side's presence yet, so # lying there doesn't start the night; None = no opinion (no radar), the usual start @@ -227,60 +228,81 @@ def _end_flash(self, now: float, source: str = "app") -> None: SNOOZE_S = 30 * 60 # a later alarm this soon after the first one rang = snooze + def _wake_day(self, now: float): + """(tonight's date, its planned wake) for following an alarm or the calendar, or None when it can't apply now: + no rhythm, or last night still running past noon (a lie-in) while the date already says tonight.""" + from datetime import datetime + d = night_date(datetime.fromtimestamp(now, self.tz)) + if self.night is not None and self.night.date != d: + return None + rhythm = pick_rhythm(self.person.rhythms, d) + if rhythm is None: + return None + return d, resolve(rhythm, d, self.tz).wake + def follow_alarm(self, now: float, alarm: float | None, reported: bool = False) -> bool: """Line tonight's wake up with the phone's next alarm (Settings: "Wake with my alarm"). Returns True when the wake moved. A wake set by hand in the app wins; an alarm far from tonight's planned wake is someone else's day. `reported`: the phone sent its next alarm lately. Then "no alarm" (None: none set, or the next one a day or more away) means the followed alarm was turned off before it rang, and the planned wake comes back. A phone that has gone quiet says nothing either way.""" - if not getattr(self.person.settings, "wake_with_alarm", True) or self.s.wake_by_hand: + s = self.s + if s.wake_by_hand or s.ended: return False - if alarm is None: - fa = self.s.wake_from_alarm - if reported and fa and now < fa and self.s.wake_override == fa: - self.s.wake_override, self.s.wake_from_alarm, self.s.wake_source = None, None, None - self._ev(now, "wake_alarm_cleared", was=fa, reason="no alarm") + fa = s.wake_from_alarm + if not getattr(self.person.settings, "wake_with_alarm", True): + if fa and now < fa and s.wake_override == fa: # switched off: an alarm it followed lets go + s.wake_override, s.wake_from_alarm, s.wake_source = None, None, None + self._ev(now, "wake_alarm_cleared", was=fa, reason="setting off") return True return False - from datetime import datetime - d = night_date(datetime.fromtimestamp(now, self.tz)) - rhythm = pick_rhythm(self.person.rhythms, d) - if rhythm is None or alarm <= now: + + def drop(**why) -> bool: + # the followed alarm was turned off before it rang + if s.wake_override == fa: + s.wake_override, s.wake_from_alarm, s.wake_source = None, None, None + self._ev(now, "wake_alarm_cleared", was=fa, **why) + return True + s.wake_from_alarm = None # the wake came from the calendar: keep it, forget the alarm + return False + if alarm is None: + if reported and fa and now < fa: + return drop(reason="no alarm") + return False + day = self._wake_day(now) + if day is None or alarm <= now: return False - planned = resolve(rhythm, d, self.tz).wake + planned = day[1] if not (planned - self.ALARM_EARLIER_S <= alarm <= planned + self.ALARM_LATER_S): # the alarm this wake came from was turned off before it rang (the phone's next alarm is now a later, # other day's one): back to the planned wake, so sleeping in really is sleeping in. An earlier odd alarm # (a 3 AM reminder) means nothing about the morning one, which is still set. - fa = self.s.wake_from_alarm - if fa and now < fa < alarm and self.s.wake_override == fa: - self.s.wake_override, self.s.wake_from_alarm, self.s.wake_source = None, None, None - self._ev(now, "wake_alarm_cleared", was=fa, planned=planned) - return True + if fa and now < fa < alarm: + return drop(planned=planned) return False - if self.s.wake_from_alarm == alarm: + if fa == alarm: return False - fa = self.s.wake_from_alarm - if fa and fa <= now and alarm > fa: - # the followed alarm already rang: the morning has begun and the wake holds at the time it rang. A later - # alarm the phone shows while they're still in bed is a snooze or a backup alarm, never a reason to push - # the wake later: that put the side back into its night phases, so getting up was read as a trip to the - # bathroom and the side kept running (and the phone's next alarm flipped between the snooze and the backup - # alarm, 2026-11-27). Staying in bed is the lie-in's job. Only a NEW alarm set after they got up (the - # night over) means going back to bed, and is followed. - up = self.s.state == "done" or self.s.lie_in_over - if not up or alarm in self.s.alarms_seen: - if not up and alarm not in self.s.alarms_seen: - self.s.alarms_seen = (self.s.alarms_seen + [alarm])[-12:] - if alarm <= fa + self.SNOOZE_S and self.s.snoozed_until != alarm: - self.s.snoozed_until = alarm + morning = s.wake_override if s.wake_override is not None else planned + if morning <= now and alarm > morning: + # the wake already came (the followed alarm rang, or the planned wake passed): the morning has begun and + # the wake holds. A later alarm the phone shows meanwhile is a snooze or a backup alarm, never a reason to + # push the wake later: that put the side back into its night phases, so getting up was read as a trip to + # the bathroom and the side kept running (and the phone's next alarm flipped between the snooze and the + # backup alarm, 2026-11-27). Staying in bed is the lie-in's job. Only a NEW alarm, set after they got up + # (the night over), followed once they lie back down, means going back to bed. + up = s.state == "done" or s.lie_in_over + if not up or alarm in s.alarms_seen or not self.last_present: + if not up and alarm not in s.alarms_seen: + s.alarms_seen = (s.alarms_seen + [alarm])[-12:] + if fa and fa <= now and alarm <= fa + self.SNOOZE_S and s.snoozed_until != alarm: + s.snoozed_until = alarm self._ev(now, "alarm_snoozed", until=alarm, alarm=fa) return False - self.s.alarms_seen = [] - if self.s.wake_source == "calendar" and self.s.wake_override is not None and alarm > self.s.wake_override: - self.s.wake_from_alarm = alarm # an early start in the calendar already woke them earlier + s.alarms_seen = [] + elif s.wake_source == "calendar" and s.wake_override is not None and alarm > s.wake_override: + s.wake_from_alarm = alarm # an early start in the calendar already wakes them earlier return False - self.s.wake_override, self.s.wake_from_alarm, self.s.wake_source = alarm, alarm, None + s.wake_override, s.wake_from_alarm, s.wake_source = alarm, alarm, None self._ev(now, "wake_from_alarm", wake=alarm, planned=planned) return True @@ -289,33 +311,36 @@ def follow_alarm(self, now: float, alarm: float | None, reported: bool = False) def follow_calendar(self, now: float, early_start: float | None) -> bool: """Move tonight's wake earlier for an early first event tomorrow morning (the phone's or an HA calendar), - Settings: "Wake for early events". Only ever earlier than the wake it would otherwise have (an earlier alarm - wins), at most ALARM_EARLIER_S before the planned wake, and never once that wake has come. A wake set by hand - wins. When the event goes away before the wake, the wake goes back (to the alarm's, if one is followed).""" - if not getattr(self.person.settings, "wake_with_calendar", True) or self.s.wake_by_hand: - return False + Settings: "Wake earlier for early events". Only ever earlier than the wake it would otherwise have (an earlier + alarm wins), at most ALARM_EARLIER_S before the planned wake, and never once the morning has begun. A wake set + by hand wins. When the event goes away (or the setting is switched off) before the wake, the wake goes back to + the alarm's, if one is followed, or the planned one.""" s = self.s + if s.wake_by_hand or s.ended or s.lie_in or s.lie_in_over or s.state == "done": + return False + day = self._wake_day(now) + if day is None: + return False + planned = day[1] + if (s.wake_override if s.wake_override is not None else planned) <= now: + return False # the morning has begun: the wake stays where it came cur = s.wake_override if s.wake_source == "calendar" else None # the wake without the calendar: the followed alarm's, or the planned one - fa = s.wake_from_alarm if s.wake_from_alarm and (cur is not None or s.wake_override == s.wake_from_alarm) else None - from datetime import datetime - d = night_date(datetime.fromtimestamp(now, self.tz)) - rhythm = pick_rhythm(self.person.rhythms, d) - if rhythm is None: - return False - planned = resolve(rhythm, d, self.tz).wake + fa = s.wake_from_alarm if (s.wake_from_alarm and s.wake_from_alarm > now + and (cur is not None or s.wake_override == s.wake_from_alarm)) else None base = fa or planned - want = early_start - self.CALENDAR_LEAD_S if early_start else None + on = getattr(self.person.settings, "wake_with_calendar", True) + want = early_start - self.CALENDAR_LEAD_S if (early_start and on) else None if want is not None and now < want and planned - self.ALARM_EARLIER_S <= want < base - 60: if cur is not None and abs(cur - want) < 60: return False - if cur is None and s.wake_override is not None and s.wake_override <= now: - return False # the morning already began on another wake s.wake_override, s.wake_source = want, "calendar" self._ev(now, "wake_from_calendar", wake=want, event=early_start, planned=planned) return True - if cur is not None and now < cur: # the event went away or moved later before the wake came + if cur is not None: # the event went away or moved later, or the setting was turned off s.wake_override, s.wake_source = fa, None + if fa is None: + s.wake_from_alarm = None self._ev(now, "wake_calendar_cleared", was=cur) return True return False @@ -396,6 +421,7 @@ def _track_personal(self, now: float, present: bool | None) -> None: def tick(self, now: float, present: bool | None, home: bool | None = None, active: float | None = None) -> float | None: """`active` = since when the people in bed have been awake and moving (engine/active.py), else None.""" + self.last_present = present # follow_alarm reads it on the next tick (back in bed after getting up?) from datetime import date, datetime dt = datetime.fromtimestamp(now, self.tz) d = night_date(dt) diff --git a/core/tests/test_wake_morning.py b/core/tests/test_wake_morning.py index 4acdcd8..4072e64 100644 --- a/core/tests/test_wake_morning.py +++ b/core/tests/test_wake_morning.py @@ -114,3 +114,54 @@ async def test_calendar_setting_off(tmp_path): PC.update(n.store, n.p1.id, {"early_start": planned - 2 * 3600}, n.clock.now_ts()) await n.step(2) assert e.s.wake_override is None + + +async def test_next_event_after_the_calendar_wake_came_moves_nothing(tmp_path): + """Review: the first event starts, the calendar's 'first event' becomes the second one: no later wake, no reopen.""" + n, e, planned = await _night(tmp_path) + ev1 = planned - 2 * 3600 + PC.update(n.store, n.p1.id, {"early_start": ev1}, n.clock.now_ts()) + await n.step(2) + w = ev1 - 45 * 60 + assert e.s.wake_override == w + await n.until(_at(n, w + 10 * 60)) + PC.update(n.store, n.p1.id, {"early_start": ev1 + 3600}, n.clock.now_ts()) + await n.step(4) + assert e.s.wake_override == w + + +async def test_a_deleted_alarm_does_not_come_back_with_the_calendar(tmp_path): + n, e, planned = await _night(tmp_path) + alarm, event = planned - 3600, planned - 75 * 60 # calendar wake 2 h before planned + PC.update(n.store, n.p1.id, {"next_alarm": alarm, "early_start": event}, n.clock.now_ts()) + await n.step(4) + assert e.s.wake_override == event - 45 * 60 + PC.update(n.store, n.p1.id, {"next_alarm": None}, n.clock.now_ts()) # alarm deleted + await n.step(2) + assert e.s.wake_from_alarm is None and e.s.wake_override == event - 45 * 60 + PC.update(n.store, n.p1.id, {"early_start": None}, n.clock.now_ts()) # and the event cancelled + await n.step(2) + assert e.s.wake_override is None and abs(e.night.wake - planned) < 1 + + +async def test_backup_alarm_first_seen_after_getting_up_is_not_followed_out_of_bed(tmp_path): + n, e, planned = await _night(tmp_path) + alarm = planned - 3 * 3600 + PC.update(n.store, n.p1.id, {"next_alarm": alarm}, n.clock.now_ts()) + await n.until(_at(n, alarm + 20 * 60)) + n.present("left", False) + await n.step(16) + assert e.s.state == "done" + PC.update(n.store, n.p1.id, {"next_alarm": alarm + 150 * 60}, n.clock.now_ts()) # appears only now + await n.step(4) + assert e.s.state == "done" and e.s.wake_override == alarm and not n.side("left").on + + +async def test_calendar_setting_switched_off_gives_the_wake_back(tmp_path): + n, e, planned = await _night(tmp_path) + PC.update(n.store, n.p1.id, {"early_start": planned - 2 * 3600}, n.clock.now_ts()) + await n.step(2) + assert e.s.wake_source == "calendar" + n.p1.settings.wake_with_calendar = False + await n.step(2) + assert e.s.wake_override is None and abs(e.night.wake - planned) < 1