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:
@@ -63,7 +63,8 @@ manages the MCP servers it connects.
|
||||
collection, below; no brain tool) and `browser` (the bot browser, below "Bot browser", and its
|
||||
brain tool `botBrowser`, `src/jarvis/tools/builtin/bot_browser.spec.md`), also on by default;
|
||||
`browserShare` (봇용 크롬창 화면공유 선택 표시, the bot browser on the virtual monitor, below
|
||||
"Virtual monitor"), off by default. The tools of a feature that
|
||||
"Virtual monitor"), off by default; `schedule` (reminders and scheduled tasks, below
|
||||
"Schedules", and the brain tool `schedule`), on by default. The tools of a feature that
|
||||
is off go into the brain's `disabled_tools`: they are neither offered nor run
|
||||
(`voice_worker.spec.md`, "Tools"). The other features of the 기능 screen (PC control, screen
|
||||
viewing) come with their milestone (M7).
|
||||
@@ -103,6 +104,39 @@ sites, search words and RSS feeds on a schedule; there are **no targets by defau
|
||||
first), each item with its `target`; a name that is not a valid target name is refused, so no
|
||||
other folder is read. Lines that do not parse are skipped.
|
||||
|
||||
## Schedules (`app/src/schedule.rs`)
|
||||
|
||||
`docs/v2/proactive.md` (제안 1). People ask Jarvis by voice or chat to remind them, set a timer or
|
||||
check something at a time or regularly; the brain's `schedule` tool
|
||||
(`src/jarvis/tools/builtin/schedule.spec.md`) asks the app, which keeps, fires and delivers them.
|
||||
|
||||
- **Store**: `config/schedules.json` in the data folder, `{nextId, items}`; each item `{id, user,
|
||||
name, kind, text, repeat, next, via, channel, created, last}`. Read and written whole, one change
|
||||
at a time in the process (the services' loop and the screen share it). Text 1-500 characters
|
||||
(whitespace collapsed), `kind` `remind|task`, `repeat` `none|daily|weekdays|weekly`, `via`
|
||||
`voice|chat` (chat needs the channel it was asked in), at most 50 per person. A one-off time that
|
||||
has passed is refused; a repeating one starts at its first time after now (`weekdays` skips
|
||||
Saturday and Sunday, `weekly` keeps the weekday). Repeats keep the local wall time.
|
||||
- **The brain's actions** (`schedule_action`, `voice_worker.spec.md`, "Schedules") are done for the
|
||||
person named in it only: `add` (named as Discord shows them now), `list` (their schedules that
|
||||
still fire, soonest first), `delete` (one of theirs). The answer carries `{id, kind, text, next,
|
||||
repeat}`; a refusal says why. With `features.schedule` off the tool is not offered; schedules
|
||||
already kept still fire and can be deleted on the screen.
|
||||
- **Firing**: while the services run, every 5 s the due ones are taken (a repeating one moves on to
|
||||
its next time at once; a one-off one stops firing). One more than 15 minutes late (the app was
|
||||
off, the PC asleep) is not delivered and is kept as missed. Each delivery runs on its own task.
|
||||
- **Delivery**: a `task` first runs in the brain (`reply` `via: "task"`: read-only tools, its own
|
||||
short-term memory, at most 300 s); no answer is a failure. The text sent is `<name>님, <reminder or
|
||||
answer>`. Asked by voice: spoken when the person is in Jarvis's voice channel, else posted in
|
||||
`schedule.chatChannel`; asked in chat: posted in that channel. Posts ping nobody and need the
|
||||
channel's send switch. A delivered one-off schedule is removed; one that failed, or was missed,
|
||||
stays (not firing again) with its outcome `last: {at, ok, note}` for the screen, and a repeating
|
||||
one keeps its latest outcome.
|
||||
- `schedule.chatChannel` (new section, null by default): a registered chat channel with sending on
|
||||
(anything else is refused), for voice schedules whose person is not in the voice channel. Null:
|
||||
those are not delivered (and the screen says so).
|
||||
- Logs (tab `conversation`): ids, kinds, repeats, channel ids, counts and outcomes, never the text.
|
||||
|
||||
## Secrets (`app/src/secrets.rs`)
|
||||
|
||||
`config/secrets.dat` holds a JSON object of named secrets (`discordToken`, the MCP servers'
|
||||
@@ -120,7 +154,7 @@ headless runs).
|
||||
`debug_log!` and `error_log!` keep printing to stderr and also feed the log hub once the app
|
||||
installs one (`logs::install`). Each line has a time, a level (`error`, `warn`, `info`, `debug`), a
|
||||
service tab and its text. The tab comes from the line's category: `app`, `discord` (`voice`,
|
||||
`receive`, `play`, `discord`), `chat`, `conversation`, `worker` (the voice worker's own lines; its
|
||||
`receive`, `play`, `discord`), `chat`, `conversation` (also `schedule`), `worker` (the voice worker's own lines; its
|
||||
STT, LLM and TTS lines go to `stt`, `llm`, `tts` by their worker category), `browser`, `capture`,
|
||||
`game` (the last three from M6-M7). Unknown categories go to `app`.
|
||||
|
||||
@@ -496,6 +530,7 @@ back as Korean messages for the screen. The Tauri shell passes the screens' `inv
|
||||
| `settings_fields` / `settings_view` / `settings_apply` `{changes}` | the settings editor above; `restartNeeded` when the services run; `sync` with the chat channels sent to Discord (below) |
|
||||
| `service_start` / `service_stop` / `service_restart` / `dashboard` | the controller and its snapshot; start and restart run in the background, stop also cancels a start |
|
||||
| `discord_channel_info` `{id}` / `channel_sync_status` | a channel's Discord name and topic / each synced chat channel's last result (above) |
|
||||
| `schedules_list` / `schedule_delete` `{id}` | every person's schedules (above), soonest first, with IDs as strings / delete one |
|
||||
| `collect_results` `{target, limit}` | `{targets, items}`: every target folder with results, and the collected items newest first (`target` null: every target; `limit` 1-500, default 100) |
|
||||
| `mcp_env_status` / `mcp_env_set` `{server, name, value}` | which MCP environment values are stored (`{server: {NAME: bool}}`, never the values) / store one (an empty value removes it); only for a saved server and name |
|
||||
| `display_driver_status` / `display_driver_install` / `display_driver_uninstall` | the virtual monitor's driver: `{supported, installed, leftover, other, action}` (Windows only, above) / install or remove it elevated (above), then its status; refused unless the services are stopped or failed, and `service_start` / `service_restart` are refused meanwhile |
|
||||
@@ -524,7 +559,7 @@ Plain HTML, CSS and an ES module, no build step, dark theme after `DESIGN.md`. A
|
||||
Strata's last line, and stop in the header; the header with start, restart and stop is rebuilt
|
||||
only when the state changes, so a click is never lost to the refresh. Every screen change starts
|
||||
a new generation: an answer that arrives after the user moved to another screen is dropped.
|
||||
- **Settings screens** (봇, 채널·호출, 채팅 채널, 대화 기억, 모델, 기능, 백그라운드 수집, 게임 모드): built from `settings_fields`; only
|
||||
- **Settings screens** (봇, 채널·호출, 채팅 채널, 대화 기억, 모델, 기능, 백그라운드 수집, 예약, 게임 모드): built from `settings_fields`; only
|
||||
changed fields are sent; the server and voice channel are pickers (choosing another server clears
|
||||
the voice channel and lists only that server's channels); the chat channels are a table
|
||||
with their switches; the bot screen also changes the token; the 기능 screen has the feature
|
||||
@@ -534,7 +569,9 @@ Plain HTML, CSS and an ES module, no build step, dark theme after `DESIGN.md`. A
|
||||
state and the button its `action` names, so a leftover can always be removed). The 백그라운드 수집 screen has the targets (a table: name, kind,
|
||||
address or words, interval in minutes, on/off, delete), the keep days, and the results (the
|
||||
newest 100, filtered by any target that has results, each with its time, title, link and the start of its text shown
|
||||
as plain text).
|
||||
as plain text). The 예약 screen has `schedule.chatChannel` and every person's schedules (next time
|
||||
or "다시 울리지 않음", repeat, who and how they asked, kind and text as plain text, the last
|
||||
outcome, delete).
|
||||
- **업데이트**: the version here, the state, "다시 확인", "받기" (with its percentage) and "설치하고
|
||||
다시 시작", and the release's notes as plain text. The app checks once when the main screens open;
|
||||
a newer release renames the button "업데이트 (새 버전)" and says so once.
|
||||
|
||||
@@ -355,6 +355,23 @@ impl AdminApi {
|
||||
Ok(json!({"targets": crate::collect::result_targets(dir.path()),
|
||||
"items": crate::collect::results(dir.path(), target, limit)?}))
|
||||
}
|
||||
// Schedules (admin.spec.md, "Schedules"): every person's, and deleting any of them.
|
||||
"schedules_list" => {
|
||||
let items = crate::schedule::Store::new(self.dir()?.path()).all()?;
|
||||
Ok(json!({"items": items.iter().map(|i| {
|
||||
let mut v = json!(i);
|
||||
v["id"] = json!(i.id.to_string());
|
||||
v["user"] = json!(i.user.to_string());
|
||||
v["channel"] = json!(i.channel.map(|c| c.to_string()));
|
||||
v
|
||||
}).collect::<Vec<_>>()}))
|
||||
}
|
||||
"schedule_delete" => {
|
||||
let id: u64 = arg_str(&args, "id")?.parse().map_err(|_| "예약 ID가 올바르지 않습니다")?;
|
||||
crate::schedule::Store::new(self.dir()?.path()).delete(id, None)?;
|
||||
crate::info_log!("admin", "schedule {id} deleted");
|
||||
Ok(json!({"deleted": id.to_string()}))
|
||||
}
|
||||
"channel_sync_status" => Ok(Value::Object(self.syncer()?.status().into_iter()
|
||||
.map(|(id, s)| (id.to_string(), json!(s))).collect())),
|
||||
"discord_channel_info" => {
|
||||
@@ -474,6 +491,26 @@ mod tests {
|
||||
assert!(a.call("nope", json!({})).await.is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_schedule_screen_lists_everyones_schedules_and_deletes_any() {
|
||||
let (a, base) = api("api-schedule");
|
||||
let data = base.join("d");
|
||||
a.call("folder_choose", json!({"path": data.to_string_lossy()})).await.unwrap();
|
||||
assert_eq!(a.call("schedules_list", json!({})).await.unwrap()["items"], json!([]));
|
||||
let store = crate::schedule::Store::new(&data);
|
||||
let now = chrono::Utc::now().timestamp();
|
||||
store.add(123456789012345678, "가", "remind", "회의", now + 600, "none", "voice", None, now).unwrap();
|
||||
let b = store.add(9, "나", "task", "날씨", now + 60, "daily", "chat", Some(77), now).unwrap();
|
||||
let items = a.call("schedules_list", json!({})).await.unwrap()["items"].as_array().unwrap().clone();
|
||||
// Soonest first; IDs as strings (JSON numbers lose Discord IDs).
|
||||
assert_eq!(items.iter().map(|i| i["text"].as_str().unwrap()).collect::<Vec<_>>(), ["날씨", "회의"]);
|
||||
assert_eq!(items[1]["user"], "123456789012345678");
|
||||
assert_eq!(items[0]["channel"], "77");
|
||||
a.call("schedule_delete", json!({"id": b.id.to_string()})).await.unwrap();
|
||||
assert_eq!(store.all().unwrap().len(), 1);
|
||||
assert!(a.call("schedule_delete", json!({"id": b.id.to_string()})).await.is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn collection_targets_are_saved_and_their_results_read_from_the_data_folder() {
|
||||
let (a, base) = api("api-collect");
|
||||
|
||||
@@ -36,7 +36,7 @@ pub trait Voice {
|
||||
fn ask_addressed(&self, id: &str, user: u64, text: &str) -> bool;
|
||||
fn ask_rank(&self, id: &str, candidates: &[(String, u64, String)]) -> bool;
|
||||
/// Have the brain answer a chat message (not spoken); its text comes as `CoreEvent::ReplyText`.
|
||||
fn chat_answer(&self, id: &str, user: u64, text: &str) -> bool;
|
||||
fn chat_answer(&self, id: &str, user: u64, channel: u64, text: &str) -> bool;
|
||||
/// Post the chat answer `id` in `channel` as a reply to `message` (never pinging anyone), then
|
||||
/// tell the brain whether it was posted.
|
||||
fn send_reply(&self, id: &str, channel: u64, message: u64, text: &str);
|
||||
@@ -66,8 +66,8 @@ impl Voice for DiscordCore {
|
||||
fn ask_rank(&self, id: &str, candidates: &[(String, u64, String)]) -> bool {
|
||||
DiscordCore::ask_rank(self, id, candidates)
|
||||
}
|
||||
fn chat_answer(&self, id: &str, user: u64, text: &str) -> bool {
|
||||
DiscordCore::chat_answer(self, id, user, text)
|
||||
fn chat_answer(&self, id: &str, user: u64, channel: u64, text: &str) -> bool {
|
||||
DiscordCore::chat_answer(self, id, user, channel, text)
|
||||
}
|
||||
fn send_reply(&self, id: &str, channel: u64, message: u64, text: &str) {
|
||||
let core = self.clone();
|
||||
@@ -190,7 +190,7 @@ impl<V: Voice> Conversation<V> {
|
||||
self.chat_answers.retain(|_, (_, _, at)| now < *at + CHAT_ANSWER_KEPT);
|
||||
self.next_id += 1;
|
||||
let id = format!("c{}", self.next_id);
|
||||
if self.voice.chat_answer(&id, m.author_id, &m.content) {
|
||||
if self.voice.chat_answer(&id, m.author_id, m.channel_id, &m.content) {
|
||||
self.chat_answers.insert(id, (m.channel_id, m.message_id, now));
|
||||
}
|
||||
}
|
||||
@@ -485,6 +485,8 @@ mod tests {
|
||||
Addressed(String, u64),
|
||||
Rank(String, Vec<String>),
|
||||
ChatAnswer(String, u64, String),
|
||||
/// The channel a chat answer was asked for.
|
||||
ChatIn(u64),
|
||||
SendReply(String, u64, u64, String),
|
||||
NotPosted(String),
|
||||
}
|
||||
@@ -493,6 +495,7 @@ mod tests {
|
||||
struct Fake {
|
||||
did: Rc<RefCell<Vec<Did>>>,
|
||||
n: Rc<RefCell<u32>>,
|
||||
chat_in: Rc<RefCell<Vec<Did>>>,
|
||||
}
|
||||
impl Voice for Fake {
|
||||
fn answer(&self, user: u64, text: &str, _heard: (Instant, Instant)) -> Option<String> {
|
||||
@@ -520,7 +523,8 @@ mod tests {
|
||||
self.did.borrow_mut().push(Did::Rank(id.into(), c.iter().map(|x| x.0.clone()).collect()));
|
||||
true
|
||||
}
|
||||
fn chat_answer(&self, id: &str, user: u64, text: &str) -> bool {
|
||||
fn chat_answer(&self, id: &str, user: u64, channel: u64, text: &str) -> bool {
|
||||
self.chat_in.borrow_mut().push(Did::ChatIn(channel));
|
||||
self.did.borrow_mut().push(Did::ChatAnswer(id.into(), user, text.into()));
|
||||
true
|
||||
}
|
||||
@@ -869,6 +873,7 @@ mod tests {
|
||||
c.on_event(&chat(CH_WAKE, 5, A, false, "자비스 내일 일정 알려 줘"), t);
|
||||
let Did::ChatAnswer(id, user, text) = f.take().remove(0) else { panic!() };
|
||||
assert_eq!((user, text.as_str()), (A, "자비스 내일 일정 알려 줘"));
|
||||
assert_eq!(*f.chat_in.borrow(), vec![Did::ChatIn(CH_WAKE)], "the brain is told where it was asked");
|
||||
c.on_event(&CoreEvent::ReplyText { id: id.clone(), text: "내일은 비어 있어요.".into(), failed: false }, t);
|
||||
assert_eq!(f.take(), vec![Did::SendReply(id.clone(), CH_WAKE, 5, "내일은 비어 있어요.".into())]);
|
||||
// A second reply_text for the same id sends nothing.
|
||||
|
||||
@@ -199,8 +199,16 @@ struct Inner {
|
||||
/// The latest voice session's number, and the session each utterance in progress started in.
|
||||
voice_session: std::sync::atomic::AtomicU64,
|
||||
utt_sessions: Mutex<UttSessions>,
|
||||
/// The reminders and scheduled tasks the brain's schedule tool adds to (admin.spec.md, "Schedules").
|
||||
schedules: OnceLock<Arc<crate::schedule::Store>>,
|
||||
/// Scheduled tasks waiting for the brain's answer, by reply id.
|
||||
tasks: Mutex<HashMap<String, tokio::sync::oneshot::Sender<String>>>,
|
||||
}
|
||||
|
||||
/// How long a scheduled task may take, waiting for an LLM switch included (the worker gives up
|
||||
/// waiting for one after 180 s).
|
||||
const TASK_TIMEOUT: Duration = Duration::from_secs(300);
|
||||
|
||||
/// The voice session each utterance in progress started in (`Heard::session`).
|
||||
#[derive(Default)]
|
||||
pub struct UttSessions(HashMap<(u64, u32), u64>);
|
||||
@@ -260,6 +268,8 @@ impl DiscordCore {
|
||||
names: Mutex::new(HashMap::new()),
|
||||
voice_session: std::sync::atomic::AtomicU64::new(0),
|
||||
utt_sessions: Mutex::new(UttSessions::default()),
|
||||
schedules: OnceLock::new(),
|
||||
tasks: Mutex::new(HashMap::new()),
|
||||
});
|
||||
tokio::spawn(player_task(Arc::downgrade(&inner), player_rx));
|
||||
tokio::spawn(worker_task(Arc::downgrade(&inner), worker_events));
|
||||
@@ -480,9 +490,28 @@ impl DiscordCore {
|
||||
Some(with_playback(&self.inner, |p| p.clip(crate::earcon::pcm().to_vec())))
|
||||
}
|
||||
|
||||
/// Have the brain answer a chat message under `id`; the text comes as `CoreEvent::ReplyText`.
|
||||
pub fn chat_answer(&self, id: &str, user: u64, text: &str) -> bool {
|
||||
self.inner.worker.reply(id, user, text, "chat", false)
|
||||
/// Have the brain answer a chat message written in `channel` under `id`; the text comes as
|
||||
/// `CoreEvent::ReplyText`.
|
||||
pub fn chat_answer(&self, id: &str, user: u64, channel: u64, text: &str) -> bool {
|
||||
self.inner.worker.reply_in(id, user, text, "chat", false, Some(channel))
|
||||
}
|
||||
|
||||
/// The store the brain's schedule tool works on; without one its actions fail.
|
||||
pub fn set_schedules(&self, store: Arc<crate::schedule::Store>) {
|
||||
let _ = self.inner.schedules.set(store);
|
||||
}
|
||||
|
||||
/// Run a scheduled task in the brain (read-only tools, not spoken) and wait for its answer.
|
||||
pub async fn run_task(&self, id: &str, user: u64, text: &str) -> Option<String> {
|
||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||
self.inner.tasks.lock().unwrap().insert(id.to_owned(), tx);
|
||||
if !self.inner.worker.reply(id, user, text, "task", false) {
|
||||
self.inner.tasks.lock().unwrap().remove(id);
|
||||
return None;
|
||||
}
|
||||
let got = tokio::time::timeout(TASK_TIMEOUT, rx).await;
|
||||
self.inner.tasks.lock().unwrap().remove(id);
|
||||
got.ok().and_then(Result::ok).filter(|t| !t.trim().is_empty())
|
||||
}
|
||||
|
||||
/// Tell the brain whether the chat answer `id` was posted.
|
||||
@@ -633,6 +662,22 @@ impl DiscordCore {
|
||||
|
||||
use songbird::CoreEvent as CoreEvent_;
|
||||
|
||||
#[async_trait]
|
||||
impl crate::schedule::Deliver for DiscordCore {
|
||||
fn hears(&self, user: u64) -> bool {
|
||||
self.voice_members().iter().any(|(u, _)| *u == user)
|
||||
}
|
||||
fn say(&self, text: &str) -> bool {
|
||||
DiscordCore::say(self, text, false).is_some()
|
||||
}
|
||||
async fn post(&self, channel: u64, text: &str) -> Result<(), String> {
|
||||
self.send_chat(channel, text).await.map(|_| ()).map_err(|e| e.to_string())
|
||||
}
|
||||
async fn task(&self, id: &str, user: u64, text: &str) -> Option<String> {
|
||||
self.run_task(id, user, text).await
|
||||
}
|
||||
}
|
||||
|
||||
fn with_playback<T>(inner: &Inner, f: impl FnOnce(&mut Playback<WorkerClient, PlayerSink>) -> T) -> T {
|
||||
let (out, events) = {
|
||||
let mut p = inner.playback.lock().unwrap();
|
||||
@@ -778,6 +823,10 @@ async fn worker_task(core: std::sync::Weak<Inner>, mut rx: mpsc::UnboundedReceiv
|
||||
WorkerEvent::TtsDone(d) => with_playback(&inner, |p| p.done(&d)),
|
||||
WorkerEvent::ReplyText { id, text, failed } => {
|
||||
debug_log!("voice", "reply {id} chars={} failed={failed}", text.chars().count());
|
||||
if let Some(tx) = inner.tasks.lock().unwrap().remove(&id) {
|
||||
let _ = tx.send(if failed { String::new() } else { text });
|
||||
continue;
|
||||
}
|
||||
let _ = inner.events.send(CoreEvent::ReplyText { id, text, failed });
|
||||
}
|
||||
WorkerEvent::Addressed { id, addressed } => {
|
||||
@@ -800,9 +849,24 @@ async fn worker_task(core: std::sync::Weak<Inner>, mut rx: mpsc::UnboundedReceiv
|
||||
core.inner.worker.chat_action_result(&a.id, result);
|
||||
});
|
||||
}
|
||||
WorkerEvent::ScheduleAction(a) => {
|
||||
let result = match inner.schedules.get() {
|
||||
Some(store) => {
|
||||
let name = a.user.parse().map(|u| name_of(&inner, u)).unwrap_or_else(|_| a.user.clone());
|
||||
crate::schedule::act(store, &a, &name, chrono::Utc::now().timestamp())
|
||||
}
|
||||
None => Err("schedules are not available".into()),
|
||||
};
|
||||
if let Err(e) = &result {
|
||||
debug_log!("schedule", "schedule {} {} refused: {e}", a.action, a.id);
|
||||
}
|
||||
inner.worker.schedule_action_result(&a.id, result);
|
||||
}
|
||||
WorkerEvent::Disconnected => {
|
||||
// The restarted worker numbers utterances afresh: the old ones' sessions are void.
|
||||
inner.utt_sessions.lock().unwrap().clear();
|
||||
// Its tasks will not be answered.
|
||||
inner.tasks.lock().unwrap().clear();
|
||||
let _ = inner.events.send(CoreEvent::WorkerLost);
|
||||
}
|
||||
WorkerEvent::Error(_) => {}
|
||||
|
||||
@@ -17,6 +17,7 @@ pub const FEATURE_TOOLS: &[(&str, &[&str])] = &[
|
||||
("webSearch", &["webSearch", "fetchWebPage"]),
|
||||
("meals", &["logMeal", "fetchMeals", "deleteMeal"]),
|
||||
("browser", &["botBrowser"]),
|
||||
("schedule", &["schedule"]),
|
||||
];
|
||||
|
||||
/// The built-in tools of the features that are off.
|
||||
@@ -25,6 +26,7 @@ pub fn disabled_tools(f: &FeatureSettings) -> Vec<&'static str> {
|
||||
"weather" => f.weather,
|
||||
"webSearch" => f.web_search,
|
||||
"browser" => f.browser,
|
||||
"schedule" => f.schedule,
|
||||
_ => f.meals,
|
||||
};
|
||||
FEATURE_TOOLS.iter().filter(|(k, _)| !on(k)).flat_map(|(_, tools)| tools.iter().copied()).collect()
|
||||
@@ -102,10 +104,10 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn features_that_are_off_turn_their_tools_off() {
|
||||
let all_on = FeatureSettings { weather: true, web_search: true, meals: true, collect: true, browser: true, browser_share: true };
|
||||
let all_on = FeatureSettings { weather: true, web_search: true, meals: true, collect: true, browser: true, browser_share: true, schedule: true };
|
||||
assert!(disabled_tools(&all_on).is_empty());
|
||||
let off = disabled_tools(&FeatureSettings { weather: false, web_search: true, meals: false, collect: false, browser: false, browser_share: false });
|
||||
assert_eq!(off, vec!["getWeather", "logMeal", "fetchMeals", "deleteMeal", "botBrowser"]);
|
||||
let off = disabled_tools(&FeatureSettings { weather: false, web_search: true, meals: false, collect: false, browser: false, browser_share: false, schedule: false });
|
||||
assert_eq!(off, vec!["getWeather", "logMeal", "fetchMeals", "deleteMeal", "botBrowser", "schedule"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -25,6 +25,7 @@ pub mod perf;
|
||||
pub mod placement;
|
||||
pub mod policy;
|
||||
pub mod receive;
|
||||
pub mod schedule;
|
||||
pub mod secrets;
|
||||
pub mod services;
|
||||
pub mod settings;
|
||||
|
||||
@@ -44,7 +44,7 @@ pub fn tab_of(category: &str) -> &'static str {
|
||||
match category {
|
||||
"voice" | "receive" | "play" | "discord" => "discord",
|
||||
"chat" => "chat",
|
||||
"conversation" => "conversation",
|
||||
"conversation" | "schedule" => "conversation",
|
||||
"worker" | "voice_worker" => "worker",
|
||||
"stt" => "stt",
|
||||
"llm" => "llm",
|
||||
|
||||
523
app/src/schedule.rs
Normal file
523
app/src/schedule.rs
Normal file
@@ -0,0 +1,523 @@
|
||||
//! Reminders and scheduled tasks (`app/src/admin.spec.md`, "Schedules"): the store in the data
|
||||
//! folder, the next times, the brain's `schedule_action`, and the loop that fires and delivers.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
|
||||
use chrono::{Datelike, Local, NaiveDateTime, TimeZone, Weekday};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use crate::worker_client::ScheduleAction;
|
||||
|
||||
/// A schedule later than this when its time comes (the app was off, the PC asleep) is not delivered.
|
||||
pub const GRACE_SECS: i64 = 15 * 60;
|
||||
/// Schedules one person may have.
|
||||
pub const PER_PERSON: usize = 50;
|
||||
pub const MAX_TEXT_CHARS: usize = 500;
|
||||
/// How often the loop looks for schedules that are due.
|
||||
pub const TICK: Duration = Duration::from_secs(5);
|
||||
|
||||
/// The store's file is read and written whole; one change at a time in this process (the services'
|
||||
/// loop and the settings screen both use it).
|
||||
static FILE_LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Outcome {
|
||||
pub at: i64,
|
||||
pub ok: bool,
|
||||
/// Why it failed, for the screen (no text of the schedule).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub note: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Schedule {
|
||||
pub id: u64,
|
||||
pub user: u64,
|
||||
pub name: String,
|
||||
/// `remind` or `task`.
|
||||
pub kind: String,
|
||||
pub text: String,
|
||||
/// `none`, `daily`, `weekdays` or `weekly`.
|
||||
pub repeat: String,
|
||||
/// When it fires next (Unix seconds); None: it will not fire again (kept to show its outcome).
|
||||
pub next: Option<i64>,
|
||||
/// `voice` or `chat`: where it was asked.
|
||||
pub via: String,
|
||||
/// The chat channel it was asked in (via chat).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub channel: Option<u64>,
|
||||
pub created: i64,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub last: Option<Outcome>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct File {
|
||||
next_id: u64,
|
||||
items: Vec<Schedule>,
|
||||
}
|
||||
|
||||
pub struct Store {
|
||||
file: PathBuf,
|
||||
}
|
||||
|
||||
/// The local time `t` (Unix seconds) one day, a weekday or a week on, at the same wall time.
|
||||
fn step(t: i64, repeat: &str) -> i64 {
|
||||
let local = Local.timestamp_opt(t, 0).single().unwrap_or_else(Local::now);
|
||||
let wall = local.naive_local();
|
||||
let mut day = wall.date();
|
||||
loop {
|
||||
day = day.succ_opt().unwrap_or(day);
|
||||
let ok = match repeat {
|
||||
"weekdays" => !matches!(day.weekday(), Weekday::Sat | Weekday::Sun),
|
||||
"weekly" => day.weekday() == wall.weekday() && day != wall.date(),
|
||||
_ => true,
|
||||
};
|
||||
if ok {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let at = NaiveDateTime::new(day, wall.time());
|
||||
// A wall time a clock change skips is taken an hour later.
|
||||
Local.from_local_datetime(&at).earliest()
|
||||
.or_else(|| Local.from_local_datetime(&(at + chrono::Duration::hours(1))).earliest())
|
||||
.map(|d| d.timestamp()).unwrap_or(t + 86_400)
|
||||
}
|
||||
|
||||
fn is_weekend(t: i64) -> bool {
|
||||
Local.timestamp_opt(t, 0).single().is_some_and(|d| matches!(d.weekday(), Weekday::Sat | Weekday::Sun))
|
||||
}
|
||||
|
||||
/// The first time a schedule asked for `at` fires: `at` itself, the next weekday for `weekdays`,
|
||||
/// and for a repeating one that has passed, its first time after `now`.
|
||||
pub fn first_time(at: i64, repeat: &str, now: i64) -> i64 {
|
||||
let mut t = at;
|
||||
if repeat == "weekdays" && is_weekend(t) {
|
||||
t = step(t, repeat);
|
||||
}
|
||||
while repeat != "none" && t <= now {
|
||||
t = step(t, repeat);
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
/// What `take_due` hands out to deliver.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Due {
|
||||
pub item: Schedule,
|
||||
/// The time it was due (the item's `next` has moved on for a repeating one).
|
||||
pub due: i64,
|
||||
}
|
||||
|
||||
impl Store {
|
||||
pub fn new(data: &Path) -> Self {
|
||||
Self { file: data.join("config").join("schedules.json") }
|
||||
}
|
||||
|
||||
fn load(&self) -> Result<File, String> {
|
||||
match std::fs::read_to_string(&self.file) {
|
||||
Ok(t) => serde_json::from_str(&t).map_err(|e| format!("예약 파일을 읽을 수 없습니다: {e}")),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(File::default()),
|
||||
Err(e) => Err(format!("예약 파일을 읽을 수 없습니다: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
fn save(&self, f: &File) -> Result<(), String> {
|
||||
let mut text = serde_json::to_string_pretty(f).unwrap();
|
||||
text.push('\n');
|
||||
crate::datadir::write_atomic(&self.file, text.as_bytes()).map_err(|e| format!("예약 파일을 쓸 수 없습니다: {e}"))
|
||||
}
|
||||
|
||||
fn change<T>(&self, f: impl FnOnce(&mut File) -> Result<T, String>) -> Result<T, String> {
|
||||
let _g = FILE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut file = self.load()?;
|
||||
let out = f(&mut file)?;
|
||||
self.save(&file)?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Every schedule, soonest first (those that will not fire again last).
|
||||
pub fn all(&self) -> Result<Vec<Schedule>, String> {
|
||||
let _g = FILE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut items = self.load()?.items;
|
||||
items.sort_by_key(|i| (i.next.is_none(), i.next, i.id));
|
||||
Ok(items)
|
||||
}
|
||||
|
||||
/// One person's schedules, soonest first.
|
||||
pub fn of(&self, user: u64) -> Result<Vec<Schedule>, String> {
|
||||
Ok(self.all()?.into_iter().filter(|i| i.user == user).collect())
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn add(&self, user: u64, name: &str, kind: &str, text: &str, at: i64, repeat: &str, via: &str,
|
||||
channel: Option<u64>, now: i64) -> Result<Schedule, String> {
|
||||
let text = text.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
if text.is_empty() || text.chars().count() > MAX_TEXT_CHARS {
|
||||
return Err(format!("text must be 1-{MAX_TEXT_CHARS} characters"));
|
||||
}
|
||||
if !["remind", "task"].contains(&kind) {
|
||||
return Err("kind must be remind or task".into());
|
||||
}
|
||||
if !["none", "daily", "weekdays", "weekly"].contains(&repeat) {
|
||||
return Err("repeat must be none, daily, weekdays or weekly".into());
|
||||
}
|
||||
let channel = match via {
|
||||
"voice" => None,
|
||||
"chat" => Some(channel.ok_or("a chat schedule needs the channel it was asked in")?),
|
||||
_ => return Err("via must be voice or chat".into()),
|
||||
};
|
||||
if repeat == "none" && at <= now {
|
||||
return Err("that time has already passed".into());
|
||||
}
|
||||
let next = first_time(at, repeat, now);
|
||||
self.change(|f| {
|
||||
if f.items.iter().filter(|i| i.user == user && i.next.is_some()).count() >= PER_PERSON {
|
||||
return Err(format!("at most {PER_PERSON} schedules per person; delete one first"));
|
||||
}
|
||||
f.next_id += 1;
|
||||
let item = Schedule { id: f.next_id, user, name: name.to_owned(), kind: kind.into(), text,
|
||||
repeat: repeat.into(), next: Some(next), via: via.into(), channel, created: now, last: None };
|
||||
f.items.push(item.clone());
|
||||
Ok(item)
|
||||
})
|
||||
}
|
||||
|
||||
/// Delete a schedule; with `user`, only one of theirs.
|
||||
pub fn delete(&self, id: u64, user: Option<u64>) -> Result<Schedule, String> {
|
||||
self.change(|f| {
|
||||
let pos = f.items.iter().position(|i| i.id == id && user.is_none_or(|u| u == i.user))
|
||||
.ok_or_else(|| "no such schedule of this person".to_string())?;
|
||||
Ok(f.items.remove(pos))
|
||||
})
|
||||
}
|
||||
|
||||
/// The schedules due at `now`. A repeating one moves on to its next time; a one-off one stops
|
||||
/// (`next` None) until `finished` records how it went. One more than `GRACE_SECS` late is not
|
||||
/// handed out and is recorded as missed.
|
||||
pub fn take_due(&self, now: i64) -> Result<Vec<Due>, String> {
|
||||
let _g = FILE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut file = self.load()?;
|
||||
let mut due = vec![];
|
||||
let mut changed = false;
|
||||
for item in file.items.iter_mut() {
|
||||
let Some(t) = item.next.filter(|t| *t <= now) else { continue };
|
||||
changed = true;
|
||||
item.next = (item.repeat != "none").then(|| first_time(t, &item.repeat, now));
|
||||
if now - t > GRACE_SECS {
|
||||
item.last = Some(Outcome { at: now, ok: false, note: Some("앱이 꺼져 있어 제때 전하지 못함".into()) });
|
||||
crate::warn_log!("schedule", "Warning: schedule {} missed ({} s late)", item.id, now - t);
|
||||
} else {
|
||||
due.push(Due { item: item.clone(), due: t });
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
self.save(&file)?;
|
||||
}
|
||||
Ok(due)
|
||||
}
|
||||
|
||||
/// Record how a delivery went. A one-off schedule delivered is removed; one that failed stays
|
||||
/// (not firing again) so the screen shows it.
|
||||
pub fn finished(&self, id: u64, outcome: Outcome) -> Result<(), String> {
|
||||
self.change(|f| {
|
||||
if let Some(pos) = f.items.iter().position(|i| i.id == id) {
|
||||
if outcome.ok && f.items[pos].next.is_none() {
|
||||
f.items.remove(pos);
|
||||
} else {
|
||||
f.items[pos].last = Some(outcome);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A schedule as the brain's tool sees it.
|
||||
pub fn brain_item(s: &Schedule) -> Value {
|
||||
json!({"id": s.id.to_string(), "kind": s.kind, "text": s.text, "repeat": s.repeat,
|
||||
"next": s.next.map(|t| t as f64)})
|
||||
}
|
||||
|
||||
/// Do what the brain's schedule tool asked for the person in `a.user` (named `name`): the item(s)
|
||||
/// for its result, or why not.
|
||||
pub fn act(store: &Store, a: &ScheduleAction, name: &str, now: i64) -> Result<Value, String> {
|
||||
let user: u64 = a.user.parse().map_err(|_| "bad user id".to_string())?;
|
||||
match a.action.as_str() {
|
||||
"list" => Ok(json!({"items": store.of(user)?.iter().filter(|s| s.next.is_some()).map(brain_item).collect::<Vec<_>>()})),
|
||||
"delete" => {
|
||||
let id: u64 = a.schedule.as_deref().and_then(|s| s.trim().parse().ok()).ok_or("delete needs the schedule's id")?;
|
||||
Ok(json!({"item": brain_item(&store.delete(id, Some(user))?)}))
|
||||
}
|
||||
"add" => {
|
||||
let at = a.at.filter(|t| t.is_finite()).ok_or("add needs at")?;
|
||||
let channel = a.channel.as_deref().and_then(|c| c.parse().ok());
|
||||
let s = store.add(user, name, a.kind.as_deref().unwrap_or("remind"), a.text.as_deref().unwrap_or(""),
|
||||
at.round() as i64, a.repeat.as_deref().unwrap_or("none"), &a.via, channel, now)?;
|
||||
crate::info_log!("schedule", "schedule {} added: {} {} by {user}", s.id, s.kind, s.repeat);
|
||||
Ok(json!({"item": brain_item(&s)}))
|
||||
}
|
||||
other => Err(format!("unknown schedule action {other}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// What the loop needs to deliver (the Discord core; a fake in tests).
|
||||
#[async_trait::async_trait]
|
||||
pub trait Deliver: Send + Sync {
|
||||
/// The person is in Jarvis's voice channel.
|
||||
fn hears(&self, user: u64) -> bool;
|
||||
/// Speak in the voice channel; false when not in one.
|
||||
fn say(&self, text: &str) -> bool;
|
||||
/// Post in a registered chat channel (never pinging anyone).
|
||||
async fn post(&self, channel: u64, text: &str) -> Result<(), String>;
|
||||
/// Run a task in the brain (read-only tools) and wait for its answer.
|
||||
async fn task(&self, id: &str, user: u64, text: &str) -> Option<String>;
|
||||
}
|
||||
|
||||
/// Deliver one due schedule: a task runs first; then by voice when it was asked by voice and the
|
||||
/// person is in Jarvis's voice channel, else in the chat channel it was asked in, or for voice the
|
||||
/// fallback channel (`schedule.chatChannel`).
|
||||
pub async fn deliver(d: &dyn Deliver, due: &Due, fallback: Option<u64>) -> Outcome {
|
||||
let s = &due.item;
|
||||
let now = || chrono::Utc::now().timestamp();
|
||||
let fail = |note: &str| Outcome { at: now(), ok: false, note: Some(note.into()) };
|
||||
let body = if s.kind == "task" {
|
||||
match d.task(&format!("s{}-{}", s.id, due.due), s.user, &s.text).await {
|
||||
Some(a) if !a.trim().is_empty() => a,
|
||||
_ => return fail("작업 결과를 만들지 못함"),
|
||||
}
|
||||
} else {
|
||||
s.text.clone()
|
||||
};
|
||||
let text = format!("{}님, {}", s.name, body.trim());
|
||||
if s.via == "voice" && d.hears(s.user) && d.say(&text) {
|
||||
crate::debug_log!("schedule", "schedule {} spoken chars={}", s.id, text.chars().count());
|
||||
return Outcome { at: now(), ok: true, note: None };
|
||||
}
|
||||
let Some(channel) = (if s.via == "chat" { s.channel } else { fallback }) else {
|
||||
return fail("음성 채널에 없고 알림 채팅 채널이 정해지지 않음");
|
||||
};
|
||||
match d.post(channel, &text).await {
|
||||
Ok(()) => {
|
||||
crate::debug_log!("schedule", "schedule {} posted in {channel} chars={}", s.id, text.chars().count());
|
||||
Outcome { at: now(), ok: true, note: None }
|
||||
}
|
||||
Err(e) => {
|
||||
crate::warn_log!("schedule", "Warning: schedule {} could not be posted in {channel}: {e}", s.id);
|
||||
fail("채팅 채널에 보내지 못함")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Fire due schedules until the task is aborted. Each delivery runs on its own, so a slow task does
|
||||
/// not hold up a reminder due meanwhile.
|
||||
pub async fn run(store: std::sync::Arc<Store>, d: std::sync::Arc<dyn Deliver>, fallback: Option<u64>) {
|
||||
loop {
|
||||
match store.take_due(chrono::Utc::now().timestamp()) {
|
||||
Ok(due) => for item in due {
|
||||
let (store, d) = (store.clone(), d.clone());
|
||||
tokio::spawn(async move {
|
||||
let out = deliver(d.as_ref(), &item, fallback).await;
|
||||
crate::info_log!("schedule", "schedule {} {}", item.item.id, if out.ok { "delivered" } else { "not delivered" });
|
||||
if let Err(e) = store.finished(item.item.id, out) {
|
||||
crate::warn_log!("schedule", "Warning: {e}");
|
||||
}
|
||||
});
|
||||
},
|
||||
Err(e) => {
|
||||
crate::warn_log!("schedule", "Warning: {e}");
|
||||
}
|
||||
}
|
||||
tokio::time::sleep(TICK).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use chrono::Timelike;
|
||||
|
||||
fn local(y: i32, mo: u32, d: u32, h: u32, mi: u32) -> i64 {
|
||||
Local.with_ymd_and_hms(y, mo, d, h, mi, 0).earliest().unwrap().timestamp()
|
||||
}
|
||||
|
||||
fn store() -> Store {
|
||||
Store::new(&crate::datadir::temp_dir("schedule"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeats_keep_the_wall_time_and_skip_what_they_leave_out() {
|
||||
// 2026-11-13 is a Friday.
|
||||
let fri = local(2026, 11, 13, 9, 0);
|
||||
assert_eq!(step(fri, "daily"), local(2026, 11, 14, 9, 0));
|
||||
assert_eq!(step(fri, "weekdays"), local(2026, 11, 16, 9, 0));
|
||||
assert_eq!(step(fri, "weekly"), local(2026, 11, 20, 9, 0));
|
||||
// Asked for a Saturday on weekdays: Monday. A daily one that passed: its next time.
|
||||
assert_eq!(first_time(local(2026, 11, 14, 9, 0), "weekdays", 0), local(2026, 11, 16, 9, 0));
|
||||
assert_eq!(first_time(fri, "daily", local(2026, 11, 15, 10, 0)), local(2026, 11, 16, 9, 0));
|
||||
assert_eq!(Local.timestamp_opt(step(fri, "daily"), 0).unwrap().hour(), 9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_person_sees_and_deletes_only_their_own() {
|
||||
let s = store();
|
||||
let a = s.add(1, "가", "remind", " 회의 준비 ", 2000, "none", "voice", None, 1000).unwrap();
|
||||
let b = s.add(2, "나", "task", "날씨", 3000, "daily", "chat", Some(77), 1000).unwrap();
|
||||
assert_eq!(a.text, "회의 준비");
|
||||
assert_eq!(s.of(1).unwrap(), vec![a.clone()]);
|
||||
assert!(s.delete(b.id, Some(1)).is_err());
|
||||
assert_eq!(s.delete(b.id, None).unwrap(), b);
|
||||
assert_eq!(s.all().unwrap(), vec![a]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_adds_are_refused() {
|
||||
let s = store();
|
||||
for (kind, text, at, repeat, via, channel) in [
|
||||
("remind", "", 2000, "none", "voice", None),
|
||||
("remind", "x", 500, "none", "voice", None),
|
||||
("alarm", "x", 2000, "none", "voice", None),
|
||||
("remind", "x", 2000, "hourly", "voice", None),
|
||||
("remind", "x", 2000, "none", "chat", None),
|
||||
] {
|
||||
assert!(s.add(1, "가", kind, text, at, repeat, via, channel, 1000).is_err(), "{kind} {text} {repeat} {via}");
|
||||
}
|
||||
assert!(s.add(1, "가", "remind", &"x".repeat(MAX_TEXT_CHARS + 1), 2000, "none", "voice", None, 1000).is_err());
|
||||
for _ in 0..PER_PERSON {
|
||||
s.add(1, "가", "remind", "x", 2000, "none", "voice", None, 1000).unwrap();
|
||||
}
|
||||
assert!(s.add(1, "가", "remind", "x", 2000, "none", "voice", None, 1000).is_err());
|
||||
assert!(s.add(2, "나", "remind", "x", 2000, "none", "voice", None, 1000).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn due_schedules_are_handed_out_once_and_late_ones_are_recorded_as_missed() {
|
||||
let s = store();
|
||||
let once = s.add(1, "가", "remind", "a", 2000, "none", "voice", None, 1000).unwrap();
|
||||
let daily = s.add(1, "가", "remind", "b", local(2026, 11, 13, 9, 0), "daily", "voice", None, 0).unwrap();
|
||||
let late = s.add(1, "가", "remind", "c", 1500, "none", "voice", None, 1000).unwrap();
|
||||
assert!(s.take_due(1499).unwrap().is_empty());
|
||||
let now = local(2026, 11, 13, 9, 1);
|
||||
let got: Vec<u64> = s.take_due(now).unwrap().into_iter().map(|d| d.item.id).collect();
|
||||
// `once` and `late` were due long before `now`: missed. The daily one moves to tomorrow.
|
||||
assert_eq!(got, vec![daily.id]);
|
||||
assert!(s.take_due(now).unwrap().is_empty());
|
||||
let all = s.all().unwrap();
|
||||
let find = |id| all.iter().find(|i| i.id == id).unwrap().clone();
|
||||
assert_eq!(find(daily.id).next, Some(local(2026, 11, 14, 9, 0)));
|
||||
for id in [once.id, late.id] {
|
||||
let i = find(id);
|
||||
assert_eq!(i.next, None);
|
||||
assert!(!i.last.unwrap().ok);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_delivered_one_off_schedule_is_removed_and_a_failed_one_kept() {
|
||||
let s = store();
|
||||
let a = s.add(1, "가", "remind", "a", 2000, "none", "voice", None, 1000).unwrap();
|
||||
let b = s.add(1, "가", "remind", "b", 2000, "none", "voice", None, 1000).unwrap();
|
||||
assert_eq!(s.take_due(2000).unwrap().len(), 2);
|
||||
s.finished(a.id, Outcome { at: 2001, ok: true, note: None }).unwrap();
|
||||
s.finished(b.id, Outcome { at: 2001, ok: false, note: Some("x".into()) }).unwrap();
|
||||
let all = s.all().unwrap();
|
||||
assert_eq!(all.len(), 1);
|
||||
assert_eq!(all[0].id, b.id);
|
||||
assert!(!all[0].last.as_ref().unwrap().ok);
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Fake {
|
||||
hears: bool,
|
||||
said: Mutex<Vec<String>>,
|
||||
posted: Mutex<Vec<(u64, String)>>,
|
||||
post_fails: bool,
|
||||
answer: Option<String>,
|
||||
tasks: Mutex<Vec<(u64, String)>>,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl Deliver for Fake {
|
||||
fn hears(&self, _user: u64) -> bool {
|
||||
self.hears
|
||||
}
|
||||
fn say(&self, text: &str) -> bool {
|
||||
self.said.lock().unwrap().push(text.into());
|
||||
true
|
||||
}
|
||||
async fn post(&self, channel: u64, text: &str) -> Result<(), String> {
|
||||
if self.post_fails {
|
||||
return Err("no".into());
|
||||
}
|
||||
self.posted.lock().unwrap().push((channel, text.into()));
|
||||
Ok(())
|
||||
}
|
||||
async fn task(&self, _id: &str, user: u64, text: &str) -> Option<String> {
|
||||
self.tasks.lock().unwrap().push((user, text.into()));
|
||||
self.answer.clone()
|
||||
}
|
||||
}
|
||||
|
||||
fn due(kind: &str, via: &str, channel: Option<u64>) -> Due {
|
||||
Due { item: Schedule { id: 1, user: 5, name: "철수".into(), kind: kind.into(), text: "회의".into(),
|
||||
repeat: "none".into(), next: None, via: via.into(), channel, created: 0, last: None }, due: 10 }
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_voice_reminder_is_spoken_to_someone_there_and_posted_otherwise() {
|
||||
let f = Fake { hears: true, ..Default::default() };
|
||||
assert!(deliver(&f, &due("remind", "voice", None), Some(9)).await.ok);
|
||||
assert_eq!(*f.said.lock().unwrap(), vec!["철수님, 회의".to_string()]);
|
||||
let away = Fake::default();
|
||||
assert!(deliver(&away, &due("remind", "voice", None), Some(9)).await.ok);
|
||||
assert_eq!(*away.posted.lock().unwrap(), vec![(9, "철수님, 회의".to_string())]);
|
||||
// Nowhere to go: not delivered, and says why.
|
||||
let out = deliver(&away, &due("remind", "voice", None), None).await;
|
||||
assert!(!out.ok && out.note.is_some());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_chat_reminder_goes_to_its_channel_even_when_the_person_is_in_voice() {
|
||||
let f = Fake { hears: true, ..Default::default() };
|
||||
assert!(deliver(&f, &due("remind", "chat", Some(77)), Some(9)).await.ok);
|
||||
assert!(f.said.lock().unwrap().is_empty());
|
||||
assert_eq!(*f.posted.lock().unwrap(), vec![(77, "철수님, 회의".to_string())]);
|
||||
let fails = Fake { post_fails: true, ..Default::default() };
|
||||
assert!(!deliver(&fails, &due("remind", "chat", Some(77)), None).await.ok);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_task_delivers_the_brains_answer_and_fails_without_one() {
|
||||
let f = Fake { answer: Some("맑아요".into()), ..Default::default() };
|
||||
assert!(deliver(&f, &due("task", "chat", Some(77)), None).await.ok);
|
||||
assert_eq!(*f.tasks.lock().unwrap(), vec![(5, "회의".to_string())]);
|
||||
assert_eq!(*f.posted.lock().unwrap(), vec![(77, "철수님, 맑아요".to_string())]);
|
||||
let none = Fake::default();
|
||||
let out = deliver(&none, &due("task", "chat", Some(77)), None).await;
|
||||
assert!(!out.ok && none.posted.lock().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_brains_actions_are_done_for_the_asker_only() {
|
||||
let s = store();
|
||||
let a = |action: &str, user: &str, extra: Value| -> ScheduleAction {
|
||||
let mut v = json!({"id": "x", "action": action, "user": user, "via": "voice"});
|
||||
v.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
|
||||
serde_json::from_value(v).unwrap()
|
||||
};
|
||||
let added = act(&s, &a("add", "1", json!({"kind": "remind", "text": "물", "at": 2000.4, "repeat": "none"})), "가", 1000).unwrap();
|
||||
assert_eq!(added["item"]["id"], "1");
|
||||
assert_eq!(added["item"]["next"], 2000.0);
|
||||
assert_eq!(act(&s, &a("list", "2", json!({})), "나", 1000).unwrap()["items"], json!([]));
|
||||
assert!(act(&s, &a("delete", "2", json!({"schedule": "1"})), "나", 1000).is_err());
|
||||
assert_eq!(act(&s, &a("list", "1", json!({})), "가", 1000).unwrap()["items"].as_array().unwrap().len(), 1);
|
||||
assert!(act(&s, &a("delete", "1", json!({"schedule": "1"})), "가", 1000).is_ok());
|
||||
assert!(act(&s, &a("add", "1", json!({"text": "x", "at": 2000.0, "via": "chat"})), "가", 1000).is_err());
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,8 @@ pub struct Services {
|
||||
pub game: Arc<crate::game::GameWatch>,
|
||||
/// Moves the LLM between the performance stages as games come and go.
|
||||
pub perf: std::sync::Mutex<Option<tokio::task::JoinHandle<()>>>,
|
||||
/// Fires the reminders and scheduled tasks (admin.spec.md, "Schedules").
|
||||
pub schedules: std::sync::Mutex<Option<tokio::task::JoinHandle<()>>>,
|
||||
}
|
||||
|
||||
/// The bot browser of a run (admin.spec.md, "Bot browser").
|
||||
@@ -68,6 +70,11 @@ impl Services {
|
||||
p.abort();
|
||||
let _ = p.await;
|
||||
}
|
||||
let schedules = self.schedules.lock().unwrap().take();
|
||||
if let Some(s) = schedules {
|
||||
s.abort();
|
||||
let _ = s.await;
|
||||
}
|
||||
self.game.stop();
|
||||
self.core.close().await;
|
||||
self.worker.close();
|
||||
@@ -191,7 +198,10 @@ pub async fn start_services(data_dir: &Path, llm: Arc<Llm>) -> Result<Services,
|
||||
|
||||
let (calls, response) = (settings.call.clone(), settings.response.clone());
|
||||
let chat_calls = conversation::ChatCalls::from_settings(&settings);
|
||||
let schedule_channel = settings.schedule_channel;
|
||||
let (core, core_events) = DiscordCore::new(settings, token, worker.clone(), worker_events);
|
||||
let schedule_store = Arc::new(crate::schedule::Store::new(data_dir));
|
||||
core.set_schedules(schedule_store.clone());
|
||||
// Call detection and the response policy answer what is heard; every event still reaches `events`.
|
||||
let (out, events) = mpsc::unbounded_channel();
|
||||
let conv = Conversation::new(core.clone(), calls, response).with_chat(chat_calls);
|
||||
@@ -203,9 +213,11 @@ pub async fn start_services(data_dir: &Path, llm: Arc<Llm>) -> Result<Services,
|
||||
return Err(after_stop(&llm, &browser, e.to_string()).await.into());
|
||||
}
|
||||
crate::info_log!("app", "services started");
|
||||
let schedules = std::sync::Mutex::new(Some(tokio::spawn(crate::schedule::run(schedule_store,
|
||||
Arc::new(core.clone()), schedule_channel))));
|
||||
let on = { let g = game.clone(); Arc::new(move || g.on()) };
|
||||
let perf = std::sync::Mutex::new(Some(tokio::spawn(perf_loop(perf_settings, llm.clone(), Arc::new(worker.clone()), on, RETRY_AFTER))));
|
||||
Ok(Services { core, events, worker, worker_process, missed, llm, browser, game, perf })
|
||||
Ok(Services { core, events, worker, worker_process, missed, llm, browser, game, perf, schedules })
|
||||
}
|
||||
|
||||
/// The brain as the performance stages see it: told the LLM's state, and asked to finish what it is
|
||||
|
||||
@@ -98,6 +98,8 @@ pub struct FeatureSettings {
|
||||
/// The bot browser's window on a virtual monitor to share in Discord (admin.spec.md, "Virtual
|
||||
/// monitor"); off by default.
|
||||
pub browser_share: bool,
|
||||
/// Reminders and scheduled tasks (admin.spec.md, "Schedules").
|
||||
pub schedule: bool,
|
||||
}
|
||||
|
||||
/// Game detection (admin.spec.md, "Game detection"): on by default; the person's own games and
|
||||
@@ -174,6 +176,9 @@ pub struct Settings {
|
||||
pub mcp_servers: Vec<McpServerSettings>,
|
||||
pub collect: CollectSettings,
|
||||
pub game: GameSettings,
|
||||
/// The registered chat channel a schedule asked by voice is posted in when its person is not in
|
||||
/// Jarvis's voice channel (admin.spec.md, "Schedules"); None: not delivered then.
|
||||
pub schedule_channel: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
@@ -217,10 +222,11 @@ impl Default for Settings {
|
||||
response: PolicySettings::default(),
|
||||
memory: Map::new(),
|
||||
llm: LlmSettings { url: None, port: 8080, context: 32768 },
|
||||
features: FeatureSettings { weather: true, web_search: true, meals: true, collect: true, browser: true, browser_share: false },
|
||||
features: FeatureSettings { weather: true, web_search: true, meals: true, collect: true, browser: true, browser_share: false, schedule: true },
|
||||
mcp_servers: vec![],
|
||||
collect: CollectSettings { keep_days: 30, targets: vec![] },
|
||||
game: GameSettings { detect: true, games: vec![], not_games: vec![], other_room_gb: 1.0, reserve_gb: 8.0, revert_seconds: 30, pause_in_game: false },
|
||||
schedule_channel: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -496,6 +502,10 @@ pub fn parse_settings(raw: &Value) -> Result<Settings, SettingsError> {
|
||||
sync_discord: get_bool(Some(m), "syncDiscord", &path, true)?,
|
||||
});
|
||||
}
|
||||
let schedule_channel = opt_snowflake(section(raw, "schedule")?, "chatChannel", "schedule", None, "a Discord channel ID")?;
|
||||
if schedule_channel.is_some_and(|c| !chat_channels.iter().any(|x| x.id == c && x.send)) {
|
||||
return err("schedule.chatChannel must be a registered chat channel with sending on");
|
||||
}
|
||||
|
||||
Ok(Settings {
|
||||
discord: DiscordSettings {
|
||||
@@ -541,11 +551,13 @@ pub fn parse_settings(raw: &Value) -> Result<Settings, SettingsError> {
|
||||
collect: get_bool(f, "collect", "features", d.features.collect)?,
|
||||
browser: get_bool(f, "browser", "features", d.features.browser)?,
|
||||
browser_share: get_bool(f, "browserShare", "features", d.features.browser_share)?,
|
||||
schedule: get_bool(f, "schedule", "features", d.features.schedule)?,
|
||||
}
|
||||
},
|
||||
mcp_servers: parse_mcp_servers(raw)?,
|
||||
collect: parse_collect(raw, &d.collect)?,
|
||||
game: parse_game(raw, &d.game)?,
|
||||
schedule_channel,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -881,18 +893,26 @@ mod tests {
|
||||
#[test]
|
||||
fn features_and_mcp_servers_are_read_and_checked() {
|
||||
let s = parse_settings(&json!({}));
|
||||
assert_eq!(s.unwrap().features, FeatureSettings { weather: true, web_search: true, meals: true, collect: true, browser: true, browser_share: false });
|
||||
assert_eq!(s.unwrap().features, FeatureSettings { weather: true, web_search: true, meals: true, collect: true, browser: true, browser_share: false, schedule: true });
|
||||
let s = parse_settings(&json!({
|
||||
"features": {"weather": false, "meals": false, "browserShare": true},
|
||||
"features": {"weather": false, "meals": false, "browserShare": true, "schedule": false},
|
||||
"mcpServers": [{"name": "brave", "command": "npx", "args": ["-y", "brave"], "env": ["BRAVE_API_KEY", " "]},
|
||||
{"name": "time-2", "command": "uvx", "enabled": false}]
|
||||
})).unwrap();
|
||||
assert_eq!(s.features, FeatureSettings { weather: false, web_search: true, meals: false, collect: true, browser: true, browser_share: true });
|
||||
assert_eq!(s.features, FeatureSettings { weather: false, web_search: true, meals: false, collect: true, browser: true, browser_share: true, schedule: false });
|
||||
assert_eq!(s.mcp_servers, vec![
|
||||
McpServerSettings { name: "brave".into(), command: "npx".into(), args: vec!["-y".into(), "brave".into()],
|
||||
env: vec!["BRAVE_API_KEY".into()], enabled: true },
|
||||
McpServerSettings { name: "time-2".into(), command: "uvx".into(), args: vec![], env: vec![], enabled: false },
|
||||
]);
|
||||
// A schedule channel must be a registered one that Jarvis may send in.
|
||||
let ch = json!([{"id": "123456789012345678", "send": true}, {"id": "123456789012345679", "send": false}]);
|
||||
let s = parse_settings(&json!({"chatChannels": ch, "schedule": {"chatChannel": "123456789012345678"}})).unwrap();
|
||||
assert_eq!(s.schedule_channel, Some(123456789012345678));
|
||||
for c in ["123456789012345679", "123456789012345670"] {
|
||||
let e = parse_settings(&json!({"chatChannels": ch, "schedule": {"chatChannel": c}})).unwrap_err();
|
||||
assert!(e.0.contains("schedule.chatChannel"), "{e}");
|
||||
}
|
||||
let cases = [
|
||||
(json!({"features": {"weather": "no"}}), "features.weather"),
|
||||
(json!({"mcpServers": {}}), "mcpServers"),
|
||||
|
||||
@@ -22,6 +22,7 @@ pub enum Screen {
|
||||
Features,
|
||||
Collect,
|
||||
Game,
|
||||
Schedule,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
|
||||
@@ -126,10 +127,14 @@ pub fn fields() -> Vec<Field> {
|
||||
f("features.collect", Features, Bool, json!(true), "백그라운드 수집"),
|
||||
f("features.browser", Features, Bool, json!(true), "브라우저 제어(봇용 크롬)"),
|
||||
f("features.browserShare", Features, Bool, json!(false), "봇용 크롬창 화면공유 선택 표시(가상 모니터, Windows)"),
|
||||
f("features.schedule", Features, Bool, json!(true), "예약 알림과 정기 작업"),
|
||||
f("mcpServers", Features, McpServers, json!([]), "MCP 서버"),
|
||||
// Background collection (admin.spec.md, "Background collection"): no targets by default.
|
||||
f("collect.targets", Collect, CollectTargets, json!([]), "수집 대상"),
|
||||
f("collect.keepDays", Collect, Int { min: 1, max: 365 }, json!(30), "보관 기간(일)"),
|
||||
// Schedules (admin.spec.md, "Schedules").
|
||||
f("schedule.chatChannel", Schedule, Id, Value::Null,
|
||||
"음성으로 맡긴 알림을 그 사람이 음성 채널에 없을 때 보낼 채팅 채널(등록한 채널)"),
|
||||
// Game detection (admin.spec.md, "Game detection").
|
||||
f("game.detect", Game, Bool, json!(true), "게임 감지"),
|
||||
f("game.games", Game, TextList { max_items: 100, nullable: false }, json!([]), "게임으로 볼 프로그램(파일 이름, 예: MyGame.exe)"),
|
||||
|
||||
@@ -122,6 +122,30 @@ pub struct ChatAction {
|
||||
pub emoji: Option<String>,
|
||||
}
|
||||
|
||||
/// The brain's schedule tool asks the app for the person asking (voice_worker.spec.md, "Schedules").
|
||||
#[derive(Debug, Clone, Deserialize, PartialEq)]
|
||||
pub struct ScheduleAction {
|
||||
pub id: String,
|
||||
/// `add`, `list` or `delete`.
|
||||
pub action: String,
|
||||
pub user: String,
|
||||
/// `voice` or `chat`: where they asked.
|
||||
pub via: String,
|
||||
#[serde(default)]
|
||||
pub channel: Option<String>,
|
||||
#[serde(default)]
|
||||
pub kind: Option<String>,
|
||||
#[serde(default)]
|
||||
pub text: Option<String>,
|
||||
#[serde(default)]
|
||||
pub at: Option<f64>,
|
||||
#[serde(default)]
|
||||
pub repeat: Option<String>,
|
||||
/// delete: the schedule's id.
|
||||
#[serde(default)]
|
||||
pub schedule: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum WorkerEvent {
|
||||
Ready(HelloOk),
|
||||
@@ -132,6 +156,7 @@ pub enum WorkerEvent {
|
||||
TtsAudio { id: String, seq: u32, pcm: Vec<u8> },
|
||||
TtsDone(TtsDone),
|
||||
ChatAction(ChatAction),
|
||||
ScheduleAction(ScheduleAction),
|
||||
/// The brain's answer to `reply` (empty and `failed` when it gave none).
|
||||
ReplyText { id: String, text: String, failed: bool },
|
||||
/// Was the utterance said to Jarvis? (a failed judgement is a no)
|
||||
@@ -320,6 +345,21 @@ impl WorkerClient {
|
||||
self.send_json(v);
|
||||
}
|
||||
|
||||
/// The outcome of a `schedule_action`: `{item}` or `{items}`, or why it failed.
|
||||
pub fn schedule_action_result(&self, id: &str, result: Result<Value, String>) {
|
||||
let msg = match result {
|
||||
Ok(Value::Object(mut m)) => {
|
||||
m.insert("type".into(), json!("schedule_action_result"));
|
||||
m.insert("id".into(), json!(id));
|
||||
m.insert("ok".into(), json!(true));
|
||||
Value::Object(m)
|
||||
}
|
||||
Ok(_) => json!({"type": "schedule_action_result", "id": id, "ok": true}),
|
||||
Err(e) => json!({"type": "schedule_action_result", "id": id, "ok": false, "error": e}),
|
||||
};
|
||||
self.send_json(msg);
|
||||
}
|
||||
|
||||
pub fn chat_delete(&self, channel: u64, message: u64) {
|
||||
self.send_json(json!({"type": "chat_delete", "channel": channel.to_string(),
|
||||
"message_id": message.to_string()}));
|
||||
@@ -330,13 +370,23 @@ impl WorkerClient {
|
||||
/// Ask the brain to answer `user`. With `speak` the answer is spoken under `id` (its audio and
|
||||
/// `tts_done` come like a TTS request's); it ends as failed when it cannot be sent, the brain gives
|
||||
/// no answer, or the worker refuses it.
|
||||
/// `via`: `voice` or `chat` (the brain's history scope and where the answer is stored).
|
||||
/// `via`: `voice`, `chat` or `task` (a scheduled task: read-only tools, never spoken).
|
||||
pub fn reply(&self, id: &str, user: u64, text: &str, via: &str, speak: bool) -> bool {
|
||||
self.reply_in(id, user, text, via, speak, None)
|
||||
}
|
||||
|
||||
/// `reply`, naming the chat channel a chat message was written in (the brain's schedule tool
|
||||
/// delivers there).
|
||||
pub fn reply_in(&self, id: &str, user: u64, text: &str, via: &str, speak: bool, channel: Option<u64>) -> bool {
|
||||
if speak {
|
||||
self.inner.state.lock().unwrap().open_tts.insert(id.to_owned());
|
||||
}
|
||||
let sent = self.send_json(json!({"type": "reply", "id": id, "user": user.to_string(), "text": text,
|
||||
"via": via, "speak": speak}));
|
||||
let mut msg = json!({"type": "reply", "id": id, "user": user.to_string(), "text": text, "via": via,
|
||||
"speak": speak});
|
||||
if let Some(c) = channel {
|
||||
msg["channel"] = json!(c.to_string());
|
||||
}
|
||||
let sent = self.send_json(msg);
|
||||
if !sent && speak {
|
||||
self.end_failed(id);
|
||||
}
|
||||
@@ -580,6 +630,7 @@ fn on_text(inner: &Inner, t: &str) {
|
||||
"partial" => serde_json::from_value(v).ok().map(WorkerEvent::Partial),
|
||||
"final" => serde_json::from_value(v).ok().map(WorkerEvent::Final),
|
||||
"chat_action" => serde_json::from_value(v).ok().map(WorkerEvent::ChatAction),
|
||||
"schedule_action" => serde_json::from_value(v).ok().map(WorkerEvent::ScheduleAction),
|
||||
"llm_idle" => {
|
||||
if let Some(id) = v["id"].as_u64() {
|
||||
inner.llm_idle.send_if_modified(|got| if id > *got { *got = id; true } else { false });
|
||||
|
||||
Reference in New Issue
Block a user