過去的對話也不再無限長大:每段有自己的封存資料夾,開新對話直接交出資料夾

第二階段。8b9bb34 之後,開新對話會把整段(含封存)讀回記憶體、寫進過去的對話檔:一次多 95 MB;
jenny-Host 的過去的對話檔已經 88 MB,開 App 就整份讀進記憶體。

- 過去的對話改成 Thread(名稱, 記憶體裡的訊息, 封存):沒封存的照舊寫成 [名稱, 訊息](舊版讀得懂),
  有封存的多一欄 {則數, 指紋, 第一句, 資料夾}。
- 開新對話:封存資料夾改名交給那段(bot-<id>.t-<時間>),不讀回、不複製;換回來時改名交回。
- /fork、/rewind 的副本:封存用硬連結(檔案寫好就不改),不占空間。
- 很長的過去對話(舊版放下的、從備份回來的):閒著時切出自己的封存資料夾。
- 搜尋、熱度圖、所有檔案、附件清理、備份、搬到大腦:過去對話的封存一起算;搜尋的位置照那段整段算。
- 啟動整理:過去對話的資料夾只有在「過去的對話全讀到、沒有壞掉的副本、目前的封存對得上」時才清沒人指名的;
  換對話後沒存好就停:資料夾照指紋接回(目前的也是它就用硬連結);目前的資料夾放的是別段的:移到 .kept- 不刪,接回對的。
  舊版 AnyBot 讀不懂而改名 .damaged- 的過去對話檔:新版讀得懂就併回來,寫進檔案後才改名 .recovered-。
- 資料夾名稱不重複;換不過去(資料夾不見)時不先停掉目標和計畫、搜尋不跳;list_conversations 照整段算則數。

獨立審查(乾淨脈絡)三輪:第一輪 3 個 P1(壞掉的過去對話檔讓資料夾全被清、/fork 副本打開後停掉資料夾丟失、
兩個檔中間停掉接錯封存);第二輪 1 個 P1(從壞檔找回的沒被存);第三輪無 P0/P1,剩 1 個 P2(找回的重複出現)也已修。

已驗證: cargo test 全綠(940 通過,含 featuremap::、layout_audit::);新測試
  past_conversations_keep_their_old_shape_and_long_ones_get_an_archive、
  past_conversations_lose_no_archive_to_damage_or_a_stop,改寫 a_stop_at_any_moment_loses_no_archived_message、
  a_long_chat_keeps_its_newest_and_comes_back_whole;verify-anybot 實跑(目前和過去各 30 000 則:兩個檔都 1.5 MB,
  開新對話資料夾直接交出、兩段都 30 000 則、搜尋兩段的封存都找得到、換回舊對話封存跟著回來、重開一致;
  證據 target/verify-anybot/20261127-182610)。
未驗證: 舊版 AnyBot 實際讀新格式後再升級(用改名 .damaged- 的測試代替);jenny-Host 實機(接著部署)。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
王性驊 2026-11-27 18:43:48 +08:00
parent 8b9bb34f6f
commit d807bbe91a
14 changed files with 679 additions and 164 deletions

View File

@ -8,7 +8,7 @@
- `threads-name` 取名:對話欄每列滑過出現 ✎(目前的那列一直有),也可以雙擊目前的那列、或右鍵「重新命名」;按 Enter 或點別處就存,Esc 不存,空白回到用第一句話。名字跟著對話:收進過去的對話、再打開都帶著;「/fork」沒給名字時叫「分岔:這個名字」(分岔的再分岔不會疊成「分岔:分岔:」)。一行、最多 40 字。也可以在聊天裡請 Bot 取(「這段叫網站改版」「把報價單那段改叫 Q3」):它用 `list_conversations` 看有哪些、`rename_conversation` 改名。名字不會放進 Bot 讀的對話裡(它要看用 `list_conversations`)。
- `threads-phone` 手機:聊天標題列 🕘(⋯ ›「對話」同一個)開「對話」:「目前的對話」那列點了取名;下面過去的對話(最新 20 段,更多時標題寫共幾段),點一段選「回到這段對話」或「重新命名」(大腦的 AnyBot 還是舊版時沒有命名)。取了名的對話,標題下那行寫名字。Bot 工作中「回到這段對話」不換,說要等它做完(還在整理摘要、支線或交辦還沒回報時,大腦不換、在聊天裡說)。團隊成員看不到 🕘(換對話、取名只有擁有者和管理員)。
- `threads-list` 收進與找回:「開始新對話」(Bot 選單、手機 ✎、對話欄的 +)把目前的收進過去的對話,最多留 50 段,再多最舊的就沒了。換對話和開始新對話一樣,這段的目標(/goal)和計畫(/plan)停掉、「還原上一個答案」不帶過去,停之前在這段留一行說停了哪個、回來再打 /goal 或 /plan 接著做(以前會被帶到另一段)。搜尋到過去對話裡的訊息時,那筆寫那段的名字(電腦「Bot · 名字」,手機在 Bot 名字旁)。在另一台裝置換過、收過或改過名,清單位置變了,改名和換回去(對話清單、手機搜尋結果都一樣)照樣找到你點的那段(認它最後一則的時間和顯示的名字);那段已經被打開或改了名就不動;為目前的對話取名時,別台已經換成另一段也不動。
- `threads-archive` 封存:目前的對話超過 2500 則、Bot 閒著(沒在做事、沒卡片等你、沒在通話)時,較早的收進封存檔(500 則一個,寫好不再改),留最近約 2000 則;切在你說的一句之前、不越過最新的摘要,Bot 讀到的不變。聊天最上面「更早的 N 則已封存」「載入更早的」(一次 500 則,只看:按表情、⋯ 不會改到它)。搜尋也搜封存(第一次在背景讀,讀好結果自己補上),點到就載入前後各 100 則捲過去,下面有「載入後面的」。手機的編號和「載入更早的對話」照整段算。開新對話、/rewind、/fork、匯出、備份、搬到大腦用整段;清除聊天記錄連封存一起清;沒取名的名字照舊是整段第一句。
- `threads-archive` 封存:目前的對話超過 2500 則、Bot 閒著(沒在做事、沒卡片等你、沒在通話)時,較早的收進封存檔(500 則一個,寫好不再改),留最近約 2000 則;切在你說的一句之前、不越過最新的摘要,Bot 讀到的不變。聊天最上面「更早的 N 則已封存」「載入更早的」(一次 500 則,只看:按表情、⋯ 不會改到它)。搜尋也搜封存(第一次在背景讀,讀好結果自己補上),點到就載入前後各 100 則捲過去,下面有「載入後面的」。手機的編號和「載入更早的對話」照整段算。開新對話時封存資料夾直接交給那段過去的對話(不讀回、不複製),換回來再交回;/fork、/rewind 的副本用硬連結共用封存;很長的過去對話(舊版放下的)閒著時也切出自己的封存;過去對話的封存一樣搜得到。匯出、備份、搬到大腦用整段;清除聊天記錄連封存一起清;沒取名的名字照舊是整段第一句。
## 使用者怎麼到

View File

