diff --git a/README.md b/README.md index 28f09d2..4055fb5 100644 --- a/README.md +++ b/README.md @@ -133,7 +133,7 @@ cached session, so it also overrides a stale cached timezone. | Tool | Description | |------|-------------| | `get_diary_groups` | The account's diary groups (meal slots) and their names, for interpreting the group in each entry's `order` | -| `add_food_entry` | Log a food serving to the diary | +| `add_food_entry` | Log a food serving to the diary, optionally at a given time of day | | `remove_food_entry` | Remove one or more diary entries: foods, exercises, notes or biometrics | | `add_custom_food` | Create a custom food with specified nutrition and optional barcodes | | `update_custom_food` | Edit a custom food in place: name, nutrition, serving size, or barcodes | @@ -144,7 +144,7 @@ cached session, so it also overrides a stale cached timezone. | `import_recipe` | Create a recipe from a free-text ingredient list; Cronometer matches each line to a database food and converts the amount to grams | | `copy_day` | Copy all entries from the previous day | | `mark_day_complete` | Mark a diary day as complete or incomplete | -| `add_note` | Add a note to a diary day | +| `add_note` | Add a note to a diary day, optionally at a given time of day | | `update_note` | Replace the text of a diary note | ### Targets & Tracking diff --git a/src/cronometer_api_mcp/client.py b/src/cronometer_api_mcp/client.py index f4ae8d5..897539d 100644 --- a/src/cronometer_api_mcp/client.py +++ b/src/cronometer_api_mcp/client.py @@ -21,7 +21,8 @@ import struct import threading import time -from datetime import date, datetime +from datetime import date, datetime, timedelta +from datetime import time as dtime from pathlib import Path from zoneinfo import ZoneInfo, ZoneInfoNotFoundError @@ -1609,6 +1610,7 @@ def add_serving( translation_id: int = 0, day: date | None = None, diary_group: int = 0, + at: dtime | None = None, ) -> dict: """Log a food serving to the diary. @@ -1627,15 +1629,17 @@ def add_serving( with the default groups. Otherwise the number from get_diary_groups; resolve_diary_group maps a name to it. + at: Time of day to stamp the entry with, in the account timezone. + Defaults to now. Also drives the auto meal group. Returns the serving confirmation dict from the API. """ - now = self.now() + when = at or self.now().time() day_str = self._format_day(day) - time_str = f"{now.hour}:{now.minute}:{now.second}" + time_str = f"{when.hour}:{when.minute}:{when.second}" if diary_group == 0: - diary_group = _meal_group_for_hour(now.hour) + diary_group = _meal_group_for_hour(when.hour) serving = { "order": (diary_group << 16) | 1, @@ -1672,7 +1676,11 @@ def add_serving( # ------------------------------------------------------------------ def add_note( - self, text: str, day: date | None = None, diary_group: int = 0 + self, + text: str, + day: date | None = None, + diary_group: int = 0, + at: dtime | None = None, ) -> dict: """Add a note to a diary day. @@ -1681,12 +1689,30 @@ def add_note( day: Date to add it to. Defaults to today. diary_group: Meal group number the note sits in, as for add_serving (0 = auto, by time of day). + at: Time of day to stamp the note with, in the account timezone. + Defaults to now. Also drives the auto meal group. - Returns the stored note: {"noteId", "text", "day", "order", ...}. + Returns the stored note: {"noteId", "text", "day", "time", "order", ...}. """ + now = self.now() + when = at or now.time() if diary_group == 0: - diary_group = _meal_group_for_hour(self.now().hour) - return self._save_note(0, text, self._format_day(day), (diary_group << 16) | 1) + diary_group = _meal_group_for_hour(when.hour) + # The UTC offset in force on the note's own date and time, in the + # account's zone (not now's offset: they differ across a DST change). + stamped = datetime.combine(day or now.date(), when, tzinfo=self._tzinfo()) + offset = int((stamped.utcoffset() or timedelta(0)).total_seconds() // 60) + extra = { + "time": f"{when.hour:02d}:{when.minute:02d}:{when.second:02d}", + "offset": str(offset), + } + return self._save_note( + 0, + text, + self._format_day(day), + (diary_group << 16) | 1, + extra=extra, + ) def update_note(self, note_id: int, text: str, day: date | None = None) -> dict: """Replace the text of an existing diary note, keeping its place. @@ -1706,7 +1732,11 @@ def update_note(self, note_id: int, text: str, day: date | None = None) -> dict: raise CronometerError( f"No note {note_id} in the diary for {self._format_day(day)}" ) - return self._save_note(note["noteId"], text, note["day"], note["order"]) + # Send the stored time and offset back so an edit doesn't drop them. + extra = {k: str(note[k]) for k in ("time", "offset") if note.get(k) is not None} + return self._save_note( + note["noteId"], text, note["day"], note["order"], extra=extra + ) def _save_note( self, @@ -1715,6 +1745,7 @@ def _save_note( day_str: str, order: int, *, + extra: dict[str, str] | None = None, _retried: bool = False, ) -> dict: """Create (note_id 0) or overwrite a note via /photoupload. @@ -1735,6 +1766,7 @@ def _save_note( "order": str(order), "deleteExistingPhoto": "true" if note_id == 0 else "false", "noteText": text, + **(extra or {}), } form = httpx.Request( "POST", "/", files={k: (None, v) for k, v in fields.items()} @@ -1746,7 +1778,9 @@ def _save_note( ) if resp.status_code in (401, 403) and not _retried: self._reauthenticate(sent_token) - return self._save_note(note_id, text, day_str, order, _retried=True) + return self._save_note( + note_id, text, day_str, order, extra=extra, _retried=True + ) resp.raise_for_status() try: @@ -1756,7 +1790,9 @@ def _save_note( if isinstance(data, dict) and data.get("result") in ("FAIL", "FAILURE"): if not _retried: self._reauthenticate(sent_token) - return self._save_note(note_id, text, day_str, order, _retried=True) + return self._save_note( + note_id, text, day_str, order, extra=extra, _retried=True + ) raise CronometerError(f"Failed to save note: {data}") if not isinstance(data, dict) or "noteId" not in data: raise CronometerError(f"Failed to save note: {data}") diff --git a/src/cronometer_api_mcp/server.py b/src/cronometer_api_mcp/server.py index ba918ce..81b5932 100644 --- a/src/cronometer_api_mcp/server.py +++ b/src/cronometer_api_mcp/server.py @@ -4,7 +4,7 @@ import logging import re import threading -from datetime import date, timedelta +from datetime import date, time, timedelta from importlib.metadata import PackageNotFoundError from importlib.metadata import version as _pkg_version from typing import Annotated @@ -98,6 +98,21 @@ def _parse_date(d: str | None) -> date | None: return date.fromisoformat(d) +def _parse_time(t: str | None) -> time | None: + """Parse an optional 24h time-of-day, "HH:MM" or "HH:MM:SS".""" + if t is None: + return None + try: + value = t.strip() + if not re.fullmatch(r"[0-9]{2}:[0-9]{2}(?::[0-9]{2})?", value): + raise ValueError + return time.fromisoformat(value) + except ValueError: + raise ValueError( + f"Invalid time '{t}'. Use 24-hour HH:MM or HH:MM:SS, e.g. '08:30'." + ) from None + + def _resolve_read_days(d: str | None, days: int = 1) -> list[date]: if type(days) is not int or not 1 <= days <= 31: raise ValueError("days must be an integer between 1 and 31.") @@ -305,6 +320,7 @@ def add_food_entry( date: str | None = None, translation_id: int = 0, diary_group: str = "auto", + time: str | None = None, ) -> str: """Add a food entry to the Cronometer diary. @@ -321,11 +337,15 @@ def add_food_entry( name of one of the account's diary groups, matched case-insensitively. Group names are customizable; call get_diary_groups to see them. + time: Time of day to log at, 24-hour HH:MM or HH:MM:SS in the account + timezone (defaults to now). With diary_group "auto", this also + picks the meal slot, so logging lunch late still lands in lunch. """ try: client = _get_client() group = client.resolve_diary_group(diary_group) day = _parse_date(date) + at = _parse_time(time) result = client.add_serving( food_id=food_id, measure_id=measure_id, @@ -333,6 +353,7 @@ def add_food_entry( translation_id=translation_id, day=day, diary_group=group["group"], + at=at, ) return _ok( { @@ -381,7 +402,12 @@ def remove_food_entry( @mcp.tool(annotations=_WRITE) -def add_note(text: str, date: str | None = None, diary_group: str = "auto") -> str: +def add_note( + text: str, + date: str | None = None, + diary_group: str = "auto", + time: str | None = None, +) -> str: """Add a note to a diary day. Notes show up in get_food_log's diary as entries of type "Note". Remove @@ -393,11 +419,16 @@ def add_note(text: str, date: str | None = None, diary_group: str = "auto") -> s diary_group: Meal slot the note sits in: "auto" (default, picks by time of day) or the name of one of the account's diary groups, matched case-insensitively (see get_diary_groups). + time: Time of day for the note, 24-hour HH:MM or HH:MM:SS in the + account timezone (defaults to now). With diary_group "auto", this + also picks the meal slot. """ try: client = _get_client() group = client.resolve_diary_group(diary_group) - note = client.add_note(text, _parse_date(date), group["group"]) + note = client.add_note( + text, _parse_date(date), group["group"], at=_parse_time(time) + ) return _ok({"note": note, **_group_echo(group)}) except Exception as e: return _err(e) diff --git a/tests/test_diary_groups.py b/tests/test_diary_groups.py index 6e0150a..a83c5c8 100644 --- a/tests/test_diary_groups.py +++ b/tests/test_diary_groups.py @@ -395,7 +395,7 @@ def __init__(self): def resolve_diary_group(self, name): return {"group": 4, "name": "Dinner"} - def add_note(self, text, day, group): + def add_note(self, text, day, group, at=None): self.calls.append(("note", group)) return {"noteId": 1} diff --git a/tests/test_entry_time.py b/tests/test_entry_time.py new file mode 100644 index 0000000..bec02e1 --- /dev/null +++ b/tests/test_entry_time.py @@ -0,0 +1,79 @@ +"""The optional `time` argument of add_food_entry and add_note.""" + +import datetime as _dt +import json +from unittest.mock import Mock + +import pytest + +from cronometer_api_mcp import server +from cronometer_api_mcp.client import CronometerClient + + +@pytest.fixture +def client(monkeypatch): + c = Mock(spec=CronometerClient) + c.resolve_diary_group.return_value = {"group": 0, "name": "auto"} + c.add_serving.return_value = {"id": 1} + c.add_note.return_value = {"noteId": 2} + monkeypatch.setattr(server, "_client", c) + return c + + +@pytest.mark.parametrize( + ("text", "expected"), + [ + ("00:00", _dt.time(0, 0)), + ("08:30", _dt.time(8, 30)), + (" 21:05:09 ", _dt.time(21, 5, 9)), + ("23:59:59", _dt.time(23, 59, 59)), + ], +) +def test_add_food_entry_passes_time_to_the_client(client, text, expected): + out = json.loads(server.add_food_entry(1, 2, 100.0, time=text)) + assert out["status"] == "success" + assert client.add_serving.call_args.kwargs["at"] == expected + + +def test_add_note_passes_time_to_the_client(client): + out = json.loads(server.add_note("hi", time="12:30")) + assert out["status"] == "success" + assert client.add_note.call_args.kwargs["at"] == _dt.time(12, 30) + + +def test_time_defaults_to_now(client): + server.add_food_entry(1, 2, 100.0) + server.add_note("hi") + assert client.add_serving.call_args.kwargs["at"] is None + assert client.add_note.call_args.kwargs["at"] is None + + +@pytest.mark.parametrize( + "bad", + [ + "", + "25:00", + "08:60", + "08:30:60", + "noon", + "8", + "08", + "0830", + "T08:30", + "08:30Z", + "08:30+02:00", + "08:30-08:00", + "08:30:00+02:00", + "08:30:00.123", + ], +) +def test_invalid_time_is_an_error_and_writes_nothing(client, bad): + for out in ( + server.add_food_entry(1, 2, 100.0, time=bad), + server.add_note("hi", time=bad), + ): + data = json.loads(out) + assert data["status"] == "error" + assert "Invalid time" in data["message"] + client.add_serving.assert_not_called() + client.add_note.assert_not_called() diff --git a/tests/test_notes.py b/tests/test_notes.py index 1747227..9449c75 100644 --- a/tests/test_notes.py +++ b/tests/test_notes.py @@ -6,7 +6,9 @@ from __future__ import annotations -from datetime import date +from datetime import date, datetime +from datetime import time as dtime +from zoneinfo import ZoneInfo import httpx import pytest @@ -61,7 +63,7 @@ def test_add_note_posts_multipart_form_with_session_key(tmp_path): client, _ = make_cold_client(tmp_path, [{}]) forms = capture_forms(client) - note = client.add_note("ate late", DAY, diary_group=3) + note = client.add_note("ate late", DAY, diary_group=3, at=dtime(13, 45)) assert forms == [ { @@ -72,11 +74,75 @@ def test_add_note_posts_multipart_form_with_session_key(tmp_path): "order": str((3 << 16) | 1), "deleteExistingPhoto": "true", "noteText": "ate late", + "time": "13:45:00", + "offset": "0", } ] assert note["noteId"] == NOTE_ID +def test_add_note_defaults_time_to_now_and_uses_account_zone(tmp_path): + client, _ = make_cold_client(tmp_path, [{}]) + forms = capture_forms(client) + zone = ZoneInfo("America/Los_Angeles") + client.now = lambda: datetime(2026, 1, 2, 12, 20, 5, tzinfo=zone) # type: ignore[method-assign] + client._tzinfo = lambda: zone # type: ignore[method-assign] + + client.add_note("now", DAY) + + assert forms[0]["time"] == "12:20:05" + assert forms[0]["offset"] == "-480" + + +@pytest.mark.parametrize( + ("day", "offset"), + [(date(2026, 1, 15), "-480"), (date(2026, 7, 15), "-420")], +) +def test_add_note_offset_is_for_the_notes_own_date(tmp_path, day, offset): + """A note backfilled across a DST change gets that day's offset, not now's.""" + client, _ = make_cold_client(tmp_path, [{}]) + forms = capture_forms(client) + zone = ZoneInfo("America/Los_Angeles") + client.now = lambda: datetime(2026, 1, 2, 9, 0, 0, tzinfo=zone) # type: ignore[method-assign] + client._tzinfo = lambda: zone # type: ignore[method-assign] + + client.add_note("backfill", day, at=dtime(12, 0)) + + assert forms[0]["offset"] == offset + + +def test_add_note_at_drives_the_auto_group(tmp_path): + client, _ = make_cold_client(tmp_path, [{}]) + forms = capture_forms(client) + client.now = lambda: datetime(2026, 1, 2, 23, 0, 0) # type: ignore[method-assign] + + client.add_note("lunchish", DAY, at=dtime(12, 30)) + + assert forms[0]["time"] == "12:30:00" + # 12:30 is Lunch, group 2 (see _meal_group_for_hour), not the 23:00 group. + assert forms[0]["order"] == str((2 << 16) | 1) + + +def test_update_note_keeps_time_and_offset(tmp_path): + stored = { + "type": "Note", + "noteId": NOTE_ID, + "text": "old", + "day": "1900-01-02", + "order": (2 << 16) | 1, + "time": "13:45:00", + "offset": -480, + "meta": {}, + } + client, _ = make_cold_client(tmp_path, [{"diary": [stored]}]) + forms = capture_forms(client) + + client.update_note(NOTE_ID, "new", DAY) + + assert forms[0]["time"] == "13:45:00" + assert forms[0]["offset"] == "-480" + + def test_update_note_keeps_day_order_and_photo(tmp_path): stored = { "type": "Note", diff --git a/tests/test_timezone.py b/tests/test_timezone.py index 50ce3cc..8e4aa4d 100644 --- a/tests/test_timezone.py +++ b/tests/test_timezone.py @@ -121,6 +121,21 @@ def test_explicit_diary_group_skips_auto(tmp_path, frozen_utc): assert captured["payload"]["serving"]["order"] == (3 << 16) | 1 +def test_at_overrides_the_stamped_time_and_drives_auto_group(tmp_path, frozen_utc): + """Backfilling lunch at 22:15 (frozen clock: 11:01 local): the entry carries + the requested time and auto-groups by it, on the same local day.""" + client = _client(tmp_path, "America/Los_Angeles") + captured = _capture_serving(client) + + client.add_serving(food_id=1, measure_id=0, grams=100.0, at=_dt.time(7, 5, 9)) + + serving = captured["payload"]["serving"] + assert serving["time"] == "7:5:9" + assert serving["day"] == "2026-7-27" + # 07:05 -> Breakfast (group 1), not the frozen clock's Lunch. + assert serving["order"] == (1 << 16) | 1 + + def test_login_captures_account_timezone(tmp_path, monkeypatch): """login() stores the timezone from the response and persists it.""" monkeypatch.setenv("CRONOMETER_USERNAME", "u@example.com")