feat: reminders and scheduled tasks (schedule tool, app store and delivery)

The brain gets a schedule tool (add, list, delete the asker's own reminders,
timers and tasks) offered only with a schedule backend. The voice worker asks
the app through schedule_action and runs fired tasks as reply via task with
read-only tools, no MCP and a fresh short-term memory. The app keeps the
schedules in config/schedules.json, fires them every 5 s, speaks them when the
person is in Jarvis's voice channel and otherwise posts in the chat channel
they asked in (or schedule.chatChannel for voice). A feature switch and a
예약 screen list and delete everyone's schedules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-14 16:27:42 +09:00
parent 3d75d74f92
commit ea2d3ba958
32 changed files with 1568 additions and 59 deletions

109
tests/test_schedule_tool.py Normal file
View File

@@ -0,0 +1,109 @@
"""The schedule tool (src/jarvis/tools/builtin/schedule.spec.md) against a fake app backend."""
from __future__ import annotations
import time
from datetime import datetime, timedelta
import pytest
from jarvis.reply import turn_state
from jarvis.tools.builtin.schedule import ScheduleTool
class FakeApp:
"""Keeps schedules as the app would for one person: add returns the item, list all, delete one."""
def __init__(self):
self.items, self.calls = [], []
def act(self, action, **kw):
self.calls.append((action, kw))
if action == "add":
item = {"id": str(len(self.items) + 1), "next": kw["at"], **kw}
self.items.append(item)
return {"ok": True, "item": item}
if action == "list":
return {"ok": True, "items": list(self.items)}
found = [i for i in self.items if i["id"] == kw["schedule"]]
if not found:
return {"ok": False, "error": "no such schedule of yours"}
self.items.remove(found[0])
return {"ok": True, "item": found[0]}
@pytest.fixture
def app():
a = FakeApp()
turn_state.reset()
turn_state.set_schedule(a)
yield a
turn_state.reset()
def run(**args):
return ScheduleTool().run(args, None)
@pytest.mark.unit
def test_a_timer_in_minutes_is_a_reminder_that_many_minutes_from_now(app):
before = time.time()
r = run(action="add", text="라면 다 됐어요", in_minutes=5)
assert r.success
action, kw = app.calls[-1]
assert action == "add" and kw["kind"] == "remind" and kw["repeat"] == "none" and kw["text"] == "라면 다 됐어요"
assert before + 300 <= kw["at"] <= time.time() + 300
assert "id 1" in r.reply_text
@pytest.mark.unit
def test_a_local_time_and_a_repeat_reach_the_app(app):
at = (datetime.now() + timedelta(days=1)).replace(hour=9, minute=0, second=0, microsecond=0)
r = run(action="add_task", kind="task", text="날씨 알려 줘", at=at.strftime("%Y-%m-%d %H:%M"), repeat="daily")
assert r.success
_, kw = app.calls[-1]
assert kw["kind"] == "task" and kw["repeat"] == "daily" and kw["at"] == at.timestamp()
assert "repeats daily" in r.reply_text
@pytest.mark.unit
@pytest.mark.parametrize("args", [
{"text": "x"}, # no time
{"text": "x", "at": "tomorrow 7"}, # not a time
{"text": "x", "in_minutes": 0},
{"text": "", "in_minutes": 5}, # nothing to say
{"text": "x" * 501, "in_minutes": 5},
{"text": "x", "at": "2000-01-01 07:00"}, # passed, and not repeating
])
def test_a_bad_add_is_refused_without_asking_the_app(app, args):
r = run(action="add", **args)
assert not r.success and r.reply_text.startswith("Error:")
assert app.calls == []
@pytest.mark.unit
def test_list_and_delete_go_through_the_app(app):
run(action="add", text="회의", in_minutes=60)
listed = run(action="list")
assert listed.success and "회의" in listed.reply_text and "id 1" in listed.reply_text
assert run(action="delete", id="1").success
assert run(action="list").reply_text == "Nothing is scheduled for this person."
gone = run(action="delete", id="1")
assert not gone.success and "no such schedule" in gone.reply_text
@pytest.mark.unit
def test_without_a_backend_the_tool_refuses_and_is_not_offered(tmp_path, monkeypatch):
import json
from jarvis.config import load_settings
from jarvis.reply.engine import _offered_builtins
turn_state.reset()
r = run(action="add", text="x", in_minutes=5)
assert not r.success
cfg = tmp_path / "config.json"
cfg.write_text(json.dumps({"db_path": str(tmp_path / "j.db")}))
monkeypatch.setenv("JARVIS_CONFIG_PATH", str(cfg))
s = load_settings()
assert "schedule" not in _offered_builtins(s, chat_available=False)
assert "schedule" in _offered_builtins(s, chat_available=False, schedule_available=True)

