diff --git a/docs/feature-map/threads.md b/docs/feature-map/threads.md index 0f86fbc..19a46bc 100644 --- a/docs/feature-map/threads.md +++ b/docs/feature-map/threads.md @@ -8,6 +8,7 @@ - `threads-name` 取名:對話欄每列滑過出現 ✎(目前的那列一直有),也可以雙擊目前的那列、或右鍵「重新命名」;按 Enter 或點別處就存,Esc 不存,空白回到用第一句話。名字跟著對話:收進過去的對話、再打開都帶著;「/fork」沒給名字時叫「分岔:這個名字」(分岔的再分岔不會疊成「分岔:分岔:」)。一行、最多 40 字。也可以在聊天裡請 Bot 取(「這段叫網站改版」「把報價單那段改叫 Q3」):它用 `list_conversations` 看有哪些、`rename_conversation` 改名。名字不會放進 Bot 讀的對話裡(它要看用 `list_conversations`)。 - `threads-phone` 手機:聊天標題列 🕘(⋯ ›「對話」同一個)開「對話」:「目前的對話」那列點了取名;下面過去的對話(最新 20 段,更多時標題寫共幾段),點一段選「回到這段對話」或「重新命名」(大腦的 AnyBot 還是舊版時沒有命名)。取了名的對話,標題下那行寫名字。Bot 工作中「回到這段對話」不換,說要等它做完(還在整理摘要、支線或交辦還沒回報時,大腦不換、在聊天裡說)。團隊成員看不到 🕘(換對話、取名只有擁有者和管理員)。 - `threads-list` 收進與找回:「開始新對話」(Bot 選單、手機 ✎、對話欄的 +)把目前的收進過去的對話,最多留 50 段,再多最舊的就沒了。換對話和開始新對話一樣,這段的目標(/goal)和計畫(/plan)停掉、「還原上一個答案」不帶過去,停之前在這段留一行說停了哪個、回來再打 /goal 或 /plan 接著做(以前會被帶到另一段)。搜尋到過去對話裡的訊息時,那筆寫那段的名字(電腦「Bot · 名字」,手機在 Bot 名字旁)。在另一台裝置換過、收過或改過名,清單位置變了,改名和換回去(對話清單、手機搜尋結果都一樣)照樣找到你點的那段(認它最後一則的時間和顯示的名字);那段已經被打開或改了名就不動;為目前的對話取名時,別台已經換成另一段也不動。 +- `threads-archive` 封存:目前的對話超過 2500 則、Bot 閒著(沒在做事、沒卡片等你、沒在通話)時,較早的收進封存檔(500 則一個,寫好不再改),留最近約 2000 則;切在你說的一句之前、不越過最新的摘要,Bot 讀到的不變。聊天最上面「更早的 N 則已封存」「載入更早的」(一次 500 則,只看:按表情、⋯ 不會改到它)。搜尋也搜封存(第一次在背景讀,讀好結果自己補上),點到就載入前後各 100 則捲過去,下面有「載入後面的」。手機的編號和「載入更早的對話」照整段算。開新對話、/rewind、/fork、匯出、備份、搬到大腦用整段;清除聊天記錄連封存一起清;沒取名的名字照舊是整段第一句。 ## 使用者怎麼到 @@ -30,10 +31,12 @@ - **為過去的對話改名、重開還在、清掉名字**(covers `threads-name`):🕘 ›「報價單」›「重新命名」改成「Q3 報價」,重開 AnyBot,再把目前的名字清成空白。指令:`$CTL phone click '#b-chats' && $CTL phone click '#sheet-in .opt' --text 報價單 && $CTL phone click '#sheet-in .opt' --text 重新命名 && $CTL phone type '#ask-in' 'Q3 報價' && $CTL phone click '#ask-ok' && $CTL wait-api '/api/state?since=0' '.bots[0].threads[0].title == "Q3 報價"' && $CTL restart && $CTL wait-api '/api/state?since=0' '.bots[0].chat_title == "網站改版" and .bots[0].threads[0].title == "Q3 報價"' && $CTL phone open --listed && $CTL phone click '.row[data-bot="1"]' && $CTL phone click '#b-chats' && $CTL phone click '#sheet-in .opt' --text 命名 && $CTL phone type '#ask-in' '' && $CTL phone click '#ask-ok' && $CTL wait-api '/api/state?since=0' '.bots[0].chat_named == false and .bots[0].chat_title == "首頁要改"' && $CTL phone shot unnamed`。看到:清單「Q3 報價」;重開後兩個名字都在;清掉後回到第一句話「首頁要改」,標題下只寫模型。 - **請 Bot 改名、換對話**(covers `threads-name`、`threads-list`):在聊天裡請它把「Q3 報價」改名、列出對話、換過去。指令:`$CTL phone send '[[call rename_conversation {"name":"第三季報價","conversation":"Q3"}]]' && $CTL wait-api '/api/state?since=0' '.bots[0].threads[0].title == "第三季報價"' 40 && $CTL phone send '[[call list_conversations {}]]' && $CTL wait-api '/api/state?since=0' '.bots[0].busy == false' 40 && $CTL phone send '換回去 [[call switch_conversation {"conversation":"第三季"}]]' && $CTL wait-api '/api/state?since=0' '.bots[0].busy == false and .bots[0].chat_title == "第三季報價"' 40 && $CTL model 'select(.tool_result != null) | .tool_result' | tail -4`。看到:「過去的對話「Q3 報價」改叫「第三季報價」了。」、清單「目前的對話:「…」…過去的對話(1 段…):- 「第三季報價」」;它回完那一輪才換,`chat_title` 是「第三季報價」,原本那段收進過去的對話。 - **桌面的對話欄**(covers `threads-column`、`threads-name`):指令:要開視窗——`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot chats-column ANYBOT_SHOT_PANEL=chats`。看到:右邊「對話」欄,目前的那列粗體、淺底、有 ✎,下面過去的對話和時間;聊天右上的「對話」按鈕亮著。點 ✎(不會打開那段)、雙擊過去那段只換一次、改名、Esc、Bot 工作中不換、記住開著、詳細資訊關掉回到對話欄靠自動測試。 +- **封存**(covers `threads-archive`):指令:走不到——要 2500 則以上、還有摘要的對話,假模型要填好幾千輪。看到:自動測試 `cargo test chatarchive::`、`a_long_chat_keeps_its_newest_and_comes_back_whole`、`an_archived_head_is_still_the_same_conversation_everywhere`。 - 自動測試:`cargo test a_conversation_keeps_the_name_it_was_given`、`cargo test a_past_conversation_is_found_by_its_time`、`cargo test chats_are_saved_apart`、`cargo test a_phone_names_and_switches_conversations`、`cargo test layout_audit::`(含 `the_chats_column_names_and_switches_conversations` 和對話欄的版面)、`cargo test a_screen_keeps_its_own_look_and_settings`、`cargo test a_bot_names_the_open_conversation`(含過去那段、`list_conversations`、支線不能)、`cargo test switching_conversations_ends_its_goal_and_plan_with_a_line`、`cargo test a_switch_asked_of_the_bot_waits_for_its_turn`、`cargo test clearing_or_stopping_calls_off_a_switch_the_bot_promised`、`cargo test nothing_on_its_way_lands_in_another_conversation`、`cargo test remote::tests::phone_login_and_api`(命名、回到的參數;成員不行)。 ## 陷阱 +- 封存只在 Bot 閒著時做:一直有事做的 Bot 要等它空下來。封存載入的訊息只能看。顯示大腦的另一台電腦上沒有「載入更早的」(封存檔在大腦上),手機照常能載。 - 名字只是給人看的:記憶、指示、檔案和例行任務是這個 Bot 共用的,不分對話;專案要分得乾淨(各自的記憶和檔案),開不同的 Bot。 - 目標和計畫只屬於一段對話:換過去再回來不會自己接著做,照那段留的一行再打一次。 - Bot 答應的換對話要等支線、同事的回報都回來,可能過幾分鐘才換;那之前按停止、清除聊天記錄,或在它閒著時又傳新訊息,就不換。 diff --git a/src/app.rs b/src/app.rs index bc9fec0..190fcc9 100644 --- a/src/app.rs +++ b/src/app.rs @@ -201,6 +201,18 @@ pub fn set_doc_folders(v: Vec) { *DOC_FOLDERS.write().unwrap() = v; } +/// The id an archived message is drawn under (archived_head): no real bot has it. +const OLDER_VIEW: u64 = 1 << 62; + +/// 載入更早的: a stretch of a bot's archived messages shown above its chat — messages +/// `start..start + msgs.len()` of the conversation, while it still has `archived` of them. +#[derive(Clone)] +struct OlderView { + archived: usize, + start: usize, + msgs: crate::shared::Shared>, +} + pub struct App { state: State, /// 智慧模式 (/smart): one switch for every live turn — a turn reads it at each step, so @@ -231,6 +243,11 @@ pub struct App { delivered: Vec<(u64, String)>, /// Save at the next frame (a typed message just entered a chat), not up to 2 s later. save_now: bool, + /// 載入更早的: archived messages of a bot's open conversation shown above its chat (read + /// only, not saved), the newest last; they end where the chat in memory starts. + older: HashMap, + /// 封存 that couldn't be written, and when (tried again later, not every frame). + archive_failed: HashMap, /// A save writing on its own thread, and the typed messages it carries (see `delivered`). saving: Option<(Receiver, Vec<(u64, String)>)>, /// 設定 › 一般 › 文件索引: the path being typed for a new folder. @@ -486,6 +503,13 @@ impl App { // ANYBOT_SHOT_REAL=1: a screenshot of the real data (and connections), not the demo. let demo = screenshot.is_some() && std::env::var("ANYBOT_SHOT_REAL").is_err(); let mut state = if demo { State::demo() } else { State::load() }; + // 封存: tidied here, at the app's own start (never by another command reading the + // settings while it runs: that once deleted a cut the app hadn't saved yet). + if !demo && screenshot.is_none() { + if let Some(data) = State::path().parent() { + crate::chatarchive::sweep(data, &state.bots, &crate::model::archived_on_disk()); + } + } if demo { // ANYBOT_SHOT_PINS=n: the grid at the top shows n bots (the main one and n-1 pinned). if let Some(n) = std::env::var("ANYBOT_SHOT_PINS").ok().and_then(|v| v.parse::().ok()) { @@ -580,6 +604,8 @@ impl App { delivered: vec![], save_now: false, saving: None, + older: HashMap::new(), + archive_failed: HashMap::new(), doc_new: String::new(), doc_new_bad: false, interrupted, @@ -3974,6 +4000,9 @@ impl App { members: vec![], threads: Default::default(), chat_title: String::new(), + archived: 0, + head_title: String::new(), + archive_mark: 0, chat_after: None, context_tokens: agent::DEFAULT_CONTEXT_TOKENS, model_limits: Default::default(), @@ -4280,6 +4309,7 @@ impl App { self.stop(id); if let Some(b) = self.state.bot_mut(id) { b.messages.clear(); + b.forget_archive(); b.chat_title.clear(); } self.mark(); @@ -4321,6 +4351,81 @@ impl App { egui::CentralPanel::default().frame(Frame::new().fill(p.pane)).show(root, |ui| self.chat_column(ui)); } + /// 封存: above the chat, how many older messages are archived and 「載入更早的」, then the + /// ones loaded (read only: drawn as another bot's, so nothing on them — reactions, menus, + /// unfolded steps — reaches the real messages). + fn archived_head(&mut self, ui: &mut egui::Ui, ctx: &egui::Context, bot: &Bot) { + if bot.archived == 0 { + self.older.remove(&bot.id); + return; + } + let p = self.pal; + let dir = crate::chatarchive::dir(bot.id); + let shown = self.older.get(&bot.id).filter(|v| v.archived == bot.archived).cloned().unwrap_or(OlderView { archived: bot.archived, start: bot.archived, msgs: Default::default() }); + let end = shown.start + shown.msgs.len(); + if shown.start > 0 { + ui.vertical_centered(|ui| { + ui.label(RichText::new(t("更早的 {n} 則已封存").replace("{n}", &shown.start.to_string())).size(FONT_XS).color(p.text3)); + // (A window showing a brain's bots: the files are on the brain.) + if self.mir.on { + return; + } + if ui.link(RichText::new(t("載入更早的")).size(FONT_XS)).clicked() { + let from = shown.start.saturating_sub(crate::chatarchive::SEGMENT); + let mut more = crate::chatarchive::read_in(&dir, from, shown.start); + more.extend(shown.msgs.iter().cloned()); + self.older.insert(bot.id, OlderView { archived: bot.archived, start: from, msgs: more.into() }); + } + }); + } + if shown.msgs.is_empty() { + return; + } + let view = Bot { id: bot.id | OLDER_VIEW, messages: shown.msgs.clone(), archived: 0, ..bot.clone() }; + for (k, m) in shown.msgs.iter().enumerate() { + self.msg_index = k; + let top = ui.cursor().top(); + self.chat_message(ui, ctx, &view, m, false); + // 搜尋 → an archived message: scrolled to and lit, as in the chat. + if let Some(g) = self.goto.filter(|g| g.is(bot.id, shown.start + k, m.at)) { + let rect = egui::Rect::from_min_max(egui::pos2(ui.min_rect().left() - 8.0, top - 4.0), egui::pos2(ui.min_rect().right() + 8.0, ui.cursor().top() - 4.0)); + let age = g.since.elapsed().as_secs_f32(); + if age < crate::find::GOTO_SCROLL_SECS { + ui.scroll_to_rect(rect, Some(Align::Center)); + } + let k = (1.0 - age / crate::find::GOTO_LIGHT_SECS).clamp(0.0, 1.0); + ui.painter().rect_filled(rect, R_M, self.pal.attention.gamma_multiply(0.28 * k)); + if k > 0.0 { + ui.ctx().request_repaint_after(anim_after(50)); + } else { + self.goto = None; + } + } + } + let after = bot.archived.saturating_sub(end); + ui.vertical_centered(|ui| { + if after > 0 { + ui.label(RichText::new(t("後面還有 {n} 則已封存").replace("{n}", &after.to_string())).size(FONT_XS).color(p.text3)); + if ui.link(RichText::new(t("載入後面的")).size(FONT_XS)).clicked() { + let to = (end + crate::chatarchive::SEGMENT).min(bot.archived); + let mut msgs = shown.msgs.to_vec(); + msgs.extend(crate::chatarchive::read_in(&dir, end, to)); + self.older.insert(bot.id, OlderView { archived: bot.archived, start: shown.start, msgs: msgs.into() }); + } + } else { + ui.label(RichText::new(t("以上是封存的訊息")).size(FONT_XS).color(p.text3)); + } + }); + } + + /// 搜尋 → a message in the archive: the stretch around it is shown above the chat. + pub(super) fn show_archived_at(&mut self, bot: u64, index: usize) { + let Some(b) = self.state.bot(bot) else { return }; + let (from, to) = (index.saturating_sub(100), (index + 100).min(b.archived)); + let msgs = crate::chatarchive::read_in(&crate::chatarchive::dir(bot), from, to); + self.older.insert(bot, OlderView { archived: b.archived, start: from, msgs: msgs.into() }); + } + /// The chat of the bot picked: its top, the messages, the input (in the middle, or beside /// the 工作流 canvas). fn chat_column(&mut self, ui: &mut egui::Ui) { @@ -4368,9 +4473,10 @@ impl App { // 之间 14px,紧组内部才用 6~8)。 ui.spacing_mut().item_spacing.y = if self.state.dense { 11.0 } else { 14.0 }; ui.add_space(18.0); - if bot.messages.is_empty() { + if bot.messages.is_empty() && bot.archived == 0 { self.empty_state(ui, &bot); } + self.archived_head(ui, ctx, &bot); let n = bot.messages.len(); for (i, m) in bot.messages.iter().enumerate() { let last = i + 1 == n; @@ -4378,7 +4484,7 @@ impl App { let top = ui.cursor().top(); self.chat_message(ui, ctx, &bot, m, last); // 搜尋 → 那則訊息: scroll to it and light it for a moment. - if let Some(g) = self.goto.filter(|g| g.is(bot.id, i, m.at)) { + if let Some(g) = self.goto.filter(|g| g.is(bot.id, bot.archived + i, m.at)) { let rect = egui::Rect::from_min_max(egui::pos2(ui.min_rect().left() - 8.0, top - 4.0), egui::pos2(ui.min_rect().right() + 8.0, ui.cursor().top() - 4.0)); let age = g.since.elapsed().as_secs_f32(); if age < crate::find::GOTO_SCROLL_SECS { @@ -7258,8 +7364,26 @@ impl App { kept.extend(self.att.pending.values().flatten().map(|a| a.path.clone())); let pages: String = self.state.pages.iter().map(|p| p.body.as_str()).collect::>().join("\n"); let sweep_files = !self.demo && !self.mir.on; + // (And the files of archived messages, read on that thread: megabytes of them.) + let archives: Vec<(u64, usize)> = self.state.bots.iter().filter(|b| b.archived > 0).map(|b| (b.id, b.archived)).collect(); std::thread::spawn(move || { - if sweep_files { + let mut kept = kept; + let mut whole = true; + for (id, n) in archives { + match crate::chatarchive::attachment_paths(id, n) { + Some(paths) => kept.extend(paths), + None => whole = false, + } + } + // (An archive kept aside because it couldn't all be read: its files' attachments + // aren't known — nothing is swept while one is there.) + if whole && State::path().parent().is_some_and(crate::chatarchive::any_kept) { + whole = false; + } + if !whole { + log::warn!("AnyBot:有對話封存讀不完整,今晚不清聊天的檔案"); + } + if sweep_files && whole { let n = crate::attach::sweep(&kept, &pages); if n > 0 { log::info!("AnyBot:清掉 {n} 個聊天已經不用的檔案"); @@ -7277,7 +7401,45 @@ impl App { }); } + /// 封存: long chats of bots that aren't doing anything (no turn, no card waiting, no call) + /// keep their newest ~2 000 messages; the head goes to their archive files first. What the + /// window remembers by a message's place in the chat (unfolded steps, fades, the open menu, + /// the 「載入更早的」 view, a search's 前往) is let go for that bot: the places moved. + fn archive_idle_chats(&mut self) { + if self.demo || self.mir.on { + return; + } + let call = self.call_state().map(|c| c.0); + // (A cut that couldn't be written is tried again in 10 minutes, not every frame.) + let failed = |id: &u64| self.archive_failed.get(id).is_some_and(|t| t.elapsed().as_secs() < 600); + let idle: Vec = self + .state + .bots + .iter() + .filter(|b| crate::chatarchive::cut_point(&b.messages).is_some() && !self.streams.contains_key(&b.id) && !self.approvals.contains_key(&b.id) && call != Some(b.id) && b.regen_undo.is_empty() && !failed(&b.id)) + .map(|b| b.id) + .collect(); + for id in idle { + if self.state.bot_mut(id).and_then(|b| b.archive_head()).is_none() { + self.archive_failed.insert(id, Instant::now()); + continue; + } + self.steps_open.retain(|(b, _)| *b != id); + self.appeared.retain(|(b, _), _| *b != id); + self.popped.retain(|(b, _, _), _| *b != id); + if self.menu_for.is_some_and(|(b, _)| b == id) { + self.menu_for = None; + } + self.older.remove(&id); + if self.goto.as_ref().is_some_and(|g| g.bot == id) { + self.goto = None; + } + self.dirty = true; + } + } + fn save_if_dirty(&mut self) { + self.archive_idle_chats(); // The save on its own thread: done, its typed messages are on disk in their chats and // the work log can let them go; still writing, the next one waits for it. if let Some((rx, _)) = &self.saving { @@ -8252,7 +8414,8 @@ fn card(ui: &mut egui::Ui, args: &str, p: Palette) { /// 匯出文字記錄: the chat as Markdown (tool steps folded in as quotes). fn transcript_markdown(b: &Bot) -> String { let mut s = format!("# {} 的對話\n\n匯出時間:{}\n\n", b.name, chrono::Local::now().format("%Y-%m-%d %H:%M")); - for m in &b.messages { + // (The whole conversation: its archived head first.) + for m in crate::chatarchive::all(b.id, b.archived).iter().chain(b.messages.iter()) { match m.role { Role::User => { s.push_str(&format!("**你**:{}\n", m.text)); diff --git a/src/app/branch.rs b/src/app/branch.rs index f545615..1c67b73 100644 --- a/src/app/branch.rs +++ b/src/app/branch.rs @@ -193,6 +193,10 @@ impl App { b.routines.clear(); b.branches.clear(); b.threads.clear(); + // (The main line's archive is the main line's: a 支線 has its own chat, nothing archived.) + b.archived = 0; + b.head_title.clear(); + b.archive_mark = 0; b.regen_undo.clear(); b.draft.clear(); b.goal = None; diff --git a/src/app/commands.rs b/src/app/commands.rs index bef682f..2ae17c5 100644 --- a/src/app/commands.rs +++ b/src/app/commands.rs @@ -189,7 +189,8 @@ impl App { if chat { let Some(b) = self.state.bot_mut(bot_id) else { return }; // The whole conversation first goes to 過去的對話: a rewind can be taken back. - let mut copy = b.messages.to_vec(); + // (Whole: its archived head too.) + let mut copy = crate::chatarchive::whole(b); copy.iter_mut().for_each(|m| m.images.clear()); let title = format!("退回前:{}", first_line(&words, 24)); b.threads.insert(0, (title.clone(), copy)); @@ -232,7 +233,8 @@ impl App { let what = if name.is_empty() { b.chat_name().trim_start_matches(FORK_PREFIX).to_string() } else { name.to_string() }; let title = format!("{FORK_PREFIX}{what}"); let Some(b) = self.state.bot_mut(bot_id) else { return }; - let mut copy = b.messages.to_vec(); + // (Whole: its archived head too.) + let mut copy = crate::chatarchive::whole(b); // (Like any conversation put aside: its words, not its screenshots in memory.) copy.iter_mut().for_each(|m| m.images.clear()); b.threads.insert(0, (title.clone(), copy)); diff --git a/src/app/library_ui.rs b/src/app/library_ui.rs index f5be264..5502518 100644 --- a/src/app/library_ui.rs +++ b/src/app/library_ui.rs @@ -65,13 +65,15 @@ impl App { let mut seen = std::collections::HashSet::new(); let mut files = vec![]; for b in &self.state.bots { - for m in b.messages.iter().chain(b.threads.iter().flat_map(|(_, m)| m.iter())) { - for a in &m.attachments { - if a.path.is_empty() || !seen.insert(a.path.clone()) { - continue; - } - files.push((m.at, serde_json::json!({"name": a.name, "path": a.path, "bot": b.id, "at": m.at, "bytes": a.bytes, "kind": library_kind(&a.name), "there": std::path::Path::new(&a.path).exists(), "image": a.image}))); + // (The archived head's files too, once its words are read: chatarchive::said.) + let said = crate::chatarchive::said(b.id, b.archived).unwrap_or_default(); + let archived = said.iter().flat_map(|s| s.files.iter().map(move |a| (s.at, a))); + let live = b.messages.iter().chain(b.threads.iter().flat_map(|(_, m)| m.iter())).flat_map(|m| m.attachments.iter().map(move |a| (m.at, a))); + for (at, a) in archived.chain(live) { + if a.path.is_empty() || !seen.insert(a.path.clone()) { + continue; } + files.push((at, serde_json::json!({"name": a.name, "path": a.path, "bot": b.id, "at": at, "bytes": a.bytes, "kind": library_kind(&a.name), "there": std::path::Path::new(&a.path).exists(), "image": a.image}))); } } files.sort_by_key(|f| std::cmp::Reverse(f.0)); @@ -82,14 +84,15 @@ impl App { let mut seen = std::collections::HashSet::new(); let mut files = vec![]; for b in &self.state.bots { - let all = b.messages.iter().chain(b.threads.iter().flat_map(|(_, m)| m.iter())); - for m in all { - for a in &m.attachments { - if a.path.is_empty() || !seen.insert(a.path.clone()) { - continue; - } - files.push(Item { name: a.name.clone(), path: a.path.clone(), bot: b.id, at: m.at, bytes: a.bytes, kind: library_kind(&a.name), there: std::path::Path::new(&a.path).exists(), image: a.image }); + // (The archived head's files too, once its words are read: chatarchive::said.) + let said = crate::chatarchive::said(b.id, b.archived).unwrap_or_default(); + let archived = said.iter().flat_map(|s| s.files.iter().map(move |a| (s.at, a))); + let live = b.messages.iter().chain(b.threads.iter().flat_map(|(_, m)| m.iter())).flat_map(|m| m.attachments.iter().map(move |a| (m.at, a))); + for (at, a) in archived.chain(live) { + if a.path.is_empty() || !seen.insert(a.path.clone()) { + continue; } + files.push(Item { name: a.name.clone(), path: a.path.clone(), bot: b.id, at, bytes: a.bytes, kind: library_kind(&a.name), there: std::path::Path::new(&a.path).exists(), image: a.image }); } } files.sort_by_key(|f| std::cmp::Reverse(f.at)); diff --git a/src/app/mirror_ui.rs b/src/app/mirror_ui.rs index e38bffa..5cef138 100644 --- a/src/app/mirror_ui.rs +++ b/src/app/mirror_ui.rs @@ -48,7 +48,8 @@ fn copy_own(to: &mut State, from: &State) { to.motion = from.motion.clone(); } /// Bot fields the brain alone changes (its chat, and what a turn leaves behind). -const BOT_RUNTIME: &[&str] = &["id", "messages", "threads", "chat_title", "unread", "last_turn", "tasks", "context_tokens", "goal", "plan", "regen_undo", "branches", "branch_of"]; +/// (封存's count and first line: the brain's archive, never set from a screen.) +const BOT_RUNTIME: &[&str] = &["id", "messages", "threads", "chat_title", "archived", "head_title", "archive_mark", "unread", "last_turn", "tasks", "context_tokens", "goal", "plan", "regen_undo", "branches", "branch_of"]; /// Stands in for a key or token the brain doesn't hand out. pub const REDACTED: &str = "••••(已設定,在大腦上)"; @@ -2543,10 +2544,11 @@ impl App { let moving: Vec<&Bot> = local .bots .iter() - .filter(|b| !self.state.bots.iter().any(|o| o.name == b.name && (b.messages.is_empty() || (o.messages.len() == b.messages.len() && last(o) == last(b))))) + .filter(|b| !self.state.bots.iter().any(|o| o.name == b.name && (b.messages.is_empty() || (o.conversation_len() == b.conversation_len() && last(o) == last(b))))) .collect(); for b in moving.iter().copied() { - let mut v = serde_json::to_value(b).unwrap_or(Value::Null); + // (Whole: the brain doesn't have this computer's archive files.) + let mut v = serde_json::to_value(crate::chatarchive::inlined(b)).unwrap_or(Value::Null); v["id"] = json!(0); ops.push(json!({"op": "bot_add", "bot": v})); } diff --git a/src/app/remote_ui.rs b/src/app/remote_ui.rs index e6826c1..edfe384 100644 --- a/src/app/remote_ui.rs +++ b/src/app/remote_ui.rs @@ -323,7 +323,7 @@ impl App { // 外觀: the phone wears the desktop's theme and colours. (self.state.theme as u8, &self.state.shell_accent, &self.state.shell_template, self.state.shell_tone.to_bits(), self.state.shell_contrast.to_bits()).hash(&mut h); for b in &self.state.bots { - (b.id, &b.name, &b.color, b.unread, b.messages.len(), &b.thinking, &b.step_model).hash(&mut h); + (b.id, &b.name, &b.color, b.unread, b.conversation_len(), &b.thinking, &b.step_model).hash(&mut h); // (What the phone's home, editor and reactions show.) (&b.description, &b.shape, b.pinned, &b.folder, b.members.len(), b.instructions.len(), b.memories.len(), b.tools_enabled).hash(&mut h); for m in b.messages.iter().rev().take(remote::PHONE_TAIL) { @@ -505,7 +505,7 @@ impl App { })), })); // (The newest PHONE_TAIL; 載入更早 asks for any stretch before it: phone_messages.) - let (msgs, deliveries) = self.phone_messages(b, &names, b.messages.len().saturating_sub(remote::PHONE_TAIL), b.messages.len()); + let (msgs, deliveries) = self.phone_messages(b, &names, b.conversation_len().saturating_sub(remote::PHONE_TAIL), b.conversation_len()); view.messages.insert(b.id, msgs); view.deliveries.insert(b.id, deliveries); view.approvals.extend(self.phone_cards(b)); @@ -741,6 +741,7 @@ impl App { self.stop(bot); if let Some(b) = self.state.bot_mut(bot) { b.messages.clear(); + b.forget_archive(); b.chat_title.clear(); } self.mark(); @@ -828,9 +829,13 @@ impl App { let mut st = self.state.clone(); // The backup is for the bots; this computer's own keys to the relay and phones stay here. st.remote = Default::default(); - let bytes = serde_json::to_vec(&st).unwrap_or_default(); let (note, busy) = (self.rm.note.clone(), self.rm.busy.clone()); std::thread::spawn(move || { + // (Whole conversations: the archive files aren't in the backup otherwise. Read here, + // off the window's thread.) + let mut st = st; + st.bots = st.bots.iter().map(crate::chatarchive::inlined).collect(); + let bytes = serde_json::to_vec(&st).unwrap_or_default(); *note.lock().unwrap() = match remote::backup_now(&s, &bytes) { Ok(n) => format!("已備份({},已加密)", crate::cloudbox::human(n as u64)), Err(e) => e, @@ -1407,6 +1412,71 @@ mod phone_tests { assert!(app.phone_act(&ctx, "older", &json!({"bot": id, "from": 50}), "admin").get("error").is_none()); } + /// 封存 as other devices see it: an idle bot's long chat is cut (not a working one's); the + /// phone still counts the whole conversation — 載入更早 walks into the archive with the same + /// numbers, a reaction finds its message by them (none on an archived one), the search finds + /// archived words, and the export has them. + #[test] + fn an_archived_head_is_still_the_same_conversation_everywhere() { + let _turn = crate::chatarchive::test_turn(); + let ctx = egui::Context::default(); + let mut app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-archive-app.png"))); + app.demo = false; + let id = 950_000 + std::process::id() as u64 % 1000; + app.state.bots[0].id = id; + let _ = std::fs::remove_dir_all(crate::chatarchive::dir(id)); + { + let b = app.state.bot_mut(id).unwrap(); + b.messages.clear(); + for i in 0..3_000 { + let mut m = if i % 6 == 0 { Message::user(&format!("問題 {i}")) } else { Message::assistant(&format!("回答 {i}"), "x") }; + if i == 600 { + m.text = "封存裡的獨角獸".into(); + } + m.at = 10_000 + i as i64; + m.summary = i == 2_950; + b.messages.push(m); + } + } + // Working: left as it is. + let (reply, _keep) = std::sync::mpsc::channel::(); + let _ = &reply; + app.streams.insert(id, 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::new(Mutex::new(vec![])), direct: Arc::new(AtomicBool::new(false)), turn_id: "t".into(), turn: 0 }); + app.archive_idle_chats(); + assert_eq!(app.state.bot(id).unwrap().archived, 0, "not under a running turn"); + app.streams.clear(); + app.archive_idle_chats(); + let (archived, live) = app.state.bot(id).map(|b| (b.archived, b.messages.len())).unwrap(); + assert!(archived > 900 && archived + live == 3_000, "{archived} + {live}"); + // The phone's newest stretch and 載入更早, across the archive's edge: the same numbers. + let v = app.phone_act(&ctx, "older", &json!({"bot": id, "from": archived + 10, "count": 60}), "owner"); + let msgs = v["messages"].as_array().unwrap(); + let idx: Vec = msgs.iter().map(|m| m["index"].as_u64().unwrap()).collect(); + assert_eq!((idx.first().copied(), idx.last().copied(), msgs.len()), (Some(archived as u64 + 10 - 60), Some(archived as u64 + 9), 60), "{v}"); + assert!(msgs.iter().all(|m| m["text"].as_str().unwrap().ends_with(&m["index"].as_u64().unwrap().to_string())), "each says its own place"); + // A reaction: by the whole conversation's number; an archived message isn't changed. + assert!(app.phone_act(&ctx, "react", &json!({"bot": id, "index": 5, "emoji": "👍"}), "owner").get("error").is_some()); + assert!(app.phone_act(&ctx, "react", &json!({"bot": id, "index": archived + 1, "emoji": "👍"}), "owner").get("error").is_none()); + assert!(!app.state.bot(id).unwrap().messages[1].reactions.is_empty()); + // The search finds archived words once read (on a thread of their own). + let t0 = Instant::now(); + let hit = loop { + let (hits, _) = crate::find::search(&app.state.bots, "獨角獸"); + if let Some(h) = hits.into_iter().next() { + break h; + } + assert!(t0.elapsed().as_secs() < 10, "the archive's words never came"); + std::thread::sleep(std::time::Duration::from_millis(20)); + }; + assert_eq!((hit.bot, hit.thread, hit.index, hit.at), (id, None, 600, 10_600)); + app.show_archived_at(id, 600); + assert!(app.older.get(&id).is_some_and(|v| v.start <= 600 && v.start + v.msgs.len() > 600)); + // The export: the whole conversation. + let md = super::super::transcript_markdown(app.state.bot(id).unwrap()); + assert!(md.contains("封存裡的獨角獸") && md.contains("回答 2999")); + let _ = std::fs::remove_dir_all(crate::chatarchive::dir(id)); + } + #[test] fn only_chat_models_are_offered() { assert!(super::chats("grok-4.7") && super::chats("claude-opus-5-5") && super::chats("gpt-5-mini")); @@ -1464,9 +1534,30 @@ impl App { /// it, its thinking and what each step brought back, in short — and the ✓ marks of the files /// among them. The published view is the newest PHONE_TAIL; 載入更早 (phone_act "older") asks /// for the stretch before what the phone holds, from the whole chat. + /// `start..end` count the whole conversation, its archived head first (`index` is that + /// place): a stretch in the archive is read from its files. fn phone_messages(&self, b: &Bot, names: &HashMap, start: usize, end: usize) -> (Vec, Vec) { - let end = end.min(b.messages.len()); + let end = end.min(b.conversation_len()); let start = start.min(end); + if start < b.archived { + // (The two parts numbered apart: the chat's own from b.archived whatever the files + // gave back — a short read must not move a reaction onto another message.) + let part = crate::chatarchive::read_in(&crate::chatarchive::dir(b.id), start, end.min(b.archived)); + let view = Bot { messages: part.into(), archived: start, ..b.clone() }; + let n = view.messages.len(); + let (mut msgs, mut deliveries) = self.phone_local(&view, names, 0, n); + if end > b.archived { + let (m2, d2) = self.phone_local(b, names, 0, end - b.archived); + msgs.extend(m2); + deliveries.extend(d2); + } + return (msgs, deliveries); + } + self.phone_local(b, names, start - b.archived, end - b.archived) + } + + /// phone_messages over `b.messages[start..end]`, each `index` counted from b.archived. + fn phone_local(&self, b: &Bot, names: &HashMap, start: usize, end: usize) -> (Vec, Vec) { // 交付確認: the ✓ marks go beside the chat, not inside the messages — a phone opening // an old chat reports every file it shows, and inside the messages that re-signed the // whole chat on every report (see remote::chat_for). @@ -1492,7 +1583,7 @@ impl App { deliveries.push(json!({"id": id, "delivery": d, "seen": seen})); } } - v["index"] = json!(start + k); + v["index"] = json!(b.archived + start + k); // 支線: its record, for the card (and the report's label). if m.branch != 0 { if let Some(r) = b.branches.iter().find(|r| r.id == m.branch) { @@ -1678,7 +1769,8 @@ impl App { // through those alone, and the button then did nothing at all). "older" => match self.state.bot(bot) { Some(x) => { - let from = b["from"].as_u64().map(|f| f as usize).unwrap_or(x.messages.len()).min(x.messages.len()); + let total = x.conversation_len(); + let from = b["from"].as_u64().map(|f| f as usize).unwrap_or(total).min(total); let count = b["count"].as_u64().unwrap_or(60).clamp(1, 120) as usize; let names: HashMap = self.state.bots.iter().map(|y| (y.id, y.name.clone())).collect(); // (Steps take room: walk back until `count` show, or the chat begins.) @@ -1923,7 +2015,9 @@ impl App { done("已重新啟動") } "react" => { - let idx = b["index"].as_u64().unwrap_or(u64::MAX) as usize; + // (The phone counts the whole conversation: an archived message keeps its words.) + let at = b["index"].as_u64().unwrap_or(u64::MAX) as usize; + let idx = self.state.bot(bot).and_then(|x| at.checked_sub(x.archived)).unwrap_or(usize::MAX); let emoji = s("emoji"); if emoji.is_empty() || emoji.chars().count() > 8 || self.state.bot(bot).map(|x| idx >= x.messages.len()).unwrap_or(true) { return fail("找不到這則訊息"); diff --git a/src/app/sidebar_ui.rs b/src/app/sidebar_ui.rs index 20940d9..6480c3d 100644 --- a/src/app/sidebar_ui.rs +++ b/src/app/sidebar_ui.rs @@ -607,6 +607,10 @@ impl App { self.open_thread(h.bot, i); } self.select_bot(&ctx, h.bot); + // (One in the open conversation's archive: the stretch around it is shown first.) + if h.thread.is_none() && self.state.bot(h.bot).is_some_and(|b| h.index < b.archived) { + self.show_archived_at(h.bot, h.index); + } self.goto = Some(crate::find::Goto { bot: h.bot, index: h.index, at: h.at, since: Instant::now() }); } } diff --git a/src/app/tasks_ui.rs b/src/app/tasks_ui.rs index c64a961..f047cef 100644 --- a/src/app/tasks_ui.rs +++ b/src/app/tasks_ui.rs @@ -189,7 +189,8 @@ impl App { } self.show_settings = false; self.select_bot(ctx, bot); - if let Some(index) = self.state.bot(bot).and_then(|b| b.messages.iter().position(|m| m.at == at && m.role == Role::User)) { + // (Its place counts the archived head: Goto goes by the whole conversation.) + if let Some(index) = self.state.bot(bot).and_then(|b| b.messages.iter().position(|m| m.at == at && m.role == Role::User).map(|i| b.archived + i)) { self.goto = Some(crate::find::Goto { bot, index, at, since: Instant::now() }); } } diff --git a/src/appctl.rs b/src/appctl.rs index ff5e6e6..18fdd00 100644 --- a/src/appctl.rs +++ b/src/appctl.rs @@ -883,7 +883,7 @@ pub fn apply(state: &mut State, bot_id: u64, name: &str, args: &str) -> Outcome "list_conversations" => { let Some(b) = state.bot(bot_id) else { return err("找不到這個 Bot".into()) }; let now_ms = crate::model::now_ms(); - let mut lines = vec![format!("目前的對話:「{}」({} 則{})", b.chat_name(), b.messages.len(), if b.chat_title.is_empty() { ";沒取名,顯示第一句話" } else { "" })]; + let mut lines = vec![format!("目前的對話:「{}」({} 則{})", b.chat_name(), b.conversation_len(), if b.chat_title.is_empty() { ";沒取名,顯示第一句話" } else { "" })]; if b.threads.is_empty() { lines.push("沒有過去的對話。".into()); } else { @@ -1053,6 +1053,9 @@ pub fn apply(state: &mut State, bot_id: u64, name: &str, args: &str) -> Outcome members: vec![], threads: Default::default(), chat_title: String::new(), + archived: 0, + head_title: String::new(), + archive_mark: 0, chat_after: None, context_tokens: model::default_context_tokens(), model_limits: Default::default(), diff --git a/src/chatarchive.rs b/src/chatarchive.rs new file mode 100644 index 0000000..b6651cb --- /dev/null +++ b/src/chatarchive.rs @@ -0,0 +1,462 @@ +//! 封存: the open conversation's oldest messages, kept on disk and out of memory. +//! +//! A bot that works all day never stopped growing its chat: jenny-Host's reached 36 000 messages +//! and 95 MB, held in memory, written whole on every save and laid out whole every frame — the +//! window stood at 90 % of a core. Now, once a chat passes ARCHIVE_AT messages and its bot is +//! idle, its head (up to the newest summary, at a message of the person's) goes to files of +//! SEGMENT messages each in `chats/archive/bot-/`, named `-.json`, each +//! written once and never changed. `Bot::archived` says how many there are: a message's place +//! in the whole conversation is `archived + its place in messages`, which is what the phone and +//! other devices go by — the same numbers as before. +//! +//! The model never notices: it reads from the newest summary on, and the cut never passes it. + +use crate::model::Message; +use std::path::{Path, PathBuf}; + +/// A chat longer than this is cut, when its bot is idle. +pub const ARCHIVE_AT: usize = 2_500; +/// About this many newest messages stay (the cut lands at a message of the person's before them). +pub const LIVE_KEEP: usize = 2_000; +/// Messages per archive file (what one 「載入更早的」 brings). +pub const SEGMENT: usize = 500; +/// A cut moving fewer than this waits (not a file for a handful). +const MIN_CUT: usize = 200; + +/// The folder of a bot's archive, beside its chat file. (Its own folder: an older AnyBot deletes +/// the `chats/bot-*.json` it doesn't know.) +pub fn dir_in(data: &Path, bot: u64) -> PathBuf { + data.join("chats").join("archive").join(format!("bot-{bot}")) +} + +fn data_dir() -> PathBuf { + crate::model::State::path().parent().map(PathBuf::from).unwrap_or_default() +} + +pub fn dir(bot: u64) -> PathBuf { + dir_in(&data_dir(), bot) +} + +/// One archive file: messages `start..start + count` of the conversation. +#[derive(Clone, Debug, PartialEq)] +pub struct Segment { + pub start: usize, + pub count: usize, + pub path: PathBuf, +} + +/// The files in `dir`, in order. +pub fn segments_in(dir: &Path) -> Vec { + let mut out: Vec = std::fs::read_dir(dir) + .map(|it| { + it.flatten() + .filter_map(|e| { + let name = e.file_name().to_str()?.to_string(); + let (start, count) = name.strip_suffix(".json")?.split_once('-')?; + Some(Segment { start: start.parse().ok()?, count: count.parse().ok()?, path: e.path() }) + }) + .collect() + }) + .unwrap_or_default(); + out.sort_by_key(|s| s.start); + out +} + +/// Write `msgs` as the conversation's messages from `start` on, in files of SEGMENT, each synced +/// to disk before this returns. A file left from a cut that never reached the chat file (the app +/// stopped in between) at or after `start` is replaced. +pub fn write_in(dir: &Path, start: usize, msgs: &[Message]) -> std::io::Result<()> { + crate::httpd::ensure_private_dir(dir); + for s in segments_in(dir).into_iter().filter(|s| s.start + s.count > start) { + let _ = std::fs::remove_file(&s.path); + } + for (k, part) in msgs.chunks(SEGMENT).enumerate() { + let first = start + k * SEGMENT; + let bytes = serde_json::to_vec(part).map_err(std::io::Error::other)?; + crate::httpd::write_private(&dir.join(format!("{first:09}-{}.json", part.len())), &bytes)?; + } + Ok(()) +} + +fn read_segment(s: &Segment) -> Vec { + std::fs::read(&s.path).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default() +} + +/// Messages `from..to` of the conversation, as far as the archive in `dir` has them. +pub fn read_in(dir: &Path, from: usize, to: usize) -> Vec { + let mut out = vec![]; + for s in segments_in(dir).into_iter().filter(|s| s.start < to && s.start + s.count > from) { + let msgs = read_segment(&s); + let a = from.saturating_sub(s.start).min(msgs.len()); + let b = (to - s.start).min(msgs.len()); + out.extend(msgs.into_iter().take(b).skip(a)); + } + out +} + +/// Every archived message of a bot's open conversation (the first `archived`). +pub fn all(bot: u64, archived: usize) -> Vec { + if archived == 0 { + return vec![]; + } + read_in(&dir(bot), 0, archived) +} + +/// The whole open conversation: the archived head and what is in memory. +pub fn whole(b: &crate::model::Bot) -> Vec { + let mut out = all(b.id, b.archived); + out.extend(b.messages.iter().cloned()); + out +} + +/// A copy of the bot with its whole conversation in `messages` and nothing archived: for what +/// takes a bot elsewhere (a backup, a move to the brain), where its archive files aren't. +pub fn inlined(b: &crate::model::Bot) -> crate::model::Bot { + if b.archived == 0 { + return b.clone(); + } + crate::model::Bot { messages: whole(b).into(), archived: 0, head_title: String::new(), archive_mark: 0, ..b.clone() } +} + +/// The archive's files go with the conversation they belonged to (it was put aside, cleared, +/// rewound into 過去的對話 whole): the folder is renamed aside now. It is deleted at a start of +/// the app only once the chat file says the conversation has nothing archived (the save that +/// carried the conversation elsewhere is then on disk); a chat file that still counts on it +/// gets it back (see sweep). +pub fn retire(bot: u64) { + forget_said(bot); + let d = dir(bot); + if d.exists() { + let to = d.with_file_name(format!("bot-{bot}.retired-{}", crate::model::now_ms())); + let _ = std::fs::rename(&d, to); + } +} + +/// An archive that couldn't all be read back is kept aside for good (never deleted by AnyBot): +/// `bot-.kept-`. Returns its folder. +pub fn keep_aside(bot: u64) -> PathBuf { + forget_said(bot); + let d = dir(bot); + let to = d.with_file_name(format!("bot-{bot}.kept-{}", crate::model::now_ms())); + let _ = std::fs::rename(&d, &to); + to +} + +/// Whether `dir`'s files hold exactly messages 0..n, with no gap. +fn covers(dir: &Path, n: usize) -> bool { + let mut next = 0; + for s in segments_in(dir) { + if s.start != next || next >= n { + return next == n && s.start >= n; + } + next = s.start + s.count; + } + next == n +} + +/// The time of message n - 1 in `dir`'s files (what a chat file keeps as its archive_mark). +fn mark_of(dir: &Path, n: usize) -> Option { + (n > 0).then(|| read_in(dir, n - 1, n).first().map(|m| m.at)).flatten() +} + +/// Whether `dir` is the archive the chat file means: messages 0..n, the last one at `mark`. +fn is_the_one(dir: &Path, n: usize, mark: i64) -> bool { + covers(dir, n) && mark_of(dir, n) == Some(mark) +} + +/// An archive folder that runs whole from message 0 (no gap): how many, the last one's time +/// and the conversation's first line — for a chat file written without the archive's count. +pub fn whole_from_start(dir: &Path) -> Option<(usize, i64, String)> { + let segs = segments_in(dir); + let mut next = 0; + for s in &segs { + if s.start != next { + break; + } + next = s.start + s.count; + } + let mark = mark_of(dir, next)?; + Some((next, mark, crate::model::auto_title(&read_in(dir, 0, next.min(SEGMENT))))) +} + +/// Whether a chat whose first message is at `first` goes on from an archive whose last one is +/// at `mark` (a cut lands just before a message of the person's: soon after, not days later — +/// a chat an older AnyBot started over since is another conversation). +pub fn goes_on_from(mark: i64, first: Option) -> bool { + first.is_some_and(|at| at > mark && at - mark <= 86_400_000) +} + +/// At the app's own start (never from another process reading the settings while it runs). +/// Nothing is deleted on a count alone, and nothing of a bot the settings don't name (settings +/// that couldn't be read name none: their archives once went with them — a deleted bot's go +/// when it is deleted, see State::write_at): +/// - a bot whose chat file says what it archived (`on_disk`: how many, the last one's time): +/// when its own folder is missing, the retired one that is exactly that comes back (newest +/// first, one at most); once its archive is the one the file means (or it has none), the +/// other retired folders go; files past the count go only when their messages are in the +/// chat again (a cut the chat file never saw); +/// - any other bot (a chat file unread, or written without the archive): nothing is touched. +pub fn sweep(data: &Path, bots: &[crate::model::Bot], on_disk: &std::collections::HashMap) { + let root = data.join("chats").join("archive"); + let entries: Vec<(String, PathBuf)> = std::fs::read_dir(&root).into_iter().flatten().flatten().map(|e| (e.file_name().to_string_lossy().to_string(), e.path())).collect(); + let id_of = |name: &str| -> Option<(u64, Option)> { + let rest = name.strip_prefix("bot-")?; + match rest.split_once(".retired-") { + Some((id, ms)) => Some((id.parse().ok()?, Some(ms.parse().ok()?))), + None => rest.parse().ok().map(|id| (id, None)), + } + }; + for b in bots { + let Some(&(n, mark)) = on_disk.get(&b.id) else { continue }; + let live = dir_in(data, b.id); + let mut retired: Vec<(u64, PathBuf)> = entries.iter().filter_map(|(name, path)| match id_of(name) { + Some((id, Some(ms))) if id == b.id => Some((ms, path.clone())), + _ => None, + }).collect(); + retired.sort_by_key(|r| std::cmp::Reverse(r.0)); + if n > 0 && !live.exists() { + if let Some(i) = retired.iter().position(|(_, r)| is_the_one(r, n, mark)) { + let (_, r) = retired.remove(i); + log::warn!("AnyBot:Bot {} 的對話封存從 {} 找回(上次換對話後沒存好就停了)", b.id, r.display()); + let _ = std::fs::rename(&r, &live); + } + } + let settled = if n == 0 { true } else { is_the_one(&live, n, mark) }; + if !settled { + log::warn!("AnyBot:Bot {} 的對話封存跟聊天檔對不上({n} 則),先不整理", b.id); + continue; + } + for (_, r) in retired { + let _ = std::fs::remove_dir_all(r); + } + for s in segments_in(&live).into_iter().filter(|s| s.start + s.count > n) { + let first = read_in(&live, s.start.max(n), s.start.max(n) + 1).first().map(|m| m.at); + if first.is_some_and(|at| at != 0 && b.messages.iter().any(|m| m.at == at)) { + let _ = std::fs::remove_file(&s.path); + } + } + } +} + +/// Before a cut writes messages `from..` to `dir`: files already there from `from` on whose +/// messages are not in the chat (`msgs`) are no leftover of an unsaved cut but the only copy of +/// something (an older AnyBot started the chat over and left them): they go to a folder kept +/// aside for good, not under the new files. +pub fn keep_strays(dir: &Path, from: usize, msgs: &[Message]) { + let strays: Vec = segments_in(dir) + .into_iter() + .filter(|s| s.start + s.count > from) + .filter(|s| { + let first = read_in(dir, s.start.max(from), s.start.max(from) + 1).first().map(|m| m.at); + !first.is_some_and(|at| at != 0 && msgs.iter().any(|m| m.at == at)) + }) + .collect(); + if strays.is_empty() { + return; + } + let kept = dir.with_file_name(format!("{}.kept-{}", dir.file_name().unwrap_or_default().to_string_lossy(), crate::model::now_ms())); + crate::httpd::ensure_private_dir(&kept); + for s in &strays { + if let Some(name) = s.path.file_name() { + let _ = std::fs::rename(&s.path, kept.join(name)); + } + } + log::warn!("AnyBot:封存資料夾裡有 {} 個檔不屬於現在的對話,移到 {}(不刪)", strays.len(), kept.display()); +} + +/// A deleted bot's archive: its folder and any retired ones. +pub fn remove_all(data: &Path, bot: u64) { + let _ = std::fs::remove_dir_all(dir_in(data, bot)); + let prefix = format!("bot-{bot}.retired-"); + for e in std::fs::read_dir(data.join("chats").join("archive")).into_iter().flatten().flatten() { + if e.file_name().to_string_lossy().starts_with(&prefix) { + let _ = std::fs::remove_dir_all(e.path()); + } + } +} + +/// Whether any archive is kept aside (it couldn't all be read): its files' attachments can't +/// be known, so none may be swept as unused. +pub fn any_kept(data: &Path) -> bool { + std::fs::read_dir(data.join("chats").join("archive")).into_iter().flatten().flatten().any(|e| e.file_name().to_string_lossy().contains(".kept-")) +} + +/// Where the head of `msgs` can be cut: at a message of the person's, no later than the newest +/// summary (the model reads from there) and leaving about LIVE_KEEP. None: not long enough, or +/// no summary yet (the model still reads it all). +pub fn cut_point(msgs: &[Message]) -> Option { + if msgs.len() < ARCHIVE_AT { + return None; + } + let view = crate::model::model_view_start(msgs); + let limit = (msgs.len() - LIVE_KEEP).min(view); + let cut = (1..=limit).rev().find(|&i| msgs[i].role == crate::model::Role::User)?; + (cut >= MIN_CUT).then_some(cut) +} + +/// Every file path an archived message of a bot holds (its attachments), for the nightly sweep +/// of files no message uses any more. None when the archive can't all be read: then nothing may +/// be swept (its files would look unused). +pub fn attachment_paths(bot: u64, archived: usize) -> Option> { + let msgs = all(bot, archived); + (msgs.len() == archived).then(|| msgs.iter().flat_map(|m| m.attachments.iter().map(|a| a.path.clone())).collect()) +} + +/// One archived message as search sees it: what the person or the bot said (not tool results, +/// not summaries) and the names of its files, with its place in the conversation. +#[derive(Clone, Debug)] +pub struct Said { + pub index: usize, + pub at: i64, + pub mine: bool, + /// AnyBot's own line, not the person's or the bot's words (the heat map leaves it out). + pub note: bool, + pub text: String, + pub files: Vec, +} + +type SaidCache = std::collections::HashMap>)>; + +fn said_cache() -> &'static std::sync::Mutex { + static M: std::sync::OnceLock> = std::sync::OnceLock::new(); + M.get_or_init(Default::default) +} + +/// Each bot's archive generation: up when its archive is retired, so a read that started before +/// doesn't put the old conversation's words back. +fn said_epoch() -> &'static std::sync::Mutex> { + static M: std::sync::OnceLock>> = std::sync::OnceLock::new(); + M.get_or_init(Default::default) +} + +fn forget_said(bot: u64) { + said_cache().lock().unwrap_or_else(|e| e.into_inner()).remove(&bot); + *said_epoch().lock().unwrap_or_else(|e| e.into_inner()).entry(bot).or_default() += 1; +} + +fn said_reading() -> &'static std::sync::Mutex> { + static M: std::sync::OnceLock>> = std::sync::OnceLock::new(); + M.get_or_init(Default::default) +} + +/// Goes up each time an archive's words are ready to search (a search waiting for them runs again). +static SAID_READY: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +pub fn said_generation() -> u64 { + SAID_READY.load(std::sync::atomic::Ordering::SeqCst) +} + +/// A bot's archived words, ready to search — or None while a thread of their own reads them +/// (the first search after a start or a cut; megabytes of files, never on the window's thread). +/// A cut that added to the archive reads only what it added. +pub fn said(bot: u64, archived: usize) -> Option>> { + if archived == 0 { + return Some(Default::default()); + } + let have = said_cache().lock().unwrap_or_else(|e| e.into_inner()).get(&bot).cloned(); + if let Some((n, list)) = &have { + if *n == archived { + return Some(list.clone()); + } + } + if !said_reading().lock().unwrap_or_else(|e| e.into_inner()).insert(bot) { + return None; + } + let d = dir(bot); + let epoch = said_epoch().lock().unwrap_or_else(|e| e.into_inner()).get(&bot).copied().unwrap_or(0); + std::thread::spawn(move || { + let (from, mut list) = match have { + Some((n, l)) if n < archived => (n, (*l).clone()), + _ => (0, vec![]), + }; + for (k, m) in read_in(&d, from, archived).into_iter().enumerate() { + if matches!(m.role, crate::model::Role::User | crate::model::Role::Assistant) && !m.summary { + if !m.text.trim().is_empty() || !m.attachments.is_empty() { + list.push(Said { index: from + k, at: m.at, mine: m.role == crate::model::Role::User, note: m.note, text: m.text, files: m.attachments }); + } + } + } + if said_epoch().lock().unwrap_or_else(|e| e.into_inner()).get(&bot).copied().unwrap_or(0) == epoch { + said_cache().lock().unwrap_or_else(|e| e.into_inner()).insert(bot, (archived, std::sync::Arc::new(list))); + } + said_reading().lock().unwrap_or_else(|e| e.into_inner()).remove(&bot); + SAID_READY.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + }); + None +} + +/// Tests that write archives under the shared test folder take turns (a sweep in one would +/// count another's bot as gone). +#[cfg(test)] +pub fn test_turn() -> std::sync::MutexGuard<'static, ()> { + static M: std::sync::Mutex<()> = std::sync::Mutex::new(()); + M.lock().unwrap_or_else(|e| e.into_inner()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::{Message, Role}; + + fn chat(n: usize, summary_at: usize) -> Vec { + (0..n) + .map(|i| { + let mut m = if i % 10 == 0 { Message::user(&format!("第 {i} 句")) } else { Message::assistant(&format!("回 {i}"), "x") }; + m.at = i as i64 + 1; + m.summary = i == summary_at; + if m.summary { + m.role = Role::Assistant; + } + m + }) + .collect() + } + + #[test] + fn the_cut_lands_at_the_persons_message_and_never_past_the_summary() { + assert_eq!(cut_point(&chat(2_400, 2_300)), None, "short enough"); + assert_eq!(cut_point(&chat(3_000, 0)), None, "no summary: the model reads it all"); + // Summary late: about LIVE_KEEP stay, the cut at a message of the person's. + let c = chat(3_000, 2_900); + let cut = cut_point(&c).unwrap(); + assert_eq!(c[cut].role, Role::User); + assert!(cut <= 1_000 && cut > 980, "{cut}"); + // Summary early: the cut stops there. + let c = chat(3_000, 455); + let cut = cut_point(&c).unwrap(); + assert!(cut <= 455 && c[cut].role == Role::User, "{cut}"); + assert_eq!(cut_point(&chat(3_000, 150)), None, "too little to move"); + } + + #[test] + fn files_hold_their_part_and_read_back_by_place() { + let d = std::env::temp_dir().join(format!("anybot-archive-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + let c = chat(1_200, 0); + write_in(&d, 0, &c[..1_100]).unwrap(); + let segs = segments_in(&d); + assert_eq!(segs.iter().map(|s| (s.start, s.count)).collect::>(), vec![(0, 500), (500, 500), (1_000, 100)]); + let got = read_in(&d, 480, 520); + assert_eq!(got.iter().map(|m| m.at).collect::>(), (481..=520).collect::>()); + assert_eq!(read_in(&d, 0, 1_100).len(), 1_100); + // A cut the chat file never saw, then the same place again with another length: replaced. + write_in(&d, 1_000, &c[1_000..1_150]).unwrap(); + assert_eq!(segments_in(&d).last().map(|s| (s.start, s.count)), Some((1_000, 150))); + // At start, past what the bot says it has: gone. + let data = std::env::temp_dir().join(format!("anybot-archive-sweep-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&data); + let mine = dir_in(&data, 7); + write_in(&mine, 0, &c[..1_100]).unwrap(); + write_in(&dir_in(&data, 8), 0, &c[..10]).unwrap(); + let mut seven = crate::model::State::samples().bots.remove(0); + seven.id = 7; + seven.messages = c[1_000..].to_vec().into(); + sweep(&data, &[seven], &[(7, (1_000, c[999].at))].into_iter().collect()); + assert_eq!(segments_in(&mine).len(), 2, "the part past 1 000 is in the chat again: gone"); + assert!(dir_in(&data, 8).exists(), "a bot the settings don't name is left alone (settings that couldn't be read name none)"); + remove_all(&data, 8); + assert!(!dir_in(&data, 8).exists(), "deleting the bot takes it"); + let _ = std::fs::remove_dir_all(&d); + let _ = std::fs::remove_dir_all(&data); + } +} diff --git a/src/find.rs b/src/find.rs index 876fd96..aa08347 100644 --- a/src/find.rs +++ b/src/find.rs @@ -18,6 +18,7 @@ pub struct Hit { /// None: the open conversation; Some(i): 過去的對話 number i. pub thread: Option, /// Where in that conversation, and when it was said (0 for old messages without a time). + /// The open conversation counts its archived head too (its first message is 0). pub index: usize, pub at: i64, pub mine: bool, @@ -43,8 +44,9 @@ fn snippet(text: &str, lower_at: usize, lower: &str) -> String { s } -fn in_messages(bot: u64, thread: Option, msgs: &[Message], q: &str, out: &mut Vec) { - for (index, m) in msgs.iter().enumerate() { +fn in_messages(bot: u64, thread: Option, msgs: &[Message], first: usize, q: &str, out: &mut Vec) { + for (k, m) in msgs.iter().enumerate() { + let index = first + k; if !matches!(m.role, Role::User | Role::Assistant) || m.summary { continue; } @@ -68,9 +70,20 @@ pub fn search(bots: &[Bot], query: &str) -> (Vec, bool) { } let mut out = vec![]; for b in bots { - in_messages(b.id, None, &b.messages, &q, &mut out); + // 封存: its words as read once on a thread of their own; until then, not yet. + if let Some(said) = crate::chatarchive::said(b.id, b.archived) { + for s in said.iter() { + let lower = s.text.to_lowercase(); + if let Some(at) = lower.find(&q) { + out.push(Hit { bot: b.id, thread: None, index: s.index, at: s.at, mine: s.mine, file: false, snippet: snippet(&s.text, at, &lower) }); + } else if let Some(f) = s.files.iter().find(|f| f.name.to_lowercase().contains(&q)) { + out.push(Hit { bot: b.id, thread: None, index: s.index, at: s.at, mine: s.mine, file: true, snippet: f.name.clone() }); + } + } + } + in_messages(b.id, None, &b.messages, b.archived, &q, &mut out); for (i, (_, msgs)) in b.threads.iter().enumerate() { - in_messages(b.id, Some(i), msgs, &q, &mut out); + in_messages(b.id, Some(i), msgs, 0, &q, &mut out); } } // Newest first; messages without a time keep their order, after the dated ones. @@ -83,9 +96,10 @@ pub fn search(bots: &[Bot], query: &str) -> (Vec, bool) { /// 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); + // (An archive's words that came ready count as a change: the search runs again with them.) + let (mut n, mut newest, mut open) = (crate::chatarchive::said_generation() as usize, 0, 0i64); for b in bots { - n += b.messages.len() + b.threads.iter().map(|t| t.1.len()).sum::() + b.threads.len(); + n += b.conversation_len() + b.threads.iter().map(|t| t.1.len()).sum::() + 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)); } diff --git a/src/i18n_table.rs b/src/i18n_table.rs index 4b13eaa..c90cbf2 100644 --- a/src/i18n_table.rs +++ b/src/i18n_table.rs @@ -546,6 +546,11 @@ pub const ROWS: &[(&str, &str, &str)] = &[ ("電腦工具", "Computer tools", "コンピューターツール"), ("記憶", "Memories", "記憶"), ("過去的對話", "Past chats", "過去の会話"), + ("更早的 {n} 則已封存", "{n} earlier messages archived", "それ以前の {n} 件はアーカイブ済み"), + ("載入更早的", "Load earlier", "以前を読み込む"), + ("以上是封存的訊息", "Archived messages above", "ここまではアーカイブ済みのメッセージ"), + ("後面還有 {n} 則已封存", "{n} more archived messages after these", "この後にアーカイブ済みが {n} 件"), + ("載入後面的", "Load later", "続きを読み込む"), ("已關閉", "Off", "オフ"), ("已開啟", "On", "オン"), ("使用的模型", "Model", "モデル"), diff --git a/src/main.rs b/src/main.rs index 2be4a1f..d5207d7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -16,6 +16,7 @@ mod botbrowser; mod browser; mod cloudbox; mod channels; +mod chatarchive; mod checkpoint; mod computer; mod desktop; diff --git a/src/model.rs b/src/model.rs index cff0145..80e6b3b 100644 --- a/src/model.rs +++ b/src/model.rs @@ -254,6 +254,17 @@ struct ChatOut<'a> { messages: &'a [Message], #[serde(skip_serializing_if = "Option::is_none")] threads: Option<&'a [(String, Vec)]>, + /// 封存: how many came before `messages` (in chats/archive), and the first line. In the + /// same file as the messages, so the two never disagree: a stop between the chat file and + /// the settings once left settings that knew nothing of a cut the chat file had made. + /// (Always written, 0 too: a file without it was written by an AnyBot that knows nothing + /// of the archive, and then nothing in it is touched.) + archived: usize, + #[serde(skip_serializing_if = "str::is_empty")] + head_title: &'a str, + /// The time of the last archived message: which archive files are this conversation's. + #[serde(skip_serializing_if = "is_zero_i64")] + archive_mark: i64, } /// A chat file as it is read (straight into the types: the 90 MB one went through a JSON tree @@ -264,6 +275,24 @@ struct ChatIn { messages: Vec, #[serde(default)] threads: Vec<(String, Vec)>, + #[serde(default)] + archived: Option, + #[serde(default)] + head_title: String, + #[serde(default)] + archive_mark: i64, +} + +/// Each bot whose chat file this run read whole and that says what it archived: (how many, the +/// time of the last one). chatarchive::sweep touches only these; a chat it couldn't read, or +/// one an AnyBot without the archive wrote, keeps all its files. +pub fn archived_on_disk() -> std::collections::HashMap { + archived_read().lock().unwrap_or_else(|e| e.into_inner()).clone() +} + +fn archived_read() -> &'static std::sync::Mutex> { + static M: std::sync::OnceLock>> = std::sync::OnceLock::new(); + M.get_or_init(Default::default) } /// The same earlier conversation (title, length, when it began). @@ -301,6 +330,8 @@ fn chat_mark(b: &Bot) -> u64 { for m in b.messages.iter().rev().take(4) { serde_json::to_string(m).unwrap_or_default().hash(&mut h); } + // (封存 is in the chat file too.) + (b.archived, b.head_title.as_str(), b.archive_mark).hash(&mut h); h.finish() } @@ -322,6 +353,10 @@ fn chat_marks() -> &'static std::sync::Mutex bool { + *n == 0 +} + fn is_zero_i64(n: &i64) -> bool { *n == 0 } @@ -478,6 +513,19 @@ pub struct Bot { /// It goes with the conversation into 過去的對話 and comes back with it. #[serde(default, skip_serializing_if = "String::is_empty")] pub chat_title: String, + /// 封存: how many of the open conversation's oldest messages are in its archive files and + /// not in `messages` (chatarchive). A message's place in the whole conversation is + /// `archived` + its place in `messages`. + #[serde(default, skip_serializing_if = "is_zero_usize")] + pub archived: usize, + /// The open conversation's first line, kept when its start went to the archive (what + /// chat_name gives a conversation nobody named). + #[serde(default, skip_serializing_if = "String::is_empty")] + pub head_title: String, + /// The time of the last archived message: tells this conversation's archive files from a + /// conversation's put aside before (chatarchive::sweep). + #[serde(default, skip_serializing_if = "is_zero_i64")] + pub archive_mark: i64, /// 換對話 asked of the bot in chat (switch_conversation): done once its turn, and what /// follows it in this conversation, is over — never under a running turn. #[serde(skip)] @@ -620,14 +668,94 @@ pub const THREADS_KEPT: usize = 50; impl Bot { /// What the open conversation is called: the name given to it, or its first line. pub fn chat_name(&self) -> String { - if self.chat_title.is_empty() { auto_title(&self.messages) } else { self.chat_title.clone() } + if !self.chat_title.is_empty() { + self.chat_title.clone() + } else if self.archived > 0 && !self.head_title.is_empty() { + self.head_title.clone() + } else { + auto_title(&self.messages) + } + } + + /// How many messages the open conversation has, its archived head with them. + pub fn conversation_len(&self) -> usize { + self.archived + self.messages.len() + } + + /// 封存: a long open conversation's head goes to its archive files (on disk before this + /// returns), the newest ~2 000 stay. Only for a bot that isn't working: a turn's steps and + /// anything else that remembers a place in `messages` would shift. Returns how many moved. + pub fn archive_head(&mut self) -> Option { + let cut = crate::chatarchive::cut_point(&self.messages)?; + let dir = crate::chatarchive::dir(self.id); + crate::chatarchive::keep_strays(&dir, self.archived, &self.messages); + if let Err(e) = crate::chatarchive::write_in(&dir, self.archived, &self.messages[..cut]) { + log::warn!("AnyBot:對話封存寫不進去({e}),先不封存"); + return None; + } + if self.archived == 0 { + self.head_title = auto_title(&self.messages); + } + self.archive_mark = self.messages[cut - 1].at; + self.messages.drain(..cut); + self.archived += cut; + log::info!("AnyBot:「{}」的對話較早的 {cut} 則收進封存(封存共 {} 則,留下 {} 則)", self.name, self.archived, self.messages.len()); + Some(cut) + } + + /// The archived head comes back into memory (the conversation goes whole somewhere: put + /// aside, rewound, copied); its files are retired. Not all of it readable: left as it is. + pub fn unarchive(&mut self) -> bool { + if self.archived == 0 { + return true; + } + let mut whole = crate::chatarchive::all(self.id, self.archived); + if whole.len() != self.archived { + log::warn!("AnyBot:封存只讀回 {}/{} 則,留在原處", whole.len(), self.archived); + return false; + } + whole.extend(std::mem::take(&mut self.messages).into_inner()); + self.messages = whole.into(); + crate::chatarchive::retire(self.id); + self.archived = 0; + self.head_title.clear(); + self.archive_mark = 0; + true + } + + /// The open conversation is emptied (清除): its archive goes too. + pub fn forget_archive(&mut self) { + if self.archived > 0 { + crate::chatarchive::retire(self.id); + } + self.archived = 0; + self.head_title.clear(); + self.archive_mark = 0; } /// 開始新對話: the open conversation goes to the top of 過去的對話 with its name (its words, /// not the screenshots held in memory), and the chat is empty and nameless. pub fn put_aside(&mut self) { + // (Its name as it was: the first line of the whole, even with the head archived.) + let named = self.chat_name(); + // (過去的對話 holds a conversation whole: its archived head comes with it. Files that + // can't all be read back: what was read comes, with a line saying so, and the files are + // kept aside for good — never deleted, never following the next conversation.) + if !self.unarchive() { + let read = crate::chatarchive::all(self.id, self.archived); + let kept = crate::chatarchive::keep_aside(self.id); + let line = format!("(這段對話較早的 {} 則封存只讀回 {} 則;原本的檔案留在 {},沒有刪。)", self.archived, read.len(), kept.display()); + log::warn!("AnyBot:{line}"); + let mut whole = read; + whole.push(Message { note: true, at: whole.last().map(|m| m.at).unwrap_or(0), ..Message::assistant(&line, "") }); + whole.extend(std::mem::take(&mut self.messages).into_inner()); + self.messages = whole.into(); + self.archived = 0; + self.head_title.clear(); + self.archive_mark = 0; + } if !self.messages.is_empty() { - let title = self.chat_name(); + let title = named; let mut msgs = std::mem::take(&mut self.messages).into_inner(); msgs.iter_mut().for_each(|m| m.images.clear()); self.threads.insert(0, (title, msgs)); @@ -1169,7 +1297,32 @@ impl State { continue; } let had_apart = apart.is_some(); - let ChatIn { messages, threads: inside } = chat.unwrap_or_default(); + let read_whole = chat.is_some(); + let ChatIn { messages, threads: inside, archived, head_title, archive_mark } = chat.unwrap_or_default(); + // 封存: the chat file says (the settings' copy may be from before a cut or after). + // One that doesn't say (an AnyBot without the archive wrote it): an archive folder + // that runs whole from the start is taken as this conversation's, and nothing is + // tidied away this time. + match (read_whole, archived) { + (true, Some(n)) => { + b.archived = n; + b.head_title = head_title; + b.archive_mark = archive_mark; + archived_read().lock().unwrap_or_else(|e| e.into_inner()).insert(b.id, (n, archive_mark)); + } + (true, None) => { + // (Where archive_head writes it: chatarchive::dir.) + let first = messages.first().map(|m| m.at); + match crate::chatarchive::whole_from_start(&crate::chatarchive::dir(b.id)).filter(|(_, mark, _)| crate::chatarchive::goes_on_from(*mark, first)) { + Some((n, mark, title)) => { + log::warn!("AnyBot:Bot {} 的聊天檔沒寫封存(舊版 AnyBot 存的),照封存資料夾接回 {n} 則", b.id); + (b.archived, b.archive_mark, b.head_title) = (n, mark, title); + } + None => (b.archived, b.archive_mark, b.head_title) = (0, 0, String::new()), + } + } + _ => {} + } // Earlier conversations still inside the chat file: one from before they were set // apart, or ones an older AnyBot put aside since (newer: they go first). let inside_empty = inside.is_empty(); @@ -1339,7 +1492,7 @@ impl State { } } }; - let out = ChatOut { messages: &b.messages, threads: if apart { None } else { Some(&b.threads) } }; + let out = ChatOut { messages: &b.messages, threads: if apart { None } else { Some(&b.threads) }, archived: b.archived, head_title: &b.head_title, archive_mark: b.archive_mark }; match serde_json::to_vec(&out) { Ok(bytes) if crate::httpd::write_private(&chat_path(&p, b.id), &bytes).is_ok() => { chat_marks().lock().unwrap().insert(key, mark); @@ -1370,6 +1523,9 @@ impl State { let tf = threads_path(&p, id); let _ = std::fs::remove_file(&tf); marks.remove(&(tf, id)); + if let Some(dir) = p.parent() { + crate::chatarchive::remove_all(dir, id); + } } return true; } @@ -1454,7 +1610,8 @@ impl State { let mut n = 0; let mut reid: Vec<(u64, u64)> = vec![]; for b in &other.bots { - if self.bots.iter().any(|o| o.name == b.name && (b.messages.is_empty() || (o.messages.len() == b.messages.len() && last(o) == last(b)))) { + // (By the whole conversation's length: one here may have its head archived.) + if self.bots.iter().any(|o| o.name == b.name && (b.messages.is_empty() || (o.conversation_len() == b.conversation_len() && last(o) == last(b)))) { continue; } let mut b = b.clone(); @@ -1533,6 +1690,9 @@ impl State { members: vec![], threads: Default::default(), chat_title: String::new(), + archived: 0, + head_title: String::new(), + archive_mark: 0, chat_after: None, context_tokens: default_context_tokens(), model_limits: Default::default(), @@ -1745,6 +1905,211 @@ pub fn bot_computer_dir(bot_id: u64) -> PathBuf { mod start_tests { use super::*; + fn long_chat(n: usize, summary_at: usize) -> Vec { + (0..n) + .map(|i| { + let mut m = if i % 8 == 0 { Message::user(&format!("第 {i} 句")) } else { Message::assistant(&format!("回 {i}"), "x") }; + m.at = 1_000 + i as i64; + m.summary = i == summary_at; + m + }) + .collect() + } + + /// 封存 and a stop at the worst moments: the count lives in the chat file with the messages + /// (settings from before the cut don't lose it, and the start's tidy keeps the files); a stop + /// after 開始新對話 but before its save gets the retired archive back, and once that save is + /// on disk the retired folder goes; an archive with a file missing comes along as far as it + /// reads, with a line, and its files are kept aside, never deleted. + #[test] + fn a_stop_at_any_moment_loses_no_archived_message() { + let _turn = crate::chatarchive::test_turn(); + let data = State::path().parent().unwrap().to_path_buf(); + let id = 910_000 + std::process::id() as u64 % 1000; + let root = data.join("chats").join("archive"); + for e in std::fs::read_dir(&root).into_iter().flatten().flatten() { + if e.file_name().to_string_lossy().starts_with(&format!("bot-{id}")) { + let _ = std::fs::remove_dir_all(e.path()); + } + } + let dir = std::env::temp_dir().join(format!("anybot-archive-stop-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let p = dir.join("state.json"); + let mut st = State::samples(); + st.bots[0].id = id; + st.bots[0].messages = long_chat(3_200, 3_100).into(); + assert!(st.save_at(&p)); + let before = std::fs::read(&p).unwrap(); + let cut = st.bots[0].archive_head().unwrap(); + assert!(st.save_at(&p)); + // The settings as they were before the cut (a stop between the chat file and them). + std::fs::write(&p, &before).unwrap(); + let back = State::load_from(&p); + let b = back.bots.iter().find(|b| b.id == id).unwrap(); + assert_eq!((b.archived, b.messages.len()), (cut, 3_200 - cut), "the chat file says"); + crate::chatarchive::sweep(&data, &back.bots, &archived_on_disk()); + assert_eq!(crate::chatarchive::whole(b).len(), 3_200, "nothing swept away"); + // 開始新對話, then a stop before its save: the archive comes back at the next start. + st.bots[0].put_aside(); + assert!(!crate::chatarchive::dir(id).exists()); + let back = State::load_from(&p); + crate::chatarchive::sweep(&data, &back.bots, &archived_on_disk()); + let b = back.bots.iter().find(|b| b.id == id).unwrap(); + assert_eq!(crate::chatarchive::whole(b).len(), 3_200, "the retired archive came back"); + // Put aside again and saved this time: the retired folder goes at the next start. + st.bots[0].messages = back.bots.iter().find(|b| b.id == id).unwrap().messages.clone(); + st.bots[0].archived = cut; + st.bots[0].put_aside(); + assert_eq!(st.bots[0].threads[0].1.len(), 3_200); + assert!(st.save_at(&p)); + let back = State::load_from(&p); + crate::chatarchive::sweep(&data, &back.bots, &archived_on_disk()); + assert_eq!(back.bots.iter().find(|b| b.id == id).unwrap().threads[0].1.len(), 3_200); + let left = |kind: &str| std::fs::read_dir(&root).into_iter().flatten().flatten().any(|e| e.file_name().to_string_lossy().starts_with(&format!("bot-{id}.{kind}"))); + assert!(!left("retired"), "gone once the conversation is saved elsewhere"); + // A file missing: what reads comes along with a line; the rest is kept aside for good. + let b = &mut st.bots[0]; + b.threads.clear(); + b.messages = long_chat(3_200, 3_100).into(); + b.archived = 0; + let cut = b.archive_head().unwrap(); + let first = crate::chatarchive::segments_in(&crate::chatarchive::dir(id)).remove(0); + std::fs::remove_file(&first.path).unwrap(); + b.put_aside(); + let t = &b.threads[0].1; + assert_eq!(t.len(), 3_200 - first.count + 1, "{cut}"); + assert!(t.iter().any(|m| m.note && m.text.contains("只讀回"))); + assert!(left("kept")); + crate::chatarchive::sweep(&data, &back.bots, &archived_on_disk()); + assert!(left("kept"), "never deleted"); + for e in std::fs::read_dir(&root).into_iter().flatten().flatten() { + if e.file_name().to_string_lossy().starts_with(&format!("bot-{id}")) { + let _ = std::fs::remove_dir_all(e.path()); + } + } + let _ = std::fs::remove_dir_all(&dir); + } + + /// Two conversations archived and put aside, the second not saved after: the one that + /// comes back is the one the chat file means (by count and the last archived message's + /// time), never an older one of the same length; only then do the others go. A chat file an + /// AnyBot without the archive wrote (no count) takes the folder back whole and loses nothing. + #[test] + fn the_right_archive_comes_back_and_an_old_writer_loses_nothing() { + let _turn = crate::chatarchive::test_turn(); + let data = State::path().parent().unwrap().to_path_buf(); + let id = 920_000 + std::process::id() as u64 % 1000; + let root = data.join("chats").join("archive"); + let clean = || { + for e in std::fs::read_dir(&root).into_iter().flatten().flatten() { + if e.file_name().to_string_lossy().starts_with(&format!("bot-{id}")) { + let _ = std::fs::remove_dir_all(e.path()); + } + } + }; + clean(); + let dir = std::env::temp_dir().join(format!("anybot-archive-two-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let p = dir.join("state.json"); + let mut st = State::samples(); + st.bots[0].id = id; + // The first conversation: longer, archived, put aside (retired), saved. + st.bots[0].messages = long_chat(3_600, 3_500).into(); + let n1 = st.bots[0].archive_head().unwrap(); + st.bots[0].put_aside(); + assert!(st.save_at(&p)); + std::thread::sleep(std::time::Duration::from_millis(5)); + // The second: other times, archived and saved, then put aside with no save after. + let mut second = long_chat(3_200, 3_100); + second.iter_mut().for_each(|m| m.at += 1_000_000); + st.bots[0].messages = second.into(); + let n2 = st.bots[0].archive_head().unwrap(); + assert!(n1 >= n2); + assert!(st.save_at(&p)); + st.bots[0].put_aside(); + let back = State::load_from(&p); + crate::chatarchive::sweep(&data, &back.bots, &archived_on_disk()); + let b = back.bots.iter().find(|b| b.id == id).unwrap(); + let whole = crate::chatarchive::whole(b); + assert_eq!(whole.len(), 3_200); + assert!(whole.iter().all(|m| m.at > 1_000_000), "the second conversation's head, not the first's"); + let retired = std::fs::read_dir(&root).into_iter().flatten().flatten().filter(|e| e.file_name().to_string_lossy().starts_with(&format!("bot-{id}.retired-"))).count(); + assert_eq!(retired, 0, "the first's retired folder goes once the right one is back"); + // An AnyBot without the archive saves the chat file: no count in it. + let f = chat_path(&p, id); + let mut v: serde_json::Value = serde_json::from_slice(&std::fs::read(&f).unwrap()).unwrap(); + for k in ["archived", "head_title", "archive_mark"] { + v.as_object_mut().unwrap().remove(k); + } + std::fs::write(&f, v.to_string()).unwrap(); + let back = State::load_from(&p); + crate::chatarchive::sweep(&data, &back.bots, &archived_on_disk()); + let b = back.bots.iter().find(|b| b.id == id).unwrap(); + assert_eq!((b.archived, crate::chatarchive::whole(b).len()), (n2, 3_200), "taken back from the folder"); + // A chat started over by that older AnyBot (days later): not taken; and when this chat + // is cut, the old head is set aside, not written over. + let mut v: serde_json::Value = serde_json::from_slice(&std::fs::read(&f).unwrap()).unwrap(); + let mut later = long_chat(3_200, 3_100); + later.iter_mut().for_each(|m| m.at += 9_000_000_000); + v["messages"] = serde_json::to_value(&later).unwrap(); + std::fs::write(&f, v.to_string()).unwrap(); + let mut back = State::load_from(&p); + let b = back.bots.iter_mut().find(|b| b.id == id).unwrap(); + assert_eq!(b.archived, 0, "another conversation"); + b.archive_head().unwrap(); + let kept: Vec<_> = std::fs::read_dir(&root).into_iter().flatten().flatten().filter(|e| e.file_name().to_string_lossy().starts_with(&format!("bot-{id}.kept-"))).collect(); + assert_eq!(kept.len(), 1); + assert_eq!(crate::chatarchive::read_in(&kept[0].path(), 0, n2).len(), n2, "the old head, whole, set aside"); + assert!(crate::chatarchive::whole(b).iter().all(|m| m.at > 9_000_000_000), "the new archive is the new chat's"); + clean(); + let _ = std::fs::remove_dir_all(&dir); + } + + /// 封存: a long chat with a summary keeps its newest ~2 000; the head goes to files, its name + /// stays its first line, the count survives a save and a start, and putting the conversation + /// aside takes it whole into 過去的對話 (the files retired). + #[test] + fn a_long_chat_keeps_its_newest_and_comes_back_whole() { + let _turn = crate::chatarchive::test_turn(); + let mut st = State::samples(); + let id = 900_000 + std::process::id() as u64 % 1000; + st.bots[0].id = id; + let mut msgs = vec![]; + for i in 0..3_200 { + let mut m = if i % 8 == 0 { Message::user(&format!("第 {i} 句:開頭的話")) } else { Message::assistant(&format!("回 {i}"), "x") }; + m.at = 1_000 + i as i64; + m.summary = i == 3_100; + msgs.push(m); + } + let b = &mut st.bots[0]; + b.messages = msgs.clone().into(); + let _ = std::fs::remove_dir_all(crate::chatarchive::dir(id)); + let name = b.chat_name(); + let cut = b.archive_head().expect("long enough, with a summary"); + assert!(b.messages.len() >= crate::chatarchive::LIVE_KEEP && b.messages.len() < crate::chatarchive::LIVE_KEEP + 8, "{}", b.messages.len()); + assert_eq!((b.archived, b.conversation_len()), (cut, 3_200)); + assert_eq!(b.messages[0].role, Role::User, "cut at a message of the person's"); + assert_eq!(b.chat_name(), name, "named as before: its first line"); + assert_eq!(crate::chatarchive::whole(b).iter().map(|m| m.at).collect::>(), msgs.iter().map(|m| m.at).collect::>()); + assert!(b.archive_head().is_none(), "nothing more to move"); + // Saved and read back: the count and the first line stay; the files are where they were. + let dir = std::env::temp_dir().join(format!("anybot-archive-state-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let p = dir.join("state.json"); + assert!(st.save_at(&p)); + let back = State::load_from(&p); + let b2 = back.bots.iter().find(|b| b.id == id).unwrap(); + assert_eq!((b2.archived, b2.messages.len(), b2.chat_name()), (cut, 3_200 - cut, name.clone())); + // Put aside: whole, in 過去的對話; the open conversation starts empty with nothing archived. + let b = &mut st.bots[0]; + b.put_aside(); + assert_eq!((b.archived, b.messages.len(), b.head_title.as_str()), (0, 0, "")); + assert_eq!(b.threads[0].1.len(), 3_200); + assert_eq!(b.threads[0].0, name); + assert!(!crate::chatarchive::dir(id).exists(), "its files retired"); + let _ = std::fs::remove_dir_all(&dir); + } + /// 你的訊息泡泡:新的預設是「安靜」(淡灰)。存著舊預設「跟著 Bot」的設定檔載入時換成安靜一次; /// 之後自己選回「跟著 Bot」就照你選的(不會每次開都被換掉)。 #[test] diff --git a/src/remote.rs b/src/remote.rs index a628798..c5ad66d 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -714,6 +714,7 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { // (The owner's conversations, by name or count, aren't a member's.) o.remove("threads_total"); o.remove("chat_title"); + o.remove("head_title"); o.remove("chat_named"); o.insert("queued".into(), json!([])); o.remove("goal"); diff --git a/src/setup.rs b/src/setup.rs index 35a8249..e7c4aa4 100644 --- a/src/setup.rs +++ b/src/setup.rs @@ -1162,6 +1162,9 @@ fn seed_first() -> i32 { members: vec![], threads: Default::default(), chat_title: String::new(), + archived: 0, + head_title: String::new(), + archive_mark: 0, chat_after: None, memories: vec![], speak_replies: false, diff --git a/src/share.rs b/src/share.rs index 80d7d48..345faba 100644 --- a/src/share.rs +++ b/src/share.rs @@ -41,7 +41,7 @@ pub fn export(b: &Bot) -> String { let mut v = serde_json::to_value(b).unwrap_or(Value::Null); if let Value::Object(m) = &mut v { // (Its 可以用的電腦 are this account's computers by name; its 草稿 is unsent words: neither travels.) - for k in ["messages", "threads", "chat_title", "allow_rules", "memories", "tools_enabled", "default_computer", "unread", "last_turn", "tasks", "goal", "plan", "workdir", "pinned", "id", "computers", "draft", "regen_undo", "branches", "branch_of", "team"] { + for k in ["messages", "threads", "chat_title", "archived", "head_title", "archive_mark", "allow_rules", "memories", "tools_enabled", "default_computer", "unread", "last_turn", "tasks", "goal", "plan", "workdir", "pinned", "id", "computers", "draft", "regen_undo", "branches", "branch_of", "team"] { m.remove(k); } if let Some(Value::Array(routines)) = m.get_mut("routines") { @@ -82,7 +82,7 @@ pub fn import(text: &str, new_id: u64, next_routine: &mut u64, now: i64) -> Resu m.insert("messages".into(), Value::Array(vec![])); // Never import another person's grants, local workdir, threads or memories — nor its // sharing with a team (a file carrying 「team」 shared the new bot at once). - for k in ["goal", "plan", "allow_rules", "tools_enabled", "workdir", "default_computer", "threads", "members", "memories", "unread", "last_turn", "tasks", "team", "branches", "branch_of"] { + for k in ["goal", "plan", "allow_rules", "tools_enabled", "workdir", "default_computer", "threads", "archived", "head_title", "archive_mark", "members", "memories", "unread", "last_turn", "tasks", "team", "branches", "branch_of"] { m.remove(k); } } diff --git a/src/stats.rs b/src/stats.rs index b7c8a96..1469e38 100644 --- a/src/stats.rs +++ b/src/stats.rs @@ -35,6 +35,10 @@ pub fn inputs(st: &crate::model::State) -> Inputs { let counts = |m: &crate::model::Message| matches!(m.role, Role::User | Role::Assistant) && !m.note && m.at >= from && !(m.role == Role::Assistant && m.text.trim().is_empty()); let mut messages = vec![]; for b in &st.bots { + // 封存: its words once read (chatarchive::said; until then the heat map lacks them). + if let Some(said) = crate::chatarchive::said(b.id, b.archived) { + messages.extend(said.iter().filter(|s| !s.note && s.at >= from && (s.mine || !s.text.trim().is_empty())).map(|s| s.at)); + } messages.extend(b.messages.iter().filter(|m| counts(m)).map(|m| m.at)); for (_, t) in b.threads.iter() { messages.extend(t.iter().filter(|m| counts(m)).map(|m| m.at));