diff --git a/app/src/activity.rs b/app/src/activity.rs new file mode 100644 index 0000000..1ec48cf --- /dev/null +++ b/app/src/activity.rs @@ -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/.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, + pub ok: bool, + /// Why it failed (never content). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub note: Option, +} + +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, ok: bool, note: Option) { + 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 { + 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::(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::>(), ["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); + } +} diff --git a/app/src/admin.spec.md b/app/src/admin.spec.md index a1c6a50..7b97764 100644 --- a/app/src/admin.spec.md +++ b/app/src/admin.spec.md @@ -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/.jsonl` (the folder is made at the first one): + `{at, kind, target, by, ok, note}`. `target` is the channel (and message) id or `예약 `; `by` + is who asked, ` ` (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. diff --git a/app/src/admin_api.rs b/app/src/admin_api.rs index 3df5fc3..0c5a073 100644 --- a/app/src/admin_api.rs +++ b/app/src/admin_api.rs @@ -366,6 +366,10 @@ impl AdminApi { v }).collect::>()})) } + "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"); diff --git a/app/src/discord.rs b/app/src/discord.rs index 945467d..be2a649 100644 --- a/app/src/discord.rs +++ b/app/src/discord.rs @@ -203,6 +203,8 @@ struct Inner { schedules: OnceLock>, /// Scheduled tasks waiting for the brain's answer, by reply id. tasks: Mutex>>, + /// What Jarvis did outside its answers (admin.spec.md, "Activity"). + activity: OnceLock>, /// Speech requests whose end someone waits for (`say_to_end`), by request id. speech_waits: Mutex>>, } @@ -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) { + 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 { let (tx, rx) = tokio::sync::oneshot::channel(); @@ -882,6 +890,18 @@ async fn worker_task(core: std::sync::Weak, 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); }); } diff --git a/app/src/lib.rs b/app/src/lib.rs index 42dda51..384f628 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -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; diff --git a/app/src/schedule.rs b/app/src/schedule.rs index 8ea3e14..239418f 100644 --- a/app/src/schedule.rs +++ b/app/src/schedule.rs @@ -351,10 +351,23 @@ pub async fn deliver(d: &dyn Deliver, due: &Due, fallback: Option) -> 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, d: std::sync::Arc, fallback: Option) { +pub async fn run(store: std::sync::Arc, activity: std::sync::Arc, + d: std::sync::Arc, fallback: Option) { 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, d: std::sync::Arc, 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) { diff --git a/app/src/services.rs b/app/src/services.rs index e49f2ba..6d96cb2 100644 --- a/app/src/services.rs +++ b/app/src/services.rs @@ -202,6 +202,8 @@ pub async fn start_services(data_dir: &Path, llm: Arc) -> Result) -> Result, #[serde(default)] pub emoji: Option, + /// Who asked (for the activity log). + #[serde(default)] + pub user: Option, } /// The brain's schedule tool asks the app for the person asking (voice_worker.spec.md, "Schedules"). diff --git a/app/tests/live_discord.rs b/app/tests/live_discord.rs index 9023d63..c75f26c 100644 --- a/app/tests/live_discord.rs +++ b/app/tests/live_discord.rs @@ -349,7 +349,7 @@ async fn discord_voice_core_on_real_discord() { // unpin, delete; a switch that is off is refused. let act = |action: &str, id: u64, text: Option<&str>, emoji: Option<&str>| jarvis_app::worker_client::ChatAction { id: "live".into(), action: action.into(), channel: voice.to_string(), message_id: Some(id.to_string()), - text: text.map(Into::into), emoji: emoji.map(Into::into) }; + text: text.map(Into::into), emoji: emoji.map(Into::into), user: None }; let tool_msg = format!("자비스 도구 시험 {}", stop_at.elapsed().as_nanos()); let tid = core.send_chat(voice, &tool_msg).await.unwrap()[0]; let edited_tool = format!("{tool_msg} 수정"); diff --git a/app/tests/worker_client.rs b/app/tests/worker_client.rs index 96c6e94..73dc8f1 100644 --- a/app/tests/worker_client.rs +++ b/app/tests/worker_client.rs @@ -302,10 +302,10 @@ async fn chat_channels_go_out_and_chat_actions_come_back_with_their_results() { c.chat_channels(Some(900), &[ChatChannelSettings { id: 5, name: "일정".into(), description: "약속".into(), read: true, send: true, edit: true, react: true, delete: false, pin: false, answer_all: false, sync_discord: true }]); w.send(Message::text(json!({"type": "chat_action", "id": "a1", "action": "react", "channel": "5", - "message_id": "77", "emoji": "👍"}).to_string())); + "message_id": "77", "emoji": "👍", "user": "42"}).to_string())); let ev = next_matching(&mut rx, |e| matches!(e, WorkerEvent::ChatAction(_))).await; assert_eq!(ev, WorkerEvent::ChatAction(ChatAction { id: "a1".into(), action: "react".into(), channel: "5".into(), - message_id: Some("77".into()), text: None, emoji: Some("👍".into()) })); + message_id: Some("77".into()), text: None, emoji: Some("👍".into()), user: Some("42".into()) })); c.chat_action_result("a1", Ok(vec![77])); c.chat_action_result("a2", Err("send is turned off".into())); until(|| w.got().len() >= 4).await; diff --git a/app/ui/app.js b/app/ui/app.js index 4d0c74e..4adf856 100644 --- a/app/ui/app.js +++ b/app/ui/app.js @@ -350,6 +350,30 @@ async function permissionsCard() { h("div", { class: "hint" }, "채팅 채널 권한은 \"채팅 채널\" 화면에서 바꿉니다.")); } +const ACTIVITY = { "chat.send": "채팅 보내기", "chat.edit": "채팅 고치기", "chat.react": "반응 달기", + "chat.delete": "채팅 지우기", "chat.pin": "고정", "chat.unpin": "고정 풀기", + "schedule.remind": "예약 알림 전달", "schedule.task": "정기 작업 전달" }; +/** What Jarvis did outside its answers (admin.spec.md, "Activity"): kind, target, who asked, outcome. */ +function activityScreen() { + const list = h("div"); + const load = async () => { + try { + const { items } = await api("activity_list", { limit: 200 }); + list.replaceChildren(items.length ? h("table", {}, h("tbody", {}, items.map((e) => h("tr", {}, + h("td", { class: "small muted" }, (e.at || "").replace("T", " ").slice(0, 19)), + h("td", {}, ACTIVITY[e.kind] || e.kind), + h("td", { class: "small" }, e.target), + h("td", { class: "small" }, e.by || ""), + h("td", { class: "small" }, e.ok ? "됨" : "실패" + (e.note ? ` (${e.note})` : "")))))) + : h("div", { class: "muted" }, "아직 기록이 없습니다.")); + } catch (err) { fail(err); } + }; + load(); + return h("div", {}, h("h1", {}, "한 일"), h("div", { class: "card" }, + h("div", { class: "hint" }, "자비스가 채팅 채널에서 한 동작과 예약 전달을 종류, 대상, 시킨 사람, 결과만 남깁니다. 내용은 남기지 않고 30일 뒤 지웁니다."), + h("div", { class: "field" }, h("button", { class: "btn", onclick: load }, "새로 고침")), list)); +} + async function settingsScreen(screen, title, extra) { const [all, view] = await Promise.all([fields(), api("settings_view")]); const list = all.filter((f) => f.screen === screen); @@ -666,6 +690,7 @@ async function show(name) { try { if (name === "dashboard") { screen.replaceChildren(); await refresh(); ticker = setInterval(refresh, 1000); return; } if (name === "logs") { const l = logsScreen(); screen.replaceChildren(l.view); ticker = setInterval(l.tick, 1000); return; } + if (name === "activity") { screen.replaceChildren(activityScreen()); return; } if (name === "update") { const u = updateScreen(); screen.replaceChildren(u.view); ticker = setInterval(u.tick, 1000); return; } const titles = { bot: "봇", channels: "채널·호출", chat: "채팅 채널", memory: "대화 기억", model: "모델", features: "기능", collect: "백그라운드 수집", game: "게임 모드", schedule: "예약", pcControl: "PC 제어" }; diff --git a/app/ui/index.html b/app/ui/index.html index 2cb284d..2f17c0b 100644 --- a/app/ui/index.html +++ b/app/ui/index.html @@ -21,6 +21,7 @@ + diff --git a/docs/v2/proactive.md b/docs/v2/proactive.md index 821bbd8..57dce6b 100644 --- a/docs/v2/proactive.md +++ b/docs/v2/proactive.md @@ -6,7 +6,8 @@ - 1 예약 알림과 정기 작업: 구현(2026-11-14). 스펙은 [schedule.spec.md](../../src/jarvis/tools/builtin/schedule.spec.md)(두뇌 도구), [admin.spec.md](../../app/src/admin.spec.md) "Schedules"(저장·시각·전달·예약 화면), [voice_worker.spec.md](../../src/voice_worker/voice_worker.spec.md) "Schedules". 음성으로 맡긴 사람이 음성 채널에 없을 때 보낼 곳은 사람마다 고르지 않고 관리 앱에서 채팅 채널 하나를 정합니다. 정기 작업이 쓸 수 있는 도구에 "수집 결과 읽기"는 아직 없습니다(두뇌가 수집 결과를 읽는 도구가 없음, 제안 2 때 함께 봄). 평가 `evals/test_schedule_tool.py`를 이 서버의 qwen3:8b(실제 모델과 같은 계열)로 v2 설정(짧은 지시문, 의도 판단, 한국어 답)에서 세 번: "5분 타이머"(전에는 도구 없이 "설정했습니다"라고만 답함), "내일 7시 회의 알림", "예약 목록"은 9번 모두 통과했고 알림 문구도 한국어였습니다. "평일마다 아침 9시에 서울 날씨"는 3번 중 1번만 작업·평일로 맞게 예약했고, 나머지는 반복을 평일로 두지 않거나 지금 날씨를 바로 답했습니다. 실제 모델(Qwen3.6-35B-A3B, 게임PC)로는 사용자가 알려 주는 GPU 시간에 돌립니다. - 3 행동별 세 단계 권한: 판단 규칙, 설정, 관리 앱 "PC 제어" 화면 구현(2026-11-14, `app/src/permissions.rs`, 스펙 [admin.spec.md](../../app/src/admin.spec.md) "PC control permissions"). 시킬 수 있는 사람은 관리 앱에 아이디로 등록한 사람만(기본은 아무도 없음). "먼저 묻기"의 다음 말 확인과 실제 동작은 M7 PC 제어 도구에서 이 규칙을 써서 만듦. -- 5, 4, 2: 그다음 차례. +- 5 자비스가 한 일 기록: 구현(2026-11-14, `app/src/activity.rs`, 스펙 [admin.spec.md](../../app/src/admin.spec.md) "Activity"). 채팅 채널 동작(보내기·고치기·반응·지우기·고정)과 예약 전달을 종류·대상·시킨 사람·결과만 30일 남기고 관리 앱 "한 일" 화면에서 봄. PC 제어 동작은 M7에서 더함. +- 4, 2: 그다음 차례. ## dots가 하는 일 (공개 자료 기준) diff --git a/src/voice_worker/chat_bridge.py b/src/voice_worker/chat_bridge.py index 0dfb8de..75815a8 100644 --- a/src/voice_worker/chat_bridge.py +++ b/src/voice_worker/chat_bridge.py @@ -16,8 +16,10 @@ def _message(rec) -> dict: class ChatBridge: - def __init__(self, session, loop: asyncio.AbstractEventLoop, turn: int, pending_deletes: dict): + def __init__(self, session, loop: asyncio.AbstractEventLoop, turn: int, pending_deletes: dict, + user: str | None = None): self._session = session + self._user = user # who asked: the app records it with the action (admin.spec.md, "Activity") self._loop = loop self._channels = [dict(c) for c in session.chat_channels] self.turn = turn @@ -39,7 +41,8 @@ class ChatBridge: return store.chat_channel_of(message_id) if store else None def act(self, action: str, channel_id: str, **kw: Any) -> dict: - fut = asyncio.run_coroutine_threadsafe(self._session.chat_action(action, channel_id, kw), self._loop) + args = {**kw, "user": self._user} if self._user else kw + fut = asyncio.run_coroutine_threadsafe(self._session.chat_action(action, channel_id, args), self._loop) try: return fut.result(self._session.worker.chat_timeout_s + 5) except Exception as e: # loop gone or the wait broke diff --git a/src/voice_worker/server.py b/src/voice_worker/server.py index c3a7514..0fa39d2 100644 --- a/src/voice_worker/server.py +++ b/src/voice_worker/server.py @@ -803,7 +803,7 @@ class Session: debug_log(f"brain reply {rid} arrived before the previous answer: a turn is skipped", "llm") from .chat_bridge import ChatBridge - chat = ChatBridge(self, asyncio.get_running_loop(), turn, w.pending_deletes.setdefault(user, {})) \ + chat = ChatBridge(self, asyncio.get_running_loop(), turn, w.pending_deletes.setdefault(user, {}), user) \ if self.chat_channels else None from .schedule_bridge import ScheduleBridge schedule = ScheduleBridge(self, asyncio.get_running_loop(), user, via, diff --git a/src/voice_worker/voice_worker.spec.md b/src/voice_worker/voice_worker.spec.md index 8882273..543da87 100644 --- a/src/voice_worker/voice_worker.spec.md +++ b/src/voice_worker/voice_worker.spec.md @@ -296,7 +296,8 @@ which carry Discord's own time. "description": "...", "read": true, "send": true, "edit": true, "react": true, "delete": false, "pin": false}]} <- {"type": "chat_action", "id": "a1", "action": "send|edit|react|delete|pin|unpin", - "channel": "...", "message_id": "...", "text": "...", "emoji": "..."} + "channel": "...", "message_id": "...", "text": "...", "emoji": "...", + "user": ""} // who asked; the app records it (Activity) -> {"type": "chat_action_result", "id": "a1", "ok": true, "message_ids": ["..."]} -> {"type": "chat_action_result", "id": "a1", "ok": false, "error": "..."} ``` diff --git a/tests/test_voice_worker_brain.py b/tests/test_voice_worker_brain.py index a0a8f72..b6816df 100644 --- a/tests/test_voice_worker_brain.py +++ b/tests/test_voice_worker_brain.py @@ -471,7 +471,9 @@ def test_a_chat_action_goes_to_the_app_and_its_answer_comes_back(store): return action action = asyncio.run(with_worker(body, store=store, brain=brain)) - assert {k: action[k] for k in ("action", "channel", "text")} == {"action": "send", "channel": "c1", "text": "안녕"} + # The app records who asked for it (its activity log). + assert {k: action[k] for k in ("action", "channel", "text", "user")} == { + "action": "send", "channel": "c1", "text": "안녕", "user": "100"} assert results == [{"ok": True, "message_ids": ["555"]}]