feat(app): an activity log of what Jarvis did (chat actions, schedule deliveries)
Each chat channel action the brain's tool asked for and each schedule delivery is recorded in activity/<day>.jsonl by kind, target, who asked and outcome, never its text, kept 30 days. The worker's chat_action carries the asker. A 한 일 screen lists the newest entries. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
143
app/src/activity.rs
Normal file
143
app/src/activity.rs
Normal file
@@ -0,0 +1,143 @@
|
||||
//! What Jarvis did outside its answers (`app/src/admin.spec.md`, "Activity"; `docs/v2/proactive.md`
|
||||
//! 제안 5): chat channel actions and schedule deliveries, by kind, target, who asked and outcome,
|
||||
//! never their text. Day files `activity/<YYYY-MM-DD>.jsonl` in the data folder, kept `KEEP_DAYS`.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
|
||||
use chrono::{Local, NaiveDate};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub const KEEP_DAYS: i64 = 30;
|
||||
|
||||
static FILE_LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Entry {
|
||||
/// Local time, RFC 3339.
|
||||
pub at: String,
|
||||
/// What was done: `chat.send`, `chat.edit`, `chat.react`, `chat.delete`, `chat.pin`,
|
||||
/// `chat.unpin`, `schedule.remind`, `schedule.task`.
|
||||
pub kind: String,
|
||||
/// What it was done to: a channel or message id, or the schedule's id and where it went.
|
||||
pub target: String,
|
||||
/// Who asked (Discord user id and name), when known.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub by: Option<String>,
|
||||
pub ok: bool,
|
||||
/// Why it failed (never content).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub note: Option<String>,
|
||||
}
|
||||
|
||||
pub struct Activity {
|
||||
dir: PathBuf,
|
||||
}
|
||||
|
||||
fn day_name(d: NaiveDate) -> String {
|
||||
format!("{d}.jsonl")
|
||||
}
|
||||
|
||||
impl Activity {
|
||||
/// The log in `data`; day files older than `KEEP_DAYS` are deleted.
|
||||
pub fn new(data: &Path) -> Self {
|
||||
let a = Self { dir: data.join("activity") };
|
||||
a.prune(Local::now().date_naive());
|
||||
a
|
||||
}
|
||||
|
||||
fn days(&self) -> Vec<(NaiveDate, PathBuf)> {
|
||||
let mut out: Vec<(NaiveDate, PathBuf)> = std::fs::read_dir(&self.dir).into_iter().flatten().flatten()
|
||||
.filter_map(|e| {
|
||||
let name = e.file_name().to_str()?.to_owned();
|
||||
let d = NaiveDate::parse_from_str(name.strip_suffix(".jsonl")?, "%Y-%m-%d").ok()?;
|
||||
Some((d, e.path()))
|
||||
})
|
||||
.collect();
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
fn prune(&self, today: NaiveDate) {
|
||||
let _g = FILE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
for (d, f) in self.days() {
|
||||
if (today - d).num_days() > KEEP_DAYS {
|
||||
let _ = std::fs::remove_file(f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Append one entry (a failure to write is logged, never raised: the action itself happened).
|
||||
pub fn record(&self, kind: &str, target: &str, by: Option<String>, ok: bool, note: Option<String>) {
|
||||
let now = Local::now();
|
||||
let e = Entry { at: now.to_rfc3339_opts(chrono::SecondsFormat::Secs, false), kind: kind.into(),
|
||||
target: target.into(), by, ok, note };
|
||||
let _g = FILE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let file = self.dir.join(day_name(now.date_naive()));
|
||||
let line = serde_json::to_string(&e).unwrap() + "\n";
|
||||
let wrote = std::fs::create_dir_all(&self.dir).and_then(|_| {
|
||||
use std::io::Write;
|
||||
std::fs::OpenOptions::new().create(true).append(true).open(&file)?.write_all(line.as_bytes())
|
||||
});
|
||||
match wrote {
|
||||
Ok(()) => {
|
||||
crate::debug_log!("conversation", "activity {kind} ok={ok}");
|
||||
}
|
||||
Err(err) => {
|
||||
crate::warn_log!("conversation", "Warning: could not record activity {kind}: {err}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The newest `limit` entries, newest first.
|
||||
pub fn recent(&self, limit: usize) -> Vec<Entry> {
|
||||
let _g = FILE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut out = vec![];
|
||||
for (_, f) in self.days().into_iter().rev() {
|
||||
let text = std::fs::read_to_string(&f).unwrap_or_default();
|
||||
for line in text.lines().rev() {
|
||||
if let Ok(e) = serde_json::from_str::<Entry>(line) {
|
||||
out.push(e);
|
||||
if out.len() == limit {
|
||||
return out;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn entries_come_back_newest_first_up_to_the_limit() {
|
||||
let data = crate::datadir::temp_dir("activity");
|
||||
let a = Activity::new(&data);
|
||||
a.record("chat.send", "123", Some("1 가".into()), true, None);
|
||||
a.record("schedule.remind", "7 → 음성", None, false, Some("음성 채널에 없음".into()));
|
||||
let got = a.recent(10);
|
||||
assert_eq!(got.iter().map(|e| e.kind.as_str()).collect::<Vec<_>>(), ["schedule.remind", "chat.send"]);
|
||||
assert_eq!(got[1].by.as_deref(), Some("1 가"));
|
||||
assert!(!got[0].ok && got[0].note.is_some());
|
||||
assert_eq!(a.recent(1).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn day_files_past_the_keep_days_are_deleted() {
|
||||
let data = crate::datadir::temp_dir("activity-prune");
|
||||
let dir = data.join("activity");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let today = Local::now().date_naive();
|
||||
let old = today - chrono::Duration::days(KEEP_DAYS + 1);
|
||||
let kept = today - chrono::Duration::days(KEEP_DAYS);
|
||||
let line = r#"{"at":"x","kind":"chat.send","target":"1","ok":true}"#;
|
||||
std::fs::write(dir.join(day_name(old)), line).unwrap();
|
||||
std::fs::write(dir.join(day_name(kept)), line).unwrap();
|
||||
let a = Activity::new(&data);
|
||||
assert!(!dir.join(day_name(old)).exists());
|
||||
assert_eq!(a.recent(10).len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -161,6 +161,21 @@ decision 2026-11-14). What Jarvis may do on this PC and for whom; the PC control
|
||||
- The PC 제어 screen edits the section and shows, read-only, what is never done and each registered
|
||||
chat channel's send and delete switches (changed on the 채팅 채널 screen).
|
||||
|
||||
## Activity (`app/src/activity.rs`)
|
||||
|
||||
`docs/v2/proactive.md` (제안 5). What Jarvis did outside its answers, for the 한 일 screen: each chat
|
||||
channel action the brain's tool asked for (`chat.send`, `chat.edit`, `chat.react`, `chat.delete`,
|
||||
`chat.pin`, `chat.unpin`) and each schedule delivery (`schedule.remind`, `schedule.task`), done or
|
||||
failed. PC control actions join it with M7. Ordinary answers are not recorded.
|
||||
|
||||
- One JSON line per action in `activity/<YYYY-MM-DD>.jsonl` (the folder is made at the first one):
|
||||
`{at, kind, target, by, ok, note}`. `target` is the channel (and message) id or `예약 <id>`; `by`
|
||||
is who asked, `<user id> <name>` (the brain's `chat_action` carries the asker, voice_worker.spec.md);
|
||||
`note` is why it failed. **Never the text** of a message, reminder or answer.
|
||||
- Day files older than 30 days are deleted when the services or the screen open the log. A failed
|
||||
write is a warning in the log and never stops the action.
|
||||
- `activity_list` `{limit}` (1-1000, default 200) reads the newest first.
|
||||
|
||||
## Secrets (`app/src/secrets.rs`)
|
||||
|
||||
`config/secrets.dat` holds a JSON object of named secrets (`discordToken`, the MCP servers'
|
||||
@@ -554,6 +569,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) |
|
||||
| `activity_list` `{limit}` | what Jarvis did (above, "Activity"), newest first |
|
||||
| `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 |
|
||||
@@ -596,6 +612,8 @@ Plain HTML, CSS and an ES module, no build step, dark theme after `DESIGN.md`. A
|
||||
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 activity (time, kind, target, who asked, outcome and why it failed), newest 200,
|
||||
with a refresh button.
|
||||
- **업데이트**: 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.
|
||||
|
||||
@@ -366,6 +366,10 @@ impl AdminApi {
|
||||
v
|
||||
}).collect::<Vec<_>>()}))
|
||||
}
|
||||
"activity_list" => {
|
||||
let limit = args.get("limit").and_then(Value::as_u64).unwrap_or(200).clamp(1, 1000) as usize;
|
||||
Ok(json!({"items": crate::activity::Activity::new(self.dir()?.path()).recent(limit)}))
|
||||
}
|
||||
"schedule_delete" => {
|
||||
let id: u64 = arg_str(&args, "id")?.parse().map_err(|_| "예약 ID가 올바르지 않습니다")?;
|
||||
crate::schedule::Store::new(self.dir()?.path()).delete(id, None)?;
|
||||
@@ -491,6 +495,20 @@ mod tests {
|
||||
assert!(a.call("nope", json!({})).await.is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_activity_screen_reads_the_newest_entries() {
|
||||
let (a, base) = api("api-activity");
|
||||
let data = base.join("d");
|
||||
a.call("folder_choose", json!({"path": data.to_string_lossy()})).await.unwrap();
|
||||
assert_eq!(a.call("activity_list", json!({})).await.unwrap()["items"], json!([]));
|
||||
let log = crate::activity::Activity::new(&data);
|
||||
log.record("chat.send", "채널 1", None, true, None);
|
||||
log.record("chat.delete", "채널 1 메시지 2", Some("9 가".into()), false, Some("no".into()));
|
||||
let items = a.call("activity_list", json!({"limit": 1})).await.unwrap()["items"].clone();
|
||||
assert_eq!(items.as_array().unwrap().len(), 1);
|
||||
assert_eq!(items[0]["kind"], "chat.delete");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_schedule_screen_lists_everyones_schedules_and_deletes_any() {
|
||||
let (a, base) = api("api-schedule");
|
||||
|
||||
@@ -203,6 +203,8 @@ struct Inner {
|
||||
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>>>,
|
||||
/// What Jarvis did outside its answers (admin.spec.md, "Activity").
|
||||
activity: OnceLock<Arc<crate::activity::Activity>>,
|
||||
/// Speech requests whose end someone waits for (`say_to_end`), by request id.
|
||||
speech_waits: Mutex<HashMap<String, tokio::sync::oneshot::Sender<PlaybackEnd>>>,
|
||||
}
|
||||
@@ -276,6 +278,7 @@ impl DiscordCore {
|
||||
schedules: OnceLock::new(),
|
||||
tasks: Mutex::new(HashMap::new()),
|
||||
speech_waits: Mutex::new(HashMap::new()),
|
||||
activity: OnceLock::new(),
|
||||
});
|
||||
tokio::spawn(player_task(Arc::downgrade(&inner), player_rx));
|
||||
tokio::spawn(worker_task(Arc::downgrade(&inner), worker_events));
|
||||
@@ -532,6 +535,11 @@ impl DiscordCore {
|
||||
let _ = self.inner.schedules.set(store);
|
||||
}
|
||||
|
||||
/// The activity log chat actions are recorded in.
|
||||
pub fn set_activity(&self, activity: Arc<crate::activity::Activity>) {
|
||||
let _ = self.inner.activity.set(activity);
|
||||
}
|
||||
|
||||
/// 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();
|
||||
@@ -882,6 +890,18 @@ async fn worker_task(core: std::sync::Weak<Inner>, mut rx: mpsc::UnboundedReceiv
|
||||
if let Err(e) = &result {
|
||||
debug_log!("chat", "chat {} {} failed: {e}", a.action, a.id);
|
||||
}
|
||||
if let Some(activity) = core.inner.activity.get() {
|
||||
let target = match &a.message_id {
|
||||
Some(m) => format!("채널 {} 메시지 {m}", a.channel),
|
||||
None => format!("채널 {}", a.channel),
|
||||
};
|
||||
let by = a.user.as_ref().map(|u| match u.parse() {
|
||||
Ok(id) => format!("{u} {}", name_of(&core.inner, id)),
|
||||
Err(_) => u.clone(),
|
||||
});
|
||||
activity.record(&format!("chat.{}", a.action), &target, by, result.is_ok(),
|
||||
result.as_ref().err().cloned());
|
||||
}
|
||||
core.inner.worker.chat_action_result(&a.id, result);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Jarvis v2 app core (see `app/src/discord_core.spec.md`).
|
||||
|
||||
pub mod log;
|
||||
pub mod activity;
|
||||
pub mod admin_api;
|
||||
pub mod browser;
|
||||
pub mod calls;
|
||||
|
||||
@@ -351,10 +351,23 @@ pub async fn deliver(d: &dyn Deliver, due: &Due, fallback: Option<u64>) -> Outco
|
||||
}
|
||||
}
|
||||
|
||||
/// Record how a delivery went: in the store (its outcome) and in the activity log (kind, id, who
|
||||
/// asked and the outcome; never the text).
|
||||
pub fn finish(store: &Store, activity: &crate::activity::Activity, due: &Due, out: Outcome) {
|
||||
let s = &due.item;
|
||||
crate::info_log!("schedule", "schedule {} {}", s.id, if out.ok { "delivered" } else { "not delivered" });
|
||||
activity.record(&format!("schedule.{}", s.kind), &format!("예약 {}", s.id), Some(format!("{} {}", s.user, s.name)),
|
||||
out.ok, out.note.clone());
|
||||
if let Err(e) = store.finished(s.id, out) {
|
||||
crate::warn_log!("schedule", "Warning: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// 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; aborting the loop aborts the deliveries it started (they
|
||||
/// are recorded as interrupted at the next start, `recover`).
|
||||
pub async fn run(store: std::sync::Arc<Store>, d: std::sync::Arc<dyn Deliver>, fallback: Option<u64>) {
|
||||
pub async fn run(store: std::sync::Arc<Store>, activity: std::sync::Arc<crate::activity::Activity>,
|
||||
d: std::sync::Arc<dyn Deliver>, fallback: Option<u64>) {
|
||||
if let Err(e) = store.recover(chrono::Utc::now().timestamp()) {
|
||||
crate::warn_log!("schedule", "Warning: {e}");
|
||||
}
|
||||
@@ -363,13 +376,10 @@ pub async fn run(store: std::sync::Arc<Store>, d: std::sync::Arc<dyn Deliver>, f
|
||||
while deliveries.try_join_next().is_some() {}
|
||||
match store.take_due(chrono::Utc::now().timestamp()) {
|
||||
Ok(due) => for item in due {
|
||||
let (store, d) = (store.clone(), d.clone());
|
||||
let (store, activity, d) = (store.clone(), activity.clone(), d.clone());
|
||||
deliveries.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}");
|
||||
}
|
||||
finish(&store, &activity, &item, out);
|
||||
});
|
||||
},
|
||||
Err(e) => {
|
||||
@@ -566,6 +576,23 @@ mod tests {
|
||||
assert_eq!(s.recover(3001).unwrap(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_delivery_is_recorded_in_the_activity_without_its_text() {
|
||||
let data = crate::datadir::temp_dir("schedule-activity");
|
||||
let s = Store::new(&data);
|
||||
let a = crate::activity::Activity::new(&data);
|
||||
let item = s.add(5, "철수", "remind", "비밀 회의", 2000, "none", "voice", None, 1000).unwrap();
|
||||
let due = s.take_due(2000).unwrap().remove(0);
|
||||
finish(&s, &a, &due, Outcome { at: 2001, ok: false, note: Some("채팅 채널에 보내지 못함".into()) });
|
||||
let got = a.recent(10);
|
||||
assert_eq!(got.len(), 1);
|
||||
assert_eq!((got[0].kind.as_str(), got[0].ok), ("schedule.remind", false));
|
||||
assert_eq!(got[0].by.as_deref(), Some("5 철수"));
|
||||
assert!(got[0].target.contains(&item.id.to_string()));
|
||||
assert!(!serde_json::to_string(&got[0]).unwrap().contains("비밀"), "no text in the activity");
|
||||
assert!(!s.all().unwrap()[0].last.as_ref().unwrap().ok, "the outcome is kept too");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stopping_the_loop_stops_the_deliveries_it_started() {
|
||||
let data = crate::datadir::temp_dir("schedule-run");
|
||||
@@ -573,7 +600,7 @@ mod tests {
|
||||
let now = chrono::Utc::now().timestamp();
|
||||
s.add(1, "가", "task", "x", now + 1, "none", "chat", Some(77), now).unwrap();
|
||||
let f = Arc::new(Fake { hang: true, ..Default::default() });
|
||||
let run = tokio::spawn(run(s.clone(), f.clone(), None));
|
||||
let run = tokio::spawn(run(s.clone(), Arc::new(crate::activity::Activity::new(&data)), f.clone(), None));
|
||||
let hung = f.hung.clone();
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
while !hung.load(std::sync::atomic::Ordering::SeqCst) {
|
||||
|
||||
@@ -202,6 +202,8 @@ pub async fn start_services(data_dir: &Path, llm: Arc<Llm>) -> Result<Services,
|
||||
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());
|
||||
let activity = Arc::new(crate::activity::Activity::new(data_dir));
|
||||
core.set_activity(activity.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);
|
||||
@@ -213,7 +215,7 @@ 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,
|
||||
let schedules = std::sync::Mutex::new(Some(tokio::spawn(crate::schedule::run(schedule_store, activity,
|
||||
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))));
|
||||
|
||||
@@ -120,6 +120,9 @@ pub struct ChatAction {
|
||||
pub text: Option<String>,
|
||||
#[serde(default)]
|
||||
pub emoji: Option<String>,
|
||||
/// Who asked (for the activity log).
|
||||
#[serde(default)]
|
||||
pub user: Option<String>,
|
||||
}
|
||||
|
||||
/// The brain's schedule tool asks the app for the person asking (voice_worker.spec.md, "Schedules").
|
||||
|
||||
Reference in New Issue
Block a user