diff --git a/FEATURES.md b/FEATURES.md index 8e58985..c94dba3 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -1423,6 +1423,16 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - **字型**:預設思源黑體(Noto Sans TC,Regular 和 Bold 兩種粗細都包在 App 裡,每台電腦看起來一樣);標題、選中的項目、回覆裡的粗體和標題用真的粗體。設定 › 一般可以換成系統字型或粉圓體(這兩種只有一種粗細)。 - **聊天跟著 Bot 的顏色**(預設;設定 › 一般 › 聊天的顏色可以改成只用黑色):你的訊息泡泡、送出鈕、側邊欄選中的那格(淡淡一層)。Bot 的回覆不用泡泡,像文件一樣排在頁面上,只有錯誤訊息有泡泡。 - **輸入框上方的臉**:Bot 的臉從輸入框後面探出來,旁邊一句話說它在做什麼(原本對話最後的轉圈那一行搬到這裡)。眼睛就是狀態:待命時往下看輸入框;在想時往上、慢慢左右飄;有步驟在跑時看著旁邊那句「正在…」;需要你時看著你,臉上多一個黃點,旁邊寫「等你決定」;做完笑兩秒;上一輪出錯時眼睛變兩條橫線。新對話時沒有這張小臉(臉是中間那張大的)。 + - **每種情境一套動作和一個小道具**(都在臉自己的方框裡,不會碰到旁邊的字;從頭後經過的畫在臉後面,在前面的壓在臉上、描一圈底色,所以頭像不會擋住動畫;換情境時淡入淡出,步驟很快連續切換時至少停 0.6 秒,不會一直閃): + - 思考(還沒開始寫、沒有步驟):頭稍微縮小,三顆小球繞著頭轉;想越久轉得越快;推理模式每收到一段推理,小球亮一下。 + - 看結果(做完步驟、還沒開始寫):右下一張小紙,橫線一條條亮起來,眼睛跟著往下讀。 + - 搜尋、讀網頁:一支放大鏡在臉下半部左右掃,眼睛跟著它。 + - 看螢幕、點擊:小游標移到一個地方按下去,按的地方冒出一圈漣漪。 + - 寫回覆:低頭點頭,一枝筆在臉下畫出一行波浪墨水;字停下來時筆也停。 + - 等你決定/回答:看著你,黃點外面一圈光慢慢擴散,每隔幾秒輕輕彈一下。 + - 完成:笑臉、跳一下,五顆金色小星星輪流冒出來再消失(約 2 秒)。 + - 失敗:眼睛變一字、搖一次頭,一滴汗滑下來後停住(之後不再動,不耗電)。 + - 其他步驟(指令、檔案、記憶…)目前還是看著旁邊那句話;道具顏色太接近頁面(深色模式的黑臉、淺色模式的白臉)時會往文字顏色調亮或調暗。 - **需要你允許**:不再是蓋住整個視窗的彈出視窗,改成固定在輸入框上方的黃色卡片,上面的聊天照樣看得到,下面的輸入框照樣可以打字告訴它怎麼改。輸入框空著時 Enter 允許、Esc 拒絕(卡片出現 0.6 秒後才算,免得原本要按的 Enter 誤答)。要你親自處理的步驟(接管畫面)還是聊天裡的卡片。 - **黃色只代表「需要你」**:允許卡片、臉上的黃點、側邊欄 Bot 上的黃點、設定裡「更新」旁的黃點(有新版)。有新訊息還是藍色小點。 - **標題列**:Bot 的名字在左邊(按一下開對話詳細資訊),右邊「分享」和「⋯」不再有圓框;圖示線條粗一點(2.25)。 diff --git a/src/app.rs b/src/app.rs index aef3a99..1d9d042 100644 --- a/src/app.rs +++ b/src/app.rs @@ -40,6 +40,7 @@ mod voice_ui; mod drops_ui; mod memory_ui; mod goal_ui; +mod mood_ui; // Sidebar rules from index.eager-app: defaults `FT={expandedWidth:280}` (), // clamp `jT(..,240,400)` (), and the drag rule in `QJe` (): @@ -292,6 +293,12 @@ pub struct App { /// The bot's writing face: (words in the answer, when the last one arrived), so the nod /// keeps time with the words flowing out. write_len: HashMap, + /// Per bot: how long its reasoning was and when it last grew (the thinking balls flash). + think_len: HashMap, + /// Per bot: where the writing pen is along its line, 0…1. + pen_run: HashMap, + /// Per bot: the mood its face above the input shows, and since when (mood_ui). + dock_moods: HashMap, /// When each bot's request card was first shown (Enter answers it only after a moment). ask_shown: HashMap, /// 問題卡: the question whose field was last given the caret (once per question). @@ -469,6 +476,9 @@ impl App { faces: HashMap::new(), cheer: HashMap::new(), write_len: HashMap::new(), + think_len: HashMap::new(), + pen_run: HashMap::new(), + dock_moods: HashMap::new(), ask_shown: HashMap::new(), ask_forms: HashMap::new(), ask_focus: None, @@ -589,6 +599,54 @@ impl App { turn: 0, }); } + // The face above the input in one mood (mood_ui), for a picture of each: + // ANYBOT_SHOT_MOOD=thinking|between|web|screen|step|writing|waiting|done|failed. + Ok("mood") => { + app.state.selected = 1; + app.approvals.clear(); + app.streams.clear(); + let mood = std::env::var("ANYBOT_SHOT_MOOD").unwrap_or_else(|_| "thinking".into()); + let step = |name: &str, args: &str, status: ToolStatus| Message { tool_calls: vec![crate::model::ToolCall { id: "m1".into(), name: name.into(), args: args.into(), status }], ..Message::assistant("", "demo") }; + let mut msgs = vec![Message::user("幫我查一下明天台北的天氣,然後整理成一張卡片")]; + match mood.as_str() { + "web" => msgs.push(step("web_fetch", r#"{"url":"https://www.google.com/search?q=台北天氣"}"#, ToolStatus::Running)), + "screen" => msgs.push(step("computer_use_click", r#"{"x":120,"y":80}"#, ToolStatus::Running)), + "step" => msgs.push(step("shell", r#"{"command":"ls ~/Downloads"}"#, ToolStatus::Running)), + "between" | "writing" | "waiting" | "done" => { + msgs.push(step("web_fetch", r#"{"url":"https://www.cwa.gov.tw"}"#, ToolStatus::Done)); + msgs.push(Message::tool_result("m1", "web_fetch", "明天台北 26°C,午後雷陣雨")); + msgs.push(Message::assistant(if mood == "between" { "" } else { "明天台北白天 26°C,午後有雷陣雨,記得帶傘。" }, "demo")); + } + "failed" => msgs.push(Message { error: true, ..Message::assistant("連線逾時,請再試一次。", "demo") }), + _ => msgs.push(Message::assistant("", "demo")), + } + if let Some(b) = app.state.bot_mut(1) { + b.messages = msgs; + } + if !matches!(mood.as_str(), "done" | "failed") { + app.streams.insert(1, Live { + cancel: Arc::new(AtomicBool::new(false)), + started: Instant::now(), + last: Instant::now(), + produced: true, + status: None, + paused: false, + paused_at: None, + unattended: false, + steer: Arc::default(), + direct: Arc::new(AtomicBool::new(false)), + turn_id: "shot".into(), + turn: 0, + }); + } + if mood == "waiting" { + let (reply, _) = channel(); + app.approvals.insert(1, Approval { call_id: "w1".into(), tool: "shell".into(), reason: "執行指令:open ~/Downloads/天氣卡片.png".into(), grant: String::new(), reply, kind: ApprovalKind::Action }); + } + if mood == "done" { + app.cheer.insert(1, Instant::now()); + } + } // 目標: 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") => { @@ -894,6 +952,11 @@ impl App { if std::env::var("ANYBOT_SHOT_DARK").is_ok() { app.state.theme = Theme::Dark; } + // ANYBOT_SHOT_ZOOM=2: drawn twice as large (with ANYBOT_SHOT_SIZE doubled, the same + // layout in sharper detail — small drawings like the face's props). + if let Some(z) = std::env::var("ANYBOT_SHOT_ZOOM").ok().and_then(|v| v.parse::().ok()).filter(|z| (0.5..=4.0).contains(z)) { + ctx.set_zoom_factor(z); + } // ANYBOT_SHOT_CALM=1: each screen without the demo's waiting pop-up and running turn on top. // ANYBOT_SHOT_SUB=1|2: 設定 › 整合's 連接器 or 技能 page. if let Some(n) = std::env::var("ANYBOT_SHOT_SUB").ok().and_then(|v| v.parse::().ok()) { diff --git a/src/app/chat_ui.rs b/src/app/chat_ui.rs index 726d097..138f9a6 100644 --- a/src/app/chat_ui.rs +++ b/src/app/chat_ui.rs @@ -57,6 +57,40 @@ pub fn status_phrase(call: Option<(&str, &str)>, place: Option<&str>, waiting: b } } +/// A step's own name: `computer` and `browser` carry the action in their arguments until the +/// step ends (computer + click → computer_use_click). +fn step_name<'a>(name: &'a str, v: &serde_json::Value) -> &'a str { + let action = v["action"].as_str().unwrap_or("").trim(); + match name { + crate::computer::TOOL => crate::computer::top_action_tool(action).unwrap_or("computer_use"), + crate::browser::TOOL => crate::browser::action_tool(action).unwrap_or("browser"), + n => n, + } +} + +/// What kind of step runs, for the face above the input (its prop): the same reading of the +/// step as the words beside it (see doing). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum StepKind { + /// Searching or reading the web, in a browser or not. + Web, + /// Looking at or working a computer's screen. + Screen, + Other, +} + +pub fn step_kind(name: &str, args: &str) -> StepKind { + let v = tools::args_of(args); + let name = step_name(name, &v); + if name.starts_with("computer_use") && name != "computer_use_check_permissions" { + StepKind::Screen + } else if crate::web::is_web_tool(name) || name.starts_with("browser") { + StepKind::Web + } else { + StepKind::Other + } +} + /// 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); @@ -65,12 +99,7 @@ fn doing(name: &str, args: &str, place: Option<&str>) -> 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, - }; + let name = step_name(name, &v); if name.starts_with("computer_use") { let verb = match name { "computer_use_screenshot" => "看螢幕".to_string(), diff --git a/src/app/mood_ui.rs b/src/app/mood_ui.rs new file mode 100644 index 0000000..49733d7 --- /dev/null +++ b/src/app/mood_ui.rs @@ -0,0 +1,566 @@ +// 輸入框上方的頭像:不同情境,不同的動作和小道具 (the face above the input, by mood). +// +// One place works out what the face is doing (mood_of: thinking, reading results, on the web, on +// a screen, writing, waiting for the person, done, failed), and each mood has its own motion and +// one small prop. Every prop lives inside the face's own square (it never reaches the words +// beside it), in the bot's colour, and keeps the head's depth: what passes behind the head is +// drawn before it, what is in front after it, with a rim in the page's colour so it reads even +// over a face of the same colour. Moods cross-fade, and a working mood holds a moment so quick +// steps don't make the face flicker. All of it is painted with egui shapes, so it looks the same +// on a Mac, on Windows and on Linux. + +use super::*; +use std::f32::consts::PI; + +/// What the face above the input is doing. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(super) enum Mood { + /// Nothing running: it looks down at the input and blinks. + Idle, + /// Working, with no words and no steps yet: three balls circle its head. + Thinking, + /// Steps done, the next not started, no words yet: it reads what came back (a sheet). + Between, + /// A web step runs: a magnifying glass sweeps, the eyes follow it. + Web, + /// A screen step runs: a pointer moves and clicks, a ripple where it clicked. + Screen, + /// Any other step runs: it looks across at the line saying what it does. + Step, + /// Words are coming out: head bowed, a pen writing a line of ink. + Writing, + /// It needs the person (a request or a question): it looks at them, a yellow dot glows. + Waiting, + /// A turn just finished well: a smile, a hop, a few sparkles (two seconds). + Done, + /// The last turn ended in an error: flat eyes, one shake, a drop of sweat. + Failed, +} + +impl Mood { + const ALL: [Mood; 10] = [Mood::Idle, Mood::Thinking, Mood::Between, Mood::Web, Mood::Screen, Mood::Step, Mood::Writing, Mood::Waiting, Mood::Done, Mood::Failed]; + + /// The moods of a running turn: they hold a moment before the next takes over. + fn busy(self) -> bool { + matches!(self, Mood::Thinking | Mood::Between | Mood::Web | Mood::Screen | Mood::Step | Mood::Writing) + } + + /// How far the head steps back to make room for the prop, and where it moves (in 40ths + /// of the face's square). + fn head(self) -> (f32, egui::Vec2) { + match self { + Mood::Thinking => (0.3, vec2(0.0, 1.5)), + Mood::Between => (0.24, vec2(-3.5, -3.0)), + Mood::Web => (0.24, vec2(0.0, -3.5)), + Mood::Screen => (0.24, vec2(-3.5, -3.5)), + Mood::Writing => (0.2, vec2(-3.5, -2.5)), + Mood::Failed => (0.12, vec2(-2.0, 1.5)), + _ => (0.0, egui::Vec2::ZERO), + } + } +} + +/// How long a working mood stays before another may take its place (seconds). +const MOOD_HOLD: f64 = 0.6; +/// The cross-fade between moods (seconds). +const MOOD_FADE: f32 = 0.25; +/// How long 「完成」 shows after a turn ends well (seconds). +pub(super) const CHEER_SECS: f32 = 2.0; + +/// The mood the facts say, for one bot: `working` (a turn runs), `waiting` (it needs the +/// person), `cheer` (a turn just ended well). +pub(super) fn mood_of(bot: &Bot, working: bool, waiting: bool, cheer: bool) -> Mood { + if waiting { + return Mood::Waiting; + } + if working { + // Only this turn's words count: the last turn's answer is long over by now. + let from = bot.messages.iter().rposition(|m| m.role == Role::User && !m.steer).unwrap_or(0); + let turn = &bot.messages[from..]; + let last = turn.iter().rev().find(|m| m.role == Role::Assistant && !m.note); + let running = last.and_then(|m| m.tool_calls.iter().rev().find(|c| matches!(c.status, ToolStatus::Running | ToolStatus::Waiting))); + return match running { + Some(c) => match chat_ui::step_kind(&c.name, &c.args) { + chat_ui::StepKind::Web => Mood::Web, + chat_ui::StepKind::Screen => Mood::Screen, + chat_ui::StepKind::Other => Mood::Step, + }, + None if last.is_some_and(|m| !m.text.trim().is_empty()) => Mood::Writing, + None if turn.iter().any(|m| m.role == Role::Tool) => Mood::Between, + None => Mood::Thinking, + }; + } + if cheer { + return Mood::Done; + } + if bot.messages.last().is_some_and(|m| m.error) { + return Mood::Failed; + } + Mood::Idle +} + +/// A colour for the props that stands out from the page: the bot's own, or — when it is too +/// close to the page's brightness — moved toward the text colour. +fn prop_ink(col: Color32, page: Color32, text: Color32) -> Color32 { + let light = |c: Color32| { + let l = egui::Rgba::from(c); + 0.2126 * l.r() + 0.7152 * l.g() + 0.0722 * l.b() + }; + if (light(col) - light(page)).abs() < 0.15 { + col.lerp_to_gamma(text, 0.6) + } else { + col + } +} + +fn smooth(x: f32) -> f32 { + let x = x.clamp(0.0, 1.0); + x * x * (3.0 - 2.0 * x) +} + +/// sin² bump between a and b. +fn bump(e: f32, a: f32, b: f32) -> f32 { + if e <= a || e >= b { + 0.0 + } else { + (PI * (e - a) / (b - a)).sin().powi(2) + } +} + +/// The thinking balls' angle after `age` seconds: they start at a calm pace and turn faster the +/// longer the thinking goes on (up to ~1.6× after 12 s), without ever jumping. +fn think_angle(age: f32) -> f32 { + const BASE: f32 = 2.2; + const EXTRA: f32 = 1.4; + const RAMP: f32 = 12.0; + BASE * age + EXTRA * if age < RAMP { age * age / (2.0 * RAMP) } else { age - RAMP / 2.0 } +} + +/// Where the magnifying glass is (web): sweeping the lower half of the face, left and right. +fn lens_at(c: egui::Pos2, u: f32, age: f32) -> egui::Pos2 { + let ph = age * 1.7; + c + vec2(8.5 * u * ph.sin(), 9.5 * u + 1.2 * u * (2.0 * ph).sin()) +} + +/// The pointer (screen): (its tip, how pressed it is 0…1, the click's ripple 0…1 or None). +fn pointer_at(c: egui::Pos2, u: f32, age: f32) -> (egui::Pos2, f32, Option) { + const CYCLE: f32 = 1.5; + let spots = [vec2(2.0, 3.0), vec2(9.5, 0.5), vec2(6.0, 6.5)]; + let n = (age / CYCLE).floor() as usize; + let e = (age / CYCLE).fract(); + let (from, to) = (spots[n % 3], spots[(n + 1) % 3]); + let tip = c + (from + (to - from) * smooth(e / 0.5)) * u; + let press = bump(e, 0.5, 0.64); + let ripple = (e >= 0.56).then(|| (e - 0.56) / 0.44); + (tip, press, ripple) +} + +/// The pen's tip (writing): it runs along a line under the face while words flow, and rests +/// where it is when they pause. `run`: how far along the line, 0…1. +fn pen_at(c: egui::Pos2, u: f32, run: f32) -> egui::Pos2 { + let x = c.x - 1.0 * u + 13.0 * u * run; + egui::pos2(x, c.y + 15.5 * u + ink_wave(x, u)) +} + +fn ink_wave(x: f32, u: f32) -> f32 { + 0.9 * u * (x / u * 1.7).sin() +} + +impl App { + /// The mood the face shows for this bot, and since when. A working mood holds MOOD_HOLD + /// before another working mood replaces it; anything else changes at once. + fn dock_mood(&mut self, ctx: &egui::Context, bot: &Bot, now: f64) -> (Mood, f64) { + let working = self.streams.contains_key(&bot.id); + let waiting = self.approvals.contains_key(&bot.id); + let cheer = self.cheer.get(&bot.id).is_some_and(|t| t.elapsed().as_secs_f32() < CHEER_SECS); + let want = mood_of(bot, working, waiting, cheer); + let shown = self.dock_moods.entry(bot.id).or_insert((want, now)); + if shown.0 != want { + let held = now - shown.1; + if shown.0.busy() && want.busy() && held < MOOD_HOLD { + ctx.request_repaint_after(std::time::Duration::from_secs_f64(MOOD_HOLD - held)); + } else { + *shown = (want, now); + } + } + *shown + } + + /// How long ago new text of the last answer arrived (`thinking`: its reasoning instead of + /// its words); None before any. Kept per bot in `seen`. + fn grew_ago(seen: &mut HashMap, key: u64, len: usize, now: f64) -> Option { + let (prev, at) = seen.get(&key).copied().unwrap_or((0, f64::NEG_INFINITY)); + let at = if len != prev && len > 0 { now } else { at }; + seen.insert(key, (len, at)); + at.is_finite().then_some(now - at) + } + + /// The face above the input (the bot itself, at work): its eyes and its little prop say how + /// things stand — see Mood. + pub(super) fn dock_face(&mut self, ui: &mut egui::Ui, bot: &Bot, rect: egui::Rect) { + let ctx = ui.ctx().clone(); + let now = ctx.input(|i| i.time); + let t = now as f32; + let (mood, since) = self.dock_mood(&ctx, bot, now); + let age = (now - since) as f32; + let u = rect.width() / 40.0; + let c = rect.center(); + let col = self.bot_color(bot); + let rim = self.pal.pane; + // The props' colour: the bot's, unless that nearly vanishes on this page (a dark face + // in the dark, a white one in the light). + let ink = prop_ink(col, rim, self.pal.text); + // Each mood's share of the picture now (they cross-fade). + let mut share = [0.0f32; Mood::ALL.len()]; + for (i, m) in Mood::ALL.iter().enumerate() { + share[i] = ctx.animate_bool_with_time(egui::Id::unique(("dock-mood", bot.id, i)), *m == mood, MOOD_FADE); + } + let w = |m: Mood| share[m as usize]; + + // This turn's answer: are words (or, while thinking, its reasoning) arriving right now? + let from = bot.messages.iter().rposition(|m| m.role == Role::User && !m.steer).unwrap_or(0); + let last = bot.messages[from..].iter().rev().find(|m| m.role == Role::Assistant && !m.note); + let words = last.map(|m| m.text.chars().count()).unwrap_or(0); + let reasoning = last.map(|m| m.thinking.chars().count()).unwrap_or(0); + let wrote_ago = Self::grew_ago(&mut self.write_len, bot.id, words, now); + let thought_ago = Self::grew_ago(&mut self.think_len, bot.id, reasoning, now); + let flowing = wrote_ago.is_some_and(|a| a < 0.7); + // A flash of light on each new piece of reasoning. + let glow = thought_ago.map(|a| (-(a as f32) * 5.0).exp()).unwrap_or(0.0); + + // Where the props are (the eyes follow them). + let lens = lens_at(c, u, age); + let (tip, press, ripple) = pointer_at(c, u, age); + let pen_run = { + // While words flow the pen runs along the line and starts a new one; it rests in a pause. + let e = self.pen_run.entry(bot.id).or_insert(0.0); + if flowing && mood == Mood::Writing { + *e = (*e + ctx.input(|i| i.stable_dt).min(0.1) * 0.55).fract(); + } + *e + }; + let pen = pen_at(c, u, pen_run); + let toward = |p: egui::Pos2| { + let d = (p - c) / (12.0 * u); + vec2(d.x.clamp(-1.0, 1.0), (-d.y).clamp(-1.0, 1.0)) + }; + + let target = match mood { + Mood::Waiting | Mood::Done => vec2(0.0, 0.1), + Mood::Thinking => vec2(0.55 * (t * 0.9).sin(), 0.85), + Mood::Between => vec2(0.35 + 0.45 * (t * 2.4).sin(), -0.55), + Mood::Web => toward(lens), + Mood::Screen => toward(tip), + Mood::Step => vec2(0.9, 0.45 + 0.06 * (t * 2.0).sin()), + Mood::Writing => vec2(0.5, -0.8), + Mood::Failed | Mood::Idle => vec2(0.15, -0.75), + }; + let moving = match mood { + Mood::Idle => false, + // An error stays on screen: the shake and the drop play once, then it rests. + Mood::Failed => age < 2.6, + _ => true, + }; + // (Its own state, apart from the same bot's face in the sidebar, which looks elsewhere.) + let mut pose = self.settle_face(&ctx, !bot.id, target, moving, false); + pose.eyes = match mood { + Mood::Done => avatar::Eyes::Smile, + Mood::Failed => avatar::Eyes::Flat, + _ => avatar::Eyes::Open, + }; + // Writing: head bowed over the words, nodding in time with them while they flow. + pose.pitch += w(Mood::Writing) * (7.0 + if flowing { 3.5 * (t * 6.5).sin() } else { 0.0 }); + // Waiting: a small hop every few seconds, so a request isn't missed. + pose.lift += w(Mood::Waiting) * 0.12 * bump((age / 3.2).fract(), 0.0, 0.16); + // Done: one hop as it finishes. + pose.lift += w(Mood::Done) * 0.32 * if age < 0.45 { (PI * age / 0.45).sin() } else { 0.0 }; + // Failed: one quick shake of the head. + pose.gaze.x += w(Mood::Failed) * 0.8 * (age * 28.0).sin() * (1.0 - age / 0.7).max(0.0); + + // The head steps back for its prop. + let (mut shrink, mut off) = (0.0f32, egui::Vec2::ZERO); + for m in Mood::ALL { + let (s, o) = m.head(); + shrink += w(m) * s; + off += w(m) * o; + } + let head = egui::Rect::from_center_size(c + off * u, rect.size() * (1.0 - shrink.clamp(0.0, 0.4))); + + let painter = ui.painter().clone(); + // Behind the head: the far side of the thinking ring. + let balls = if w(Mood::Thinking) > 0.0 { think_balls(c, rect, age, w(Mood::Thinking), glow) } else { vec![] }; + for b in balls.iter().filter(|b| b.depth < 0.5) { + b.paint(&painter, ink, None, u); + } + avatar::paint_posed(&painter, head, &bot.shape, col, pose); + // In front of it: everything else. + for b in balls.iter().filter(|b| b.depth >= 0.5) { + b.paint(&painter, ink, Some(rim), u); + } + if w(Mood::Between) > 0.0 { + paint_sheet(&painter, c, u, t, ink, rim, w(Mood::Between)); + } + if w(Mood::Web) > 0.0 { + paint_lens(&painter, lens, u, ink, rim, w(Mood::Web)); + } + if w(Mood::Screen) > 0.0 { + paint_pointer(&painter, tip, press, ripple, u, ink, rim, w(Mood::Screen)); + } + if w(Mood::Writing) > 0.0 { + paint_pen(&painter, c, pen, u, ink, rim, w(Mood::Writing)); + } + if w(Mood::Waiting) > 0.0 { + // The yellow dot that means 「需要你」, and a ring of light leaving it. + let k = rect.width() / 64.0; + let at = rect.right_top() + vec2(-7.0, 7.0) * k; + let a = w(Mood::Waiting); + let e = (age / 1.6).fract(); + painter.circle_stroke(at, 6.0 * k + 6.0 * u * e, Stroke::new(1.6 * u, self.pal.attention.gamma_multiply(0.75 * (1.0 - e) * a))); + painter.circle_filled(at, 7.0 * k + 1.5, rim.gamma_multiply(a)); + painter.circle_filled(at, 6.0 * k, self.pal.attention.gamma_multiply(a)); + } + if w(Mood::Done) > 0.0 { + paint_sparkles(&painter, c, u, age, w(Mood::Done)); + } + if w(Mood::Failed) > 0.0 { + paint_sweat(&painter, rect, u, age, rim, w(Mood::Failed)); + } + } +} + +/// One of the three thinking balls. +struct Ball { + at: egui::Pos2, + r: f32, + /// 0 at the back of the ring (above the middle), 1 at the front (below). + depth: f32, + alpha: f32, + glow: f32, +} + +impl Ball { + fn paint(&self, painter: &egui::Painter, col: Color32, rim: Option, u: f32) { + if self.glow > 0.02 { + painter.circle_filled(self.at, self.r + 2.5 * u * self.glow, col.gamma_multiply(0.18 * self.glow * self.alpha)); + } + if let Some(rim) = rim { + painter.circle_filled(self.at, self.r + 1.2 * u, rim.gamma_multiply(self.alpha)); + } + painter.circle_filled(self.at, self.r, col.gamma_multiply((0.45 + 0.55 * self.depth) * self.alpha)); + } +} + +/// Thinking: three balls on a flat ring around the head; the far ones small and dim, the near +/// ones large. `glow`: a new piece of reasoning just arrived (they swell and shine). +fn think_balls(c: egui::Pos2, rect: egui::Rect, age: f32, k: f32, glow: f32) -> Vec { + let u = rect.width() / 40.0; + let (rx, ry) = (rect.width() / 2.0 - 2.5 * u, rect.height() * 0.17); + let ring = c + vec2(0.0, rect.height() * 0.08); + (0..3) + .map(|n| { + let a = think_angle(age) + n as f32 * 2.0 * PI / 3.0; + let depth = (a.sin() + 1.0) / 2.0; + Ball { at: ring + vec2(a.cos() * rx, a.sin() * ry), r: (1.4 + 1.4 * depth) * u * (0.4 + 0.6 * k) * (1.0 + 0.3 * glow), depth, alpha: k, glow } + }) + .collect() +} + +/// Between steps: a small sheet at its lower right, its lines lighting up one after another +/// (reading what came back). +fn paint_sheet(painter: &egui::Painter, c: egui::Pos2, u: f32, t: f32, col: Color32, rim: Color32, k: f32) { + let bob = 0.6 * u * (t * 2.0).sin(); + let sheet = egui::Rect::from_min_size(c + vec2(5.5 * u, 1.5 * u + bob), vec2(12.0 * u, 15.0 * u)); + painter.rect_filled(sheet.expand(1.2 * u), 3.0 * u, rim.gamma_multiply(k)); + painter.rect_filled(sheet, 2.0 * u, rim.gamma_multiply(k)); + painter.rect_stroke(sheet, 2.0 * u, Stroke::new(1.3 * u, col.gamma_multiply(k)), egui::StrokeKind::Inside); + let reading = ((t * 0.9).fract() * 4.0) as usize; + for i in 0..4 { + let y = sheet.top() + 3.6 * u + i as f32 * 3.0 * u; + let right = if i == 3 { sheet.left() + sheet.width() * 0.55 } else { sheet.right() - 2.6 * u }; + let a = match i.cmp(&reading) { + std::cmp::Ordering::Less => 0.55, + std::cmp::Ordering::Equal => 1.0, + std::cmp::Ordering::Greater => 0.22, + }; + painter.line_segment([egui::pos2(sheet.left() + 2.6 * u, y), egui::pos2(right, y)], Stroke::new(1.3 * u, col.gamma_multiply(a * k))); + } +} + +/// On the web: a magnifying glass, its handle down and to the right. +fn paint_lens(painter: &egui::Painter, at: egui::Pos2, u: f32, col: Color32, rim: Color32, k: f32) { + let r = 4.4 * u; + let dir = vec2(1.0, 1.0).normalized(); + let (h0, h1) = (at + dir * r, at + dir * (r + 4.2 * u)); + painter.line_segment([h0, h1], Stroke::new(3.8 * u, rim.gamma_multiply(k))); + painter.circle_filled(at, r + 1.6 * u, rim.gamma_multiply(k)); + painter.line_segment([h0, h1], Stroke::new(2.2 * u, col.gamma_multiply(k))); + painter.circle_stroke(at, r, Stroke::new(1.7 * u, col.gamma_multiply(k))); + // A glint on the glass. + let g = at + vec2(-1.6 * u, -1.6 * u); + painter.line_segment([g + vec2(-0.6 * u, 0.9 * u), g + vec2(0.9 * u, -0.6 * u)], Stroke::new(1.1 * u, col.gamma_multiply(0.35 * k))); +} + +/// On a screen: a pointer (pressed a little as it clicks), and a ripple where it clicked. +#[allow(clippy::too_many_arguments)] +fn paint_pointer(painter: &egui::Painter, tip: egui::Pos2, press: f32, ripple: Option, u: f32, col: Color32, rim: Color32, k: f32) { + if let Some(e) = ripple { + painter.circle_stroke(tip, 1.5 * u + 6.5 * u * e, Stroke::new(1.3 * u, col.gamma_multiply(0.8 * (1.0 - e) * k))); + } + let s = 0.95 * u * (1.0 - 0.15 * press); + let p = |x: f32, y: f32| tip + vec2(x, y) * s; + // The arrow's outline (for the rim), then its two convex halves filled. + let outline = vec![p(0.0, 0.0), p(0.0, 10.0), p(2.5, 7.7), p(4.4, 11.5), p(6.1, 10.7), p(4.3, 7.0), p(7.6, 7.0)]; + painter.add(egui::Shape::closed_line(outline, Stroke::new(2.6 * u, rim.gamma_multiply(k)))); + let fill = col.gamma_multiply(k); + painter.add(egui::Shape::convex_polygon(vec![p(0.0, 0.0), p(0.0, 10.0), p(7.6, 7.0)], fill, Stroke::NONE)); + painter.add(egui::Shape::convex_polygon(vec![p(2.3, 7.0), p(4.3, 7.0), p(6.1, 10.7), p(4.4, 11.5)], fill, Stroke::NONE)); +} + +/// The pen, from its tip to its end (in 40ths of the face's square). +const PEN: egui::Vec2 = egui::Vec2::new(5.5, -10.0); + +/// Writing: a pen whose tip draws a wavy line of ink under the face. +fn paint_pen(painter: &egui::Painter, c: egui::Pos2, tip: egui::Pos2, u: f32, col: Color32, rim: Color32, k: f32) { + let start = c.x - 1.0 * u; + if tip.x - start > 0.5 * u { + let n = ((tip.x - start) / (0.8 * u)).ceil().max(2.0) as usize; + let ink: Vec = (0..=n).map(|i| { + let x = start + (tip.x - start) * i as f32 / n as f32; + egui::pos2(x, c.y + 15.5 * u + ink_wave(x, u)) + }).collect(); + painter.add(egui::Shape::line(ink.clone(), Stroke::new(3.4 * u, rim.gamma_multiply(k)))); + painter.add(egui::Shape::line(ink, Stroke::new(1.7 * u, col.gamma_multiply(0.8 * k)))); + } + let end = tip + PEN * u; + painter.line_segment([tip, end], Stroke::new(5.2 * u, rim.gamma_multiply(k))); + painter.line_segment([tip + vec2(0.8 * u, -1.4 * u), end], Stroke::new(3.2 * u, col.gamma_multiply(k))); + // The nib, and a band near the top of the pen. + painter.circle_filled(tip, 1.1 * u, col.gamma_multiply(k)); + let band = tip + PEN * u * 0.72; + painter.line_segment([band + vec2(-1.3 * u, -0.7 * u), band + vec2(1.3 * u, 0.7 * u)], Stroke::new(0.9 * u, rim.gamma_multiply(0.8 * k))); +} + +/// Done: five small gold sparkles pop out around the head, one after another, and fade. +fn paint_sparkles(painter: &egui::Painter, c: egui::Pos2, u: f32, age: f32, k: f32) { + const GOLD: Color32 = Color32::from_rgb(0xf5, 0xb8, 0x2e); + const SPOTS: [(f32, f32, f32); 5] = [(-14.5, -13.0, 1.0), (14.5, -13.5, 0.8), (16.0, 5.5, 1.0), (-15.5, 8.0, 0.75), (2.0, -17.0, 0.6)]; + for (i, (x, y, size)) in SPOTS.iter().enumerate() { + let e = (age - i as f32 * 0.1) / 1.1; + if !(0.0..1.0).contains(&e) { + continue; + } + // Grows fast, then shrinks away. + let s = 4.4 * u * size * (PI * e.powf(0.6)).sin(); + let at = c + vec2(*x, *y) * u; + let a = GOLD.gamma_multiply(k * (1.0 - e * 0.4)); + let thin = 0.3 * s; + painter.add(egui::Shape::convex_polygon(vec![at + vec2(0.0, -s), at + vec2(thin, 0.0), at + vec2(0.0, s), at + vec2(-thin, 0.0)], a, Stroke::NONE)); + painter.add(egui::Shape::convex_polygon(vec![at + vec2(-s, 0.0), at + vec2(0.0, -thin), at + vec2(s, 0.0), at + vec2(0.0, thin)], a, Stroke::NONE)); + } +} + +/// Failed: a drop of sweat at its upper right, sliding down a little, once. +fn paint_sweat(painter: &egui::Painter, rect: egui::Rect, u: f32, age: f32, rim: Color32, k: f32) { + const SWEAT: Color32 = Color32::from_rgb(0x5b, 0x9c, 0xf6); + let slide = 2.5 * u * smooth((age - 0.3) / 1.8); + let d = rect.right_top() + vec2(-7.5 * u, 10.0 * u + slide); + let r = 2.7 * u; + let drop = |grow: f32| vec![egui::pos2(d.x, d.y - 2.1 * r - grow), egui::pos2(d.x + r * 0.95 + grow * 0.7, d.y - 0.3 * r), egui::pos2(d.x - r * 0.95 - grow * 0.7, d.y - 0.3 * r)]; + painter.add(egui::Shape::convex_polygon(drop(1.2 * u), rim.gamma_multiply(k), Stroke::NONE)); + painter.circle_filled(d, r + 1.2 * u, rim.gamma_multiply(k)); + painter.add(egui::Shape::convex_polygon(drop(0.0), SWEAT.gamma_multiply(k), Stroke::NONE)); + painter.circle_filled(d, r, SWEAT.gamma_multiply(k)); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::{Message, ToolCall}; + + fn bot_with(msgs: Vec) -> Bot { + let mut b = crate::model::State::demo().bots[0].clone(); + b.messages = msgs; + b + } + + fn step(name: &str, args: &str, status: ToolStatus) -> Message { + Message { tool_calls: vec![ToolCall { id: "s".into(), name: name.into(), args: args.into(), status }], ..Message::assistant("", "m") } + } + + #[test] + fn each_moment_of_a_turn_has_its_mood() { + let ask = Message::user("幫我查明天台北的天氣"); + // Nothing yet: thinking. + assert_eq!(mood_of(&bot_with(vec![ask.clone(), Message::assistant("", "m")]), true, false, false), Mood::Thinking); + // A web step, in its own name or the browser's. + assert_eq!(mood_of(&bot_with(vec![ask.clone(), step("web_fetch", r#"{"url":"https://example.com"}"#, ToolStatus::Running)]), true, false, false), Mood::Web); + assert_eq!(mood_of(&bot_with(vec![ask.clone(), step(crate::browser::TOOL, r#"{"action":"open"}"#, ToolStatus::Running)]), true, false, false), Mood::Web); + // A screen step. + assert_eq!(mood_of(&bot_with(vec![ask.clone(), step("computer_use_click", "{}", ToolStatus::Running)]), true, false, false), Mood::Screen); + // Any other step. + assert_eq!(mood_of(&bot_with(vec![ask.clone(), step("shell", r#"{"command":"ls"}"#, ToolStatus::Running)]), true, false, false), Mood::Step); + // A step done, nothing running, no words: reading what came back. + let done = vec![ask.clone(), step("web_fetch", "{}", ToolStatus::Done), Message::tool_result("s", "web_fetch", "26°C"), Message::assistant("", "m")]; + assert_eq!(mood_of(&bot_with(done.clone()), true, false, false), Mood::Between); + // Words coming out. + let mut writing = done.clone(); + writing.push(Message::assistant("明天 26°C", "m")); + assert_eq!(mood_of(&bot_with(writing.clone()), true, false, false), Mood::Writing); + // The person is asked: that comes first. + assert_eq!(mood_of(&bot_with(writing.clone()), true, true, false), Mood::Waiting); + // After the turn: done for a moment, else resting; an error shows. + assert_eq!(mood_of(&bot_with(writing.clone()), false, false, true), Mood::Done); + assert_eq!(mood_of(&bot_with(writing), false, false, false), Mood::Idle); + let failed = vec![ask.clone(), Message { error: true, ..Message::assistant("連線逾時", "m") }]; + assert_eq!(mood_of(&bot_with(failed), false, false, false), Mood::Failed); + // Last turn's words don't count in a new turn. + let next = vec![ask.clone(), Message::assistant("上一題的答案", "m"), Message::user("再查高雄"), Message::assistant("", "m")]; + assert_eq!(mood_of(&bot_with(next), true, false, false), Mood::Thinking); + } + + #[test] + fn props_stand_out_from_the_page() { + let (light, dark) = (Color32::from_rgb(0xff, 0xff, 0xff), Color32::from_rgb(0x16, 0x16, 0x16)); + let (ink_on_light, ink_on_dark) = (Color32::from_rgb(0x1c, 0x1c, 0x1c), Color32::from_rgb(0xec, 0xec, 0xec)); + // A black face on a light page, a green one anywhere: their own colour. + assert_eq!(prop_ink(Color32::BLACK, light, ink_on_light), Color32::BLACK); + let green = Color32::from_rgb(0x12, 0x9a, 0x4f); + assert_eq!(prop_ink(green, dark, ink_on_dark), green); + // A dark-grey face in the dark, a white one in the light: lifted toward the text. + let grey = Color32::from_gray(0x4a); + assert!(prop_ink(grey, dark, ink_on_dark).r() > 0x90); + assert!(prop_ink(Color32::WHITE, light, ink_on_light).r() < 0x90); + } + + #[test] + fn the_thinking_ring_speeds_up_smoothly() { + // Continuous (no jump where the speed-up ends) and always moving forward. + let a = |x: f32| think_angle(x); + assert!((a(12.0 - 1e-3) - a(12.0 + 1e-3)).abs() < 0.02); + let mut prev = a(0.0); + for i in 1..400 { + let next = a(i as f32 * 0.05); + assert!(next > prev); + prev = next; + } + // Faster after a while than at the start. + assert!(a(21.0) - a(20.0) > (a(1.0) - a(0.0)) * 1.4); + } + + #[test] + fn props_stay_inside_the_faces_square() { + let rect = egui::Rect::from_min_size(egui::pos2(100.0, 100.0), vec2(40.0, 40.0)); + let (c, u) = (rect.center(), 1.0); + let inside = |p: egui::Pos2, margin: f32| p.x >= rect.left() - margin && p.x <= rect.right() + margin && p.y >= rect.top() - margin && p.y <= rect.bottom() + margin; + for i in 0..200 { + let age = i as f32 * 0.037; + let lens = lens_at(c, u, age); + // The lens with its handle. + assert!(inside(lens + vec2(4.4 + 1.6, 4.4 + 1.6), 0.5) && inside(lens - vec2(6.0, 6.0), 0.5), "lens {lens:?}"); + let (tip, _, _) = pointer_at(c, u, age); + assert!(inside(tip, 0.0) && inside(tip + vec2(7.6, 11.5), 0.5), "pointer {tip:?}"); + let pen = pen_at(c, u, (age * 0.3).fract()); + assert!(inside(pen + PEN, 0.5) && inside(pen + vec2(0.0, 1.5), 0.5), "pen {pen:?}"); + } + } +} diff --git a/src/app/sidebar_ui.rs b/src/app/sidebar_ui.rs index 5c79ed8..10562ea 100644 --- a/src/app/sidebar_ui.rs +++ b/src/app/sidebar_ui.rs @@ -106,7 +106,7 @@ impl App { /// A face (kept under `key`) turning its eyes toward `target`, blinking now and then, and /// carrying out a poke; `busy` keeps the window drawing. `spin`: turn slowly while working /// (Grok-style), easing back upright when the bot finishes. - fn settle_face(&mut self, ctx: &egui::Context, key: u64, target: egui::Vec2, busy: bool, spin: bool) -> avatar::Pose { + pub(super) fn settle_face(&mut self, ctx: &egui::Context, key: u64, target: egui::Vec2, busy: bool, spin: bool) -> avatar::Pose { let now = ctx.input(|i| i.time); let id = key; let working = busy; @@ -186,100 +186,6 @@ impl App { avatar::paint_posed(painter, rect, &b.shape, col, pose); } - /// The face above the input (the bot itself, looking at what it does): its eyes say how - /// things stand — down at the input while it waits for words, up while it thinks, across at - /// the line saying what it is doing, straight at the person (with a yellow dot) when it needs - /// them, smiling for two seconds when it has finished, two flat lines after an error. - pub(super) fn dock_face(&mut self, ui: &mut egui::Ui, bot: &Bot, rect: egui::Rect) { - let ctx = ui.ctx().clone(); - let now = ctx.input(|i| i.time) as f32; - let waiting = self.approvals.contains_key(&bot.id); - let working = self.streams.contains_key(&bot.id); - // Only this turn's words count (see working_phrase): the last turn's answer is long - // over by now, and must not make a thinking face pretend it is still writing. - let from = bot.messages.iter().rposition(|m| m.role == Role::User && !m.steer).unwrap_or(0); - let last = bot.messages[from..].iter().rev().find(|m| m.role == Role::Assistant && !m.note); - let running = working && last.is_some_and(|m| m.tool_calls.iter().any(|c| matches!(c.status, ToolStatus::Running | ToolStatus::Waiting))); - let cheer = self.cheer.get(&bot.id).is_some_and(|t| t.elapsed().as_secs_f32() < 2.0); - let failed = !working && bot.messages.last().is_some_and(|m| m.error); - // Writing: words are flowing out and no step runs — the face bows to its own writing. - // Thinking: it works, nothing runs and no words yet — three small balls circle its head. - let has_text = last.is_some_and(|m| !m.text.trim().is_empty()); - let writing = working && has_text && !running && !waiting; - let thinking = working && !running && !waiting && !has_text; - let target = if waiting { - vec2(0.0, 0.1) - } else if running { - vec2(0.9, 0.45 + 0.06 * (now * 2.0).sin()) - } else if writing { - vec2(0.5, -0.8) - } else if working { - vec2(0.55 * (now * 0.9).sin(), 0.85) - } else { - vec2(0.15, -0.75) - }; - // (Its own state, apart from the same bot's face in the sidebar, which looks elsewhere.) - // The spin rests here: thinking and writing have their own motions (balls, nod). - let mut pose = self.settle_face(&ctx, !bot.id, target, working, false); - pose.eyes = if cheer { avatar::Eyes::Smile } else if failed { avatar::Eyes::Flat } else { avatar::Eyes::Open }; - if writing { - // Head bowed over the words, nodding in time with them: the nod runs while words - // arrived in the last blink of an eye, and rests when the flowing stops. - let len = last.map(|m| m.text.chars().count()).unwrap_or(0); - let (prev, at) = self.write_len.get(&bot.id).copied().unwrap_or((len, now as f64)); - // The count moving at all (a new word, or a fresh answer) means words came just now. - let grow_at = if len != prev { now as f64 } else { at }; - self.write_len.insert(bot.id, (len, grow_at)); - let flowing = now as f64 - grow_at < 0.7; - pose.pitch = 7.0 + if flowing { 3.5 * (now * 6.5).sin() } else { 0.0 }; - } - if cheer { - ctx.request_repaint_after(std::time::Duration::from_millis(200)); - } - let col = self.bot_color(bot); - // Thinking: three balls circle the head on a flat ring. The head steps back a little to - // make room, so the ring runs AROUND it — the balls on the far side pass behind the head, - // the near ones in front (with a rim in the page's colour, so they read even over a face - // of the same colour). All inside the face's own square: they never reach the words - // beside it. It eases in and out instead of popping. - let k = ctx.animate_bool_with_time(egui::Id::unique(("dock-think", bot.id)), thinking, 0.25); - let head = egui::Rect::from_center_size(rect.center() + vec2(0.0, 1.5 * k), rect.size() * (1.0 - 0.3 * k)); - let balls: Vec<(egui::Pos2, f32, f32)> = if k > 0.0 { - let (rx, ry) = (rect.width() / 2.0 - 2.5, rect.height() * 0.17); - let ring = rect.center() + vec2(0.0, rect.height() * 0.08); - (0..3) - .map(|n| { - let a = now * 2.2 + n as f32 * 2.0 * PI / 3.0; - // Depth: 0 at the back of the ring (above), 1 at the front (below). - let d = (a.sin() + 1.0) / 2.0; - (ring + vec2(a.cos() * rx, a.sin() * ry), (1.4 + 1.4 * d) * (0.4 + 0.6 * k), d) - }) - .collect() - } else { - Vec::new() - }; - let ball = |painter: &egui::Painter, (at, r, d): (egui::Pos2, f32, f32), rim: Color32| { - if rim != Color32::TRANSPARENT { - painter.circle_filled(at, r + 1.2, rim.gamma_multiply(k)); - } - painter.circle_filled(at, r, col.gamma_multiply((0.45 + 0.55 * d) * k)); - }; - for b in balls.iter().copied().filter(|b| b.2 < 0.5) { - ball(ui.painter(), b, Color32::TRANSPARENT); - } - avatar::paint_posed(ui.painter(), head, &bot.shape, col, pose); - for b in balls.iter().copied().filter(|b| b.2 >= 0.5) { - ball(ui.painter(), b, self.pal.pane); - } - if waiting { - // (Sized with the face.) - let k = rect.width() / 64.0; - let at = rect.right_top() + vec2(-7.0, 7.0) * k; - ui.painter().circle_filled(at, 7.0 * k + 1.5, self.pal.pane); - ui.painter().circle_filled(at, 6.0 * k, self.pal.attention); - } - } - /// The sidebar's contents (the panel itself, its width and dragging live in sidebar()). /// The bottom row (you, 連結應用程式) has its own fixed strip so it is never cut off. pub(super) fn sidebar_body(&mut self, ui: &mut egui::Ui) {