Add MeshCore Agent HACS integration: todo module with reminders

Custom HA integration (domain meshcore_agent) that lets MeshCore nodes
manage a todo list over mesh messages:

- todo / todo list, todo add, todo done, todo uncheck, todo remove
- remind <n> <when> / remind off <n> (relative, clock, weekday, absolute)
- replies via meshcore.send_message / send_channel_message
- reminders scheduled with async_track_point_in_time and delivered to
  the sender who set them
- todo list also exposed as a HA todo entity
- config flow with sender allowlist, allow-all toggle, reply length cap
- pure-Python core (core/) covered by pytest; adapter flow tested with
  stubbed hass
This commit is contained in:
Dejvino
2026-12-01 19:15:05 +01:00
parent 9d759612e0
commit 8eba7fa24c
23 changed files with 2035 additions and 0 deletions
+6
View File
@@ -0,0 +1,6 @@
"""Make the repository root importable so tests can load custom_components."""
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))
+38
View File
@@ -0,0 +1,38 @@
"""Tests for the HA-independent parts of the adapter (truncation, targets)."""
from custom_components.meshcore_agent import target_from_event, truncate
from custom_components.meshcore_agent.core.store import Reminder
def test_truncate_short_untouched():
assert truncate("hello", 200) == "hello"
def test_truncate_long():
text = "a" * 300
out = truncate(text, 200)
assert len(out) == 200
assert out.endswith("...")
def test_truncate_prefers_newline():
text = "line one\n" + "b" * 300
out = truncate(text, 200)
assert out == "line one..."
def test_target_direct():
event = {"message_type": "direct", "pubkey_prefix": "abc123def456"}
assert target_from_event(event) == Reminder(
at="", kind="direct", target="abc123def456"
)
def test_target_channel():
event = {"message_type": "channel", "channel_idx": 2}
assert target_from_event(event) == Reminder(at="", kind="channel", target="2")
def test_target_missing():
assert target_from_event({"message_type": "direct"}) is None
assert target_from_event({"message_type": "channel"}) is None
+251
View File
@@ -0,0 +1,251 @@
"""End-to-end tests of the adapter: meshcore_message event -> reply service call.
Uses small stubs for hass/config entry/storage so the real event handling,
allowlist, reply routing and reminder firing paths run without a full HA.
"""
import asyncio
from datetime import datetime, timedelta, timezone
from types import SimpleNamespace
import pytest
from homeassistant.core import Event
from homeassistant.util import dt as dt_util
from custom_components.meshcore_agent import MeshCoreAgent
from custom_components.meshcore_agent.core.store import TodoStore
UTC = timezone.utc
class FakeBus:
def __init__(self):
self.listeners = []
def async_listen(self, event_type, callback):
self.listeners.append((event_type, callback))
return lambda: None
class FakeServices:
def __init__(self):
self.calls = []
async def async_call(self, domain, service, data, blocking=False):
self.calls.append((domain, service, data))
class FakeHass:
def __init__(self):
self.bus = FakeBus()
self.services = FakeServices()
self.data = {}
self.loop = asyncio.get_running_loop()
def async_create_task(self, coro):
return asyncio.get_running_loop().create_task(coro)
def verify_event_loop_thread(self, *_args, **_kwargs):
"""Stub for homeassistant.helpers.dispatcher."""
class FakeAgentStore:
def __init__(self):
self.todo_store = TodoStore()
self.saved = 0
async def async_save(self):
self.saved += 1
def make_event(data):
return Event("meshcore_message", data)
@pytest.fixture(autouse=True)
def _utc_tz():
previous = None
try:
previous = dt_util.get_default_time_zone()
except ValueError:
pass
dt_util.set_default_time_zone(UTC)
yield
if previous is not None:
dt_util.set_default_time_zone(previous)
def make_agent(allowlist="aabbcc,10bb", allow_all=False, data=None, options=None):
hass = FakeHass()
entry = SimpleNamespace(
entry_id="test_entry",
title="Agent",
data=data
if data is not None
else {"allowlist": allowlist, "allow_all": allow_all},
options=options if options is not None else {},
)
agent_store = FakeAgentStore()
agent = MeshCoreAgent(hass, entry, agent_store)
return agent, hass
async def deliver(agent, data):
await agent._handle_event(make_event(data))
async def test_direct_message_roundtrip():
agent, hass = make_agent()
await deliver(
agent,
{
"message_type": "direct",
"outgoing": False,
"pubkey_prefix": "aabbcc",
"sender_name": "Phone",
"message": "todo add Buy milk",
},
)
assert hass.services.calls == [
("meshcore", "send_message", {"pubkey_prefix": "aabbcc", "message": "Added #1: Buy milk"})
]
assert agent.todo_store.items[0].text == "Buy milk"
assert agent.agent_store.saved == 1
async def test_ignores_outgoing_and_non_allowlisted():
agent, hass = make_agent()
await deliver(
agent,
{"message_type": "direct", "outgoing": True, "pubkey_prefix": "aabbcc", "message": "todo"},
)
await deliver(
agent,
{"message_type": "direct", "outgoing": False, "pubkey_prefix": "ffff00", "message": "todo"},
)
await deliver(
agent,
{"message_type": "direct", "outgoing": False, "pubkey_prefix": "aabbcc", "message": "hello"},
)
assert hass.services.calls == []
assert agent.todo_store.items == []
async def test_allow_all_option():
agent, hass = make_agent(allow_all=True)
await deliver(
agent,
{"message_type": "direct", "pubkey_prefix": "ffff00", "message": "todo"},
)
assert len(hass.services.calls) == 1
assert "No todos" in hass.services.calls[0][2]["message"]
async def test_channel_message_replies_to_channel():
agent, hass = make_agent(allowlist="groupchat")
await deliver(
agent,
{
"message_type": "channel",
"channel_idx": 1,
"sender_name": "groupchat",
"message": "agent todo add From channel",
},
)
assert hass.services.calls == [
("meshcore", "send_channel_message", {"channel_idx": 1, "message": "Added #1: From channel"})
]
# The reminder target from a channel message is the channel itself.
await deliver(
agent,
{
"message_type": "channel",
"channel_idx": 1,
"sender_name": "groupchat",
"message": "remind 1 in 30m",
},
)
reminder = agent.todo_store.items[0].reminder
assert reminder.kind == "channel"
assert reminder.target == "1"
async def test_reminder_firing():
agent, hass = make_agent()
await deliver(
agent,
{
"message_type": "direct",
"pubkey_prefix": "aabbcc",
"message": "todo add Buy milk",
},
)
await deliver(
agent,
{
"message_type": "direct",
"pubkey_prefix": "aabbcc",
"message": "remind 1 in 1h",
},
)
item = agent.todo_store.items[0]
from custom_components.meshcore_agent.core.store import Reminder
# Simulate the scheduler reaching the reminder time.
agent.todo_store.set_reminder(
item,
Reminder(at=(dt_util.now() - timedelta(seconds=1)).isoformat(), kind="direct", target="aabbcc"),
)
hass.services.calls.clear()
await agent._fire_reminder(item.id)
assert hass.services.calls == [
("meshcore", "send_message", {"pubkey_prefix": "aabbcc", "message": "Reminder: Buy milk"})
]
assert item.reminder is None
async def test_reminder_scheduling_starts_and_cancels():
agent, hass = make_agent()
await deliver(
agent,
{
"message_type": "direct",
"pubkey_prefix": "aabbcc",
"message": "todo add Buy milk",
},
)
await deliver(
agent,
{
"message_type": "direct",
"pubkey_prefix": "aabbcc",
"message": "remind 1 in 1h",
},
)
assert set(agent._reminder_unsubs) == {agent.todo_store.items[0].id}
# Clearing the reminder removes the scheduled job.
await deliver(
agent,
{
"message_type": "direct",
"pubkey_prefix": "aabbcc",
"message": "remind off 1",
},
)
assert agent._reminder_unsubs == {}
async def test_long_reply_is_truncated():
agent, hass = make_agent()
await deliver(
agent,
{
"message_type": "direct",
"pubkey_prefix": "aabbcc",
"message": "todo add " + "x " * 100,
},
)
reply = hass.services.calls[0][2]["message"]
assert len(reply) <= 200
assert reply.endswith("...")
+191
View File
@@ -0,0 +1,191 @@
"""Tests for the command registry (the todo feature over mesh messages)."""
from datetime import datetime, timedelta, timezone
from custom_components.meshcore_agent.core.commands import (
Context,
handle_message,
)
from custom_components.meshcore_agent.core.store import Reminder, TodoStore
NOW = datetime(2026, 12, 1, 10, 0, 0, tzinfo=timezone.utc)
def make_ctx(*texts, target=None):
return Context(store=TodoStore(), now=NOW, target=target)
def populate(ctx: Context):
for text in ("Buy milk", "Fix antenna", "Water plants"):
ctx.store.add(text)
def test_non_command_messages_are_ignored():
ctx = make_ctx()
assert handle_message("hey, how are you?", ctx) is None
assert handle_message("", ctx) is None
assert handle_message(" ", ctx) is None
def test_todo_list_empty():
ctx = make_ctx()
assert "No todos" in handle_message("todo", ctx)
def test_todo_list_shows_items():
ctx = make_ctx()
populate(ctx)
reply = handle_message("todo", ctx)
assert reply.splitlines() == [
"1. [ ] Buy milk",
"2. [ ] Fix antenna",
"3. [ ] Water plants",
]
def test_todo_list_marks_completed_and_reminders():
ctx = make_ctx()
populate(ctx)
ctx.store.complete(ctx.store.items[1])
ctx.store.set_reminder(
ctx.store.items[0],
Reminder(at="2026-12-02T10:00:00+00:00", kind="direct", target="ab"),
)
reply = handle_message("todo", ctx)
assert reply.splitlines() == [
"1. [ ] Buy milk - Wed 02 Dec 10:00",
"2. [ ] Water plants",
"3. [x] Fix antenna",
]
def test_todo_add():
ctx = make_ctx()
assert handle_message("todo add Buy milk", ctx) == "Added #1: Buy milk"
assert handle_message("todo add Fix antenna ", ctx) == "Added #2: Fix antenna"
assert [i.text for i in ctx.store.items] == ["Buy milk", "Fix antenna"]
def test_todo_add_usage():
ctx = make_ctx()
assert "Usage" in handle_message("todo add", ctx)
def test_todo_done_by_number_and_text():
ctx = make_ctx()
populate(ctx)
assert handle_message("todo done 2", ctx) == "Done: Fix antenna"
assert ctx.store.items[1].is_completed
assert handle_message("todo done buy m", ctx) == "Done: Buy milk"
# Numbers now refer to the new display order (open items first).
assert handle_message("todo done 2", ctx) == "Already done: Buy milk"
assert handle_message("todo done 1", ctx) == "Done: Water plants"
def test_todo_done_by_full_text():
ctx = make_ctx()
populate(ctx)
assert handle_message("todo done fix antenna", ctx) == "Done: Fix antenna"
def test_todo_done_missing():
ctx = make_ctx()
populate(ctx)
assert "No todo matches" in handle_message("todo done 99", ctx)
ctx.store.add("Buy bread") # makes the "buy" prefix ambiguous
assert "No todo matches" in handle_message("todo done buy", ctx) # ambiguous
assert "Missing todo number" in handle_message("todo done", ctx)
def test_todo_uncheck():
ctx = make_ctx()
populate(ctx)
handle_message("todo done 1", ctx)
# Buy milk is now the third item in display order (open items first).
assert handle_message("todo uncheck 3", ctx) == "Reopened: Buy milk"
assert handle_message("todo uncheck buy", ctx) == "Not done yet: Buy milk"
def test_todo_remove():
ctx = make_ctx()
populate(ctx)
assert handle_message("todo remove 2", ctx) == "Removed: Fix antenna"
assert [i.text for i in ctx.store.items] == ["Buy milk", "Water plants"]
assert handle_message("todo rm 1", ctx) == "Removed: Buy milk"
def test_remind_by_number_relative():
ctx = make_ctx()
populate(ctx)
reply = handle_message("remind 1 in 30m", ctx)
assert "Reminder set for #1 (Buy milk)" in reply
expected = NOW + timedelta(minutes=30)
assert ctx.store.items[0].reminder is not None
parsed = datetime.fromisoformat(ctx.store.items[0].reminder.at)
assert parsed == expected
def test_remind_by_text_prefix():
ctx = make_ctx()
populate(ctx)
reply = handle_message("remind water plants tomorrow 09:00", ctx)
assert "Reminder set for #3 (Water plants)" in reply
parsed = datetime.fromisoformat(ctx.store.items[2].reminder.at)
assert parsed == (NOW + timedelta(days=1)).replace(hour=9)
def test_remind_stores_target():
target = Reminder(at="", kind="direct", target="aabbcc")
ctx = make_ctx(target=target)
populate(ctx)
handle_message("remind 1 in 1h", ctx)
reminder = ctx.store.items[0].reminder
assert reminder.kind == "direct"
assert reminder.target == "aabbcc"
def test_remind_off():
ctx = make_ctx()
populate(ctx)
handle_message("remind 1 in 1h", ctx)
assert handle_message("remind off 1", ctx) == "Reminder cleared: Buy milk"
assert ctx.store.items[0].reminder is None
assert handle_message("remind off 1", ctx) == "No reminder set: Buy milk"
def test_remind_usage_errors():
ctx = make_ctx()
populate(ctx)
assert "Usage" in handle_message("remind", ctx)
assert "Usage" in handle_message("remind 1", ctx) # no when
assert "Bad time" in handle_message("remind 1 gibberish", ctx)
assert "No todo matches" in handle_message("remind 9 in 30m", ctx)
def test_help():
ctx = make_ctx()
assert handle_message("help", ctx) == handle_message("help", make_ctx())
assert "todo" in handle_message("help", ctx).lower()
def test_wake_word_prefix():
ctx = make_ctx()
populate(ctx)
assert "Buy milk" in handle_message("agent todo", ctx)
assert "Buy milk" in handle_message("bot, todo", ctx)
assert "Usage" in handle_message("agent remind 1", ctx)
def test_alias_commands():
ctx = make_ctx()
populate(ctx)
assert handle_message("todos", ctx) == handle_message("todo", ctx)
assert handle_message("done 1", ctx) == "Done: Buy milk"
# After done 1, Fix antenna is #1 in display order.
assert handle_message("rm 1", ctx) == "Removed: Fix antenna"
assert "Added #2" in handle_message("add New item", ctx)
def test_unknown_todo_subcommand():
ctx = make_ctx()
assert "Unknown todo command" in handle_message("todo zap", ctx)
+102
View File
@@ -0,0 +1,102 @@
"""Tests for the pure todo store."""
from custom_components.meshcore_agent.core.store import (
Reminder,
TodoStore,
)
def make_store(*texts):
store = TodoStore()
for text in texts:
store.add(text)
return store
def test_add_and_list():
store = make_store("Buy milk", "Fix antenna")
assert [i.text for i in store.items] == ["Buy milk", "Fix antenna"]
assert all(not i.is_completed for i in store.items)
def test_display_order_open_first():
store = make_store("One", "Two", "Three")
one, two, three = store.items
store.complete(two)
assert [i.text for i in store.ordered()] == ["One", "Three", "Two"]
def test_resolve_by_number():
store = make_store("One", "Two", "Three")
store.complete(store.items[0])
assert store.resolve("1").text == "Two"
assert store.resolve("3").text == "One"
assert store.resolve("0") is None
assert store.resolve("9") is None
def test_resolve_by_text_prefix():
store = make_store("Buy milk", "Buy bread", "Fix antenna")
assert store.resolve("fix").text == "Fix antenna"
assert store.resolve("BUY MILK").text == "Buy milk"
# Ambiguous prefix resolves to nothing.
assert store.resolve("buy") is None
assert store.resolve("nope") is None
def test_complete_reopen_remove():
store = make_store("One", "Two")
one, two = store.items
store.complete(one)
assert one.is_completed
store.reopen(one)
assert not one.is_completed
store.remove(two)
assert [i.text for i in store.items] == ["One"]
def test_roundtrip_serialization():
store = make_store("Buy milk", "Fix antenna")
store.complete(store.items[1])
store.set_reminder(
store.items[0], Reminder(at="2026-12-02T10:00:00+01:00", kind="direct", target="ab12cd")
)
restored = TodoStore.from_dict(store.to_dict())
assert [i.text for i in restored.items] == ["Buy milk", "Fix antenna"]
assert restored.items[1].is_completed
assert restored.items[0].reminder is not None
assert restored.items[0].reminder.target == "ab12cd"
assert restored.items[0].reminder.kind == "direct"
def test_from_dict_tolerates_bad_rows():
data = {
"version": 1,
"items": [
{"text": "Good", "id": "a1", "status": "needs_action", "created": 0},
{"no_text": True},
"not-a-dict",
],
}
store = TodoStore.from_dict(data)
assert [i.text for i in store.items] == ["Good"]
def test_from_dict_empty():
assert TodoStore.from_dict(None).items == []
assert TodoStore.from_dict({}).items == []
def test_reminders_and_clearing():
store = make_store("One", "Two")
store.set_reminder(
store.items[0],
Reminder(at="2026-12-02T10:00:00+01:00", kind="channel", target="0"),
)
pending = store.pending_reminders()
assert len(pending) == 1
item, reminder = pending[0]
assert item.text == "One"
assert reminder.kind == "channel"
store.clear_reminder(item)
assert store.pending_reminders() == []
+77
View File
@@ -0,0 +1,77 @@
"""Tests for reminder time parsing."""
from datetime import datetime, timedelta, timezone
import pytest
from custom_components.meshcore_agent.core.timeparse import (
TimeParseError,
parse_when,
)
NOW = datetime(2026, 12, 1, 10, 0, 0, tzinfo=timezone.utc) # a Tuesday
def assert_future(value: datetime):
assert value > NOW
def test_relative_minutes_hours_days():
assert parse_when("in 30m", NOW) == NOW + timedelta(minutes=30)
assert parse_when("in 2h", NOW) == NOW + timedelta(hours=2)
assert parse_when("in 1d", NOW) == NOW + timedelta(days=1)
assert parse_when("in 1h30m", NOW) == NOW + timedelta(hours=1, minutes=30)
assert parse_when("In 45 M", NOW) == NOW + timedelta(minutes=45)
def test_relative_rejects_zero():
with pytest.raises(TimeParseError):
parse_when("in 0m", NOW)
def test_clock_time_same_day():
assert parse_when("14:30", NOW) == NOW.replace(hour=14, minute=30)
assert parse_when("today 14:30", NOW) == NOW.replace(hour=14, minute=30)
with pytest.raises(TimeParseError):
parse_when("today 09:15", NOW) # already passed
def test_clock_time_rolls_to_tomorrow():
assert parse_when("09:00", NOW) == (NOW + timedelta(days=1)).replace(hour=9)
assert parse_when("tomorrow 09:00", NOW) == (NOW + timedelta(days=1)).replace(hour=9)
# tomorrow always rolls even if the time already passed today
assert parse_when("tomorrow 11:00", NOW) == (NOW + timedelta(days=1)).replace(hour=11)
def test_weekday():
# Now is Tuesday; monday is next Monday.
expected = (NOW + timedelta(days=6)).replace(hour=8)
assert parse_when("monday 08:00", NOW) == expected
# Friday is later this week.
assert parse_when("friday 18:00", NOW) == (NOW + timedelta(days=3)).replace(hour=18)
# Tuesday same day, later hour.
assert parse_when("tuesday 12:00", NOW) == NOW.replace(hour=12)
# Tuesday same hour rolls a week ahead.
assert parse_when("tuesday 10:00", NOW) == (NOW + timedelta(days=7)).replace(hour=10)
def test_absolute_date():
assert parse_when("2026-12-24 14:30", NOW) == datetime(
2026, 12, 24, 14, 30, tzinfo=timezone.utc
)
# Date without time defaults to 09:00.
assert parse_when("2026-12-24", NOW) == datetime(
2026, 12, 24, 9, 0, tzinfo=timezone.utc
)
def test_invalid_inputs():
for bad in ("", "gibberish", "in ", "25:00", "tomorrow 24:30", "2026-13-01", "2026-02-30 10:00"):
with pytest.raises((TimeParseError, ValueError)):
parse_when(bad, NOW)
def test_requires_aware_now():
naive = datetime(2026, 12, 1, 10, 0)
with pytest.raises(ValueError):
parse_when("in 30m", naive)