diff --git a/FEATURES.md b/FEATURES.md index 7f3f447..2c6bde3 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -534,7 +534,8 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 - **「Tailscale」看通道,不看位址像不像 100.x**:100.64.0.0/10 是電信業者 NAT 的共用位址,有些 Wi-Fi、PPPoE、Cloudflare WARP 也用這一段。Tailscale 通道是:macOS 上帶著 Tailscale IPv6 位址的 utun、Linux 的 tailscale… 介面、Windows 名字有 Tailscale 的介面卡。區網直連只有「來源在 Tailscale 範圍、而且連到這台 Tailscale 通道上的位址」才收 http,列出的網址也只有通道位址寫 http。帳號伺服器用 http:// 時,帳號密碼、配對碼和這台電腦的金鑰只送到這台電腦、一個字的名字(同一個 Docker 網路),或位址都是 Tailscale 的、而且路由從 Tailscale 通道出去的伺服器——在開連線那一刻對真正要連的位址查:http 的帳號伺服器每個請求都開新連線、每次都查,長連線在每次連上和重連時查(連著時不中途重查)。不符合就不連:登入、還原、配對回到表單說原因;長連線、備用連線在狀態寫原因、之後自己再試。http 的帳號伺服器不走代理;一個字的名字要以英文字母開頭(純數字、0x 的寫法不算),`localhost` 只連它查到的 loopback 位址(其他的略過,一個都沒有就不連)。網址照 HTTP 程式庫自己的讀法讀(`?`、`#` 後面不是主機)。`ANYBOT_PHONE_BIND` 讓直接連線只聽一個位址;位址還不在、連接埠被占用或不准用時,紀錄和設定照實說,之後每 5 秒自己再試,不用關掉再開。 - **手腳只聽大腦簽過的指令**:在大腦這台按「產生配對碼」,貼上的那一行裡,6 位配對碼後面多一段密鑰(`135790-abc…`)。密鑰只在兩台電腦上,不會傳給帳號伺服器;之後大腦給這台手腳的每個指令都帶簽章(綁定是哪台電腦、時間、只能用一次),手腳驗不過就拒絕。所以帳號伺服器(或攻進去的人)不能自己造指令、也不能重放。用手機產生的配對碼、或是當「另一個大腦的螢幕」時產生的,沒有密鑰(跟以前一樣,沒有簽章)。舊版 AnyBot 讀到新格式只取 6 位數字,照舊配對。 - **更新要驗簽章**:`make sign-setup`(作者做一次)讓之後每個 commit 用 SSH 金鑰簽章,公鑰記在 `deploy/allowed_signers`。安裝時把它記到原始碼資料夾外面(`~/.config/anybot/allowed_signers`);之後 `make update`/重跑安裝腳本,新版不是那把金鑰簽的就不裝(Mac、Linux、Windows 都一樣)。換金鑰:用舊金鑰簽一個把新公鑰加進名單的 commit。確定要跳過一次:`ANYBOT_UNSIGNED=1`。還沒有 `deploy/allowed_signers` 時跟以前一樣不檢查。 -- **聊天各存各的檔**:state.json 只剩設定;每個 Bot 的聊天存在 `chats/bot-<編號>.json`,有變才寫。Bot 工作時每兩秒存一次的不再是整份幾十 MB;刪掉 Bot 時它的聊天檔一起刪。舊版存的(聊天在 state.json 裡)照樣讀得進來,下次存檔就分開。 +- **聊天各存各的檔**:state.json 只剩設定;每個 Bot 的聊天存在 `chats/bot-<編號>.json`,有變才寫;過去的對話(討論串)另外存在 `chats/threads/bot-<編號>.json`,只有收起、切換或刪掉對話時才寫。Bot 工作時每 5 秒的存檔只寫目前這段對話:一個留了 3.5 萬則舊訊息(60 MB)的 Bot,存一次從 90–290 毫秒、寫 77 MB 降到 7–10 毫秒、寫 0.75 MB(以前每 5 秒整份重寫,在 2 核、沒有顯示卡的電腦上視窗每次停住快一秒)。刪掉 Bot 時兩個檔一起刪。舊版存的(聊天在 state.json 裡、或過去的對話在聊天檔裡)照樣讀得進來,下次存檔就分開;中間跑過舊版 AnyBot(它看不到另存的對話、放下的新對話寫在聊天檔裡)也不會少:兩邊合在一起,舊版放下的排前面。壞掉的檔案改名留著,不會被蓋掉。 +- **沒有顯示卡的電腦**(虛擬機、透過遠端桌面看的電腦:畫面由 CPU 畫,例如 llvmpipe):開視窗時認出來、紀錄寫一行。Bot 工作時的轉圈、流光字、側欄頭像、串流的重畫從每秒 20–30 次放慢成每秒 4 次——每一張都是整個視窗用 CPU 重畫,原本吃掉大半個核心、旁邊 Bot 自己開的瀏覽器跟著卡,從遠端桌面看視窗一直閃。有顯示卡的電腦照舊。 - **帳號伺服器的資源**:閒置的連線從每秒醒 25 次降到 5 次;每條連線的讀取緩衝從 128 KB 降到 32 KB;請求的開頭 15 秒內沒送完就斷(原本最長 90 秒)。本機壓測(100 台電腦連著、3000 個請求、120 次錯誤登入、128 個送一半的請求、3 輪重連):記憶體 32 MB 持平,執行緒和檔案描述元都回到起點,閒置 CPU 約 1.5%(一個核心)。 - **團隊成員在 Bot 忙的時候傳的訊息**不再被丟掉:排在後面,Bot 做完手上的事就輪到它(每個 Bot 最多排 8 則)。成員的話不會插進擁有者正在跑的那一輪。 - **群組沒有 @ 時看擅長分派**:訊息的內容對得上某些成員「擅長」寫的事(而且不在它「不找它做的事」裡),就只由那幾位回答,聊天裡會有一行「這題看擅長交給「…」。要其他人也回答,用 @ 點名。」;對不上任何人、或每個人都對得上,就跟以前一樣全員輪流。 diff --git a/docs/feature-map/chat.md b/docs/feature-map/chat.md index 211d9c2..2498561 100644 --- a/docs/feature-map/chat.md +++ b/docs/feature-map/chat.md @@ -12,7 +12,7 @@ - `chat-followthrough` 說了就做:回答說了要做什麼(「我把它整理成一頁」)卻沒動手,或問「要我現在就開始嗎?」,這一輪不停:上方閃過「說了要做還沒動手,提醒它接著做…」,它接著做。其實做完、或接下來要你決定(刪除、付款、寄出、斷線),就停在原來那句;連兩次沒動手就停。 - `chat-actions` 回答旁的操作:滑過 Bot 的回答出現「新增表情回應」「回覆」(引用這則)「更多訊息操作」;⋯ 裡有「複製」「重新產生」(只有最後一則)「還原上一個答案」「顯示步驟(N)」,最下面寫是哪個模型寫的。出錯的回答下面直接有「重試」。 - `chat-select` 選取一段文字(手機頁面和網頁版):按住一則訊息(或回答下的 ⋯)開訊息選單,「複製」是整則;「選取文字」把這則放進下方面板,在那裡按住開始選、拖兩端調整、按系統的「拷貝」(電腦上拖曳後按 ⌘C/Ctrl+C),「完成」關掉。用電腦的瀏覽器能在聊天裡拖曳選字;選好的字上右鍵(長按)是瀏覽器選單,別處右鍵才開訊息選單。 -- `chat-steps` 步驟和思考:預設收起。「顯示步驟」一行一個工具(等你允許/執行中/完成/被拒絕或停止/失敗),滑過那一行看結果;「思考過程」也在這裡。工作中,輸入框上方的臉旁邊寫它正在做什麼。臉和「正在…」最多每秒畫 20 次;等決定時的黃點輕彈約 5 次。沒在動不重畫;你不在(視窗不在前、90 秒沒動)頭像不眨眼。 +- `chat-steps` 步驟和思考:預設收起。「顯示步驟」一行一個工具(等你允許/執行中/完成/被拒絕或停止/失敗),滑過那一行看結果;「思考過程」也在這裡。工作中,輸入框上方的臉旁邊寫它正在做什麼。臉和「正在…」最多每秒畫 20 次(CPU 畫圖 4 次);等決定時的黃點輕彈約 5 次。沒在動不重畫;你不在(視窗不在前、90 秒沒動)頭像不眨眼。 - `chat-attach` 附件:「附加檔案」、拖進視窗、⌘V 貼圖;每檔最多 50 MB,文字檔最多讀 20,000 字給模型。 - `chat-compact` 長對話:舊步驟的長結果(連同長指令)累積到可讀長度 15% 就整批收起(聊天裡照樣完整);用到 6 成才寫可展開的「較早的對話已整理成摘要」。一個要求做很多步時也寫;摘要分段寫,模型寫不出來由 AnyBot 整理。 - `chat-window` 開聊天分頁(手機頁面):打開給最新 30 條,頂上「載入更早的對話」點一次往前補 60 條,到最頂消失;回答中手機每秒最多更新一次,打完的整句補齊。電腦和聊底指令照舊拿整段。 diff --git a/src/app.rs b/src/app.rs index 6e63726..043b62d 100644 --- a/src/app.rs +++ b/src/app.rs @@ -54,6 +54,27 @@ mod profile_ui; mod asks; /// A server's brain was told to stop (see App::serve). static STOPPING: AtomicBool = AtomicBool::new(false); + +/// The window is drawn by the processor: no graphics card (a virtual machine, a computer seen +/// through a remote desktop). Set once, when the window opens. +static DRAWN_BY_CPU: AtomicBool = AtomicBool::new(false); + +pub fn set_drawn_by_cpu(on: bool) { + DRAWN_BY_CPU.store(on, Ordering::Relaxed); + if on { + log::info!("AnyBot:這台沒有顯示卡,畫面由 CPU 畫:等待和串流的動畫放慢成每秒 4 張"); + } +} + +/// When an animation (a spinner, shimmering words, a fade, words streaming in) draws its next +/// frame. Each frame is the whole window drawn again: on a 2-core virtual machine drawing it on the +/// processor, 20 frames a second while a bot worked took most of a core, beside the bot's own +/// browser, and over a remote desktop the window flickered. There, 4 a second: still moving. +pub(crate) fn anim_after(ms: u64) -> std::time::Duration { + std::time::Duration::from_millis(if DRAWN_BY_CPU.load(Ordering::Relaxed) { ms.max(CPU_FRAME_MS) } else { ms }) +} + +const CPU_FRAME_MS: u64 = 250; mod branch; mod followup_ui; mod deliver_ui; @@ -1365,7 +1386,7 @@ impl App { .map(|d| c + egui::vec2(d.x * cs - d.y * sn, d.x * sn + d.y * cs)); paint.add(egui::Shape::convex_polygon(pts.to_vec(), col, Stroke::NONE)); } - ctx.request_repaint_after(std::time::Duration::from_millis(33)); + ctx.request_repaint_after(anim_after(33)); } /// What the shell is built from, to notice a change (f32s by their bits: equal means unchanged). @@ -3967,7 +3988,7 @@ impl App { 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(std::time::Duration::from_millis(50)); + ui.ctx().request_repaint_after(anim_after(50)); } else { self.goto = None; } @@ -7094,7 +7115,7 @@ impl eframe::App for App { ctx.request_repaint_after(std::time::Duration::from_secs(15)); } if !self.streams.is_empty() || !self.model_fetch.is_empty() { - ctx.request_repaint_after(std::time::Duration::from_millis(100)); + ctx.request_repaint_after(anim_after(100)); } // A selection copied with ⌘C (in a text box, a selectable label) rides the same // platform clipboard eframe would feed after this returns — on a Mac the path that @@ -8167,6 +8188,20 @@ fn dialog_body(ui: &mut egui::Ui, id: impl std::hash::Hash + std::fmt::Debug, #[cfg(test)] mod tests { + /// On a window the processor draws, the animations go at 4 frames a second; with a graphics + /// card they keep their own pace (a slower one stays as it is). + #[test] + fn animations_slow_down_when_the_processor_draws_the_window() { + use super::*; + let ms = |d: std::time::Duration| d.as_millis() as u64; + assert_eq!((ms(anim_after(33)), ms(anim_after(50)), ms(anim_after(400))), (33, 50, 400)); + set_drawn_by_cpu(true); + let slowed = (ms(anim_after(33)), ms(anim_after(50)), ms(anim_after(400))); + set_drawn_by_cpu(false); + assert_eq!(slowed, (CPU_FRAME_MS, CPU_FRAME_MS, 400)); + assert_eq!(ms(anim_after(50)), 50); + } + /// A routine's runs reach its record when its turns end, and two failures in a row pause it /// with a line in the chat (the demo app: nothing read from or written to disk). #[test] diff --git a/src/app/chat_ui.rs b/src/app/chat_ui.rs index b32c604..f17ce11 100644 --- a/src/app/chat_ui.rs +++ b/src/app/chat_ui.rs @@ -431,7 +431,7 @@ pub fn spinner_at(ui: &egui::Ui, rect: egui::Rect, col: Color32) { c + vec2(a.cos(), a.sin()) * r }).collect(); ui.painter().add(egui::Shape::line(pts, Stroke::new(2.0, col))); - ui.ctx().request_repaint_after(std::time::Duration::from_millis(50)); + ui.ctx().request_repaint_after(super::anim_after(50)); } /// Text with a light band sweeping across it (the original's sand-shimmer-text). @@ -447,7 +447,7 @@ pub fn shimmer(ui: &mut egui::Ui, text: &str, base: Color32, bright: Color32, si job.append(&ch.to_string(), 0.0, egui::TextFormat { font_id: egui::FontId::proportional(size), color: col, ..Default::default() }); } ui.label(job); - ui.ctx().request_repaint_after(std::time::Duration::from_millis(50)); + ui.ctx().request_repaint_after(super::anim_after(50)); } /// A message of yours the chat doesn't have yet (on its way, or waiting for the brain): a @@ -522,7 +522,7 @@ impl App { let e = t0.elapsed().as_secs_f32() / ROW_ENTER; if e < 1.0 { // (30 a second is smooth for a fade; the display's 120 isn't needed on an old Mac.) - ctx.request_repaint_after(std::time::Duration::from_millis(33)); + ctx.request_repaint_after(super::anim_after(33)); } ease_out(e) } else { @@ -970,7 +970,7 @@ impl App { let p = self.pal; let scale = match self.popped.get(&(bot_id, idx, e.to_string())) { Some(t0) if t0.elapsed().as_secs_f32() < REACTION_POP => { - ui.ctx().request_repaint_after(std::time::Duration::from_millis(33)); + ui.ctx().request_repaint_after(super::anim_after(33)); pop(t0.elapsed().as_secs_f32() / REACTION_POP) } _ => 1.0, @@ -995,7 +995,7 @@ impl App { let now = ui.input(|i| i.time); self.jump_bottom = jump_still_on(self.jump_bottom, from_bottom, now); if self.jump_bottom.is_some() { - ui.ctx().request_repaint_after(std::time::Duration::from_millis(50)); + ui.ctx().request_repaint_after(super::anim_after(50)); } let id = egui::Id::unique("jump-bottom"); let k = ui.ctx().animate_bool_with_time(id, jump_shows(from_bottom, self.jump_bottom.is_some()), JUMP_BOTTOM_FADE); diff --git a/src/app/computers_ui.rs b/src/app/computers_ui.rs index 79fba68..f170169 100644 --- a/src/app/computers_ui.rs +++ b/src/app/computers_ui.rs @@ -92,7 +92,7 @@ fn status_pill(ui: &mut egui::Ui, r: &Run, p: Palette) { if matches!(r, Run::Starting(_) | Run::Rebuilding(..)) { let t = ui.input(|i| i.time) as f32; ui.painter().circle_filled(c, 4.0 + (t * 4.0).sin().abs() * 2.0, col.gamma_multiply(0.35)); - ui.ctx().request_repaint_after(std::time::Duration::from_millis(60)); + ui.ctx().request_repaint_after(super::anim_after(60)); } ui.painter().circle_filled(c, 3.5, col); ui.painter().galley(rect.left_center() + vec2(20.0, -galley.size().y / 2.0), galley, p.text2); diff --git a/src/app/sidebar_ui.rs b/src/app/sidebar_ui.rs index 1d309ea..a396400 100644 --- a/src/app/sidebar_ui.rs +++ b/src/app/sidebar_ui.rs @@ -167,7 +167,7 @@ impl App { if moving { // One frame of the whole window, not as fast as the display can go: on a slower // machine an uncapped face redrew the chat flat out and the fans never stopped. - ctx.request_repaint_after(std::time::Duration::from_millis(50)); + ctx.request_repaint_after(super::anim_after(50)); } else if here { ctx.request_repaint_after(std::time::Duration::from_secs_f64((f.next_blink - now).max(0.05))); } @@ -1071,7 +1071,7 @@ impl App { ui.allocate_exact_size(screen.size(), egui::Sense::click()); }); } - ctx.request_repaint_after(std::time::Duration::from_millis(50)); + ctx.request_repaint_after(super::anim_after(50)); true } } diff --git a/src/main.rs b/src/main.rs index 8fa498b..2d1cc80 100644 --- a/src/main.rs +++ b/src/main.rs @@ -508,6 +508,10 @@ fn main() -> eframe::Result<()> { options, Box::new(move |cc| { load_fonts(&cc.egui_ctx); + // No graphics card: the window is drawn by the processor (llvmpipe, lavapipe…). + if let Some(rs) = &cc.wgpu_render_state { + app::set_drawn_by_cpu(rs.adapter.get_info().device_type == eframe::wgpu::DeviceType::Cpu); + } Ok(Box::new(app::App::new(&cc.egui_ctx, screenshot))) }), ) diff --git a/src/model.rs b/src/model.rs index 0c3371c..b1a0464 100644 --- a/src/model.rs +++ b/src/model.rs @@ -219,6 +219,54 @@ fn chat_path(state: &std::path::Path, bot: u64) -> PathBuf { state.parent().map(PathBuf::from).unwrap_or_default().join("chats").join(format!("bot-{bot}.json")) } +/// A bot's earlier conversations (討論串) in a file of their own. On a long-lived bot they are +/// nearly all of its chat (one bot: 35 000 earlier messages, 60 MB, beside 1 000 current ones) and +/// change only when a conversation is put aside — yet the save every 5 s while the bot worked +/// wrote them whole each time, on the window's thread: on a 2-core computer without a graphics +/// card the window stood still for most of a second, every 5 s, as long as the bot worked. +/// (In a folder of their own: an older AnyBot deletes the `chats/bot-*.json` it doesn't know.) +fn threads_path(state: &std::path::Path, bot: u64) -> PathBuf { + state.parent().map(PathBuf::from).unwrap_or_default().join("chats").join("threads").join(format!("bot-{bot}.json")) +} + +/// Whether the earlier conversations changed since they were last written: each one's title and +/// every message's shape. +fn threads_mark(b: &Bot) -> u64 { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + for (title, msgs) in b.threads.iter() { + (title, msgs.len()).hash(&mut h); + for m in msgs { + (m.at, m.text.len(), m.thinking.len(), m.tool_calls.len(), m.reactions.len(), m.attachments.len(), m.folded).hash(&mut h); + } + } + h.finish() +} + +/// A chat file as it is written: the messages, and the earlier conversations only when their +/// own file couldn't be written. +#[derive(Serialize)] +struct ChatOut<'a> { + messages: &'a [Message], + #[serde(skip_serializing_if = "Option::is_none")] + threads: Option<&'a [(String, Vec)]>, +} + +/// A chat file as it is read (straight into the types: the 90 MB one went through a JSON tree +/// first, twice the work at every start). +#[derive(Deserialize, Default)] +struct ChatIn { + #[serde(default)] + messages: Vec, + #[serde(default)] + threads: Vec<(String, Vec)>, +} + +/// The same earlier conversation (title, length, when it began). +fn same_thread(a: &(String, Vec), b: &(String, Vec)) -> bool { + a.0 == b.0 && a.1.len() == b.1.len() && a.1.first().map(|m| m.at) == b.1.first().map(|m| m.at) +} + /// Whether a chat changed since it was last written: every message's shape (what a turn, a /// reaction, a fold, a fix can change), and the newest few word for word. fn chat_mark(b: &Bot) -> u64 { @@ -956,27 +1004,45 @@ impl State { // the chats were set apart, or one an older AnyBot wrote since — is the newer one.) let parsed = parsed.map(|mut s| { for b in s.bots.iter_mut().filter(|b| b.messages.is_empty() && b.threads.is_empty()) { + // (A damaged file is kept aside, not written over.) + let aside = |f: &std::path::Path| { + let _ = std::fs::rename(f, f.with_extension(format!("json.damaged-{}", chrono::Utc::now().timestamp()))); + }; let f = chat_path(p, b.id); - let Ok(bytes) = std::fs::read(&f) else { continue }; - match serde_json::from_slice::(&bytes) { - Ok(v) => { - b.messages = serde_json::from_value(v["messages"].clone()).unwrap_or_default(); - b.threads = serde_json::from_value(v["threads"].clone()).unwrap_or_default(); - chat_marks().lock().unwrap().insert((p.to_path_buf(), b.id), chat_mark(b)); - } - // (A damaged chat file is kept aside, not written over.) - Err(_) => { - let _ = std::fs::rename(&f, f.with_extension(format!("json.damaged-{}", chrono::Utc::now().timestamp()))); + let chat = std::fs::read(&f).ok().and_then(|bytes| serde_json::from_slice::(&bytes).inspect_err(|_| aside(&f)).ok()); + let tf = threads_path(p, b.id); + let apart = std::fs::read(&tf).ok().and_then(|bytes| serde_json::from_slice::)>>(&bytes).inspect_err(|_| aside(&tf)).ok()); + if chat.is_none() && apart.is_none() { + continue; + } + let had_apart = apart.is_some(); + let ChatIn { messages, threads: inside } = chat.unwrap_or_default(); + // 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(); + let mut threads = apart.unwrap_or_default(); + let new: Vec<_> = inside.into_iter().filter(|t| !threads.iter().any(|x| same_thread(x, t))).collect(); + threads.splice(0..0, new); + b.messages = messages.into(); + b.threads = threads.into(); + // What is on disk is what a save would write: nothing to write until it changes. + // (Inside the chat file still: the first save moves them out, once.) + if inside_empty { + chat_marks().lock().unwrap().insert((p.to_path_buf(), b.id), chat_mark(b)); + if had_apart { + chat_marks().lock().unwrap().insert((tf, b.id), threads_mark(b)); } } } - // Chats of bots that are gone. + // Chats of bots that are gone (and their earlier conversations). let live: Vec = s.bots.iter().map(|b| format!("bot-{}.json", b.id)).collect(); if let Some(dir) = p.parent() { - for e in std::fs::read_dir(dir.join("chats")).into_iter().flatten().flatten() { - let name = e.file_name().to_string_lossy().to_string(); - if name.starts_with("bot-") && name.ends_with(".json") && !live.contains(&name) { - let _ = std::fs::remove_file(e.path()); + for d in [dir.join("chats"), dir.join("chats").join("threads")] { + for e in std::fs::read_dir(d).into_iter().flatten().flatten() { + let name = e.file_name().to_string_lossy().to_string(); + if name.starts_with("bot-") && name.ends_with(".json") && !live.contains(&name) { + let _ = std::fs::remove_file(e.path()); + } } } } @@ -1058,7 +1124,38 @@ impl State { if chat_marks().lock().unwrap().get(&key) == Some(&mark) { continue; } - match serde_json::to_vec(&serde_json::json!({"messages": b.messages, "threads": b.threads})) { + // The earlier conversations first, to their own file, only when they changed. (None + // left: their file goes, but only one this AnyBot read or wrote — not one it couldn't + // read.) When it can't be written they go in the chat file, as before: nothing is lost. + let tf = threads_path(&p, b.id); + let tkey = (tf.clone(), b.id); + let known = chat_marks().lock().unwrap().get(&tkey).copied(); + let apart = if b.threads.is_empty() { + if known.is_some() { + let _ = std::fs::remove_file(&tf); + chat_marks().lock().unwrap().remove(&tkey); + } + true + } else { + let tmark = threads_mark(b); + known == Some(tmark) + || match serde_json::to_vec(&*b.threads) { + Ok(bytes) if crate::httpd::write_private(&tf, &bytes).is_ok() => { + chat_marks().lock().unwrap().insert(tkey, tmark); + true + } + // (An older copy there would come back at the next start.) + _ => { + if known.is_some() { + let _ = std::fs::remove_file(&tf); + chat_marks().lock().unwrap().remove(&tkey); + } + false + } + } + }; + let out = ChatOut { messages: &b.messages, threads: if apart { None } else { Some(&b.threads) } }; + 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); } @@ -1085,6 +1182,9 @@ impl State { for id in gone { let _ = std::fs::remove_file(chat_path(&p, id)); marks.remove(&(p.clone(), id)); + let tf = threads_path(&p, id); + let _ = std::fs::remove_file(&tf); + marks.remove(&(tf, id)); } return true; } @@ -1522,6 +1622,80 @@ mod start_tests { let _ = std::fs::remove_dir_all(&dir); } + /// A long-lived bot's earlier conversations are most of its chat: they sit in their own file, + /// and the saves while the bot works write only the current messages. A chat file from + /// before (or from an older AnyBot run in between) is read whole, nothing lost. + #[test] + fn earlier_conversations_are_not_written_again_while_a_bot_works() { + let dir = std::env::temp_dir().join(format!("anybot-threads-apart-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let p = dir.join("state.json"); + let mut st = State::samples(); + let id = st.bots[0].id; + let mut old = vec![Message::user("很久以前的問題"), Message::assistant("很久以前的回答", "x")]; + old[0].at = 1_000; + st.bots[0].threads = vec![("上個月".into(), old.clone())].into(); + st.bots[0].messages = vec![Message::user("現在的問題")].into(); + assert!(st.save_at(&p)); + let (chat, apart) = (chat_path(&p, id), threads_path(&p, id)); + assert!(!std::fs::read_to_string(&chat).unwrap().contains("很久以前"), "not in the chat file"); + assert!(std::fs::read_to_string(&apart).unwrap().contains("很久以前的回答")); + // The bot works: its chat is written again, the earlier conversations aren't. + let stamp = |f: &std::path::Path| std::fs::metadata(f).unwrap().modified().unwrap(); + let (tc, ta) = (stamp(&chat), stamp(&apart)); + std::thread::sleep(std::time::Duration::from_millis(1100)); + st.bots[0].messages.push(Message::assistant("正在處理", "x")); + assert!(st.save_at(&p)); + assert!(stamp(&chat) > tc && stamp(&apart) == ta, "only the current messages"); + let back = State::load_from(&p); + assert_eq!(back.bot(id).unwrap().messages.len(), 2); + assert_eq!(back.bot(id).unwrap().threads[0].1[1].text, "很久以前的回答"); + // Read back as written: nothing to write again. + std::thread::sleep(std::time::Duration::from_millis(1100)); + assert!(back.save_at(&p)); + assert!(stamp(&apart) == ta); + // Put aside another one: the file is written then. + st.bots[0].threads.insert(0, ("剛剛".into(), vec![Message::user("上一段")])); + assert!(st.save_at(&p)); + assert!(stamp(&apart) > ta); + assert_eq!(State::load_from(&p).bot(id).unwrap().threads.len(), 2); + + // From before they were set apart: read whole, moved out at the first save. + let before = dir.join("before").join("state.json"); + std::fs::create_dir_all(before.parent().unwrap().join("chats")).unwrap(); + let mut s2 = State::samples(); + s2.bots[0].messages = vec![Message::user("現在的問題")].into(); + std::fs::write(&before, serde_json::to_string(&State { bots: s2.bots.iter().map(|b| Bot { messages: Default::default(), threads: Default::default(), ..b.clone() }).collect(), ..s2.clone() }).unwrap()).unwrap(); + let old_file = serde_json::json!({"messages": [Message::user("現在的問題")], "threads": [["上個月", old]]}); + std::fs::write(chat_path(&before, id), old_file.to_string()).unwrap(); + let read = State::load_from(&before); + assert_eq!(read.bot(id).unwrap().threads[0].1[0].text, "很久以前的問題"); + assert!(read.save_at(&before)); + assert!(!std::fs::read_to_string(chat_path(&before, id)).unwrap().contains("很久以前"), "moved out"); + assert!(std::fs::read_to_string(threads_path(&before, id)).unwrap().contains("很久以前")); + + // An older AnyBot ran in between: it saw no earlier conversations, put a new one aside + // inside the chat file. Both are there afterwards, its new one first. + let older = serde_json::json!({"messages": [Message::user("舊版時的訊息")], "threads": [["舊版放下的", [Message::user("舊版時說的")]]]}); + std::fs::write(chat_path(&before, id), older.to_string()).unwrap(); + let merged = State::load_from(&before); + let titles: Vec<&str> = merged.bot(id).unwrap().threads.iter().map(|t| t.0.as_str()).collect(); + assert_eq!(titles, ["舊版放下的", "上個月"]); + assert!(merged.save_at(&before)); + assert!(!std::fs::read_to_string(chat_path(&before, id)).unwrap().contains("舊版時說的")); + assert_eq!(State::load_from(&before).bot(id).unwrap().threads.len(), 2, "not twice"); + + // A damaged file is kept aside, not written over; a deleted bot's goes with it. + std::fs::write(threads_path(&before, id), b"{not json").unwrap(); + let hurt = State::load_from(&before); + assert!(hurt.bot(id).unwrap().threads.is_empty()); + assert!(std::fs::read_dir(before.parent().unwrap().join("chats").join("threads")).unwrap().flatten().any(|e| e.file_name().to_string_lossy().contains("damaged"))); + st.bots.retain(|b| b.id != id); + assert!(st.save_at(&p)); + assert!(!threads_path(&p, id).exists() && !chat_path(&p, id).exists()); + let _ = std::fs::remove_dir_all(&dir); + } + /// 「儲存」 in a bot's settings puts on the bot what the person changed there, and leaves /// what the bot got while the settings were open. #[test]