AnyBot/src/find.rs

169 lines
7.3 KiB
Rust
Raw Normal View History

問題卡、搜尋: the bot asks with a card; every chat is searched; a refusal holds for the turn - 問題卡 (ask_person, src/ask.rs): up to 6 questions on a card above the input, one at a time — a choice (one click moves on), several choices, or a field that arrives filled for the person to correct; 「自己回答」 on every question, 上一題 and 略過. The turn waits; a message typed instead leaves the card unanswered. Travels as an approval of kind Question (questions as JSON) with a new answer Answered, so the window, a screen of another brain and the phone draw the same card. - 搜尋所有聊天 (src/find.rs): the sidebar's search also lists what the person and the bots said in every chat, past conversations included, and attachment names; newest first, 40 at most. A click opens the bot (bringing a past conversation back first), scrolls to the message and lights it for a moment. - 拒絕後停下: a step the person refused is refused for them when it comes back unchanged in the same turn — no second card, no second review — until they write again. - The bot's instructions: stop after a refusal instead of trying another way; before sending, posting, buying or deleting, check the person's own messages asked for exactly that, and ask with the card when they didn't. - 直接操作 no longer answers a hand-off (or a question) on the person's behalf. - The repeated-step check leaves questions to the person alone. - Screenshot views `ask` and `find`; FEATURES.md. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha3QxSfoydRPM9mjj6d
2026-11-12 02:17:32 +00:00
// 搜尋所有聊天: the words of every chat — the open conversation of each bot and its past ones —
// and the names of the files in them. What the person and the bots said is searched; the
// results of tools are not (a page read once would drown the rest).
//
// Newest first. A hit knows where it is (bot, conversation, message), so a click opens it there.
use crate::model::{Bot, Message, Role};
/// The most that is shown; `search` says whether there was more.
pub const LIMIT: usize = 40;
/// A snippet: this much before the match, and this much in all.
const BEFORE: usize = 12;
const SNIPPET: usize = 70;
#[derive(Clone, Debug, PartialEq)]
pub struct Hit {
pub bot: u64,
/// None: the open conversation; Some(i): 過去的對話 number i.
pub thread: Option<usize>,
/// Where in that conversation, and when it was said (0 for old messages without a time).
pub index: usize,
pub at: i64,
pub mine: bool,
/// The match is a file's name.
pub file: bool,
pub snippet: String,
}
/// One line around the match, with … where it was cut.
fn snippet(text: &str, lower_at: usize, lower: &str) -> String {
// (Lower-casing can change a string's length, so the place is counted in characters.)
let at = lower[..lower_at].chars().count();
let chars: Vec<char> = text.chars().map(|c| if c.is_whitespace() { ' ' } else { c }).collect();
let from = at.saturating_sub(BEFORE).min(chars.len());
let to = (from + SNIPPET).min(chars.len());
let mut s: String = chars[from..to].iter().collect::<String>().split(' ').filter(|w| !w.is_empty()).collect::<Vec<_>>().join(" ");
if from > 0 {
s.insert(0, '…');
}
if to < chars.len() {
s.push('…');
}
s
}
fn in_messages(bot: u64, thread: Option<usize>, msgs: &[Message], q: &str, out: &mut Vec<Hit>) {
for (index, m) in msgs.iter().enumerate() {
if !matches!(m.role, Role::User | Role::Assistant) || m.summary {
continue;
}
let mine = m.role == Role::User;
let lower = m.text.to_lowercase();
if let Some(at) = lower.find(q) {
out.push(Hit { bot, thread, index, at: m.at, mine, file: false, snippet: snippet(&m.text, at, &lower) });
continue;
}
if let Some(a) = m.attachments.iter().find(|a| a.name.to_lowercase().contains(q)) {
out.push(Hit { bot, thread, index, at: m.at, mine, file: true, snippet: a.name.clone() });
}
}
}
/// Every message that has `query` in it, newest first, and whether there were more than LIMIT.
pub fn search(bots: &[Bot], query: &str) -> (Vec<Hit>, bool) {
let q = query.trim().to_lowercase();
if q.is_empty() {
return (vec![], false);
}
let mut out = vec![];
for b in bots {
in_messages(b.id, None, &b.messages, &q, &mut out);
for (i, (_, msgs)) in b.threads.iter().enumerate() {
in_messages(b.id, Some(i), msgs, &q, &mut out);
}
}
// Newest first; messages without a time keep their order, after the dated ones.
out.sort_by_key(|a| std::cmp::Reverse(a.at));
問題卡、搜尋: the bot asks with a card; every chat is searched; a refusal holds for the turn - 問題卡 (ask_person, src/ask.rs): up to 6 questions on a card above the input, one at a time — a choice (one click moves on), several choices, or a field that arrives filled for the person to correct; 「自己回答」 on every question, 上一題 and 略過. The turn waits; a message typed instead leaves the card unanswered. Travels as an approval of kind Question (questions as JSON) with a new answer Answered, so the window, a screen of another brain and the phone draw the same card. - 搜尋所有聊天 (src/find.rs): the sidebar's search also lists what the person and the bots said in every chat, past conversations included, and attachment names; newest first, 40 at most. A click opens the bot (bringing a past conversation back first), scrolls to the message and lights it for a moment. - 拒絕後停下: a step the person refused is refused for them when it comes back unchanged in the same turn — no second card, no second review — until they write again. - The bot's instructions: stop after a refusal instead of trying another way; before sending, posting, buying or deleting, check the person's own messages asked for exactly that, and ask with the card when they didn't. - 直接操作 no longer answers a hand-off (or a question) on the person's behalf. - The repeated-step check leaves questions to the person alone. - Screenshot views `ask` and `find`; FEATURES.md. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha3QxSfoydRPM9mjj6d
2026-11-12 02:17:32 +00:00
let more = out.len() > LIMIT;
out.truncate(LIMIT);
(out, more)
}
/// What the chats amount to, cheaply: a search is done again only when this or the query changes.
/// (How many messages, the newest one's time, and which conversations are the open ones.)
pub fn stamp(bots: &[Bot]) -> (usize, i64, i64) {
let (mut n, mut newest, mut open) = (0, 0, 0i64);
for b in bots {
n += b.messages.len() + b.threads.iter().map(|t| t.1.len()).sum::<usize>() + b.threads.len();
newest = newest.max(b.messages.last().map(|m| m.at).unwrap_or(0));
open = open.wrapping_mul(31).wrapping_add(b.messages.first().map(|m| m.at).unwrap_or(0));
}
(n, newest, open)
}
/// 搜尋 → 那則訊息: the message a click on a hit goes to (the chat scrolls there and lights it
/// for a moment).
#[derive(Clone, Copy, Debug)]
pub struct Goto {
pub bot: u64,
pub index: usize,
pub at: i64,
pub since: std::time::Instant,
}
/// How long the chat keeps scrolling to it (the layout settles over a few frames), and how long
/// the light stays.
pub const GOTO_SCROLL_SECS: f32 = 0.35;
pub const GOTO_LIGHT_SECS: f32 = 1.8;
impl Goto {
/// Is it this message? By its time; by its place for old messages that have none.
pub fn is(&self, bot: u64, index: usize, at: i64) -> bool {
self.bot == bot && if self.at != 0 { self.at == at } else { self.index == index }
}
}
#[cfg(test)]
mod tests {
use super::*;
fn bot(id: u64, msgs: Vec<Message>, threads: Vec<(String, Vec<Message>)>) -> Bot {
let mut b = crate::model::State::demo().bots[0].clone();
b.id = id;
perf+fix: 舊電腦也輕、連上才進去、送出不重複、小模型說了就做、智慧模式常開、提早壓縮 畫面省資源(舊 Intel Mac) - 聊天紀錄改成共用、寫入時才複製(src/shared.rs):側欄和聊天每一格不再複製整份聊天(約 13 MB/格) - Markdown 解析、程式碼上色依內容快取,只有串流中的那則重算 - 用內建顯示晶片(wgpu LowPower),雙 GPU 的 Mac 不再喚醒獨顯;WGPU_POWER_PREF 照樣優先 - 所有轉圈圖示限每秒 20 次(egui 內建 Spinner 跑滿刷新率);淡入、彩帶、跳轉高亮也限速 - 頭像共用一個眨眼時鐘、捲出畫面的不畫;你不在(視窗不在前面或 90 秒沒動)不眨眼 - ioreg 移出畫面執行緒;Bot 工作中每 5 秒存一次(原 2 秒) - 螢幕電腦的大腦副本每 5 秒在背景寫一次(原本每次同步都在畫面執行緒寫整份) - 手機狀態裡的指令輸出先截短再遮罩金鑰 連線(螢幕電腦 ↔ 大腦) - 連上、拿到最新資料才進去:之前整個視窗停在「正在連到「…」…」,連不上 10 秒以上可改回這台自己的 Bot - 重開只補差異:副本旁記下版本與這台在大腦的名字;第一次拉取帶 config=1、不等新消息 - 漏收一次回應只補差異(大腦保留上一份 Seen),不再整份重抓 - 送出不重複:POST 只在根本沒送出去時才重試;訊息與動作帶編號、斷線自己重送約 100 秒,大腦同一個只做一次;改動依 (client, seq) 只做一次,seq 從時鐘起算 - 斷一下還能送(排隊),真的送不到文字放回輸入框;按過的允許卡片 30 秒內不再跳出 - 獨立審查修正:動作編號加上這次啟動的標記(沿用 client 時不再撞號被當重送);等待頁以「收到第一個回答」為準、設定讀不出來照樣進去並說原因、等滿 10 秒就有離開鈕;整份重抓失敗會再要;上一次拉取失敗時帶 retry,大腦從上一份算差異;去重表滿了淘汰最舊的 - 手機頁在背景時不重畫訊息,回到前景再畫 小模型持續做(src/agent/followthrough.rs) - 回答說了要做什麼卻沒呼叫工具、或問「要我現在就開始嗎?」:告訴模型、下一步安靜地跑;動手才顯示,標記「〔到此為止〕」或又只說一次都不顯示;連兩次、一輪 12 次為限;最後一句提到刪除、付款、寄出、關機這類收不回來的事一律不提醒 - OpenCode Go 模型清單改讀新格式 api/recommended_api(舊的 endpoint 照讀) 智慧模式常開 - 預設開、/smart off 與手機都關不掉(只有管理員鎖時關);設定頁只剩逾時滑桿 30–1800 秒;輸入列不再有它的圖示 token 壓縮提早 - 門檻 70→60%(進行中 65%);估算改成英數 3.5 字元一 token;一個要求做很多步時主動把這一輪較早的步驟寫成摘要(至少 10 則),不等模型說太長 feature-map:chat.md 新增 chat-followthrough(含步驟)、chat-compact 6 成、chat-steps;autonomy.md 智慧模式一直開著(步驟改寫);account.md 連上才進去、重送與去重;settings/safety/phone 同步。FEATURES.md 同步。 已驗證: cargo test 739 通過、clippy 無新警告(含 featuremap:: 11 項、layout_audit::、新增 followthrough/shared/mirror 去重與漏收補差異測試);verify-anybot:chat.md「/ 指令」(/context 寫「到 60% 會自動」)、「說了就做」(只說「我把它整理成一頁做法文件。」後同一輪接著執行 echo ft-done 並收尾,模型那層收到提醒)、autonomy.md「智慧模式一直開著」(/smart off 回不能關,重開後 smart_mode 仍 true);審查修正後三步重跑結果相同;ctl down 無殘留;乾淨脈絡獨立審查 1 次(P0×1、P1×1 已修) 未驗證: 手機頁面畫面那一層(這台沒有 Google Chrome,無頭手機頁面開不起來,改走同一個大腦的手機 API);螢幕電腦連大腦的實際路徑(要帳號伺服器與第二台電腦:等待頁、重開續傳、斷線重送只在單元測試);真 Intel Mac 的 CPU/風扇與 LowPower GPU 實測;真的小模型(muse-spark 等)是否照提醒動手;動到審批路徑(智慧模式常開)需實機測試+人類簽名,本輪不發佈 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 14:28:31 +00:00
b.messages = msgs.into();
b.threads = threads.into();
問題卡、搜尋: the bot asks with a card; every chat is searched; a refusal holds for the turn - 問題卡 (ask_person, src/ask.rs): up to 6 questions on a card above the input, one at a time — a choice (one click moves on), several choices, or a field that arrives filled for the person to correct; 「自己回答」 on every question, 上一題 and 略過. The turn waits; a message typed instead leaves the card unanswered. Travels as an approval of kind Question (questions as JSON) with a new answer Answered, so the window, a screen of another brain and the phone draw the same card. - 搜尋所有聊天 (src/find.rs): the sidebar's search also lists what the person and the bots said in every chat, past conversations included, and attachment names; newest first, 40 at most. A click opens the bot (bringing a past conversation back first), scrolls to the message and lights it for a moment. - 拒絕後停下: a step the person refused is refused for them when it comes back unchanged in the same turn — no second card, no second review — until they write again. - The bot's instructions: stop after a refusal instead of trying another way; before sending, posting, buying or deleting, check the person's own messages asked for exactly that, and ask with the card when they didn't. - 直接操作 no longer answers a hand-off (or a question) on the person's behalf. - The repeated-step check leaves questions to the person alone. - Screenshot views `ask` and `find`; FEATURES.md. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha3QxSfoydRPM9mjj6d
2026-11-12 02:17:32 +00:00
b
}
#[test]
fn every_chat_is_searched_newest_first() {
let file: crate::attach::Attachment = serde_json::from_value(serde_json::json!({"name": "Q3 報價單.xlsx", "path": "/x"})).unwrap();
let bots = vec![
bot(1, vec![Message { at: 10, ..Message::user("幫我查台北到東京的機票") }, Message { at: 20, ..Message::assistant("最便宜的是飛東京 Tokyo 成田,NT$ 8,200", "m") }, Message { at: 25, ..Message::tool_result("c", "web_fetch", "tokyo tokyo tokyo") }], vec![]),
bot(2, vec![Message { at: 30, attachments: vec![file], ..Message::user("看這個") }], vec![("舊的".into(), vec![Message { at: 5, ..Message::user("東京天氣") }, Message { at: 6, summary: true, ..Message::assistant("摘要:東京", "m") }])]),
];
let (hits, more) = search(&bots, " TOKYO ");
assert!(!more);
// Not the tool's result, and whatever the letters' case.
assert_eq!(hits.len(), 1);
assert_eq!((hits[0].bot, hits[0].thread, hits[0].index, hits[0].mine), (1, None, 1, false));
assert!(hits[0].snippet.contains("Tokyo 成田"));
let (hits, _) = search(&bots, "東京");
// The open chats and the past one, newest first; the summary isn't something anyone said.
assert_eq!(hits.iter().map(|h| (h.bot, h.thread, h.index)).collect::<Vec<_>>(), vec![(1, None, 1), (1, None, 0), (2, Some(0), 0)]);
let (hits, _) = search(&bots, "報價");
assert_eq!(hits.len(), 1);
assert!(hits[0].file && hits[0].snippet == "Q3 報價單.xlsx" && hits[0].bot == 2);
assert!(search(&bots, " ").0.is_empty());
assert!(search(&bots, "沒有這個字").0.is_empty());
}
#[test]
fn a_snippet_is_one_line_around_the_match() {
let text = format!("{}\n第二行說到 重點在這裡,後面還有很多很多字{}", "前".repeat(40), "後".repeat(100));
let bots = vec![bot(1, vec![Message::user(&text)], vec![])];
let (hits, _) = search(&bots, "重點");
let s = &hits[0].snippet;
assert!(s.starts_with('…') && s.ends_with('…'), "{s}");
assert!(s.contains("第二行說到 重點在這裡") && !s.contains('\n'), "{s}");
assert!(s.chars().count() <= SNIPPET + 2);
// More than can be shown: the newest LIMIT, and it says so.
let many: Vec<Message> = (0..LIMIT as i64 + 5).map(|i| Message { at: i + 1, ..Message::user("重複的話") }).collect();
let (hits, more) = search(&[bot(1, many, vec![])], "重複");
assert!(more);
assert_eq!(hits.len(), LIMIT);
assert_eq!(hits[0].at, LIMIT as i64 + 5);
}
}