diff --git a/FEATURES.md b/FEATURES.md index 2a4a5b8..4e5b469 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -138,7 +138,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 - 找的範圍:每個 Bot 目前的對話和「過去的對話」裡,你和 Bot 說的話,以及附加檔案的檔名(標「檔案:」)。工具的結果和摘要不找(讀過一次的網頁會把別的都蓋掉)。不分大小寫。 - 每一筆兩行:Bot 的名字(在過去的對話裡的加「· 過去的對話」)和時間(「剛剛」「昨天 09:33」「11/3」),下面是那句話裡相符處前後的一行,你說的前面加「你:」。最新的在最上面,最多列 40 筆,超過會提示多打幾個字。 - 點一筆:打開那個 Bot,聊天捲到那則訊息,並用黃色亮一下(約 1.8 秒淡掉)。在過去的對話裡的,會先把那段對話換回來(目前的對話收進「過去的對話」最上面);那個 Bot 正在工作時不換,改提示「「(名字)」正在工作。等它做完,再打開過去的對話。」 -- 連到別台大腦的電腦上也能用(找的是大腦的聊天)。手機版還沒有。 +- 連到別台大腦的電腦上也能用(找的是大腦的聊天)。手機一樣有(擁有者):首頁放大鏡打字,相符的 Bot 在上,下面「聊天裡」列訊息和檔名(含過去的對話);點一筆打開那個聊天,捲到那則訊息亮一下(太早、手機沒留的會說);過去的對話先問要不要換回來。 ### 任務(2026-11-20) @@ -301,7 +301,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 ### 外觀 -- 外框圓角 20 px;正在輸入時框線變深。 +- 浮在聊天上的一張圓角卡片(圓角 14 px,跟手機同一張):細框線加一層柔和陰影,正在輸入時框線變深;+、麥克風、送出都是圓鈕。 - 提示文字「傳訊息給 (Bot 名稱)」。 - 從一行開始,跟著內容長高,最高 160 px,再多就在框內捲動。 - 每個 Bot 各自保留打到一半的草稿;草稿會跟著存檔,重新啟動或切 Bot 都不会吃掉打到一半的字。 @@ -639,8 +639,8 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 ### AI 供應商 -- 左邊是供應商清單,寬 200 px(估計值)。「● 」表示已經可以用,「○ 」表示還沒設定。 -- 右邊是選中的那家: +- 先是每家一塊圖塊(照 OpenBot 的設定排版,三塊一排,窄的時候兩塊):服務的圖案(AnyBot 自己畫的簡單圖形,不是任何人的商標圖檔)、名字、「● 可以用」或「還沒設定」(ChatGPT 方案:「還沒登入」)、右下雲端/本機。以前是設定分頁旁邊再一排供應商清單,三欄字擠在一起。 +- 點一塊進那家的頁,上面「‹ 模型」回到圖塊;從別處跳來(聊天的「設定 API 金鑰」、搜尋設定)直接進那家的頁: - 名稱。 - 取得金鑰的說明(第 11 節)。 - 「API 金鑰」:隱藏顯示。提示「貼上金鑰,或設定環境變數 (變數名)」。Ollama 沒有這一欄。 @@ -956,7 +956,16 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 - 票會出現在網址裡(瀏覽紀錄、記錄檔),所以:網頁一打開就把連結裡的票換成新的,連結裡那張當場作廢;每次斷線重連前再換一張;票只在發出後 10 分鐘內能開新的連線,已經連上的畫面只要當初要票的手機還登入著(或那台電腦還在帳號裡)就一直開著。斷線後 10 分鐘內回來換得到新票;超過 10 分鐘,手機網頁用自己的登入重新要,電腦開的網頁則顯示「這個畫面連結已過期」(不再一直重試),回 AnyBot 再開一次就好。「登出所有裝置」會讓所有畫面立刻斷掉。 - 同一個網路的手機(不經帳號伺服器):同一個網頁,連 AnyBot 自己的 `/api/vnc`。 - 這台電腦自己的 Bot 的電腦:直接開它的 noVNC。 -- **網頁**:最上面是返回、電腦名稱、狀態(即時觀看/你在操作)和「接管/交還給 Bot」。預設只看,按「接管」才會把你的滑鼠鍵盤送過去;需要處理卡片的「接管」直接打開接管。接管時有「打字」:打中文或任何語言(貼進目前的視窗,就是畫面上這個螢幕:那個 Bot 的螢幕沒開、看到的是共用桌面時就打在共用桌面;畫面關掉後打的字不會另外開一個看不到的螢幕),還有 Enter、Esc、Tab、⌫。斷線會自己重連(每次用新的票)。 +- **網頁**:最上面是返回、電腦名稱、狀態(即時觀看/你在操作)和「接管/交還給 Bot」。預設只看,按「接管」才會把你的滑鼠鍵盤送過去;需要處理卡片的「接管」直接打開接管。接管時下方出現按鍵列(見下面「手機接手:觸控板和按鍵列」),其中「⌨ 打字」打中文或任何語言(貼進目前的視窗,就是畫面上這個螢幕:那個 Bot 的螢幕沒開、看到的是共用桌面時就打在共用桌面;畫面關掉後打的字不會另外開一個看不到的螢幕)。斷線會自己重連(每次用新的票)。 +- **手機接手:觸控板和按鍵列**(照 OpenBot 手機 App 的觸控板模式;`mobile/trackpad.js`,Bot 的電腦和「這台 Mac」共用一份): + - 預設是**虛擬觸控板**,像筆電的觸控板,不用手指去戳縮小的畫面:一指滑動移游標(滑得快走得遠),點一下在游標的位置按左鍵,點兩下是連點,點兩下第二下按住再滑是拖曳,兩指滑動捲動(自然捲動:手指往上、頁面往下;Bot 的電腦上下左右都可以),兩指點一下或長按是右鍵。游標是畫面上自己畫的白色箭頭,打開時在正中間。頭三次接手時下方提示一次手勢。按鍵列最前面的「觸控板」關掉,改成點哪裡按哪裡(noVNC 自己的觸控,或「這台 Mac」的點一下左鍵、長按右鍵、快點兩下雙擊);選擇記在這支手機。 + - **修飾鍵不用按住**:Bot 的電腦是 Ctrl、Alt、Shift、❖(Super),這台 Mac 是 ⌘ ⌥ ⌃ ⇧。點一下變淡色=下一個鍵或下一次點擊時按著,用過就放開;點兩下變實心=鎖住,直到再點一下。所以 Ctrl+Tab 是點 Ctrl 再點 Tab,⌘+點擊是點 ⌘ 再在觸控板點一下。 + - 手機鍵盤沒有的鍵:Esc、Tab、← ↑ ↓ →、⌫、Del、⏎、Home、End、PgUp、PgDn(一排,左右滑)。 + - **快捷鍵**面板:一格一個名字,下面寫按法——切換視窗/切換 App、下一個分頁、上一個分頁、新分頁、關閉分頁、網址列、上一頁、下一頁、重新整理、拷貝、貼上、剪下、全選、復原、重做、尋找、存檔、全螢幕(Linux)/Spotlight(Mac)。Linux 寫字(Ctrl+Shift+Tab),Mac 寫符號(⌘⇧Z)。 + - 「⌨ 打字」:打字列;修飾鍵按著時只打一個字就送那組快捷鍵(點 Ctrl、打 c=Ctrl+C),不是打出那個字。 + - 接管的鎖每次只算 30 秒,畫面頁每 10 秒續一次:手機斷線、瀏覽器被關掉時最多 30 秒就自己放開(不會卡到重開大腦);手機放開不會放掉電腦那邊的接管。 + - **接管會鎖住那個螢幕**:手機按「接管」,Bot 在那個螢幕上的滑鼠鍵盤步驟等你(跟電腦版和需要處理卡的接管一樣),按「交還給 Bot」、關掉畫面、手機鎖住或切到別的 App 就放開,回來還在接管就再鎖上。以前手機的接管只把畫面切成可操作,Bot 只在你點擊或按鍵後停 8 秒,單純移動游標時它照做。 + - 「這台 Mac」的觸控板經大腦的 `api/screen/mac`:移動游標(最多每 150 毫秒送一次)、拖曳放開時整條路徑送出、點擊和組合鍵帶著修飾鍵。 - **你在操作時 Bot 會等**:你點擊或按鍵後 8 秒內,在你正在看的那個螢幕上做事的 Bot,滑鼠鍵盤操作會收到「使用者正在自己操作這台電腦」(別的螢幕上的 Bot 照做)。開著看畫面的螢幕不算閒置、不會被收掉,不管從哪裡開的(第 13 版起 Bot 的電腦自己看有沒有人連著)。不用另外按什麼;停下 8 秒它就繼續。需要處理卡片的「接管」會讓 Bot 一直等,直到你按「我完成了」或「跳過」。 - **VNC 密碼不出大腦**:大腦用 Bot 的電腦自己的 VNC 密碼登入,給看的人的是「不用密碼」;能連到這裡的人已經過帳號伺服器(或手機密碼)。 - 以前的做法(每 0.45~1 秒拍一張 1 MB 的圖、解開再壓、經過帳號伺服器傳;點擊另走一條路)已經拆掉。 @@ -1577,10 +1586,11 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) ### 個人資料與用量(設定 › 個人資料) - 設定多一頁「個人資料」(一般的下一頁;左下角選單也有「個人資料與用量…」)。最上面名字和「過去一年有 N 個活躍日」。 -- 五張卡:**Token**(過去一年,不算快取命中:模型新讀的、寫進快取的和寫出來的)、**最活躍的一天**(token 最多那天和日期)、**訊息**(你和 Bot 寫的,不算步驟和 AnyBot 自己的提示行)、**目前連續天數**(今天還沒用不算斷,寫「自 11月22日 起」)、**最長連續天數**(起訖日期)。視窗夠寬三張一排,否則兩張。 -- **活動**:一年的熱度格子(53 週,一週一欄、週日在上),依最忙那天分四級深淺,沒有用量只有訊息的那天照訊息算;滑過看「2026年11月20日:3,610 token、12 則訊息」。 -- **用量**:7 天/30 天/90 天/一年。token(新讀、寫、快取讀到)、呼叫次數、花費——只算模型服務自己回報的(例如 OpenRouter),沒回報的寫「未定價」(部分有部分沒有:「US$0.97(另有 694 次呼叫未定價)」),不是 0 元;每天一條(滑過看數字)、依模型、依 Bot(前 8 名,發布前檢查、目標檢查各自一列,刪掉的 Bot 寫「Bot 9(已刪除)」)。 +- 一條淡底、沒有框的數字列(大數字、底下一行小字,窄的時候兩個一排):**Token・一年**(不算快取命中:模型新讀的、寫進快取的和寫出來的)、**訊息・一年**(你和 Bot 寫的,不算步驟和 AnyBot 自己的提示行)、**連續使用**(今天還沒用不算斷;滑過看「自 11月22日 起」)、**最長連續**(滑過看起訖日期)。以前是五張有框的卡、兩三欄,一整片字。數字過千萬不帶小數(3,699萬),整數不寫「.0」。 +- **活動**:一年的熱度格子(53 週,一週一欄、週日在上),依最忙那天分四級深淺,沒有用量只有訊息的那天照訊息算;滑過看「2026年11月20日:3,610 token、12 則訊息」。圖例旁邊一行「最活躍:11月20日・3,610 token」。 +- **用量**:7 天/30 天/90 天/一年。一個大數字 token(滑過看新讀、寫、快取讀到),下面一行呼叫次數、花費——只算模型服務自己回報的(例如 OpenRouter),沒回報的寫「未定價」(部分有部分沒有:「US$0.97(另有 694 次呼叫未定價)」),不是 0 元;每天一條長條(滑過看數字,那條變深);再用「依模型/依 Bot」切換:依模型是一條彩色比例條,下面每個模型一列(服務的圖案、色點、名字、token・百分比),依 Bot 每列是頭像、名字、細長條、token・百分比(前 8 名,發布前檢查、目標檢查各自一列,刪掉的 Bot 寫「Bot 9(已刪除)」)。 - 都從已經有的紀錄算(`usage/YYYY-MM.jsonl` 和每則訊息的時間),不另外存;用大腦的時區切日子;打開時在背景算,一分鐘內再看不重算。螢幕電腦向大腦要(`api/sync/stats`),手機用 `api/stats`(擁有者才有)。 +- 手機:設定 ›「個人資料與用量」(擁有者才有),同一套:四個大數字一條、一年的熱度點(點一下看那天)、用量的期間切換、大數字、每天的長條、依模型(彩色比例條)/依 Bot(頭像和長條)。 ### 所有檔案(側邊欄的資料夾按鈕) @@ -1588,7 +1598,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 從哪裡開:側邊欄最左邊那一欄的資料夾圖示(任務下面);左下角選單「所有檔案…」。截圖用 `ANYBOT_SHOT_VIEW=library`。 - 左欄:搜尋檔名、「所有檔案」、「最近 7 天」、每個有檔案的 Bot(顏色點、數量)。上面種類分頁帶數量:全部、圖片、文件、程式碼、表格、影音、其他(沒有的不列)。右上「格子/清單」:格子是縮圖或副檔名+檔名+「Bot · 日期」,一排幾張撐滿寬度;清單是「Bot · 日期 · 大小」。視窗高度固定,切種類、看法不跳。 - 檔案不在原處(刪掉或搬走):灰字、紅字「不見了」,點不開。其他點一下用 AnyBot 的檢視器打開(Markdown、表格、圖片、PDF、影音、程式碼;用其他 App 打開、下載)。 -- 螢幕電腦看的是從大腦抓過來的副本。手機還沒有(只有每個對話的「資料庫」)。功能地圖新的一區 library.md。 +- 螢幕電腦看的是從大腦抓過來的副本。手機首頁上面一排的「檔案」是同一份(`api/act/library`,最新的 500 個):搜尋檔名、種類分頁帶數量、圖片三欄格子(捲到才載縮圖)、其他一列一個(Bot・多久前・大小),不見了的變淡點不開,點一個用手機的檢視器打開;每個對話的「資料庫」也還在。功能地圖新的一區 library.md。 ### 備用模型(Bot 設定 › AI 供應商與模型) @@ -1746,7 +1756,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - **只管你自己的訊息**:例行任務、訊息管道和團隊成員的訊息照平常做,不受計畫模式限制。照計畫做的期間每一輪都帶著這份計畫(像 Claude Code 把核准的計畫交回給模型),所以聊別的事前先取消。清除聊天記錄、開始新對話會連計畫一起清掉;分享 Bot 的檔案不含計畫。重開 AnyBot 計畫還在;還沒核准時重開,傳一句話它就接著規劃。 - 手機一樣:計畫卡、問題卡都有;目標和計畫在輸入框上方是一排小圖示(計畫旁邊寫「2/5」),點一下展開那一行和「清除目標」/「取消計畫」。 - **外觀(Bot 是主角)**:介面本身安靜(黑、白、灰),顏色和動作都留給 Bot。 - - **字型**:介面用思源黑體(Noto Sans TC),讀的文字——Bot 的回答、頁面內文和標題——用思源宋體(Noto Serif TC),像 Claude 的回答一樣是書的字;兩種都有 Regular 和 Bold,包在 App 裡,每台電腦看起來一樣。程式碼用系統的等寬字。沒有字型選項。 + - **字型**:跟 Apple 的 App 一樣,介面和讀的文字(Bot 的回答、頁面)都用 macOS 自己的字:英文 SF Pro、中文蘋方(PingFang TC),粗體用半粗(Semibold,比 Bold 輕鬆)。沒有蘋方的電腦(Windows、Linux)用包在 App 裡的思源黑體。程式碼用系統的等寬字。沒有字型選項。(以前回答用思源宋體,讀起來正式、重。) - **你的訊息是淡灰泡泡**(預設「安靜」;設定 › 一般 › 聊天的顏色可以改成「跟著 Bot」:你的訊息泡泡、送出鈕、側邊欄選中的那格用 Bot 的顏色,或「只用黑色」)。Bot 的回覆不用泡泡,像文件一樣排在頁面上,只有錯誤訊息有泡泡。 - **輸入框上方的臉**:Bot 的臉從輸入框後面探出來,旁邊一句話說它在做什麼(原本對話最後的轉圈那一行搬到這裡)。眼睛就是狀態:待命時往下看輸入框;在想時往上、慢慢左右飄;有步驟在跑時看著旁邊那句「正在…」;需要你時看著你,臉上多一個黃點,旁邊寫「等你決定」;做完笑兩秒;上一輪出錯時眼睛變兩條橫線。新對話時沒有這張小臉(臉是中間那張大的)。 - **每種情境一套動作和一個小道具**(都在臉自己的方框裡,不會碰到旁邊的字;從頭後經過的畫在臉後面,在前面的壓在臉上、描一圈底色,所以頭像不會擋住動畫;換情境時淡入淡出,步驟很快連續切換時至少停 0.6 秒,不會一直閃): @@ -1762,7 +1772,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - **需要你允許**:不再是蓋住整個視窗的彈出視窗,改成固定在輸入框上方的黃色卡片,上面的聊天照樣看得到,下面的輸入框照樣可以打字告訴它怎麼改。輸入框空著時 Enter 允許、Esc 拒絕(卡片出現 0.6 秒後才算,免得原本要按的 Enter 誤答);游標在輸入框裡也一樣(以前輸入框先把 Enter 當成「送出」拿走,框是空的什麼都沒送出,也沒有允許)。框裡有字時 Enter 照樣是送出。要你親自處理的步驟(接管畫面)還是聊天裡的卡片。 - **黃色只代表「需要你」**:允許卡片、臉上的黃點、側邊欄 Bot 上的黃點、設定裡「更新」旁的黃點(有新版)。有新訊息是強調色(黏土橘)小點。 - **標題列**:Bot 的名字在左邊(按一下開對話詳細資訊),右邊「分享」和「⋯」不再有圓框;圖示線條粗一點(2.25)。 - - **新對話**:Bot 的臉放大、依時段的問候(早安/午安/晚上好/夜深了;看的是 設定 › 一般 的時區,不是這台電腦的系統時區)、一句「嗨,我是 …」和它的描述,下面三個可以直接點的開頭(點了把字放進輸入框)。 + - **新對話**:Bot 的臉放大、依時段的問候(早安/午安/晚上好/夜深了;看的是 設定 › 一般 的時區,不是這台電腦的系統時區)、一句「嗨,我是 …」和它的描述,下面三個可以直接點的開頭(一排細框膠囊,沒有底色、滑過才有;點了把字放進輸入框)。 - **設定**:左邊分頁只有文字,選中的淡底粗字;每組設定一張白色細框卡片,一列一件事(左邊名稱、右邊控制項,名稱下最多一行小字,其餘說明在「?」裡);選項是分段按鈕,開關是黑軌白鈕。「一般」的名稱改成白話(聊天的顏色、用意思找記憶、Bot 可以翻的資料夾)。「整合」分成三頁(訊息管道、連接器、技能);訊息管道先列「已連接」(標記、名稱 · 種類、誰回覆、狀態、開關、⋯ 裡移除),「新增管道」是八個方塊,點了才在下面打開那一種的表單。權限頁的「直接操作」「自動審核」也是開關。 - **手機**:顏色跟電腦一樣(設定 › 一般 › 外觀 的主題、底色、強調色、對比都照著穿;手機的「外觀」預設「跟著電腦」,也可以選跟著手機、淺色、深色)。你的訊息泡泡照「聊天的顏色」(預設淡灰)、Bot 的回覆不用泡泡、允許卡片是黃色細框、輸入框是底部一張圓角卡片;工作中在對話最後顯示 Bot 的小臉和跟電腦上一樣的那句「正在…」。 - **自己進化**:一件事做了 5 步以上(操作電腦、網頁、指令,不算記憶和設定),回答完後在背景回頭看一次:這是在網站或程式上動手操作的事(填表、發文、回留言、上傳下載、改設定),就把這次真的成功的最短做法存成技能(用畫面上的名字,不寫編號和座標;繞路和失敗寫成「注意」;使用者說過的偏好寫進去);已經有同一件事的技能就合併成更好的一版,照著做而且很順就不動。回覆下面會多一行「(學會了新做法「…」)」或「(把做法「…」更新了)」。系統指示要 Bot 開始做事前先看技能清單、有符合的先 use_skill。實測(httpbin 訂 pizza,真的 Grok):第一次 11 步學到技能;第二次先讀技能、10 步 24 秒一次做完,回頭看後判斷不用改。 @@ -1943,7 +1953,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 執行:照線從觸發器往下(一張接到好幾張時上面的先、再左邊);觸發器後面還沒有步驟時不跑,說「這個工作流還沒有步驟,沒有執行:…」(以前馬上記一次「完成」,日程、執行紀錄、Bot 看到的「最近一次」都是假的)。Bot 步驟是那個 Bot 聊天裡的一則「[工作流「名稱」第 k/n 步]…」加上一步的結果(聊天裡泡泡上面一行小標、淡色泡泡,結果只顯示前三行,滑過看全文;以前看起來像你自己打的),它這一輪最後的回答交給下一步(它正忙就排在後面)。檢查回「通過」才往下。等你確認在畫布上方一條「繼續/停止」,並發通知。一次只跑一個,排程到了自動跑;卡片標完成、進行中、等你確認、失敗;執行紀錄留 20 次。 - 版本歷史:停手 20 秒、關畫布、每次執行前、Bot 每次改之前各留一版,最多 30 版,點一版就還原。 - 在聊天裡做:跟 Bot 用一般的話說要什麼流程(「每天早上 9 點去 Threads 找 5 則熱門育兒討論,整理好先問我,我說可以再傳給我」),Bot 用 `workflow` 工具建立、看、改(加步驟、改內容、刪步驟、連線、貼便利貼、整理排版)、執行、停止、刪除(刪除先問)。你看著那個 Bot 的聊天時,畫布自動開在聊天旁邊(視窗夠寬時),它改到的卡片和便利貼亮一下,跑出畫面就縮到看得到全部;Bot 做的排成一欄,插在中間時後面的往下移,你自己排過的不重排。旁邊的聊天跟著側邊欄選的 Bot 換。 -- 手機沒有畫布:在聊天裡請 Bot 做、改、跑,它用文字說工作流的樣子;「等你確認」的通知會到手機,按「繼續」要在電腦上。螢幕電腦(看著帳號裡大腦的那台)一樣能新增、修改、刪除、畫和註解,執行、停止、繼續交給大腦做;執行紀錄以大腦的為準。螢幕上的修改一張卡片、一個欄位地傳給大腦(舊版大腦收到的是整個工作流,跟以前一樣):你在螢幕上搬卡片、改名,Bot 同時在大腦上加的步驟和線都留著;兩邊同時新建、編號一樣的工作流各留一個,螢幕那個換新編號。同一張卡片兩邊都改了,後到的為準;線整組一起傳,兩邊同時拉線時後到的為準。 +- 手機沒有畫布(改要在電腦上或請 Bot 改),但首頁上面一排有「工作流」:每個一張卡(名字、觸發和下次、步驟數、這次或最近一次怎麼了、右邊 ▷ 執行/■ 停止),等你確認時卡下面直接有「繼續」「停止」;點進去看步驟由上到下和每一步這次(或最近一次)的狀態、Bot 的結果前三行、最近 10 次執行紀錄(點一次看每一步)。跑的時候每 3 秒更新。手機按的執行算「手動」,不上日程。大腦的路是 `api/act/workflows`(讀)和 `api/act/workflow`(run/stop/go/halt);同一個網路直接連的手機也可以(不放寬任何權限)。螢幕電腦(看著帳號裡大腦的那台)一樣能新增、修改、刪除、畫和註解,執行、停止、繼續交給大腦做;執行紀錄以大腦的為準。螢幕上的修改一張卡片、一個欄位地傳給大腦(舊版大腦收到的是整個工作流,跟以前一樣):你在螢幕上搬卡片、改名,Bot 同時在大腦上加的步驟和線都留著;兩邊同時新建、編號一樣的工作流各留一個,螢幕那個換新編號。同一張卡片兩邊都改了,後到的為準;線整組一起傳,兩邊同時拉線時後到的為準。 - 側邊欄最左邊一條直欄(照 OpenBot 的排版):上面「聊天、工作流、日程、任務、所有檔案」,下面「傳送、市集、設定」,現在在哪一個就亮哪一個,滑過寫名字;從 Mac 視窗左上角的紅黃綠按鈕下面開始。Bot 那一欄最上面只剩「搜尋」「+」,最下面是你的名字和 Bot 在哪一台(整個寬度)。以前這些全擠在最上面一排,側邊欄一窄就被切掉、或被紅黃綠按鈕壓到。 ### 日程(側邊欄最左邊那一欄的日曆圖示) @@ -1954,7 +1964,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 排程或事件自己跑的那幾次照執行紀錄:✓ 完成、✗ 失敗或中斷、■ 停止、圓點執行中。你按的「立即執行」「執行工作流」、請 Bot 跑的、試跑一步都不放(以前一按就出現在日曆上,像是排好的事);它們在執行紀錄裡。還沒到的照排程算出來(跟真的排程同一套算法),暫停的變灰帶 ‖。事件觸發的例行任務只看得到跑過的。週每筆是時間、Bot 的頭像和名稱;月每天最多三筆、多的「還有 N 個」,點那天換成日看法;日照時間一列列。 - 下面「即將執行」:每個例行任務、工作流各一行,寫它下一次什麼時候跑,照時間排、最多六行,帶頭像(以前一個每天跑的就把六行占滿)。 - 點任何一筆打開卡片:哪個 Bot、那次的時間和狀態、怎麼重複、最近一次怎麼樣、要它做什麼;「打開聊天」「立即執行」「暫停/繼續」(工作流:「打開工作流」「立即執行」)。 -- 「+ 新增例行任務」回到 Bot 的聊天,輸入框先放好「每天早上 9 點幫我」,接著用一般的話說要做什麼。手機還沒有日程。 +- 「+ 新增例行任務」回到 Bot 的聊天,輸入框先放好「每天早上 9 點幫我」,接著用一般的話說要做什麼。手機首頁上面一排有「日程」:最上面「即將執行」(每件一行,寫下次的日子和時間),接著三天前到七天後一天一組,每列時間、名字、Bot、怎麼重複,跑過的寫 ✓ 完成/✗ 失敗/停止了,暫停的變淡;打開捲到今天;點例行任務打開它的卡、點工作流打開那個工作流。大腦的路是 `api/act/schedule`(同一份 `schedule::items`/`coming`)。 ## 26. Bot 可以直接操作 App 的功能 @@ -2160,8 +2170,11 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 字級 7 階:說明 12(時間、標記、圖表軸)、小字 13(說明、次要)、介面 14(按鈕、清單、輸入框、設定列)、閱讀 16(回答、頁面內文、輸入框裡你打的字)、小標 18、中標 22、大標 28。 - 行高:閱讀字 1.7 倍(16 px 字 27 px 行),介面字 20,小字 18,標題 26/30/36。 - 間距:4、8、12、16、24、32。 -- 圓角三種:6(標籤、色塊、小控制項)、10(輸入框、按鈕、程式碼、提示框)、14(卡片、對話框、面板);膠囊和圓形全圓。 -- 中文和英文用同一套字型(介面思源黑體、閱讀思源宋體),基準線和大小對得齊;缺的字用系統字型(蘋方等)補。程式碼用 **SF Mono**,沒有就用 Menlo。 +- **風格**(設定 › 一般 › 外觀最上面一排小圖;手機 設定 › 一般 最上面同一排;Bot 用 `update_settings` 的 `style`):一次換整套樣子——淺色和深色各一組墨、紙、強調色(`theme::TEMPLATES`,從同一個產生器長出整個殼),加上聊天背景的花紋:紙(預設)、夜、墨、苔(點點)、海(波浪)、糖(點點)、夕陽(波浪)、終端機(黑底綠字、格線)。每張小圖是那個風格的縮小畫面(側邊欄、字、你的泡泡、強調色、花紋),現在用的有一圈強調色。電腦和手機一起換;點強調色、動「底色」或「外殼顏色重設」回到自訂。 +- **設定每一列都有圖示**:照名字裡的字配(`icons::setting_icon`/手機的 `setIcon`:主題月亮、風格和顏色調色盤、通知鈴鐺、時區地球、權限盾牌、電腦螢幕…),沒對到的是滑桿;電腦和手機同一套。 +- 圓角三種:6(標籤、色塊、小控制項)、10(輸入框、程式碼、提示框)、14(卡片、對話框、面板);按鈕、分段選擇是膠囊(跟手機、macOS 26 一樣:形狀本身就說「可以按」,不用框)。 +- 浮在上面的東西(聊天的輸入框、工作流畫布上的工具列和面板、選單)用一層柔和陰影浮起來(調色盤的 `shade`,手機的 `--shade`),不靠粗框線;平放的卡片用細框和底色分組。 +- 中文和英文用 Apple 的一對字(SF Pro+蘋方),基準線和大小對得齊;沒有蘋方時用思源黑體,缺的字用系統字型補。程式碼用 **SF Mono**,沒有就用 Menlo。 - 「·」分隔號前後不加空格。 ### 共用元件(`src/app/kit.rs`) @@ -2173,7 +2186,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - **設定列**:左邊名稱 14 px(可以多一行 13 px 灰色狀態)和「?」說明,右邊開關、選單或按鈕;名稱太長就「…」,不會擠掉右邊。 - **卡片**:一整塊有標題、有欄位的內容(Bot 設定的「Bot 資料」「頭像」等)。**卡片裡不再放卡片**(以前「瀏覽器設定檔」裡的兩個選項各自是一張小卡;「更新」頁每一列都是一張卡)。 - **欄位**:上面 13 px 灰色小標,下面輸入框。**說明**:13 px 灰字、一行(長的滑過看全文;以前 12 px 更淡的灰、整段攤開)。設定列名稱旁的「?」只在滑鼠移到那一列時出現。 -- **按鈕**:實心(一個畫面一顆主要動作)、淡底、紅色;刪除這種不能回頭的按兩次。 +- **按鈕**:全是膠囊。實心(一個畫面一顆主要動作)、淡底、紅字(停止、移除、登出:能回頭、也不是那個地方的主要動作,所以不搶眼)、紅底(只給不能回頭的刪除);刪除這種不能回頭的按兩次。 - 設定左邊的分頁:選中的是淡底加粗字(以前是一整顆黑色膠囊)。 - 測試看守:畫面程式裡自己畫的「底色+外框」卡片只准變少(`kit.rs` 以外)。 @@ -2311,11 +2324,14 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 保險庫:只說明,不傳任何密碼到手機; - 手機與帳號:直接連線的手機清單,可以登出別支手機; - 更新:版本和有沒有新版。 + - 個人資料與用量:見「個人資料與用量」。 +- 手機補上的(以前只有電腦有):搜尋聊天裡的訊息和檔名;Bot 設定的「執行步驟用的模型」「思考模式」;釘選的 Bot 在 ⋯ ›「更多…」往前、往後移,分區的 ⋯「往上移/往下移」;「匯出 Bot 檔案(.anybot)」「匯出文字記錄(.md)」「匯入 Bot 檔案」(iPhone 跳分享選單,可以存到「檔案」或 AirDrop);每個 Bot 各自的草稿(切換 Bot、關掉頁面都留著,存在這支手機);程式碼塊右上的「複製」;頁面 ⋯ 的「存成檔案(.md)」。之後又補:設定 › 一般「電腦的外觀」(電腦的主題、聊天的顏色)和「其他時區…」自己打;Bot 設定技能「全選/全不選」、模型可讀長度 400K;稽核的「只看沒人看著時做的」;首頁上面一排「日程」「工作流」「檔案」(見各節)。手機的短提示(「已複製」、被擋下的原因)是標題列下面一張毛玻璃卡片:半透明、後面的內容模糊、細框和柔和陰影、圓角 14,多行時靠左排,字越多停越久(2.6 秒起、最多 7 秒);以前是黑色膠囊,兩三行字就撐成橢圓。設定首頁最上面「搜尋設定…」(跟電腦同一份目錄,`api/act/settings_find`,點一筆到手機的那一頁);一般「電腦的外觀」多強調色(選了回到自訂)、對比(柔和/標準/鮮明)、語言;從 設定 › 電腦 打開 Bot 的電腦時先選看哪個 Bot 的螢幕或共用的桌面。聊天裡的流程圖(```mermaid)由大腦畫成圖(`api/diagram`,跟頁面的圖同一個畫法),畫不出來時顯示原始碼;圖表的 SVG 只放在 裡顯示(以前被當成下載檔,頁面和聊天的圖都破圖)。再補:權限頁「一律放行」開關(跟 /always-approve 同一件事)和「智慧模式:卡片沒人回答時」幾秒後自己回答;聊天上方「一律放行開著」一條,擁有者可以「關閉」;一般「記憶與文件」(用意思找記憶、Bot 可以翻的資料夾);更新頁「你不在時自動更新」「園丁報告」;模型的服務網址、測試連線並取得模型清單、本機模型的看圖小幫手;設定 ›「語音」整頁;Bot 設定的備用模型、起始資料夾、自訂頭像顏色(手機自己的選色器)、語音(朗讀每個回答、聲音、速度、語言)。同一個網路直接連的手機照樣只能收緊:打開一律放行、縮短智慧模式等待、加資料夾、換起始資料夾、打開看圖小幫手都被擋,說明「請在電腦上改,或用帳號連線」。 - 看電腦畫面: - 「Bot 的電腦」每秒更新一次畫面;在休眠時按「叫醒」。 - 「這台 Mac」要先在設定裡打開才會出現。 - - 操作方式:點一下是左鍵;長按是右鍵;點兩下是雙擊;「右鍵:開」之後每次點都是右鍵。 - - 「⌨︎ 打字」可以打中文,會打進目前的視窗;還有 Enter、Esc、Tab、⌫ 和捲動按鈕。 + - 操作方式:預設是虛擬觸控板,下面一排按鍵列和「快捷鍵」面板(見「手機接手:觸控板和按鍵列」);關掉觸控板時點一下是左鍵、長按是右鍵、快點兩下是雙擊(以前點兩下會多送一兩下點擊;「右鍵:開」拿掉了,兩指點就是右鍵)。 + - 「⌨ 打字」可以打中文,會打進目前的視窗。 + - 對話詳細資訊、需要處理卡上的小畫面是那個 Bot 自己的螢幕(以前一律是共用的那個)。 - 右上角頭像:傳送到其他裝置(只有擁有者有,見下面「傳送到其他裝置」)、通知(開關、要通知哪幾種、送一則測試通知;開關顯示的是帳號伺服器上這支手機的狀態,按下去就照它顯示的開或關——帳號伺服器已經沒有這支手機的訂閱時顯示「關閉中」,打開會重新訂閱;連不上帳號伺服器時照這支手機上的設定,種類和測試等連上再改;直接連線的手機會說明收不到推播;iPhone 要先加入主畫面)、安裝成 App(還沒裝時才有)、切換到別台 AnyBot、登出這支手機。 - 手機做的事都交給電腦版原本的功能處理(同一套規則、同一份資料),不是另外寫一套。 - 團隊(用帳號伺服器分享時)權限跟以前一樣: @@ -2547,7 +2563,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) ### 字型 -- 介面用 **思源黑體**(Noto Sans TC),讀的文字(回答、頁面)用 **思源宋體**(Noto Serif TC),都是 SIL OFL 1.1 授權,檔案和授權在 `fonts/`,直接包進 App。 +- Mac 上用系統的 **SF Pro** 和 **蘋方**(不包進 App);其他電腦用 **思源黑體**(Noto Sans TC,SIL OFL 1.1 授權,檔案和授權在 `fonts/`,包進 App)。 - 它們沒有的字,改用系統字型(蘋方)補上。Mermaid 圖表裡的字也是思源黑體。 - 沒有字型選項(以前的粉圓體和「系統字型」已經拿掉)。Bot 的電腦的桌面也是思源黑體(第 14 版起)。 @@ -2835,7 +2851,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) ## 對話的 Markdown 與流程圖(2026-11-04) -- 以 pulldown-cmark 解析(表格、刪除線、待辦清單、數學區塊):思源宋體 16 px、標題 22/18/16 px、單一換行照樣換行、粗體(思源宋體的真粗體)、斜體、刪除線、行內程式碼、可點的連結、多層清單、待辦勾選框、引用線、表格(可橫向捲動)、分隔線。 +- 以 pulldown-cmark 解析(表格、刪除線、待辦清單、數學區塊):16 px(跟介面同一種字)、標題 22/18/16 px、單一換行照樣換行、粗體(真的半粗字,不是描粗)、斜體、刪除線、行內程式碼、可點的連結、多層清單、待辦勾選框、引用線、表格(可橫向捲動)、分隔線。 - 程式碼區塊:圓角邊框、上色(註解、字串、數字、關鍵字)、可橫向捲動、滑過時右上角「複製程式碼」,複製後兩秒顯示勾。 - ```mermaid:用純 Rust 的 mermaid-rs-renderer 畫成圖(流程圖、時序圖、類別圖、狀態圖、ER、甘特圖、圓餅圖、心智圖、時間軸…),中文用思源黑體,跟著深淺色主題。回覆還在產生時先顯示原始碼,結束後才畫。點圖可放大檢視(縮放、拖曳、下載 PNG 到「下載項目」)。畫不出來時顯示「無法顯示此圖表」並保留原始碼。 diff --git a/docs/feature-map/activity.md b/docs/feature-map/activity.md index 5a73820..c1c7e82 100644 --- a/docs/feature-map/activity.md +++ b/docs/feature-map/activity.md @@ -7,7 +7,7 @@ - `activity-who` 誰發起:「你」、「例行任務」(例行任務和 ⏰ 提醒叫醒的那一輪)、「別的 Bot」(「[來自 Bot]」開頭的那一輪)。 - `activity-evidence` 做了什麼:看了(打開的網址、web_fetch、讀的檔案、看的資料夾(空的寫「工作資料夾」)、搜尋、找文件或記憶、讀的頁面)、寫了(改的檔案、寫的頁面、下載的檔案、存成的 PDF)、執行了(指令、網頁腳本,太長的截短),各自不重複、最多 12 項;工具各幾次;被拒絕或失敗的步數;從開始到最後一步結束花多久。 - `activity-panel` 電腦版:右側面板「動態」最上面「操作紀錄」,最近 8 輪,每輪一張:時間 · 誰 · 結果(完成/停止/失敗/進行中),開頭那句話,「N 步 · 看了 a · 寫了 b · 執行 c · 失敗 d · 花多久」(有失敗的那行字是紅的);點一下展開看了、寫了、執行了的清單和每個工具的次數。「只看沒人看著時做的」只留例行任務和別的 Bot 叫的。面板開著時每 5 秒重讀;螢幕電腦向大腦要(`api/sync/audit/`)。 -- `activity-phone` 手機「稽核」:每一輪最上面一列「你發起 · 2 分 13 秒 · 失敗 1 步」,下面「看了:…、寫了:…、執行了:…」(各前 4 項,多的寫「等 N 項」),再來是原本每一步的清單。 +- `activity-phone` 手機「稽核」:每一輪最上面一列「你發起 · 2 分 13 秒 · 失敗 1 步」,下面「看了:…、寫了:…、執行了:…」(各前 4 項,多的寫「等 N 項」),再來是原本每一步的清單。最上面一格「只看沒人看著時做的」(跟電腦一樣,只留例行任務和別的 Bot 叫的;沒有時寫「最近 30 天沒有沒人看著時做的事。」)。 ## 使用者怎麼到 diff --git a/docs/feature-map/appearance.md b/docs/feature-map/appearance.md index 49cf410..41200da 100644 --- a/docs/feature-map/appearance.md +++ b/docs/feature-map/appearance.md @@ -4,12 +4,13 @@ AnyBot 長什麼樣子、用什麼語言,和怎麼聽、怎麼說:設定 › ## 子功能 +- `appearance-style` 風格(外觀最上面一排小圖,每張就是那個風格的樣子):紙(預設)、夜、墨、苔(點點)、海(波浪)、糖(點點)、夕陽(波浪)、終端機(格線)——一套淺色和深色的顏色,加上聊天背景的花紋;電腦和手機一起換(手機 設定 › 一般 最上面同一排)。點下面的強調色或動「底色」回到自訂(小圖下寫「現在是自訂的顏色」)。 - `appearance-theme` 主題:淺色/深色/跟隨系統;手機的外觀預設跟著電腦([phone](phone.md))。 - `appearance-colors` 強調色(八個點:黏土、靛藍、苔綠、藍綠、玫紅、琥珀、石板、墨黑)、聊天的顏色(你的訊息泡泡:安靜=淡灰,預設;跟著 Bot;只用黑色——手機同一個設定;只有點,選中的有外圈)。 - `appearance-language` 語言:選單和 Bot 回答用的語言。 - `appearance-more` 外觀最後一列「更多外觀設定」按「展開」才出現:底色(冷→暖滑桿)、對比(柔和→鮮明滑桿)、密度(寬鬆/緊湊)、慶祝動畫(開/關,目標達成時撒彩帶)、頭像動態(自動/完整/減少:Bot 頭像做事時的呼吸和眼神,減少只換表情;自動在畫面用 CPU 畫的電腦上減少,那時下面寫「這台的畫面用 CPU 畫,自動減少」)、外殼顏色重設(回預設「紙」)。這幾項和上面的一樣,調了立刻整個殼跟著換,不用重開。 -- `appearance-fonts` 字型:沒有字型選項:介面思源黑體、讀的文字(回答、頁面)思源宋體。設定列名稱旁的「?」平常不顯示,滑鼠移到那一列才出現;設定下面的說明只有一行,長的滑過看全文。 -- `appearance-voice` 語音:「語音服務」一張清單,「聽(語音轉文字)」把說的話變文字(語音輸入、語音聊天、會議錄音),「說(朗讀)」把回答唸出來;各自在右邊選服務,選了在那一列下面展開要填的欄位(快速填入、網址、金鑰、模型;「說」還有「聲音」選單),能用了列上寫「可以用」,並有「試試看(說一句話)」或「試聽」。沒設定時沒有語音輸入,請 AnyBot 唸會說「還沒設定語音」。 +- `appearance-fonts` 字型:沒有字型選項:跟 Apple 一樣,介面和讀的文字(回答、頁面)都是 SF Pro 加蘋方(PingFang TC),粗體用半粗(Semibold);沒有蘋方的電腦用包在 App 裡的思源黑體。設定列名稱旁的「?」平常不顯示,滑鼠移到那一列才出現;設定下面的說明只有一行,長的滑過看全文。 +- `appearance-voice` 語音:「語音服務」一張清單,「聽(語音轉文字)」把說的話變文字(語音輸入、語音聊天、會議錄音),「說(朗讀)」把回答唸出來;各自在右邊選服務,選了在那一列下面展開要填的欄位(快速填入、網址、金鑰、模型;「說」還有「聲音」選單),能用了列上寫「可以用」,並有「試試看(說一句話)」或「試聽」。沒設定時沒有語音輸入,請 AnyBot 唸會說「還沒設定語音」。手機在 設定 ›「語音」:聽和說各一列(服務、網址、金鑰只能寫入、模型,說多「聲音」和「試聽」)。 - `appearance-voices` 「聲音」選單:第一項「預設(eve)」,下面是服務列出的聲音,選了試唸一句;拿不到清單時寫原因,可以直接輸入名稱或「再試一次」。每個 Bot 的 對話詳細資訊 › 語音聊天 ›「聲音」是同一個選單(預設是這裡選的)。 ## 使用者怎麼到 @@ -20,7 +21,7 @@ AnyBot 長什麼樣子、用什麼語言,和怎麼聽、怎麼說:設定 › ## 怎麼操作(verify-anybot) -- Bot:`update_settings` 改得到 `theme`(light/dark/system)和 `accent`(quiet/bot_color/black,聊天的顏色),其他外觀和語音設定告訴使用者在哪裡([settings](settings.md))。 +- Bot:`update_settings` 改得到 `theme`(light/dark/system)、`style`(風格)和 `accent`(quiet/bot_color/black,聊天的顏色),其他外觀和語音設定告訴使用者在哪裡([settings](settings.md))。 前提: @@ -28,6 +29,7 @@ AnyBot 長什麼樣子、用什麼語言,和怎麼聽、怎麼說:設定 › - **Bot 換深色**(covers `appearance-theme`、`appearance-language`):請 Bot 換深色。指令:`$CTL phone send '換深色 [[call update_settings {"theme":"dark"}]]' && $CTL phone wait-text '主題 → dark' --in '#msgs' && $CTL phone wait 'html[data-theme="dark"]' && $CTL phone shot appearance-dark && $CTL state .theme && $CTL model 'select(.kind == "call") | .user'`。看到:手機不用重新整理就變深色;大腦存成 Dark;Bot 收到的訊息後面帶著語言的提示〔用繁體中文和台灣用語回答…〕。 - **手機上改主題、聊天的顏色**(covers `appearance-theme`、`appearance-colors`):重新整理,帳戶選單 › 設定 › 一般,主題選「淺色」,聊天的顏色選「跟著 Bot」。指令:`$CTL phone open --listed && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone click '[data-go="general"]' && $CTL phone click '[data-s="theme"]' && $CTL phone click '#sheet-in .opt' --text 淺色 && $CTL phone wait 'html[data-theme="light"]' && $CTL phone click '[data-s="accent"]' && $CTL phone click '#sheet-in .opt' --text 跟著 && $CTL phone wait-text '跟著 Bot' --in '#list' && $CTL api GET /api/settings --jq '{theme, accent}'`。看到:選了馬上變淺色;聊天的顏色寫「跟著 Bot」;大腦那邊 light、bot_color。 +- **換風格**(covers `appearance-style`):手機 設定 › 一般 點「海」,再請 Bot 換成終端機。指令:`$CTL phone click '[data-go="general"]' && $CTL phone click '[data-style="ocean"]' && $CTL phone wait-text 換好了 --in '#toast' && $CTL state '.shell_template' && $CTL phone js 'document.documentElement.dataset.backdrop' && $CTL phone send '換終端機 [[call update_settings {"style":"terminal"}]]' && $CTL wait-api /api/settings '.style == "terminal"'`。看到:ocean、waves(聊天背景變波浪);Bot 換完 style 是 terminal;桌面 `ANYBOT_SHOT_STYLE=terminal` 的截圖是黑底綠字加格線。 - **重開還在**(covers `appearance-theme`、`appearance-colors`):指令:`$CTL restart && $CTL api GET /api/settings --jq '{theme, accent}' && $CTL phone open --listed && $CTL phone wait 'html[data-theme="light"]'`。看到:重開後還是 light、bot_color。 - **語音還沒設定**(covers `appearance-voice`):打開聊天,看輸入框,請大腦唸一句。指令:`$CTL phone click '.row[data-bot="1"]' && $CTL phone wait '#input' && $CTL phone wait-gone '#b-mic' && $CTL api GET '/api/state?since=0' --jq '.voice' && $CTL api --expect 409 POST /api/voice/speech '{"text":"你好"}'`。看到:沒有「開始語音輸入」;聽、說都是 false;唸一句回「還沒設定語音:請到「設定 → 語音」選一個服務。」 - **桌面的外觀、語音**(covers `appearance-colors`、`appearance-more`、`appearance-fonts`、`appearance-language`、`appearance-voice`、`appearance-voices`):指令:要開視窗——`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot appearance ANYBOT_SHOT_VIEW=general && ABV_ALLOW_WINDOW=1 $CTL desktop-shot voice ANYBOT_SHOT_VIEW=voiceoff`(示範資料)。看到:外觀的八個點、聊天的顏色三個點、語言、「更多外觀設定」;「語音服務」的聽、說兩列和各自的服務選單。拉滑桿當下就換、設好的樣子靠自動測試。 diff --git a/docs/feature-map/autonomy.md b/docs/feature-map/autonomy.md index 31594d0..dee1ef5 100644 --- a/docs/feature-map/autonomy.md +++ b/docs/feature-map/autonomy.md @@ -11,7 +11,7 @@ - `autonomy-review` 自動審核:兩組用一般的話寫的規則「無需詢問直接允許」「一律詢問」,由這個 Bot 的模型判斷,兩邊都符合時「一律詢問」優先。符合允許就直接做;符合詢問就問你,而且沒有「一律允許」;都不符合照常問;審核沒回應就先問你。連接器的工具、瀏覽器要問的步驟(本機網址、上傳)也經過它,「一律允許」過的除外。審核員只讀參數前 3000 字和最後 1000 字;中間省略後它說允許(直接操作下說都不符合也一樣)仍先問,卡片寫「參數很長…所以先問你」。 - `autonomy-patterns` 固定樣式的規則:規則也可以寫成 `shell(git *)`(指令;允許要 `a && b` 每一段都符合,詢問只要一段)、`file(~/Projects/**)`(檔案或資料夾,** 任何層、* 一層)、`connector(gitlab__*)`(連接器的工具)、`web(domain:example.com)`(用網址打開或讀那個網站和它底下的網址;點連結、轉址到的不算)、`tool(browser_click)`(工具的名字)。樣式先判斷、每次一樣、不呼叫模型:要問的步驟、連接器的工具、瀏覽器的步驟和 `web_fetch` 符合「一律詢問」的樣式一定問(模型說允許也沒用);指令、檔案不用問或「一律允許」過的不比對;符合允許的樣式就允許,但一般話寫的「一律詢問」還是會先讓模型看一次;有藏起來的指令($()、反引號)樣式不會允許。樣式對不上任何東西時(`connector(…)` 沒有那個工具、`web(…)` 沒寫成 `web(domain:網站)`、`tool(…)` 不是哪一步的名字),新增的地方會說。 - `autonomy-hooks` Hooks:使用者(和管理員)自己的程式,AnyBot 在固定的時間點跑它們,格式跟 Claude Code 一樣(hooks.json)。PreToolUse 可以擋下一步(exit 2 或 deny)、改參數、要先問或省掉一次詢問(但擋不過安全規則,也省不掉付款/傳送/刪除這類每次問);PostToolUse 改 Bot 讀到的結果或加一句;UserPromptSubmit、SessionStart 補資訊給模型或擋下這一輪;Stop 叫它多做(一輪最多 3 次);Notification 跟著通知跑。hook 出錯(結束碼不對、逾時、JSON 看不懂)當它不在,紀錄檔寫原因。 -- `autonomy-remote` 從手機打開:直接連線(同一個網路)的手機只能收緊、不能放寬(「這會放寬 Bot 能做的事:同一個網路直接連的裝置只能收緊、不能放寬…」)。擋下的:打開直接操作、/always-approve(或 /yolo)、打開自動審核、加允許規則、拿掉詢問規則、加連接器或打開關掉的、打開訊息管道、打開 Bot 的電腦工具、分享 Bot 給團隊、把 Bot 加進團隊群組、勾回能力或電腦、Bot 的電腦從強隔離換回標準。不認得的動作也擋(不是放行)。可以的:上面每一項反過來,和不動權限的(名字、外觀、模型、金鑰、技能、例行任務、記憶;匯入的 Bot 不帶電腦工具、授權和團隊分享)。打開了「從手機看這台電腦的螢幕並操作」就不算數:那等於坐在電腦前,什麼都改得了。設定的名字要一字不差(多空白、大小寫不同就回「不認得這個設定」,什麼都不改)。要放寬:在電腦上的 AnyBot,或用帳號連線。卡片上的「允許一次」「一律允許」照樣可按(那是回答眼前那張卡)。手機的權限頁跟著電腦那邊的改變重讀,不用重新整理。 +- `autonomy-remote` 從手機打開:直接連線(同一個網路)的手機只能收緊、不能放寬(「這會放寬 Bot 能做的事:同一個網路直接連的裝置只能收緊、不能放寬…」)。擋下的:打開直接操作、一律放行(開關或 /always-approve、/yolo)、智慧模式卡片自己回答的秒數、打開自動審核、加允許規則、拿掉詢問規則、加連接器或打開關掉的、打開訊息管道、打開電腦工具、分享 Bot 給團隊或加進團隊群組、勾回能力或電腦、Bot 可以翻的資料夾、起始資料夾、看圖小幫手、改服務網址、強隔離換回標準。不認得的動作也擋(不是放行)。可以的:上面每一項反過來,和不動權限的(名字、外觀、模型、技能、記憶;匯入的 Bot 不帶電腦工具和授權)。打開了「從手機看這台電腦的螢幕並操作」就不算數:那等於坐在電腦前,什麼都改得了。設定的名字要一字不差(不然回「不認得這個設定」)。要放寬:在電腦上的 AnyBot,或用帳號連線。卡片上的「允許一次」「一律允許」照樣可按(那是回答眼前那張卡)。手機的權限頁跟著電腦重讀。 ## 使用者怎麼到 diff --git a/docs/feature-map/bots.md b/docs/feature-map/bots.md index 716a430..29aa51a 100644 --- a/docs/feature-map/bots.md +++ b/docs/feature-map/bots.md @@ -6,8 +6,8 @@ - `bots-sidebar` 側邊欄:最上面是主要 Bot(大頭像),接著是釘選的格子(把 Bot 拖進去就釘選,格子裡可以拖曳排序),再來是各分區和「未分區」(分區見 [team](team.md))。每一列第二行是「正在工作…」「需要你允許」「等你回答」「等你處理」,或最後一則訊息。選中的 Bot 整列淺底(比滑過深一階),左邊沒有色條。 - `bots-moods` 頭像的表情:側邊欄、釘選格子、右側面板和任務卡上的 Bot 頭像跟輸入框上方那張臉一樣看狀態——等你允許或回答時往上看你;上網時眼睛左右掃,看畫面時往右上看,寫字時往下看,想事情或讀回來的結果時往左上看,其他步驟慢慢左右讀;做事時微微呼吸(2.6 秒一次);上一輪失敗是兩條平的眼睛,剛做完笑兩秒;閒著時眼睛跟著滑鼠。做事時一個樣子至少停 1.4 秒,步驟換得快也不會一直閃。設定 › 一般 › 更多外觀設定 ›「頭像動態」選「減少」(「自動」在畫面用 CPU 畫的電腦上也是)只換表情、不動([appearance](appearance.md))。 -- `bots-search` 搜尋「搜尋 Bot 和訊息」:上面列名字或描述相符的 Bot,下面「訊息」列你和 Bot 說過的話和附件檔名(含過去的對話,最多 40 筆),點一筆就捲到那則訊息。按 🔍 或 ⌘F 打開時游標在搜尋框;之後點輸入框打字,字就留在輸入框(搜尋框開著也不會把游標搶回去)。 -- `bots-menu` Bot 選單:「釘選」/「取消釘選」、「移至」、「標示為已讀」/「標示為未讀」、「設為主要 Bot」、「編輯 Bot…」、「記憶…」、「開始新對話」、「過去的對話」、「分享與匯出」(「匯出 Bot(分享給別人)…」「匯出文字記錄…」「匯入 Bot…」「複製對話 ID」)、「重新啟動這個 Bot」、「清除聊天記錄」、「刪除」。 +- `bots-search` 搜尋「搜尋 Bot 和訊息」:上面列名字或描述相符的 Bot,下面「訊息」列你和 Bot 說過的話和附件檔名(含過去的對話,最多 40 筆),點一筆就捲到那則訊息。手機一樣:Bot 在上,下面「聊天裡」列訊息和檔名(擁有者),點一筆打開那個聊天、捲到那則亮一下,過去的對話先問要不要換回來。按 🔍 或 ⌘F 打開時游標在搜尋框;之後點輸入框打字,字就留在輸入框(搜尋框開著也不會把游標搶回去)。 +- `bots-menu` Bot 選單:「釘選」/「取消釘選」、「移至」、「標示為已讀」/「標示為未讀」、「設為主要 Bot」、「編輯 Bot…」、「記憶…」、「開始新對話」、「過去的對話」、「分享與匯出」(「匯出 Bot(分享給別人)…」「匯出文字記錄…」「匯入 Bot…」「複製對話 ID」)、「重新啟動這個 Bot」、「清除聊天記錄」、「刪除」。手機:⋯ ›「更多…」有「釘選裡往前移/往後移」「匯出 Bot 檔案(.anybot)」,聊天的 ⋯ 有「匯出文字記錄(.md)」,首頁 + 有「匯入 Bot 檔案」,分區的 ⋯ 有「往上移/往下移」。 - `bots-create` 建立:「新增 Bot」,或「從範本建立」(研究助理、寫作夥伴、電腦助手、客服助理、開發助手)。新 Bot 沿用目前選中 Bot 的供應商和模型,電腦工具關著。 - `bots-chat` 在聊天裡請 Bot:列出所有 Bot(`list_bots`)、建 Bot(`create_bot`,不用問)、改名稱等(`update_bot`,先跳確認卡片)。 @@ -29,6 +29,7 @@ - **建 Bot**(covers `bots-create`):+ ›「建立 Bot」打名字;再從範本建一個。指令:`$CTL phone click '[data-back]' && $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 click '[data-back]' && $CTL phone click '#b-newbot' && $CTL phone click '#sheet-in .opt' --text 從範本建立 && $CTL phone wait-text 開發助手 --in '#sheet-in' && $CTL phone click '#sheet-in .opt' --text 寫作夥伴 && $CTL phone wait-text 寫作夥伴 --in '#isl-name' && $CTL state '[.bots[] | {id, name, provider, model, tools_enabled}]'`。看到:範本有研究助理、寫作夥伴、電腦助手、客服助理、開發助手;建好就打開它的聊天;兩個新 Bot 都是 Custom · fake-model,tools_enabled false。 - **Bot 自己建、列出**(covers `bots-chat`):指令:`$CTL phone click '[data-back]' && $CTL phone click '.row[data-bot="1"]' && $CTL phone send '建 [[call create_bot {"template":"研究助理"}]]' && $CTL wait-api '/api/state?since=0' '.bots | length == 4' && $CTL phone send '列出 [[call list_bots {}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]? | select(.name == "list_bots" and .status == "done")] | length == 1' && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | select(.name == "list_bots") | .result]'`。看到:沒跳卡片就建好研究助理;清單一行一個 Bot(供應商 · 模型,主要 Bot 標出來、「就是你」)。 - **搜尋**(covers `bots-search`):首頁放大鏡打「研究」。指令:`$CTL phone click '[data-back]' && $CTL phone click '#b-search' && $CTL phone type '#search' '研究' && $CTL phone wait-gone '.row[data-bot="1"]' && $CTL phone wait '.row[data-bot="2"]' && $CTL phone shot bots-search && $CTL phone click '#b-search-x' && $CTL phone wait '.row[data-bot="1"]'`。看到:只剩名字或描述含「研究」的(研究員、研究助理);✕ 清掉回到全部。 +- **手機搜尋聊天裡、排序、匯出**(covers `bots-search`、`bots-menu`):指令:`$CTL phone click '.row[data-bot="1"]' && $CTL phone send '週末想去台南玩' && $CTL phone wait-text '台南' --in '#msgs' && $CTL phone click '[data-back]' && $CTL phone click '#b-search' && $CTL phone type '#search' '台南' && $CTL phone wait '[data-hit="0"]' && $CTL phone click '[data-hit="0"]' && $CTL phone wait '#msgs .lit' && $CTL phone click '#b-chatmore' && $CTL phone click '#sheet-in .opt' --text '匯出文字記錄' && $CTL phone wait-text '已存成' --in '#toast'`。看到:「聊天裡」兩筆(你的話和回答),點了打開聊天、那則亮一下;「已存成「… 對話.md」」。 - **選單**(covers `bots-menu`、`bots-sidebar`):研究員那列「⋯」› 釘選、「更多…」› 標示為未讀;寫作夥伴 ›「刪除 Bot」。指令:`$CTL phone click '[data-botmenu="2"]' && $CTL phone click '#sheet-in .opt' --text 釘選 && $CTL phone wait-text '已釘選的 Bot' --in '#home' && $CTL phone click '[data-botmenu="2"]' && $CTL phone click '#sheet-in .opt' --text 更多 && $CTL phone click '#sheet-in .opt' --text 標示為未讀 && $CTL wait-api '/api/state?since=0' '.bots[] | select(.name == "研究員") | .pinned and .unread' && $CTL phone click '[data-botmenu="3"]' && $CTL phone click '#sheet-in .opt' --text '刪除 Bot' && $CTL phone wait-text '此操作無法復原' --in '#sheet-in' && $CTL phone click '#sheet-in .opt' --text 刪除 && $CTL wait-api '/api/state?since=0' '[.bots[].name] | index("寫作夥伴") == null' && $CTL phone shot bots-menu`。看到:研究員移到「已釘選的 Bot」、有未讀的點;刪除先問「這會刪除它和它的聊天記錄。此操作無法復原。」,刪掉後清單和大腦都沒有它。 - **重開還在**(covers `bots-create`、`bots-sidebar`):指令:`$CTL restart && $CTL phone open --listed && $CTL phone wait-text '已釘選的 Bot' --in '#home' && $CTL state '[.bots[] | {name, pinned}]'`。看到:小幫手二號、研究員(還是釘選)、研究助理都還在。 - **桌面**(covers `bots-sidebar`、`bots-search`、`bots-menu`、`bots-create`):指令:要開視窗——`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot bots-find ANYBOT_SHOT_VIEW=find ANYBOT_SHOT_FIND=台南`。看到:搜尋下面「訊息」列說過的話(含過去的對話);選中那列淺底、沒有色條;釘選格子的拖曳、桌面的選單項目(分享與匯出…)、「建立 Bot」視窗(填 Soul 與指示、擅長,名字或模型空白按不下去)靠自動測試。 diff --git a/docs/feature-map/box.md b/docs/feature-map/box.md index 843efb9..fe58f24 100644 --- a/docs/feature-map/box.md +++ b/docs/feature-map/box.md @@ -8,6 +8,7 @@ - `box-desktop` 畫面(「開啟電腦」):下方工作列由左到右是「應用程式」選單、「瀏覽器」、「檔案管理員」、「終端機」、開著的視窗、時鐘;桌面按右鍵也有應用程式選單(瀏覽器、檔案管理員、終端機、文字編輯器、影像檢視器,Bot 裝的程式在「其他」)。瀏覽器開機就開好(第一次是說明頁),跟 Bot 的瀏覽器工具是同一個、登入共用。檔案管理員側邊欄的「下載」是 Bot 下載的檔案;檔案按兩下用對的程式開。 - `box-manage` 管理:狀態、更新、自動更新、快照、重設、磁碟;終端機與環境密鑰;在哪裡執行(Docker 主機、容器隔離)。 - `box-account-view` 從帳號看畫面:手機或另一台電腦經帳號伺服器看 Bot 電腦的畫面,只要開著就不會斷。 +- `box-phone-drive` 手機接手(畫面右上「接管」;從 設定 › 電腦 打開時先選看哪個 Bot 的螢幕或共用的桌面):Bot 在那個螢幕的步驟等你(「交還給 Bot」、關掉畫面、手機鎖住或切走都放開;手機斷線、被關掉時 30 秒內自己放開)。預設是虛擬觸控板:一指移游標、點一下按、點兩下按住拖曳、兩指捲動、兩指點或長按右鍵(下方「觸控板」關掉改成點哪裡按哪裡)。下方按鍵列:Ctrl、Alt、Shift、❖ 點一下按住給下一個鍵或點擊,點兩下鎖住;Esc、Tab、方向鍵、⌫、Del、⏎、Home、End、PgUp、PgDn;「快捷鍵」一格格寫名字(切換視窗 Alt+Tab、下一個分頁 Ctrl+Tab、拷貝、貼上…);「⌨ 打字」可打中文,按住修飾鍵打一個字就是那組快捷鍵。手機看「這台 Mac」(要開「從手機看這台電腦的螢幕並操作」)是同一套,修飾鍵是 ⌘⌥⌃⇧。 ## 使用者怎麼到 @@ -26,6 +27,7 @@ - **沒有 Docker 時**(covers `box-machine`、`box-manage`):首頁點「電腦」。指令:`$CTL phone wait-text 0/1 --in '#quick' && $CTL phone click '#quick [data-q="computers"]' && $CTL phone wait-text '沒有 Docker' && $CTL phone wait-text '沒有 Docker,現在沒有這台電腦' && $CTL phone shot box-nodocker && $CTL api GET '/api/state?since=0' --jq '{box, box_available}' && $CTL api GET /api/settings --jq '.box | {state, available, version, runtime, snapshot, auto_update}'`。看到:「驗證小幫手 的電腦 · 沒有 Docker」,沒有畫面小圖;按鈕列、「更新 Bot 的電腦:沒有 Docker,現在沒有這台電腦」「自動更新:關」「容器隔離:標準」(不說主機有沒有 gVisor)「上次快照:還沒有」「重設電腦」;API 是 box「沒有 Docker」、available false、runtime runc。 - **聊天裡的電腦**(covers `box-machine`):Bot 在自己的電腦寫檔,再看對話詳細資訊的「電腦」。指令:`$CTL phone click '[data-back]' && $CTL phone click '.row[data-bot="1"]' && $CTL phone send '[[call shell {"command":"echo hi > box.txt; ls"}]]' && $CTL phone wait-text '的電腦] box.txt' && $CTL phone click '#b-chatmore' && $CTL phone click '#sheet-in .opt' --text 對話詳細資訊 && $CTL phone click '[data-tab="computer"]' && $CTL phone wait-text 沒有畫面 --in '#details' && $CTL botfile box.txt && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | .status]'`。看到:沒有卡片就跑完(自己的電腦不用問),回覆裡有 box.txt;「電腦」分頁是「驗證小幫手 的電腦 · 沒有 Docker」「沒有畫面」;檔案內容 hi。 - **畫面、更新、重設**(covers `box-desktop`、`box-manage`):指令:要開視窗——`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot box ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_VIEW=computers`;畫面本身走不到——要 Docker(scratch 不准碰使用者的 Docker、Lima)。看到:設定 › 電腦「Bot 的電腦」一段沒有 Docker 時的樣子;桌面、工作列、檔案視窗、更新排隊靠下面要 Docker 的實機測試。`make update-box` 也不跑:它找的是裝好的那台 AnyBot。 +- **手機接手的按鍵列**(covers `box-phone-drive`):打開畫面頁接手(scratch 沒有 Docker,連不上畫面,看得到列)。指令:`$CTL phone js 'location.href = "screen#lan=1&control=1&bot=1"; 1' && $CTL phone wait-text 快捷鍵 --in '#bar' && $CTL phone click '#bar button' --text 快捷鍵 && $CTL phone click '#bar button[data-mod="ctrl"]' && $CTL phone shot box-drive && node mobile/trackpad.test.mjs`。看到:列上「觸控板、Ctrl、Alt、Shift、❖、Esc、Tab、←…」,快捷鍵面板「切換視窗 Alt+Tab」等 18 格,Ctrl 變亮;手勢測試全部 OK。觸控板動到真的畫面走不到——要 Docker。 - **從帳號看畫面**(covers `box-account-view`):指令:走不到——要帳號伺服器和 Docker。看到:最接近的真路是 `relay/` 的 `cargo test` 和 `cargo test remote::`(畫面的票)。 - 自動測試:`cargo test cloudbox::`、`cargo test tools::`、`cargo test remote::`;要 Docker 的實機測試(會建一台 box):`cargo test cloudbox:: -- --ignored`(`box_end_to_end`、`each_bot_has_its_own_screen`、`box_update_keeps_files`…),只在有 Docker、不是使用者正在用的那台上跑。 @@ -36,5 +38,6 @@ - 桌面是第 12 版起換的(照 LazyBoy2 的 box:XFCE 工作列、深色主題、繁中、台北時間;字型第 14 版起是思源黑體,和 AnyBot 視窗同一套,以前是粉圓);第 11 版以前是 fluxbox,只有右鍵選單和一條細工作列,設定 › 電腦「更新 Bot 的電腦」換新版。桌面設定每次開機照映像檔重放,在桌面上改的外觀、工作列不會留下;留下的是檔案和瀏覽器的登入。工作列鎖住(xfconf 的鎖要寫使用者名稱 bot,寫「*」不算數);它的「面板 › 登出 › 結束」只關掉工作列,一秒後自己回來。網頁上傳檔案的視窗開機時設好大小和位置(GTK 沒記著位置就照字型算大小,比螢幕大)。時區是 /etc/localtime(台北),沒有 TZ 變數,Bot 改了就生效。 - 檔案視窗的「取消」「開啟」在最上面(第 11 版以前在最下面、被螢幕切掉,網頁上傳圖片選得到檔案卻送不出去——換新版)。看畫面時可以跟自己的電腦互相複製貼上;在畫面裡打的字進到正在看的那個螢幕(Bot 自己的螢幕也一樣,不會打到共用的)。那個 Bot 的螢幕沒開時,看到的是共用桌面,點擊和打字也算在共用桌面(共用桌面上的 Bot 會停手);畫面中途關掉,之後打的字不會另外開一個看不到的螢幕。 - 實機要確認的:選單是中文、只有一層;工作列按右鍵沒有「移除」;網頁上傳檔案的視窗整個在螢幕裡(看得到「開啟」);請 Bot 打開終端機要開出跟工作列「終端機」同一種視窗,打開檔案總管要開出檔案管理員、在 bot 家目錄;開著畫面關掉 Wi-Fi 一分鐘再打開要自己接回;把畫面連結複製到另一個瀏覽器(原本的開著)要連不上。 +- 手機的畫面(接管)每次打開都是一個新的框,關掉就拿掉:以前同一個框換網址,iframe 換頁會留在上一頁紀錄裡,第二次之後按 ✕ 或返回退的是框裡的那一頁,畫面卡著回不去。 - 從帳號看畫面:之前靜止一分鐘、或看超過十分鐘會被帳號伺服器切掉,要更新帳號伺服器(make update-server)。 - 從帳號看畫面的票會出現在網址裡,所以網頁一打開就換掉連結裡那張(舊的當場作廢),每次斷線重連再換一張;票只在發出後十分鐘內能開新連線,已連上的畫面在要票的手機還登入時一直開著。斷線超過十分鐘:手機網頁用自己的登入重新要票;電腦開的網頁顯示「這個畫面連結已過期」並停止重試,回 AnyBot 再開一次。 diff --git a/docs/feature-map/library.md b/docs/feature-map/library.md index fba829a..b6e2a1d 100644 --- a/docs/feature-map/library.md +++ b/docs/feature-map/library.md @@ -11,6 +11,7 @@ - `library-gone` 不見了:檔案已經不在原來的地方(刪掉或搬走),檔名變灰、紅字「不見了(檔案已經刪掉或搬走)」(清單寫「不見了」),點不開。 - `library-open` 點一下用 AnyBot 自己的檢視器打開,跟聊天裡的檔案卡片一樣(Markdown 排版、表格、圖片、PDF、錄音影片、程式碼…),右上「用其他 App 打開」、下載、關閉。 +- `library-phone` 手機的所有檔案(首頁上面一排的「檔案」):上面搜尋檔名和種類分頁(全部、圖片、文件、程式碼、表格、影音、其他,只列有的,帶數量),圖片排成三欄格子(捲到才載縮圖),其他一列一個(圖示、檔名、Bot・多久前・大小);不在原處的變淡、寫「不見了」、點不開;點一個用手機的檢視器打開。 ## 使用者怎麼到 - 側邊欄最左邊那一欄第五個(資料夾圖示,滑過寫「所有檔案」),在任務下面。 @@ -28,6 +29,7 @@ - **放七個檔案**(covers `library-gather`):從手機附上七個檔案送出,再刪掉其中一個存在 AnyBot 裡的那份。指令:`D=$(mktemp -d) && cp cat-1.png "$D/貓一.png" && cp cat-2.png "$D/貓二.png" && printf '# 發布計畫\n\n- 11/22 上線\n' > "$D/release-notes-v4.md" && printf '日期,用量\n11/20,3610\n' > "$D/用量.csv" && printf 'print("hello")\n' > "$D/hello.py" && printf 'x' > "$D/舊的.txt" && (cd "$D" && zip -q 封存.zip hello.py) && for f in 貓一.png 貓二.png release-notes-v4.md 用量.csv hello.py 舊的.txt 封存.zip; do $CTL phone upload '#file' "$D/$f" && $CTL phone wait-text "$f" --in '#chips' 20; done && $CTL phone send 這些檔案先放著 && $CTL phone wait-text 'FAKE-MODEL 回答:這些檔案先放著' --in '#msgs' && SCR=$(sed -n 's/^SCR=//p' target/verify-anybot/current/run.env) && rm -f "$(find "$SCR/data/attachments" -name '*舊的.txt' | head -1)" && $CTL api GET /api/bots/1 --jq '[.messages[].attachments[]?.name]'`。看到:API 列出七個檔名;舊的.txt 在 AnyBot 裡的那份刪掉了。 - **格子、分類、不見了**(covers `library-place`、`library-kinds`、`library-view`、`library-gone`):從側邊欄的資料夾按鈕打開。指令:`$CTL phone stop && $CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot library ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_SIZE=1200x820 ANYBOT_SHOT_FRAMES=520 'ANYBOT_SHOT_CLICK=26,236@440'`。看到:「所有檔案」視窗,左欄「所有檔案 7」「最近 7 天 7」、「Bot」下「驗證小幫手 7」;上面「全部 7、圖片 2、文件 2、程式碼 1、表格 1、其他 1」(沒有影音);三張一排撐滿,兩張貓是縮圖,其他寫 MD、CSV、PY、TXT、ZIP;舊的.txt 灰字、紅字「不見了(檔案已經刪掉或搬走)」。 - **清單、打開**(covers `library-view`、`library-open`、`library-gone`):按「清單」,再按 release-notes-v4.md 那列。指令:`ABV_ALLOW_WINDOW=1 $CTL desktop-shot library-list ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_SIZE=1200x820 ANYBOT_SHOT_FRAMES=500 'ANYBOT_SHOT_CLICK=26,236@440;1033,127@470' && ABV_ALLOW_WINDOW=1 $CTL desktop-shot library-open ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_SIZE=1200x820 ANYBOT_SHOT_FRAMES=540 'ANYBOT_SHOT_CLICK=26,236@440;1033,127@470;450,267@500'`。看到:視窗沒有跳動;每列「名稱……驗證小幫手 · 今天 HH:MM · 31 B」,舊的.txt 右邊紅字「不見了」;release-notes-v4.md 在 AnyBot 的檢視器打開:「發布計畫」「11/22 上線」,右上「用其他 App 打開」、下載、關閉。帳戶選單的「所有檔案…」、搜尋、選某個 Bot:靠自動測試和版面檢查。 +- **手機的所有檔案**(covers `library-phone`):在聊天附一張圖和一個 .md 送出,再到首頁「檔案」。指令:`$CTL phone upload '#file' 圖.png && $CTL phone upload '#file' 行程.md && $CTL phone click '#b-send' && $CTL wait-api /api/bots/1 '.messages[-1].role == "assistant"' && $CTL phone click '[data-back]' && $CTL phone click '#quick [data-q="files"]' && $CTL phone wait '.lib-pic img[src]' && $CTL phone click '[data-lk="doc"]' && $CTL phone click '[data-ln="行程.md"]' && $CTL phone shot library-phone`。看到:「全部 2、圖片 1、文件 1」,圖片在格子裡有縮圖,行程.md 一列「驗證小幫手・剛剛・25 B」,點了打開內容。 - 自動測試:`cargo test app::library_ui::`、`cargo test layout_audit::`(「所有檔案」這一景)。 ## 陷阱 @@ -35,5 +37,4 @@ - 只列聊天裡記下的附件:Bot 在它電腦上做出來、沒有用 `send_file` 交的檔案不在這裡(請它交給你)。刪掉 Bot,它的檔案也不再列。 - 「不見了」只看檔案還在不在,不比內容;內容對不對看檔案卡上的「檔案核對」([deliver](deliver.md))。 - 螢幕電腦上看的是從大腦抓過來的副本:剛連上還沒抓完的暫時顯示「不見了」;大腦那邊刪掉了,這台的副本照樣在。 -- 手機還沒有「所有檔案」,只有每個對話的「資料庫」。 - (驗證)座標是 1200×820 的視窗;視窗大小一換,按鈕位置跟著換。 diff --git a/docs/feature-map/models.md b/docs/feature-map/models.md index a7556d2..47bba12 100644 --- a/docs/feature-map/models.md +++ b/docs/feature-map/models.md @@ -5,9 +5,9 @@ ## 子功能 - `models-providers` 供應商:xAI Grok、OpenAI、ChatGPT 方案、Claude、Google Gemini、OpenRouter、OpenCode Go、Ollama、自訂(OpenAI 相容),每個 Bot 各選各的。 -- `models-where` 在哪裡跑:每家依服務網址標「本機」(localhost)、「區網」(私有位址、tailnet、.local、沒有點的名字)或「雲端」(其他;分不出來也算雲端),本機、區網是綠字。標在:設定 › 模型 每列右邊、標題下一句(在哪台跑、對話和檔案內容會不會送出去);Bot 設定「AI 供應商與模型」;聊天頂端名字後面;空聊天的模型那行;+ 的模型選單每家後面;手機 Bot 設定 › 模型 右邊、選模型時每家的標題、設定 › 模型。螢幕電腦和手機上,「本機」是大腦那台。只看網址、不查名字。 +- `models-where` 在哪裡跑:每家依服務網址標「本機」(localhost)、「區網」(私有位址、tailnet、.local、沒有點的名字)或「雲端」(其他;分不出來也算雲端),本機、區網是綠字。標在:設定 › 模型 每列右邊、標題下一句(在哪台跑、會不會送出去);Bot 設定「AI 供應商與模型」;聊天頂端名字後面;空聊天的模型那行;+ 的模型選單每家後面;手機上同樣這些地方。螢幕電腦和手機上,「本機」是大腦那台。只看網址、不查名字。 - `models-switch` 換模型:資料、記憶、聊天都不用動;換過之後的第一個回答前面,聊天裡留一行「改用 ○○ 回答(上一個回答是 ○○)」(從哪裡換的都一樣;不送給模型;群組聊天不寫)。正在跑的那一輪照舊。換過去的第一個請求先把舊步驟的結果收起(要用再讀);另一個模型的思考內容不會送過去(它會拒絕);模型說過的可讀長度各記各的。 -- `models-fallback` 備用模型(Bot 設定,最多 8 個,依序):Bot 自己的模型額度用完(402、「已達用量上限」)、太忙(429)、金鑰或登入不能用(401、403)、服務出錯(5xx)或連不上,換下一個還沒休息的,從同一步接著做,聊天裡一行「改用 ○○ 繼續(○○:原因,10 分鐘內先不用它)」。不能用的休息 10 分鐘,這段時間新的一輪直接用備用(「改用 ○○ 回答(○○ 剛剛不能用…)」)。對話太長、不支援工具、模型名稱錯不換;沒金鑰的跳過;換過去不用思考模式、快速模型。手機這兩行是星星圖示。 +- `models-fallback` 備用模型(Bot 設定,最多 8 個,依序):Bot 自己的模型額度用完(402、「已達用量上限」)、太忙(429)、金鑰或登入不能用(401、403)、服務出錯(5xx)或連不上,換下一個還沒休息的,從同一步接著做,聊天裡一行「改用 ○○ 繼續(○○:原因,10 分鐘內先不用它)」。不能用的休息 10 分鐘,這段時間新的一輪直接用備用(「改用 ○○ 回答(○○ 剛剛不能用…)」)。對話太長、不支援工具、模型名稱錯不換;沒金鑰的跳過;換過去不用思考和快速模型。手機這兩行是星星圖示。 - `models-bot` 「AI 供應商與模型」(Bot 設定裡):供應商、「模型名稱」、「選擇」、「執行步驟用的模型」、「思考模式」、「備用模型」——欄位名稱在上,說明在名稱旁的「?」。 - `models-thinking` 思考模式:「自動(模型自己決定)」「快速(想得少,回得快)」「平衡」「深入(想得久,較慢)」。執行步驟用的模型:「自動」、「不分開(每一步都用上面的模型)」或指定一個;上面的模型負責想計畫、遇到問題和最後確認,中間的步驟交給快的模型。 - `models-chatgpt` 「ChatGPT 方案」:用 ChatGPT 帳號登入(OpenAI 的 Sign in with ChatGPT),用你 ChatGPT 方案(Plus、Pro、Business…)的額度,不用 API 金鑰。第一次登入時 AnyBot 向 OpenAI 註冊自己,之後重用;登入後 設定 › 模型 寫「已用 ChatGPT 登入(信箱)」,第一次回答會說一次「你正在使用你的 ChatGPT 方案」。 @@ -16,7 +16,7 @@ - 換模型最快:輸入框左邊 + 裡的模型那一行(「選擇這個 Bot 用來思考的模型」),每家一個子選單,沒金鑰的標「(未設定金鑰)」,「其他模型…」打開 Bot 設定自己填。 - 金鑰在「設定 › 模型」;ChatGPT 方案在同一頁按「使用 ChatGPT 繼續」,瀏覽器登入並勾同意。聊天還沒有訊息又沒金鑰時,中間有「設定 (供應商) 的 API 金鑰」直接帶過去;Bot 設定裡是紅字加「前往設定」。 -- 手機:設定 › 模型(每家「可以用」或「未設定」,點進去設金鑰;ChatGPT 方案 →「使用 ChatGPT 繼續…」);聊天標題 › 對話詳細資訊 › 模型(只列可以用的,加「其他模型…」)。 +- 手機:設定 › 模型(每家「可以用」或「未設定」,點進去設金鑰、網址、測試連線、本機的看圖小幫手;ChatGPT 方案 →「使用 ChatGPT 繼續…」);Bot 設定的「備用模型」;聊天標題 › 對話詳細資訊 › 模型(只列可以用的,加「其他模型…」)。 ## 怎麼操作(verify-anybot) diff --git a/docs/feature-map/pages.md b/docs/feature-map/pages.md index 118880c..d1e63c9 100644 --- a/docs/feature-map/pages.md +++ b/docs/feature-map/pages.md @@ -17,7 +17,7 @@ Bot 把要追蹤、整理、比較的事寫成一頁,之後一直更新同一 - 回覆裡的 [標題](page:ID) 連結,和回覆下面的頁面卡片(電腦版一張精簡卡:頁面圖示、標題一次、一行它說什麼——更新過的是「已更新:改了什麼」,否則是現況那句——和一行灰字「種類 · 頁面 · 時間 · 第 N 版」;手機是標題、幾行預覽和「頁面 · 時間 · 已更新」):點一下打開。一個回覆裡每一頁只出一張卡,在最後存那一頁的步驟下面(被退回再存、或存了又更新,都不會重複);沒存成的(別的 Bot 的頁面被擋、被退回那一次)不出卡。 - 右側面板的「資料庫」分頁,最上面的「頁面」:這個 Bot 的頁面,最近改過的在前面。 - 打開的頁面下方左邊「版本紀錄」(看舊版時有「回到最新版」)和「刪除」(按兩次),右邊「複製」(Markdown)、「存成檔案」(存成 .md 到「下載」)、「完成」。 -- 手機:首頁上面一排的「頁面」列出所有頁面;聊天裡的頁面卡片;打開的頁面的「⋯」有「複製 Markdown」「其他版本」,一條細線下面才是「刪除頁面」。 +- 手機:首頁上面一排的「頁面」列出所有頁面;聊天裡的頁面卡片;打開的頁面的「⋯」有「複製 Markdown」「存成檔案(.md)」「其他版本」,一條細線下面才是「刪除頁面」。 ## 怎麼操作(verify-anybot) diff --git a/docs/feature-map/pageview.md b/docs/feature-map/pageview.md index 0de213b..f99f57d 100644 --- a/docs/feature-map/pageview.md +++ b/docs/feature-map/pageview.md @@ -9,8 +9,8 @@ - `pageview-steps` ```steps 進度:[x] 完成、[>] 進行中、[ ] 還沒到。 - `pageview-chart` ```chart 圖表(bar/line/pie,可以多系列):長條圖自動由大到小排序,月份/年份等自有順序的標籤不排;單系列把數字直接標在圖上不畫 y 軸;多條線在線尾標系列名;長條的 y 軸一定從 0 開始,折線離 0 很遠(最小值比資料的高低差還大,例如 1,649–1,796)時照資料範圍畫、不從 0 開始;圖下附數據表(名稱靠左、數字靠右、每欄只有內容那麼寬,太寬就左右捲動,不會把頁面撐寬;超過 6 列時收成「▸ 數據 · N 筆」,點了展開);第一行可以是「圖型 標題」、只寫圖型(bar/line/pie 或 長條/折線/圓餅)或只寫標題,`#` 開頭是註解,`|---|` 分隔列略過,少填的格子當 0;手機也畫原生圖,讀法和樣式相同:照手機寬度畫、字不縮小,折線和多系列長條有 y 軸數字,只有一項的圓餅是整圓,圖例再多項都畫得到。 - `pageview-callout` 提示框:`> [!NOTE]`/`[!TIP]`/`[!WARNING]`/`[!IMPORTANT]`。 -- `pageview-desktop` 打開的頁面像一份文件(電腦和手機同一套):標題宋體粗體 28,下面一行小字作者、「更新於」、第幾版和「這一版更新了:…」;一行現況(summary)是開頭段落、不加框;結論(verdict)是淡底的「結論」提示框;kpis 是只有細框的數字卡(每張三行疊著:標籤、數字、變化;四張並排每張太窄時一排兩張;字太長以 … 結尾,滑過看全文)。頁面視窗不會被內容撐寬:太寬的表格在閱讀欄裡左右捲動,其他太寬的東西在視窗邊緣切掉,標題列的 × 一直在右上角。有 3 個以上的標題時有一行「▸ 目錄 · N 節」,點開才是標題清單和小搜尋框(⌘F 直接展開)。內文宋體 16、行距 1.7,閱讀欄最寬 680。 -- `pageview-phone` 手機打開的頁面:標題宋體粗體大字,下面一行小字作者和「更新於」;現況、kpis、結論同上;有 3 個以上的標題時多一行「目錄 · N 節」,點開是標題清單,點一個捲到那裡(沒有搜尋框)。內文宋體 16px、行距寬;表格沒有直線和斑馬紋、數字欄靠右;提示框同一種淡底,只有圖示依種類上色。 +- `pageview-desktop` 打開的頁面像一份文件(電腦和手機同一套):標題半粗體 28,下面一行小字作者、「更新於」、第幾版和「這一版更新了:…」;一行現況(summary)是開頭段落、不加框;結論(verdict)是淡底的「結論」提示框;kpis 是只有細框的數字卡(每張三行疊著:標籤、數字、變化;四張並排每張太窄時一排兩張;字太長以 … 結尾,滑過看全文)。頁面視窗不會被內容撐寬:太寬的表格在閱讀欄裡左右捲動,其他太寬的東西在視窗邊緣切掉,標題列的 × 一直在右上角。有 3 個以上的標題時有一行「▸ 目錄 · N 節」,點開才是標題清單和小搜尋框(⌘F 直接展開)。內文16(跟介面同一種字)、行距 1.7,閱讀欄最寬 680。 +- `pageview-phone` 手機打開的頁面:標題半粗體大字,下面一行小字作者和「更新於」;現況、kpis、結論同上;有 3 個以上的標題時多一行「目錄 · N 節」,點開是標題清單,點一個捲到那裡(沒有搜尋框)。內文 16px(跟介面同一種黑體)、行距寬;表格沒有直線和斑馬紋、數字欄靠右;提示框同一種淡底,只有圖示依種類上色。 ## 使用者怎麼到 @@ -27,7 +27,7 @@ - **區塊**(covers `pageview-details`、`pageview-stats`、`pageview-steps`、`pageview-callout`、`pageview-phone`):請 Bot 寫一頁各種區塊和結論,點卡片打開,點「目錄」和「證據」。指令:`$CTL phone send '[[call write_page {"title":"區塊","kind":"decision","verdict":"先別買","content":"## 數字\n\u0060\u0060\u0060stats\n訂單 | +3\n退貨 | -2%\n評分 | -\n\u0060\u0060\u0060\n## 進度\n\u0060\u0060\u0060steps\n[x] 審查 | 開過兩次會\n[>] 路測\n[ ] 開放\n\u0060\u0060\u0060\n## 細節\n\u0060\u0060\u0060details 證據\n- 七月會議\n\u0060\u0060\u0060\n> [!WARNING] 先別花錢"}]]' && $CTL phone click '.pcard[data-page="1"]' && $CTL phone wait '.stats .v.up' && $CTL phone wait '.stats .v.dn' && $CTL phone wait 'ul.steps li.now' && $CTL phone wait '.call.k-warning' && $CTL phone wait-text '目錄 · 3 節' --in '#page' && $CTL phone shot pageview-blocks && $CTL phone click 'details.toc summary' && $CTL phone click '[data-toc]' --text 細節 && $CTL phone click 'details.dt summary' --text 證據 && $CTL phone wait-text 七月會議 --in '#page' && $CTL phone shot pageview-open && $CTL api GET /api/pages/1 --jq '{verdict, body}'`。看到:「結論 先別買」提示框;+3 綠、-2% 紅、單獨的 - 不上色;✓ 審查、進行中的路測、還沒到的開放;「先別花錢」警告框;「目錄 · 3 節」點開是三個標題;「證據」原本收著,點了才看到「七月會議」。 - **圖表**(covers `pageview-chart`、`pageview-phone`):回聊天請它寫一頁四張圖,打開看。指令:`$CTL phone click '[data-back]' && $CTL phone send '[[call write_page {"title":"圖表","content":"\u0060\u0060\u0060chart\nbar 水果\n香蕉 | 3\n蘋果 | 9\n芒果 | 5\n\u0060\u0060\u0060\n\u0060\u0060\u0060chart\n長條 月份\n1月 | 3\n2月 | 9\n3月 | 5\n\u0060\u0060\u0060\n\u0060\u0060\u0060chart\nline 功率\n# 瓦\n1 | 1649\n2 | 1700\n3 | 1796\n4 | 1720\n5 | 1680\n6 | 1750\n7 | 1710\n\u0060\u0060\u0060\n\u0060\u0060\u0060chart\npie\n全部 | 5\n\u0060\u0060\u0060"}]]' && $CTL phone click '.pcard[data-page="2"]' && $CTL phone wait-text '數據 · 7 筆' --in '#page' && $CTL phone shot pageview-charts && $CTL phone text '#page'`。看到:四張原生圖,字跟內文差不多大;水果長條排成蘋果、芒果、香蕉,月份照 1、2、3 月;單系列數字標在條上;功率折線 y 軸從 1,6xx 起、看得出起伏,數據表收成「▸ 數據 · 7 筆」;只寫 pie 也畫得出來,一項是整圓。 -- **桌面的頁面視窗**(covers `pageview-desktop`、`pageview-chart`):指令:要開視窗——`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot pageview ANYBOT_SHOT_VIEW=page`。看到:示範頁像一份文件:宋體標題、作者和「更新於」、數字卡、進度、警告框、折線和圓餅、「▸ 目錄 · N 節」(點開有搜尋框,⌘F),× 在右上角;加 `ANYBOT_SHOT_THEME=dark` 時頁面視窗也不超出畫面。data 頁四張數字卡排成兩排、十欄寬表格在閱讀欄裡捲動:沒同意就靠 `cargo test layout_audit::`(它畫的就是這種頁)。 +- **桌面的頁面視窗**(covers `pageview-desktop`、`pageview-chart`):指令:要開視窗——`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot pageview ANYBOT_SHOT_VIEW=page`。看到:示範頁像一份文件:半粗體標題、作者和「更新於」、數字卡、進度、警告框、折線和圓餅、「▸ 目錄 · N 節」(點開有搜尋框,⌘F),× 在右上角;加 `ANYBOT_SHOT_THEME=dark` 時頁面視窗也不超出畫面。data 頁四張數字卡排成兩排、十欄寬表格在閱讀欄裡捲動:沒同意就靠 `cargo test layout_audit::`(它畫的就是這種頁)。 - 自動測試:`cargo test pages::`(`stat_trend_reads_arrows_and_both_minus_signs`、`a_line_far_from_zero_fits_its_data_and_bars_start_at_zero`)、`cargo test layout_audit::`。 ## 陷阱 diff --git a/docs/feature-map/phone.md b/docs/feature-map/phone.md index d71d8c7..c65c8fd 100644 --- a/docs/feature-map/phone.md +++ b/docs/feature-map/phone.md @@ -4,13 +4,13 @@ ## 子功能 -- `phone-pages` 頁面:Bot 清單(分區、工作中/等你)、聊天(附檔、拍照、語音輸入、插話、停止;叫醒 Bot 的訊息上方標是什麼叫醒的:目標、例行任務、觸發、訊息管道、來自其他 Bot、監看)、允許請求卡片(「一律允許」「允許一次」、「這輪都准」(智慧模式,一直開著;它是主按鈕)、「拒絕」、「全部允許,之後直接操作」;卡片太高時卡在內面自己捲,輸入框不會被頂出螢幕)、問題卡、「需要處理」與接管、Bot 設定、例行任務(詳細頁有最近幾次執行和送出證據)、頁面、記憶、檔案預覽、Bot 的電腦畫面、設定(一般、模型、權限、整合、電腦、保險庫、手機與帳號、更新,能改的比電腦少;開著的設定頁跟著電腦那邊的改變重讀,不用重新整理;直接連線只能收緊、不能放寬,見 [autonomy](autonomy.md))、傳送到其他裝置。智慧模式一直開著,輸入列沒有它的晶片。 +- `phone-pages` 頁面:Bot 清單(分區、工作中/等你)、聊天(附檔、拍照、語音輸入、插話、停止;叫醒 Bot 的訊息上方標是什麼叫醒的;各 Bot 自己的草稿;程式碼塊的「複製」;流程圖畫成圖)、允許請求卡片(「一律允許」「允許一次」、「這輪都准」(智慧模式,一直開著;它是主按鈕)、「拒絕」、「全部允許,之後直接操作」;卡片太高時卡在內面自己捲,輸入框不會被頂出螢幕)、問題卡、「需要處理」與接管、Bot 設定、例行任務(詳細頁有最近幾次執行和送出證據)、頁面、記憶、檔案預覽、Bot 的電腦畫面、設定(一般、個人資料與用量、模型、權限、整合、電腦、保險庫、語音、手機與帳號、更新;開著的設定頁跟著電腦那邊的改變重讀,不用重新整理;直接連線只能收緊、不能放寬,見 [autonomy](autonomy.md))、傳送到其他裝置。智慧模式一直開著,輸入列沒有它的晶片。 - `phone-cards` 手機上的卡(允許、需要處理、問題卡)只答它畫出來的那一張:那張已經在電腦或另一支手機上回答、被停止、或換成下一張時,按了不算,聊天裡寫「手機上的回答沒有用上…」;開了很久沒重新整理的舊頁面也一樣。螢幕電腦上的卡也是;比大腦舊的螢幕電腦答不了任何卡,要在那台 設定 › 更新 換新版(重新整理沒用)。支線的卡沒用上時,寫在主線的聊天。 -- `phone-look` 長相(和電腦版同一份設計規格:字級、間距、圓角都是同一組數字):Bot 的回答不放在泡泡裡,像文件一樣直接排在畫面上,用宋體(思源宋體,沒有就用系統的宋體)、16px、行距寬;裡面的表格只有橫向細線、數字欄靠右,提示框([!NOTE] 等)同一種淡底、只有圖示依種類上色,程式碼是淡底圓角塊。你自己的訊息(泡泡)和所有按鈕、清單、設定用黑體。手機沒有字型選項。 +- `phone-look` 長相(和電腦版同一份設計規格:字級、間距、圓角都是同一組數字):Bot 的回答不放在泡泡裡,像文件一樣直接排在畫面上,跟介面同一種字(iPhone 是 SF Pro 加蘋方)、16px、行距寬;裡面的表格只有橫向細線、數字欄靠右,提示框([!NOTE] 等)同一種淡底、只有圖示依種類上色,程式碼是淡底圓角塊。標題用半粗體。手機沒有字型選項。 - `phone-colors` 顏色跟電腦版一樣:電腦上 設定 › 一般 › 外觀 的主題(淺色/深色/跟隨系統)、底色、強調色、對比,手機照著穿;手機自己的「外觀」可以選「跟著電腦」(預設)、「跟著手機」、「淺色」、「深色」。狀態列的顏色跟著畫面。舊版的電腦沒送顏色時,手機用內建的「紙」。 - `phone-claude` 像 Claude 的手機 App:上面一條簡單的標題列(Bot 名稱,第二行是它在做什麼或用哪個模型),輸入框是底部一張圓角卡片,回答下面只有時間和複製/重新產生/⋯;按鈕和點的地方至少 44px;清單每列的說明只有一行(太長以 … 結尾);顏色少,強調色只用在連結、選取和新訊息的點。 - `phone-net` 網路慢或斷線都不擋操作:存過這台電腦的資料,打開 App 就用上次的內容進去,不等網路,連上後只補變了的;浮著提示「離線中:顯示的是上次的內容」,拿到就消失。只有第一次(還沒有這台的資料)停在連線畫面:打開 App 時的頭像留在正中間呼吸、外圈漾開,不顯示文字(讀螢幕軟體唸「正在連線」;減少動態時不動),第一份狀態到手才進去。用帳號連、那台不在線上時留在它上次的內容裡,不換到別台。進去之後斷線:浮「連線中斷,正在重新連線…」,自己重試,回到前景或網路恢復時立刻重連。設定、詳細、例行任務先畫手上有的,背景讀新的;要改的先讀到最新的。傳訊息不等網路:按下就出現在聊天裡;連不上標「等連線後送出(點一下拿回來)」,存手機排隊(關 App 也還在),連上後照順序自己送、不限時間,同一則只送一次;點一下連同附件拿回輸入框;連不上時選的附件也排隊。大腦拒收的才標「沒送出,點一下拿回來重送」。從通知打開時按的允許/拒絕等連上才送。只傳有變的部分、文字壓縮;Bot 回答中手機每秒最多更新一次聊天(見 [chat](chat.md) 的開聊天分頁)。頁面和圖示存在手機上:打開直接用,背景問一次換版沒;換了,還在連線畫面就重新載入,已進去就等退到背景、手上沒東西(沒打字、附件、排隊、錄音、選單)才換;重新整理一定先問伺服器。上次的狀態、看過的聊天(合計最多 12 個)、詳細資料、設定、排隊的訊息每台電腦各自存在這個網址的儲存空間,登出(或登入失效)全部清掉。 -- `phone-app` 像 App 一樣:加入主畫面後全螢幕、沒有網址列(瀏海、動態島、底部手勢條、橫放都避開);首頁會提示「把 AnyBot 裝成 App」(Android 直接安裝,iPhone 教你加入主畫面,可以關掉);換畫面會左右滑動;iPhone 主畫面 App 從左邊緣往右滑回上一頁。 +- `phone-app` 像 App 一樣:加入主畫面後全螢幕、沒有網址列(避開瀏海和手勢條);首頁會提示「把 AnyBot 裝成 App」(Android 直接安裝,iPhone 教你加入主畫面,可以關掉);換畫面會左右滑動;iPhone 主畫面 App 從左邊緣往右滑回上一頁。 ## 使用者怎麼到 @@ -28,11 +28,11 @@ - **還沒連上就在外面**(covers `phone-net`):打開頁面,等它自己連上。指令:`$CTL phone open --listed && $CTL phone wait-gone '#v-gate.on' 20 && $CTL phone wait '#v-login.on'`。看到:連上之後停在登入,不是 Bot 清單;登入後才進得去。 - **清單和選單**(covers `phone-pages`、`phone-claude`):看首頁,打開 Bot 那列的「⋯」。指令:`$CTL phone wait '.row[data-bot="1"]' && $CTL phone click '[data-botmenu="1"]' && $CTL phone wait-text 對話詳細資訊 --in '#sheet-in' && $CTL phone shot phone-menu && $CTL phone click '#sheet-in .opt' --text 釘選 && $CTL wait-api '/api/state?since=0' '.bots[0].pinned == true'`。看到:一列一個 Bot(第二行一行說明);選單有「對話詳細資訊」「釘選」「移至分區」「更多…」;釘選後大腦那邊 pinned。 -- **聊天**(covers `phone-pages`、`phone-look`、`phone-claude`):打開 Bot、傳一句。指令:`$CTL phone click '.row[data-bot="1"]' && $CTL phone send '你好,從手機傳的' && $CTL phone wait-text 'FAKE-MODEL 回答:你好,從手機傳的' --in '#msgs' && $CTL phone shot phone-chat`。看到:標題列是名稱和 fake-model;你的話是泡泡,回答直接排在畫面上(宋體)、下面只有時間和圖示;輸入框是底部圓角卡片。 +- **聊天**(covers `phone-pages`、`phone-look`、`phone-claude`):打開 Bot、傳一句。指令:`$CTL phone click '.row[data-bot="1"]' && $CTL phone send '你好,從手機傳的' && $CTL phone wait-text 'FAKE-MODEL 回答:你好,從手機傳的' --in '#msgs' && $CTL phone shot phone-chat`。看到:標題列是名稱和 fake-model;你的話是泡泡,回答直接排在畫面上、下面只有時間和圖示;輸入框是底部圓角卡片。 - **全部允許,之後直接操作**(covers `phone-pages`、`phone-cards`):請 Bot 改名,在卡片上按「全部允許,之後直接操作」›「打開」,再按「允許」。指令:`$CTL phone send '請改名 [[call update_bot {"name":"手機改的名字"}]]' && $CTL phone click '#ask [data-direct]' && $CTL phone click '#sheet-in .opt' --text 打開 && $CTL phone wait-text '只能收緊、不能放寬' && $CTL phone wait '#ask .ask' && $CTL phone click '#ask button[data-a="once"]' && $CTL phone wait-text 手機改的名字 --in '#isl-name'`。看到:直接連線打不開直接操作([autonomy](autonomy.md)),卡片留著;按「允許」才改名。 - **舊頁面的回答不算**(covers `phone-cards`):卡片在等時,一個說不出是哪張卡的回答進來。指令:`$CTL phone send '再改 [[call update_bot {"name":"不該出現的名字"}]]' && $CTL wait-api '/api/state?since=0' '.approvals | length == 1' && $CTL api POST /api/bots/1/answer '{"answer":"once"}' && $CTL phone wait-text '手機上的回答沒有用上' --in '#msgs' && $CTL phone click '#ask button[data-a="reject"]' && $CTL phone wait-gone '#ask .ask' && $CTL state '.bots[0].name'`。看到:「手機上的回答沒有用上:這個頁面太舊…」,卡片還在;拒絕後名字還是「手機改的名字」。 - **顏色跟著電腦**(covers `phone-colors`):請 Bot 把電腦換成深色,重新整理;再把這支手機選「淺色」。指令:`$CTL phone send '換深色 [[call update_settings {"theme":"dark"}]]' && $CTL phone wait-text '主題 → dark' --in '#msgs' && $CTL phone open --listed && $CTL phone wait 'html[data-theme="dark"]' && $CTL phone shot phone-dark && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 這支手機的外觀 && $CTL phone click '#sheet-in .opt' --text 淺色 && $CTL phone wait 'html[data-theme="light"]'`。看到:外觀「跟著電腦」時變深色;選「淺色」就只有這支手機變回淺色。 -- **設定頁**(covers `phone-pages`):帳戶選單 › 設定,再點「保險庫」。指令:`$CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone wait '[data-go="updates"]' && $CTL phone shot phone-settings && $CTL phone click '[data-go="vault"]' && $CTL phone wait-text '只在電腦上的 AnyBot 管理'`。看到:一般、模型、權限、整合、電腦、保險庫、手機與帳號、更新;保險庫只有一句說明(手機看不到密碼)。 +- **設定頁**(covers `phone-pages`):帳戶選單 › 設定,再點「保險庫」。指令:`$CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone wait '[data-go="updates"]' && $CTL phone shot phone-settings && $CTL phone click '[data-go="vault"]' && $CTL phone wait-text '只在電腦上的 AnyBot 管理'`。看到:一般、個人資料與用量、模型、權限、整合、電腦、保險庫、語音、手機與帳號、更新;保險庫只有一句說明(手機看不到密碼)。 - **裝成 App 的提示**(covers `phone-app`):回首頁,看「把 AnyBot 裝成 App」,按 ✕ 關掉。指令:`$CTL phone open --listed && $CTL phone wait-text '把 AnyBot 裝成 App' && $CTL phone shot phone-install && $CTL phone click '#install-no' && $CTL phone wait-gone '#install-go' && $CTL api --no-auth GET /manifest.webmanifest --jq '.display'`。看到:提示和「安裝」(Chrome 給了安裝提示;iPhone 是「怎麼做」);按 ✕ 就不見了;manifest 的 display 是 standalone。 - **斷線又回來**(covers `phone-net`):打開 Bot,把大腦關掉,看提示;斷線時傳一句,再把大腦開回來。指令:`$CTL phone click '.row[data-bot="1"]' && $CTL stop && $CTL phone wait '#net.on' 30 && $CTL phone send '斷線時傳的' && $CTL phone wait-text '等連線後送出' --in '#msgs' 30 && $CTL phone shot phone-offline && $CTL serve && $CTL phone wait-gone '#net.on' 40 && $CTL phone wait-text 'FAKE-MODEL 回答:斷線時傳的' --in '#msgs' 60 && $CTL phone shot phone-back && $CTL model 'select(.tools > 0 and ((.user // "") | startswith("斷線時傳的"))) | .t' | grep -c '^"20'`。看到:標題列下方「連線中斷,正在重新連線…」,沒有另外跳「連不上」的提示,標題沒被蓋住;那句馬上出現在聊天裡,下面寫「等連線後送出(點一下拿回來)」;大腦回來後提示自己消失(沒有重新整理),斷線時傳的那句自己送到、有回答;最後印 `1`:重送了幾次,Bot 都只收到一次。 - **沒網路也打得開**(covers `phone-net`):看過聊天、回首頁後把大腦關掉,重新打開頁面;打開聊天傳一句,再重新打開一次,最後把大腦開回來。指令:`$CTL phone click '[data-back]' && $CTL stop && $CTL phone open --listed && $CTL phone wait '.row[data-bot="1"]' 3 && $CTL phone wait-text '離線中' --in '#net' 15 && $CTL phone click '.row[data-bot="1"]' && $CTL phone wait-text 'FAKE-MODEL 回答:斷線時傳的' --in '#msgs' 2 && $CTL phone send '要拿回來的' && $CTL phone click '.m.sending.held' && $CTL phone wait-gone '.m.sending' 5 && $CTL phone js 'document.querySelector("#input").value=""' && $CTL phone send '離線時傳的' && $CTL phone wait-text '等連線後送出' --in '#msgs' 30 && $CTL phone open --listed && $CTL phone click '.row[data-bot="1"]' && $CTL phone wait-text '離線時傳的' --in '#msgs' 3 && $CTL phone shot phone-kept && $CTL serve && $CTL phone wait-text 'FAKE-MODEL 回答:離線時傳的' --in '#msgs' 90`。看到:大腦關著也在 3 秒內看到 Bot 清單(不是連線畫面),提示「離線中:顯示的是上次的內容」;聊天是上次的內容;點「要拿回來的」它就回到輸入框;離線傳的那句關掉重開還在,大腦回來後自己送到、有回答。 diff --git a/docs/feature-map/profile.md b/docs/feature-map/profile.md index 52ba8ad..12d3da1 100644 --- a/docs/feature-map/profile.md +++ b/docs/feature-map/profile.md @@ -13,7 +13,7 @@ - Bot 選單(右鍵側邊欄的 Bot,或聊天右上角「更多」)›「編輯 Bot…」;或在右側面板點 Bot 的大頭像。視窗第一張卡是「Bot 資料」(頭像、名稱、描述),和下面的卡片同一種排版。 - 在聊天裡請 Bot 改自己(「把你的檔案與指令能力關掉」)。 -- 手機:聊天標題 › 對話詳細資訊 › 右上角「Bot 設定」,沒有自訂色盤([phone](phone.md))。 +- 手機:聊天標題 › 對話詳細資訊 › 右上角「Bot 設定」,沒有自訂色盤([phone](phone.md));「AI 與電腦」有「執行步驟用的模型」(自動/不分開/同一家的其他模型)和「思考模式」(自動、快速、平衡、深入),跟電腦一樣;技能標題旁「全選/全不選」;模型可讀長度有 400K;「備用模型」「起始資料夾」、頭像的「自訂顏色」(手機自己的選色器)、「語音」(朗讀每個回答、聲音、速度、語言)。 ## 怎麼操作(verify-anybot) diff --git a/docs/feature-map/schedule.md b/docs/feature-map/schedule.md index 15456ba..c691efe 100644 --- a/docs/feature-map/schedule.md +++ b/docs/feature-map/schedule.md @@ -10,10 +10,11 @@ - `schedule-card` 點任何一筆打開卡片:哪個 Bot、那一次的時間和狀態、怎麼重複、最近一次怎麼樣、要它做什麼;按鈕「打開聊天」「立即執行」「暫停/繼續」。工作流的是「打開工作流」「立即執行」(在螢幕電腦上按,交給大腦執行)。 - `schedule-new` 「+ 新增例行任務」:回到那個 Bot 的聊天,輸入框先放好「每天早上 9 點幫我」,接著說要做什麼;Bot 用 `create_routine` 設好,日程上就出現。 +- `schedule-phone` 手機的日程:最上面「即將執行」(每件一行:頭像、名字、怎麼重複、下次的日子和時間),接著三天前到七天後一天一組(「今天・11月22日(日)」,沒事的那天只有今天寫「這一天沒有排定的事」),每列時間、名字、Bot、怎麼重複,跑過的右邊 ✓ 完成/✗ 失敗/停止了,暫停的變淡;打開時捲到今天。點例行任務打開它的卡,點工作流打開那個工作流。手按的執行一樣不放。 ## 使用者怎麼到 - 側邊欄最左邊那一欄第三個(日曆圖示,滑過寫「日程」),在工作流和任務中間;再按一次、按那一欄的「聊天」、或左上「‹ 聊天」都回到聊天;在側邊欄點別的 Bot 也回到聊天。 -- 手機沒有日程:在聊天裡問 Bot「你有哪些例行任務」,它用 `list_routines` 回答(只有它自己的)。 +- 手機:首頁上面一排的「日程」(`schedule-phone`);或在聊天裡問 Bot「你有哪些例行任務」,它用 `list_routines` 回答(只有它自己的)。 ## 怎麼操作(verify-anybot) @@ -27,6 +28,7 @@ - **從側邊欄打開日程**(covers `schedule-views`、`schedule-entries`、`schedule-coming`):按側邊欄的日曆。指令:要開視窗——`ABV_ALLOW_WINDOW=1 $CTL desktop-shot schedule-open ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_SIZE=1200x820 ANYBOT_SHOT_FRAMES=520 'ANYBOT_SHOT_CLICK=26,152@440'`。看到:「日程」,週看法這一週,今天那格強調色框、裡面沒有剛才立即執行的那次,之後每天 08:30 圓點「競品掃描」;工作日 09:00「晨間簡報」從週一起;右上沒有時區(跟這台一樣);下面「即將執行」競品掃描、晨間簡報各一行,照時間排、有 Bot 的頭像。 - **月和日**(covers `schedule-views`、`schedule-entries`):指令:要開視窗——`ABV_ALLOW_WINDOW=1 $CTL desktop-shot schedule-month ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_VIEW=schedule ANYBOT_SHOT_TAB=month ANYBOT_SHOT_SIZE=1400x900 ANYBOT_SHOT_FRAMES=520 && ABV_ALLOW_WINDOW=1 $CTL desktop-shot schedule-day ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_VIEW=schedule ANYBOT_SHOT_TAB=day ANYBOT_SHOT_SIZE=1400x900 ANYBOT_SHOT_FRAMES=520`。看到:月:週一到週日的格子,這個月以外的日期灰字,工作日的格子兩筆(08:30、09:00),今天之前沒跑過的日子是空的;日:今天寫「這一天沒有排定的事。」(立即執行的不放),下面照樣是即將執行。 - **卡片和暫停**(covers `schedule-card`、`schedule-coming`):按即將執行第一筆,再按卡片上的「暫停」。指令:要開視窗——`ABV_ALLOW_WINDOW=1 $CTL desktop-shot schedule-card ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_VIEW=schedule ANYBOT_SHOT_SIZE=1400x900 ANYBOT_SHOT_FRAMES=560 'ANYBOT_SHOT_CLICK=700,439@530' && ABV_ALLOW_WINDOW=1 $CTL desktop-shot schedule-paused ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_VIEW=schedule ANYBOT_SHOT_SIZE=1400x900 ANYBOT_SHOT_FRAMES=580 'ANYBOT_SHOT_CLICK=700,439@530;705,558@545' && $CTL state '[.bots[0].routines[] | {title, paused}]'`。看到:卡片「競品掃描」:驗證小幫手的頭像和名字、「明天 08:30(啟用中)」「每天 08:30」、最近一次完成、「找三則競品新聞」,按鈕「打開聊天、立即執行、暫停」;暫停後之後的競品掃描變灰帶 ‖,即將執行只剩晨間簡報;state 裡競品掃描 paused 是 true。 +- **手機的日程**(covers `schedule-phone`):先照 [workflow](workflow.md) 建好每天 09:00 的「Threads 早報」並在手機按過一次執行。指令:`$CTL phone click '#quick [data-q="schedule"]' && $CTL phone wait-text '即將執行' --in '#list' && $CTL phone shot schedule-phone && $CTL phone click '[data-sch^="workflow:1"]' && $CTL phone wait '.wf-steps'`。看到:即將執行「Threads 早報・明天 09:00」;今天「這一天沒有排定的事」(手機按的那次不在上面);明天起每天 09:00 一列;點了打開那個工作流。 - 自動測試:`cargo test schedule`、`cargo test layout_audit::`(「日程」週、月、日三景)。 ## 陷阱 diff --git a/docs/feature-map/settings.md b/docs/feature-map/settings.md index c591d89..0e19406 100644 --- a/docs/feature-map/settings.md +++ b/docs/feature-map/settings.md @@ -1,6 +1,6 @@ # 設定總覽 -設定視窗有八個分頁(下面由上到下),另外每個 Bot 有自己的「Bot 設定」視窗。這份是地圖:每一項一句話,細節到括號裡那一區看。 +設定視窗有九個分頁(下面由上到下,每個前面一個圖示:齒輪、人、星光、格子、螢幕、盾牌、保險庫、麥克風、雲),另外每個 Bot 有自己的「Bot 設定」視窗。這份是地圖:每一項一句話,細節到括號裡那一區看。 ## 子功能 @@ -11,10 +11,10 @@ - Bot:時區,例行任務和提醒用([routines](routines.md))。 - 帳戶:「登入」或「管理帳戶」打開「手機與帳號」頁;資料放在哪。 - `settings-whose` 左下角(你的名字):名字下面一行寫 Bot 在哪一台——「這台電腦」,或「大腦「名字」」(綠點連得到、灰點連不到)。點一下開「Bot 在哪一台」選單:「這台電腦(這台的名字)」、帳號裡每台可以當大腦的電腦(現在用的打勾,離線的灰、不能點),點一下就換——跟「手機與帳號」頁大腦那一欄的「改用它當大腦」「改回用這台自己的 Bot」一樣([account](account.md));沒登入帳號多一行「登入帳號,才能換到別台大腦…」;分隔線下「所有檔案…」([library](library.md))、「個人資料與用量…」、「設定…」(⌘, 也可以)。 -- `settings-me` 「個人資料」:名字、過去一年有幾個活躍日;五張卡——Token(過去一年,不算快取命中)、最活躍的一天、訊息、目前連續天數(今天還沒用不算斷)、最長連續天數;「活動」一年的熱度格子(一週一欄、越忙顏色越深,滑過看日期、token、訊息數);「用量」選 7 天/30 天/90 天/一年:token(新讀、寫、快取讀到)、呼叫次數、花費(模型服務回報的,沒回報寫「未定價」,不是 0 元)、每天一條、依模型、依 Bot。左下角選單也有「個人資料與用量…」。螢幕電腦上算的是大腦的(向大腦要);手機和螢幕的路是 `api/stats`、`api/sync/stats`(擁有者才有)。 +- `settings-me` 「個人資料」:名字、過去一年有幾個活躍日;一條沒有框的數字列——Token・一年(不算快取命中)、訊息・一年、連續使用(今天還沒用不算斷)、最長連續,細節在滑過;「活動」一年的熱度格子(一週一欄、越忙顏色越深,滑過看日期、token、訊息數),旁邊一行「最活躍:日期・token」;「用量」選 7 天/30 天/90 天/一年:一個大數字 token(滑過看新讀、寫、快取讀到)、呼叫次數和花費(模型服務回報的,沒回報寫「未定價」,不是 0 元)、每天一條長條,再切「依模型」(一條彩色比例條,每個模型有服務的圖案)或「依 Bot」(頭像和長條),各寫 token 和百分比。左下角選單也有「個人資料與用量…」。手機 設定 ›「個人資料與用量」同一套(擁有者才有)。螢幕電腦上算的是大腦的(向大腦要);手機和螢幕的路是 `api/stats`、`api/sync/stats`(擁有者才有)。 - `settings-search` 「搜尋設定…」(左欄最上面):打字時頁面清單換成符合的設定(最多 12 個),標題開頭相符的在前,再來標題包含的,再來所在區塊或別的說法(「深色」找到「主題」、「billing」找到「用量」;模型供應商用名字找);每個下面寫在哪(「一般 › Bot」)。點一個或按 Enter 拿第一個:換到那一頁(整合的小分頁、市集、收起來的「更多外觀設定」會跟著打開)、捲到那一列,外框用強調色亮一下(約 2 秒淡掉);Esc 清空。 - `settings-account` 「手機與帳號」頁(從 一般 › 帳戶 進去,[account](account.md)):「AnyBot 帳號」(登入、備份、還原)、大腦和「加一台電腦」([computers](computers.md))、「同一個網路直接連」、「手機可以做什麼」、「直接連線的裝置」、「分享給團隊」([team](team.md))、「帳號裡的電腦」。 -- `settings-models` 「模型」:每家 AI 供應商的 API 金鑰、服務網址、新 Bot 預設模型、「測試連線並取得模型清單」([models](models.md));本機或區網的供應商多「看不到圖時,請雲端模型看截圖和附件」(預設關,[chat](chat.md))。「ChatGPT 方案」沒有金鑰和網址欄,改成「ChatGPT 帳號」:登入狀態、「使用 ChatGPT 繼續」「登出」「換帳號」「打開登入頁」「管理用量」;連到別台大腦時多一格貼回登入網址和「完成登入」。 +- `settings-models` 「模型」:先是每家 AI 供應商一塊圖塊(自己的圖案、名字、「可以用」或「還沒設定」、雲端/本機),點一塊進去、上面「‹ 模型」回來;裡面是 API 金鑰、服務網址、新 Bot 預設模型、「測試連線並取得模型清單」([models](models.md));本機或區網的供應商多「看不到圖時,請雲端模型看截圖和附件」(預設關,[chat](chat.md))。「ChatGPT 方案」沒有金鑰和網址欄,改成「ChatGPT 帳號」:登入狀態、「使用 ChatGPT 繼續」「登出」「換帳號」「打開登入頁」「管理用量」;連到別台大腦時多一格貼回登入網址和「完成登入」。 - `settings-integrations` 「整合」,三個小分頁: - 訊息管道:Slack、Discord、Telegram、Teams…([channels](channels.md))。 - 連接器:「連接器(MCP)」和「已加入」清單(每列進到它自己的頁:設定、工具、移除);「瀏覽市集」頁(「連接器市集」、公用市集)、「新增連接器」頁([connectors](connectors.md))。 @@ -31,7 +31,7 @@ - `settings-voice` 「語音」:「語音服務」清單,「聽(語音轉文字)」和「說(朗讀)」各選一個服務([appearance](appearance.md))。 - `settings-updates` 「更新」:「版本」、「自動更新」(你離開時換新版)、「園丁報告」、「待改進」清單([garden](garden.md))、「重新啟動」。 - `settings-bot` Bot 設定(每個 Bot 一個視窗,[profile](profile.md)):「Bot 資料」(名稱、描述;個人檔案、能力、「技能」,群組沒有這三張)、「頭像」(形狀和顏色,可自訂顏色)、「AI 供應商與模型」(供應商、模型、執行步驟用的模型、思考模式,[models](models.md))、「電腦操作」(查看、修改檔案和執行指令;做事的電腦、起始資料夾、模型可讀長度;「一律允許」清單,[safety](safety.md))、「指示」「群組成員」(只有群組,[team](team.md))、「記憶」(記得幾件事、「打開記憶」);最下面釘選到側邊欄、團隊成員可以使用,按「儲存」。 -- `settings-by-bot` Bot 能改的只有三樣:`theme`(light/dark/system)、`accent`(quiet/bot_color/black)、`timezone`(像 Asia/Taipei,不是有效的時區名稱就不改)。 +- `settings-by-bot` Bot 能改的只有四樣:`theme`(light/dark/system)、`style`(風格:paper、night、ink、moss、ocean、candy、sunset、terminal,custom 回到自訂)、`accent`(quiet/bot_color/black)、`timezone`(像 Asia/Taipei,不是有效的時區名稱就不改)。 ## 使用者怎麼到 @@ -41,18 +41,18 @@ ## 怎麼操作(verify-anybot) -- Bot:大部分設定改不了。`update_settings` 只改三樣(`theme`、`accent`、`timezone`);「在這台電腦上執行」只有使用者能打開。改自己的個人檔案、能力、技能、電腦、模型、頭像:先 `my_profile` 看,再 `update_my_profile` 改(使用者看到確認卡片、按允許才生效)。其他設定告訴使用者在哪個分頁、哪一塊。 +- Bot:大部分設定改不了。`update_settings` 只改四樣(`theme`、`style`、`accent`、`timezone`);「在這台電腦上執行」只有使用者能打開。改自己的個人檔案、能力、技能、電腦、模型、頭像:先 `my_profile` 看,再 `update_my_profile` 改(使用者看到確認卡片、按允許才生效)。其他設定告訴使用者在哪個分頁、哪一塊。 前提: - 基本前提和「手機已登入」(README),開著 Bot 1 的聊天:`$CTL phone click '.row[data-bot="1"]'`。 - **左下角:Bot 在哪一台**(covers `settings-whose`):前提:要開視窗。指令:`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot whose ANYBOT_SHOT_VIEW=whose ANYBOT_SHOT_SIZE=1000x620 'ANYBOT_SHOT_CLICK=150,592@6' ANYBOT_SHOT_FRAMES=60`(示範資料:已登入、是「雲端大腦」的螢幕、jenny-Host 離線),再不帶 `ANYBOT_SHOT_VIEW` 跑一次(沒登入)。看到:左下角「daniel/● 大腦「雲端大腦」」;選單「Bot 在哪一台」下「這台電腦(…)」「✓ 雲端大腦」「jenny-Host(離線)」(灰),分隔線下「所有檔案…」「個人資料與用量…」「設定…」;沒登入時是「✓ 這台電腦(…)」「登入帳號,才能換到別台大腦…」,分隔線下同樣三項。真的切換要帳號裡有另一台大腦:走不到,和「手機與帳號」頁的按鈕是同一段(`mir.want`、`mir.leave`)。 -- **個人資料與用量**(covers `settings-me`):指令:`$CTL api GET /api/stats --jq '{tokens_year, messages_year, streak_now, active_days, d: (.days|length), p: (.periods|keys)}'`;桌面要開視窗:`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot me ANYBOT_SHOT_TAB=me ANYBOT_SHOT_SIZE=1000x900`。看到:API 有 371 天的 days、periods 7/30/90/365;畫面上五張卡、熱度格子、「用量」和那四個期間、依模型、依 Bot。scratch 的假模型不回報用量,token 是 0、花費「未定價」(真的數字靠 `cargo test stats::`)。 +- **個人資料與用量**(covers `settings-me`):指令:`$CTL api GET /api/stats --jq '{tokens_year, messages_year, streak_now, active_days, d: (.days|length), p: (.periods|keys)}'`;桌面要開視窗:`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot me ANYBOT_SHOT_TAB=me ANYBOT_SHOT_SIZE=1000x900`。看到:API 有 371 天的 days、periods 7/30/90/365;畫面(示範資料)上數字列、熱度格子、「用量」的大數字、長條、四個期間、依模型的比例條。scratch 的假模型不回報用量,API 的 token 是 0、花費「未定價」(真的數字靠 `cargo test stats::`)。 - **搜尋設定**(covers `settings-search`):前提:要開視窗。指令:`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot set-search ANYBOT_SHOT_TAB=general ANYBOT_SHOT_SIZE=1100x760 ANYBOT_SHOT_FRAMES=60 'ANYBOT_SHOT_CLICK=245,159@20' 'ANYBOT_SHOT_TYPE=自動@30'`;再跑兩次,加 `'ANYBOT_SHOT_KEYS=Enter@40'`、`ANYBOT_SHOT_FRAMES=66`:打 `時區@30`,和從更新頁(`ANYBOT_SHOT_TAB=updates`)打 `對比@30`。看到:「自動更新/電腦 › Bot 的電腦」「自動審核/權限」「自動更新/更新」;時區那次換到一般、捲到「Bot」下的「時區」,那列有強調色外框;對比那次「更多外觀設定」變「收起」、「對比」有外框。 - **Bot 改三樣**(covers `settings-by-bot`、`settings-general`):請 Bot 換深色、只用黑色、時區紐約,再傳一句。指令:`$CTL phone send '改 [[call update_settings {"theme":"dark","accent":"black","timezone":"America/New_York"}]]' && $CTL phone wait-text '時區 → America/New_York' --in '#msgs' && $CTL phone send 幾點 && $CTL phone wait-text 'FAKE-MODEL 回答:幾點' --in '#msgs' && $CTL model 'select(.kind == "turn") | .user' && TZ=America/New_York date +%H:%M`。看到:不用卡片,「已更新:主題 → dark、聊天的顏色 → black、時區 → America/New_York」;Bot 收到的〔送出時間〕是紐約時間。 - **錯的時區**(covers `settings-by-bot`):指令:`$CTL phone send '錯 [[call update_settings {"timezone":"Mars/Base"}]]' && $CTL phone wait-text '不是有效的時區名稱' --in '#msgs' && $CTL state .timezone`。看到:「「Mars/Base」不是有效的時區名稱(例如 Asia/Taipei)」;還是 America/New_York。 -- **手機的設定**(covers `settings-general`、`settings-account`、`settings-models`、`settings-integrations`、`settings-computers`、`settings-perms`、`settings-vault`、`settings-updates`):重新整理,帳戶選單 › 設定 › 一般。指令:`$CTL phone open --listed && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone wait '[data-go="updates"]' && $CTL phone shot settings-tabs && $CTL phone click '[data-go="general"]' && $CTL phone wait-text America/New_York --in '#list' && $CTL phone wait-text 只用黑色 --in '#list' && $CTL phone shot settings-general`。看到:八列(沒有語音);一般裡主題「深色」、聊天的顏色「只用黑色」、時區、通知、這支手機的外觀。 +- **手機的設定**(covers `settings-general`、`settings-account`、`settings-models`、`settings-integrations`、`settings-computers`、`settings-perms`、`settings-vault`、`settings-updates`):重新整理,帳戶選單 › 設定 › 一般。指令:`$CTL phone open --listed && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone wait '[data-go="updates"]' && $CTL phone shot settings-tabs && $CTL phone click '[data-go="general"]' && $CTL phone wait-text America/New_York --in '#list' && $CTL phone wait-text 只用黑色 --in '#list' && $CTL phone shot settings-general`。看到:最上面「搜尋設定…」(打「通知」列出一般 › 通知的那幾項,點了到那頁),十列(多了個人資料與用量、語音);一般裡「電腦的外觀」強調色、對比、語言、主題「深色」、聊天的顏色「只用黑色」,時區(最後一項「其他時區…」自己打)、通知、這支手機的外觀。 - **桌面每個分頁、Bot 設定**(covers `settings-voice`、`settings-bot`、`settings-account`、`settings-computers`):每個分頁和 Bot 設定。指令:要開視窗——`$CTL stop && (for t in general remote providers channels computers review vault voice updates; do ABV_ALLOW_WINDOW=1 $CTL desktop-shot settings-$t ANYBOT_SHOT_TAB=$t || exit 1; done) && ABV_ALLOW_WINDOW=1 $CTL desktop-shot settings-bot ANYBOT_SHOT_VIEW=editor`。看到:各分頁的區塊照上面順序;Bot 設定最下面「儲存」。問候照時區(紐約晚上「晚上好」)也只在桌面。 - 自動測試:`cargo test app::settings_find::`(設定頁畫的每個區塊和列都要在搜尋的清單裡)、`cargo test stats::`、`cargo test featuremap::`(每個分頁和區塊標題、Bot 能改的設定都要在這份)、`cargo test appctl::`、`cargo test policy::`、`cargo test the_greeting_follows_the_timezone_setting`、`cargo test layout_audit::`(每個分頁、Bot 設定、例行任務、右側面板,用三種字型、最窄和一般的視窗、示範和很長的資料畫:字被切、疊在一起,或對話框被撐得比標題列寬就失敗)。 diff --git a/docs/feature-map/workflow.md b/docs/feature-map/workflow.md index 1101316..66bf1a9 100644 --- a/docs/feature-map/workflow.md +++ b/docs/feature-map/workflow.md @@ -4,18 +4,19 @@ ## 子功能 -- `workflow-canvas` 畫布:左上是名稱,按下去是選單(每個工作流和它的步驟數、新建工作流、版本歷史、重新命名、建立副本、刪除工作流);右上「聊天」(聊天放在旁邊或收起來)、「執行紀錄」、「▷ 執行工作流」(跑的時候變「■ 停止」)。點點底的畫布拖曳空白處移動、⌘+滾輪或捏合縮放;下面工具列「選取、拖曳|畫筆、便利貼、形狀、文字|搜尋|+ 新增節點」,左下「- 百分比 +|符合畫面|小地圖」。搜尋卡片和註解的字,Enter 跳到下一個。視窗窄時縮放列移到工具列上面。 +- `workflow-canvas` 畫布:左上是名稱,按下去是選單(每個工作流和它的步驟數、新建工作流、版本歷史、重新命名、建立副本、刪除工作流);右上「聊天」(聊天放在旁邊或收起來)、「執行紀錄」、「▷ 執行工作流」(跑的時候變淡底紅字的「■ 停止」)。點點底的畫布拖曳空白處移動、⌘+滾輪或捏合縮放;下面工具列「選取、拖曳|畫筆、便利貼、形狀、文字|搜尋|+ 新增節點」,左下「- 百分比 +|符合畫面|小地圖」。搜尋卡片和註解的字,Enter 跳到下一個。視窗窄時縮放列移到工具列上面。 - `workflow-nodes` 卡片:觸發器(手動、定時(每天、每週…,寫「下次執行」)、Webhook(給一個呼叫網址和密碼)、GitHub(存放庫和事件:PR 合併、CI 失敗…);Slack、新信這些在聊天裡請 Bot 設,跟例行任務的事件觸發是同一套;事情發生時,發生了什麼交給第一步;都有「立即執行」)。「+ 新增節點」可以搜尋,分三組——輸入:提示詞(一段話交給下一步)、素材(檔案,Bot 收到附件);步驟:LLM(直接問模型,選模型、系統提示詞,不用 Bot)、助手(Bot 用它的工具做)、圖片、影片(請 Bot 做出檔案);流程:條件(成立走「是」、不成立走「否」,兩個點各拉一條線;「否」沒接就停下來說原因)、審批(停下來等你按繼續)、輸出(放進哪個 Bot 的聊天,和/或通知你,「{結果}」換成上一步結果的第一行)。舊的「檢查」就是條件,「交付」「通知你」併成輸出。從卡片底下的點拉到另一張卡就連線;不能連回觸發器、不能繞成一圈。點卡片在右邊改設定,選到的卡片上面有「複製」「刪除」;助手、LLM、圖片、影片、條件有「試跑這一步」(只跑這一步,用前一步上次的結果)。Delete 刪掉選到的卡片或線(觸發器刪不掉)。 - `workflow-draw` 畫和註解:畫筆、便利貼(六種顏色,下面寫誰貼的,雙擊改字)、形狀、文字;點選後右邊換顏色、改文字、刪除。只是給人看,不會執行。 - `workflow-run` 執行:照線從觸發器往下走(一張接到好幾張時,上面的先,再左邊)。Bot 步驟是那個 Bot 聊天裡的一則訊息「[工作流「名稱」第 k/n 步]…」加上上一步的結果(聊天裡泡泡上面一行小標「工作流「名稱」第 k/n 步」、淡色泡泡,結果只顯示前三行,滑過看全文),它這一輪最後的回答就是這一步的結果;它正忙就排在後面,等它做完手上那一輪。檢查要回「通過」才往下,否則停下並寫原因。等你確認:畫布上方一條「等你確認:…」,「繼續」/「停止」,並發通知(電腦和手機)。交付把結果放進那個 Bot 的聊天(它正在回答時,等這一輪結束才放);通知你發通知。每一步不另外通知「完成」,只有審批和輸出會通知;Bot 的步驟算沒人在看的一輪(卡在等允許 15 分鐘就結束)。一次只跑一個;排程到了自動跑。觸發器後面還沒有步驟時,按「執行工作流」只說「這個工作流還沒有步驟,沒有執行:…」,不記一次執行。停止時,還排在 Bot 後面的那一步問題直接拿掉,不會停掉 Bot 手上別的事。卡片上標完成、進行中、等你確認、失敗;「執行紀錄」留最近 20 次(誰開始的、每一步的結果、為什麼停);日程只放定時和觸發跑的那幾次。 - `workflow-chat` 聊出來:在聊天裡請 Bot 做工作流,它用 `workflow` 工具建立、看、改(加步驟、改內容、刪步驟、連線、貼便利貼、整理排版)、執行、停止、刪除(刪除先問你)。你正看著那個 Bot 的聊天時(只有它),畫布自動開在聊天旁邊,跳到那個工作流,它改到的卡片和便利貼亮一下;跑出畫面就自動縮放到看得到全部。Bot 做的排成一欄,插在中間時後面的往下移;你自己排過的不重排。要刪除時,允許卡片寫的就是會刪的那一個(沒指定時是畫布上開著的)。旁邊的聊天跟著側邊欄選的 Bot 換。Bot 知道有哪些工作流(說明裡列著),你在畫布旁邊打的每一則都帶著「開著工作流「X」(#1)的畫布」,所以「這個」「畫布上」它知道是哪一個。 - `workflow-versions` 版本歷史:改完停手 20 秒、關掉畫布、每次執行前、Bot 每次改之前,各留一版(一樣的不重複留),最多 30 版;選單 › 版本歷史點一版就還原,還原前先留目前的樣子。 +- `workflow-phone` 手機的工作流:每個一張卡(名字、觸發和下次、幾個步驟、這次或最近一次怎麼了,右邊 ▷ 執行/■ 停止),等你確認時卡下面一條「等你確認:…」和「繼續」「停止」;點卡片看步驟由上到下(每一步這次或最近一次:完成、進行中、等你確認、失敗、略過,還沒到的變淡,Bot 的結果前三行)和最近 10 次執行紀錄。手機按的執行算「手動」,不上日程。跑的時候每 3 秒更新。 ## 使用者怎麼到 - 側邊欄最左邊那一欄第二個(流程圖示,滑過寫「工作流」),在聊天和日程中間;再按一次、按那一欄的「聊天」、或左上「‹ 聊天」都回到聊天。 - 在 Bot 的聊天裡說「幫我做一個…的工作流」:畫布開在聊天旁邊(視窗夠寬時;右上「聊天」收起或放回)。 -- 手機沒有畫布:在聊天裡請 Bot 做、改、跑,它用文字說工作流長怎樣;「等你確認」的通知會到手機,但要在電腦上按「繼續」。 +- 手機:首頁上面一排的「工作流」(`workflow-phone`)。手機沒有畫布,改要在電腦上或請 Bot 改。 ## 怎麼操作(verify-anybot) @@ -28,10 +29,11 @@ - **聊天裡建立**(covers `workflow-chat`、`workflow-nodes`、`workflow-draw`):請 Bot 做一個早報工作流。指令:`$CTL phone send '幫我做早報工作流 [[call workflow {"action":"create","name":"Threads 早報","schedule":{"frequency":"daily","time":"09:00"},"steps":[{"kind":"step","prompt":"找 5 則熱門育兒討論,每則附連結"},{"kind":"check","condition":"每則都有連結"},{"kind":"approve","prompt":"要把早報傳給你嗎?"},{"kind":"notify","text":"早報好了:{結果}"}],"notes":[{"text":"週末改十點?","near":2}]}]]' && $CTL phone wait-text '已建立工作流 #1' --in '#msgs' 60 && $CTL phone shot workflow-create && $CTL state '.workflows[0] | {name, nodes: [.nodes[] | {id, t: .kind.type, x, y}], edges, notes: [.notes[] | {text, author, x, y}]}'`。看到:聊天裡「工作流」那一步完成,回答列出 #1 觸發器 → #2 … #5 和便利貼;state 裡五張卡 x 都是 0、y 每張差 190,線 1→2→3→4→5,便利貼在 #2 左邊、作者「驗證小幫手」。 - **聊天裡修改**(covers `workflow-chat`、`workflow-versions`):在「等你確認」後面插一步交付,再貼一張綠色便利貼。指令:`$CTL phone send '確認後也放到聊天 [[call workflow {"action":"edit","steps":[{"kind":"deliver","after":4}],"notes":[{"text":"交付會放進這個聊天","near":4,"color":"green"}]}]]' && $CTL phone wait-text '已修改工作流 #1' --in '#msgs' 60 && $CTL state '.workflows[0] | {order: [.edges[] | [.from, .to]], ys: [.nodes[] | [.id, .y]], versions: (.versions | length)}'`。看到:回答「新增 #7;加了 1 張便利貼」;線 4→7→5,#5 往下移到 950、#7 在 760;versions 是 1(改之前的樣子)。 - **聊天裡執行**(covers `workflow-run`、`workflow-chat`):檢查的回答指定成「通過」,請 Bot 跑一次。指令:`$CTL model-reply '步・檢查' '通過' && $CTL phone send '跑一次 [[call workflow {"action":"run"}]]' && $CTL phone wait-text '已開始執行「Threads 早報」' --in '#msgs' 60 && $CTL phone wait-text '[工作流「Threads 早報」第 1/5 步]' --in '#msgs' 60 && $CTL phone wait-text '步・檢查' --in '#msgs' 60 && $CTL wait-api /api/bots/1 '.messages[-1].text == "通過"' 60 && $CTL phone shot workflow-run`。看到:同一個聊天裡先是第 1/5 步的問題和 Bot 的回答,再是第 2/5 步・檢查和最後一則「通過」。 -- **畫布在聊天旁邊**(covers `workflow-canvas`、`workflow-run`、`workflow-draw`):在電腦上打開畫布。指令:要開視窗——`$CTL phone stop && $CTL stop && $CTL state '.workflows[0].runs[-1] | {state, at, by, steps: [.steps[] | [.node, .state]]}' && ABV_ALLOW_WINDOW=1 $CTL desktop-shot workflow-beside ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_VIEW=workflow ANYBOT_SHOT_SIZE=1400x900 ANYBOT_SHOT_FRAMES=520`。看到:state 的 run 是 waiting、at 3、by「驗證小幫手」,#1–#3 done;左邊畫布「Threads 早報」,上方「等你確認:要把早報傳給你嗎? 繼續 停止」沒有蓋到卡片,觸發器、助手、條件標「完成」,審批是黃框;黃、綠便利貼在卡片左邊;右上「等你確認、執行紀錄、聊天、■ 停止」;右邊是驗證小幫手的聊天,最下面是「通過」。 +- **畫布在聊天旁邊**(covers `workflow-canvas`、`workflow-run`、`workflow-draw`):在電腦上打開畫布。指令:要開視窗——`$CTL phone stop && $CTL stop && $CTL state '.workflows[0].runs[-1] | {state, at, by, steps: [.steps[] | [.node, .state]]}' && ABV_ALLOW_WINDOW=1 $CTL desktop-shot workflow-beside ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_VIEW=workflow ANYBOT_SHOT_SIZE=1400x900 ANYBOT_SHOT_FRAMES=520`。看到:state 的 run 是 waiting、at 3、by「驗證小幫手」,#1–#3 done;左邊畫布「Threads 早報」,上方「等你確認:要把早報傳給你嗎? 繼續 停止」沒有蓋到卡片,觸發器、助手、條件標「完成」,審批是黃框;黃、綠便利貼在卡片左邊;右上「執行紀錄、聊天、■ 停止」(停止是淡底紅字);右邊是驗證小幫手的聊天,最下面是「通過」。 - **在旁邊聊、畫布跟著變**(covers `workflow-chat`、`workflow-canvas`):在旁邊的聊天打字請它加一步。指令:要開視窗——`ABV_ALLOW_WINDOW=1 $CTL desktop-shot workflow-live ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_VIEW=workflow ANYBOT_SHOT_SIZE=1400x900 ANYBOT_SHOT_FRAMES=600 'ANYBOT_SHOT_CLICK=1180,847@525' 'ANYBOT_SHOT_TYPE=通知前先檢查格式 [[call workflow {"action":"edit","steps":[{"kind":"check","condition":"是條列清單","after":7}],"notes":[{"text":"這步是在聊天裡加的","near":7,"color":"blue"}]}]]@530' 'ANYBOT_SHOT_KEYS=Enter@540'`。看到:聊天裡「已修改工作流 #1…新增 #9」;畫布上交付下面多一張「條件 是條列清單」、左邊一張藍色便利貼,兩個都有黃色光圈;通知你往下移,整個縮到看得到。 - **自己畫、拉線、搜尋**(covers `workflow-draw`、`workflow-nodes`、`workflow-canvas`):示範資料上貼便利貼打字、從交付底下的點拉線到通知你、搜尋「週末」。指令:要開視窗——`ABV_ALLOW_WINDOW=1 $CTL desktop-shot workflow-sticky ANYBOT_SHOT_VIEW=workflow ANYBOT_SHOT_SIZE=1400x900 ANYBOT_SHOT_FRAMES=44 'ANYBOT_SHOT_CLICK=720,860@20;450,600@26' 'ANYBOT_SHOT_TYPE=記得週末改時間@34' && ABV_ALLOW_WINDOW=1 $CTL desktop-shot workflow-link ANYBOT_SHOT_VIEW=workflow ANYBOT_SHOT_SIZE=1400x900 ANYBOT_SHOT_FRAMES=40 'ANYBOT_SHOT_DRAG=740,747>965,725@24' && ABV_ALLOW_WINDOW=1 $CTL desktop-shot workflow-search ANYBOT_SHOT_VIEW=workflow ANYBOT_SHOT_SIZE=1400x900 ANYBOT_SHOT_FRAMES=48 'ANYBOT_SHOT_CLICK=844,860@20' 'ANYBOT_SHOT_TYPE=週末@26' 'ANYBOT_SHOT_KEYS=Enter@32'`。看到:新的便利貼框著、裡面是「記得週末改時間」、作者 daniel,右邊便利貼的顏色和刪除;交付底下多一條線連到通知你(交付沒被拖走);搜尋框裡「週末」、旁邊「1/1」,畫面移到「週末改成十點」那張並選起來。版本歷史、選單、窄視窗:靠自動測試和版面檢查。 - **新的節點和觸發器**(covers `workflow-nodes`):示範資料的第二個工作流。指令:要開視窗——`ABV_ALLOW_WINDOW=1 $CTL desktop-shot workflow-kinds ANYBOT_SHOT_VIEW=workflow ANYBOT_SHOT_TAB=2 ANYBOT_SHOT_SIZE=1400x900 ANYBOT_SHOT_FRAMES=30 && ABV_ALLOW_WINDOW=1 $CTL desktop-shot workflow-palette ANYBOT_SHOT_VIEW=workflow ANYBOT_SHOT_TAB=2 ANYBOT_SHOT_SIZE=1400x900 ANYBOT_SHOT_FRAMES=30 'ANYBOT_SHOT_CLICK=1060,860@18' && ABV_ALLOW_WINDOW=1 $CTL desktop-shot workflow-trigger ANYBOT_SHOT_VIEW=workflow ANYBOT_SHOT_TAB=2 ANYBOT_SHOT_SIZE=1400x900 ANYBOT_SHOT_FRAMES=30 'ANYBOT_SHOT_CLICK=942,135@18'`。看到:「PR 合併後的發布貼文」:觸發器寫「GitHub anybot/app:pr_merged」「事情發生時」,下面提示詞、LLM(主要 Bot 的模型)、條件(下面「是」「否」兩個點),是→圖片→審批→輸出、否→輸出(通知);新增節點是搜尋框和「輸入/步驟/流程」三組;點觸發器右邊是「GitHub」、存放庫、事件(PR 合併亮著)、Token。 +- **手機的工作流**(covers `workflow-phone`、`workflow-run`):接著上面建好的早報(檢查指定「通過」)。指令:`$CTL model-reply '步・檢查' '通過' && $CTL phone click '[data-back]' && $CTL phone click '#quick [data-q="workflows"]' && $CTL phone wait '[data-wfopen="1"]' && $CTL phone click '[data-wfdo="run"]' && $CTL phone wait '.wf-ask' 150 && $CTL phone click '[data-wfopen="1"] .k' && $CTL phone wait '.wf-steps' && $CTL phone shot wf-phone && $CTL phone click '.wf-ask [data-wfdo="go"]' && $CTL wait-api '/api/state?since=0' 'true' 2 && $CTL state '.workflows[0].runs[-1] | {state, by}'`。看到:卡上「等你確認」和「繼續」「停止」;步驟觸發器、助手、條件「完成」,審批黃色「等你確認」,輸出變淡;按繼續後最後一次 state done、by「手動」。 - 自動測試:`cargo test workflow`、`cargo test layout_audit::`(「工作流」四景)、`cargo test theme::`。 ## 陷阱 diff --git a/fonts/NotoSerifTC-Bold.otf b/fonts/NotoSerifTC-Bold.otf deleted file mode 100644 index 9b9991c..0000000 Binary files a/fonts/NotoSerifTC-Bold.otf and /dev/null differ diff --git a/fonts/NotoSerifTC-Regular.otf b/fonts/NotoSerifTC-Regular.otf deleted file mode 100644 index abc153d..0000000 Binary files a/fonts/NotoSerifTC-Regular.otf and /dev/null differ diff --git a/fonts/OFL.txt b/fonts/OFL.txt index f62091b..515358e 100644 --- a/fonts/OFL.txt +++ b/fonts/OFL.txt @@ -1,9 +1,6 @@ [Noto Sans TC](思源黑體,fonts/NotoSansTC-Regular.otf, NotoSansTC-Bold.otf) Copyright © 2014-2021 Adobe (http://www.adobe.com/), with Reserved Font Name 'Source'. -[Noto Serif TC](思源宋體,fonts/NotoSerifTC-Regular.otf, NotoSerifTC-Bold.otf) -Copyright © 2017-2024 Adobe (http://www.adobe.com/), with Reserved Font Name 'Source'. - This Font Software is licensed under the SIL Open Font License, Version 1.1. This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL diff --git a/icons/lucide/globe.svg b/icons/lucide/globe.svg new file mode 100644 index 0000000..6c8dff2 --- /dev/null +++ b/icons/lucide/globe.svg @@ -0,0 +1,17 @@ + + + + + + diff --git a/icons/lucide/hard-drive.svg b/icons/lucide/hard-drive.svg new file mode 100644 index 0000000..bba81d6 --- /dev/null +++ b/icons/lucide/hard-drive.svg @@ -0,0 +1,18 @@ + + + + + + + diff --git a/icons/lucide/moon.svg b/icons/lucide/moon.svg new file mode 100644 index 0000000..174f00d --- /dev/null +++ b/icons/lucide/moon.svg @@ -0,0 +1,15 @@ + + + + diff --git a/icons/lucide/palette.svg b/icons/lucide/palette.svg new file mode 100644 index 0000000..a423e4f --- /dev/null +++ b/icons/lucide/palette.svg @@ -0,0 +1,19 @@ + + + + + + + + diff --git a/icons/lucide/sliders-horizontal.svg b/icons/lucide/sliders-horizontal.svg new file mode 100644 index 0000000..e54f9f4 --- /dev/null +++ b/icons/lucide/sliders-horizontal.svg @@ -0,0 +1,23 @@ + + + + + + + + + + + + diff --git a/icons/lucide/volume-2.svg b/icons/lucide/volume-2.svg new file mode 100644 index 0000000..ba0e148 --- /dev/null +++ b/icons/lucide/volume-2.svg @@ -0,0 +1,17 @@ + + + + + + diff --git a/mobile/index.html b/mobile/index.html index 5bcd02b..adedd04 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -37,7 +37,8 @@ --lh-read:1.7; --sp-1:4px;--sp-2:8px;--sp-3:12px;--sp-4:16px;--sp-5:24px;--sp-6:32px; --r-s:6px;--r-m:10px;--r-l:14px; - --font-read:"Noto Serif TC","Songti TC","Source Han Serif TC","Noto Serif CJK TC",serif; + /* Answers and pages read in the same calm sans as the interface (Apple's way; they were in a serif). */ + --font-read:var(--font); /* Floating shadows, the sheet's backdrop, the black stage under a screen, words on a strong fill. */ --shade:#00000024;--scrim:#00000066;--stage:#000;--on-stage:#ffffff99;--on-color:#fff; } @@ -158,12 +159,15 @@ details.dt>.dt-in{padding-left:var(--sp-4);margin-top:var(--sp-2)} :is(.bub,.page,.tk-a) li{margin:0 0 6px} :is(.bub,.page,.tk-a) li:last-child{margin-bottom:0} :is(.bub,.page,.tk-a) li.task{list-style:none;margin-left:-1.2em} -:is(.bub,.page) :is(h2,h3,h4){font-family:var(--font-read);font-weight:700;line-height:1.35;color:var(--text)} +:is(.bub,.page) :is(h2,h3,h4){font-family:var(--font-read);font-weight:600;line-height:1.35;color:var(--text)} .bub h2{font-size:var(--fs-h3);margin:1.2em 0 .4em} .bub :is(h3,h4){font-size:var(--fs-read);margin:1.1em 0 .3em} .tk-a :is(h2,h3,h4){font-size:var(--fs-ui);margin:.8em 0 .3em} :is(.bub,.page,.tk-a) code{font-family:var(--mono);font-size:var(--fs-small);background:var(--hover);padding:1px 5px;border-radius:var(--r-s)} :is(.bub,.page,.tk-a) pre{margin:0 0 .75em;padding:var(--sp-3) var(--sp-4);border-radius:var(--r-m);background:var(--hover);overflow-x:auto;font:var(--fs-small)/1.55 var(--mono)} +/* 複製程式碼: a small button on each code block (the whole message's 複製 is in its menu). */ +pre.cb{position:relative} +pre.cb .cpy{position:absolute;top:4px;right:4px;width:30px;height:30px;border-radius:var(--r-s);display:grid;place-items:center;color:var(--text3);background:var(--elev);opacity:.85} :is(.bub,.page,.tk-a) pre code{background:none;padding:0;border-radius:0;font:inherit} :is(.bub,.page,.tk-a) blockquote{margin:0 0 .75em;padding-left:var(--sp-3);border-left:2px solid var(--line);color:var(--text2)} :is(.bub,.page,.tk-a) hr{border:0;border-top:1px solid var(--line);margin:var(--sp-5) 0} @@ -369,7 +373,7 @@ details.dt>.dt-in{padding-left:var(--sp-4);margin-top:var(--sp-2)} .composer:focus-within{box-shadow:inset 0 0 0 1px var(--text4),0 2px 10px -2px var(--shade)} .composer.tall{border-radius:var(--r-l)} .composer textarea{flex:1;border:0;outline:0;background:none;resize:none;font-size:var(--fs-read);line-height:22px;max-height:140px;min-height:28px;padding:3px 4px} -.cbtn{width:36px;height:36px;border-radius:var(--r-m);display:grid;place-items:center;flex:none;color:var(--text2)} +.cbtn{width:36px;height:36px;border-radius:50%;display:grid;place-items:center;flex:none;color:var(--text2)} .cbtn.plus{background:none} .cbtn.go{background:var(--bot,var(--primary));color:var(--bot-ink,var(--on-primary))} .cbtn.go:disabled{opacity:.35} @@ -479,7 +483,10 @@ textarea.field{min-height:96px;line-height:1.5} .sheet .seltext.page{padding-bottom:var(--sp-3)} .seltext.mine{padding:var(--sp-2) 18px var(--sp-3);white-space:pre-wrap;font-size:var(--fs-read);line-height:1.5} .seltext .quote{display:block;-webkit-line-clamp:none;overflow:visible} -.toast{position:fixed;left:50%;top:calc(var(--safe-t) + 60px);transform:translate(-50%,-12px);background:var(--primary);color:var(--on-primary);padding:9px 16px;border-radius:999px;font-size:var(--fs-ui);opacity:0;pointer-events:none;transition:.2s;z-index:40;max-width:86vw;text-align:center} +/* A short notice floating under the title bar: frosted glass (what is under it blurs, so it + reads as above the page, not one more card on it), a hairline, a soft shadow, the card's + corners. It was a black capsule, and two or three lines swelled it into an oval. */ +.toast{position:fixed;left:50%;top:calc(var(--safe-t) + 60px);transform:translate(-50%,-10px);width:max-content;max-width:min(360px,calc(100vw - 32px));background:color-mix(in srgb,var(--elev) 78%,transparent);-webkit-backdrop-filter:blur(18px) saturate(1.6);backdrop-filter:blur(18px) saturate(1.6);color:var(--text);padding:11px 16px;border-radius:var(--r-l);box-shadow:inset 0 0 0 .5px var(--line),0 12px 32px -8px var(--shade),0 2px 6px -2px var(--shade);font-size:var(--fs-ui);line-height:1.5;text-align:left;opacity:0;pointer-events:none;transition:opacity .2s,transform .2s;z-index:40} .toast.on{opacity:1;transform:translate(-50%,0)} .net{position:fixed;left:50%;top:calc(var(--safe-t) + 64px);transform:translate(-50%,-12px);background:var(--elev);color:var(--text2);border:1px solid var(--line);box-shadow:0 2px 10px #0000001a;padding:5px 12px;border-radius:999px;font-size:var(--fs-small);opacity:0;pointer-events:none;transition:.2s;z-index:39;white-space:nowrap} .net.on{opacity:1;transform:translate(-50%,0)} @@ -507,7 +514,7 @@ textarea.field{min-height:96px;line-height:1.5} /* ---- page viewer ---- */ .page{padding:var(--sp-2) 18px 40px;max-width:760px;margin:0 auto} -.page h1.pt{font-family:var(--font-read);font-weight:700;font-size:var(--fs-h1);line-height:1.3;margin:var(--sp-3) 0 var(--sp-1)} +.page h1.pt{font-family:var(--font-read);font-weight:600;font-size:var(--fs-h1);line-height:1.3;margin:var(--sp-3) 0 var(--sp-1)} .page .mt{font-family:var(--font);font-size:var(--fs-caption);color:var(--text3);margin-bottom:var(--sp-4)} .page h2{font-size:var(--fs-h2);margin:1.6em 0 .5em} .page h3{font-size:var(--fs-h3);margin:1.4em 0 .4em} @@ -569,8 +576,104 @@ textarea.field{min-height:96px;line-height:1.5} .stage .msg{color:var(--on-stage);font-size:var(--fs-ui);padding:20px;text-align:center} .stage .tapdot{position:absolute;width:26px;height:26px;margin:-13px 0 0 -13px;border-radius:50%;background:color-mix(in srgb,var(--accent) 53%,transparent);pointer-events:none;animation:fade .6s forwards} @keyframes fade{to{opacity:0;transform:scale(1.8)}} -.tools{display:flex;gap:6px;padding:8px 10px calc(var(--safe-b) + 8px);overflow-x:auto;flex:none;background:var(--chrome)} -.tools .btn{flex:none} +.tools{display:flex;gap:6px;padding:8px 10px calc(var(--safe-b) + 8px);overflow-x:auto;flex:none;background:var(--chrome);scrollbar-width:none} +.tools::-webkit-scrollbar{display:none} +.tools .btn{flex:none;height:36px;min-width:40px;padding:0 10px;border-radius:var(--r-m)} +.tools .sep{width:1px;background:var(--line);margin:4px 2px;flex:none} +.tools .btn.once{background:color-mix(in srgb,var(--accent) 18%,transparent);color:var(--accent-ink)} +.tools .btn.lock{background:var(--accent);color:var(--on-color)} +.tools .btn.on{background:var(--primary);color:var(--on-primary)} +/* 所有檔案: a search, the kinds with their counts, pictures in a grid, the rest as rows. */ +.lib-top{position:sticky;top:0;z-index:2;background:var(--pane);padding:var(--sp-3) var(--sp-4) var(--sp-2)} +.lib-tabs{padding:0;position:static;background:none;margin-top:var(--sp-2)} +.lib-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:4px;margin:var(--sp-2) var(--sp-4) var(--sp-3)} +.lib-pic{aspect-ratio:1;border-radius:var(--r-m);overflow:hidden;background:var(--hover);padding:0} +.lib-pic img{width:100%;height:100%;object-fit:cover;display:block} +.item.gone{opacity:.5}.item.gone .v{color:var(--danger)} +/* 日程: 即將執行, then a group a day — a row a time: when, what, how it went. */ +.item.sch .sch-t{width:44px;flex:none;font-size:var(--fs-small);color:var(--text2);font-variant-numeric:tabular-nums;display:flex;align-items:center} +.item.sch .av.sm{width:26px;height:26px}.item.sch .av.sm svg{width:26px;height:26px} +.item.sch .r{display:flex;align-items:center;gap:4px;font-size:var(--fs-caption);white-space:nowrap} +.item.sch .r.good{color:var(--ok)}.item.sch .r.bad{color:var(--danger)}.item.sch .r.go{color:var(--accent-ink)} +.item.sch.todo{opacity:.55} +/* 工作流: a card each (run / stop at the right, the 等你確認 under it); one opened: its steps as a + line from top to bottom, each with how this run (or the last) went there. */ +.wf-card{padding:12px 16px;border-bottom:1px solid var(--line2);cursor:pointer} +.wf-card:last-child{border-bottom:0} +.wf-row{display:flex;align-items:center;gap:12px} +.wf-row .mid{flex:1;min-width:0}.wf-row .k{font-size:var(--fs-ui);font-weight:500}.wf-row .v{font-size:var(--fs-small);color:var(--text3);line-height:1.5} +.wf-i{width:30px;height:30px;border-radius:var(--r-m);background:var(--hover);display:grid;place-items:center;flex:none;color:var(--text2)} +.wf-i.big{width:36px;height:36px} +.wf-ask{display:flex;align-items:center;gap:8px;margin-top:10px;padding:10px 12px;border-radius:var(--r-m);background:var(--attention-bg);font-size:var(--fs-small)} +.wf-ask span{flex:1;min-width:0} +.wf-head{display:flex;align-items:center;gap:12px;margin:var(--sp-3) var(--sp-4) 0} +.wf-head .v{flex:1;min-width:0;font-size:var(--fs-small);color:var(--text3)} +.wf-head + .wf-ask{margin:var(--sp-3) var(--sp-4) 0} +.wf-steps{margin:0 var(--sp-4);padding:4px 0;background:var(--elev);border-radius:var(--r-l)} +.wf-step{display:flex;gap:12px;padding:10px 14px;position:relative} +.wf-step:not(:last-child)::after{content:"";position:absolute;left:28px;top:44px;bottom:-6px;width:2px;background:var(--line)} +.wf-step .mid{flex:1;min-width:0}.wf-step .k{font-size:var(--fs-ui);font-weight:500}.wf-step .v{font-size:var(--fs-small);color:var(--text2);line-height:1.5;white-space:pre-line;overflow:hidden;display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical} +.wf-step .v.out{color:var(--text3);margin-top:4px;padding-left:8px;border-left:2px solid var(--line)} +.wf-step.good .wf-i{background:color-mix(in srgb,var(--ok) 16%,transparent);color:var(--ok)} +.wf-step.go .wf-i{background:color-mix(in srgb,var(--accent) 16%,transparent);color:var(--accent-ink)} +.wf-step.wait .wf-i{background:var(--attention-bg);color:var(--warn)} +.wf-step.bad .wf-i{background:color-mix(in srgb,var(--danger) 14%,transparent);color:var(--danger)} +.wf-step.skip,.wf-step.todo{opacity:.5} +.pill.good{background:color-mix(in srgb,var(--ok) 16%,transparent);color:var(--ok)} +.pill.go{background:color-mix(in srgb,var(--accent) 16%,transparent);color:var(--accent-ink)} +.pill.wait{background:var(--attention-bg);color:var(--warn)} +.pill.bad{background:color-mix(in srgb,var(--danger) 14%,transparent);color:var(--danger)} +/* 風格 gallery: four little pictures a row, the one worn ringed in the accent. */ +.tpl-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin:0 var(--sp-4) var(--sp-2)} +.tpl{display:flex;flex-direction:column;align-items:center;gap:5px;padding:0;min-width:0} +.tpl .pic{position:relative;width:100%;aspect-ratio:1.25;border-radius:var(--r-m);border:1px solid;overflow:hidden;display:block} +.tpl.on .pic{box-shadow:0 0 0 2px var(--pane),0 0 0 4px var(--accent)} +.tpl .pic i{position:absolute;display:block;border-radius:999px} +.tpl .pic .sd{left:0;top:0;bottom:0;width:26%;border-radius:0;display:flex;flex-direction:column;gap:4px;padding:6px 4px} +.tpl .pic .sd b{display:block;height:3px;border-radius:999px} +.tpl .pic .ln{left:34%;top:14%;width:50%;height:3px}.tpl .pic .ln.s{top:24%;width:36%} +.tpl .pic .bb{right:8%;top:42%;width:38%;height:9px} +.tpl .pic .dt{right:8%;bottom:10%;width:8px;height:8px} +.tpl .nm{font-size:var(--fs-caption);color:var(--text2)}.tpl.on .nm{color:var(--text);font-weight:600} +/* 風格's chat backdrop: dots, a grid or waves in the page's faintest line colour, behind the chat. */ +html[data-backdrop="dots"] #scroller{background-image:radial-gradient(var(--grid) 1.3px,transparent 1.5px);background-size:22px 22px} +html[data-backdrop="grid"] #scroller{background-image:linear-gradient(var(--grid) 1px,transparent 1px),linear-gradient(90deg,var(--grid) 1px,transparent 1px);background-size:24px 24px} +html[data-backdrop="waves"] #scroller{background-image:radial-gradient(circle at 50% 100%,transparent 13.5px,var(--grid) 14px,var(--grid) 14.6px,transparent 15.2px);background-size:32px 16px} +/* 個人資料與用量: one strip of big numbers, the year's dots, a big number and bars. */ +.me-figs{display:grid;grid-template-columns:repeat(4,1fr);gap:4px;margin:var(--sp-3) var(--sp-4) 0;padding:var(--sp-3) var(--sp-2);background:var(--elev);border-radius:var(--r-l)} +.me-figs div{display:flex;flex-direction:column;align-items:center;gap:2px;min-width:0} +.me-figs b{font-size:var(--fs-h3);font-weight:600;white-space:nowrap} +.me-figs span{font-size:var(--fs-caption);color:var(--text3);white-space:nowrap} +.me-card{margin:0 var(--sp-4);padding:var(--sp-3) var(--sp-4);background:var(--elev);border-radius:var(--r-l)} +.me-heat{width:100%;height:auto;display:block} +.me-note{font-size:var(--fs-caption);color:var(--text3);margin-top:var(--sp-2);line-height:1.5} +.me-seg{display:flex;gap:2px;padding:3px;background:var(--active);border-radius:999px;margin:var(--sp-1) 0 var(--sp-3)} +.me-seg button{flex:1;height:30px;border-radius:999px;font-size:var(--fs-small);color:var(--text2)} +.me-seg button.on{background:var(--elev);color:var(--text);font-weight:600} +.me-hero{font-size:var(--fs-small);color:var(--text3)} +.me-hero b{font-size:var(--fs-h1);font-weight:600;color:var(--text);margin-right:4px} +.me-bars{width:100%;height:84px;display:block;margin:var(--sp-3) 0 var(--sp-4);border-bottom:1px solid var(--grid)} +.me-split{display:flex;height:10px;border-radius:999px;overflow:hidden;background:var(--hover);margin-bottom:var(--sp-2)} +.me-split i{display:block;height:100%} +.me-row{display:flex;align-items:center;gap:10px;min-height:36px} +.me-dot{width:8px;height:8px;border-radius:50%;flex:none} +.me-av{width:22px;height:22px;flex:none;display:grid}.me-av svg{width:22px;height:22px} +.me-name{flex:1;min-width:0;font-size:var(--fs-small);white-space:nowrap;overflow:hidden;text-overflow:ellipsis} +.me-bar{width:70px;height:6px;border-radius:999px;background:var(--hover);overflow:hidden;flex:none}.me-bar i{display:block;height:100%;background:var(--accent)} +.me-n{font-size:var(--fs-small);color:var(--text2);white-space:nowrap} +/* 虛擬觸控板 over this Mac's screen: a layer that takes the fingers, and the pointer drawn on it. */ +.stagewrap{flex:1;min-height:0;position:relative;display:flex} +.pad{position:absolute;inset:0;display:none;touch-action:none;-webkit-user-select:none;user-select:none;-webkit-touch-callout:none} +.pad.on{display:block} +.ptr{position:absolute;width:20px;height:20px;margin:-2px 0 0 -3px;pointer-events:none;display:none;filter:drop-shadow(0 1px 2px #0009)} +.ptr.on{display:block} +.padtip{position:absolute;left:50%;bottom:12px;transform:translateX(-50%);max-width:calc(100% - 24px);background:var(--elev);border-radius:var(--r-l);padding:9px 12px;font-size:var(--fs-small);line-height:1.6;box-shadow:0 2px 10px -2px var(--shade);pointer-events:none;opacity:0;transition:opacity .3s} +.padtip.on{opacity:1} +.padtip b{font-weight:600;color:var(--accent-ink)} +.combos{display:none;grid-template-columns:repeat(3,1fr);gap:6px;padding:10px;background:var(--chrome);max-height:40vh;overflow-y:auto;flex:none} +.combos.on{display:grid} +.combos .btn{height:auto;min-height:48px;flex-direction:column;gap:2px;border-radius:var(--r-l);padding:6px 4px} +.combos .btn small{color:var(--text3);font-size:var(--fs-caption);font-weight:400} .typebar{display:none;gap:6px;padding:8px 10px 0;background:var(--chrome)} .typebar.on{display:flex} .typebar input{flex:1} @@ -680,6 +783,7 @@ button,.row,.ib,.island,.opt,.chip,.tab,label.sw,[role="button"]{-webkit-user-se
+
@@ -745,18 +849,10 @@ button,.row,.ib,.island,.opt,.chip,.tab,label.sw,[role="button"]{-webkit-user-se

這台 Mac

-
載入中…
+
載入中…
+
-
- - - - - - - - -
+
@@ -814,11 +910,15 @@ const LUCIDE = { "target": '', "alarm-clock": '', "sparkles": '', + "calendar": '', "list-checks": '', "camera": '', "paperclip": '', "log-out": '', "bell": '', + "clock": '', + "circle-dot": '', + "palette": '', "moon": '', "shield": '', "plug": '', @@ -848,7 +948,8 @@ function ic(name, size = 18) { return `"']/g, (c) => ({"&": "&", "<": "<", ">": ">", '"': """, "'": "'"}[c])); } // (No network is told once, by the line at the top — not again by every request that failed.) -function toast(t) { if (t === OFFLINE_MSG) return netDown(true); const e = $("toast"); e.textContent = t; e.classList.add("on"); clearTimeout(toast.t); toast.t = setTimeout(() => e.classList.remove("on"), 2600); } +// (A longer one stays longer: time to read it — 2.6 s, and more for each word past a short line.) +function toast(t) { if (t === OFFLINE_MSG) return netDown(true); const e = $("toast"); e.textContent = t; e.classList.add("on"); clearTimeout(toast.t); toast.t = setTimeout(() => e.classList.remove("on"), Math.min(7000, 2600 + Math.max(0, String(t).length - 16) * 70)); } const nap = (ms) => new Promise((r) => setTimeout(r, ms)); // Times as the desktop's sidebar shows them: 剛剛 / 5 分鐘 / 3 小時 / 昨天 / 4 天 / 11/5. function ago(ms) { @@ -912,6 +1013,9 @@ function applyPalette(p) { const css = paletteCss(p); let el = document.getElementById("desk-palette"); if (!el) { el = document.createElement("style"); el.id = "desk-palette"; document.head.appendChild(el); } + // The 風格's chat backdrop (dots, a grid, waves), drawn in the page's own faint line colour. + const bd = p && ["dots", "grid", "waves"].includes(p.backdrop) ? p.backdrop : ""; + if (bd) document.documentElement.dataset.backdrop = bd; else delete document.documentElement.dataset.backdrop; if (el.textContent === css) return; el.textContent = css; try { if (css) localStorage.setItem("anybot.palette", JSON.stringify(p)); else localStorage.removeItem("anybot.palette"); } catch (_) {} @@ -1133,7 +1237,7 @@ function draw(v, arg) { else if (v === "botset") renderBotset(arg.bot); else if (v === "list") renderList(arg); else if (v === "page") openPage(arg.id, arg.rev); - else if (v === "screen") startFrames(); + else if (v === "screen") { startFrames(); macTools(); } } const cur = () => NAV[NAV.length - 1] || {v: "home", arg: {}}; @@ -1408,7 +1512,7 @@ function mergeState(prev, v) { } function apply(v) { S.bots = v.bots || []; S.approvals = v.approvals || []; S.hostName = v.host || ""; S.mac = !!v.mac; - S.box = v.box || ""; S.boxOn = !!v.box_available; S.pages = v.pages || []; S.tasks = v.tasks || []; S.models = v.models || []; S.sections = v.sections || null; S.role = v.role || "owner"; + S.box = v.box || ""; S.boxOn = !!v.box_available; S.pages = v.pages || []; S.tasks = v.tasks || []; S.models = v.models || []; S.sections = v.sections || null; S.pinOrder = v.pin_order || null; S.always = !!v.always; S.role = v.role || "owner"; S.voice = v.voice || {}; micShown(); appBadge(); // The computer's 外觀 (an older brain sends neither: the built-in look stays). if (v.palettes) applyPalette(v.palettes); @@ -1456,8 +1560,43 @@ function apply(v) { // ---------- home: the sidebar ---------- $("b-search").innerHTML = ic("search", 20); $("b-newbot").innerHTML = ic("plus", 22); $("search-ic").innerHTML = ic("search", 16); $("b-search-x").innerHTML = ic("x", 16); $("b-search").onclick = () => { $("searchbox").classList.add("on"); $("search").focus(); }; -$("b-search-x").onclick = () => { $("search").value = ""; S.search = ""; $("searchbox").classList.remove("on"); renderHome(); }; -$("search").oninput = () => { S.search = $("search").value.trim().toLowerCase(); renderHome(); }; +$("b-search-x").onclick = () => { $("search").value = ""; S.search = ""; S.hits = null; $("searchbox").classList.remove("on"); renderHome(); }; +// 搜尋 finds bots by name, and (the owner's) words in every chat — past conversations and file +// names too — as on the computer: a tap opens that chat at that message. +let searchTimer = 0, searchSeq = 0; +$("search").oninput = () => { + S.search = $("search").value.trim().toLowerCase(); + S.hits = null; clearTimeout(searchTimer); + if (S.search && owner()) searchTimer = setTimeout(searchChats, 300); + renderHome(); +}; +async function searchChats() { + const q = S.search, seq = ++searchSeq; + const v = await act("search", {q: $("search").value.trim()}, false); + if (seq !== searchSeq || q !== S.search) return; + S.hits = v || {hits: [], more: false}; + renderHome(); +} +function hitsHtml() { + if (!S.search || !S.hits) return ""; + const hits = S.hits.hits || []; + if (!hits.length) return `
聊天裡也沒有找到
`; + return `
${ic("message", 13)}聊天裡 ${hits.length}${S.hits.more ? "+" : ""}
${hits.map((h, i) => { + const b = bot(h.bot) || {}; + const where = h.thread != null ? `過去的對話` : ""; + const what = (h.file ? "📎 " + h.file + " " : "") + (h.snippet || ""); + return `
${avatarSvg(b.shape, b.color)}
${esc(h.bot_name || b.name || "")}${where}
${esc(what)}
${ago(h.at)}
`; + }).join("")}
`; +} +async function openHit(i) { + const h = ((S.hits || {}).hits || [])[i]; + if (!h) return; + if (h.thread != null) { + if (!await confirmSheet("回到這段對話?", `「${h.thread_title || "對話"}」會換回來,現在的對話留在「過去的對話」裡。`, "回到這段對話", false)) return; + try { await api(base() + `api/bots/${h.bot}/restore`, {json: {index: h.thread}}); } catch (e) { toast(e.message); return; } + } + go("chat", {bot: h.bot, at: h.at}); +} function botState(b) { const waiting = S.approvals.find((a) => a.bot === b.id); if (waiting) return {cls: "wait", dot: "wait", text: waiting.kind === "question" ? "等你回答:" + waiting.reason : "等你處理:" + (waiting.kind === "handoff" ? waiting.reason : waiting.title)}; @@ -1483,18 +1622,27 @@ function renderHome() { const tn = taskAttention(); $("quick").innerHTML = owner() ? [ ``, + ``, + ``, ``, ``, + ``, ``, isOwner() ? `` : "", ].join("") : ""; $("b-newbot").style.display = isOwner() ? "" : "none"; $("quick").querySelectorAll("[data-q]").forEach((b) => b.onclick = () => go("list", {kind: b.dataset.q})); if (!S.bots.length) { $("home").innerHTML = `
還沒有 Bot。按右上角的 + 建立第一個。
`; return; } - if (!bots.length) { $("home").innerHTML = `
沒有相符的 Bot
`; return; } + if (!bots.length) { + $("home").innerHTML = (q && S.hits && (S.hits.hits || []).length ? "" : `
${q && owner() && !S.hits ? "找找看聊天裡…" : "沒有相符的 Bot"}
`) + hitsHtml(); + $("home").querySelectorAll("[data-hit]").forEach((r) => r.onclick = () => openHit(+r.dataset.hit)); + return; + } // The sidebar's sections: 主要 Bot, 已釘選的 Bot, the person's own sections, then Bot. const primary = bots.filter((b) => b.primary); - const pinned = bots.filter((b) => !b.primary && b.pinned); + // (In the desktop's order, which the owner can change from a bot's ⋯ › 更多.) + const pinAt = (b) => { const i = (S.pinOrder || []).indexOf(b.id); return i < 0 ? 1e9 : i; }; + const pinned = bots.filter((b) => !b.primary && b.pinned).sort((a, b) => pinAt(a) - pinAt(b)); const rest = bots.filter((b) => !b.primary && !b.pinned); // The desktop's 分區 in its order (null = 未分區), empty ones too. const order = S.sections || [...new Set(rest.map((b) => b.folder).filter(Boolean)), null]; @@ -1506,7 +1654,8 @@ function renderHome() { if (f == null) h += sec(folders.length ? "未分區" : "Bot", "", rest.filter((b) => !folders.includes(b.folder)), folders.length ? "loose" : ""); else h += sec(f, "folder", rest.filter((b) => b.folder === f), "f:" + f, isOwner() ? `` : "", !q); } - $("home").innerHTML = h + `
`; + $("home").innerHTML = h + hitsHtml() + `
`; + $("home").querySelectorAll("[data-hit]").forEach((r) => r.onclick = () => openHit(+r.dataset.hit)); $("home").querySelectorAll(".row[data-bot]").forEach((r) => { r.onclick = (e) => { if (e.target.closest("[data-botmenu]")) return; go("chat", {bot: +r.dataset.bot}); }; let t = null; r.addEventListener("touchstart", () => { t = setTimeout(() => { t = "long"; botMenu(+r.dataset.bot); }, 520); }, {passive: true}); @@ -1518,6 +1667,8 @@ function renderHome() { e.stopPropagation(); const f = b.dataset.fmenu; sheet(f, [ + {icon: "arrow-up", label: "往上移", on: () => act("section_move", {folder: f, by: -1}, false)}, + {icon: "arrow-down", label: "往下移", on: () => act("section_move", {folder: f, by: 1}, false)}, {icon: "pen", label: "重新命名分區", on: async () => { const n = await ask("分區名稱", f); if (n && n !== f) app("rename_group", {group: f, new_name: n}); }}, {icon: "trash", label: "刪除分區", danger: true, on: async () => { if (await confirmSheet(`刪除分區「${f}」?`, "裡面的 Bot 會移到未分區,不會刪除任何 Bot。", "刪除分區")) app("delete_group", {group: f}); }}, ]); @@ -1535,6 +1686,13 @@ function botMenu(id) { // 團隊: whether teammates may use this bot (they see its chat, pages and files). if (isOwner() && !b.members) more.push({icon: "users", label: b.team ? "不再分享給團隊成員" : "分享給團隊成員", on: () => act("bot", {bot: id, key: "team", value: !b.team}, b.team ? "團隊成員看不到這個 Bot 了" : "團隊成員現在可以使用這個 Bot")}); if (!b.primary && isOwner()) more.push({icon: "star", label: "設為主要 Bot", on: () => act("bot", {bot: id, key: "primary", value: true}, "已設為主要 Bot")}); + // 已釘選的 Bot in another order (the desktop drags them; here one step at a time). + const pins = (S.pinOrder || []).filter((x) => { const y = bot(x); return y && y.pinned && !y.primary; }); + const at = pins.indexOf(id); + if (isOwner() && b.pinned && at > 0) more.push({icon: "arrow-up", label: "釘選裡往前移", on: () => act("bot", {bot: id, key: "pin_at", value: at - 1}, false)}); + if (isOwner() && b.pinned && at >= 0 && at < pins.length - 1) more.push({icon: "arrow-down", label: "釘選裡往後移", on: () => act("bot", {bot: id, key: "pin_at", value: at + 1}, false)}); + // 分享: the bot as a file (another AnyBot imports it), or this chat as Markdown. + if (isOwner()) more.push({icon: "share", label: "匯出 Bot 檔案(.anybot)", on: () => exportAs("export_bot", id)}); more.push({icon: "refresh", label: "重新啟動這個 Bot", on: () => act("restart_bot", {bot: id})}); items.push({icon: "ellipsis", label: "更多…", on: () => sheet(b.name, more)}); if (isOwner()) items.push({sep: true}, {icon: "trash", label: "刪除 Bot", danger: true, on: () => deleteBot(b)}); @@ -1562,8 +1720,36 @@ $("b-newbot").onclick = async () => { {icon: "sparkles", label: "從範本建立", on: templates}, {icon: "users", label: "建立群組聊天", on: groupChat}, {icon: "folder", label: "新增分區", on: async () => { const n = await ask("新增分區", "", "例如:文宣組"); if (n) app("create_group", {name: n}); }}, + {icon: "download", label: "匯入 Bot 檔案(.anybot)", on: importBot}, ]); }; +// A file the brain made (a bot, a transcript): saved on the phone — the share sheet where there +// is one (iPhone: 儲存到檔案, AirDrop…), else a download. +async function exportAs(what, id) { + const v = await act(what, {bot: id}, false); + if (!v || !v.content) return; + const file = new File([v.content], v.filename || "AnyBot.txt", {type: what === "export_bot" ? "application/json" : "text/markdown"}); + try { if (navigator.canShare && navigator.canShare({files: [file]})) { await navigator.share({files: [file]}); return; } } catch (e) { if (e.name === "AbortError") return; } + const a = document.createElement("a"); a.href = URL.createObjectURL(file); a.download = file.name; document.body.appendChild(a); a.click(); a.remove(); + setTimeout(() => URL.revokeObjectURL(a.href), 4000); + toast("已存成「" + file.name + "」"); +} +async function saveText(text, name) { + const file = new File([text], name, {type: "text/markdown"}); + try { if (navigator.canShare && navigator.canShare({files: [file]})) { await navigator.share({files: [file]}); return; } } catch (e) { if (e.name === "AbortError") return; } + const a = document.createElement("a"); a.href = URL.createObjectURL(file); a.download = name; document.body.appendChild(a); a.click(); a.remove(); + setTimeout(() => URL.revokeObjectURL(a.href), 4000); + toast("已存成「" + name + "」"); +} +function importBot() { + const pick = document.createElement("input"); pick.type = "file"; pick.accept = ".anybot,application/json"; + pick.onchange = async () => { + const f = pick.files && pick.files[0]; if (!f) return; + const v = await act("import_bot", {content: await f.text()}, false); + if (v && v.ok !== false) { toast(v.text || "已匯入"); newBotDone(v); } + }; + pick.click(); +} function newBotDone(v) { if (v && v.bot) setTimeout(() => go("chat", {bot: v.bot}), 400); } async function templates() { if (!S.settings) await loadSettings(); @@ -1696,8 +1882,25 @@ function keepChat(id, msgs, sig) { CHATS.delete(k); CHATS.set(k, was && was.sig === sig && Date.now() - (was.t || 0) <= 3600000 ? was : c); while (CHATS.size > 12) { const old = CHATS.keys().next().value; CHATS.delete(old); KEEP.del("chat:" + old); } } +// What was typed and not sent stays with its bot, as on the computer: switching bots, or closing +// the page, does not lose it (kept on this phone, per AnyBot). +const draftKey = () => "anybot.drafts:" + (S.host || "lan"); +function drafts() { try { return JSON.parse(localStorage.getItem(draftKey()) || "{}"); } catch (_) { return {}; } } +function keepDraft(id, text) { + if (!id) return; + const d = drafts(); + if (text && text.trim()) d[id] = text; else delete d[id]; + try { localStorage.setItem(draftKey(), JSON.stringify(d)); } catch (_) {} +} function openChat(id, at) { S.jumpAt = at || 0; + // (Whose words the box holds is kept on its own: a notification sets S.open before coming here.) + if (S.draftOf !== id) { + const box = $("input"); + keepDraft(S.draftOf, box.value); + S.draftOf = id; + box.value = drafts()[id] || ""; box.style.height = "auto"; setTimeout(() => box.dispatchEvent(new Event("input")), 0); + } if (S.open !== id) { keepChat(S.open, S.msgs, S.chatSig); S.msgs = []; S.pending = []; S.quote = null; S.unfold = {}; S.openSteps = {}; S.chatSig = ""; S.prevShown = 0; S.prevFirst = ""; MODE_OPEN = ""; $("msgs").innerHTML = ""; @@ -1747,7 +1950,7 @@ async function loadChat(jump) { loading = false; if (again) { again = false; loadChat(); } // 任務 → a message older than what the phone keeps of the chat: the chat stays at its end. - else if (S.jumpAt && S.chatLoaded && S.open === id && !jumpTo()) { S.jumpAt = 0; toast("那件事開頭的訊息太早了,手機上只留最近的訊息"); } + else if (S.jumpAt && S.chatLoaded && S.open === id && !jumpTo()) { S.jumpAt = 0; toast("那則訊息太早了,手機上只留最近的訊息"); } } // 載入更早:開頁只拿最新 30 條,這裡一次往回補 60 條(序號去重,接在上方)——從大腦上整段聊天拿, // 不只手機那份最新的。按了一定有回應:載入中、補上了、或「已是對話最開頭」(按鈕收起來)。 @@ -2093,6 +2296,8 @@ function renderMsgs() { h += `
${x.text ? `
${esc(x.text)}
` : ""}${names}
${said}
`; }); $("msgs").innerHTML = h; + // (Diagrams in the answers: drawn by the brain once they are on the page.) + if ($("msgs").querySelector(".chart[data-mermaid]")) loadCharts(); renderSendBtn(); loadFiles(); seenWatch(); @@ -2183,6 +2388,7 @@ function selectSheet(i, m) { el.scrollTop = 0; } async function copyText(t) { try { await navigator.clipboard.writeText(t || ""); toast("已複製"); } catch (_) { toast("這支手機不讓網頁複製"); } } +document.addEventListener("click", (e) => { const b = e.target.closest("[data-copycode]"); if (!b) return; e.stopPropagation(); copyText((b.parentElement.querySelector("code") || {}).textContent || ""); }, true); const QUICK = ["👍", "❤️", "😂", "🎉", "👀", "🙏", "👌", "🔥"]; function msgMenu(i) { const m = S.msgs[i]; if (!m) return; @@ -2217,7 +2423,7 @@ function renderDock() { const own = /的電腦$/.test(a.computer || "") && S.boxOn; $("ask").innerHTML = `
${ic("hand", 16)} 需要處理 · ${esc(a.computer || "")}
${esc(a.reason)}
${own ? `` : ""}
`; $("ask").querySelector("[data-screen]").onclick = () => openBox(true); - if (own) { const load = () => boxThumb($("hand-thumb")); load(); thumbTimer = setInterval(load, 3000); } + if (own) { const load = () => boxThumb($("hand-thumb"), b.id); load(); thumbTimer = setInterval(load, 3000); } } else { // 智慧模式開著時主按鈕是「這輪都准」(这一轮同类不再问,比「一律允許」小一格);否则主按鈕是「允許一次」。 const yes = a.can_scope ? `` : ``; @@ -2312,6 +2518,9 @@ function renderDockRest(b) { try { await api(base() + `api/bots/${S.open}/send`, {json: {text: "/goal clear", attachments: []}}); toast("已清除目標"); loadChat(); } catch (e) { toast(e.message); } }; $("planbar").innerHTML = pl && MODE_OPEN === "plan" ? `
${ic("list-checks", 14)}${esc(pl.line)}
${owner() ? `` : ""}
` : ""; + // 一律放行 is on (every chat: it is everyone's), with 關閉 — as the desktop's icon above the input. + $("alwaysbar").innerHTML = S.always ? `
${ic("zap", 14)}一律放行開著:要允許的都自動答應
${isOwner() ? `` : ""}
` : ""; + if ($("always-x")) $("always-x").onclick = async () => { if (await act("setting", {key: "always_approve", value: false, bot: S.open}, false)) toast("一律放行關了"); }; if ($("plan-x")) $("plan-x").onclick = async () => { try { await api(base() + `api/bots/${S.open}/send`, {json: {text: "/plan clear", attachments: []}}); toast("已取消計畫"); loadChat(); } catch (e) { toast(e.message); } }; @@ -2320,10 +2529,11 @@ function renderDockRest(b) { renderSendBtn(); } const BOXIMG = {}; -async function boxThumb(img) { +// (Of this bot's own screen when it has one open; else the shared one.) +async function boxThumb(img, bot) { if (!img) return; try { - const r = await api(base() + "api/box/thumb", {raw: true}); + const r = await api(base() + "api/box/thumb" + (bot ? "?bot=" + bot : ""), {raw: true}); if (!r.ok) throw new Error(); const u = URL.createObjectURL(await safeBlob(r)); if (BOXIMG.last) URL.revokeObjectURL(BOXIMG.last); @@ -2337,6 +2547,7 @@ function renderQuote() { if (q) $("q-x").onclick = () => { S.quote = null; renderQuote(); }; } const input = $("input"); +input.addEventListener("input", () => { clearTimeout(S.draftTimer); S.draftTimer = setTimeout(() => keepDraft(S.draftOf, input.value), 400); }); input.addEventListener("input", () => { input.style.height = "auto"; input.style.height = Math.min(input.scrollHeight, 140) + "px"; $("composer").classList.toggle("tall", input.scrollHeight > 40); renderSendBtn(); @@ -2481,7 +2692,7 @@ async function send() { memReset(); // (A command takes no file that isn't up yet: those stay above the input for the next message.) const had = S.pending; S.pending = quiet ? S.pending.filter((p) => p.blob) : []; - input.value = ""; input.style.height = "auto"; $("composer").classList.remove("tall"); renderChips(); renderSlash(); + input.value = ""; keepDraft(S.open, ""); input.style.height = "auto"; $("composer").classList.remove("tall"); renderChips(); renderSlash(); // A command (not words for the chat): sent now, or said that it couldn't be (its words and files back). if (quiet) { try { await deliver(base() + `api/bots/${S.open}/send`, {text, attachments}); loadChat(); } catch (e) { toast(e.message); if (!input.value) { input.value = text; input.dispatchEvent(new Event("input")); } S.pending = [...had.filter((p) => !S.pending.includes(p)), ...S.pending]; renderChips(); } return; } // 先顯示: in the chat at once, network or not; it goes when the line is there (kept on this @@ -2648,6 +2859,7 @@ $("b-chatmore").onclick = () => { {icon: "info", label: "對話詳細資訊", on: () => go("details", {bot: b.id})}, {icon: "history", label: "過去的對話", x: String((b.threads || []).length || ""), on: () => threads(b)}, {icon: "copy", label: "複製整段對話", on: () => copyText(S.msgs.filter((m) => m.text && !m.summary).map((m) => (m.role === "user" ? "我:" : b.name + ":") + m.text).join("\n\n"))}, + ...(owner() ? [{icon: "download", label: "匯出文字記錄(.md)", on: () => exportAs("export_transcript", b.id)}] : []), ]; if (owner()) items.splice(1, 0, {icon: "refresh", label: "重新產生上一個回答", on: regen}); if (isOwner()) items.push({icon: "settings", label: "Bot 設定", on: () => go("botset", {bot: b.id})}); @@ -2702,6 +2914,13 @@ async function freshDetail(id) { } const item = (o) => `<${o.tap ? "button" : "div"} class="item ${o.danger ? "danger" : ""}" ${o.data || ""}>${o.icon ? ic(o.icon, 19) : ""}
${esc(o.k)}
${o.v ? `
${esc(o.v)}
` : ""}
${o.r != null ? `
${esc(o.r)}
` : ""}${o.sw != null ? `` : ""}${o.tap && o.chev !== false ? `${ic("chevron-right", 16)}` : ""}`; const group = (title, inner, extra = "") => `${title ? `
${esc(title)}${extra}
` : ""}
${inner}
`; +// 設定 rows all have a picture (as on the computer, src/icons.rs setting_icon): by the words in +// the name, first match wins; a name that matches none gets the sliders. +const SET_ICON = [[["上網"], "globe"], [["頁面"], "file-text"], [["合作", "同事"], "users"], [["電話", "簡訊"], "message"], [["Mac App"], "laptop"], [["管理 App"], "settings"], [["主題"], "moon"], [["風格", "強調色", "顏色", "外觀"], "palette"], [["頭像", "形狀"], "smile-plus"], [["語言", "時區"], "globe"], [["通知", "響一聲"], "bell"], [["記憶"], "brain"], [["資料夾", "文件", "檔案", "資料庫"], "folder"], [["金鑰", "Token", "密碼", "保險庫", "兩步"], "lock"], [["瀏覽器", "網址"], "globe"], [["更新", "版本", "重新啟動"], "refresh"], [["備份", "還原", "快照"], "history"], [["磁碟", "用量"], "hard-drive"], [["團隊", "成員", "分享"], "users"], [["帳號", "登入", "登出", "角色", "名稱"], "info"], [["手機", "裝置"], "smartphone"], [["語音", "聲音"], "audio-lines"], [["規則", "權限", "直接操作", "一律", "允許", "詢問", "審核", "隔離"], "shield"], [["連接器", "整合"], "plug"], [["管道"], "message"], [["技能"], "sparkles"], [["模型", "思考", "步驟"], "sparkles"], [["電腦", "螢幕", "Docker", "主機", "終端機"], "monitor"], [["例行"], "alarm-clock"], [["指示", "描述", "擅長", "不找"], "pen"], [["釘選"], "pin"], [["分區"], "folder"], [["主要"], "star"]]; +const SMART_SECS = [[30, "30 秒後"], [60, "1 分鐘後"], [120, "2 分鐘後"], [300, "5 分鐘後"], [600, "10 分鐘後"]]; +const VOICE_KINDS = [["off", "關閉"], ["open_ai", "OpenAI 相容"], ["xai", "xAI"], ["eleven_labs", "ElevenLabs"]]; +const setIcon = (k) => (SET_ICON.find(([ws]) => ws.some((w) => String(k || "").includes(w))) || [0, "settings"])[1]; +const sitem = (o) => item(o.icon || o.noIcon ? o : {...o, icon: setIcon(o.k)}); async function loadAudit(id) { try { S.audit[id] = await api(base() + `api/bots/${id}/audit`); } catch (e) { S.audit[id] = {turns: []}; } if (cur().v === "details" && S.tab === "audit") renderDetails(id, "audit", true); @@ -2742,11 +2961,15 @@ function tabBody(b, d) { const a = S.audit[b.id]; if (a === undefined) { loadAudit(b.id); return `
載入中…
`; } if (!a.turns.length) return `
最近 30 天沒有工作紀錄。
`; + // 只看沒人看著時做的 (as on the computer): the turns a routine or another bot started. + const alone = !!S.auditAlone, turns = alone ? a.turns.filter((t) => t.who && t.who !== "person") : a.turns; const OUT = {completed: "已結束", aborted: "被你停止", failed: "失敗"}; const ST = {done: "完成", running: "進行中…", waiting: "等核准", denied: "沒有完成(拒絕或停止)", failed: "失敗"}; const TI = {computer: "zap", menu_click: "zap", fill_form: "zap", wait_for: "clock", run_cmd: "zap", web_fetch: "globe", browser: "globe"}; let h = ""; - for (const t of [...a.turns].reverse()) { + h += `
`; + if (!turns.length) h += `
最近 30 天沒有沒人看著時做的事。
`; + for (const t of [...turns].reverse()) { const steps = t.steps.map((x) => { if (x.type === "model") return item({icon: "sparkles", k: x.step === "assistant" ? "問模型" : x.step === "compaction" ? "整理長對話" : x.step, v: x.attempts > 1 ? `試了 ${x.attempts} 次(有重試)` : ""}); if (x.type === "tool") return item({icon: TI[x.name] || "zap", k: x.name, v: (x.args || "").slice(0, 200), r: ST[x.status] || x.status}); @@ -2814,6 +3037,7 @@ function wireDetails(b, d) { else if (k === "mac") go("screen"); }); on("[data-forget]", async (x) => { if (await app("forget", {what: x.dataset.forget}, b.id)) renderDetails(b.id, S.tab); }); + el.querySelectorAll("[data-alone]").forEach((x) => x.onchange = () => { S.auditAlone = x.checked; renderDetails(b.id, S.tab); }); on("[data-sg]", (x) => { const s = SUGGEST[+x.dataset.sg]; back(); setTimeout(() => { input.value = s[3]; input.focus(); input.dispatchEvent(new Event("input")); }, 60); }); on("[data-rt]", (x) => routineSheet(b, (d.routines || []).find((r) => r.id === +x.dataset.rt))); on("[data-mem]", (x) => oneAtATime(async () => { @@ -2823,7 +3047,7 @@ function wireDetails(b, d) { ids.has(id) ? ids.delete(id) : ids.add(id); if (await act("bot", {bot: b.id, key: "members", value: [...ids]}, "已更新成員")) { delete S.detail[b.id]; renderDetails(b.id, S.tab); } })); - const t = $("box-thumb"); if (t) boxThumb(t); + const t = $("box-thumb"); if (t) boxThumb(t, b.id); el.querySelectorAll(".files [data-img]").forEach(async (f) => { if (f.querySelector("img")) return; try { const u = await fileUrl(f.dataset.file); f.innerHTML = ``; } catch (_) {} }); el.querySelectorAll(".files [data-img]").forEach((f) => f.onclick = async () => { try { window.open(await fileUrl(f.dataset.file), "_blank"); } catch (e) { toast(e.message); } }); } @@ -3038,24 +3262,32 @@ async function renderBotset(id) { let d = S.detail[id] || await loadDetail(id) || {}; if (cur().v !== "botset") return; const st = S.settings || {}; - const CTX = [[32000, "32K"], [64000, "64K"], [128000, "128K"], [200000, "200K"], [1000000, "1M"]]; + const CTX = [[32000, "32K"], [64000, "64K"], [128000, "128K"], [200000, "200K"], [400000, "400K"], [1000000, "1M"]]; // Shown from a copy kept from before: read anew first, then it can be changed. const held = !isNew(id); let h = `
${face(b, "lg")}
${esc(b.name)}
${held ? `
顯示的是上次的設定,讀到最新的才能改
` : ""}
`; - h += group("基本", item({k: "名稱", r: b.name, tap: 1, data: 'data-e="name"'}) + item({k: "描述", v: d.description || "還沒有寫", tap: 1, data: 'data-e="desc"'}) + item({k: "指示", v: d.instructions ? d.instructions.slice(0, 160) + (d.instructions.length > 160 ? "…" : "") : "還沒有寫", tap: 1, data: 'data-e="instr"'})); + h += group("基本", sitem({k: "名稱", r: b.name, tap: 1, data: 'data-e="name"'}) + sitem({k: "描述", v: d.description || "還沒有寫", tap: 1, data: 'data-e="desc"'}) + sitem({k: "指示", v: d.instructions ? d.instructions.slice(0, 160) + (d.instructions.length > 160 ? "…" : "") : "還沒有寫", tap: 1, data: 'data-e="instr"'})); if (isOwner()) { - h += group("個人檔案", item({k: "擅長", v: d.strengths || "還沒有寫(同事會看到,知道什麼事找它)", tap: 1, data: 'data-e="strengths"'}) + item({k: "不找它做的事", v: d.not_for || "還沒有寫", tap: 1, data: 'data-e="not_for"'})); - const ticks = (title, key, list, note) => (list || []).length ? group(title, list.map((x) => item({k: x.name, v: x.note || "", sw: !!x.on, swdata: `data-tick="${key}" data-key="${esc(x.key)}"`, disabled: !!x.fixed})).join("") + (note ? `
${note}
` : "")) : ""; + h += group("個人檔案", sitem({k: "擅長", v: d.strengths || "還沒有寫(同事會看到,知道什麼事找它)", tap: 1, data: 'data-e="strengths"'}) + sitem({k: "不找它做的事", v: d.not_for || "還沒有寫", tap: 1, data: 'data-e="not_for"'})); + const ticks = (title, key, list, note) => (list || []).length ? group(title, list.map((x) => sitem({k: x.name, v: x.note || "", sw: !!x.on, swdata: `data-tick="${key}" data-key="${esc(x.key)}"`, disabled: !!x.fixed})).join("") + (note ? `
${note}
` : "")) : ""; h += ticks("能力", "abilities", d.abilities, "沒勾的工具不會給它,也不佔它每一輪的字數。"); - h += ticks("會的技能", "skills", d.skills, ""); + h += ticks("會的技能", "skills", d.skills, "") .replace(/^(
會的技能)/, `$1`); h += ticks("可以用的電腦", "may_use", (d.may_use || []).length > 1 ? d.may_use : [], "它自己的電腦一定可以用。"); } - h += `
頭像
${(st.shapes || []).map((s) => ``).join("")}
${(st.colors || []).map((c) => ``).join("")}
`; - h += group("AI 與電腦", item({icon: "sparkles", k: "模型", v: b.via || b.model, r: b.runs || "", tap: 1, data: 'data-e="model"'}) + item({icon: "monitor", k: "做事的電腦", r: b.computer || "", tap: 1, data: 'data-e="comp"'}) + item({icon: "terminal", k: "電腦操作", v: S.settings && S.settings.direct_mode ? "直接操作開著:照樣可以用電腦(關掉直接操作才照這裡)" : "關掉時,用電腦前會先問你", sw: d.tools_enabled !== false, swdata: 'data-sw="tools"', disabled: !isOwner()}) + item({icon: "brain", k: "模型可讀長度", r: (CTX.find((c) => c[0] === d.context_tokens) || [0, Math.round((d.context_tokens || 0) / 1000) + "K"])[1], tap: 1, data: 'data-e="ctx"'})); + h += `
頭像
${(st.shapes || []).map((s) => ``).join("")}
${(st.colors || []).map((c) => ``).join("")}${isOwner() ? `` : ""}
`; + // (As on the computer's Bot 設定: who carries out the planned steps, and how long it thinks.) + const EFFORTS = [["", "自動(模型自己決定)"], ["low", "快速(想得少,回得快)"], ["medium", "平衡"], ["high", "深入(想得久,較慢)"]]; + const stepShown = !d.step_model ? "自動" : d.step_model === "off" ? "不分開" : d.step_model; + const fbs = d.fallbacks || []; + const extra2 = isOwner() ? sitem({icon: "refresh", k: "備用模型", v: fbs.length ? fbs.map((f) => f.model).join("、") : "主模型失敗時改用(還沒有)", tap: 1, data: 'data-e="fallbacks"'}) + sitem({icon: "folder", k: "起始資料夾", v: d.workdir || "", tap: 1, data: 'data-e="workdir"'}) : ""; + const extra = isOwner() ? sitem({icon: "zap", k: "執行步驟用的模型", v: "想計畫和確認用上面的模型;照計畫做的步驟交給這個比較快的", r: stepShown, tap: 1, data: 'data-e="step"'}) + sitem({icon: "lightbulb", k: "思考模式", r: (EFFORTS.find((e) => e[0] === (d.thinking || "")) || EFFORTS[0])[1].replace(/(.*)/, ""), tap: 1, data: 'data-e="think"'}) : ""; + h += group("AI 與電腦", sitem({icon: "sparkles", k: "模型", v: b.via || b.model, r: b.runs || "", tap: 1, data: 'data-e="model"'}) + extra + extra2 + sitem({icon: "monitor", k: "做事的電腦", r: b.computer || "", tap: 1, data: 'data-e="comp"'}) + sitem({icon: "terminal", k: "電腦操作", v: S.settings && S.settings.direct_mode ? "直接操作開著:照樣可以用電腦(關掉直接操作才照這裡)" : "關掉時,用電腦前會先問你", sw: d.tools_enabled !== false, swdata: 'data-sw="tools"', disabled: !isOwner()}) + sitem({icon: "brain", k: "模型可讀長度", r: (CTX.find((c) => c[0] === d.context_tokens) || [0, Math.round((d.context_tokens || 0) / 1000) + "K"])[1], tap: 1, data: 'data-e="ctx"'})); + // 語音聊天 (as the computer's right panel): read every answer aloud, the voice, speed, language. + if (isOwner()) h += group("語音", sitem({icon: "audio-lines", k: "朗讀每個回答", v: "回答好了就唸出來(要先在 設定 › 語音 選「說」的服務)", sw: !!d.speak_replies, swdata: 'data-sw="speak_replies"'}) + sitem({icon: "smile-plus", k: "聲音", r: d.voice || "跟著 設定 › 語音", tap: 1, data: 'data-e="voice"'}) + sitem({icon: "zap", k: "速度", r: (d.voice_rate || 1) + " 倍", tap: 1, data: 'data-e="rate"'}) + sitem({icon: "globe", k: "語言", r: ({"": "自動", "zh-TW": "中文", en: "英文", ja: "日文"})[d.voice_lang || ""] || d.voice_lang, tap: 1, data: 'data-e="vlang"'})); if (isOwner()) h += group("已設定「一律允許」", (d.allow_rules || []).map((r) => `
${ic("shield", 17)}
${esc(r)}
`).join("") || `
還沒有。在核准時選「一律允許」就會記在這裡。
`); - h += group("整理", item({icon: "pin", k: "釘選", sw: !!d.pinned, swdata: 'data-sw="pinned"'}) + item({icon: "star", k: "主要 Bot", v: d.primary ? "這是主要 Bot" : "", sw: !!d.primary, swdata: 'data-sw="primary"', disabled: !!d.primary}) + item({icon: "folder", k: "分區", r: d.folder || "未分區", tap: 1, data: 'data-e="folder"'})); - if ((d.demos || []).length) h += group("示範教學", d.demos.map((x) => item({icon: "eye", k: x.name, v: `${x.steps} 個步驟 · ${x.created}`})).join("") + `
示範要在那台電腦上錄;Bot 在對話裡會照著做。
`); - h += group("", item({icon: "refresh", k: "重新啟動這個 Bot", v: "卡住時用:停止它正在做的事和背景指令", tap: 1, data: 'data-e="restart"', chev: false}) + item({icon: "trash", k: "清除聊天記錄", tap: 1, data: 'data-e="clear"', danger: true, chev: false}) + (isOwner() ? item({icon: "trash", k: "刪除 Bot", tap: 1, data: 'data-e="delete"', danger: true, chev: false}) : "")); + h += group("整理", sitem({icon: "pin", k: "釘選", sw: !!d.pinned, swdata: 'data-sw="pinned"'}) + sitem({icon: "star", k: "主要 Bot", v: d.primary ? "這是主要 Bot" : "", sw: !!d.primary, swdata: 'data-sw="primary"', disabled: !!d.primary}) + sitem({icon: "folder", k: "分區", r: d.folder || "未分區", tap: 1, data: 'data-e="folder"'})); + if ((d.demos || []).length) h += group("示範教學", d.demos.map((x) => sitem({icon: "eye", k: x.name, v: `${x.steps} 個步驟 · ${x.created}`})).join("") + `
示範要在那台電腦上錄;Bot 在對話裡會照著做。
`); + h += group("", sitem({icon: "refresh", k: "重新啟動這個 Bot", v: "卡住時用:停止它正在做的事和背景指令", tap: 1, data: 'data-e="restart"', chev: false}) + sitem({icon: "trash", k: "清除聊天記錄", tap: 1, data: 'data-e="clear"', danger: true, chev: false}) + (isOwner() ? sitem({icon: "trash", k: "刪除 Bot", tap: 1, data: 'data-e="delete"', danger: true, chev: false}) : "")); $("botset").innerHTML = h + `
`; const el = $("botset"); el.classList.toggle("held", held); @@ -3063,7 +3295,21 @@ async function renderBotset(id) { const refresh = () => { delete S.detail[id]; setTimeout(() => cur().v === "botset" && renderBotset(id), 300); }; el.querySelectorAll("[data-shape]").forEach((x) => x.onclick = async () => { if (await act("bot", {bot: id, key: "shape", value: x.dataset.shape}, false)) refresh(); }); el.querySelectorAll("[data-color]").forEach((x) => x.onclick = async () => { if (await act("bot", {bot: id, key: "color", value: x.dataset.color}, false)) refresh(); }); + // 自訂顏色: the phone's own colour picker; the bot wears #rrggbb. + el.querySelectorAll("[data-color-own]").forEach((x) => x.onclick = () => { + const pick = document.createElement("input"); pick.type = "color"; pick.value = /^#[0-9a-f]{6}$/i.test(d.color || "") ? d.color : "#c06244"; + pick.style.cssText = "position:fixed;opacity:0;pointer-events:none"; document.body.appendChild(pick); + pick.onchange = async () => { pick.remove(); if (await act("bot", {bot: id, key: "color", value: pick.value}, "已換顏色")) refresh(); }; + pick.click(); + }); el.querySelectorAll("[data-rule]").forEach((x) => x.onclick = async () => { if (await act("bot", {bot: id, key: "allow_remove", value: x.dataset.rule}, "已移除")) refresh(); }); + // 技能:全選/全不選 at once (the brain's list as it is now, all on or all off). + el.querySelectorAll("[data-allsk]").forEach((x) => x.onclick = () => oneAtATime(async () => { + const now = await freshDetail(id); + if (!now) { toast("連上後才能改"); return; } + const all = (now.skills || []).every((y) => y.on); + if (await act("bot", {bot: id, key: "skills", value: all ? [] : (now.skills || []).map((y) => y.key)}, all ? "技能都不帶了" : "技能都帶上了")) { delete S.detail[id]; refresh(); } + })); el.querySelectorAll("[data-tick]").forEach((x) => x.onchange = () => oneAtATime(async () => { // (The whole ticked list goes: the app keeps "all of them" as no list at all.) // (Built on the brain's list as it is now, with only this tick changed: never a list read @@ -3091,6 +3337,26 @@ async function renderBotset(id) { else if (k === "not_for") { const n = await ask("不找它做的事", d.not_for || "", "例如:不寫程式、不碰帳務", true); if (n != null && n !== (d.not_for || "") && await act("bot", {bot: id, key: "not_for", value: n}, "已更新")) refresh(); } else if (k === "model") modelSheet(b); else if (k === "comp") pickComputer(b, d); + else if (k === "fallbacks") { + const save = async (list, ok) => { if (await act("bot", {bot: id, key: "fallbacks", value: list.map((f) => ({provider: f.provider, model: f.model}))}, ok)) refresh(); }; + const add = () => { + const items = []; + for (const p of S.models || []) { items.push({group: p.label}); for (const m of p.models || []) items.push({label: m, on: () => save([...fbs, {provider: p.provider, model: m}], "已加入備用模型")}); } + sheet("加一個備用模型", items); + }; + sheet("備用模型(照順序試)", [{group: "主模型失敗(額度用完、連不上)時照順序改用"}, ...fbs.map((f, i) => ({icon: "x", label: `${i + 1}. ${f.label} · ${f.model}`, x: "移除", on: () => save(fbs.filter((_, j) => j !== i), "已移除")})), ...(fbs.length < 8 ? [{icon: "plus", label: "加一個備用模型…", on: () => setTimeout(add, 60)}] : [])]); + } + else if (k === "voice") { const v = await ask("聲音(空白=跟著 設定 › 語音)", d.voice || ""); if (v != null && await act("bot", {bot: id, key: "voice", value: v}, "已更新")) refresh(); } + else if (k === "rate") sheet("朗讀速度", [0.8, 1, 1.2, 1.5, 2].map((r) => ({label: r + " 倍", check: (d.voice_rate || 1) === r, on: async () => { if (await act("bot", {bot: id, key: "voice_rate", value: r}, "已更新")) refresh(); }}))); + else if (k === "vlang") sheet("朗讀的語言", [["", "自動"], ["zh-TW", "中文"], ["en", "英文"], ["ja", "日文"]].map(([v, n]) => ({label: n, check: (d.voice_lang || "") === v, on: async () => { if (await act("bot", {bot: id, key: "voice_lang", value: v}, "已更新")) refresh(); }}))); + else if (k === "workdir") { const w = await ask("起始資料夾(它的檔案和指令從這裡開始)", d.workdir || ""); if (w && w !== d.workdir && await act("bot", {bot: id, key: "workdir", value: w}, "已更新起始資料夾")) refresh(); } + else if (k === "think") sheet("思考模式", [{group: "想得越久越仔細,也越慢、越花額度"}].concat(EFFORTS.map(([v, l]) => ({label: l, check: v === (d.thinking || ""), on: async () => { if (await act("bot", {bot: id, key: "thinking", value: v}, "已更新")) refresh(); }})))); + else if (k === "step") { + const models = ((S.models || []).find((p) => p.provider === b.provider) || {}).models || []; + const pick = (v, ok) => async () => { if (await act("bot", {bot: id, key: "step_model", value: v}, ok)) refresh(); }; + sheet("執行步驟用的模型", [{label: "自動", check: !d.step_model, on: pick("", "已改成自動")}, {label: "不分開(每一步都用上面的模型)", check: d.step_model === "off", on: pick("off", "已改成不分開")}] + .concat(models.filter((m) => m !== b.model).map((m) => ({label: m, check: d.step_model === m, on: pick(m, "步驟改用 " + m)})))); + } else if (k === "ctx") sheet("模型可讀長度", CTX.map(([n, l]) => ({label: l + " 個 token", check: n === d.context_tokens, on: async () => { if (await act("bot", {bot: id, key: "context", value: n}, "已更新")) refresh(); }}))); else if (k === "folder") moveToFolder(b); else if (k === "restart") act("restart_bot", {bot: id}); @@ -3112,7 +3378,7 @@ async function loadSettings() { } catch (e) { S.settingsOld = true; toast(e.message); } return S.settings; } -const SETTINGS_PAGES = ["computers", "settings", "general", "models", "perms", "integrations", "vault", "account", "updates"]; +const SETTINGS_PAGES = ["computers", "settings", "general", "models", "perms", "integrations", "vault", "voice", "account", "updates"]; /** Something changed on the computer (the state's version moved): the settings read before are * old — the page showing them is read again now, any other the next time it opens. (They were * read once: after /always-approve filled the 一律詢問 rules, 權限 still said 還沒有規則.) */ @@ -3127,7 +3393,7 @@ async function settingsChanged() { } let listTimer = null; function stopListTimer() { clearInterval(listTimer); listTimer = null; } -const TITLES = {tasks: "任務", routines: "例行任務", pages: "頁面", computers: "電腦", settings: "設定", general: "一般", models: "模型", perms: "權限", integrations: "整合", vault: "保險庫", account: "手機與帳號", updates: "更新"}; +const TITLES = {tasks: "任務", files: "所有檔案", schedule: "日程", workflows: "工作流", routines: "例行任務", pages: "頁面", computers: "電腦", settings: "設定", general: "一般", me: "個人資料與用量", models: "模型", perms: "權限", integrations: "整合", vault: "保險庫", voice: "語音", account: "手機與帳號", updates: "更新"}; async function renderList(arg) { const kind = arg.kind; $("list-title").textContent = TITLES[kind] || ""; @@ -3137,6 +3403,10 @@ async function renderList(arg) { if (kind === "tasks") return listTasks(el); if (kind === "routines") return listRoutines(el); if (kind === "pages") return listPages(el); + if (kind === "me") return listMe(el); + if (kind === "workflows") return listWorkflows(el, arg.wf); + if (kind === "schedule") return listSchedule(el); + if (kind === "files") return listFiles(el); if (SETTINGS_PAGES.includes(kind)) { // (Drawn from what this phone has at once; read again behind it when it may be old.) if (!S.settings) { el.innerHTML = `
載入中…
`; await loadSettings(); } @@ -3147,6 +3417,221 @@ async function renderList(arg) { if (["computers", "integrations"].includes(kind)) listTimer = setInterval(async () => { await loadSettings(); if (cur().v === "list" && cur().arg.kind === kind) drawSettings(kind, true); }, 4000); } } +// ---------- 所有檔案 ---------- +// Every file the bots handed over or were given, across bots and conversations (from the +// attachments the chats keep, as on the computer): by kind, a search, pictures as a grid; a tap +// opens it in the viewer. A file moved or deleted since is greyed out and says 不見了. +const LIB = {kind: "all", q: "", files: null}; +const THUMBS = new Map(); +const LIB_KINDS = [["all", "全部"], ["image", "圖片"], ["doc", "文件"], ["code", "程式碼"], ["sheet", "表格"], ["media", "影音"], ["other", "其他"]]; +const LIB_ICON = {image: "image", doc: "file-text", code: "terminal", sheet: "list-checks", media: "play", other: "file"}; +const fsize = (n) => !n ? "" : n < 1024 ? n + " B" : n < 1048576 ? Math.round(n / 1024) + " KB" : (n / 1048576).toFixed(1) + " MB"; +async function listFiles(el) { + const here = () => cur().v === "list" && cur().arg.kind === "files"; + if (LIB.files) drawFiles(el); else el.innerHTML = `
載入中…
`; + const v = await act("library", {}, false); + if (!here() || !v) return; + LIB.files = v.files || []; + drawFiles(el); +} +function drawFiles(el) { + const all = LIB.files || [], q = LIB.q.trim().toLowerCase(); + const byQ = all.filter((f) => !q || f.name.toLowerCase().includes(q)); + const count = (k) => byQ.filter((f) => k === "all" || f.kind === k).length; + if (LIB.kind !== "all" && !count(LIB.kind)) LIB.kind = "all"; + const shown = byQ.filter((f) => LIB.kind === "all" || f.kind === LIB.kind); + let h = `
${LIB_KINDS.filter(([k]) => k === "all" || count(k)).map(([k, l]) => ``).join("")}
`; + if (!all.length) h += `
還沒有檔案。
你傳給 Bot、Bot 交給你的檔案都會收在這裡。
`; + else if (!shown.length) h += `
沒有相符的檔案
`; + else { + const pics = shown.filter((f) => f.image && f.there), rest = shown.filter((f) => !(f.image && f.there)); + if (pics.length) h += `
${pics.slice(0, 120).map((f) => ``).join("")}
`; + if (rest.length) h += group("", rest.slice(0, 300).map((f) => { const b = bot(f.bot) || {}; return ``; }).join("")); + } + h += `
`; + el.innerHTML = h; + const qEl = $("lib-q"); + qEl.oninput = () => { LIB.q = qEl.value; const pos = qEl.selectionStart; drawFiles(el); const n = $("lib-q"); n.focus(); n.setSelectionRange(pos, pos); }; + el.querySelectorAll("[data-lk]").forEach((b) => b.onclick = () => { LIB.kind = b.dataset.lk; drawFiles(el); }); + el.querySelectorAll("[data-lf]").forEach((b) => b.onclick = () => openFile(b.dataset.lf, b.dataset.ln)); + // Thumbnails as they come into view (the brain's own small copies of the pictures). + const io = new IntersectionObserver((es) => es.forEach(async (e) => { + if (!e.isIntersecting) return; + io.unobserve(e.target); + try { const r = await api(base() + "api/preview/image?path=" + encodeURIComponent(e.target.dataset.thumb), {raw: true}); if (r.ok) { const u = URL.createObjectURL(await safeBlob(r)); THUMBS.set(e.target.dataset.thumb, u); e.target.src = u; } } catch (_) {} + }), {root: el}); + el.querySelectorAll("img[data-thumb]").forEach((i) => io.observe(i)); +} +// ---------- 日程 ---------- +// What the bots are set to do, as on the computer's 日程: 即將執行 (each routine or workflow once, +// at its next time), then day by day from three days back to a week ahead — what ran on its own +// and how it went (✓ ✗ ■), what is coming, what is paused. (What you ran by hand is in each +// one's own runs, not here.) +const SCH_MARK = {done: ["good", "circle-check", "完成"], failed: ["bad", "circle-x", "失敗"], stopped: ["", "minus", "停止了"], running: ["go", "loader", "執行中"], coming: ["", "clock", ""], paused: ["todo", "pause", "暫停中"]}; +async function listSchedule(el) { + const here = () => cur().v === "list" && cur().arg.kind === "schedule"; + S.schedShown = false; + if (S.sched) drawSchedule(el); else el.innerHTML = `
載入中…
`; + const v = await act("schedule", {}, false); + if (!here() || !v) return; + S.sched = v; + drawSchedule(el); +} +function schedDay(d, today) { + const [y, m, dd] = d.split("-").map(Number), t = new Date(y, m - 1, dd), [ty, tm, td] = today.split("-").map(Number); + const diff = Math.round((t - new Date(ty, tm - 1, td)) / 864e5); + const wd = "日一二三四五六"[t.getDay()]; + return (diff === 0 ? "今天・" : diff === 1 ? "明天・" : diff === -1 ? "昨天・" : "") + `${m}月${dd}日(${wd})`; +} +function drawSchedule(el) { + const v = S.sched || {}, items = v.items || [], today = v.today || ""; + const row = (i, showDay) => { + const b = bot(i.bot) || {}, [cls, icon, word] = SCH_MARK[i.status] || ["", "clock", ""]; + const right = showDay ? (i.day === today ? "今天 " : schedDay(i.day, today).replace(/(.)$/, "") + " ") + i.clock : word; + return ``; + }; + let h = group("即將執行", (v.coming || []).map((i) => row(i, true)).join("") || `
接下來兩週沒有排定的事
`); + const days = [...new Set(items.map((i) => i.day))]; + if (!days.includes(today)) days.push(today); + days.sort(); + for (const d of days) { + const list = items.filter((i) => i.day === d); + if (!list.length && d !== today) continue; + h += group(schedDay(d, today), list.map((i) => row(i, false)).join("") || `
這一天沒有排定的事
`); + } + h += `
只放排程或事件自己跑的;你按的「立即執行」在各自的執行紀錄裡。新增:在聊天裡跟 Bot 說「每天早上 9 點幫我…」。
`; + const sc = el.scrollTop; + el.innerHTML = h; + // (Today in view the first time; where you were after that.) + if (!S.schedShown) { S.schedShown = true; const t = [...el.querySelectorAll(".gt")].find((g) => g.textContent.startsWith("今天")); if (t) t.scrollIntoView({block: "start"}); } else el.scrollTop = sc; + el.querySelectorAll("[data-sch]").forEach((x) => x.onclick = async () => { + const [kind, id, bid] = x.dataset.sch.split(":"); + if (kind === "workflow") return go("list", {kind: "workflows", wf: +id}); + const b = bot(+bid); if (!b) return; + const d = S.detail[b.id] || await loadDetail(b.id) || {}; + const r = (d.routines || []).find((y) => y.id === +id); + if (r) routineSheet(b, r); else go("chat", {bot: b.id}); + }); +} +// ---------- 工作流 ---------- +// The workflows on the brain: what starts each, its steps in order, how its runs went — run it, +// stop it, answer the 等你確認 a 審批 step waits on. (Drawing and editing are on the computer's +// canvas, or by asking a bot in the chat.) +const WF_ICON = {"觸發器": "zap", "提示詞": "text-cursor", "素材": "paperclip", "助手": "bot", "LLM": "sparkles", "圖片": "image", "影片": "play", "審批": "hand", "條件": "list-checks", "輸出": "send"}; +const WF_STATE = {running: ["go", "執行中"], waiting: ["wait", "等你確認"], done: ["good", "完成"], failed: ["bad", "失敗"], stopped: ["", "停止了"]}; +// A step's own state: not reached yet is just dimmed; the one a waiting run stands on waits for you. +const WF_STEP = {waiting: ["todo", ""], running: ["go", "進行中"], done: ["good", "完成"], failed: ["bad", "失敗"], skipped: ["skip", "略過"]}; +const stepLook = (s, run, id) => !s ? ["", ""] : s.state === "running" && run && run.state === "waiting" && (run.steps || []).find((x) => x.state === "running") === s ? ["wait", "等你確認"] : WF_STEP[s.state] || ["", ""]; +async function listWorkflows(el, wf) { + const here = () => cur().v === "list" && cur().arg.kind === "workflows" && cur().arg.wf === wf; + if (S.wfs) drawWorkflows(el, wf); else el.innerHTML = `
載入中…
`; + const v = await act("workflows", {}, false); + if (!here()) return; + S.wfs = (v && v.workflows) || S.wfs || []; + drawWorkflows(el, wf); + // (While one runs, how it goes is read again every few seconds.) + stopListTimer(); + if (S.wfs.some((w) => w.live)) listTimer = setInterval(async () => { const v = await act("workflows", {}, false); if (!here()) return stopListTimer(); if (v) { S.wfs = v.workflows || []; drawWorkflows(el, wf); if (!S.wfs.some((w) => w.live)) stopListTimer(); } }, 3000); +} +function wfLine(w) { + const r = w.live || w.runs[0]; + return [w.when, w.step_count + " 個步驟", w.next ? "下次 " + w.next : ""].filter(Boolean).join(" · ") + (r ? `\n${w.live ? "" : "最近一次:"}${r.words}${w.live ? "" : " · " + ago((r.ended || r.started) * 1000)}` : ""); +} +function wfWaiting(w) { + const r = w.live; + if (!r || r.state !== "waiting" || !isOwner()) return ""; + return `
${ic("hand", 15)}等你確認:${esc(r.asks || "要繼續嗎?")}
`; +} +function drawWorkflows(el, wf) { + const list = S.wfs || []; + if (wf) { + const w = list.find((x) => x.id === wf); + if (!w) { el.innerHTML = `
找不到這個工作流(可能刪掉了)
`; return; } + $("list-title").textContent = w.name; + const r = w.live || w.runs[0]; + const stepOf = (id) => r && (r.steps || []).find((s) => s.node === id); + let h = `
${esc(w.when)}${w.next ? " · 下次 " + esc(w.next) : ""}
${isOwner() ? (w.live ? `` : ``) : ""}
`; + h += wfWaiting(w); + h += `
步驟${r ? `(${w.live ? "這一次" : "最近一次"}:${esc(r.words)})` : ""}
${w.steps.map((st, i) => { + const s = stepOf(st.id), [cls, word] = stepLook(s, r, st.id); + return `
${ic(WF_ICON[st.kind] || "circle-dot", 15)}
${esc(st.kind)}${st.bot ? ` · ${esc(st.bot)}` : ""}${word ? ` ${esc(word)}` : ""}
${st.words ? `
${esc(st.words)}
` : ""}${s && s.output ? `
${esc(s.output.split("\n").slice(0, 3).join("\n"))}
` : ""}
`; + }).join("")}
`; + h += group("執行紀錄", (w.runs || []).map((x, i) => item({icon: x.state === "done" ? "circle-check" : x.state === "failed" ? "circle-x" : x.state === "waiting" ? "hand" : x.state === "running" ? "loader" : "minus", k: x.words, v: (x.by || "") + " · " + ago(x.started * 1000), tap: 1, data: `data-wfrun="${i}"`})).join("") || `
還沒有跑過
`); + h += `
畫布在電腦上改;或在聊天裡請 Bot 改這個工作流。
`; + el.innerHTML = h; + el.querySelectorAll("[data-wfout]").forEach((x) => x.onclick = () => { const s = stepOf(+x.dataset.wfout); if (s) sheet("這一步的結果", [{group: s.output.slice(0, 600)}, {icon: "copy", label: "複製", on: () => copyText(s.output)}]); }); + el.querySelectorAll("[data-wfrun]").forEach((x) => x.onclick = () => { + const run = w.runs[+x.dataset.wfrun]; + sheet(run.words, (run.steps || []).map((s) => { const st = w.steps.find((y) => y.id === s.node) || {kind: "步驟"}; return {icon: WF_ICON[st.kind] || "circle-dot", label: st.kind + ":" + (stepLook(s, run, s.node)[1] || "還沒到"), x: (s.output || "").slice(0, 24), on: () => s.output && copyText(s.output)}; })); + }); + } else { + el.innerHTML = list.length ? `
${list.map((w) => { + const st = w.live ? WF_STATE[w.live.state] || ["", ""] : null; + return `
${ic("workflow", 18)}
${esc(w.name)}${st ? ` ${st[1]}` : ""}
${esc(wfLine(w))}
${isOwner() ? (w.live ? `` : ``) : ""}
${wfWaiting(w)}
`; + }).join("")}
` : `
還沒有工作流。
在聊天裡請 Bot「做一個每天早上整理新聞的工作流」,或在電腦上畫。
`; + el.querySelectorAll("[data-wfopen]").forEach((x) => x.onclick = (e) => { if (e.target.closest("button")) return; go("list", {kind: "workflows", wf: +x.dataset.wfopen}); }); + } + el.querySelectorAll("[data-wfdo]").forEach((b) => b.onclick = async (e) => { + e.stopPropagation(); + const what = b.dataset.wfdo, id = +b.dataset.wf; + if (what === "stop" && !await confirmSheet("停止這次執行?", "已經做完的步驟不會復原。", "停止")) return; + b.disabled = true; + if (await act("workflow", {wf: id, do: what})) setTimeout(() => { if (cur().v === "list" && cur().arg.kind === "workflows" && cur().arg.wf === wf) listWorkflows(el, wf); }, 600); + else b.disabled = false; + }); +} +// ---------- 個人資料與用量(設定)---------- +// The year in figures, a heat map of its days, and 用量 by period — as on the computer +// (設定 › 個人資料): big numbers and bars instead of lines of words; the fine print in a tap. +const ME = {span: "30", by: "model", data: null, at: 0}; +const wan = (n) => { n = n || 0; return n < 1e4 ? n.toLocaleString("en-US") : n < 1e7 ? (n / 1e4).toFixed(1).replace(/\.0$/, "") + "萬" : n < 1e8 ? Math.round(n / 1e4).toLocaleString("en-US") + "萬" : (n / 1e8).toFixed(2).replace(/\.00$/, "") + "億"; }; +const costWords = (micros, unpriced, calls) => !micros ? "未定價" : "US$" + (micros / 1e6).toFixed(2) + (unpriced > 0 && unpriced < calls ? `(另有 ${unpriced} 次呼叫未定價)` : ""); +const shortDate = (d) => { const [, m, dd] = (d || "").split("-"); return m ? `${+m}月${+dd}日` : d || ""; }; +async function listMe(el) { + if (ME.data) drawMe(el); else el.innerHTML = `
正在算過去一年的用量…
`; + if (ME.data && Date.now() - ME.at < 60000) return; + try { ME.data = await api(base() + "api/stats"); ME.at = Date.now(); } + catch (e) { if (!ME.data) { el.innerHTML = `
讀不到用量:${esc(e.message)}
`; return; } } + if (cur().v === "list" && cur().arg.kind === "me") drawMe(el); +} +function drawMe(el) { + const d = ME.data || {}; + const figs = [[wan(d.tokens_year), "Token・一年"], [wan(d.messages_year), "訊息・一年"], [(d.streak_now || 0) + " 天", "連續使用"], [(d.streak_best || 0) + " 天", "最長連續"]]; + let h = `
${figs.map(([v, l]) => `
${esc(v)}${esc(l)}
`).join("")}
`; + // The year: a dot a day, a column a week (Sunday on top), deeper the busier. + const days = d.days || [], off = d.weekday_first || 0, weeks = Math.ceil((days.length + off) / 7) || 1; + const cell = 7, W = weeks * cell, H = 7 * cell; + const lv = ["var(--hover)", "color-mix(in srgb,var(--accent) 30%,transparent)", "color-mix(in srgb,var(--accent) 50%,transparent)", "color-mix(in srgb,var(--accent) 75%,transparent)", "var(--accent)"]; + const dots = days.map((x, i) => { const k = i + off; return `${esc(shortDate(x[0]))}:${wan(x[1])} token、${x[2]} 則訊息`; }).join(""); + const busy = d.busiest && d.busiest.date ? `最活躍:${shortDate(d.busiest.date)}・${wan(d.busiest.tokens)} token` : ""; + h += `
活動
${dots}
過去一年有 ${d.active_days || 0} 個活躍日${busy ? "・" + esc(busy) : ""}
`; + // 用量: the period's big number, a bar a day, then by model or by bot. + const u = (d.periods || {})[ME.span] || {}; + const seg = (list, cur, key) => `
${list.map(([v, l]) => ``).join("")}
`; + h += `
用量
${seg([["7", "7 天"], ["30", "30 天"], ["90", "90 天"], ["365", "一年"]], ME.span, "mespan")}`; + h += `
${wan(u.tokens)} token
${wan(u.calls)} 次呼叫・花費 ${esc(costWords(u.cost_micros, u.unpriced, u.calls))}・新讀 ${wan((u.input || 0) + (u.cache_write || 0))}、寫 ${wan(u.output)}、快取 ${wan(u.cache_read)}
`; + const daily = u.daily || [], max = Math.max(1, ...daily.map((x) => x[1] || 0)), bw = 100 / Math.max(1, daily.length); + h += `${daily.map((x, i) => x[1] ? `${esc(shortDate(x[0]))}:${wan(x[1])} token` : "").join("")}`; + const rows = (u[ME.by === "bot" ? "by_bot" : "by_model"] || []).slice(0, 8); + const total = Math.max(1, rows.reduce((n, r) => n + (r.tokens || 0), 0)); + const cat = (i) => `var(--cat${(i % 6) + 1})`; + h += seg([["model", "依模型"], ["bot", "依 Bot"]], ME.by, "meby"); + if (!rows.length) h += `
這段時間沒有用量紀錄
`; + else { + if (ME.by === "model") h += `
${rows.map((r, i) => ``).join("")}
`; + const top = Math.max(1, rows[0].tokens || 0); + h += rows.map((r, i) => { + const b = ME.by === "bot" ? S.bots.find((x) => x.name === r.name) : null; + const mark = ME.by === "bot" ? `${b ? avatarSvg(b.shape, b.color) : ""}` : ``; + const bar = ME.by === "bot" ? `` : ""; + return `
${mark}${esc(r.name)}${bar}${wan(r.tokens)}・${Math.round((r.tokens || 0) / total * 100)}%
`; + }).join(""); + } + h += `
`; + el.innerHTML = h; + el.querySelectorAll("[data-mespan]").forEach((b) => b.onclick = () => { ME.span = b.dataset.mespan; drawMe(el); }); + el.querySelectorAll("[data-meby]").forEach((b) => b.onclick = () => { ME.by = b.dataset.meby; drawMe(el); }); +} // ---------- 任務 ---------- // Every bot's tasks as the brain works them out — from the steps, the turn's end, the follow-ups, // the goal checks and whether a device showed the files, never from what a bot says. They come @@ -3185,7 +3670,9 @@ function listTasks(el) { // 任務 → 那則訊息: the chat at where the task began, lit a moment (once that message is here). function jumpTo() { if (!S.jumpAt || S.view !== "chat") return false; - const i = S.msgs.findIndex((m) => m.at === S.jumpAt && m.role === "user"); + // (A task opens at the person's opening message; a search hit may be any message.) + let i = S.msgs.findIndex((m) => m.at === S.jumpAt && m.role === "user"); + if (i < 0) i = S.msgs.findIndex((m) => m.at === S.jumpAt); const el = i < 0 ? null : document.querySelector(`#msgs [data-msg="${i}"]`); if (!el) return false; S.jumpAt = 0; @@ -3233,64 +3720,116 @@ function drawSettings(kind, quiet) { const sc = el.scrollTop; let h = ""; if (kind === "settings") { + // 搜尋設定 (the computer's index): what matches stands where the pages were. + h += `
`; + if (S.setQ && S.setHits) h += group("", S.setHits.map((x) => sitem({icon: setIcon(x.title), k: x.title, v: x.path, tap: 1, data: `data-go="${x.page}"`})).join("") || `
沒有符合的設定
`); + } + if (kind === "settings" && !(S.setQ && S.setHits)) { h += group("", [ - ["general", "settings", "一般", "外觀、時區、通知總開關"], ["models", "sparkles", "模型", "可以用的 AI 服務"], ["perms", "shield", "權限", st.direct_mode ? "直接操作:開" : "Bot 做事前的規則"], - ["integrations", "plug", "整合", "訊息管道、連接器、技能"], ["computers", "monitor", "電腦", "Bot 的電腦和你帳號裡的電腦"], ["vault", "lock", "保險庫", "密碼和卡號"], + ["general", "settings", "一般", "外觀、時區、通知總開關"], ...(isOwner() ? [["me", "activity", "個人資料與用量", ""]] : []), ["models", "sparkles", "模型", "可以用的 AI 服務"], ["perms", "shield", "權限", st.direct_mode ? "直接操作:開" : "Bot 做事前的規則"], + ["integrations", "plug", "整合", "訊息管道、連接器、技能"], ["computers", "monitor", "電腦", "Bot 的電腦和你帳號裡的電腦"], ["vault", "lock", "保險庫", "密碼和卡號"], ["voice", "audio-lines", "語音", "聽和說的服務"], ["account", "smartphone", "手機與帳號", "登入的手機、這支手機的通知"], ["updates", "download", "更新", st.version || ""], - ].map(([k, i, n, v]) => item({icon: i, k: n, r: k === "updates" ? v : "", tap: 1, data: `data-go="${k}"`})).join("")); + ].map(([k, i, n, v]) => sitem({icon: i, k: n, r: k === "updates" ? v : "", tap: 1, data: `data-go="${k}"`})).join("")); } if (kind === "general") { st.accent = ({Quiet: "quiet", BotColor: "bot_color", Black: "black"})[st.accent] || st.accent; - // (The computer's own 主題 and 聊天的顏色 are set on the computer; this phone has its own 外觀 below.) - h += group("", item({icon: "globe", k: "時區", r: st.timezone || "", tap: 1, data: 'data-s="tz"'}) + item({icon: "bell", k: "通知總開關", v: "Bot 做完或等你時通知,電腦和手機都算;關掉就都不通知", sw: !!st.notify, swdata: 'data-sset="notify"', disabled: !isOwner()})); - h += group("這支手機", item({icon: "smartphone", k: "外觀", r: (THEMES.find((t) => t[0] === phoneTheme()) || THEMES[0])[1], tap: 1, data: 'data-s="phonetheme"'})); + // The computer's 主題 and 聊天的顏色 (the phone follows them unless its own 外觀 says otherwise). + const ACC = {quiet: "安靜(淡灰泡泡)", bot_color: "跟著 Bot", black: "只用黑色"}; + // 風格: a little picture of each (the sidebar, words, your bubble, the accent, its backdrop). + if (isOwner() && (st.styles || []).length) { + const dk = isDark(); + h += `
風格
${st.styles.map((t) => { + const c = dk ? t.dark : t.light, on = st.style === t.id; + const bd = t.backdrop === "dots" ? `background-image:radial-gradient(${c.grid} 1px,transparent 1.2px);background-size:9px 9px;` : t.backdrop === "grid" ? `background-image:linear-gradient(${c.grid} 1px,transparent 1px),linear-gradient(90deg,${c.grid} 1px,transparent 1px);background-size:10px 10px;` : t.backdrop === "waves" ? `background-image:radial-gradient(circle at 50% 100%,transparent 6px,${c.grid} 6.5px,${c.grid} 7.5px,transparent 8px);background-size:14px 7px;` : ""; + return ``; + }).join("")}
${st.style ? "" : `
現在是自訂的顏色(電腦上的強調色);點一個風格整套換,電腦和手機一起。
`}`; + } + const accName = ((st.accents || []).find((a) => a.key === st.shell_accent) || {}).name || ""; + const look = isOwner() ? sitem({icon: "palette", k: "強調色", r: st.style ? "跟著風格" : accName, tap: 1, data: 'data-s="accentcolor"'}) + sitem({icon: "palette", k: "對比", r: (st.shell_contrast || 1) < 0.95 ? "柔和" : (st.shell_contrast || 1) > 1.1 ? "鮮明" : "標準", tap: 1, data: 'data-s="contrast"'}) + sitem({icon: "globe", k: "語言", r: st.language === "auto" || !st.language ? "自動偵測" : ((st.languages || []).find((l) => l[0] === st.language) || [0, st.language])[1], tap: 1, data: 'data-s="lang"'}) : ""; + if (isOwner()) h += group("電腦的外觀", look + sitem({icon: "moon", k: "主題", r: ({system: "跟隨系統", light: "淺色", dark: "深色"})[st.theme] || "跟隨系統", tap: 1, data: 'data-s="theme"'}) + sitem({icon: "message", k: "聊天的顏色", r: ACC[st.accent || "quiet"] || "", tap: 1, data: 'data-s="accent"'})); + h += group("", sitem({icon: "globe", k: "時區", r: st.timezone || "", tap: 1, data: 'data-s="tz"'}) + sitem({icon: "bell", k: "通知總開關", v: "Bot 做完或等你時通知,電腦和手機都算;關掉就都不通知", sw: !!st.notify, swdata: 'data-sset="notify"', disabled: !isOwner()})); + if (isOwner()) h += group("記憶與文件", sitem({icon: "brain", k: "用意思找記憶", v: "在這台電腦上算,不會上傳", r: ({local: "本機模型", ollama: "Ollama", off: "關閉"})[st.embed] || "本機模型", tap: 1, data: 'data-s="embed"'}) + + (st.doc_folders || []).map((f) => `
${ic("folder", 19)}
${esc(f)}
`).join("") + + sitem({icon: "plus", k: (st.doc_folders || []).length ? "再加一個 Bot 可以翻的資料夾" : "Bot 可以翻的資料夾", v: "Bot 在這些資料夾的文字檔裡找答案(在那台電腦上的路徑)", tap: 1, data: 'data-s="docadd"', chev: false})); + h += group("這支手機", sitem({icon: "smartphone", k: "外觀", r: (THEMES.find((t) => t[0] === phoneTheme()) || THEMES[0])[1], tap: 1, data: 'data-s="phonetheme"'})); } if (kind === "models") { - h += group("AI 服務", (st.providers || []).map((p, i) => item({k: p.label, v: [p.runs, p.ready && p.default_model ? p.default_model : ""].filter(Boolean).join(" · "), r: p.ready ? "可以用" : "未設定", tap: isOwner() ? 1 : 0, data: `data-prov="${i}"`})).join("")); + h += group("AI 服務", (st.providers || []).map((p, i) => sitem({icon: "sparkles", k: p.label, v: [p.runs, p.ready && p.default_model ? p.default_model : "", p.status || ""].filter(Boolean).join(" · "), r: p.ready ? "可以用" : "未設定", tap: isOwner() ? 1 : 0, data: `data-prov="${i}"`})).join("")); h += `
金鑰只存在這台 AnyBot,手機寫得進去、看不到。
`; } if (kind === "perms") { - h += group("", item({icon: "zap", k: "直接操作", v: st.direct_locked ? "已由管理員關閉" : "Bot 直接做事,只有危險操作和「一律詢問」規則會先問你", sw: !!st.direct_mode, swdata: 'data-sset="direct_mode"', disabled: !isOwner() || st.direct_locked}) + item({icon: "shield", k: "自動審核", v: "照下面的規則自動允許或先問你", sw: !!st.auto_review, swdata: 'data-sset="auto_review"', disabled: !isOwner()})); + h += group("", sitem({icon: "zap", k: "直接操作", v: st.direct_locked ? "已由管理員關閉" : "Bot 直接做事,只有危險操作和「一律詢問」規則會先問你", sw: !!st.direct_mode, swdata: 'data-sset="direct_mode"', disabled: !isOwner() || st.direct_locked}) + sitem({icon: "shield", k: "自動審核", v: "照下面的規則自動允許或先問你", sw: !!st.auto_review, swdata: 'data-sset="auto_review"', disabled: !isOwner()}) + + sitem({icon: "zap", k: "一律放行", v: "你自己的對話裡,要允許的都自動答應(和聊天打 /always-approve 一樣);危險操作和「一律詢問」照樣擋", sw: !!st.always_approve, swdata: 'data-sset="always_approve"', disabled: !isOwner() || st.direct_locked}) + + sitem({icon: "clock", k: "智慧模式:卡片沒人回答時", r: SMART_SECS.find((x) => x[0] === (st.smart_timeout_secs || 0))?.[1] || (st.smart_timeout_secs + " 秒後"), tap: isOwner() ? 1 : 0, data: 'data-s="smartsecs"'})); h += rulesGroup("一律詢問(優先)", st.ask_rules, "ask") + rulesGroup("無需詢問直接允許", st.allow_rules, "allow"); // 直接操作 always asks about these three too (not written into the rules: turning it off leaves nothing behind). - if (st.direct_mode) h += group("直接操作開著時也一定先問", ["刪除檔案或資料夾", "付款、購買或轉帳", "用我的帳號發文、留言,或傳訊息給別人"].map((r) => item({icon: "hand", k: r})).join("")); + if (st.direct_mode) h += group("直接操作開著時也一定先問", ["刪除檔案或資料夾", "付款、購買或轉帳", "用我的帳號發文、留言,或傳訊息給別人"].map((r) => sitem({icon: "hand", k: r})).join("")); h += `
用一般的話寫,例如「付款前先問我」。兩邊都符合時先問。${st.direct_mode ? "直接操作開著:「一律詢問」照樣檢查,「直接允許」用不到。" : st.auto_review === false ? "自動審核關著時不會用這些規則。" : ""}
`; } if (kind === "integrations") { const dot = (ok, on) => ``; h += group("訊息管道", (st.channels || []).map((c) => `
${dot(c.ok, c.enabled)}
${esc(c.kind)} · ${esc(c.name)}
由「${esc(c.bot)}」回覆${c.note ? " · " + esc(c.note) : ""}
${isOwner() ? `` : ""}
`).join("") || `
還沒有。Telegram、Slack、Discord… 要在電腦上的 AnyBot 新增(需要輸入 Token)。
`); - h += group("連接器(MCP)", ((st.mcp || []).map((m) => `
${dot(m.tools != null, m.enabled)}
${esc(m.name)}
${!m.enabled ? "已關閉" : m.tools != null ? `已連上,${m.tools} 個工具` : m.error ? esc(m.error) : "連線中…"}
${isOwner() ? `${m.enabled ? `` : ""}` : ""}
`).join("") || `
還沒有連接器
`) + (isOwner() ? item({icon: "plus", k: "從公用市集加入", v: "搜尋官方 MCP Registry 裡用網址連的連接器", tap: 1, data: 'data-mcpmarket="1"'}) : "")); + h += group("連接器(MCP)", ((st.mcp || []).map((m) => `
${dot(m.tools != null, m.enabled)}
${esc(m.name)}
${!m.enabled ? "已關閉" : m.tools != null ? `已連上,${m.tools} 個工具` : m.error ? esc(m.error) : "連線中…"}
${isOwner() ? `${m.enabled ? `` : ""}` : ""}
`).join("") || `
還沒有連接器
`) + (isOwner() ? sitem({icon: "plus", k: "從公用市集加入", v: "搜尋官方 MCP Registry 裡用網址連的連接器", tap: 1, data: 'data-mcpmarket="1"'}) : "")); const skRows = (st.skills || []).map((k, i) => { const tags = [...(k.resources && k.resources.length ? [`${k.resources.length} 檔`] : []), ...(k.steps ? [`可重播 ${k.steps} 步`] : [])].join(" · "); - return `
${esc(k.name)}${tags ? ` ${esc(tags)}` : ""}
${esc(k.description)}
${isOwner() ? `` : ""}
`; + return `
${ic("sparkles", 19)}
${esc(k.name)}${tags ? ` ${esc(tags)}` : ""}
${esc(k.description)}
${isOwner() ? `` : ""}
`; }).join(""); const skActions = isOwner() - ? item({icon: "sparkles", k: "從技能市集加入", v: "內建繁中核心技能包與 Anthropic 官方開源技能", tap: 1, data: 'data-skillmarket="1"'}) + - item({icon: "plus", k: "從 GitHub 或網址安裝技能", v: "支援 anthropics/skills 網址、owner/repo/path 或 SKILL.md 連結", tap: 1, data: 'data-skilladd="1"', chev: false}) + ? sitem({icon: "sparkles", k: "從技能市集加入", v: "內建繁中核心技能包與 Anthropic 官方開源技能", tap: 1, data: 'data-skillmarket="1"'}) + + sitem({icon: "plus", k: "從 GitHub 或網址安裝技能", v: "支援 anthropics/skills 網址、owner/repo/path 或 SKILL.md 連結", tap: 1, data: 'data-skilladd="1"', chev: false}) : ""; h += group("技能", (skRows || `
還沒有技能。可從下方「技能市集」一鍵加入,或在聊天裡請 Bot 幫你建立。
`) + skActions); } if (kind === "computers") h += computersHtml(st); + // 語音: who hears you (聽) and who reads answers aloud (說) — on the brain, for every device. + if (kind === "voice") { + const V = st.voice || {}; + const engine = (which, title, about) => { + const e = V[which] || {}, kindName = (VOICE_KINDS.find((k) => k[0] === e.kind) || VOICE_KINDS[0])[1]; + let rows = sitem({icon: which === "listen" ? "mic" : "audio-lines", k: title, v: about, r: e.kind === "off" || !e.kind ? "關閉" : kindName + (e.ready ? "・可以用" : "・還不能用"), tap: isOwner() ? 1 : 0, data: `data-vk="${which}"`}); + if (e.kind && e.kind !== "off") { + if (e.kind === "open_ai") rows += sitem({icon: "globe", k: "網址", r: e.base_url || "OpenAI", tap: 1, data: `data-vf="${which}:base_url"`}); + rows += sitem({icon: "key", k: "金鑰", r: e.has_key ? "已設定" : "用「模型」裡同一家的", tap: 1, data: `data-vf="${which}:api_key"`}); + rows += sitem({icon: "sparkles", k: "模型", r: e.model || "預設", tap: 1, data: `data-vf="${which}:model"`}); + if (which === "speak") rows += sitem({icon: "smile-plus", k: "聲音", r: e.voice || "預設", tap: 1, data: `data-vf="speak:voice"`}) + (e.ready ? sitem({icon: "play", k: "試聽", tap: 1, data: 'data-vtest="1"', chev: false}) : ""); + } + return group("", rows); + }; + h += engine("listen", "聽(語音轉文字)", "語音輸入、語音聊天、會議錄音都用它") + engine("speak", "說(朗讀)", "把回答唸出來"); + h += `
每台電腦和手機的錄音、朗讀都交給大腦,用這裡選的服務;金鑰只存在大腦,手機看不到。沒選服務時,麥克風和朗讀不會出現。
`; + } if (kind === "vault") h += `
${ic("lock", 28)}

保險庫裡的密碼、卡號和聯絡資訊,只在電腦上的 AnyBot 管理。
Bot 用到時由 AnyBot 直接填進網頁,不會交給模型,也不會經過手機。
`; if (kind === "account") { - h += group("這台 AnyBot", item({icon: "monitor", k: "名稱", r: st.host || S.hostName}) + item({icon: "info", k: "你的角色", r: isOwner() ? "擁有者" : "管理員"})); - if (st.devices) h += group("直接連線的手機", st.devices.map((d, i) => item({icon: "smartphone", k: d.name, v: d.last_seen ? "上次使用 " + ago(d.last_seen * 1000) : "登入於 " + ago(d.created * 1000), tap: 1, data: `data-dev="${i}"`})).join("") || `
沒有
`); + h += group("這台 AnyBot", sitem({icon: "monitor", k: "名稱", r: st.host || S.hostName}) + sitem({icon: "info", k: "你的角色", r: isOwner() ? "擁有者" : "管理員"})); + if (st.devices) h += group("直接連線的手機", st.devices.map((d, i) => sitem({icon: "smartphone", k: d.name, v: d.last_seen ? "上次使用 " + ago(d.last_seen * 1000) : "登入於 " + ago(d.created * 1000), tap: 1, data: `data-dev="${i}"`})).join("") || `
沒有
`); const acts = []; - if (S.relay) acts.push(item({icon: "bell", k: "通知", v: "Bot 需要你允許、或做完事時,手機跳通知", tap: 1, data: 'data-s="push"'})); - if (S.relay) acts.push(item({icon: "shield", k: "兩步驗證", v: "登入要密碼+驗證器 App 的六位碼", tap: 1, data: 'data-s="2fa"'})); - if (S.relay) acts.push(item({icon: "smartphone", k: "登入的裝置", v: "看看有哪些裝置登著,可逐台踢掉", tap: 1, data: 'data-s="devices"'})); - if (S.relay && owner()) acts.push(item({icon: "plus", k: "加一台電腦", v: "Linux、伺服器當 Bot 的手腳", tap: 1, data: 'data-s="pair"'})); - if (S.relay) acts.push(item({icon: "refresh", k: "切換到別台 AnyBot", tap: 1, data: 'data-s="host"'})); - acts.push(item({icon: "log-out", k: "登出這支手機", tap: 1, data: 'data-s="out"', danger: true, chev: false})); + if (S.relay) acts.push(sitem({icon: "bell", k: "通知", v: "Bot 需要你允許、或做完事時,手機跳通知", tap: 1, data: 'data-s="push"'})); + if (S.relay) acts.push(sitem({icon: "shield", k: "兩步驗證", v: "登入要密碼+驗證器 App 的六位碼", tap: 1, data: 'data-s="2fa"'})); + if (S.relay) acts.push(sitem({icon: "smartphone", k: "登入的裝置", v: "看看有哪些裝置登著,可逐台踢掉", tap: 1, data: 'data-s="devices"'})); + if (S.relay && owner()) acts.push(sitem({icon: "plus", k: "加一台電腦", v: "Linux、伺服器當 Bot 的手腳", tap: 1, data: 'data-s="pair"'})); + if (S.relay) acts.push(sitem({icon: "refresh", k: "切換到別台 AnyBot", tap: 1, data: 'data-s="host"'})); + acts.push(sitem({icon: "log-out", k: "登出這支手機", tap: 1, data: 'data-s="out"', danger: true, chev: false})); h += group("這支手機", acts.join("")); } if (kind === "updates") { - h += group("", item({icon: "info", k: "版本", v: st.built ? `${stamp(st.built)} 建置` : "", r: st.version || ""}) + (st.newer ? item({icon: "download", k: "有新版", v: "電腦上的 AnyBot 已經下載新版,重新啟動就會換上"}) : item({icon: "circle-check", k: "已是最新版"}))); + h += group("", sitem({icon: "info", k: "版本", v: st.built ? `${stamp(st.built)} 建置` : "", r: st.version || ""}) + (st.newer ? sitem({icon: "download", k: "有新版", v: "電腦上的 AnyBot 已經下載新版,重新啟動就會換上"}) : sitem({icon: "circle-check", k: "已是最新版"}))); + if (isOwner()) h += group("自動", sitem({icon: "refresh", k: "你不在時自動更新", v: "有新版時,等你離開電腦再換上", sw: st.auto_update !== false, swdata: 'data-sset="auto_update"'}) + sitem({icon: "target", k: "園丁報告", v: "每天、每週整理 Bot 卡住和做錯的地方,給你看要不要改", sw: st.garden_reports !== false, swdata: 'data-sset="garden_reports"'})); h += `
Bot 的電腦的更新在「電腦」裡。
`; - h += group("這支手機", item({icon: "smartphone", k: "畫面", v: fitWords(), tap: 1, data: 'data-ruler="1"'})); + h += group("這支手機", sitem({icon: "smartphone", k: "畫面", v: fitWords(), tap: 1, data: 'data-ruler="1"'})); h += `
畫面看起來被切到、上面糊糊的、下面空一塊時,按「畫面」打開量尺截圖給我們。
`; } el.innerHTML = h + `
`; + const sq = $("set-q"); + if (sq) sq.oninput = () => { + S.setQ = sq.value.trim(); clearTimeout(S.setT); + S.setT = setTimeout(async () => { + const q = S.setQ; + const v = q ? await act("settings_find", {q}, false) : null; + if (q !== S.setQ || cur().v !== "list" || cur().arg.kind !== "settings") return; + S.setHits = v ? v.hits || [] : null; + const pos = sq.selectionStart; drawSettings("settings", true); const n = $("set-q"); if (n) { n.focus(); n.setSelectionRange(pos, pos); } + }, 200); + }; el.querySelectorAll("[data-ruler]").forEach((x) => x.onclick = ruler); if (quiet) el.scrollTop = sc; wireSettings(kind, st); @@ -3312,17 +3851,17 @@ function computersHtml(st) { const steps = f.steps && f.steps.n ? `平均每步 ${Math.round(f.steps.total_ms / f.steps.n)} ms(${f.steps.n} 步)` : ""; // (Not looked at yet: undefined. Nothing to look at — no Docker, no box yet: null.) const upd = f.update === undefined ? "檢查中…" : f.update === null ? (box.available ? `還沒建立(建立時是 v${box.version})` : "沒有 Docker,現在沒有這台電腦") : f.update ? `有新版(v${box.version})。檔案和登入都會留著` : `已是 v${box.version}`; - h += group("", item({icon: "download", k: "更新 Bot 的電腦", v: upd, tap: isOwner() && f.update ? 1 : 0, data: 'data-bx="update"'}) + - item({icon: "alarm-clock", k: "自動更新", r: box.auto_update || "關", tap: isOwner() ? 1 : 0, data: 'data-bx="auto"'}) + - item({icon: "shield", k: "容器隔離", v: running_rt && running_rt !== rt.slice(0, 2) ? `目前是${running_rt};按更新後改成${rt}` : (f.gvisor === false && box.runtime !== "runsc" ? "這台 Docker 主機沒有 gVisor" : ""), r: rt, tap: isOwner() && (f.gvisor || box.runtime === "runsc") ? 1 : 0, data: 'data-bx="runtime"'}) + - item({icon: "hard-drive", k: "上次快照", r: box.snapshot || "還沒有"}) + - (steps ? item({icon: "activity", k: "速度", r: steps}) : "") + - (st.docker_host ? item({icon: "server", k: "Docker 主機", v: st.docker_host}) : "")); - h += group("", item({icon: "sparkles", k: "請 Bot 提出清理方案", v: "先列出用量最大的地方,不會直接刪除", tap: 1, data: 'data-bx="clean"'}) + - (isOwner() ? item({icon: "refresh", k: box.snapshot ? "從快照復原" : "重設電腦", v: box.snapshot ? `回到 ${box.snapshot} 的快照(目前的內容會先存起來)` : "換一台全新的電腦(檔案和登入會清除)", tap: 1, data: 'data-bx="reset"', danger: true, chev: false}) : "")); + h += group("", sitem({icon: "download", k: "更新 Bot 的電腦", v: upd, tap: isOwner() && f.update ? 1 : 0, data: 'data-bx="update"'}) + + sitem({icon: "alarm-clock", k: "自動更新", r: box.auto_update || "關", tap: isOwner() ? 1 : 0, data: 'data-bx="auto"'}) + + sitem({icon: "shield", k: "容器隔離", v: running_rt && running_rt !== rt.slice(0, 2) ? `目前是${running_rt};按更新後改成${rt}` : (f.gvisor === false && box.runtime !== "runsc" ? "這台 Docker 主機沒有 gVisor" : ""), r: rt, tap: isOwner() && (f.gvisor || box.runtime === "runsc") ? 1 : 0, data: 'data-bx="runtime"'}) + + sitem({icon: "hard-drive", k: "上次快照", r: box.snapshot || "還沒有"}) + + (steps ? sitem({icon: "activity", k: "速度", r: steps}) : "") + + (st.docker_host ? sitem({icon: "server", k: "Docker 主機", v: st.docker_host}) : "")); + h += group("", sitem({icon: "sparkles", k: "請 Bot 提出清理方案", v: "先列出用量最大的地方,不會直接刪除", tap: 1, data: 'data-bx="clean"'}) + + (isOwner() ? sitem({icon: "refresh", k: box.snapshot ? "從快照復原" : "重設電腦", v: box.snapshot ? `回到 ${box.snapshot} 的快照(目前的內容會先存起來)` : "換一台全新的電腦(檔案和登入會清除)", tap: 1, data: 'data-bx="reset"', danger: true, chev: false}) : "")); if ((box.log || []).length) h += `
紀錄
${esc(box.log.slice(-25).join("\n"))}
`; const others = comps.filter((c) => c.kind !== "own"); - if (others.length) h += group("帳號裡的電腦", others.map((c) => item({icon: {this: "monitor", device: "laptop", ssh: "server"}[c.kind] || "monitor", k: c.name, v: (c.online ? "在線上" : "離線") + (c.person ? " · 你正在用的" : ""), tap: c.kind === "this" && S.mac ? 1 : 0, data: c.kind === "this" && S.mac ? 'data-bx="mac"' : ""})).join("")); + if (others.length) h += group("帳號裡的電腦", others.map((c) => sitem({icon: {this: "monitor", device: "laptop", ssh: "server"}[c.kind] || "monitor", k: c.name, v: (c.online ? "在線上" : "離線") + (c.person ? " · 你正在用的" : ""), tap: c.kind === "this" && S.mac ? 1 : 0, data: c.kind === "this" && S.mac ? 'data-bx="mac"' : ""})).join("")); return h; } async function devicesSheet() { @@ -3382,6 +3921,15 @@ function wireSettings(kind, st) { if (!await act("setting", {key: k, value: x.checked})) x.checked = !x.checked; else again(); }); on("[data-addrule]", "onclick", async (x) => { const t = await ask(x.dataset.addrule === "ask" ? "一律詢問的規則" : "無需詢問的規則", "", x.dataset.addrule === "ask" ? "例如:發文、寄信、付款前先問我" : "例如:讀取網頁和檔案"); if (t && await act("setting", {key: "rule_add", list: x.dataset.addrule, value: t})) again(); }); + on("[data-vk]", "onclick", (x) => { const w = x.dataset.vk, cur = ((st.voice || {})[w] || {}).kind || "off"; sheet(w === "listen" ? "聽(語音轉文字)" : "說(朗讀)", VOICE_KINDS.map(([k, n]) => ({label: n, check: cur === k, on: async () => { if (await act("voice", {which: w, kind: k})) again(); }}))); }); + on("[data-vf]", "onclick", async (x) => { + const [w, f] = x.dataset.vf.split(":"), e = (st.voice || {})[w] || {}; + const label = {base_url: "網址(以 /v1 結尾;空白=OpenAI 自己的)", api_key: "金鑰(空白=用「模型」裡同一家的)", model: "模型(空白=服務預設的)", voice: "聲音(空白=服務預設的)"}[f]; + const val = await ask(label, f === "api_key" ? "" : e[f] || ""); + if (val != null && await act("voice", {which: w, [f]: val}, "已更新")) again(); + }); + on("[data-vtest]", "onclick", () => speakText("你好,這是朗讀的聲音。")); + on("[data-docrm]", "onclick", async (x) => { if (await act("setting", {key: "doc_folder_remove", value: x.dataset.docrm}, "已移除")) again(); }); on("[data-rmrule]", "onclick", async (x) => { if (await act("setting", {key: "rule_remove", list: x.dataset.rmrule, value: x.dataset.r}, "已移除")) again(); }); on("[data-ch]", "onchange", async (x) => { if (!await act("channel", {id: +x.dataset.ch, enabled: x.checked})) x.checked = !x.checked; else again(); }); on("[data-chrm]", "onclick", async (x) => { if (await confirmSheet("移除這個管道?", "", "移除") && await act("channel", {id: +x.dataset.chrm, remove: true}, "已移除")) again(); }); @@ -3407,6 +3955,10 @@ function wireSettings(kind, st) { if (r) { toast(r.text || (r.ok ? "已登入" : "沒有登入成功")); again(); } }}, ...(p.ready ? [{icon: "trash", label: "登出 ChatGPT", danger: true, on: async () => { if (await confirmSheet("登出 ChatGPT?", "用 ChatGPT 方案的 Bot 會沒辦法回答,直到再登入。", "登出") && await act("chatgpt", {action: "logout"})) again(); }}] : [])] : []), {icon: "sparkles", label: "新 Bot 預設模型…", x: p.default_model || "", on: async () => { const m = await ask("新 Bot 預設用的模型", p.default_model || ""); if (m != null && await act("provider", {provider: p.key, default_model: m}, "已更新")) again(); }}, + // 服務網址, 測試連線並取得模型清單, and a local model's 看圖小幫手 — as on the computer. + ...(p.account ? [] : [{icon: "globe", label: "服務網址…", x: p.base_url ? "自訂" : "預設", on: async () => { const u = await ask("服務網址(空白=預設)", p.base_url || "", p.default_url || ""); if (u != null && await act("provider", {provider: p.key, base_url: u}, "已更新網址")) again(); }}]), + {icon: "refresh", label: p.testing ? "正在測試連線…" : "測試連線並取得模型清單", x: p.status ? p.status.slice(0, 18) : p.known ? `記住 ${p.known} 個` : "", on: async () => { if (await act("provider", {provider: p.key, fetch: true})) { setTimeout(again, 2500); setTimeout(again, 8000); } }}, + ...(p.local ? [{icon: "eye", label: p.cloud_eyes ? "看不到圖時請雲端模型看:開" : "看不到圖時請雲端模型看:關", x: "", on: async () => { if (await act("provider", {provider: p.key, cloud_eyes: !p.cloud_eyes}, p.cloud_eyes ? "圖片不會離開了" : "看不到的圖會給雲端模型看")) again(); }}] : []), ...(p.ready && p.needs_key ? [{icon: "trash", label: "清除金鑰", danger: true, on: async () => { if (await confirmSheet(`清除 ${p.label} 的金鑰?`, "用這個服務的 Bot 會沒辦法回答,直到再設定一把。", "清除") && await act("provider", {provider: p.key, key: ""}, "已清除")) again(); }}] : []), ]); }); @@ -3477,11 +4029,20 @@ function wireSettings(kind, st) { }); on("[data-s]", "onclick", async (x) => { const k = x.dataset.s; - if (k === "theme") sheet("主題", [["system", "跟隨系統"], ["light", "淺色"], ["dark", "深色"]].map(([v, n]) => ({label: n, check: st.theme === v, on: async () => { if (await app("update_settings", {theme: v})) again(); }}))); + if (k === "accentcolor") sheet("強調色(會回到自訂的顏色)", (st.accents || []).map((a) => ({label: "● " + a.name, check: !st.style && st.shell_accent === a.key, on: async () => { if (await act("setting", {key: "shell_accent", value: a.key})) again(); }}))); + else if (k === "contrast") sheet("對比", [[0.85, "柔和"], [1, "標準"], [1.2, "鮮明"]].map(([v, n]) => ({label: n, check: Math.abs((st.shell_contrast || 1) - v) < 0.06, on: async () => { if (await act("setting", {key: "shell_contrast", value: v})) again(); }}))); + else if (k === "lang") sheet("語言(選單和 Bot 回答)", [["auto", "自動偵測"], ...(st.languages || [])].map(([v, n]) => ({label: n, check: (st.language || "auto") === v, on: async () => { if (await act("setting", {key: "language", value: v})) again(); }}))); + else if (k === "smartsecs") sheet("智慧模式:卡片沒人回答時", SMART_SECS.map(([v, n]) => ({label: n, check: (st.smart_timeout_secs || 0) === v, on: async () => { if (await act("setting", {key: "smart_timeout_secs", value: v})) again(); }}))); + else if (k === "embed") sheet("用意思找記憶", [["local", "本機模型(在這台電腦上算)"], ["ollama", "Ollama"], ["off", "關閉"]].map(([v, n]) => ({label: n, check: (st.embed || "local") === v, on: async () => { if (await act("setting", {key: "embed", value: v})) again(); }}))); + else if (k === "docadd") { const f = await ask("資料夾路徑(那台電腦上的)", "", "例如:~/Documents/筆記"); if (f && await act("setting", {key: "doc_folder_add", value: f}, "已加入")) again(); } + else if (k === "style") { if (await app("update_settings", {style: x.dataset.style}, 0, false)) { toast("換好了"); again(); } } + else if (k === "theme") sheet("主題", [["system", "跟隨系統"], ["light", "淺色"], ["dark", "深色"]].map(([v, n]) => ({label: n, check: st.theme === v, on: async () => { if (await app("update_settings", {theme: v})) again(); }}))); else if (k === "accent") sheet("聊天的顏色", [["quiet", "安靜(淡灰泡泡)"], ["bot_color", "跟著 Bot"], ["black", "只用黑色"]].map(([v, n]) => ({label: n, check: (st.accent || "quiet") === v, on: async () => { if (await app("update_settings", {accent: v})) again(); }}))); else if (k === "tz") { const zones = [...new Set([TZ, "Asia/Taipei", "Asia/Tokyo", "Asia/Shanghai", "Asia/Hong_Kong", "Asia/Singapore", "Europe/London", "America/New_York", "America/Los_Angeles", "UTC"].filter(Boolean))]; - sheet("時區", zones.map((z) => ({label: z + (z === TZ ? "(這支手機)" : ""), check: st.timezone === z, on: async () => { if (await app("update_settings", {timezone: z})) again(); }}))); + sheet("時區", zones.map((z) => ({label: z + (z === TZ ? "(這支手機)" : ""), check: st.timezone === z, on: async () => { if (await app("update_settings", {timezone: z})) again(); }})) + // (Any IANA name, as on the computer: Europe/Berlin, Australia/Sydney…) + .concat([{icon: "pen", label: "其他時區…", on: async () => { const z = await ask("時區(例如 Europe/Berlin)", st.timezone || ""); if (z && z !== st.timezone && await app("update_settings", {timezone: z.trim()})) again(); }}])); } else if (k === "phonetheme") sheet("這支手機的外觀", THEMES.map(([v, n]) => ({label: n, check: phoneTheme() === v, on: () => { try { localStorage.setItem("anybot.theme", v); } catch (_) {} applyTheme(); drawSettings(kind, true); }}))); else if (k === "push") notifySheet(); @@ -3493,8 +4054,8 @@ function wireSettings(kind, st) { }); on("[data-bx]", "onclick", async (x) => { const k = x.dataset.bx, box = st.box || {}; - if (k === "open") openBox(false); - else if (k === "take") openBox(true); + if (k === "open") pickBoxBot(false); + else if (k === "take") pickBoxBot(true); else if (k === "mac") go("screen"); else if (k === "wake") { await act("box", {op: "wake"}, "正在喚醒…"); again(); } else if (k === "snapshot") { await act("box", {op: "snapshot"}, "正在儲存快照…"); again(); } @@ -3554,7 +4115,7 @@ function pageToc(root) { } $("b-pagemore").onclick = () => { const v = S.pageData; if (!v) return; - const items = [{icon: "copy", label: "複製 Markdown", on: () => copyText(v.body)}]; + const items = [{icon: "copy", label: "複製 Markdown", on: () => copyText(v.body)}, {icon: "download", label: "存成檔案(.md)", on: () => saveText(v.body, (v.title || "頁面").replace(/[\\/:*?"<>|]/g, "_") + ".md")}]; if ((v.versions || []).length) items.push({icon: "history", label: "其他版本", on: () => sheet("版本", [{label: `第 ${v.latest} 版(最新)`, check: v.revision === v.latest, on: () => openPage(v.id)}, ...v.versions.map((x) => ({label: `第 ${x.revision} 版`, x: x.at, check: v.revision === x.revision, on: () => openPage(v.id, x.revision)}))])}); if (isOwner()) items.push({sep: true}, {icon: "trash", label: "刪除頁面", danger: true, on: async () => { if (await confirmSheet(`刪除「${v.title}」?`, "", "刪除") && await act("delete_page", {id: v.id}, "已刪除頁面")) back(); }}); sheet(v.title, items); @@ -3705,13 +4266,34 @@ function saveFile(path, name, att, bot) { $("b-filesave").innerHTML = ic("download", 20); $("b-filesave").onclick = () => { if (S.file) saveFile(S.file.path, S.file.name, S.file.att, S.file.bot); }; const isDark = () => document.documentElement.dataset.theme === "dark" || (!document.documentElement.dataset.theme && matchMedia("(prefers-color-scheme: dark)").matches); +// A drawn chart as a picture: an SVG kept as an SVG image — only ever shown in an , where it +// runs nothing (safeBlob turns SVG into a download, so the picture showed broken). +const DIAGRAMS = new Map(); +async function chartUrl(r) { + if (/^image\/svg\+xml/i.test(r.headers.get("Content-Type") || "")) return URL.createObjectURL(new Blob([await r.text()], {type: "image/svg+xml"})); + return URL.createObjectURL(await safeBlob(r)); +} async function loadCharts() { + for (const el of document.querySelectorAll(".chart[data-mermaid]")) { + // (The answer still being written: its diagram is drawn when it is whole.) + const m = el.closest(".m"); + if (m && !m.nextElementSibling && el.closest("#msgs") && (bot(S.open) || {}).busy) continue; + const src = el.dataset.mermaid, key = (isDark() ? "d:" : "l:") + src; el.removeAttribute("data-mermaid"); + try { + const r = await api(base() + "api/diagram", {json: {src, dark: isDark()}, raw: true}); + if (!r.ok) { if (r.status === 422) DIAGRAMS.set(key, "fail"); throw new Error(); } + const u = await chartUrl(r); + DIAGRAMS.set(key, u); + if (DIAGRAMS.size > 60) { const old = DIAGRAMS.keys().next().value, v = DIAGRAMS.get(old); DIAGRAMS.delete(old); if (v !== "fail") URL.revokeObjectURL(v); } + el.innerHTML = `圖表`; + } catch (_) { el.innerHTML = `
${esc(src)}
`; } + } for (const el of document.querySelectorAll(".chart[data-src]")) { const src = el.dataset.src; el.removeAttribute("data-src"); try { const r = await api(base() + src + (src.includes("?") ? "&" : "?") + "dark=" + (isDark() ? 1 : 0), {raw: true}); if (!r.ok) throw new Error(); - el.innerHTML = `圖表`; + el.innerHTML = `圖表`; } catch (_) { el.innerHTML = `
這張圖畫不出來
`; } } } @@ -3981,6 +4563,13 @@ function pageMd(text, id, rev) { while (i < L.length && !L[i].trim().startsWith("```")) body.push(L[i++]); i++; if (lang === "mermaid" && id) { out.push(`
圖表載入中…
`); continue; } + // (A diagram in a chat: drawn by the brain from its words, as the computer draws it.) + if (lang === "mermaid") { + // (Drawn once: a chat is redrawn on every change, and the picture must not blink or be asked for again.) + const src = body.join("\n"), had = DIAGRAMS.get((isDark() ? "d:" : "l:") + src); + out.push(had === "fail" ? `
${esc(src)}
` : had ? `
圖表
` : `
圖表載入中…
`); + continue; + } // ```details : folded under one quiet line (細節 without a title); the inside is the page's Markdown. if (lang === "details") { const title = t.replace(/^```\s*details/i, "").trim() || "細節"; out.push(`<details class="dt"><summary>${esc(title)}</summary><div class="dt-in">${pageMd(body.join("\n"), id, rev)}</div></details>`); continue; } if (lang === "chart") { const html = chartMd(body); if (html) { out.push(html); continue; } } @@ -3996,7 +4585,7 @@ function pageMd(text, id, rev) { }); if (items.length) { out.push(`<ul class="steps">${items.join("")}</ul>`); continue; } } - out.push(`<pre><code>${esc(body.join("\n"))}</code></pre>`); continue; + out.push(`<pre class="cb"><button class="cpy" data-copycode>${ic("copy", 14)}</button><code>${esc(body.join("\n"))}</code></pre>`); continue; } const h = t.match(/^(#{1,6})\s+(.*)$/); if (h) { const n = Math.min(h[1].length + 1, 4); out.push(`<h${n}>${inl(h[2])}</h${n}>`); i++; continue; } @@ -4039,19 +4628,34 @@ function pageMd(text, id, rev) { // The bots' computer: its live screen shown over the app (screen.html embedded), where you // can also take over. Its ✕ posts a close; a back gesture closes it too. let boxOpen = false; -function openBox(control) { - const b = bot(S.open) || S.bots.find((x) => x.primary) || {}; +// From 設定 › 電腦 (no chat open): whose screen — each bot has its own, plus the shared desktop. +function pickBoxBot(control) { + const bots = S.bots.filter((b) => !b.members); + if (bots.length <= 1) return openBox(control); + sheet(control ? "接管哪個 Bot 的螢幕?" : "看哪個 Bot 的螢幕?", [...bots.map((b) => ({icon: "monitor", label: b.name + " 的螢幕", on: () => openBox(control, b.id)})), {icon: "monitor", label: "共用的桌面", on: () => openBox(control, 0)}]); +} +function openBox(control, which) { + const b = which === undefined ? (bot(S.open) || S.bots.find((x) => x.primary) || {}) : which ? bot(which) || {} : {}; const own = (b.computers || []).find((c) => c.kind === "own"); const at = S.relay ? "host=" + encodeURIComponent(S.host) : "lan=1"; boxOpen = true; history.pushState({box: 1}, ""); - $("boxframe").src = "screen#" + at + "&name=" + encodeURIComponent(own ? own.name : "Bot 的電腦") + (b.id ? "&bot=" + b.id : "") + (control ? "&control=1" : "") + "&embed=1"; + newBoxFrame("screen#" + at + "&name=" + encodeURIComponent(own ? own.name : "Bot 的電腦") + (b.id ? "&bot=" + b.id : "") + (control ? "&control=1" : "") + "&embed=1"); $("boxwrap").style.display = "block"; } function closeBox() { boxOpen = false; $("boxwrap").style.display = "none"; - $("boxframe").src = "about:blank"; + newBoxFrame(""); +} +// A fresh frame each time, never a new address in the same one: an iframe that navigates adds +// to the page's back history, and after the first open and close 返回 (and the screen's ✕) went +// back inside the frame instead of closing it — the takeover screen stayed and could not be left. +function newBoxFrame(url) { + const old = $("boxframe"), f = old.cloneNode(false); + f.removeAttribute("src"); + if (url) f.src = url; + old.replaceWith(f); } window.addEventListener("message", (e) => { if (e.origin !== location.origin || !e.data) return; @@ -4067,11 +4671,11 @@ async function frames(run) { try { const r = await api(base() + "api/screen/mac", {raw: true}); if (S.frameRun !== run) return; - if (!r.ok) { const v = await r.json().catch(() => ({})); $("stage").innerHTML = `<div class="msg">${esc(v.error || "看不到畫面")}</div>`; $("screen-live").textContent = ""; await nap(1500); continue; } + if (!r.ok) { const v = await r.json().catch(() => ({})); $("stage").innerHTML = `<div class="msg">${esc(v.error || "看不到畫面")}</div>`; $("screen-live").textContent = ""; macShowPad(); await nap(1500); continue; } S.size = (r.headers.get("X-Size") || "0x0").split("x").map(Number); const url = URL.createObjectURL(await safeBlob(r)); let img = $("stage").querySelector("img"); - if (!img) { $("stage").innerHTML = ""; img = document.createElement("img"); img.draggable = false; $("stage").appendChild(img); bindStage(img); } + if (!img) { $("stage").innerHTML = ""; img = document.createElement("img"); img.draggable = false; $("stage").appendChild(img); bindStage(img); img.onload = () => { img.onload = null; macShowPad(); }; } img.src = url; if (lastUrl) URL.revokeObjectURL(lastUrl); lastUrl = url; $("screen-live").innerHTML = `<span class="live"></span>即時`; await nap(700); @@ -4083,25 +4687,131 @@ function point(img, e) { const w = S.size[0] || img.naturalWidth, h = S.size[1] || img.naturalHeight; return {x: Math.round((e.clientX - r.left) / r.width * w), y: Math.round((e.clientY - r.top) / r.height * h), cx: e.clientX - $("stage").getBoundingClientRect().left, cy: e.clientY - $("stage").getBoundingClientRect().top}; } +// Without the touchpad: a tap clicks where it lands, a long press right-clicks, two quick taps +// are a double click. function bindStage(img) { - let pressTimer = null, long = false; - img.addEventListener("pointerdown", (e) => { long = false; pressTimer = setTimeout(() => { long = true; tap(img, e, "right"); }, 550); }); - img.addEventListener("pointerup", (e) => { clearTimeout(pressTimer); if (!long) tap(img, e, S.right ? "right" : "left"); }); + let pressTimer = null, long = false, last = 0; + img.addEventListener("pointerdown", (e) => { if (MAC.padOn) return; long = false; pressTimer = setTimeout(() => { long = true; tap(img, e, "right"); }, 550); }); + img.addEventListener("pointerup", (e) => { + clearTimeout(pressTimer); + if (MAC.padOn || long) return; + const t = Date.now(); + if (t - last < 320) { const p = point(img, e); screenInput({kind: "click", x: p.x, y: p.y, count: 2, modifiers: MAC.mods ? MAC.mods.list() : []}); last = 0; return; } + last = t; + tap(img, e, "left"); + }); img.addEventListener("pointercancel", () => clearTimeout(pressTimer)); - img.addEventListener("dblclick", (e) => { const p = point(img, e); screenInput({kind: "click", x: p.x, y: p.y, count: 2}); }); } function tap(img, e, button) { const p = point(img, e); const d = document.createElement("div"); d.className = "tapdot"; d.style.left = p.cx + "px"; d.style.top = p.cy + "px"; $("stage").appendChild(d); setTimeout(() => d.remove(), 600); - screenInput({kind: "click", x: p.x, y: p.y, button}); + screenInput({kind: "click", x: p.x, y: p.y, button, modifiers: MAC.mods ? MAC.mods.list() : []}); + MAC.mods?.used(); } async function screenInput(body) { try { await api(base() + "api/screen/mac", {json: body}); } catch (e) { toast(e.message); } } -document.querySelectorAll("[data-key]").forEach((b) => b.onclick = () => screenInput({kind: "key", key: b.dataset.key})); -document.querySelectorAll("[data-scroll]").forEach((b) => b.onclick = () => screenInput({kind: "scroll", x: Math.round(S.size[0] / 2), y: Math.round(S.size[1] / 2), direction: b.dataset.scroll, amount: 5})); -$("k-type").onclick = () => { $("typebar").classList.toggle("on"); if ($("typebar").classList.contains("on")) $("typein").focus(); }; -$("b-type").onclick = () => { const t = $("typein").value; if (!t) return; $("typein").value = ""; screenInput({kind: "type", text: t}); }; + +// 虛擬觸控板 and the key bar on this Mac's screen (mobile/trackpad.js, shared with the bots' +// computer): the pointer lives in the shown picture's pixels and is sent in the screenshot's. +const MAC = {padOn: localStorage.getItem("anybot.pad") !== "0", pad: null, mods: null, T: null, path: null, moveAt: 0, moveTimer: 0}; +const MAC_KEY = {Delete: "forwarddelete", BackSpace: "backspace", Return: "return", PageUp: "pageup", PageDown: "pagedown", "[": "bracketleft", "]": "bracketright"}; +const macKey = (k) => MAC_KEY[k] || k.toLowerCase(); +function macShot(x, y) { + const img = $("stage").querySelector("img"); + if (!img || !img.clientWidth) return {x: 0, y: 0}; + const w = S.size[0] || img.naturalWidth, h = S.size[1] || img.naturalHeight; + return {x: Math.round(x / img.clientWidth * w), y: Math.round(y / img.clientHeight * h)}; +} +function macPlace(x, y) { + const img = $("stage").querySelector("img"); + if (!img) return; + const ir = img.getBoundingClientRect(), wr = $("mac-pad").getBoundingClientRect(); + $("mac-ptr").style.left = (ir.left - wr.left + x) + "px"; + $("mac-ptr").style.top = (ir.top - wr.top + y) + "px"; +} +function macPress(key, extra = []) { + const list = [...new Set([...(MAC.mods ? MAC.mods.list() : []), ...extra])]; + screenInput({kind: "key", key: [...list, macKey(key)].join("+")}); + MAC.mods?.used(); +} +async function macTools() { + if (!MAC.T) { + try { MAC.T = await import("./trackpad.js"); } catch (_) { MAC.padOn = false; renderMacBar(); return; } + const T = MAC.T; + MAC.mods = T.modState(() => renderMacBar()); + MAC.pad = T.trackpad($("mac-pad"), { + bounds() { const img = $("stage").querySelector("img"); return img ? {w: img.clientWidth || 1, h: img.clientHeight || 1} : {w: 1, h: 1}; }, + move(x, y) { + if (MAC.path) { const p = macShot(x, y), l = MAC.path[MAC.path.length - 1]; if (Math.hypot(p.x - l.x, p.y - l.y) > 10 && MAC.path.length < 80) MAC.path.push(p); return; } + // (At most every 150 ms, the last place always sent.) + clearTimeout(MAC.moveTimer); + const go = () => { MAC.moveAt = Date.now(); const p = macShot(x, y); screenInput({kind: "move", x: p.x, y: p.y}); }; + if (Date.now() - MAC.moveAt > 150) go(); else MAC.moveTimer = setTimeout(go, 150); + }, + down(x, y) { MAC.path = [macShot(x, y)]; }, + up(x, y) { + const path = MAC.path || []; MAC.path = null; + path.push(macShot(x, y)); + if (path.length >= 2) screenInput({kind: "drag", path, modifiers: MAC.mods.list()}); + MAC.mods.used(); + }, + click(x, y, button, count) { const p = macShot(x, y); screenInput({kind: "click", x: p.x, y: p.y, button, count, modifiers: MAC.mods.list()}); MAC.mods.used(); }, + scroll(x, y, dx, dy) { if (!dy) return; const p = macShot(x, y); screenInput({kind: "scroll", x: p.x, y: p.y, direction: dy > 0 ? "down" : "up", amount: Math.min(20, Math.abs(dy) * 2)}); }, + show: macPlace, + }); + $("mac-combos").innerHTML = T.COMBOS.mac.map(([name, ms, k], i) => `<button class="btn" data-combo="${i}">${esc(name)}<small>${esc(T.comboLabel(ms, k))}</small></button>`).join(""); + } + macShowPad(); + renderMacBar(); +} +function macShowPad() { + const on = MAC.padOn && !!MAC.pad && !!$("stage").querySelector("img"); + $("mac-pad").classList.toggle("on", on); + $("mac-ptr").classList.toggle("on", on); + if (MAC.pad) MAC.pad.enabled = on; + if (on && !MAC.centered) { MAC.centered = true; MAC.pad.center(); macTip(); } +} +function macTip() { + const n = Number(localStorage.getItem("anybot.padTip") || 0); + if (n >= 3) return; + localStorage.setItem("anybot.padTip", String(n + 1)); + $("mac-tip").innerHTML = "<b>一指</b>移動游標・<b>點一下</b>按・<b>點兩下按住</b>拖曳・<b>兩指</b>捲動・<b>兩指點</b>右鍵"; + $("mac-tip").classList.add("on"); + setTimeout(() => $("mac-tip").classList.remove("on"), 5000); +} +// 觸控板 | ⌘ ⌥ ⌃ ⇧ | Esc Tab ← ↑ ↓ → ⌫ Del ⏎ … | 快捷鍵 ⌨ 打字 +function renderMacBar() { + const T = MAC.T; + const b = (attrs, label, cls = "") => `<button class="btn ${cls}" ${attrs}>${label}</button>`; + $("mac-bar").innerHTML = b('data-pad="1"', "觸控板", MAC.padOn ? "on" : "") + '<span class="sep"></span>' + + (T ? T.MODS.mac.map(([m, l]) => b(`data-mod="${m}"`, l, MAC.mods.get(m))).join("") + '<span class="sep"></span>' + T.KEYS.map(([k, l]) => b(`data-key="${k}"`, esc(l))).join("") + '<span class="sep"></span>' : "") + + (T ? b('data-combos="1"', "快捷鍵", $("mac-combos").classList.contains("on") ? "on" : "") : "") + + b('data-kb="1"', "⌨ 打字", $("typebar").classList.contains("on") ? "on" : ""); +} +$("mac-bar").onclick = (e) => { + const t = e.target.closest("button"); + if (!t) return; + if (t.dataset.pad) { MAC.padOn = !MAC.padOn; localStorage.setItem("anybot.pad", MAC.padOn ? "1" : "0"); macShowPad(); } + else if (t.dataset.mod) MAC.mods.tap(t.dataset.mod); + else if (t.dataset.key) macPress(t.dataset.key); + else if (t.dataset.combos) $("mac-combos").classList.toggle("on"); + else if (t.dataset.kb) { $("typebar").classList.toggle("on"); if ($("typebar").classList.contains("on")) $("typein").focus(); } + renderMacBar(); +}; +$("mac-combos").onclick = (e) => { + const c = e.target.closest("[data-combo]"); + if (!c || !MAC.T) return; + const [, ms, k] = MAC.T.COMBOS.mac[Number(c.dataset.combo)]; + macPress(k, ms); + navigator.vibrate?.(8); +}; +$("b-type").onclick = () => { + const t = $("typein").value; if (!t) return; $("typein").value = ""; + // A modifier held and one letter typed: that shortcut (⌘, then c → ⌘C), not the letter. + if (MAC.mods && MAC.mods.list().length && [...t].length === 1) macPress(t); + else screenInput({kind: "type", text: t}); +}; $("typein").addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.isComposing) { e.preventDefault(); $("b-type").click(); } }); -$("k-right").onclick = () => { S.right = !S.right; $("k-right").textContent = "右鍵:" + (S.right ? "開" : "關"); }; +window.addEventListener("resize", () => { if (MAC.pad && $("mac-pad").classList.contains("on")) { const p = MAC.pad.pos; macPlace(p.x, p.y); } }); // ---------- 傳送: a file or a few words to another device of the account ---------- // The brain carries it (src/drops.rs): to a computer it lands in 下載/AnyBot (words: on its diff --git a/mobile/screen.html b/mobile/screen.html index 34dc527..5e1406b 100644 --- a/mobile/screen.html +++ b/mobile/screen.html @@ -66,8 +66,38 @@ background: #0e0e0e; border: 1px solid var(--line); border-radius: 10px; padding: 0 10px; outline: none; } #type input:focus { border-color: var(--accent); } - .key-group { display: flex; gap: 4px; flex-wrap: wrap; } - .key-group button { height: 28px; padding: 0 9px; border-radius: 8px; font-size: 12px; } + /* 虛擬觸控板: a layer over the picture that takes the fingers; the pointer drawn on it. */ + #pad { position: absolute; inset: 0; z-index: 5; display: none; touch-action: none; -webkit-user-select: none; user-select: none; -webkit-touch-callout: none; } + #pad.on { display: block; } + #ptr { position: absolute; z-index: 6; width: 20px; height: 20px; margin: -2px 0 0 -3px; pointer-events: none; display: none; filter: drop-shadow(0 1px 2px rgba(0,0,0,0.6)); } + #ptr.on { display: block; } + #tip { + position: absolute; z-index: 7; left: 50%; bottom: 12px; transform: translateX(-50%); max-width: calc(100% - 24px); + background: rgba(30, 29, 27, 0.92); border: 1px solid var(--line); border-radius: 14px; padding: 9px 12px; + font-size: 12.5px; line-height: 1.6; color: var(--text); pointer-events: none; opacity: 0; transition: opacity 0.3s; + } + #tip.on { opacity: 1; } + #tip b { font-weight: 600; color: var(--accent); } + /* The key bar: modifiers you tap (once: the next key; twice: locked), and the keys a phone lacks. */ + #bar { + display: none; gap: 6px; padding: 8px 10px; padding-bottom: max(8px, env(safe-area-inset-bottom)); + background: var(--bar); border-top: 1px solid var(--line); overflow-x: auto; scrollbar-width: none; flex: none; + } + #bar::-webkit-scrollbar { display: none; } + #bar.on { display: flex; } + #bar button { height: 36px; min-width: 40px; padding: 0 10px; border-radius: 10px; flex: none; font-size: 13px; } + #bar .sep { width: 1px; background: var(--line); margin: 4px 2px; flex: none; } + #bar button.once { background: rgba(216, 131, 102, 0.22); border-color: var(--accent); color: var(--accent); } + #bar button.lock { background: var(--accent); border-color: var(--accent); color: #fff; } + #bar button.on { background: var(--text); border-color: var(--text); color: var(--bar); } + #combos { + display: none; grid-template-columns: repeat(3, 1fr); gap: 6px; padding: 10px; background: var(--bar); + border-top: 1px solid var(--line); max-height: 40vh; overflow-y: auto; flex: none; + } + #combos.on { display: grid; } + #combos button { height: auto; min-height: 48px; flex-direction: column; gap: 2px; border-radius: 12px; padding: 6px 4px; } + #combos button small { color: var(--dim); font-size: 11px; font-weight: 400; letter-spacing: 0.5px; } + body.has-bar #type { padding-bottom: 8px; } </style> </head> <body> @@ -77,25 +107,19 @@ <div class="name" id="name">Bot 的電腦</div> <div class="state"><span class="dot" id="dot"></span><span id="state">連線中…</span></div> </div> - <button id="kb" title="輸入文字(支援中文與貼上)">打字</button> <button class="main" id="take">接管</button> <button class="icon" id="popout" title="在新分頁打開" style="display:none">↗</button> </header> -<div id="screen"><div id="msg">正在連接畫面…</div></div> +<div id="screen"><div id="msg">正在連接畫面…</div><div id="pad"></div><svg id="ptr" viewBox="0 0 20 20"><path d="M3 2 L3 16 L7 12.5 L9.6 18 L12 17 L9.5 11.6 L14.5 11.6 Z" fill="#fff" stroke="#111" stroke-width="1.2" stroke-linejoin="round"/></svg><div id="tip"></div></div> +<div id="combos"></div> <div id="type"> <input id="text" placeholder="輸入文字(支援中文輸入法),按 Enter 送出到電腦" autocomplete="off" enterkeyhint="send"> <button class="main" id="send">送出</button> - <div class="key-group"> - <button data-k="Return">Enter</button> - <button data-k="Escape">Esc</button> - <button data-k="Tab">Tab</button> - <button data-k="BackSpace">⌫</button> - <button data-k="Up">↑</button> - <button data-k="Down">↓</button> - </div> </div> +<div id="bar"></div> <script type="module"> import RFB from "./novnc.js"; +import { trackpad, MODS, KEYS, COMBOS, comboLabel, modState } from "./trackpad.js"; const q = new URLSearchParams(location.hash.slice(1)); const sq = new URLSearchParams(location.search); @@ -174,16 +198,128 @@ if (embed) { } let rfb = null, ws = null, control = q.get("control") === "1", tries = 0, connected = false, closed = false; -const KEYS = { Return: 0xff0d, Escape: 0xff1b, Tab: 0xff09, BackSpace: 0xff08, Up: 0xff52, Down: 0xff54 }; +// X11 keysyms (the bots' computer is Linux) and the browser key codes noVNC sends beside them. +const SYM = { Return: 0xff0d, Escape: 0xff1b, Tab: 0xff09, BackSpace: 0xff08, Delete: 0xffff, Up: 0xff52, Down: 0xff54, Left: 0xff51, Right: 0xff53, Home: 0xff50, End: 0xff57, PageUp: 0xff55, PageDown: 0xff56, F11: 0xffc8, space: 0x20, ctrl: 0xffe3, alt: 0xffe9, shift: 0xffe1, super: 0xffeb }; +const CODE = { Return: "Enter", Escape: "Escape", Tab: "Tab", BackSpace: "Backspace", Delete: "Delete", Up: "ArrowUp", Down: "ArrowDown", Left: "ArrowLeft", Right: "ArrowRight", Home: "Home", End: "End", PageUp: "PageUp", PageDown: "PageDown", F11: "F11", space: "Space", ctrl: "ControlLeft", alt: "AltLeft", shift: "ShiftLeft", super: "MetaLeft" }; +const symOf = (k) => SYM[k] !== undefined ? SYM[k] : k.length === 1 ? k.toLowerCase().charCodeAt(0) : 0; +const codeOf = (k) => CODE[k] || (/^[a-z]$/i.test(k) ? "Key" + k.toUpperCase() : /^[0-9]$/.test(k) ? "Digit" + k : ""); +const mods = modState(() => renderBar()); +// Hold the modifiers down around `fn` (a key or a click), then let the once-held ones go. +function withMods(list, fn) { + if (!rfb) return; + for (const m of list) rfb.sendKey(SYM[m], CODE[m], true); + fn(); + for (const m of [...list].reverse()) rfb.sendKey(SYM[m], CODE[m], false); +} +function press(key, extra = []) { + const list = [...new Set([...mods.list(), ...extra])]; + withMods(list, () => rfb.sendKey(symOf(key), codeOf(key))); + mods.used(); +} + +// 虛擬觸控板 over noVNC: the pointer lives in the canvas's own (shown) pixels; noVNC turns them +// into the remote screen's. (Its _handleMouse* are the same calls its own mouse handling makes.) +let mask = 0, padOn = localStorage.getItem("anybot.pad") !== "0"; +const BIT = { left: 1, right: 4 }; +const canvas = () => rfb && rfb._canvas; +function placePtr(x, y) { + const c = canvas(); + if (!c) return; + const cr = c.getBoundingClientRect(), sr = $("screen").getBoundingClientRect(); + $("ptr").style.left = (cr.left - sr.left + x) + "px"; + $("ptr").style.top = (cr.top - sr.top + y) + "px"; +} +const pad = trackpad($("pad"), { + bounds() { const c = canvas(); return c ? { w: c.clientWidth || 1, h: c.clientHeight || 1 } : { w: 1, h: 1 }; }, + move(x, y) { rfb?._handleMouseMove(x, y); }, + down(x, y, b) { if (!rfb) return; mask |= BIT[b]; rfb._handleMouseButton(x, y, mask); }, + up(x, y, b) { if (!rfb) return; mask &= ~BIT[b]; rfb._handleMouseButton(x, y, mask); }, + click(x, y, b, n) { + if (!rfb) return; + // (n = 2: the second click of a double click — one more press; the screen counts them itself.) + withMods(mods.list(), () => { rfb._handleMouseButton(x, y, mask | BIT[b]); rfb._handleMouseButton(x, y, mask); }); + mods.used(); + }, + scroll(x, y, dx, dy) { + if (!rfb) return; + const notch = (bit, n) => { for (let i = 0; i < Math.abs(n); i++) { rfb._handleMouseButton(x, y, mask | bit); rfb._handleMouseButton(x, y, mask); } }; + if (dy) notch(dy > 0 ? 16 : 8, dy); + if (dx) notch(dx > 0 ? 64 : 32, dx); + }, + show: placePtr, +}); +function tip() { + const n = Number(localStorage.getItem("anybot.padTip") || 0); + if (n >= 3) return; + localStorage.setItem("anybot.padTip", String(n + 1)); + $("tip").innerHTML = "<b>一指</b>移動游標・<b>點一下</b>按・<b>點兩下按住</b>拖曳・<b>兩指</b>捲動・<b>兩指點</b>右鍵"; + $("tip").classList.add("on"); + setTimeout(() => $("tip").classList.remove("on"), 5000); +} +function showPad() { + const on = control && padOn && connected; + $("pad").classList.toggle("on", on); + $("ptr").classList.toggle("on", on); + pad.enabled = on; + if (on) { pad.center(); tip(); } +} + +// The bar: 觸控板 | Ctrl Alt Shift ❖ | Esc Tab ← ↑ ↓ → ⌫ Del ⏎ Home End PgUp PgDn | 快捷鍵 ⌨ +function renderBar() { + const b = $("bar"); + const btn = (attrs, label, cls = "") => `<button ${attrs} class="${cls}">${label}</button>`; + b.innerHTML = btn('data-pad="1" title="觸控板:手指移動游標;關掉改成點哪裡按哪裡"', "觸控板", padOn ? "on" : "") + + '<span class="sep"></span>' + + MODS.linux.map(([m, l]) => btn(`data-mod="${m}"`, l, mods.get(m))).join("") + + '<span class="sep"></span>' + + KEYS.map(([k, l]) => btn(`data-key="${k}"`, l)).join("") + + '<span class="sep"></span>' + + btn('data-combos="1"', "快捷鍵", $("combos").classList.contains("on") ? "on" : "") + + btn('data-kb="1" title="輸入文字(支援中文與貼上)"', "⌨ 打字", $("type").classList.contains("on") ? "on" : ""); +} +$("combos").innerHTML = COMBOS.linux.map(([name, ms, k], i) => `<button data-combo="${i}">${name}<small>${comboLabel(ms, k, "linux")}</small></button>`).join(""); +$("combos").onclick = (e) => { + const c = e.target.closest("[data-combo]"); + if (!c) return; + const [, ms, k] = COMBOS.linux[Number(c.dataset.combo)]; + press(k, ms); + navigator.vibrate?.(8); +}; +$("bar").onclick = (e) => { + const t = e.target.closest("button"); + if (!t) return; + if (t.dataset.pad) { padOn = !padOn; localStorage.setItem("anybot.pad", padOn ? "1" : "0"); showPad(); } + else if (t.dataset.mod) mods.tap(t.dataset.mod); + else if (t.dataset.key) press(t.dataset.key); + else if (t.dataset.combos) $("combos").classList.toggle("on"); + else if (t.dataset.kb) { $("type").classList.toggle("on"); if ($("type").classList.contains("on")) $("text").focus(); } + renderBar(); +}; function state(text, kind) { $("state").textContent = text; $("dot").className = "dot" + (kind ? " " + kind : ""); } function message(text) { $("msg").textContent = text; $("msg").style.display = text ? "" : "none"; } +// 接管 holds the bot's screen: its steps there wait while you drive (交還給 Bot lets them go on). +const apiBase = lan ? "" : "h/" + encodeURIComponent(host) + "/"; +// (The brain keeps a hold for half a minute: said again every ten seconds while it lasts, so a +// phone that drops off the line lets go by itself, and a brain that restarted hears it again.) +let holding = false; +setInterval(() => { if (holding) hold(true, true); }, 10000); +function hold(on, again) { + if ((on === holding && !again) || !token) return; + holding = on; + const bot = /^\d+$/.test(q.get("bot") || "") ? Number(q.get("bot")) : null; + fetch(apiBase + "api/box/hold", { method: "POST", keepalive: true, headers: { Authorization: "Bearer " + token, "Content-Type": "application/json" }, body: JSON.stringify({ bot, on }) }).catch(() => {}); +} function showControl() { $("take").textContent = control ? "交還給 Bot" : "接管"; $("take").className = control ? "hold-on" : "main"; - $("kb").style.display = control ? "" : "none"; - if (!control) $("type").classList.remove("on"); - if (rfb) { rfb.viewOnly = !control; if (control) rfb.focus(); } + $("bar").classList.toggle("on", control); + document.body.classList.toggle("has-bar", control); + if (!control) { $("type").classList.remove("on"); $("combos").classList.remove("on"); } + renderBar(); + hold(control && connected); + showPad(); + if (rfb) { rfb.viewOnly = !control; if (control && !padOn) rfb.focus(); } if (connected) state(control ? "你在操作(Bot 會等你完成)" : "即時觀看", control ? "hold" : "live"); if (embed && window.parent !== window) { try { window.parent.postMessage({ anybotScreen: "control", control }, location.origin); } catch (_) {} @@ -219,25 +355,26 @@ async function connect() { rfb.viewOnly = !control; rfb.addEventListener("connect", () => { tries = 0; connected = true; message(""); showControl(); }); rfb.addEventListener("disconnect", () => { - rfb = null; connected = false; + rfb = null; connected = false; mask = 0; hold(false); showPad(); if (closed) return; retry(); }); } $("take").onclick = () => { control = !control; showControl(); }; -$("kb").onclick = () => { $("type").classList.toggle("on"); if ($("type").classList.contains("on")) $("text").focus(); }; function send() { const t = $("text").value; if (!t || !ws || ws.readyState !== 1) return; - ws.send(t); + // A modifier held and one letter typed: that shortcut (Ctrl, then c → Ctrl+C), not the letter. + if (mods.list().length && [...t].length === 1) press(t); + else ws.send(t); $("text").value = ""; } $("send").onclick = send; $("text").addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.isComposing) { e.preventDefault(); send(); } }); -document.querySelectorAll("[data-k]").forEach((b) => b.onclick = () => { if (rfb) rfb.sendKey(KEYS[b.dataset.k], b.dataset.k); }); $("back").onclick = () => { closed = true; + hold(false); if (rfb) { try { rfb.disconnect(); } catch (_) {} } if (embed && window.parent !== window) { window.parent.postMessage({ anybotScreen: "close" }, location.origin); @@ -256,6 +393,11 @@ window.addEventListener("message", (e) => { } }); +// Away from the page (the phone locked, another app): let the bot go on; back again, hold again. +document.addEventListener("visibilitychange", () => hold(control && connected && !document.hidden)); +window.addEventListener("pagehide", () => hold(false)); +window.addEventListener("resize", () => { if ($("pad").classList.contains("on")) { const p = pad.pos; placePtr(p.x, p.y); } }); + showControl(); connect(); </script> diff --git a/mobile/trackpad.js b/mobile/trackpad.js new file mode 100644 index 0000000..c0aabd4 --- /dev/null +++ b/mobile/trackpad.js @@ -0,0 +1,229 @@ +// 虛擬觸控板:在手機上操作一台電腦的畫面,像用筆電的觸控板,不是用手指去戳小小的畫面。 +// 用在 Bot 的電腦(screen.html,noVNC)和這台 Mac 的畫面(index.html #v-screen)。 +// +// 一指滑動 移動游標(滑得快走得遠) +// 點一下 在游標的位置按左鍵 +// 點兩下 連點(點兩下、第二下按住不放再滑:拖曳) +// 兩指滑動 捲動(上下左右) +// 兩指點 右鍵;長按也是右鍵 +// +// The page gives a `host` that knows its own screen: +// bounds() → {w, h}: the picture's size, in the same units as the pointer +// move(x, y) the pointer moved (no button change) +// down(x, y, button) a button went down ("left" | "right") +// up(x, y, button) …and up +// click(x, y, button, n) n clicks there +// scroll(x, y, dx, dy) whole wheel notches (positive dy: the page goes down) +// show(x, y) draw the pointer there +// and an element `pad` laid over the picture that takes the touches. + +const SLOP = 7; // px a finger may wander and still be a tap +const TAP_MS = 260; // a two-finger tap is quicker than this (and a half) +const DOUBLE_MS = 320; // the second tap of a double tap comes within this +const DOUBLE_SLOP = 40; // …and this near the first +const HOLD_MS = 560; // a press this long without moving is a right click +const NOTCH = 22; // px of two-finger travel per wheel notch +const GAIN = 1.15; // pointer px per finger px, slowly +const ACCEL_FROM = 0.3; // finger px/ms where it starts to speed up +const ACCEL_MAX = 1.6; // at most this much extra gain + +export function trackpad(pad, host) { + const pos = { x: 0, y: 0 }; + const fingers = new Map(); + let mode = null; // "tap" | "move" | "second" | "drag" | "two" | "scroll" | "done" + let lastTap = null; // {t, x, y} of the last single tap (where the finger was) + let holdTimer = 0; + let twoAt = 0, twoMoved = false, acc = { x: 0, y: 0 }, prevMid = null; + let enabled = true; + + const now = () => performance.now(); + const clamp = () => { + const b = host.bounds(); + pos.x = Math.max(0, Math.min(b.w - 1, pos.x)); + pos.y = Math.max(0, Math.min(b.h - 1, pos.y)); + }; + const center = () => { + const b = host.bounds(); + pos.x = b.w / 2; pos.y = b.h / 2; + host.show(pos.x, pos.y); + }; + const mid = () => { + const a = [...fingers.values()]; + return { x: a.reduce((s, f) => s + f.x, 0) / a.length, y: a.reduce((s, f) => s + f.y, 0) / a.length }; + }; + const stopHold = () => { clearTimeout(holdTimer); holdTimer = 0; }; + + function onDown(e) { + if (!enabled) return; + e.preventDefault(); + try { pad.setPointerCapture(e.pointerId); } catch (_) {} + const t = now(); + fingers.set(e.pointerId, { x: e.clientX, y: e.clientY, sx: e.clientX, sy: e.clientY, lx: e.clientX, ly: e.clientY, lt: t, t }); + if (fingers.size === 1) { + const near = lastTap && t - lastTap.t < DOUBLE_MS && Math.hypot(e.clientX - lastTap.x, e.clientY - lastTap.y) < DOUBLE_SLOP; + mode = near ? "second" : "tap"; + stopHold(); + if (!near) holdTimer = setTimeout(() => { + if (mode === "tap") { host.click(pos.x, pos.y, "right", 1); mode = "done"; navigator.vibrate?.(10); } + }, HOLD_MS); + } else if (fingers.size === 2) { + stopHold(); + if (mode === "drag") host.up(pos.x, pos.y, "left"); + mode = "two"; twoAt = t; twoMoved = false; acc = { x: 0, y: 0 }; prevMid = mid(); + } + } + + function onMove(e) { + const f = fingers.get(e.pointerId); + if (!f || !enabled) return; + e.preventDefault(); + const t = now(); + f.x = e.clientX; f.y = e.clientY; + if (fingers.size === 1) { + const far = Math.hypot(f.x - f.sx, f.y - f.sy) > SLOP; + if (mode === "tap" && far) { mode = "move"; stopHold(); } + if (mode === "second" && far) { mode = "drag"; host.down(pos.x, pos.y, "left"); } + if (mode === "move" || mode === "drag") { + const dx = f.x - f.lx, dy = f.y - f.ly, dt = Math.max(1, t - f.lt); + const speed = Math.hypot(dx, dy) / dt; + const gain = GAIN * (1 + Math.min(ACCEL_MAX, Math.max(0, speed - ACCEL_FROM) * 1.2)); + pos.x += dx * gain; pos.y += dy * gain; + clamp(); + host.move(pos.x, pos.y); + host.show(pos.x, pos.y); + } + } else if (fingers.size === 2 && (mode === "two" || mode === "scroll")) { + const m = mid(); + const dx = m.x - prevMid.x, dy = m.y - prevMid.y; + prevMid = m; + if (!twoMoved && Math.hypot(acc.x + dx, acc.y + dy) > SLOP) { twoMoved = true; mode = "scroll"; } + acc.x += dx; acc.y += dy; + if (mode === "scroll") { + // Natural scrolling, like a Mac's trackpad: fingers up, the page goes down. + const nx = Math.trunc(acc.x / NOTCH), ny = Math.trunc(acc.y / NOTCH); + if (nx || ny) { + host.scroll(pos.x, pos.y, -nx, -ny); + acc.x -= nx * NOTCH; acc.y -= ny * NOTCH; + } + } + } + f.lx = f.x; f.ly = f.y; f.lt = t; + } + + function onUp(e) { + const f = fingers.get(e.pointerId); + if (!f) return; + e.preventDefault(); + const t = now(); + fingers.delete(e.pointerId); + stopHold(); + // (Still "tap": it never moved and the long press hasn't fired — a slow tap is a tap too.) + if (mode === "tap" && fingers.size === 0) { + host.click(pos.x, pos.y, "left", 1); + lastTap = { t, x: f.sx, y: f.sy }; + mode = null; + return; + } + if (mode === "second" && fingers.size === 0) { + // The second tap of a double tap: the first click went already; this one says it is the + // second (a Mac counts clicks by what it is told; a VNC screen counts them itself). + host.click(pos.x, pos.y, "left", 2); + lastTap = null; + mode = null; + return; + } + if (mode === "drag" && fingers.size === 0) host.up(pos.x, pos.y, "left"); + if (mode === "two" && !twoMoved && t - twoAt < TAP_MS * 1.5) { + host.click(pos.x, pos.y, "right", 1); + mode = "done"; + } + if (fingers.size === 0) { mode = null; lastTap = null; } + } + + pad.addEventListener("pointerdown", onDown); + pad.addEventListener("pointermove", onMove); + pad.addEventListener("pointerup", onUp); + // (The system took the touch away — a gesture, a call: nothing was pressed.) + pad.addEventListener("pointercancel", (e) => { + if (!fingers.has(e.pointerId)) return; + fingers.delete(e.pointerId); stopHold(); + if (mode === "drag") host.up(pos.x, pos.y, "left"); + if (fingers.size === 0) mode = null; else mode = "done"; + }); + // (No page zoom, no text selection, no long-press menu while the fingers are the mouse.) + pad.addEventListener("contextmenu", (e) => e.preventDefault()); + pad.style.touchAction = "none"; + + return { + center, + get pos() { return { ...pos }; }, + // (Switched off in the middle of a drag: the button is let go first.) + set enabled(v) { if (mode === "drag") host.up(pos.x, pos.y, "left"); enabled = !!v; fingers.clear(); mode = null; stopHold(); }, + get enabled() { return enabled; }, + }; +} + +// ── The key bar: modifier keys you tap instead of hold, and the keys a phone keyboard lacks ── +// A modifier tapped once is held for the next key or click, then lets go; tapped twice it +// stays held (locked) until tapped again. `kind`: "linux" (Ctrl Alt Shift Super) or "mac" +// (⌘ ⌥ ⌃ ⇧). +export const MODS = { + linux: [["ctrl", "Ctrl"], ["alt", "Alt"], ["shift", "Shift"], ["super", "❖"]], + mac: [["cmd", "⌘"], ["option", "⌥"], ["ctrl", "⌃"], ["shift", "⇧"]], +}; + +export const KEYS = [ + ["Escape", "Esc"], ["Tab", "Tab"], ["Left", "←"], ["Up", "↑"], ["Down", "↓"], ["Right", "→"], + ["BackSpace", "⌫"], ["Delete", "Del"], ["Return", "⏎"], ["Home", "Home"], ["End", "End"], ["PageUp", "PgUp"], ["PageDown", "PgDn"], +]; + +// The shortcuts people reach for, by name (no one should have to find Ctrl and Tab at once). +export const COMBOS = { + linux: [ + ["切換視窗", ["alt"], "Tab"], ["下一個分頁", ["ctrl"], "Tab"], ["上一個分頁", ["ctrl", "shift"], "Tab"], + ["新分頁", ["ctrl"], "t"], ["關閉分頁", ["ctrl"], "w"], ["網址列", ["ctrl"], "l"], + ["上一頁", ["alt"], "Left"], ["下一頁", ["alt"], "Right"], ["重新整理", ["ctrl"], "r"], + ["拷貝", ["ctrl"], "c"], ["貼上", ["ctrl"], "v"], ["剪下", ["ctrl"], "x"], + ["全選", ["ctrl"], "a"], ["復原", ["ctrl"], "z"], ["重做", ["ctrl", "shift"], "z"], + ["尋找", ["ctrl"], "f"], ["存檔", ["ctrl"], "s"], ["全螢幕", [], "F11"], + ], + mac: [ + ["切換 App", ["cmd"], "Tab"], ["下一個分頁", ["ctrl"], "Tab"], ["上一個分頁", ["ctrl", "shift"], "Tab"], + ["新分頁", ["cmd"], "t"], ["關閉分頁", ["cmd"], "w"], ["網址列", ["cmd"], "l"], + ["上一頁", ["cmd"], "["], ["下一頁", ["cmd"], "]"], ["重新整理", ["cmd"], "r"], + ["拷貝", ["cmd"], "c"], ["貼上", ["cmd"], "v"], ["剪下", ["cmd"], "x"], + ["全選", ["cmd"], "a"], ["復原", ["cmd"], "z"], ["重做", ["cmd", "shift"], "z"], + ["尋找", ["cmd"], "f"], ["存檔", ["cmd"], "s"], ["Spotlight", ["cmd"], "space"], + ], +}; + +const MOD_SIGN = { ctrl: "⌃", alt: "⌥", option: "⌥", shift: "⇧", super: "❖", cmd: "⌘" }; +const MOD_WORD = { ctrl: "Ctrl", alt: "Alt", shift: "Shift", super: "Super" }; +const KEY_SIGN = { Tab: "⇥", Left: "←", Right: "→", Up: "↑", Down: "↓", space: "空白" }; +// How a shortcut is written under its name: the Mac's signs (⌘⇧Z), or Linux's words (Ctrl+Shift+Z). +export function comboLabel(mods, key, kind = "mac") { + const k = kind === "linux" && key === "Tab" ? "Tab" : (KEY_SIGN[key] || (key.length === 1 ? key.toUpperCase() : key)); + return kind === "linux" ? [...mods.map((m) => MOD_WORD[m] || m), k].join("+") : mods.map((m) => MOD_SIGN[m] || m).join("") + k; +} + +// The bar's state: which modifiers are held for the next key ("once") or locked ("lock"). +export function modState(onChange) { + const held = new Map(); + let lastTap = { m: "", t: 0 }; + return { + tap(m) { + const t = performance.now(); + const was = held.get(m); + if (was === "lock") held.delete(m); + else if (was === "once" && lastTap.m === m && t - lastTap.t < 400) held.set(m, "lock"); + else if (was === "once") held.delete(m); + else held.set(m, "once"); + lastTap = { m, t }; + onChange(); + }, + get(m) { return held.get(m) || ""; }, + list() { return [...held.keys()]; }, + // After a key or a click: the once-held let go, the locked stay. + used() { let any = false; for (const [m, v] of held) if (v === "once") { held.delete(m); any = true; } if (any) onChange(); }, + }; +} diff --git a/mobile/trackpad.test.mjs b/mobile/trackpad.test.mjs new file mode 100644 index 0000000..7d6a791 --- /dev/null +++ b/mobile/trackpad.test.mjs @@ -0,0 +1,52 @@ +// 虛擬觸控板的手勢(mobile/trackpad.js):手指怎麼變成滑鼠和按鍵。`node mobile/trackpad.test.mjs`; +// cargo test 的 remote::tests::the_touchpad_turns_fingers_into_mouse_and_keys 也跑它(有 node 時)。 +import { trackpad, modState, comboLabel } from "./trackpad.js"; +const L = {}; const pad = { addEventListener: (t, f) => (L[t] = f), setPointerCapture() {}, style: {} }; +let calls = []; +const host = { bounds: () => ({ w: 400, h: 300 }), move: (x, y) => calls.push(["move", Math.round(x), Math.round(y)]), down: (x, y, b) => calls.push(["down", b]), up: (x, y, b) => calls.push(["up", b]), click: (x, y, b, n) => calls.push(["click", b, n]), scroll: (x, y, dx, dy) => calls.push(["scroll", dx, dy]), show() {} }; +const tp = trackpad(pad, host); tp.center(); +const ev = (id, x, y) => ({ pointerId: id, clientX: x, clientY: y, preventDefault() {} }); +const wait = (ms) => new Promise((r) => setTimeout(r, ms)); +const ok = (name, cond) => { console.log((cond ? "OK " : "FAIL ") + name, cond ? "" : JSON.stringify(calls)); if (!cond) process.exitCode = 1; }; +// 1. tap +calls = []; L.pointerdown(ev(1, 100, 100)); await wait(50); L.pointerup(ev(1, 100, 100)); +ok("點一下=左鍵一下", JSON.stringify(calls) === '[["click","left",1]]'); +await wait(400); +// 2. one-finger move +calls = []; L.pointerdown(ev(1, 100, 100)); for (let i = 1; i <= 10; i++) { await wait(16); L.pointermove(ev(1, 100 + i * 5, 100)); } L.pointerup(ev(1, 150, 100)); +ok("一指滑動=移動游標、不按", calls.length > 0 && calls.every((c) => c[0] === "move") && tp.pos.x > 250); +await wait(400); +// 3. two-finger tap +calls = []; L.pointerdown(ev(1, 100, 100)); L.pointerdown(ev(2, 160, 100)); await wait(60); L.pointerup(ev(1, 100, 100)); L.pointerup(ev(2, 160, 100)); +ok("兩指點=右鍵", JSON.stringify(calls) === '[["click","right",1]]'); +await wait(400); +// 4. two-finger scroll up (fingers move up → page goes down: dy > 0) +calls = []; L.pointerdown(ev(1, 100, 200)); L.pointerdown(ev(2, 160, 200)); for (let i = 1; i <= 10; i++) { await wait(16); L.pointermove(ev(1, 100, 200 - i * 8)); L.pointermove(ev(2, 160, 200 - i * 8)); } L.pointerup(ev(1, 100, 120)); L.pointerup(ev(2, 160, 120)); +ok("兩指往上滑=往下捲", calls.length > 0 && calls.every((c) => c[0] === "scroll" && c[2] > 0) && !calls.some((c) => c[0] === "click")); +await wait(400); +// 5. double tap and drag +calls = []; L.pointerdown(ev(1, 200, 150)); await wait(40); L.pointerup(ev(1, 200, 150)); await wait(80); +L.pointerdown(ev(1, 202, 151)); for (let i = 1; i <= 6; i++) { await wait(16); L.pointermove(ev(1, 202 + i * 6, 151)); } L.pointerup(ev(1, 238, 151)); +const kinds = calls.map((c) => c[0]); +ok("點兩下按住滑=拖曳", kinds[0] === "click" && kinds[1] === "down" && kinds.includes("move") && kinds[kinds.length - 1] === "up"); +await wait(400); +// 6. double tap (no drag) = two clicks +calls = []; L.pointerdown(ev(1, 200, 150)); await wait(40); L.pointerup(ev(1, 200, 150)); await wait(80); L.pointerdown(ev(1, 201, 150)); await wait(40); L.pointerup(ev(1, 201, 150)); +ok("點兩下=第一下、再說是第二下", JSON.stringify(calls) === '[["click","left",1],["click","left",2]]'); +await wait(400); +// 6b. a slow tap (longer than a quick one, shorter than a long press) is still a click +calls = []; L.pointerdown(ev(1, 120, 120)); await wait(400); L.pointerup(ev(1, 120, 120)); +ok("按慢一點也算點一下", JSON.stringify(calls) === '[["click","left",1]]'); +await wait(400); +// 6c. the system cancels the touch: nothing is clicked; in a drag, the button is let go +calls = []; L.pointerdown(ev(1, 120, 120)); await wait(40); L.pointercancel(ev(1, 120, 120)); +ok("被系統打斷不算點", calls.length === 0); +await wait(400); +// 7. long press = right click, no left click after +calls = []; L.pointerdown(ev(1, 120, 120)); await wait(650); L.pointerup(ev(1, 120, 120)); +ok("長按=右鍵", JSON.stringify(calls) === '[["click","right",1]]'); +// 8. modifiers: once, lock, used +let n = 0; const m = modState(() => n++); +m.tap("ctrl"); ok("點一下修飾鍵=下一下按住", m.get("ctrl") === "once"); m.used(); ok("用過就放開", m.get("ctrl") === ""); +m.tap("cmd"); m.tap("cmd"); ok("點兩下=鎖住", m.get("cmd") === "lock"); m.used(); ok("鎖住的用過不放開", m.get("cmd") === "lock"); m.tap("cmd"); ok("再點一下放開", m.get("cmd") === ""); +ok("組合鍵的字", comboLabel(["ctrl", "shift"], "Tab") === "⌃⇧⇥" && comboLabel(["cmd"], "c") === "⌘C" && comboLabel(["ctrl", "shift"], "Tab", "linux") === "Ctrl+Shift+Tab" && comboLabel(["alt"], "Left", "linux") === "Alt+←"); diff --git a/relay/src/main.rs b/relay/src/main.rs index 60c89b8..35c402c 100644 --- a/relay/src/main.rs +++ b/relay/src/main.rs @@ -32,6 +32,8 @@ const PAGE: &str = include_str!("../../mobile/index.html"); /// The bots' computer, watched and used in a browser (noVNC). const SCREEN_PAGE: &str = include_str!("../../mobile/screen.html"); const NOVNC: &str = include_str!("../../mobile/novnc.js"); +/// 虛擬觸控板 and the key bar, shared by the screen page and the phone page. +const TRACKPAD: &str = include_str!("../../mobile/trackpad.js"); /// The phone app's manifest and service worker (notifications), shared with the desktop's own /// phone page (src/remote.rs). const MANIFEST: &str = include_str!("../../mobile/manifest.webmanifest"); @@ -1003,6 +1005,7 @@ impl Relay { .with_header("Content-Security-Policy", &format!("default-src 'self'; img-src 'self' blob: data:; style-src 'self' 'unsafe-inline'; {}; connect-src 'self' wss: ws:; base-uri 'none'; object-src 'none'; frame-ancestors 'self'", httpd::script_src(SCREEN_PAGE))) .with_header("Strict-Transport-Security", "max-age=31536000"), ("GET", ["novnc.js"]) => Resp::bytes("text/javascript; charset=utf-8", NOVNC.as_bytes().to_vec()).with_header("Cache-Control", "public, max-age=86400"), + ("GET", ["trackpad.js"]) => Resp::bytes("text/javascript; charset=utf-8", TRACKPAD.as_bytes().to_vec()).with_header("Cache-Control", "no-cache"), // A link for this account's browser to watch one of its AnyBots' computer (the app // opens it; the browser has no session of its own). ("POST", ["relay", "screen-ticket"]) => { diff --git a/src/app.rs b/src/app.rs index c57eda6..7ac8445 100644 --- a/src/app.rs +++ b/src/app.rs @@ -43,6 +43,7 @@ mod voice_ui; mod drops_ui; mod tasks_ui; mod me_ui; +mod models_ui; mod activity_ui; mod library_ui; mod market_ui; @@ -153,7 +154,6 @@ const DRAFT_SAVE_AFTER: std::time::Duration = std::time::Duration::from_millis(1 const WINDOW_SCREEN_MARGIN: f32 = 80.0; /// Provider names in Settings fit on one line (「自訂(OpenAI 相容)」) (estimated). // (Wide enough for 「自訂(OpenAI 相容)」 and the 本機/區網/雲端 tag beside it.) -const PROVIDER_LIST_WIDTH: f32 = 212.0; /// The chat header's 本機/區網/雲端 tag after the bot's name (with its gap). const HEADER_TAG_W: f32 = 40.0; /// Settings: dialog width, its left-hand page list, and a steady height so tabs don't jump. @@ -323,6 +323,8 @@ pub struct App { show_settings: bool, settings_tab: SettingsTab, settings_provider: ProviderKind, + /// 設定 › 模型: one service open (its key and address), or false for the grid of all of them. + settings_provider_open: bool, edit_bot: Option<(Bot, bool)>, /// The bot as its settings were opened (what 「儲存」 measures the person's changes against). edit_bot_from: Option<Bot>, @@ -619,6 +621,7 @@ impl App { show_settings: false, settings_tab: SettingsTab::General, settings_provider: ProviderKind::Xai, + settings_provider_open: false, edit_bot: None, edit_bot_from: None, confirm_delete: None, @@ -758,6 +761,10 @@ impl App { if std::env::var("ANYBOT_SHOT_THEME").as_deref() == Ok("dark") { app.state.theme = Theme::Dark; } + // 風格 for pictures: ANYBOT_SHOT_STYLE=ocean (theme::TEMPLATES). + if let Ok(v) = std::env::var("ANYBOT_SHOT_STYLE") { + app.state.shell_template = v; + } // Shell dials for concept pictures: ANYBOT_SHOT_SHELL=tone,accent,contrast. if let Ok(v) = std::env::var("ANYBOT_SHOT_SHELL") { let mut it = v.split(','); @@ -1038,6 +1045,7 @@ impl App { app.show_settings = true; app.settings_tab = SettingsTab::Providers; app.settings_provider = ProviderKind::Anthropic; + app.settings_provider_open = true; } Ok("general") => { app.show_settings = true; @@ -1440,6 +1448,10 @@ impl App { if let Some(tab) = tab { app.show_settings = true; app.settings_tab = tab; + // 個人資料: a year of sample figures (the demo has no usage of its own). + if tab == SettingsTab::Me { + app.me.demo_fill(); + } } } // ANYBOT_SHOT_STATUS=<text>: what a running turn says it is doing (a long retry message). @@ -1528,7 +1540,7 @@ impl App { /// What the shell is built from, to notice a change (f32s by their bits: equal means unchanged). fn shell_key(&self) -> ShellKey { - (self.state.theme, self.state.shell_tone.to_bits(), self.state.shell_accent.clone(), self.state.shell_contrast.to_bits(), self.state.dense) + (self.state.theme, self.state.shell_tone.to_bits(), format!("{}/{}", self.state.shell_accent, self.state.shell_template), self.state.shell_contrast.to_bits(), self.state.dense) } fn apply_theme(&mut self, ctx: &egui::Context) { @@ -1539,7 +1551,7 @@ impl App { Theme::System => ctx.input(|i| i.raw.system_theme) == Some(egui::Theme::Dark), }; // The shell from the person's three dials (設定 › 一般); defaults reproduce 「紙」. - self.pal = crate::theme::shell(self.state.shell_tone, &self.state.shell_accent, self.state.shell_contrast, dark); + self.pal = crate::theme::palette_for(&self.state.shell_template, self.state.shell_tone, &self.state.shell_accent, self.state.shell_contrast, dark); // Screenshot concept themes for picking a colour direction (see theme.rs `shot_palette`). if let Ok(t) = std::env::var("ANYBOT_SHOT_PAL") { if let Some(p) = crate::theme::shot_palette(&t, dark) { @@ -4296,6 +4308,8 @@ impl App { }; self.header(ui, &bot); self.mirror_banner(ui); + // 風格's backdrop behind the conversation (dots, a grid, waves; the faintest line colour). + chat_backdrop(ui.painter(), ui.available_rect_before_wrap(), crate::theme::backdrop(&self.state.shell_template), p); // The composer grows with a long draft: keep room for last frame's height — but never all // of it: the conversation keeps a strip, and the input stops growing (it scrolls) where // the column ends, even in a short window or the narrow chat beside a workflow. @@ -4462,19 +4476,25 @@ impl App { }); }); ui.add_space(22.0); - let fill = if tinted { crate::theme::mist(col, p) } else { p.hover }; - for words in EMPTY_STARTS { - let words = t(words); - let (rect, r) = ui.allocate_exact_size(vec2(ui.available_width().min(560.0), 48.0), egui::Sense::click()); - ui.painter().rect_filled(rect, R_L, if r.hovered() { fill.gamma_multiply(0.92).to_opaque().lerp_to_gamma(p.text, 0.04) } else { fill }); - ui.painter().text(rect.left_center() + vec2(18.0, 0.0), egui::Align2::LEFT_CENTER, &words, egui::FontId::proportional(FONT_BASE), p.text); - if r.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() { - self.drafts.insert(bot.id, words); - ui.memory_mut(|m| m.request_focus(egui::Id::unique(("composer", bot.id)))); + // The starters are shortcuts, not content: light capsules in a row (a hairline, no + // fill — in the bot's colour under 「跟著 Bot」), filled only under the pointer. + let (rest, edge) = if tinted { (crate::theme::mist(col, p), Stroke::NONE) } else { (Color32::TRANSPARENT, Stroke::new(1.0, p.border)) }; + ui.allocate_ui_with_layout(vec2(ui.available_width().min(560.0), 0.0), Layout::left_to_right(Align::Min).with_main_wrap(true), |ui| { + ui.spacing_mut().item_spacing = vec2(8.0, 8.0); + for words in EMPTY_STARTS { + let words = t(words); + let galley = ui.painter().layout_no_wrap(words.clone(), egui::FontId::proportional(FONT_BASE), p.text); + let (rect, r) = ui.allocate_exact_size(vec2(galley.size().x + 32.0, 36.0), egui::Sense::click()); + let fill = if r.hovered() { if tinted { rest.lerp_to_gamma(p.text, 0.06) } else { p.hover } } else { rest }; + ui.painter().rect(rect, R_FULL, fill, edge, egui::StrokeKind::Inside); + ui.painter().galley(rect.center() - galley.size() / 2.0, galley, p.text); + if r.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() { + self.drafts.insert(bot.id, words); + ui.memory_mut(|m| m.request_focus(egui::Id::unique(("composer", bot.id)))); + } } - ui.add_space(8.0); - } - ui.add_space(6.0); + }); + ui.add_space(14.0); { let runs = providers::runs_at(bot.provider, &providers::resolve_base(bot.provider, &self.state.provider(bot.provider).base_url)); ui.label(RichText::new(format!("{} · {} · {}", bot.provider.label(), bot.model, t(runs.short()))).size(FONT_XS).color(p.text3)).on_hover_text(runs.words(self.brain_for_words().as_deref())); @@ -4487,14 +4507,21 @@ impl App { if !providers::ready(bot.provider, &ps.api_key) { ui.add_space(10.0); let words = if bot.provider == ProviderKind::ChatGpt { t("用 ChatGPT 登入") } else { format!("設定 {} 的 API 金鑰", bot.provider.label()) }; - if ui.button(words).clicked() { + if ui.add(egui::Button::new(words).corner_radius(R_FULL)).clicked() { self.show_settings = true; self.settings_tab = SettingsTab::Providers; self.settings_provider = bot.provider; + self.settings_provider_open = true; } } } + /// Whether a card offers 「之後都直接操作,不再一個個問」: direct mode is off, and the + /// managed settings let the person turn it (and this computer) on. + fn offers_direct(&self) -> bool { + !self.direct_on() && self.managed.direct.allows() && self.managed.local.allows() + } + /// "The bot wants to …": allow once, always allow this kind, or say no. /// The question, the details and the buttons, shared by the chat card and the pop-up. fn approval_body(&self, ui: &mut egui::Ui, bot: &Bot, big: bool) -> Option<ApprovalAnswer> { @@ -4548,13 +4575,13 @@ impl App { ui.spacing_mut().button_padding = vec2(14.0, 7.0); let scope_on = kind == ApprovalKind::Action && !grant.is_empty() && self.smart_flag.load(Ordering::Relaxed); let main = |label: &str, ui: &mut egui::Ui| { - ui.add(egui::Button::new(RichText::new(t(label)).strong().family(crate::bold()).color(p.on_primary)).fill(p.primary).corner_radius(R_M).min_size(vec2(0.0, if big { 34.0 } else { 0.0 }))) + ui.add(egui::Button::new(RichText::new(t(label)).strong().family(crate::bold()).color(p.on_primary)).fill(p.primary).corner_radius(R_FULL).min_size(vec2(0.0, if big { 34.0 } else { 0.0 }))) }; if scope_on { if main("這輪都准", ui).on_hover_text(format!("這一輪之內{}這類操作都不再問你;下一輪會再問。(智慧模式)", grant_label(&grant))).clicked() { answer = Some(ApprovalAnswer::Scope(grant.clone())); } - if ui.button(t("允許一次")).clicked() { + if ui.add(egui::Button::new(t("允許一次")).corner_radius(R_FULL)).clicked() { answer = Some(ApprovalAnswer::Once); } } else if main("允許一次", ui).clicked() { @@ -4567,11 +4594,11 @@ impl App { ApprovalKind::Action | ApprovalKind::Handoff | ApprovalKind::Question => None, }; if let Some((label, why)) = always { - if ui.button(t(&label)).on_hover_text(t(&why)).clicked() { + if ui.add(egui::Button::new(t(&label)).corner_radius(R_FULL)).on_hover_text(t(&why)).clicked() { answer = Some(ApprovalAnswer::Always(grant.clone())); } } - if ui.button(t("拒絕")).clicked() { + if ui.add(egui::Button::new(t("拒絕")).corner_radius(R_FULL)).clicked() { answer = Some(ApprovalAnswer::Reject); } }); @@ -4583,7 +4610,7 @@ impl App { .color(p.text3)); } // One click to work like the reference assistant: allow this and stop asking from now on. - if !self.direct_on() && self.managed.direct.allows() && self.managed.local.allows() { + if self.offers_direct() { ui.add_space(8.0); // (A way out of asking, offered quietly: grey, not a second call to action.) let b = crate::icons::label(ui, crate::icons::Icon::Zap, &t("之後都直接操作,不再一個個問"), FONT_SM, p.text2).interact(egui::Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand); @@ -4632,7 +4659,9 @@ impl App { let reason = self.approvals.get(&bot.id).map(|a| a.reason.clone()).unwrap_or_default(); // (And within what the chat column has left for it: room, less the card's edges and the space after.) let cap = (ui.ctx().content_rect().height() * 0.45).max(160.0).min(room - 48.0).max(72.0); - let body = ask_dock_height(&reason, ui.available_width(), cap); + // (Plus the line 「之後都直接操作」 when the card offers it: left out, the card's last line + // was cut off at the bottom.) + let body = (ask_dock_height(&reason, ui.available_width(), f32::INFINITY) + if self.offers_direct() { ASK_DIRECT_ROW } else { 0.0 }).min(cap); needs_you_card(ui, p, |ui| { ui.set_width(ui.available_width()); egui::ScrollArea::vertical().id_salt(("ask-dock", bot.id)).max_height(body).min_scrolled_height(body).auto_shrink([false, false]).show(ui, |ui| { @@ -4811,13 +4840,13 @@ impl App { ui.spacing_mut().button_padding = vec2(14.0, 7.0); let go = if last { t("送出") } else { t("下一題") }; let (fill, ink) = if ready { (p.primary, p.on_primary) } else { (p.active, p.text3) }; - if ui.add_enabled(ready, egui::Button::new(RichText::new(go).strong().family(crate::bold()).color(ink)).fill(fill).corner_radius(R_M).min_size(vec2(0.0, 34.0))).clicked() { + if ui.add_enabled(ready, egui::Button::new(RichText::new(go).strong().family(crate::bold()).color(ink)).fill(fill).corner_radius(R_FULL).min_size(vec2(0.0, 34.0))).clicked() { act = Some(Act::Next); } - if step > 0 && ui.button(t("上一題")).clicked() { + if step > 0 && ui.add(egui::Button::new(t("上一題")).corner_radius(R_FULL)).clicked() { act = Some(Act::Back); } - if ui.button(t("略過")).on_hover_text(t("不回答這張卡片。也可以直接在下面打字跟它說。")).clicked() { + if ui.add(egui::Button::new(t("略過")).corner_radius(R_FULL)).on_hover_text(t("不回答這張卡片。也可以直接在下面打字跟它說。")).clicked() { act = Some(Act::Skip); } }); @@ -4958,13 +4987,13 @@ impl App { } ui.add_space(10.0); ui.horizontal(|ui| { - if ui.button(t("跳過")).on_hover_text(t("取消此要求且不執行該步驟;Bot 會跳過它並繼續")).clicked() { + if ui.add(egui::Button::new(t("跳過")).corner_radius(R_FULL)).on_hover_text(t("取消此要求且不執行該步驟;Bot 會跳過它並繼續")).clicked() { act = Some(Act::Skip); } - if ui.button(t("我完成了")).clicked() { + if ui.add(egui::Button::new(t("我完成了")).corner_radius(R_FULL)).clicked() { act = Some(Act::Done); } - if shows && ui.add(egui::Button::new(RichText::new(t("接管")).color(p.on_primary)).fill(p.primary).corner_radius(R_M)).clicked() { + if shows && ui.add(egui::Button::new(RichText::new(t("接管")).color(p.on_primary)).fill(p.primary).corner_radius(R_FULL)).clicked() { act = Some(Act::TakeOver); } }); @@ -5262,11 +5291,14 @@ impl App { self.face_dock(ui, bot); // What is left for the box: past it, the words scroll inside it. let box_room = cap - (ui.cursor().top() - composer_top) - below - 16.0; - // The input: one box with an ink edge — +, the words, the mic, and a button in the - // bot's colour (voice chat while empty, send ↑ once there is something to send). + // The input: one box floating over the chat — lifted by a soft shadow with a hairline + // edge that darkens while you type (as on the phone) — +, the words, the mic, and a + // round button in the bot's colour (voice chat while empty, send ↑ once there is + // something to send). let input = Frame::new() .fill(p.elevated) - .stroke(Stroke::new(1.5, if had_focus { p.text } else { p.text.gamma_multiply(0.45) })) + .stroke(Stroke::new(1.0, if had_focus { p.text.gamma_multiply(0.4) } else { p.border })) + .shadow(kit::lift(p)) .corner_radius(R_L) .inner_margin(Margin { left: 8, right: 8, top: 8, bottom: 8 }) .show(ui, |ui| { @@ -5998,6 +6030,7 @@ impl App { self.show_settings = true; self.settings_tab = SettingsTab::Providers; self.settings_provider = b.provider; + self.settings_provider_open = true; } }); } @@ -6288,29 +6321,34 @@ impl App { } } else { use crate::icons::Icon; - for (tab, name, icon) in [(SettingsTab::General, "一般", Icon::Gear), (SettingsTab::Me, "個人資料", Icon::Person), (SettingsTab::Providers, "模型", Icon::Sparkle), (SettingsTab::Channels, "整合", Icon::Chat), (SettingsTab::Computers, "電腦", Icon::Monitor), (SettingsTab::Review, "權限", Icon::Shield), (SettingsTab::Vault, "保險庫", Icon::Vault), (SettingsTab::Voice, "語音", Icon::Mic), (SettingsTab::Updates, "更新", Icon::CloudDownload)] { + for (tab, name, icon) in [(SettingsTab::General, "一般", Icon::Gear), (SettingsTab::Me, "個人資料", Icon::Person), (SettingsTab::Providers, "模型", Icon::Sparkle), (SettingsTab::Channels, "整合", Icon::Apps), (SettingsTab::Computers, "電腦", Icon::Monitor), (SettingsTab::Review, "權限", Icon::Shield), (SettingsTab::Vault, "保險庫", Icon::Vault), (SettingsTab::Voice, "語音", Icon::Mic), (SettingsTab::Updates, "更新", Icon::CloudDownload)] { let (rect, r) = ui.allocate_exact_size(vec2(ui.available_width(), 38.0), egui::Sense::click()); let on = self.settings_tab == tab || (tab == SettingsTab::General && self.settings_tab == SettingsTab::Remote); if on || r.hovered() { ui.painter().rect_filled(rect, R_M, if on { p.active } else { p.hover }); } let col = if on { p.text } else { p.text2 }; - let _ = icon; + // A picture before each name (as OpenBot and System Settings do): the eye + // finds 權限 by its shield before it reads the word. + crate::icons::paint(ui.painter(), egui::Rect::from_center_size(rect.left_center() + vec2(20.0, 0.0), vec2(16.0, 16.0)), icon, if on { p.text } else { p.text3 }); let font = if on { egui::FontId::new(FONT_BASE, crate::bold()) } else { egui::FontId::proportional(FONT_BASE) }; - ui.painter().text(rect.left_center() + vec2(12.0, 0.0), egui::Align2::LEFT_CENTER, t(name), font, col); + ui.painter().text(rect.left_center() + vec2(36.0, 0.0), egui::Align2::LEFT_CENTER, t(name), font, col); // 更新: a newer build is waiting (the yellow that means 「需要你」). if tab == SettingsTab::Updates && self.newer_build.is_some() && rect.width() > 110.0 { ui.painter().circle_filled(rect.right_center() - vec2(14.0, 0.0), 5.0, p.attention); } if r.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() { + // (模型 opens on its tiles, not the last service looked at.) + if tab == SettingsTab::Providers { + self.settings_provider_open = false; + } self.settings_tab = tab; } } } }); }); - let r = ui.min_rect(); - ui.painter().vline(r.right(), r.y_range(), Stroke::new(1.0, p.border)); + // (No line between the list and the page: the list's own tint already parts them.) ui.vertical(|ui| { ui.spacing_mut().item_spacing = vec2(8.0, 6.0); // On a screen of a brain: whose settings this page is — this computer's, the @@ -6324,6 +6362,12 @@ impl App { SettingsTab::General => { // One thing a row, in plain words; what needs explaining is behind the ?. section(ui, "外觀", p); + // 風格: a whole look in one press — a little picture of each. + if let Some(id) = self.style_gallery(ui) { + self.state.shell_template = id.to_string(); + self.dirty = true; + } + ui.add_space(crate::theme::sp::S2); rows_card(ui, p, |ui| { card_row(ui, p, "主題", "", "", |ui| { if let Some(th) = segmented(ui, p, self.state.theme, &[(Theme::Light, "淺色"), (Theme::Dark, "深色"), (Theme::System, "跟著系統")]) { @@ -6337,11 +6381,13 @@ impl App { let (rect, r) = ui.allocate_exact_size(vec2(26.0, 26.0), egui::Sense::click()); let c = rect.center(); ui.painter().circle_filled(c, 10.0, if darkish { darkv } else { light }); - if self.state.shell_accent == name { + if self.state.shell_accent == name && self.state.shell_template.is_empty() { ui.painter().circle_stroke(c, 13.0, Stroke::new(2.0, p.text)); } - if r.on_hover_text(t(label)).on_hover_cursor(egui::CursorIcon::PointingHand).clicked() && self.state.shell_accent != name { + if r.on_hover_text(t(label)).on_hover_cursor(egui::CursorIcon::PointingHand).clicked() && (self.state.shell_accent != name || !self.state.shell_template.is_empty()) { + // (A colour of one's own: the 風格 goes back to 自訂.) self.state.shell_accent = name.to_string(); + self.state.shell_template.clear(); self.dirty = true; } } @@ -6411,6 +6457,7 @@ impl App { let before = self.state.shell_tone; ui.add(egui::Slider::new(&mut self.state.shell_tone, 0.0..=1.0).show_value(false).text(" ")); if self.state.shell_tone != before { + self.state.shell_template.clear(); self.dirty = true; } }); @@ -6442,10 +6489,11 @@ impl App { } }); card_row(ui, p, "外殼顏色重設", "", "底色、強調色、對比回到預設(紙)。", |ui| { - if ui.button(t("重設")).clicked() { + if ui.add(egui::Button::new(t("重設")).corner_radius(R_FULL)).clicked() { self.state.shell_tone = 1.0; self.state.shell_accent = "clay".into(); self.state.shell_contrast = 1.0; + self.state.shell_template.clear(); self.dirty = true; } }); @@ -6758,41 +6806,29 @@ impl App { }); } } + SettingsTab::Providers if !self.settings_provider_open => { + // All the services as tiles (a mark, the name, ready or not, where it + // runs) — one column of pages, not a list beside the page beside the + // settings list. A press opens that one. + if let Some(k) = self.provider_grid(ui) { + self.settings_provider = k; + self.settings_provider_open = true; + } + } SettingsTab::Providers => { - ui.horizontal_top(|ui| { - ui.vertical(|ui| { - ui.set_width(PROVIDER_LIST_WIDTH); - ui.spacing_mut().item_spacing.y = 2.0; - for k in ALL_PROVIDERS { - let ps = self.state.provider(k); - let ready = providers::ready(k, &ps.api_key); - let (rect, r) = ui.allocate_exact_size(vec2(PROVIDER_LIST_WIDTH, 32.0), egui::Sense::click()); - let on = self.settings_provider == k; - if on || r.hovered() { - ui.painter().rect_filled(rect, R_M, if on { p.active } else { p.hover }); - } - let dot = rect.left_center() + vec2(14.0, 0.0); - // Only the ready ones get a mark (a green dot); an empty ring before - // every other one read as a radio button to pick. - if ready { - ui.painter().circle_filled(dot, 4.0, p.up); - } - ui.painter().text(rect.left_center() + vec2(28.0, 0.0), egui::Align2::LEFT_CENTER, k.label(), egui::FontId::proportional(FONT_BASE), if on { p.text } else { p.text2 }); - // Where it runs, at a glance: the ones that keep the chats home in green. - let runs = providers::runs_at(k, &providers::resolve_base(k, &ps.base_url)); - let tag = if matches!(runs, providers::RunsAt::Cloud(_)) { p.text3 } else { p.up }; - ui.painter().text(rect.right_center() - vec2(10.0, 0.0), egui::Align2::RIGHT_CENTER, t(runs.short()), egui::FontId::proportional(FONT_XS), tag); - let tip = t(if ready { "已可使用" } else if k == ProviderKind::ChatGpt { "還沒用 ChatGPT 登入" } else { "還沒設定金鑰" }); - if r.on_hover_text(format!("{tip}\n{}", runs.words(self.brain_for_words().as_deref()))).clicked() { - self.settings_provider = k; - } - } - }); - ui.add_space(16.0); + { + if back_link(ui, "模型", p) { + self.settings_provider_open = false; + } + ui.add_space(4.0); ui.vertical(|ui| { let k = self.settings_provider; let w = ui.available_width(); - ui.label(RichText::new(k.label()).strong().family(crate::bold()).size(FONT_H3)); + ui.horizontal(|ui| { + let (m, _) = ui.allocate_exact_size(vec2(32.0, 32.0), egui::Sense::hover()); + crate::icons::provider_mark(ui.painter(), m, k, R_M); + ui.label(RichText::new(k.label()).strong().family(crate::bold()).size(FONT_H3)); + }); { let runs = providers::runs_at(k, &providers::resolve_base(k, &self.state.provider(k).base_url)); runs_line(ui, &runs, self.brain_for_words().as_deref(), p); @@ -6841,7 +6877,7 @@ impl App { hint(ui, format!("已記住 {count} 個模型"), p); } }); - }); + } } } }); @@ -8413,6 +8449,62 @@ fn ask_dock_height(reason: &str, width: f32, cap: f32) -> f32 { (wrapped_lines(detail, (width - 92.0).max(120.0), cw) * 17.0 + 168.0).min(cap) } +/// The chat's backdrop of a 風格: dots, a grid or waves in the grid colour; "" draws nothing. +fn chat_backdrop(painter: &egui::Painter, rect: egui::Rect, kind: &str, p: Palette) { + let painter = painter.with_clip_rect(rect); + match kind { + "dots" => { + let step = 22.0; + let mut y = rect.top() + step / 2.0; + while y < rect.bottom() { + let mut x = rect.left() + step / 2.0; + while x < rect.right() { + painter.circle_filled(egui::pos2(x, y), 1.3, p.grid); + x += step; + } + y += step; + } + } + "grid" => { + let step = 24.0; + let line = Stroke::new(1.0, p.grid); + let mut x = rect.left(); + while x < rect.right() { + painter.vline(x, rect.y_range(), line); + x += step; + } + let mut y = rect.top(); + while y < rect.bottom() { + painter.hline(rect.x_range(), y, line); + y += step; + } + } + "waves" => { + // Rows of shallow arcs (scallops), like the phone's. + let (w, h) = (32.0, 16.0); + let line = Stroke::new(1.0, p.grid); + let mut y = rect.top() + h; + while y < rect.bottom() + h { + let mut x = rect.left(); + while x < rect.right() + w { + let pts: Vec<egui::Pos2> = (0..=8).map(|i| { + let a = std::f32::consts::PI * (i as f32 / 8.0); + egui::pos2(x + w / 2.0 - a.cos() * (w / 2.0 - 2.0), y - a.sin() * (h - 2.0)) + }).collect(); + painter.add(egui::Shape::line(pts, line)); + x += w; + } + y += h; + } + } + _ => {} + } +} + +/// What the card's 「之後都直接操作」 line adds past `ask_dock_height`'s guess (measured: the +/// guess already leaves a little room under the last line). +const ASK_DIRECT_ROW: f32 = 14.0; + /// Under the words in the composer before it has been measured: the frame's bottom (8 + its /// edge), and the line and space under the box (see composer). const COMPOSER_BELOW: f32 = 8.0 + 1.5 + 4.0 + 20.0 + 10.0; @@ -8454,14 +8546,14 @@ const EMPTY_STARTS: [&str; 3] = ["幫我規劃這個週末的行程", "把這段 fn round_tool(ui: &mut egui::Ui, icon: crate::icons::Icon, fill: Color32, ink: Color32) -> egui::Response { let (rect, r) = ui.allocate_exact_size(vec2(28.0, 28.0), egui::Sense::click()); let f = if r.hovered() { fill.gamma_multiply(0.82).to_opaque().lerp_to_gamma(fill, 0.3) } else { fill }; - ui.painter().rect_filled(rect, R_M, f); + ui.painter().rect_filled(rect, R_FULL, f); crate::icons::paint(ui.painter(), egui::Rect::from_center_size(rect.center(), vec2(15.0, 15.0)), icon, ink); r.on_hover_cursor(egui::CursorIcon::PointingHand) } /// A 36 px rounded button with a hairline border (the original's 分享 / ⋯). fn pill_text(ui: &mut egui::Ui, text: &str, p: Palette) -> egui::Response { - ui.add(egui::Button::new(RichText::new(text).size(FONT_BASE).color(p.text)).fill(Color32::TRANSPARENT).stroke(Stroke::NONE).corner_radius(R_M).min_size(vec2(0.0, 36.0))) + ui.add(egui::Button::new(RichText::new(text).size(FONT_BASE).color(p.text)).fill(Color32::TRANSPARENT).stroke(Stroke::NONE).corner_radius(R_FULL).min_size(vec2(0.0, 36.0))) } fn pill_icon(ui: &mut egui::Ui, icon: crate::icons::Icon, p: Palette) -> egui::Response { diff --git a/src/app/chat_ui.rs b/src/app/chat_ui.rs index b3a310b..52d0e1d 100644 --- a/src/app/chat_ui.rs +++ b/src/app/chat_ui.rs @@ -571,7 +571,7 @@ impl App { ui.label(RichText::new(&m.text).size(FONT_SM).color(p.text2)); if can_go_on { ui.add_space(6.0); - go_on = ui.button(RichText::new(t("繼續")).size(FONT_SM)).clicked(); + go_on = ui.add(egui::Button::new(RichText::new(t("繼續")).size(FONT_SM)).corner_radius(R_FULL)).clicked(); } }); ui.add_space(10.0); diff --git a/src/app/computers_ui.rs b/src/app/computers_ui.rs index 34cb407..5568724 100644 --- a/src/app/computers_ui.rs +++ b/src/app/computers_ui.rs @@ -288,7 +288,7 @@ impl App { for c in &ssh { let mut remove = false; sec_row_s(ui, p, &c.name, &format!("SSH · {}", c.ssh_target), "", |ui| { - if ui.add(egui::Button::new(RichText::new(t("移除")).color(p.danger)).corner_radius(R_M)).on_hover_text(format!("{} {}", t("移除"), c.name)).clicked() { + if ui.add(danger_text_button("移除", p)).on_hover_text(format!("{} {}", t("移除"), c.name)).clicked() { remove = true; } }); @@ -468,7 +468,7 @@ impl App { // 更新 Bot 的電腦: two clicks (the first arms it for 3 s). sec_row(ui, p, "更新 Bot 的電腦", "更新你的 Bot 共用的電腦。你的檔案和登入資訊會保留,但已安裝的應用程式和套件會被移除。所有 Bot 會一起更新。", |ui| { let b = if armed { - egui::Button::new(RichText::new(t("再點選一次以確認")).color(p.danger)).fill(p.danger.gamma_multiply(0.14)).corner_radius(R_M).min_size(vec2(64.0, 30.0)) + danger_text_button("再點選一次以確認", p).fill(p.danger.gamma_multiply(0.14)) } else { secondary_button("更新") }; diff --git a/src/app/drops_ui.rs b/src/app/drops_ui.rs index b62d79a..bcf9442 100644 --- a/src/app/drops_ui.rs +++ b/src/app/drops_ui.rs @@ -285,7 +285,7 @@ impl App { crate::icons::paint(ui.painter(), egui::Rect::from_center_size(rect.center_top() + vec2(0.0, 26.0), vec2(20.0, 20.0)), crate::icons::Icon::Upload, if hovering { p.accent } else { p.text3 }); ui.painter().text(rect.center_top() + vec2(0.0, 50.0), egui::Align2::CENTER_CENTER, t(if hovering { "放開就傳送" } else { "把檔案拖到這裡" }), egui::FontId::proportional(FONT_BASE), p.text2); let btn = egui::Rect::from_center_size(rect.center_top() + vec2(0.0, 78.0), vec2(96.0, 26.0)); - if ui.put(btn, egui::Button::new(RichText::new(t("選擇檔案…")).size(FONT_SM)).corner_radius(R_M)).clicked() { + if ui.put(btn, egui::Button::new(RichText::new(t("選擇檔案…")).size(FONT_SM)).corner_radius(R_FULL)).clicked() { if pg.to.is_empty() { pg.note = t("先選要傳到哪一台"); } else { diff --git a/src/app/kit.rs b/src/app/kit.rs index a9c3c7b..b2e2759 100644 --- a/src/app/kit.rs +++ b/src/app/kit.rs @@ -114,7 +114,9 @@ pub(super) fn card_row(ui: &mut egui::Ui, p: Palette, label: &str, sub: &str, he let mut right = ui.new_child(egui::UiBuilder::new().max_rect(rect).layout(Layout::right_to_left(Align::Center))); right.spacing_mut().item_spacing.x = 8.0; control(&mut right); - let words = egui::Rect::from_min_max(rect.min, egui::pos2((right.min_rect().left() - 12.0).max(rect.left() + 80.0), rect.bottom())); + // Every setting has its picture before its name (crate::icons::setting_icon). + crate::icons::paint(ui.painter(), egui::Rect::from_center_size(egui::pos2(rect.left() + 9.0, rect.center().y), vec2(17.0, 17.0)), crate::icons::setting_icon(label), p.text2); + let words = egui::Rect::from_min_max(egui::pos2(rect.left() + 28.0, rect.top()), egui::pos2((right.min_rect().left() - 12.0).max(rect.left() + 108.0), rect.bottom())); if sub.is_empty() { let mut left = ui.new_child(egui::UiBuilder::new().max_rect(words).layout(Layout::left_to_right(Align::Center))); left.spacing_mut().item_spacing.x = 4.0; @@ -135,7 +137,7 @@ pub(super) fn card_row(ui: &mut egui::Ui, p: Palette, label: &str, sub: &str, he /// A choice among a few: the one chosen is the raised, bold one. Returns a new choice. pub(super) fn segmented<T: PartialEq + Copy>(ui: &mut egui::Ui, p: Palette, cur: T, options: &[(T, &str)]) -> Option<T> { let mut picked = None; - Frame::new().fill(p.active).corner_radius(R_M).inner_margin(Margin::same(3)).show(ui, |ui| { + Frame::new().fill(p.active).corner_radius(R_FULL).inner_margin(Margin::same(3)).show(ui, |ui| { ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 2.0; // (In a row laid out from the right, the first choice is still the left one.) @@ -145,7 +147,7 @@ pub(super) fn segmented<T: PartialEq + Copy>(ui: &mut egui::Ui, p: Palette, cur: let on = *v == cur; let text = RichText::new(t(label)).size(FONT_SM).color(if on { p.text } else { p.text2 }); let text = if on { text.family(crate::bold()) } else { text }; - if ui.add(egui::Button::new(text).fill(if on { p.elevated } else { Color32::TRANSPARENT }).stroke(Stroke::NONE).corner_radius(R_M).min_size(vec2(0.0, 26.0))).clicked() && !on { + if ui.add(egui::Button::new(text).fill(if on { p.elevated } else { Color32::TRANSPARENT }).stroke(Stroke::NONE).corner_radius(R_FULL).min_size(vec2(0.0, 26.0))).clicked() && !on { picked = Some(*v); } } @@ -157,6 +159,9 @@ pub(super) fn segmented<T: PartialEq + Copy>(ui: &mut egui::Ui, p: Palette, cur: pub(super) fn setting_title(ui: &mut egui::Ui, title: &str, desc: &str, p: Palette) { let r = ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 4.0; + // (Its picture, as every setting row has one.) + let (pic, _) = ui.allocate_exact_size(vec2(22.0, 18.0), egui::Sense::hover()); + crate::icons::paint(ui.painter(), egui::Rect::from_center_size(pic.left_center() + vec2(8.0, 0.0), vec2(16.0, 16.0)), crate::icons::setting_icon(title), p.text2); ui.label(RichText::new(t(title)).strong().family(crate::bold()).size(FONT_BASE)); help_mark(ui, desc, p); }); @@ -194,21 +199,6 @@ pub(super) fn settings_side_line(ui: &mut egui::Ui, tag: &str, words: &str, p: P ui.add_space(6.0); } -/// A figure on its own card (個人資料): what it is, the number, a line under it — `w` wide. -pub(super) fn stat_card(ui: &mut egui::Ui, p: Palette, w: f32, label: &str, value: &str, sub: &str) { - Frame::new().fill(p.elevated).stroke(Stroke::new(1.0, p.border)).corner_radius(R_L).inner_margin(egui::Margin::symmetric(14, 12)).show(ui, |ui| { - // (The 14 px margins and the 1 px border on each side.) - ui.set_width(w - 30.0); - // (Stacked: a row of cards lays things side by side.) - ui.vertical(|ui| { - ui.spacing_mut().item_spacing.y = 4.0; - ui.label(RichText::new(label).size(FONT_SM).color(p.text2)); - ui.label(RichText::new(value).size(FONT_H1).strong().family(crate::bold()).color(p.text)); - ui.add(egui::Label::new(RichText::new(sub).size(FONT_XS).color(p.text3)).truncate()); - }); - }); -} - /// A rounded group of related settings, like a macOS settings card. pub(super) fn setting_card<R>(ui: &mut egui::Ui, p: Palette, body: impl FnOnce(&mut egui::Ui) -> R) -> R { let r = Frame::new() @@ -300,9 +290,15 @@ pub(super) fn fold_title(ui: &mut egui::Ui, p: Palette, id: impl std::hash::Hash } /// Something floating over a canvas (工作流: the toolbar, the zoom, the settings at the right, -/// the 等你確認 bar): the raised fill, a thin edge, large corners. +/// the 等你確認 bar): the raised fill, a thin edge, large corners, and the soft shadow that +/// says it floats (the same lift as the chat's input). pub(super) fn floating<R>(ui: &mut egui::Ui, p: Palette, edge: Color32, margin: Margin, body: impl FnOnce(&mut egui::Ui) -> R) -> egui::InnerResponse<R> { - Frame::new().fill(p.elevated).stroke(Stroke::new(1.0, edge)).corner_radius(R_L).inner_margin(margin).show(ui, body) + Frame::new().fill(p.elevated).stroke(Stroke::new(1.0, edge)).shadow(lift(p)).corner_radius(R_L).inner_margin(margin).show(ui, body) +} + +/// The shadow under what floats over the page: one soft lift for all of it. +pub(super) fn lift(p: Palette) -> egui::epaint::Shadow { + egui::epaint::Shadow { offset: [0, 2], blur: 14, spread: 0, color: p.shade } } /// The card of something waiting for you — an approval, a question, a step handed to you on a @@ -382,16 +378,27 @@ pub(super) fn field_label(ui: &mut egui::Ui, text: &str, p: Palette) { ui.add_space(sp::S1 * 0.5); } +// Buttons are capsules (as on the phone, and as macOS 26 draws them): the shape alone says +// "press me", so a button never needs a border. One filled button per place — the thing to +// do; the rest are quiet. + pub(super) fn primary_button(text: &str, p: Palette) -> egui::Button<'static> { - egui::Button::new(RichText::new(t(text)).color(p.on_primary).strong().family(crate::bold())).fill(p.primary).corner_radius(R_M).min_size(vec2(72.0, 30.0)) + egui::Button::new(RichText::new(t(text)).color(p.on_primary).strong().family(crate::bold())).fill(p.primary).corner_radius(R_FULL).min_size(vec2(72.0, 30.0)) } pub(super) fn secondary_button(text: &str) -> egui::Button<'static> { - egui::Button::new(t(text)).corner_radius(R_M).min_size(vec2(64.0, 30.0)) + egui::Button::new(t(text)).corner_radius(R_FULL).min_size(vec2(64.0, 30.0)) } +/// Filled red: only where pressing it destroys something and that is the point of the place. pub(super) fn danger_button(text: &str, p: Palette) -> egui::Button<'static> { - egui::Button::new(RichText::new(t(text)).color(Color32::WHITE).strong().family(crate::bold())).fill(p.danger).corner_radius(R_M).min_size(vec2(72.0, 30.0)) + egui::Button::new(RichText::new(t(text)).color(Color32::WHITE).strong().family(crate::bold())).fill(p.danger).corner_radius(R_FULL).min_size(vec2(72.0, 30.0)) +} + +/// A quiet button in red words (停止, 移除, 登出): it can undo something, but it is not what +/// the place is for, so it does not shout. +pub(super) fn danger_text_button(text: &str, p: Palette) -> egui::Button<'static> { + egui::Button::new(RichText::new(t(text)).color(p.danger)).corner_radius(R_FULL).min_size(vec2(64.0, 30.0)) } /// The bottom bar of a dialog: a line above, buttons laid out right to left. @@ -404,3 +411,60 @@ pub(super) fn dialog_footer(ui: &mut egui::Ui, p: Palette, body: impl FnOnce(&mu ui.horizontal(|ui| body(ui)); }); } + +impl App { + /// 設定 › 一般 › 外觀 › 風格: each template as a little picture of the app in its colours + /// (the sidebar, a line of words, your bubble, the accent, its backdrop) with its name; the + /// one worn has a ring. Returns the one pressed. The last card is 自訂 (the dials below). + pub(super) fn style_gallery(&mut self, ui: &mut egui::Ui) -> Option<&'static str> { + let p = self.pal; + let dark = is_dark(p); + let mut picked = None; + let width = ui.available_width(); + let gap = 10.0; + let cols = if width >= 560.0 { 4 } else { 3 }; + let w = ((width - gap * (cols as f32 - 1.0)) / cols as f32).floor(); + let h = (w * 0.62).round(); + for row in crate::theme::TEMPLATES.chunks(cols) { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = gap; + for t in row { + let tp = crate::theme::palette_for(t.id, 1.0, "clay", self.state.shell_contrast, dark); + let (rect, r) = ui.allocate_exact_size(vec2(w, h + 22.0), egui::Sense::click()); + let pic = egui::Rect::from_min_size(rect.min, vec2(w, h)); + let paint = ui.painter(); + paint.rect(pic, R_M, tp.pane, Stroke::new(1.0, tp.border), egui::StrokeKind::Inside); + // The backdrop, faintly. + super::chat_backdrop(paint, pic.shrink(2.0), t.backdrop, tp); + let side = egui::Rect::from_min_max(pic.min, egui::pos2(pic.left() + w * 0.26, pic.bottom())); + paint.rect_filled(side.shrink(1.0), CornerRadius { nw: R_M - 1, sw: R_M - 1, ..Default::default() }, tp.sidebar); + for i in 0..3 { + let y = side.top() + 10.0 + i as f32 * 9.0; + paint.rect_filled(egui::Rect::from_min_size(egui::pos2(side.left() + 7.0, y), vec2(side.width() - 14.0, 4.0)), R_FULL, if i == 0 { tp.active } else { tp.hover }); + } + let body = egui::Rect::from_min_max(egui::pos2(side.right() + 8.0, pic.top() + 10.0), pic.max - vec2(8.0, 8.0)); + paint.rect_filled(egui::Rect::from_min_size(body.min, vec2(body.width() * 0.8, 4.0)), R_FULL, tp.text3); + paint.rect_filled(egui::Rect::from_min_size(body.min + vec2(0.0, 9.0), vec2(body.width() * 0.6, 4.0)), R_FULL, tp.text3); + let bubble = egui::Rect::from_min_size(egui::pos2(body.right() - body.width() * 0.5, body.top() + 20.0), vec2(body.width() * 0.5, 11.0)); + paint.rect_filled(bubble, R_FULL, tp.bubble_user); + paint.circle_filled(egui::pos2(body.right() - 6.0, body.bottom() - 6.0), 5.0, tp.accent); + let on = self.state.shell_template == t.id; + if on { + paint.rect_stroke(pic.expand(2.0), R_M + 2, Stroke::new(2.0, p.accent), egui::StrokeKind::Outside); + } else if r.hovered() { + paint.rect_stroke(pic.expand(1.0), R_M + 1, Stroke::new(1.0, p.text3), egui::StrokeKind::Outside); + } + paint.text(egui::pos2(pic.center().x, pic.bottom() + 5.0), egui::Align2::CENTER_TOP, t.name, if on { egui::FontId::new(FONT_SM, crate::bold()) } else { egui::FontId::proportional(FONT_SM) }, if on { p.text } else { p.text2 }); + if r.on_hover_text(t.about).on_hover_cursor(egui::CursorIcon::PointingHand).clicked() && !on { + picked = Some(t.id); + } + } + }); + ui.add_space(gap); + } + if self.state.shell_template.is_empty() { + ui.label(RichText::new(t("現在是自訂的顏色(下面的強調色和更多外觀設定);點一個風格整套換。")).size(FONT_XS).color(p.text3)); + } + picked + } +} diff --git a/src/app/library_ui.rs b/src/app/library_ui.rs index 2bcc1e5..f5be264 100644 --- a/src/app/library_ui.rs +++ b/src/app/library_ui.rs @@ -60,6 +60,24 @@ pub(super) fn library_kind(name: &str) -> &'static str { } impl App { + /// 所有檔案 for the phone: the same files, newest first (at most 500). + pub(super) fn library_json(&self) -> serde_json::Value { + let mut seen = std::collections::HashSet::new(); + let mut files = vec![]; + for b in &self.state.bots { + for m in b.messages.iter().chain(b.threads.iter().flat_map(|(_, m)| m.iter())) { + for a in &m.attachments { + if a.path.is_empty() || !seen.insert(a.path.clone()) { + continue; + } + files.push((m.at, serde_json::json!({"name": a.name, "path": a.path, "bot": b.id, "at": m.at, "bytes": a.bytes, "kind": library_kind(&a.name), "there": std::path::Path::new(&a.path).exists(), "image": a.image}))); + } + } + } + files.sort_by_key(|f| std::cmp::Reverse(f.0)); + serde_json::json!({"ok": true, "files": files.into_iter().take(500).map(|f| f.1).collect::<Vec<_>>()}) + } + fn library_gather(&mut self) { let mut seen = std::collections::HashSet::new(); let mut files = vec![]; diff --git a/src/app/me_ui.rs b/src/app/me_ui.rs index d3a78c2..3a5d84b 100644 --- a/src/app/me_ui.rs +++ b/src/app/me_ui.rs @@ -14,6 +14,16 @@ pub(super) struct MeUi { error: Option<String>, /// 用量's period: 7, 30, 90 or 365 days. span: u16, + /// 用量 split by bot instead of by model. + by_bot: bool, +} + +impl MeUi { + /// Sample figures for screenshots (ANYBOT_SHOT_TAB=me on the demo). + pub(super) fn demo_fill(&mut self) { + self.data = Some(demo_figures()); + self.at = Some(Instant::now()); + } } /// How long the figures stand before the page reads them again. @@ -101,7 +111,7 @@ impl App { } return; }; - self.me_cards(ui, &d); + self.me_figures(ui, &d); ui.add_space(18.0); self.me_heat(ui, &d); ui.add_space(18.0); @@ -111,31 +121,33 @@ impl App { } } - /// The five figures. - fn me_cards(&mut self, ui: &mut egui::Ui, d: &serde_json::Value) { + /// The year in four figures, in one quiet strip — big numbers, a small word under each, no + /// boxes (they were five bordered cards in two or three columns: a wall of text). What each + /// one means in full is in its hover. + fn me_figures(&mut self, ui: &mut egui::Ui, d: &serde_json::Value) { let p = self.pal; let g = |k: &str| d[k].as_u64().unwrap_or(0); let date = |k: &str| d[k].as_str().map(long_date).unwrap_or_default(); - let busiest = &d["busiest"]; - let cards: Vec<(String, String, String)> = vec![ - ("Token".into(), crate::stats::wan(g("tokens_year")), t("過去一年(不算快取命中)")), - (t("最活躍的一天"), if busiest.is_object() { crate::stats::wan(busiest["tokens"].as_u64().unwrap_or(0)) } else { "—".into() }, busiest["date"].as_str().map(long_date).unwrap_or_else(|| t("還沒有用量紀錄"))), - (t("訊息"), crate::stats::wan(g("messages_year")), t("過去一年")), - (t("目前連續天數"), format!("{} 天", g("streak_now")), d["streak_now_since"].as_str().map(|s| format!("自 {} 起", short_date(s))).unwrap_or_else(|| t("今天開始就算一天"))), - (t("最長連續天數"), format!("{} 天", g("streak_best")), if g("streak_best") > 0 { format!("{} – {}", date("streak_best_from"), date("streak_best_to")) } else { String::new() }), + let figures: Vec<(String, String, String)> = vec![ + (crate::stats::wan(g("tokens_year")), t("Token・一年"), t("過去一年用掉的 token(不算快取命中)")), + (crate::stats::wan(g("messages_year")), t("訊息・一年"), t("過去一年的訊息")), + (format!("{} 天", g("streak_now")), t("連續使用"), d["streak_now_since"].as_str().map(|s| format!("自 {} 起", short_date(s))).unwrap_or_else(|| t("今天開始就算一天"))), + (format!("{} 天", g("streak_best")), t("最長連續"), if g("streak_best") > 0 { format!("{} – {}", date("streak_best_from"), date("streak_best_to")) } else { String::new() }), ]; - let gap = 10.0; let width = ui.available_width(); - let cols = if width >= 640.0 { 3 } else { 2 }; - let w = ((width - gap * (cols as f32 - 1.0)) / cols as f32).floor(); - for row in cards.chunks(cols) { - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = gap; - for (label, value, sub) in row { - stat_card(ui, p, w, label, value, sub); - } - }); - ui.add_space(gap); + let cols = if width >= 420.0 { 4 } else { 2 }; + let rows = figures.len().div_ceil(cols); + let cell = vec2(width / cols as f32, 64.0); + let (rect, _) = ui.allocate_exact_size(vec2(width, cell.y * rows as f32 + 16.0), egui::Sense::hover()); + ui.painter().rect_filled(rect, R_L, p.muted); + for (i, (value, label, more)) in figures.iter().enumerate() { + let at = rect.min + vec2(8.0 + (i % cols) as f32 * ((width - 16.0) / cols as f32), 8.0 + (i / cols) as f32 * cell.y); + let r = egui::Rect::from_min_size(at, vec2((width - 16.0) / cols as f32, cell.y)); + ui.painter().text(r.center_top() + vec2(0.0, 10.0), egui::Align2::CENTER_TOP, value, egui::FontId::new(FONT_H2, crate::bold()), p.text); + ui.painter().text(r.center_top() + vec2(0.0, 40.0), egui::Align2::CENTER_TOP, label, egui::FontId::proportional(FONT_XS), p.text3); + if !more.is_empty() { + ui.interact(r, egui::Id::unique(("me-fig", i)), egui::Sense::hover()).on_hover_text(more); + } } } @@ -188,10 +200,20 @@ impl App { ui.painter().circle_filled(r.center(), 5.0, shade(lvl)); } ui.label(RichText::new(t("多")).size(FONT_XS).color(p.text3)); + // The busiest day, in words beside the legend (it was a card of its own). + let busiest = &d["busiest"]; + if busiest.is_object() { + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + let words = format!("{}{}・{} token", t("最活躍:"), short_date(busiest["date"].as_str().unwrap_or("")), crate::stats::wan(busiest["tokens"].as_u64().unwrap_or(0))); + ui.label(RichText::new(words).size(FONT_XS).color(p.text3)); + }); + } }); } - /// 用量: a period's tokens and cost, a bar a day, and the models and bots that used them. + /// 用量: the period's tokens as one big number, a bar a day, then what used them — by model + /// (one bar split in colours, each model with its service's mark) or by bot (each with its + /// face). The fine print (new / written / cached, how cost is known) is in the hovers. fn me_usage(&mut self, ui: &mut egui::Ui, d: &serde_json::Value) { let p = self.pal; section_with(ui, "用量", p, |ui| { @@ -201,33 +223,42 @@ impl App { }); let u = &d["periods"][self.me.span.to_string()]; let g = |k: &str| u[k].as_u64().unwrap_or(0); - let words = format!( - "{} token(新讀 {}、寫 {}、快取讀到 {})· {} 次呼叫 · 花費 {}", - crate::stats::wan(g("tokens")), + // The big number. + let hero = ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 6.0; + ui.label(RichText::new(crate::stats::wan(g("tokens"))).size(FONT_H1).strong().family(crate::bold()).color(p.text)); + ui.label(RichText::new("token").size(FONT_SM).color(p.text3)); + }); + hero.response.on_hover_text(format!( + "新讀 {}、寫 {}、快取讀到 {}", crate::stats::wan(g("input") + g("cache_write")), crate::stats::wan(g("output")), - crate::stats::wan(g("cache_read")), - crate::stats::wan(g("calls")), - crate::stats::cost_words(g("cost_micros"), g("unpriced"), g("calls")) - ); - ui.add(egui::Label::new(RichText::new(words).size(FONT_SM).color(p.text2)).wrap()); - hint(ui, "花費是模型服務自己回報的(例如 OpenRouter);沒回報的寫「未定價」,不是 0 元。", p); - ui.add_space(8.0); + crate::stats::wan(g("cache_read")) + )); + let cost = crate::stats::cost_words(g("cost_micros"), g("unpriced"), g("calls")); + ui.label(RichText::new(format!("{} 次呼叫・花費 {cost}", crate::stats::wan(g("calls")))).size(FONT_SM).color(p.text3)) + .on_hover_text(t("花費是模型服務自己回報的(例如 OpenRouter);沒回報的寫「未定價」,不是 0 元。")); + ui.add_space(10.0); // A bar a day. let daily = u["daily"].as_array().cloned().unwrap_or_default(); if !daily.is_empty() { let max = daily.iter().filter_map(|x| x[1].as_u64()).max().unwrap_or(0).max(1); let w = ui.available_width(); - let (rect, resp) = ui.allocate_exact_size(vec2(w, 90.0), egui::Sense::hover()); + let (rect, resp) = ui.allocate_exact_size(vec2(w, 84.0), egui::Sense::hover()); let paint = ui.painter_at(rect); + paint.hline(rect.x_range(), rect.bottom() - 0.5, Stroke::new(1.0, p.grid)); let slot = w / daily.len() as f32; let mut hovered: Option<&serde_json::Value> = None; for (i, x) in daily.iter().enumerate() { let v = x[1].as_u64().unwrap_or(0); - let h = (v as f32 / max as f32 * (rect.height() - 4.0)).max(if v > 0 { 2.0 } else { 1.0 }); - let r = egui::Rect::from_min_max(egui::pos2(rect.left() + i as f32 * slot + slot * 0.15, rect.bottom() - h), egui::pos2(rect.left() + (i as f32 + 1.0) * slot - slot * 0.15, rect.bottom())); - paint.rect_filled(r, 2.0, if v > 0 { p.accent } else { p.hover }); - if resp.hover_pos().is_some_and(|q| q.x >= rect.left() + i as f32 * slot && q.x < rect.left() + (i as f32 + 1.0) * slot) { + if v == 0 { + continue; + } + let h = (v as f32 / max as f32 * (rect.height() - 4.0)).max(3.0); + let r = egui::Rect::from_min_max(egui::pos2(rect.left() + i as f32 * slot + slot * 0.18, rect.bottom() - h), egui::pos2(rect.left() + (i as f32 + 1.0) * slot - slot * 0.18, rect.bottom())); + let on = resp.hover_pos().is_some_and(|q| q.x >= rect.left() + i as f32 * slot && q.x < rect.left() + (i as f32 + 1.0) * slot); + paint.rect_filled(r, CornerRadius { nw: R_S / 2, ne: R_S / 2, ..Default::default() }, if on { p.text } else { p.accent }); + if on { hovered = Some(x); } } @@ -235,38 +266,119 @@ impl App { resp.on_hover_text(format!("{}:{} token", long_date(x[0].as_str().unwrap_or("")), crate::stats::wan(x[1].as_u64().unwrap_or(0)))); } } - ui.add_space(10.0); - for (title, key) in [("依模型", "by_model"), ("依 Bot", "by_bot")] { - let rows = u[key].as_array().cloned().unwrap_or_default(); - ui.label(RichText::new(t(title)).size(FONT_SM).strong().color(p.text)); - if rows.is_empty() { - hint(ui, "這段時間沒有用量紀錄", p); + ui.add_space(16.0); + // What used them: one at a time (by model, or by bot). + if let Some(b) = segmented(ui, p, self.me.by_bot, &[(false, "依模型"), (true, "依 Bot")]) { + self.me.by_bot = b; + } + ui.add_space(8.0); + let rows = u[if self.me.by_bot { "by_bot" } else { "by_model" }].as_array().cloned().unwrap_or_default(); + if rows.is_empty() { + hint(ui, "這段時間沒有用量紀錄", p); + return; + } + let total: u64 = rows.iter().filter_map(|r| r["tokens"].as_u64()).sum::<u64>().max(1); + let rows: Vec<&serde_json::Value> = rows.iter().take(8).collect(); + let colour = |i: usize| p.chart_cat[i % p.chart_cat.len()]; + // By model: the whole in one bar, a colour each. + if !self.me.by_bot { + let w = ui.available_width(); + let (bar, _) = ui.allocate_exact_size(vec2(w, 10.0), egui::Sense::hover()); + ui.painter().rect_filled(bar, R_FULL, p.hover); + let mut x = bar.left(); + for (i, r) in rows.iter().enumerate() { + let part = r["tokens"].as_u64().unwrap_or(0) as f32 / total as f32 * w; + let seg = egui::Rect::from_min_max(egui::pos2(x, bar.top()), egui::pos2((x + part).min(bar.right()), bar.bottom())); + let round = CornerRadius { nw: if i == 0 { R_FULL } else { 0 }, sw: if i == 0 { R_FULL } else { 0 }, ne: if i + 1 == rows.len() { R_FULL } else { 0 }, se: if i + 1 == rows.len() { R_FULL } else { 0 } }; + ui.painter().rect_filled(seg, round, colour(i)); + x += part; } - let top = rows.first().and_then(|r| r["tokens"].as_u64()).unwrap_or(0).max(1); - rows_card(ui, p, |ui| { - for r in rows.iter().take(8) { - let tokens = r["tokens"].as_u64().unwrap_or(0); - ui.horizontal(|ui| { - let w = ui.available_width(); - let right = format!("{} · {}", crate::stats::wan(tokens), crate::stats::cost_words(r["cost_micros"].as_u64().unwrap_or(0), 0, 0)); - ui.allocate_ui_with_layout(vec2((w * 0.55).max(80.0), 24.0), Layout::left_to_right(Align::Center), |ui| { - ui.set_width((w * 0.55).max(80.0)); - ui.add(egui::Label::new(RichText::new(r["name"].as_str().unwrap_or("")).size(FONT_SM).color(p.text)).truncate()); - }); - let (bar, _) = ui.allocate_exact_size(vec2((w * 0.18).max(30.0), 8.0), egui::Sense::hover()); - ui.painter().rect_filled(bar, 3.0, p.hover); - ui.painter().rect_filled(egui::Rect::from_min_size(bar.min, vec2(bar.width() * tokens as f32 / top as f32, bar.height())), 3.0, p.accent); - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - ui.label(RichText::new(right).size(FONT_XS).color(p.text3)); - }); - }); + ui.add_space(10.0); + } + let top = rows.first().and_then(|r| r["tokens"].as_u64()).unwrap_or(0).max(1); + for (i, r) in rows.iter().enumerate() { + let name = r["name"].as_str().unwrap_or(""); + let tokens = r["tokens"].as_u64().unwrap_or(0); + let share = (tokens as f32 / total as f32 * 100.0).round(); + let (row, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 32.0), egui::Sense::hover()); + let paint = ui.painter(); + let mark = egui::Rect::from_center_size(egui::pos2(row.left() + 11.0, row.center().y), vec2(22.0, 22.0)); + if self.me.by_bot { + match self.state.bots.iter().find(|b| b.name == name) { + Some(b) => crate::avatar::paint(paint, mark, &b.shape, self.bot_color(b)), + None => { + paint.circle_filled(mark.center(), 9.0, p.active); + } } - }); - ui.add_space(8.0); + } else { + let service = name.split(" · ").next().unwrap_or(""); + match ALL_PROVIDERS.iter().find(|k| k.label() == service) { + Some(k) => crate::icons::provider_mark(paint, mark, *k, R_S), + None => { + paint.rect_filled(mark, R_S, p.active); + } + } + } + // (By model the name's colour dot ties it to the bar; by bot, a thin bar of its own.) + let right = format!("{}・{share:.0}%", crate::stats::wan(tokens)); + let right_w = ui.fonts_mut(|f| f.layout_no_wrap(right.clone(), egui::FontId::proportional(FONT_SM), p.text2).size().x); + let left = mark.right() + 10.0; + let bar_w = if self.me.by_bot { (row.width() * 0.22).clamp(40.0, 140.0) } else { 0.0 }; + let room = row.right() - right_w - bar_w - 16.0 - left - if self.me.by_bot { 0.0 } else { 14.0 }; + let mut x = left; + if !self.me.by_bot { + paint.circle_filled(egui::pos2(x + 4.0, row.center().y), 4.0, colour(i)); + x += 14.0; + } + let shown = sidebar_ui::shorten_width(ui, name, room.max(40.0), FONT_SM); + paint.text(egui::pos2(x, row.center().y), egui::Align2::LEFT_CENTER, shown, egui::FontId::proportional(FONT_SM), p.text); + if self.me.by_bot { + let b = egui::Rect::from_min_size(egui::pos2(row.right() - right_w - 12.0 - bar_w, row.center().y - 3.0), vec2(bar_w, 6.0)); + paint.rect_filled(b, R_FULL, p.hover); + paint.rect_filled(egui::Rect::from_min_size(b.min, vec2(b.width() * tokens as f32 / top as f32, b.height())), R_FULL, p.accent); + } + paint.text(row.right_center(), egui::Align2::RIGHT_CENTER, right, egui::FontId::proportional(FONT_SM), p.text2); + resp.on_hover_text(format!("{name}\n{} token・{}", crate::stats::wan(tokens), crate::stats::cost_words(r["cost_micros"].as_u64().unwrap_or(0), 0, 0))); } } } +/// Sample figures for screenshots: a year that ramps up, a few models and bots. +fn demo_figures() -> serde_json::Value { + let today = chrono::Local::now().date_naive(); + let day = |back: i64| (today - chrono::Duration::days(back)).format("%Y-%m-%d").to_string(); + let wave = |i: i64| -> u64 { let x = ((i * 7919) % 13) as u64; if i % 9 == 4 { 0 } else { 20_000 + x * 9_000 + (365 - i.min(365)) as u64 * 300 } }; + let days: Vec<serde_json::Value> = (0..365).rev().map(|i| { let tk = if i > 300 { 0 } else { wave(i) }; serde_json::json!([day(i), tk, tk / 900, if tk == 0 { 0 } else { 1 + (tk / 40_000).min(3) }]) }).collect(); + let period = |n: i64| { + let daily: Vec<serde_json::Value> = (0..n).rev().map(|i| serde_json::json!([day(i), wave(i)])).collect(); + let tokens: u64 = (0..n).map(wave).sum(); + let part = |f: f64| (tokens as f64 * f) as u64; + serde_json::json!({ + "tokens": tokens, "input": part(0.55), "cache_write": part(0.05), "output": part(0.12), "cache_read": part(0.28), + "calls": tokens / 2_400, "cost_micros": tokens * 3, "unpriced": 0, "daily": daily, + "by_model": [ + {"name": "xAI Grok · grok-4", "tokens": part(0.46), "cost_micros": part(0.46) * 3}, + {"name": "Claude · claude-sonnet-5-5", "tokens": part(0.27), "cost_micros": part(0.27) * 4}, + {"name": "OpenAI · gpt-5", "tokens": part(0.15), "cost_micros": part(0.15) * 3}, + {"name": "Ollama · qwen3:8b", "tokens": part(0.12), "cost_micros": 0}, + ], + "by_bot": [ + {"name": "Bot", "tokens": part(0.41), "cost_micros": part(0.41) * 3}, + {"name": "研究助理", "tokens": part(0.33), "cost_micros": part(0.33) * 3}, + {"name": "寫作夥伴", "tokens": part(0.16), "cost_micros": part(0.16) * 3}, + {"name": "電腦助手", "tokens": part(0.10), "cost_micros": part(0.10) * 3}, + ], + }) + }; + serde_json::json!({ + "tokens_year": days.iter().filter_map(|d| d[1].as_u64()).sum::<u64>(), "messages_year": 4_812, + "busiest": {"date": day(12), "tokens": 148_200}, "streak_now": 23, "streak_now_since": day(22), + "streak_best": 61, "streak_best_from": day(140), "streak_best_to": day(80), "active_days": 271, + "days": days, "weekday_first": 0, + "periods": {"7": period(7), "30": period(30), "90": period(90), "365": period(365)}, + }) +} + /// 2025-11-27 → 2025年11月27日. fn long_date(s: &str) -> String { let mut it = s.split('-'); diff --git a/src/app/models_ui.rs b/src/app/models_ui.rs new file mode 100644 index 0000000..94c8fb7 --- /dev/null +++ b/src/app/models_ui.rs @@ -0,0 +1,53 @@ +// 設定 › 模型: every model service as a tile — its mark, its name, whether it is ready, where it +// runs — in one column with the page (it used to be a list beside the page, beside the settings +// list: three columns of words). A press opens the service's page (its key, address, model). + +use super::*; + +impl App { + /// The tiles; returns the one pressed. + pub(super) fn provider_grid(&mut self, ui: &mut egui::Ui) -> Option<ProviderKind> { + let p = self.pal; + let mut picked = None; + let gap = 10.0; + let width = ui.available_width(); + let cols = if width >= 560.0 { 3 } else { 2 }; + let w = ((width - gap * (cols as f32 - 1.0)) / cols as f32).floor(); + for row in ALL_PROVIDERS.chunks(cols) { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = gap; + for &k in row { + let ps = self.state.provider(k); + let ready = providers::ready(k, &ps.api_key); + let runs = providers::runs_at(k, &providers::resolve_base(k, &ps.base_url)); + let (rect, r) = ui.allocate_exact_size(vec2(w, 76.0), egui::Sense::click()); + let paint = ui.painter(); + paint.rect(rect, R_L, if r.hovered() { p.hover } else { p.elevated }, Stroke::new(1.0, p.border), egui::StrokeKind::Inside); + let mark = egui::Rect::from_min_size(rect.min + vec2(14.0, 14.0), vec2(34.0, 34.0)); + crate::icons::provider_mark(paint, mark, k, R_M); + let left = mark.right() + 12.0; + let room = rect.right() - 12.0 - left; + let name = sidebar_ui::shorten_width(ui, k.label(), room, FONT_BASE); + paint.text(egui::pos2(left, mark.top() + 1.0), egui::Align2::LEFT_TOP, name, egui::FontId::new(FONT_BASE, crate::bold()), p.text); + // Ready: a green dot and 可以用; else what is missing, quietly. + let y = mark.top() + 24.0; + let (words, col) = if ready { (t("可以用"), p.text2) } else if k == ProviderKind::ChatGpt { (t("還沒登入"), p.text3) } else { (t("還沒設定"), p.text3) }; + let mut x = left; + if ready { + paint.circle_filled(egui::pos2(x + 4.0, y + 8.0), 4.0, p.up); + x += 13.0; + } + paint.text(egui::pos2(x, y), egui::Align2::LEFT_TOP, &words, egui::FontId::proportional(FONT_SM), col); + // Where it runs: the ones that keep the chats at home in green. + let tag = if matches!(runs, providers::RunsAt::Cloud(_)) { p.text3 } else { p.up }; + paint.text(rect.right_bottom() - vec2(12.0, 10.0), egui::Align2::RIGHT_BOTTOM, t(runs.short()), egui::FontId::proportional(FONT_XS), tag); + if r.on_hover_text(runs.words(self.brain_for_words().as_deref())).on_hover_cursor(egui::CursorIcon::PointingHand).clicked() { + picked = Some(k); + } + } + }); + ui.add_space(gap); + } + picked + } +} diff --git a/src/app/remote_ui.rs b/src/app/remote_ui.rs index 023a2e8..5891c4b 100644 --- a/src/app/remote_ui.rs +++ b/src/app/remote_ui.rs @@ -97,8 +97,9 @@ const MAX_WAITING_FROM_MEMBERS: usize = 8; /// 設定 › 一般 › 外觀 as the phone's colours: the shell the desktop draws, light and dark. pub(super) fn phone_palettes(st: &crate::model::State) -> serde_json::Value { - let one = |dark| remote::palette_json(&crate::theme::shell(st.shell_tone, &st.shell_accent, st.shell_contrast, dark)); - json!({"light": one(false), "dark": one(true)}) + let one = |dark| remote::palette_json(&crate::theme::palette_for(&st.shell_template, st.shell_tone, &st.shell_accent, st.shell_contrast, dark)); + // (And the 風格's chat backdrop: dots, a grid, waves, or none.) + json!({"light": one(false), "dark": one(true), "backdrop": crate::theme::backdrop(&st.shell_template)}) } impl App { @@ -318,9 +319,9 @@ impl App { self.state.remote.host_name.hash(&mut h); self.state.timezone.hash(&mut h); self.scr.cfg_hash.hash(&mut h); - (&self.state.folders, self.state.loose_index, &self.state.pin_order, self.state.accent as u8, self.newer_build.is_some()).hash(&mut h); + (&self.state.folders, self.state.loose_index, &self.state.pin_order, self.state.accent as u8, self.newer_build.is_some(), self.state.always_approve).hash(&mut h); // 外觀: the phone wears the desktop's theme and colours. - (self.state.theme as u8, &self.state.shell_accent, self.state.shell_tone.to_bits(), self.state.shell_contrast.to_bits()).hash(&mut h); + (self.state.theme as u8, &self.state.shell_accent, &self.state.shell_template, self.state.shell_tone.to_bits(), self.state.shell_contrast.to_bits()).hash(&mut h); for b in &self.state.bots { (b.id, &b.name, &b.color, b.unread, b.messages.len(), &b.thinking, &b.step_model).hash(&mut h); // (What the phone's home, editor and reactions show.) @@ -418,6 +419,7 @@ impl App { accent, pin_order: self.pinned_ids(), newer: self.newer_build.is_some(), + always: self.always_on(), sections: self.section_order(), theme: match self.state.theme { crate::model::Theme::Light => "light", @@ -912,7 +914,7 @@ impl App { ui.label(RichText::new(t("登出帳號")).size(FONT_SM).strong().family(crate::bold())); help_mark(ui, "這台電腦會從帳號移除:手機從外面連、裝置連結、分享都會斷。這台的 Bot 和聊天還在。", p); ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - if ui.add(egui::Button::new(RichText::new(t("登出")).color(p.danger)).corner_radius(R_M).min_size(vec2(64.0, 30.0))).clicked() { + if ui.add(danger_text_button("登出", p)).clicked() { let keep_name = self.state.remote.host_name.clone(); // Say goodbye to the account server: the machine's registration is // removed, so its key dies with the sign-out. @@ -1271,6 +1273,56 @@ pub(super) fn remote_legs(relay: &str, brain_online: Option<bool>, brain: &str, out } +impl App { + /// One workflow as the phone shows it (it is edited on the computer or by asking a bot; here + /// it is looked at and run). + fn workflow_json(&self, w: &crate::workflow::Workflow) -> serde_json::Value { + use crate::workflow::{NodeKind as K, RunState, StepState}; + let bot_name = |id: u64| self.state.bot(id).map(|b| b.name.clone()).unwrap_or_default(); + let state = |s: &RunState| match s { + RunState::Running => "running", + RunState::Waiting => "waiting", + RunState::Done => "done", + RunState::Failed => "failed", + RunState::Stopped => "stopped", + }; + let step_state = |s: StepState| match s { + StepState::Waiting => "waiting", + StepState::Running => "running", + StepState::Done => "done", + StepState::Failed => "failed", + StepState::Skipped => "skipped", + }; + let steps: Vec<serde_json::Value> = w + .order() + .iter() + .filter_map(|id| w.node(*id)) + .map(|n| { + let who = match &n.kind { + K::Step { bot, .. } | K::Media { bot, .. } | K::Check { bot, .. } | K::Deliver { bot } | K::Output { bot, .. } => bot_name(*bot), + _ => String::new(), + }; + json!({"id": n.id, "kind": n.kind.label(), "words": clip(&n.kind.words(), 240), "bot": who}) + }) + .collect(); + let run = |r: &crate::workflow::Run| { + // (What a 審批 step asks, while the run waits on it.) + let asks = (r.state == RunState::Waiting).then(|| r.order.get(r.at).and_then(|id| w.node(*id))).flatten().map(|n| n.kind.words()).unwrap_or_default(); + json!({ + "id": r.id, "state": state(&r.state), "words": crate::workflow::describe_run(r), "by": r.by, "started": r.started, "ended": r.ended, "why": r.why, "asks": asks, + "steps": r.steps.iter().map(|s| json!({"node": s.node, "state": step_state(s.state), "output": clip(&s.output, 600)})).collect::<Vec<_>>(), + }) + }; + let trigger = w.trigger().map(|t| t.kind.words()).unwrap_or_else(|| "手動".into()); + json!({ + "id": w.id, "name": w.name, "when": trigger, "steps": steps, "step_count": w.step_count(), + "next": w.next_run.map(|t| crate::routines::describe_when(t, &self.state.timezone)), + "live": w.live_run().map(run), + "runs": w.runs.iter().rev().take(10).map(run).collect::<Vec<_>>(), + }) + } +} + #[cfg(test)] mod phone_tests { use super::*; @@ -1456,7 +1508,7 @@ impl App { // model and computer, a new chat, regenerate) plus looking and small chat things; making, // changing or deleting bots, routines, memories, pages and settings stays the owner's. let admin_ok = match action { - "detail" | "settings" | "pages" | "search" | "export_bot" | "export_transcript" | "restart_bot" | "react" | "reply" | "resume" | "older" => true, + "detail" | "settings" | "pages" | "search" | "export_bot" | "export_transcript" | "restart_bot" | "react" | "reply" | "resume" | "older" | "workflows" | "schedule" | "library" | "settings_find" => true, "bot" => b["key"].as_str() == Some("unread"), "box" => matches!(b["op"].as_str(), Some("wake" | "disk")), _ => false, @@ -1478,6 +1530,64 @@ impl App { .collect(); json!({"ok": true, "hits": items, "more": more}) } + // 工作流 on the phone: each one's steps in order, what starts it, how its runs went, and + // the question it waits on — read here; run, stop, 繼續 and 停止 below. + "workflows" => json!({"ok": true, "workflows": self.state.workflows.iter().map(|w| self.workflow_json(w)).collect::<Vec<_>>()}), + // 搜尋設定 on the phone (the computer's index, with the phone page for each). + "settings_find" => super::settings_find::find_for_phone(&s("q")), + // 所有檔案 on the phone: every file the chats keep, across bots and conversations. + "library" => self.library_json(), + // 日程 on the phone: three days back to a week ahead — what ran on its own and how it + // went, what is coming — and 即將執行 (each thing once, soonest first). + "schedule" => { + use crate::schedule::{self as sch, Status, What}; + let now = crate::routines::now(); + let tz = self.state.timezone.clone(); + let today = sch::day_of(now, &tz); + let from = sch::day_start(today - chrono::Duration::days(3), &tz); + let to = sch::day_start(today + chrono::Duration::days(7), &tz); + let one = |i: &sch::Item| { + let (kind, id) = match i.what { + What::Routine { id, .. } => ("routine", id), + What::Workflow { id } => ("workflow", id), + }; + let status = match i.status { + Status::Done => "done", + Status::Failed => "failed", + Status::Stopped => "stopped", + Status::Running => "running", + Status::Coming => "coming", + Status::Paused => "paused", + }; + json!({"at": i.at, "clock": sch::clock(i.at, &tz), "day": sch::day_of(i.at, &tz).to_string(), "title": i.title, "when": i.when, "bot": i.bot, "kind": kind, "id": id, "status": status}) + }; + let items: Vec<serde_json::Value> = sch::items(&self.state, from, to, now).iter().take(400).map(one).collect(); + let coming: Vec<serde_json::Value> = sch::coming(&self.state, now, 6).iter().map(one).collect(); + json!({"ok": true, "today": today.to_string(), "items": items, "coming": coming}) + } + "workflow" => { + let wf = b["wf"].as_u64().unwrap_or(0); + let what = b["do"].as_str().unwrap_or(""); + let Some(w) = self.state.workflows.iter().find(|w| w.id == wf) else { return fail("找不到這個工作流") }; + if !["run", "stop", "go", "halt"].contains(&what) { + return fail("不認得的操作"); + } + if what == "run" && !w.has_steps() { + return fail(crate::workflow::NO_STEPS); + } + if what == "run" && w.live_run().is_some() { + return fail("這個工作流正在執行"); + } + let name = w.name.clone(); + self.wf_do(ctx, wf, what); + self.mark(); + done(&match what { + "run" => format!("開始執行「{name}」"), + "stop" => format!("已停止「{name}」"), + "go" => "好,繼續".to_string(), + _ => "停下來了".to_string(), + }) + } "export_bot" => match self.state.bot(bot) { Some(x) => json!({"ok": true, "filename": format!("{}.anybot", x.name), "content": crate::share::export(x)}), None => fail("找不到這個 Bot"), @@ -1700,7 +1810,23 @@ impl App { "unread" => x.unread = v.as_bool().unwrap_or(true), "tools" => x.tools_enabled = v.as_bool().unwrap_or(true), "shape" if v.as_str().map(|t| crate::avatar::SHAPES.contains(&t)).unwrap_or(false) => x.shape = v.as_str().unwrap_or("").to_string(), - "color" if v.as_str().map(|t| crate::avatar::COLORS.iter().any(|c| c.0 == t)).unwrap_or(false) => x.color = v.as_str().unwrap_or("").to_string(), + // (A preset, or a colour of one's own as #rrggbb, as on the computer.) + "color" if v.as_str().map(|t| crate::avatar::COLORS.iter().any(|c| c.0 == t) || (t.len() == 7 && t.starts_with('#') && t[1..].chars().all(|c| c.is_ascii_hexdigit()))).unwrap_or(false) => x.color = v.as_str().unwrap_or("").to_lowercase(), + // 備用模型: tried in order when the main one fails (at most MAX_FALLBACKS). + "fallbacks" if v.is_array() => { + x.fallbacks = v.as_array().unwrap().iter().filter_map(|f| { + let provider = crate::providers::ALL_PROVIDERS.iter().copied().find(|k| serde_json::to_value(k).ok().as_ref() == Some(&f["provider"]))?; + let model = f["model"].as_str()?.trim().to_string(); + (!model.is_empty()).then_some(crate::model::Fallback { provider, model }) + }).take(crate::model::MAX_FALLBACKS).collect(); + } + // 語音聊天 for this bot: read every answer aloud, its voice, speed and language. + "speak_replies" => x.speak_replies = v.as_bool().unwrap_or(false), + "voice" if v.is_string() => x.voice = v.as_str().unwrap_or("").trim().to_string(), + "voice_rate" if v.is_number() => x.voice_rate = (v.as_f64().unwrap_or(1.0) as f32).clamp(0.5, 2.0), + "voice_lang" if v.is_string() => x.voice_lang = v.as_str().unwrap_or("").trim().to_string(), + // 起始資料夾: where its files and commands start. + "workdir" if v.as_str().is_some_and(|w| !w.trim().is_empty()) => x.workdir = v.as_str().unwrap_or("").trim().to_string(), "context" => x.context_tokens = v.as_u64().unwrap_or(x.context_tokens).clamp(4_000, 2_000_000), "thinking" if v.as_str().is_some_and(|t| ["", "low", "medium", "high"].contains(&t)) => x.thinking = v.as_str().unwrap_or("").to_string(), "step_model" if v.is_string() => x.step_model = v.as_str().unwrap_or("").trim().to_string(), @@ -1809,6 +1935,69 @@ impl App { } "auto_review" => self.state.auto_review = v.as_bool().unwrap_or(false), "notify" => self.state.notify = v.as_bool().unwrap_or(true), + // 一律放行 as the chat's /always-approve does it (direct mode with it, and back). + "always_approve" => { + let on = v.as_bool().unwrap_or(false); + if on && !(self.managed.direct.allows() && self.managed.local.allows()) { + return fail(crate::always::LOCKED_NOTE); + } + // (The line about it goes into the chat it was switched from; from the + // settings page, into none.) + let bot = b["bot"].as_u64().unwrap_or(0); + self.always_command(ctx, bot, if on { crate::always::Command::On } else { crate::always::Command::Off }); + return done(if on { "一律放行:開" } else { "一律放行:關" }); + } + "smart_timeout_secs" => self.state.smart_timeout_secs = v.as_u64().unwrap_or(0).clamp(crate::smart::MIN_TIMEOUT_SECS, 3600), + // 外觀 from the phone: the accent (back to 自訂 from a 風格), the contrast, the language. + "shell_accent" => { + let name = v.as_str().unwrap_or(""); + if !crate::theme::ACCENTS.iter().any(|a| a.0 == name) { + return fail("不認得這個強調色"); + } + self.state.shell_accent = name.to_string(); + self.state.shell_template.clear(); + if let Some(ctx) = self.ctx_handle.clone() { + self.apply_theme(&ctx); + } + } + "shell_contrast" => { + self.state.shell_contrast = (v.as_f64().unwrap_or(1.0) as f32).clamp(0.75, 1.35); + if let Some(ctx) = self.ctx_handle.clone() { + self.apply_theme(&ctx); + } + } + "language" => { + let tag = v.as_str().unwrap_or("auto"); + if tag != "auto" && !crate::i18n::LANGS.iter().any(|l| l.0 == tag) { + return fail("不認得這個語言"); + } + self.state.language = tag.to_string(); + crate::i18n::set(tag); + } + "auto_update" => self.state.auto_update_when_away = v.as_bool().unwrap_or(true), + "garden_reports" => self.state.garden_reports = v.as_bool().unwrap_or(true), + "embed" => { + self.state.embed_model = match v.as_str().unwrap_or("") { + "off" => "off".into(), + "ollama" => "ollama".into(), + _ => String::new(), + }; + crate::embed::configure(&crate::embed::ollama_base(&self.state.provider(crate::providers::ProviderKind::Ollama).base_url), &self.state.embed_model); + } + "doc_folder_add" | "doc_folder_remove" => { + let f = v.as_str().unwrap_or("").trim().to_string(); + if f.is_empty() { + return fail("資料夾是空的"); + } + if key == "doc_folder_add" { + if !self.state.doc_folders.contains(&f) { + self.state.doc_folders.push(f); + } + } else { + self.state.doc_folders.retain(|x| *x != f); + } + *DOC_FOLDERS.write().unwrap_or_else(|e| e.into_inner()) = self.state.doc_folders.clone(); + } "rule_add" | "rule_remove" => { let text = v.as_str().unwrap_or("").trim().to_string(); // (Any list but 「ask」 used to be the allow list.) @@ -1836,6 +2025,34 @@ impl App { self.dirty = true; done("好了") } + // 設定 › 語音 from the phone: 聽 or 說's service, its address, key (written, never read + // back), model and (說) voice. + "voice" => { + if !owner { + return owner_only(); + } + let mut v = self.state.voice.clone(); + let e = match b["which"].as_str() { + Some("listen") => &mut v.listen, + Some("speak") => &mut v.speak, + _ => return fail("要說是「聽」還是「說」"), + }; + if let Some(k) = b["kind"].as_str() { + e.kind = match serde_json::from_value(json!(k)) { + Ok(k) => k, + Err(_) => return fail("不認得這個語音服務"), + }; + } + for (field, slot) in [("base_url", &mut e.base_url), ("api_key", &mut e.api_key), ("model", &mut e.model), ("voice", &mut e.voice)] { + if let Some(x) = b[field].as_str() { + *slot = x.trim().to_string(); + } + } + v.saved = true; + self.state.voice = v; + self.mark(); + done("好了") + } // 設定 › 模型: a provider's key (written, never read back) and new bots' model. "provider" => { if !owner { @@ -1849,7 +2066,19 @@ impl App { if let Some(m) = b["default_model"].as_str() { ps.default_model = m.trim().to_string(); } + // 服務網址 (empty: the service's own) and 看不到圖時請雲端模型看 (a local model's). + if let Some(u) = b["base_url"].as_str() { + ps.base_url = u.trim().to_string(); + } + if let Some(on) = b["cloud_eyes"].as_bool() { + ps.cloud_eyes = on; + } self.dirty = true; + // 測試連線並取得模型清單: asked on its own thread; the page reads how it went. + if b["fetch"].as_bool() == Some(true) { + self.fetch_models(kind); + return done("正在測試連線…"); + } done("好了") } // 手機與帳號: sign a direct-connection phone out (as the desktop's list does). @@ -2060,6 +2289,9 @@ impl App { "id": b.id, "name": b.name, "description": b.description, "instructions": b.instructions, "shape": b.shape, "color": b.color, "provider": serde_json::to_value(b.provider).unwrap_or_default(), "model": b.model, "thinking": b.thinking, "step_model": b.step_model, + "fallbacks": b.fallbacks.iter().map(|f| json!({"provider": serde_json::to_value(f.provider).unwrap_or_default(), "model": f.model, "label": f.provider.label()})).collect::<Vec<_>>(), + "workdir": b.workdir, + "speak_replies": b.speak_replies, "voice": b.voice, "voice_rate": b.voice_rate, "voice_lang": b.voice_lang, // 個人檔案 (each list: every choice there is, and whether this bot has it). "strengths": b.strengths, "not_for": b.not_for, "abilities": crate::profile::ABILITIES.iter().map(|(k, label, what)| json!({"key": k, "name": label, "note": what, "on": b.abilities.as_ref().is_none_or(|a| a.iter().any(|x| x == k))})).collect::<Vec<_>>(), @@ -2105,8 +2337,26 @@ impl App { crate::model::Accent::BotColor => "bot_color", }, "timezone": st.timezone, "notify": st.notify, "language": st.language, + // 風格: the one worn ("" = 自訂) and each one's colours for the phone's little pictures. + "style": st.shell_template, + "shell_accent": st.shell_accent, "shell_contrast": st.shell_contrast, + "accents": crate::theme::ACCENTS.iter().map(|(n, label, l, d)| json!({"key": n, "name": label, "light": format!("#{:02x}{:02x}{:02x}", l.r(), l.g(), l.b()), "dark": format!("#{:02x}{:02x}{:02x}", d.r(), d.g(), d.b())})).collect::<Vec<_>>(), + "languages": crate::i18n::LANGS.iter().map(|(tag, endo, _)| json!([tag, endo])).collect::<Vec<_>>(), + "styles": crate::theme::TEMPLATES.iter().map(|t| { + let look = |dark| { let p = crate::theme::palette_for(t.id, 1.0, "clay", st.shell_contrast, dark); let pj = remote::palette_json(&p); json!({"pane": pj["pane"], "side": pj["side"], "text3": pj["text3"], "hover": pj["hover"], "active": pj["active"], "bubble": pj["bubble-user"], "accent": pj["accent"], "line": pj["line"], "grid": pj["grid"]}) }; + json!({"id": t.id, "name": t.name, "about": t.about, "backdrop": t.backdrop, "light": look(false), "dark": look(true)}) + }).collect::<Vec<_>>(), "direct_mode": st.direct_mode, "direct_locked": !self.managed.direct.allows() || !self.managed.local.allows(), "smart_mode": st.smart_mode, + // 權限's 一律放行 and how long a 智慧模式 card waits; 更新's switches; 記憶與文件. + // 語音: who hears (聽) and who reads aloud (說); a key is only said to be there. + "voice": { + "listen": {"kind": serde_json::to_value(st.voice.listen.kind).unwrap_or_default(), "base_url": st.voice.listen.base_url, "model": st.voice.listen.model, "has_key": !st.voice.listen.api_key.is_empty(), "ready": crate::speech::resolve(&st.voice.listen, st, false).is_some()}, + "speak": {"kind": serde_json::to_value(st.voice.speak.kind).unwrap_or_default(), "base_url": st.voice.speak.base_url, "model": st.voice.speak.model, "voice": st.voice.speak.voice, "has_key": !st.voice.speak.api_key.is_empty(), "ready": crate::speech::resolve(&st.voice.speak, st, true).is_some()}, + }, + "always_approve": st.always_approve, "smart_timeout_secs": st.smart_timeout_secs, + "auto_update": st.auto_update_when_away, "garden_reports": st.garden_reports, + "embed": match st.embed_model.trim() { "" | "local" => "local", "off" => "off", _ => "ollama" }, "doc_folders": st.doc_folders, "auto_review": st.auto_review, "allow_rules": st.review_allow_rules, "ask_rules": st.review_ask_rules, "providers": crate::providers::ALL_PROVIDERS.iter().map(|&k| { let ps = st.provider(k); @@ -2114,6 +2364,9 @@ impl App { json!({"key": serde_json::to_value(k).unwrap_or_default(), "label": k.label(), "needs_key": k.needs_key() && k != crate::providers::ProviderKind::ChatGpt, "account": k == crate::providers::ProviderKind::ChatGpt, "ready": crate::providers::ready(k, &ps.api_key), "default_model": ps.default_model, "custom_url": !ps.base_url.is_empty(), + "base_url": ps.base_url, "default_url": k.default_base_url(), "cloud_eyes": ps.cloud_eyes, + "local": crate::providers::is_local_model(k, &crate::providers::resolve_base(k, &ps.base_url)), + "known": ps.known_models.len(), "testing": self.model_fetch.contains_key(&k), "status": self.fetch_status.get(&k).cloned().unwrap_or_default(), "runs": crate::providers::runs_at(k, &crate::providers::resolve_base(k, &ps.base_url)).short()}) }).collect::<Vec<_>>(), "skills": st.skills.iter().map(|k| json!({ @@ -2725,6 +2978,101 @@ mod phone_act_tests { assert!(!d.contains(key) && d.contains("\"memories\""), "{d}"); } + /// 工作流 on the phone: the list carries each one's steps in order and its runs; a workflow + /// with no steps is not run (no fake 完成); a run started there is 手動, and a member can't. + #[test] + fn the_phone_reads_and_runs_workflows() { + let (ctx, mut app) = demo(); + app.wf_demo(); + let list = app.phone_act(&ctx, "workflows", &json!({}), "admin"); + let first = &list["workflows"][0]; + assert!(first["steps"][0]["kind"] == "觸發器" && first["steps"].as_array().unwrap().len() > 2, "{first}"); + let empty = crate::workflow::Workflow::new(99, "空的", 0); + app.state.workflows.push(empty); + assert_eq!(app.phone_act(&ctx, "workflow", &json!({"wf": 99, "do": "run"}), "owner")["error"], crate::workflow::NO_STEPS); + assert!(app.state.workflows.iter().find(|w| w.id == 99).unwrap().runs.is_empty()); + assert!(app.phone_act(&ctx, "workflow", &json!({"wf": 99, "do": "run"}), "member")["error"].is_string()); + assert!(app.phone_act(&ctx, "workflow", &json!({"wf": 99, "do": "explode"}), "owner")["error"].is_string()); + } + + /// The settings the phone took over from the computer: 一律放行 (with direct mode, and back), + /// how long a 智慧模式 card waits, 更新's switches, 記憶與文件, and a bot's 備用模型, + /// 起始資料夾 and a colour of its own. + #[test] + fn the_phone_changes_the_rest_of_the_settings() { + let (ctx, mut app) = demo(); + let set = |app: &mut App, key: &str, value: serde_json::Value| app.phone_act(&ctx, "setting", &json!({"key": key, "value": value}), "owner"); + assert_eq!(set(&mut app, "always_approve", json!(true))["ok"], true); + assert!(app.state.always_approve && app.state.direct_mode); + assert_eq!(set(&mut app, "always_approve", json!(false))["ok"], true); + assert!(!app.state.always_approve && !app.state.direct_mode, "direct mode goes back to how it was"); + set(&mut app, "smart_timeout_secs", json!(0)); + assert_eq!(app.state.smart_timeout_secs, crate::smart::MIN_TIMEOUT_SECS, "never 0, never under the minimum"); + set(&mut app, "smart_timeout_secs", json!(60)); + set(&mut app, "auto_update", json!(false)); + set(&mut app, "garden_reports", json!(false)); + set(&mut app, "embed", json!("off")); + set(&mut app, "doc_folder_add", json!("~/Documents/筆記")); + assert_eq!((app.state.smart_timeout_secs, app.state.auto_update_when_away, app.state.garden_reports, app.state.embed_model.as_str(), app.state.doc_folders.clone()), (60, false, false, "off", vec!["~/Documents/筆記".to_string()])); + set(&mut app, "doc_folder_remove", json!("~/Documents/筆記")); + assert!(app.state.doc_folders.is_empty()); + let b = app.state.bots[0].id; + let bot = |app: &mut App, key: &str, value: serde_json::Value| app.phone_act(&ctx, "bot", &json!({"bot": b, "key": key, "value": value}), "owner"); + assert_eq!(bot(&mut app, "color", json!("#12AB9f"))["ok"], true); + assert!(bot(&mut app, "color", json!("#12AB9")).get("error").is_some(), "not a colour"); + let xai = serde_json::to_value(crate::providers::ProviderKind::Xai).unwrap(); + let openai = serde_json::to_value(crate::providers::ProviderKind::OpenAi).unwrap(); + bot(&mut app, "fallbacks", json!([{"provider": xai, "model": "grok-4"}, {"provider": "nope", "model": "x"}, {"provider": openai, "model": " "}])); + bot(&mut app, "workdir", json!("~/work")); + let x = app.state.bot(b).unwrap(); + assert_eq!((x.color.as_str(), x.fallbacks.len(), x.workdir.as_str()), ("#12ab9f", 1, "~/work")); + // Over the same network: what loosens is refused there, the rest goes. + let g = |action: &str, body: serde_json::Value| crate::remote::lan_guard(action, &body, || serde_json::Value::Null, "runc"); + use crate::remote::Guard; + assert_eq!(g("setting", json!({"key": "always_approve", "value": true})), Guard::Loosens); + assert_eq!(g("setting", json!({"key": "always_approve", "value": false})), Guard::Keeps); + assert_eq!(g("setting", json!({"key": "smart_timeout_secs", "value": 60})), Guard::Loosens); + assert_eq!(g("setting", json!({"key": "smart_timeout_secs", "value": 600})), Guard::Loosens); + assert_eq!(g("provider", json!({"provider": "x", "base_url": "https://elsewhere"})), Guard::Loosens); + assert_eq!(g("provider", json!({"provider": "x", "key": "k", "fetch": true})), Guard::Keeps); + assert_eq!(g("voice", json!({"which": "listen", "base_url": "https://elsewhere/v1"})), Guard::Loosens); + assert_eq!(g("voice", json!({"which": "listen", "kind": "xai"})), Guard::Keeps); + assert_eq!(g("setting", json!({"key": "doc_folder_add", "value": "~"})), Guard::Loosens); + assert_eq!(g("bot", json!({"bot": 1, "key": "workdir", "value": "~"})), Guard::Loosens); + assert_eq!(g("bot", json!({"bot": 1, "key": "fallbacks", "value": []})), Guard::Keeps); + } + + /// 所有檔案 on the phone: each attachment once (across bots and past conversations), newest + /// first, with its kind and whether it is still there. + #[test] + fn the_phone_reads_all_files() { + let (ctx, mut app) = demo(); + let b0 = app.state.bots[0].id; + let b1 = app.state.bots[1].id; + let att = |name: &str, path: &str| crate::attach::Attachment { name: name.into(), path: path.into(), ..Default::default() }; + app.state.bot_mut(b0).unwrap().messages.push(Message { at: 100, attachments: vec![att("a.png", "/nowhere/a.png")], ..Message::user("") }); + app.state.bot_mut(b1).unwrap().messages.push(Message { at: 200, attachments: vec![att("b.md", "/nowhere/b.md"), att("a.png", "/nowhere/a.png")], ..Message::user("") }); + let v = app.phone_act(&ctx, "library", &json!({}), "admin"); + let files: Vec<(&str, &str, bool)> = v["files"].as_array().unwrap().iter().filter(|f| f["path"].as_str().unwrap_or("").starts_with("/nowhere/")).map(|f| (f["name"].as_str().unwrap(), f["kind"].as_str().unwrap(), f["there"].as_bool().unwrap())).collect(); + assert_eq!(files, vec![("b.md", "doc", false), ("a.png", "image", false)]); + } + + /// 日程 on the phone: the days around today and 即將執行, each thing once there. + #[test] + fn the_phone_reads_the_schedule() { + let (ctx, mut app) = demo(); + app.sched_demo(); + let v = app.phone_act(&ctx, "schedule", &json!({}), "admin"); + let items = v["items"].as_array().expect("items"); + assert!(!items.is_empty() && items.iter().all(|i| i["day"].as_str().is_some_and(|d| d.len() == 10) && i["clock"].as_str().is_some_and(|c| c.len() == 5)), "{v}"); + let coming: Vec<(String, u64)> = v["coming"].as_array().unwrap().iter().map(|i| (i["kind"].as_str().unwrap().to_string(), i["id"].as_u64().unwrap())).collect(); + let mut once = coming.clone(); + once.dedup(); + assert_eq!(coming.len(), once.len(), "即將執行 lists each thing once: {coming:?}"); + // (A team member never gets this far: the route refuses them.) + assert!(!crate::remote::role_allows("member", "POST", &["api", "act", "schedule"])); + } + #[test] fn web_client_search_export_import_and_pin_order() { let (ctx, mut app) = demo(); diff --git a/src/app/settings_find.rs b/src/app/settings_find.rs index 1aea88e..40b542c 100644 --- a/src/app/settings_find.rs +++ b/src/app/settings_find.rs @@ -198,6 +198,34 @@ pub(super) fn tab_name(tab: SettingsTab) -> &'static str { const MAX_HITS: usize = 12; +/// 搜尋設定 for the phone: the same hits, each with the phone's page that has it (its 設定 pages +/// are named like the computer's tabs; a model service is under 模型). +pub(super) fn find_for_phone(q: &str) -> serde_json::Value { + let page = |tab: SettingsTab| match tab { + S::General => "general", + S::Remote => "account", + S::Me => "me", + S::Providers => "models", + S::Channels => "integrations", + S::Computers => "computers", + S::Review => "perms", + S::Vault => "vault", + S::Voice => "voice", + S::Updates => "updates", + }; + let hits: Vec<serde_json::Value> = find(q) + .into_iter() + .map(|h| { + let go = match &h.target { + Target::Entry(i) => page(INDEX[*i].tab), + Target::Provider(_) => "models", + }; + serde_json::json!({"title": h.title, "path": h.path, "page": go}) + }) + .collect(); + serde_json::json!({"ok": true, "hits": hits}) +} + /// What matches: titles that start with it, then titles that contain it, then the heading or the /// other words. pub(super) fn find(q: &str) -> Vec<Hit> { @@ -250,6 +278,10 @@ impl App { Target::Entry(i) => { let x = &INDEX[*i]; self.settings_tab = x.tab; + // (模型 itself: its tiles, not the service looked at last.) + if x.tab == S::Providers && x.title.is_empty() { + self.settings_provider_open = false; + } if let Some(open) = x.open { open(self); } @@ -260,6 +292,7 @@ impl App { Target::Provider(k) => { self.settings_tab = SettingsTab::Providers; self.settings_provider = *k; + self.settings_provider_open = true; } } } diff --git a/src/app/tasks_ui.rs b/src/app/tasks_ui.rs index de8ce09..c64a961 100644 --- a/src/app/tasks_ui.rs +++ b/src/app/tasks_ui.rs @@ -165,8 +165,8 @@ impl App { }; hint(ui, head, p); ui.add_space(10.0); - for task in &list { - if self.task_card(ui, task, now) { + for (i, task) in list.iter().enumerate() { + if self.task_card(ui, task, i, now) { open_at = Some((task.bot, task.at)); } } @@ -195,7 +195,7 @@ impl App { } /// One task's card; true when clicked. - fn task_card(&mut self, ui: &mut egui::Ui, task: &Task, now: i64) -> bool { + fn task_card(&mut self, ui: &mut egui::Ui, task: &Task, i: usize, now: i64) -> bool { let p = self.pal; let name = self.state.bot(task.bot).map(|b| b.name.clone()).unwrap_or_else(|| t("已刪除的 Bot")); // (The kit's card: its content's rect, out to the card's edge, is what a click lands on.) @@ -249,7 +249,9 @@ impl App { } ui.min_rect().expand2(vec2(16.0, 14.0)) }); - let r = ui.interact(card, egui::Id::unique(format!("task-card-{}", task.id)), egui::Sense::click()); + // (Its place in the list too: two openings written in the same millisecond share a task + // id, and two cards on one id fought over one press.) + let r = ui.interact(card, egui::Id::unique(("task-card", &task.id, i)), egui::Sense::click()); if r.hovered() { ui.painter().rect_stroke(card, R_L, Stroke::new(1.0, p.text3), egui::StrokeKind::Inside); } diff --git a/src/app/welcome_ui.rs b/src/app/welcome_ui.rs index 0b14932..ba44998 100644 --- a/src/app/welcome_ui.rs +++ b/src/app/welcome_ui.rs @@ -84,6 +84,7 @@ impl App { self.show_settings = true; self.settings_tab = SettingsTab::Providers; self.settings_provider = ProviderKind::Xai; + self.settings_provider_open = true; } if go_new { self.new_bot(); diff --git a/src/app/workflow_ui.rs b/src/app/workflow_ui.rs index afdde76..62002af 100644 --- a/src/app/workflow_ui.rs +++ b/src/app/workflow_ui.rs @@ -372,7 +372,7 @@ impl App { } match live { Some(_) => { - if ui.add(danger_button("■ 停止", p)).clicked() { + if ui.add(danger_text_button("■ 停止", p)).clicked() { let (ctx, id) = (ui.ctx().clone(), self.wf.current); self.wf_do(&ctx, id, "stop"); } @@ -1654,7 +1654,7 @@ impl App { } } }); - if !self.mir.on && ui.button(t("選檔案…")).clicked() { + if !self.mir.on && ui.add(egui::Button::new(t("選檔案…")).corner_radius(R_FULL)).clicked() { for f in crate::attach::pick_files() { let f = f.display().to_string(); if !files.contains(&f) { diff --git a/src/appctl.rs b/src/appctl.rs index e51474a..53c49db 100644 --- a/src/appctl.rs +++ b/src/appctl.rs @@ -174,9 +174,11 @@ pub fn specs() -> Vec<Value> { "step_model": {"type": "string", "description": "The quicker model for planned steps: \"\" automatic, \"off\" none."}, "color": {"type": "string", "description": "black, red, orange, yellow, green, cyan, blue, purple, magenta, brown, or #rrggbb."}, "shape": {"type": "string", "description": "squircle, blob, capsule, egg, hex, gem, cloud, arch, star, heart, shield, pebble."}}}}), - json!({"name": "update_settings", "description": "Change app settings: theme (light/dark/system), accent (bot_color/black), timezone (IANA). Running tasks on the person's own computer can only be turned on by the person.", + json!({"name": "update_settings", "description": "Change app settings: theme (light/dark/system), style (風格: a whole look), accent (bot_color/black), timezone (IANA). Running tasks on the person's own computer can only be turned on by the person.", "parameters": {"type": "object", "properties": { - "theme": {"type": "string", "enum": ["light", "dark", "system"]}, "accent": {"type": "string", "enum": ["quiet", "bot_color", "black"], "description": "聊天的顏色: quiet = your messages in a light grey bubble (default), bot_color = in the bot's colour, black"}, "timezone": {"type": "string"}}}}), + "theme": {"type": "string", "enum": ["light", "dark", "system"]}, + "style": {"type": "string", "enum": ["paper", "night", "ink", "moss", "ocean", "candy", "sunset", "terminal", "custom"], "description": "風格 (colours and the chat's backdrop, desktop and phone): paper 紙 (default), night 夜, ink 墨, moss 苔 (dots), ocean 海 (waves), candy 糖 (dots), sunset 夕陽 (waves), terminal 終端機 (grid); custom = the person's own accent and dials"}, + "accent": {"type": "string", "enum": ["quiet", "bot_color", "black"], "description": "聊天的顏色: quiet = your messages in a light grey bubble (default), bot_color = in the bot's colour, black"}, "timezone": {"type": "string"}}}}), crate::mcp::manage_spec(), crate::hooks::manage_spec(), crate::chatgpt::spec(), @@ -1095,6 +1097,20 @@ pub fn apply(state: &mut State, bot_id: u64, name: &str, args: &str) -> Outcome out.text.push_str(&format!("主題「{t}」不存在(可用 dark、light、system)。\n")); } } + if let Some(st) = s("style") { + if st == "custom" { + state.shell_template.clear(); + out.theme_changed = true; + changed.push("風格 → 自訂".to_string()); + } else if let Some(t) = crate::theme::template(&st) { + state.shell_template = t.id.to_string(); + out.theme_changed = true; + changed.push(format!("風格 → {}({})", t.name, t.about)); + } else { + let ids: Vec<&str> = crate::theme::TEMPLATES.iter().map(|t| t.id).collect(); + out.text.push_str(&format!("風格「{st}」不存在(可用 {}、custom)。\n", ids.join("、"))); + } + } if let Some(a) = s("accent") { state.accent = match a.as_str() { "bot_color" => Accent::BotColor, @@ -1444,6 +1460,10 @@ mod tests { assert!(m.ok && m.wake[0].0 == 3, "{}", m.text); assert!(apply(&mut st, 1, "update_bot", r#"{"default_computer":"火星"}"#).text.contains("沒有")); assert!(apply(&mut st, 1, "update_settings", r#"{"theme":"dark","timezone":"Asia/Tokyo"}"#).theme_changed); + // 風格: a whole look by name; custom goes back to the person's own dials. + let styled = apply(&mut st, 1, "update_settings", r#"{"style":"ocean"}"#); + assert!(styled.theme_changed && st.shell_template == "ocean" && styled.text.contains("海"), "{}", styled.text); + assert!(apply(&mut st, 1, "update_settings", r#"{"style":"custom"}"#).theme_changed && st.shell_template.is_empty()); assert_eq!(st.timezone, "Asia/Tokyo"); } diff --git a/src/cloudbox.rs b/src/cloudbox.rs index 3b517cc..4f3e64b 100644 --- a/src/cloudbox.rs +++ b/src/cloudbox.rs @@ -1412,7 +1412,7 @@ pub fn start_background() { if !brain { sleep_on_a_screen(); } - let quiet = idle >= QUIET_SECS && !is_busy() && !HELD_BY_PERSON.load(Ordering::SeqCst) && !viewer_open(); + let quiet = idle >= QUIET_SECS && !is_busy() && !held_by_person() && !viewer_open(); let due = snapshot_time().map(|t| (chrono::Local::now() - t).num_seconds() >= SNAPSHOT_EVERY_SECS).unwrap_or(true); if quiet && due && run_state().is_running() { let _ = save_snapshot(); @@ -1440,7 +1440,7 @@ pub fn start_background() { /// row, keeping the first try's snapshot (auto_update). Files and logins stay (the home volume). fn update_when_idle(idle_secs: u64) { static TRIED: Mutex<String> = Mutex::new(String::new()); - if !IS_BRAIN.load(Ordering::SeqCst) || idle_secs < 60 || is_busy() || HELD_BY_PERSON.load(Ordering::SeqCst) || viewer_open() { + if !IS_BRAIN.load(Ordering::SeqCst) || idle_secs < 60 || is_busy() || held_by_person() || viewer_open() { return; } if !update_available() { @@ -1589,7 +1589,7 @@ fn update_box_here() -> i32 { /// wants neither running then, from the start: stop the box at once, and the VM when nothing /// else runs in it. Becoming a brain again starts both (probe and ensure_running wake the VM). fn sleep_on_a_screen() { - if IS_BRAIN.load(Ordering::SeqCst) || is_busy() || HELD_BY_PERSON.load(Ordering::SeqCst) || viewer_open() { + if IS_BRAIN.load(Ordering::SeqCst) || is_busy() || held_by_person() || viewer_open() { return; } // Docker is down already (the VM sleeps), or nothing of ours runs: nothing to do. @@ -2684,8 +2684,39 @@ pub fn hold(key: &str, on: bool) { HELD_BY_PERSON.store(!h.is_empty(), Ordering::SeqCst); } +/// 接管 from a phone (a page that may vanish without a word: the line drops, the browser is +/// killed): held until `secs` from now, and the page says so again every few seconds — a hold +/// nobody renews lets go by itself. Kept apart from the desktop's holds, so a phone letting go +/// never releases a takeover made at a computer. +fn phone_holds() -> &'static Mutex<std::collections::HashMap<String, std::time::Instant>> { + static H: OnceLock<Mutex<std::collections::HashMap<String, std::time::Instant>>> = OnceLock::new(); + H.get_or_init(|| Mutex::new(Default::default())) +} + +pub const PHONE_HOLD_SECS: u64 = 30; + +pub fn hold_for(key: &str, on: bool) { + let mut h = phone_holds().lock().unwrap_or_else(|e| e.into_inner()); + if on { + h.insert(key.to_string(), std::time::Instant::now() + std::time::Duration::from_secs(PHONE_HOLD_SECS)); + } else { + h.remove(key); + } +} + +/// Whether anyone holds any screen (the box must not sleep then). +fn held_by_person() -> bool { + let now = std::time::Instant::now(); + let mut h = phone_holds().lock().unwrap_or_else(|e| e.into_inner()); + h.retain(|_, until| *until > now); + !h.is_empty() || HELD_BY_PERSON.load(Ordering::SeqCst) +} + fn is_held(key: &str) -> bool { - held().lock().unwrap_or_else(|e| e.into_inner()).contains(key) + if held().lock().unwrap_or_else(|e| e.into_inner()).contains(key) { + return true; + } + phone_holds().lock().unwrap_or_else(|e| e.into_inner()).get(key).is_some_and(|until| *until > std::time::Instant::now()) } /// AT-SPI roles as words. @@ -3949,6 +3980,17 @@ mod tests { assert!(is_held("bot1") && !is_held("bot2") && HELD_BY_PERSON.load(Ordering::SeqCst)); hold("bot1", false); assert!(!is_held("bot1") && !HELD_BY_PERSON.load(Ordering::SeqCst)); + // A phone's hold is its own (letting go leaves a desktop's takeover), and one nobody + // renews runs out by itself. + hold("bot1", true); + hold_for("bot1", true); + hold_for("bot1", false); + assert!(is_held("bot1")); + hold("bot1", false); + hold_for("bot2", true); + assert!(is_held("bot2") && held_by_person()); + phone_holds().lock().unwrap().insert("bot2".into(), std::time::Instant::now() - std::time::Duration::from_secs(1)); + assert!(!is_held("bot2") && !held_by_person()); // What viewers name (a bot) maps to the screen the brain published. set_bot_screens([(5u64, "bot5".to_string())].into_iter().collect()); assert_eq!(screen_for_bot("5"), "bot5"); diff --git a/src/icons.rs b/src/icons.rs index c3aa4fe..944166f 100644 --- a/src/icons.rs +++ b/src/icons.rs @@ -97,6 +97,13 @@ pub enum Icon { Map, Scan, Send, + // 設定's rows (setting_icon). + Palette, + Moon, + Globe, + Sliders, + Volume, + Drive, } impl Icon { @@ -199,6 +206,12 @@ impl Icon { Icon::Map => include_str!("../icons/lucide/map.svg"), Icon::Scan => include_str!("../icons/lucide/scan.svg"), Icon::Send => include_str!("../icons/lucide/send.svg"), + Icon::Palette => include_str!("../icons/lucide/palette.svg"), + Icon::Moon => include_str!("../icons/lucide/moon.svg"), + Icon::Globe => include_str!("../icons/lucide/globe.svg"), + Icon::Sliders => include_str!("../icons/lucide/sliders-horizontal.svg"), + Icon::Volume => include_str!("../icons/lucide/volume-2.svg"), + Icon::Drive => include_str!("../icons/lucide/hard-drive.svg"), Icon::CircleCheck => include_str!("../icons/lucide/circle-check.svg"), Icon::CircleX => include_str!("../icons/lucide/circle-x.svg"), Icon::Minus => include_str!("../icons/lucide/minus.svg"), @@ -342,6 +355,137 @@ pub fn button(ui: &mut egui::Ui, icon: Icon, size: f32, col: Color32, hover_fill r.on_hover_cursor(egui::CursorIcon::PointingHand) } +/// The picture before a setting's name (設定: every row has one — the eye finds 通知 by its bell +/// before it reads the word). By the words in its name, first match wins; a name that matches +/// none gets the plain sliders. +pub fn setting_icon(label: &str) -> Icon { + const RULES: &[(&[&str], Icon)] = &[ + (&["上網"], Icon::Globe), + (&["頁面"], Icon::FileText), + (&["合作", "同事"], Icon::Users), + (&["電話", "簡訊"], Icon::Message), + (&["主題"], Icon::Moon), + (&["風格", "強調色", "顏色", "底色", "對比", "外觀", "外殼"], Icon::Palette), + (&["密度"], Icon::Apps), + (&["慶祝"], Icon::Star), + (&["頭像"], Icon::Smile), + (&["語言"], Icon::Globe), + (&["時區", "時間"], Icon::Clock), + (&["通知", "響一聲", "提醒"], Icon::Bell), + (&["記憶", "意思找"], Icon::Brain), + (&["資料夾", "文件", "檔案"], Icon::Folder), + (&["金鑰", "Token", "token", "密鑰"], Icon::Key), + (&["密碼", "保險庫", "兩步"], Icon::Lock), + (&["瀏覽器", "網址", "網頁"], Icon::Globe), + (&["發布前", "檢查"], Icon::CircleCheck), + (&["更新", "版本", "重新啟動"], Icon::Update), + (&["備份", "快照", "還原"], Icon::History), + (&["磁碟", "用量", "容量"], Icon::Drive), + (&["團隊", "成員", "分享"], Icon::Users), + (&["帳號", "帳戶", "登入", "登出", "個人"], Icon::Person), + (&["手機", "裝置"], Icon::Monitor), + (&["語音", "聽", "說", "朗讀", "聲音"], Icon::Volume), + (&["麥克風", "錄音"], Icon::Mic), + (&["審核", "規則", "權限", "直接操作", "一律", "允許", "詢問", "隔離", "智慧"], Icon::Shield), + (&["連接器", "MCP", "整合"], Icon::Apps), + (&["管道", "Telegram", "Slack", "Discord", "訊息"], Icon::Message), + (&["技能"], Icon::Sparkle), + (&["模型", "AI"], Icon::Sparkle), + (&["電腦", "螢幕", "SSH", "Docker", "主機", "容器", "終端機", "執行"], Icon::Monitor), + (&["例行", "排程", "日程"], Icon::Alarm), + (&["工作流"], Icon::Workflow), + (&["Bot"], Icon::Bot), + (&["園丁", "改進", "診斷"], Icon::Target), + (&["資料", "放在哪"], Icon::Drive), + ]; + RULES.iter().find(|(words, _)| words.iter().any(|w| label.contains(w))).map(|(_, i)| *i).unwrap_or(Icon::Sliders) +} + +/// A model service's mark: a small rounded tile in the service's own colour with a simple shape +/// drawn here (no one's artwork copied — just enough to tell them apart at a glance, the way an +/// app icon is found before its name is read). The same tile in light and dark. +pub fn provider_mark(p: &Painter, rect: Rect, kind: crate::providers::ProviderKind, radius: u8) { + use crate::providers::ProviderKind as K; + use egui::{pos2, Shape, Stroke}; + let rgb = |r, g, b| Color32::from_rgb(r, g, b); + let (tile, ink) = match kind { + K::Xai => (rgb(0x14, 0x14, 0x14), Color32::WHITE), + K::OpenAi => (rgb(0x14, 0x14, 0x14), Color32::WHITE), + K::ChatGpt => (rgb(0x10, 0xa3, 0x7f), Color32::WHITE), + K::Anthropic => (rgb(0xd9, 0x77, 0x57), Color32::WHITE), + K::Gemini => (rgb(0xee, 0xf2, 0xfd), rgb(0x3f, 0x7b, 0xf0)), + K::OpenRouter => (rgb(0x64, 0x67, 0xf2), Color32::WHITE), + K::OpenCodeGo => (rgb(0x23, 0x20, 0x1e), Color32::WHITE), + K::Ollama => (rgb(0xf4, 0xf4, 0xf2), rgb(0x1a, 0x1a, 0x1a)), + K::Custom => (rgb(0x6b, 0x72, 0x80), Color32::WHITE), + }; + p.rect_filled(rect, radius, tile); + let c = rect.center(); + let r = rect.width().min(rect.height()) * 0.28; + let line = |w: f32| Stroke::new((rect.width() * w).max(1.2), ink); + match kind { + // A plain X, one stroke longer. + K::Xai => { + p.line_segment([pos2(c.x - r, c.y - r), pos2(c.x + r, c.y + r)], line(0.075)); + p.line_segment([pos2(c.x + r * 1.1, c.y - r * 1.25), pos2(c.x - r, c.y + r)], line(0.075)); + } + // Six rings around a centre: a flower. + K::OpenAi | K::ChatGpt => { + for i in 0..6 { + let a = i as f32 * std::f32::consts::TAU / 6.0; + p.circle_stroke(c + vec2(a.cos(), a.sin()) * r * 0.45, r * 0.55, line(0.045)); + } + } + // A burst of rays. + K::Anthropic => { + for i in 0..10 { + let a = i as f32 * std::f32::consts::TAU / 10.0; + let len = if i % 2 == 0 { r * 1.15 } else { r * 0.8 }; + p.line_segment([c + vec2(a.cos(), a.sin()) * r * 0.18, c + vec2(a.cos(), a.sin()) * len], line(0.07)); + } + } + // A four-pointed sparkle (four thin triangles from a small centre). + K::Gemini => { + let k = r * 0.2; + for (tip, a, b) in [ + (pos2(c.x, c.y - r * 1.3), pos2(c.x - k, c.y), pos2(c.x + k, c.y)), + (pos2(c.x, c.y + r * 1.3), pos2(c.x - k, c.y), pos2(c.x + k, c.y)), + (pos2(c.x - r * 1.3, c.y), pos2(c.x, c.y - k), pos2(c.x, c.y + k)), + (pos2(c.x + r * 1.3, c.y), pos2(c.x, c.y - k), pos2(c.x, c.y + k)), + ] { + p.add(Shape::convex_polygon(vec![tip, a, b], ink, Stroke::NONE)); + } + } + // Two arrows passing each other: a router. + K::OpenRouter => { + let s = line(0.06); + let (y1, y2) = (c.y - r * 0.45, c.y + r * 0.45); + p.line_segment([pos2(c.x - r, y1), pos2(c.x + r, y1)], s); + p.line_segment([pos2(c.x + r, y1), pos2(c.x + r * 0.55, y1 - r * 0.4)], s); + p.line_segment([pos2(c.x + r, y2), pos2(c.x - r, y2)], s); + p.line_segment([pos2(c.x - r, y2), pos2(c.x - r * 0.55, y2 + r * 0.4)], s); + } + // Angle brackets: code. + K::OpenCodeGo => { + let s = line(0.06); + p.line_segment([pos2(c.x - r * 0.3, c.y - r * 0.8), pos2(c.x - r, c.y)], s); + p.line_segment([pos2(c.x - r, c.y), pos2(c.x - r * 0.3, c.y + r * 0.8)], s); + p.line_segment([pos2(c.x + r * 0.3, c.y - r * 0.8), pos2(c.x + r, c.y)], s); + p.line_segment([pos2(c.x + r, c.y), pos2(c.x + r * 0.3, c.y + r * 0.8)], s); + } + // A round face with two ears. + K::Ollama => { + let s = line(0.055); + p.circle_stroke(pos2(c.x, c.y + r * 0.25), r * 0.75, s); + p.line_segment([pos2(c.x - r * 0.4, c.y - r * 0.35), pos2(c.x - r * 0.5, c.y - r * 1.1)], s); + p.line_segment([pos2(c.x + r * 0.4, c.y - r * 0.35), pos2(c.x + r * 0.5, c.y - r * 1.1)], s); + p.circle_filled(pos2(c.x - r * 0.28, c.y + r * 0.15), r * 0.09, ink); + p.circle_filled(pos2(c.x + r * 0.28, c.y + r * 0.15), r * 0.09, ink); + } + K::Custom => paint(p, Rect::from_center_size(c, vec2(r * 2.2, r * 2.2)), Icon::Gear, ink), + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/main.rs b/src/main.rs index 030d911..f75f0ff 100644 --- a/src/main.rs +++ b/src/main.rs @@ -131,6 +131,12 @@ fn pingfang_path() -> Option<PathBuf> { /// PingFang TC Regular inside PingFang.ttc. const PINGFANG_TC_INDEX: u32 = 2; +/// PingFang TC Semibold inside PingFang.ttc: the bold Apple sets titles in (lighter than Bold). +const PINGFANG_TC_SEMIBOLD_INDEX: u32 = 10; + +/// SF Pro, macOS's own Latin face (one variable font: the weight is an axis). +const SF_PRO: &str = "/System/Library/Fonts/SFNS.ttf"; + /// The window's first size (screenshot mode can ask for another, e.g. ANYBOT_SHOT_SIZE=760x560). fn shot_size() -> [f32; 2] { std::env::var("ANYBOT_SHOT_SIZE").ok().and_then(|v| { @@ -139,45 +145,73 @@ fn shot_size() -> [f32; 2] { }).unwrap_or([1180.0, 780.0]) } -/// 思源黑體 (Noto Sans TC Regular, SIL OFL 1.1, fonts/OFL.txt): the interface's one font — -/// plain, clear, the same on every computer. +/// 思源黑體 (Noto Sans TC Regular, SIL OFL 1.1, fonts/OFL.txt): the interface's font where the +/// computer has no Apple fonts (Windows, Linux), and what fills in a character the system's lack. pub const NOTO_TC: &[u8] = include_bytes!("../fonts/NotoSansTC-Regular.otf"); /// 思源黑體's bold weight, for titles, bold words and the main button of a choice. pub const NOTO_TC_BOLD: &[u8] = include_bytes!("../fonts/NotoSansTC-Bold.otf"); -/// 思源宋體 (Noto Serif TC Regular, SIL OFL 1.1): what is read at length — a bot's answer, a -/// page's text — is set in a book face, the way Claude sets its answers. -pub const NOTO_SERIF_TC: &[u8] = include_bytes!("../fonts/NotoSerifTC-Regular.otf"); - -/// 思源宋體's bold weight: headings and bold words in reading text. -pub const NOTO_SERIF_TC_BOLD: &[u8] = include_bytes!("../fonts/NotoSerifTC-Bold.otf"); - /// The family bold interface text is set in (`RichText::family(bold())`, `FontId::new(size, bold())`). pub fn bold() -> egui::FontFamily { egui::FontFamily::Name("bold".into()) } -/// The reading family (思源宋體): answers and pages. +/// The reading family: answers and pages. The same face as the interface (Apple's way: one +/// calm sans everywhere; answers used to be in 思源宋體, which read formal and heavy). pub fn read() -> egui::FontFamily { egui::FontFamily::Name("read".into()) } -/// The reading family's bold (思源宋體 Bold): headings and bold words in answers and pages. +/// The reading family's bold: headings and bold words in answers and pages. pub fn read_bold() -> egui::FontFamily { egui::FontFamily::Name("read-bold".into()) } -/// The fonts, one set for every computer: 思源黑體 for the interface, 思源宋體 for reading, the -/// system's mono for code. The system's CJK font only fills in what the bundled ones lack -/// (symbols, a rare character); egui's own fonts stay last for emoji. +/// The fonts. On a Mac, Apple's own: SF Pro for Latin and 蘋方 (PingFang TC) for Chinese, the +/// pair macOS itself sets text in — Regular, and Semibold for bold (Apple's titles are +/// Semibold, not Bold: lighter, more relaxed). Elsewhere 思源黑體, bundled, so every computer +/// gets a good Chinese face; it also fills in what the Apple fonts lack. The system's mono for +/// code; egui's own fonts stay last for emoji. pub fn load_fonts(ctx: &egui::Context) { + use std::sync::Arc; let mut fonts = egui::FontDefinitions::default(); - // One font for Chinese *and* English: mixing egui's built-in Latin font with a Chinese - // fallback put the two on different baselines and sizes ("Bot 設定" looked broken). - let mut candidates: Vec<(PathBuf, u32)> = pingfang_path().map(|p| vec![(p, PINGFANG_TC_INDEX)]).unwrap_or_default(); - candidates.extend( - [ + // Code: the original's `--cursor-font-family-mono` list is ui-monospace, SFMono-Regular, Menlo… + for path in ["/System/Library/Fonts/SFNSMono.ttf", "/System/Library/Fonts/Menlo.ttc"] { + if let Ok(bytes) = std::fs::read(path) { + fonts.font_data.insert("mono".into(), egui::FontData::from_owned(bytes).into()); + fonts.families.entry(egui::FontFamily::Monospace).or_default().insert(0, "mono".into()); + break; + } + } + // Apple's pair, when this Mac has 蘋方 (a downloadable system asset; nearly always there). + // (SF Pro first: it has the Latin letters and digits, 蘋方 everything Chinese. One file each, + // shared between the weights.) + let mut regular: Vec<String> = vec![]; + let mut semibold: Vec<String> = vec![]; + // (Read once per run and shared: 蘋方 is 78 MB, and a window or a check may set fonts again.) + static APPLE: std::sync::OnceLock<(Option<egui::epaint::text::Blob>, Option<egui::epaint::text::Blob>)> = std::sync::OnceLock::new(); + let (pf, sf) = APPLE.get_or_init(|| { + let blob = |b: Vec<u8>| -> egui::epaint::text::Blob { Arc::new(b) }; + (pingfang_path().and_then(|p| std::fs::read(p).ok()).map(blob), std::fs::read(SF_PRO).ok().map(blob)) + }); + if let Some(pf) = pf.clone() { + if let Some(sf) = sf.clone() { + for (name, wght) in [("sf", 400.0), ("sf-bold", 600.0)] { + let mut d = egui::FontData::from_blob(sf.clone(), 0); + d.tweak.coords = egui::epaint::text::VariationCoords::new([(b"wght", wght)]); + fonts.font_data.insert(name.into(), d.into()); + } + regular.push("sf".into()); + semibold.push("sf-bold".into()); + } + fonts.font_data.insert("pf".into(), egui::FontData::from_blob(pf.clone(), PINGFANG_TC_INDEX).into()); + fonts.font_data.insert("pf-bold".into(), egui::FontData::from_blob(pf, PINGFANG_TC_SEMIBOLD_INDEX).into()); + regular.push("pf".into()); + semibold.push("pf-bold".into()); + } else { + // No 蘋方: the system's CJK font only fills in what 思源黑體 lacks (a symbol, a rare character). + let candidates = [ ("/System/Library/Fonts/Hiragino Sans GB.ttc", 0), ("/System/Library/Fonts/STHeiti Medium.ttc", 0), ("/System/Library/Fonts/Supplemental/Arial Unicode.ttf", 0), @@ -188,46 +222,43 @@ pub fn load_fonts(ctx: &egui::Context) { ("/usr/share/fonts/noto-cjk/NotoSansCJK-Regular.ttc", 3), ("/usr/share/fonts/google-noto-cjk/NotoSansCJK-Regular.ttc", 3), ("/usr/share/fonts/truetype/wqy/wqy-microhei.ttc", 0), - ] - .into_iter() - .map(|(p, i)| (PathBuf::from(p), i)), - ); - // Code: the original's `--cursor-font-family-mono` list is ui-monospace, SFMono-Regular, Menlo… - for path in ["/System/Library/Fonts/SFNSMono.ttf", "/System/Library/Fonts/Menlo.ttc"] { - if let Ok(bytes) = std::fs::read(path) { - fonts.font_data.insert("mono".into(), egui::FontData::from_owned(bytes).into()); - fonts.families.entry(egui::FontFamily::Monospace).or_default().insert(0, "mono".into()); - break; + ]; + for (path, index) in candidates { + if let Ok(bytes) = std::fs::read(path) { + let mut data = egui::FontData::from_owned(bytes); + data.index = index; + fonts.font_data.insert("cjk".into(), data.into()); + break; + } } } - for (path, index) in candidates { - if let Ok(bytes) = std::fs::read(&path) { - let mut data = egui::FontData::from_owned(bytes); - data.index = index; - fonts.font_data.insert("cjk".into(), data.into()); - fonts.families.entry(egui::FontFamily::Proportional).or_default().insert(0, "cjk".into()); - // Code stays in the monospace font; Chinese inside code falls back to the same font. - fonts.families.entry(egui::FontFamily::Monospace).or_default().push("cjk".into()); - break; - } - } - for (name, bytes) in [("noto", NOTO_TC), ("noto-bold", NOTO_TC_BOLD), ("serif", NOTO_SERIF_TC), ("serif-bold", NOTO_SERIF_TC_BOLD)] { + for (name, bytes) in [("noto", NOTO_TC), ("noto-bold", NOTO_TC_BOLD)] { fonts.font_data.insert(name.into(), egui::FontData::from_static(bytes).into()); } - // 思源黑體 first everywhere it has the letter (code: after the mono font, before the system's). + regular.push("noto".into()); + semibold.push("noto-bold".into()); + if fonts.font_data.contains_key("cjk") { + regular.push("cjk".into()); + } + // The interface: the faces in front of egui's own (emoji last). let base = { let p = fonts.families.entry(egui::FontFamily::Proportional).or_default(); - p.insert(0, "noto".into()); + for (i, f) in regular.iter().enumerate() { + p.insert(i, f.clone()); + } p.clone() }; + // Code: after the mono font, the same faces for Chinese inside code. let mono = fonts.families.entry(egui::FontFamily::Monospace).or_default(); - let at = mono.iter().position(|f| f == "cjk").unwrap_or(mono.len()); - mono.insert(at, "noto".into()); - // Each other family: its face in front of the same list (what it lacks comes from 思源黑體). - let with = |first: &[&str]| first.iter().map(|f| f.to_string()).chain(base.iter().cloned()).collect::<Vec<_>>(); - fonts.families.insert(bold(), with(&["noto-bold"])); - fonts.families.insert(read(), with(&["serif"])); - fonts.families.insert(read_bold(), with(&["serif-bold", "noto-bold"])); + for f in ®ular { + if f != "sf" { + mono.push(f.clone()); + } + } + let bold_list: Vec<String> = semibold.iter().cloned().chain(base.iter().cloned()).collect(); + fonts.families.insert(bold(), bold_list.clone()); + fonts.families.insert(read(), base); + fonts.families.insert(read_bold(), bold_list); ctx.set_fonts(fonts); } diff --git a/src/model.rs b/src/model.rs index 3a072aa..46c8396 100644 --- a/src/model.rs +++ b/src/model.rs @@ -762,6 +762,9 @@ pub struct State { pub shell_accent: String, #[serde(default = "default_shell_contrast")] pub shell_contrast: f32, + /// 風格 (theme::TEMPLATES): one whole look; empty = 自訂 (the dials above). + #[serde(default, skip_serializing_if = "String::is_empty")] + pub shell_template: String, /// 緊湊間距(設定 › 一般);關=寬鬆。 #[serde(default)] pub dense: bool, @@ -1420,6 +1423,7 @@ impl State { shell_tone: 1.0, shell_accent: "clay".into(), shell_contrast: 1.0, + shell_template: String::new(), dense: false, celebrate: true, motion: String::new(), diff --git a/src/remote.rs b/src/remote.rs index 7403158..0c44252 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -247,6 +247,8 @@ pub struct View { pub accent: String, pub pin_order: Vec<u64>, pub newer: bool, + /// 一律放行 is on (the phone shows it above the input, with 關閉, as the desktop does). + pub always: bool, pub bots: Vec<Value>, pub approvals: Vec<Value>, pub messages: HashMap<u64, Vec<Value>>, @@ -605,6 +607,8 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { ("GET", []) | ("GET", ["index.html"]) => return page(&req), ("GET", ["screen"]) => return Resp::bytes("text/html; charset=utf-8", SCREEN_PAGE.as_bytes().to_vec()).with_header("Content-Security-Policy", &format!("default-src 'self'; img-src 'self' blob: data:; style-src 'self' 'unsafe-inline'; {}; connect-src 'self' ws: wss:; base-uri 'none'; object-src 'none'; frame-ancestors 'self'", httpd::script_src(SCREEN_PAGE))), ("GET", ["novnc.js"]) => return Resp::bytes("text/javascript; charset=utf-8", NOVNC.as_bytes().to_vec()).with_header("Cache-Control", "public, max-age=86400"), + // (The touchpad and key bar both screens use; asked fresh, so it matches the page.) + ("GET", ["trackpad.js"]) => return Resp::bytes("text/javascript; charset=utf-8", TRACKPAD.as_bytes().to_vec()).with_header("Cache-Control", "no-cache"), ("GET", ["manifest.webmanifest"]) => return Resp::bytes("application/manifest+json", MANIFEST.as_bytes().to_vec()), // (Keeps the page and its icons on the phone; see mobile/sw.js.) ("GET", ["sw.js"]) => return Resp::bytes("text/javascript; charset=utf-8", SW.as_bytes().to_vec()), @@ -704,7 +708,7 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { let tasks: Vec<&Value> = v.tasks.iter().filter(|t| shared(t["bot"].as_u64().unwrap_or(0))).collect(); let out = json!({ "version": v.version, "host": v.host, "person": v.person, "accent": v.accent, - "pin_order": v.pin_order, "newer": v.newer, "bots": bots, "tasks": tasks, + "pin_order": v.pin_order, "newer": v.newer, "always": v.always && role != "member", "bots": bots, "tasks": tasks, "approvals": if role == "member" { vec![] } else { v.approvals.clone() }, "box": crate::cloudbox::run_state().label(), "box_available": crate::cloudbox::available(), @@ -772,6 +776,20 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { out["latest"] = json!(cur.revision); Resp::json(&out) } + // A Mermaid diagram in a chat (a page's have their own path above): drawn here, the same + // way, from the words the phone holds (nothing else is read). + ("POST", ["api", "diagram"]) => { + let v = req.json(); + let src = v["src"].as_str().unwrap_or(""); + if src.trim().is_empty() || src.len() > 20_000 { + return Resp::error(400, "這張圖太大或是空的"); + } + match crate::diagram::svg(src, v["dark"].as_bool().unwrap_or(false)) { + Ok(svg) if !svg_is_plain(&svg) => Resp::error(422, "這張圖畫不出來"), + Ok(svg) => Resp::bytes("image/svg+xml", svg.into_bytes()), + Err(e) => Resp::error(422, &e), + } + } ("GET", ["api", "pages", id, "chart", n]) => { let id: u64 = id.parse().unwrap_or(0); let n: usize = n.parse().unwrap_or(0); @@ -782,6 +800,7 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { }; let Some(src) = crate::pages::mermaid_blocks(&body).into_iter().nth(n) else { return Resp::error(404, "找不到這張圖") }; match crate::diagram::svg(&src, req.query.get("dark").map(|d| d == "1").unwrap_or(false)) { + Ok(svg) if !svg_is_plain(&svg) => Resp::error(422, "這張圖畫不出來"), Ok(svg) => Resp::bytes("image/svg+xml", svg.into_bytes()), Err(e) => Resp::error(422, &e), } @@ -861,7 +880,17 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { // 個人資料與用量 (the owner's): the year in figures, worked out on the brain (stats.rs). ("GET", ["api", "stats"]) => phone_act("stats", json!({}), &role), ("GET", ["api", "sync", "stats"]) => phone_act_for("stats", json!({}), "owner", 40), - ("GET", ["api", "box", "thumb"]) => box_thumb(), + ("GET", ["api", "box", "thumb"]) => box_thumb(req.query.get("bot").map(String::as_str).unwrap_or("")), + // 接管 from the phone: while the person drives the bot's screen, the bot's steps on it wait + // (as 接管 on a screen of this brain does); 交還給 Bot lets them go on. + // (Held for half a minute at a time: the page says so again every ten seconds, so a phone + // that drops off without a word lets go by itself.) + ("POST", ["api", "box", "hold"]) => { + let v = req.json(); + let bot = v["bot"].as_u64().map(|b| b.to_string()).unwrap_or_default(); + crate::cloudbox::hold_for(&crate::cloudbox::screen_for_bot(&bot), v["on"].as_bool().unwrap_or(false)); + Resp::json(&json!({"ok": true})) + } // 看畫面 on 區網: a ticket for the screen's connection, so the login isn't in its address. ("POST", ["api", "vnc", "ticket"]) if !via_relay => { let t = httpd::random_hex(24); @@ -1237,7 +1266,13 @@ pub(crate) fn lan_guard(action: &str, body: &Value, now: impl FnOnce() -> Value, "setting" => match key { // (As phone_act reads them: a missing value is off.) "direct_mode" | "auto_review" => looser(on(&body["value"])), - "notify" => Guard::Keeps, + "notify" | "auto_update" | "garden_reports" | "embed" | "shell_accent" | "shell_contrast" | "language" => Guard::Keeps, + // 一律放行 on, a 智慧模式 card answering itself, a folder bots may read: looser. + "always_approve" => looser(on(&body["value"])), + // (Shorter is looser; this guard can't see the value it has now, so any change is.) + "smart_timeout_secs" => Guard::Loosens, + "doc_folder_add" => Guard::Loosens, + "doc_folder_remove" => Guard::Keeps, "rule_add" | "rule_remove" => match body["list"].as_str().unwrap_or("") { "allow" => looser(key == "rule_add"), "ask" => looser(key == "rule_remove"), @@ -1260,10 +1295,18 @@ pub(crate) fn lan_guard(action: &str, body: &Value, now: impl FnOnce() -> Value, let had: Vec<u64> = now["members"].as_array().into_iter().flatten().filter_map(|m| m["id"].as_u64()).collect(); looser(now["team"] != false && body["value"].as_array().into_iter().flatten().any(|m| !m.as_u64().is_some_and(|m| had.contains(&m)))) } - "allow_remove" | "skills" | "pinned" | "pin_at" | "folder" | "primary" | "strengths" | "not_for" | "unread" | "shape" | "color" | "context" | "thinking" | "step_model" => Guard::Keeps, + "allow_remove" | "skills" | "pinned" | "pin_at" | "folder" | "primary" | "strengths" | "not_for" | "unread" | "shape" | "color" | "context" | "thinking" | "step_model" | "fallbacks" | "speak_replies" | "voice" | "voice_rate" | "voice_lang" => Guard::Keeps, + // A colour of one's own is only a look; a new 起始資料夾 is a folder its files and + // commands reach without asking: looser. + "workdir" => Guard::Loosens, _ => Guard::Unknown, }, // (Renaming is refused before this; reconnecting connects only what is on.) + // A model's key, address and list; letting a local model's pictures go to a cloud one + // (看不到圖時請雲端模型看) is looser. + // A new 服務網址 too: the key kept for that service would go to whatever address it names. + "provider" => looser(on(&body["cloud_eyes"]) || body["base_url"].as_str().is_some_and(|u| !u.trim().is_empty())), + "voice" => looser(body["base_url"].as_str().is_some_and(|u| !u.trim().is_empty())), "mcp" => looser(body["add"].is_object() || (!on(&body["reconnect"]) && !on(&body["remove"]) && on(&body["enabled"]))), "channel" => looser(!on(&body["remove"]) && on(&body["enabled"])), "box" => match body["op"].as_str().unwrap_or("") { @@ -1273,14 +1316,31 @@ pub(crate) fn lan_guard(action: &str, body: &Value, now: impl FnOnce() -> Value, }, // Looking; chats, pages and memories; bots made, imported (with no tools, grants, team or // running routines), deleted or restarted; models and keys; skills; signing in to ChatGPT; - // signing a phone out — none of these moves a guard. - "search" | "detail" | "settings" | "pages" | "export_bot" | "export_transcript" | "import_bot" | "section_move" | "memory" | "app" | "group_chat" | "delete_bot" | "restart_bot" | "react" | "reply" | "resume" | "clear" | "delete_page" | "provider" | "device_remove" | "skill" | "chatgpt" => Guard::Keeps, + // signing a phone out; a workflow looked at, run, stopped or answered (its steps run with + // the bots' own settings, as when its schedule starts it); the 日程, 所有檔案 — none of + // these moves a guard. + "search" | "detail" | "settings" | "pages" | "export_bot" | "export_transcript" | "import_bot" | "section_move" | "memory" | "app" | "group_chat" | "delete_bot" | "restart_bot" | "react" | "reply" | "resume" | "clear" | "delete_page" | "device_remove" | "skill" | "chatgpt" | "workflows" | "workflow" | "schedule" | "library" | "settings_find" => Guard::Keeps, // An action this list doesn't name is refused, not let through (import_bot slipped by // that way with a file's 「team」). A new one has to be put on one side or the other. _ => Guard::Unknown, } } +/// A drawn chart is only shapes and words: no script, no foreign content, no event handler +/// (the phone shows it as a picture; opened on its own it must still run nothing). +fn svg_is_plain(svg: &str) -> bool { + let l = svg.to_ascii_lowercase(); + if l.contains("<script") || l.contains("<foreignobject") || l.contains("javascript:") { + return false; + } + // (An attribute named on…: ` onload=`, ` onclick =`.) + !l.match_indices(" on").any(|(i, _)| { + let rest = &l[i + 3..]; + let name: String = rest.chars().take_while(|c| c.is_ascii_alphabetic()).collect(); + !name.is_empty() && rest[name.len()..].trim_start().starts_with('=') + }) +} + fn phone_act(action: &str, body: Value, role: &str) -> Resp { phone_act_for(action, body, role, 20) } @@ -1319,9 +1379,11 @@ fn voice_speech(req: &Req) -> Resp { } } -/// The bots' computer's screen, small (the phone's 電腦 card and a hand-off), as JPEG. -fn box_thumb() -> Resp { - let Some(img) = crate::cloudbox::thumbnail(480) else { return Resp::error(404, "Bot 的電腦沒有開著") }; +/// The bots' computer's screen, small (the phone's 電腦 card and a hand-off), as JPEG: the screen +/// of the bot asked about (`?bot=`; its own when it has one open), else the shared one. +fn box_thumb(bot: &str) -> Resp { + let own = (!bot.is_empty()).then(|| crate::cloudbox::thumbnail_of(&crate::cloudbox::screen_for_bot(bot), 480)).flatten(); + let Some(img) = own.or_else(|| crate::cloudbox::thumbnail(480)) else { return Resp::error(404, "Bot 的電腦沒有開著") }; let mut out = std::io::Cursor::new(vec![]); match image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 72).encode_image(&image::DynamicImage::ImageRgba8(img).to_rgb8()) { Ok(()) => Resp::bytes("image/jpeg", out.into_inner()), @@ -1337,7 +1399,7 @@ pub fn role_allows(role: &str, method: &str, path: &[&str]) -> bool { // 大腦: the owner's other AnyBots showing this one's bots. "mirror" => sync, "owner" | "admin" => !device && !sync, - "member" => matches!((method, path), ("GET", ["api", "state"]) | ("GET", ["api", "bots", _]) | ("GET", ["api", "pages", ..]) | ("GET", ["api", "file"]) | ("GET", ["api", "preview", ..]) | ("POST", ["api", "bots", _, "send" | "read" | "seen" | "upload"]) | ("POST", ["api", "voice", "transcribe" | "speech"])), + "member" => matches!((method, path), ("GET", ["api", "state"]) | ("GET", ["api", "bots", _]) | ("GET", ["api", "pages", ..]) | ("GET", ["api", "file"]) | ("GET", ["api", "preview", ..]) | ("POST", ["api", "bots", _, "send" | "read" | "seen" | "upload"]) | ("POST", ["api", "voice", "transcribe" | "speech"]) | ("POST", ["api", "diagram"])), _ => false, } } @@ -1387,7 +1449,7 @@ struct Told<T> { /// The state's keys whose fingerprints only change when the app publishes: memoized for the /// newest view (single slot), so waking polls don't re-hash the whole bot list per wake. -const FP_STABLE: [&str; 11] = ["host", "person", "accent", "pin_order", "newer", "bots", "approvals", "models", "sections", "theme", "palettes"]; +const FP_STABLE: [&str; 12] = ["host", "person", "accent", "pin_order", "newer", "always", "bots", "approvals", "models", "sections", "theme", "palettes"]; fn fp_cache() -> &'static Mutex<Vec<(u64, HashMap<String, u64>)>> { static C: std::sync::OnceLock<Mutex<Vec<(u64, HashMap<String, u64>)>>> = std::sync::OnceLock::new(); @@ -1738,17 +1800,25 @@ fn screen(which: &str, s: &Settings) -> Resp { } } -/// The phone taps, types or scrolls on this Mac's screen, as the person, in the pixels of the -/// picture it was sent (shot_size). The bots' computer takes the person's input through VNC. +/// The phone taps, types, scrolls, moves the pointer or drags on this Mac's screen, as the +/// person, in the pixels of the picture it was sent (shot_size). The bots' computer takes the +/// person's input through VNC. fn screen_input(which: &str, v: &Value, s: &Settings) -> Resp { + // The held modifier keys, only the ones a click knows. + let mods = |v: &Value| -> Value { json!(v["modifiers"].as_array().map(|a| a.iter().filter(|m| matches!(m.as_str(), Some("cmd" | "shift" | "option" | "ctrl" | "alt"))).cloned().collect::<Vec<_>>()).unwrap_or_default()) }; let (x, y) = (v["x"].as_f64().unwrap_or(0.0), v["y"].as_f64().unwrap_or(0.0)); let down = v["direction"].as_str().unwrap_or("down") != "up"; let amount = v["amount"].as_i64().unwrap_or(3).clamp(1, 20); match which { "mac" if s.mac_from_phone => { let (name, args) = match v["kind"].as_str().unwrap_or("") { - "click" => ("computer_use_click", json!({"x": x, "y": y, "button": v["button"].as_str().unwrap_or("left"), "count": v["count"].as_u64().unwrap_or(1)})), + // (With the key bar's held keys: ⌘-click, ⇧-click…) + "click" => ("computer_use_click", json!({"x": x, "y": y, "button": v["button"].as_str().unwrap_or("left"), "count": v["count"].as_u64().unwrap_or(1).clamp(1, 3), "modifier_keys": mods(v)})), + // 虛擬觸控板: the pointer moves (no click), and a drag goes along the finger's path. + "move" => ("computer_use_mouse_move", json!({"x": x, "y": y})), + "drag" => ("computer_use_drag", json!({"path": v["path"], "modifier_keys": mods(v)})), "type" => ("computer_use_typing", json!({"value": v["text"]})), + // (A combination too: "cmd+tab", from the key bar.) "key" => ("computer_use_press_key", json!({"key": v["key"]})), "scroll" => ("computer_use_scroll", json!({"x": x, "y": y, "direction": if down { "down" } else { "up" }, "amount": amount})), _ => return Resp::error(400, "不認得的操作"), @@ -3551,6 +3621,8 @@ const PAGE: &str = include_str!("../mobile/index.html"); /// The bots' computer, watched and used in a browser (noVNC; see vnc.rs). const SCREEN_PAGE: &str = include_str!("../mobile/screen.html"); const NOVNC: &str = include_str!("../mobile/novnc.js"); +/// 虛擬觸控板 and the key bar (mobile/trackpad.js), shared by the screen page and the phone page. +pub const TRACKPAD: &str = include_str!("../mobile/trackpad.js"); pub const MANIFEST: &str = include_str!("../mobile/manifest.webmanifest"); /// The app's icon, the same drawing everywhere (icons/anybot.svg is the Mac/Linux one). pub const ICON: &str = include_str!("../mobile/icon.svg"); @@ -3583,6 +3655,45 @@ pub fn page(req: &Req) -> Resp { #[cfg(test)] mod tests { + /// The phone page is one file of plain scripts sharing one global scope: a function or a + /// top-level name declared twice silently replaces the first (a second `dayLabel`, for the + /// 日程, once replaced the chat's — every chat on the phone drew empty). Each name once. + #[test] + fn the_phone_page_names_each_thing_once() { + let mut seen: HashMap<String, usize> = HashMap::new(); + for line in PAGE.lines() { + let l = line.strip_prefix("async ").unwrap_or(line); + let name = if let Some(r) = l.strip_prefix("function ") { + r.split('(').next() + } else if let Some(r) = l.strip_prefix("const ").or_else(|| l.strip_prefix("let ")) { + r.split([' ', '=']).next() + } else { + None + }; + if let Some(n) = name.map(str::trim).filter(|n| !n.is_empty() && n.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '$')) { + *seen.entry(n.to_string()).or_default() += 1; + } + } + let twice: Vec<&String> = seen.iter().filter(|(_, n)| **n > 1).map(|(k, _)| k).collect(); + assert!(twice.is_empty(), "declared more than once in mobile/index.html: {twice:?}"); + } + + /// 虛擬觸控板 (mobile/trackpad.js): a tap clicks, one finger moves the pointer, two fingers + /// scroll or right-click, double tap and slide drags, a long press right-clicks; the key + /// bar's modifiers hold for one key or lock. Run in node when it is there (the gestures are + /// the page's JavaScript; there is no browser in cargo test). + #[test] + fn the_touchpad_turns_fingers_into_mouse_and_keys() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("mobile"); + let Ok(out) = std::process::Command::new("node").arg("trackpad.test.mjs").current_dir(&dir).output() else { + eprintln!("(沒有 node:略過觸控板的手勢測試)"); + return; + }; + let text = String::from_utf8_lossy(&out.stdout); + assert!(out.status.success() && !text.contains("FAIL"), "{text}{}", String::from_utf8_lossy(&out.stderr)); + assert!(text.matches("OK").count() >= 13, "{text}"); + } + use super::*; /// A page holding a state is told only what changed: the keys that did, a bot that didn't as diff --git a/src/stats.rs b/src/stats.rs index db690ab..b7c8a96 100644 --- a/src/stats.rs +++ b/src/stats.rs @@ -207,8 +207,14 @@ pub fn wan(n: u64) -> String { let s = n.to_string(); if n >= 1_000 { format!("{},{}", &s[..s.len() - 3], &s[s.len() - 3..]) } else { s } } - 10_000..=99_999_999 => format!("{:.1}萬", n as f64 / 10_000.0), - _ => format!("{:.2}億", n as f64 / 100_000_000.0), + // (No「.0」, and no decimal at all past a thousand 萬: 3,699萬, not 3699.0萬.) + // (The edges by what they round to: 9,995,000 is 1,000萬, 99,995,000 is 1億.) + 10_000..=9_994_999 => format!("{:.1}萬", n as f64 / 10_000.0).replace(".0萬", "萬"), + 9_995_000..=99_994_999 => { + let s = ((n as f64 / 10_000.0).round() as u64).to_string(); + format!("{},{}萬", &s[..s.len() - 3], &s[s.len() - 3..]) + } + _ => format!("{:.2}億", n as f64 / 100_000_000.0).replace(".00億", "億"), } } @@ -287,7 +293,9 @@ mod tests { #[test] fn counts_and_costs_are_said_plainly() { - assert_eq!((wan(999), wan(9_999), wan(59_934_000), wan(294_000), wan(120_000_000)), ("999".into(), "9,999".into(), "5993.4萬".into(), "29.4萬".into(), "1.20億".into())); + assert_eq!((wan(999), wan(9_999), wan(59_934_000), wan(294_000), wan(120_000_000)), ("999".into(), "9,999".into(), "5,993萬".into(), "29.4萬".into(), "1.20億".into())); + assert_eq!((wan(20_000), wan(100_000_000)), ("2萬".into(), "1億".into())); + assert_eq!((wan(9_994_999), wan(9_995_000), wan(99_994_999), wan(99_995_000)), ("999.5萬".into(), "1,000萬".into(), "9,999萬".into(), "1億".into())); assert_eq!(cost_words(0, 5, 5), "未定價"); assert_eq!(cost_words(1_230_000, 0, 4), "US$1.23"); assert_eq!(cost_words(1_230_000, 2, 4), "US$1.23(另有 2 次呼叫未定價)"); diff --git a/src/theme.rs b/src/theme.rs index 64ea292..5b1510e 100644 --- a/src/theme.rs +++ b/src/theme.rs @@ -7,6 +7,11 @@ use eframe::egui::Color32; // --fs-* --lh-read --sp-* --r-*;`the_phone_uses_the_same_design_spec` 比對兩邊)。 // 依 Claude 的設計原則:定一套字級並守住、卡片樣式按角色用、重複的元素一致。 // 畫面上的字級、圓角只從這裡拿(`no_new_literal_sizes_radii_or_colours` 看守)。 +// 三條第一性原理(2026-11 這一版的樣子,電腦和手機一樣): +// 1. 浮的東西用影子浮起來(輸入框、畫布上的工具列、選單:`shade`),平放的用底色和髮絲線分組, +// 不畫粗框。 +// 2. 按鈕是膠囊、圓鈕是圓的:形狀本身就說「可以按」。一個地方只有一顆實心按鈕。 +// 3. 顏色只給意思:強調色、要你處理的黃、壞事的紅;能回頭的停止、移除用紅字不用紅底。 /// 字級(px)。介面用思源黑體,閱讀(回答、頁面)用思源宋體。 pub mod fs { @@ -98,6 +103,9 @@ pub struct Palette { pub grid: Color32, /// Up / good (charts, stat tiles). Down and bad is `danger`. pub up: Color32, + /// The shadow under what floats over the page (the input, a canvas toolbar): things that + /// float are lifted by a soft shadow, not drawn round with a line (手機的 --shade). + pub shade: Color32, } const fn hexa(r: u8, g: u8, b: u8, a: u8) -> Color32 { @@ -134,6 +142,7 @@ pub const LIGHT: Palette = Palette { ], grid: hexa(0x25, 0x22, 0x1f, 0x10), up: hexa(0x2e, 0x7d, 0x3f, 0xff), + shade: hexa(0x24, 0x1f, 0x1a, 0x1c), }; // From the original's renderer (index.eager-common: appearance primitives dark neutral/0..6 and the @@ -172,6 +181,7 @@ pub const DARK: Palette = Palette { ], grid: hexa(0xf2, 0xf0, 0xeb, 0x14), up: hexa(0x6f, 0xb9, 0x7d, 0xff), + shade: hexa(0x00, 0x00, 0x00, 0x60), }; /// A bot's colour as a quiet background (its selected tile, its cards): a little of it over the @@ -212,6 +222,52 @@ const fn rgb(r: u8, g: u8, b: u8) -> Color32 { Color32::from_rgb(r, g, b) } +/// 風格 (設定 › 一般 › 外觀): a whole look in one choice — its ink, paper and accent in light and +/// in dark — and the chat's backdrop (none, dots, grid, waves). Picking a 強調色 or moving the +/// 色調 dial after goes back to 自訂 (the dials). The desktop and the phone wear the same one. +pub struct Template { + pub id: &'static str, + pub name: &'static str, + pub about: &'static str, + /// (ink, paper, accent) in light, and in dark. + pub light: (Color32, Color32, Color32), + pub dark: (Color32, Color32, Color32), + /// The chat's backdrop: "" (plain), "dots", "grid" or "waves". + pub backdrop: &'static str, +} + +pub const TEMPLATES: [Template; 8] = [ + Template { id: "paper", name: "紙", about: "溫暖的紙和墨,黏土色點綴(預設)", light: (rgb(0x25, 0x22, 0x1f), rgb(0xfa, 0xf9, 0xf6), rgb(0xc0, 0x62, 0x44)), dark: (rgb(0xf2, 0xf0, 0xeb), rgb(0x1e, 0x1d, 0x1b), rgb(0xd8, 0x83, 0x66)), backdrop: "" }, + Template { id: "night", name: "夜", about: "冷靜的灰,一點靛藍", light: (rgb(0x20, 0x21, 0x24), rgb(0xf6, 0xf6, 0xf8), rgb(0x5e, 0x6a, 0xd2)), dark: (rgb(0xf0, 0xf0, 0xf2), rgb(0x10, 0x11, 0x12), rgb(0x7c, 0x87, 0xe0)), backdrop: "" }, + Template { id: "ink", name: "墨", about: "只有黑和白,最安靜", light: (rgb(0x0d, 0x0d, 0x0d), rgb(0xf9, 0xf9, 0xf9), rgb(0x0d, 0x0d, 0x0d)), dark: (rgb(0xf7, 0xf7, 0xf7), rgb(0x0a, 0x0a, 0x0a), rgb(0xf7, 0xf7, 0xf7)), backdrop: "" }, + Template { id: "moss", name: "苔", about: "綠色的紙,背景有點點", light: (rgb(0x1f, 0x24, 0x20), rgb(0xf4, 0xf6, 0xf2), rgb(0x4a, 0x7c, 0x59)), dark: (rgb(0xec, 0xf0, 0xea), rgb(0x15, 0x18, 0x15), rgb(0x7f, 0xaa, 0x8a)), backdrop: "dots" }, + Template { id: "ocean", name: "海", about: "藍色的海,背景有波浪", light: (rgb(0x13, 0x29, 0x3d), rgb(0xf2, 0xf7, 0xfb), rgb(0x1f, 0x7a, 0xb8)), dark: (rgb(0xe3, 0xee, 0xf7), rgb(0x0c, 0x18, 0x22), rgb(0x5f, 0xb0, 0xe6)), backdrop: "waves" }, + Template { id: "candy", name: "糖", about: "粉粉的糖果色,背景有點點", light: (rgb(0x3b, 0x23, 0x40), rgb(0xff, 0xf5, 0xfa), rgb(0xd6, 0x45, 0x7f)), dark: (rgb(0xf7, 0xe6, 0xf0), rgb(0x1f, 0x14, 0x20), rgb(0xf0, 0x7a, 0xab)), backdrop: "dots" }, + Template { id: "sunset", name: "夕陽", about: "橘紅的傍晚,暖暖的", light: (rgb(0x3a, 0x22, 0x14), rgb(0xff, 0xf6, 0xee), rgb(0xe0, 0x6a, 0x2c)), dark: (rgb(0xf6, 0xe9, 0xde), rgb(0x1d, 0x13, 0x0d), rgb(0xf2, 0x9a, 0x5c)), backdrop: "waves" }, + Template { id: "terminal", name: "終端機", about: "黑底綠字,背景有格線", light: (rgb(0x0e, 0x2a, 0x12), rgb(0xf1, 0xf7, 0xee), rgb(0x2d, 0x8a, 0x3e)), dark: (rgb(0xa8, 0xf0, 0xa0), rgb(0x07, 0x10, 0x0a), rgb(0x4f, 0xe3, 0x6a)), backdrop: "grid" }, +]; + +pub fn template(id: &str) -> Option<&'static Template> { + TEMPLATES.iter().find(|t| t.id == id) +} + +/// The shell to wear: the 風格 picked (`template`), else the three dials (`shell`). +pub fn palette_for(template_id: &str, tone: f32, accent: &str, contrast: f32, dark: bool) -> Palette { + match template(template_id) { + Some(t) => { + let (ink, paper, acc) = if dark { t.dark } else { t.light }; + let (danger, up) = if dark { (rgb(0xe2, 0x6e, 0x6e), rgb(0x6f, 0xb9, 0x7d)) } else { (rgb(0xb4, 0x2a, 0x2a), rgb(0x2e, 0x7d, 0x3f)) }; + build(ink, paper, acc, danger, up, contrast.clamp(0.6, 1.5), dark) + } + None => shell(tone, accent, contrast, dark), + } +} + +/// The chat's backdrop of a 風格 ("" for none, or 自訂). +pub fn backdrop(template_id: &str) -> &'static str { + template(template_id).map(|t| t.backdrop).unwrap_or("") +} + /// The accents the person can pick (設定 › 一般): name, 中文名, light, dark. pub const ACCENTS: [(&str, &str, Color32, Color32); 8] = [ ("clay", "黏土", rgb(0xc0, 0x62, 0x44), rgb(0xd8, 0x83, 0x66)), @@ -272,6 +328,7 @@ fn build(ink: Color32, paper: Color32, accent: Color32, danger: Color32, up: Col chart_cat: cat, grid: with(ink, (14.0 * contrast) as u8), up, + shade: if dark { with(rgb(0, 0, 0), 0x60) } else { with(mix(ink, rgb(0, 0, 0), 0.4), (28.0 * contrast) as u8) }, } } @@ -391,6 +448,29 @@ pub fn is_dark(p: Palette) -> bool { (0.2126 * p.pane.r() as f32 + 0.7152 * p.pane.g() as f32 + 0.0722 * p.pane.b() as f32) < 128.0 } +#[cfg(test)] +mod template_tests { + use super::*; + + /// Every 風格 reads: its text stands off its page in light and in dark, its sidebar steps + /// the right way, and 紙 is the shipped default exactly. + #[test] + fn every_template_reads_in_light_and_dark() { + let luma = |c: Color32| 0.2126 * c.r() as f32 + 0.7152 * c.g() as f32 + 0.0722 * c.b() as f32; + for t in &TEMPLATES { + let l = palette_for(t.id, 1.0, "clay", 1.0, false); + let d = palette_for(t.id, 1.0, "clay", 1.0, true); + assert!(luma(l.pane) - luma(l.text) > 150.0, "{} light", t.id); + assert!(luma(d.text) - luma(d.pane) > 150.0, "{} dark", t.id); + assert!(!is_dark(l) && is_dark(d), "{}", t.id); + assert!(["", "dots", "grid", "waves"].contains(&t.backdrop), "{}", t.id); + } + assert_eq!(palette_for("paper", 1.0, "clay", 1.0, false).pane, LIGHT.pane); + // No 風格 (自訂): the dials, as before. + assert_eq!(palette_for("", 0.0, "indigo", 1.0, false).accent, shell(0.0, "indigo", 1.0, false).accent); + } +} + #[cfg(test)] mod dark_tests { use super::*;