View File

@@ -28,9 +28,9 @@ class FakeBrain:
self.answer = answer
self.calls = []
def reply(self, user, text, history, chat=None):
def reply(self, user, text, history, chat=None, schedule=None, task=False):
self.calls.append((user, text, history))
self.chat = chat
self.chat, self.schedule, self.task = chat, schedule, task
return self.answer(user, text)
def addressed(self, user, text, names):
@@ -1037,7 +1037,8 @@ def _jarvis_brain(tmp_path, monkeypatch, plans):
monkeypatch.setenv("JARVIS_CONFIG_PATH", str(cfg))
seen = {"judged": [], "prepared": []}
def fake_prepare(cfg, text, mem, chat_available):
def fake_prepare(cfg, text, mem, chat_available, schedule_available=False):
assert schedule_available # the reply it is made for has the schedule tool
seen["judged"].append((text, chat_available))
return plans.get(text)
@@ -1095,7 +1096,7 @@ def test_a_reply_waits_for_a_pick_still_being_prepared_for_its_text(tmp_path, mo
b, seen = _jarvis_brain(tmp_path, monkeypatch, {})
import jarvis.reply.engine as engine
def slow_prepare(cfg, text, mem, chat_available):
def slow_prepare(cfg, text, mem, chat_available, schedule_available=False):
_time.sleep(0.4)
return plan
monkeypatch.setattr(engine, "prepare_intent", slow_prepare)
@@ -1290,3 +1291,113 @@ def test_in_a_game_no_partials_are_transcribed_while_an_answer_is_written(store)
assert first_partial is None or (replies and first_partial > replies[0]), "no partial while answering"
else:
assert partials and replies and first_partial < replies[0], "partials go on without a game"
@pytest.mark.unit
@pytest.mark.parametrize("via, channel", [("voice", None), ("chat", "c1")])
def test_a_schedule_action_goes_to_the_app_for_the_asker_and_where_they_asked(store, via, channel):
results = []
brain = FakeBrain(lambda u, t: results.append(brain.schedule.act("add", kind="remind", text="회의",
at=1_900_000_000.0, repeat="none")) or "ok")
async def body(url):
async with connect(url) as ws:
await hello(ws)
await send(ws, type="reply", id="r1", user="100", text="q", via=via, speak=False,
**({"channel": channel} if channel else {}))
seen = await recv_until(ws, lambda m: isinstance(m, dict) and m.get("type") == "schedule_action")
action = seen[-1]
await send(ws, type="schedule_action_result", id=action["id"], ok=True, item={"id": "7", "text": "회의"})
await recv_until(ws, lambda m: isinstance(m, dict) and m.get("type") == "reply_text")
return action
action = asyncio.run(with_worker(body, store=store, brain=brain))
assert {k: v for k, v in action.items() if k not in ("type", "id")} == {
"action": "add", "user": "100", "via": via, **({"channel": channel} if channel else {}),
"kind": "remind", "text": "회의", "at": 1_900_000_000.0, "repeat": "none"}
assert results == [{"ok": True, "item": {"id": "7", "text": "회의"}}]
@pytest.mark.unit
def test_a_schedule_action_the_app_refuses_or_never_answers_fails(store):
results = []
brain = FakeBrain(lambda u, t: results.extend([brain.schedule.act("list"), brain.schedule.act("list")]) or "ok")
async def body(url):
async with connect(url) as ws:
await hello(ws)
await send(ws, type="reply", id="r1", user="100", text="q", via="voice", speak=False)
seen = await recv_until(ws, lambda m: isinstance(m, dict) and m.get("type") == "schedule_action")
await send(ws, type="schedule_action_result", id=seen[-1]["id"], ok=False, error="no")
await recv_until(ws, lambda m: isinstance(m, dict) and m.get("type") == "reply_text")
asyncio.run(with_worker(body, store=store, brain=brain, chat_timeout_s=0.3))
assert results == [{"ok": False, "error": "no"}, {"ok": False, "error": "the app did not answer in time"}]
@pytest.mark.unit
def test_a_scheduled_task_is_answered_without_schedule_or_chat_and_is_no_turn(store):
brain = FakeBrain()
async def body(url):
async with connect(url) as ws:
await hello(ws)
await ws.send(json.dumps(CHANNELS))
await send(ws, type="reply", id="t1", user="100", text="날씨 알려 줘", via="task")
seen = await recv_until(ws, lambda m: isinstance(m, dict) and m.get("type") == "reply_text")
await send(ws, type="reply", id="t2", user="100", text="x", via="task", speak=True)
seen += await recv_until(ws, lambda m: isinstance(m, dict) and m.get("type") == "error")
return seen
worker_turns = {}
async def run():
worker = VoiceWorker(TOKEN, LevelTranscriber(), AmplitudeVad, None, history=store, brain=brain)
server = await worker.serve("127.0.0.1", 0)
try:
seen = await asyncio.wait_for(body(f"ws://127.0.0.1:{server.sockets[0].getsockname()[1]}"), 15)
worker_turns.update(worker.reply_turns)
return seen
finally:
server.close()
await server.wait_closed()
await worker.stop()
seen = asyncio.run(run())
answer = next(m for m in seen if isinstance(m, dict) and m.get("type") == "reply_text")
assert answer == {"type": "reply_text", "id": "t1", "text": "answer for 날씨 알려 줘", "failed": False}
assert brain.task is True and brain.chat is None and brain.schedule is None
assert worker_turns == {} # not a turn: a delete asked before it is still confirmable
assert any(isinstance(m, dict) and m.get("type") == "error" and m.get("id") == "t2" for m in seen)
@pytest.mark.unit
def test_a_scheduled_task_runs_with_the_read_only_tools_and_no_mcp(tmp_path, monkeypatch):
pytest.importorskip("mcp")
from jarvis.memory.history import HistoryContext
from jarvis.reply import turn_state
from jarvis.reply.engine import _offered_builtins
from voice_worker import brain as brain_mod
cfg = tmp_path / "config.json"
cfg.write_text(json.dumps({"db_path": str(tmp_path / "jarvis.db"), "disabled_tools": ["getWeather"],
"mcps": {"x": {"transport": "stdio", "command": "nope"}}}))
monkeypatch.setenv("JARVIS_CONFIG_PATH", str(cfg))
monkeypatch.setattr(brain_mod, "_connect_mcp", lambda mcps: None)
seen = []
def fake_engine(db, cfg, tts, text, mem, **kw):
seen.append((set(_offered_builtins(cfg, turn_state.get_chat() is not None,
turn_state.get_schedule() is not None)), cfg.mcps, mem))
return "ok"
import jarvis.reply.engine as engine
monkeypatch.setattr(engine, "run_reply_engine", fake_engine)
b = brain_mod.JarvisBrain()
b.reply("100", "q", HistoryContext(), chat=object(), schedule=object())
b.reply("100", "q", HistoryContext(), chat=object(), schedule=object(), task=True)
(normal, normal_mcps, normal_mem), (task, task_mcps, task_mem) = seen
assert {"schedule", "chatChannels", "logMeal"} <= normal and normal_mcps
# Only looking things up, and a feature switched off stays off.
assert task == set(brain_mod.TASK_TOOLS) - {"getWeather"} and task_mcps == {}
assert task_mem is not normal_mem # not a turn of their conversation