對話不再無限長大:長對話較早的部分收進封存檔,只留最近約 2000 則
jenny-Host 的對話 36 000 則、95 MB:整份放在記憶體,每次存檔整份重寫,每格畫面整份排過一次。 現在這段對話超過 2500 則、Bot 閒著(沒在做事、沒卡片、沒在通話)時,切在使用者說的一句之前、 不越過最新的摘要(Bot 讀到的不變),較早的寫進 chats/archive/bot-<id>/<起點>-<則數>.json (500 則一個、寫好就不再改、寫完同步到磁碟),記憶體和聊天檔只留最近約 2000 則。 - 整段對話的編號 = 封存數 + 記憶體裡的位置:手機的 index、載入更早的、表情回應、搜尋的前往都照整段算, 手機頁面和伺服器不用改。 - 桌面:最上面「更早的 N 則已封存/載入更早的」,載入的只看不存(畫在另一個 id 下); 搜尋到封存裡的那則就載入前後各 100 則並捲過去,下面有「載入後面的」。 - 搜尋、熱度圖、所有檔案:封存的話第一次在背景讀成精簡清單(chatarchive::said)。 - 開新對話、/rewind、/fork、匯出、備份、搬到大腦用整段;清除連封存一起;附件清理算進封存的附件 (讀不齊或有保留的封存時整晚不清)。分享匯出入、支線、團隊成員不帶封存欄位。 - 封存數、第一句、指紋(最後一則的時間)跟訊息寫在同一個聊天檔:任何時候停掉都對得上。 整理只在 App 自己啟動時做,只對聊天檔有寫封存數的 Bot;退役的封存只在對得上的那一個沒存好時找回, 對得上之後才刪其他的;舊版 AnyBot 寫的聊天檔照資料夾接回(緊接著才接); 讀不齊的、不屬於現在對話的封存移到 .kept- 資料夾,永遠不刪。設定讀不到時什麼都不刪;刪 Bot 時才刪它的封存。 - 寫不進去 10 分鐘後再試,不每格重試。 獨立審查(乾淨脈絡)四輪:第一輪 3 個 P0(停在聊天檔和設定之間、別的指令讀設定時清理、換對話後沒存好) 和 4 個 P1;第二輪 1 個 P0(兩個退役資料夾搬錯)、1 個 P1(舊版改寫聊天檔);第三輪 1 個 P0(設定讀不到時全刪); 第四輪剩 1 個 P1(沒接回的舊封存在下次封存被蓋掉),已修。每個都有測試。 已驗證: cargo test 全綠(938 通過,含 featuremap::、layout_audit::);新測試 chatarchive::、 a_long_chat_keeps_its_newest_and_comes_back_whole、a_stop_at_any_moment_loses_no_archived_message、 the_right_archive_comes_back_and_an_old_writer_loses_nothing、an_archived_head_is_still_the_same_conversation_everywhere; verify-anybot 實跑兩次(36 000 則:聊天檔 28 MB → 1.5 MB、68 個封存檔、手機 API 跨封存載入編號連續、 搜尋找得到封存、重開後還在;證據 target/verify-anybot/20261127-172809、20261127-175512)。 未驗證: 手機頁面點搜尋結果跳到很舊的一則(手機本來就只留最近的,提示「那則訊息太早了」,未改); 顯示大腦的另一台電腦上載入封存(設計上不提供);第二階段「過去的對話」(threads,88 MB)還沒拆。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
66e8f944f6
commit
8b9bb34f6f
|
|
@ -8,6 +8,7 @@
|
||||||
- `threads-name` 取名:對話欄每列滑過出現 ✎(目前的那列一直有),也可以雙擊目前的那列、或右鍵「重新命名」;按 Enter 或點別處就存,Esc 不存,空白回到用第一句話。名字跟著對話:收進過去的對話、再打開都帶著;「/fork」沒給名字時叫「分岔:這個名字」(分岔的再分岔不會疊成「分岔:分岔:」)。一行、最多 40 字。也可以在聊天裡請 Bot 取(「這段叫網站改版」「把報價單那段改叫 Q3」):它用 `list_conversations` 看有哪些、`rename_conversation` 改名。名字不會放進 Bot 讀的對話裡(它要看用 `list_conversations`)。
|
- `threads-name` 取名:對話欄每列滑過出現 ✎(目前的那列一直有),也可以雙擊目前的那列、或右鍵「重新命名」;按 Enter 或點別處就存,Esc 不存,空白回到用第一句話。名字跟著對話:收進過去的對話、再打開都帶著;「/fork」沒給名字時叫「分岔:這個名字」(分岔的再分岔不會疊成「分岔:分岔:」)。一行、最多 40 字。也可以在聊天裡請 Bot 取(「這段叫網站改版」「把報價單那段改叫 Q3」):它用 `list_conversations` 看有哪些、`rename_conversation` 改名。名字不會放進 Bot 讀的對話裡(它要看用 `list_conversations`)。
|
||||||
- `threads-phone` 手機:聊天標題列 🕘(⋯ ›「對話」同一個)開「對話」:「目前的對話」那列點了取名;下面過去的對話(最新 20 段,更多時標題寫共幾段),點一段選「回到這段對話」或「重新命名」(大腦的 AnyBot 還是舊版時沒有命名)。取了名的對話,標題下那行寫名字。Bot 工作中「回到這段對話」不換,說要等它做完(還在整理摘要、支線或交辦還沒回報時,大腦不換、在聊天裡說)。團隊成員看不到 🕘(換對話、取名只有擁有者和管理員)。
|
- `threads-phone` 手機:聊天標題列 🕘(⋯ ›「對話」同一個)開「對話」:「目前的對話」那列點了取名;下面過去的對話(最新 20 段,更多時標題寫共幾段),點一段選「回到這段對話」或「重新命名」(大腦的 AnyBot 還是舊版時沒有命名)。取了名的對話,標題下那行寫名字。Bot 工作中「回到這段對話」不換,說要等它做完(還在整理摘要、支線或交辦還沒回報時,大腦不換、在聊天裡說)。團隊成員看不到 🕘(換對話、取名只有擁有者和管理員)。
|
||||||
- `threads-list` 收進與找回:「開始新對話」(Bot 選單、手機 ✎、對話欄的 +)把目前的收進過去的對話,最多留 50 段,再多最舊的就沒了。換對話和開始新對話一樣,這段的目標(/goal)和計畫(/plan)停掉、「還原上一個答案」不帶過去,停之前在這段留一行說停了哪個、回來再打 /goal 或 /plan 接著做(以前會被帶到另一段)。搜尋到過去對話裡的訊息時,那筆寫那段的名字(電腦「Bot · 名字」,手機在 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 報價」;重開後兩個名字都在;清掉後回到第一句話「首頁要改」,標題下只寫模型。
|
- **為過去的對話改名、重開還在、清掉名字**(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` 是「第三季報價」,原本那段收進過去的對話。
|
- **請 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-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`(命名、回到的參數;成員不行)。
|
- 自動測試:`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 共用的,不分對話;專案要分得乾淨(各自的記憶和檔案),開不同的 Bot。
|
||||||
- 目標和計畫只屬於一段對話:換過去再回來不會自己接著做,照那段留的一行再打一次。
|
- 目標和計畫只屬於一段對話:換過去再回來不會自己接著做,照那段留的一行再打一次。
|
||||||
- Bot 答應的換對話要等支線、同事的回報都回來,可能過幾分鐘才換;那之前按停止、清除聊天記錄,或在它閒著時又傳新訊息,就不換。
|
- Bot 答應的換對話要等支線、同事的回報都回來,可能過幾分鐘才換;那之前按停止、清除聊天記錄,或在它閒著時又傳新訊息,就不換。
|
||||||
|
|
|
||||||
171
src/app.rs
171
src/app.rs
|
|
@ -201,6 +201,18 @@ pub fn set_doc_folders(v: Vec<String>) {
|
||||||
*DOC_FOLDERS.write().unwrap() = v;
|
*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<Vec<Message>>,
|
||||||
|
}
|
||||||
|
|
||||||
pub struct App {
|
pub struct App {
|
||||||
state: State,
|
state: State,
|
||||||
/// 智慧模式 (/smart): one switch for every live turn — a turn reads it at each step, so
|
/// 智慧模式 (/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)>,
|
delivered: Vec<(u64, String)>,
|
||||||
/// Save at the next frame (a typed message just entered a chat), not up to 2 s later.
|
/// Save at the next frame (a typed message just entered a chat), not up to 2 s later.
|
||||||
save_now: bool,
|
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<u64, OlderView>,
|
||||||
|
/// 封存 that couldn't be written, and when (tried again later, not every frame).
|
||||||
|
archive_failed: HashMap<u64, Instant>,
|
||||||
/// A save writing on its own thread, and the typed messages it carries (see `delivered`).
|
/// A save writing on its own thread, and the typed messages it carries (see `delivered`).
|
||||||
saving: Option<(Receiver<bool>, Vec<(u64, String)>)>,
|
saving: Option<(Receiver<bool>, Vec<(u64, String)>)>,
|
||||||
/// 設定 › 一般 › 文件索引: the path being typed for a new folder.
|
/// 設定 › 一般 › 文件索引: 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.
|
// 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 demo = screenshot.is_some() && std::env::var("ANYBOT_SHOT_REAL").is_err();
|
||||||
let mut state = if demo { State::demo() } else { State::load() };
|
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 {
|
if demo {
|
||||||
// ANYBOT_SHOT_PINS=n: the grid at the top shows n bots (the main one and n-1 pinned).
|
// 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::<usize>().ok()) {
|
if let Some(n) = std::env::var("ANYBOT_SHOT_PINS").ok().and_then(|v| v.parse::<usize>().ok()) {
|
||||||
|
|
@ -580,6 +604,8 @@ impl App {
|
||||||
delivered: vec![],
|
delivered: vec![],
|
||||||
save_now: false,
|
save_now: false,
|
||||||
saving: None,
|
saving: None,
|
||||||
|
older: HashMap::new(),
|
||||||
|
archive_failed: HashMap::new(),
|
||||||
doc_new: String::new(),
|
doc_new: String::new(),
|
||||||
doc_new_bad: false,
|
doc_new_bad: false,
|
||||||
interrupted,
|
interrupted,
|
||||||
|
|
@ -3974,6 +4000,9 @@ impl App {
|
||||||
members: vec![],
|
members: vec![],
|
||||||
threads: Default::default(),
|
threads: Default::default(),
|
||||||
chat_title: String::new(),
|
chat_title: String::new(),
|
||||||
|
archived: 0,
|
||||||
|
head_title: String::new(),
|
||||||
|
archive_mark: 0,
|
||||||
chat_after: None,
|
chat_after: None,
|
||||||
context_tokens: agent::DEFAULT_CONTEXT_TOKENS,
|
context_tokens: agent::DEFAULT_CONTEXT_TOKENS,
|
||||||
model_limits: Default::default(),
|
model_limits: Default::default(),
|
||||||
|
|
@ -4280,6 +4309,7 @@ impl App {
|
||||||
self.stop(id);
|
self.stop(id);
|
||||||
if let Some(b) = self.state.bot_mut(id) {
|
if let Some(b) = self.state.bot_mut(id) {
|
||||||
b.messages.clear();
|
b.messages.clear();
|
||||||
|
b.forget_archive();
|
||||||
b.chat_title.clear();
|
b.chat_title.clear();
|
||||||
}
|
}
|
||||||
self.mark();
|
self.mark();
|
||||||
|
|
@ -4321,6 +4351,81 @@ impl App {
|
||||||
egui::CentralPanel::default().frame(Frame::new().fill(p.pane)).show(root, |ui| self.chat_column(ui));
|
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 chat of the bot picked: its top, the messages, the input (in the middle, or beside
|
||||||
/// the 工作流 canvas).
|
/// the 工作流 canvas).
|
||||||
fn chat_column(&mut self, ui: &mut egui::Ui) {
|
fn chat_column(&mut self, ui: &mut egui::Ui) {
|
||||||
|
|
@ -4368,9 +4473,10 @@ impl App {
|
||||||
// 之间 14px,紧组内部才用 6~8)。
|
// 之间 14px,紧组内部才用 6~8)。
|
||||||
ui.spacing_mut().item_spacing.y = if self.state.dense { 11.0 } else { 14.0 };
|
ui.spacing_mut().item_spacing.y = if self.state.dense { 11.0 } else { 14.0 };
|
||||||
ui.add_space(18.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.empty_state(ui, &bot);
|
||||||
}
|
}
|
||||||
|
self.archived_head(ui, ctx, &bot);
|
||||||
let n = bot.messages.len();
|
let n = bot.messages.len();
|
||||||
for (i, m) in bot.messages.iter().enumerate() {
|
for (i, m) in bot.messages.iter().enumerate() {
|
||||||
let last = i + 1 == n;
|
let last = i + 1 == n;
|
||||||
|
|
@ -4378,7 +4484,7 @@ impl App {
|
||||||
let top = ui.cursor().top();
|
let top = ui.cursor().top();
|
||||||
self.chat_message(ui, ctx, &bot, m, last);
|
self.chat_message(ui, ctx, &bot, m, last);
|
||||||
// 搜尋 → 那則訊息: scroll to it and light it for a moment.
|
// 搜尋 → 那則訊息: 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 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();
|
let age = g.since.elapsed().as_secs_f32();
|
||||||
if age < crate::find::GOTO_SCROLL_SECS {
|
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()));
|
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::<Vec<_>>().join("\n");
|
let pages: String = self.state.pages.iter().map(|p| p.body.as_str()).collect::<Vec<_>>().join("\n");
|
||||||
let sweep_files = !self.demo && !self.mir.on;
|
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 || {
|
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);
|
let n = crate::attach::sweep(&kept, &pages);
|
||||||
if n > 0 {
|
if n > 0 {
|
||||||
log::info!("AnyBot:清掉 {n} 個聊天已經不用的檔案");
|
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<u64> = 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) {
|
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 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.
|
// the work log can let them go; still writing, the next one waits for it.
|
||||||
if let Some((rx, _)) = &self.saving {
|
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).
|
/// 匯出文字記錄: the chat as Markdown (tool steps folded in as quotes).
|
||||||
fn transcript_markdown(b: &Bot) -> String {
|
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"));
|
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 {
|
match m.role {
|
||||||
Role::User => {
|
Role::User => {
|
||||||
s.push_str(&format!("**你**:{}\n", m.text));
|
s.push_str(&format!("**你**:{}\n", m.text));
|
||||||
|
|
|
||||||
|
|
@ -193,6 +193,10 @@ impl App {
|
||||||
b.routines.clear();
|
b.routines.clear();
|
||||||
b.branches.clear();
|
b.branches.clear();
|
||||||
b.threads.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.regen_undo.clear();
|
||||||
b.draft.clear();
|
b.draft.clear();
|
||||||
b.goal = None;
|
b.goal = None;
|
||||||
|
|
|
||||||
|
|
@ -189,7 +189,8 @@ impl App {
|
||||||
if chat {
|
if chat {
|
||||||
let Some(b) = self.state.bot_mut(bot_id) else { return };
|
let Some(b) = self.state.bot_mut(bot_id) else { return };
|
||||||
// The whole conversation first goes to 過去的對話: a rewind can be taken back.
|
// 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());
|
copy.iter_mut().for_each(|m| m.images.clear());
|
||||||
let title = format!("退回前:{}", first_line(&words, 24));
|
let title = format!("退回前:{}", first_line(&words, 24));
|
||||||
b.threads.insert(0, (title.clone(), copy));
|
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 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 title = format!("{FORK_PREFIX}{what}");
|
||||||
let Some(b) = self.state.bot_mut(bot_id) else { return };
|
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.)
|
// (Like any conversation put aside: its words, not its screenshots in memory.)
|
||||||
copy.iter_mut().for_each(|m| m.images.clear());
|
copy.iter_mut().for_each(|m| m.images.clear());
|
||||||
b.threads.insert(0, (title.clone(), copy));
|
b.threads.insert(0, (title.clone(), copy));
|
||||||
|
|
|
||||||
|
|
@ -65,13 +65,15 @@ impl App {
|
||||||
let mut seen = std::collections::HashSet::new();
|
let mut seen = std::collections::HashSet::new();
|
||||||
let mut files = vec![];
|
let mut files = vec![];
|
||||||
for b in &self.state.bots {
|
for b in &self.state.bots {
|
||||||
for m in b.messages.iter().chain(b.threads.iter().flat_map(|(_, m)| m.iter())) {
|
// (The archived head's files too, once its words are read: chatarchive::said.)
|
||||||
for a in &m.attachments {
|
let said = crate::chatarchive::said(b.id, b.archived).unwrap_or_default();
|
||||||
if a.path.is_empty() || !seen.insert(a.path.clone()) {
|
let archived = said.iter().flat_map(|s| s.files.iter().map(move |a| (s.at, a)));
|
||||||
continue;
|
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) {
|
||||||
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})));
|
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));
|
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 seen = std::collections::HashSet::new();
|
||||||
let mut files = vec![];
|
let mut files = vec![];
|
||||||
for b in &self.state.bots {
|
for b in &self.state.bots {
|
||||||
let all = b.messages.iter().chain(b.threads.iter().flat_map(|(_, m)| m.iter()));
|
// (The archived head's files too, once its words are read: chatarchive::said.)
|
||||||
for m in all {
|
let said = crate::chatarchive::said(b.id, b.archived).unwrap_or_default();
|
||||||
for a in &m.attachments {
|
let archived = said.iter().flat_map(|s| s.files.iter().map(move |a| (s.at, a)));
|
||||||
if a.path.is_empty() || !seen.insert(a.path.clone()) {
|
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)));
|
||||||
continue;
|
for (at, a) in archived.chain(live) {
|
||||||
}
|
if a.path.is_empty() || !seen.insert(a.path.clone()) {
|
||||||
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 });
|
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));
|
files.sort_by_key(|f| std::cmp::Reverse(f.at));
|
||||||
|
|
|
||||||
|
|
@ -48,7 +48,8 @@ fn copy_own(to: &mut State, from: &State) {
|
||||||
to.motion = from.motion.clone();
|
to.motion = from.motion.clone();
|
||||||
}
|
}
|
||||||
/// Bot fields the brain alone changes (its chat, and what a turn leaves behind).
|
/// 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.
|
/// Stands in for a key or token the brain doesn't hand out.
|
||||||
pub const REDACTED: &str = "••••(已設定,在大腦上)";
|
pub const REDACTED: &str = "••••(已設定,在大腦上)";
|
||||||
|
|
||||||
|
|
@ -2543,10 +2544,11 @@ impl App {
|
||||||
let moving: Vec<&Bot> = local
|
let moving: Vec<&Bot> = local
|
||||||
.bots
|
.bots
|
||||||
.iter()
|
.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();
|
.collect();
|
||||||
for b in moving.iter().copied() {
|
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);
|
v["id"] = json!(0);
|
||||||
ops.push(json!({"op": "bot_add", "bot": v}));
|
ops.push(json!({"op": "bot_add", "bot": v}));
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -323,7 +323,7 @@ impl App {
|
||||||
// 外觀: the phone wears the desktop's theme and colours.
|
// 外觀: 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);
|
(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 {
|
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.)
|
// (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);
|
(&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) {
|
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.)
|
// (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.messages.insert(b.id, msgs);
|
||||||
view.deliveries.insert(b.id, deliveries);
|
view.deliveries.insert(b.id, deliveries);
|
||||||
view.approvals.extend(self.phone_cards(b));
|
view.approvals.extend(self.phone_cards(b));
|
||||||
|
|
@ -741,6 +741,7 @@ impl App {
|
||||||
self.stop(bot);
|
self.stop(bot);
|
||||||
if let Some(b) = self.state.bot_mut(bot) {
|
if let Some(b) = self.state.bot_mut(bot) {
|
||||||
b.messages.clear();
|
b.messages.clear();
|
||||||
|
b.forget_archive();
|
||||||
b.chat_title.clear();
|
b.chat_title.clear();
|
||||||
}
|
}
|
||||||
self.mark();
|
self.mark();
|
||||||
|
|
@ -828,9 +829,13 @@ impl App {
|
||||||
let mut st = self.state.clone();
|
let mut st = self.state.clone();
|
||||||
// The backup is for the bots; this computer's own keys to the relay and phones stay here.
|
// The backup is for the bots; this computer's own keys to the relay and phones stay here.
|
||||||
st.remote = Default::default();
|
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());
|
let (note, busy) = (self.rm.note.clone(), self.rm.busy.clone());
|
||||||
std::thread::spawn(move || {
|
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) {
|
*note.lock().unwrap() = match remote::backup_now(&s, &bytes) {
|
||||||
Ok(n) => format!("已備份({},已加密)", crate::cloudbox::human(n as u64)),
|
Ok(n) => format!("已備份({},已加密)", crate::cloudbox::human(n as u64)),
|
||||||
Err(e) => e,
|
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());
|
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::<ApprovalAnswer>();
|
||||||
|
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<u64> = 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]
|
#[test]
|
||||||
fn only_chat_models_are_offered() {
|
fn only_chat_models_are_offered() {
|
||||||
assert!(super::chats("grok-4.7") && super::chats("claude-opus-5-5") && super::chats("gpt-5-mini"));
|
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
|
/// 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
|
/// 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.
|
/// 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<u64, String>, start: usize, end: usize) -> (Vec<serde_json::Value>, Vec<serde_json::Value>) {
|
fn phone_messages(&self, b: &Bot, names: &HashMap<u64, String>, start: usize, end: usize) -> (Vec<serde_json::Value>, Vec<serde_json::Value>) {
|
||||||
let end = end.min(b.messages.len());
|
let end = end.min(b.conversation_len());
|
||||||
let start = start.min(end);
|
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<u64, String>, start: usize, end: usize) -> (Vec<serde_json::Value>, Vec<serde_json::Value>) {
|
||||||
// 交付確認: the ✓ marks go beside the chat, not inside the messages — a phone opening
|
// 交付確認: 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
|
// 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).
|
// whole chat on every report (see remote::chat_for).
|
||||||
|
|
@ -1492,7 +1583,7 @@ impl App {
|
||||||
deliveries.push(json!({"id": id, "delivery": d, "seen": seen}));
|
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).
|
// 支線: its record, for the card (and the report's label).
|
||||||
if m.branch != 0 {
|
if m.branch != 0 {
|
||||||
if let Some(r) = b.branches.iter().find(|r| r.id == m.branch) {
|
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).
|
// through those alone, and the button then did nothing at all).
|
||||||
"older" => match self.state.bot(bot) {
|
"older" => match self.state.bot(bot) {
|
||||||
Some(x) => {
|
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 count = b["count"].as_u64().unwrap_or(60).clamp(1, 120) as usize;
|
||||||
let names: HashMap<u64, String> = self.state.bots.iter().map(|y| (y.id, y.name.clone())).collect();
|
let names: HashMap<u64, String> = self.state.bots.iter().map(|y| (y.id, y.name.clone())).collect();
|
||||||
// (Steps take room: walk back until `count` show, or the chat begins.)
|
// (Steps take room: walk back until `count` show, or the chat begins.)
|
||||||
|
|
@ -1923,7 +2015,9 @@ impl App {
|
||||||
done("已重新啟動")
|
done("已重新啟動")
|
||||||
}
|
}
|
||||||
"react" => {
|
"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");
|
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) {
|
if emoji.is_empty() || emoji.chars().count() > 8 || self.state.bot(bot).map(|x| idx >= x.messages.len()).unwrap_or(true) {
|
||||||
return fail("找不到這則訊息");
|
return fail("找不到這則訊息");
|
||||||
|
|
|
||||||
|
|
@ -607,6 +607,10 @@ impl App {
|
||||||
self.open_thread(h.bot, i);
|
self.open_thread(h.bot, i);
|
||||||
}
|
}
|
||||||
self.select_bot(&ctx, h.bot);
|
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() });
|
self.goto = Some(crate::find::Goto { bot: h.bot, index: h.index, at: h.at, since: Instant::now() });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -189,7 +189,8 @@ impl App {
|
||||||
}
|
}
|
||||||
self.show_settings = false;
|
self.show_settings = false;
|
||||||
self.select_bot(ctx, bot);
|
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() });
|
self.goto = Some(crate::find::Goto { bot, index, at, since: Instant::now() });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -883,7 +883,7 @@ pub fn apply(state: &mut State, bot_id: u64, name: &str, args: &str) -> Outcome
|
||||||
"list_conversations" => {
|
"list_conversations" => {
|
||||||
let Some(b) = state.bot(bot_id) else { return err("找不到這個 Bot".into()) };
|
let Some(b) = state.bot(bot_id) else { return err("找不到這個 Bot".into()) };
|
||||||
let now_ms = crate::model::now_ms();
|
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() {
|
if b.threads.is_empty() {
|
||||||
lines.push("沒有過去的對話。".into());
|
lines.push("沒有過去的對話。".into());
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -1053,6 +1053,9 @@ pub fn apply(state: &mut State, bot_id: u64, name: &str, args: &str) -> Outcome
|
||||||
members: vec![],
|
members: vec![],
|
||||||
threads: Default::default(),
|
threads: Default::default(),
|
||||||
chat_title: String::new(),
|
chat_title: String::new(),
|
||||||
|
archived: 0,
|
||||||
|
head_title: String::new(),
|
||||||
|
archive_mark: 0,
|
||||||
chat_after: None,
|
chat_after: None,
|
||||||
context_tokens: model::default_context_tokens(),
|
context_tokens: model::default_context_tokens(),
|
||||||
model_limits: Default::default(),
|
model_limits: Default::default(),
|
||||||
|
|
|
||||||
|
|
@ -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-<id>/`, named `<first index>-<count>.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<Segment> {
|
||||||
|
let mut out: Vec<Segment> = 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<Message> {
|
||||||
|
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<Message> {
|
||||||
|
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<Message> {
|
||||||
|
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<Message> {
|
||||||
|
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-<id>.kept-<ms>`. 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<i64> {
|
||||||
|
(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<i64>) -> 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<u64, (usize, i64)>) {
|
||||||
|
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<u64>)> {
|
||||||
|
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<Segment> = 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<usize> {
|
||||||
|
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<Vec<String>> {
|
||||||
|
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<crate::attach::Attachment>,
|
||||||
|
}
|
||||||
|
|
||||||
|
type SaidCache = std::collections::HashMap<u64, (usize, std::sync::Arc<Vec<Said>>)>;
|
||||||
|
|
||||||
|
fn said_cache() -> &'static std::sync::Mutex<SaidCache> {
|
||||||
|
static M: std::sync::OnceLock<std::sync::Mutex<SaidCache>> = 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<std::collections::HashMap<u64, u64>> {
|
||||||
|
static M: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<u64, u64>>> = 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<std::collections::HashSet<u64>> {
|
||||||
|
static M: std::sync::OnceLock<std::sync::Mutex<std::collections::HashSet<u64>>> = 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<std::sync::Arc<Vec<Said>>> {
|
||||||
|
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<Message> {
|
||||||
|
(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<_>>(), vec![(0, 500), (500, 500), (1_000, 100)]);
|
||||||
|
let got = read_in(&d, 480, 520);
|
||||||
|
assert_eq!(got.iter().map(|m| m.at).collect::<Vec<_>>(), (481..=520).collect::<Vec<i64>>());
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
26
src/find.rs
26
src/find.rs
|
|
@ -18,6 +18,7 @@ pub struct Hit {
|
||||||
/// None: the open conversation; Some(i): 過去的對話 number i.
|
/// None: the open conversation; Some(i): 過去的對話 number i.
|
||||||
pub thread: Option<usize>,
|
pub thread: Option<usize>,
|
||||||
/// Where in that conversation, and when it was said (0 for old messages without a time).
|
/// 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 index: usize,
|
||||||
pub at: i64,
|
pub at: i64,
|
||||||
pub mine: bool,
|
pub mine: bool,
|
||||||
|
|
@ -43,8 +44,9 @@ fn snippet(text: &str, lower_at: usize, lower: &str) -> String {
|
||||||
s
|
s
|
||||||
}
|
}
|
||||||
|
|
||||||
fn in_messages(bot: u64, thread: Option<usize>, msgs: &[Message], q: &str, out: &mut Vec<Hit>) {
|
fn in_messages(bot: u64, thread: Option<usize>, msgs: &[Message], first: usize, q: &str, out: &mut Vec<Hit>) {
|
||||||
for (index, m) in msgs.iter().enumerate() {
|
for (k, m) in msgs.iter().enumerate() {
|
||||||
|
let index = first + k;
|
||||||
if !matches!(m.role, Role::User | Role::Assistant) || m.summary {
|
if !matches!(m.role, Role::User | Role::Assistant) || m.summary {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
@ -68,9 +70,20 @@ pub fn search(bots: &[Bot], query: &str) -> (Vec<Hit>, bool) {
|
||||||
}
|
}
|
||||||
let mut out = vec![];
|
let mut out = vec![];
|
||||||
for b in bots {
|
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() {
|
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.
|
// 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<Hit>, bool) {
|
||||||
/// What the chats amount to, cheaply: a search is done again only when this or the query changes.
|
/// 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.)
|
/// (How many messages, the newest one's time, and which conversations are the open ones.)
|
||||||
pub fn stamp(bots: &[Bot]) -> (usize, i64, i64) {
|
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 {
|
for b in bots {
|
||||||
n += b.messages.len() + b.threads.iter().map(|t| t.1.len()).sum::<usize>() + b.threads.len();
|
n += b.conversation_len() + b.threads.iter().map(|t| t.1.len()).sum::<usize>() + b.threads.len();
|
||||||
newest = newest.max(b.messages.last().map(|m| m.at).unwrap_or(0));
|
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));
|
open = open.wrapping_mul(31).wrapping_add(b.messages.first().map(|m| m.at).unwrap_or(0));
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -546,6 +546,11 @@ pub const ROWS: &[(&str, &str, &str)] = &[
|
||||||
("電腦工具", "Computer tools", "コンピューターツール"),
|
("電腦工具", "Computer tools", "コンピューターツール"),
|
||||||
("記憶", "Memories", "記憶"),
|
("記憶", "Memories", "記憶"),
|
||||||
("過去的對話", "Past chats", "過去の会話"),
|
("過去的對話", "Past chats", "過去の会話"),
|
||||||
|
("更早的 {n} 則已封存", "{n} earlier messages archived", "それ以前の {n} 件はアーカイブ済み"),
|
||||||
|
("載入更早的", "Load earlier", "以前を読み込む"),
|
||||||
|
("以上是封存的訊息", "Archived messages above", "ここまではアーカイブ済みのメッセージ"),
|
||||||
|
("後面還有 {n} 則已封存", "{n} more archived messages after these", "この後にアーカイブ済みが {n} 件"),
|
||||||
|
("載入後面的", "Load later", "続きを読み込む"),
|
||||||
("已關閉", "Off", "オフ"),
|
("已關閉", "Off", "オフ"),
|
||||||
("已開啟", "On", "オン"),
|
("已開啟", "On", "オン"),
|
||||||
("使用的模型", "Model", "モデル"),
|
("使用的模型", "Model", "モデル"),
|
||||||
|
|
|
||||||
|
|
@ -16,6 +16,7 @@ mod botbrowser;
|
||||||
mod browser;
|
mod browser;
|
||||||
mod cloudbox;
|
mod cloudbox;
|
||||||
mod channels;
|
mod channels;
|
||||||
|
mod chatarchive;
|
||||||
mod checkpoint;
|
mod checkpoint;
|
||||||
mod computer;
|
mod computer;
|
||||||
mod desktop;
|
mod desktop;
|
||||||
|
|
|
||||||
375
src/model.rs
375
src/model.rs
|
|
@ -254,6 +254,17 @@ struct ChatOut<'a> {
|
||||||
messages: &'a [Message],
|
messages: &'a [Message],
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
threads: Option<&'a [(String, Vec<Message>)]>,
|
threads: Option<&'a [(String, Vec<Message>)]>,
|
||||||
|
/// 封存: 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
|
/// 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<Message>,
|
messages: Vec<Message>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
threads: Vec<(String, Vec<Message>)>,
|
threads: Vec<(String, Vec<Message>)>,
|
||||||
|
#[serde(default)]
|
||||||
|
archived: Option<usize>,
|
||||||
|
#[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<u64, (usize, i64)> {
|
||||||
|
archived_read().lock().unwrap_or_else(|e| e.into_inner()).clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn archived_read() -> &'static std::sync::Mutex<std::collections::HashMap<u64, (usize, i64)>> {
|
||||||
|
static M: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<u64, (usize, i64)>>> = std::sync::OnceLock::new();
|
||||||
|
M.get_or_init(Default::default)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The same earlier conversation (title, length, when it began).
|
/// 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) {
|
for m in b.messages.iter().rev().take(4) {
|
||||||
serde_json::to_string(m).unwrap_or_default().hash(&mut h);
|
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()
|
h.finish()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -322,6 +353,10 @@ fn chat_marks() -> &'static std::sync::Mutex<std::collections::HashMap<(PathBuf,
|
||||||
M.get_or_init(Default::default)
|
M.get_or_init(Default::default)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn is_zero_usize(n: &usize) -> bool {
|
||||||
|
*n == 0
|
||||||
|
}
|
||||||
|
|
||||||
fn is_zero_i64(n: &i64) -> bool {
|
fn is_zero_i64(n: &i64) -> bool {
|
||||||
*n == 0
|
*n == 0
|
||||||
}
|
}
|
||||||
|
|
@ -478,6 +513,19 @@ pub struct Bot {
|
||||||
/// It goes with the conversation into 過去的對話 and comes back with it.
|
/// It goes with the conversation into 過去的對話 and comes back with it.
|
||||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||||
pub chat_title: String,
|
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
|
/// 換對話 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.
|
/// follows it in this conversation, is over — never under a running turn.
|
||||||
#[serde(skip)]
|
#[serde(skip)]
|
||||||
|
|
@ -620,14 +668,94 @@ pub const THREADS_KEPT: usize = 50;
|
||||||
impl Bot {
|
impl Bot {
|
||||||
/// What the open conversation is called: the name given to it, or its first line.
|
/// What the open conversation is called: the name given to it, or its first line.
|
||||||
pub fn chat_name(&self) -> String {
|
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<usize> {
|
||||||
|
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,
|
/// 開始新對話: 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.
|
/// not the screenshots held in memory), and the chat is empty and nameless.
|
||||||
pub fn put_aside(&mut self) {
|
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() {
|
if !self.messages.is_empty() {
|
||||||
let title = self.chat_name();
|
let title = named;
|
||||||
let mut msgs = std::mem::take(&mut self.messages).into_inner();
|
let mut msgs = std::mem::take(&mut self.messages).into_inner();
|
||||||
msgs.iter_mut().for_each(|m| m.images.clear());
|
msgs.iter_mut().for_each(|m| m.images.clear());
|
||||||
self.threads.insert(0, (title, msgs));
|
self.threads.insert(0, (title, msgs));
|
||||||
|
|
@ -1169,7 +1297,32 @@ impl State {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let had_apart = apart.is_some();
|
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
|
// 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).
|
// apart, or ones an older AnyBot put aside since (newer: they go first).
|
||||||
let inside_empty = inside.is_empty();
|
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) {
|
match serde_json::to_vec(&out) {
|
||||||
Ok(bytes) if crate::httpd::write_private(&chat_path(&p, b.id), &bytes).is_ok() => {
|
Ok(bytes) if crate::httpd::write_private(&chat_path(&p, b.id), &bytes).is_ok() => {
|
||||||
chat_marks().lock().unwrap().insert(key, mark);
|
chat_marks().lock().unwrap().insert(key, mark);
|
||||||
|
|
@ -1370,6 +1523,9 @@ impl State {
|
||||||
let tf = threads_path(&p, id);
|
let tf = threads_path(&p, id);
|
||||||
let _ = std::fs::remove_file(&tf);
|
let _ = std::fs::remove_file(&tf);
|
||||||
marks.remove(&(tf, id));
|
marks.remove(&(tf, id));
|
||||||
|
if let Some(dir) = p.parent() {
|
||||||
|
crate::chatarchive::remove_all(dir, id);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
@ -1454,7 +1610,8 @@ impl State {
|
||||||
let mut n = 0;
|
let mut n = 0;
|
||||||
let mut reid: Vec<(u64, u64)> = vec![];
|
let mut reid: Vec<(u64, u64)> = vec![];
|
||||||
for b in &other.bots {
|
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;
|
continue;
|
||||||
}
|
}
|
||||||
let mut b = b.clone();
|
let mut b = b.clone();
|
||||||
|
|
@ -1533,6 +1690,9 @@ impl State {
|
||||||
members: vec![],
|
members: vec![],
|
||||||
threads: Default::default(),
|
threads: Default::default(),
|
||||||
chat_title: String::new(),
|
chat_title: String::new(),
|
||||||
|
archived: 0,
|
||||||
|
head_title: String::new(),
|
||||||
|
archive_mark: 0,
|
||||||
chat_after: None,
|
chat_after: None,
|
||||||
context_tokens: default_context_tokens(),
|
context_tokens: default_context_tokens(),
|
||||||
model_limits: Default::default(),
|
model_limits: Default::default(),
|
||||||
|
|
@ -1745,6 +1905,211 @@ pub fn bot_computer_dir(bot_id: u64) -> PathBuf {
|
||||||
mod start_tests {
|
mod start_tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
fn long_chat(n: usize, summary_at: usize) -> Vec<Message> {
|
||||||
|
(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::<Vec<_>>(), msgs.iter().map(|m| m.at).collect::<Vec<_>>());
|
||||||
|
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」的設定檔載入時換成安靜一次;
|
||||||
/// 之後自己選回「跟著 Bot」就照你選的(不會每次開都被換掉)。
|
/// 之後自己選回「跟著 Bot」就照你選的(不會每次開都被換掉)。
|
||||||
#[test]
|
#[test]
|
||||||
|
|
|
||||||
|
|
@ -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.)
|
// (The owner's conversations, by name or count, aren't a member's.)
|
||||||
o.remove("threads_total");
|
o.remove("threads_total");
|
||||||
o.remove("chat_title");
|
o.remove("chat_title");
|
||||||
|
o.remove("head_title");
|
||||||
o.remove("chat_named");
|
o.remove("chat_named");
|
||||||
o.insert("queued".into(), json!([]));
|
o.insert("queued".into(), json!([]));
|
||||||
o.remove("goal");
|
o.remove("goal");
|
||||||
|
|
|
||||||
|
|
@ -1162,6 +1162,9 @@ fn seed_first() -> i32 {
|
||||||
members: vec![],
|
members: vec![],
|
||||||
threads: Default::default(),
|
threads: Default::default(),
|
||||||
chat_title: String::new(),
|
chat_title: String::new(),
|
||||||
|
archived: 0,
|
||||||
|
head_title: String::new(),
|
||||||
|
archive_mark: 0,
|
||||||
chat_after: None,
|
chat_after: None,
|
||||||
memories: vec![],
|
memories: vec![],
|
||||||
speak_replies: false,
|
speak_replies: false,
|
||||||
|
|
|
||||||
|
|
@ -41,7 +41,7 @@ pub fn export(b: &Bot) -> String {
|
||||||
let mut v = serde_json::to_value(b).unwrap_or(Value::Null);
|
let mut v = serde_json::to_value(b).unwrap_or(Value::Null);
|
||||||
if let Value::Object(m) = &mut v {
|
if let Value::Object(m) = &mut v {
|
||||||
// (Its 可以用的電腦 are this account's computers by name; its 草稿 is unsent words: neither travels.)
|
// (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);
|
m.remove(k);
|
||||||
}
|
}
|
||||||
if let Some(Value::Array(routines)) = m.get_mut("routines") {
|
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![]));
|
m.insert("messages".into(), Value::Array(vec![]));
|
||||||
// Never import another person's grants, local workdir, threads or memories — nor its
|
// 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).
|
// 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);
|
m.remove(k);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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 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![];
|
let mut messages = vec![];
|
||||||
for b in &st.bots {
|
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));
|
messages.extend(b.messages.iter().filter(|m| counts(m)).map(|m| m.at));
|
||||||
for (_, t) in b.threads.iter() {
|
for (_, t) in b.threads.iter() {
|
||||||
messages.extend(t.iter().filter(|m| counts(m)).map(|m| m.at));
|
messages.extend(t.iter().filter(|m| counts(m)).map(|m| m.at));
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue