From deec40fd02445730d3794bf38243d319b35c7812 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 20:53:27 +0800 Subject: [PATCH] =?UTF-8?q?=E8=BC=B8=E5=85=A5=E6=A1=86:=20Shift+Enter=20is?= =?UTF-8?q?=20a=20new=20line=20and=20goes=20on=20with=20a=20list,=20the=20?= =?UTF-8?q?box=20grows=20with=20its=20words;=20the=20working=20row=20says?= =?UTF-8?q?=20what=20the=20bot=20is=20doing?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Shift+Enter made a new line in name only: egui's shortcut matching ignores Shift unless asked, so it sent the message too; Enter and Shift+Enter are now read by hand (the / list takes plain Enter only) - Shift+Enter on 「1. 買菜」 starts 「2. 」 (also 「9) 」→「10) 」, 「1、」, 「- 」「* 」「• 」, 「- [ ] 」, with the indent); on an empty item it ends the list - the words box sat in a 28 px slot, so its scroll area stopped at 64 px and cut lines off; it now grows with the words (15 px on 22 px lines, wrapped) up to two fifths of the window, then scrolls; + and the buttons stay at the bottom - the working row names the running step and what it is on (「正在搜尋網頁:台北 天氣」, 「正在打開網頁: github.com」, 「正在執行指令:cargo test」, every tool), and with none running a phrase that changes every 3 s (thinking / looking at results / writing) - screenshot hooks: Shift+ in ANYBOT_SHOT_KEYS, ANYBOT_SHOT_TYPE, ANYBOT_SHOT_VIEW=working Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Uirha3QxSfoydRPM9mjj6d --- FEATURES.md | 18 +- src/app.rs | 130 +++++++++++++-- src/app/chat_ui.rs | 403 ++++++++++++++++++++++++++++++++++++++++----- 3 files changed, 489 insertions(+), 62 deletions(-) diff --git a/FEATURES.md b/FEATURES.md index d8da17c..4a74fe1 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -291,7 +291,9 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 ### 按鍵 -- Enter 送出,Shift+Enter 換行。 +- Enter 送出,Shift+Enter 換行(以前 Shift+Enter 也會送出:egui 的快捷鍵比對不管 Shift,現在兩個鍵分開讀)。/ 清單開著時,Enter/Tab 帶入技能,Shift+Enter 照樣換行。 +- **清單自己長出來**:在「1. 買菜」這一行按 Shift+Enter,下一行自動是「2. 」;「9) 」之後是「10) 」,「1、」之後是「2、」,「- 」「* 」「• 」照樣接下去,「- [x] 」之後是「- [ ] 」,縮排也一樣。在還沒寫字的「3. 」上再按一次 Shift+Enter,就把「3. 」拿掉、結束清單(像備忘錄)。游標在一項中間時,後面的字移到新的一項;「1.5 公斤」「2026年」「-1 度」這種不算清單。 +- **輸入框跟著字長高**:一行時還是 44 px 的膠囊;字多了(換行或一行太長自動折行)就往上長,最多長到視窗高度的 4 成(120–360 px),再多就在框裡捲動。字跟聊天一樣大(15 px、行高 22 px),多行也好讀;+、麥克風和送出鈕都貼在底部。 - 用注音、拼音等輸入法選字時按 Enter,不會誤送出。 - 送出後游標留在輸入框。 @@ -2148,15 +2150,11 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 你的訊息:回覆和 ⋯(複製)。 - **AI 也會按表情**:Bot 有 `react` 工具,可以在你最新的訊息按 ❤️、👍、😂、🎉、👀 等,顯示在你的泡泡下面。 - **工作中**: - - 對話最後是一個不停轉的圓環,加上一句有光掃過的狀態,文字取自原版的清單: - - 讀檔:「正在讀取檔案」 - - 跑指令:「正在執行幾個指令」 - - 操作 Bot 的電腦:「正在四處點擊」 - - 操作你的 Mac:「正在你的電腦上工作」 - - 瀏覽網頁:「正在逐頁瀏覽」 - - 等你:「需要你的輸入」 - - 思考時:「正在仔細思考/正在琢磨/正在整理思緒」 - - 其他:「正在推進」等 + - 對話最後是一個不停轉的圓環,加上一句有光掃過的狀態,**說它現在在做什麼**,做的事換了字就跟著換: + - 每個工具都有自己的說法,能短短帶到在做什麼就帶(超過 24 字用「…」):「正在搜尋網頁:台北 明天 天氣」(網址是 Google、Bing、DuckDuckGo、Yahoo、百度、Brave 或「…/search?q=…」的搜尋)、「正在打開網頁:github.com」、「正在讀取網頁:example.com」、「正在執行指令:cargo test」、「正在讀取檔案:main.rs」、「正在讀技能:pptx」、「正在用連接器:notion」、「正在翻記憶」、「正在寄出郵件」…… + - 操作畫面:「正在看螢幕」「正在點擊」「正在打開 Safari」;在別台電腦上就說是哪台:「正在「Mac mini」上打字」。 + - 沒有步驟在跑時,每 3 秒換一句:還沒動手前「正在思考/正在琢磨/正在整理思緒」;做過步驟後「正在看剛才的結果/正在想下一步/正在確認進度」;開始寫回答後「正在寫回覆/正在整理回答」。 + - 等你:「需要你的輸入」。樣式不變(同一個圓環和掃光)。大腦的螢幕也一樣(照同步過來的聊天說)。 - 原版的動畫時間: - 圓環每 1.2 秒轉一圈; - 文字上的光每 1.4 秒掃過一次; diff --git a/src/app.rs b/src/app.rs index 56263df..6e310c0 100644 --- a/src/app.rs +++ b/src/app.rs @@ -464,6 +464,37 @@ impl App { // Optional view for checking the dialogs in a picture. match std::env::var("ANYBOT_SHOT_VIEW").as_deref() { Ok("chat") => app.state.selected = 1, + // The working row: a turn with ANYBOT_SHOT_TOOL running (its arguments in + // ANYBOT_SHOT_ARGS); without one, a step already done and the model thinking. + Ok("working") => { + app.state.selected = 1; + app.approvals.clear(); + let tool = std::env::var("ANYBOT_SHOT_TOOL").unwrap_or_default(); + let args = std::env::var("ANYBOT_SHOT_ARGS").unwrap_or_else(|_| "{}".into()); + if let Some(b) = app.state.bot_mut(1) { + b.messages.clear(); + b.messages.push(Message::user("幫我查一下明天台北的天氣,然後整理成一張卡片")); + if tool.is_empty() { + b.messages.push(Message { tool_calls: vec![crate::model::ToolCall { id: "w0".into(), name: "web_fetch".into(), args: r#"{"url":"https://www.google.com/search?q=台北天氣"}"#.into(), status: ToolStatus::Done }], ..Message::assistant("", "demo") }); + b.messages.push(Message::tool_result("w0", "web_fetch", "明天台北 26°C,午後雷陣雨")); + b.messages.push(Message::assistant("", "demo")); + } else { + b.messages.push(Message { tool_calls: vec![crate::model::ToolCall { id: "w1".into(), name: tool, args, status: ToolStatus::Running }], ..Message::assistant("", "demo") }); + } + } + app.streams.insert(1, Live { + cancel: Arc::new(AtomicBool::new(false)), + started: Instant::now(), + last: Instant::now(), + produced: true, + status: None, + paused: false, + steer: Arc::default(), + direct: Arc::new(AtomicBool::new(false)), + turn_id: "shot".into(), + turn: 0, + }); + } // 目標: a goal on its way (ANYBOT_SHOT_GOAL=paused: stopped to ask), with the // person's 「/goal …」, a 「還沒達成」 and a line of AnyBot's; ANYBOT_SHOT_DRAFT in the input. Ok("goal") => { @@ -2849,8 +2880,19 @@ impl App { 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; + // Enter sends; Shift+Enter is a new line — in a list, the next item's 「2. 」 or 「- 」. + if had_focus && !composing { + let (enter, shift_enter) = ui.input_mut(chat_ui::take_enter); + send_now |= enter; + if shift_enter { + let mut s = egui::text_edit::TextEditState::load(ctx, composer_id).unwrap_or_default(); + let n = draft.chars().count(); + let (a, b) = s.cursor.char_range().map(|r| (r.primary.index.0.min(r.secondary.index.0), r.primary.index.0.max(r.secondary.index.0))).unwrap_or((n, n)); + let (text, at) = chat_ui::list_newline(&draft, a, b); + draft = text; + s.cursor.set_char_range(Some(egui::text::CCursorRange::one(egui::text::CCursor::new(at)))); + s.store(ctx, composer_id); + } } self.attachments_poll(ctx, bot.id, had_focus); self.voice_poll(ctx); @@ -2904,10 +2946,33 @@ impl App { .inner_margin(Margin { left: 8, right: 8, top: 8, bottom: 8 }) .show(ui, |ui| { ui.set_width(ui.available_width()); - ui.horizontal(|ui| { + // (Bottom-aligned: as the words grow taller, + and the buttons stay at the bottom.) + ui.with_layout(Layout::left_to_right(Align::Max), |ui| { ui.spacing_mut().item_spacing.x = 8.0; - // +: 附加檔案 / 教它一項任務 / the model. - let plus = round_tool(ui, crate::icons::Icon::Plus, p.hover, p.text2).on_hover_text(t("輸入框操作")); + // (+, then the words, then two buttons: 28 px each, 8 px apart.) + let right_w = 28.0 * 2.0 + 8.0 + 4.0; + let text_w = (ui.available_width() - 28.0 - 8.0 - right_w).max(60.0); + let hint = if self.mir.on && !self.mir.online { t("連不到大腦,現在只能看") } else { t("傳訊息給 {name}").replace("{name}", &bot.name) }; + // The words at the chat's size and spacing; the box grows with them (long lines + // wrap) up to about two fifths of the window, then scrolls. + let text_col = p.text; + let mut layouter = |ui: &egui::Ui, buf: &dyn egui::TextBuffer, wrap: f32| { + let mut job = egui::text::LayoutJob::single_section( + buf.as_str().to_owned(), + egui::TextFormat { font_id: egui::FontId::proportional(COMPOSER_FONT), color: text_col, line_height: Some(COMPOSER_LINE_H), ..Default::default() }, + ); + job.wrap.max_width = wrap; + ui.fonts_mut(|f| f.layout_job(job)) + }; + let text_h = layouter(ui, &draft, text_w).size().y.max(COMPOSER_LINE_H); + let max_h = (ctx.content_rect().height() * 0.4).clamp(120.0, 360.0); + let box_h = composer_box_h(text_h, max_h); + // +: 附加檔案 / 教它一項任務 / the model. In a slot as tall as the words, at its + // bottom (the row grows only after it, so Align::Max alone left it at the top). + let plus = ui + .allocate_ui_with_layout(vec2(28.0, box_h), Layout::bottom_up(Align::Center), |ui| round_tool(ui, crate::icons::Icon::Plus, p.hover, p.text2)) + .inner + .on_hover_text(t("輸入框操作")); egui::Popup::menu(&plus).show(|ui| { ui.set_min_width(menu_ui::MENU_W); if menu_ui::item(ui, p, crate::icons::Icon::Paperclip, "附加檔案").clicked() { @@ -2926,13 +2991,20 @@ impl App { ui.label(RichText::new(format!("{}{}", t("成員:"), names.join("、"))).size(FONT_XS).color(p.text2)); } }); - let right_w = 28.0 * 2.0 + 8.0 + 4.0; - let text_w = (ui.available_width() - right_w).max(60.0); - let hint = if self.mir.on && !self.mir.online { t("連不到大腦,現在只能看") } else { t("傳訊息給 {name}").replace("{name}", &bot.name) }; - ui.allocate_ui_with_layout(vec2(text_w, 28.0), Layout::top_down(Align::Min), |ui| { - egui::ScrollArea::vertical().id_salt(("composer_scroll", bot.id)).max_height(160.0).show(ui, |ui| { - ui.add_space(4.0); - ui.add(egui::TextEdit::multiline(&mut draft).id(composer_id).hint_text(RichText::new(hint).color(p.text3)).frame(Frame::NONE).margin(Margin::ZERO).desired_rows(1).desired_width(text_w).lock_focus(true)); + ui.allocate_ui_with_layout(vec2(text_w, box_h), Layout::top_down(Align::Min), |ui| { + egui::ScrollArea::vertical().id_salt(("composer_scroll", bot.id)).auto_shrink([false, false]).max_height(box_h).min_scrolled_height(box_h).show(ui, |ui| { + ui.add_space(COMPOSER_TOP); + ui.add( + egui::TextEdit::multiline(&mut draft) + .id(composer_id) + .hint_text(RichText::new(hint).size(COMPOSER_FONT).color(p.text3)) + .frame(Frame::NONE) + .margin(Margin::ZERO) + .desired_rows(1) + .desired_width(text_w) + .layouter(&mut layouter) + .lock_focus(true), + ); }); }); ui.with_layout(Layout::right_to_left(Align::Max), |ui| { @@ -4349,18 +4421,33 @@ impl eframe::App for App { } } } - // ANYBOT_SHOT_KEYS="ArrowDown@50;Enter@54": press and release that key at that frame. + // ANYBOT_SHOT_KEYS="ArrowDown@50;Shift+Enter@54": press and release that key at that frame + // (with Shift held, for a 「Shift+」 one). 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 }; + let (shift, name) = match name.trim().strip_prefix("Shift+") { + Some(n) => (true, n), + None => (false, name.trim()), + }; + let (Some(key), Ok(at)) = (Key::from_name(name), at.trim().parse::()) else { continue }; if self.frames + 1 == at { + let modifiers = egui::Modifiers { shift, ..Default::default() }; for pressed in [true, false] { - raw.events.push(egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Default::default() }); + raw.events.push(egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers }); } } } } + // ANYBOT_SHOT_TYPE="寫測試@60": type these words at that frame. + if let Ok(spec) = std::env::var("ANYBOT_SHOT_TYPE") { + for one in spec.split(';') { + let Some((words, at)) = one.rsplit_once('@') else { continue }; + if at.trim().parse::().ok() == Some(self.frames + 1) { + raw.events.push(egui::Event::Text(words.to_string())); + } + } + } 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) }; @@ -4856,6 +4943,19 @@ fn small_button(ui: &mut egui::Ui, text: &str, p: Palette) -> egui::Response { ui.add(egui::Button::new(RichText::new(t(text)).size(11.5).color(p.text3)).frame_when_inactive(false).corner_radius(6).min_size(vec2(0.0, 22.0))) } +/// The input's words: the chat's size (15 px) on 22 px lines, so several lines read as easily as +/// the messages above (the default 14 px lines sat tight). +const COMPOSER_FONT: f32 = FONT_LG; +const COMPOSER_LINE_H: f32 = LINE_HEIGHT_LG; +/// Above the first line, so one line sits in the middle of the 28 px row. +const COMPOSER_TOP: f32 = 3.0; + +/// How tall the words' box is: one 28 px row for a line, then as tall as the words, up to +/// `max_h` (beyond that it scrolls). +fn composer_box_h(text_h: f32, max_h: f32) -> f32 { + (text_h + COMPOSER_TOP + 3.0).clamp(28.0, max_h.max(28.0)) +} + /// The input's 28 px round buttons (+, mic, voice chat / send). fn round_tool(ui: &mut egui::Ui, icon: crate::icons::Icon, fill: Color32, ink: Color32) -> egui::Response { let (rect, r) = ui.allocate_exact_size(vec2(28.0, 28.0), egui::Sense::click()); diff --git a/src/app/chat_ui.rs b/src/app/chat_ui.rs index 7dbbfb4..91082dc 100644 --- a/src/app/chat_ui.rs +++ b/src/app/chat_ui.rs @@ -29,40 +29,313 @@ const JUMP_BOTTOM_SIZE: f32 = 36.0; /// Between the button and the bottom of the chat (the top of the composer). const JUMP_BOTTOM_GAP: f32 = 12.0; -/// The original's status phrases (renderer table vit). -const THINKING: [&str; 3] = ["正在仔細思考", "正在琢磨", "正在整理思緒"]; -const WORKING: [&str; 5] = ["正在完成", "正在推進", "正在處理", "正在搞定", "正在一點一點推進"]; +/// The working row's words when no step is running: thinking before the first step, looking at +/// what a step brought back between steps, writing once the answer has words. They take turns +/// every [`PHRASE_SECS`]. +const THINKING: [&str; 3] = ["正在思考", "正在琢磨", "正在整理思緒"]; +const BETWEEN: [&str; 3] = ["正在看剛才的結果", "正在想下一步", "正在確認進度"]; +const WRITING: [&str; 2] = ["正在寫回覆", "正在整理回答"]; +/// How long one phrase stays before the next takes its place. +pub const PHRASE_SECS: f64 = 3.0; +/// The longest detail in a phrase (a search, a site, a file, a command). +const DETAIL_CHARS: usize = 24; -/// What the bot is doing, as the original says it. -pub fn status_phrase(tool: Option<&str>, on_box: bool, waiting: bool, has_text: bool, seed: u64) -> String { - let pick = |list: &[&str]| list[(seed as usize) % list.len()].to_string(); +/// What the bot is doing now, in a few words: the running step — what it is and what it is on +/// (「正在搜尋網頁:台北天氣」「正在打開網頁:github.com」「正在執行指令:cargo test」) — or, with +/// none running, a phrase that changes with `tick`. `place`: the computer a screen step is on, +/// when it isn't the bot's own. +pub fn status_phrase(call: Option<(&str, &str)>, place: Option<&str>, waiting: bool, has_text: bool, did_steps: bool, tick: u64) -> String { + let pick = |list: &[&str]| list[(tick as usize) % list.len()].to_string(); if waiting { return "需要你的輸入".into(); } - let Some(name) = tool else { return if has_text { pick(&WORKING) } else { pick(&THINKING) } }; + match call { + Some((name, args)) => doing(name, args, place), + None if has_text => pick(&WRITING), + None if did_steps => pick(&BETWEEN), + None => pick(&THINKING), + } +} + +/// One step, said the way a person would say what they're doing. +fn doing(name: &str, args: &str, place: Option<&str>) -> String { + let v = tools::args_of(args); + let s = |k: &str| v[k].as_str().unwrap_or("").trim().to_string(); + let with = |what: &str, detail: String| { + let d = clip_detail(&detail); + if d.is_empty() { what.to_string() } else { format!("{what}:{d}") } + }; + // `computer` and `browser` carry the action in their arguments until the step ends. + let name = match name { + crate::computer::TOOL => crate::computer::top_action_tool(&s("action")).unwrap_or("computer_use"), + crate::browser::TOOL => crate::browser::action_tool(&s("action")).unwrap_or("browser"), + n => n, + }; + if name.starts_with("computer_use") { + let verb = match name { + "computer_use_screenshot" => "看螢幕".to_string(), + "computer_use_zoom" => "放大看螢幕".into(), + "computer_use_show" => return "正在把畫面傳給你".into(), + "computer_use_click" => "點擊".into(), + "computer_use_typing" => "打字".into(), + "computer_use_press_key" => "按鍵".into(), + "computer_use_scroll" => "捲動畫面".into(), + "computer_use_mouse_move" => "移動滑鼠".into(), + "computer_use_drag" => "拖曳".into(), + "computer_use_open_app" => match clip_detail(&s("app")) { + a if a.is_empty() => "打開 App".into(), + a => format!("打開 {a}"), + }, + "computer_use_menu_click" => "走選單".into(), + "computer_use_fill_form" => "填表單".into(), + "computer_use_wait_for" => "等畫面出現".into(), + "computer_use_batch" => "依序操作畫面".into(), + "computer_use_check_permissions" => "檢查螢幕權限".into(), + "computer_use_intent" => "調整電腦設定".into(), + _ => "操作畫面".into(), + }; + return match place { + Some(p) => format!("正在「{p}」上{verb}"), + None => format!("正在{verb}"), + }; + } + let url = s("url"); + let file = || s("path").trim_end_matches('/').rsplit('/').next().unwrap_or("").to_string(); match name { - "read_file" | "list_dir" | "search" => "正在讀取檔案".into(), - "edit_file" => "正在記下來".into(), + "web_fetch" => match search_words(&url) { + Some(q) => with("正在搜尋網頁", q), + None => with("正在讀取網頁", site(&url)), + }, + "browser_open" => match search_words(&url) { + Some(q) => with("正在搜尋網頁", q), + None => with("正在打開網頁", site(&url)), + }, + "browser_read" => "正在閱讀網頁".into(), + "browser_profiles" => "正在切換瀏覽器設定檔".into(), + "browser_elements" => "正在看網頁上有什麼".into(), + "browser_click" => "正在點網頁上的按鈕".into(), + "browser_hover" => "正在網頁上移動滑鼠".into(), + "browser_type" => "正在網頁上打字".into(), + "browser_press" => "正在網頁上按鍵".into(), + "browser_select" => "正在網頁上選擇".into(), + "browser_scroll" => "正在捲動網頁".into(), + "browser_wait" => "正在等網頁載入".into(), + "browser_find" => with("正在網頁上找字", s("text")), + "browser_table" => "正在讀網頁上的表格".into(), + "browser_screenshot" => "正在看網頁畫面".into(), + "browser_tabs" => "正在切換分頁".into(), + "browser_back" => "正在回上一頁".into(), + "browser_upload" => "正在上傳檔案到網頁".into(), + "browser_download" => "正在從網頁下載".into(), + "browser_pdf" => "正在把網頁存成 PDF".into(), + "browser_dialog" => "正在處理網頁對話框".into(), + "browser_eval" => "正在網頁上執行程式".into(), + "browser_fill_login" => with("正在用保險庫登入", s("site")), + "browser_fill_card" => "正在填入卡片資料".into(), + "browser_fill_contact" => "正在填入聯絡資訊".into(), + "vault_list" => "正在查看保險庫".into(), + "shell" => with("正在執行指令", s("command").lines().next().unwrap_or("").to_string()), + "read_terminal" => "正在看背景指令的結果".into(), + "write_terminal" => "正在輸入到背景指令".into(), + "read_file" => with("正在讀取檔案", file()), + "edit_file" => with("正在修改檔案", file()), + "list_dir" => with("正在查看資料夾", file()), + "search" => with("正在搜尋檔案", s("pattern")), + "search_documents" => with("正在翻你的文件", s("query")), + "open_for_person" => "正在打開給你看".into(), "send_file" => "正在傳檔案給你".into(), "send_to_device" => "正在傳到你的另一台裝置".into(), - "computer_use_show" => "正在把畫面傳給你".into(), - "shell" | "write_terminal" => "正在執行幾個指令".into(), - "read_terminal" => "正在等待結果".into(), - "web_fetch" | "browser_read" => "正在閱讀資料".into(), - "browser_open" => "正在逐頁瀏覽".into(), - "message_bot" => "正在詢問另一個 Bot".into(), - "mac_send_mail" | "mac_send_message" | "send_sms" | "post_to_x" | "mac_draft_mail" => "正在傳送訊息".into(), - "publish_site" => "正在發布".into(), - "vault_list" => "正在查看保險庫".into(), - "browser_fill_login" | "browser_fill_card" | "browser_fill_contact" => "正在填入保險庫的資料".into(), - n if n.starts_with("computer_use") => if on_box { "正在四處點擊".into() } else { "正在你的電腦上工作".into() }, - n if n.contains("search") => "正在四處查找".into(), - n if n.starts_with("mcp__") => "正在已連結的應用程式中工作".into(), - n if n.starts_with("mac_") || n.starts_with("ios_") || n.starts_with("mobile_") => "正在你的電腦上工作".into(), - _ => pick(&WORKING), + "publish_site" => "正在發布網站".into(), + "show_card" => "正在整理成卡片".into(), + "react" => "正在按表情".into(), + "view_demo_step" => "正在看示範".into(), + "place_call" => "正在打電話".into(), + "send_sms" => "正在傳簡訊".into(), + "post_to_x" => "正在 X 上發文".into(), + "remember" => "正在記下來".into(), + "forget" => "正在忘掉".into(), + "search_memory" => with("正在翻記憶", s("query")), + "use_skill" => with("正在讀技能", s("name")), + agent::REPLAY_TOOL => with("正在照技能重做", s("name")), + "save_skill" | "skillify" => "正在存成技能".into(), + "skill_install" => "正在安裝技能".into(), + "delete_skill" => "正在刪除技能".into(), + "message_bot" => with("正在問另一個 Bot", s("bot")), + "list_routines" => "正在查看例行任務".into(), + "create_routine" | "update_routine" | "delete_routine" => "正在安排例行任務".into(), + "run_routine_now" => "正在執行例行任務".into(), + "list_bots" | "create_bot" | "update_bot" => "正在設定 Bot".into(), + "create_group" | "move_to_group" | "rename_group" | "delete_group" => "正在整理 Bot 群組".into(), + "list_computers" => "正在查看有哪些電腦".into(), + "update_settings" => "正在修改設定".into(), + "write_page" => with("正在寫頁面", s("title")), + "read_page" | "list_pages" => "正在看頁面".into(), + "ios_read_reminders" => "正在看提醒事項".into(), + "ios_write_reminders" => "正在修改提醒事項".into(), + "mobile_read_calendar" => "正在看行事曆".into(), + "mobile_write_calendar" => "正在修改行事曆".into(), + "mobile_read_contacts" => "正在查聯絡人".into(), + "mac_read_notes" => "正在讀備忘錄".into(), + "mac_write_notes" => "正在寫備忘錄".into(), + "mac_read_mail" => "正在讀郵件".into(), + "mac_draft_mail" => "正在起草郵件".into(), + "mac_send_mail" => "正在寄出郵件".into(), + "mac_mail_accounts" => "正在查看郵件帳號".into(), + crate::macapps::SEND_MESSAGE => "正在傳訊息".into(), + tools::HANDOFF_TOOL => "正在等你接手".into(), + // mcp____: the connector by its name. + n if n.starts_with(crate::mcp::PREFIX) => with("正在用連接器", n[crate::mcp::PREFIX.len()..].split("__").next().unwrap_or("").to_string()), + n => match crate::remote::tool_label(n) { + "工具" | "App 操作" | "網頁" | "瀏覽器" | "Mac App" => "正在處理".into(), + l => format!("正在{l}"), + }, } } +/// The words of a web search, when the address is one (Google, Bing, DuckDuckGo, Yahoo, Baidu, +/// Brave, or any 「…/search?q=…」). +pub fn search_words(url: &str) -> Option { + let rest = url.split_once("://").map(|x| x.1).unwrap_or(url); + let (place, query) = rest.split_once('?')?; + let (host, path) = place.split_once('/').map(|(h, p)| (h.to_lowercase(), format!("/{p}"))).unwrap_or((place.to_lowercase(), String::new())); + let searchy = host.contains("duckduckgo.") || host.contains("bing.com") || host.contains("baidu.com") || host.starts_with("search.") || path.contains("search") || path == "/s"; + if !searchy { + return None; + } + query.split('&').filter_map(|kv| kv.split_once('=')).find(|(k, _)| matches!(*k, "q" | "query" | "p" | "wd" | "text" | "keyword" | "search_query")).map(|(_, v)| url_decode(v)).filter(|w| !w.trim().is_empty()) +} + +/// 「https://www.github.com/a/b」 → 「github.com」. +fn site(url: &str) -> String { + let rest = url.split_once("://").map(|x| x.1).unwrap_or(url); + let host = rest.split(['/', '?', '#']).next().unwrap_or(""); + host.strip_prefix("www.").unwrap_or(host).to_string() +} + +fn url_decode(s: &str) -> String { + let b = s.as_bytes(); + let mut out = Vec::with_capacity(b.len()); + let mut i = 0; + while i < b.len() { + match b[i] { + b'+' => out.push(b' '), + b'%' if i + 2 < b.len() => { + let hex = |c: u8| (c as char).to_digit(16); + match (hex(b[i + 1]), hex(b[i + 2])) { + (Some(h), Some(l)) => { + out.push((h * 16 + l) as u8); + i += 2; + } + _ => out.push(b'%'), + } + } + c => out.push(c), + } + i += 1; + } + String::from_utf8_lossy(&out).trim().to_string() +} + +fn clip_detail(s: &str) -> String { + let s = s.split_whitespace().collect::>().join(" "); + if s.chars().count() <= DETAIL_CHARS { + return s; + } + format!("{}…", s.chars().take(DETAIL_CHARS).collect::()) +} + +/// Shift+Enter in the input: a new line — and in a list, the next item's marker +/// (「1. 買菜」 → 「2. 」, 「- 」 → 「- 」). Shift+Enter on an item that is still empty ends the list +/// instead (the marker goes, like in a notes app). `start..end` is the selection, in characters. +/// Returns the text and where the caret goes. +pub fn list_newline(text: &str, start: usize, end: usize) -> (String, usize) { + let chars: Vec = text.chars().collect(); + let (start, end) = (start.min(chars.len()), end.min(chars.len()).max(start.min(chars.len()))); + let line_start = chars[..start].iter().rposition(|c| *c == '\n').map(|i| i + 1).unwrap_or(0); + let line_end = chars[end..].iter().position(|c| *c == '\n').map(|i| end + i).unwrap_or(chars.len()); + let line: String = chars[line_start..line_end].iter().collect(); + let plain = |chars: &[char]| { + let mut out: Vec = chars[..start].to_vec(); + out.push('\n'); + out.extend_from_slice(&chars[end..]); + (out.into_iter().collect::(), start + 1) + }; + let Some((marker_len, next)) = list_marker(&line) else { return plain(&chars) }; + // The caret has to be past the marker (Shift+Enter inside 「1. 」 is just a new line). + if start < line_start + marker_len { + return plain(&chars); + } + let item_empty = line.chars().skip(marker_len).all(char::is_whitespace); + if item_empty && start == end { + // An empty item: the list ends here. + let indent: String = line.chars().take_while(|c| *c == ' ' || *c == '\t').collect(); + let mut out: Vec = chars[..line_start].to_vec(); + out.extend(indent.chars()); + let at = out.len(); + out.extend_from_slice(&chars[line_end..]); + return (out.into_iter().collect(), at); + } + let mut out: Vec = chars[..start].to_vec(); + out.push('\n'); + out.extend(next.chars()); + let at = out.len(); + out.extend_from_slice(&chars[end..]); + (out.into_iter().collect(), at) +} + +/// A list item's marker at the start of `line`: its length in characters, and the marker the +/// next item gets (same indent; a number one up). 「1. 」「2) 」「3、」「- 」「* 」「• 」「- [ ] 」. +fn list_marker(line: &str) -> Option<(usize, String)> { + let indent: String = line.chars().take_while(|c| *c == ' ' || *c == '\t').collect(); + let rest: Vec = line.chars().skip(indent.chars().count()).collect(); + let n = indent.chars().count(); + let spaces = |from: usize| rest[from.min(rest.len())..].iter().take_while(|c| **c == ' ').count(); + let digits = rest.iter().take_while(|c| c.is_ascii_digit()).count(); + if (1..=3).contains(&digits) { + let num: u32 = rest[..digits].iter().collect::().parse().ok()?; + let delim = *rest.get(digits)?; + let gap = spaces(digits + 1); + return match delim { + '.' | ')' if gap > 0 => Some((n + digits + 1 + gap, format!("{indent}{}{delim}{}", num + 1, " ".repeat(gap)))), + '、' => Some((n + digits + 1 + gap, format!("{indent}{}、{}", num + 1, " ".repeat(gap)))), + _ => None, + }; + } + let bullet = *rest.first()?; + if !matches!(bullet, '-' | '*' | '•') { + return None; + } + let gap = spaces(1); + if gap == 0 { + return None; + } + let after: String = rest[1 + gap..].iter().take(4).collect(); + if after.starts_with("[ ] ") || after.starts_with("[x] ") || after.starts_with("[X] ") { + return Some((n + 1 + gap + 4, format!("{indent}{bullet}{}[ ] ", " ".repeat(gap)))); + } + Some((n + 1 + gap, format!("{indent}{bullet}{}", " ".repeat(gap)))) +} + +/// Enter and Shift+Enter in the input, taken before the text field sees them: Enter sends, +/// Shift+Enter makes a new line (list_newline). egui's own shortcut matching ignores Shift unless +/// it is asked for, which made Shift+Enter send too; these are read by hand. (Cmd/Ctrl/Alt+Enter +/// are left alone.) +pub fn take_enter(i: &mut egui::InputState) -> (bool, bool) { + let (mut plain, mut shift) = (false, false); + i.events.retain(|e| match e { + egui::Event::Key { key: Key::Enter, pressed: true, modifiers, .. } if !modifiers.command && !modifiers.ctrl && !modifiers.alt && !modifiers.mac_cmd => { + if modifiers.shift { + shift = true; + } else { + plain = true; + } + false + } + _ => true, + }); + (plain, shift) +} + /// "11月2日週一 上午9:50" (today: just the time). pub fn date_label(ms: i64) -> String { use chrono::{Datelike, Local, TimeZone, Timelike}; @@ -500,14 +773,15 @@ impl App { let own = crate::model::own_computer_name(&bot.name); let on_box = running.is_some() && named.as_deref().map(|n| n == own || n == crate::model::BOT_COMPUTER_NAME).unwrap_or(true); let has_text = last.map(|m| !m.text.trim().is_empty()).unwrap_or(false); + // Steps already done this turn (between them it is looking at what came back). + let from = bot.messages.iter().rposition(|m| m.role == Role::User && !m.steer).unwrap_or(0); + let did_steps = bot.messages[from..].iter().any(|m| m.role == Role::Tool); let seed = live.turn_id.bytes().fold(0u64, |a, b| a.wrapping_mul(31).wrapping_add(b as u64)); - let phrase = live.status.clone().unwrap_or_else(|| { - let ph = status_phrase(running.map(|c| c.name.as_str()), on_box, waiting, has_text, seed); - match &named { - Some(n) if ph == "正在你的電腦上工作" => t("正在「{name}」上工作").replace("{name}", n), - _ => t(&ph), - } - }); + // The words change every few seconds while nothing new is running (the ring keeps the + // window drawing, so no extra repaint is needed). + let tick = seed.wrapping_add((ui.input(|i| i.time) / PHRASE_SECS) as u64); + let place = named.as_deref().filter(|_| !on_box); + let phrase = live.status.clone().unwrap_or_else(|| t(&status_phrase(running.map(|c| (c.name.as_str(), c.args.as_str())), place, waiting, has_text, did_steps, tick))); ui.add_space(4.0); ui.horizontal(|ui| { ui.add_space(6.0); @@ -625,6 +899,10 @@ impl App { self.slash.lit = (self.slash.lit + n - 1) % n; self.slash.moved = true; } + // (Plain Enter only: Shift+Enter is a new line, and egui's matching ignores Shift.) + if i.modifiers.shift { + return None; + } (i.consume_key(Modifiers::NONE, Key::Enter) || i.consume_key(Modifiers::NONE, Key::Tab)).then_some(self.slash.lit) }) } @@ -734,12 +1012,36 @@ mod tests { #[test] fn phrases_follow_what_it_does() { - assert_eq!(status_phrase(Some("read_file"), false, false, false, 0), "正在讀取檔案"); - assert_eq!(status_phrase(Some("computer_use_click"), true, false, false, 0), "正在四處點擊"); - assert_eq!(status_phrase(Some("computer_use_click"), false, false, false, 0), "正在你的電腦上工作"); - assert_eq!(status_phrase(None, false, true, false, 0), "需要你的輸入"); - assert!(THINKING.contains(&status_phrase(None, false, false, false, 7).as_str())); - assert!(WORKING.contains(&status_phrase(None, false, false, true, 7).as_str())); + let say = |name: &str, args: &str| status_phrase(Some((name, args)), None, false, false, false, 0); + // What it is, and what it is on. + assert_eq!(say("web_fetch", r#"{"url":"https://www.google.com/search?q=%E5%8F%B0%E5%8C%97+%E5%A4%A9%E6%B0%A3&hl=zh"}"#), "正在搜尋網頁:台北 天氣"); + assert_eq!(say("browser_open", r#"{"url":"https://duckduckgo.com/?q=rust+egui"}"#), "正在搜尋網頁:rust egui"); + assert_eq!(say("browser_open", r#"{"url":"https://www.github.com/anybot/issues"}"#), "正在打開網頁:github.com"); + assert_eq!(say("browser", r#"{"action":"open","url":"https://news.ycombinator.com"}"#), "正在打開網頁:news.ycombinator.com"); + assert_eq!(say("web_fetch", r#"{"url":"https://example.com/a?id=3"}"#), "正在讀取網頁:example.com"); + assert_eq!(say("shell", r#"{"command":"cargo test --release\necho done"}"#), "正在執行指令:cargo test --release"); + assert_eq!(say("read_file", r#"{"path":"src/app/chat_ui.rs"}"#), "正在讀取檔案:chat_ui.rs"); + assert_eq!(say("use_skill", r#"{"name":"pptx"}"#), "正在讀技能:pptx"); + assert_eq!(say("mcp__notion__search", "{}"), "正在用連接器:notion"); + assert_eq!(say("shell", &format!(r#"{{"command":"{}"}}"#, "x".repeat(60))), format!("正在執行指令:{}…", "x".repeat(24))); + // Screen steps: on the bot's own computer, or on another one by its name. + assert_eq!(say("computer", r#"{"action":"click"}"#), "正在點擊"); + assert_eq!(say("computer_use_open_app", r#"{"app":"Safari"}"#), "正在打開 Safari"); + assert_eq!(status_phrase(Some(("computer_use_typing", "{}")), Some("Mac mini"), false, false, false, 0), "正在「Mac mini」上打字"); + // Every tool says something of its own (nothing falls back to a vague word). + for n in ["remember", "search_memory", "mac_read_mail", "browser_click", "send_file", "create_routine", "write_page", "computer_use_screenshot", "browser_profiles"] { + assert!(!say(n, "{}").contains("處理"), "{n}: {}", say(n, "{}")); + } + // No step running: words that take turns. + assert_eq!(status_phrase(None, None, true, false, false, 0), "需要你的輸入"); + let thinking: Vec = (0..3).map(|k| status_phrase(None, None, false, false, false, k)).collect(); + assert!(thinking.iter().all(|p| THINKING.contains(&p.as_str())) && thinking[0] != thinking[1]); + assert!(BETWEEN.contains(&status_phrase(None, None, false, false, true, 1).as_str())); + assert!(WRITING.contains(&status_phrase(None, None, false, true, true, 1).as_str())); + assert!(search_words("https://www.google.com/maps/place/x").is_none()); + // Broken or raw escapes don't trip it. + assert_eq!(search_words("https://www.bing.com/search?q=%E5%8F%B0%zz%"), Some("台%zz%".into())); + assert_eq!(search_words("https://www.bing.com/search?q=%台北"), Some("%台北".into())); assert!((pop(1.0) - 1.0).abs() < 1e-4 && pop(0.6) > 1.0); } @@ -755,6 +1057,33 @@ mod tests { assert_eq!((tag.map(|t| t.1), body), (Some("目標"), "還沒達成:還有 1 個失敗")); } + #[test] + fn shift_enter_goes_on_with_a_list() { + let nl = |text: &str| list_newline(text, text.chars().count(), text.chars().count()); + // Numbers count up; the delimiter and spacing stay. + assert_eq!(nl("待辦:\n1. 買菜"), ("待辦:\n1. 買菜\n2. ".into(), 13)); + assert_eq!(nl("9) 九"), ("9) 九\n10) ".into(), 9)); + assert_eq!(nl("1、買菜").0, "1、買菜\n2、"); + // Bullets and checkboxes, with their indent. + assert_eq!(nl(" - 蘋果").0, " - 蘋果\n - "); + assert_eq!(nl("• 一").0, "• 一\n• "); + assert_eq!(nl("- [x] 做完的").0, "- [x] 做完的\n- [ ] "); + // An empty item ends the list: the marker goes, no new line. + assert_eq!(nl("1. 買菜\n2. "), ("1. 買菜\n".into(), 6)); + assert_eq!(nl(" - "), (" ".into(), 2)); + // Not a list: just a new line. + assert_eq!(nl("你好"), ("你好\n".into(), 3)); + assert_eq!(nl("1.5 公斤"), ("1.5 公斤\n".into(), 7)); + assert_eq!(nl("2026年"), ("2026年\n".into(), 6)); + assert_eq!(nl("-1 度"), ("-1 度\n".into(), 5)); + // In the middle of an item: the rest moves to the new item. + assert_eq!(list_newline("1. 買菜和水果", 5, 5), ("1. 買菜\n2. 和水果".into(), 9)); + // A selection is replaced. + assert_eq!(list_newline("abcdef", 2, 4), ("ab\nef".into(), 3)); + // Before the marker ends: a plain new line. + assert_eq!(list_newline("1. 買菜", 0, 0), ("\n1. 買菜".into(), 1)); + } + #[test] fn jump_to_bottom_shows_far_up_and_lets_go() { // Near the newest message: no button. Far up: the button.