繁體中文、換電腦: what a model writes is put into Traditional Chinese whatever the setting's system; a work folder from another computer lands under this home

- 繁體中文: converted at the one place every model call comes back (providers::run_step),
  decided from the request itself: the setting is 繁體中文, or it follows the system and
  the person writes Traditional. It used to be on only for the explicit setting, so a
  brain on an English server with 跟著系統 never converted, whatever the instructions said.
  Not when another language is chosen, nor when the latest message asks for Simplified.
- Converted: the reply, the thinking, and steps whose words are for the person (question
  card, card, page, memory, routine). Left as written: code blocks and `inline code`, a
  line of Japanese, file names, commands, searches, recipients.
- Taiwan wording after the characters: about 55 one-meaning computer terms (網絡→網路,
  文件夾→資料夾, 默認→預設…), and zhconv's OpenCC tables on (设置里的 → 設定裡的).
- The reply instruction says it too: no Simplified characters, no mainland wording.
- 換電腦: a bot's work folder chosen on one computer (/Users/daniel on a Mac) no longer
  breaks every file and command step on another (Linux, another user). It is sent as ~/…
  with the folder as chosen alongside; the receiving computer uses the folder if it is
  there, else the same place under its own home, else its home.
- FEATURES.md.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3QxSfoydRPM9mjj6d
This commit is contained in:
王性驊 2026-11-12 10:29:02 +08:00
parent 3720ee501e
commit 935cee9346
8 changed files with 376 additions and 27 deletions

View File

@ -11,7 +11,7 @@ name = "anybot"
path = "src/main.rs" path = "src/main.rs"
[dependencies] [dependencies]
zhconv = { version = "0.4", default-features = false, features = ["mediawiki"] } zhconv = { version = "0.4", default-features = false, features = ["mediawiki", "opencc"] }
eframe = "0.37" eframe = "0.37"
ureq = { version = "3", features = ["json"] } ureq = { version = "3", features = ["json"] }
# Web pages that are not UTF-8 (Big5, GBK, Shift_JIS…), read as what they say they are. # Web pages that are not UTF-8 (Big5, GBK, Shift_JIS…), read as what they say they are.

View File

@ -1957,6 +1957,10 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
- 指令和改檔案的規則跟 SSH 電腦一樣。 - 指令和改檔案的規則跟 SSH 電腦一樣。
- 詢問會出現在發出動作的那台 AnyBot,也就是手機或那台電腦的視窗。原版是在被操作的那台裝置上詢問。 - 詢問會出現在發出動作的那台 AnyBot,也就是手機或那台電腦的視窗。原版是在被操作的那台裝置上詢問。
- 經過帳號伺服器,最多等 35 秒(原版的裝置工具等 30 秒)。 - 經過帳號伺服器,最多等 35 秒(原版的裝置工具等 30 秒)。
- **工作資料夾換了電腦也能用**(2026-11-12):Bot 的工作資料夾是在某一台上選的(例如 Mac 的 `/Users/daniel/Documents`),換到另一台系統或使用者名稱不同的電腦(Linux 的家目錄在 `/home/…`)時那個路徑不存在,以前檔案和指令工具會全部失敗在「進入資料夾」那一步,Bot 還會回頭問你要改設定還是換電腦。現在自動處理,不問你:
- 送出去時,家目錄底下的資料夾寫成 `~/…`(`/Users/名字/…`、`/home/名字/…`、`C:\Users\名字\…` 都認得),由對方換成它自己的家目錄;原本的路徑也一起送。
- 收到的那台:原本的路徑在這台真的存在就用它;否則用自己家目錄底下同樣的位置;那裡也沒有,就用家目錄。資料夾不存在不再讓工具失敗(跟沒設資料夾時一樣)。
- 兩邊各做一半:大腦更新後,還沒更新的那台也能用(它本來就認得 `~`);那台更新後,連 `~/…` 底下沒有的資料夾也會退回家目錄。
### 傳送到其他裝置(檔案和文字,任意兩台之間) ### 傳送到其他裝置(檔案和文字,任意兩台之間)
@ -2112,6 +2116,13 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
- English、日本語:翻譯了約 370 個常見字串(側邊欄、聊天頂部、輸入框、右側面板、整個設定頁);較少見的訊息仍是中文。 - English、日本語:翻譯了約 370 個常見字串(側邊欄、聊天頂部、輸入框、右側面板、整個設定頁);較少見的訊息仍是中文。
- 其他語言:選單用英文。 - 其他語言:選單用英文。
- **Bot 回答**:在指示最後加上「一律用 {語言} 回答」,37 種都適用。 - **Bot 回答**:在指示最後加上「一律用 {語言} 回答」,37 種都適用。
- **繁體中文,不管模型寫什麼**(2026-11-12 重做):模型常常不理指示、寫出簡體字(剛讀過簡體網頁時尤其會),所以不靠指示:模型寫給你看的字,在每一次模型呼叫回來的地方(聊天、摘要、目標檢查…同一個出口)直接轉成繁體字和台灣用語。
- 什麼時候轉:語言設「繁體中文」時一律轉;設「自動偵測」時看你怎麼寫——你最近的訊息是繁體就轉,是簡體就不轉,看不出來(只有「你好」這種兩邊都一樣的字,或沒有中文)就照系統語言,不是簡體中文就轉。以前只有設「繁體中文」才轉,而伺服器上的大腦系統語言是英文,「自動偵測」等於完全不轉。
- 什麼時候不轉:語言設成简体中文或其他語言;或你最新一則訊息要簡體(「翻成簡體」「用简体写」),只那一次。說「不要再出簡體」「為什麼一直出簡體」不算要簡體。
- 轉哪些:回覆、思考過程,以及給你看的步驟內容(問題卡、生活卡片、頁面、記住的事、例行任務的名稱和任務)。不轉:檔名、指令、搜尋的字、收件人——那些要照原樣。
- 不動的地方:程式碼區塊和 `反引號裡的字`(檔案可能真的叫「文档.txt」);有假名的那一行(你要的日文翻譯,「学校」不會變「學校」)。
- 用語:字轉完再換台灣的說法,約 55 個只有一個意思的電腦用語(網絡→網路、文件夾→資料夾、默認→預設、視頻→影片、信息→資訊、屏幕→螢幕、插件→外掛、算法→演算法…)。有別的意思的不換(餐廳的「菜單」、聯絡「窗口」、「質量」「項目」「程序」)。
- 指示也加強了:「自動偵測」多一句「使用者寫繁體中文時,用繁體中文和台灣用語回答,不要用簡體字」;「繁體中文」多一句不要用中國大陸的用語。
### 設定的分類(照原版) ### 設定的分類(照原版)

