From 41b6b7f4659254178f8d843cce4e5c51acb6b0f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Wed, 11 Nov 2026 16:54:58 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8A=80=E8=83=BD:=20/=20in=20the=20input=20pi?= =?UTF-8?q?cks=20one;=20on=20a=20brain's=20screen=20the=20brain=20adds,=20?= =?UTF-8?q?installs=20and=20deletes=20them;=20=E8=A8=AD=E5=AE=9A=20?= =?UTF-8?q?=E2=80=BA=20=E6=95=B4=E5=90=88's=20lists=20keep=20their=20butto?= =?UTF-8?q?ns=20clear?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Typing / at the start of the input (computer and phone) lists the skills that are on: names that start with what is typed first, then names containing it, then descriptions (「/簡報」 finds pptx). A click, or ↑↓ and Enter/Tab, puts 「/name 」 in the input; Esc closes the list. Sent, the brain recognises 「/name」 and adds a line after the message telling the model to read that skill with use_skill first, so a phone or a message channel gets it too; a / that names no skill (a path) gets nothing. The phone asks the brain for the list again at each new /, so a skill added since is there. - On a screen, 加入 / 安裝 / 刪除 ran on the screen's own disk and only the list entry reached the brain: a GitHub skill's scripts stayed on the screen's computer, an install also pushed every skill in that computer's folder into the brain's list, and a deleted skill's folder stayed on the brain and came back at its next start. These now go to the brain (/api/sync/skill, the phone's own 「skill」 action): it fetches an address itself, a folder or .md file on the screen's computer goes up whole with its files, and a delete takes the folder too. 「把這台的 Bot 搬到大腦」 hands over skills the same way. A refused package leaves no folder behind. - 技能, 技能市集 and 連接器市集 rows: a long description took the whole row and 開啟 / 檢視 / 刪除 / 已加入 / 安裝 were drawn over it. The buttons are laid out first and the description ends in … before them (the whole of it on hover). - Screenshot mode: ANYBOT_SHOT_KEYS="ArrowDown@60;Enter@64" presses keys at given frames. Co-Authored-By: Claude Opus 5.5 --- FEATURES.md | 2 + mobile/index.html | 61 +++++++++- src/app.rs | 67 ++++++++++- src/app/channels_ui.rs | 246 ++++++++++++++++++++++++++--------------- src/app/chat_ui.rs | 95 ++++++++++++++++ src/app/mirror_ui.rs | 84 +++++++++++++- src/app/remote_ui.rs | 55 +++++++++ src/memory.rs | 72 ++++++++++++ src/remote.rs | 10 +- src/skills.rs | 139 ++++++++++++++++++++--- 10 files changed, 717 insertions(+), 114 deletions(-) diff --git a/FEATURES.md b/FEATURES.md index 420bc34..618b5dd 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -1357,6 +1357,8 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 每條顯示種類、日期、「帶過 N 次 · 上次…」或「還沒被帶入過」;按鈕「釘選」「編輯」「忘記」,在最近刪除裡是「還原」。最近刪除的最下面有「清空最近刪除」。 - 一次顯示 60 條,按「再顯示 N」看更多。 - **技能**:教 Bot 一套做法後請它「存成技能」(save_skill),所有 Bot 共用;系統指示只列名稱和一句說明,Bot 要用時先用 use_skill 讀完整做法。設定 →「連接器」頁的「技能」卡可以刪除。 +- **技能在大腦上**:Bot 在大腦上跑,技能也從大腦的硬碟讀。所以在大腦的螢幕(連到大腦的電腦)上,設定 › 整合的「加入」「安裝」「刪除」都請大腦做:GitHub/網址由大腦自己下載;填這台電腦上的資料夾或 .md 檔,就在這台讀好,連同 scripts/、references/ 和其他附檔整包交給大腦;刪除時大腦連資料夾一起刪,大腦重開也不會再冒出來。「開啟」照舊是一般的設定同步。「把這台的 Bot 搬到大腦」時,這台有、大腦沒有的技能也是整包交過去(連同開關和可重播的步驟)。手機本來就是請大腦做。大腦是舊版時,螢幕上的這些動作會說要先更新大腦。 +- **用 / 指定技能**:輸入框第一個字打「/」,上面就列出開著的技能(名稱開頭符合的先、名稱含有的次之、再來是說明裡有的,例如「/簡報」找到 pptx);點一下,或 ↑↓ 選、Enter/Tab 帶入,輸入框變成「/pptx 」接著打要做的事,Esc 關掉清單。電腦和手機都有,Bot 正在做事時不列(那時打的字會併進正在做的事)。送出後由大腦認出「/名稱」,在這則訊息後面替模型加一行「使用者用 /pptx 指定了技能「pptx」:先用 use_skill 讀出它的完整做法」,所以從手機、訊息管道打的也算;不是技能名稱的(例如 /Users/… 路徑)不加。新加的技能(技能市集、GitHub 安裝、Bot 存的或自己學會的、「教我做」)馬上就在清單裡:電腦直接讀技能名單(大腦的螢幕讀的是大腦同步過來的那份);手機每次打出新的「/」會向大腦再拿一次名單,拿到前先列手上已有的。篩選本身不連網,也不多送東西給模型(技能清單本來就在系統指示裡)。 - **自己進化**:一件事做了 5 步以上(操作電腦、網頁、指令,不算記憶和設定),回答完後在背景回頭看一次:這是在網站或程式上動手操作的事(填表、發文、回留言、上傳下載、改設定),就把這次真的成功的最短做法存成技能(用畫面上的名字,不寫編號和座標;繞路和失敗寫成「注意」;使用者說過的偏好寫進去);已經有同一件事的技能就合併成更好的一版,照著做而且很順就不動。回覆下面會多一行「(學會了新做法「…」)」或「(把做法「…」更新了)」。系統指示要 Bot 開始做事前先看技能清單、有符合的先 use_skill。實測(httpbin 訂 pizza,真的 Grok):第一次 11 步學到技能;第二次先讀技能、10 步 24 秒一次做完,回頭看後判斷不用改。 - **重播學會的做法**(replay_skill):存技能時,模型會挑出這次真的成功、必要、會改變東西的步驟(不含截圖、讀取這類只是看的步驟、不含繞路和失敗),連同每一步點的是哪個東西(「勾選框「自動更新」」,不是編號)一起存下來;內容每次不同的工作(發文的文字、回覆的留言)不存步驟。技能清單裡標「可重播,N 步」。 - 要做的事和技能一模一樣時,Bot 叫 replay_skill,AnyBot 就一步一步照做,中間不問模型:畫面上的步驟在最近的畫面清單裡找同一種、同名的東西換成現在的編號(值和勾選狀態不算),網頁上的步驟改用字找;找不到時先自動截一次圖再找,還是找不到就停下來,告訴 Bot 停在第幾步、找不到什麼,由它接手。 diff --git a/mobile/index.html b/mobile/index.html index 0e2a916..8d8d33d 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -220,6 +220,13 @@ a{color:var(--accent-ink)} .memchips .lbl{font-size:12px;color:var(--text3);display:inline-flex;gap:4px;align-items:center} .mchip{font-size:12.5px;padding:4px 10px;border-radius:14px;box-shadow:inset 0 0 0 .5px var(--line);color:var(--text2);max-width:220px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} .mchip.on{background:color-mix(in srgb,var(--accent) 14%,transparent);box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--accent) 55%,transparent);color:var(--text)} +.slash{max-width:760px;margin:0 auto 6px;padding:4px;max-height:min(272px,38vh);overflow-y:auto;border-radius:16px;background:var(--elev);box-shadow:inset 0 0 0 .5px var(--line),0 6px 24px -6px #0000002e} +.slash:empty{display:none} +.slash .hd{font-size:11.5px;color:var(--text3);padding:6px 10px 4px} +.slash button{display:flex;align-items:center;gap:8px;width:100%;min-height:40px;padding:6px 10px;border-radius:10px;text-align:left} +.slash button.on{background:var(--active)} +.slash b{flex:none;font-size:14px;font-weight:600} +.slash span{min-width:0;font-size:12.5px;color:var(--text3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis} .memtok{font-size:11.5px;color:var(--text3)} .carried{font-size:11.5px;color:var(--text3);margin:3px 6px 0;display:inline-flex;gap:4px;align-items:center} .carried-list{font-size:12.5px;color:var(--text2);background:var(--hover);border-radius:10px;padding:8px 12px;margin:4px 4px 0;max-width:85%;line-height:1.5;white-space:pre-wrap;word-break:break-word} @@ -457,6 +464,7 @@ textarea.field{min-height:96px;line-height:1.5}
+
@@ -1256,9 +1264,58 @@ const input = $("input"); input.addEventListener("input", () => { input.style.height = "auto"; input.style.height = Math.min(input.scrollHeight, 140) + "px"; $("composer").classList.toggle("tall", input.scrollHeight > 40); renderSendBtn(); - memSuggestSoon(); renderMemChips(); + memSuggestSoon(); renderMemChips(); renderSlash(); +}); +// 技能: a / at the start of the input lists them — tap one, or ↑↓ and Enter/Tab on a keyboard; +// Esc closes the list until the / is gone. (First here: Enter picks instead of sending.) +input.addEventListener("keydown", (e) => { + const n = SL.hits.length; + if (!n || e.isComposing) return; + const k = e.key, stop = () => { e.preventDefault(); e.stopImmediatePropagation(); }; + if (k === "ArrowDown" || k === "ArrowUp") { stop(); SL.lit = (SL.lit + (k === "ArrowDown" ? 1 : n - 1)) % n; SL.moved = true; renderSlash(); } + else if ((k === "Enter" && !e.shiftKey) || k === "Tab") { stop(); slashPick(SL.lit); } + else if (k === "Escape") { stop(); SL.closed = true; renderSlash(); } }); input.addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.shiftKey && !e.isComposing && matchMedia("(pointer:fine)").matches) { e.preventDefault(); send(); } }); +const SL = {hits: [], lit: 0, q: null, moved: false, closed: false, loading: false, fresh: false}; +/** The skills a draft like 「/pp」 asks for, as the brain ranks them: name starts with it, name + * contains it, then description. None once a space ends the name, or while the bot works. */ +function slashHits() { + const v = input.value; + if (!v.startsWith("/")) { SL.closed = false; SL.fresh = false; return []; } + if (SL.closed || (bot(S.open) || {}).busy || /\s/.test(v.slice(1))) return []; + // Each new / asks the brain once more, so a skill added since (on the computer, from the + // market, or one a bot just learned) is there; what was known shows in the meantime. + if (!SL.fresh && owner() && !SL.loading) { + SL.fresh = SL.loading = true; + api(base() + "api/settings").then((st) => { S.settings = st; }).catch(() => {}).finally(() => { SL.loading = false; renderSlash(); }); + } + if (!S.settings) return []; + const q = v.slice(1).toLowerCase(); + const rank = (k) => { const n = k.name.toLowerCase(); return n.startsWith(q) ? 0 : n.includes(q) ? 1 : (k.description || "").toLowerCase().includes(q) ? 2 : 3; }; + return (S.settings.skills || []).filter((k) => k.enabled !== false && k.name).map((k) => [rank(k), k]).filter(([r]) => r < 3).sort((a, b) => a[0] - b[0]).map(([, k]) => k); +} +function renderSlash() { + const el = $("slash"); + SL.hits = slashHits(); + if (input.value !== SL.q) { SL.q = input.value; SL.lit = 0; } + if (!SL.hits.length) { el.innerHTML = ""; return; } + SL.lit = Math.min(SL.lit, SL.hits.length - 1); + el.innerHTML = `
技能
` + SL.hits.map((k, i) => ``).join(""); + el.querySelectorAll("[data-sl]").forEach((x) => { + // Keep the caret (and the phone's keyboard) in the input while a row is pressed. + x.onpointerdown = x.onmousedown = (e) => e.preventDefault(); + x.onclick = () => slashPick(+x.dataset.sl); + }); + if (SL.moved) { SL.moved = false; const on = el.querySelector(".on"); if (on) on.scrollIntoView({block: "nearest"}); } +} +function slashPick(i) { + const k = SL.hits[i]; + if (!k) return; + input.value = "/" + k.name + " "; + input.focus(); input.setSelectionRange(input.value.length, input.value.length); + input.dispatchEvent(new Event("input")); +} function renderSendBtn() { const b = bot(S.open) || {}; const empty = !input.value.trim() && !S.pending.length; @@ -1280,7 +1337,7 @@ async function send() { // 記憶 ticked above the composer (none of it if the shelf never answered: the brain chooses). const memories = b.busy ? undefined : memPicks(); memReset(); - input.value = ""; input.style.height = "auto"; $("composer").classList.remove("tall"); S.pending = []; renderChips(); + input.value = ""; input.style.height = "auto"; $("composer").classList.remove("tall"); S.pending = []; renderChips(); renderSlash(); if (!b.busy) { S.msgs.push({role: "user", text, attachments: [], memories: memories || []}); renderMsgs(); $("scroller").scrollTop = 1e9; } const body = {text, attachments}; if (memories) body.memories = memories; try { await api(base() + `api/bots/${S.open}/send`, {json: body}); if (b.busy) toast("已排入,Bot 會在下一步看到"); } catch (e) { toast(e.message); input.value = text; } diff --git a/src/app.rs b/src/app.rs index 9192486..9ab81f0 100644 --- a/src/app.rs +++ b/src/app.rs @@ -213,6 +213,9 @@ pub struct App { /// 記憶: the composer's suggestions per bot, and the memory page when open. mem_suggest: HashMap, mem_page: Option, + /// 技能: the composer's / list — the draft it was made for, the row that is lit, and whether + /// Esc closed it (until the / is gone). + slash: chat_ui::Slash, /// 傳送到其他裝置, when its dialog is open; and the device chosen last time. drop_page: Option, drop_last: String, @@ -372,6 +375,7 @@ impl App { page_view: None, mem_suggest: HashMap::new(), mem_page: None, + slash: Default::default(), drop_page: None, drop_last: String::new(), nightly_checked: None, @@ -2740,12 +2744,26 @@ impl App { // Enter sends, Shift+Enter is a new line, and Enter while an input method is // composing (e.g. picking Chinese characters) is left alone: index.eager-app `mwt` (). let composing = ui.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Ime(egui::ImeEvent::Preedit { text, .. }) if !text.is_empty()))); + let mut draft = self.drafts.remove(&bot.id).unwrap_or_default(); + // 技能: a / at the start lists them; ↑↓ choose, Enter or Tab puts the name in, Esc closes. + // (Not while it works: what is typed then joins the running turn.) + let mut slash = if streaming { vec![] } else { self.slash_list(&draft) }; + let mut slash_pick = None; + if had_focus && !composing && !slash.is_empty() { + slash_pick = self.slash_keys(ui, slash.len()); + } + // Esc: egui takes the focus away before the input sees the key, so it's the input's + // focus a frame ago that counts; the list closes and the input keeps the caret. + if !had_focus && self.slash.focused && !slash.is_empty() && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape)) { + self.slash.closed = true; + slash.clear(); + ui.memory_mut(|m| m.request_focus(composer_id)); + } if had_focus && !composing && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Enter)) { send_now = true; } self.attachments_poll(ctx, bot.id, had_focus); self.voice_poll(ctx); - let mut draft = self.drafts.remove(&bot.id).unwrap_or_default(); ui.add_space(4.0); // Quote and attachments sit just above the pill. if let Some(q) = self.quoting.get(&bot.id).cloned() { @@ -2774,6 +2792,17 @@ impl App { self.mem_suggest_tick(ctx, bot.id, &draft); self.mem_chips(ui, bot.id); } + if !slash.is_empty() { + slash_pick = slash_pick.or(self.slash_menu(ui, &slash)); + } + if let Some(i) = slash_pick { + draft = format!("/{} ", slash[i].0); + // The caret after the name, ready for what to do with it. + let mut s = egui::text_edit::TextEditState::load(ctx, composer_id).unwrap_or_default(); + s.cursor.set_char_range(Some(egui::text::CCursorRange::one(egui::text::CCursor::new(draft.chars().count())))); + s.store(ctx, composer_id); + ui.memory_mut(|m| m.request_focus(composer_id)); + } // The original's input: one 44 px pill — +, the words, the mic, and a round button in the // bot's colour (voice chat while empty, send ↑ once there is something to send). Frame::new() @@ -2892,6 +2921,7 @@ impl App { }); ui.add_space(10.0); self.drafts.insert(bot.id, draft); + self.slash.focused = ui.memory(|m| m.has_focus(composer_id)); if send_now { self.send(ctx, bot.id); ui.memory_mut(|m| m.request_focus(composer_id)); @@ -4224,6 +4254,18 @@ impl eframe::App for App { } } } + // ANYBOT_SHOT_KEYS="ArrowDown@50;Enter@54": press and release that key at that frame. + if let Ok(spec) = std::env::var("ANYBOT_SHOT_KEYS") { + for one in spec.split(';') { + let Some((name, at)) = one.split_once('@') else { continue }; + let (Some(key), Ok(at)) = (Key::from_name(name.trim()), at.trim().parse::()) else { continue }; + if self.frames + 1 == at { + for pressed in [true, false] { + raw.events.push(egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Default::default() }); + } + } + } + } let Ok(spec) = std::env::var("ANYBOT_SHOT_CLICK") else { return }; for one in spec.split(';') { let (pos, right) = match one.strip_suffix(":right") { Some(p) => (p, true), None => (one, false) }; @@ -4438,6 +4480,11 @@ fn group_history(messages: &[Message], speaker: Option, st: &State) -> Vec< // model's cache holds from the first message to the newest. if m.role == Role::User && !m.summary { m.context = crate::memory::context_of(&m, &st.timezone); + // 「/pptx …」: the person picked the skill, so the model reads it before anything else. + if let Some(k) = crate::memory::named_skill(&m.text, &st.skills) { + let line = crate::memory::named_skill_line(k); + m.context = if m.context.is_empty() { line } else { format!("{}\n{line}", m.context) }; + } } if !m.attachments.is_empty() { let (extra, images) = crate::attach::for_model(&m.attachments); @@ -4960,6 +5007,24 @@ mod tests { assert!(h1[1].context.is_empty(), "only the person's messages get the tail"); } + /// 「/pptx …」 picked from the composer's list: the model is told to read that skill first, + /// after the 送出時間; a / that names no skill (a path) gets nothing. + #[test] + fn a_named_skill_is_read_first() { + let mut st = State::demo(); + st.timezone = "Asia/Taipei".into(); + st.skills = vec![crate::memory::Skill { name: "pptx".into(), description: "簡報".into(), ..Default::default() }]; + let msgs = vec![ + Message { at: 1_762_826_400_000, ..Message::user("/pptx 把這份週報做成五頁簡報") }, + Message::assistant("好", "x"), + Message::user("/Users/daniel/a.txt 是什麼"), + ]; + let h = group_history(&msgs, None, &st); + assert_eq!(h[0].context, "〔送出時間:2025-11-11(週二)10:00〕\n〔使用者用 /pptx 指定了技能「pptx」:先用 use_skill 讀出它的完整做法,再照著做這件事〕"); + assert_eq!(h[0].text, "/pptx 把這份週報做成五頁簡報", "the person's words stay as typed"); + assert!(!h[2].context.contains("技能")); + } + /// What an earlier message in view already carried isn't carried again. #[test] fn a_memory_rides_once_per_chat() { diff --git a/src/app/channels_ui.rs b/src/app/channels_ui.rs index 13bcfe6..9df9ccc 100644 --- a/src/app/channels_ui.rs +++ b/src/app/channels_ui.rs @@ -38,13 +38,15 @@ pub struct ChannelUi { skill_busy: Arc, skill_reload: Arc, skill_note: Arc>>, + /// The last skill request came from the 技能 list (a delete): its answer shows there. + skill_note_list: bool, } impl Default for ChannelUi { fn default() -> Self { let (tx, rx) = channel(); let (trig_tx, trig_rx) = channel(); - ChannelUi { tx, rx, replies: HashMap::new(), waiting: VecDeque::new(), new_kind: Kind::Telegram, new_name: String::new(), new_token: String::new(), new_target: String::new(), new_bot: 0, note: Default::default(), started: false, trig_tx, trig_rx, trig_sig: String::new(), new_client: String::new(), new_tenant: String::new(), ms_login: Default::default(), mcp_sig: String::new(), mcp_errors: Default::default(), mcp_busy: Default::default(), new_mcp: Default::default(), focus_market: false, skill_src: String::new(), skill_open: None, skill_busy: Default::default(), skill_reload: Default::default(), skill_note: Default::default() } + ChannelUi { tx, rx, replies: HashMap::new(), waiting: VecDeque::new(), new_kind: Kind::Telegram, new_name: String::new(), new_token: String::new(), new_target: String::new(), new_bot: 0, note: Default::default(), started: false, trig_tx, trig_rx, trig_sig: String::new(), new_client: String::new(), new_tenant: String::new(), ms_login: Default::default(), mcp_sig: String::new(), mcp_errors: Default::default(), mcp_busy: Default::default(), new_mcp: Default::default(), focus_market: false, skill_src: String::new(), skill_open: None, skill_busy: Default::default(), skill_reload: Default::default(), skill_note: Default::default(), skill_note_list: false } } } @@ -362,25 +364,29 @@ impl App { let mut remove = None; for (i, s) in self.state.mcp_servers.iter_mut().enumerate() { setting_card(ui, p, |ui| { - ui.horizontal(|ui| { - ui.label(RichText::new(&s.name).strong().size(FONT_BASE)); - let (col, text) = match (s.enabled, status.get(&s.name), errors.iter().find(|e| e.0 == s.name)) { - (false, _, _) => (p.text3, "已關閉".to_string()), - (_, Some(n), _) => (Color32::from_rgb(0x14, 0xc3, 0x70), format!("已連上,{n} 個工具")), - (_, _, Some(e)) => (p.danger, e.1.clone()), - _ if busy => (p.text3, "連線中…".to_string()), - _ => (p.text3, "未連線".to_string()), - }; - let (r, _) = ui.allocate_exact_size(vec2(10.0, 10.0), egui::Sense::hover()); - ui.painter().circle_filled(r.center(), 4.0, col); - ui.add(egui::Label::new(RichText::new(text).size(11.5).color(p.text3)).truncate()); - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + let (col, text) = match (s.enabled, status.get(&s.name), errors.iter().find(|e| e.0 == s.name)) { + (false, _, _) => (p.text3, "已關閉".to_string()), + (_, Some(n), _) => (Color32::from_rgb(0x14, 0xc3, 0x70), format!("已連上,{n} 個工具")), + (_, _, Some(e)) => (p.danger, e.1.clone()), + _ if busy => (p.text3, "連線中…".to_string()), + _ => (p.text3, "未連線".to_string()), + }; + let name = s.name.clone(); + listing_row( + ui, + |ui| { if ui.add(egui::Button::new(RichText::new(t("移除")).size(12.0).color(p.danger)).frame(false)).clicked() { remove = Some(i); } ui.checkbox(&mut s.enabled, t("開啟")); - }); - }); + }, + |ui| { + ui.label(RichText::new(&name).strong().size(FONT_BASE)); + let (r, _) = ui.allocate_exact_size(vec2(10.0, 10.0), egui::Sense::hover()); + ui.painter().circle_filled(r.center(), 4.0, col); + ui.add(egui::Label::new(RichText::new(&text).size(11.5).color(p.text3)).truncate()).on_hover_text(&text); + }, + ); let what = if s.url.is_empty() { format!("{} {}", s.command, s.args.join(" ")) } else { s.url.clone() }; ui.label(RichText::new(what).monospace().size(11.5).color(p.text3)); field_label(ui, "給 Bot 的使用說明(選填)", p); @@ -399,32 +405,13 @@ impl App { } }); } - if self.ch.skill_reload.swap(false, Ordering::SeqCst) { + // A finished install: this computer's skill folder joins the list. (Not on a screen: its + // list is the brain's, and the brain installs there itself.) + if self.ch.skill_reload.swap(false, Ordering::SeqCst) && !self.mir.on { crate::memory::merge_skill_files(&mut self.state.skills); self.dirty = true; } let skill_busy = self.ch.skill_busy.load(Ordering::SeqCst); - let start_skill_install = |src: String, busy: &Arc, reload: &Arc, note: &Arc>>, ctx: &egui::Context| { - if busy.swap(true, Ordering::SeqCst) { - return; - } - *note.lock().unwrap() = None; - let (busy2, reload2, note2, ctx2) = (busy.clone(), reload.clone(), note.clone(), ctx.clone()); - std::thread::spawn(move || { - let res = crate::skills::install_from_source(&src); - match res { - Ok(name) => { - reload2.store(true, Ordering::SeqCst); - *note2.lock().unwrap() = Some((true, format!("已安裝技能「{name}」"))); - } - Err(e) => { - *note2.lock().unwrap() = Some((false, e)); - } - } - busy2.store(false, Ordering::SeqCst); - ctx2.request_repaint(); - }); - }; setting_card(ui, p, |ui| { setting_title(ui, "技能", "所有 Bot 共用的專業指南與標準作業流程(相容 Agent Skills SKILL.md 規格,支援隨附 scripts/ 與 references/)。開啟的技能會列在 Bot 的目錄中,需要時自動載入。", p); @@ -435,28 +422,33 @@ impl App { let mut dirty_toggle = false; for (i, k) in self.state.skills.iter_mut().enumerate() { let is_open = self.ch.skill_open.as_deref() == Some(k.name.as_str()); - ui.horizontal(|ui| { - let name_col = if k.enabled { p.text } else { p.text3 }; - ui.label(RichText::new(&k.name).strong().size(FONT_SM).color(name_col)).on_hover_text(&k.description); - if !k.resources.is_empty() { - ui.label(RichText::new(format!("{} 檔", k.resources.len())).size(11.0).color(p.accent)); - } - if !k.steps.is_empty() { - ui.label(RichText::new(format!("可重播 {} 步", k.steps.len())).size(11.0).color(p.text3)); - } - ui.add(egui::Label::new(RichText::new(&k.description).size(FONT_XS).color(p.text3)).truncate()); - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + let name_col = if k.enabled { p.text } else { p.text3 }; + let (name, description) = (k.name.clone(), k.description.clone()); + let (files, steps) = (k.resources.len(), k.steps.len()); + listing_row( + ui, + |ui| { if ui.add(egui::Button::new(RichText::new(t("刪除")).size(12.0).color(p.danger)).frame(false)).clicked() { remove = Some(i); } if ui.add(egui::Button::new(RichText::new(t(if is_open { "收起" } else { "檢視" })).size(12.0).color(p.text2)).frame(false)).clicked() { - self.ch.skill_open = if is_open { None } else { Some(k.name.clone()) }; + self.ch.skill_open = if is_open { None } else { Some(name.clone()) }; } if ui.checkbox(&mut k.enabled, t("開啟")).changed() { dirty_toggle = true; } - }); - }); + }, + |ui| { + ui.label(RichText::new(&name).strong().size(FONT_SM).color(name_col)).on_hover_text(&description); + if files > 0 { + ui.label(RichText::new(format!("{files} 檔")).size(11.0).color(p.accent)); + } + if steps > 0 { + ui.label(RichText::new(format!("可重播 {steps} 步")).size(11.0).color(p.text3)); + } + ui.add(egui::Label::new(RichText::new(&description).size(FONT_XS).color(p.text3)).truncate()).on_hover_text(&description); + }, + ); if is_open { egui::Frame::new() .fill(p.pane) @@ -477,12 +469,23 @@ impl App { self.dirty = true; } if let Some(i) = remove { - let gone = self.state.skills.remove(i); - crate::memory::remove_skill_files(&gone.name); - if self.ch.skill_open.as_deref() == Some(gone.name.as_str()) { - self.ch.skill_open = None; + if self.mir.on { + // The brain takes it off its list and its disk (a folder left there would + // bring it back when the brain restarts); the list here follows. + let name = self.state.skills[i].name.clone(); + self.ch.skill_note_list = true; + self.mirror_skill(serde_json::json!({"name": name, "remove": true}), self.ch.skill_note.clone(), self.ch.skill_busy.clone()); + } else { + let gone = self.state.skills.remove(i); + crate::memory::remove_skill_files(&gone.name); + if self.ch.skill_open.as_deref() == Some(gone.name.as_str()) { + self.ch.skill_open = None; + } + self.dirty = true; } - self.dirty = true; + } + if self.ch.skill_note_list { + skill_status(ui, &self.ch, skill_busy, p); } }); @@ -492,43 +495,56 @@ impl App { let mut add_builtin = None; for b in crate::skills::BUILTIN_SKILLS { let added = self.state.skills.iter().any(|s| s.name == b.slug); - ui.horizontal(|ui| { - ui.label(RichText::new(b.slug).strong().size(FONT_SM)); - ui.add(egui::Label::new(RichText::new(format!("{} — {}", b.title, b.summary)).size(FONT_XS).color(p.text3)).truncate()); - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + listing_row( + ui, + |ui| { if added { ui.label(RichText::new(t("已加入")).size(12.0).color(p.text3)); } else if ui.add(secondary_button("加入")).clicked() { add_builtin = Some(b.slug); } - }); - }); + }, + |ui| { + ui.label(RichText::new(b.slug).strong().size(FONT_SM)); + let about = format!("{} — {}", b.title, b.summary); + ui.add(egui::Label::new(RichText::new(&about).size(FONT_XS).color(p.text3)).truncate()).on_hover_text(&about); + }, + ); } if let Some(slug) = add_builtin { - match crate::skills::install_builtin(slug, &mut self.state.skills) { - Ok(name) => { - *self.ch.skill_note.lock().unwrap() = Some((true, format!("已加入技能「{name}」"))); - self.dirty = true; + self.ch.skill_note_list = false; + if self.mir.on { + self.mirror_skill(serde_json::json!({"builtin": slug}), self.ch.skill_note.clone(), self.ch.skill_busy.clone()); + } else { + match crate::skills::install_builtin(slug, &mut self.state.skills) { + Ok(name) => { + *self.ch.skill_note.lock().unwrap() = Some((true, format!("已加入技能「{name}」"))); + self.dirty = true; + } + Err(e) => *self.ch.skill_note.lock().unwrap() = Some((false, e)), } - Err(e) => *self.ch.skill_note.lock().unwrap() = Some((false, e)), } } ui.add_space(6.0); field_label(ui, "Anthropic 開源技能精選(GitHub: anthropics/skills)", p); + let mut install = None; for r in crate::skills::REMOTE_MARKET { let added = self.state.skills.iter().any(|s| s.name == r.name); - ui.horizontal(|ui| { - ui.label(RichText::new(r.name).strong().size(FONT_SM)); - ui.add(egui::Label::new(RichText::new(r.summary).size(FONT_XS).color(p.text3)).truncate()); - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + listing_row( + ui, + |ui| { if added { ui.label(RichText::new(t("已加入")).size(12.0).color(p.text3)); } else if ui.add_enabled(!skill_busy, secondary_button("安裝")).clicked() { - start_skill_install(r.source.to_string(), &self.ch.skill_busy, &self.ch.skill_reload, &self.ch.skill_note, ctx); + install = Some(r.source.to_string()); } - }); - }); + }, + |ui| { + ui.label(RichText::new(r.name).strong().size(FONT_SM)); + ui.add(egui::Label::new(RichText::new(r.summary).size(FONT_XS).color(p.text3)).truncate()).on_hover_text(r.summary); + }, + ); } ui.add_space(8.0); @@ -545,14 +561,14 @@ impl App { let can_install = !skill_busy && !self.ch.skill_src.trim().is_empty(); let enter = resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); if ui.add_enabled(can_install, primary_button("安裝", p)).clicked() || (can_install && enter) { - let src = std::mem::take(&mut self.ch.skill_src); - start_skill_install(src, &self.ch.skill_busy, &self.ch.skill_reload, &self.ch.skill_note, ctx); + install = Some(std::mem::take(&mut self.ch.skill_src)); } }); - if skill_busy { - ui.label(RichText::new(t("正在下載並安裝技能套件…")).size(FONT_XS).color(p.text3)); - } else if let Some((ok, msg)) = self.ch.skill_note.lock().unwrap().clone() { - ui.label(RichText::new(msg).size(FONT_XS).color(if ok { Color32::from_rgb(0x14, 0xc3, 0x70) } else { p.danger })); + if let Some(src) = install { + self.skill_install(src, ctx); + } + if !self.ch.skill_note_list { + skill_status(ui, &self.ch, skill_busy, p); } }); // 外掛市集: common connectors, one click away (ones needing a key fill the form below). @@ -563,10 +579,9 @@ impl App { setting_title(ui, "連接器市集", "常用的連接器,按「加入」就能用。需要金鑰的會填好下面的表單,補上金鑰再按「新增」。本機的需要先裝 Node.js(npx)或 uv(uvx)。", p); for (name, desc, cmd, needs) in crate::mcp::MARKET { let added = self.state.mcp_servers.iter().any(|s| s.name == name); - ui.horizontal(|ui| { - ui.label(RichText::new(name).strong().size(FONT_SM)); - ui.add(egui::Label::new(RichText::new(desc).size(FONT_XS).color(p.text3)).truncate()); - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + listing_row( + ui, + |ui| { if added { ui.label(RichText::new(t("已加入")).size(12.0).color(p.text3)); } else if ui.add(secondary_button("加入")).clicked() { @@ -576,8 +591,12 @@ impl App { self.ch.new_mcp = (name.to_string(), cmd.to_string(), if cmd.starts_with("http") { String::new() } else { needs.to_string() }, if cmd.starts_with("http") { needs.to_string() } else { String::new() }); } } - }); - }); + }, + |ui| { + ui.label(RichText::new(name).strong().size(FONT_SM)); + ui.add(egui::Label::new(RichText::new(desc).size(FONT_XS).color(p.text3)).truncate()).on_hover_text(desc); + }, + ); } }); setting_card(ui, p, |ui| { @@ -622,6 +641,59 @@ impl App { } } +impl App { + /// Install a skill from an address or a folder. On a screen the brain does it — it fetches + /// an address itself, and a folder on this computer goes up whole — since the bots read skills + /// from the brain's disk. Otherwise it is fetched in the background and the list reloads. + fn skill_install(&mut self, src: String, ctx: &egui::Context) { + self.ch.skill_note_list = false; + let (busy, note) = (self.ch.skill_busy.clone(), self.ch.skill_note.clone()); + let src = src.trim().to_string(); + if self.mir.on { + let body = if crate::tools::expand_home(&src).exists() { serde_json::json!({"local": src}) } else { serde_json::json!({"install": src}) }; + self.mirror_skill(body, note, busy); + return; + } + if busy.swap(true, Ordering::SeqCst) { + return; + } + *note.lock().unwrap() = None; + let (reload, ctx) = (self.ch.skill_reload.clone(), ctx.clone()); + std::thread::spawn(move || { + *note.lock().unwrap() = Some(match crate::skills::install_from_source(&src) { + Ok(name) => { + reload.store(true, Ordering::SeqCst); + (true, format!("已安裝技能「{name}」")) + } + Err(e) => (false, e), + }); + busy.store(false, Ordering::SeqCst); + ctx.request_repaint(); + }); + } +} + +/// How the last skill request went (or that it is still on its way). +fn skill_status(ui: &mut egui::Ui, ch: &ChannelUi, busy: bool, p: Palette) { + if busy { + ui.label(RichText::new(t("處理中…")).size(FONT_XS).color(p.text3)); + } else if let Some((ok, msg)) = ch.skill_note.lock().unwrap().clone() { + ui.label(RichText::new(msg).size(FONT_XS).color(if ok { Color32::from_rgb(0x14, 0xc3, 0x70) } else { p.danger })); + } +} + +/// One line of a list: its buttons on the right (`buttons` adds them rightmost first), and the +/// words on the left in the room that is left — a long description ends in … before the +/// buttons instead of running under them. +fn listing_row(ui: &mut egui::Ui, buttons: impl FnOnce(&mut egui::Ui), words: impl FnOnce(&mut egui::Ui)) { + ui.horizontal(|ui| { + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + buttons(ui); + ui.with_layout(Layout::left_to_right(Align::Center), words); + }); + }); +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/app/chat_ui.rs b/src/app/chat_ui.rs index aff33eb..c10aa9f 100644 --- a/src/app/chat_ui.rs +++ b/src/app/chat_ui.rs @@ -588,8 +588,103 @@ impl App { ui.ctx().request_repaint(); } } + + /// The / list for this draft: each skill's name and what it is for (empty when the draft + /// isn't asking, or Esc closed it). A new draft lights the first row again. + pub(super) fn slash_list(&mut self, draft: &str) -> Vec<(String, String)> { + if !draft.starts_with('/') { + self.slash.closed = false; + } + if self.slash.closed { + return vec![]; + } + let list: Vec<(String, String)> = crate::memory::slash_matches(draft, &self.state.skills).unwrap_or_default().into_iter().map(|k| (k.name.clone(), k.description.clone())).collect(); + if draft != self.slash.draft { + self.slash.draft = draft.to_string(); + self.slash.lit = 0; + } + self.slash.lit = self.slash.lit.min(list.len().saturating_sub(1)); + list + } + + /// The keys the / list takes before the input sees them: ↑↓ move, Enter or Tab picks the + /// lit row. (Esc is the composer's: egui has taken the focus by the time it arrives.) + pub(super) fn slash_keys(&mut self, ui: &mut egui::Ui, n: usize) -> Option { + use egui::{Key, Modifiers}; + ui.input_mut(|i| { + if i.consume_key(Modifiers::NONE, Key::ArrowDown) { + self.slash.lit = (self.slash.lit + 1) % n; + self.slash.moved = true; + } + if i.consume_key(Modifiers::NONE, Key::ArrowUp) { + self.slash.lit = (self.slash.lit + n - 1) % n; + self.slash.moved = true; + } + (i.consume_key(Modifiers::NONE, Key::Enter) || i.consume_key(Modifiers::NONE, Key::Tab)).then_some(self.slash.lit) + }) + } + + /// The / list just above the input: 「/名稱」 and what it is for, the lit row shaded; a click + /// picks. Six rows show, the rest scroll. + pub(super) fn slash_menu(&mut self, ui: &mut egui::Ui, list: &[(String, String)]) -> Option { + let p = self.pal; + let mut picked = None; + let moved = std::mem::take(&mut self.slash.moved); + Frame::new() + .fill(p.elevated) + .stroke(Stroke::new(1.0, p.border)) + .corner_radius(14) + .inner_margin(Margin::symmetric(6, 6)) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + ui.add_space(10.0); + ui.label(RichText::new(t("技能 · ↑↓ 選擇,Enter 帶入,Esc 關閉")).size(11.0).color(p.text3)); + }); + // Its full height even when the composer had less room last frame (the + // composer's room is last frame's height, so a squeezed list would stay squeezed). + let h = SLASH_ROWS.min(list.len() as f32) * SLASH_ROW_H; + egui::ScrollArea::vertical().id_salt("slash-list").max_height(h).min_scrolled_height(h).show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + for (i, (name, about)) in list.iter().enumerate() { + let (rect, r) = ui.allocate_exact_size(vec2(ui.available_width(), SLASH_ROW_H), egui::Sense::click()); + let lit = i == self.slash.lit; + if lit || r.hovered() { + ui.painter().rect_filled(rect, 9, if lit { p.active } else { p.hover }); + } + if lit && moved { + r.scroll_to_me(None); + } + let mut row = ui.new_child(egui::UiBuilder::new().max_rect(rect.shrink2(vec2(10.0, 0.0))).layout(Layout::left_to_right(Align::Center))); + // Not selectable: a selectable label takes the click the row is waiting for. + row.add(egui::Label::new(RichText::new(format!("/{name}")).strong().size(FONT_SM).color(p.text)).selectable(false)); + row.add(egui::Label::new(RichText::new(about).size(FONT_XS).color(p.text3)).truncate().selectable(false)); + if r.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() { + picked = Some(i); + } + } + }); + }); + ui.add_space(4.0); + picked + } } +/// The composer's / list (技能): the draft it was made for, which row is lit, whether ↑↓ just +/// moved it (so it scrolls into view), whether Esc closed it, and whether the input had the +/// focus last frame (Esc arrives after egui has taken it). +#[derive(Default)] +pub struct Slash { + draft: String, + lit: usize, + moved: bool, + pub(super) closed: bool, + pub(super) focused: bool, +} + +const SLASH_ROWS: f32 = 6.0; +const SLASH_ROW_H: f32 = 30.0; + /// After a press of 回到底部: still pulling down (`Some`), or done once the chat is at its bottom /// or [`JUMP_BOTTOM_SECS`] have passed (new words can keep it from ever quite arriving). fn jump_still_on(since: Option, from_bottom: f32, now: f64) -> Option { diff --git a/src/app/mirror_ui.rs b/src/app/mirror_ui.rs index 10b86d7..177c826 100644 --- a/src/app/mirror_ui.rs +++ b/src/app/mirror_ui.rs @@ -9,6 +9,7 @@ // window stays readable and waits. use super::*; +use crate::memory::Skill; use crate::remote::{self, SyncKind}; use serde_json::{json, Value}; use std::hash::{Hash, Hasher}; @@ -360,7 +361,21 @@ enum Out { Edit { seq: u64, ops: Vec }, Act(Value), Send { bot: u64, text: String, atts: Vec, memories: Option> }, - Move { ops: Vec, n: usize }, + Move { ops: Vec, n: usize, skills: Vec }, + /// 技能 on a screen: done at the brain (see [`App::mirror_skill`]); the answer goes to `note`. + Skill { body: Value, note: SkillNote, busy: Arc }, +} + +/// Where a skill request's answer is shown: (worked, words). +pub(super) type SkillNote = Arc>>; + +/// What the brain is asked for a skill request: a folder or `.md` file named by its path on this +/// computer (`{"local": …}`) goes up whole, read here — the brain can't see this disk. +fn skill_request(body: Value) -> Result { + match body["local"].as_str() { + Some(p) => Ok(json!({"package": crate::skills::package_from_path(&crate::tools::expand_home(p))?})), + None => Ok(body), + } } /// The bots whose turn ended well since the last update (`seen` keeps when each bot's last turn @@ -1209,12 +1224,28 @@ impl App { resync.store(true, Ordering::SeqCst); } } - Out::Move { ops, n } => { - *note.lock().unwrap() = match remote::sync_post(&s, "edit", &json!({"ops": ops})) { - Ok(_) if n == 0 => "已同步:大腦上已經有這台的 Bot;模型金鑰、技能和連接器有缺的已補上".into(), + Out::Move { ops, n, skills } => { + let mut said = match remote::sync_post(&s, "edit", &json!({"ops": ops})) { + Ok(_) if n == 0 => "已同步:大腦上已經有這台的 Bot;模型金鑰、技能和連接器有缺的已補上".to_string(), Ok(_) => format!("已把 {n} 個 Bot(連同聊天)搬到大腦"), Err(e) => format!("搬移失敗:{e}"), }; + // This computer's skills go up whole (with their files), one by one. + let failed: Vec = skills + .iter() + .filter_map(|k| crate::skills::package_of(k).and_then(|p| remote::sync_post(&s, "skill", &json!({"package": p}))).err().map(|e| format!("「{}」:{e}", k.name))) + .collect(); + if !failed.is_empty() { + said.push_str(&format!(";這些技能沒有搬過去:{}", failed.join("、"))); + } + *note.lock().unwrap() = said; + busy.store(false, Ordering::SeqCst); + } + Out::Skill { body, note, busy } => { + *note.lock().unwrap() = Some(match skill_request(body).and_then(|b| remote::sync_post(&s, "skill", &b)) { + Ok(v) => (true, v["text"].as_str().unwrap_or("好了").to_string()), + Err(e) => (false, e), + }); busy.store(false, Ordering::SeqCst); } } @@ -1232,6 +1263,25 @@ impl App { self.mirror_out(Out::Act(body)); } + /// 技能 on a screen — add one from the market, install from an address or a folder here, + /// delete one — is done by the brain: the bots read skills from the brain's disk, and a + /// folder left there would bring a deleted skill back when the brain restarts. Turning one + /// on or off stays an ordinary edit. Edits made before go first. + pub(super) fn mirror_skill(&mut self, body: Value, note: SkillNote, busy: Arc) { + if !self.mir.online { + *note.lock().unwrap() = Some((false, "連不到大腦,技能沒有改。".into())); + return; + } + if busy.swap(true, Ordering::SeqCst) { + return; + } + *note.lock().unwrap() = None; + if self.dirty { + self.mirror_save(); + } + self.mirror_out(Out::Skill { body, note, busy }); + } + /// Send a message through the brain: files go up first, then the text. pub(super) fn mirror_send(&mut self, bot: u64, text: String, atts: Vec, memories: Option>) -> bool { if !self.mir.online { @@ -1274,12 +1324,15 @@ impl App { ops.push(json!({"op": "bot_add", "bot": v})); } let top = serde_json::to_value(&local).unwrap_or(Value::Null); - for k in ["providers", "skills", "mcp_servers"] { + for k in ["providers", "mcp_servers"] { ops.push(json!({"op": "merge", "key": k, "value": top[k]})); } + // Skills the brain doesn't have yet go up with their files (a bare entry in the list + // would leave its scripts on this computer). + let skills: Vec = local.skills.iter().filter(|k| !self.state.skills.iter().any(|b| b.name == k.name)).cloned().collect(); let n = moving.len(); *self.mir.move_note.lock().unwrap() = "搬移中…".into(); - self.mirror_out(Out::Move { ops, n }); + self.mirror_out(Out::Move { ops, n, skills }); } /// The bar above the chat while showing a brain. @@ -1444,6 +1497,25 @@ mod tests { assert_eq!(brain["bots"][0]["memories"], json!(["y", "z"])); } + /// A skill folder named on a screen goes up read here (the brain can't see this disk); an + /// address, a market name or a delete goes as it is. + #[test] + fn a_skill_folder_here_goes_up_whole() { + let src = std::env::temp_dir().join(format!("anybot-screen-pkg-{}", std::process::id())); + std::fs::create_dir_all(src.join("references")).unwrap(); + std::fs::write(src.join("SKILL.md"), "---\nname: 週報\ndescription: 整理每週進度\n---\n\n照 references/a.md 寫\n").unwrap(); + std::fs::write(src.join("references/a.md"), "# 格式").unwrap(); + let b = skill_request(json!({"local": src.display().to_string()})).unwrap(); + assert!(b["package"]["skill_md"].as_str().unwrap().contains("name: 週報")); + assert_eq!(b["package"]["files"][0]["path"], "references/a.md"); + assert!(b.get("local").is_none(), "no path of this computer goes to the brain"); + std::fs::remove_dir_all(&src).unwrap(); + for as_is in [json!({"install": "https://github.com/anthropics/skills/tree/main/skills/pdf"}), json!({"builtin": "pdf"}), json!({"name": "週報", "remove": true})] { + assert_eq!(skill_request(as_is.clone()).unwrap(), as_is); + } + assert!(skill_request(json!({"local": "/nonexistent/anybot-skill"})).is_err()); + } + #[test] fn lists_without_names_are_sent_whole() { let p = patch_of(&json!([[1], [2]]), &json!([[2]])); diff --git a/src/app/remote_ui.rs b/src/app/remote_ui.rs index ae70093..bd0d2db 100644 --- a/src/app/remote_ui.rs +++ b/src/app/remote_ui.rs @@ -1285,6 +1285,30 @@ impl App { Err(e) => fail(&e), }; } + // From a screen (設定 › 整合 on a computer showing this brain): a GitHub or web + // address is fetched here, and a folder on that computer arrives whole — the + // bots read skills from this disk. + if let Some(src) = b["install"].as_str().filter(|s| !s.trim().is_empty()) { + return match crate::skills::install_from_source(src) { + Ok(name) => { + crate::memory::merge_skill_files(&mut self.state.skills); + self.dirty = true; + done(&format!("已安裝技能「{name}」")) + } + Err(e) => fail(&e), + }; + } + if b["package"].is_object() { + return match crate::skills::install_package(&b["package"]) { + Ok(k) => { + let name = k.name.clone(); + crate::memory::upsert_skill(&mut self.state.skills, k); + self.dirty = true; + done(&format!("已安裝技能「{name}」")) + } + Err(e) => fail(&e), + }; + } let name = s("name"); if !self.state.skills.iter().any(|k| k.name == name) { return fail("找不到這個技能"); @@ -1538,6 +1562,37 @@ mod phone_act_tests { assert!(app.state.bot(gid).is_none() && app.state.bot(app.state.primary_bot).is_some()); } + /// 技能 from a screen are the brain's to do: a folder from that computer lands on the brain's + /// disk whole (text and binary files), and a delete takes the folder too, so the next start + /// doesn't bring the skill back. + #[test] + fn a_screen_hands_a_skill_to_the_brain_and_takes_it_away() { + let (ctx, mut app) = demo(); + let name = format!("螢幕交來的技能-{}", std::process::id()); + let src = std::env::temp_dir().join(format!("anybot-screen-skill-{}", std::process::id())); + std::fs::create_dir_all(src.join("scripts")).unwrap(); + std::fs::write(src.join("SKILL.md"), format!("---\nname: {name}\ndescription: 測試用\n---\n\n先跑 scripts/go.py\n")).unwrap(); + std::fs::write(src.join("scripts/go.py"), "print('hi')\n").unwrap(); + std::fs::write(src.join("scripts/logo.bin"), [0u8, 159, 146, 150]).unwrap(); + let pkg = crate::skills::package_from_path(&src).unwrap(); + // (The brain never sees the screen's disk.) + std::fs::remove_dir_all(&src).unwrap(); + let r = app.phone_act(&ctx, "skill", &json!({"package": pkg}), "owner"); + assert_eq!(r["ok"], true, "{r}"); + let k = app.state.skills.iter().find(|k| k.name == name).cloned().expect("on the brain's list"); + assert_eq!(k.resources, ["scripts/go.py", "scripts/logo.bin"]); + assert_eq!(crate::skills::read_resource(&k, "scripts/go.py").unwrap(), "print('hi')\n"); + let dir = crate::skills::resolve_skill_dir(&k).expect("a folder on the brain"); + assert_eq!(std::fs::read(dir.join("scripts/logo.bin")).unwrap(), [0u8, 159, 146, 150]); + // Deleted from the screen: off the list and off the disk. + assert_eq!(app.phone_act(&ctx, "skill", &json!({"name": name, "remove": true}), "owner")["ok"], true); + assert!(!dir.exists()); + crate::memory::merge_skill_files(&mut app.state.skills); + assert!(!app.state.skills.iter().any(|k| k.name == name), "a restart doesn't bring it back"); + // Only the owner's. + assert!(app.phone_act(&ctx, "skill", &json!({"builtin": "pdf"}), "admin")["error"].is_string()); + } + #[test] fn the_phone_never_gets_keys_or_secrets() { let (ctx, mut app) = demo(); diff --git a/src/memory.rs b/src/memory.rs index 4bffda8..7794711 100644 --- a/src/memory.rs +++ b/src/memory.rs @@ -602,6 +602,53 @@ pub fn prompt_section(pinned: &[String], skills: &[Skill]) -> String { s } +/// 「/名稱 …」 at the start of a message: the skill the person named (picked from the / list +/// under the composer, or typed). Only a skill that is on; the longest name wins, so a name +/// with a space in it is found too. +pub fn named_skill<'a>(text: &str, skills: &'a [Skill]) -> Option<&'a Skill> { + let rest = text.trim_start().strip_prefix('/')?; + skills + .iter() + .filter(|k| k.enabled && !k.name.is_empty()) + .filter(|k| rest.strip_prefix(k.name.as_str()).is_some_and(|after| after.chars().next().is_none_or(char::is_whitespace))) + .max_by_key(|k| k.name.len()) +} + +/// What the model reads after a message that names a skill. +pub fn named_skill_line(k: &Skill) -> String { + format!("〔使用者用 /{0} 指定了技能「{0}」:先用 use_skill 讀出它的完整做法,再照著做這件事〕", k.name) +} + +/// The composer's / list for a draft like 「/pp」: the skills that are on, those whose name +/// starts with what is typed first, then names containing it, then descriptions. None once the +/// draft is not a / at its start, or a space ends the name (the person has moved on). +pub fn slash_matches<'a>(draft: &str, skills: &'a [Skill]) -> Option> { + let q = draft.strip_prefix('/')?; + if q.chars().any(char::is_whitespace) { + return None; + } + let q = q.to_lowercase(); + let mut hits: Vec<(u8, &Skill)> = skills + .iter() + .filter(|k| k.enabled && !k.name.is_empty()) + .filter_map(|k| { + let name = k.name.to_lowercase(); + let rank = if name.starts_with(&q) { + 0 + } else if name.contains(&q) { + 1 + } else if k.description.to_lowercase().contains(&q) { + 2 + } else { + return None; + }; + Some((rank, k)) + }) + .collect(); + hits.sort_by_key(|(rank, _)| *rank); + Some(hits.into_iter().map(|(_, k)| k).collect()) +} + /// Near enough to be the same memory said again (words or meaning). const SAME_SCORE: f32 = 0.85; /// Shared words over all words (words and two-character pairs) from which two lines are one. @@ -1093,6 +1140,31 @@ mod tests { assert!(learned_note("Threads 發文附圖", true).contains("學會了新做法「Threads 發文附圖」")); } + /// The composer's / list and what a sent 「/名稱」 names: only skills that are on, a name with + /// a space in it whole, and nothing once the name is followed by more of a word. + #[test] + fn a_slash_names_a_skill() { + let k = |name: &str, description: &str, enabled: bool| Skill { name: name.into(), description: description.into(), enabled, ..Default::default() }; + let skills = vec![k("pdf", "PDF 檔", true), k("pptx", "簡報投影片", true), k("web-design", "網頁與儀表板", true), k("訂 pizza", "在網站上訂披薩", true), k("pptx-old", "舊的", false)]; + let names = |d: &str| slash_matches(d, &skills).map(|v| v.iter().map(|k| k.name.clone()).collect::>()); + assert_eq!(names("/").unwrap(), ["pdf", "pptx", "web-design", "訂 pizza"], "every skill that is on, in its order"); + assert_eq!(names("/P").unwrap(), ["pdf", "pptx", "訂 pizza"], "name first; case doesn't matter"); + assert_eq!(names("/簡報").unwrap(), ["pptx"], "a description finds it too"); + assert_eq!(names("/design").unwrap(), ["web-design"]); + assert_eq!(names("/pptx 做五頁"), None, "a space: the name is done, the list goes"); + assert_eq!(names("幫我 /pdf"), None, "only a / at the start"); + assert!(names("/zzz").unwrap().is_empty()); + + let named = |t: &str| named_skill(t, &skills).map(|k| k.name.clone()); + assert_eq!(named("/pptx 把週報做成簡報").as_deref(), Some("pptx")); + assert_eq!(named(" /pdf").as_deref(), Some("pdf"), "the name alone, spaces before it"); + assert_eq!(named("/訂 pizza 兩個大的").as_deref(), Some("訂 pizza"), "a name with a space"); + assert_eq!(named("/pptxx 做簡報"), None, "more of a word is another name"); + assert_eq!(named("/pptx-old 做簡報"), None, "a skill that is off"); + assert_eq!(named("/Users/me/a.pdf"), None); + assert!(named_skill_line(&skills[1]).contains("use_skill") && named_skill_line(&skills[1]).contains("「pptx」")); + } + #[test] fn a_skill_round_trips_through_a_file() { let sk = Skill { diff --git a/src/remote.rs b/src/remote.rs index d48fbdd..549ee31 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -615,6 +615,9 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { _ => Resp::error(404, "大腦上找不到這個檔案"), } } + // 技能 from a screen: add, install, hand over a folder, delete — done here, where the + // bots read them (the files land on this disk, and a deleted one's folder goes too). + ("POST", ["api", "sync", "skill"]) => phone_act_for("skill", req.json(), "owner", 55), ("POST", ["api", "sync", "act"]) => { let b = req.json(); let bot = b["bot"].as_u64().unwrap_or(0); @@ -662,7 +665,12 @@ fn picks_of(b: &Value) -> Option> { /// account) may run tools here. /// A phone action carried out on the app's thread (where the state is), with its answer. fn phone_act(action: &str, body: Value, role: &str) -> Resp { - match hub().ask_sync_for(SyncKind::Phone { action: action.to_string(), body, role: role.to_string() }, 20) { + phone_act_for(action, body, role, 20) +} + +/// [`phone_act`], waiting up to `secs` (installing a skill from GitHub takes a while). +fn phone_act_for(action: &str, body: Value, role: &str, secs: u64) -> Resp { + match hub().ask_sync_for(SyncKind::Phone { action: action.to_string(), body, role: role.to_string() }, secs) { Ok(v) if v.get("error").is_some() => Resp::error(400, v["error"].as_str().unwrap_or("做不到")), Ok(v) => Resp::json(&v), Err(e) => Resp::error(503, &e), diff --git a/src/skills.rs b/src/skills.rs index 9534597..68208b7 100644 --- a/src/skills.rs +++ b/src/skills.rs @@ -798,25 +798,9 @@ fn install_from_github(spec: &GitHubSpec) -> Result { } fn install_from_local_dir(dir: &Path) -> Result { - let md_path = [dir.join("SKILL.md"), dir.join("skill.md")] - .into_iter() - .find(|p| p.is_file()) - .ok_or_else(|| format!("資料夾「{}」裡找不到 SKILL.md", dir.display()))?; - let md_text = std::fs::read_to_string(&md_path).map_err(|e| format!("讀不到 SKILL.md:{e}"))?; + let (md_text, extra) = read_package(dir)?; let mut skill = parse_skill_markdown(&md_text).ok_or("SKILL.md 開頭需要有 name: 欄位")?; skill.source = dir.display().to_string(); - let rels = discover_resources(dir); - let mut extra = vec![]; - let mut total = 0usize; - for r in rels { - let p = dir.join(&r); - let bytes = std::fs::read(&p).map_err(|e| e.to_string())?; - total += bytes.len(); - if total > MAX_PACKAGE_BYTES { - return Err("技能資料夾超過大小上限(6 MB)".into()); - } - extra.push((r, bytes)); - } let extra_n = extra.len(); write_skill_package(&skill, &extra)?; Ok(if extra_n > 0 { @@ -826,6 +810,96 @@ fn install_from_local_dir(dir: &Path) -> Result { }) } +/// A skill as files: its `SKILL.md`, and each bundled file's relative path and bytes. +type Package = (String, Vec<(String, Vec)>); + +/// A skill folder on this disk: its `SKILL.md` and the files that come with it (within the +/// package limits). +fn read_package(dir: &Path) -> Result { + let md_path = [dir.join("SKILL.md"), dir.join("skill.md")] + .into_iter() + .find(|p| p.is_file()) + .ok_or_else(|| format!("資料夾「{}」裡找不到 SKILL.md", dir.display()))?; + let md_text = std::fs::read_to_string(&md_path).map_err(|e| format!("讀不到 SKILL.md:{e}"))?; + let mut extra = vec![]; + let mut total = 0usize; + for r in discover_resources(dir) { + let bytes = std::fs::read(dir.join(&r)).map_err(|e| e.to_string())?; + total += bytes.len(); + if total > MAX_PACKAGE_BYTES { + return Err("技能資料夾超過大小上限(6 MB)".into()); + } + extra.push((r, bytes)); + } + Ok((md_text, extra)) +} + +// ---------- A skill handed from a screen to its brain ---------- +// +// The bots run on the brain and read skills from the brain's own disk, so a skill a screen has +// (a folder picked on that computer, or its own skills moved over) goes up whole: `SKILL.md` and +// every file with it, as one JSON value. + +fn package_json(skill_md: String, files: Vec<(String, Vec)>, source: &str, enabled: bool) -> serde_json::Value { + use base64::Engine; + let files: Vec = files.into_iter().map(|(path, bytes)| serde_json::json!({"path": path, "b64": base64::engine::general_purpose::STANDARD.encode(bytes)})).collect(); + serde_json::json!({"skill_md": skill_md, "files": files, "source": source, "enabled": enabled}) +} + +/// A folder with a `SKILL.md`, or one `.md` file, on this computer — as a package. +pub fn package_from_path(p: &Path) -> Result { + if p.is_dir() { + let (md, files) = read_package(p)?; + return Ok(package_json(md, files, &p.display().to_string(), true)); + } + let md = std::fs::read_to_string(p).map_err(|e| format!("讀不到檔案:{e}"))?; + Ok(package_json(md, vec![], &p.display().to_string(), true)) +} + +/// One of this computer's skills as a package: its folder when it has one (the files win, as at +/// start), or else the list's own entry written out as a `SKILL.md`. +pub fn package_of(k: &Skill) -> Result { + let (md, files) = match resolve_skill_dir(k) { + Some(dir) => read_package(&dir)?, + None => (render_skill_markdown(k), vec![]), + }; + Ok(package_json(md, files, &k.source, k.enabled)) +} + +/// The brain's side: write the package into `/skills//` and give back the skill as +/// the list keeps it. +pub fn install_package(v: &serde_json::Value) -> Result { + use base64::Engine; + let md = v["skill_md"].as_str().ok_or("技能內容是空的")?; + let mut skill = parse_skill_markdown(md).ok_or("SKILL.md 開頭需要有 name: 欄位")?; + let list = v["files"].as_array().map(Vec::as_slice).unwrap_or_default(); + if list.len() > MAX_PACKAGE_FILES { + return Err(format!("技能的隨附檔案太多(最多 {MAX_PACKAGE_FILES} 個)")); + } + let mut files = vec![]; + let mut total = 0usize; + for f in list { + let path = f["path"].as_str().unwrap_or("").to_string(); + // Every path checked before anything is written: a refused package leaves no folder + // behind (one would put the skill on the list at the next start). + if safe_rel_path(&path).is_none() { + return Err(format!("不允許的隨附檔案路徑:{path}")); + } + let bytes = base64::engine::general_purpose::STANDARD.decode(f["b64"].as_str().unwrap_or("")).map_err(|_| format!("隨附檔案「{path}」壞了"))?; + total += bytes.len(); + if total > MAX_PACKAGE_BYTES { + return Err("技能資料夾超過大小上限(6 MB)".into()); + } + files.push((path, bytes)); + } + skill.enabled = v["enabled"].as_bool().unwrap_or(skill.enabled); + skill.source = v["source"].as_str().unwrap_or("").to_string(); + let dir = write_skill_package(&skill, &files)?; + skill.dir = dir.display().to_string(); + skill.resources = discover_resources(&dir); + Ok(skill) +} + /// Universal installer: accepts `builtin:`, a local skill folder, a local `.md` file, /// a GitHub tree/blob URL or `owner/repo/path` shorthand, or any `http(s)://` `.md` URL. pub fn install_from_source(src: &str) -> Result { @@ -880,6 +954,37 @@ pub fn install_from_source(src: &str) -> Result { Err(format!("找不到路徑或無法識別的技能來源:「{src}」")) } +#[cfg(test)] +mod package_tests { + use super::*; + + /// A skill with no folder (learned in a chat) goes up as its list entry written out: the + /// steps a replay follows and its off switch come through. + #[test] + fn a_skill_without_a_folder_goes_up_as_written() { + let name = format!("學會的做法-{}", std::process::id()); + let k = Skill { + name: name.clone(), + description: "訂 pizza".into(), + instructions: "打開網站,選大的".into(), + steps: vec![crate::memory::ReplayStep { tool: "shell".into(), args: "{\"cmd\":\"date\"}".into(), targets: vec![] }], + enabled: false, + source: "learned".into(), + ..Default::default() + }; + assert!(resolve_skill_dir(&k).is_none()); + let back = install_package(&package_of(&k).unwrap()).unwrap(); + assert_eq!((back.name.as_str(), back.instructions.as_str(), back.enabled, back.source.as_str()), (name.as_str(), "打開網站,選大的", false, "learned")); + assert_eq!(back.steps, k.steps); + let _ = std::fs::remove_dir_all(&back.dir); + // Nothing outside its folder, and nothing too big. + let refused = format!("不收的-{}", std::process::id()); + let bad = serde_json::json!({"skill_md": format!("---\nname: {refused}\ndescription: y\n---\n\nz"), "files": [{"path": "../evil.sh", "b64": ""}]}); + assert!(install_package(&bad).is_err()); + assert!(!crate::memory::skill_dir().join(slug_of(&refused)).exists(), "a refused package leaves no folder"); + } +} + #[cfg(test)] mod tests { use super::*;