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").
|
||||
|
||||
@@ -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} 수정");
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 제어" };
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
<button data-screen="collect" class="nav">백그라운드 수집</button>
|
||||
<button data-screen="schedule" class="nav">예약</button>
|
||||
<button data-screen="pcControl" class="nav">PC 제어</button>
|
||||
<button data-screen="activity" class="nav">한 일</button>
|
||||
<button data-screen="game" class="nav">게임 모드</button>
|
||||
<button data-screen="logs" class="nav">로그</button>
|
||||
<button data-screen="update" class="nav" id="nav-update">업데이트</button>
|
||||
|
||||
@@ -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가 하는 일 (공개 자료 기준)
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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": "<id>"} // 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": "..."}
|
||||
```
|
||||
|
||||
@@ -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"]}]
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user