@ -507,7 +507,7 @@ impl App {
// 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());
crate::chatarchive::sweep(data, &state.bots, &crate::model::archived_on_disk(), &crate::model::threads_known());
}
}
if demo {
@ -4898,12 +4898,18 @@ impl App {
/// 過去的對話 number `i` becomes the open one (the open one goes to the top of the list); not
/// while the bot works (it says so).
fn open_thread(&mut self, id: u64, i: usize) {
fn open_thread(&mut self, id: u64, i: usize) -> bool {
// Not while something is still to land in the open conversation (the same everywhere a
// conversation is opened): it would land in this one.
if let Some(why) = self.chat_pending(id, true) {
self.notice = Some(why);
return;
return false;
}
// (One whose archive folder is gone isn't opened: nothing is left first.)
let missing = self.state.bot(id).and_then(|b| b.threads.get(i)).is_some_and(|t| !t.2.is_empty() && !crate::chatarchive::thread_dir(id, &t.2.folder).exists());
if !self.mir.on && missing {
self.notice = Some(t("這段對話較早的封存檔案不見了,先不換過去"));
return false;
}
if !self.mir.on && self.state.bot(id).is_some_and(|b| i < b.threads.len()) {
self.leave_conversation(id);
@ -4914,9 +4920,13 @@ impl App {
let (at, was) = (t.and_then(|t| t.1.last()).map(|m| m.at).unwrap_or(0), t.map(|t| t.0.clone()).unwrap_or_default());
self.mirror_act(serde_json::json!({"bot": id, "action": "restore", "index": i, "at": at, "was": was}));
} else if let Some(b) = self.state.bot_mut(id) {
b.open_thread(i);
if !b.open_thread(i) {
self.mark();
return false;
}
}
self.mark();
true
}
/// 重新命名 a conversation: the open one (`None`) or 過去的對話 number `i` (on a screen of a
@ -7358,19 +7368,20 @@ impl App {
// by 重新產生, uploads waiting in a composer): the rest of the chats' folders is swept.
let mut kept: std::collections::HashSet<String> = Default::default();
for b in self.state.bots.iter().chain(self.state.branch_bots.iter()) {
let all = b.messages.iter().chain(b.threads.iter().flat_map(|(_, m)| m.iter())).chain(b.regen_undo.iter());
let all = b.messages.iter().chain(b.threads.iter().flat_map(|t| t.1.iter())).chain(b.regen_undo.iter());
kept.extend(all.flat_map(|m| m.attachments.iter().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 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();
let mut archives: Vec<(PathBuf, usize)> = self.state.bots.iter().filter(|b| b.archived > 0).map(|b| (crate::chatarchive::dir(b.id), b.archived)).collect();
archives.extend(self.state.bots.iter().flat_map(|b| b.threads.iter().filter(|t| !t.2.is_empty()).map(|t| (crate::chatarchive::thread_dir(b.id, &t.2.folder), t.2.archived))));
std::thread::spawn(move || {
let mut kept = kept;
let mut whole = true;
for (id, n) in archives {
match crate::chatarchive::attachment_paths(id, n) {
for (d, n) in archives {
match crate::chatarchive::attachment_paths_in(&d, n) {
Some(paths) => kept.extend(paths),
None => whole = false,
}
@ -7412,14 +7423,28 @@ impl App {
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 long_thread = |b: &Bot| b.threads.iter().any(|t| t.2.is_empty() && crate::chatarchive::cut_point(&t.1).is_some());
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))
.filter(|b| (crate::chatarchive::cut_point(&b.messages).is_some() || long_thread(b)) && !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 {
// 過去的對話 too: a long one gets its own archive (one at a time, a frame each).
if let Some(b) = self.state.bot_mut(id) {
if let Some(i) = b.threads.iter().position(|t| t.2.is_empty() && crate::chatarchive::cut_point(&t.1).is_some()) {
let mut t = b.threads[i].clone();
if crate::chatarchive::archive_thread(id, &mut t) {
b.threads[i] = t;
self.dirty = true;
} else {
self.archive_failed.insert(id, Instant::now());
}
continue;
}
}
if self.state.bot_mut(id).and_then(|b| b.archive_head()).is_none() {
self.archive_failed.insert(id, Instant::now());
continue;

View File

@ -189,11 +189,10 @@ impl App {
if chat {
let Some(b) = self.state.bot_mut(bot_id) else { return };
// The whole conversation first goes to 過去的對話: a rewind can be taken back.
// (Whole: its archived head too.)
let mut copy = crate::chatarchive::whole(b);
copy.iter_mut().for_each(|m| m.images.clear());
// (Whole: its archived head too — linked, not read back.)
let title = format!("退回前:{}", first_line(&words, 24));
b.threads.insert(0, (title.clone(), copy));
let copy = crate::chatarchive::copy_as_thread(b, title.clone());
b.threads.insert(0, copy);
b.threads.truncate(50);
b.messages.truncate(i);
b.regen_undo.clear();
@ -233,11 +232,10 @@ impl App {
let what = if name.is_empty() { b.chat_name().trim_start_matches(FORK_PREFIX).to_string() } else { name.to_string() };
let title = format!("{FORK_PREFIX}{what}");
let Some(b) = self.state.bot_mut(bot_id) else { return };
// (Whole: its archived head too.)
let mut copy = crate::chatarchive::whole(b);
// (Like any conversation put aside: its words, not its screenshots in memory.)
copy.iter_mut().for_each(|m| m.images.clear());
b.threads.insert(0, (title.clone(), copy));
// (Whole: its archived head too — linked, not read back. Like any conversation put
// aside: its words, not its screenshots in memory.)
let copy = crate::chatarchive::copy_as_thread(b, title.clone());
b.threads.insert(0, copy);
b.threads.truncate(50);
self.goal_note(bot_id, &format!("已分岔:這段對話到這裡為止存了一份「{title}」。接著在這裡做;要回到這一點走另一條路,從 Bot 的選單 › 過去的對話 打開它(這邊會自動收進過去的對話,不會不見)。"));
self.mark();

View File

@ -66,9 +66,10 @@ impl App {
let mut files = vec![];
for b in &self.state.bots {
// (The archived head's files too, once its words are read: chatarchive::said.)
let said = crate::chatarchive::said(b.id, b.archived).unwrap_or_default();
let archived = said.iter().flat_map(|s| s.files.iter().map(move |a| (s.at, a)));
let live = b.messages.iter().chain(b.threads.iter().flat_map(|(_, m)| m.iter())).flat_map(|m| m.attachments.iter().map(move |a| (m.at, a)));
let mut said: Vec<std::sync::Arc<Vec<crate::chatarchive::Said>>> = crate::chatarchive::said(b.id, b.archived).into_iter().collect();
said.extend(b.threads.iter().filter_map(|t| crate::chatarchive::said_thread(b.id, &t.2)));
let archived = said.iter().flat_map(|l| l.iter()).flat_map(|s| s.files.iter().map(move |a| (s.at, a)));
let live = b.messages.iter().chain(b.threads.iter().flat_map(|t| t.1.iter())).flat_map(|m| m.attachments.iter().map(move |a| (m.at, a)));
for (at, a) in archived.chain(live) {
if a.path.is_empty() || !seen.insert(a.path.clone()) {
continue;
@ -85,9 +86,10 @@ impl App {
let mut files = vec![];
for b in &self.state.bots {
// (The archived head's files too, once its words are read: chatarchive::said.)
let said = crate::chatarchive::said(b.id, b.archived).unwrap_or_default();
let archived = said.iter().flat_map(|s| s.files.iter().map(move |a| (s.at, a)));
let live = b.messages.iter().chain(b.threads.iter().flat_map(|(_, m)| m.iter())).flat_map(|m| m.attachments.iter().map(move |a| (m.at, a)));
let mut said: Vec<std::sync::Arc<Vec<crate::chatarchive::Said>>> = crate::chatarchive::said(b.id, b.archived).into_iter().collect();
said.extend(b.threads.iter().filter_map(|t| crate::chatarchive::said_thread(b.id, &t.2)));
let archived = said.iter().flat_map(|l| l.iter()).flat_map(|s| s.files.iter().map(move |a| (s.at, a)));
let live = b.messages.iter().chain(b.threads.iter().flat_map(|t| t.1.iter())).flat_map(|m| m.attachments.iter().map(move |a| (m.at, a)));
for (at, a) in archived.chain(live) {
if a.path.is_empty() || !seen.insert(a.path.clone()) {
continue;

View File

@ -204,8 +204,8 @@ fn msg_sig(m: &Message) -> u64 {
fn threads_sig(b: &Bot) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
for (t, msgs) in &b.threads {
(t, msgs.len()).hash(&mut h);
for crate::model::Thread(t, msgs, a) in b.threads.iter() {
(t, msgs.len(), a.archived).hash(&mut h);
}
h.finish()
}

View File

@ -195,7 +195,7 @@ impl App {
let last_at = |m: &[Message]| m.last().map(|m| m.at).unwrap_or(0);
// (The rows: which, name, the grey line, the time to find it by.)
let mut rows: Vec<(Option<usize>, String, String, i64)> = vec![(None, bot.chat_name(), if bot.messages.is_empty() { t("還沒有訊息") } else { t("目前的對話") }, 0)];
for (i, (title, msgs)) in bot.threads.iter().enumerate() {
for (i, crate::model::Thread(title, msgs, _)) in bot.threads.iter().enumerate() {
let at = last_at(msgs);
rows.push((Some(i), title.clone(), if at > 0 { crate::pages::ago(at, now) } else { String::new() }, at));
}

View File

@ -480,7 +480,7 @@ impl App {
"routines": b.routines.iter().map(|r| json!({"id": r.id, "title": r.title, "paused": r.paused, "when": crate::appctl::routine_when(r)})).collect::<Vec<_>>(),
// 過去的對話, newest first (the newest 20; it gave the oldest 20, oldest first), and
// what the open one is called.
"threads": b.threads.iter().enumerate().take(20).map(|(i, (title, msgs))| json!({"index": i, "title": title, "count": msgs.len(), "at": msgs.last().map(|m| m.at).unwrap_or(0)})).collect::<Vec<_>>(),
"threads": b.threads.iter().enumerate().take(20).map(|(i, t)| json!({"index": i, "title": t.0, "count": t.len(), "at": t.1.last().map(|m| m.at).unwrap_or(0)})).collect::<Vec<_>>(),
"threads_total": b.threads.len(),
"chat_title": b.chat_name(), "chat_named": !b.chat_title.is_empty(),
// The sidebar's sections, the colour by name (the editor), what is queued while it works.
@ -2452,7 +2452,7 @@ impl App {
"runs": r.runs.iter().rev().take(5).map(|x| json!({"line": crate::routines::describe_run(x, &r.schedule.timezone), "bad": matches!(x.outcome, crate::routines::RunOutcome::Failed | crate::routines::RunOutcome::Interrupted), "sends": x.sends})).collect::<Vec<_>>(),
"target": crate::appctl::target_words(r),
})).collect::<Vec<_>>(),
"threads": b.threads.iter().enumerate().map(|(i, (title, msgs))| json!({"index": i, "title": title, "count": msgs.len(), "at": msgs.last().map(|m| m.at).unwrap_or(0)})).collect::<Vec<_>>(),
"threads": b.threads.iter().enumerate().map(|(i, t)| json!({"index": i, "title": t.0, "count": t.len(), "at": t.1.last().map(|m| m.at).unwrap_or(0)})).collect::<Vec<_>>(),
"files": files,
})
}
@ -2584,7 +2584,7 @@ mod phone_act_tests {
let bot = app.state.bots[0].id;
{
let b = app.state.bot_mut(bot).unwrap();
b.threads = Vec::new().into();
b.threads = Default::default();
b.messages = vec![Message { at: 100, ..Message::user("網站首頁") }].into();
}
let sig = app.remote_signature();

View File

@ -604,11 +604,14 @@ impl App {
self.notice = Some(why);
} else {
if let Some(i) = h.thread {
self.open_thread(h.bot, i);
if !self.open_thread(h.bot, i) {
return;
}
}
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) {
// (One in the archive — the open conversation's, or the one just brought back:
// the stretch around it is shown first.)
if 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() });

View File

@ -888,9 +888,11 @@ pub fn apply(state: &mut State, bot_id: u64, name: &str, args: &str) -> Outcome
lines.push("沒有過去的對話。".into());
} else {
lines.push(format!("過去的對話({} 段,新的在前):", b.threads.len()));
for (t, msgs) in b.threads.iter() {
for th in b.threads.iter() {
let (t, msgs) = (&th.0, &th.1);
let count = th.len();
let at = msgs.last().map(|m| m.at).unwrap_or(0);
lines.push(format!("- 「{t}」{},{} 則", if at > 0 { format!(" {}", crate::pages::ago(at, now_ms)) } else { String::new() }, msgs.len()));
lines.push(format!("- 「{t}」{},{} 則", if at > 0 { format!(" {}", crate::pages::ago(at, now_ms)) } else { String::new() }, count));
}
}
lines.push("使用者自己從聊天右上的「對話」(手機標題列 🕘)換;請你換時用 switch_conversation。".into());

View File

@ -112,10 +112,50 @@ pub fn whole(b: &crate::model::Bot) -> Vec<Message> {
/// 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 {
if b.archived == 0 && b.threads.iter().all(|t| t.2.is_empty()) {
return b.clone();
}
crate::model::Bot { messages: whole(b).into(), archived: 0, head_title: String::new(), archive_mark: 0, ..b.clone() }
let threads: Vec<crate::model::Thread> = b
.threads
.iter()
.map(|t| {
if t.2.is_empty() {
return t.clone();
}
let mut msgs = read_in(&thread_dir(b.id, &t.2.folder), 0, t.2.archived);
if msgs.len() < t.2.archived {
// (Said where it happens, not left to look whole.)
let line = format!("(這段對話較早的 {} 則封存只讀回 {} 則。)", t.2.archived, msgs.len());
msgs.push(Message { note: true, ..Message::assistant(&line, "") });
}
msgs.extend(t.1.iter().cloned());
crate::model::Thread::new(t.0.clone(), msgs)
})
.collect();
crate::model::Bot { messages: whole(b).into(), archived: 0, head_title: String::new(), archive_mark: 0, threads: threads.into(), ..b.clone() }
}
/// 封存 for one of 過去的對話 that is long (one put aside before there was an archive, or
/// brought back from a backup): its head goes to an archive folder of its own, as for the open
/// conversation. Only a thread with no archive yet. True when it moved some.
pub fn archive_thread(bot: u64, t: &mut crate::model::Thread) -> bool {
if !t.2.is_empty() {
return false;
}
let Some(cut) = cut_point(&t.1) else { return false };
let folder = fresh_thread_folder(bot);
let d = thread_dir(bot, &folder);
if let Err(e) = write_in(&d, 0, &t.1[..cut]) {
log::warn!("AnyBot:過去的對話封存寫不進去({e})");
let _ = std::fs::remove_dir_all(&d);
return false;
}
let head_title = crate::model::auto_title(&t.1);
let mark = t.1[cut - 1].at;
t.1.drain(..cut);
t.2 = crate::model::ThreadArchive { archived: cut, mark, head_title, folder };
log::info!("AnyBot:過去的對話「{}」較早的 {cut} 則收進封存", t.0);
true
}
/// The archive's files go with the conversation they belonged to (it was put aside, cleared,
@ -189,36 +229,71 @@ pub fn goes_on_from(mark: i64, first: Option<i64>) -> bool {
/// 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)>) {
/// when it is deleted, see State::write_at). For a bot whose chat file says what it archived
/// (`on_disk`: how many, the last one's time):
/// - one of 過去的對話 whose folder is missing while the open conversation's folder is exactly
/// it (a stop right after it was opened again, before the save): the folder goes back to it;
/// - the open conversation's folder missing: the retired one, or one of 過去的對話's that none
/// of them names (when they were all read: `known`), that is exactly what the chat file
/// means comes back (newest first, one at most) — one a past conversation names (a /fork's
/// linked copy looks the same) is never taken;
/// - once the open conversation's archive is the one the file means (or it has none): other
/// retired folders go, folders of 過去的對話 none of them names go (when all were read), and
/// files past the count go when their messages are in the chat again.
/// Anything else is left. Folders kept aside (`.kept-`) are never touched.
pub fn sweep(data: &Path, bots: &[crate::model::Bot], on_disk: &std::collections::HashMap<u64, (usize, i64)>, known: &std::collections::HashSet<u64>) {
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>)> {
// (bot, stamp, kind): kind 'r' retired, 't' one of 過去的對話's.
let parse = |name: &str| -> Option<(u64, u64, char)> {
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)),
}
let (id, kind, ms) = if let Some((id, ms)) = rest.split_once(".retired-") { (id, 'r', ms) } else { let (id, ms) = rest.split_once(".t-")?; (id, 't', ms) };
Some((id.parse().ok()?, ms.parse().ok()?, kind))
};
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));
let threads_known = known.contains(&b.id);
let named: Vec<&str> = b.threads.iter().filter(|t| !t.2.is_empty()).map(|t| t.2.folder.as_str()).collect();
// One of 過去的對話 opened again, then a stop: its folder is the open one's.
// (When the open conversation's folder is also exactly the open one's — a /fork's copy
// opened, then a stop — it is linked, not taken away from the open one.)
for t in b.threads.iter().filter(|t| !t.2.is_empty()) {
let theirs = root.join(&t.2.folder);
if !theirs.exists() && live.exists() && is_the_one(&live, t.2.archived, t.2.mark) {
log::warn!("AnyBot:過去的對話「{}」的封存從目前的對話資料夾接回(上次換對話後沒存好就停了)", t.0);
if n > 0 && is_the_one(&live, n, mark) {
link_into(&live, &theirs);
} else {
let _ = std::fs::rename(&live, &theirs);
}
}
}
let mut mine: Vec<(u64, char, PathBuf, String)> = entries
.iter()
.filter_map(|(name, path)| parse(name).filter(|(id, _, _)| *id == b.id).map(|(_, ms, k)| (ms, k, path.clone(), name.clone())))
.collect();
mine.sort_by_key(|m| std::cmp::Reverse(m.0));
let unnamed = |m: &(u64, char, PathBuf, String)| m.1 == 'r' || (threads_known && !named.contains(&m.3.as_str()));
// The open conversation's folder holding another conversation's archive (a stop between
// the two files of a save): that one is kept aside for good, and the right one comes.
if n > 0 && live.exists() && !is_the_one(&live, n, mark) && mine.iter().any(|m| m.2.exists() && is_the_one(&m.2, n, mark)) {
let kept = live.with_file_name(format!("bot-{}.kept-{}", b.id, crate::model::now_ms()));
log::warn!("AnyBot:Bot {} 的對話資料夾放的是別段的封存,移到 {}(不刪)", b.id, kept.display());
forget_said_at(&live);
let _ = std::fs::rename(&live, &kept);
}
if n > 0 && !live.exists() {
if let Some(i) = retired.iter().position(|(_, r)| is_the_one(r, n, mark)) {
let (_, r) = retired.remove(i);
if let Some(i) = mine.iter().position(|m| m.2.exists() && is_the_one(&m.2, n, mark)) {
let (_, _, r, name) = mine.remove(i);
log::warn!("AnyBot:Bot {} 的對話封存從 {} 找回(上次換對話後沒存好就停了)", b.id, r.display());
// (One a past conversation names, or might — 過去的對話 not all read — stays
// where it is: linked.)
if name.contains(".retired-") || (threads_known && !named.contains(&name.as_str())) {
let _ = std::fs::rename(&r, &live);
} else {
link_into(&r, &live);
}
}
}
let settled = if n == 0 { true } else { is_the_one(&live, n, mark) };
@ -226,8 +301,8 @@ pub fn sweep(data: &Path, bots: &[crate::model::Bot], on_disk: &std::collections
log::warn!("AnyBot:Bot {} 的對話封存跟聊天檔對不上({n} 則),先不整理", b.id);
continue;
}
for (_, r) in retired {
let _ = std::fs::remove_dir_all(r);
for m in mine.iter().filter(|m| m.2.exists() && unnamed(m)) {
let _ = std::fs::remove_dir_all(&m.2);
}
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);
@ -267,14 +342,98 @@ pub fn keep_strays(dir: &Path, from: usize, msgs: &[Message]) {
/// 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-");
let (retired, thread) = (format!("bot-{bot}.retired-"), format!("bot-{bot}.t-"));
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 name = e.file_name().to_string_lossy().to_string();
if name.starts_with(&retired) || name.starts_with(&thread) {
let _ = std::fs::remove_dir_all(e.path());
}
}
}
/// A folder name for one of 過去的對話's archive that no folder has: `bot-<id>.t-<ms>`, the
/// time moved on while one is there (two in the same millisecond, a clock set back).
fn fresh_thread_folder(bot: u64) -> String {
let mut ms = crate::model::now_ms();
loop {
let name = format!("bot-{bot}.t-{ms}");
if !dir(bot).with_file_name(&name).exists() {
return name;
}
ms += 1;
}
}
/// Hard links of `from`'s files in a new folder `to` (copies where links can't be made).
fn link_into(from: &Path, to: &Path) -> bool {
if to.exists() {
return false;
}
crate::httpd::ensure_private_dir(to);
for s in segments_in(from) {
let Some(name) = s.path.file_name() else { return false };
let target = to.join(name);
if std::fs::hard_link(&s.path, &target).is_err() && std::fs::copy(&s.path, &target).is_err() {
let _ = std::fs::remove_dir_all(to);
return false;
}
}
true
}
/// The folder of one of 過去的對話's archive (`folder` as its ThreadArchive names it).
pub fn thread_dir(bot: u64, folder: &str) -> PathBuf {
dir(bot).with_file_name(folder)
}
/// 開始新對話: the open conversation's archive folder becomes the one of 過去的對話 it goes
/// to — renamed, nothing read or copied. Its new name, or None when it couldn't be renamed.
pub fn hand_to_thread(bot: u64) -> Option<String> {
let d = dir(bot);
forget_said_at(&d);
let name = fresh_thread_folder(bot);
std::fs::rename(&d, d.with_file_name(&name)).ok().map(|_| name)
}
/// One of 過去的對話 opened again: its archive folder becomes the open conversation's.
pub fn take_from_thread(bot: u64, folder: &str) -> bool {
let (from, to) = (thread_dir(bot, folder), dir(bot));
if to.exists() {
return false;
}
forget_said_at(&from);
std::fs::rename(&from, &to).is_ok()
}
/// A thread's archive that couldn't be taken back: kept aside for good.
pub fn keep_thread_aside(bot: u64, folder: &str) -> PathBuf {
let from = thread_dir(bot, folder);
forget_said_at(&from);
let to = from.with_file_name(format!("bot-{bot}.kept-{}", crate::model::now_ms()));
let _ = std::fs::rename(&from, &to);
to
}
/// /fork, /rewind: a copy of the open conversation's archive for the copy in 過去的對話 — hard
/// links (the files never change), so it costs no room. Its folder name, or None.
pub fn link_copy(bot: u64) -> Option<String> {
let name = fresh_thread_folder(bot);
link_into(&dir(bot), &thread_dir(bot, &name)).then_some(name)
}
/// The open conversation as one of 過去的對話 (/fork, /rewind): its messages in memory, and its
/// archive linked (or, when that can't be done, read back whole).
pub fn copy_as_thread(b: &crate::model::Bot, title: String) -> crate::model::Thread {
let tail = |msgs: Vec<Message>| msgs.into_iter().map(|mut m| { m.images.clear(); m }).collect::<Vec<_>>();
if b.archived > 0 {
if let Some(folder) = link_copy(b.id) {
let arch = crate::model::ThreadArchive { archived: b.archived, mark: b.archive_mark, head_title: b.head_title.clone(), folder };
return crate::model::Thread(title, tail(b.messages.to_vec()), arch);
}
}
crate::model::Thread::new(title, tail(whole(b)))
}
/// 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 {
@ -297,8 +456,8 @@ pub fn cut_point(msgs: &[Message]) -> Option<usize> {
/// 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);
pub fn attachment_paths_in(d: &Path, archived: usize) -> Option<Vec<String>> {
let msgs = read_in(d, 0, archived);
(msgs.len() == archived).then(|| msgs.iter().flat_map(|m| m.attachments.iter().map(|a| a.path.clone())).collect())
}
@ -315,27 +474,31 @@ pub struct Said {
pub files: Vec<crate::attach::Attachment>,
}
type SaidCache = std::collections::HashMap<u64, (usize, std::sync::Arc<Vec<Said>>)>;
type SaidCache = std::collections::HashMap<PathBuf, (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();
/// Each archive folder's generation: up when it is renamed or retired, so a read that started
/// before doesn't put another conversation's words back under that name.
fn said_epoch() -> &'static std::sync::Mutex<std::collections::HashMap<PathBuf, u64>> {
static M: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<PathBuf, 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;
forget_said_at(&dir(bot));
}
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();
fn forget_said_at(d: &Path) {
said_cache().lock().unwrap_or_else(|e| e.into_inner()).remove(d);
*said_epoch().lock().unwrap_or_else(|e| e.into_inner()).entry(d.to_path_buf()).or_default() += 1;
}
fn said_reading() -> &'static std::sync::Mutex<std::collections::HashSet<PathBuf>> {
static M: std::sync::OnceLock<std::sync::Mutex<std::collections::HashSet<PathBuf>>> = std::sync::OnceLock::new();
M.get_or_init(Default::default)
}
@ -346,24 +509,34 @@ 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
/// A bot's open conversation's archived words, ready to search (see said_in).
pub fn said(bot: u64, archived: usize) -> Option<std::sync::Arc<Vec<Said>>> {
said_in(&dir(bot), archived)
}
/// One of 過去的對話's archived words (see said_in).
pub fn said_thread(bot: u64, t: &crate::model::ThreadArchive) -> Option<std::sync::Arc<Vec<Said>>> {
said_in(&thread_dir(bot, &t.folder), t.archived)
}
/// An archive folder's 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>>> {
pub fn said_in(d: &Path, 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();
let have = said_cache().lock().unwrap_or_else(|e| e.into_inner()).get(d).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) {
if !said_reading().lock().unwrap_or_else(|e| e.into_inner()).insert(d.to_path_buf()) {
return None;
}
let d = dir(bot);
let epoch = said_epoch().lock().unwrap_or_else(|e| e.into_inner()).get(&bot).copied().unwrap_or(0);
let d = d.to_path_buf();
let epoch = said_epoch().lock().unwrap_or_else(|e| e.into_inner()).get(&d).copied().unwrap_or(0);
std::thread::spawn(move || {
let (from, mut list) = match have {
Some((n, l)) if n < archived => (n, (*l).clone()),
@ -376,10 +549,10 @@ pub fn said(bot: u64, archived: usize) -> Option<std::sync::Arc<Vec<Said>>> {
}
}
}
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)));
if said_epoch().lock().unwrap_or_else(|e| e.into_inner()).get(&d).copied().unwrap_or(0) == epoch {
said_cache().lock().unwrap_or_else(|e| e.into_inner()).insert(d.clone(), (archived, std::sync::Arc::new(list)));
}
said_reading().lock().unwrap_or_else(|e| e.into_inner()).remove(&bot);
said_reading().lock().unwrap_or_else(|e| e.into_inner()).remove(&d);
SAID_READY.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
});
None
@ -451,7 +624,7 @@ mod tests {
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());
sweep(&data, &[seven], &[(7, (1_000, c[999].at))].into_iter().collect(), &Default::default());
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);

View File

@ -62,6 +62,18 @@ fn in_messages(bot: u64, thread: Option<usize>, msgs: &[Message], first: usize,
}
}
/// An archive's words that have `q` in them.
fn said_hits(bot: u64, thread: Option<usize>, said: &[crate::chatarchive::Said], q: &str, out: &mut Vec<Hit>) {
for s in said {
let lower = s.text.to_lowercase();
if let Some(at) = lower.find(q) {
out.push(Hit { bot, thread, 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, thread, index: s.index, at: s.at, mine: s.mine, file: true, snippet: f.name.clone() });
}
}
}
/// Every message that has `query` in it, newest first, and whether there were more than LIMIT.
pub fn search(bots: &[Bot], query: &str) -> (Vec<Hit>, bool) {
let q = query.trim().to_lowercase();
@ -72,18 +84,15 @@ pub fn search(bots: &[Bot], query: &str) -> (Vec<Hit>, bool) {
for b in bots {
// 封存: 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() });
}
}
said_hits(b.id, None, &said, &q, &mut out);
}
in_messages(b.id, None, &b.messages, b.archived, &q, &mut out);
for (i, (_, msgs)) in b.threads.iter().enumerate() {
in_messages(b.id, Some(i), msgs, 0, &q, &mut out);
for (i, t) in b.threads.iter().enumerate() {
// (Its archived head too, once read; its place counts from the conversation's start.)
if let Some(said) = crate::chatarchive::said_thread(b.id, &t.2) {
said_hits(b.id, Some(i), &said, &q, &mut out);
}
in_messages(b.id, Some(i), &t.1, t.2.archived, &q, &mut out);
}
}
// Newest first; messages without a time keep their order, after the dated ones.
@ -99,7 +108,7 @@ pub fn stamp(bots: &[Bot]) -> (usize, i64, i64) {
// (An archive's words that came ready count as a change: the search runs again with them.)
let (mut n, mut newest, mut open) = (crate::chatarchive::said_generation() as usize, 0, 0i64);
for b in bots {
n += b.conversation_len() + b.threads.iter().map(|t| t.1.len()).sum::<usize>() + b.threads.len();
n += b.conversation_len() + b.threads.iter().map(|t| t.len()).sum::<usize>() + b.threads.len();
newest = newest.max(b.messages.last().map(|m| m.at).unwrap_or(0));
open = open.wrapping_mul(31).wrapping_add(b.messages.first().map(|m| m.at).unwrap_or(0));
}

View File

@ -551,6 +551,7 @@ pub const ROWS: &[(&str, &str, &str)] = &[
("以上是封存的訊息", "Archived messages above", "ここまではアーカイブ済みのメッセージ"),
("後面還有 {n} 則已封存", "{n} more archived messages after these", "この後にアーカイブ済みが {n} 件"),
("載入後面的", "Load later", "続きを読み込む"),
("這段對話較早的封存檔案不見了,先不換過去", "This conversation's archived messages are missing, so it wasn't opened", "この会話のアーカイブが見つからないため、切り替えませんでした"),
("已關閉", "Off", "オフ"),
("已開啟", "On", "オン"),
("使用的模型", "Model", "モデル"),

View File

@ -214,7 +214,91 @@ fn chats_apart<T>(_: &T) -> bool {
CHATS_APART.with(|c| c.get())
}
fn threads_apart(t: &crate::shared::Shared<Vec<(String, Vec<Message>)>>) -> bool {
/// 封存 of one of 過去的對話: how many of its oldest messages are in its own archive folder
/// (`chats/archive/<folder>`), the last one's time, and its first line. Empty: none.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct ThreadArchive {
pub archived: usize,
pub mark: i64,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub head_title: String,
pub folder: String,
}
impl ThreadArchive {
pub fn is_empty(&self) -> bool {
self.archived == 0
}
}
/// One of 過去的對話: its name, the messages kept in memory (the newest; all of them when
/// nothing is archived), and its archive. Written as `[name, messages]` like before when nothing
/// is archived (an older AnyBot reads it), `[name, messages, archive]` when something is.
#[derive(Clone, Debug, Default)]
pub struct Thread(pub String, pub Vec<Message>, pub ThreadArchive);
impl Thread {
pub fn new(title: String, msgs: Vec<Message>) -> Self {
Thread(title, msgs, ThreadArchive::default())
}
/// How many messages the conversation has, its archived head with them.
pub fn len(&self) -> usize {
self.2.archived + self.1.len()
}
/// Its first line, archived head or not (what a conversation nobody named is called).
pub fn auto_title(&self) -> String {
if self.2.archived > 0 && !self.2.head_title.is_empty() { self.2.head_title.clone() } else { auto_title(&self.1) }
}
}
impl From<(String, Vec<Message>)> for Thread {
fn from((title, msgs): (String, Vec<Message>)) -> Self {
Thread::new(title, msgs)
}
}
impl From<Vec<(String, Vec<Message>)>> for crate::shared::Shared<Vec<Thread>> {
fn from(v: Vec<(String, Vec<Message>)>) -> Self {
crate::shared::Shared::new(v.into_iter().map(Thread::from).collect())
}
}
impl Serialize for Thread {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeTuple;
let n = if self.2.is_empty() { 2 } else { 3 };
let mut t = s.serialize_tuple(n)?;
t.serialize_element(&self.0)?;
t.serialize_element(&self.1)?;
if n == 3 {
t.serialize_element(&self.2)?;
}
t.end()
}
}
impl<'de> Deserialize<'de> for Thread {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
struct V;
impl<'de> serde::de::Visitor<'de> for V {
type Value = Thread;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("[name, messages] or [name, messages, archive]")
}
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut a: A) -> Result<Thread, A::Error> {
let title: String = a.next_element()?.ok_or_else(|| serde::de::Error::invalid_length(0, &self))?;
let msgs: Vec<Message> = a.next_element()?.ok_or_else(|| serde::de::Error::invalid_length(1, &self))?;
let arch: ThreadArchive = a.next_element()?.unwrap_or_default();
Ok(Thread(title, msgs, arch))
}
}
d.deserialize_seq(V)
}
}
fn threads_apart(t: &crate::shared::Shared<Vec<Thread>>) -> bool {
t.is_empty() || chats_apart(t)
}
@ -238,8 +322,8 @@ fn threads_path(state: &std::path::Path, bot: u64) -> PathBuf {
fn threads_mark(b: &Bot) -> u64 {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
for (title, msgs) in b.threads.iter() {
(title, msgs.len()).hash(&mut h);
for Thread(title, msgs, arch) in b.threads.iter() {
(title, msgs.len(), arch.archived, arch.mark, &arch.folder).hash(&mut h);
for m in msgs {
(m.at, m.text.len(), m.thinking.len(), m.tool_calls.len(), m.reactions.len(), m.attachments.len(), m.folded).hash(&mut h);
}
@ -253,7 +337,7 @@ fn threads_mark(b: &Bot) -> u64 {
struct ChatOut<'a> {
messages: &'a [Message],
#[serde(skip_serializing_if = "Option::is_none")]
threads: Option<&'a [(String, Vec<Message>)]>,
threads: Option<&'a [Thread]>,
/// 封存: 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.
@ -274,7 +358,7 @@ struct ChatIn {
#[serde(default)]
messages: Vec<Message>,
#[serde(default)]
threads: Vec<(String, Vec<Message>)>,
threads: Vec<Thread>,
#[serde(default)]
archived: Option<usize>,
#[serde(default)]
@ -290,13 +374,30 @@ pub fn archived_on_disk() -> std::collections::HashMap<u64, (usize, i64)> {
archived_read().lock().unwrap_or_else(|e| e.into_inner()).clone()
}
/// Damaged threads copies each bot's 過去的對話 were taken back from this run: renamed
/// recovered once the threads file with them is written (State::write_at).
fn recovering() -> &'static std::sync::Mutex<std::collections::HashMap<u64, Vec<PathBuf>>> {
static M: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<u64, Vec<PathBuf>>>> = std::sync::OnceLock::new();
M.get_or_init(Default::default)
}
/// Bots whose 過去的對話 this run read whole (or that have none written).
pub fn threads_known() -> std::collections::HashSet<u64> {
threads_read().lock().unwrap_or_else(|e| e.into_inner()).clone()
}
fn threads_read() -> &'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)
}
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).
fn same_thread(a: &(String, Vec<Message>), b: &(String, Vec<Message>)) -> bool {
fn same_thread(a: &Thread, b: &Thread) -> bool {
a.0 == b.0 && a.1.len() == b.1.len() && a.1.first().map(|m| m.at) == b.1.first().map(|m| m.at)
}
@ -322,8 +423,8 @@ fn chat_mark(b: &Bot) -> u64 {
m.check.len().hash(&mut h);
};
b.messages.iter().for_each(&mut shape);
for (title, msgs) in &b.threads {
title.hash(&mut h);
for Thread(title, msgs, arch) in b.threads.iter() {
(title, arch.archived, &arch.folder).hash(&mut h);
msgs.len().hash(&mut h);
msgs.last().map(|m| (m.at, m.text.len())).hash(&mut h);
}
@ -508,7 +609,7 @@ pub struct Bot {
pub members: Vec<u64>,
/// 討論串: earlier conversations put aside with 「開始新對話」 (title, messages), newest first.
#[serde(default, skip_serializing_if = "threads_apart")]
pub threads: crate::shared::Shared<Vec<(String, Vec<Message>)>>,
pub threads: crate::shared::Shared<Vec<Thread>>,
/// The open conversation's name, given by the person (empty: its first line, auto_title).
/// It goes with the conversation into 過去的對話 and comes back with it.
#[serde(default, skip_serializing_if = "String::is_empty")]
@ -738,10 +839,17 @@ impl Bot {
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() {
// 封存: the archive goes with the conversation — its folder handed over, renamed,
// nothing read back or copied (過去的對話 used to take the whole conversation into
// memory and into its file: 95 MB more with each 開始新對話). Where the folder can't
// be handed over: read back whole as before; what can't be read comes as far as it reads,
// with a line, and its files are kept aside for good.
let mut arch = ThreadArchive::default();
if self.archived > 0 {
match crate::chatarchive::hand_to_thread(self.id) {
Some(folder) => arch = ThreadArchive { archived: self.archived, mark: self.archive_mark, head_title: std::mem::take(&mut self.head_title), folder },
None if self.unarchive() => {}
None => {
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());
@ -750,15 +858,18 @@ impl Bot {
whole.push(Message { note: true, at: whole.last().map(|m| m.at).unwrap_or(0), ..Message::assistant(&line, "") });
whole.extend(std::mem::take(&mut self.messages).into_inner());
self.messages = whole.into();
}
}
self.archived = 0;
self.head_title.clear();
self.archive_mark = 0;
}
if !self.messages.is_empty() {
let title = named;
if !self.messages.is_empty() || !arch.is_empty() {
let mut msgs = std::mem::take(&mut self.messages).into_inner();
msgs.iter_mut().for_each(|m| m.images.clear());
self.threads.insert(0, (title, msgs));
self.threads.insert(0, Thread(named, msgs, arch));
// (One that drops off the end leaves its archive folder behind: it goes at the next
// start, chatarchive::sweep.)
self.threads.truncate(THREADS_KEPT);
}
self.chat_title.clear();
@ -772,7 +883,7 @@ impl Bot {
/// times; the name tells apart copies that end at the same message (分岔). 0 and "" are not
/// sent (an older page): its number, as before. None: it isn't there any more.
pub fn find_thread(&self, index: usize, at: i64, was: &str) -> Option<usize> {
let fits = |t: &(String, Vec<Message>)| (at == 0 || t.1.last().map(|m| m.at).unwrap_or(0) == at) && (was.is_empty() || t.0 == was);
let fits = |t: &Thread| (at == 0 || t.1.last().map(|m| m.at).unwrap_or(0) == at) && (was.is_empty() || t.0 == was);
if at == 0 && was.is_empty() {
return (index < self.threads.len()).then_some(index);
}
@ -782,16 +893,34 @@ impl Bot {
self.threads.iter().position(fits)
}
/// 過去的對話 number `i` becomes the open one, its name with it; the open one is put aside.
/// 過去的對話 number `i` becomes the open one, its name and its archive with it; the open
/// one is put aside. One whose archive folder isn't there stays where it is (false).
pub fn open_thread(&mut self, i: usize) -> bool {
if i >= self.threads.len() {
return false;
}
let (title, msgs) = self.threads.remove(i);
if !self.threads[i].2.is_empty() && !crate::chatarchive::thread_dir(self.id, &self.threads[i].2.folder).exists() {
log::warn!("AnyBot:過去的對話「{}」的封存資料夾不見了,先不換", self.threads[i].0);
return false;
}
let first_line = self.threads[i].auto_title();
let Thread(title, msgs, arch) = self.threads.remove(i);
self.put_aside();
// (A name that is only its first line stays unset: it follows the words, as before.)
self.chat_title = if title == auto_title(&msgs) { String::new() } else { title };
self.chat_title = if title == first_line { String::new() } else { title };
self.messages = msgs.into();
if !arch.is_empty() {
if crate::chatarchive::take_from_thread(self.id, &arch.folder) {
(self.archived, self.archive_mark, self.head_title) = (arch.archived, arch.mark, arch.head_title);
} else {
// (Not moved: kept aside for good rather than left to look unused.)
let kept = crate::chatarchive::keep_thread_aside(self.id, &arch.folder);
let line = format!("(這段對話較早的 {} 則封存沒能接回,檔案留在 {},沒有刪。)", arch.archived, kept.display());
log::warn!("AnyBot:{line}");
let at = self.messages.first().map(|m| m.at).unwrap_or(0);
self.messages.insert(0, Message { note: true, at, ..Message::assistant(&line, "") });
}
}
true
}
@ -802,7 +931,7 @@ impl Bot {
match which {
None => self.chat_title = name,
Some(i) => match self.threads.get_mut(i) {
Some(t) => t.0 = if name.is_empty() { auto_title(&t.1) } else { name },
Some(t) => t.0 = if name.is_empty() { t.auto_title() } else { name },
None => return false,
},
}
@ -1292,7 +1421,41 @@ impl State {
let f = chat_path(p, b.id);
let chat = std::fs::read(&f).ok().and_then(|bytes| serde_json::from_slice::<ChatIn>(&bytes).inspect_err(|_| aside(&f)).ok());
let tf = threads_path(p, b.id);
let apart = std::fs::read(&tf).ok().and_then(|bytes| serde_json::from_slice::<Vec<(String, Vec<Message>)>>(&bytes).inspect_err(|_| aside(&tf)).ok());
let tf_there = tf.exists();
let mut apart = std::fs::read(&tf).ok().and_then(|bytes| serde_json::from_slice::<Vec<Thread>>(&bytes).inspect_err(|_| aside(&tf)).ok());
// 過去的對話 an older AnyBot set aside as damaged (it can't read one with an
// archive): this one reads them, so they come back. The copy stays until a start
// finds them all in the threads file already (then it is renamed recovered), and
// a start that brought any back doesn't count them as written: the first save does.
let mut damaged_left = false;
let mut recovered = false;
for e in std::fs::read_dir(tf.parent().unwrap_or(std::path::Path::new("."))).into_iter().flatten().flatten() {
let name = e.file_name().to_string_lossy().to_string();
if !name.starts_with(&format!("bot-{}.json.damaged-", b.id)) {
continue;
}
match std::fs::read(e.path()).ok().and_then(|bytes| serde_json::from_slice::<Vec<Thread>>(&bytes).ok()) {
Some(old) => {
let list = apart.get_or_insert_with(Vec::new);
let back: Vec<Thread> = old.into_iter().filter(|t| !list.iter().any(|x| same_thread(x, t))).collect();
if back.is_empty() {
let _ = std::fs::rename(e.path(), e.path().with_file_name(name.replace(".damaged-", ".recovered-")));
} else {
log::warn!("AnyBot:從 {name} 找回 {} 段過去的對話", back.len());
list.extend(back);
recovered = true;
recovering().lock().unwrap_or_else(|e| e.into_inner()).entry(b.id).or_default().push(e.path());
}
}
None => damaged_left = true,
}
}
// (過去的對話 known whole: read, or none written, and no damaged copy left. Only
// then may sweep tell an archive folder none of them names from one of theirs.)
let chat_damaged = std::fs::read_dir(f.parent().unwrap_or(std::path::Path::new("."))).into_iter().flatten().flatten().any(|e| e.file_name().to_string_lossy().starts_with(&format!("bot-{}.json.damaged-", b.id)));
if (apart.is_some() || !tf_there) && !damaged_left && !chat_damaged {
threads_read().lock().unwrap_or_else(|e| e.into_inner()).insert(b.id);
}
if chat.is_none() && apart.is_none() {
continue;
}
@ -1333,7 +1496,13 @@ impl State {
b.threads = threads.into();
// What is on disk is what a save would write: nothing to write until it changes.
// (Inside the chat file still: the first save moves them out, once.)
if inside_empty {
if recovered {
// (Whatever was marked written before: not this.)
let mut marks = chat_marks().lock().unwrap();
marks.remove(&(p.to_path_buf(), b.id));
marks.remove(&(tf.clone(), b.id));
}
if inside_empty && !recovered {
chat_marks().lock().unwrap().insert((p.to_path_buf(), b.id), chat_mark(b));
if had_apart {
chat_marks().lock().unwrap().insert((tf, b.id), threads_mark(b));
@ -1480,6 +1649,11 @@ impl State {
|| match serde_json::to_vec(&*b.threads) {
Ok(bytes) if crate::httpd::write_private(&tf, &bytes).is_ok() => {
chat_marks().lock().unwrap().insert(tkey, tmark);
// (Damaged copies this run took 過去的對話 back from: in the file now.)
for d in recovering().lock().unwrap_or_else(|e| e.into_inner()).remove(&b.id).unwrap_or_default() {
let name = d.file_name().map(|n| n.to_string_lossy().replace(".damaged-", ".recovered-")).unwrap_or_default();
let _ = std::fs::rename(&d, d.with_file_name(name));
}
true
}
// (An older copy there would come back at the next start.)
@ -1947,41 +2121,41 @@ mod start_tests {
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());
crate::chatarchive::sweep(&data, &back.bots, &archived_on_disk(), &threads_known());
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.
// 開始新對話, then a stop before its save: the folder 過去的對話 got (none of them
// names it on disk) 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());
crate::chatarchive::sweep(&data, &back.bots, &archived_on_disk(), &threads_known());
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;
assert_eq!(crate::chatarchive::whole(b).len(), 3_200, "the handed-over archive came back");
// Put aside again and saved this time: 過去的對話 names the folder, which stays.
st.bots[0] = b.clone();
st.bots[0].put_aside();
assert_eq!(st.bots[0].threads[0].1.len(), 3_200);
let folder = st.bots[0].threads[0].2.folder.clone();
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);
crate::chatarchive::sweep(&data, &back.bots, &archived_on_disk(), &threads_known());
let t = &back.bots.iter().find(|b| b.id == id).unwrap().threads[0];
assert_eq!((t.len(), t.2.folder.as_str()), (3_200, folder.as_str()));
assert_eq!(crate::chatarchive::read_in(&crate::chatarchive::thread_dir(id, &folder), 0, t.2.archived).len(), t.2.archived, "named: kept");
// Opened again, then a stop before its save: the open conversation on disk has nothing
// archived; the folder goes back to the past conversation that names it.
st.bots[0] = back.bots.iter().find(|b| b.id == id).unwrap().clone();
assert!(st.bots[0].open_thread(0));
assert!(crate::chatarchive::dir(id).exists() && !crate::chatarchive::thread_dir(id, &folder).exists());
let back = State::load_from(&p);
crate::chatarchive::sweep(&data, &back.bots, &archived_on_disk(), &threads_known());
assert!(!crate::chatarchive::dir(id).exists() && crate::chatarchive::thread_dir(id, &folder).exists(), "back with the conversation that names it");
// An old folder none of 過去的對話 names (one dropped off the end) goes, once all were read.
let stray = crate::chatarchive::thread_dir(id, &format!("bot-{id}.t-1"));
crate::chatarchive::write_in(&stray, 0, &long_chat(10, 0)).unwrap();
crate::chatarchive::sweep(&data, &back.bots, &archived_on_disk(), &threads_known());
assert!(!stray.exists() && crate::chatarchive::thread_dir(id, &folder).exists());
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");
assert!(!left("retired"));
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());
@ -1990,6 +2164,121 @@ mod start_tests {
let _ = std::fs::remove_dir_all(&dir);
}
/// 過去的對話 on disk: one with nothing archived is written as before (`[name, messages]`, an
/// older AnyBot reads it); one with an archive carries it as a third element. A long one put
/// aside before there was an archive (jenny-Host's 88 MB) gets its own archive folder, and
/// search finds its archived words with their place in that conversation.
#[test]
fn past_conversations_keep_their_old_shape_and_long_ones_get_an_archive() {
let _turn = crate::chatarchive::test_turn();
let plain = Thread::new("甲".into(), vec![Message::user("你好")]);
let v = serde_json::to_value(&plain).unwrap();
assert_eq!(v.as_array().unwrap().len(), 2);
let _: (String, Vec<Message>) = serde_json::from_value(v.clone()).unwrap();
assert_eq!(serde_json::from_value::<Thread>(v).unwrap().0, "甲");
let id = 930_000 + std::process::id() as u64 % 1000;
let mut t = Thread::new("很長的".into(), long_chat(3_200, 3_100));
t.1[16].text = "過去對話封存裡的斑馬".into();
assert!(crate::chatarchive::archive_thread(id, &mut t));
assert!(t.2.archived > 900 && t.len() == 3_200 && t.auto_title() == "第 0 句");
let back: Thread = serde_json::from_value(serde_json::to_value(&t).unwrap()).unwrap();
assert_eq!((back.2.archived, back.2.folder.as_str(), back.1.len()), (t.2.archived, t.2.folder.as_str(), t.1.len()));
let mut b = State::samples().bots.remove(0);
b.id = id;
b.threads = vec![t.clone()].into();
let t0 = std::time::Instant::now();
let hit = loop {
if let Some(h) = crate::find::search(std::slice::from_ref(&b), "斑馬").0.into_iter().next() {
break h;
}
assert!(t0.elapsed().as_secs() < 10);
std::thread::sleep(std::time::Duration::from_millis(20));
};
assert_eq!((hit.thread, hit.index), (Some(0), 16));
let _ = std::fs::remove_dir_all(crate::chatarchive::thread_dir(id, &t.2.folder));
}
/// Stops and damage around 過去的對話's archives: a damaged threads file (an older AnyBot
/// can't read one with an archive) leaves every folder alone and comes back once this one
/// reads it; a /fork's copy opened then a stop gets its folder back (linked: the open one
/// keeps its own); an open folder holding another conversation's archive (a stop between
/// the two files of a save) is kept aside and the right one comes.
#[test]
fn past_conversations_lose_no_archive_to_damage_or_a_stop() {
let _turn = crate::chatarchive::test_turn();
let data = State::path().parent().unwrap().to_path_buf();
let id = 940_000 + std::process::id() as u64 % 1000;
let root = data.join("chats").join("archive");
let mine = || std::fs::read_dir(&root).into_iter().flatten().flatten().filter(|e| e.file_name().to_string_lossy().starts_with(&format!("bot-{id}"))).map(|e| e.file_name().to_string_lossy().to_string()).collect::<Vec<_>>();
for n in mine() {
let _ = std::fs::remove_dir_all(root.join(n));
}
let dir = std::env::temp_dir().join(format!("anybot-thread-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();
st.bots[0].archive_head().unwrap();
st.bots[0].put_aside();
let folder = st.bots[0].threads[0].2.folder.clone();
assert!(st.save_at(&p));
// 1. The threads file damaged (as an older AnyBot leaves it): nothing deleted, and
// once this AnyBot reads the damaged copy, the conversation is back.
let tf = threads_path(&p, id);
let good = std::fs::read(&tf).unwrap();
std::fs::write(&tf, b"{oops").unwrap();
let back = State::load_from(&p);
crate::chatarchive::sweep(&data, &back.bots, &archived_on_disk(), &threads_known());
assert!(crate::chatarchive::thread_dir(id, &folder).exists(), "unknown: left alone");
let damaged: Vec<_> = std::fs::read_dir(tf.parent().unwrap()).unwrap().flatten().filter(|e| e.file_name().to_string_lossy().starts_with(&format!("bot-{id}.json.damaged-"))).collect();
std::fs::write(damaged[0].path(), &good).unwrap();
let back = State::load_from(&p);
crate::chatarchive::sweep(&data, &back.bots, &archived_on_disk(), &threads_known());
let b = back.bots.iter().find(|b| b.id == id).unwrap();
assert_eq!((b.threads.len(), b.threads[0].len()), (1, 3_200), "back from the damaged copy");
assert!(crate::chatarchive::thread_dir(id, &folder).exists());
// Not counted as written: the first save writes it; until then the damaged copy stays,
// and once written it is renamed recovered.
assert!(damaged[0].path().exists());
let mut again = back.clone();
assert!(again.save_at(&p));
assert!(!damaged[0].path().exists(), "renamed once the threads file has them");
let back = State::load_from(&p);
crate::chatarchive::sweep(&data, &back.bots, &archived_on_disk(), &threads_known());
let b = back.bots.iter().find(|b| b.id == id).unwrap();
assert_eq!(b.threads.len(), 1, "in the threads file now");
assert!(!damaged[0].path().exists() && crate::chatarchive::thread_dir(id, &folder).exists(), "the copy renamed recovered only now");
// 2. A /fork copy of an archived conversation, opened, then a stop before the save.
st.bots[0] = b.clone();
assert!(st.bots[0].open_thread(0));
let copy = crate::chatarchive::copy_as_thread(&st.bots[0], "分岔:甲".into());
st.bots[0].threads.insert(0, copy);
assert!(st.save_at(&p));
let fork_folder = st.bots[0].threads[0].2.folder.clone();
assert!(st.bots[0].open_thread(0));
let back = State::load_from(&p);
crate::chatarchive::sweep(&data, &back.bots, &archived_on_disk(), &threads_known());
let b = back.bots.iter().find(|b| b.id == id).unwrap();
assert_eq!(crate::chatarchive::whole(b).len(), 3_200, "the open one keeps its own");
assert_eq!(crate::chatarchive::read_in(&crate::chatarchive::thread_dir(id, &fork_folder), 0, b.threads[0].2.archived).len(), b.threads[0].2.archived, "the copy's folder back");
// 3. The open folder holding another conversation's archive: kept aside, the right one back.
let n = b.archived;
let other = long_chat(n, 0).into_iter().map(|mut m| { m.at += 7_000_000; m }).collect::<Vec<_>>();
let live = crate::chatarchive::dir(id);
let spare = live.with_file_name(format!("bot-{id}.t-2"));
std::fs::rename(&live, &spare).unwrap();
crate::chatarchive::write_in(&live, 0, &other).unwrap();
crate::chatarchive::sweep(&data, &back.bots, &archived_on_disk(), &threads_known());
assert_eq!(crate::chatarchive::whole(b).len(), 3_200);
assert!(crate::chatarchive::whole(b).iter().all(|m| m.at < 7_000_000), "its own archive, not the other's");
assert!(mine().iter().any(|n| n.contains(".kept-")), "the other's kept aside");
for n in mine() {
let _ = std::fs::remove_dir_all(root.join(n));
}
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
@ -2028,7 +2317,7 @@ mod start_tests {
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());
crate::chatarchive::sweep(&data, &back.bots, &archived_on_disk(), &threads_known());
let b = back.bots.iter().find(|b| b.id == id).unwrap();
let whole = crate::chatarchive::whole(b);
assert_eq!(whole.len(), 3_200);
@ -2043,7 +2332,7 @@ mod start_tests {
}
std::fs::write(&f, v.to_string()).unwrap();
let back = State::load_from(&p);
crate::chatarchive::sweep(&data, &back.bots, &archived_on_disk());
crate::chatarchive::sweep(&data, &back.bots, &archived_on_disk(), &threads_known());
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
@ -2100,13 +2389,23 @@ mod start_tests {
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.
// Put aside: into 過去的對話 with its archive folder handed over (nothing read back);
// the open conversation starts empty with nothing archived. Opened again: all back.
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");
assert_eq!((b.threads[0].len(), b.threads[0].2.archived, b.threads[0].1.len()), (3_200, cut, 3_200 - cut));
assert_eq!((b.threads[0].0.as_str(), b.threads[0].auto_title()), (name.as_str(), name.clone()));
assert!(!crate::chatarchive::dir(id).exists() && crate::chatarchive::thread_dir(id, &b.threads[0].2.folder).exists(), "the folder went with it");
assert!(b.open_thread(0));
assert_eq!((b.archived, b.conversation_len(), b.chat_name(), b.chat_title.as_str()), (cut, 3_200, name.clone(), ""));
assert_eq!(crate::chatarchive::whole(b).len(), 3_200);
// /fork: a copy in 過去的對話 with its archive linked; both read whole.
let copy = crate::chatarchive::copy_as_thread(b, "分岔:x".into());
assert_eq!((copy.len(), copy.2.archived), (3_200, cut));
assert_eq!(crate::chatarchive::read_in(&crate::chatarchive::thread_dir(id, &copy.2.folder), 0, cut).len(), cut);
let _ = std::fs::remove_dir_all(crate::chatarchive::thread_dir(id, &copy.2.folder));
let _ = std::fs::remove_dir_all(crate::chatarchive::dir(id));
let _ = std::fs::remove_dir_all(&dir);
}
@ -2240,7 +2539,7 @@ mod start_tests {
assert!(back.save_at(&p));
assert!(stamp(&apart) == ta);
// Put aside another one: the file is written then.
st.bots[0].threads.insert(0, ("剛剛".into(), vec![Message::user("上一段")]));
st.bots[0].threads.insert(0, ("剛剛".to_string(), vec![Message::user("上一段")]).into());
assert!(st.save_at(&p));
assert!(stamp(&apart) > ta);
assert_eq!(State::load_from(&p).bot(id).unwrap().threads.len(), 2);
@ -2301,7 +2600,7 @@ mod start_tests {
bot.messages.push(Message::assistant("你好", "x"));
bot.memories.push("咖啡不加糖".into());
bot.allow_rules.push("shell:git".into());
bot.threads.push(("舊對話".into(), vec![Message::user("之前")]));
bot.threads.push(("舊對話".to_string(), vec![Message::user("之前")]).into());
bot.workdir = "/tmp/work".into();
bot.tools_enabled = !from.tools_enabled;
bot.take_edit(from.clone(), edited);
@ -2417,7 +2716,7 @@ mod start_tests {
#[test]
fn a_conversation_keeps_the_name_it_was_given() {
let mut b = State::demo().bots[0].clone();
b.threads = Vec::new().into();
b.threads = Default::default();
b.chat_title.clear();
let said = |text: &str, at: i64| Message { at, ..Message::user(text) };
b.messages = vec![said("# 幫我看網站首頁\n第二行", 10), Message { at: 11, ..Message::assistant("好", "m") }].into();
@ -2470,7 +2769,7 @@ mod start_tests {
assert_eq!(b.find_thread(2, 99, ""), None, "gone: nothing, not number 2");
assert_eq!((b.find_thread(2, 0, ""), b.find_thread(3, 0, "")), (Some(2), None), "an older page sends neither");
// Two forks of one point end at the same message: the name tells them apart.
b.threads.insert(0, ("分岔:甲".into(), vec![Message { at: 20, ..Message::user("x") }]));
b.threads.insert(0, ("分岔:甲".to_string(), vec![Message { at: 20, ..Message::user("x") }]).into());
assert_eq!(b.find_thread(0, 20, "中"), Some(2));
assert_eq!(b.find_thread(1, 20, "分岔:甲"), Some(0));
assert_eq!(b.find_thread(2, 20, "改過的名字"), None, "renamed meanwhile: not guessed");

View File

@ -40,8 +40,11 @@ pub fn inputs(st: &crate::model::State) -> Inputs {
messages.extend(said.iter().filter(|s| !s.note && s.at >= from && (s.mine || !s.text.trim().is_empty())).map(|s| s.at));
}
messages.extend(b.messages.iter().filter(|m| counts(m)).map(|m| m.at));
for (_, t) in b.threads.iter() {
messages.extend(t.iter().filter(|m| counts(m)).map(|m| m.at));
for th in b.threads.iter() {
if let Some(said) = crate::chatarchive::said_thread(b.id, &th.2) {
messages.extend(said.iter().filter(|s| !s.note && s.at >= from && (s.mine || !s.text.trim().is_empty())).map(|s| s.at));
}
messages.extend(th.1.iter().filter(|m| counts(m)).map(|m| m.at));
}
}
Inputs { messages, names: st.bots.iter().map(|b| (b.id, b.name.clone())).collect(), timezone: st.timezone.clone() }