diff --git a/README.md b/README.md index c6c7de9..fabfdfe 100644 --- a/README.md +++ b/README.md @@ -134,6 +134,7 @@ cached session, so it also overrides a stale cached timezone. |------|-------------| | `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, optionally at a given time of day | +| `update_food_entry` | Change a logged entry's amount or measure, or move it to another diary group | | `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 | diff --git a/src/cronometer_api_mcp/client.py b/src/cronometer_api_mcp/client.py index 08781b1..9d3bf7a 100644 --- a/src/cronometer_api_mcp/client.py +++ b/src/cronometer_api_mcp/client.py @@ -197,7 +197,8 @@ class CronometerClient: dispatches on worker threads. Auth state transitions are serialized (see `_auth_lock`), edits to a given custom food are serialized per food id (see `_food_lock`), and macro split reads/writes share `_macro_split_lock`. - Macro target updates share `_macro_targets_lock`. + Macro target updates share `_macro_targets_lock`, and diary serving edits + are serialized per serving id (see `_serving_lock`). """ def __init__(self, *, session_path: Path | None = None) -> None: @@ -216,6 +217,8 @@ def __init__(self, *, session_path: Path | None = None) -> None: # entire object. `_food_locks_guard` protects the lock registry. self._food_locks: dict[int, threading.Lock] = {} self._food_locks_guard = threading.Lock() + self._serving_locks: dict[str, threading.Lock] = {} + self._serving_locks_guard = threading.Lock() self._macro_targets_lock = threading.Lock() self._macro_split_lock = threading.Lock() @@ -1670,6 +1673,95 @@ def add_serving( ) return data + def _serving_lock(self, serving_id: str | int) -> threading.Lock: + """Serialize the fetch-modify-save cycle for one diary serving.""" + key = str(serving_id) + with self._serving_locks_guard: + lock = self._serving_locks.get(key) + if lock is None: + lock = self._serving_locks[key] = threading.Lock() + return lock + + def update_serving( + self, + serving_id: str | int, + day: date | None = None, + *, + grams: float | None = None, + measure_id: int | None = None, + diary_group: int | None = None, + ) -> dict: + """Change the amount, measure or meal group of a logged serving. + + Fetches the day's diary, takes the serving as stored and sends it back + to /api/v2/edit_serving with the changed fields. The server keeps the + serving id. The meal group lives in the high bits of `order` (see + add_serving); a moved serving goes to the end of its new group. The + app moves entries with /api/v2/update_order, but edit_serving accepts + a new `order` as well (verified against the live API), so one call + covers both. + + Args: + serving_id: The servingId from get_diary. + day: The day the serving is logged on. Defaults to today. + grams: New weight in grams. Requires a weight-based food or recipe; + serving-based recipes store reference-serving counts instead. + measure_id: New display measure (grams stays the amount). + diary_group: New meal group number, as resolve_diary_group + returns it for one of the account's enabled groups. + + Returns the updated serving as sent. + """ + if grams is None and measure_id is None and diary_group is None: + raise ValueError("update_serving needs grams, measure_id or diary_group") + if grams is not None and grams <= 0: + raise ValueError(f"grams must be positive, got {grams}") + # Group numbers come from the account's layout (resolve_diary_group); + # they occupy the high 16 bits of `order`. + if diary_group is not None and not 0 <= diary_group <= 0xFFFF: + raise ValueError(f"diary_group must be 0-65535, got {diary_group}") + + with self._serving_lock(serving_id): + entries = self.get_diary(day).get("diary", []) + serving = next( + (e for e in entries if str(e.get("servingId")) == str(serving_id)), + None, + ) + if serving is None: + raise CronometerError( + f"No serving {serving_id} in the diary for {self._format_day(day)}" + ) + + serving = dict(serving) + if grams is not None: + food = self.get_food(serving["foodId"]) + if any(m.get("type") == "Recipe" for m in food.get("measures") or []): + raise CronometerError( + f"Serving {serving_id} is a serving-based recipe; grams updates " + "require a weight-based food or recipe. Change this amount " + "in Cronometer instead." + ) + serving["grams"] = grams + if measure_id is not None: + serving["measureId"] = measure_id + if diary_group is not None and serving.get("order", 0) >> 16 != diary_group: + last = max( + ( + e.get("order", 0) & 0xFFFF + for e in entries + if e.get("order", 0) >> 16 == diary_group + ), + default=0, + ) + serving["order"] = (diary_group << 16) | (last + 1) + + payload = {"serving": serving, "config": {"call_version": 2}} + data = self._request("/api/v2/edit_serving", payload) + if str(data.get("id")) != str(serving["servingId"]): + raise CronometerError(f"Failed to update serving {serving_id}: {data}") + logger.info("Updated serving %s on %s", serving_id, serving.get("day")) + return serving + # ------------------------------------------------------------------ # Diary: notes # ------------------------------------------------------------------ diff --git a/src/cronometer_api_mcp/server.py b/src/cronometer_api_mcp/server.py index 07cb84f..06815b0 100644 --- a/src/cronometer_api_mcp/server.py +++ b/src/cronometer_api_mcp/server.py @@ -458,6 +458,51 @@ def add_food_entry( return _err(e) +@mcp.tool(annotations=_WRITE_IDEMPOTENT) +def update_food_entry( + entry_id: str, + date: str | None = None, + grams: float | None = None, + measure_id: int | None = None, + diary_group: str | None = None, +) -> str: + """Change a logged food entry: its amount, its measure, or its meal. + + Use get_food_log to find the entry ID. Pass only what should change. + + Args: + entry_id: Serving/entry ID from get_food_log. + date: Date the entry is logged on as YYYY-MM-DD (defaults to today). + grams: New weight of the serving in grams. Only supported for weight-based + foods and recipes; change serving-based recipe amounts in Cronometer. + measure_id: New measure/unit ID from get_food_details (the amount is + still given in grams). + diary_group: Move to another meal: the name of one of the account's + enabled diary groups (see get_diary_groups), matched ignoring case + and whitespace. "auto" is not accepted here. + """ + try: + client = _get_client() + group = None + if diary_group is not None: + group = client.resolve_diary_group(diary_group) + if group["group"] is None: + raise ValueError( + 'diary_group "auto" cannot move an entry; name the target ' + "group (see get_diary_groups)." + ) + entry = client.update_serving( + entry_id, + _parse_date(date), + grams=grams, + measure_id=measure_id, + diary_group=group["group"] if group else None, + ) + return _ok({"entry": entry, **(_group_echo(group) if group else {})}) + except Exception as e: + return _err(e) + + @mcp.tool(annotations=_DESTRUCTIVE) def remove_food_entry( entry_ids: list[str], diff --git a/tests/test_diary_edit.py b/tests/test_diary_edit.py new file mode 100644 index 0000000..d4c3822 --- /dev/null +++ b/tests/test_diary_edit.py @@ -0,0 +1,236 @@ +"""update_serving: change a logged serving's amount, measure or meal group. + +The serving is read back from get_diary and re-sent whole to +/api/v2/edit_serving. The meal group is the high 16 bits of `order`. +""" + +from __future__ import annotations + +import copy +import json +import threading +from concurrent.futures import ThreadPoolExecutor +from datetime import date + +import pytest +from test_client import SAMPLE_FOODS, make_cold_client +from test_custom_food_edit import stored_recipe + +from cronometer_api_mcp.client import CronometerError + +DAY = date(1900, 1, 2) +SERVING_ID = 5312202908 + + +def serving(**overrides) -> dict: + """A get_diary entry shaped like the real one.""" + entry = { + "servingId": SERVING_ID, + "type": "Serving", + "foodId": 5442, + "measureId": 14990, + "translationId": 0, + "grams": 100, + "day": "1900-01-02", + "time": "11:23:50", + "offset": 0, + "userId": 42, + "order": (1 << 16) | 1, # breakfast, first + } + entry.update(overrides) + return entry + + +def diary(*entries) -> dict: + return {"diary": list(entries), "summary": {}, "messages": []} + + +EDITED = {"messages": [], "id": SERVING_ID} +FOOD = { + "id": 5442, + "defaultMeasureId": 14990, + "measures": [{"id": 14990, "name": "g", "type": "Weight", "value": 1}], +} + + +def test_update_serving_changes_grams_and_keeps_the_rest(tmp_path): + client, state = make_cold_client(tmp_path, [diary(serving()), FOOD, EDITED]) + + result = client.update_serving(SERVING_ID, DAY, grams=150) + + assert state["payloads"][1]["id"] == FOOD["id"] + sent = state["payloads"][2] + assert sent["config"] == {"call_version": 2} + assert sent["serving"] == serving(grams=150) + assert result == serving(grams=150) + + +def test_update_serving_moves_to_end_of_new_group(tmp_path): + lunch = [ + serving(servingId=1, order=(2 << 16) | 1), + serving(servingId=2, order=(2 << 16) | 4), + ] + client, state = make_cold_client(tmp_path, [diary(serving(), *lunch), EDITED]) + + client.update_serving(str(SERVING_ID), DAY, diary_group=2) + + assert state["payloads"][1]["serving"]["order"] == (2 << 16) | 5 + + +def test_update_serving_same_group_keeps_position(tmp_path): + entry = serving(order=(1 << 16) | 3) + client, state = make_cold_client(tmp_path, [diary(entry), EDITED]) + + client.update_serving(SERVING_ID, DAY, diary_group=1, measure_id=7) + + sent = state["payloads"][1]["serving"] + assert sent["order"] == (1 << 16) | 3 + assert sent["measureId"] == 7 + + +def test_update_serving_unknown_id_raises_without_editing(tmp_path): + client, state = make_cold_client(tmp_path, [diary(serving()), EDITED]) + + with pytest.raises(CronometerError, match="No serving 999"): + client.update_serving(999, DAY, grams=10) + + assert len(state["payloads"]) == 1 + + +@pytest.mark.parametrize( + ("kwargs", "message"), + [ + ({}, "needs grams"), + ({"grams": 0}, "positive"), + ({"diary_group": -1}, "0-65535"), + ({"diary_group": 1 << 16}, "0-65535"), + ], +) +def test_update_serving_validates_before_any_request(tmp_path, kwargs, message): + client, state = make_cold_client(tmp_path, [diary(serving()), EDITED]) + + with pytest.raises(ValueError, match=message): + client.update_serving(SERVING_ID, DAY, **kwargs) + + assert state["payloads"] == [] + + +@pytest.mark.parametrize( + "kwargs", + [ + {"grams": 100}, + {"grams": 100, "measure_id": 31}, + {"grams": 100, "diary_group": 5}, + ], +) +def test_update_serving_rejects_recipe_weights_without_editing(tmp_path, kwargs): + entry = serving(foodId=300, measureId=30, grams=1.1) + recipe = SAMPLE_FOODS[2] + client, state = make_cold_client(tmp_path, [diary(entry), recipe, EDITED]) + + with pytest.raises(CronometerError, match="serving-based recipe"): + client.update_serving(SERVING_ID, DAY, **kwargs) + + assert len(state["payloads"]) == 2 + assert all("serving" not in p for p in state["payloads"]) + + +def test_update_food_entry_reports_unsupported_recipe_weight(tmp_path, monkeypatch): + from cronometer_api_mcp import server + + entry = serving(foodId=300, measureId=30, grams=1.1) + client, state = make_cold_client(tmp_path, [diary(entry), SAMPLE_FOODS[2]]) + monkeypatch.setattr(server, "_client", client) + + result = json.loads( + server.update_food_entry(str(SERVING_ID), DAY.isoformat(), grams=100) + ) + + assert result["status"] == "error" + assert "serving-based recipe" in result["message"] + assert "in Cronometer instead" in result["message"] + assert len(state["payloads"]) == 2 + + +def test_update_serving_changes_weight_based_recipe_amount(tmp_path): + recipe = stored_recipe() + entry = serving(foodId=recipe["id"], measureId=1) + client, state = make_cold_client(tmp_path, [diary(entry), recipe, EDITED]) + + result = client.update_serving(SERVING_ID, DAY, grams=150) + + assert result == {**entry, "grams": 150} + assert state["payloads"][-1]["serving"] == result + + +@pytest.mark.parametrize( + "kwargs", + [{"measure_id": 31}, {"diary_group": 5}, {"measure_id": 31, "diary_group": 5}], +) +def test_update_serving_preserves_recipe_amount_on_measure_or_group_edit( + tmp_path, kwargs +): + entry = serving(foodId=300, measureId=30, grams=1.1) + client, state = make_cold_client(tmp_path, [diary(entry), EDITED]) + + result = client.update_serving(SERVING_ID, DAY, **kwargs) + + expected = dict(entry) + if "measure_id" in kwargs: + expected["measureId"] = kwargs["measure_id"] + if "diary_group" in kwargs: + expected["order"] = (kwargs["diary_group"] << 16) | 1 + assert result == expected + assert state["payloads"][-1]["serving"] == expected + assert len(state["payloads"]) == 2 + + +def test_concurrent_serving_edits_preserve_both_changes(tmp_path, monkeypatch): + client, _ = make_cold_client(tmp_path, []) + stored = serving() + state_lock = threading.Lock() + first_fetched = threading.Event() + release_first = threading.Event() + second_started = threading.Event() + second_fetched = threading.Event() + reads = 0 + + def request(endpoint, payload): + nonlocal stored, reads + if endpoint == "/api/v2/get_diary": + with state_lock: + snapshot = copy.deepcopy(stored) + reads += 1 + first = reads == 1 + if first: + first_fetched.set() + assert release_first.wait(timeout=5) + else: + second_fetched.set() + return diary(snapshot) + if endpoint == "/api/v2/get_food": + return FOOD + assert endpoint == "/api/v2/edit_serving" + with state_lock: + stored = copy.deepcopy(payload["serving"]) + return EDITED + + def move(): + second_started.set() + return client.update_serving(str(SERVING_ID), DAY, diary_group=5) + + monkeypatch.setattr(client, "_request", request) + with ThreadPoolExecutor(max_workers=2) as pool: + amount = pool.submit(client.update_serving, SERVING_ID, DAY, grams=150) + try: + assert first_fetched.wait(timeout=5) + moved = pool.submit(move) + assert second_started.wait(timeout=5) + fetched_before_save = second_fetched.wait(timeout=0.2) + finally: + release_first.set() + amount.result(timeout=5) + moved.result(timeout=5) + + assert not fetched_before_save + assert stored == serving(grams=150, order=(5 << 16) | 1) diff --git a/tests/test_diary_groups.py b/tests/test_diary_groups.py index ed5d084..e7375f6 100644 --- a/tests/test_diary_groups.py +++ b/tests/test_diary_groups.py @@ -731,3 +731,44 @@ def test_label_diary_groups_reuses_groups_cached_by_a_write(tmp_path): assert state["post"] == 1 assert diary["diary"][0]["diary_group"]["name"] == "Dinner" + + +# ------------------------------------------------------------------ +# update_food_entry resolves the target group from the account layout +# ------------------------------------------------------------------ + + +def test_update_food_entry_moves_to_a_named_custom_group(tmp_path, monkeypatch): + from test_diary_edit import EDITED, diary, serving + + from cronometer_api_mcp import server + + client, state = make_cold_client( + tmp_path, [profile(**CUSTOM_GROUPS), diary(serving()), EDITED] + ) + monkeypatch.setattr(server, "_client", client) + + result = json.loads( + server.update_food_entry( + entry_id=str(serving()["servingId"]), + date="1900-01-02", + diary_group="Pre-bedtime", + ) + ) + + assert result["status"] == "success" + assert result["diary_group"] == {"group": 5, "name": "Pre-bedtime"} + assert state["payloads"][-1]["serving"]["order"] >> 16 == 5 + + +def test_update_food_entry_refuses_auto_without_editing(tmp_path, monkeypatch): + from cronometer_api_mcp import server + + client, state = make_cold_client(tmp_path, []) + monkeypatch.setattr(server, "_client", client) + + result = json.loads(server.update_food_entry(entry_id="1", diary_group="auto")) + + assert result["status"] == "error" + assert '"auto" cannot move an entry' in result["message"] + assert state["payloads"] == [] diff --git a/tests/test_server_import.py b/tests/test_server_import.py index 1838cd2..c4ae0d2 100644 --- a/tests/test_server_import.py +++ b/tests/test_server_import.py @@ -39,6 +39,7 @@ "search_foods", "set_macro_split", "update_custom_food", + "update_food_entry", "update_note", "update_recipe", }