AnyBot/src/publish.rs

660 lines
32 KiB
Rust
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 發布關卡: before the bot's browser puts words out (a reply, a post, a message), the system —
// not the bot — looks at what is going out and where it goes:
// - 已送帳本: the same account never answers the same post twice. A routine run again after
// AnyBot was closed used to reply again; the bot checked by opening the replies itself.
// - 發布前檢查: another model reads the words against the rules first (a reply goes out for good).
// - 證據: after it, the page is read again — the words are there, and the reply's own address is
// kept, so a run's record says what went out and where, not what the bot says it sent.
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::path::PathBuf;
use std::sync::atomic::AtomicBool;
use std::sync::Mutex;
use crate::model::Message;
use crate::providers::ChatRequest;
/// How a step may send: a key (Enter, ctrl+Enter), typing with submit, a click on a control.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Way {
Key,
Submit,
Click,
}
impl Way {
pub fn word(self) -> &'static str {
match self {
Way::Key => "key",
Way::Submit => "type",
Way::Click => "click",
}
}
}
/// Whether a browser step may send something out (before it runs, from its arguments and, for a
/// click on a control by number, what the latest list called that control).
pub fn way_of(name: &str, args: &Value, control: Option<&str>) -> Option<Way> {
let text = |k: &str| args[k].as_str().unwrap_or("").to_string();
match name {
"browser_press" => {
let k = text("key").to_lowercase();
(k.contains("enter") || k.contains("return")).then_some(Way::Key)
}
"browser_type" => (args["submit"].as_bool() == Some(true)).then_some(Way::Submit),
"browser_click" => crate::evidence::sends_words(&format!("{} {} {}", text("text"), text("name"), control.unwrap_or(""))).then_some(Way::Click),
_ => None,
}
}
/// What the page said just before a step that may send.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct Before {
pub url: String,
/// "editor" (a multi-line box), "search", "input" (one line), "none".
pub kind: String,
/// The words that would go out.
pub text: String,
/// The post (or comment) it answers, when the page shows one: its address.
pub target: String,
/// The words around it (what it answers), short — for the check.
pub quoted: String,
/// The browser profile it goes from (the account).
pub profile: String,
/// Post addresses on the page now (the reply's own is the one that appears after).
pub links: Vec<String>,
}
impl Before {
pub fn parse(v: &Value) -> Before {
let s = |k: &str| v[k].as_str().unwrap_or("").to_string();
Before {
url: s("url"),
kind: s("kind"),
text: s("text"),
target: s("target"),
quoted: s("quoted"),
profile: s("profile"),
links: v["links"].as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(String::from)).collect()).unwrap_or_default(),
}
}
/// Words go out with this step: a multi-line box with words in it, sent by a key or by
/// typing with submit; or a click on a 送出/發佈-like control with words waiting in its box.
/// (Enter in a search box or a one-line field is a search or a form, not a post.)
pub fn publishes(&self, way: Way) -> bool {
if self.text.trim().is_empty() {
return false;
}
match way {
Way::Key | Way::Submit => self.kind == "editor",
Way::Click => self.kind == "editor" || self.kind == "input",
}
}
}
/// What the page said just after: the words still in the box (not sent), seen on the page, the
/// reply's own address.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct After {
pub left: bool,
pub seen: bool,
pub link: String,
}
impl After {
pub fn parse(v: &Value) -> After {
After { left: v["left"].as_bool().unwrap_or(false), seen: v["seen"].as_bool().unwrap_or(false), link: v["link"].as_str().unwrap_or("").to_string() }
}
}
/// The few words looked for on the page after sending: the first line with words, links taken
/// out (a page shows them shortened), at most EXCERPT_CHARS.
pub fn excerpt(text: &str) -> String {
let clean = |l: &str| -> String {
let no_links: Vec<&str> = l.split_whitespace().filter(|w| !(w.starts_with("http://") || w.starts_with("https://") || w.starts_with("www."))).collect();
no_links.join(" ")
};
text.lines().map(clean).find(|l| l.chars().count() >= 4).or_else(|| text.lines().map(|l| l.split_whitespace().collect::<Vec<_>>().join(" ")).find(|l| !l.is_empty())).unwrap_or_default().chars().take(EXCERPT_CHARS).collect()
}
const EXCERPT_CHARS: usize = 20;
/// Starts the line a step's result gets when the system saw words go out (the chat keeps the
/// same in Message::sent, which is what the counts read — a page can't fake that field).
pub const SENT_MARK: &str = "【系統】已送出";
/// Starts the line when the words are still in the box after the step.
pub const NOT_SENT_MARK: &str = "【系統】沒有送出";
/// An address in one shape: no query, no #, no trailing /, host without www. (threads.net is
/// threads.com now: the same post either way).
pub fn same_place(u: &str) -> String {
let u = u.trim();
let rest = u.split_once("://").map(|(_, r)| r).unwrap_or(u);
let rest = rest.split(['?', '#']).next().unwrap_or("");
let (host, path) = rest.split_once('/').unwrap_or((rest, ""));
let host = host.to_lowercase();
let host = host.strip_prefix("www.").unwrap_or(&host);
let host = if host == "threads.net" { "threads.com" } else { host };
let path = path.trim_end_matches('/');
if path.is_empty() {
host.to_string()
} else {
format!("{host}/{path}")
}
}
/// Words in one shape, to tell the same words sent twice.
fn same_words(t: &str) -> String {
t.split_whitespace().collect::<Vec<_>>().join(" ")
}
// ---------- 已送帳本 ----------
/// One thing that went out.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
pub struct Sent {
/// Milliseconds since 1970.
pub at: i64,
pub bot: String,
/// Which computer's browser and which profile: the account it went out from.
pub account: String,
/// What it answered (its address), when the page showed one.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub target: String,
/// The page it was sent on.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub page: String,
/// Its words (the start).
pub text: String,
/// Its own address, when the page showed it after.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub link: String,
/// The words were found on the page after.
#[serde(default)]
pub seen: bool,
}
/// How long the book remembers (and so how long the same post isn't answered again).
pub const KEEP_DAYS: i64 = 60;
/// Without a post address, the same words on the same page within this long are the same send.
const SAME_WORDS_HOURS: i64 = 24;
/// Words kept per entry.
const TEXT_KEPT: usize = 300;
const DAY_MS: i64 = 86_400_000;
static BOOK_LOCK: Mutex<()> = Mutex::new(());
/// The book: one line of JSON per send, in the data folder (every bot's, every account's).
pub struct Ledger {
path: PathBuf,
}
impl Ledger {
pub fn open() -> Ledger {
let path = if cfg!(test) {
std::env::temp_dir().join(format!("anybot-sent-test-{}.jsonl", std::process::id()))
} else {
crate::model::State::path().parent().map(|p| p.join("sent.jsonl")).unwrap_or_else(|| std::env::temp_dir().join("anybot-sent.jsonl"))
};
Ledger { path }
}
#[cfg(test)]
pub fn at(path: PathBuf) -> Ledger {
Ledger { path }
}
#[cfg(test)]
pub fn forget(&self) {
let _ = std::fs::remove_file(&self.path);
}
pub fn all(&self) -> Vec<Sent> {
let _g = BOOK_LOCK.lock().unwrap_or_else(|e| e.into_inner());
self.read()
}
fn read(&self) -> Vec<Sent> {
std::fs::read_to_string(&self.path).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).collect()
}
/// The oldest entry (the first line), without reading the rest.
fn oldest(&self) -> Option<Sent> {
use std::io::BufRead;
let f = std::fs::File::open(&self.path).ok()?;
let mut first = String::new();
std::io::BufReader::new(f).read_line(&mut first).ok()?;
serde_json::from_str(first.trim()).ok()
}
/// Write one down (and, when the oldest is past KEEP_DAYS, forget what is).
pub fn add(&self, s: &Sent) {
let _g = BOOK_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let mut s = s.clone();
s.text = s.text.chars().take(TEXT_KEPT).collect();
let Ok(line) = serde_json::to_string(&s) else { return };
if let Some(d) = self.path.parent() {
let _ = std::fs::create_dir_all(d);
}
if self.oldest().is_some_and(|f| s.at - f.at > KEEP_DAYS * DAY_MS) {
let kept: Vec<String> = self.read().iter().filter(|o| s.at - o.at <= KEEP_DAYS * DAY_MS).filter_map(|o| serde_json::to_string(o).ok()).chain([line]).collect();
let tmp = self.path.with_extension("jsonl.tmp");
if std::fs::write(&tmp, kept.join("\n") + "\n").is_ok() {
let _ = std::fs::rename(&tmp, &self.path);
}
return;
}
use std::io::Write;
if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&self.path) {
let _ = writeln!(f, "{line}");
}
}
/// The earlier send this one would repeat (see `earlier_in`).
#[cfg(test)]
pub fn earlier(&self, account: &str, b: &Before, now: i64) -> Option<Sent> {
earlier_in(&self.all(), account, b, now)
}
/// The account's latest sends, newest first.
#[cfg(test)]
pub fn recent(&self, account: &str, n: usize) -> Vec<Sent> {
recent_in(&self.all(), account, n)
}
}
/// The earlier send in `all` this one would repeat: the same account answering the same post
/// (within KEEP_DAYS), or — where the page shows no post address — the same words on the same
/// page within SAME_WORDS_HOURS.
pub fn earlier_in(all: &[Sent], account: &str, b: &Before, now: i64) -> Option<Sent> {
let target = same_place(&b.target);
let page = same_place(&b.url);
let words: String = same_words(&b.text).chars().take(TEXT_KEPT).collect();
all.iter()
.rev()
.filter(|s| s.account == account && now - s.at <= KEEP_DAYS * DAY_MS)
.find(|s| {
if !b.target.is_empty() {
!s.target.is_empty() && same_place(&s.target) == target
} else {
now - s.at <= SAME_WORDS_HOURS * 3_600_000 && same_place(&s.page) == page && same_words(&s.text) == words
}
})
.cloned()
}
/// The account's latest sends in `all`, newest first.
pub fn recent_in(all: &[Sent], account: &str, n: usize) -> Vec<Sent> {
all.iter().rev().filter(|s| s.account == account).take(n).cloned().collect()
}
/// Who a post address belongs to (threads.com/@a/post/X → @a), "" when it doesn't say.
fn author_of(target: &str) -> String {
same_place(target).split('/').find(|p| p.starts_with('@')).unwrap_or("").to_string()
}
/// Most posts a `sent` look lists (the accounts answered are all named).
const LOG_LISTED: usize = 60;
/// What the bot reads for browser action `sent`: per account (only `profile`'s when given), the
/// accounts it answered and its latest sends, newest first — the book instead of reading the
/// site's own replies page to the bottom every run.
pub fn log_text(all: &[Sent], profile: &str, days: i64, now: i64, timezone: &str) -> String {
let profile = profile.trim();
let mine: Vec<&Sent> = all.iter().rev().filter(|s| now - s.at <= days * DAY_MS && (profile.is_empty() || s.account.ends_with(&format!(" · {profile}")))).collect();
if mine.is_empty() {
let who = if profile.is_empty() { String::new() } else { format!("「{profile}」") };
return format!("帳本裡{who}最近 {days} 天沒有送出紀錄(AnyBot 從開始記帳本那天起才有;更早的要看網站自己的回覆頁)。");
}
let mut accounts: Vec<&str> = vec![];
for s in &mine {
if !accounts.contains(&s.account.as_str()) {
accounts.push(&s.account);
}
}
let mut out = vec![];
for a in accounts {
let sends: Vec<&&Sent> = mine.iter().filter(|s| s.account == a).collect();
let mut authors: Vec<String> = vec![];
for s in &sends {
let who = author_of(&s.target);
if !who.is_empty() && !authors.contains(&who) {
authors.push(who);
}
}
out.push(format!("【{a}】最近 {days} 天送出 {} 則{}", sends.len(), if authors.is_empty() { String::new() } else { format!(";回過的帳號:{}", authors.join("、")) }));
for s in sends.iter().take(LOG_LISTED) {
let to = if s.target.is_empty() { same_place(&s.page) } else { same_place(&s.target) };
out.push(format!("- {} {to}「{}」", when_text(s.at, timezone), s.text.split_whitespace().collect::<Vec<_>>().join(" ").chars().take(24).collect::<String>()));
}
if sends.len() > LOG_LISTED {
out.push(format!("…還有 {} 則較早的", sends.len() - LOG_LISTED));
}
}
out.join("\n")
}
/// What a step that would repeat an earlier send is told (it doesn't run).
pub fn repeat_refusal(s: &Sent, timezone: &str) -> String {
let when = when_text(s.at, timezone);
let what = if s.target.is_empty() { format!("在同一頁送過一模一樣的內容({})", s.page) } else { format!("已經回過這篇({})", s.target) };
format!("沒有送出:這個帳號({}){when} {what},內容是「{}」。同一篇不要再回:跳過它,換下一篇。", s.account, s.text.chars().take(60).collect::<String>())
}
fn when_text(at_ms: i64, timezone: &str) -> String {
use chrono::TimeZone;
let tz: chrono_tz::Tz = timezone.parse().unwrap_or(chrono_tz::Asia::Taipei);
chrono::Utc.timestamp_millis_opt(at_ms).single().map(|t| t.with_timezone(&tz).format("%m/%d %H:%M").to_string()).unwrap_or_default()
}
/// The line a step's result gets after words went out (or didn't), and what the chat keeps as
/// the evidence (Message::sent; empty when nothing went out).
pub fn after_line(b: &Before, a: &After) -> (String, String) {
if a.left {
return (format!("{NOT_SENT_MARK}:輸入框裡還留著這段文字,這一下沒有把它送出去(本來只是要換行就沒關係)。先看畫面確認,不要直接再送一次。"), String::new());
}
let to = if b.target.is_empty() { String::new() } else { format!("回覆 {}", b.target) };
let proof = match (a.seen, a.link.is_empty()) {
(_, false) => format!("{to} → {}", a.link),
(true, true) => format!("{to}(頁面上看得到,沒找到它自己的網址)"),
(false, true) => format!("{to}(輸入框清空了,但頁面上還沒看到這段文字)"),
};
let proof = proof.trim().to_string();
let line = if a.seen || !a.link.is_empty() { format!("{SENT_MARK},系統重新讀過頁面確認:{proof}") } else { format!("{SENT_MARK}(還沒確認):{proof}。可能要重新整理才看得到;不要因為沒看到就再送一次。") };
(line, if proof.is_empty() { "送出(頁面沒有顯示是哪一篇)".into() } else { proof })
}
// ---------- 發布前檢查 ----------
/// The model that reads the words before they go out, and the person's own rules for it.
#[derive(Clone)]
pub struct Check {
/// Who to ask (its system and history are filled in per check).
pub req: ChatRequest,
pub rules: String,
/// Words that already passed this turn (in one shape): sent again after a send that didn't
/// go through, they aren't asked about twice.
pub passed: std::sync::Arc<Mutex<std::collections::HashSet<String>>>,
}
impl Check {
pub fn new(req: ChatRequest, rules: String) -> Check {
Check { req, rules, passed: Default::default() }
}
}
/// What the check is shown besides the words.
pub struct Ask<'a> {
pub site: &'a str,
pub quoted: &'a str,
pub task: &'a str,
pub skills: &'a str,
pub recent: &'a [Sent],
pub text: &'a str,
}
#[derive(Debug, PartialEq)]
pub enum Verdict {
Pass,
Fail(String),
/// It couldn't be asked, or its answer couldn't be read.
Unknown,
}
const CHECK_SYSTEM: &str = "你是發文前的檢查員。Bot 正要在網路上公開送出一段文字(留言、回覆、貼文或訊息),送出後收不回來。照下面的規則檢查這段文字,只回一行 JSON:通過回 {\"ok\":true};不通過回 {\"ok\":false,\"why\":\"哪一條規則、哪幾個字有問題,要怎麼改(一兩句)\"}。
基本規則:
1. 語言要跟對方或任務一致;寫中文時要用繁體字(台灣用語),出現簡體字就不通過。
2. 讀起來不能像 AI 寫的:條列或標題格式、「首先/其次/總之/總而言之」、「希望對你有幫助」「如果你需要…」、每句都很客套、一堆驚嘆號或表情符號、套公式的開頭結尾。
3. 不能有不該公開的東西:個人資料、密碼、驗證碼,或寫給使用者看的話(例如「好的,我來回覆」「以下是留言」「(待補)」)。
4. 要回應對方說的內容,不能是放到哪一篇都通用的話;不能跟這個帳號最近送過的幾乎一樣。
5. 要符合「這個 Bot 的規則」和這一輪讀過的技能裡寫的帳號規則(語氣、能不能放連結、產品怎麼提)。
只檢查這段文字本身,不要因為你不喜歡這個話題就擋;拿不定的就通過。";
fn or_none(s: &str, n: usize) -> String {
if s.trim().is_empty() {
"(沒有)".to_string()
} else {
s.trim().chars().take(n).collect()
}
}
/// The check's instructions: the rules, then what stays the same for the whole turn (the task,
/// the skills it read, the person's rules). Every send of a turn starts with the very same
/// words, so a service that caches a prompt's start reads them once — only the question changes.
pub fn check_system(rules: &str, task: &str, skills: &str) -> String {
format!("{CHECK_SYSTEM}\n\n這一輪的任務:\n{}\n\n這一輪讀過的技能:\n{}\n\n這個 Bot 的規則:\n{}", or_none(task, 1500), or_none(skills, 6000), or_none(rules, 2000))
}
/// The question for one send: where, what it answers, the account's latest, the words.
pub fn check_question(a: &Ask) -> String {
let recent = if a.recent.is_empty() { "(沒有)".to_string() } else { a.recent.iter().map(|s| format!("- {}", s.text.chars().take(120).collect::<String>())).collect::<Vec<_>>().join("\n") };
format!("網站:{}\n回覆的對象(頁面上看到的):{}\n\n這個帳號最近送過:\n{recent}\n\n要送出的文字:\n「{}」", a.site, or_none(a.quoted, 400), a.text)
}
/// The check's one line of JSON.
pub fn parse_verdict(text: &str) -> Verdict {
let t = text.trim();
let Some(json) = t.find('{').and_then(|a| t.rfind('}').filter(|b| *b >= a).map(|b| &t[a..=b])) else { return Verdict::Unknown };
let v: Value = serde_json::from_str(json).unwrap_or_default();
match v["ok"].as_bool() {
Some(true) => Verdict::Pass,
Some(false) => Verdict::Fail(v["why"].as_str().map(str::trim).filter(|w| !w.is_empty()).unwrap_or("沒說原因").to_string()),
None => Verdict::Unknown,
}
}
/// Ask the check (words that already passed this turn aren't asked about again). It thinks
/// little: a yes or no with a reason, not an essay.
pub fn check(c: &Check, a: &Ask, cancel: &AtomicBool) -> Verdict {
let key = same_words(a.text);
if c.passed.lock().map(|p| p.contains(&key)).unwrap_or(false) {
return Verdict::Pass;
}
let req = ChatRequest { system: check_system(&c.rules, a.task, a.skills), history: vec![Message::user(&check_question(a))], tools: vec![], effort: "low".into(), ..c.req.clone() };
let v = match crate::providers::run_step_as_written(&req, cancel, &|_| {}) {
Ok(out) => parse_verdict(&out.text),
Err(_) => Verdict::Unknown,
};
if v == Verdict::Pass {
if let Ok(mut p) = c.passed.lock() {
p.insert(key);
}
}
v
}
/// What a step whose words didn't pass is told (it doesn't run).
pub fn check_refusal(why: &str, model: &str) -> String {
format!("沒有送出:發布前檢查({model})沒通過:{why}\n照這點改好輸入框裡的文字(type 不加 append 會整段換掉)再送;改不了就跳過這篇。")
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn before(target: &str, text: &str) -> Before {
Before { url: "https://www.threads.com/search?q=貓".into(), kind: "editor".into(), text: text.into(), target: target.into(), ..Default::default() }
}
#[test]
fn only_words_leaving_a_post_box_are_a_send() {
assert_eq!(way_of("browser_press", &json!({"key": "ctrl+Return"}), None), Some(Way::Key));
assert_eq!(way_of("browser_press", &json!({"key": "Tab"}), None), None);
assert_eq!(way_of("browser_type", &json!({"value": "貓抓板", "submit": true}), None), Some(Way::Submit));
assert_eq!(way_of("browser_type", &json!({"value": "貓抓板"}), None), None);
assert_eq!(way_of("browser_click", &json!({"ref": "12"}), Some("按鈕「發佈」")), Some(Way::Click));
assert_eq!(way_of("browser_click", &json!({"ref": "12"}), Some("按鈕「回覆」")), None);
// Enter in a search box searches; Enter in an editor with words in it sends.
let search = Before { kind: "search".into(), text: "貓抓板".into(), ..Default::default() };
assert!(!search.publishes(Way::Submit) && !search.publishes(Way::Key));
assert!(before("", "好可愛").publishes(Way::Key));
assert!(!before("", " ").publishes(Way::Key));
let one_line = Before { kind: "input".into(), text: "hi".into(), ..Default::default() };
assert!(!one_line.publishes(Way::Key) && one_line.publishes(Way::Click));
}
#[test]
fn the_same_post_is_one_place_however_it_is_written() {
assert_eq!(same_place("https://www.threads.net/@kubi.neko/post/DAbc123/?xmt=1#r"), "threads.com/@kubi.neko/post/DAbc123");
assert_eq!(same_place("threads.com/@kubi.neko/post/DAbc123"), "threads.com/@kubi.neko/post/DAbc123");
assert_eq!(same_place("https://Example.com/"), "example.com");
}
#[test]
fn an_account_never_answers_the_same_post_twice() {
let path = std::env::temp_dir().join(format!("anybot-sent-{}-{}.jsonl", std::process::id(), line!()));
let _ = std::fs::remove_file(&path);
let book = Ledger::at(path.clone());
let now = 1_800_000_000_000;
let post = "https://www.threads.com/@a/post/X1";
book.add(&Sent { at: now - DAY_MS, bot: "貓".into(), account: "這台電腦 · 主婦(Firefox)".into(), target: post.into(), text: "好可愛".into(), ..Default::default() });
// Same account, same post (written another way): the earlier one.
let e = book.earlier("這台電腦 · 主婦(Firefox)", &before("https://threads.net/@a/post/X1/", "換句話說也一樣"), now).unwrap();
assert_eq!(e.text, "好可愛");
assert!(repeat_refusal(&e, "Asia/Taipei").starts_with("沒有送出:這個帳號(這台電腦 · 主婦(Firefox))"));
// Another account, or another post: fine.
assert!(book.earlier("這台電腦 · 拾日(Firefox)", &before(post, "好可愛"), now).is_none());
assert!(book.earlier("這台電腦 · 主婦(Firefox)", &before("https://www.threads.com/@a/post/X2", "好可愛"), now).is_none());
// Long ago: forgotten.
assert!(book.earlier("這台電腦 · 主婦(Firefox)", &before(post, "x"), now + KEEP_DAYS * DAY_MS).is_none());
// No post address: only the very same words on the same page count.
book.add(&Sent { at: now, account: "A".into(), page: "https://chat.example.com/room/1".into(), text: "明天 10 點見".into(), ..Default::default() });
let page = |t: &str| Before { url: "https://chat.example.com/room/1?x=1".into(), kind: "editor".into(), text: t.into(), ..Default::default() };
assert!(book.earlier("A", &page("明天 10 點見"), now + 1000).is_some());
assert!(book.earlier("A", &page("改成 11 點"), now + 1000).is_none());
assert_eq!(book.recent("A", 5).len(), 1);
let _ = std::fs::remove_file(&path);
}
/// A model service on this computer that answers every check with `answer` and keeps the
/// bodies it was sent.
fn fake_model(answer: &'static str) -> (String, std::sync::Arc<Mutex<Vec<String>>>) {
use std::io::{Read, Write};
let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = l.local_addr().unwrap().port();
let seen: std::sync::Arc<Mutex<Vec<String>>> = Default::default();
let keep = seen.clone();
std::thread::spawn(move || {
for mut c in l.incoming().flatten() {
let mut req = Vec::new();
let mut buf = [0u8; 65536];
loop {
let n = c.read(&mut buf).unwrap_or(0);
if n == 0 {
break;
}
req.extend_from_slice(&buf[..n]);
let t = String::from_utf8_lossy(&req).to_string();
if let Some(end) = t.find("\r\n\r\n") {
let len = t[..end].lines().find_map(|l| l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0))).unwrap_or(0);
if req.len() >= end + 4 + len {
keep.lock().unwrap().push(t[end + 4..].to_string());
break;
}
}
}
let out = format!("data: {}\n\ndata: [DONE]\n\n", json!({"choices": [{"delta": {"content": answer}}]}));
let _ = c.write_all(b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n");
let _ = c.write_all(out.as_bytes());
}
});
(format!("http://127.0.0.1:{port}/v1"), seen)
}
#[test]
fn the_check_is_asked_once_per_words_with_the_turns_part_up_front() {
let (base, seen) = fake_model("{\"ok\":true}");
let req = ChatRequest { kind: crate::providers::ProviderKind::Custom, base_url: base, api_key: String::new(), model: "m".into(), system: String::new(), history: vec![], tools: vec![], session: String::new(), effort: String::new() };
let c = Check::new(req, "不放連結".into());
let never = AtomicBool::new(false);
let ask = |text: &'static str| Ask { site: "threads.com", quoted: "我家貓每天半夜跑酷", task: "[例行任務]回 5 則", skills: "## 語氣\n短句", recent: &[], text };
assert_eq!(check(&c, &ask("我家也是 這樣"), &never), Verdict::Pass);
// The same words again (sent again after a send that didn't go): not asked again.
assert_eq!(check(&c, &ask("我家也是\n 這樣"), &never), Verdict::Pass);
assert_eq!(seen.lock().unwrap().len(), 1);
assert_eq!(check(&c, &ask("換一句"), &never), Verdict::Pass);
let bodies = seen.lock().unwrap().clone();
assert_eq!(bodies.len(), 2);
// Both start the same (the task, skills and rules in the instructions); only the
// question differs.
let sys = |b: &str| -> String {
let v: Value = serde_json::from_str(b).unwrap();
v["messages"].as_array().unwrap().iter().find(|m| m["role"] == "system").map(|m| m["content"].to_string()).unwrap_or_default()
};
assert_eq!(sys(&bodies[0]), sys(&bodies[1]));
assert!(sys(&bodies[0]).contains("回 5 則") && sys(&bodies[0]).contains("不放連結"));
// A check that says no isn't remembered as passed.
let (base, _) = fake_model("{\"ok\":false,\"why\":\"有簡體字\"}");
let no = Check::new(ChatRequest { base_url: base, ..c.req.clone() }, String::new());
assert_eq!(check(&no, &ask("这样"), &never), Verdict::Fail("有簡體字".into()));
assert!(no.passed.lock().unwrap().is_empty());
}
#[test]
fn the_book_says_who_an_account_answered_without_reading_the_site() {
let now = 1_800_000_000_000;
let s = |acc: &str, target: &str, text: &str, ago_days: i64| Sent { at: now - ago_days * DAY_MS, account: acc.into(), target: target.into(), text: text.into(), ..Default::default() };
let all = vec![
s("這台電腦 · 主婦(Firefox)", "https://www.threads.com/@a/post/X1", "好可愛", 40),
s("這台電腦 · 主婦(Firefox)", "https://www.threads.com/@b/post/X2", "我家也是", 1),
s("這台電腦 · 主婦(Firefox)", "https://www.threads.com/@a/post/X3?x=1", "又見面了", 0),
s("這台電腦 · 貓咪(Firefox)", "https://www.threads.com/@c/post/X4", "喵", 0),
];
let t = log_text(&all, "主婦(Firefox)", 30, now, "Asia/Taipei");
assert!(t.starts_with("【這台電腦 · 主婦(Firefox)】最近 30 天送出 2 則;回過的帳號:@a、@b"), "{t}");
assert!(t.contains("threads.com/@a/post/X3「又見面了」") && !t.contains("X1") && !t.contains("貓咪"), "{t}");
assert!(log_text(&all, "", 60, now, "Asia/Taipei").contains("【這台電腦 · 貓咪(Firefox)】"));
assert!(log_text(&all, "拾日(Firefox)", 30, now, "Asia/Taipei").contains("沒有送出紀錄"));
}
#[test]
fn the_book_forgets_what_is_older_than_it_keeps() {
let path = std::env::temp_dir().join(format!("anybot-sent-{}-{}.jsonl", std::process::id(), line!()));
let _ = std::fs::remove_file(&path);
let book = Ledger::at(path.clone());
book.add(&Sent { at: 0, account: "A".into(), text: "old".into(), ..Default::default() });
book.add(&Sent { at: (KEEP_DAYS + 1) * DAY_MS, account: "A".into(), text: "new".into(), ..Default::default() });
let all = book.all();
assert_eq!(all.len(), 1);
assert_eq!(all[0].text, "new");
let _ = std::fs::remove_file(&path);
}
#[test]
fn what_is_looked_for_after_sending_skips_links_and_blank_lines() {
assert_eq!(excerpt("\n\n我家貓也超愛這款 https://s.shopee.tw/abc 真的好用"), "我家貓也超愛這款 真的好用");
assert_eq!(excerpt("https://s.shopee.tw/abc"), "https://s.shopee.tw/");
assert_eq!(excerpt("短\n第二行比較長一點"), "第二行比較長一點");
}
#[test]
fn the_result_says_what_went_out_and_where() {
let b = before("https://www.threads.com/@a/post/X1", "好可愛");
let (line, proof) = after_line(&b, &After { left: false, seen: true, link: "https://www.threads.com/@me/post/Y9".into() });
assert!(line.starts_with(SENT_MARK) && line.contains("確認"));
assert_eq!(proof, "回覆 https://www.threads.com/@a/post/X1 → https://www.threads.com/@me/post/Y9");
let (line, proof) = after_line(&b, &After { left: true, ..Default::default() });
assert!(line.starts_with(NOT_SENT_MARK) && proof.is_empty());
let (line, proof) = after_line(&b, &After::default());
assert!(line.contains("還沒確認") && proof.contains("還沒看到"));
}
#[test]
fn the_checks_answer_is_read_loosely() {
assert_eq!(parse_verdict("{\"ok\":true}"), Verdict::Pass);
assert_eq!(parse_verdict("好的 {\"ok\": false, \"why\": \"有簡體字「这」\"}"), Verdict::Fail("有簡體字「这」".into()));
assert_eq!(parse_verdict("{\"ok\": false}"), Verdict::Fail("沒說原因".into()));
assert_eq!(parse_verdict("通過"), Verdict::Unknown);
// What stays the same all turn leads the instructions; each send's question is short.
let sys = check_system("", "回 5 則", "## 語氣\n短句");
assert!(sys.starts_with(CHECK_SYSTEM) && sys.contains("這一輪的任務:\n回 5 則") && sys.contains("## 語氣") && sys.ends_with("這個 Bot 的規則:\n(沒有)"));
let q = check_question(&Ask { site: "threads.com", quoted: "", task: "回 5 則", skills: "## 語氣", recent: &[], text: "好可愛" });
assert!(q.contains("「好可愛」") && !q.contains("回 5 則") && !q.contains("語氣"), "{q}");
}
}