diff --git a/FEATURES.md b/FEATURES.md index 9259e8a..56f6635 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -805,6 +805,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 - 操作螢幕和讀你自己的瀏覽器:一律在「你的電腦」。 - 其他工具:用 Bot 指定的電腦,沒指定就用預設電腦。 - 指定的電腦不存在:「沒有「{名稱}」這台電腦。可以用:…」 + - 你在 Bot 設定選了別台當「做事的電腦」(不是 Bot 自己的電腦):瀏覽器和螢幕步驟只在那台做。那台開不了瀏覽器(沒裝 Chrome/Brave…、用 SSH 連的)或沒有螢幕時,那一步停下來告訴 Bot 為什麼、要它先問你,不會改開在你自己的 Mac 上;Bot 自己指名你的 Mac 也一樣拉回選的那台。你在訊息裡指名哪一台(「用我的電腦開」)就照做。沒選過時(用 Bot 自己的電腦),它沒有螢幕或瀏覽器還是可以借你的。 2. **直接操作有開時**:第 3 步和第 5 步自動算已開。 3. **關卡一:電腦工具還沒開** - 詢問:「讓 {Bot} 使用電腦工具:{動作}\n(在 {電腦} 上)」 @@ -1252,7 +1253,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 ## 24. 操作螢幕(滑鼠、鍵盤、截圖) -- 有螢幕的電腦:Bot 自己的電腦(Linux 桌面,Docker)、這台電腦、帳號裡其他開了「裝置連結」的電腦。每個螢幕工具都有 `computer` 參數;沒指定時用 Bot 的預設電腦。 +- 有螢幕的電腦:Bot 自己的電腦(Linux 桌面,Docker)、這台電腦、帳號裡其他開了「裝置連結」的電腦。每個螢幕工具都有 `computer` 參數;沒指定時用 Bot 的預設電腦(你選的那台沒有螢幕時停下來說,不換到別台的螢幕)。 - **看:截圖上每個能點的東西都框起來、標了編號。** Bot 拿到的截圖上,每個按鈕、連結、輸入框、選單項目都有編號,另外附同樣編號的清單(例如「[21] 連結「Profile」」)。編號來自系統的無障礙資訊(Mac 的 AX、Linux 的 AT-SPI;Bot 的電腦裡網頁內容也有,Chromium 開了無障礙),所以網頁上的小圖示也有編號。只有被別的視窗擋住的按鈕不給編號(Mac 上逐一檢查最上層的視窗是不是同一個 App),免得點到別的 App。 - Linux 上用前景視窗所屬程式的執行檔名稱去找 App(agent-desktop 認的是這個):Snap 版 Firefox 的視窗類別是「firefox_firefox」,程式是「firefox」,以前因此找不到、只剩一張沒有編號的截圖。 - Linux 上一個編號都沒有、而且桌面的無障礙開關(AT-SPI 的 IsEnabled)是關著時,AnyBot 會把它打開(跟螢幕閱讀器一樣),並告訴 Bot:「這台的無障礙介面原本是關著的,AnyBot 剛把它打開:之後打開的 App 才會有編號,已經開著的 App 要關掉重開。網頁請改用 browser_* 工具。」 @@ -1566,8 +1567,8 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) ### 頁面(Bot 做、Bot 持續更新的報告) -- 你請 Bot 追蹤、整理、比較一件之後還會回來看的事(例如「幫我追蹤一下台灣 FSD 狀況」),它用 `write_page` 做成一頁:先寫現況,再寫細節和來源(附日期)。回答裡用「[標題](page:ID)」連到它,回答下面出現頁面卡片(一張精簡卡:頁面圖示、標題、一行它說什麼或這次改了什麼、一行灰字的種類和時間),點一下打開。 -- 頁面可以放表格、Mermaid 圖表(圓餅、長條、折線、時間軸…白底卡節點、細灰連線),以及頁面專用的區塊:```stats 數字卡片(數字大字,超過 10 個字的值縮成小一號;值和備註開頭 ↑/+ 綠色、↓/−/- 紅色,「+」「-」後面要緊接著東西才算,單獨一個「-」當作沒資料;電腦和手機同一套規則)、```steps 進度(✓ 完成、◉ 進行中、○ 還沒到)、```chart 原生圖表(bar 長條、line 折線、pie 圓餅;只畫淡水平參考線,長條自動由大到小排序——月份/年份等自有順序的標籤不排;單系列把數字直接標在圖上、不畫 y 軸;多條線在線尾標系列名;懸停看數值、拖曳平移、右鍵框選放大、雙擊還原,圖下自動附數據表,不會破版;多系列用 `| 1月 | 2月` 當表頭;第一行可以是「圖型 標題」、只寫圖型(bar/line/pie 或 長條/折線/圓餅)或只寫標題,`#` 開頭的行是註解,`|---|` 分隔列略過,少填的格子當 0——電腦和手機同一套讀法;手機看同一頁也畫同樣樣式的原生 SVG 圖:照手機寬度畫、字不會縮小,折線和多系列長條有 y 軸數字,圖下同樣附數據表,只有一項的圓餅畫成整圓,圖例項目再多也都畫得到,負數的數字不會壓到下面的標籤)、`> [!NOTE]`/`[!TIP]`/`[!WARNING]`/`[!IMPORTANT]` 提示框。這些區塊在聊天裡也能用。所有圖表(含 Mermaid 圓餅)共用同一套低飽和六色色板,深淺兩主題各一組。 +- 你請 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 字、一節超過一處粗體、括號裡一串數字、標題編號、分隔線、用「→」帶結論、表格裡放指令、正文很長卻沒有收起的細節——有就退回一次、列出每一處要怎麼改;同一頁第二次照存,不會卡住。 - 頁面是「閱讀排版」:內文排在置中的 720 像素欄位裡,行高 1.55 倍、段落有呼吸空間,不會貼著視窗邊緣;聊天室保持原本的緊湊排版。頁面上的數字表格(2–3 欄、資料不超過 8 列)在寬度夠時會自動左表右圖併排。 diff --git a/docs/feature-map/browser.md b/docs/feature-map/browser.md index de763ad..975add5 100644 --- a/docs/feature-map/browser.md +++ b/docs/feature-map/browser.md @@ -28,6 +28,7 @@ Bot 用 AnyBot 自己的瀏覽器上網、登入網站、點按、打字、送 - 別人傳來的訊息(訊息管道、團隊成員)那一輪不能用 AnyBot 瀏覽器、保險庫和 `sent`:瀏覽器帶著使用者的登入。公開網頁用 `web_fetch`。 - 同一個網站在不同電腦、不同設定檔的登入不共用;沒帶 `profile` 會用到別的設定檔。 +- 使用者選了「做事的電腦」而那台開不了瀏覽器(沒裝 Chrome/Brave…、SSH):瀏覽器步驟回「使用者選的電腦「…」現在開不了 AnyBot 的瀏覽器」,不會開在使用者自己的 Mac 上。公開網頁改用 `web_fetch`,其他的先問使用者。 - 使用者自己的 Firefox 設定檔,如果他已經用平常的方式開著,要先請他關掉那個視窗,AnyBot 才開得起來。 - 一模一樣的按鈕(例如每篇貼文都有的「回覆」)在清單裡只列一次;要點第二篇的,先 `open` 那篇貼文的網址再點。 - 下拉選單用 `select`,`option` 填選項上看得到的字(給 `value` 也行,對下拉選單 `type` 也會改成選選項);什麼都沒給會報錯。 diff --git a/docs/feature-map/computers.md b/docs/feature-map/computers.md index 58f2ad6..590aa17 100644 --- a/docs/feature-map/computers.md +++ b/docs/feature-map/computers.md @@ -9,7 +9,7 @@ - 這台電腦(AnyBot 開著的這台,名字可以改):從 Bot 的「起始資料夾」開始。大腦放在伺服器上時,伺服器本身不在清單裡。 - SSH 電腦:自己加的,一個名稱加一個位址(例如 me@studio.local)。 - 帳號裡的其他電腦:登入同一個帳號、打開「讓帳號裡的其他電腦使用這台」、而且現在在線上的 AnyBot(螢幕電腦、手腳電腦),經過帳號伺服器操作檔案、指令、瀏覽器、看畫面和點擊。 -- 預設電腦:沒選就在 Bot 自己的電腦上做;使用者在 Bot 設定選了別台,或在訊息裡指名別台,才換過去。 +- 預設電腦:沒選就在 Bot 自己的電腦上做;使用者在 Bot 設定選了別台,或在訊息裡指名別台,才換過去。選了別台之後,瀏覽器和螢幕步驟只在那台做:那台開不了瀏覽器或沒有螢幕,那一步失敗並說為什麼(要 Bot 先問使用者),不會改開在使用者自己的 Mac;Bot 自己指名別台也拉回選的那台,除非使用者在訊息裡指名。 - 可以用的電腦:每個 Bot 勾自己能用哪幾台,它自己的電腦一定可以;沒勾的看不到也不能用。同事名冊會寫每個 Bot 在哪幾台做事。 - 「在這台電腦上執行」:一律允許/每次詢問(預設)/永不允許。只有使用者能打開,Bot 不能自己開。 - 傳到別的裝置:Bot 用 `send_to_device` 把檔案送到帳號裡另一台電腦(放進「下載/AnyBot」並跳通知)或手機;對方沒開機時大腦先收著,7 天內一上線就送到。使用者自己傳用「傳送到其他裝置」。 diff --git a/docs/feature-map/pages.md b/docs/feature-map/pages.md index b74a137..99b3edd 100644 --- a/docs/feature-map/pages.md +++ b/docs/feature-map/pages.md @@ -4,7 +4,7 @@ Bot 把要追蹤、整理、比較的事寫成一頁,之後一直更新同一 ## 子功能 -- 寫頁面:標題和整頁 Markdown(標題、表格、連結、Mermaid 圖),加上頁面區塊:```details 標題(預設收起的一段 Markdown,「▸ 標題」點了才展開;放證據、長清單、指令,電腦和手機都是)、```stats 數字卡(數字大字顯示;值和備註開頭是 ↑/+ 綠色、↓/−/- 紅色,+ − - 後面要緊接著字才算,單獨一個「-」是沒資料、不上色;電腦和手機同一條規則)、```steps 進度([x] 完成、[>] 進行中、[ ] 還沒到)、```chart 圖表(bar/line/pie,可以多系列;長條圖自動由大到小排序,月份/年份等自有順序的標籤不排;單系列把數字直接標在圖上不畫 y 軸;多條線在線尾標系列名;圖下附數據表;第一行可以是「圖型 標題」、只寫圖型(bar/line/pie 或 長條/折線/圓餅)或只寫標題,`#` 開頭是註解,`|---|` 分隔列略過,少填的格子當 0;手機也畫原生圖,讀法和樣式相同:照手機寬度畫、字不縮小,折線和多系列長條有 y 軸數字,只有一項的圓餅是整圓,圖例再多項都畫得到)、`> [!NOTE]`/`[!TIP]`/`[!WARNING]`/`[!IMPORTANT]` 提示框。 +- 寫頁面:標題和整頁 Markdown(標題、表格、連結、Mermaid 圖),加上頁面區塊:```details 標題(預設收起的一段 Markdown,「▸ 標題」點了才展開;放證據、長清單、指令,電腦和手機都是)、```stats 數字卡(數字大字顯示;值和備註開頭是 ↑/+ 綠色、↓/−/- 紅色,+ − - 後面要緊接著字才算,單獨一個「-」是沒資料、不上色;電腦和手機同一條規則)、```steps 進度([x] 完成、[>] 進行中、[ ] 還沒到)、```chart 圖表(bar/line/pie,可以多系列;長條圖自動由大到小排序,月份/年份等自有順序的標籤不排;單系列把數字直接標在圖上不畫 y 軸;多條線在線尾標系列名;長條的 y 軸一定從 0 開始,折線離 0 很遠(最小值比資料的高低差還大,例如 1,649–1,796)時照資料範圍畫、不從 0 開始;圖下附數據表(名稱靠左、數字靠右、每欄只有內容那麼寬,太寬就左右捲動,不會把頁面撐寬;超過 6 列時收成「▸ 數據 · N 筆」,點了展開);第一行可以是「圖型 標題」、只寫圖型(bar/line/pie 或 長條/折線/圓餅)或只寫標題,`#` 開頭是註解,`|---|` 分隔列略過,少填的格子當 0;手機也畫原生圖,讀法和樣式相同:照手機寬度畫、字不縮小,折線和多系列長條有 y 軸數字,只有一項的圓餅是整圓,圖例再多項都畫得到)、`> [!NOTE]`/`[!TIP]`/`[!WARNING]`/`[!IMPORTANT]` 提示框。 - 寫法檢查(Anthropic 的報告寫法):Bot 用 write_page 存頁面時先檢查——段落超過 120 字、一節超過一處粗體、括號裡一串數字、標題編號(一、二、1.)、分隔線、用「→」帶結論、表格裡放指令、正文超過 1800 字卻沒有 ```details——有就退回一次並列出要改的地方,同樣的標題第二次照存(不會卡住)。程式碼、```stats、```details 等區塊裡面不檢查。 - 種類(kind):data 數據分析、compare 比較評測、decision 決策備忘、howto 教學步驟、timeline 時間線、prose 長文、notes 筆記。種類決定第一屏:data 頁上面放 2–4 個 KPI 數字(kpis),compare/decision 頁先給一行「結論」(verdict)。沒給種類就是一般頁面。 - 更新:帶 id(或同一個標題)就換掉內容,上一版留著,最多留 10 版;note 寫這次改了什麼,頁面上顯示「這一版更新了:…」。內容一模一樣就不更新。 @@ -14,7 +14,7 @@ Bot 把要追蹤、整理、比較的事寫成一頁,之後一直更新同一 ## 使用者怎麼到 -- 回覆裡的 [標題](page:ID) 連結,和回覆下面的頁面卡片(一張精簡卡:頁面圖示、標題一次、一行它說什麼——更新過的是「已更新:改了什麼」,否則是現況那句——和一行灰字「種類 · 頁面 · 時間 · 第 N 版」):點一下打開。 +- 回覆裡的 [標題](page:ID) 連結,和回覆下面的頁面卡片(一張精簡卡:頁面圖示、標題一次、一行它說什麼——更新過的是「已更新:改了什麼」,否則是現況那句——和一行灰字「種類 · 頁面 · 時間 · 第 N 版」):點一下打開。一個回覆裡每一頁只出一張卡,在最後存那一頁的步驟下面(被寫法檢查退回再存、或存了又更新,都不會重複);沒存成的(別的 Bot 的頁面被擋、被退回那一次)不出卡。手機一樣。 - 右側面板的「資料庫」分頁,最上面的「頁面」:這個 Bot 的頁面,最近改過的在前面。 - 打開的頁面像一份文件(和手機同一套):標題宋體粗體 28,下面一行小字作者、「更新於」、第幾版和「這一版更新了:…」;一行現況(summary)是開頭段落、不加框;結論(verdict)是淡底的「結論」提示框;kpis 是只有細框的數字卡。有 3 個以上的標題時有一行「▸ 目錄 · N 節」,點開才是標題清單和小搜尋框(⌘F 直接展開)。內文宋體 16、行距 1.7,閱讀欄最寬 680。下方左邊「版本紀錄」(看舊版時有「回到最新版」)和「刪除」(按兩次),右邊「複製」(Markdown)、「存成檔案」(存成 .md 到「下載」)、「完成」。 - 手機:首頁上面一排的「頁面」列出所有頁面;聊天裡的頁面卡片;打開的頁面的「⋯」有「複製 Markdown」「其他版本」,一條細線下面才是「刪除頁面」。 @@ -23,7 +23,7 @@ Bot 把要追蹤、整理、比較的事寫成一頁,之後一直更新同一 ## 怎麼操作 - 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「幫我追蹤某件事,整理成一頁」,回覆下面要出現頁面卡片,右側面板 資料庫 › 頁面 要列出它;再請它更新,卡片寫「已更新」,打開頁面的「版本紀錄」有上一版。請另一個 Bot 改這一頁,要被擋下並說是誰的頁面。頁裡的 ```chart:長條要按大小排序(月份圖不排)、單系列數字在條上;手機同頁看同一張圖要是同一套樣式——字跟內文差不多大、折線有 y 軸數字、圖下有數據表、只寫 `pie` 當第一行也畫得出來、只有一項的圓餅是整圓。手機打開有 3 個以上標題的頁面,標題下面要有收起來的「目錄 · N 節」一行,點開點一個標題會捲過去;內文是宋體、表格沒有直線。自動測試:`cargo test pages::`、`cargo test appctl::`。 +- 驗證:請 Bot「幫我追蹤某件事,整理成一頁」,回覆下面要出現頁面卡片,右側面板 資料庫 › 頁面 要列出它;再請它更新,卡片寫「已更新」,打開頁面的「版本紀錄」有上一版;同一個回覆裡就算寫了好幾次(被退回再存),下面也只有一張卡。請另一個 Bot 改這一頁,要被擋下並說是誰的頁面。頁裡的 ```chart:長條要按大小排序(月份圖不排)、單系列數字在條上;手機同頁看同一張圖要是同一套樣式——字跟內文差不多大、折線有 y 軸數字、圖下有數據表(24 筆的折線收成「▸ 數據 · 24 筆」)、一條在 1,700 上下的折線看得出起伏(y 軸不從 0 開始)、深色模式下打開頁面視窗不會超出畫面、只寫 `pie` 當第一行也畫得出來、只有一項的圓餅是整圓。手機打開有 3 個以上標題的頁面,標題下面要有收起來的「目錄 · N 節」一行,點開點一個標題會捲過去;內文是宋體、表格沒有直線。自動測試:`cargo test pages::`、`cargo test appctl::`。 ## 陷阱 diff --git a/mobile/index.html b/mobile/index.html index f09cb1a..f0b0a49 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -2786,6 +2786,16 @@ function chartTicks(lo, hi) { for (let k = Math.floor(lo / step + 1e-9); k <= Math.ceil(hi / step - 1e-9) && out.length < 12; k++) out.push(+(k * step).toPrecision(12)); return out.length >= 2 && isFinite(step) ? out : [lo, hi]; } +// Whether the value axis starts at 0 (src/pages.rs chart_from_zero): bars always; a line only when 0 +// is within reach of its data (its lowest value is 0 or less, or no bigger than its spread) — a +// reading of 1,649–1,796 W drawn from 0 was a flat line pressed against the top. +function chartFromZero(c) { + if (c.kind !== "line") return true; + const all = c.series.flatMap((s) => s[1]).filter((v) => isFinite(v)); + if (!all.length) return true; + const lo = Math.min(...all), hi = Math.max(...all); + return lo <= 0 || lo <= hi - lo; +} // Bar and line. function chartPlot(c, W) { const FS = 12, line = c.kind === "line", single = c.series.length === 1, labelBars = single && !line; @@ -2798,7 +2808,9 @@ function chartPlot(c, W) { order.sort((a, b) => tot(b) - tot(a) || a - b); } const all = c.series.flatMap((s) => s[1]); - const vmin = Math.min(0, ...all), vmax = Math.max(0, ...all); + // Bars from 0; a line far from 0 fits its data (chartFromZero). + const z = chartFromZero(c) ? [0] : []; + const vmin = Math.min(...z, ...all), vmax = Math.max(...z, ...all); const ticks = chartTicks(vmin, vmax), lo = ticks[0], hi = ticks[ticks.length - 1]; // The value axis on the left — except a single series of bars, which carries its own numbers. const L = labelBars ? 4 : Math.ceil(Math.max(...ticks.map((t) => chartTextW(chartNum(t), FS)))) + 10; @@ -2915,8 +2927,11 @@ function chartTable(c) { const total = Math.max(1e-9, vals.reduce((a, b) => a + b, 0)); const cols = pie ? ["項目", "數值", "佔比"] : one ? ["項目", c.series[0][0].trim() || "數值"] : ["項目", ...c.series.map((s) => s[0])]; const cell = (i, ci) => pie && ci === 2 ? Math.round(vals[i] / total * 100) + "%" : chartNum(pie || one ? vals[i] : c.series[ci - 1][1][i]); - return `
${cols.map((h) => ``).join("")}${labels.map((l, i) => `${cols.slice(1).map((_, k) => ``).join("")}`).join("")}
${esc(h)}
${esc(l)}${cell(i, k + 1)}
`; + const tbl = `
${cols.map((h) => ``).join("")}${labels.map((l, i) => `${cols.slice(1).map((_, k) => ``).join("")}`).join("")}
${esc(h)}
${esc(l)}${cell(i, k + 1)}
`; + // Longer than CHART_TABLE_FOLD rows: folded into 「▸ 數據 · N 筆」 (the chart already shows them). + return labels.length > CHART_TABLE_FOLD ? `
數據 · ${labels.length} 筆${tbl}
` : tbl; } +const CHART_TABLE_FOLD = 6; function chartMd(lines) { const c = chartParse(lines); if (!c) return ""; diff --git a/src/agent.rs b/src/agent.rs index 62b2d7b..b7f318d 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -426,6 +426,7 @@ impl Drop for UsedBrowsers { } } +#[derive(Debug)] enum BrowserAt { Here, Box, @@ -458,8 +459,25 @@ fn browser_place(job: &Job, name: &str, args: &str) -> Result<(BrowserAt, String job.computers.iter().filter(|t| at(t).is_some()).map(|t| t.name.as_str()).collect::>().join("、"))); } // Not named: the chosen computer's browser, then the person's, then any that has one. - if let Some((b, n)) = job.computers.iter().find(|t| t.name == job.default_computer).and_then(|t| at(t).map(|b| (b, t.name.clone()))) { - return Ok((b, n)); + if let Some(t) = job.computers.iter().find(|t| t.name == job.default_computer) { + if let Some(b) = at(t) { + return Ok((b, t.name.clone())); + } + // A computer the person chose: nothing opens anywhere else. (A bot sent to a server with + // no browser yet opened one on the person's own Mac, step after step.) + if chosen_by_person(job) { + let why = match &t.place { + tools::Place::Box { .. } | tools::Place::Sealed { .. } => "它要 Docker,這裡沒有", + tools::Place::Local { .. } => "那台沒有 Chrome、Brave、Edge、Chromium 或 Firefox", + _ => "用 SSH 連的電腦沒有瀏覽器視窗", + }; + return Err(format!( + "使用者選的電腦「{}」現在開不了 AnyBot 的瀏覽器({why})。不要換到別台開,尤其不要開在使用者自己的電腦上。公開網頁用 web_fetch;要登入或操作的網頁,先告訴使用者:請他在「{}」裝瀏覽器、換做事的電腦,或在訊息裡指名一台。現在開得了瀏覽器的:{}。", + t.name, + t.name, + job.computers.iter().filter(|c| at(c).is_some()).map(|c| c.name.as_str()).collect::>().join("、") + )); + } } let person = roles_now(job).person.and_then(|p| job.computers.iter().find(|t| t.name == p)); match person.and_then(|t| at(t).map(|b| (b, t.name.clone()))).or_else(|| job.computers.iter().find_map(|t| at(t).map(|b| (b, t.name.clone())))) { @@ -557,10 +575,12 @@ fn wrap_untrusted(name: &str, text: String) -> String { fn keep_to_chosen(job: &Job, history: &[Message], name: &str, args: &str) -> (String, Option) { let mut v = tools::args_of(args); let Some(named) = v.get("computer").and_then(|c| c.as_str()).map(|c| c.trim().to_string()).filter(|c| !c.is_empty()) else { return (args.to_string(), None) }; - // The chosen computer can't do this kind of step (no screen, no browser): moving it there - // would only fail, so the step stays where the bot sent it. + // The bot's own computer can't do this kind of step (no screen, no browser): moving it there + // would only fail, so the step stays where the bot sent it. A computer the person chose is + // different: the step goes there even so, and fails there with why — it doesn't run on + // another computer (their own Mac) that nobody asked for. match job.computers.iter().find(|t| t.name == job.default_computer) { - Some(chosen) if named != job.default_computer && can_do(chosen, name) => {} + Some(chosen) if named != job.default_computer && (can_do(chosen, name) || chosen_by_person(job)) => {} _ => return (args.to_string(), None), } let said = history.iter().rev().filter(|m| m.role == Role::User && !m.summary).take(3).map(|m| m.text.as_str()).collect::>().join("\n"); @@ -823,6 +843,13 @@ fn noted(moved: &std::collections::HashMap, id: &str, text: &str } /// A computer the step names that isn't among this bot's computers right now, in plain words. +/// The person chose this bot's computer (Bot 設定 › 做事的電腦): another one than the bot's own. +/// Then no step goes to another computer unless the person names it — the bot's own, whose +/// screen or browser may be missing (no Docker), still borrows the person's. +fn chosen_by_person(job: &Job) -> bool { + !job.default_computer.is_empty() && job.default_computer != job.roles.own +} + fn not_here(job: &Job, name: &str) -> String { format!("「{name}」現在連不到:那台電腦可能沒開,或上面的 AnyBot 沒開、沒登入。請告訴使用者,等它連上再做(或問他要不要改用別台)。現在可以用:{}。絕對不要自己換到清單上的別台做同一件事——那台不是使用者指名的。", job.computers.iter().map(|t| t.name.as_str()).collect::>().join("、")) } @@ -864,8 +891,14 @@ fn screen_target(job: &Job, args: &str) -> Result { } return Ok(t.clone()); } - if let Some(t) = job.computers.iter().find(|t| t.name == job.default_computer && has_screen(t)) { - return Ok(t.clone()); + if let Some(t) = job.computers.iter().find(|t| t.name == job.default_computer) { + if has_screen(t) { + return Ok(t.clone()); + } + // A computer the person chose, with no screen to work (SSH): not someone else's screen. + if chosen_by_person(job) { + return Err(format!("使用者選的電腦「{}」不能操作螢幕(用 SSH 連的電腦只有檔案和指令)。不要換到別台的螢幕,尤其不要用使用者自己的電腦;先告訴使用者,請他換做事的電腦,或在訊息裡指名要用哪台的螢幕。", t.name)); + } } // Not named: a screen that is really there — the bot's desktop, this computer's, then one of // the account's other computers (a brain on a server has no screen of its own). @@ -4604,6 +4637,39 @@ echo 'done送出了' > done.html; (setsid pyt assert!(args.contains("王小明的Mac mini") && note.is_none(), "{args}"); } + /// 指定電腦之後:使用者選了一台沒有瀏覽器、沒有螢幕的電腦(雲端大腦所在的伺服器、SSH), + /// Bot 沒指名的瀏覽器和螢幕步驟不再跑到使用者自己的 Mac;Bot 自己指名那台 Mac 也拉回選的 + /// 那台(在那裡說清楚為什麼做不了)。使用者自己在訊息裡指名 Mac 就照做。沒選過(用 Bot + /// 自己的電腦)時照舊可以借 Mac 的。 + #[test] + fn a_chosen_computer_keeps_its_steps_off_the_persons_mac() { + let roles = tools::Roles { own: "工程 的電腦".into(), person: Some("王性驊的MacBook Pro".into()), server: true }; + let job = Job { + computers: vec![ + tools::Target { name: "工程 的電腦".into(), place: tools::Place::Sealed { root: std::env::temp_dir() } }, + tools::Target { name: "nobledesktop".into(), place: tools::Place::Ssh { target: "noble".into(), dir: String::new() } }, + tools::Target { name: "王性驊的MacBook Pro".into(), place: tools::Place::Device { host: "m".into(), dir: String::new() } }, + ], + default_computer: "nobledesktop".into(), + roles: roles.clone(), + ..test_job() + }; + let e = browser_place(&job, "browser_open", r#"{"url":"https://example.com"}"#).unwrap_err(); + assert!(e.contains("「nobledesktop」") && e.contains("不要換到別台") && e.contains("王性驊的MacBook Pro"), "{e}"); + let e = screen_target(&job, "{}").unwrap_err(); + assert!(e.contains("「nobledesktop」不能操作螢幕"), "{e}"); + // The bot naming the Mac on its own: back to the chosen one (where it says why it can't). + let (args, note) = keep_to_chosen(&job, &[Message::user("幫我看一下這個網頁")], "browser_open", r#"{"computer":"王性驊的MacBook Pro","url":"https://example.com"}"#); + assert!(args.contains("nobledesktop") && note.is_some(), "{args}"); + // The person naming the Mac: it goes there. + let (args, note) = keep_to_chosen(&job, &[Message::user("用我的電腦開這個網頁")], "browser_open", r#"{"computer":"王性驊的MacBook Pro","url":"https://example.com"}"#); + assert!(args.contains("王性驊的MacBook Pro") && note.is_none(), "{args}"); + assert!(matches!(browser_place(&job, "browser_open", &args), Ok((BrowserAt::Device(_), _)))); + // Not chosen (the bot's own, no Docker here): it still borrows the person's browser. + let own = Job { default_computer: roles.own.clone(), ..job }; + assert!(matches!(browser_place(&own, "browser_open", r#"{"url":"https://example.com"}"#), Ok((BrowserAt::Device(_), _)))); + } + #[test] fn cut_keeps_tool_pairs_and_recent_messages() { let mut h = vec![]; diff --git a/src/app.rs b/src/app.rs index c84b935..8924a85 100644 --- a/src/app.rs +++ b/src/app.rs @@ -803,6 +803,12 @@ impl App { m.tool_calls.push(crate::model::ToolCall { id: "pg1".into(), name: "write_page".into(), args: serde_json::json!({"id": id, "title": "台灣 Tesla FSD 追蹤"}).to_string(), status: crate::model::ToolStatus::Done }); b.messages.push(m); } + // ANYBOT_SHOT_PAGE_BODY=: the page's Markdown from that file instead. + if let Some(body) = std::env::var("ANYBOT_SHOT_PAGE_BODY").ok().and_then(|f| std::fs::read_to_string(f).ok()) { + if let Some(pg) = app.state.pages.iter_mut().find(|x| x.id == id) { + pg.body = body; + } + } if v == "page" { app.page_view = Some((id, None)); } diff --git a/src/app/chat_ui.rs b/src/app/chat_ui.rs index a0aabf4..fa7be0d 100644 --- a/src/app/chat_ui.rs +++ b/src/app/chat_ui.rs @@ -788,10 +788,13 @@ impl App { for c in m.tool_calls.iter().filter(|c| is_talk(&c.name)) { self.talk_card(ui, ctx, bot, m, c); } - // 頁面 written in this reply: the card (the page as it is now). - for id in crate::pages::ids_in(&m.tool_calls) { - ui.add_space(8.0); - self.page_card(ui, id); + // 頁面 saved in this reply: the card (the page as it is now) — once a reply, under the step + // that saved it last. (Worked out only for a message that saved one: few do.) + if !crate::pages::ids_in(&m.tool_calls).is_empty() { + for id in crate::pages::cards_by_message(&bot.messages).get(idx).cloned().unwrap_or_default() { + ui.add_space(8.0); + self.page_card(ui, id); + } } for a in m.attachments.clone() { ui.add_space(6.0); diff --git a/src/app/markdown_ui.rs b/src/app/markdown_ui.rs index 9da8e19..2aca423 100644 --- a/src/app/markdown_ui.rs +++ b/src/app/markdown_ui.rs @@ -464,6 +464,12 @@ fn category_steps(input: egui_plot::GridInput) -> [f64; 3] { #[cfg(target_os = "macos")] const ZOOM_HINT: &str = "拖曳平移 · 右鍵拖曳框選放大 · ⌘+滾輪或雙指縮放 · 雙擊還原"; +/// A chart's data table longer than this many rows starts folded (the chart already shows them). +const CHART_TABLE_FOLD: usize = 6; +/// A chart table's line height (the phone's .ctab: 1.45, with 6 px above and below). +const CHART_ROW_LH: f32 = 1.45; +/// The narrowest a chart table's name column gets before the table scrolls instead. +const CHART_NAME_MIN: f32 = 64.0; #[cfg(not(target_os = "macos"))] const ZOOM_HINT: &str = "拖曳平移 · 右鍵拖曳框選放大 · Ctrl+滾輪縮放 · 雙擊還原"; @@ -831,13 +837,20 @@ impl App { // Direct labels replace the axis: a single-series bar chart writes its numbers. let label_bars = single && !line; let hide_y = label_bars; + // Bars from 0; a line far from 0 fits its data (pages::chart_from_zero) — its own lowest + // point, which the plot takes in anyway. + let floor = if crate::pages::chart_from_zero(c) { + 0.0 + } else { + c.series.iter().flat_map(|(_, v)| v.iter().copied()).filter(|v| v.is_finite()).fold(f64::INFINITY, f64::min) + }; Plot::new(id) .height(230.0) .grid_color(p.grid) .show_grid(egui::Vec2b::new(false, true)) .x_grid_spacer(uniform_grid_spacer(category_steps)) .allow_scroll(false) - .include_y(0.0) + .include_y(floor) // Lines with names at their ends need room past the last point for the name. .include_x(if line && !single { c.labels.len() as f64 } else { 0.0 }) .y_axis_min_width(if hide_y { 2.0 } else { 30.0 }) @@ -905,8 +918,9 @@ impl App { }); } - /// The numbers behind a chart, as a compact table: readable without hovering, and the page - /// can be copied with its data. Pie rows say their share; series names head the columns. + /// The numbers behind a chart, under it like the page's own tables: readable without + /// hovering, and the page can be copied with its data. Pie rows say their share; series + /// names head the columns. More than CHART_TABLE_FOLD rows fold into 「▸ 數據 · N 筆」. fn md_chart_table(&self, ui: &mut egui::Ui, c: &crate::pages::Chart, id: egui::Id) { let p = self.pal; let pie = c.kind == crate::pages::ChartKind::Pie; @@ -927,37 +941,38 @@ impl App { } else { std::iter::once(t("項目").to_string()).chain(c.series.iter().map(|(s, _)| s.clone())).collect() }; - let lw = (ui.available_width() * 0.3).clamp(64.0, 140.0); - let cw = ((ui.available_width() - lw - 12.0 * (cols.len() - 1) as f32) / (cols.len() - 1) as f32).clamp(52.0, 120.0); - egui::Grid::new(id.with("tbl")).num_columns(cols.len()).spacing([12.0, 5.0]).striped(true).show(ui, |ui| { - let head = |s: String| RichText::new(s).size(FONT_XS).color(p.text3); - ui.add_sized([lw, 15.0], egui::Label::new(head(cols[0].clone())).truncate()); - for h in &cols[1..] { - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - ui.add_sized([cw, 15.0], egui::Label::new(head(h.clone())).truncate()); - }); - } - ui.end_row(); - for (i, label) in labels.iter().enumerate() { - ui.add_sized([lw, 15.0], egui::Label::new(RichText::new(label).size(FONT_SM).color(p.text2)).truncate()); - for ci in 1..cols.len() { - let text = if pie && ci == 2 { - format!("{:.0}%", vals[i] / total * 100.0) - } else { - let v = if pie || c.series.len() == 1 { - vals[i] + let rows: Vec> = labels + .iter() + .enumerate() + .map(|(i, label)| { + std::iter::once(label.clone()) + .chain((1..cols.len()).map(|ci| { + if pie && ci == 2 { + format!("{:.0}%", vals.get(i).copied().unwrap_or(0.0) / total * 100.0) + } else if pie || c.series.len() == 1 { + crate::pages::chart_num(vals.get(i).copied().unwrap_or(0.0)) } else { - c.series.get(ci - 1).and_then(|(_, vv)| vv.get(i).copied()).unwrap_or(0.0) - }; - crate::pages::chart_num(v) - }; - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - ui.add_sized([cw, 15.0], egui::Label::new(RichText::new(text).size(FONT_XS).family(egui::FontFamily::Monospace).color(p.text)).truncate()); - }); - } - ui.end_row(); + crate::pages::chart_num(c.series.get(ci - 1).and_then(|(_, vv)| vv.get(i).copied()).unwrap_or(0.0)) + } + })) + .collect() + }) + .collect(); + if rows.len() > CHART_TABLE_FOLD { + let open_id = id.with("tbl-open"); + let open = ui.data(|d| d.get_temp::(open_id)).unwrap_or(false); + let head = format!("{} {} · {} {}", if open { "▾" } else { "▸" }, t("數據"), rows.len(), t("筆")); + let r = ui.add(egui::Label::new(RichText::new(head).size(FONT_SM).color(p.text2)).sense(egui::Sense::click())); + if r.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() { + ui.data_mut(|d| d.insert_temp(open_id, !open)); } - }); + if !open { + return; + } + ui.add_space(crate::theme::sp::S1); + } + // Wider than the card (many series): it scrolls sideways, never widens the page. + egui::ScrollArea::horizontal().id_salt(id.with("tbl")).auto_shrink([true, true]).show(ui, |ui| chart_table(ui, p, &cols, &rows)); } /// Pie: slices from positive values, legend with value and share (charts have no negatives). @@ -1396,6 +1411,42 @@ fn looks_numeric(t: &str) -> bool { !digits.is_empty() && digits.chars().next().is_some_and(|c| c.is_ascii_digit()) && digits.chars().all(|c| c.is_ascii_digit() || c == ',' || c == '.') && t.len() - digits.len() <= 6 } +/// A chart's numbers drawn as one block (no grid, no layouts that take "all the width there +/// is" — a right-aligned egui cell did, and a pie's 「佔比」 column then pushed the 頁面 window off +/// the screen): a grey header, a hairline under each row, the names left, the numbers right, each +/// column as wide as its widest cell. Too little room cuts the names first (with …). +fn chart_table(ui: &mut egui::Ui, p: Palette, cols: &[String], rows: &[Vec]) { + use crate::theme::sp; + let font = egui::FontId::proportional(FONT_SM); + let n = cols.len(); + let gap = sp::S5; + let measure = |s: &str| ui.painter().layout_no_wrap(s.to_string(), font.clone(), p.text).size().x.ceil(); + let mut w: Vec = (0..n).map(|i| rows.iter().filter_map(|r| r.get(i)).map(|s| measure(s)).fold(measure(&cols[i]), f32::max)).collect(); + let others: f32 = w[1..].iter().sum::() + gap * (n - 1) as f32; + w[0] = w[0].min((ui.available_width() - others).max(CHART_NAME_MIN)); + let width = w.iter().sum::() + gap * (n - 1) as f32; + let row_h = (FONT_SM * CHART_ROW_LH).round() + sp::S3; + let (rect, _) = ui.allocate_exact_size(vec2(width, row_h * (rows.len() + 1) as f32), egui::Sense::hover()); + let painter = ui.painter().with_clip_rect(rect.expand(1.0).intersect(ui.clip_rect())); + let mut y = rect.top(); + for (ri, row) in std::iter::once(cols).chain(rows.iter().map(|r| r.as_slice())).enumerate() { + let mut x = rect.left(); + for (ci, text) in row.iter().enumerate() { + let color = if ri == 0 { p.text3 } else if ci == 0 { p.text2 } else { p.text }; + let mut job = egui::text::LayoutJob::simple_singleline(text.clone(), font.clone(), color); + job.wrap = egui::text::TextWrapping { max_width: w[ci], max_rows: 1, break_anywhere: true, overflow_character: Some('…') }; + let g = painter.layout_job(job); + let left = if ci == 0 { x } else { x + w[ci] - g.size().x }; + painter.galley(egui::pos2(left, y + (row_h - g.size().y) * 0.5), g, color); + x += w[ci] + gap; + } + y += row_h; + // The header's line a little stronger than the rows' hairlines (as the page's tables). + let line = if ri == 0 { p.text3.gamma_multiply(0.45) } else { p.border }; + painter.hline(rect.x_range(), y - 0.5, Stroke::new(1.0, line)); + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/app/remote_ui.rs b/src/app/remote_ui.rs index c537c2f..7e7b216 100644 --- a/src/app/remote_ui.rs +++ b/src/app/remote_ui.rs @@ -410,11 +410,14 @@ impl App { // Each message with its place in the chat (表情回應), its thinking and, on each step, // what came back (the desktop's 顯示步驟 / 思考過程), in short. let results: HashMap<&str, &str> = b.messages[start..].iter().filter(|m| m.role == Role::Tool).map(|m| (m.tool_call_id.as_str(), m.text.as_str())).collect(); + // 頁面 cards: once a reply, under the step that saved the page last (over the whole chat, + // so a reply cut by the tail still knows its later steps). + let cards = crate::pages::cards_by_message(&b.messages); let msgs: Vec = b.messages[start..] .iter() .enumerate() .filter_map(|(k, m)| { - let mut v = remote::message_json(m, &names, &self.state.pages)?; + let mut v = remote::message_json(m, &names, &self.state.pages, cards.get(start + k).map(Vec::as_slice).unwrap_or(&[]))?; v["index"] = json!(start + k); // 支線: its record, for the card (and the report's label). if m.branch != 0 { diff --git a/src/pages.rs b/src/pages.rs index 2687a38..73e2d2b 100644 --- a/src/pages.rs +++ b/src/pages.rs @@ -381,8 +381,8 @@ pub fn mermaid_blocks(body: &str) -> Vec { /// The pages written in one reply (its write_page calls), each once, in order. pub fn ids_in(calls: &[crate::model::ToolCall]) -> Vec { let mut out = vec![]; - for c in calls.iter().filter(|c| c.name == "write_page") { - if let Some(id) = serde_json::from_str::(&c.args).ok().and_then(|v| v["id"].as_u64()) { + for c in calls.iter().filter(|c| saved(c)) { + if let Some(id) = written_id(c) { if !out.contains(&id) { out.push(id); } @@ -391,6 +391,39 @@ pub fn ids_in(calls: &[crate::model::ToolCall]) -> Vec { out } +/// A write_page call that saved its page. A refused try (another bot's page) or one sent back by +/// the 寫法檢查 changed nothing — its card showed someone else's page, or the page as a later +/// try left it. +fn saved(c: &crate::model::ToolCall) -> bool { + c.name == "write_page" && c.status == crate::model::ToolStatus::Done +} + +/// The page a write_page call names (the app writes the id in once it has saved a new page). +fn written_id(c: &crate::model::ToolCall) -> Option { + serde_json::from_str::(&c.args).ok().and_then(|v| v["id"].as_u64()) +} + +/// For each message, the pages whose card shows under it: each page a reply saved, once, under the +/// step that saved it last (a reply that wrote its page three times — sent back, fixed, updated — +/// showed three cards of the same 第 3 版). A reply runs from one message of yours to the next. +pub fn cards_by_message(messages: &[crate::model::Message]) -> Vec> { + let mut out = vec![vec![]; messages.len()]; + let mut shown: Vec = vec![]; + for (i, m) in messages.iter().enumerate().rev() { + if m.role == crate::model::Role::User { + shown.clear(); + continue; + } + for id in ids_in(&m.tool_calls).into_iter().rev() { + if !shown.contains(&id) { + shown.push(id); + out[i].insert(0, id); + } + } + } + out +} + /// ```stats lines: 標籤 | 數值 | 說明 pub fn stats(src: &str) -> Vec<(String, String, String)> { src.lines() @@ -643,6 +676,19 @@ pub fn chart(src: &str) -> Option { (!series.is_empty()).then_some(Chart { kind, title, labels, series }) } +/// Whether the value axis starts at 0. Bars always (their length is the value); a line only when +/// 0 is within reach of its data — a reading of 1,649–1,796 W drawn from 0 was a flat line pressed +/// against the top. Within reach: the smallest value is 0 or less, or no bigger than the data's +/// own spread. (mobile/index.html chartFromZero says the same.) +pub fn chart_from_zero(c: &Chart) -> bool { + if c.kind != ChartKind::Line { + return true; + } + let all = c.series.iter().flat_map(|(_, v)| v.iter().copied()).filter(|v| v.is_finite()); + let (lo, hi) = all.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| (lo.min(v), hi.max(v))); + !lo.is_finite() || lo <= 0.0 || lo <= hi - lo +} + /// A number for an axis, a tooltip, a legend: no trailing .0, at most 2 decimals. pub fn chart_num(v: f64) -> String { if v == v.round() && v.abs() < 1e15 { @@ -741,6 +787,43 @@ mod tests { /// Markdown 表格習慣在列尾多打一個「|」:不會多出一欄空的「3」。只有一行的圓餅,那一片叫 /// 那一行的名字,不是「1」。(手機的 chartParse 同樣這麼讀。) + #[test] + fn a_line_far_from_zero_fits_its_data_and_bars_start_at_zero() { + let watts = chart("line 用電\n| 0時 | 1時 | 2時\n用電 | 1699 | 1651 | 1796").unwrap(); + assert!(!chart_from_zero(&watts), "1,651–1,796 spread 145: drawn from 0 it is a flat line"); + let news = chart("line\n| 7月 | 8月 | 9月\n媒體 | 12 | 1 | 34").unwrap(); + assert!(chart_from_zero(&news), "1–34: 0 is within reach"); + let below = chart("line\n| a | b\n溫度 | -3 | 8").unwrap(); + assert!(chart_from_zero(&below)); + let bars = chart("bar\n客廳 | 1699\n廚房 | 1796").unwrap(); + assert!(chart_from_zero(&bars), "a bar's length is its value"); + } + + /// 一個回覆裡:想改別的 Bot 的頁面被擋、寫法檢查退回一次、再存兩次——只出一張卡,在最後 + /// 存的那一步下面;被擋的那頁不出卡。下一個回覆又寫同一頁,就再出一張。 + #[test] + fn a_reply_shows_each_saved_page_once_under_its_last_save() { + use crate::model::{Message, ToolCall, ToolStatus}; + let call = |id: &str, page: u64, st: ToolStatus| ToolCall { id: id.into(), name: "write_page".into(), args: json!({"id": page, "title": "SCC 機房狀態報告"}).to_string(), status: st }; + let step = |calls: Vec| { + let mut m = Message::assistant("", ""); + m.tool_calls = calls; + m + }; + let msgs = vec![ + Message::user("做成報告"), + step(vec![call("a", 3, ToolStatus::Failed)]), + step(vec![call("b", 7, ToolStatus::Failed)]), + step(vec![call("c", 7, ToolStatus::Done)]), + step(vec![call("d", 7, ToolStatus::Done)]), + Message::assistant("資料齊了,我做成一份報告頁面。", ""), + Message::user("再補一點"), + step(vec![call("e", 7, ToolStatus::Done)]), + ]; + let cards = cards_by_message(&msgs); + assert_eq!(cards, vec![vec![], vec![], vec![], vec![], vec![7], vec![], vec![], vec![7]]); + } + #[test] fn chart_ignores_a_closing_pipe_and_names_a_lone_pie_slice() { let c = chart("bar\n| 1月 | 2月 |\n下載 | 120 | 320 |\n上傳 | 90 | 140 |").unwrap(); diff --git a/src/remote.rs b/src/remote.rs index 753ea06..c370384 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -385,11 +385,14 @@ pub(crate) fn tool_detail(name: &str, args: &str) -> String { } /// One message as the phone shows it (tool results are folded away like in the window). -pub fn message_json(m: &crate::model::Message, names: &HashMap, pages: &[crate::pages::Page]) -> Option { +/// `cards`: the pages whose card shows under this message (pages::cards_by_message); a write_page +/// call for any other is an ordinary step. +pub fn message_json(m: &crate::model::Message, names: &HashMap, pages: &[crate::pages::Page], cards: &[u64]) -> Option { use crate::model::{Role, ToolStatus}; if m.role == Role::Tool { return None; } + let mut carded: Vec = vec![]; let calls: Vec = m .tool_calls .iter() @@ -401,7 +404,16 @@ pub fn message_json(m: &crate::model::Message, names: &HashMap, pag ToolStatus::Denied => "denied", ToolStatus::Failed => "failed", }; - let page = (c.name == "write_page").then(|| serde_json::from_str::(&c.args).ok().and_then(|a| a["id"].as_u64())).flatten().and_then(|id| pages.iter().find(|p| p.id == id)); + // A page's card once, on the first call that saved it here (and only if it is this + // message's to show). + let page = (c.name == "write_page" && c.status == ToolStatus::Done) + .then(|| serde_json::from_str::(&c.args).ok().and_then(|a| a["id"].as_u64())) + .flatten() + .filter(|id| cards.contains(id) && !carded.contains(id)) + .and_then(|id| pages.iter().find(|p| p.id == id)); + if let Some(p) = page { + carded.push(p.id); + } if c.name == "show_card" { json!({"card": serde_json::from_str::(&c.args).unwrap_or(Value::Null), "status": st}) } else if matches!(c.name.as_str(), "ask_bot" | "message_bot") {