View File

@ -1167,7 +1167,7 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc<
} }
let msg = Message { let msg = Message {
role: Role::Assistant, role: Role::Assistant,
text: crate::i18n::reply_text(&out.text), text: out.text,
thinking: out.thinking, thinking: out.thinking,
via, via,
tool_calls: out.tool_calls, tool_calls: out.tool_calls,
@ -1637,7 +1637,7 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc<
// Another of the person's computers: it sends the file over, then it is // Another of the person's computers: it sends the file over, then it is
// put in the chat like any other. // put in the chat like any other.
Ok(tools::Target { place: tools::Place::Device { host, dir }, .. }) => { Ok(tools::Target { place: tools::Place::Device { host, dir }, .. }) => {
let args = serde_json::json!({"path": path, "workdir": dir}).to_string(); let args = serde_json::json!({"path": path, "workdir": tools::portable_dir(&dir), "workdir_as_chosen": dir.trim()}).to_string();
let tmp_dir = fetch_tmp.clone(); let tmp_dir = fetch_tmp.clone();
crate::remote::run_on_device(&host, crate::remote::FETCH_FILE, &args, &job.via_name).and_then(|v| { crate::remote::run_on_device(&host, crate::remote::FETCH_FILE, &args, &job.via_name).and_then(|v| {
let bytes = v["data"].as_str().and_then(|d| base64::engine::general_purpose::STANDARD.decode(d).ok()).ok_or_else(|| v["text"].as_str().unwrap_or("那台電腦沒有把檔案傳過來").to_string())?; let bytes = v["data"].as_str().and_then(|d| base64::engine::general_purpose::STANDARD.decode(d).ok()).ok_or_else(|| v["text"].as_str().unwrap_or("那台電腦沒有把檔案傳過來").to_string())?;

View File

@ -1969,7 +1969,7 @@ impl App {
other => { other => {
let Some(m) = b.messages.last_mut() else { continue }; let Some(m) = b.messages.last_mut() else { continue };
match other { match other {
StreamEvent::Text(t) => m.text.push_str(&crate::i18n::reply_text(&t)), StreamEvent::Text(t) => m.text.push_str(&t),
StreamEvent::Thinking(t) => m.thinking.push_str(&t), StreamEvent::Thinking(t) => m.thinking.push_str(&t),
StreamEvent::ToolCall(c) => m.tool_calls.push(c), StreamEvent::ToolCall(c) => m.tool_calls.push(c),
StreamEvent::StepDone(full) => { StreamEvent::StepDone(full) => {

View File

@ -55,22 +55,186 @@ fn current() -> &'static RwLock<String> {
L.get_or_init(|| RwLock::new("zh-TW".into())) L.get_or_init(|| RwLock::new("zh-TW".into()))
} }
/// Replies are wanted in Traditional Chinese (the language setting says so, not "auto"). // 繁體中文, whatever the model writes. Models slip into Simplified characters despite every
static REPLIES_HANT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); // instruction (Qwen and Grok especially, and anything that has just read a Simplified page), so
// the instruction isn't what is relied on: what a model wrote for the person is converted —
// Traditional characters, Taiwan wording — at the one place every model call comes back
// through (providers::run_step). Whether to is read off the request itself, so it holds for
// the chat, the summaries, the goal checks and every other call alike:
// • the language setting is 繁體中文, or
// • it is 跟著系統 and the person writes Traditional Chinese (a brain on a server has an
// English system, which is why the setting alone used to leave this off),
// and not when the person's latest message asks for Simplified (「翻成簡體」).
/// What the bot wrote, in Traditional Chinese with Taiwan wording when that is the setting. /// The line reply_instruction gives for each setting (wants_hant reads the setting back off them).
/// Models (Qwen especially) slip into Simplified characters despite the instruction. const HANT_LINE: &str = "一律用繁體中文回答(台灣用語)";
pub fn reply_text(s: &str) -> String { const HANS_LINE: &str = "一律用简体中文回答";
if REPLIES_HANT.load(std::sync::atomic::Ordering::Relaxed) && !s.is_empty() { const OTHER_LINE: &str = "Always answer in ";
zhconv::zhconv(s, zhconv::Variant::ZhTW)
} else { fn is_han(c: char) -> bool {
s.to_string() matches!(c as u32, 0x3400..=0x4DBF | 0x4E00..=0x9FFF | 0xF900..=0xFAFF | 0x20000..=0x2FA1F)
}
/// Mainland wording the converter's tables leave alone, and what Taiwan says instead. Only
/// words that mean one thing: not 菜單 (a restaurant's), 窗口 (a contact), 文本, 在線, 質量,
/// 項目, 程序, 對象… whose other meaning is everyday Taiwan Chinese. Longer words first.
const TW_WORDS: &[(&str, &str)] = &[
("筆記本電腦", "筆記型電腦"),
("演示文稿", "簡報"),
("電子表格", "試算表"),
("快捷方式", "捷徑"),
("文件夾", "資料夾"),
("字符串", "字串"),
("攝像頭", "攝影機"),
("二維碼", "QR Code"),
("回收站", "資源回收筒"),
("剪貼板", "剪貼簿"),
("快捷鍵", "快速鍵"),
("用戶名", "使用者名稱"),
("台式機", "桌上型電腦"),
("幻燈片", "投影片"),
("充電寶", "行動電源"),
("網絡", "網路"),
("信息", "資訊"),
("視頻", "影片"),
("音頻", "音訊"),
("默認", "預設"),
("屏幕", "螢幕"),
("登錄", "登入"),
("博客", "部落格"),
("內存", "記憶體"),
("字符", "字元"),
("短信", "簡訊"),
("卸載", "解除安裝"),
("兼容", "相容"),
("緩存", "快取"),
("插件", "外掛"),
("光標", "游標"),
("加載", "載入"),
("搜索", "搜尋"),
("代碼", "程式碼"),
("模塊", "模組"),
("變量", "變數"),
("郵箱", "信箱"),
("設置", "設定"),
("激活", "啟用"),
("截屏", "截圖"),
("文檔", "文件"),
("寬帶", "寬頻"),
("編程", "寫程式"),
("調試", "除錯"),
("線程", "執行緒"),
("粘貼", "貼上"),
("發送", "傳送"),
("U盤", "隨身碟"),
("實時", "即時"),
("圖標", "圖示"),
("數組", "陣列"),
("主頁", "首頁"),
("拖拽", "拖曳"),
("算法", "演算法"),
];
/// Traditional characters first (the converter), then Taiwan's words for what is left.
fn to_taiwan(t: &str) -> String {
let mut s = zhconv::zhconv(t, zhconv::Variant::ZhTW);
for (from, to) in TW_WORDS {
if s.contains(from) {
s = s.replace(from, to);
}
}
// (演算法 was already right.)
s.replace("演演算法", "演算法")
}
/// Japanese: kana in the line. Its kanji are not Chinese to be converted (学校 stays 学校).
fn is_japanese(line: &str) -> bool {
line.chars().any(|c| matches!(c as u32, 0x3041..=0x309F | 0x30A1..=0x30FA))
}
/// What a model wrote, in Traditional Chinese with Taiwan wording. Line by line: a line of
/// Japanese (a translation the person asked for) is left as it is, and so is code — a fenced
/// block, or `between backticks` — where a file's name or a command must stay as written.
pub fn hant(s: &str) -> String {
if !s.chars().any(is_han) {
return s.to_string();
}
let convert = |t: &str| if t.chars().any(is_han) { to_taiwan(t) } else { t.to_string() };
let mut fenced = false;
let mut out = String::with_capacity(s.len());
for line in s.split_inclusive('\n') {
if line.trim_start().starts_with("```") {
fenced = !fenced;
out.push_str(line);
} else if fenced || is_japanese(line) {
out.push_str(line);
} else {
// Outside the backticks only (the even pieces).
for (i, piece) in line.split('`').enumerate() {
if i > 0 {
out.push('`');
}
out.push_str(&if i % 2 == 0 { convert(piece) } else { piece.to_string() });
}
}
}
out
}
/// Which Chinese a text is written in, by the characters only one of the two has: Some(true)
/// Traditional, Some(false) Simplified, None when it can't be told (no Chinese, or only
/// characters both share, like 「你好」).
pub fn written_traditional(s: &str) -> Option<bool> {
// (Japanese lines say nothing about which Chinese: 国 and 学 look Simplified and aren't.)
let s: String = s.lines().filter(|l| !is_japanese(l)).collect::<Vec<_>>().join("\n");
let s = s.as_str();
if !s.chars().any(is_han) {
return None;
}
let changed = |to: zhconv::Variant| zhconv::zhconv(s, to).chars().zip(s.chars()).filter(|(a, b)| a != b).count();
// (Characters that change on the way to Simplified are Traditional ones, and the reverse.)
let (trad, simp) = (changed(zhconv::Variant::ZhHans), changed(zhconv::Variant::ZhHant));
match trad.cmp(&simp) {
std::cmp::Ordering::Greater => Some(true),
std::cmp::Ordering::Less => Some(false),
std::cmp::Ordering::Equal => None,
}
}
/// The person asks for Simplified Chinese this time (「翻成簡體」「用简体写」) — and isn't saying
/// they don't want it (「不要再出簡體」).
pub fn asks_simplified(text: &str) -> bool {
let t = text.to_lowercase();
let named = ["簡體", "简体", "簡中", "simplified chinese"].iter().any(|w| t.contains(w));
let against = ["不要", "不用", "不准", "不可", "不能", "不想", "別", "别", "勿", "禁止", "為什麼", "为什么", "怎麼", "怎么", "一直", "老是", "總是", "don't", "do not", "stop", "never", "why"].iter().any(|w| t.contains(w));
named && !against
}
/// Should what the model writes back for this request be put into Traditional Chinese?
/// (`system` is the request's instructions, `history` its messages.)
pub fn wants_hant(system: &str, history: &[crate::model::Message]) -> bool {
use crate::model::Role;
// Another language was chosen outright.
if system.contains(HANS_LINE) || system.contains(OTHER_LINE) {
return false;
}
let said: Vec<&str> = history.iter().rev().filter(|m| m.role == Role::User && !m.text.trim().is_empty()).take(6).map(|m| m.text.as_str()).collect();
if said.first().is_some_and(|t| asks_simplified(t)) {
return false;
}
if system.contains(HANT_LINE) {
return true;
}
// 跟著系統 (or a call with its own instructions — a summary, a check): what the person
// writes decides; when that can't be told, the instructions' own Chinese, then the system.
match written_traditional(&said.join("\n")).or_else(|| written_traditional(system)) {
Some(trad) => trad,
None => lang() != "zh-CN",
} }
} }
/// "auto" follows the system language. /// "auto" follows the system language.
pub fn set(tag: &str) { pub fn set(tag: &str) {
REPLIES_HANT.store(tag == "zh-TW", std::sync::atomic::Ordering::Relaxed);
let t = if tag == "auto" || tag.is_empty() { system() } else { tag.to_string() }; let t = if tag == "auto" || tag.is_empty() { system() } else { tag.to_string() };
*current().write().unwrap() = t; *current().write().unwrap() = t;
} }
@ -122,11 +286,11 @@ pub fn endonym(tag: &str) -> &'static str {
/// Added to every bot's instructions: answer in the chosen language ("auto" = the person's). /// Added to every bot's instructions: answer in the chosen language ("auto" = the person's).
pub fn reply_instruction(setting: &str) -> String { pub fn reply_instruction(setting: &str) -> String {
if setting == "auto" || setting.is_empty() { if setting == "auto" || setting.is_empty() {
return "回答時使用使用者所用的語言。".into(); return "回答時使用使用者所用的語言。使用者寫繁體中文時,用繁體中文和台灣用語回答,不要用簡體字。".into();
} }
match setting { match setting {
"zh-TW" => "一律用繁體中文回答(台灣用語)。".into(), "zh-TW" => format!("{HANT_LINE}。不要用簡體字,也不要用中國大陸的用語(例如說「軟體」不說「软件」、說「網路」不說「网络」)。"),
"zh-CN" => "一律用简体中文回答。".into(), "zh-CN" => format!("{HANS_LINE}。"),
t => format!("Always answer in {} ({}), whatever language the instructions are written in.", english_name(t), endonym(t)), t => format!("Always answer in {} ({}), whatever language the instructions are written in.", english_name(t), endonym(t)),
} }
} }
@ -218,12 +382,56 @@ pub fn to_simplified(s: &str) -> String {
mod tests { mod tests {
use super::*; use super::*;
/// 繁體中文: what the model writes is converted when the setting says so, or when the
/// setting follows the system and the person writes Traditional — not when another
/// language was chosen, nor when they ask for Simplified this once.
#[test]
fn replies_are_put_into_traditional_chinese_for_someone_who_writes_it() {
use crate::model::Message;
assert_eq!(hant("指令/檔案工具全挂,这台是 Ubuntu,根本没有这个文件夹"), "指令/檔案工具全掛,這台是 Ubuntu,根本沒有這個資料夾");
assert_eq!(hant("no Chinese here: /Users/daniel"), "no Chinese here: /Users/daniel");
// Taiwan's words, not only its characters — and what is already right stays right.
assert_eq!(hant("网络和默认设置里的视频插件,用这个算法搜索信息"), "網路和預設設定裡的影片外掛,用這個演算法搜尋資訊");
assert_eq!(hant("演算法、網路、資料夾、這家餐廳的菜單、聯絡窗口"), "演算法、網路、資料夾、這家餐廳的菜單、聯絡窗口");
// A Japanese line is left alone (its 学 and 国 are not Simplified Chinese); the Chinese around it isn't.
assert_eq!(hant("这句的日文是:\n学校に行きます。国語の授業です。\n意思是去学校。\n"), "這句的日文是:\n学校に行きます。国語の授業です。\n意思是去學校。\n");
assert_eq!(written_traditional("這句日文是什麼意思\n学校に行きます。国語の授業"), Some(true));
// Code stays as written: a file may really be called 文档.txt.
assert_eq!(hant("请执行 `rm 旧文档.txt`,然后:\n```sh\ncat 说明.md\n```\n完成后告诉我。"), "請執行 `rm 旧文档.txt`,然後:\n```sh\ncat 说明.md\n```\n完成後告訴我。");
assert_eq!(written_traditional("学校に行きます"), None);
assert_eq!(written_traditional("確認一下你現在用的電腦"), Some(true));
assert_eq!(written_traditional("确认一下你现在用的电脑"), Some(false));
assert_eq!(written_traditional("你好"), None);
assert_eq!(written_traditional("hello"), None);
assert!(asks_simplified("把這段翻成簡體中文") && asks_simplified("用简体写给我客户") && asks_simplified("Translate to Simplified Chinese"));
assert!(!asks_simplified("不要再出簡體中文了") && !asks_simplified("為什麼一直出簡體") && !asks_simplified("今天天氣"));
let (auto, tw, cn, en) = (reply_instruction("auto"), reply_instruction("zh-TW"), reply_instruction("zh-CN"), reply_instruction("en"));
let trad = vec![Message::user("確認一下你現在用的電腦"), Message::assistant("好", "m")];
let simp = vec![Message::user("确认一下你现在用的电脑")];
// 跟著系統: by what the person writes — the case a brain on an English server got wrong.
assert!(wants_hant(&auto, &trad));
assert!(!wants_hant(&auto, &simp));
// 繁體中文: always, whatever they paste; 简体中文 and other languages: never.
assert!(wants_hant(&tw, &simp) && wants_hant(&tw, &[]));
assert!(!wants_hant(&cn, &trad) && !wants_hant(&en, &trad));
// Asked for Simplified this once — and only by the latest message.
let once = vec![Message::user("確認一下"), Message::user("把這封信翻成簡體中文")];
assert!(!wants_hant(&tw, &once) && !wants_hant(&auto, &once));
let after = vec![Message::user("把這封信翻成簡體中文"), Message::user("謝謝,再幫我查天氣")];
assert!(wants_hant(&tw, &after) && wants_hant(&auto, &after));
assert!(wants_hant(&auto, &[Message::user("不要再出簡體中文")]));
// A call with its own instructions and nothing from the person (a check, a summary):
// the instructions' own Chinese.
assert!(wants_hant("你是驗收員。只回一行 JSON。", &[]));
}
#[test] #[test]
fn languages_and_tables() { fn languages_and_tables() {
assert_eq!(LANGS.len(), 37); assert_eq!(LANGS.len(), 37);
assert_eq!(match_tag("zh-Hant-TW"), "zh-TW"); assert_eq!(match_tag("zh-Hant-TW"), "zh-TW");
set("zh-TW"); set("zh-TW");
assert_eq!(reply_text("那边的软件"), "那邊的軟體"); assert_eq!(hant("那边的软件"), "那邊的軟體");
assert_eq!(match_tag("zh-Hans-CN"), "zh-CN"); assert_eq!(match_tag("zh-Hans-CN"), "zh-CN");
assert_eq!(match_tag("ja-JP"), "ja"); assert_eq!(match_tag("ja-JP"), "ja");
assert_eq!(match_tag("pt-PT"), "pt-PT"); assert_eq!(match_tag("pt-PT"), "pt-PT");
@ -237,10 +445,12 @@ mod tests {
assert_eq!(t("權限"), "Permissions"); assert_eq!(t("權限"), "Permissions");
set("zh-TW"); set("zh-TW");
assert_eq!(t("權限"), "權限"); assert_eq!(t("權限"), "權限");
assert!(reply_instruction("ko").contains("Korean")); assert!(reply_instruction("ko").contains("Korean") && reply_instruction("ko").contains(OTHER_LINE));
assert!(reply_instruction("zh-TW").contains(HANT_LINE) && reply_instruction("zh-CN").contains(HANS_LINE));
// Every row has an English translation. // Every row has an English translation.
for r in crate::i18n_table::ROWS { for r in crate::i18n_table::ROWS {
assert!(!r.1.is_empty() && !r.2.is_empty(), "{}", r.0); assert!(!r.1.is_empty() && !r.2.is_empty(), "{}", r.0);
} }
} }
} }

View File

@ -433,6 +433,40 @@ fn retry_after_ms(resp: &ureq::http::Response<ureq::Body>) -> Option<u64> {
/// One model call with the original's retry rules: retry overloads, resets and unreachable /// One model call with the original's retry rules: retry overloads, resets and unreachable
/// backends up to 3 tries (1 s, 2 s, 4 s or Retry-After), but never once output reached the screen. /// backends up to 3 tries (1 s, 2 s, 4 s or Retry-After), but never once output reached the screen.
pub fn run_step(req: &ChatRequest, cancel: &AtomicBool, send: &dyn Fn(StreamEvent)) -> Result<StepOutput, String> { pub fn run_step(req: &ChatRequest, cancel: &AtomicBool, send: &dyn Fn(StreamEvent)) -> Result<StepOutput, String> {
// 繁體中文: what the model writes for the person, in Traditional Chinese whatever it wrote
// (see i18n::wants_hant) — as it streams, and in what the step comes to.
if !crate::i18n::wants_hant(&req.system, &req.history) {
return run_step_as_written(req, cancel, send);
}
use crate::i18n::hant;
let in_hant = |ev: StreamEvent| {
send(match ev {
StreamEvent::Text(t) => StreamEvent::Text(hant(&t)),
StreamEvent::Thinking(t) => StreamEvent::Thinking(hant(&t)),
StreamEvent::ToolCall(c) => StreamEvent::ToolCall(hant_call(c)),
other => other,
})
};
let mut out = run_step_as_written(req, cancel, &in_hant)?;
out.text = hant(&out.text);
out.thinking = hant(&out.thinking);
out.tool_calls = out.tool_calls.into_iter().map(hant_call).collect();
Ok(out)
}
/// Steps whose words are for the person to read (a question card, a card, a page, a memory, a
/// routine's name and task): their arguments are converted too. Not the others — a file's
/// name, a command, a search or a mail's recipient must stay as written.
const WORDS_FOR_THE_PERSON: &[&str] = &[crate::ask::TOOL, "show_card", "write_page", "remember", "create_routine", "update_routine"];
fn hant_call(mut c: ToolCall) -> ToolCall {
if WORDS_FOR_THE_PERSON.contains(&c.name.as_str()) {
c.args = crate::i18n::hant(&c.args);
}
c
}
fn run_step_as_written(req: &ChatRequest, cancel: &AtomicBool, send: &dyn Fn(StreamEvent)) -> Result<StepOutput, String> {
// The bot's instructions and tool descriptions in this system's words ("this computer" on Linux). // The bot's instructions and tool descriptions in this system's words ("this computer" on Linux).
#[cfg(not(target_os = "macos"))] #[cfg(not(target_os = "macos"))]
let localized = { let localized = {

View File

@ -920,11 +920,9 @@ fn device_run(v: &Value, s: &Settings, via_relay: bool, from: &str) -> Resp {
} }
if matches!(tool, "shell" | "read_file" | "edit_file" | "list_dir" | "search" | "read_terminal" | "write_terminal") { if matches!(tool, "shell" | "read_file" | "edit_file" | "list_dir" | "search" | "read_terminal" | "write_terminal") {
// The brain passes the bot's work folder inside the tool's args (empty = this home). // The brain passes the bot's work folder inside the tool's args (empty = this home).
let dir = crate::tools::args_of(args).get("workdir").and_then(Value::as_str).unwrap_or("").trim().to_string(); // (A folder chosen on another computer may not be here: then its like under this
let mut workdir = crate::tools::expand_home(if dir.is_empty() { "~" } else { &dir }); // home, or this home. The tools never fail for the folder alone.)
if !workdir.is_absolute() { let workdir = crate::tools::workdir_of_args(&crate::tools::args_of(args));
workdir = dirs::home_dir().unwrap_or(workdir);
}
let t = crate::tools::Target { name: crate::model::THIS_COMPUTER_NAME.into(), place: crate::tools::Place::Local { workdir } }; let t = crate::tools::Target { name: crate::model::THIS_COMPUTER_NAME.into(), place: crate::tools::Place::Local { workdir } };
let ids = crate::tools::RunIds { conversation: "device".into(), request: httpd::random_hex(6) }; let ids = crate::tools::RunIds { conversation: "device".into(), request: httpd::random_hex(6) };
let (text, ok) = crate::tools::run_on(tool, args, &t, &std::sync::atomic::AtomicBool::new(false), &ids); let (text, ok) = crate::tools::run_on(tool, args, &t, &std::sync::atomic::AtomicBool::new(false), &ids);
@ -941,8 +939,7 @@ const FETCH_FILE_MAX: u64 = 20 * 1024 * 1024;
fn fetch_file_here(args: &str) -> Resp { fn fetch_file_here(args: &str) -> Resp {
let v = crate::tools::args_of(args); let v = crate::tools::args_of(args);
let path = v["path"].as_str().unwrap_or("").trim().to_string(); let path = v["path"].as_str().unwrap_or("").trim().to_string();
let dir = v["workdir"].as_str().unwrap_or("").trim().to_string(); let base = crate::tools::workdir_of_args(&v);
let base = crate::tools::expand_home(if dir.is_empty() { "~" } else { &dir });
let full = crate::tools::resolve(&base, &path); let full = crate::tools::resolve(&base, &path);
// Same rule as reading a file: keys, the app's own data and other secrets never leave. // Same rule as reading a file: keys, the app's own data and other secrets never leave.
if crate::tools::is_ignored(&full) || crate::tools::is_ignored(std::path::Path::new(&path)) { if crate::tools::is_ignored(&full) || crate::tools::is_ignored(std::path::Path::new(&path)) {

View File

@ -154,6 +154,67 @@ pub fn expand_home(p: &str) -> PathBuf {
PathBuf::from(p) PathBuf::from(p)
} }
/// A folder under somebody's home — `/Users/name/…` (macOS), `/home/name/…` (Linux),
/// `C:\Users\name\…` (Windows) — as what comes after the home, with `/` between the parts
/// ("" for the home itself). None when it isn't under a home.
fn under_a_home(p: &str) -> Option<String> {
let parts: Vec<&str> = p.split(['/', '\\']).filter(|s| !s.is_empty()).collect();
let skip = match parts.as_slice() {
["Users" | "home", _, ..] if p.starts_with('/') => 2,
[drive, users, _, ..] if drive.len() == 2 && drive.ends_with(':') && users.eq_ignore_ascii_case("Users") => 3,
_ => return None,
};
Some(parts[skip..].join("/"))
}
/// A bot's work folder as it is sent to another computer: a folder under a home goes as
/// `~/…`, so `/Users/daniel/Documents` chosen on a Mac is `~/Documents` on a Linux computer,
/// whose home is elsewhere. Anything else goes as it is.
pub fn portable_dir(dir: &str) -> String {
let dir = dir.trim();
match under_a_home(dir) {
Some(rest) if rest.is_empty() => "~".into(),
Some(rest) => format!("~/{rest}"),
None => dir.to_string(),
}
}
/// The folder a tool runs in on this computer, from the work folder another computer sent.
/// The folder if it is here; else the same place under this computer's home (the folder was
/// chosen on a computer with another system or another user name); else the home itself — a
/// folder that isn't here never stops the tools, the way an unset folder doesn't.
pub fn workdir_here(dir: &str) -> PathBuf {
let home = dirs::home_dir().unwrap_or_else(std::env::temp_dir);
workdir_under(dir, &home)
}
/// The same, from a tool's arguments: `workdir_as_chosen` when that very folder is here,
/// else `workdir` (see workdir_here).
pub fn workdir_of_args(v: &Value) -> PathBuf {
let s = |k: &str| v.get(k).and_then(Value::as_str).unwrap_or("").trim().to_string();
let chosen = PathBuf::from(s("workdir_as_chosen"));
if chosen.is_absolute() && chosen.is_dir() {
return chosen;
}
workdir_here(&s("workdir"))
}
fn workdir_under(dir: &str, home: &Path) -> PathBuf {
let dir = dir.trim();
if dir.is_empty() || dir == "~" {
return home.to_path_buf();
}
let rest = dir.strip_prefix("~/").map(|r| r.to_string()).or_else(|| under_a_home(dir));
let as_given = PathBuf::from(dir);
if as_given.is_absolute() && as_given.is_dir() {
return as_given;
}
match rest {
Some(rest) if home.join(&rest).is_dir() => home.join(rest),
_ => home.to_path_buf(),
}
}
/// Make a path absolute and tidy (no `.` or `..`) without touching the disk. /// Make a path absolute and tidy (no `.` or `..`) without touching the disk.
pub fn resolve(workdir: &Path, p: &str) -> PathBuf { pub fn resolve(workdir: &Path, p: &str) -> PathBuf {
let raw = if p.trim().is_empty() { workdir.to_path_buf() } else { let raw = if p.trim().is_empty() { workdir.to_path_buf() } else {
@ -1320,7 +1381,10 @@ pub fn run_on(name: &str, args: &str, target: &Target, cancel: &AtomicBool, ids:
let cap = timeout_of(&v).min(DEVICE_SHELL_TIMEOUT_MS); let cap = timeout_of(&v).min(DEVICE_SHELL_TIMEOUT_MS);
if let Some(o) = v.as_object_mut() { if let Some(o) = v.as_object_mut() {
if !dir.is_empty() && o.get("workdir").and_then(Value::as_str).unwrap_or("").is_empty() { if !dir.is_empty() && o.get("workdir").and_then(Value::as_str).unwrap_or("").is_empty() {
o.insert("workdir".into(), serde_json::Value::String(dir.clone())); // (As `~/…` when it is under a home: that computer's home is its own. The
// folder as it was chosen goes along, for a computer where it is real.)
o.insert("workdir".into(), serde_json::Value::String(portable_dir(dir)));
o.insert("workdir_as_chosen".into(), serde_json::Value::String(dir.trim().to_string()));
} }
o.insert("timeout_ms".into(), serde_json::Value::from(cap)); o.insert("timeout_ms".into(), serde_json::Value::from(cap));
} }
@ -2027,6 +2091,39 @@ mod tests {
assert_eq!(decide("edit_file", r#"{"path":"a.txt","new_text":"x"}"#, &w, &["edit_file".into()]), Decision::Allow); assert_eq!(decide("edit_file", r#"{"path":"a.txt","new_text":"x"}"#, &w, &["edit_file".into()]), Decision::Allow);
} }
/// 換電腦: a work folder chosen on one computer still works on another with a different
/// system or user name.
#[test]
fn a_work_folder_from_another_computer_lands_under_this_home() {
assert_eq!(portable_dir("/Users/daniel"), "~");
assert_eq!(portable_dir("/Users/daniel/Documents/專案/"), "~/Documents/專案");
assert_eq!(portable_dir("/home/user/work"), "~/work");
assert_eq!(portable_dir(r"C:\Users\Daniel\Desktop"), "~/Desktop");
// Not under a home: as it is.
assert_eq!(portable_dir("/srv/data"), "/srv/data");
assert_eq!(portable_dir("~/x"), "~/x");
assert_eq!(portable_dir("Users/daniel"), "Users/daniel");
assert_eq!(portable_dir(""), "");
let home = std::env::temp_dir().join(format!("anybot-home-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&home);
std::fs::create_dir_all(home.join("Documents")).unwrap();
// The Mac's home, on a Linux computer: this home.
assert_eq!(workdir_under("/Users/someone-else", &home), home);
// A folder under it that is here too, and one that isn't.
assert_eq!(workdir_under("/Users/someone-else/Documents", &home), home.join("Documents"));
assert_eq!(workdir_under("/Users/someone-else/Nope", &home), home);
assert_eq!(workdir_under("~/Documents", &home), home.join("Documents"));
assert_eq!(workdir_under("~/Nope", &home), home);
assert_eq!(workdir_under("", &home), home);
assert_eq!(workdir_under("relative/path", &home), home);
// A real folder outside any home is used as given; a missing one falls back.
let real = home.join("Documents");
assert_eq!(workdir_under(real.to_str().unwrap(), &home), real);
assert_eq!(workdir_under("/no/such/folder/anywhere", &home), home);
let _ = std::fs::remove_dir_all(&home);
}
#[test] #[test]
fn edit_read_search() { fn edit_read_search() {
let w = wd(); let w = wd();