feat: personal notes, each person's standing instructions for how Jarvis answers them
A personalNotes tool (add, list, delete the asker's own notes) offered only with a notes backend. The app keeps the notes in config/notes.json and sends the asker's with every voice, chat and task reply; the reply engine puts them in a <person_notes> fence as that person's preferences, which never permit an action or a tool. The worker's schedule bridge becomes a shared app bridge for schedule_action and note_action. A 사람별 지침 screen edits and deletes any note; features.notes turns the tool and the notes off. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -64,7 +64,8 @@ manages the MCP servers it connects.
|
||||
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; `schedule` (reminders and scheduled tasks, below
|
||||
"Schedules", and the brain tool `schedule`), on by default. The tools of a feature that
|
||||
"Schedules", and the brain tool `schedule`), on by default; `notes` (personal notes, below
|
||||
"Personal notes", and the brain tool `personalNotes`), 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).
|
||||
@@ -161,6 +162,23 @@ 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).
|
||||
|
||||
## Personal notes (`app/src/notes.rs`)
|
||||
|
||||
`docs/v2/proactive.md` (제안 4). Each person's standing instructions for how Jarvis answers them,
|
||||
saved by the brain's `personalNotes` tool (`src/jarvis/tools/builtin/personal_notes.spec.md`) and
|
||||
editable on the 사람별 지침 screen.
|
||||
|
||||
- **Store**: `config/notes.json`, `{nextId, items}`; each `{id, user, name, text, created}`. Text
|
||||
1-300 characters (whitespace collapsed), at most 20 per person. Read and written whole, one change
|
||||
at a time in the process.
|
||||
- **The brain's actions** (`note_action`, `voice_worker.spec.md`, "Personal notes") are done for the
|
||||
person named in it only: `add` (named as Discord shows them now), `list`, `delete` (one of theirs).
|
||||
- **Sent with replies**: every voice answer, chat answer and scheduled task carries the asker's notes
|
||||
(`reply` `notes`), oldest first; nobody else's. With `features.notes` off (on by default) none are
|
||||
sent and the tool is not offered; the notes stay and can be edited.
|
||||
- `notes_list` (everyone's, by person, IDs as strings), `note_update` `{id, text}` and `note_delete`
|
||||
`{id}` serve the screen. Logs carry note ids only, never their text.
|
||||
|
||||
## Activity (`app/src/activity.rs`)
|
||||
|
||||
`docs/v2/proactive.md` (제안 5). What Jarvis did outside its answers, for the 한 일 screen: each chat
|
||||
@@ -572,6 +590,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) |
|
||||
| `notes_list` / `note_update` `{id, text}` / `note_delete` `{id}` | everyone's personal notes (above) / change one's text / delete one |
|
||||
| `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) |
|
||||
@@ -615,6 +634,7 @@ 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).
|
||||
- **사람별 지침**: every person's notes (name and ID, the text in a box, save and 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 "설치하고
|
||||
|
||||
@@ -366,6 +366,28 @@ impl AdminApi {
|
||||
v
|
||||
}).collect::<Vec<_>>()}))
|
||||
}
|
||||
// Personal notes (admin.spec.md, "Personal notes"): everyone's, editable on the screen.
|
||||
"notes_list" => {
|
||||
let items = crate::notes::Notes::new(self.dir()?.path()).all()?;
|
||||
Ok(json!({"items": items.iter().map(|n| {
|
||||
let mut v = json!(n);
|
||||
v["id"] = json!(n.id.to_string());
|
||||
v["user"] = json!(n.user.to_string());
|
||||
v
|
||||
}).collect::<Vec<_>>()}))
|
||||
}
|
||||
"note_update" => {
|
||||
let id: u64 = arg_str(&args, "id")?.parse().map_err(|_| "지침 ID가 올바르지 않습니다")?;
|
||||
crate::notes::Notes::new(self.dir()?.path()).update(id, arg_str(&args, "text")?)?;
|
||||
crate::info_log!("admin", "note {id} changed");
|
||||
Ok(json!({"updated": id.to_string()}))
|
||||
}
|
||||
"note_delete" => {
|
||||
let id: u64 = arg_str(&args, "id")?.parse().map_err(|_| "지침 ID가 올바르지 않습니다")?;
|
||||
crate::notes::Notes::new(self.dir()?.path()).delete(id, None)?;
|
||||
crate::info_log!("admin", "note {id} deleted");
|
||||
Ok(json!({"deleted": id.to_string()}))
|
||||
}
|
||||
"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)}))
|
||||
@@ -495,6 +517,22 @@ mod tests {
|
||||
assert!(a.call("nope", json!({})).await.is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_notes_screen_lists_edits_and_deletes_anyones_notes() {
|
||||
let (a, base) = api("api-notes");
|
||||
let data = base.join("d");
|
||||
a.call("folder_choose", json!({"path": data.to_string_lossy()})).await.unwrap();
|
||||
let store = crate::notes::Notes::new(&data);
|
||||
let n = store.add(123456789012345678, "가", "반말로 해", 0).unwrap();
|
||||
let items = a.call("notes_list", json!({})).await.unwrap()["items"].clone();
|
||||
assert_eq!(items[0]["user"], "123456789012345678");
|
||||
a.call("note_update", json!({"id": n.id.to_string(), "text": "존댓말로 해"})).await.unwrap();
|
||||
assert_eq!(store.texts_of(123456789012345678), vec!["존댓말로 해".to_string()]);
|
||||
assert!(a.call("note_update", json!({"id": n.id.to_string(), "text": " "})).await.is_err());
|
||||
a.call("note_delete", json!({"id": n.id.to_string()})).await.unwrap();
|
||||
assert!(store.all().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_activity_screen_reads_the_newest_entries() {
|
||||
let (a, base) = api("api-activity");
|
||||
|
||||
@@ -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>>>,
|
||||
/// Each person's standing instructions, sent with their replies (admin.spec.md, "Personal notes").
|
||||
notes: OnceLock<Arc<crate::notes::Notes>>,
|
||||
/// 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.
|
||||
@@ -279,6 +281,7 @@ impl DiscordCore {
|
||||
tasks: Mutex::new(HashMap::new()),
|
||||
speech_waits: Mutex::new(HashMap::new()),
|
||||
activity: OnceLock::new(),
|
||||
notes: OnceLock::new(),
|
||||
});
|
||||
tokio::spawn(player_task(Arc::downgrade(&inner), player_rx));
|
||||
tokio::spawn(worker_task(Arc::downgrade(&inner), worker_events));
|
||||
@@ -513,7 +516,7 @@ impl DiscordCore {
|
||||
let id = with_playback(&self.inner, |p| p.adopt());
|
||||
let _ = self.inner.events.send(CoreEvent::AnswerAsked { id: id.clone(), user, ended_at: heard.0,
|
||||
final_at: heard.1 });
|
||||
self.inner.worker.reply(&id, user, text, "voice", true);
|
||||
self.inner.worker.reply_in(&id, user, text, "voice", true, None, ¬es_of(&self.inner, user));
|
||||
Some(id)
|
||||
}
|
||||
|
||||
@@ -527,7 +530,7 @@ impl DiscordCore {
|
||||
/// 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))
|
||||
self.inner.worker.reply_in(id, user, text, "chat", false, Some(channel), ¬es_of(&self.inner, user))
|
||||
}
|
||||
|
||||
/// The store the brain's schedule tool works on; without one its actions fail.
|
||||
@@ -535,6 +538,11 @@ impl DiscordCore {
|
||||
let _ = self.inner.schedules.set(store);
|
||||
}
|
||||
|
||||
/// The store of each person's standing instructions.
|
||||
pub fn set_notes(&self, notes: Arc<crate::notes::Notes>) {
|
||||
let _ = self.inner.notes.set(notes);
|
||||
}
|
||||
|
||||
/// The activity log chat actions are recorded in.
|
||||
pub fn set_activity(&self, activity: Arc<crate::activity::Activity>) {
|
||||
let _ = self.inner.activity.set(activity);
|
||||
@@ -544,7 +552,7 @@ impl DiscordCore {
|
||||
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) {
|
||||
if !self.inner.worker.reply_in(id, user, text, "task", false, None, ¬es_of(&self.inner, user)) {
|
||||
self.inner.tasks.lock().unwrap().remove(id);
|
||||
return None;
|
||||
}
|
||||
@@ -789,6 +797,14 @@ fn report_chat_channels(inner: &Inner) {
|
||||
inner.worker.chat_channels(inner.bot_id.get().copied(), &inner.settings.chat_channels);
|
||||
}
|
||||
|
||||
/// The person's standing instructions for a reply; none with `features.notes` off.
|
||||
fn notes_of(inner: &Inner, user: u64) -> Vec<String> {
|
||||
match inner.notes.get() {
|
||||
Some(n) if inner.settings.features.notes => n.texts_of(user),
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
fn should_hear(inner: &Inner, user: u64) -> bool {
|
||||
if Some(user) == inner.bot_id.get().copied() {
|
||||
return false;
|
||||
@@ -905,6 +921,19 @@ async fn worker_task(core: std::sync::Weak<Inner>, mut rx: mpsc::UnboundedReceiv
|
||||
core.inner.worker.chat_action_result(&a.id, result);
|
||||
});
|
||||
}
|
||||
WorkerEvent::NoteAction(a) => {
|
||||
let result = match inner.notes.get() {
|
||||
Some(notes) => {
|
||||
let name = a.user.parse().map(|u| name_of(&inner, u)).unwrap_or_else(|_| a.user.clone());
|
||||
crate::notes::act(notes, &a, &name, chrono::Utc::now().timestamp())
|
||||
}
|
||||
None => Err("notes are not available".into()),
|
||||
};
|
||||
if let Err(e) = &result {
|
||||
debug_log!("conversation", "note {} {} refused: {e}", a.action, a.id);
|
||||
}
|
||||
inner.worker.note_action_result(&a.id, result);
|
||||
}
|
||||
WorkerEvent::ScheduleAction(a) => {
|
||||
let result = match inner.schedules.get() {
|
||||
Some(store) => {
|
||||
|
||||
@@ -18,6 +18,7 @@ pub const FEATURE_TOOLS: &[(&str, &[&str])] = &[
|
||||
("meals", &["logMeal", "fetchMeals", "deleteMeal"]),
|
||||
("browser", &["botBrowser"]),
|
||||
("schedule", &["schedule"]),
|
||||
("notes", &["personalNotes"]),
|
||||
];
|
||||
|
||||
/// The built-in tools of the features that are off.
|
||||
@@ -27,6 +28,7 @@ pub fn disabled_tools(f: &FeatureSettings) -> Vec<&'static str> {
|
||||
"webSearch" => f.web_search,
|
||||
"browser" => f.browser,
|
||||
"schedule" => f.schedule,
|
||||
"notes" => f.notes,
|
||||
_ => f.meals,
|
||||
};
|
||||
FEATURE_TOOLS.iter().filter(|(k, _)| !on(k)).flat_map(|(_, tools)| tools.iter().copied()).collect()
|
||||
@@ -104,10 +106,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, schedule: true };
|
||||
let all_on = FeatureSettings { weather: true, web_search: true, meals: true, collect: true, browser: true, browser_share: true, schedule: true, notes: 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, schedule: false });
|
||||
assert_eq!(off, vec!["getWeather", "logMeal", "fetchMeals", "deleteMeal", "botBrowser", "schedule"]);
|
||||
let off = disabled_tools(&FeatureSettings { weather: false, web_search: true, meals: false, collect: false, browser: false, browser_share: false, schedule: false, notes: false });
|
||||
assert_eq!(off, vec!["getWeather", "logMeal", "fetchMeals", "deleteMeal", "botBrowser", "schedule", "personalNotes"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -21,6 +21,7 @@ pub mod game;
|
||||
pub mod frames;
|
||||
pub mod install;
|
||||
pub mod logs;
|
||||
pub mod notes;
|
||||
pub mod playback;
|
||||
pub mod perf;
|
||||
pub mod permissions;
|
||||
|
||||
193
app/src/notes.rs
Normal file
193
app/src/notes.rs
Normal file
@@ -0,0 +1,193 @@
|
||||
//! Each person's standing instructions for how Jarvis answers them (`app/src/admin.spec.md`,
|
||||
//! "Personal notes"; `docs/v2/proactive.md` 제안 4): the store in the data folder, the brain's
|
||||
//! `note_action`, and the notes sent with each of that person's replies.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use crate::worker_client::NoteAction;
|
||||
|
||||
pub const MAX_TEXT_CHARS: usize = 300;
|
||||
/// Notes one person may have (the worker takes at most this many with a reply).
|
||||
pub const PER_PERSON: usize = 20;
|
||||
|
||||
static FILE_LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Note {
|
||||
pub id: u64,
|
||||
pub user: u64,
|
||||
pub name: String,
|
||||
pub text: String,
|
||||
pub created: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct File {
|
||||
next_id: u64,
|
||||
items: Vec<Note>,
|
||||
}
|
||||
|
||||
pub struct Notes {
|
||||
file: PathBuf,
|
||||
}
|
||||
|
||||
fn clean(text: &str) -> Result<String, String> {
|
||||
let text = text.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
if text.is_empty() || text.chars().count() > MAX_TEXT_CHARS {
|
||||
return Err(format!("a note must be 1-{MAX_TEXT_CHARS} characters"));
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
impl Notes {
|
||||
pub fn new(data: &Path) -> Self {
|
||||
Self { file: data.join("config").join("notes.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 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)?;
|
||||
let mut text = serde_json::to_string_pretty(&file).unwrap();
|
||||
text.push('\n');
|
||||
crate::datadir::write_atomic(&self.file, text.as_bytes()).map_err(|e| format!("지침 파일을 쓸 수 없습니다: {e}"))?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Every note, by person then age.
|
||||
pub fn all(&self) -> Result<Vec<Note>, String> {
|
||||
let _g = FILE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut items = self.load()?.items;
|
||||
items.sort_by_key(|n| (n.user, n.id));
|
||||
Ok(items)
|
||||
}
|
||||
|
||||
/// One person's notes, oldest first.
|
||||
pub fn of(&self, user: u64) -> Result<Vec<Note>, String> {
|
||||
Ok(self.all()?.into_iter().filter(|n| n.user == user).collect())
|
||||
}
|
||||
|
||||
/// The texts sent with that person's replies; a store that cannot be read sends none.
|
||||
pub fn texts_of(&self, user: u64) -> Vec<String> {
|
||||
match self.of(user) {
|
||||
Ok(n) => n.into_iter().map(|n| n.text).take(PER_PERSON).collect(),
|
||||
Err(e) => {
|
||||
crate::warn_log!("conversation", "Warning: {e}");
|
||||
vec![]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn add(&self, user: u64, name: &str, text: &str, now: i64) -> Result<Note, String> {
|
||||
let text = clean(text)?;
|
||||
self.change(|f| {
|
||||
if f.items.iter().filter(|n| n.user == user).count() >= PER_PERSON {
|
||||
return Err(format!("at most {PER_PERSON} notes per person; delete one first"));
|
||||
}
|
||||
f.next_id += 1;
|
||||
let n = Note { id: f.next_id, user, name: name.to_owned(), text, created: now };
|
||||
f.items.push(n.clone());
|
||||
Ok(n)
|
||||
})
|
||||
}
|
||||
|
||||
/// Change a note's text (the screen).
|
||||
pub fn update(&self, id: u64, text: &str) -> Result<Note, String> {
|
||||
let text = clean(text)?;
|
||||
self.change(|f| {
|
||||
let n = f.items.iter_mut().find(|n| n.id == id).ok_or("no such note")?;
|
||||
n.text = text;
|
||||
Ok(n.clone())
|
||||
})
|
||||
}
|
||||
|
||||
/// Delete a note; with `user`, only one of theirs.
|
||||
pub fn delete(&self, id: u64, user: Option<u64>) -> Result<Note, String> {
|
||||
self.change(|f| {
|
||||
let pos = f.items.iter().position(|n| n.id == id && user.is_none_or(|u| u == n.user))
|
||||
.ok_or_else(|| "no such note of this person".to_string())?;
|
||||
Ok(f.items.remove(pos))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn brain_item(n: &Note) -> Value {
|
||||
json!({"id": n.id.to_string(), "text": n.text})
|
||||
}
|
||||
|
||||
/// Do what the brain's personalNotes tool asked for the person in `a.user` (named `name`).
|
||||
pub fn act(notes: &Notes, a: &NoteAction, 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": notes.of(user)?.iter().map(brain_item).collect::<Vec<_>>()})),
|
||||
"add" => {
|
||||
let n = notes.add(user, name, a.text.as_deref().unwrap_or(""), now)?;
|
||||
crate::info_log!("conversation", "note {} added by {user}", n.id);
|
||||
Ok(json!({"item": brain_item(&n)}))
|
||||
}
|
||||
"delete" => {
|
||||
let id: u64 = a.note.as_deref().and_then(|s| s.trim().parse().ok()).ok_or("delete needs the note's id")?;
|
||||
Ok(json!({"item": brain_item(¬es.delete(id, Some(user))?)}))
|
||||
}
|
||||
other => Err(format!("unknown note action {other}")),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn notes() -> Notes {
|
||||
Notes::new(&crate::datadir::temp_dir("notes"))
|
||||
}
|
||||
|
||||
fn action(action: &str, user: &str, extra: Value) -> NoteAction {
|
||||
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()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_persons_notes_are_theirs_alone() {
|
||||
let n = notes();
|
||||
let added = act(&n, &action("add", "1", json!({"text": " 반말로 해 "})), "가", 10).unwrap();
|
||||
assert_eq!(added["item"]["text"], "반말로 해");
|
||||
act(&n, &action("add", "2", json!({"text": "섭씨로"})), "나", 10).unwrap();
|
||||
assert_eq!(n.texts_of(1), vec!["반말로 해".to_string()]);
|
||||
assert!(!act(&n, &action("list", "2", json!({})), "나", 10).unwrap().to_string().contains("반말"));
|
||||
let id = added["item"]["id"].as_str().unwrap().to_owned();
|
||||
assert!(act(&n, &action("delete", "2", json!({"note": id})), "나", 10).is_err());
|
||||
assert!(act(&n, &action("delete", "1", json!({"note": id})), "가", 10).is_ok());
|
||||
assert!(n.texts_of(1).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_notes_and_too_many_are_refused_and_the_screen_can_edit_any() {
|
||||
let n = notes();
|
||||
assert!(n.add(1, "가", " ", 0).is_err());
|
||||
assert!(n.add(1, "가", &"x".repeat(MAX_TEXT_CHARS + 1), 0).is_err());
|
||||
for i in 0..PER_PERSON {
|
||||
n.add(1, "가", &format!("지침 {i}"), 0).unwrap();
|
||||
}
|
||||
assert!(n.add(1, "가", "하나 더", 0).is_err());
|
||||
let first = n.of(1).unwrap()[0].clone();
|
||||
assert_eq!(n.update(first.id, "고친 지침").unwrap().text, "고친 지침");
|
||||
assert!(n.update(first.id, "").is_err());
|
||||
assert_eq!(n.texts_of(1)[0], "고친 지침");
|
||||
assert_eq!(n.delete(first.id, None).unwrap().id, first.id);
|
||||
}
|
||||
}
|
||||
@@ -204,6 +204,7 @@ pub async fn start_services(data_dir: &Path, llm: Arc<Llm>) -> Result<Services,
|
||||
core.set_schedules(schedule_store.clone());
|
||||
let activity = Arc::new(crate::activity::Activity::new(data_dir));
|
||||
core.set_activity(activity.clone());
|
||||
core.set_notes(Arc::new(crate::notes::Notes::new(data_dir)));
|
||||
// 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);
|
||||
|
||||
@@ -100,6 +100,8 @@ pub struct FeatureSettings {
|
||||
pub browser_share: bool,
|
||||
/// Reminders and scheduled tasks (admin.spec.md, "Schedules").
|
||||
pub schedule: bool,
|
||||
/// Each person's standing instructions (admin.spec.md, "Personal notes").
|
||||
pub notes: bool,
|
||||
}
|
||||
|
||||
/// Game detection (admin.spec.md, "Game detection"): on by default; the person's own games and
|
||||
@@ -251,7 +253,7 @@ 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, schedule: true },
|
||||
features: FeatureSettings { weather: true, web_search: true, meals: true, collect: true, browser: true, browser_share: false, schedule: true, notes: 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 },
|
||||
@@ -583,6 +585,7 @@ pub fn parse_settings(raw: &Value) -> Result<Settings, SettingsError> {
|
||||
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)?,
|
||||
notes: get_bool(f, "notes", "features", d.features.notes)?,
|
||||
}
|
||||
},
|
||||
mcp_servers: parse_mcp_servers(raw)?,
|
||||
@@ -945,13 +948,13 @@ 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, schedule: true });
|
||||
assert_eq!(s.unwrap().features, FeatureSettings { weather: true, web_search: true, meals: true, collect: true, browser: true, browser_share: false, schedule: true, notes: true });
|
||||
let s = parse_settings(&json!({
|
||||
"features": {"weather": false, "meals": false, "browserShare": true, "schedule": false},
|
||||
"features": {"weather": false, "meals": false, "browserShare": true, "schedule": false, "notes": 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, schedule: false });
|
||||
assert_eq!(s.features, FeatureSettings { weather: false, web_search: true, meals: false, collect: true, browser: true, browser_share: true, schedule: false, notes: 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 },
|
||||
|
||||
@@ -132,6 +132,7 @@ pub fn fields() -> Vec<Field> {
|
||||
f("features.browser", Features, Bool, json!(true), "브라우저 제어(봇용 크롬)"),
|
||||
f("features.browserShare", Features, Bool, json!(false), "봇용 크롬창 화면공유 선택 표시(가상 모니터, Windows)"),
|
||||
f("features.schedule", Features, Bool, json!(true), "예약 알림과 정기 작업"),
|
||||
f("features.notes", 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!([]), "수집 대상"),
|
||||
|
||||
@@ -149,6 +149,21 @@ pub struct ScheduleAction {
|
||||
pub schedule: Option<String>,
|
||||
}
|
||||
|
||||
/// The brain's personalNotes tool asks the app for the person asking (voice_worker.spec.md,
|
||||
/// "Personal notes").
|
||||
#[derive(Debug, Clone, Deserialize, PartialEq)]
|
||||
pub struct NoteAction {
|
||||
pub id: String,
|
||||
/// `add`, `list` or `delete`.
|
||||
pub action: String,
|
||||
pub user: String,
|
||||
#[serde(default)]
|
||||
pub text: Option<String>,
|
||||
/// delete: the note's id.
|
||||
#[serde(default)]
|
||||
pub note: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum WorkerEvent {
|
||||
Ready(HelloOk),
|
||||
@@ -160,6 +175,7 @@ pub enum WorkerEvent {
|
||||
TtsDone(TtsDone),
|
||||
ChatAction(ChatAction),
|
||||
ScheduleAction(ScheduleAction),
|
||||
NoteAction(NoteAction),
|
||||
/// 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)
|
||||
@@ -350,15 +366,24 @@ impl WorkerClient {
|
||||
|
||||
/// 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>) {
|
||||
self.app_action_result("schedule_action_result", id, result);
|
||||
}
|
||||
|
||||
/// The outcome of a `note_action`: `{item}` or `{items}`, or why it failed.
|
||||
pub fn note_action_result(&self, id: &str, result: Result<Value, String>) {
|
||||
self.app_action_result("note_action_result", id, result);
|
||||
}
|
||||
|
||||
fn app_action_result(&self, kind: &str, 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("type".into(), json!(kind));
|
||||
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}),
|
||||
Ok(_) => json!({"type": kind, "id": id, "ok": true}),
|
||||
Err(e) => json!({"type": kind, "id": id, "ok": false, "error": e}),
|
||||
};
|
||||
self.send_json(msg);
|
||||
}
|
||||
@@ -375,12 +400,14 @@ impl WorkerClient {
|
||||
/// no answer, or the worker refuses it.
|
||||
/// `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)
|
||||
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 {
|
||||
/// delivers there) and carrying the asker's standing instructions (`notes`, at most 20).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn reply_in(&self, id: &str, user: u64, text: &str, via: &str, speak: bool, channel: Option<u64>,
|
||||
notes: &[String]) -> bool {
|
||||
if speak {
|
||||
self.inner.state.lock().unwrap().open_tts.insert(id.to_owned());
|
||||
}
|
||||
@@ -389,6 +416,9 @@ impl WorkerClient {
|
||||
if let Some(c) = channel {
|
||||
msg["channel"] = json!(c.to_string());
|
||||
}
|
||||
if !notes.is_empty() {
|
||||
msg["notes"] = json!(notes);
|
||||
}
|
||||
let sent = self.send_json(msg);
|
||||
if !sent && speak {
|
||||
self.end_failed(id);
|
||||
@@ -634,6 +664,7 @@ fn on_text(inner: &Inner, t: &str) {
|
||||
"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),
|
||||
"note_action" => serde_json::from_value(v).ok().map(WorkerEvent::NoteAction),
|
||||
"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 });
|
||||
|
||||
7
app/tests/fixtures/fake_engine_worker.py
vendored
7
app/tests/fixtures/fake_engine_worker.py
vendored
@@ -29,9 +29,12 @@ class FakeBrain:
|
||||
"예약" adds a reminder through the schedule backend and answers with its result; a task answers
|
||||
"task: <text>"."""
|
||||
|
||||
def reply(self, user, text, history, chat=None, schedule=None, task=False):
|
||||
def reply(self, user, text, history, chat=None, schedule=None, task=False, notes=None, notes_backend=None):
|
||||
if task:
|
||||
return f"task: {text}"
|
||||
return f"task: {text}" + (f" notes={'|'.join(notes)}" if notes else "")
|
||||
if "지침" in text and notes_backend is not None:
|
||||
got = notes_backend.act("add", text="반말로 해")
|
||||
return f"noted {got.get('item', {}).get('id')} {got.get('error', '')}".strip()
|
||||
if "예약" in text and schedule is not None:
|
||||
got = schedule.act("add", kind="remind", text="물 마시기", at=4_000_000_000.0, repeat="daily")
|
||||
return f"scheduled {got.get('item', {}).get('id')} {got.get('error', '')}".strip()
|
||||
|
||||
@@ -150,7 +150,7 @@ async fn audio_and_tts_round_trip_through_the_python_server() {
|
||||
// app's store answers; a scheduled task comes back as text.
|
||||
let data = std::env::temp_dir().join(format!("jarvis-proto-schedule-{}", std::process::id()));
|
||||
let store = jarvis_app::schedule::Store::new(&data);
|
||||
assert!(c.reply_in("c1", 42, "예약해 줘", "chat", false, Some(77)));
|
||||
assert!(c.reply_in("c1", 42, "예약해 줘", "chat", false, Some(77), &[]));
|
||||
let text = tokio::time::timeout(Duration::from_secs(5), async {
|
||||
loop {
|
||||
match rx.recv().await.unwrap() {
|
||||
@@ -169,7 +169,7 @@ async fn audio_and_tts_round_trip_through_the_python_server() {
|
||||
assert_eq!(text, "scheduled 1");
|
||||
let kept = store.all().unwrap();
|
||||
assert_eq!((kept[0].user, kept[0].channel, kept[0].repeat.as_str()), (42, Some(77), "daily"));
|
||||
assert!(c.reply("t1", 42, "날씨", "task", false));
|
||||
assert!(c.reply_in("t1", 42, "날씨", "task", false, None, &["섭씨로".to_string()]));
|
||||
let task = tokio::time::timeout(Duration::from_secs(5), async {
|
||||
loop {
|
||||
if let WorkerEvent::ReplyText { id, text, failed } = rx.recv().await.unwrap() {
|
||||
@@ -181,7 +181,26 @@ async fn audio_and_tts_round_trip_through_the_python_server() {
|
||||
})
|
||||
.await
|
||||
.expect("task answer");
|
||||
assert_eq!(task, ("task: 날씨".to_string(), false));
|
||||
assert_eq!(task, ("task: 날씨 notes=섭씨로".to_string(), false));
|
||||
// The personalNotes tool's actions come to the app's notes store for the asker.
|
||||
let notes = jarvis_app::notes::Notes::new(&data);
|
||||
assert!(c.reply("n1", 42, "지침 저장해 줘", "voice", false));
|
||||
let noted = tokio::time::timeout(Duration::from_secs(5), async {
|
||||
loop {
|
||||
match rx.recv().await.unwrap() {
|
||||
WorkerEvent::NoteAction(a) => {
|
||||
assert_eq!((a.action.as_str(), a.user.as_str()), ("add", "42"));
|
||||
c.note_action_result(&a.id, jarvis_app::notes::act(¬es, &a, "가", 1000));
|
||||
}
|
||||
WorkerEvent::ReplyText { id, text, .. } if id == "n1" => return text,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("note round trip");
|
||||
assert_eq!(noted, "noted 1");
|
||||
assert_eq!(notes.texts_of(42), vec!["반말로 해".to_string()]);
|
||||
let _ = std::fs::remove_dir_all(&data);
|
||||
c.close();
|
||||
let _ = child.kill().await;
|
||||
|
||||
@@ -350,6 +350,31 @@ async function permissionsCard() {
|
||||
h("div", { class: "hint" }, "채팅 채널 권한은 \"채팅 채널\" 화면에서 바꿉니다."));
|
||||
}
|
||||
|
||||
/** Each person's standing instructions (admin.spec.md, "Personal notes"): edit or delete any. */
|
||||
function notesScreen() {
|
||||
const list = h("div");
|
||||
const load = async () => {
|
||||
try {
|
||||
const { items } = await api("notes_list");
|
||||
list.replaceChildren(items.length ? h("table", {}, h("tbody", {}, items.map((n) => {
|
||||
const input = h("input", { type: "text", value: n.text, maxlength: 300 });
|
||||
return h("tr", {},
|
||||
h("td", { class: "small" }, n.name, h("div", { class: "small muted" }, n.user)),
|
||||
h("td", {}, input),
|
||||
h("td", {}, h("button", { class: "btn", onclick: async () => {
|
||||
try { await api("note_update", { id: n.id, text: input.value }); toast("저장했습니다"); load(); } catch (e) { fail(e); }
|
||||
} }, "저장"), " ", h("button", { class: "btn", onclick: async () => {
|
||||
try { await api("note_delete", { id: n.id }); toast("지웠습니다"); load(); } catch (e) { fail(e); }
|
||||
} }, "삭제")));
|
||||
}))) : h("div", { class: "muted" }, "저장된 지침이 없습니다. \"앞으로 나한테는 반말로 해\"처럼 말하면 여기에 나옵니다."));
|
||||
} catch (e) { fail(e); }
|
||||
};
|
||||
load();
|
||||
return h("div", {}, h("h1", {}, "사람별 지침"), h("div", { class: "card" },
|
||||
h("div", { class: "hint" }, "사람마다 고쳐 준 답하는 방식입니다. 그 사람에게 답할 때만 넣고, 어떤 동작이나 도구도 허락하지 않습니다. 한 사람에 20개, 하나에 300자까지입니다."),
|
||||
h("div", { class: "field" }, h("button", { class: "btn", onclick: load }, "새로 고침")), list));
|
||||
}
|
||||
|
||||
const ACTIVITY = { "chat.send": "채팅 보내기", "chat.edit": "채팅 고치기", "chat.react": "반응 달기",
|
||||
"chat.delete": "채팅 지우기", "chat.pin": "고정", "chat.unpin": "고정 풀기",
|
||||
"schedule.remind": "예약 알림 전달", "schedule.task": "정기 작업 전달" };
|
||||
@@ -691,6 +716,7 @@ async function show(name) {
|
||||
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 === "notes") { screen.replaceChildren(notesScreen()); 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="notes" class="nav">사람별 지침</button>
|
||||
<button data-screen="activity" class="nav">한 일</button>
|
||||
<button data-screen="game" class="nav">게임 모드</button>
|
||||
<button data-screen="logs" class="nav">로그</button>
|
||||
|
||||
Reference in New Issue
Block a user