Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
5 changes: 3 additions & 2 deletions core/embertide/engine/away.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ def night_verdict(c, p, d) -> tuple[str | None, str]:
x = max(rings, key=lambda x: x["end"] - x["start"])
# only minutes the bed knew about count: no rows (bed or server down) or presence unknown isn't "empty"
rows = [r for r in c.store.history(p.zone, x["start"], x["end"], step_s=60, person=p.id) if r.get("occupied") is not None]
if len(rows) * 60 < KNOWN_COVER * (x["end"] - x["start"]):
if not rows or len(rows) * 60 < KNOWN_COVER * (x["end"] - x["start"]):
return None, "the bed didn't report for much of the night"
occ = sum(1 for r in rows if r.get("occupied") == 1) / len(rows)
if occ < 0.2:
Expand Down Expand Up @@ -273,7 +273,8 @@ def morning_check(c, p, now: float) -> dict | None:
if key in cs:
return None
rec = c.store.get(_key(p.id))
away_then = isinstance(rec, dict) and bool(rec.get("since")) and rec["since"] <= _night_span(d, c.clock.tz)[1]
span = _night_span(d, c.clock.tz)
away_then = (isinstance(rec, dict) and bool(rec.get("since")) and rec["since"] <= span[1]) or away_share(away_periods(c.store, p.id, now), *span) >= 0.5 # away then, even if back since
verdict, why = night_verdict(c, p, d)
if verdict is None:
return None # can't be sure (yet): ask nothing, try again later
Expand Down
18 changes: 15 additions & 3 deletions core/embertide/engine/night.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,9 +138,11 @@ def adjust(self, now: float, *, delta_c: float | None = None, temp_c: float | No
source: str = "app", minutes: int | None = None) -> None:
step, set_to = delta_c, temp_c
self.s.empty_off, self.s.empty_on_since = False, None
resumed = False
if self.s.skip or (self.s.pause_until and now < self.s.pause_until):
# pressing + or − while paused / off for the night means "I want my side back": resume, then apply the step
self.s.skip, self.s.pause_until = False, None
resumed = True
self._ev(now, "tonight_resume", source=source, reason="adjusted while off")
cur = self.s.override
if delta_c is not None and cur and cur.delta_c is not None and cur.until == until:
Expand All @@ -150,7 +152,8 @@ def adjust(self, now: float, *, delta_c: float | None = None, temp_c: float | No
merged = cur is not None and step is not None and cur.until == until and cur.phase_id == self.s.phase_id
# turned on by hand while the rhythm has the side off (a nap, an early night): it runs until the timer, or
# until the rhythm itself starts, and never carries on into the night
idle = self.s.base_c is None and self.s.state not in ("skipped", "paused") # off because of the rhythm, not the person
# off because of the rhythm, not the person (a side that was off or paused a moment ago was just resumed above)
idle = self.s.base_c is None and (resumed or self.s.state not in ("skipped", "paused"))
manual = (cur.manual if merged else False) or (idle and temp_c is not None)
end_ts = now + minutes * 60 if minutes else (cur.end_ts if merged else None)
self.s.override = Override(cur.set_ts if merged else now, until, self.s.phase_id, temp_c=temp_c, delta_c=delta_c,
Expand Down Expand Up @@ -187,19 +190,23 @@ def tonight(self, now: float, action: str, minutes: int | None = None, source: s
if self.s.lie_in or (self.running() and self.night is not None and self.s.phase_id == "wake"):
self.end_night(now, source, "off pressed") # in the morning "off" means "I'm up", not "skip tonight"
action = "end"
elif self.night is not None and now >= self.night.end:
elif self.s.ended or (self.night is not None and now >= self.night.end):
self.s.skip_next = True # this morning's night is over; "tonight" means the next one
else:
self.s.skip = True
self._end_flash(now, source) # "off" means off, even mid-flash
elif action == "resume":
self.s.skip, self.s.skip_next, self.s.pause_until = False, False, None
self.s.empty_off, self.s.empty_on_since = False, None
if self.s.started and self.s.state == "out_of_bed":
# off after the out-of-bed hold (or the bed lost whoever was there): carry on with the night now. If the
# side stays empty, the hold runs again and turns it off once more
self.s.absent_since = now
elif action == "start_now":
self.s.skip, self.s.started, self.s.in_bed = False, True, now
self.s.pause_until, self.s.ended, self.s.lie_in_over = None, False, False
self.s.absent_since = self.s.out_since = None
self.s.empty_off, self.s.empty_on_since = False, None
self._began(now, "hand")
elif action in ("pause", "delay"):
self.s.pause_until = now + (minutes or 60) * 60
Expand Down Expand Up @@ -440,7 +447,9 @@ def tick(self, now: float, present: bool | None, home: bool | None = None, activ
s_ended = self.s.ended
base: float | None
phase = None
if self.s.skip:
if self.s.skip and self.s.started and now >= n.end and not self.s.lie_in:
state, base = "done", None # switched off during the night: it still ends at its end
elif self.s.skip:
state, base = "skipped", None
elif self.s.pause_until and now < self.s.pause_until:
state, base = "paused", None
Expand Down Expand Up @@ -473,6 +482,8 @@ def tick(self, now: float, present: bool | None, home: bool | None = None, activ
state, base = "waiting", n.phases[0].temp_c if n.phases else None
phase = n.phases[0].id if n.phases else None

if state == "waiting" and self.s.state != "waiting":
self.s.empty_off, self.s.empty_on_since = False, None # a cutoff from the afternoon doesn't stop pre-conditioning
if state == "done" and self.s.state != "done" and self.s.started:
# when the night really ended (the alarm can move it before the schedule's end): the summary counts
# getting up only until here
Expand Down Expand Up @@ -649,6 +660,7 @@ def _sleep_tick(self, now: float, rhythm, d, n: ResolvedNight, present: bool | N
def _began(self, now: float, by: str) -> None:
"""The night has just started (any way): note how, and whether it started again after being given up."""
self.s.started_by = by
self.s.empty_off, self.s.empty_on_since = False, None
r = self.s.reanchor
if r:
self.s.reanchor = None
Expand Down
86 changes: 86 additions & 0 deletions core/tests/test_engine_fixes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
"""Night engine fixes from the 2026-11 bug pass: Start now really starts, "off" after "I'm up" is for tonight, a night
switched off still finishes, the empty-side cutoff doesn't outlive its afternoon, and a by-hand temperature right after
"Off tonight" turns the side on."""
from datetime import datetime

from test_scenarios import TZ, Night


def iso(t):
return datetime.fromtimestamp(t, TZ).replace(tzinfo=None).isoformat()


async def test_start_now_after_a_pause_starts(tmp_path):
n = Night(tmp_path, "2026-11-05T21:00")
await n.step(2)
e = n.e(n.p1)
now = n.clock.now_ts()
e.tonight(now, "pause", minutes=60)
await n.step(2)
assert e.s.state == "paused"
e.tonight(n.clock.now_ts(), "start_now")
await n.step(2)
assert e.s.state in ("rhythm", "out_of_bed_hold") and n.side("left").on


async def test_start_now_after_out_of_bed_starts(tmp_path):
n = Night(tmp_path, "2026-11-05T22:20")
n.present("left", True)
await n.until("2026-11-06T00:30")
n.present("left", False)
await n.until("2026-11-06T02:00")
e = n.e(n.p1)
assert e.s.state == "out_of_bed" and not n.side("left").on
e.tonight(n.clock.now_ts(), "start_now")
await n.step(2)
assert e.s.state != "out_of_bed" and n.side("left").on


async def test_off_after_im_up_skips_tonight_not_the_ended_night(tmp_path):
n = Night(tmp_path, "2026-11-05T22:20")
n.present("left", True)
await n.until("2026-11-06T05:00")
e = n.e(n.p1)
assert n.clock.now_ts() < e.night.end
e.tonight(n.clock.now_ts(), "end") # "I'm up" an hour or two early
await n.step(2)
e.tonight(n.clock.now_ts(), "skip") # then "Off tonight": meant for the coming night
await n.step(2)
assert e.s.skip_next is True and e.s.skip is False and e.s.state == "done"


async def test_a_night_switched_off_still_finishes_at_its_end(tmp_path):
n = Night(tmp_path, "2026-11-05T22:20")
n.present("left", True)
await n.until("2026-11-06T02:00")
e = n.e(n.p1)
e.tonight(n.clock.now_ts(), "skip") # off at 2 AM, still in bed
await n.step(2)
assert e.s.state == "skipped" and not n.side("left").on
n.present("left", False)
await n.until(iso(e.night.end + 300))
assert e.s.state == "done" and len(n.events("night_done")) == 1 and not n.side("left").on


async def test_empty_side_cutoff_from_the_afternoon_doesnt_stop_preconditioning(tmp_path):
n = Night(tmp_path, "2026-11-05T13:00")
await n.step(2)
e = n.e(n.p1)
n.present("left", False)
e.adjust(n.clock.now_ts(), temp_c=24.0) # turned on by hand in the afternoon, then nobody came
await n.until("2026-11-05T17:30")
assert e.s.empty_off and not n.side("left").on
await n.until(iso(e.night.precool + 600))
assert e.s.state == "waiting" and not e.s.empty_off and n.side("left").on


async def test_temperature_right_after_off_tonight_turns_the_side_on(tmp_path):
n = Night(tmp_path, "2026-11-05T15:00")
await n.step(2)
e = n.e(n.p1)
e.tonight(n.clock.now_ts(), "skip")
await n.step(2)
assert e.s.state == "skipped"
e.adjust(n.clock.now_ts(), temp_c=22.0)
await n.step(2)
assert e.s.override is not None and e.s.override.manual and n.side("left").on
3 changes: 2 additions & 1 deletion core/tests/test_lie_in.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,8 @@ async def test_skipped_night_has_no_lie_in(tmp_path):
n, e, end, _ = await _to_end(tmp_path)
e.s.skip = True
await n.until(iso(end + 600))
assert e.s.state == "skipped" and not n.events("lie_in_started")
# switched off: no lie-in, and the night still finishes at its end (night_done, morning summary)
assert e.s.state == "done" and not n.events("lie_in_started")


async def test_noon_rollover_waits_for_lie_in_to_finish(tmp_path):
Expand Down