From 292d07a7afb6dfc1aecaf86be094146fca345b56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Fri, 20 Nov 2026 16:16:43 +0800 Subject: [PATCH] =?UTF-8?q?wip:=20=E5=AE=8C=E6=88=90=E5=AE=A3=E7=A8=B1?= =?UTF-8?q?=E6=AA=A2=E6=9F=A5=EF=BC=88=E5=8F=AF=E4=BF=A1=E4=BB=BB=EF=BC=89?= =?UTF-8?q?=E2=80=94=E2=80=94claims.rs=20=E5=9B=9E=E8=A6=86=E5=B0=8D?= =?UTF-8?q?=E6=AD=A5=E9=A9=9F=E6=A0=B8=E5=B0=8D=E3=80=81=E6=9C=AA=E9=A9=97?= =?UTF-8?q?=E8=AD=89=E6=A8=99=E8=A8=98=E3=80=81=E5=8F=AB=E9=86=92=E6=94=B9?= =?UTF-8?q?=E6=AD=A3=E3=80=81sandbox=20=E9=80=A3=E7=B5=90=E6=94=B9?= =?UTF-8?q?=E9=81=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- FEATURES.md | 11 +- docs/feature-map/README.md | 1 + docs/feature-map/claims.md | 48 +++ docs/feature-map/pages.md | 11 +- mobile/index.html | 31 +- src/app.rs | 9 + src/app/chat_ui.rs | 8 +- src/app/claims_ui.rs | 184 +++++++++++ src/app/markdown_ui.rs | 6 + src/app/mirror_ui.rs | 14 + src/app/remote_ui.rs | 2 + src/appctl.rs | 54 +++- src/claims.rs | 615 +++++++++++++++++++++++++++++++++++++ src/featuremap.rs | 1 + src/i18n_table.rs | 4 + src/main.rs | 1 + src/model.rs | 8 +- src/pages.rs | 102 +++++- src/remote.rs | 25 +- 19 files changed, 1102 insertions(+), 33 deletions(-) create mode 100644 docs/feature-map/claims.md create mode 100644 src/app/claims_ui.rs create mode 100644 src/claims.rs diff --git a/FEATURES.md b/FEATURES.md index 6c2dc58..38e2fe8 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -1694,7 +1694,8 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 你請 Bot 追蹤、整理、比較一件之後還會回來看的事(例如「幫我追蹤一下台灣 FSD 狀況」),它用 `write_page` 做成一頁:先寫現況,再寫細節和來源(附日期)。回答裡用「[標題](page:ID)」連到它,回答下面出現頁面卡片(一張精簡卡:頁面圖示、標題、一行它說什麼或這次改了什麼、一行灰字的種類和時間),點一下打開。一個回覆裡每一頁只出一張卡(在最後存的那一步下面);沒存成的寫入(改別的 Bot 的頁面被擋、被寫法檢查退回的那一次)不出卡;手機一樣。 - 頁面可以放表格、Mermaid 圖表(圓餅、長條、折線、時間軸…白底卡節點、細灰連線),以及頁面專用的區塊:```stats 數字卡片(數字大字,超過 10 個字的值縮成小一號;值和備註開頭 ↑/+ 綠色、↓/−/- 紅色,「+」「-」後面要緊接著東西才算,單獨一個「-」當作沒資料;電腦和手機同一套規則)、```steps 進度(✓ 完成、◉ 進行中、○ 還沒到)、```chart 原生圖表(bar 長條、line 折線、pie 圓餅;只畫淡水平參考線,長條自動由大到小排序——月份/年份等自有順序的標籤不排;單系列把數字直接標在圖上、不畫 y 軸;多條線在線尾標系列名;懸停看數值、拖曳平移、右鍵框選放大、雙擊還原;長條的 y 軸從 0 開始,折線離 0 很遠時(最小值比資料的高低差還大)照資料範圍畫,起伏才看得出來;圖下自動附數據表,和頁面的表格同一種樣子(灰字表頭、每列一條細線、名稱靠左、數字靠右,每欄只有內容那麼寬,太寬就在卡片裡左右捲動,不會把頁面視窗撐出畫面),超過 6 列收成「▸ 數據 · N 筆」,點了展開;多系列用 `| 1月 | 2月` 當表頭;第一行可以是「圖型 標題」、只寫圖型(bar/line/pie 或 長條/折線/圓餅)或只寫標題,`#` 開頭的行是註解,`|---|` 分隔列略過,少填的格子當 0——電腦和手機同一套讀法;手機看同一頁也畫同樣樣式的原生 SVG 圖:照手機寬度畫、字不會縮小,折線和多系列長條有 y 軸數字(y 軸從不從 0 開始的規則和電腦一樣),圖下同樣附數據表(超過 6 列同樣收起),只有一項的圓餅畫成整圓,圖例項目再多也都畫得到,負數的數字不會壓到下面的標籤)、`> [!NOTE]`/`[!TIP]`/`[!WARNING]`/`[!IMPORTANT]` 提示框。這些區塊在聊天裡也能用。所有圖表(含 Mermaid 圓餅)共用同一套低飽和六色色板,深淺兩主題各一組。 - **細節區塊** ```details 標題:預設收起,只顯示一行灰色「▸ 標題」(沒寫標題就是「細節」),點了展開裡面的 Markdown。讓第一屏只有結論、數字和下一步;證據、長清單、指令收在下面。 -- **寫法檢查**:Bot 存頁面時程式先看一遍(Anthropic 的報告寫法:結論先講、句子短、少粗體、數字放卡片或表格、不用裝飾)。段落超過 120 字、一節超過一處粗體、括號裡一串數字、標題編號、分隔線、用「→」帶結論、表格裡放指令、正文很長卻沒有收起的細節——有就退回一次、列出每一處要怎麼改;同一頁第二次照存,不會卡住。 +- **寫法檢查**:Bot 存頁面時程式先看一遍(Anthropic 的報告寫法:結論先講、句子短、少粗體、數字放卡片或表格、不用裝飾)。段落超過 120 字、一節超過一處粗體、括號裡一串數字、標題編號、分隔線、用「→」帶結論、表格裡放指令、正文很長卻沒有收起的細節——有就退回一次、列出每一處要怎麼改;同一頁第二次照存,不會卡住。「同一頁」用 id 或標題認(不分大小寫、不管空白),中間夾著只改欄位的呼叫也一樣是第二次。 +- **只改欄位**:`write_page` 帶 id(或同一個標題)、沒有 content 時,只改帶來的標題、摘要、更新說明、種類、數字卡、結論,內容和版本不動(「已更新頁面「…」的種類、結論(內容沒動,還是第 N 版)」);什麼都沒帶才說內容是空的。起因:Bot 習慣先送內容、再單獨送 kind、note、summary、verdict,每次都被回「頁面內容是空的」,那次呼叫還把「退回過一次」的記號清掉,寫法檢查退回了八次、頁面一直停在舊版。用 id 更新內容、沒帶標題時保留原標題。 - 頁面是「閱讀排版」:內文排在置中的 720 像素欄位裡,行高 1.55 倍、段落有呼吸空間,不會貼著視窗邊緣;聊天室保持原本的緊湊排版。頁面上的數字表格(2–3 欄、資料不超過 8 列)在寬度夠時會自動左表右圖併排。 - 頁面視窗(和其他對話框)不會被內容撐寬:太寬的表格在閱讀欄裡左右捲動,其他太寬的東西在視窗邊緣切掉,標題列的 × 一直在右上角。(以前一頁四張數字卡把視窗撐出自己的標題列,× 跑到中間。) - 有 3 個以上標題的頁面,標題下面有一行小字「▸ 目錄 · N 節」(不佔第一屏):點了展開成標題清單,每條可點、點了跳到那一節;展開時上面有小搜尋框可以篩標題(⌘F 直接展開並把光標放進去,Esc 離開)。 @@ -2551,6 +2552,14 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 畫面:Bot 傳來的附件下面只多一個灰色小記號——✓ 已在聊天、✓✓ 已在某台裝置顯示、點開過的 ✓✓ 是強調色。失敗不另外跳字(手機的「這張圖讀不到」照舊)。電腦版滑過記號、手機點記號,列出每台裝置、什麼時候、顯示/點開/失敗和原因。你自己附的檔案沒有記號。手機聊天停在最新訊息時,圖片載入、內容變高也一直停在底部(往上捲在讀的不會被拉回來),新傳來的圖真的出現在畫面上;重畫時已經讀到的圖直接沿用,不會閃回檔名再長高。 - Bot 知道:`send_file` 的結果只說「已放進聊天」,下一輪起結果後面帶一行〔交付狀態:…〕;系統提示要它不要說你已經看到,你問「收到了嗎」照那個狀態回答。 - 有裝置回報顯示失敗、而且還沒有任何裝置顯示過,大腦叫醒那個 Bot 一次(團隊成員、管理員的裝置只記下、不叫醒,最多佔 4 筆;群組聊天、給你看畫面的截圖、團隊成員、訊息管道的人或別的 Bot 要的檔案都只記下、不叫醒;Bot 還在忙、叫醒在排隊時別台顯示了就取消)(「[交付]」開頭:附件編號和副檔名、哪台、為什麼;不寫檔名——檔名可能來自外面,這則訊息帶著你的信任開一輪),請它換方式交付(換格式、縮小、`send_to_device`)。你上次說話之後最多叫醒兩次。你只是還沒打開 App 不算失敗,不催。支線、交辦帶回主聊天的檔案只有記號,不叫醒、主 Bot 也讀不到狀態;管理員要的檔案和你的一樣會叫醒。 + - **完成宣稱檢查**(程式擋,不靠提示):每一輪成功結束時,大腦把 Bot 最後那則回覆跟這一輪實際的步驟、附件對一遍(群組聊天只看回答的成員自己的步驟)。只抓說得很明白的,寧可漏、不要錯: + - 說做好了、傳好了(已完成、做好了、搞定、已傳、已送出、已寄出、已上傳、已發佈、已附上…),這一輪最後一個相關的步驟卻失敗或被擋(說傳的看傳送類步驟,說做好的看最後一個不是只有讀、查的步驟;指令結束代碼 1 又沒輸出——grep 沒找到——不算失敗)。 + - 說傳了檔案(「報告已傳給你」「已附上 x.pdf」),這一輪卻沒有檔案放進聊天(說傳到手機、信箱、雲端,用別的方式送出了,或提到之前、剛剛、上面,不算)。 + - 連結指到 Bot 電腦上的位置(`sandbox:`、`file://`、/home/…、~/…、C:\…、./…),手機和其他電腦都打不開。聊天裡有同名的檔案:點連結就打開那個檔案(電腦版、手機、螢幕電腦都是),不標記、只讓 Bot 知道;沒有就標記。起因:Bot 用 send_file 真的把規格傳進聊天,回覆卻寫 `[下載:….md](sandbox:/home/bot/bot-12/….md)`,點了沒用。 + - 數字對不上:「送出 2 則」系統只數到 1 則(跟例行任務、目標用的同一套計數);「傳了 3 張圖」這一輪只放了 1 個檔案。用連接器送出的數不到,就不比。 + - 不算宣稱:還沒、尚未、如果、等…之後、完成後會…、應該、可能、問句、「已完成的部分…但…還沒」、回覆裡自己說了失敗或被擋、引號和程式碼裡的字、「你已上傳…」。 + - 記在大腦那則回覆上(重開還在),回覆下面一個灰色小「未驗證」:電腦版滑過、手機點一下看原因;螢幕電腦一樣。Bot 下一輪讀到自己那則回覆後面多一行〔AnyBot 核對這則回覆時發現(這行是系統加的,不是你寫的):…〕。 + - 說做好了卻沒做到、說傳了檔案卻沒有、連結打不開又沒有那個檔案:叫醒 Bot 一次(「[核對]」開頭、標「回覆沒對上」,只寫固定的字,不夾回覆裡的檔名或連結),請它真的做完、用 `send_file` 交付,或照實說還沒好。只在那一輪是你自己開的才叫醒;訊息管道、團隊成員、別的 Bot 開的一輪、群組聊天、目標進行中、你又傳了新訊息在排隊,都只標記。你上次說話之後最多叫醒一次;數字對不上只標記。支線、出錯或被停止的一輪不檢查。 - 卡片(天氣、機票等)照舊顯示在回答下面。 - 深色主題改成原版量到的顏色:聊天背景 #131313、側欄 #101010、卡片 #1F1F1F。 diff --git a/docs/feature-map/README.md b/docs/feature-map/README.md index 71e1d87..16d4d11 100644 --- a/docs/feature-map/README.md +++ b/docs/feature-map/README.md @@ -95,6 +95,7 @@ Bot 讀得到的是開頭、子功能、使用者怎麼到、Bot 那一行和沒 - [box](box.md):Bot 的電腦:桌面、更新、從帳號看畫面。 - [files](files.md):指令、檔案、終端機、監看、檢查點(/rewind)。 - [deliver](deliver.md):送檔、打開給使用者看、發佈網站。 +- [claims](claims.md):完成宣稱檢查:說做好了卻沒做到、打不開的連結、未驗證、叫醒改正。 - [browser](browser.md):AnyBot 瀏覽器、設定檔、發布關卡、已送帳本。 - [screen](screen.md):截圖、點擊、打字、批次、交給使用者操作、示範教學。 - [vault](vault.md):保險庫、填入帳密卡號地址。 diff --git a/docs/feature-map/claims.md b/docs/feature-map/claims.md new file mode 100644 index 0000000..5e01718 --- /dev/null +++ b/docs/feature-map/claims.md @@ -0,0 +1,48 @@ +# 完成宣稱檢查 + +Bot 說「已完成」「已傳」,不等於真的做到。每一輪結束時,AnyBot 用程式把 Bot 最後那則回覆跟這一輪實際的步驟、附件對一遍:對不上的,回覆下面標一個小小的「未驗證」,Bot 下一輪讀得到;使用者拿不到結果的,叫醒 Bot 一次改正。只抓說得很明白的,寧可漏、不要錯。傳檔和交付確認見 [deliver](deliver.md)。 + +## 子功能 + +- `claims-check` 對什麼:只看這一輪最後那則回覆(群組聊天只看回答的那個成員自己的步驟)。 + - 說做好了、傳好了(已完成、做好了、搞定、已傳、已送出、已寄出、已上傳、已發佈、已附上…),這一輪最後一個相關的步驟卻失敗或被擋下。說傳的看傳送類的步驟;說做好的看最後一個不是只有讀、查的步驟;指令只回「沒有」(結束代碼 1、沒有輸出,例如 grep 沒找到)不算失敗。 + - 說傳了檔案(「報告已傳給你」「已附上 x.pdf」),這一輪卻沒有任何檔案放進聊天。說傳到手機、信箱、雲端,這一輪用別的方式送出了,或說的是之前、剛剛、上面傳的,不算。 + - 數字對不上:「送出 2 則」系統只數到 1 則真的送出去(跟例行任務、目標用的同一套計數);「傳了 3 張圖」這一輪只放了 1 個檔案。用連接器送出的數不到,就不比。 + - 不算宣稱:還沒、尚未、如果、等…之後、完成後會…、應該、可能、問句、「已完成的部分…但…還沒」、回覆裡自己說了失敗或被擋、引號和程式碼裡的字、使用者自己做的(「你已上傳」)。 +- `claims-link` 打不開的連結:回覆裡的連結指到 Bot 電腦上的位置——`sandbox:`、`file://`、/home/…、~/…、C:\…、./…——在手機和其他電腦上都打不開。聊天裡有同名的檔案:點連結就打開那個檔案,不標記,只讓 Bot 知道;沒有就標「未驗證」。 +- `claims-mark` 未驗證:對不上的回覆下面一個灰色的小「未驗證」,點(手機)或滑過(電腦)看原因。記在大腦那則回覆上,重開 AnyBot 還在;手機、電腦版、螢幕電腦看到同一份。 +- `claims-wake` 叫醒改正:說做好了卻沒做到、說傳了檔案卻沒有、連結打不開又沒有那個檔案,叫醒 Bot 一次(「[核對]」開頭、標「回覆沒對上」;只寫固定的字,不夾回覆裡的檔名或連結),請它真的做完、用 `send_file` 交付,或照實說還沒好、卡在哪。只在那一輪是使用者自己開的才叫醒;訊息管道、團隊成員、別的 Bot 開的那一輪、群組聊天、目標(/goal)進行中、使用者又有新訊息在排隊,都只標記。使用者上次說話之後最多叫醒一次。數字對不上只標記、不叫醒。 +- `claims-history` Bot 讀得到:下一輪起,Bot 讀到自己那則回覆後面多一行〔AnyBot 核對這則回覆時發現(這行是系統加的,不是你寫的):…〕。 + +## 使用者怎麼到 + +- 聊天裡 Bot 的回覆下面:灰色小「未驗證」,滑過列出原因。 +- 回覆裡指到 Bot 電腦的連結:點了打開聊天裡同名的檔案預覽;沒有這個檔案就說這裡打不開。 +- 叫醒的那則訊息標「回覆沒對上」。 +- 手機:一樣的「未驗證」,點一下跳出原因;連結點了打開檔案預覽,沒有就跳出提示。 + +## 怎麼操作(verify-anybot) + +- Bot:回覆只寫真的發生的事:檔案用 `send_file` 傳進聊天,說「檔案在上面的附件」,不要寫 sandbox:、file:// 或電腦上的路徑當連結;步驟失敗就照實說。被「[核對]」叫醒時,先看自己上一則回覆後面的〔AnyBot 核對…〕,真的補做(用 `send_file` 交付)或更正說法。 + +前提: + +- 基本前提和「手機已登入」(README),開著 Bot 1 的聊天:`$CTL phone click '.row[data-bot="1"]'`。 + +- **連結指到聊天裡的檔案**(covers `claims-link`、`claims-history`):Bot 寫好 spec.md、用 `send_file` 傳過來,回覆卻寫 sandbox: 的下載連結;點那個連結,再跟它說一句話。指令:`$CTL phone send '寫 [[call edit_file {"path":"spec.md","old_text":"","new_text":"# 規格\n\n先做可信任。\n"}]]' && $CTL phone wait-text 已建立 --in '#msgs' && $CTL model-reply 傳規格給我 '[[call send_file {"path":"spec.md"}]] 規格寫好了。[下載:spec.md](sandbox:/home/bot/bot-1/spec.md)' && $CTL phone send '傳規格給我' && $CTL phone wait-text 規格寫好了 --in '#msgs' && $CTL phone shot claims-filelink && $CTL phone click 'a.flink' --text spec.md && $CTL phone wait-text 先做可信任 --in '#filebody' && $CTL phone click '[data-back]' && $CTL api GET /api/bots/1 --jq '[.messages[] | select(.check)] | length' && $CTL phone send '看一下' && $CTL phone wait-text 'FAKE-MODEL 回答:看一下' --in '#msgs' && $CTL model 'select(.kind == "turn" and (.user | startswith("看一下"))) | .prev.tail'`。看到:回覆「規格寫好了。下載:spec.md」,「下載:spec.md」是可點的連結,下面沒有「未驗證」;點連結打開 spec.md 的預覽「規格/先做可信任。」;API 沒有任何回覆帶 check(0);模型下一輪讀到的上一則回覆結尾是〔AnyBot 核對這則回覆時發現(這行是系統加的,不是你寫的):連結「下載:spec.md」指到 Bot 電腦上的位置(sandbox:/home/bot/bot-1/spec.md),手機和其他電腦打不開;畫面改成打開聊天裡的附件「spec.md」〕。 +- **說傳好了、連結打不開:未驗證、叫醒一次**(covers `claims-check`、`claims-link`、`claims-mark`、`claims-wake`、`claims-history`):Bot 什麼都沒傳,回覆「已傳好了」加一個 sandbox: 連結。指令:`$CTL model-reply 傳報告給我 '已傳好了 [下載:report.md](sandbox:/home/bot/report.md)' && $CTL phone send '傳報告給我' && $CTL phone wait '.unv' && $CTL phone wait-text 回覆沒對上 --in '#msgs' && $CTL phone wait-text 'FAKE-MODEL 回答:[核對]' --in '#msgs' && $CTL phone shot claims-unverified && $CTL phone click '.unv' && $CTL phone wait-text '聊天裡也沒有這個檔案' --in '#sheet-in' && $CTL phone shot claims-why && $CTL phone click '#sheet' && $CTL phone click 'a.flink' --text report.md && $CTL phone wait-text 手機打不開 && $CTL api GET /api/bots/1 --jq '{check: [.messages[] | select(.check) | .check[].kind], wakes: [.messages[] | select(.wake) | .text[0:20]]}' && $CTL model 'select(.user | startswith("[核對]")) | .prev.tail'`。看到:回覆下面灰色「未驗證」;聊天多一則標「回覆沒對上」的訊息:「你上一則回覆跟這一輪實際做到的對不上:回覆裡的連結指到你電腦上的位置…;回覆說傳了檔案,但這一輪沒有任何檔案放進聊天。…」(沒有 report.md、沒有路徑),Bot 接著回答;點「未驗證」跳出「未驗證」、「AnyBot 核對這一輪實際做了什麼,跟這則回覆對不上」和兩條紅字原因;點連結跳出「這個連結指到 Bot 電腦上的位置,手機打不開;聊天裡也沒有這個檔案」;API check 是 dead_link、no_file,叫醒 1 次;被叫醒那一輪模型讀到的上一則回覆結尾是〔AnyBot 核對這則回覆時發現…〕。 +- **步驟失敗還說傳好了**(covers `claims-check`、`claims-wake`):Bot 傳一個不存在的檔案(失敗),回覆卻說完成了。指令:`$CTL model-reply 傳不存在的檔案 '[[call send_file {"path":"nope.md"}]] 完成了,檔案已傳給你。' && $CTL phone send '傳不存在的檔案' && $CTL phone wait '.step.failed' && $CTL wait-api /api/bots/1 '[.messages[] | select(.wake)] | length == 2' 60 && $CTL phone wait-text 'FAKE-MODEL 回答:[核對]你上一則回覆跟這一輪實際做到的對不上:回覆說做好了' --in '#msgs' && $CTL phone shot claims-undone && $CTL api GET /api/bots/1 --jq '[.messages[] | select(.check) | .check[] | select(.kind == "undone") | .why]'`。看到:傳檔那一步失敗,回覆「完成了,檔案已傳給你。」下面「未驗證」;第二則「回覆沒對上」(使用者說了話,可以再叫一次);原因「說「已傳」,但這一輪最後一個相關的步驟「傳檔案給你」失敗了」。 +- **不是宣稱的不標**(covers `claims-check`):Bot 說還沒好。指令:`$CTL model-reply 慢慢來 '我還沒完成,完成後會傳給你。' && $CTL phone send '慢慢來' && $CTL phone wait-text 完成後會傳給你 --in '#msgs' && $CTL api GET /api/bots/1 --jq '.messages[-1] | {text, check}'`。看到:回覆下面沒有「未驗證」;API 那則的 check 是 null。 +- **重開還在**(covers `claims-mark`、`claims-wake`):指令:`$CTL restart && $CTL phone open --listed && $CTL phone wait '.row[data-bot="1"]' && $CTL phone click '.row[data-bot="1"]' && $CTL phone wait '.unv' && $CTL phone shot claims-after-restart && $CTL api GET /api/bots/1 --jq '{marked: [.messages[] | select(.check)] | length, wakes: [.messages[] | select(.wake)] | length}'`。看到:重開後「未驗證」還在;標記 2 則、叫醒還是 2 次(重開不會再叫)。 +- **別人開的一輪、群組、數字**(covers `claims-wake`、`claims-check`):指令:走不到——訊息管道要 Slack/Telegram 帳號,團隊成員要帳號伺服器,數「送出幾則」要真的能送出的管道(X、簡訊)。看到:最接近的真路是自動測試:訊息管道、團隊成員、別的 Bot 開的一輪和群組聊天只標記不叫醒;「共送出 3 則」只數到 1 則標 Count、不叫醒。 +- **電腦版的標示和連結**(covers `claims-mark`、`claims-link`):指令:要開視窗——`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot claims ANYBOT_SHOT_REAL=1`。看到:回覆下面灰色「未驗證」,滑過列出原因;點 sandbox: 連結打開聊天裡同名的檔案。 +- 自動測試:`cargo test claims::`、`cargo test app::claims_ui::`、`cargo test the_phone_gets_what_made_a_reply_unverified`、`cargo test a_replys_check_reaches_the_screens`、`cargo test the_phone_tags_woken_messages_like_the_window`。 + +## 陷阱 + +- 只看最後那則回覆;只認說得很明白的宣稱,換個說法(「弄完囉」「OK 了」)抓不到——沒有「未驗證」不代表驗證過。 +- 「未驗證」是對不上,不一定做錯(例如說的是上一輪的事):點開看原因。 +- 檢查不重做 Bot 的工作,也不判斷內容好不好;檔案在使用者裝置上有沒有顯示,看交付確認([deliver](deliver.md))。 +- 叫醒的那一輪如果又對不上,只標記、不再叫醒,等使用者說話。支線、出錯或被停止的那一輪不檢查。 +- (驗證)假模型只照規則回答:叫醒那一輪的回答是「FAKE-MODEL 回答:[核對]…」,不會真的補做。 +- (驗證)`$CTL model-reply` 的字也會比對到之後的請求(最後一則使用者訊息含那段字就回):每一步用不同的字。 diff --git a/docs/feature-map/pages.md b/docs/feature-map/pages.md index addb1b5..0e2017c 100644 --- a/docs/feature-map/pages.md +++ b/docs/feature-map/pages.md @@ -5,9 +5,10 @@ Bot 把要追蹤、整理、比較的事寫成一頁,之後一直更新同一 ## 子功能 - `pages-write` 寫頁面:標題和整頁 Markdown(標題、表格、連結、Mermaid 圖),加上頁面區塊(```details、```stats、```steps、```chart、提示框,見 [pageview](pageview.md))。 -- `pages-review` 寫法檢查(Anthropic 的報告寫法):存之前先檢查——段落超過 120 字、一節超過一處粗體、括號裡一串數字、標題編號(一、二、1.)、分隔線、用「→」帶結論、表格裡放指令、正文超過 1800 字卻沒有 ```details——有就退回一次並列出要改的地方,同樣的標題第二次照存(不會卡住)。程式碼、```stats、```details 等區塊裡面不檢查。 +- `pages-review` 寫法檢查(Anthropic 的報告寫法):存之前先檢查——段落超過 120 字、一節超過一處粗體、括號裡一串數字、標題編號(一、二、1.)、分隔線、用「→」帶結論、表格裡放指令、正文超過 1800 字卻沒有 ```details——有就退回一次並列出要改的地方,同一頁(同樣的 id 或標題)下一次帶內容的就照存(不會卡住;中間夾著只改欄位的也一樣)。程式碼、```stats、```details 等區塊裡面不檢查。 - `pages-kind` 種類(kind):data 數據分析、compare 比較評測、decision 決策備忘、howto 教學步驟、timeline 時間線、prose 長文、notes 筆記。種類決定第一屏:data 頁上面放 2–4 個 KPI 數字(kpis),compare/decision 頁先給一行「結論」(verdict)。沒給種類就是一般頁面。 -- `pages-update` 更新:帶 id(或同一個標題)就換掉內容,上一版留著,最多留 10 版;note 寫這次改了什麼,頁面上顯示「這一版更新了:…」。內容一模一樣就不更新。 +- `pages-update` 更新:帶 id(或同一個標題)就換掉內容,上一版留著,最多留 10 版;note 寫這次改了什麼,頁面上顯示「這一版更新了:…」。內容一模一樣就不更新。只帶 id 沒帶標題時,標題不變。 +- `pages-fields` 只改欄位:帶 id(或同一個標題)、不帶 content,只改帶來的 title、summary、note、kind、kpis、verdict,內容和版本不動;什麼都沒帶才說內容是空的。 - `pages-keep` 一直留著:跨聊天、跨例行任務都在(例行任務每一輪從新的開始,要接著上次做就先讀頁面)。頁面存在大腦上,螢幕電腦和手機看到的是同一份。 - `pages-colleague` 同事的頁面:`list_pages` 先列自己的,再列其他 Bot 的(標是誰的,最新 30 頁;更舊的用標題也讀得到);`read_page` 讀得到,會註明是誰的、只能讀;要改會被擋下,說是誰的頁面。 @@ -20,7 +21,7 @@ Bot 把要追蹤、整理、比較的事寫成一頁,之後一直更新同一 ## 怎麼操作(verify-anybot) -- Bot:使用者要你追蹤、整理、比較、研究一件之後還會回來看的事,用 `write_page`(title、content;summary 一行現況;kind;kpis、verdict 只放真的資料;更新時帶 id 和 note),回覆裡用 [標題](page:ID) 連過去。更新前先 `read_page`(id 或 title)看現在的內容。要查的事同事可能已經在追,先 `list_pages`、`read_page` 讀它的,不要重查一遍。要定期追蹤就配一條例行任務([routines](routines.md)):每次讀頁面、查新消息,有實質進展才更新,沒有就說「沒有新消息」。這三個工具屬於「頁面」能力。 +- Bot:使用者要你追蹤、整理、比較、研究一件之後還會回來看的事,用 `write_page`(title、content;summary 一行現況;kind;kpis、verdict 只放真的資料;更新時帶 id 和 note;只改種類、摘要、結論這些就不帶 content),回覆裡用 [標題](page:ID) 連過去。更新前先 `read_page`(id 或 title)看現在的內容。要查的事同事可能已經在追,先 `list_pages`、`read_page` 讀它的,不要重查一遍。要定期追蹤就配一條例行任務([routines](routines.md)):每次讀頁面、查新消息,有實質進展才更新,沒有就說「沒有新消息」。這三個工具屬於「頁面」能力。 前提: @@ -29,6 +30,7 @@ Bot 把要追蹤、整理、比較的事寫成一頁,之後一直更新同一 - **退回一次、再存**(covers `pages-write`、`pages-review`、`pages-kind`):請 Bot 寫一頁有編號標題和分隔線的,同樣的標題再存一次 data 頁(問題還在)。指令:`$CTL phone send '寫一頁 [[call write_page {"title":"FSD 追蹤","content":"## 一、現況\n交通部審查中。\n\n---"}]]' && $CTL phone wait-text '頁面還沒存' --in '#msgs' && $CTL phone send '再存 [[call write_page {"title":"FSD 追蹤","kind":"data","summary":"審查中","kpis":[{"label":"審查會議","value":"2 次","delta":"+1"}],"content":"## 一、現況\n交通部審查中。\n\n---\n\n| 項目 | 狀態 |\n|---|---|\n| 路測 | 未核定 |"}]]' && $CTL phone wait '.pcard[data-page="1"]' && $CTL phone shot pages-card && $CTL model 'select(.kind == "after-tool") | .tool_result' && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | select(.page) | .page.title]'`。看到:第一次「頁面還沒存:照這幾點改寫…• 標題「一、現況」不用編號…• 不用分隔線(---)…」,沒有卡片;第二次照存「已建立頁面「FSD 追蹤」…」,下面一張卡(只有這一張;同一個回覆存好幾次只出一張靠自動測試)。 - **打開頁面**(covers `pages-kind`、`pages-write`):點卡片。指令:`$CTL phone click '.pcard[data-page="1"]' && $CTL phone wait-text 審查會議 --in '#page' && $CTL phone shot pages-open && $CTL api GET /api/pages/1 --jq '{title, kind, summary, kpis, revision, bot}'`。看到:標題、「驗證小幫手 · 更新於 …」、現況一句、數字卡「審查會議 2 次 +1」、表格。 - **更新、舊版**(covers `pages-update`):回聊天請它帶 id 更新,再送一次一模一樣的;打開頁面 ›「⋯」›「其他版本」›「第 1 版」。指令:`$CTL phone click '[data-back]' && $CTL phone send '更新 [[call write_page {"id":1,"title":"FSD 追蹤","note":"路測核定了","content":"## 現況\n路測核定了。"}]]' && $CTL phone wait-text '第 2 版,上一版留著' --in '#msgs' && $CTL phone send '再一次 [[call write_page {"id":1,"title":"FSD 追蹤","content":"## 現況\n路測核定了。"}]]' && $CTL phone wait-text '內容沒有變化,沒有更新' --in '#msgs' && $CTL phone click '.pcard[data-page="1"]' && $CTL phone wait-text '這一版更新了:路測核定了' --in '#page' && $CTL phone click '#b-pagemore' && $CTL phone click '#sheet-in .opt' --text 其他版本 && $CTL phone click '#sheet-in .opt' --text '第 1 版' && $CTL phone wait-text 你在看舊的版本 --in '#page' && $CTL api GET /api/pages/1 --jq '{revision: .latest, versions}'`。看到:卡片「頁面 · … · 已更新」;頁面「第 2 版」和「這一版更新了:路測核定了」;舊版是「你在看舊的版本。回到最新版」和原本的內容;API 最新第 2 版、留著第 1 版。 +- **退回後只改欄位、再送內容**(covers `pages-fields`、`pages-review`):回聊天請它用 id 改寫成有編號標題的版本(被退回),再只送種類和結論,最後同樣的內容再送一次。指令:`$CTL phone click '[data-back]' && $CTL phone send '改寫 [[call write_page {"id":1,"content":"## 一、現況\n路測核定了。\n\n---"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]? | select(.label == "寫頁面" and .status == "failed")] | length == 2' 60 && $CTL phone send '補欄位 [[call write_page {"id":1,"kind":"decision","verdict":"可以開始路測"}]]' && $CTL phone wait-text '內容沒動,還是第 2 版' --in '#msgs' && $CTL phone send '再送 [[call write_page {"id":1,"content":"## 一、現況\n路測核定了。\n\n---"}]]' && $CTL phone wait-text '第 3 版,上一版留著' --in '#msgs' && $CTL phone shot pages-fields && $CTL model 'select(.kind == "after-tool") | .tool_result' && $CTL api GET /api/pages/1 --jq '{title, kind, verdict, revision: .latest}'`。看到:第一次「頁面還沒存…改不掉的地方第二次會照樣存。只改 kind、summary、verdict 這些的話,不用帶 content。」;只送欄位是「已更新頁面「FSD 追蹤」的種類、結論(內容沒動,還是第 2 版)」(不是「頁面內容是空的」);再送內容照存「第 3 版」;API 標題還是「FSD 追蹤」、kind decision、verdict「可以開始路測」、第 3 版。 - **同事讀得到、改不了**(covers `pages-colleague`):首頁 + ›「建立 Bot」叫「同事」,在它的聊天裡列頁面、改頁面、讀頁面。指令:`$CTL phone open --listed && $CTL phone click '#b-newbot' && $CTL phone click '#sheet-in .opt' --text '建立 Bot' && $CTL phone type '#ask-in' 同事 && $CTL phone click '#ask-ok' && $CTL phone wait-text 同事 --in '#isl-name' && $CTL phone send '[[call list_pages {}]]' && $CTL phone wait-text '其他 Bot 的頁面' --in '#msgs' && $CTL phone send '[[call write_page {"id":1,"title":"FSD 追蹤","content":"我改的"}]]' && $CTL phone wait-text '這是「驗證小幫手」的頁面,你只能讀不能改' --in '#msgs' && $CTL phone send '[[call read_page {"id":1}]]' && $CTL phone wait-text '你只能讀,要改請它改' --in '#msgs' && $CTL model 'select(.kind == "after-tool") | .tool_result' && $CTL api GET /api/pages/1 --jq .body`。看到:列表「你還沒有做任何頁面。…其他 Bot 的頁面…#1 「FSD 追蹤」…(驗證小幫手)」;改的被擋、沒有卡片;讀到「(「驗證小幫手」的頁面,你只能讀…)」;內容沒變。 - **一直留著、刪除**(covers `pages-keep`、`pages-update`):重開 AnyBot,首頁「頁面」打開它,「⋯」›「刪除頁面」›「刪除」。指令:`$CTL restart && $CTL phone open --listed && $CTL phone click '[data-q="pages"]' && $CTL phone click '#list [data-page="1"]' && $CTL phone wait-text '路測核定了' --in '#page' && $CTL phone click '#b-pagemore' && $CTL phone click '#sheet-in .opt' --text 刪除頁面 && $CTL phone click '#sheet-in .opt' --text 刪除 && $CTL phone wait-text '還沒有頁面' --in '#list' && $CTL api --expect 404 GET /api/pages/1`。看到:重開後還在;刪了清單變空,API「這個頁面已經刪除了」。 - **桌面的卡片和頁面視窗**(covers `pages-write`、`pages-update`):指令:要開視窗——`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot pages-card ANYBOT_SHOT_VIEW=pagecard`(打開的頁面:`ANYBOT_SHOT_VIEW=page`)。看到:精簡卡和灰字那一行;頁面下方「版本紀錄」「刪除」「複製」「存成檔案」「完成」;資料庫 › 頁面。 @@ -39,9 +41,10 @@ Bot 把要追蹤、整理、比較的事寫成一頁,之後一直更新同一 - 只能改自己做的頁面:帶別人頁面的 id 會被擋下(請它改,或不帶 id 自己做一頁);帶一個找不到的 id 會說找不到頁面,不會另開新的。 - 同一個 Bot 用同樣的標題寫(不分大小寫、不管空白),會換掉那一頁,不是另開一頁。 -- content 是整頁內容,不是要加上去的那一段:更新時要給完整的新版本。 +- content 是整頁內容,不是要加上去的那一段:更新時要給完整的新版本。只改種類、摘要、結論這些時不帶 content,內容就不會被換掉。 - 舊版最多留 10 版,更早的就沒了。 - 內容上限 200,000 位元組(中文約 6 萬字),太長會被退回,要拆成幾頁。 - 使用者不能在畫面上改頁面內容,要請 Bot 改。Bot 沒有刪頁面的工具,刪除要使用者自己按。 - 頁面上的「刪除」要再按一次「確定刪除」才刪(手機也會先確認),刪了救不回來;刪掉後,舊聊天裡的卡片顯示「(這個頁面已刪除)」。 - kpis、verdict 沒有真的數字或結論就不要填,頁面不會硬湊卡片。 +- (驗證)假模型只把工具結果的前 80 字說出來:後面的字(例如退回訊息最後一句)用 `$CTL model` 看,不要在聊天裡等。 diff --git a/mobile/index.html b/mobile/index.html index 389a600..5f419e6 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -251,7 +251,9 @@ details.dt>.dt-in{padding-left:var(--sp-4);margin-top:var(--sp-2)} .dlv .ic+.ic{margin-left:-7px}.dlv.opened{color:var(--accent)} .dlv-list{padding:0 16px 12px}.dlv-list .r{display:flex;gap:8px;align-items:baseline;padding:8px 0;border-top:.5px solid var(--line);font-size:var(--fs-small)} .dlv-list .r b{font-weight:600}.dlv-list .r .w{color:var(--text3);margin-left:auto;white-space:nowrap}.dlv-list .r.failed span{color:var(--danger)} -.plink{cursor:pointer;color:var(--accent-ink);text-decoration:underline;text-decoration-color:color-mix(in srgb,var(--accent-ink) 40%,transparent)} +/* 完成宣稱關卡: a quiet 「未驗證」 under a reply AnyBot couldn't verify (tap: why). */ +.unv{display:inline-flex;align-items:center;gap:4px;align-self:flex-start;background:none;border:0;padding:2px 6px;margin:2px 0 0;min-height:24px;color:var(--text3);font-size:var(--fs-caption)} +.plink,.flink{cursor:pointer;color:var(--accent-ink);text-decoration:underline;text-decoration-color:color-mix(in srgb,var(--accent-ink) 40%,transparent)} /* empty chat */ .intro{display:flex;flex-direction:column;align-items:center;text-align:center;padding:36px 16px 10px;gap:6px} .intro .hi{font-size:var(--fs-h2);font-weight:600;margin-top:8px} @@ -1744,6 +1746,24 @@ function dlvSheet(id) { const rows = (a.seen || []).map((x) => `
${esc(x.device)}${esc(what[x.kind] || "")}${x.why ? ":" + esc(x.why) : ""}${x.at ? esc(dayLabel(x.at) + " " + clock(x.at)) : ""}
`).join(""); sheet(DLV_TITLE[d], [], `
${esc(a.name)}
${rows || `
還沒有裝置回報顯示
`}
`); } +// 完成宣稱關卡: under a reply that didn't match what its turn did; tapping it says why. +function unvMark(m, i) { + return (m.check || []).length ? `` : ""; +} +function unvSheet(i) { + const m = S.msgs[i]; + if (!m || !(m.check || []).length) return; + sheet("未驗證", [], `
AnyBot 核對這一輪實際做了什麼,跟這則回覆對不上
${m.check.map((c) => `
${esc(c.why)}
`).join("")}
`); +} +// A link to a place on the bot's computer (sandbox:, file://, a path): the chat's file of that +// name opens; otherwise it is said plainly that it can't open here. +function openDeadLink(name) { + let n = name || ""; + try { n = decodeURIComponent(n); } catch (_) {} + const a = [...S.msgs].reverse().flatMap((m) => m.attachments || []).find((x) => x.path && n && x.name.toLowerCase() === n.toLowerCase()); + if (a) openFile(a.path, a.name, a.id || ""); + else toast("這個連結指到 Bot 電腦上的位置,手機打不開;聊天裡也沒有這個檔案"); +} // The device this page names for itself in 交付確認. function deviceLabel() { const ua = navigator.userAgent || ""; @@ -1935,7 +1955,8 @@ function renderMsgs() { const bub = m.text ? `
${pageMd(m.text, 0)}
` : ""; const atts = (m.attachments || []).map((a) => attHtml(a) + dlvMark(a)).join(""); const meta = end && m.text ? `
${m.at ? esc(clock(m.at)) : ""}${owner() && m === lastBot && t === lastTurn ? `` : ""}
` : ""; - h += `
${who}${think}${bub}${steps ? `
${steps}
` : ""}${extra}${atts}${reacts}${meta}
`; + const unv = running ? "" : unvMark(m, i); + h += `
${who}${think}${bub}${steps ? `
${steps}
` : ""}${extra}${atts}${unv}${reacts}${meta}
`; }); // Still working: what it is doing now; a message nobody answered yet can be sent again. if (busy) h += (lastMsg && lastMsg.role !== "user" && !lastMsg.text && !(lastMsg.tools || []).length) || lastMsg?.role === "user" ? `
` : ""; @@ -1969,6 +1990,8 @@ $("msgs").addEventListener("click", async (e) => { // The end of a drag that selected words is not a tap: nothing folds, opens or goes. if (!e.target.closest("button,a") && selIn(e.target)) return; const dv = e.target.closest("[data-dlv]"); if (dv) { dlvSheet(dv.dataset.dlv); return; } + const uv = e.target.closest("[data-unv]"); if (uv) { unvSheet(+uv.dataset.unv); return; } + const fl = e.target.closest("a.flink"); if (fl) { e.preventDefault(); openDeadLink(fl.dataset.fname); return; } const st = e.target.closest(".step .h"); if (st) { const k = st.parentElement.dataset.step; S.openSteps[k] = !S.openSteps[k]; st.parentElement.classList.toggle("open"); return; } const f = e.target.closest(".fold"); if (f) { S.unfold[f.dataset.turn] = true; renderMsgs(); return; } @@ -2223,7 +2246,7 @@ const COMMANDS = [{name: "goal", description: "設一個目標,一直做到達 /** What woke the bot, from the tag its message starts with (app::chat_ui::wake_tag on the * desktop): [tag, icon, label], and the words after it. 監看's tag carries the command's number, so * its words stay whole. (Every wake used to say 例行任務 — a 監看's lines, a colleague's message.) */ -const WAKE_TAGS = [["[目標]", "target", "目標"], ["[例行任務]", "alarm-clock", "例行任務"], ["[觸發]", "zap", "觸發"], ["[訊息管道]", "message", "訊息管道"], ["[來自 Bot]", "bot", "來自其他 Bot"], ["[交付]", "circle-alert", "交付沒顯示"], ["⏰ ", "alarm-clock", "例行任務"], ["⚡ ", "zap", "觸發"], ["💬 ", "message", "訊息管道"], ["📨 ", "bot", "來自其他 Bot"]]; +const WAKE_TAGS = [["[目標]", "target", "目標"], ["[例行任務]", "alarm-clock", "例行任務"], ["[觸發]", "zap", "觸發"], ["[訊息管道]", "message", "訊息管道"], ["[來自 Bot]", "bot", "來自其他 Bot"], ["[交付]", "circle-alert", "交付沒顯示"], ["[核對]", "circle-alert", "回覆沒對上"], ["⏰ ", "alarm-clock", "例行任務"], ["⚡ ", "zap", "觸發"], ["💬 ", "message", "訊息管道"], ["📨 ", "bot", "來自其他 Bot"]]; function wakeTag(text) { const t = String(text || ""); for (const [tag, icon, label] of WAKE_TAGS) if (t.startsWith(tag)) return {icon, label, body: t.slice(tag.length)}; @@ -3507,6 +3530,8 @@ function inl(s) { .replace(/(^|[^*])\*([^*\s][^*]*)\*/g, "$1$2") .replace(/~~([^~]+)~~/g, "$1") .replace(/\[([^\]]+)\]\(page:(\d+)\)/g, (_, t, id) => `${t}`) + // A place on the bot's computer (sandbox:, file://, a path): opens the chat's file of that name. + .replace(/\[([^\]]+)\]\(((?:sandbox:|file:)[^)\s]*|(?:\/(?!\/)|~\/|\.\.?\/)[^)\s]*|[A-Za-z]:[\\/][^)\s]*)\)/g, (_, t, u) => `${t}`) .replace(/\[([^\]]+)\]\((https?:[^)\s]+)\)/g, '$1') .replace(/(^|[\s((::,、「])(https?:\/\/[^\s<))」,。]+)/g, '$1$2'); } diff --git a/src/app.rs b/src/app.rs index 5166e83..bb63afd 100644 --- a/src/app.rs +++ b/src/app.rs @@ -56,6 +56,7 @@ static STOPPING: AtomicBool = AtomicBool::new(false); mod branch; mod followup_ui; mod deliver_ui; +mod claims_ui; mod talk_ui; mod group; #[cfg(test)] @@ -2285,6 +2286,10 @@ impl App { if !leftover.is_empty() { self.pending_turns.push((bot_id, leftover)); } + // 完成宣稱關卡: what the reply says, against what the turn did (claims_ui.rs). + if outcome == TurnOutcome::Success && !is_branch { + self.check_claims(bot_id); + } } self.approvals.remove(&bot_id); self.app_pending.remove(&bot_id); @@ -7364,6 +7369,10 @@ fn group_history(messages: &[Message], speaker: Option, conv: u64, st: &Sta if m.role == Role::Assistant && !m.reactions.is_empty() { m.text = format!("{}\n(使用者對這則回應:{})", m.text, m.reactions.join(" ")); } + // 完成宣稱關卡: what AnyBot found when it checked this reply against its turn. + if m.role == Role::Assistant && !m.check.is_empty() { + m.text = format!("{}\n{}", m.text, crate::claims::history_line(&m.check)); + } // In a bot's own chat, a colleague's report (message_bot's answer back) is its words, // labelled — not this bot's own. if speaker.is_none() && m.role == Role::Assistant && m.author != 0 && m.author != conv && !m.summary { diff --git a/src/app/chat_ui.rs b/src/app/chat_ui.rs index 7cab1dc..bbceb52 100644 --- a/src/app/chat_ui.rs +++ b/src/app/chat_ui.rs @@ -835,6 +835,10 @@ impl App { self.delivery_mark(ui, bot.id, &a, &card); } } + // 完成宣稱關卡: 「未驗證」 when the reply didn't match what its turn did. + if !m.check.is_empty() && !streaming { + self.claims_mark(ui, &m.check); + } if !m.reactions.is_empty() { ui.add_space(4.0); ui.horizontal(|ui| { @@ -1195,9 +1199,9 @@ pub fn slash_commands(draft: &str) -> Vec<(&'static str, &'static str)> { /// The tags a woken message starts with: (tag, icon, label). The emoji forms are what older chats /// were saved with. (The phone has the same table: mobile/index.html WAKE_TAGS.) -const WAKE_TAGS: [(&str, crate::icons::Icon, &str); 10] = { +const WAKE_TAGS: [(&str, crate::icons::Icon, &str); 11] = { use crate::icons::Icon; - [("[目標]", Icon::Target, "目標"), ("[例行任務]", Icon::Alarm, "例行任務"), ("[觸發]", Icon::Zap, "觸發"), ("[訊息管道]", Icon::Message, "訊息管道"), ("[來自 Bot]", Icon::Bot, "來自其他 Bot"), ("[交付]", Icon::Alert, "交付沒顯示"), ("⏰ ", Icon::Alarm, "例行任務"), ("⚡ ", Icon::Zap, "觸發"), ("💬 ", Icon::Message, "訊息管道"), ("📨 ", Icon::Bot, "來自其他 Bot")] + [("[目標]", Icon::Target, "目標"), ("[例行任務]", Icon::Alarm, "例行任務"), ("[觸發]", Icon::Zap, "觸發"), ("[訊息管道]", Icon::Message, "訊息管道"), ("[來自 Bot]", Icon::Bot, "來自其他 Bot"), ("[交付]", Icon::Alert, "交付沒顯示"), (crate::claims::WAKE_TAG, Icon::Alert, "回覆沒對上"), ("⏰ ",Icon::Alarm, "例行任務"), ("⚡ ", Icon::Zap, "觸發"), ("💬 ", Icon::Message, "訊息管道"), ("📨 ", Icon::Bot, "來自其他 Bot")] }; /// "[例行任務]…" → (icon, label) and the words after the tag. diff --git a/src/app/claims_ui.rs b/src/app/claims_ui.rs new file mode 100644 index 0000000..3b43713 --- /dev/null +++ b/src/app/claims_ui.rs @@ -0,0 +1,184 @@ +// 完成宣稱關卡 in the window: when a turn ends well, its reply is held up against what the turn +// really did (claims.rs) and what is found is kept on the reply. A hard one — said done or sent +// and it wasn't, a link only the bot's computer opens — wakes the bot once to put it right, when +// the turn was the owner's. Under the reply: a quiet 「未驗證」, why on hover. (The phone draws the +// same from message_json's `check`; a screen computer from the brain's message.) A link to a +// place on the bot's computer whose file is in the chat opens that file (markdown_ui). + +use super::*; +use crate::claims::{self, Flag, Kind}; + +/// Wakes for replies that didn't match since the person last wrote: no more than this. +const WAKES_PER_EXCHANGE: usize = 1; + +/// How many times the bot was woken for a reply that didn't match since the owner last wrote. +fn wakes_since_person(msgs: &[Message]) -> usize { + // (The owner's own word: a teammate's, another bot's or a 支線's report doesn't count again.) + let from = msgs.iter().rposition(|m| m.role == Role::User && !m.wake && !m.untrusted_sender && m.from_bot == 0 && m.branch == 0).map_or(0, |i| i + 1); + msgs[from..].iter().filter(|m| m.wake && m.text.starts_with(claims::WAKE_TAG)).count() +} + +impl App { + /// After a turn that ended well (settle): its reply against its steps. Kept on the reply; a + /// hard one wakes the bot once — only when the owner started the turn (not a messaging + /// channel, a teammate or another bot: their request must not come back as a turn with the + /// owner's trust), not in a group chat (every member would take a turn), not while a goal + /// goes on (its judge reads the steps and carries on) or the person's next words wait. + pub(super) fn check_claims(&mut self, bot_id: u64) { + if self.demo { + return; + } + let goal_on = self.state.bot(bot_id).and_then(|b| b.goal.as_ref()).is_some_and(|g| g.active()); + let person_next = self.pending_turns.iter().any(|(b, _)| *b == bot_id); + let waiting = self.waiting_wakes.iter().filter(|(b, m)| *b == bot_id && m.text.starts_with(claims::WAKE_TAG)).count(); + let Some(b) = self.state.bot_mut(bot_id) else { return }; + // The turn: from the message that started it (words sent while it worked are part of it). + let Some(start) = b.messages.iter().rposition(|m| m.role == Role::User && !m.steer) else { return }; + let Some((at, flags)) = claims::check(&b.messages, start, !b.members.is_empty()) else { return }; + if flags.is_empty() || b.messages[at].check == flags { + return; + } + log::info!("AnyBot:完成宣稱關卡 Bot {bot_id}:{}", flags.iter().map(|f| format!("{:?}", f.kind)).collect::>().join("、")); + b.messages[at].check = flags.clone(); + let starter = &b.messages[start]; + let owners = !starter.untrusted_sender && starter.from_bot == 0; + let quiet = !b.members.is_empty() || !owners || goal_on || person_next; + let hard: Vec = flags.iter().map(|f| f.kind).filter(|k| k.hard()).collect(); + let since = wakes_since_person(&b.messages) + waiting; + self.mark(); + self.save_now = true; + if hard.is_empty() || quiet || since >= WAKES_PER_EXCHANGE { + return; + } + // (The bot is free now: the wake starts its own turn on the next tick.) + self.waiting_wakes.push((bot_id, Message { wake: true, ..Message::user(&claims::wake_text(&hard)) })); + } + + /// Under a reply AnyBot couldn't verify: 「未驗證」, and why on hover. + pub(super) fn claims_mark(&self, ui: &mut egui::Ui, flags: &[Flag]) { + let shown: Vec<&Flag> = flags.iter().filter(|f| f.kind.shown()).collect(); + if shown.is_empty() { + return; + } + let p = self.pal; + ui.add_space(2.0); + let row = ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 4.0; + let (rect, _) = ui.allocate_exact_size(vec2(12.0, 12.0), egui::Sense::hover()); + crate::icons::paint(ui.painter(), rect, crate::icons::Icon::Alert, p.text3); + ui.label(RichText::new(t("未驗證")).size(FONT_XS).color(p.text3)); + }); + row.response.interact(egui::Sense::hover()).on_hover_ui(|ui| { + ui.set_max_width(340.0); + ui.label(RichText::new(t("AnyBot 核對這一輪實際做了什麼,跟這則回覆對不上")).size(FONT_SM).color(p.text)); + for f in shown { + ui.label(RichText::new(format!("• {}", f.why)).size(FONT_XS).color(p.text2)); + } + }); + } + + /// A link to a place on the bot's computer (claims::dead_link): a file of that name in the + /// open chat opens; a path that is on this computer opens as before; otherwise it is said + /// plainly that it can't open here. + pub(super) fn open_dead_link(&mut self, url: &str, name: &str) { + let local = url.strip_prefix("file://").unwrap_or(url); + let local = local.strip_prefix("~/").map(|r| dirs::home_dir().unwrap_or_default().join(r)).unwrap_or_else(|| std::path::PathBuf::from(local)); + let found = self.state.bot(self.state.selected).and_then(|b| b.messages.iter().rev().flat_map(|m| m.attachments.iter()).find(|a| !name.is_empty() && a.name.eq_ignore_ascii_case(name)).map(|a| (a.name.clone(), a.path.clone()))); + if let Some((n, path)) = found { + self.open_file(&n, &path); + } else if !url.to_lowercase().starts_with("sandbox:") && local.is_absolute() && local.exists() { + let _ = crate::computer::spawn_reaped(&mut crate::preview::system_open(&local.display().to_string())); + } else { + self.notice = Some(t("這個連結指到 Bot 電腦上的位置,這裡打不開;聊天裡也沒有這個檔案。請 Bot 用 send_file 傳過來。")); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::ToolCall; + + fn test_app(ctx: &egui::Context) -> App { + let mut app = App::new(ctx, Some(std::env::temp_dir().join("anybot-claims.png"))); + // (A made-up screenshot chat checks nothing: this one is real.) + app.demo = false; + app + } + + /// A turn the owner started: the bot's failed send_file, and a reply that says 「已傳」 with a + /// sandbox link. + fn bad_turn(app: &mut App, bot: u64, first: Message) { + let b = app.state.bot_mut(bot).unwrap(); + b.messages.push(first); + b.messages.push(Message { tool_calls: vec![ToolCall { id: "c1".into(), name: "send_file".into(), args: r#"{"path":"x.md"}"#.into(), status: ToolStatus::Failed }], ..Message::assistant("", "") }); + b.messages.push(Message::tool_result("c1", "send_file", "找不到 x.md")); + b.messages.push(Message::assistant("已傳好了 [下載](sandbox:/home/bot/x.md)", "")); + } + + /// Kept on the reply, and the owner's turn wakes the bot once — with fixed words only. + #[test] + fn a_reply_that_doesnt_match_is_marked_and_wakes_once() { + let ctx = egui::Context::default(); + let mut app = test_app(&ctx); + let bot = app.state.bots[0].id; + bad_turn(&mut app, bot, Message::user("把 x.md 傳給我")); + app.check_claims(bot); + let reply = app.state.bot(bot).unwrap().messages.last().unwrap().clone(); + let kinds: Vec = reply.check.iter().map(|f| f.kind).collect(); + assert!(kinds.contains(&Kind::Undone) && kinds.contains(&Kind::DeadLink), "{kinds:?}"); + let woke: Vec = app.waiting_wakes.iter().filter(|(b, _)| *b == bot).map(|(_, m)| m.text.clone()).collect(); + assert_eq!(woke.len(), 1); + assert!(woke[0].starts_with(claims::WAKE_TAG) && !woke[0].contains("x.md") && !woke[0].contains("/home/bot"), "{}", woke[0]); + // Again (the same reply, or the woken turn's reply as bad): no second wake. + app.check_claims(bot); + let woken = app.waiting_wakes.remove(0).1; + bad_turn(&mut app, bot, woken); + app.check_claims(bot); + assert!(app.waiting_wakes.is_empty(), "once since the owner last wrote"); + assert!(!app.state.bot(bot).unwrap().messages.last().unwrap().check.is_empty(), "still marked"); + // The owner writes again: one more is allowed. + bad_turn(&mut app, bot, Message::user("再傳一次")); + app.check_claims(bot); + assert_eq!(app.waiting_wakes.len(), 1); + } + + /// Someone else's turn (a messaging channel, a teammate, another bot), a group chat, a count + /// only: marked, never woken. + #[test] + fn others_turns_and_soft_ones_are_only_marked() { + let ctx = egui::Context::default(); + let mut app = test_app(&ctx); + let bot = app.state.bots[0].id; + for first in [Message { wake: true, untrusted_sender: true, ..Message::user("[訊息管道]【路人】傳給我") }, Message { untrusted_sender: true, ..Message::user("【小明】傳給我") }, Message { from_bot: 99, ..Message::user("傳給我") }] { + bad_turn(&mut app, bot, first); + app.check_claims(bot); + assert!(!app.state.bot(bot).unwrap().messages.last().unwrap().check.is_empty()); + assert!(app.waiting_wakes.is_empty()); + } + let other = app.state.bots[1].id; + app.state.bot_mut(bot).unwrap().members = vec![other]; + bad_turn(&mut app, bot, Message::user("誰傳一下")); + app.check_claims(bot); + assert!(app.waiting_wakes.is_empty(), "a group chat"); + app.state.bot_mut(bot).unwrap().members.clear(); + let b = app.state.bot_mut(bot).unwrap(); + b.messages.push(Message::user("發文")); + b.messages.push(Message { tool_calls: vec![ToolCall { id: "p1".into(), name: "post_to_x".into(), args: r#"{"text":"早安"}"#.into(), status: ToolStatus::Done }], ..Message::assistant("", "") }); + b.messages.push(Message::tool_result("p1", "post_to_x", "已發文")); + b.messages.push(Message::assistant("共送出 3 則。", "")); + app.check_claims(bot); + assert_eq!(app.state.bot(bot).unwrap().messages.last().unwrap().check[0].kind, Kind::Count); + assert!(app.waiting_wakes.is_empty(), "a count is only marked"); + } + + /// The bot reads, after its own reply, what was found (and that it isn't its own words). + #[test] + fn the_bot_reads_what_was_found_under_its_reply() { + let st = State::demo(); + let flags = vec![Flag { kind: Kind::FileLink, why: "連結「下載」指到 Bot 電腦上的位置".into() }]; + let msgs = vec![Message::user("傳"), Message { check: flags, ..Message::assistant("好了 [下載](sandbox:/x.md)", "") }]; + let h = super::super::group_history(&msgs, None, 0, &st); + assert!(h[1].text.contains("〔AnyBot 核對這則回覆時發現") && h[1].text.contains("不是你寫的") && h[1].text.contains("連結「下載」"), "{}", h[1].text); + } +} diff --git a/src/app/markdown_ui.rs b/src/app/markdown_ui.rs index f6f2635..e46ea1a 100644 --- a/src/app/markdown_ui.rs +++ b/src/app/markdown_ui.rs @@ -755,6 +755,12 @@ impl App { if resp.clicked() { self.page_view = Some((pid, None)); } + } else if let Some(name) = crate::claims::dead_link(&url) { + // 完成宣稱關卡: a place on the bot's computer — the chat's file of that name. + let resp = resp.on_hover_text(&url); + if resp.clicked() { + self.open_dead_link(&url, &name); + } } else { let resp = resp.on_hover_text(&url); if resp.clicked() { diff --git a/src/app/mirror_ui.rs b/src/app/mirror_ui.rs index 78b0bae..19dfa14 100644 --- a/src/app/mirror_ui.rs +++ b/src/app/mirror_ui.rs @@ -194,6 +194,8 @@ fn msg_sig(m: &Message) -> u64 { for a in &m.attachments { a.seen.len().hash(&mut h); } + // 完成宣稱關卡: so does the 「未驗證」 under a reply. + m.check.len().hash(&mut h); h.finish() } @@ -2671,6 +2673,18 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// 完成宣稱關卡: a reply marked on the brain changes its fingerprint, so the screens hear of it + /// (and get the mark with the message). + #[test] + fn a_replys_check_reaches_the_screens() { + let m = Message::assistant("已傳好了", ""); + let before = msg_sig(&m); + let marked = Message { check: vec![crate::claims::Flag { kind: crate::claims::Kind::NoFile, why: "沒有檔案".into() }], ..m }; + assert_ne!(msg_sig(&marked), before); + let back: Message = serde_json::from_value(serde_json::to_value(&marked).unwrap()).unwrap(); + assert_eq!(back.check, marked.check); + } + /// 交付確認 on a screen computer: the brain's file is shown from a local copy, but keeps its /// id; what the screen saw goes to the brain by that id (named there, by who asked); a /// device's word on a file changes the message's fingerprint, so the screens hear of it. diff --git a/src/app/remote_ui.rs b/src/app/remote_ui.rs index 675c07a..ed6be01 100644 --- a/src/app/remote_ui.rs +++ b/src/app/remote_ui.rs @@ -306,6 +306,8 @@ impl App { for a in &m.attachments { a.seen.len().hash(&mut h); } + // 完成宣稱關卡: the reply's 「未驗證」. + m.check.len().hash(&mut h); } if let Some(l) = self.streams.get(&b.id) { (1u8, &l.status, l.paused, l.steer.lock().unwrap().len()).hash(&mut h); diff --git a/src/appctl.rs b/src/appctl.rs index bf600f9..bf52cbf 100644 --- a/src/appctl.rs +++ b/src/appctl.rs @@ -311,7 +311,8 @@ pub struct Outcome { pub page: Option, } -/// Pages sent back once by the 寫法檢查 (bot, title): the next write of the same page is saved. +/// Pages sent back once by the 寫法檢查 (bot, pages::write_key): the next write of the same page +/// is saved. static SENT_BACK: std::sync::Mutex> = std::sync::Mutex::new(std::collections::BTreeSet::new()); fn ok(text: String) -> Outcome { @@ -502,14 +503,18 @@ pub fn apply(state: &mut State, bot_id: u64, name: &str, args: &str) -> Outcome return err(format!("這是「{who}」的頁面,你只能讀不能改。要改請它改(ask_bot 或 message_bot 交代要改什麼),或不帶 id 做一頁你自己的。")); } // 寫法檢查: a page that reads badly is sent back once with what to fix; the next try - // is saved whatever it still has (no loop when something can't be helped). - let key = (bot_id, v["title"].as_str().unwrap_or("").trim().to_string()); - let fixes = crate::pages::review(v["content"].as_str().unwrap_or("")); - { + // is saved whatever it still has (no loop when something can't be helped). The same + // page by id or by title; only a try with content counts — a bot that sends the + // content, then the kind and summary on their own, was sent back again and again + // (the second call, with no content, used to clear the first). + let content = v["content"].as_str().unwrap_or(""); + if !content.trim().is_empty() { + let key = (bot_id, crate::pages::write_key(&state.pages, bot_id, &v)); + let fixes = crate::pages::review(content); let mut sent_back = SENT_BACK.lock().unwrap_or_else(|e| e.into_inner()); if !fixes.is_empty() && sent_back.insert(key.clone()) { return err(format!( - "頁面還沒存:照這幾點改寫後再呼叫一次 write_page(同樣的標題)——\n• {}\n改不掉的地方第二次會照樣存。", + "頁面還沒存:照這幾點改寫後再呼叫一次 write_page(同樣的 id 或標題,帶整頁 content)——\n• {}\n改不掉的地方第二次會照樣存。只改 kind、summary、verdict 這些的話,不用帶 content。", fixes.join("\n• ") )); } @@ -1287,6 +1292,43 @@ mod tests { assert!(apply(&mut st, b, "write_page", &clean).ok); } + /// The real case: a bot updating its page sent the content (sent back), then the kind, note, + /// summary and verdict on their own with only the id (「頁面內容是空的」, and that cleared the + /// sent-back mark) — eight rounds, and the page stayed old. Now the fields change, and the + /// next try with content is the second try of the same page: saved. + #[test] + fn a_page_sent_back_is_saved_on_its_next_content_whatever_comes_between() { + let mut st = State::samples(); + let b = st.bots[0].id; + assert!(apply(&mut st, b, "write_page", &json!({"title": "助理規格", "content": "## 現況\n舊版。"}).to_string()).ok); + let pid = st.pages.iter().find(|p| p.bot == b && p.title == "助理規格").unwrap().id; + let messy = json!({"id": pid, "content": "## 一、目的\n新版。\n\n---"}).to_string(); + let first = apply(&mut st, b, "write_page", &messy); + assert!(!first.ok && first.text.contains("頁面還沒存") && first.text.contains("不用帶 content"), "{}", first.text); + let meta = apply(&mut st, b, "write_page", &json!({"id": pid, "kind": "decision", "note": "改寫", "summary": "定稿", "verdict": "先做可信任"}).to_string()); + assert!(meta.ok && meta.page == Some(pid) && meta.text.contains("種類") && meta.text.contains("內容沒動"), "{}", meta.text); + let p = st.pages.iter().find(|p| p.id == pid).unwrap(); + assert_eq!((p.kind.as_str(), p.summary.as_str(), p.verdict.as_str(), p.body.as_str(), p.revision), ("decision", "定稿", "先做可信任", "## 現況\n舊版。", 1)); + // The same page by its title this time: still its second try. + let second = apply(&mut st, b, "write_page", &json!({"title": "助理規格", "content": "## 一、目的\n新版。\n\n---"}).to_string()); + assert!(second.ok, "{}", second.text); + let p = st.pages.iter().find(|p| p.id == pid).unwrap(); + assert!(p.body.contains("新版") && p.revision == 2 && p.title == "助理規格" && p.kind == "decision", "{p:?}"); + // A new page: sent back by its title, a fields-only try in between (no page yet), saved next. + let new = json!({"title": "新的一頁", "content": "## 一、開頭\n內容"}).to_string(); + assert!(!apply(&mut st, b, "write_page", &new).ok); + let between = apply(&mut st, b, "write_page", &json!({"title": "新的一頁", "kind": "notes"}).to_string()); + assert!(!between.ok && between.text.contains("內容是空的"), "{}", between.text); + assert!(apply(&mut st, b, "write_page", &new).ok); + // Nothing to change at all: said so. + let nothing = apply(&mut st, b, "write_page", &json!({"id": pid}).to_string()); + assert!(!nothing.ok && nothing.text.contains("沒有要改的欄位"), "{}", nothing.text); + // New content by id alone keeps the title. + assert!(apply(&mut st, b, "write_page", &json!({"id": pid, "content": "## 現況\n第三版。"}).to_string()).ok); + let p = st.pages.iter().find(|p| p.id == pid).unwrap(); + assert_eq!((p.title.as_str(), p.revision), ("助理規格", 3)); + } + /// 共用資源: a colleague's page is read, never overwritten; a skill is taught (the person is /// asked first); what's about the person is kept once for every bot; a request can't go /// round the bots for ever. diff --git a/src/claims.rs b/src/claims.rs new file mode 100644 index 0000000..d59acf7 --- /dev/null +++ b/src/claims.rs @@ -0,0 +1,615 @@ +// 完成宣稱關卡: what a bot's reply says it did, checked by the program against what its turn +// really did — at the end of every turn, never by asking the bot. Real cases: a bot sent a file +// into the chat and ended with 「[下載:….md](sandbox:/home/bot/bot-12/….md)」, a link that opens +// nothing on the person's phone; another said 「已完成」 after the step that would have done it +// failed; another 「送出 2 則」 when one went (evidence.rs). +// +// Few and sure — a wrong mark costs more than a missed one: a claim counts only where the words +// plainly say it is done (not 「還沒」, 「如果…」, 「…之後」, a question, a hedge, a reply that +// owns up to a failure), and a link only where it can't open anywhere but the bot's computer. +// What is found is kept on the reply (Message::check): a quiet 「未驗證」 under it, the bot reads +// it with its reply next turn (app::group_history), and a hard one wakes the bot once (app.rs). + +use crate::model::{Message, Role, ToolCall, ToolStatus}; +use serde::{Deserialize, Serialize}; + +/// The tag a woken message starts with when a reply didn't match its turn (chat_ui WAKE_TAGS, +/// mobile/index.html WAKE_TAGS). +pub const WAKE_TAG: &str = "[核對]"; + +/// What kind of mismatch. +#[derive(Clone, Copy, Serialize, Deserialize, Debug, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum Kind { + /// Said done or sent, and the turn's last step that would have done it failed or was refused. + Undone, + /// Said it put a file in the chat, and the turn put none there. + NoFile, + /// A link to a place on the bot's computer (sandbox:, file://, a path) — opens on no device + /// of the person's — and no file of that name in the chat. + DeadLink, + /// A link like that to a file that is in the chat: the screens open that file instead. + FileLink, + /// A number (or 「全部」) the steps don't bear out. + Count, +} + +impl Kind { + /// The person can't get what the reply says they have: the bot is woken once to put it right. + pub fn hard(self) -> bool { + matches!(self, Kind::Undone | Kind::NoFile | Kind::DeadLink) + } + /// Shown under the reply. (A link to a file in the chat opens that file: nothing to show — + /// the bot is still told.) + pub fn shown(self) -> bool { + self != Kind::FileLink + } +} + +/// One thing found, with why in plain words (shown behind the mark and read by the bot). +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)] +pub struct Flag { + pub kind: Kind, + pub why: String, +} + +/// Words that say it is done. +const DONE: [&str; 15] = ["已完成", "已經完成", "完成了", "做好了", "弄好了", "處理好了", "辦好了", "搞定", "都好了", "寫好了", "改好了", "修好了", "設好了", "建好了", "整理好了"]; +/// Words that say something went to the person or out. +const SENT: [&str; 29] = [ + "已傳", "已經傳", "傳好了", "傳給你了", "傳過去了", "已送出", "已經送出", "送出了", "已寄出", "已經寄出", "寄出了", "寄好了", "已交付", "已上傳", "已經上傳", "上傳好了", "上傳了", "已發佈", "已發布", "已經發佈", "已經發布", "發佈了", "發布了", "已發送", "已附上", "附上了", "已放進聊天", "放進聊天了", "已經附上", +]; +/// …of those, the ones that say a file came with the reply (in the chat). +const FILE_SENT: [&str; 12] = ["已傳", "已經傳", "傳好了", "傳給你了", "已附上", "附上了", "已經附上", "已放進聊天", "放進聊天了", "已上傳", "已經上傳", "已交付"]; +/// What a file is called. +const FILE_WORDS: [&str; 12] = ["檔案", "文件", "附件", "圖片", "圖檔", "照片", "截圖", "報告", "規格", "簡報", "試算表", "PDF"]; +/// Where a file goes that isn't the chat (send_to_device, mail, a drive, a site…). +const ELSEWHERE: [&str; 17] = ["手機", "裝置", "信箱", "郵件", "email", "Email", "雲端", "Drive", "Slack", "Telegram", "Discord", "LINE", "網站", "網址", "資料夾", "桌面", "伺服器"]; +/// The same in English (lower case). +const EN_CLAIMS: [&str; 16] = ["i've sent", "i have sent", "has been sent", "have been sent", "i've uploaded", "has been uploaded", "i've attached", "is attached", "i've delivered", "has been delivered", "i've published", "has been published", "i've completed", "has been completed", "all done", "it's done"]; +const EN_NOT: [&str; 12] = ["not ", "n't", "never", "if ", "once ", "when ", "after ", "will ", "going to", "unable", "failed", "couldn"]; +/// Anywhere in the sentence: it isn't (all) done, or it owns up to a problem. +const NOT_DONE: [&str; 23] = ["還沒", "尚未", "沒有", "沒能", "沒辦法", "無法", "未能", "失敗", "不能", "不了", "未完成", "沒完成", "沒傳", "沒送", "沒成功", "不成功", "出錯", "卡住", "但", "不過", "只是", "除了", "部分"]; +/// Said kindly, not a "not" (removed before NOT_DONE is looked for). +const BENIGN: [&str; 6] = ["沒有問題", "沒問題", "沒有錯誤", "沒有任何錯誤", "沒錯", "不客氣"]; +/// Before the claim: a condition, a plan, a hedge. +const IF_LATER: [&str; 24] = ["如果", "若", "假如", "要是", "萬一", "一旦", "等你", "等我", "等它", "等到", "等一下", "之後", "以後", "稍後", "待會", "我會", "會再", "將會", "準備", "打算", "應該", "可能", "希望", "是否"]; +/// Right after the claim: what it modifies or waits for (「已完成的部分」「傳好了之後」「做好了再…」). +const AFTER: [&str; 9] = ["的", "之後", "以後", "後", "再", "嗎", "沒", "與否", "了沒"]; +/// Words in the reply that own up to a step that didn't go (then a 「已完成」 elsewhere in it +/// isn't taken against the failed step). +const OWNS_UP: [&str; 12] = ["失敗", "沒成功", "不成功", "出錯", "被擋", "擋下", "拒絕", "無法", "沒辦法", "卡住", "還沒", "尚未"]; +/// The reply refers to something sent before this turn. +const BEFORE: [&str; 10] = ["之前", "剛才", "剛剛", "上次", "先前", "稍早", "上一則", "前面", "上面", "昨天"]; + +/// The words of a reply that make claims: without code (```…``` and `…`) and quoted lines. +fn prose(text: &str) -> String { + let mut out = String::new(); + let mut fenced = false; + for line in text.lines() { + let t = line.trim_start(); + if t.starts_with("```") || t.starts_with("~~~") { + fenced = !fenced; + } else if !fenced && !t.starts_with('>') { + let mut code = false; + for ch in line.chars() { + if ch == '`' { + code = !code; + } else if !code { + out.push(ch); + } + } + } + out.push('\n'); + } + out +} + +/// Its sentences, each with whether it asks. +fn sentences(text: &str) -> Vec<(String, bool)> { + let mut out = vec![]; + let mut cur = String::new(); + let chars: Vec = text.chars().collect(); + for (i, &ch) in chars.iter().enumerate() { + let end = match ch { + '。' | '!' | '!' | '\n' | ';' | ';' => Some(false), + '?' | '?' => Some(true), + // (A full stop, not the dot of a file name.) + '.' if chars.get(i + 1).is_none_or(|c| c.is_whitespace()) => Some(false), + _ => None, + }; + match end { + Some(asks) => { + if !cur.trim().is_empty() { + out.push((std::mem::take(&mut cur), asks)); + } + cur.clear(); + } + None => cur.push(ch), + } + } + if !cur.trim().is_empty() { + out.push((cur, false)); + } + out +} + +/// The sentence when nothing in it says 「not (all) done」 (said kindly — 「沒問題」 — isn't a 「沒」). +fn unhedged(sentence: &str) -> Option { + let mut s = sentence.to_string(); + for b in BENIGN { + s = s.replace(b, ""); + } + (!s.contains('嗎') && !NOT_DONE.iter().any(|n| s.contains(n))).then_some(s) +} + +fn add(flags: &mut Vec, f: Flag) { + if !flags.iter().any(|g| g.kind == f.kind) { + flags.push(f); + } +} + +/// A claim in a sentence: (the claim word, whether it is about sending). +fn claim_in(sentence: &str, asks: bool) -> Option<(&'static str, bool)> { + if asks || sentence.contains('嗎') { + return None; + } + let low = sentence.to_lowercase(); + if let Some(w) = EN_CLAIMS.iter().copied().find(|w| low.contains(w)) { + if EN_NOT.iter().any(|n| low.contains(n)) { + return None; + } + let sent = !w.contains("done") && !w.contains("completed"); + return Some((w, sent)); + } + let s = unhedged(sentence)?; + let words = SENT.iter().map(|w| (*w, true)).chain(DONE.iter().map(|w| (*w, false))); + for (w, sent) in words { + let Some(at) = s.find(w) else { continue }; + let before = &s[..at]; + let after = &s[at + w.len()..]; + // Inside 「…」: quoted, not said. + if before.matches('「').count() > before.matches('」').count() { + continue; + } + // Someone else did it (「你已上傳」), not 「幫你…」. + let last2: String = before.trim_end().chars().rev().take(2).collect::>().into_iter().rev().collect(); + if (last2.ends_with('你') || last2.ends_with('您') || last2.ends_with('他') || last2.ends_with('她')) && !["幫你", "替你", "給你", "為你", "幫您", "替您", "給您", "為您"].contains(&last2.as_str()) { + continue; + } + if IF_LATER.iter().any(|m| before.contains(m)) || AFTER.iter().any(|m| after.trim_start().starts_with(m)) { + continue; + } + return Some((w, sent)); + } + None +} + +/// Steps that only look (reading, searching, a card): never what a 「已完成」 rests on. +fn only_looks(name: &str) -> bool { + const PREFIX: [&str; 12] = ["read_", "list_", "search_", "get_", "find", "view_", "query", "web_search", "web_fetch", "fetch", "recall", "look"]; + const NAMES: [&str; 10] = ["anybot_guide", "react", "show_card", "wait_answer", "browser_snapshot", "browser_screenshot", "computer_use_screenshot", "use_skill", "update_plan", "think"]; + PREFIX.iter().any(|p| name.starts_with(p)) || NAMES.contains(&name) +} + +/// Steps that hand something over or send it out. +fn delivers(call: &ToolCall) -> bool { + const NAMES: [&str; 6] = ["send_file", "send_to_device", "publish_site", "message_bot", "post_to_x", "send_sms"]; + let low = call.name.to_lowercase(); + NAMES.contains(&call.name.as_str()) || crate::evidence::sends(call) || ["send", "upload", "publish", "post", "mail", "reply"].iter().any(|w| low.contains(w)) +} + +/// Whether a step that ended failed really didn't go: a command that only answered 「no」 +/// (grep found nothing, a test was false: exit code 1 and nothing printed) isn't a failure. +fn really_failed(call: &ToolCall, result: Option<&Message>) -> bool { + match call.status { + ToolStatus::Denied => true, + ToolStatus::Failed => !(call.name == "shell" && result.is_some_and(|r| r.text.strip_prefix("結束代碼 1").is_some_and(|rest| rest.trim().is_empty()))), + _ => false, + } +} + +/// A link target that opens only on the bot's computer: sandbox:…, file://…, an absolute path +/// (/home/…, ~/…, C:\…) or one relative to a folder (./…, ../…). Its file name when it is one. +pub fn dead_link(target: &str) -> Option { + let t = target.trim().trim_start_matches('<').trim_end_matches('>'); + let low = t.to_lowercase(); + let b = t.as_bytes(); + let path = if low.starts_with("sandbox:") || low.starts_with("file:") { + t.split_once(':').map(|(_, p)| p).unwrap_or("") + } else if (t.starts_with('/') && !t.starts_with("//")) || t.starts_with("~/") || t.starts_with("./") || t.starts_with("../") || (b.len() > 2 && b[0].is_ascii_alphabetic() && b[1] == b':' && (b[2] == b'\\' || b[2] == b'/')) { + t + } else { + return None; + }; + let path = path.split(['?', '#']).next().unwrap_or(""); + let name = path.rsplit(['/', '\\']).next().unwrap_or(""); + Some(percent_decode(name)) +} + +fn percent_decode(s: &str) -> String { + let b = s.as_bytes(); + let mut out = Vec::with_capacity(b.len()); + let mut i = 0; + while i < b.len() { + if b[i] == b'%' && i + 2 < b.len() { + if let Some(v) = std::str::from_utf8(&b[i + 1..i + 3]).ok().and_then(|h| u8::from_str_radix(h, 16).ok()) { + out.push(v); + i += 3; + continue; + } + } + out.push(b[i]); + i += 1; + } + String::from_utf8(out).unwrap_or_else(|_| s.to_string()) +} + +/// The links in a reply: (their words, where they point). Markdown [words](target) and . +fn links(text: &str) -> Vec<(String, String)> { + let mut out = vec![]; + let mut rest = text; + while let Some(i) = rest.find("](") { + let words = rest[..i].rsplit_once('[').map(|(_, w)| w).unwrap_or(""); + let tail = &rest[i + 2..]; + let end = tail.find(')').unwrap_or(tail.len()); + let target = tail[..end].trim(); + // (A title after the target: [a](/x.md "title").) + let target = target.split_once(" \"").map(|(t, _)| t).unwrap_or(target); + out.push((words.to_string(), target.to_string())); + rest = &tail[end.min(tail.len())..]; + } + let mut rest = text; + while let Some(i) = rest.find('<') { + let tail = &rest[i + 1..]; + let Some(end) = tail.find('>') else { break }; + let t = &tail[..end]; + let low = t.to_lowercase(); + if (low.starts_with("sandbox:") || low.starts_with("file:")) && !t.contains(char::is_whitespace) { + out.push((String::new(), t.to_string())); + } + rest = &tail[end..]; + } + out +} + +/// 一、二、兩…九十九, or digits. +fn number(s: &str) -> Option { + if let Ok(n) = s.parse() { + return Some(n); + } + let digit = |c: char| "零一二三四五六七八九".chars().position(|d| d == c).map(|p| p as u32).or((c == '兩').then_some(2)); + let cs: Vec = s.chars().collect(); + match cs.as_slice() { + [a] if *a == '十' => Some(10), + [a] => digit(*a), + ['十', b] => Some(10 + digit(*b)?), + [a, '十'] => Some(digit(*a)? * 10), + [a, '十', b] => Some(digit(*a)? * 10 + digit(*b)?), + _ => None, + } +} + +/// 「送出 2 則」「已傳 3 張圖」: (how many, whether it is files rather than messages). +fn counts(sentence: &str) -> Vec<(u32, bool)> { + use std::sync::OnceLock; + static MSGS: OnceLock = OnceLock::new(); + static FILES: OnceLock = OnceLock::new(); + let msgs = MSGS.get_or_init(|| regex::Regex::new(r"(?:傳送|發送|送出|發出|發了|發佈|發布|回覆|回了|貼出|貼了|留言|私訊|傳)了?\s*(\d+|[一二兩三四五六七八九十]+)\s*(?:則|篇|條)").unwrap()); + let files = FILES.get_or_init(|| regex::Regex::new(r"(?:傳|附上|放進聊天|送出)了?\s*(\d+|[一二兩三四五六七八九十]+)\s*(?:個檔案|份檔案|個附件|份|張圖片|張圖|張照片|張)").unwrap()); + let mut out = vec![]; + for (re, file) in [(msgs, false), (files, true)] { + for c in re.captures_iter(sentence) { + if let Some(n) = c.get(1).and_then(|m| number(m.as_str())) { + out.push((n, file)); + } + } + } + out +} + +/// Short, for a reason shown in one line. +fn short(s: &str, n: usize) -> String { + let t: String = s.chars().take(n).collect(); + if s.chars().count() > n { format!("{t}…") } else { t } +} + +/// What a turn's reply claims that its steps don't bear out. `chat`: the whole chat; `start`: +/// the message that began the turn; `group`: a group chat. The reply is the turn's last message +/// of the bot's own with words — not a 支線's report or a colleague's (put in the chat as the +/// bot's, with `branch` or another `author`); in a group chat, the member who answered, and only +/// its steps count. Its index and what was found (maybe nothing). +pub fn check(chat: &[Message], start: usize, group: bool) -> Option<(usize, Vec)> { + let own = |m: &Message| m.role == Role::Assistant && m.branch == 0 && (group || m.author == 0); + let reply_at = (start..chat.len()).rev().find(|&i| { + let m = &chat[i]; + own(m) && !m.text.trim().is_empty() && !m.note && !m.error && !m.summary && !m.interrupted + })?; + let reply = &chat[reply_at]; + let turn: Vec<&Message> = chat[start..].iter().filter(|m| m.role != Role::Assistant || (own(m) && m.author == reply.author)).collect(); + let results: std::collections::HashMap<&str, &Message> = turn.iter().filter(|m| m.role == Role::Tool).map(|m| (m.tool_call_id.as_str(), *m)).collect(); + let steps: Vec<(&ToolCall, Option<&Message>)> = turn.iter().filter(|m| m.role == Role::Assistant).flat_map(|m| m.tool_calls.iter()).map(|c| (c, results.get(c.id.as_str()).copied())).collect(); + // Files this turn put in the chat (send_file's land on its message; a picture shown too). + let attached: usize = turn.iter().filter(|m| m.role == Role::Assistant).map(|m| m.attachments.len()).sum(); + let files_here = attached.max(steps.iter().filter(|(c, _)| c.name == "send_file" && c.status == ToolStatus::Done).count()); + let words = prose(&reply.text); + let owns_up = OWNS_UP.iter().any(|w| words.contains(w)); + let mut flags: Vec = vec![]; + + // (b) Links that open only on the bot's computer. + let chat_files: Vec<&crate::attach::Attachment> = chat[..=reply_at].iter().flat_map(|m| m.attachments.iter()).collect(); + for (label, target) in links(&words) { + let Some(name) = dead_link(&target) else { continue }; + let shown = if label.trim().is_empty() { short(&target, 40) } else { short(label.trim(), 30) }; + let place = short(&target, 48); + match chat_files.iter().rev().find(|a| !name.is_empty() && a.name.eq_ignore_ascii_case(&name)) { + Some(a) => add(&mut flags, Flag { kind: Kind::FileLink, why: format!("連結「{shown}」指到 Bot 電腦上的位置({place}),手機和其他電腦打不開;畫面改成打開聊天裡的附件「{}」", short(&a.name, 40)) }), + None => add(&mut flags, Flag { kind: Kind::DeadLink, why: format!("連結「{shown}」指到 Bot 電腦上的位置({place}),手機和其他電腦打不開;聊天裡也沒有這個檔案") }), + } + } + + // (a) Said done or sent, and the step that would have done it didn't go; said a file came, and none did. + for (s, asks) in sentences(&words) { + let Some((word, about_sending)) = claim_in(&s, asks) else { continue }; + let related = |c: &ToolCall| if about_sending { delivers(c) } else { !only_looks(&c.name) }; + if let Some((c, r)) = steps.iter().rev().find(|(c, _)| related(c)) { + if really_failed(c, *r) && !owns_up { + let how = if c.status == ToolStatus::Denied { "被擋下了" } else { "失敗了" }; + add(&mut flags, Flag { kind: Kind::Undone, why: format!("說「{word}」,但這一輪最後一個相關的步驟「{}」{how}", crate::remote::tool_label(&c.name)) }); + continue; + } + } + let file_claim = FILE_SENT.contains(&word) && (FILE_WORDS.iter().any(|w| s.contains(w)) || has_file_name(&s)); + let went_elsewhere = ELSEWHERE.iter().any(|w| s.contains(w)) || steps.iter().any(|(c, _)| c.status == ToolStatus::Done && c.name != "send_file" && delivers(c)); + let named_before = file_names(&s).iter().any(|n| chat[..start].iter().flat_map(|m| m.attachments.iter()).any(|a| a.name.eq_ignore_ascii_case(n))); + if file_claim && files_here == 0 && !went_elsewhere && !owns_up && !named_before && !BEFORE.iter().any(|w| s.contains(w)) { + add(&mut flags, Flag { kind: Kind::NoFile, why: format!("說「{word}」檔案,但這一輪沒有任何檔案放進聊天") }); + } + } + + // (c) Numbers the steps don't bear out. + let tally = crate::evidence::tally(&turn.iter().map(|m| (*m).clone()).collect::>()); + let tried_sends = steps.iter().any(|(c, r)| crate::evidence::sends(c) || crate::evidence::went_out(c, *r)); + let uncounted = steps.iter().any(|(c, _)| crate::mcp::is_mcp_tool(&c.name)); + if !flags.iter().any(|f| f.kind == Kind::Undone) { + for (s, asks) in sentences(&words) { + if asks || unhedged(&s).is_none() || IF_LATER.iter().any(|m| s.contains(m)) { + continue; + } + for (n, file) in counts(&s) { + if file && files_here >= 1 && n as usize > files_here { + add(&mut flags, Flag { kind: Kind::Count, why: format!("說傳了 {n} 個檔案,這一輪只有 {files_here} 個放進聊天") }); + } else if !file && tried_sends && !uncounted && n > tally.sent { + add(&mut flags, Flag { kind: Kind::Count, why: format!("說送出 {n} 則,系統只數到 {} 則真的送出去", tally.sent) }); + } + } + } + } + Some((reply_at, flags)) +} + +/// File names (x.md, 規格-給CodeAgent.md) in a sentence. +fn file_names(s: &str) -> Vec { + use std::sync::OnceLock; + static RE: OnceLock = OnceLock::new(); + let re = RE.get_or_init(|| regex::Regex::new(r"[^\s「」『』()()\[\]<>、,,::]+\.(?:md|txt|pdf|png|jpe?g|gif|webp|svg|docx?|xlsx?|csv|pptx?|zip|html?|json|mp3|mp4|mov|wav)\b").unwrap()); + re.find_iter(s).map(|m| m.as_str().to_string()).collect() +} + +fn has_file_name(s: &str) -> bool { + !file_names(s).is_empty() +} + +/// What the bot reads after its own reply next turn (app::group_history). +pub fn history_line(flags: &[Flag]) -> String { + format!("〔AnyBot 核對這則回覆時發現(這行是系統加的,不是你寫的):{}〕", flags.iter().map(|f| f.why.as_str()).collect::>().join(";")) +} + +/// The message that wakes the bot once to put a hard one right. Only fixed words: what it said +/// and linked is its own, but the message starts a turn with the owner's trust, so nothing from +/// the reply (or from a page or a file name it may have copied) rides along — the bot reads its +/// reply and the line under it. +pub fn wake_text(kinds: &[Kind]) -> String { + let mut why: Vec<&str> = vec![]; + for k in kinds { + let w = match k { + Kind::Undone => "回覆說做好了或傳好了,但這一輪最後一個相關的步驟失敗或被擋下了", + Kind::NoFile => "回覆說傳了檔案,但這一輪沒有任何檔案放進聊天", + Kind::DeadLink => "回覆裡的連結指到你電腦上的位置(sandbox:、file:// 或路徑),使用者的手機和電腦打不開,聊天裡也沒有同名的附件", + _ => continue, + }; + if !why.contains(&w) { + why.push(w); + } + } + format!("{WAKE_TAG}你上一則回覆跟這一輪實際做到的對不上:{}。使用者在他的裝置上還拿不到結果。先查清楚,再做其中一件:真的做完(檔案用 send_file 傳進聊天),或照實告訴使用者還沒好、卡在哪裡、下一步是什麼。不要寫 sandbox:、file:// 或電腦上的路徑當連結。(這是系統的通知,不是使用者說的話。)", why.join(";")) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::attach::Attachment; + + fn step(id: &str, name: &str, args: &str, status: ToolStatus) -> ToolCall { + ToolCall { id: id.into(), name: name.into(), args: args.into(), status } + } + + /// A turn: the person's words, the bot's steps (each with its result), then its reply (with + /// files, if any). + fn turn(steps: Vec<(ToolCall, &str)>, reply: &str, files: Vec<&str>) -> Vec { + let mut msgs = vec![Message::user("幫我做")]; + for (c, result) in steps { + let id = c.id.clone(); + let name = c.name.clone(); + msgs.push(Message { tool_calls: vec![c], ..Message::assistant("", "") }); + msgs.push(Message::tool_result(&id, &name, result)); + } + let atts = files.into_iter().map(|n| Attachment { name: n.into(), path: format!("/brain/{n}"), id: "a1b2c3".into(), ..Default::default() }).collect(); + msgs.push(Message { attachments: atts, ..Message::assistant(reply, "") }); + msgs + } + + fn kinds(msgs: &[Message]) -> Vec { + check(msgs, 0, false).map(|(_, f)| f.into_iter().map(|f| f.kind).collect()).unwrap_or_default() + } + + /// The real case: the file went into the chat, and the reply links it at sandbox:/… — the + /// link opens the attachment instead (nothing to show); with no such file it is marked. + #[test] + fn a_sandbox_link_to_a_file_in_the_chat_opens_it_one_to_nowhere_is_marked() { + let name = "人類助理工程規格-給CodeAgent.md"; + let sent = step("c1", "send_file", &format!(r#"{{"path":"{name}"}}"#), ToolStatus::Done); + let reply = format!("規格寫好了。\n\n[下載:{name}](sandbox:/home/bot/bot-12/{name})"); + let msgs = turn(vec![(sent.clone(), "已把檔案放進聊天(附件 a1b2c3)")], &reply, vec![name]); + let (at, flags) = check(&msgs, 0, false).unwrap(); + assert_eq!(at, msgs.len() - 1); + assert_eq!(flags.iter().map(|f| f.kind).collect::>(), vec![Kind::FileLink]); + assert!(flags[0].why.contains("sandbox:/home/bot") && flags[0].why.contains(name), "{}", flags[0].why); + assert!(!flags[0].kind.shown() && !flags[0].kind.hard()); + // No file of that name: marked, and a hard one. + let msgs = turn(vec![], "已傳好了 [下載](sandbox:/home/bot/x.md)", vec![]); + assert!(kinds(&msgs).contains(&Kind::DeadLink)); + for target in ["file:///Users/me/x.pdf", "/home/bot/out/x.png", "~/報告.docx", "./out/a.csv", "C:\\Users\\me\\a.xlsx", "/mnt/data/%E5%A0%B1%E5%91%8A.md"] { + let msgs = turn(vec![], &format!("在這裡:[檔案]({target})"), vec![]); + assert_eq!(kinds(&msgs), vec![Kind::DeadLink], "{target}"); + } + assert_eq!(dead_link("/mnt/data/%E5%A0%B1%E5%91%8A.md").as_deref(), Some("報告.md")); + assert_eq!(dead_link("").as_deref(), Some("a b.md")); + // Links that open: the web, a page, a mail; a link inside code isn't a link. + for ok in ["[來源](https://example.com/a.md)", "[頁面](page:3)", "[信](mailto:a@b.c)", "[網站](//cdn.example.com/x)", "`[x](/home/bot/x.md)`", "```\n[x](sandbox:/x.md)\n```"] { + assert!(kinds(&turn(vec![], ok, vec![])).is_empty(), "{ok}"); + } + } + + /// (a): 「已完成」「已傳」 after the step that would have done it failed or was refused. + #[test] + fn done_after_the_step_failed_is_marked() { + let failed = step("c1", "send_file", r#"{"path":"a.md"}"#, ToolStatus::Failed); + let msgs = turn(vec![(failed.clone(), "找不到 a.md")], "已傳給你了。", vec![]); + let f = check(&msgs, 0, false).unwrap().1; + assert_eq!(f[0].kind, Kind::Undone); + assert!(f[0].why.contains("已傳") && f[0].why.contains("失敗了"), "{}", f[0].why); + let denied = step("c1", "publish_site", r#"{"path":"a.html"}"#, ToolStatus::Denied); + assert_eq!(kinds(&turn(vec![(denied, "使用者拒絕了這個操作")], "網站已發佈。", vec![])), vec![Kind::Undone]); + let edit = step("c1", "edit_file", r#"{"path":"a.md"}"#, ToolStatus::Failed); + assert_eq!(kinds(&turn(vec![(edit, "找不到要換掉的字")], "搞定!", vec![])), vec![Kind::Undone]); + // Tried again and it went: fine. + let again = step("c2", "send_file", r#"{"path":"a.md"}"#, ToolStatus::Done); + assert!(kinds(&turn(vec![(failed.clone(), "找不到"), (again, "已放進聊天(附件 a1b2c3)")], "已傳給你了。", vec!["a.md"])).is_empty()); + // A look at something after the work (a read that failed) isn't what 「完成」 rests on. + let wrote = step("c1", "edit_file", r#"{"path":"a.md"}"#, ToolStatus::Done); + let read = step("c2", "read_file", r#"{"path":"log.txt"}"#, ToolStatus::Failed); + assert!(kinds(&turn(vec![(wrote, "已修改"), (read, "找不到")], "已完成。", vec![])).is_empty()); + // grep that found nothing (exit 1, nothing printed) didn't fail. + let grep = step("c1", "shell", r#"{"command":"grep -c ERROR log"}"#, ToolStatus::Failed); + assert!(kinds(&turn(vec![(grep, "結束代碼 1\n")], "檢查完成了,處理好了。", vec![])).is_empty()); + let build = step("c1", "shell", r#"{"command":"cargo build"}"#, ToolStatus::Failed); + assert_eq!(kinds(&turn(vec![(build, "結束代碼 101\nerror[E0425]")], "做好了。", vec![])), vec![Kind::Undone]); + } + + /// Not claims: not yet, a plan, a condition, a question, part of it, owning up — and the + /// person's own doing. + #[test] + fn words_that_arent_a_claim_are_left_alone() { + let failed = step("c1", "send_file", r#"{"path":"a.md"}"#, ToolStatus::Failed); + for reply in [ + "我還沒完成。", + "完成後我會通知你。", + "如果傳了,你會在上面看到。", + "已完成的部分是第一章,但第二章還沒。", + "傳好了之後跟你說。", + "要我現在傳給你嗎?", + "檔案傳好了嗎", + "做好了再給你看。", + "已完成大部分,不過最後一步失敗了。", + "傳檔失敗了,我換個方式。報告已完成。", + "你已上傳的檔案我看過了。", + "等你確認我就送出了", + "應該已經完成了,我再確認一次。", + "我把「已完成」的項目標成綠色。", + "I have not sent it yet.", + "Once it is done I will send it.", + ] { + assert!(kinds(&turn(vec![(failed.clone(), "找不到")], reply, vec![])).is_empty(), "{reply}"); + } + // Nothing failed, nothing claimed about a file: nothing to say. + assert!(kinds(&turn(vec![], "好的,了解。", vec![])).is_empty()); + // Said kindly is still a claim (「沒問題」 isn't a 「沒」). + assert_eq!(kinds(&turn(vec![(failed, "找不到")], "沒問題,已傳給你了。", vec![])), vec![Kind::Undone]); + // English claims are read too. + let failed = step("c1", "send_file", r#"{"path":"a.md"}"#, ToolStatus::Failed); + assert_eq!(kinds(&turn(vec![(failed, "找不到")], "I've sent the report.", vec![])), vec![Kind::Undone]); + } + + /// Said a file came with the reply, and the turn put none in the chat. + #[test] + fn a_file_said_sent_with_none_in_the_chat_is_marked() { + assert_eq!(kinds(&turn(vec![], "報告已傳給你,請查收。", vec![])), vec![Kind::NoFile]); + assert_eq!(kinds(&turn(vec![], "已附上 summary.pdf。", vec![])), vec![Kind::NoFile]); + // There is one: fine. + assert!(kinds(&turn(vec![], "報告已傳給你,請查收。", vec!["報告.md"])).is_empty()); + // Sent somewhere else (a phone, mail), said so, or sent before this turn: not about this turn's chat. + let to_phone = step("c1", "send_to_device", r#"{"path":"a.pdf"}"#, ToolStatus::Done); + assert!(kinds(&turn(vec![(to_phone, "已傳到 iPhone")], "檔案已傳給你。", vec![])).is_empty()); + assert!(kinds(&turn(vec![], "檔案已上傳到 Google Drive。", vec![])).is_empty()); + assert!(kinds(&turn(vec![], "檔案剛剛已傳給你了。", vec![])).is_empty()); + let mut earlier = vec![Message::user("傳報告"), Message { attachments: vec![Attachment { name: "a.pdf".into(), ..Default::default() }], ..Message::assistant("好了", "") }]; + let start = earlier.len(); + earlier.extend(turn(vec![], "a.pdf 已傳給你了。", vec![])); + assert!(check(&earlier, start, false).unwrap().1.is_empty()); + // Not about a file: 「已完成」 alone needs a failed step, not a file. + assert!(kinds(&turn(vec![], "已完成,網站更新了。", vec![])).is_empty()); + } + + /// (c): a number the counts don't bear out — marked, never woken. + #[test] + fn a_count_the_steps_dont_bear_out_is_marked() { + let posted = step("c1", "post_to_x", r#"{"text":"早安"}"#, ToolStatus::Done); + let f = check(&turn(vec![(posted.clone(), "已發文")], "已發佈,共送出 2 則。", vec![]), 0, false).unwrap().1; + assert_eq!(f.iter().map(|f| f.kind).collect::>(), vec![Kind::Count]); + assert!(f[0].why.contains("2 則") && f[0].why.contains("1 則"), "{}", f[0].why); + assert!(!Kind::Count.hard() && Kind::Count.shown()); + let again = step("c2", "post_to_x", r#"{"text":"午安"}"#, ToolStatus::Done); + assert!(kinds(&turn(vec![(posted.clone(), "已發文"), (again, "已發文")], "送出兩則了。", vec![])).is_empty()); + // Nothing the counts can see (a connector's mail): no number is held against it. + assert!(kinds(&turn(vec![], "已寄出 3 則通知。", vec![])).is_empty()); + // Files: said three, one came. + assert_eq!(kinds(&turn(vec![], "已傳 3 張圖給你。", vec!["a.png"])), vec![Kind::Count]); + assert!(kinds(&turn(vec![], "已傳 2 張圖給你。", vec!["a.png", "b.png"])).is_empty()); + } + + /// A group chat: only the member who answered — another's failed step isn't its. + #[test] + fn in_a_group_only_the_answering_members_steps_count() { + let failed = step("c1", "send_file", r#"{"path":"a.md"}"#, ToolStatus::Failed); + let mut msgs = vec![Message::user("你們誰傳一下"), Message { author: 7, tool_calls: vec![failed], ..Message::assistant("", "") }, Message::tool_result("c1", "send_file", "找不到"), Message { author: 7, ..Message::assistant("我傳不了。", "") }]; + let sent = step("c2", "send_file", r#"{"path":"a.md"}"#, ToolStatus::Done); + msgs.push(Message { author: 8, tool_calls: vec![sent], ..Message::assistant("", "") }); + msgs.push(Message::tool_result("c2", "send_file", "已放進聊天(附件 a1b2c3)")); + msgs.push(Message { author: 8, attachments: vec![Attachment { name: "a.md".into(), ..Default::default() }], ..Message::assistant("已傳給你了。", "") }); + let (at, flags) = check(&msgs, 0, true).unwrap(); + assert!(at == msgs.len() - 1 && flags.is_empty(), "{flags:?}"); + } + + /// A 支線's report or a colleague's (put in the chat as the bot's after its reply) isn't the + /// reply: the bot's own last words are. + #[test] + fn a_report_put_in_after_the_reply_isnt_the_reply() { + let failed = step("c1", "send_file", r#"{"path":"a.md"}"#, ToolStatus::Failed); + let mut msgs = turn(vec![(failed, "找不到")], "傳不了,找不到 a.md。", vec![]); + msgs.push(Message { branch: 3, ..Message::assistant("支線做完了,已傳給你了 [結果](sandbox:/home/bot/r.md)", "") }); + msgs.push(Message { author: 9, ..Message::assistant("【同事】已完成。", "") }); + let (at, flags) = check(&msgs, 0, false).unwrap(); + assert_eq!(at, msgs.len() - 3); + assert!(flags.is_empty(), "{flags:?}"); + } + + #[test] + fn the_wake_says_only_fixed_words() { + let w = wake_text(&[Kind::DeadLink, Kind::Undone, Kind::DeadLink]); + assert!(w.starts_with(WAKE_TAG) && w.contains("sandbox:") && w.contains("失敗或被擋下") && w.contains("不是使用者說的話"), "{w}"); + assert_eq!(w.matches("同名的附件").count(), 1); + let line = history_line(&[Flag { kind: Kind::FileLink, why: "連結「x」…".into() }]); + assert!(line.contains("不是你寫的") && line.contains("連結「x」"), "{line}"); + } +} diff --git a/src/featuremap.rs b/src/featuremap.rs index 79a3255..5f8b627 100644 --- a/src/featuremap.rs +++ b/src/featuremap.rs @@ -52,6 +52,7 @@ pub const AREAS: &[Area] = &[ area!("box", "Bot 的電腦"), area!("files", "檔案與指令"), area!("deliver", "交出結果:傳檔、打開、發佈網站"), + area!("claims", "完成宣稱檢查"), area!("browser", "瀏覽器"), area!("screen", "螢幕操作"), area!("vault", "保險庫"), diff --git a/src/i18n_table.rs b/src/i18n_table.rs index 84cae88..10b639b 100644 --- a/src/i18n_table.rs +++ b/src/i18n_table.rs @@ -770,4 +770,8 @@ pub const ROWS: &[(&str, &str, &str)] = &[ ("名稱不能空白,沒有改。", "A name can't be empty; it wasn't changed.", "名前は空にできません。変更していません。"), ("已經有叫「{n}」的連接器,名稱沒有改。", "There is already a connector called “{n}”; the name wasn't changed.", "「{n}」というコネクタがすでにあります。名前は変更していません。"), ("常用的連接器,按「加入」就能用。需要金鑰的會打開「新增連接器」並填好,補上金鑰再按「新增」。本機的需要先裝 Node.js(npx)或 uv(uvx)。下面的「公用市集」搜尋官方 MCP Registry 裡用網址連的連接器。", "Common connectors, ready with Add. One that needs a key opens Add connector filled in: add the key and press Add. Local ones need Node.js (npx) or uv (uvx). The public market below searches the official MCP Registry for connectors reached by address.", "よく使うコネクタは「追加」ですぐ使えます。キーが必要なものは「コネクタを追加」を入力済みで開きます。キーを入れて「追加」を押してください。ローカルのものは Node.js(npx)か uv(uvx)が必要です。下の「公開マーケット」は公式 MCP Registry からアドレスで接続するコネクタを検索します。"), + ("未驗證", "Unverified", "未検証"), + ("AnyBot 核對這一輪實際做了什麼,跟這則回覆對不上", "AnyBot checked what this turn really did, and it doesn't match this reply", "AnyBot がこのターンで実際に行われたことを確認したところ、この返信と一致しません"), + ("回覆沒對上", "Reply didn't match", "返信が一致しません"), + ("這個連結指到 Bot 電腦上的位置,這裡打不開;聊天裡也沒有這個檔案。請 Bot 用 send_file 傳過來。", "This link points to a place on the bot's computer and can't open here; the chat has no such file either. Ask the bot to send it with send_file.", "このリンクは Bot のコンピュータ上の場所を指しているため、ここでは開けません。チャットにもこのファイルはありません。Bot に send_file で送ってもらってください。"), ]; diff --git a/src/main.rs b/src/main.rs index db81919..64a680b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -73,6 +73,7 @@ mod tools; mod triggers; mod embed; mod evidence; +mod claims; mod featuremap; mod garden; mod goal; diff --git a/src/model.rs b/src/model.rs index 5f9bbb5..27a9913 100644 --- a/src/model.rs +++ b/src/model.rs @@ -137,6 +137,11 @@ pub struct Message { /// what it found (its report, which the main line reads too). #[serde(default, skip_serializing_if = "is_zero")] pub branch: u64, + /// 完成宣稱關卡 (claims.rs): what AnyBot found when it held this reply up against what its turn + /// really did — a claim the steps don't bear out, a link only the bot's computer can open. + /// Set by AnyBot at the turn's end, never by the model; shown as 「未驗證」 under the reply. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub check: Vec, /// What the model reads after the person's words (送出時間, the memories): made by /// app::group_history from the fields above, never saved. #[serde(skip)] @@ -229,10 +234,11 @@ fn chat_mark(b: &Bot) -> u64 { for r in &m.reactions { r.hash(&mut h); } - // (交付確認: a device's word on a file is kept too.) + // (交付確認: a device's word on a file is kept too; and 完成宣稱關卡's on a reply.) for a in &m.attachments { a.seen.len().hash(&mut h); } + m.check.len().hash(&mut h); }; b.messages.iter().for_each(&mut shape); for (title, msgs) in &b.threads { diff --git a/src/pages.rs b/src/pages.rs index 73e2d2b..278927d 100644 --- a/src/pages.rs +++ b/src/pages.rs @@ -77,17 +77,17 @@ fn one() -> u32 { pub fn specs() -> Vec { vec![ - json!({"name": "write_page", "description": "Make or update a page: a lasting, nicely laid-out document the person can open from the chat and that you keep up to date — a tracker (e.g. 「台灣 Tesla FSD 追蹤」), a report, a comparison, a plan, research notes. Use it whenever the person asks you to track, follow, summarise or compare something they will come back to; then link it in your reply as [標題](page:ID). With an id (or the same title) it replaces that page's content and keeps the old version. Write Markdown: headings, short paragraphs, lists, tables, links to sources, Mermaid charts (```mermaid: pie, xychart-beta bar/line, timeline, gantt, flowchart), and these page blocks:\n```stats\n狀態 | 審查中 | 第 1 步\n預計開放 | 2027 Q2 | 媒體推估\n```\n```steps\n[x] 道路測試計畫審查 | 7/9 月開過兩次會\n[>] 道路測試 | 等交通部核定\n[ ] 正式開放\n```\n```chart\nbar 標題(bar | line | pie 換圖型)\n1月 | 120\n2月 | 320\n```\n```details 指令與原始數據\n(預設收起的 Markdown:證據、長清單、指令)\n```\n多系列:首行 `| 1月 | 2月`(第一格留空),每列 `名稱 | 120 | 320`。圖表用原生繪製(可縮放、hover 看數值,下方自動附數據表),優於 ```mermaid 的圖片。排版由渲染器接手:長條圖自動由大到小排序(月份/年份等自有順序的標籤不排);單系列把數字直接標在圖上、不畫 y 軸;多條線在線尾標系列名——你只要把圖標題寫成結論。\n> [!NOTE] / [!TIP] / [!WARNING] / [!IMPORTANT] call-outs.\n\n寫法(Anthropic 的報告寫法:讀者先掃一眼,需要才往下讀):\n• 選 kind(data 數據分析 / compare 比較評測 / decision 決策備忘 / howto 教學步驟 / timeline 時間線 / prose 純敘述 / notes 筆記),第一屏跟著它:data → 一句結論+kpis 三個真數字+主圖表;compare → 一句取捨+verdict+對比表;decision → verdict 先講+三個理由+風險;howto → 適合誰+steps;timeline → mermaid timeline;prose/notes → 直接內文,不硬湊 KPI 卡。kpis 只放算得出的真數字(附 delta 如 +12%),verdict 只在有明確結論時寫。\n• 每一節的標題就是結論(「240 環境是測試場」,不是「240 環境的現實」),下面第一句補一個理由,再最多三點清單。\n• 數字放 ```stats 或表格,不塞在句子和括號裡;有趨勢或比較就出 ```chart,圖標題寫結論並帶數字,軸標籤帶單位。\n• 粗體一節最多一處(或不用);不用「→」帶結論、不用分隔線(---)、標題不編號(一、二、1.)——標題本身就是分段。\n• 待辦寫成 ```steps 勾選清單;指令放程式碼區塊,不放進表格。\n• 證據、長清單、指令、原始數據放進 ```details 標題(預設收起);第一屏只留結論、數字和下一步。\n• 句子短、主動語氣、用讀者的話(說「通知」不說「webhook 設定」);不寫「值得注意的是」這類套話。\n• 來源放最後,帶連結與日期。更新時把整頁維持成現況(不是日誌),並在 `note` 寫出改了什麼。\n• 存檔時會自動檢查寫法:被退回就照列出的地方改,用同樣的標題再送一次。", + json!({"name": "write_page", "description": "Make or update a page: a lasting, nicely laid-out document the person can open from the chat and that you keep up to date — a tracker (e.g. 「台灣 Tesla FSD 追蹤」), a report, a comparison, a plan, research notes. Use it whenever the person asks you to track, follow, summarise or compare something they will come back to; then link it in your reply as [標題](page:ID). With an id (or the same title) it replaces that page's content and keeps the old version; with an id and no content, only the other fields you send (title, summary, note, kind, kpis, verdict) change. Write Markdown: headings, short paragraphs, lists, tables, links to sources, Mermaid charts (```mermaid: pie, xychart-beta bar/line, timeline, gantt, flowchart), and these page blocks:\n```stats\n狀態 | 審查中 | 第 1 步\n預計開放 | 2027 Q2 | 媒體推估\n```\n```steps\n[x] 道路測試計畫審查 | 7/9 月開過兩次會\n[>] 道路測試 | 等交通部核定\n[ ] 正式開放\n```\n```chart\nbar 標題(bar | line | pie 換圖型)\n1月 | 120\n2月 | 320\n```\n```details 指令與原始數據\n(預設收起的 Markdown:證據、長清單、指令)\n```\n多系列:首行 `| 1月 | 2月`(第一格留空),每列 `名稱 | 120 | 320`。圖表用原生繪製(可縮放、hover 看數值,下方自動附數據表),優於 ```mermaid 的圖片。排版由渲染器接手:長條圖自動由大到小排序(月份/年份等自有順序的標籤不排);單系列把數字直接標在圖上、不畫 y 軸;多條線在線尾標系列名——你只要把圖標題寫成結論。\n> [!NOTE] / [!TIP] / [!WARNING] / [!IMPORTANT] call-outs.\n\n寫法(Anthropic 的報告寫法:讀者先掃一眼,需要才往下讀):\n• 選 kind(data 數據分析 / compare 比較評測 / decision 決策備忘 / howto 教學步驟 / timeline 時間線 / prose 純敘述 / notes 筆記),第一屏跟著它:data → 一句結論+kpis 三個真數字+主圖表;compare → 一句取捨+verdict+對比表;decision → verdict 先講+三個理由+風險;howto → 適合誰+steps;timeline → mermaid timeline;prose/notes → 直接內文,不硬湊 KPI 卡。kpis 只放算得出的真數字(附 delta 如 +12%),verdict 只在有明確結論時寫。\n• 每一節的標題就是結論(「240 環境是測試場」,不是「240 環境的現實」),下面第一句補一個理由,再最多三點清單。\n• 數字放 ```stats 或表格,不塞在句子和括號裡;有趨勢或比較就出 ```chart,圖標題寫結論並帶數字,軸標籤帶單位。\n• 粗體一節最多一處(或不用);不用「→」帶結論、不用分隔線(---)、標題不編號(一、二、1.)——標題本身就是分段。\n• 待辦寫成 ```steps 勾選清單;指令放程式碼區塊,不放進表格。\n• 證據、長清單、指令、原始數據放進 ```details 標題(預設收起);第一屏只留結論、數字和下一步。\n• 句子短、主動語氣、用讀者的話(說「通知」不說「webhook 設定」);不寫「值得注意的是」這類套話。\n• 來源放最後,帶連結與日期。更新時把整頁維持成現況(不是日誌),並在 `note` 寫出改了什麼。\n• 存檔時會自動檢查寫法:被退回就照列出的地方改,用同樣的 id 或標題、帶整頁 content 再送一次(第二次一定存)。", "parameters": {"type": "object", "properties": { "title": {"type": "string", "description": "Short title, e.g. 台灣 Tesla FSD 追蹤"}, - "content": {"type": "string", "description": "The whole page in Markdown (without the title)"}, + "content": {"type": "string", "description": "The whole page in Markdown (without the title). Leave it out only to change the other fields of an existing page (with its id)."}, "summary": {"type": "string", "description": "One line for the card: the current state in a few words"}, "note": {"type": "string", "description": "When updating: what changed, in one short sentence"}, "kind": {"type": "string", "enum": ["data", "compare", "decision", "howto", "timeline", "prose", "notes"], "description": "What kind of document this is; it decides the first screen. Omit for a plain page."}, "kpis": {"type": "array", "description": "Only for data pages: the 2-4 real numbers a reader must see first (never invented, never placeholders).", "items": {"type": "object", "properties": {"label": {"type": "string"}, "value": {"type": "string"}, "delta": {"type": "string", "description": "Change, e.g. +12% / -3 天 (empty when none)"}}, "required": ["label", "value"]}}, "verdict": {"type": "string", "description": "One-line conclusion, for decision/compare pages (rendered as a card before the text)"}, "id": {"type": "integer", "description": "The page to update (from list_pages or an earlier write_page)"}}, - "required": ["title", "content"]}}), + "required": ["title"]}}), json!({"name": "read_page", "description": "Read a page (its Markdown): one of yours before updating it, or another bot's to use what it already found (theirs you can read, not change).", "parameters": {"type": "object", "properties": {"id": {"type": "integer"}, "title": {"type": "string"}}}}), json!({"name": "list_pages", "description": "List the pages you made, then the other bots' pages you can read (id, title, whose, last update). Look here before researching something a colleague may already track.", "parameters": {"type": "object", "properties": {}}}), ] @@ -144,28 +144,37 @@ pub struct Written { pub text: String, } -/// write_page: make a page, or replace one (by id, or the same title from this bot). +/// Which page a write_page call is about, for the 寫法檢查's 「the second try is saved」: its id +/// (given, or this bot's page of that title), else its title (a page not made yet). A try that +/// names the page by id and one by its title are the same page. +pub fn write_key(pages: &[Page], bot: u64, args: &Value) -> String { + let title = args["title"].as_str().unwrap_or(""); + match find(pages, bot, args["id"].as_u64(), title) { + Some(p) => format!("#{}", p.id), + None => format!("「{}」", title.chars().filter(|c| !c.is_whitespace()).collect::().to_lowercase()), + } +} + +/// write_page: make a page, or replace one (by id, or the same title from this bot). With no +/// content, a page of this bot's (by id or title) has only the other fields sent changed — a bot +/// sends the content, then the kind, summary, verdict on their own, and that used to come back +/// 「頁面內容是空的」. pub fn write(pages: &mut Vec, next_id: &mut u64, bot: u64, args: &Value, now: i64) -> Result { let title: String = args["title"].as_str().unwrap_or("").trim().chars().take(MAX_TITLE).collect(); let body = args["content"].as_str().unwrap_or("").trim().to_string(); let summary: String = args["summary"].as_str().unwrap_or("").trim().chars().take(200).collect(); let note: String = args["note"].as_str().unwrap_or("").trim().chars().take(300).collect(); - if title.is_empty() { - return Err("頁面要有標題".into()); - } if body.is_empty() { - return Err("頁面內容是空的".into()); + return update_fields(pages, bot, args, now); + } + if title.is_empty() && args["id"].as_u64().is_none() { + return Err("頁面要有標題".into()); } if body.len() > MAX_BODY { return Err(format!("頁面太長了(最多 {} 字)。請精簡,或拆成幾頁。", MAX_BODY)); } let id = args["id"].as_u64(); - // 結構由內容決定:kind 決定第一屏怎麼排,kpis/verdict 有真資料才填、有才渲染。 - const KINDS: [&str; 7] = ["data", "compare", "decision", "howto", "timeline", "prose", "notes"]; - let kind: String = args["kind"].as_str().unwrap_or("").trim().to_lowercase().chars().take(12).collect(); - let kind = if KINDS.contains(&kind.as_str()) { kind } else { String::new() }; - let kpis: Vec = args["kpis"].as_array().map(|a| a.iter().filter_map(|k| Some(Kpi { label: k["label"].as_str()?.trim().chars().take(40).collect(), value: k["value"].as_str()?.trim().chars().take(40).collect(), delta: k["delta"].as_str().unwrap_or("").trim().chars().take(20).collect() })).take(4).collect()).unwrap_or_default(); - let verdict: String = args["verdict"].as_str().unwrap_or("").trim().chars().take(300).collect(); + let (kind, kpis, verdict) = shape_of(args); let existing = find(pages, bot, id, &title).map(|p| p.id); if id.is_some() && existing.is_none() { return Err(format!("找不到頁面 #{}。用 list_pages 看有哪些頁面,或不帶 id 建立新的。", id.unwrap_or(0))); @@ -176,6 +185,8 @@ pub fn write(pages: &mut Vec, next_id: &mut u64, bot: u64, args: &Value, n if p.bot != bot { return Err("這是別的 Bot 的頁面,不能改".into()); } + // (Updated by id with no title: it keeps its title.) + let title = if title.is_empty() { p.title.clone() } else { title }; if p.body == body && p.title == title && (summary.is_empty() || p.summary == summary) && (kind.is_empty() || p.kind == kind) && (kpis.is_empty() || p.kpis == kpis) && (verdict.is_empty() || p.verdict == verdict) { return Ok(Written { id: pid, text: format!("頁面「{}」內容沒有變化,沒有更新。連結:[{}](page:{})", p.title, p.title, pid) }); } @@ -213,6 +224,69 @@ pub fn write(pages: &mut Vec, next_id: &mut u64, bot: u64, args: &Value, n } } +/// The page's shape as sent: its kind, KPI numbers and verdict (empty: not sent). +fn shape_of(args: &Value) -> (String, Vec, String) { + // 結構由內容決定:kind 決定第一屏怎麼排,kpis/verdict 有真資料才填、有才渲染。 + const KINDS: [&str; 7] = ["data", "compare", "decision", "howto", "timeline", "prose", "notes"]; + let kind: String = args["kind"].as_str().unwrap_or("").trim().to_lowercase().chars().take(12).collect(); + let kind = if KINDS.contains(&kind.as_str()) { kind } else { String::new() }; + let kpis: Vec = args["kpis"].as_array().map(|a| a.iter().filter_map(|k| Some(Kpi { label: k["label"].as_str()?.trim().chars().take(40).collect(), value: k["value"].as_str()?.trim().chars().take(40).collect(), delta: k["delta"].as_str().unwrap_or("").trim().chars().take(20).collect() })).take(4).collect()).unwrap_or_default(); + let verdict: String = args["verdict"].as_str().unwrap_or("").trim().chars().take(300).collect(); + (kind, kpis, verdict) +} + +/// write_page with no content: the fields sent (title, summary, note, kind, kpis, verdict) of a +/// page of this bot's change; its content and versions stay as they are. +fn update_fields(pages: &mut [Page], bot: u64, args: &Value, now: i64) -> Result { + let title: String = args["title"].as_str().unwrap_or("").trim().chars().take(MAX_TITLE).collect(); + let summary: String = args["summary"].as_str().unwrap_or("").trim().chars().take(200).collect(); + let note: String = args["note"].as_str().unwrap_or("").trim().chars().take(300).collect(); + let (kind, kpis, verdict) = shape_of(args); + let id = args["id"].as_u64(); + let Some(pid) = find(pages, bot, id, &title).map(|p| p.id) else { + return Err(match id { + Some(i) => format!("找不到頁面 #{i}。用 list_pages 看有哪些頁面,或不帶 id 建立新的。"), + None if title.is_empty() => "頁面要有標題和內容".into(), + None => "頁面內容是空的".into(), + }); + }; + let p = pages.iter_mut().find(|p| p.id == pid).unwrap(); + let mut changed: Vec<&str> = vec![]; + if !title.is_empty() && title != p.title { + p.title = title; + changed.push("標題"); + } + if !summary.is_empty() && summary != p.summary { + p.summary = summary; + changed.push("摘要"); + } + if !note.is_empty() && note != p.note { + p.note = note; + changed.push("更新說明"); + } + if !kind.is_empty() && kind != p.kind { + p.kind = kind; + changed.push("種類"); + } + if !kpis.is_empty() && kpis != p.kpis { + p.kpis = kpis; + changed.push("數字卡"); + } + if !verdict.is_empty() && verdict != p.verdict { + p.verdict = verdict; + changed.push("結論"); + } + if changed.is_empty() { + // (Nothing at all sent to change: said as the mistake it is.) + if !["summary", "note", "kind", "kpis", "verdict"].iter().any(|k| !args[*k].is_null()) && args["title"].as_str().is_none_or(|t| t.trim().is_empty()) { + return Err(format!("頁面內容是空的,也沒有要改的欄位:要換內容就帶 content(整頁),只改其他的就帶 title、summary、note、kind、kpis 或 verdict。頁面「{}」沒有動。", p.title)); + } + return Ok(Written { id: pid, text: format!("頁面「{}」沒有變化,沒有更新。連結:[{}](page:{pid})", p.title, p.title) }); + } + p.updated = now; + Ok(Written { id: pid, text: format!("已更新頁面「{}」的{}(內容沒動,還是第 {} 版)。在回答裡用 [{}](page:{pid}) 連到它。", p.title, changed.join("、"), p.revision, p.title) }) +} + /// read_page: its own first; then another bot's (同事的頁面, to read — what a colleague already /// tracks needn't be looked up again). `name` gives a bot's name. pub fn read(pages: &[Page], bot: u64, args: &Value, name: impl Fn(u64) -> String) -> Result { diff --git a/src/remote.rs b/src/remote.rs index 7d04c15..b82f63b 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -451,7 +451,7 @@ pub fn message_json(m: &crate::model::Message, names: &HashMap, pag } }) .collect(); - Some(json!({ + let mut v = json!({ "role": match m.role { Role::User => "user", _ => "assistant" }, "text": m.text, "via": m.via, @@ -466,7 +466,13 @@ pub fn message_json(m: &crate::model::Message, names: &HashMap, pag "at": m.at, "tools": calls, "memories": m.memories, - })) + }); + // 完成宣稱關卡: what makes the reply 「未驗證」 (only on a reply that has one). + let check: Vec = m.check.iter().filter(|f| f.kind.shown()).map(|f| json!({"kind": f.kind, "why": f.why})).collect(); + if !check.is_empty() { + v["check"] = json!(check); + } + Some(v) } /// A file in a message, for the phone. One the bot handed over (`by_bot`) also carries its id @@ -3600,6 +3606,21 @@ mod tests { assert!(!LOOSEN_REFUSED.contains("加密") && LOOSEN_REFUSED.contains("只能收緊、不能放寬")); } + /// 完成宣稱關卡 on the phone: a reply's 「未驗證」 and why; a link to a file in the chat (opened + /// there instead) isn't shown; a reply with nothing found has no `check` at all. + #[test] + fn the_phone_gets_what_made_a_reply_unverified() { + use crate::claims::{Flag, Kind}; + let names = HashMap::new(); + let plain = crate::model::Message::assistant("好了", ""); + assert!(message_json(&plain, &names, &[], &[]).unwrap().get("check").is_none()); + let m = crate::model::Message { check: vec![Flag { kind: Kind::DeadLink, why: "連結「下載」打不開".into() }, Flag { kind: Kind::FileLink, why: "改開附件".into() }], ..plain.clone() }; + let v = message_json(&m, &names, &[], &[]).unwrap(); + assert_eq!(v["check"], json!([{"kind": "dead_link", "why": "連結「下載」打不開"}])); + let only_file = crate::model::Message { check: vec![Flag { kind: Kind::FileLink, why: "改開附件".into() }], ..plain }; + assert!(message_json(&only_file, &names, &[], &[]).unwrap().get("check").is_none()); + } + /// 交付確認 from a phone: a teammate may tell it too; the page's words never reach the bot as /// they are (the device from a short list, the reason a code); the bot's file carries its id /// and how it stands, the person's own file nothing new.