From c596322c3b07f2fa6a399564419e4c22e694bde5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Tue, 17 Nov 2026 12:35:31 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=AA=A2=E6=9F=A5=E9=BB=9E=E8=88=87=20?= =?UTF-8?q?/rewind=EF=BC=9ABot=20=E7=94=A8=20edit=5Ffile=20=E6=94=B9?= =?UTF-8?q?=E7=9A=84=E6=AA=94=E6=A1=88=E5=92=8C=E5=B0=8D=E8=A9=B1=E5=8F=AF?= =?UTF-8?q?=E4=BB=A5=E9=80=80=E5=9B=9E=E4=B9=8B=E5=89=8D=E8=AA=AA=E7=9A=84?= =?UTF-8?q?=E6=9F=90=E4=B8=80=E5=8F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - edit_file 改檔案前先存原本的樣子(沒有這個檔案也記),記在開始那一輪的那句話底下,同一輪同一個檔案只記一次;你的電腦、Bot 自己的電腦(Docker、封閉資料夾)、SSH 電腦都記;存在資料夾的 checkpoints/,同樣內容存一份,一週後清掉。 - /rewind 列出最近 10 句和之後改過幾個檔案;/rewind N 檔案和對話都退回(新的先退,新建的刪掉;那句話放回輸入框;退回前的整段對話收進過去的對話「退回前:…」);/rewind N 檔案、/rewind N 對話 只退一邊。檔案在背景還原,好了一行報告。 - 用指令改的、其他 AnyBot 電腦上的、超過 2 MB 的不在裡面,照實說。 - tools.rs:file_spot、file_now、file_put(box 的路徑檢查抽成 box_guard 共用);Place 可以存檔。 - 背景做完的一行字(later_notes)走同一個地方進聊天。 已驗證:cargo test 593 通過(兩輪改三個檔案:退到第二輪只還原那輪的、退到第一輪全部還原、新建的刪掉、太大的照實說;App 裡 /rewind 清單、編號不存在、退回後只剩 AnyBot 的字、草稿是那句話、退回前收進過去的對話、README 回到中文、INSTALL.md 刪掉)、clippy -D warnings 乾淨。 未驗證:Docker 和 SSH 電腦上的存與還原(走同一個 cat 的路)、真的 App 和手機上打 /rewind。 Co-Authored-By: Claude Opus 5.5 --- FEATURES.md | 11 +- docs/feature-map/chat.md | 2 +- docs/feature-map/files.md | 4 +- docs/plan-2026-11-engineering.md | 2 +- mobile/index.html | 4 +- src/agent.rs | 5 + src/app.rs | 6 +- src/app/chat_ui.rs | 2 +- src/app/commands.rs | 131 ++++++++++++++++ src/checkpoint.rs | 253 +++++++++++++++++++++++++++++++ src/main.rs | 3 + src/tools.rs | 94 +++++++++++- 12 files changed, 501 insertions(+), 16 deletions(-) create mode 100644 src/checkpoint.rs diff --git a/FEATURES.md b/FEATURES.md index 9472438..9920bd7 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -487,7 +487,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 ### 「/」清單只放指令 -- 輸入框只打「/」時,清單只列 AnyBot 自己的指令(/goal、/plan、/btw、/always-approve、/usage、/doctor、/context、/compact、/fork),標題「指令」。技能已經多到一整牆,而且 Bot 本來就讀得到自己會的技能,自己會用。 +- 輸入框只打「/」時,清單只列 AnyBot 自己的指令(/goal、/plan、/btw、/always-approve、/usage、/doctor、/context、/compact、/fork、/rewind),標題「指令」。技能已經多到一整牆,而且 Bot 本來就讀得到自己會的技能,自己會用。 - 「/」後面打字,才會再找**這個 Bot 自己會的**技能(名稱開頭符合的先,最多 6 個),想指定它用某個技能時還是可以。手機一樣。 ### 上線前補上的防護(安全和資源) @@ -1522,7 +1522,14 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 「/fork」或「/fork 名字」:把這段對話到現在為止存一份到「過去的對話」最上面,標題「分岔:名字」(沒給名字就用第一句話),聊天裡留一行「已分岔:…」。接著照常在這裡做;想回到分岔那一點走另一條路,從 Bot 選單 › 過去的對話 打開它,目前這段會自動收進過去的對話,兩條路之後互不影響、可以來回切換。參考 grok-build 的 /fork、Claude Code 的 /branch。 - 不複製整個 Bot:複製的 Bot 會把例行任務跑兩次、訊息管道回兩次。目標、計畫、記憶屬於 Bot,不跟著分岔。 - Bot 正在做事時不行(「等它做完(或按停止)再 /fork」);對話是空的也不行。電腦、大腦的螢幕、手機打的都算,由大腦做;訊息管道和團隊成員打的不算指令。 -- AnyBot 自己的指令(/btw、/goal、/plan、/always-approve、/usage、/doctor、/context、/compact、/fork)在電腦和手機/螢幕兩條路上由同一個地方認出來、同一個地方做,新增指令只要加一次。 +- AnyBot 自己的指令(/btw、/goal、/plan、/always-approve、/usage、/doctor、/context、/compact、/fork、/rewind)在電腦和手機/螢幕兩條路上由同一個地方認出來、同一個地方做,新增指令只要加一次。 + +### 檢查點與退回(/rewind) + +- Bot 用 `edit_file` 改檔案之前,AnyBot 先把那個檔案原本的樣子存起來(還沒有這個檔案也記下來),記在開始那一輪的你那句話底下;同一輪改同一個檔案好幾次只記第一次。在你的電腦、Bot 自己的電腦(Docker 或封閉資料夾)、SSH 電腦上改的都記;存在資料夾的 checkpoints/,一週後清掉,同樣的內容只存一份。參考 Claude Code 的檢查點、grok-build 的 /rewind。 +- 「/rewind」:列出這個對話裡你最近說的 10 句話(最新的在上面),每句寫「之後改過 N 個檔案」。 +- 「/rewind 編號」:檔案和對話都退回那句話之前——那句話之後改的檔案一個個還原(之後才新建的刪掉),新的改動先退,所以每個檔案都回到那句話之前的樣子;對話從那句話起拿掉,那句話放回輸入框(在別台打的照聊天裡寫的再打一次),退回前的整段對話收在過去的對話「退回前:…」,退錯了可以打開拿回來。「/rewind 編號 檔案」只退檔案、「/rewind 編號 對話」只退對話。檔案在背景還原,好了一行列出每個檔案還原了、刪掉了,或為什麼沒還原。 +- 不在檢查點裡的,照實說:用指令改的(shell 的 cat >、sed -i、git、npm…),帳號裡其他 AnyBot 電腦上改的,超過 2 MB 的檔案(退回時說「太大,當時沒有存」)。Bot 正在做事時不能退回(等它做完或按停止)。電腦、大腦的螢幕、手機打的都算,由大腦做。 ### 摘要(/context、/compact) diff --git a/docs/feature-map/chat.md b/docs/feature-map/chat.md index 25e6d2c..f1f26d4 100644 --- a/docs/feature-map/chat.md +++ b/docs/feature-map/chat.md @@ -5,7 +5,7 @@ ## 子功能 - 版面:左邊 Bot 清單(側邊欄拖到比 210 px 窄會收成頭像直欄),右邊聊天。點聊天頂部的 Bot 名稱(「查看對話詳細資訊」)打開右側面板,有「動態」「資料庫」兩頁。 -- 輸入框:Enter 送出、Shift+Enter 換行(在「1. 」「- 」這種清單裡會自動接下一項);輸入框空著按 ↑ 找回上一則;每個 Bot 的草稿各存一份,重開也在。打「/」列出 /goal、/plan、/btw、/always-approve(一律放行,見 [safety](safety.md))、/usage(用量:最近一天和一週、各 Bot 和各模型用了多少 token,模型服務有回報才有;有回報花費的才寫花費)、/doctor(診斷,見 [garden](garden.md))、/context(這個對話用了模型可讀的多少)、/compact(現在就把較早的對話整理成摘要)、/fork(分岔:這段對話到這裡為止存一份到「過去的對話」,標題「分岔:…」,之後各走各的),打「@」列出其他 Bot。 +- 輸入框:Enter 送出、Shift+Enter 換行(在「1. 」「- 」這種清單裡會自動接下一項);輸入框空著按 ↑ 找回上一則;每個 Bot 的草稿各存一份,重開也在。打「/」列出 /goal、/plan、/btw、/always-approve(一律放行,見 [safety](safety.md))、/usage(用量:最近一天和一週、各 Bot 和各模型用了多少 token,模型服務有回報才有;有回報花費的才寫花費)、/doctor(診斷,見 [garden](garden.md))、/context(這個對話用了模型可讀的多少)、/compact(現在就把較早的對話整理成摘要)、/fork(分岔:這段對話到這裡為止存一份到「過去的對話」,標題「分岔:…」,之後各走各的)、/rewind(退回:Bot 改的檔案和對話退回之前說的某一句,見 [files](files.md)),打「@」列出其他 Bot。 - 記憶小卡片:打字停一下,輸入框上方出現「帶入記憶」一列,見 [memory](memory.md)。 - 插話:Bot 工作中照樣打字送出,不另開一輪,Bot 下一步就讀到(附檔一起進去);輸入框下方寫「已排入「…」,Bot 會在下一步看到」。這一輪剛好結束、來不及讀的,自動變成下一輪。 - 停止:工作中、輸入框空著時,送出鈕變成「停止」。 diff --git a/docs/feature-map/files.md b/docs/feature-map/files.md index a752e04..87825e6 100644 --- a/docs/feature-map/files.md +++ b/docs/feature-map/files.md @@ -11,6 +11,7 @@ Bot 在它能用的電腦上跑指令、讀寫和搜尋檔案、開背景指令 - 工作資料夾:這台電腦是 Bot 設定的「起始資料夾」(沒填就是家目錄);Bot 自己的電腦是它自己的資料夾;SSH 電腦是設定的資料夾或對方的家目錄。 - 交出結果:`send_file` 把檔案放進聊天變成檔案卡片,點一下預覽、可以下載;`open_for_person` 在使用者的螢幕上打開檔案或網址;`publish_site` 把一個 .html 檔或有 index.html 的資料夾發佈成公開網站,回傳網址,同一個名字再發佈就取代。 - 傳到帳號裡另一台裝置是 `send_to_device`(見 [computers](computers.md))。 +- 檢查點:`edit_file` 改檔案前,AnyBot 先把檔案原本的樣子存起來(記在開始那一輪的那句話底下,存一週)。使用者打「/rewind」看可以退回的點,「/rewind 編號」把那句話之後改的檔案還原、對話退回那句話之前,「/rewind 編號 檔案」只退檔案、「/rewind 編號 對話」只退對話。 ## 使用者怎麼到 @@ -23,7 +24,7 @@ Bot 在它能用的電腦上跑指令、讀寫和搜尋檔案、開背景指令 ## 怎麼操作 - Bot:先用 `list_dir`、`search`、`read_file` 看清楚再動手,改檔案用 `edit_file`。跑很久的指令讓它進背景,再用 `read_terminal` 的 wait_ms 等,不要一直重查;指令列的 AI 工具用它們的非互動模式(例如 `claude -p "…"`)。一定要看終端機畫面時才用 interactive,用完關掉。每個工具都有 `computer`。交結果用 `send_file`,不要只說檔案在哪;要使用者馬上看到用 `open_for_person`;要公開網址用 `publish_site`(path,name 只用英文字母、數字和 -)。除了 `send_file`,這些都屬於「檔案與指令」能力。結果太長被截(只留開頭和結尾,中間寫「完整內容用 read_result 讀:id=…」)或較早的結果被收起時,用 `read_result`(id、from、chars,一次最多兩萬字)讀完整的,不要為了看完整的再做一次那一步(每個 Bot 都有,完整結果留 7 天)。 -- 驗證:請 Bot 在它自己的電腦寫一個 report.md 傳給你,聊天要出現檔案卡片,點開看得到內容;請它讀這台電腦工作資料夾外的檔案,要跳出「讀取工作資料夾以外的地方:…」;請它跑 `sleep 40; echo done`,要說已移到背景,再用 `read_terminal` 等到 done。自動測試:`cargo test tools::`、`cargo test pty::`、`cargo test agent::`、`cargo test preview::`、`cargo test app::files_ui::`。 +- 驗證:請 Bot 在它自己的電腦寫一個 report.md 傳給你,聊天要出現檔案卡片,點開看得到內容;請它讀這台電腦工作資料夾外的檔案,要跳出「讀取工作資料夾以外的地方:…」;請它跑 `sleep 40; echo done`,要說已移到背景,再用 `read_terminal` 等到 done。自動測試:`cargo test tools::`、`cargo test pty::`、`cargo test agent::`、`cargo test preview::`、`cargo test app::files_ui::`、`cargo test rewind`。請 Bot 改兩個檔案,再打「/rewind」選那一句,兩個檔案要回到原本的內容、那句話回到輸入框。 ## 陷阱 @@ -36,4 +37,5 @@ Bot 在它能用的電腦上跑指令、讀寫和搜尋檔案、開背景指令 - `open_for_person` 不打開程式或指令檔(打開就會執行),改用 `send_file`;AnyBot 在伺服器上時,網址會在使用者正在用的那台電腦打開(不知道是哪台就打不開),檔案打不開,也改用 `send_file`。 - SSH 電腦上的檔案不能直接 `send_file`、`open_for_person` 或 `publish_site`;帳號裡其他電腦的檔案可以 `send_file`(最多 20 MB),但不能打開或發佈。先複製到 Bot 自己的電腦。 - `publish_site`:任何知道網址的人都看得到。每個網站名字第一次會問(工作資料夾外的每次都問);最多 500 個檔案、25 MB;點開頭的檔案、node_modules、機密檔案、指到資料夾外的連結會略過;一定要有 index.html。 +- 檢查點只記 `edit_file` 改的:用 `shell` 改的(cat >、sed -i、git、npm…)不在裡面,帳號裡其他 AnyBot 電腦上的檔案也不在;超過 2 MB 的檔案不存,退回時會說沒辦法還原。要能退回,改檔案就用 `edit_file`。 - 按停止會停掉正在跑的那一步,和這個 Bot 的互動終端機(連同它們啟動的程式);一般的背景指令(例如故意開著的伺服器)會繼續跑。「重新啟動這個 Bot」停掉這個 Bot 的全部背景指令,關掉 App 全部停掉。整個 AnyBot 同時最多 24 個背景指令在跑,滿了新的不會留在背景(會先停掉),用不到的用 stop 關掉。 diff --git a/docs/plan-2026-11-engineering.md b/docs/plan-2026-11-engineering.md index 1ca1da8..15b47ff 100644 --- a/docs/plan-2026-11-engineering.md +++ b/docs/plan-2026-11-engineering.md @@ -97,7 +97,7 @@ ## 軌 M:新機制 -### M1. 檢查點與 /rewind ⬜ +### M1. 檢查點與 /rewind ✅(只記 edit_file 改的,跟 Claude Code 一樣;git stash create 沒做:指令改的東西太多種,退回時會連使用者自己改的一起退) - 做法:每一輪第一次改檔案前,替工作資料夾的檔案(git 專案用 `git stash create`,其他用改之前的副本)存一個檢查點;`/rewind` 列出最近的檢查點,選一個把檔案和對話退回那裡。 - 做完:改了三個檔案後 /rewind,三個檔案回到原本內容。 diff --git a/mobile/index.html b/mobile/index.html index 20a0630..27f39b5 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -1656,7 +1656,7 @@ input.addEventListener("keydown", (e) => { input.addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.shiftKey && !e.isComposing && matchMedia("(pointer:fine)").matches) { e.preventDefault(); send(); } }); const SL = {hits: [], lit: 0, q: null, moved: false, closed: false, loading: false, fresh: false, at: false}; /** AnyBot's own / commands (goal.rs on the brain). */ -const COMMANDS = [{name: "goal", description: "設一個目標,一直做到達成為止(/goal clear 清除)"}, {name: "plan", description: "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"}, {name: "always-approve", description: "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)"}, {name: "usage", description: "用量:最近一天和一週,各 Bot、各模型用了多少 token"}, {name: "doctor", description: "診斷:檢查大腦的連線、模型服務、Bot 的電腦、連接器、磁碟"}, {name: "context", description: "這個對話用了模型可讀的多少"}, {name: "compact", description: "現在就把較早的對話整理成摘要"}, {name: "fork", description: "分岔:這段對話存一份到過去的對話,之後各走各的"}, {name: "btw", description: "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"}]; +const COMMANDS = [{name: "goal", description: "設一個目標,一直做到達成為止(/goal clear 清除)"}, {name: "plan", description: "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"}, {name: "always-approve", description: "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)"}, {name: "usage", description: "用量:最近一天和一週,各 Bot、各模型用了多少 token"}, {name: "doctor", description: "診斷:檢查大腦的連線、模型服務、Bot 的電腦、連接器、磁碟"}, {name: "context", description: "這個對話用了模型可讀的多少"}, {name: "compact", description: "現在就把較早的對話整理成摘要"}, {name: "fork", description: "分岔:這段對話存一份到過去的對話,之後各走各的"}, {name: "rewind", description: "退回:把 Bot 改的檔案和對話退回之前說的某一句"}, {name: "btw", description: "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"}]; const GOAL_TAG = "[目標]"; /** The skills a draft like 「/pp」 asks for, as the brain ranks them: name starts with it, name * contains it, then description. None once a space ends the name, or while the bot works. */ @@ -1754,7 +1754,7 @@ async function send() { const memories = b.busy ? undefined : memPicks(); memReset(); input.value = ""; input.style.height = "auto"; $("composer").classList.remove("tall"); S.pending = []; renderChips(); renderSlash(); - const quiet = /^\/(goal|plan)(\s+(clear|stop|off|reset|none|cancel|清除|取消|停止))?\s*$/i.test(text) || /^\/(always-approve|yolo)(\s|$)/i.test(text) || /^\/(usage|doctor|context|compact)\s*$/i.test(text) || /^\/fork(\s|$)/.test(text); + const quiet = /^\/(goal|plan)(\s+(clear|stop|off|reset|none|cancel|清除|取消|停止))?\s*$/i.test(text) || /^\/(always-approve|yolo)(\s|$)/i.test(text) || /^\/(usage|doctor|context|compact)\s*$/i.test(text) || /^\/(fork|rewind)(\s|$)/.test(text); if (!b.busy && !quiet) { S.msgs.push({role: "user", text, attachments: [], memories: memories || []}); renderMsgs(); $("scroller").scrollTop = 1e9; } // 先顯示: while it works the words aren't in the chat yet — shown at once all the same. const sent = b.busy && text ? {bot: S.open, text, at: Date.now(), failed: false} : null; diff --git a/src/agent.rs b/src/agent.rs index bc0e923..ff23dbd 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -3290,6 +3290,11 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< (Ok(()), Ok(t)) => { started(); let ids = tools::RunIds { conversation: bot_id.to_string(), request: call.id.clone() }; + // 檢查點: the file as it was, kept under the person's message that started this turn (/rewind). + if call.name == "edit_file" { + let turn = history.iter().rev().find(|m| m.role == Role::User && !m.note && m.at > 0).map(|m| m.at).unwrap_or(0); + crate::checkpoint::before_edit(bot_id, turn, t, &call.args); + } let (out, ok) = if is_mac && on_device.is_none() { crate::macapps::run(&call.name, &call.args) } else if let (true, Some(host)) = (is_screen || is_web || is_mac, on_device.as_ref()) { diff --git a/src/app.rs b/src/app.rs index 38676fb..d51b4c2 100644 --- a/src/app.rs +++ b/src/app.rs @@ -214,6 +214,8 @@ pub struct App { want_direct: std::cell::Cell, /// 診斷 (/doctor) reports finished on their thread: (the chat it was asked in, the report). doctor_out: Arc>>, + /// Lines for a bot's chat that work on another thread finished (/rewind's files…). + later_notes: Arc>>, /// 「/compact」 summaries finished on their thread: (bot, (messages replaced, summary, first kept message's time)). #[allow(clippy::type_complexity)] compact_out: Arc)>>>, @@ -496,6 +498,7 @@ impl App { want_direct: Default::default(), strangers: Default::default(), doctor_out: Default::default(), + later_notes: Default::default(), compact_out: Default::default(), managed: if demo { policy::Managed::default() } else { policy::read() }, settings_was_open: false, @@ -5961,6 +5964,7 @@ impl App { // 診斷: a 「/doctor」 that finished; a 「/compact」 too. self.doctor_tick(); self.compact_tick(); + self.later_tick(); // A screen of another AnyBot's brain: its bots work there, not here. if self.mir.on { self.remote_tick(ctx); @@ -8532,7 +8536,7 @@ mod tests { let mut bot = app.state.bots[0].clone(); bot.skills = Some(vec!["週報".into()]); let names = |l: Vec<(String, String)>| l.into_iter().map(|x| x.0).collect::>(); - assert_eq!(names(app.slash_list("/", &bot)), vec!["goal", "plan", "btw", "always-approve", "usage", "doctor", "context", "compact", "fork"]); + assert_eq!(names(app.slash_list("/", &bot)), vec!["goal", "plan", "btw", "always-approve", "usage", "doctor", "context", "compact", "fork", "rewind"]); assert_eq!(names(app.slash_list("/週", &bot)), vec!["週報"], "its own, by the word"); assert_eq!(names(app.slash_list("/b", &bot)), vec!["btw"]); } diff --git a/src/app/chat_ui.rs b/src/app/chat_ui.rs index 28eb00f..7d36438 100644 --- a/src/app/chat_ui.rs +++ b/src/app/chat_ui.rs @@ -1134,7 +1134,7 @@ fn jump_shows(from_bottom: f32, jumping: bool) -> bool { } /// AnyBot's own / commands: (name, what it does). The brain acts on them itself (goal.rs). -pub const SLASH_COMMANDS: [(&str, &str); 9] = [("goal", "設一個目標,一直做到達成為止(/goal clear 清除)"), ("plan", "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"), ("btw", "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"), ("always-approve", "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)"), ("usage", "用量:最近一天和一週,各 Bot、各模型用了多少 token"), ("doctor", "診斷:檢查這台電腦的連線、大腦、模型服務、Bot 的電腦、連接器、磁碟"), ("context", "這個對話用了模型可讀的多少"), ("compact", "現在就把較早的對話整理成摘要"), ("fork", "分岔:這段對話存一份到過去的對話,之後各走各的")]; +pub const SLASH_COMMANDS: [(&str, &str); 10] = [("goal", "設一個目標,一直做到達成為止(/goal clear 清除)"), ("plan", "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"), ("btw", "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"), ("always-approve", "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)"), ("usage", "用量:最近一天和一週,各 Bot、各模型用了多少 token"), ("doctor", "診斷:檢查這台電腦的連線、大腦、模型服務、Bot 的電腦、連接器、磁碟"), ("context", "這個對話用了模型可讀的多少"), ("compact", "現在就把較早的對話整理成摘要"), ("fork", "分岔:這段對話存一份到過去的對話,之後各走各的"), ("rewind", "退回:把 Bot 改的檔案和對話退回之前說的某一句")]; /// What the bot is doing, in the one line beside its face (and on a colleague's card, the phone). /// A status of several lines — a retry: the error, what it means, when it tries again — used to diff --git a/src/app/commands.rs b/src/app/commands.rs index 0cd1965..f5d7ac3 100644 --- a/src/app/commands.rs +++ b/src/app/commands.rs @@ -21,8 +21,12 @@ pub(super) enum AppCommand { Compact, Doctor, Fork(String), + Rewind(Result), } +/// How many of the person's messages /rewind offers. +const REWIND_POINTS: usize = 10; + /// A branch's title: 「分岔:」 and the name given, or the conversation's first words. pub(super) const FORK_PREFIX: &str = "分岔:"; @@ -55,6 +59,9 @@ pub(super) fn app_command(text: &str) -> Option { if let Some(name) = fork_command(text) { return Some(AppCommand::Fork(name)); } + if let Some(r) = crate::checkpoint::command(text) { + return Some(AppCommand::Rewind(r)); + } match text.trim() { "/context" => Some(AppCommand::Context), "/compact" => Some(AppCommand::Compact), @@ -75,9 +82,88 @@ impl App { AppCommand::Compact => self.compact_now(bot_id), AppCommand::Doctor => self.doctor_start(bot_id), AppCommand::Fork(name) => self.fork_now(bot_id, &name), + AppCommand::Rewind(Err(e)) => self.goal_note(bot_id, &e), + AppCommand::Rewind(Ok(r)) => self.rewind(bot_id, r), } } + /// Lines that work on another thread finished, into their chats. + pub(super) fn later_tick(&mut self) { + let later = std::mem::take(&mut *self.later_notes.lock().unwrap()); + for (bot_id, text) in later { + self.goal_note(bot_id, &text); + self.save_now = true; + } + } + + /// The points 「/rewind」 can go back to: the person's messages in this conversation, newest + /// first (index in the chat, its time, its words). + fn rewind_points(&self, bot_id: u64) -> Vec<(usize, i64, String)> { + let Some(b) = self.state.bot(bot_id) else { return vec![] }; + b.messages.iter().enumerate().rev().filter(|(_, m)| m.role == Role::User && !m.note && m.at > 0).take(REWIND_POINTS).map(|(i, m)| (i, m.at, m.text.clone())).collect() + } + + /// 「/rewind」 (the points) or 「/rewind N [檔案|對話]」 (back to one). + pub(super) fn rewind(&mut self, bot_id: u64, r: crate::checkpoint::Rewind) { + use crate::checkpoint::Rewind; + let points = self.rewind_points(bot_id); + let kept = crate::checkpoint::entries(bot_id); + let Some(b) = self.state.bot(bot_id) else { return }; + let name = b.name.clone(); + let (n, files, chat) = match r { + Rewind::List => { + if points.is_empty() { + self.goal_note(bot_id, "這個對話還沒有可以退回的點。"); + return; + } + let now = crate::model::now_ms(); + let mut text = format!("可以退回的點(最新的在最上面):退回去會把那句話之後 {name} 用 edit_file 改的檔案還原;用指令(shell、git…)改的不在裡面。"); + for (k, (_, at, words)) in points.iter().enumerate() { + let n = crate::checkpoint::files_since(&kept, *at).len(); + text.push_str(&format!("\n{}. {}「{}」:{}", k + 1, crate::pages::ago(*at, now), first_line(words, 30), if n == 0 { "之後沒有改過檔案".to_string() } else { format!("之後改過 {n} 個檔案") })); + } + text.push_str("\n打「/rewind 編號」檔案和對話都退回那句話之前;「/rewind 編號 檔案」只退檔案;「/rewind 編號 對話」只退對話。"); + self.goal_note(bot_id, &text); + return; + } + Rewind::To { n, files, chat } => (n, files, chat), + }; + if self.streams.contains_key(&bot_id) { + self.goal_note(bot_id, &format!("{name} 正在做事:等它做完(或按停止)再 /rewind。")); + return; + } + let Some((i, at, words)) = points.get(n - 1).cloned() else { + self.goal_note(bot_id, &format!("沒有第 {n} 個點:打 /rewind 看有哪些。")); + return; + }; + 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. + let mut copy = b.messages.clone(); + copy.iter_mut().for_each(|m| m.images.clear()); + let title = format!("退回前:{}", first_line(&words, 24)); + b.threads.insert(0, (title.clone(), copy)); + b.threads.truncate(50); + b.messages.truncate(i); + b.regen_undo.clear(); + b.draft = words.clone(); + self.drafts.insert(bot_id, words.clone()); + self.goal_note(bot_id, &format!("對話退回到你說「{}」之前,那句話放回輸入框了(在別台打的就照這裡再打一次)。退回前的整段對話收在過去的對話「{title}」。", first_line(&words, 40))); + } + if files { + let out = self.later_notes.clone(); + let repaint = self.repaint_fn(); + self.goal_note(bot_id, "正在還原檔案…"); + std::thread::spawn(move || { + let lines = crate::checkpoint::restore(bot_id, at); + let text = if lines.is_empty() { "檔案:那句話之後沒有用 edit_file 改過檔案,沒有要還原的(用指令改的不在檢查點裡)。".to_string() } else { format!("檔案退回到那句話之前:\n{}", lines.iter().map(|l| format!("- {l}")).collect::>().join("\n")) }; + out.lock().unwrap().push((bot_id, text)); + repaint(); + }); + } + self.mark(); + } + /// 「/fork」: this conversation, as it is now, kept in 過去的對話 too. pub(super) fn fork_now(&mut self, bot_id: u64, name: &str) { let Some(b) = self.state.bot(bot_id) else { return }; @@ -152,4 +238,49 @@ mod tests { assert!(app.state.bot(busy).unwrap().messages.iter().any(|m| m.note && m.text.contains("正在做事"))); } } + + /// 「/rewind」 lists the person's messages with how many files changed after each; going + /// back to one puts the files back, the chat back to before it (its words in the input box, + /// the whole chat in 過去的對話). + #[test] + fn rewind_takes_files_and_chat_back() { + let ctx = egui::Context::default(); + let mut app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-rewind.png"))); + let id = app.state.bots.iter().find(|b| b.members.is_empty() && !app.streams.contains_key(&b.id)).unwrap().id; + let w = std::env::temp_dir().join(format!("anybot-rewind-app-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&w); + std::fs::create_dir_all(&w).unwrap(); + std::fs::write(w.join("README.md"), "中文版").unwrap(); + let t = crate::tools::Target { name: "你的電腦".into(), place: crate::tools::Place::Local { workdir: w.clone() } }; + let said = |text: &str, at: i64| Message { at, ..Message::user(text) }; + app.state.bot_mut(id).unwrap().messages = vec![said("把 README 改成英文", 1_000), Message::assistant("改好了", "m"), said("再加一段安裝說明", 2_000), Message::assistant("加好了", "m")]; + crate::checkpoint::before_edit(id, 1_000, &t, r#"{"path":"README.md"}"#); + std::fs::write(w.join("README.md"), "English").unwrap(); + crate::checkpoint::before_edit(id, 2_000, &t, r#"{"path":"INSTALL.md"}"#); + std::fs::write(w.join("INSTALL.md"), "install").unwrap(); + let run = |app: &mut App, text: &str| { + let cmd = app_command(text).unwrap(); + app.run_app_command(&ctx, id, cmd, text, vec![], None); + }; + run(&mut app, "/rewind"); + let list = app.state.bot(id).unwrap().messages.last().unwrap().text.clone(); + assert!(list.contains("1. ") && list.contains("再加一段安裝說明") && list.contains("之後改過 1 個檔案") && list.contains("把 README 改成英文") && list.contains("之後改過 2 個檔案"), "{list}"); + run(&mut app, "/rewind 9"); + assert!(app.state.bot(id).unwrap().messages.last().unwrap().text.contains("沒有第 9 個")); + run(&mut app, "/rewind 2"); + let b = app.state.bot(id).unwrap(); + assert!(b.messages.iter().all(|m| m.note), "only AnyBot's lines are left: {:?}", b.messages); + assert_eq!(b.draft, "把 README 改成英文"); + assert!(b.threads[0].0.starts_with("退回前:") && b.threads[0].1.len() >= 4); + let until = std::time::Instant::now() + std::time::Duration::from_secs(10); + while app.later_notes.lock().unwrap().is_empty() && std::time::Instant::now() < until { + std::thread::sleep(std::time::Duration::from_millis(20)); + } + app.later_tick(); + let report = app.state.bot(id).unwrap().messages.last().unwrap().text.clone(); + assert!(report.contains("README.md") && report.contains("INSTALL.md"), "{report}"); + assert_eq!(std::fs::read_to_string(w.join("README.md")).unwrap(), "中文版"); + assert!(!w.join("INSTALL.md").exists()); + let _ = std::fs::remove_dir_all(&w); + } } diff --git a/src/checkpoint.rs b/src/checkpoint.rs new file mode 100644 index 0000000..d8f7e87 --- /dev/null +++ b/src/checkpoint.rs @@ -0,0 +1,253 @@ +//! 檢查點與 /rewind (M1). Before a bot changes a file with edit_file, what the file was is kept, +//! under the person's message that started that turn (its time). 「/rewind」 lists those messages; +//! 「/rewind N」 puts the files back as they were before the N-th and takes the chat back to just +//! before it; 「/rewind N 檔案」 only the files, 「/rewind N 對話」 only the chat. Like Claude +//! Code's checkpoints: what commands changed (shell, git, npm…) isn't in them, nor files on +//! another AnyBot (裝置連結: that computer's files are its own). Kept a week, in the data folder. + +use crate::tools::{Place, Target}; +use serde::{Deserialize, Serialize}; +use std::path::PathBuf; + +/// Kept this long. +const KEEP_DAYS: i64 = 7; +/// A file bigger than this isn't kept (it can't be put back; /rewind says so). +pub const MAX_FILE_BYTES: usize = 2 * 1024 * 1024; + +/// One file as it was before a turn changed it. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct Entry { + /// When it was kept. + pub at: i64, + /// The person's message that started the turn (its `at`). + pub turn: i64, + /// The computer's name, to show. + pub computer: String, + pub place: Place, + pub path: String, + /// Its content before (the name it is kept under); None: the file wasn't there. + pub before: Option, + /// Too big to keep: it can't be put back. + #[serde(default)] + pub too_big: bool, +} + +fn dir() -> PathBuf { + crate::model::State::path().parent().map(|d| d.join("checkpoints")).unwrap_or_else(|| std::env::temp_dir().join("anybot-checkpoints")) +} + +fn log_of(bot: u64) -> PathBuf { + dir().join(format!("bot-{bot}.jsonl")) +} + +fn blob(name: &str) -> PathBuf { + dir().join("blobs").join(name) +} + +/// This bot's kept files, oldest first (a week's). +pub fn entries(bot: u64) -> Vec { + let since = crate::model::now_ms() - KEEP_DAYS * 86_400_000; + std::fs::read_to_string(log_of(bot)).unwrap_or_default().lines().filter_map(|l| serde_json::from_str::(l).ok()).filter(|e| e.at >= since).collect() +} + +fn write_all(bot: u64, list: &[Entry]) -> Result<(), String> { + let text: String = list.iter().filter_map(|e| serde_json::to_string(e).ok()).map(|l| l + "\n").collect(); + std::fs::create_dir_all(dir()).map_err(|e| e.to_string())?; + std::fs::write(log_of(bot), text).map_err(|e| e.to_string()) +} + +/// Before edit_file changes `args`' file on `target` in the turn that `turn` started: keep it as +/// it is now (once per turn and file). Nothing on another AnyBot; a failure only goes to the log. +pub fn before_edit(bot: u64, turn: i64, target: &Target, args: &str) { + if turn == 0 { + return; + } + let path = crate::tools::arg_str(&crate::tools::args_of(args), "path"); + if path.trim().is_empty() { + return; + } + let Some(spot) = crate::tools::file_spot(target, &path) else { return }; + let (place, path) = match spot { + Ok(s) => s, + Err(e) => { + log::info!("檢查點:{path} 找不到位置:{e}"); + return; + } + }; + let mut list = entries(bot); + if list.iter().any(|e| e.turn == turn && e.place == place && e.path == path) { + return; + } + let (before, too_big) = match crate::tools::file_now(&place, &path) { + Ok(None) => (None, false), + Ok(Some(b)) if b.len() > MAX_FILE_BYTES => (None, true), + Ok(Some(b)) => match keep(&b) { + Ok(name) => (Some(name), false), + Err(e) => { + log::warn!("檢查點:存不了 {path}:{e}"); + return; + } + }, + Err(e) => { + log::warn!("檢查點:讀不到 {path}:{e}"); + return; + } + }; + list.push(Entry { at: crate::model::now_ms(), turn, computer: target.name.clone(), place, path, before, too_big }); + if let Err(e) = write_all(bot, &list) { + log::warn!("檢查點:寫不進紀錄:{e}"); + } +} + +/// Keep a file's content under the name of its hash (the same content kept once). +fn keep(bytes: &[u8]) -> Result { + let name: String = ring::digest::digest(&ring::digest::SHA256, bytes).as_ref().iter().map(|x| format!("{x:02x}")).collect(); + let p = blob(&name); + std::fs::create_dir_all(dir().join("blobs")).map_err(|e| e.to_string())?; + // (Written again when already there: its time says it is still in use, for prune.) + std::fs::write(&p, bytes).map_err(|e| e.to_string())?; + Ok(name) +} + +/// The files the turns from `turn` on changed (each file once), to show. +pub fn files_since(list: &[Entry], turn: i64) -> Vec<&Entry> { + let mut seen: Vec<&Entry> = vec![]; + for e in list.iter().filter(|e| e.turn >= turn) { + if !seen.iter().any(|s| s.place == e.place && s.path == e.path) { + seen.push(e); + } + } + seen +} + +/// Put back every file the turns from `turn` on changed, as it was before them (newest change +/// undone first, so each file ends as it was before the first). Those entries are used up. +/// One line per file. +pub fn restore(bot: u64, turn: i64) -> Vec { + let list = entries(bot); + let (undo, keep_list): (Vec, Vec) = list.into_iter().partition(|e| e.turn >= turn); + let mut lines: Vec<(String, String)> = vec![]; + for e in undo.iter().rev() { + let what = if e.computer.is_empty() { e.path.clone() } else { format!("{}({})", e.path, e.computer) }; + let r = if e.too_big { + Err("太大(超過 2 MB),當時沒有存".to_string()) + } else { + match &e.before { + None => crate::tools::file_put(&e.place, &e.path, None).map(|_| "刪掉了(那時還沒有這個檔案)"), + Some(name) => std::fs::read(blob(name)).map_err(|err| format!("存的內容不見了:{err}")).and_then(|b| crate::tools::file_put(&e.place, &e.path, Some(&b))).map(|_| "還原了"), + } + }; + // (Each file is reported once: by the change undone last, the one that counts.) + lines.retain(|l| l.0 != what); + lines.push((what.clone(), match r { + Ok(word) => format!("{what}:{word}"), + Err(err) => format!("{what}:沒有還原,{err}"), + })); + } + if let Err(e) = write_all(bot, &keep_list) { + log::warn!("檢查點:寫不進紀錄:{e}"); + } + lines.into_iter().map(|(_, l)| l).collect() +} + +/// Kept content no entry has used for longer than a week goes (at start). +pub fn prune() { + let Ok(rd) = std::fs::read_dir(dir().join("blobs")) else { return }; + let old = std::time::SystemTime::now() - std::time::Duration::from_secs((KEEP_DAYS as u64 + 1) * 86_400); + for e in rd.flatten() { + if e.metadata().and_then(|m| m.modified()).is_ok_and(|t| t < old) { + let _ = std::fs::remove_file(e.path()); + } + } +} + +/// What 「/rewind …」 asks for. +#[derive(Clone, Debug, PartialEq)] +pub enum Rewind { + /// The list of points. + List, + /// Back to point N (1 = the newest): files, chat, or both. + To { n: usize, files: bool, chat: bool }, +} + +/// 「/rewind」, 「/rewind 2」, 「/rewind 2 檔案」, 「/rewind 2 對話」 (None: not this command; +/// Some(Err) when the words after it can't be read). +pub fn command(text: &str) -> Option> { + let rest = text.trim().strip_prefix("/rewind")?; + if !(rest.is_empty() || rest.starts_with(char::is_whitespace)) { + return None; + } + let mut words = rest.split_whitespace(); + let Some(n) = words.next() else { return Some(Ok(Rewind::List)) }; + let Ok(n) = n.parse::() else { return Some(Err(format!("「{n}」不是編號:先打 /rewind 看有哪些點,再打 /rewind 編號"))) }; + if n == 0 { + return Some(Err("編號從 1 開始".into())); + } + let (files, chat) = match words.next() { + None => (true, true), + Some("檔案" | "files" | "code") => (true, false), + Some("對話" | "chat" | "conversation") => (false, true), + Some(w) => return Some(Err(format!("「{w}」看不懂:後面可以加「檔案」(只退檔案)或「對話」(只退對話),不加就兩個都退"))), + }; + Some(Ok(Rewind::To { n, files, chat })) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_words_after_rewind() { + assert_eq!(command("/rewind"), Some(Ok(Rewind::List))); + assert_eq!(command(" /rewind 2 "), Some(Ok(Rewind::To { n: 2, files: true, chat: true }))); + assert_eq!(command("/rewind 1 檔案"), Some(Ok(Rewind::To { n: 1, files: true, chat: false }))); + assert_eq!(command("/rewind 3 對話"), Some(Ok(Rewind::To { n: 3, files: false, chat: true }))); + assert!(matches!(command("/rewind x"), Some(Err(_))) && matches!(command("/rewind 0"), Some(Err(_))) && matches!(command("/rewind 1 全部"), Some(Err(_)))); + assert_eq!(command("/rewinder"), None); + assert_eq!(command("請 /rewind"), None); + } + + /// Three files changed over two turns: going back to the first puts all three back (one that + /// didn't exist goes); going back to the second only what that turn changed. + #[test] + fn rewinding_puts_the_files_back() { + let bot = 900_000 + std::process::id() as u64; + let w = std::env::temp_dir().join(format!("anybot-rewind-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&w); + std::fs::create_dir_all(&w).unwrap(); + let _ = std::fs::remove_file(log_of(bot)); + let t = Target { name: "這台".into(), place: Place::Local { workdir: w.clone() } }; + std::fs::write(w.join("a.txt"), "a0").unwrap(); + std::fs::write(w.join("b.txt"), "b0").unwrap(); + let edit = |turn: i64, f: &str, text: &str| { + before_edit(bot, turn, &t, &serde_json::json!({"path": f, "new_text": text}).to_string()); + std::fs::write(w.join(f), text).unwrap(); + }; + edit(100, "a.txt", "a1"); + edit(100, "a.txt", "a2"); // (the same turn: kept once, as it was before the turn) + edit(100, "new.txt", "n1"); + edit(200, "b.txt", "b1"); + edit(200, "a.txt", "a3"); + assert_eq!(entries(bot).len(), 4); + assert_eq!(files_since(&entries(bot), 100).len(), 3); + assert_eq!(files_since(&entries(bot), 200).len(), 2); + // Back to the second turn: b and a as they were before it. + let lines = restore(bot, 200); + assert_eq!(lines.len(), 2, "{lines:?}"); + assert_eq!(std::fs::read_to_string(w.join("a.txt")).unwrap(), "a2"); + assert_eq!(std::fs::read_to_string(w.join("b.txt")).unwrap(), "b0"); + assert_eq!(std::fs::read_to_string(w.join("new.txt")).unwrap(), "n1"); + // Then to the first: everything as it was, the new file gone. + let lines = restore(bot, 100); + assert!(lines.iter().any(|l| l.contains("new.txt") && l.contains("刪掉了")), "{lines:?}"); + assert_eq!(std::fs::read_to_string(w.join("a.txt")).unwrap(), "a0"); + assert!(!w.join("new.txt").exists()); + assert!(entries(bot).is_empty(), "used up"); + // Too big to keep: said, not pretended. + std::fs::write(w.join("big.bin"), vec![b'x'; MAX_FILE_BYTES + 1]).unwrap(); + edit(300, "big.bin", "small"); + assert!(restore(bot, 300)[0].contains("太大")); + let _ = std::fs::remove_file(log_of(bot)); + let _ = std::fs::remove_dir_all(&w); + } +} diff --git a/src/main.rs b/src/main.rs index 3e03afc..3f51aeb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -13,6 +13,7 @@ mod botbrowser; mod browser; mod cloudbox; mod channels; +mod checkpoint; mod computer; mod desktop; mod diagram; @@ -344,6 +345,8 @@ fn main() -> eframe::Result<()> { logfile::init(); // 完整結果 older than a week go. outputs::prune(); + // 檢查點 kept content no change has used for a week. + checkpoint::prune(); // `anybot --update-box` (make update-box): 更新 Bot 的電腦 from a terminal, by this AnyBot — // or the one running on this data folder (cloudbox::update_box_cli). if args.get(1).map(String::as_str) == Some("--update-box") { diff --git a/src/tools.rs b/src/tools.rs index 749b9c1..45ef254 100644 --- a/src/tools.rs +++ b/src/tools.rs @@ -132,7 +132,7 @@ pub fn unwrapped_args(args: &str, props: Option<&Value>) -> Option { inner.is_object().then(|| inner.to_string()) } -fn arg_str(v: &Value, k: &str) -> String { +pub(crate) fn arg_str(v: &Value, k: &str) -> String { v.get(k).and_then(Value::as_str).unwrap_or("").to_string() } @@ -1445,7 +1445,7 @@ fn timeout_of(v: &Value) -> u64 { // Here the bot's own computer is a sealed folder, this Mac is the person's computer, and other // computers are reached over SSH. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub enum Place { /// The bot's own computer when Docker isn't there: everything outside `root` in the home /// folder is invisible. @@ -1742,11 +1742,7 @@ pub fn run_on(name: &str, args: &str, target: &Target, cancel: &AtomicBool, ids: let (p, path, box_guard) = match place { Place::Box { dir } if name != "shell" => match box_path(std::path::Path::new(dir), &p) { Ok(s) => { - let g = format!( - "base=$(realpath -m -- {base}) && real=$(realpath -m -- {target}) && case \"$real\" in \"$base\"|\"$base\"/*) ;; *) echo '連結指到了你的專屬資料夾以外的地方' >&2; exit 1;; esac; ", - base = sh_quote(dir), - target = sh_quote(&s), - ); + let g = box_guard(dir, &s); (s.clone(), s, g) } Err(e) => return (e, false), @@ -1806,6 +1802,90 @@ pub fn run_on(name: &str, args: &str, target: &Target, cancel: &AtomicBool, ids: } } +/// The check in front of a Box file command: the real path (links followed) stays inside the +/// bot's own folder. +fn box_guard(dir: &str, path: &str) -> String { + format!( + "base=$(realpath -m -- {base}) && real=$(realpath -m -- {target}) && case \"$real\" in \"$base\"|\"$base\"/*) ;; *) echo '連結指到了你的專屬資料夾以外的地方' >&2; exit 1;; esac; ", + base = sh_quote(dir), + target = sh_quote(path), + ) +} + +/// 檢查點 (checkpoint.rs): where the file `path` that edit_file names really is on this target — +/// a path here, or one on the box or an SSH computer (None: on another AnyBot, whose files it +/// keeps itself). +pub fn file_spot(target: &Target, path: &str) -> Option> { + Some(match &target.place { + Place::Local { workdir } => Ok((Place::Local { workdir: "/".into() }, resolve(workdir, path).display().to_string())), + Place::Sealed { root } => Ok((Place::Local { workdir: "/".into() }, resolve(root, path).display().to_string())), + Place::Box { dir } => box_path(Path::new(dir), path).map(|p| (target.place.clone(), p)), + Place::Ssh { .. } => Ok((target.place.clone(), path.to_string())), + Place::Device { .. } => return None, + }) +} + +/// What a file is now (None: it isn't there), at a spot from file_spot. +pub fn file_now(place: &Place, path: &str) -> Result>, String> { + match place { + Place::Local { workdir } => { + let p = resolve(workdir, path); + match std::fs::read(&p) { + Ok(b) => Ok(Some(b)), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(format!("讀不到 {}:{e}", p.display())), + } + } + Place::Box { dir } | Place::Ssh { dir, .. } => { + if matches!(place, Place::Box { .. }) { + crate::cloudbox::ensure_running()?; + } + let guard = if matches!(place, Place::Box { .. }) { box_guard(dir, path) } else { String::new() }; + let q = sh_quote(path); + let out = remote_capture(place, &format!("{guard}if [ -e {q} ]; then printf Y; cat {q}; else printf N; fi"), None)?; + match out.strip_prefix('Y') { + Some(rest) => Ok(Some(rest.as_bytes().to_vec())), + None if out.starts_with('N') => Ok(None), + None => Err(format!("看不懂 {path} 的狀態")), + } + } + Place::Sealed { .. } | Place::Device { .. } => Err("這台不保留檢查點".into()), + } +} + +/// Put a file back as it was (None: it wasn't there, so it goes), at a spot from file_spot. +pub fn file_put(place: &Place, path: &str, content: Option<&[u8]>) -> Result<(), String> { + match place { + Place::Local { workdir } => { + let p = resolve(workdir, path); + match content { + Some(b) => { + if let Some(d) = p.parent() { + std::fs::create_dir_all(d).map_err(|e| format!("無法建立資料夾:{e}"))?; + } + std::fs::write(&p, b).map_err(|e| format!("寫不進 {}:{e}", p.display())) + } + None => match std::fs::remove_file(&p) { + Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(format!("刪不掉 {}:{e}", p.display())), + _ => Ok(()), + }, + } + } + Place::Box { dir } | Place::Ssh { dir, .. } => { + if matches!(place, Place::Box { .. }) { + crate::cloudbox::ensure_running()?; + } + let guard = if matches!(place, Place::Box { .. }) { box_guard(dir, path) } else { String::new() }; + let q = sh_quote(path); + match content { + Some(b) => remote_capture(place, &format!("{guard}mkdir -p \"$(dirname {q})\" && cat > {q}"), Some(b)).map(|_| ()), + None => remote_capture(place, &format!("{guard}rm -f -- {q}"), None).map(|_| ()), + } + } + Place::Sealed { .. } | Place::Device { .. } => Err("這台不保留檢查點".into()), + } +} + /// Keep a Box file path inside the bot's own folder: relative paths join the bot's dir, and /// a normalised result that lands outside it (`../`, absolute paths to other bots' folders) /// is refused. All bots share one container and one user, so the folder is the only wall.