diff --git a/FEATURES.md b/FEATURES.md index 1e9eb0c..826926e 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -136,8 +136,8 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 - 側邊欄上面的放大鏡:提示文字改成「搜尋 Bot 和訊息」。打字時,上面照舊列出名字或說明相符的 Bot,下面多一區「訊息」。 - 找的範圍:每個 Bot 目前的對話和「過去的對話」裡,你和 Bot 說的話,以及附加檔案的檔名(標「檔案:」)。工具的結果和摘要不找(讀過一次的網頁會把別的都蓋掉)。不分大小寫。 -- 每一筆兩行:Bot 的名字(在過去的對話裡的加「· 過去的對話」)和時間(「剛剛」「昨天 09:33」「11/3」),下面是那句話裡相符處前後的一行,你說的前面加「你:」。最新的在最上面,最多列 40 筆,超過會提示多打幾個字。 -- 點一筆:打開那個 Bot,聊天捲到那則訊息,並用黃色亮一下(約 1.8 秒淡掉)。在過去的對話裡的,會先把那段對話換回來(目前的對話收進「過去的對話」最上面);那個 Bot 正在工作時不換,改提示「「(名字)」正在工作。等它做完,再打開過去的對話。」 +- 每一筆兩行:Bot 的名字(在過去的對話裡的加「· 那段對話的名字」)和時間(「剛剛」「昨天 09:33」「11/3」),下面是那句話裡相符處前後的一行,你說的前面加「你:」。最新的在最上面,最多列 40 筆,超過會提示多打幾個字。 +- 點一筆:打開那個 Bot,聊天捲到那則訊息,並用黃色亮一下(約 1.8 秒淡掉)。在過去的對話裡的,會先把那段對話換回來(目前的對話收進「過去的對話」最上面);那個 Bot 正在工作(或還有摘要、支線、交辦的回報要回到目前這段)時不換,改提示要等什麼,例如「「(名字)」正在工作。等它做完(或先按停止),再換對話。」 - 連到別台大腦的電腦上也能用(找的是大腦的聊天)。手機一樣有(擁有者):首頁放大鏡打字,相符的 Bot 在上,下面「聊天裡」列訊息和檔名(含過去的對話);點一筆打開那個聊天,捲到那則訊息亮一下(太早、手機沒留的會說);過去的對話先問要不要換回來。 ### 任務(2026-11-20) @@ -1734,7 +1734,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - `context: fork`:使用者打「/名稱 …」時不在主對話做,改開一條支線(跟 /btw 一樣,做完回報),主對話不會被它的步驟塞滿。Bot 自己用 use_skill 讀它時照常在這一輪做。 - **用 / 指定技能**(現在只打「/」只列指令,打字後才找這個 Bot 自己的技能,見「「/」清單只放指令」):輸入框第一個字打「/」,上面就列出開著的技能(名稱開頭符合的先、名稱含有的次之、再來是說明裡有的,例如「/簡報」找到 pptx);點一下,或 ↑↓ 選、Enter/Tab 帶入,輸入框變成「/pptx 」接著打要做的事,Esc 關掉清單。電腦和手機都有,Bot 正在做事時不列(那時打的字會併進正在做的事)。送出後由大腦認出「/名稱」,在這則訊息後面替模型加一行「使用者用 /pptx 指定了技能「pptx」:先用 use_skill 讀出它的完整做法」,所以從手機、訊息管道打的也算;不是技能名稱的(例如 /Users/… 路徑)不加。新加的技能(技能市集、GitHub 安裝、Bot 存的或自己學會的、「教我做」)馬上就在清單裡:電腦直接讀技能名單(大腦的螢幕讀的是大腦同步過來的那份);手機每次打出新的「/」會向大腦再拿一次名單,拿到前先列手上已有的。篩選本身不連網,也不多送東西給模型(技能清單本來就在系統指示裡)。 - **/goal 目標**(照 Claude Code 的 /goal 做):給 Bot 一個「做到什麼程度才算完成」的條件,它就一輪接一輪做下去,不用每一步都叫它。關鍵是**做事的模型不能自己宣布完成**:每一輪結束後,另一個模型(Bot 的「執行步驟用的模型」,通常是快速模型;設成「關閉」就用 Bot 自己的模型)只看這段對話(Bot 說的話、用了哪些工具、工具回了什麼),判斷條件成立了沒有。 - - **用法**:「/goal 所有測試都通過,而且 clippy 沒有新的警告」設定並馬上開始做(已經有目標就換掉);「/goal」看目前的目標、做了多久、檢查了幾輪、最近一次檢查的理由;「/goal clear」清除(stop、off、reset、none、cancel、清除、取消、停止也可以)。在 / 清單最上面,標「指令和技能」。電腦、大腦的螢幕、手機打的都算,由大腦處理;訊息管道(Slack、Telegram…)和團隊成員打的不算指令,別人不能替你設目標。條件最多 4000 字;群組聊天還不能設目標。「清除聊天記錄」和「開始新對話」會連目標一起清掉;分享 Bot 的檔案不含目標。 + - **用法**:「/goal 所有測試都通過,而且 clippy 沒有新的警告」設定並馬上開始做(已經有目標就換掉);「/goal」看目前的目標、做了多久、檢查了幾輪、最近一次檢查的理由;「/goal clear」清除(stop、off、reset、none、cancel、清除、取消、停止也可以)。在 / 清單最上面,標「指令和技能」。電腦、大腦的螢幕、手機打的都算,由大腦處理;訊息管道(Slack、Telegram…)和團隊成員打的不算指令,別人不能替你設目標。條件最多 4000 字;群組聊天還不能設目標。「清除聊天記錄」「開始新對話」和換到另一段對話會連目標一起清掉(換走時那段留一行說停了哪個目標);分享 Bot 的檔案不含目標。 - **檢查的結果**:還沒達成 → AnyBot 自己送出一則標「目標」的「還沒達成:(理由)」開始下一輪,理由就是下一步該做什麼;達成 → 聊天裡一行「目標達成:…(N 輪 · 多久)」,目標清掉,這個聊天上撒一下彩帶(慶祝動畫,設定 › 一般可關);做不到 → 「目標做不到,已清除:…」;Bot 在等你回答或動手(登入、付款、做決定)→「目標暫停,等你回覆:…」,不會一直空轉。 - **煞車**(比 Claude Code 嚴,因為 AnyBot 一輪可以做很多步、用的是你自己的金鑰):一個目標做 20 輪還沒達成就暫停問你;連續 3 輪都沒有用任何工具(只是在說話)就暫停;連續兩輪檢查說差的是同一件事(用字稍有不同也算)就暫停「同樣的問題連續兩次」,再做一輪多半還是卡在那裡(參考 grok-build);這一輪出錯、你按了停止(兩輪之間正在檢查時按也算)、檢查的模型沒回應、AnyBot 重新啟動過,也都是暫停。重新啟動後按中斷卡片上的「繼續」,目標也跟著接下去。暫停時目標還在,**傳一句話(例如「繼續」)就接著做**,用完 20 輪的再給 20 輪;不要了就 /goal clear。 - **看得到的地方**:輸入框上方那張臉的同一行右邊一個目標圖示(不另外佔一行,免得擋住對話;暫停時變灰),滑過去看「目標進行中 · 12 分 · 3 輪」(檢查時是「正在檢查有沒有達成…」,暫停時是「目標暫停 · 原因」)、條件和最近一次的理由,點一下打開同樣的說明和「清除目標」。目標、計畫、一律放行同時開著時三個圖示排成一排。AnyBot 自己的那幾行(達成、暫停、狀態)在聊天中間用小字顯示,不是 Bot 的話,**不會送給模型**,也不算檢查的證據。手機一樣,大腦的螢幕看到的是大腦同步過來的。 @@ -1756,7 +1756,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - **計畫卡**:Bot 用 submit_plan 交出計畫,聊天裡是一張「計畫」卡:一兩句摘要、照順序的步驟(通常 3 到 7 步,每步是一個看得到的結果,最後一步是驗證)、「怎麼確認做對了」、「注意」(假設、風險、花錢、對外送出、不能復原的)。只寫它建議的那一個做法。研究顯示錯的計畫比沒有計畫更糟,所以要求它根據查到的事實、寧可短而對。 - **核准**:聊天最下面的問題卡「照這個計畫做嗎?」(跟聊天一起捲):「開始照計畫做」、「先不要」,或直接打字寫要改哪裡(它改完再交一張新卡,舊卡變「已修改,見下面新版」)。在卡片外傳訊息也算要修改;只有按「開始照計畫做」才算核准,不會等太久自己核准。按「先不要」或略過,計畫就取消,什麼都沒做。 - **照計畫做**:核准後同一輪接著做(不用再傳訊息),所有工具打開,第 1 步自動標成進行中;它每做完一步用 update_plan 更新一次(整份清單、同時只有一步進行中;不用每個小動作都更新——Manus 發現打勾佔了三分之一的動作)。計畫和實際不符就改清單並在訊息裡說為什麼,大改先問。卡上的步驟跟著打勾(✓ 做完、▸ 進行中、– 略過),輸入框上方臉的同一行右邊一個計畫圖示,旁邊寫「2/5」,滑過去看「照計畫做 · 2/5 · 現在這一步」和整份清單,點一下有「取消計畫」。全部做完那一輪結束時留一行「計畫完成:5 步都做完了。」,計畫清掉。 - - **只管你自己的訊息**:例行任務、訊息管道和團隊成員的訊息照平常做,不受計畫模式限制。照計畫做的期間每一輪都帶著這份計畫(像 Claude Code 把核准的計畫交回給模型),所以聊別的事前先取消。清除聊天記錄、開始新對話會連計畫一起清掉;分享 Bot 的檔案不含計畫。重開 AnyBot 計畫還在;還沒核准時重開,傳一句話它就接著規劃。 + - **只管你自己的訊息**:例行任務、訊息管道和團隊成員的訊息照平常做,不受計畫模式限制。照計畫做的期間每一輪都帶著這份計畫(像 Claude Code 把核准的計畫交回給模型),所以聊別的事前先取消。清除聊天記錄、開始新對話、換到另一段對話會連計畫一起清掉;分享 Bot 的檔案不含計畫。重開 AnyBot 計畫還在;還沒核准時重開,傳一句話它就接著規劃。 - 手機一樣:計畫卡、問題卡都有;目標和計畫在輸入框上方是一排小圖示(計畫旁邊寫「2/5」),點一下展開那一行和「清除目標」/「取消計畫」。 - **外觀(Bot 是主角)**:介面本身安靜(黑、白、灰),顏色和動作都留給 Bot。 - **字型**:跟 Apple 的 App 一樣,介面和讀的文字(Bot 的回答、頁面)都用 macOS 自己的字:英文 SF Pro、中文蘋方(PingFang TC),粗體用半粗(Semibold,比 Bold 輕鬆)。沒有蘋方的電腦(Windows、Linux)用包在 App 裡的思源黑體。程式碼用系統的等寬字。沒有字型選項。(以前回答用思源宋體,讀起來正式、重。) @@ -1830,7 +1830,10 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - **每一步都標著是誰說的**:以前成員的回答做了好幾步(用了工具)時,後面的步驟會掉名字,其他成員只看到「其他成員」;現在每一步都記得是哪個成員。 - **表情回應**:滑鼠移到 Bot 的回答上,可以按 👍 ❤️ 😂 🎉 🙏;回應顯示在回答下面,按一下可以拿掉;Bot 下一回合會知道你的回應。 - **引用**:回答下的「引用」:輸入框上方出現「引用:…」(左邊一條強調色),送出時引用的內容會變成 Markdown 引言放在你的訊息前面。 -- **討論串**:Bot 選單 →「開始新對話」:目前的對話收起來(用第一則訊息當標題,最多保留 50 個),聊天重新開始;「過去的對話」可以切回任何一個(目前的會先收起來)。 +- **討論串**:Bot 選單 →「開始新對話」:目前的對話收起來(沒取名的用第一則訊息當標題,最多保留 50 個),聊天重新開始;「過去的對話」可以切回任何一個(目前的會先收起來)。 + - **對話欄**:同一個 Bot 做好幾個專案時,不用進選單找。聊天右上(⋯ 和「分享」中間)的「對話」打開右邊的對話欄,再按一次關掉;對話取了名,按鈕上就寫名字。欄裡最上面是目前的對話(粗體、淺底),下面是過去的對話,最新的在上、寫多久以前;點一段就換過去(目前的收進過去的對話最上面),欄頂的 + 開始新對話。還有東西要回到這段時不換,說要等什麼:Bot 在工作或還有排著的訊息(「正在工作。等它做完(或先按停止),再換對話」)、正在整理摘要(/compact)、支線還在做或還沒開始、同事正在做它交辦的事(寫出是哪位同事,到那裡按停止就會回報「沒有做完」;還排著沒開始的不擋,回報落在那時開著的那段)——以前照換,摘要或回報就落進換過去的那段(摘要還會讓模型看不到那段較早的話)。Bot 選單的「過去的對話」、搜尋、手機都一樣(以前選單會先停下它);「開始新對話」照舊停下正在跑的那一輪,其餘幾樣也要等(連到大腦的電腦上按,由大腦決定:不開新對話時那一輪也不會被停掉)。換對話和開始新對話一樣,「還原上一個答案」不帶過去(以前換過去再按,會把上一段的舊答案塞進這段),這段的目標(/goal)和計畫(/plan)停掉:它們只屬於這段對話,以前會被帶到另一段(下一輪照著上一段的計畫做);停之前在這段留一行「換到另一段對話,這段的目標「…」和計畫「…」(做到 N/M 步)停了…回到這裡要接著做,再打 /goal 或 /plan。」對話欄開著的話重開 AnyBot 還開著,每台電腦自己記(視窗太窄、放不下在聊天旁邊時先不開,按「對話」才浮出來);聊天標題太窄時按鈕只寫「對話」,滑過看名字;點 Bot 名字開對話詳細資訊時,對話欄讓出位置,關掉詳細資訊就回來(按 ✕ 或再按「對話」才是真的關掉)。以前要按 ⋯ ›「過去的對話」› 再找。 + - **取名**:以前每段只顯示第一句話。對話欄的每列滑過出現 ✎(目前的那列一直有),或雙擊目前的那列、右鍵「重新命名」;Enter 或點別處就存,Esc 不存,空白回到第一句話。名字一行、最多 40 字,跟著對話走:收進過去的對話、再打開都帶著,「/fork」沒給名字時叫「分岔:這個名字」(分岔的再分岔不疊成「分岔:分岔:」),搜尋到過去對話裡的訊息時寫「Bot · 這個名字」。也可以在聊天裡請 Bot 取(「這段叫網站改版」「把報價單那段改叫 Q3」):工具 `list_conversations` 列出目前的和過去的對話(名字、多久以前、幾則),`rename_conversation` 為目前這段、或用名字指定的過去那段取名(支線不能);`switch_conversation` 換到用名字指定的過去那段,或 `new: true` 開始新對話(`name` 為換過去的那段取名:「開個新對話叫網站改版」)——這一輪和接著要在這段做的(來不及插話的訊息、AnyBot 的更正、群組的下一位、交辦的回報)都做完、Bot 閒下來才換,回覆留在原來那段,不在一輪做到一半時換掉聊天;那之前按了停止、清除聊天記錄、重新啟動,或在它閒著時又傳了新訊息(還要留在這段),就不換(以前在停止的收尾裡就換了,清除聊天記錄清到的是換過去的那段);要等支線、同事回報時可能過幾分鐘才換;同一輪先換再改那段的名字也找得到;那段那時已經不在(換過、改了名)就在聊天裡說沒換。名字不會放進 Bot 讀的對話裡;記憶、指示、檔案還是這個 Bot 共用的。 + - **手機**:聊天標題列多一顆 🕘「對話」(⋯ ›「對話」同一個):「目前的對話」那列點了取名,下面是過去的對話(最新 20 段;以前給的是最舊的 20 段、舊的在上),點一段選「回到這段對話」或「重新命名」;取了名的對話,標題下那行寫名字;團隊成員看不到 🕘(大腦本來就不讓成員換對話)。在另一台裝置換過、收過或改過名、清單位置變了,改名和換回去(對話清單和手機搜尋結果都是)照樣找到點的那段(認最後一則的時間和顯示的名字),那段已經被打開或改了名就不動;為目前的對話取名時,別台已經換成另一段也不動。手機搜尋結果點到過去的對話,Bot 工作中也不換(頁面太舊沒擋到的,大腦不換、在聊天裡留一行);大腦的 AnyBot 還是舊版時,手機的對話清單不提供命名;那筆在 Bot 名字旁寫那段對話的名字(以前一律寫「過去的對話」)。成員看不到擁有者的對話名和段數。清除聊天記錄帶著畫面上那段的名字:手機或連到大腦的電腦還顯示舊的那段、大腦那邊已經換了(別台換的、或 Bot 答應的換對話剛發生),就不清,說開著的已經換成哪段(以前會清掉換過去的那段,救不回來)。 - **匯出文字記錄**:Bot 選單 →「匯出文字記錄…」存成 Markdown(你的訊息、附件名稱、Bot 的回答、工具步驟、摘要)。 - **錄會議**:Bot 選單 →「錄會議…」:用麥克風錄音(最長 2 小時,估計值),頂部顯示紅色「● 正在錄會議 · 結束」。結束後轉成文字記錄,當作附件放進輸入框,並幫你打好「這是剛才會議的文字記錄,請整理:重點、做了哪些決定、待辦事項(誰、做什麼、什麼時候)。」,由你按送出。 @@ -2307,7 +2310,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 輸入:工作中再傳是插話(顯示排隊)、空白時送出鍵變停止、附加照片/檔案(最大 30 MB)、拍照、語音輸入、建議問題; - 記憶小卡片(擁有者):打字停 300 ms 後出現在輸入框上方,排成一行可以左右滑,和電腦版一樣預先勾好、點一下加入或拿掉; - 你的訊息下面有「帶了 N 條記憶」,點開看是哪幾條; - - 上方「⋯」:新對話、過去的對話、清除對話、對話詳細資訊、Bot 設定。 + - 上方 ✎ 新對話、🕘 對話(取名、換回過去的對話),「⋯」:對話、清除對話、對話詳細資訊、Bot 設定。 - 對話詳細資訊:動態、記憶(只有擁有者)、例行任務、資料庫(頁面、記憶、檔案)、電腦、稽核、成員(群組)。 - 「記憶」分頁和電腦版的記憶頁一樣:統計、搜尋、新增、篩選、整理建議、每條的釘選/編輯/忘記/還原。 - Bot 設定:名稱、說明、指示、外型和顏色、模型、電腦、電腦工具開關、上下文長度、允許規則、釘選、主要 Bot、分區、範例、重新啟動、清除對話、刪除。 diff --git a/docs/feature-map/README.md b/docs/feature-map/README.md index 887c3af..ed7d80b 100644 --- a/docs/feature-map/README.md +++ b/docs/feature-map/README.md @@ -72,6 +72,7 @@ Bot 讀得到的是開頭、子功能、使用者怎麼到、Bot 那一行和沒 ### 跟 Bot 說話 - [chat](chat.md):輸入框、/ 指令、插話、停止、重新產生、附件、長對話。 +- [threads](threads.md):一個 Bot 的好幾段對話:右邊的對話欄、取名、換回過去的對話、手機的 🕘。 - [cards](cards.md):問題卡、生活卡片、表情、重新看圖。 - [bots](bots.md):側邊欄、搜尋、Bot 選單、建立 Bot。 - [profile](profile.md):Bot 設定、個人檔案、能力、頭像。 diff --git a/docs/feature-map/chat.md b/docs/feature-map/chat.md index 478ce41..5cdb7a0 100644 --- a/docs/feature-map/chat.md +++ b/docs/feature-map/chat.md @@ -4,7 +4,7 @@ ## 子功能 -- `chat-layout` 版面:左邊 Bot 清單(拖到比 210 px 窄收成頭像直欄),右邊聊天;點頂部 Bot 名稱開右側面板(「動態」「資料庫」)。 +- `chat-layout` 版面:左邊 Bot 清單(拖到比 210 px 窄收成頭像直欄),右邊聊天;點頂部 Bot 名稱開右側面板(「動態」「資料庫」),右上「對話」開對話欄。 - `chat-input` 輸入框:Enter 送出、Shift+Enter 換行(「1. 」清單裡自動接下一項);↑ 找回上一則;草稿每個 Bot 各存一份;框最高長到這欄放得下(聊天留一段),再多就捲;打字停一下,上方出現「帶入記憶」小卡片([memory](memory.md))。 - `chat-commands` 打「/」列出 /goal、/plan、/btw、/always-approve(一律放行,見 [autonomy](autonomy.md))、/usage(最近一天、一週的 token 用量)、/doctor(診斷,見 [garden](garden.md))、/context(模型可讀用量)、/compact(現在就把較早的整理成摘要)、/fork(分岔:這段對話到這裡存一份進「過去的對話」);打「@」列出其他 Bot。 - `chat-steer` 插話:Bot 工作中照樣送出,下一步就讀到(附檔一起),下方寫「已排入「…」」;來不及讀的變成下一輪。它在做例行任務、工作流或回外面的訊息時,你的話等那輪做完才回,不混進去。 @@ -22,9 +22,9 @@ - 點側邊欄的 Bot;⌘1–⌘9 切到前九個。 - 輸入框左邊的 +:「附加檔案」「教它一項任務」,下面是換模型(見 [models](models.md));右邊是語音輸入和送出鈕。 -- Bot 選單(右鍵 Bot,或聊天右上角「更多」):「開始新對話」把目前的收進「過去的對話」;/fork 留一份分岔,打開分岔時目前的自動收進去;「清除聊天記錄」不會再問;「重新啟動這個 Bot」卡住時用,記錄和檔案保留。 +- Bot 選單(右鍵 Bot,或聊天右上角「更多」):新對話、過去的對話見 [threads](threads.md);「清除聊天記錄」不會再問;「重新啟動這個 Bot」卡住時用,記錄和檔案保留。 - 你的最後一則沒有回覆時,下面有「還沒有回覆」和「重新傳送」;被 AnyBot 關掉打斷的回合有「繼續」。 -- 手機:標題列 ✎「開始新對話」和「更多」([phone](phone.md));按住一則訊息是訊息選單(表情、「複製」「選取文字」「引用回覆」…)。 +- 手機:標題列 ✎「開始新對話」、🕘「對話」和「更多」([phone](phone.md));按住一則訊息是訊息選單(表情、「複製」「選取文字」「引用回覆」…)。 ## 怎麼操作(verify-anybot) diff --git a/docs/feature-map/goal.md b/docs/feature-map/goal.md index d999a37..88aceeb 100644 --- a/docs/feature-map/goal.md +++ b/docs/feature-map/goal.md @@ -45,6 +45,6 @@ - 評審只讀最近約 2 萬 4 千字的對話;太早做的事它看不到,條件要寫成現在看得出來的狀態。 - 條件寫得含糊(「做好一點」)評審很難判,會一直「還沒」直到滿 20 輪。 - 目標會一輪接一輪自己用掉模型額度;不要了記得「/goal clear」。 -- 清除聊天記錄或開始新對話,目標會跟著清掉。 +- 清除聊天記錄、開始新對話或換到另一段對話([threads](threads.md)),目標會跟著清掉;換走時那段留一行說停了哪個目標。 - Bot 用文字問使用者會讓這輪結束,目標停在「等你回覆」;直到使用者回覆前不會自己繼續。 - (驗證)條件裡的 `[[call …]]` 每一輪都會再叫一次(目標的說明帶著條件);假模型沒有指定時,評審照字回聲、永遠「還沒」。 diff --git a/docs/feature-map/phone.md b/docs/feature-map/phone.md index 85b9b07..1789bae 100644 --- a/docs/feature-map/phone.md +++ b/docs/feature-map/phone.md @@ -8,7 +8,7 @@ - `phone-cards` 手機上的卡(允許、需要處理、問題卡)只答它畫出來的那一張:那張已經在電腦或另一支手機上回答、被停止、或換成下一張時,按了不算,聊天裡寫「手機上的回答沒有用上…」;開了很久沒重新整理的舊頁面也一樣。螢幕電腦上的卡也是;比大腦舊的螢幕電腦答不了任何卡,要在那台 設定 › 更新 換新版(重新整理沒用)。支線的卡沒用上時,寫在主線的聊天。 - `phone-look` 長相(字級、間距、圓角和電腦版同一組數字):回答不放在泡泡裡,像文件一樣直接排在畫面上,跟介面同一種字(iPhone 是 SF Pro 加蘋方)、16px、行距寬;表格只有橫向細線、數字欄靠右,提示框([!NOTE] 等)同一種淡底、只有圖示依種類上色,程式碼是淡底圓角塊。標題用半粗體。手機沒有字型選項。 - `phone-colors` 顏色跟電腦版一樣:電腦上 設定 › 一般 › 外觀 的主題(淺色/深色/跟隨系統)、底色、強調色、對比,手機照著穿;手機自己的「外觀」選「跟著電腦」(預設)、「跟著手機」、「淺色」、「深色」。狀態列的顏色跟著畫面。舊版電腦沒送顏色時用內建的「紙」。 -- `phone-claude` 像 Claude 的手機 App:上面一條簡單的標題列(Bot 名稱,第二行是它在做什麼或用哪個模型),輸入框是底部一張圓角卡片,回答下面只有時間和複製/重新產生/⋯;思考和步驟不在聊天裡,長按(右鍵)回答或 ⋯ ›「顯示步驟」才展開(工作中點「正在…」);按鈕和點的地方至少 44px;清單每列的說明只有一行(太長以 … 結尾);顏色少,強調色只用在連結、選取和新訊息的點。 +- `phone-claude` 像 Claude 的手機 App:一條簡單的標題列(Bot 名稱,第二行是它在做什麼,或對話的名字和模型),輸入框是底部一張圓角卡片,回答下面只有時間和複製/重新產生/⋯;思考和步驟不在聊天裡,長按(右鍵)回答或 ⋯ ›「顯示步驟」才展開(工作中點「正在…」);按鈕和點的地方至少 44px;清單每列的說明只有一行(太長以 … 結尾);強調色只用在連結、選取和新訊息的點。 - `phone-net` 網路慢或斷線都不擋操作:存過這台電腦的資料,打開 App 就用上次的內容進去,不等網路,連上後只補變了的;浮著「離線中:顯示的是上次的內容」,拿到就消失。只有第一次(還沒有這台的資料)停在連線畫面:頭像在正中間呼吸、外圈漾開,沒有文字(讀螢幕軟體唸「正在連線」;減少動態時不動),拿到第一份狀態才進去。用帳號連、那台不在線上時留在它上次的內容,不換台。進去後斷線:浮「連線中斷,正在重新連線…」,自己重試,回到前景或網路恢復時立刻重連。設定、詳細、例行任務先畫手上有的,背景讀新的;要改的先讀到最新的。傳訊息不等網路:按下就出現在聊天裡;連不上標「等連線後送出(點一下拿回來)」,存手機排隊(關 App 也還在),連上後照順序自己送、不限時間,同一則只送一次;點一下連同附件拿回輸入框;連不上時選的附件也排隊。大腦拒收的才標「沒送出,點一下拿回來重送」。從通知打開時按的允許/拒絕等連上才送。只傳有變的部分、文字壓縮;Bot 回答中手機每秒最多更新一次聊天([chat](chat.md))。頁面和圖示存在手機上:打開直接用,背景問一次換版沒;換了,還在連線畫面就重新載入,已進去就等退到背景、手上沒東西(沒打字、附件、排隊、錄音、選單)才換;重新整理一定先問伺服器。上次的狀態、看過的聊天(合計最多 12 個)、詳細資料、設定、排隊的訊息每台電腦各自存在這個網址的儲存空間,登出(或登入失效)全部清掉。 - `phone-app` 像 App 一樣:加入主畫面後全螢幕、沒有網址列(避開瀏海和手勢條);首頁會提示「把 AnyBot 裝成 App」(Android 直接安裝,iPhone 教你加入主畫面,可以關掉);換畫面會左右滑動;iPhone 主畫面 App 從左邊緣往右滑回上一頁。 diff --git a/docs/feature-map/plan.md b/docs/feature-map/plan.md index bc84bdc..a4de70b 100644 --- a/docs/feature-map/plan.md +++ b/docs/feature-map/plan.md @@ -38,6 +38,6 @@ - 計畫模式只管使用者自己的訊息:例行任務、訊息管道和團隊成員傳來的訊息照平常做,不受計畫影響;群組聊天不能用 /plan。 - Bot 漏了 `update_plan`,計畫圖示的進度會停在舊的步驟,計畫也不會自己結束:叫它更新進度,或「/plan clear」。 - 照計畫做的期間,每一輪都會帶著這份計畫;聊別的事前先取消,免得它一直想回到計畫。 -- 清除聊天記錄或開始新對話,計畫跟著清掉。 +- 清除聊天記錄、開始新對話或換到另一段對話([threads](threads.md)),計畫跟著清掉;換走時那段留一行說停了哪個計畫、做到第幾步。 - 在同一步裡跟計畫一起要求的動作(例如交計畫的同時要執行指令)不會執行:那時還沒核准。 - 終端機的 `anybot --ask "/plan …"` 沒有人按卡片:核准卡會被自動拒絕(等於「先不要」),所以只會規劃、不會動手。 diff --git a/docs/feature-map/threads.md b/docs/feature-map/threads.md new file mode 100644 index 0000000..0f86fbc --- /dev/null +++ b/docs/feature-map/threads.md @@ -0,0 +1,43 @@ +# 對話:取名與切換 + +同一個 Bot 可以有好幾段對話,例如同一個職位做不同專案:每段可以取名字,從聊天右上的「對話」(手機標題列 🕘)一下就換過去,不用進選單找。 + +## 子功能 + +- `threads-column` 對話欄(電腦):聊天右上「對話」(取了名就寫名字)打開右邊的對話欄,再按一次關掉。最上面是目前的對話(粗體、淺底;沒取名就是你說的第一句話),下面是過去的對話,最新的在上,每段寫多久以前。點一段就換過去,目前的收進過去的對話最上面;欄頂的 + 開始新對話(Bot 工作中不開,跟選單的「開始新對話」不同:那個會先停下它)。Bot 工作中、或還有摘要、支線、交辦的回報要回到這段時不換,說要等什麼(「正在工作。等它做完(或先按停止),再換對話」…)。開著的對話欄重開 AnyBot 後還開著(每台電腦自己記;視窗太窄、放不下在聊天旁邊時先不開,按「對話」才浮出來);聊天標題太窄時按鈕只寫「對話」,滑過看名字;點 Bot 名字開對話詳細資訊時,對話欄讓出位置,關掉詳細資訊就回來;按 ✕ 或再按「對話」才是真的關掉。 +- `threads-name` 取名:對話欄每列滑過出現 ✎(目前的那列一直有),也可以雙擊目前的那列、或右鍵「重新命名」;按 Enter 或點別處就存,Esc 不存,空白回到用第一句話。名字跟著對話:收進過去的對話、再打開都帶著;「/fork」沒給名字時叫「分岔:這個名字」(分岔的再分岔不會疊成「分岔:分岔:」)。一行、最多 40 字。也可以在聊天裡請 Bot 取(「這段叫網站改版」「把報價單那段改叫 Q3」):它用 `list_conversations` 看有哪些、`rename_conversation` 改名。名字不會放進 Bot 讀的對話裡(它要看用 `list_conversations`)。 +- `threads-phone` 手機:聊天標題列 🕘(⋯ ›「對話」同一個)開「對話」:「目前的對話」那列點了取名;下面過去的對話(最新 20 段,更多時標題寫共幾段),點一段選「回到這段對話」或「重新命名」(大腦的 AnyBot 還是舊版時沒有命名)。取了名的對話,標題下那行寫名字。Bot 工作中「回到這段對話」不換,說要等它做完(還在整理摘要、支線或交辦還沒回報時,大腦不換、在聊天裡說)。團隊成員看不到 🕘(換對話、取名只有擁有者和管理員)。 +- `threads-list` 收進與找回:「開始新對話」(Bot 選單、手機 ✎、對話欄的 +)把目前的收進過去的對話,最多留 50 段,再多最舊的就沒了。換對話和開始新對話一樣,這段的目標(/goal)和計畫(/plan)停掉、「還原上一個答案」不帶過去,停之前在這段留一行說停了哪個、回來再打 /goal 或 /plan 接著做(以前會被帶到另一段)。搜尋到過去對話裡的訊息時,那筆寫那段的名字(電腦「Bot · 名字」,手機在 Bot 名字旁)。在另一台裝置換過、收過或改過名,清單位置變了,改名和換回去(對話清單、手機搜尋結果都一樣)照樣找到你點的那段(認它最後一則的時間和顯示的名字);那段已經被打開或改了名就不動;為目前的對話取名時,別台已經換成另一段也不動。 + +## 使用者怎麼到 + +- 聊天右上「對話」(在 ⋯ 和「分享」中間)。 +- Bot 選單(右鍵 Bot,或聊天右上 ⋯):「開始新對話」「過去的對話 ›」照樣在。 +- 在聊天裡請 Bot:「這段叫網站改版」「換回報價單那段」「開個新對話」。 +- 手機:聊天標題列 🕘、⋯ ›「對話」、對話詳細資訊 ›「過去的對話」;✎ 開始新對話([phone](phone.md))。 + +## 怎麼操作(verify-anybot) + +- Bot:`list_conversations` 列出目前的和過去的對話(名字、多久以前、幾則);取名或改名用 `rename_conversation`(`name` 空白回到第一句話;`conversation` 給過去那段的名字或只有它有的一段字,不給是目前這段);使用者要換時用 `switch_conversation`(`conversation` 同上,或 `new: true` 開始新對話;`name` 為換過去的那段取名):這一輪和接著要做的都做完、Bot 閒下來才換,回覆留在現在這段;那之前使用者按停止或清除聊天記錄就不換。支線只能用 `list_conversations`,不能改名或換。 + +前提: + +- 基本前提和「手機已登入」(README),開著 Bot 1 的聊天,聊天是空的。 + +- **為目前的對話取名**(covers `threads-name`、`threads-phone`):傳一句,🕘 › 目前的對話 › 取名「網站改版」。指令:`$CTL phone send '首頁要改' && $CTL phone wait-text 'FAKE-MODEL 回答:首頁要改' --in '#msgs' && $CTL phone click '#b-chats' && $CTL phone wait-text 目前的對話 --in '#sheet-in' && $CTL phone click '#sheet-in .opt' --text 命名 && $CTL phone type '#ask-in' 網站改版 && $CTL phone click '#ask-ok' && $CTL wait-api '/api/state?since=0' '.bots[0].chat_named == true' && $CTL phone wait-text 網站改版 --in '#isl-sub' && $CTL phone shot named`。看到:標題下那行「網站改版 · fake-model」;API `chat_title` 是「網站改版」。 +- **開始新對話、對話清單**(covers `threads-list`、`threads-phone`):✎ 開始新對話,再傳一句,打開 🕘。指令:`$CTL phone click '#b-newchat' && $CTL phone click '#sheet-in .opt' --text 開始新對話 && $CTL wait-api '/api/state?since=0' '.bots[0].threads[0].title == "網站改版"' && $CTL phone send '報價單' && $CTL phone wait-text 'FAKE-MODEL 回答:報價單' --in '#msgs' && $CTL phone click '#b-chats' && $CTL phone wait-text 網站改版 --in '#sheet-in' && $CTL phone shot chats-sheet`。看到:「對話」:目前的對話「報價單」,過去的對話「網站改版」和「剛剛」。 +- **換回去**(covers `threads-list`、`threads-name`):點「網站改版」›「回到這段對話」。指令:`$CTL phone wait-text fake-model --in '#isl-sub' && $CTL phone click '#sheet-in .opt' --text 網站改版 && $CTL phone click '#sheet-in .opt' --text 回到這段對話 && $CTL phone wait-text 'FAKE-MODEL 回答:首頁要改' --in '#msgs' && $CTL phone wait-text 網站改版 --in '#isl-sub' && $CTL api GET '/api/state?since=0' --jq '.bots[0] | {chat_title, threads: [.threads[].title]}'`。看到:聊天換回「首頁要改」、名字跟著回來;`threads` 只剩「報價單」。 +- **為過去的對話改名、重開還在、清掉名字**(covers `threads-name`):🕘 ›「報價單」›「重新命名」改成「Q3 報價」,重開 AnyBot,再把目前的名字清成空白。指令:`$CTL phone click '#b-chats' && $CTL phone click '#sheet-in .opt' --text 報價單 && $CTL phone click '#sheet-in .opt' --text 重新命名 && $CTL phone type '#ask-in' 'Q3 報價' && $CTL phone click '#ask-ok' && $CTL wait-api '/api/state?since=0' '.bots[0].threads[0].title == "Q3 報價"' && $CTL restart && $CTL wait-api '/api/state?since=0' '.bots[0].chat_title == "網站改版" and .bots[0].threads[0].title == "Q3 報價"' && $CTL phone open --listed && $CTL phone click '.row[data-bot="1"]' && $CTL phone click '#b-chats' && $CTL phone click '#sheet-in .opt' --text 命名 && $CTL phone type '#ask-in' '' && $CTL phone click '#ask-ok' && $CTL wait-api '/api/state?since=0' '.bots[0].chat_named == false and .bots[0].chat_title == "首頁要改"' && $CTL phone shot unnamed`。看到:清單「Q3 報價」;重開後兩個名字都在;清掉後回到第一句話「首頁要改」,標題下只寫模型。 +- **請 Bot 改名、換對話**(covers `threads-name`、`threads-list`):在聊天裡請它把「Q3 報價」改名、列出對話、換過去。指令:`$CTL phone send '[[call rename_conversation {"name":"第三季報價","conversation":"Q3"}]]' && $CTL wait-api '/api/state?since=0' '.bots[0].threads[0].title == "第三季報價"' 40 && $CTL phone send '[[call list_conversations {}]]' && $CTL wait-api '/api/state?since=0' '.bots[0].busy == false' 40 && $CTL phone send '換回去 [[call switch_conversation {"conversation":"第三季"}]]' && $CTL wait-api '/api/state?since=0' '.bots[0].busy == false and .bots[0].chat_title == "第三季報價"' 40 && $CTL model 'select(.tool_result != null) | .tool_result' | tail -4`。看到:「過去的對話「Q3 報價」改叫「第三季報價」了。」、清單「目前的對話:「…」…過去的對話(1 段…):- 「第三季報價」」;它回完那一輪才換,`chat_title` 是「第三季報價」,原本那段收進過去的對話。 +- **桌面的對話欄**(covers `threads-column`、`threads-name`):指令:要開視窗——`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot chats-column ANYBOT_SHOT_PANEL=chats`。看到:右邊「對話」欄,目前的那列粗體、淺底、有 ✎,下面過去的對話和時間;聊天右上的「對話」按鈕亮著。點 ✎(不會打開那段)、雙擊過去那段只換一次、改名、Esc、Bot 工作中不換、記住開著、詳細資訊關掉回到對話欄靠自動測試。 +- 自動測試:`cargo test a_conversation_keeps_the_name_it_was_given`、`cargo test a_past_conversation_is_found_by_its_time`、`cargo test chats_are_saved_apart`、`cargo test a_phone_names_and_switches_conversations`、`cargo test layout_audit::`(含 `the_chats_column_names_and_switches_conversations` 和對話欄的版面)、`cargo test a_screen_keeps_its_own_look_and_settings`、`cargo test a_bot_names_the_open_conversation`(含過去那段、`list_conversations`、支線不能)、`cargo test switching_conversations_ends_its_goal_and_plan_with_a_line`、`cargo test a_switch_asked_of_the_bot_waits_for_its_turn`、`cargo test clearing_or_stopping_calls_off_a_switch_the_bot_promised`、`cargo test nothing_on_its_way_lands_in_another_conversation`、`cargo test remote::tests::phone_login_and_api`(命名、回到的參數;成員不行)。 + +## 陷阱 + +- 名字只是給人看的:記憶、指示、檔案和例行任務是這個 Bot 共用的,不分對話;專案要分得乾淨(各自的記憶和檔案),開不同的 Bot。 +- 目標和計畫只屬於一段對話:換過去再回來不會自己接著做,照那段留的一行再打一次。 +- Bot 答應的換對話要等支線、同事的回報都回來,可能過幾分鐘才換;那之前按停止、清除聊天記錄,或在它閒著時又傳新訊息,就不換。 +- 清除聊天記錄只清畫面上那段:別台已經換成另一段時不清,說開著的是哪段。 +- 過去的對話最多 50 段,第 51 段收進來時最舊的那段就沒了,取了名的也一樣。 +- 還有東西要回到這段時不換對話(對話欄、Bot 選單、搜尋、手機都一樣),說要等什麼:Bot 在工作或還有排著的訊息、正在整理摘要(/compact)、支線還在做或還沒開始、同事正在做它交辦的事(寫出是哪位同事,到那裡按停止就會回報「沒有做完」)——換了,摘要或回報會落進另一段。交辦給同事、但同事還沒開始做的不擋:它之後的回報落在那時開著的那段。手機的舊頁面送來的,大腦不換、在聊天裡留一行。「開始新對話」照舊會先停下正在跑的那一輪,其餘幾樣也要等。 +- (驗證)手機的清單只有最新 20 段;`wait-api` 看 `threads_total` 才是全部有幾段。 diff --git a/mobile/index.html b/mobile/index.html index 9b46276..74d64be 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -776,6 +776,7 @@ button,.row,.ib,.island,.opt,.chip,.tab,label.sw,[role="button"]{-webkit-user-se +
@@ -1591,7 +1592,8 @@ function hitsHtml() { 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 ? `過去的對話` : ""; + // (Which past conversation: its name — a project's, when the person named it.) + const where = h.thread != null ? `${esc(h.thread_title || "過去的對話")}` : ""; 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("")}
`; @@ -1600,8 +1602,10 @@ async function openHit(i) { const h = ((S.hits || {}).hits || [])[i]; if (!h) return; if (h.thread != null) { + const b = bot(h.bot) || {}; + if (b.busy) { toast(`「${b.name || h.bot_name}」正在工作。等它做完(或先按停止),再換對話。`); return; } 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; } + try { await api(base() + `api/bots/${h.bot}/restore`, {json: {index: h.thread, at: h.thread_at || 0, was: h.thread_title || ""}}); } catch (e) { toast(e.message); return; } } go("chat", {bot: h.bot, at: h.at}); } @@ -1796,7 +1800,7 @@ $("b-me").onclick = () => { "use strict"; // ---------- chat ---------- $("isl-chev").innerHTML = ic("chevron-right", 14); -$("b-newchat").innerHTML = ic("pen", 19); $("b-chatmore").innerHTML = ic("ellipsis", 20); +$("b-newchat").innerHTML = ic("pen", 19); $("b-chats").innerHTML = ic("history", 19); $("b-chatmore").innerHTML = ic("ellipsis", 20); $("b-plus").innerHTML = ic("plus", 16); $("b-mic").innerHTML = ic("mic", 18); $("b-down").innerHTML = ic("arrow-down", 18); const ST = {waiting: "circle-alert", running: "loader", done: "circle-check", denied: "minus", failed: "circle-x"}; // What the bot is doing, in the words the desktop uses (its status line, or a waiting question). @@ -1804,7 +1808,8 @@ function chatSub(b) { const a = S.approvals.find((x) => x.bot === b.id); if (a) return ["wait", a.kind === "handoff" ? "需要你的輸入" : a.kind === "question" ? "等你回答" : "需要你核准"]; if (b.busy) return ["busy", b.status || "工作中…"]; - return ["", b.model || ""]; + // (A conversation the person named says which one this is.) + return ["", b.chat_named ? b.chat_title + (b.model ? " · " + b.model : "") : b.model || ""]; } function chatHead() { const b = bot(S.open); @@ -1815,6 +1820,8 @@ function chatHead() { $("isl-sub").className = "s " + cls; $("isl-sub").textContent = text; $("input").placeholder = "傳訊息給 " + b.name; $("b-newchat").style.display = owner() ? "" : "none"; + // (A team member can't change conversations: the brain refuses it.) + $("b-chats").style.display = owner() ? "" : "none"; } $("island").onclick = () => go("details", {bot: S.open}); // 存在這支手機上的(這個網址自己的儲存空間,登出就全部清掉):每台電腦上次的狀態、看過的聊天、 @@ -3006,23 +3013,47 @@ $("b-chatmore").onclick = () => { const b = bot(S.open); if (!b) return; const items = [ {icon: "info", label: "對話詳細資訊", on: () => go("details", {bot: b.id})}, - {icon: "history", label: "過去的對話", x: String((b.threads || []).length || ""), on: () => threads(b)}, + ...(owner() ? [{icon: "history", label: "對話", x: String(b.threads_total || (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})}); - if (isOwner()) items.push({icon: "trash", label: "清除聊天記錄", danger: true, on: async () => { if (await confirmSheet("清除聊天記錄?", "這段對話的訊息會全部刪除,無法復原。", "清除")) { await act("clear", {bot: b.id}); setTimeout(() => loadChat(true), 500); } }}); + if (isOwner()) items.push({icon: "trash", label: "清除聊天記錄", danger: true, on: async () => { if (await confirmSheet("清除聊天記錄?", "這段對話的訊息會全部刪除,無法復原。", "清除")) { await act("clear", {bot: b.id, was: b.chat_title || ""}); setTimeout(() => loadChat(true), 500); } }}); sheet(b.name, items); }; +// 對話 (the title bar's 🕘, 更多 › 對話): the open conversation (a tap names it), then 過去的對話, +// newest first (a tap: 回到這段對話 or 重新命名). Each is found by its last message's time too: a +// list that moved since (one opened on another device) still names the same one. function threads(b) { - const list = b.threads || []; - if (!list.length) { toast("還沒有過去的對話"); return; } - sheet("過去的對話", list.map((t) => ({icon: "message", label: t.title || "對話", x: ago(t.at), on: async () => { - if (!await confirmSheet("回到這段對話?", "現在的對話會留在「過去的對話」裡。", "回到這段對話", false)) return; - try { await api(base() + `api/bots/${b.id}/restore`, {json: {index: t.index}}); toast("已回到那段對話"); S.unfold = {}; setTimeout(() => loadChat(true), 700); } catch (e) { toast(e.message); } - }}))); + const list = b.threads || [], total = b.threads_total || list.length; + // (A brain from before names: no 命名 — it would answer 「沒有這個動作」.) + const named = b.chat_title !== undefined; + sheet("對話", [ + {group: "目前的對話"}, + {icon: "message", label: b.chat_title || "對話", x: named ? "命名" : "", on: () => named ? renameChat(b, null) : toast("這台大腦還不能為對話取名:先更新它的 AnyBot")}, + {group: list.length ? (total > list.length ? `過去的對話(最新 ${list.length} 段,共 ${total} 段)` : "過去的對話") : "還沒有過去的對話"}, + ...list.map((t) => ({icon: "history", label: t.title || "對話", x: ago(t.at), on: () => threadActions(b, t)})), + ]); } +function threadActions(b, t) { + sheet(t.title || "對話", [ + {icon: "history", label: "回到這段對話", on: async () => { + // (Not while it works: changing the conversation would stop it.) + if ((bot(b.id) || b).busy) { toast(`「${b.name}」正在工作。等它做完(或先按停止),再換對話。`); return; } + try { await api(base() + `api/bots/${b.id}/restore`, {json: {index: t.index, at: t.at, was: t.title || ""}}); toast("已回到那段對話"); S.unfold = {}; kick(); setTimeout(() => loadChat(true), 700); } catch (e) { toast(e.message); } + }}, + ...(b.chat_title !== undefined ? [{icon: "pen", label: "重新命名", on: () => renameChat(b, t)}] : []), + {label: "取消"}, + ], `
回到這段對話時,現在的對話留在「過去的對話」裡。
`); +} +async function renameChat(b, t) { + const name = await ask(t ? "為這段對話命名" : "為目前的對話命名", t ? t.title || "" : (b.chat_named ? b.chat_title : ""), "例如:網站改版(空白=用第一句話)"); + if (name === null) return; + // (With the name it showed: another device may have opened or renamed another meanwhile.) + try { await api(base() + `api/bots/${b.id}/rename`, {json: t ? {index: t.index, at: t.at, was: t.title || "", title: name} : {was: b.chat_title || "", title: name}}); toast(name ? `已命名「${name}」` : "改回用第一句話"); kick(); } catch (e) { toast(e.message); } +} +$("b-chats").onclick = () => { const b = bot(S.open); if (b) threads(b); }; // At the newest message, it stays in view while what is above it grows after being drawn (a // picture that loads, a preview); scrolled up to read, nothing moves. (A question card taller // than the screen is left where renderQuestion put it: its question, not its buttons.) @@ -3509,7 +3540,7 @@ async function renderBotset(id) { 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}); - else if (k === "clear") { if (await confirmSheet("清除聊天記錄?", "這段對話的訊息會全部刪除,無法復原。", "清除")) act("clear", {bot: id}); } + else if (k === "clear") { if (await confirmSheet("清除聊天記錄?", "這段對話的訊息會全部刪除,無法復原。", "清除")) act("clear", {bot: id, was: (bot(id) || {}).chat_title || ""}); } else if (k === "delete") deleteBot(b); }); } diff --git a/src/agent.rs b/src/agent.rs index 6e9510f..d8d0064 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -358,7 +358,7 @@ fn parse_verdict(text: &str) -> ReviewVerdict { /// the person tells the bot to keep is another matter: that is `remember`, the bot's own call.) pub(crate) fn worth_noting(turn: &[Message]) -> bool { let calls: Vec<&str> = turn.iter().flat_map(|m| m.tool_calls.iter().map(|c| c.name.as_str())).collect(); - let quiet = |n: &str| only_looks(n) || matches!(n, "remember" | "forget" | "search_memory" | "search_documents" | "use_skill" | "react" | "show_card" | crate::ask::TOOL | "list_routines" | crate::tasks::TOOL | "list_bots" | "list_computers"); + let quiet = |n: &str| only_looks(n) || matches!(n, "remember" | "forget" | "search_memory" | "search_documents" | "use_skill" | "react" | "show_card" | crate::ask::TOOL | "list_routines" | crate::tasks::TOOL | "list_bots" | "list_computers" | "list_conversations"); calls.iter().any(|n| !quiet(n)) || calls.len() >= NOTE_MIN_LOOKS } /// This many steps of only looking are a piece of work too (a long research). @@ -1685,7 +1685,7 @@ pub const QUICK_TROUBLE_MAX: usize = 2; fn only_looks(name: &str) -> bool { matches!( name, - "computer_use_screenshot" | "computer_use_zoom" | "computer_use_show" | "computer_use_check_permissions" | crate::outputs::TOOL | "browser_read" | "browser_screenshot" | "browser_elements" | "browser_find" | "browser_table" | "browser_tabs" | "browser_wait" | "browser_sent_log" | "anybot_guide" | "web_fetch" | "read_file" | "list_dir" | "search" | "read_terminal" | "list_computers" | "list_bots" | "list_routines" | crate::tasks::TOOL | "read_page" | "use_skill" | "react" | "show_card" | "search_documents" | "search_memory" + "computer_use_screenshot" | "computer_use_zoom" | "computer_use_show" | "computer_use_check_permissions" | crate::outputs::TOOL | "browser_read" | "browser_screenshot" | "browser_elements" | "browser_find" | "browser_table" | "browser_tabs" | "browser_wait" | "browser_sent_log" | "anybot_guide" | "web_fetch" | "read_file" | "list_dir" | "search" | "read_terminal" | "list_computers" | "list_bots" | "list_routines" | "list_conversations" | crate::tasks::TOOL | "read_page" | "use_skill" | "react" | "show_card" | "search_documents" | "search_memory" ) } diff --git a/src/app.rs b/src/app.rs index b306098..d4d7e6c 100644 --- a/src/app.rs +++ b/src/app.rs @@ -289,6 +289,8 @@ pub struct App { /// 「/compact」 summaries finished on their thread: (bot, (messages replaced, summary, first kept message's time)). #[allow(clippy::type_complexity)] compact_out: Arc)>>>, + /// Bots whose 「/compact」 is being written (its summary goes into the open conversation). + compacting: HashMap, /// Bots whose running turn came from someone else's message (a channel, a teammate): /// 一律放行 doesn't answer for them. strangers: std::collections::HashSet, @@ -426,6 +428,10 @@ pub struct App { typed_on: Option, /// 右側面板 and its tab (None = closed). panel: Option, + /// 對話欄's 重新命名 under way. + chat_rename: Option, + /// The 對話欄 is open only because it was left open last time (not opened since). + chats_remembered: bool, /// When each emoji reaction appeared (for its pop) and when each message first showed (fade-in). popped: HashMap<(u64, usize, String), Instant>, appeared: HashMap<(u64, usize), Instant>, @@ -600,6 +606,7 @@ impl App { ask_keys: Default::default(), settled_by_direct: Default::default(), compact_out: Default::default(), + compacting: Default::default(), managed: if demo { policy::Managed::default() } else { policy::read() }, settings_was_open: false, exe_built: crate::version::exe_modified(), @@ -677,6 +684,8 @@ impl App { asking: false, typed_on: None, panel: None, + chat_rename: None, + chats_remembered: false, popped: HashMap::new(), appeared: HashMap::new(), steps_open: Default::default(), @@ -709,6 +718,11 @@ impl App { app.drafts.insert(b.id, b.draft.clone()); } } + // 對話欄, left open last time. + if app.state.chats_column { + app.panel = Some(panel_ui::PanelTab::Chats); + app.chats_remembered = true; + } crate::i18n::set(&app.state.language); app.computers_start(); @@ -1426,9 +1440,10 @@ impl App { if std::env::var("ANYBOT_SHOT_NOPOPUP").is_ok() { app.popup_hidden.extend(app.state.bots.iter().map(|b| b.id)); } - // ANYBOT_SHOT_PANEL=1: the right panel open on any demo view (without starting the box). - if std::env::var("ANYBOT_SHOT_PANEL").is_ok() { - app.panel = Some(panel_ui::PanelTab::Activity); + // ANYBOT_SHOT_PANEL=1: the right panel open on any demo view (without starting the box); + // =chats: the 對話欄. + if let Ok(v) = std::env::var("ANYBOT_SHOT_PANEL") { + app.panel = Some(if v == "chats" { panel_ui::PanelTab::Chats } else { panel_ui::PanelTab::Activity }); } // ANYBOT_SHOT_TAB=: 設定 open on that page (each page checked at any window size). if let Ok(tab) = std::env::var("ANYBOT_SHOT_TAB") { @@ -1646,6 +1661,12 @@ impl App { if text.trim().is_empty() && !self.has_pending_attachments(bot_id) { return; } + // A new message to an idle bot: the person goes on here — a 換對話 it promised is off. + if !self.streams.contains_key(&bot_id) { + if let Some(b) = self.state.bot_mut(bot_id) { + b.chat_after = None; + } + } // 診斷: 「/doctor」 checks this computer — here even on a screen of a brain, and above // all when the brain can't be reached. if crate::doctor::command(&text) { @@ -2774,6 +2795,11 @@ impl App { self.start_reply(ctx, id); } self.pending_turns.extend(held); + // 換對話 a bot was asked for in chat: now that its turn and what followed are over. + let asked: Vec = self.state.bots.iter().filter(|b| b.chat_after.is_some()).map(|b| b.id).collect(); + for id in asked { + self.chat_after_turn(id); + } } /// The running turn of a bot is someone else's — a routine's, an event's, a workflow step's, @@ -2867,6 +2893,11 @@ impl App { } fn stop(&mut self, bot_id: u64) { + // 停止 (and what stops it: 清除聊天記錄, 重新啟動, quitting) calls off a 換對話 the bot + // promised — the person stepped in; and it is never done under what stopping writes. + if let Some(b) = self.state.bot_mut(bot_id) { + b.chat_after = None; + } if self.mir.on { if self.streams.contains_key(&bot_id) || self.approvals.contains_key(&bot_id) { self.mirror_act(serde_json::json!({"bot": bot_id, "action": "stop"})); @@ -3939,6 +3970,8 @@ impl App { memories: vec![], members: vec![], threads: Default::default(), + chat_title: String::new(), + chat_after: None, context_tokens: agent::DEFAULT_CONTEXT_TOKENS, model_limits: Default::default(), follow_ups: vec![], @@ -4164,23 +4197,7 @@ impl App { } // 討論串: put this conversation aside and start fresh; earlier ones can come back. if menu_ui::item(ui, p, Icon::NewChat, "開始新對話").clicked() { - if !self.mir.on { - self.goal_drop(id); - } - self.stop(id); - if self.mir.on { - self.mirror_act(serde_json::json!({"bot": id, "action": "new"})); - } else if let Some(b) = self.state.bot_mut(id) { - if !b.messages.is_empty() { - let title = b.messages.iter().find(|m| m.role == Role::User).map(|m| first_line(&m.text, 24)).unwrap_or_else(|| "對話".into()); - let mut msgs = std::mem::take(&mut b.messages); - // (An earlier conversation keeps its words, not its screenshots in memory.) - msgs.iter_mut().for_each(|m| m.images.clear()); - b.threads.insert(0, (title, msgs.into_inner())); - b.threads.truncate(50); - } - } - self.mark(); + self.new_chat(id); ui.close(); } let threads: Vec = b.threads.iter().map(|t| t.0.clone()).collect(); @@ -4253,12 +4270,14 @@ impl App { if self.mir.on { // The chat lives on the brain: clearing only this copy left the brain sure this // screen still had it, and its next changes landed in the wrong place. - self.mirror_act(serde_json::json!({"bot": id, "action": "clear"})); + let was = self.state.bot(id).map(|b| b.chat_name()).unwrap_or_default(); + self.mirror_act(serde_json::json!({"bot": id, "action": "clear", "was": was})); } else { self.goal_drop(id); self.stop(id); if let Some(b) = self.state.bot_mut(id) { b.messages.clear(); + b.chat_title.clear(); } self.mark(); } @@ -4414,6 +4433,21 @@ impl App { right.spacing_mut().item_spacing.x = 8.0; let more = pill_icon(&mut right, crate::icons::Icon::More, p).on_hover_text(t("更多")); egui::Popup::menu(&more).show(|ui| self.bot_menu_items(ui, bot.id)); + // 對話: which conversation this is (its name, once it has one); a click opens the column + // of this bot's conversations beside the chat, to switch in one click (it took ⋯ › + // 過去的對話 › a name before). + // (Not beside a 工作流 canvas: no column is drawn there.) The name gets what room the + // title has left once the bot's name keeps its own; little room, just 「對話」. + if !self.wf.open { + let chats_on = self.panel == Some(PanelTab::Chats); + let room = (bar.width() - 420.0).min(150.0); + let label = if bot.chat_title.is_empty() || room < 48.0 { t("對話") } else { sidebar_ui::shorten_width(&right, &bot.chat_title, room, 13.0) }; + let tip = if bot.threads.is_empty() { t("這個 Bot 的對話") } else { t("這個 Bot 的對話(過去的 {n} 段)").replace("{n}", &bot.threads.len().to_string()) }; + let tip = if bot.chat_title.is_empty() || label == bot.chat_title { tip } else { format!("{}\n{tip}", bot.chat_title) }; + if crate::icons::pill(&mut right, crate::icons::Icon::History, &label, if chats_on { p.active } else { Color32::TRANSPARENT }, p.text, 36.0).on_hover_text(tip).clicked() { + self.set_panel(if chats_on { None } else { Some(PanelTab::Chats) }); + } + } if pill_text(&mut right, &t("分享"), p).on_hover_text(t("匯出 Bot(分享給別人)…")).clicked() { let (text, name) = (crate::share::export(bot), format!("{}.anybot", bot.name)); let note = self.ch.note.clone(); @@ -4456,9 +4490,10 @@ impl App { ui.painter().galley(tag_rect.min, tag, tag_col); ui.interact(tag_rect.expand(4.0), egui::Id::unique(("runs-tag", bot.id)), egui::Sense::hover()).on_hover_text(format!("{} · {}\n{}", bot.provider.label(), bot.model, runs.words(self.brain_for_words().as_deref()))); let _ = color; - let open = self.panel.is_some(); + // (The 對話欄 open, the name opens the details in its place.) + let open = self.panel.is_some_and(|t| t != PanelTab::Chats); if r.on_hover_text(t(if open { "關閉對話詳細資訊" } else { "查看對話詳細資訊" })).on_hover_cursor(egui::CursorIcon::PointingHand).clicked() { - self.panel = if open { None } else { Some(PanelTab::Activity) }; + self.set_panel(if open { None } else { Some(PanelTab::Activity) }); } } @@ -4728,27 +4763,75 @@ impl App { } } - /// 過去的對話 number `i` becomes the open one (the open one goes to the top of the list). The - /// bot's running turn, if any, is stopped first. - fn open_thread(&mut self, id: u64, i: usize) { - self.stop(id); + /// 開始新對話: the open conversation goes to 過去的對話 and the chat is empty (its goal and + /// running turn, if any, stop). + fn new_chat(&mut self, id: u64) { + // (A running turn is stopped, as before; a summary, a 支線 or a colleague's report on the + // way can't be, and would land in the new conversation.) + if let Some(why) = self.chat_pending(id, false) { + self.notice = Some(why); + return; + } if self.mir.on { - self.mirror_act(serde_json::json!({"bot": id, "action": "restore", "index": i})); - } else if let Some(b) = self.state.bot_mut(id) { - if i < b.threads.len() { - let (_, msgs) = b.threads.remove(i); - if !b.messages.is_empty() { - let cur_title = b.messages.iter().find(|m| m.role == Role::User).map(|m| first_line(&m.text, 24)).unwrap_or_else(|| "對話".into()); - let mut cur = std::mem::take(&mut b.messages); - cur.iter_mut().for_each(|m| m.images.clear()); - b.threads.insert(0, (cur_title, cur.into_inner())); - } - b.messages = msgs.into(); + // (The brain stops the running turn itself, and only once it starts the new one: a + // stop sent first ended the turn even when the brain then kept the conversation for + // something this screen couldn't see.) + self.mirror_act(serde_json::json!({"bot": id, "action": "new"})); + } else { + self.leave_conversation(id); + self.stop(id); + if let Some(b) = self.state.bot_mut(id) { + b.put_aside(); } } self.mark(); } + /// 過去的對話 number `i` becomes the open one (the open one goes to the top of the list); not + /// while the bot works (it says so). + fn open_thread(&mut self, id: u64, i: usize) { + // Not while something is still to land in the open conversation (the same everywhere a + // conversation is opened): it would land in this one. + if let Some(why) = self.chat_pending(id, true) { + self.notice = Some(why); + return; + } + if !self.mir.on && self.state.bot(id).is_some_and(|b| i < b.threads.len()) { + self.leave_conversation(id); + } + if self.mir.on { + // (With its last message's time and its name: the brain's list may have moved since.) + let t = self.state.bot(id).and_then(|b| b.threads.get(i)); + let (at, was) = (t.and_then(|t| t.1.last()).map(|m| m.at).unwrap_or(0), t.map(|t| t.0.clone()).unwrap_or_default()); + self.mirror_act(serde_json::json!({"bot": id, "action": "restore", "index": i, "at": at, "was": was})); + } else if let Some(b) = self.state.bot_mut(id) { + b.open_thread(i); + } + self.mark(); + } + + /// 重新命名 a conversation: the open one (`None`) or 過去的對話 number `i` (on a screen of a + /// brain, the brain does it: the chats live there). + pub(super) fn rename_chat(&mut self, id: u64, which: Option, name: &str) { + if self.mir.on { + let Some(b) = self.state.bot(id) else { return }; + let (at, was) = match which.and_then(|i| b.threads.get(i)) { + Some(t) => (t.1.last().map(|m| m.at).unwrap_or(0), t.0.clone()), + None => (0, b.chat_name()), + }; + let sent = self.mirror_can_send(); + self.mirror_act(serde_json::json!({"bot": id, "action": "rename", "index": which, "at": at, "was": was, "title": name})); + if !sent { + return; + } + } + // (Here too on a screen, so the name shows now; the brain's comes back the same.) + if let Some(b) = self.state.bot_mut(id) { + b.rename_chat(which, name); + } + self.mark(); + } + /// 問題卡, the last thing in the chat (it used to be docked above the input, where a card /// with several choices covered most of what the bot had just said): it scrolls with the /// messages, as tall as its content, and the chat comes to it when it appears or moves to @@ -8423,15 +8506,7 @@ fn tidy_dots(s: &str) -> String { /// The avatar's picture on a notification (pixels; the system scales it down). const NOTICE_PX: u32 = 128; -fn first_line(s: &str, max: usize) -> String { - let line = s.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or(""); - let line = line.trim_start_matches(['#', '-', '*', ' ']); - let mut out: String = line.chars().take(max).collect(); - if line.chars().count() > max { - out.push('…'); - } - out -} +use crate::model::first_line; fn icon_button(ui: &mut egui::Ui, icon: &str, tip: &str, p: Palette) -> egui::Response { if let Some(ic) = crate::icons::Icon::from_name(icon) { diff --git a/src/app/commands.rs b/src/app/commands.rs index 79efb9b..bef682f 100644 --- a/src/app/commands.rs +++ b/src/app/commands.rs @@ -227,7 +227,9 @@ impl App { self.goal_note(bot_id, "對話還是空的,沒有東西可以分岔。"); return; } - let what = if name.is_empty() { words.iter().find(|m| m.role == Role::User).map(|m| first_line(&m.text, 24)).unwrap_or_else(|| "對話".into()) } else { name.to_string() }; + // (Named after the conversation: its name, when it has one.) + // (A fork of a fork is 「分岔:名字」 again, not 「分岔:分岔:名字」.) + let what = if name.is_empty() { b.chat_name().trim_start_matches(FORK_PREFIX).to_string() } else { name.to_string() }; let title = format!("{FORK_PREFIX}{what}"); let Some(b) = self.state.bot_mut(bot_id) else { return }; let mut copy = b.messages.to_vec(); diff --git a/src/app/context_ui.rs b/src/app/context_ui.rs index b178493..7a8fbae 100644 --- a/src/app/context_ui.rs +++ b/src/app/context_ui.rs @@ -55,6 +55,7 @@ impl App { m => Some(m.to_string()), }; self.goal_note(bot_id, "正在把較早的對話整理成摘要…"); + self.compacting.insert(bot_id, Instant::now()); let (out, repaint) = (self.compact_out.clone(), self.repaint_fn()); std::thread::spawn(move || { agent::set_turn_bot(bot_id); @@ -70,6 +71,7 @@ impl App { pub(super) fn compact_tick(&mut self) { let done = std::mem::take(&mut *self.compact_out.lock().unwrap()); for (bot_id, got) in done { + self.compacting.remove(&bot_id); match got { Some((n, summary, boundary)) => { if let Some(b) = self.state.bot_mut(bot_id) { diff --git a/src/app/goal_ui.rs b/src/app/goal_ui.rs index b27eddf..529394d 100644 --- a/src/app/goal_ui.rs +++ b/src/app/goal_ui.rs @@ -137,6 +137,106 @@ impl App { crate::remote::notify(crate::remote::Notice::Done, &name, &body, bot_id); } + /// What is still to land in this bot's open conversation (None: nothing), said for the + /// person: opening another one now would put it there. `turn`: its own running turn counts + /// (開始新對話 stops that one instead). A message too late to steer, a wake, a group's next + /// member, a colleague's report held for it; a 「/compact」 being written; a 支線 working; + /// a colleague working on what it handed over. + pub(super) fn chat_pending(&self, bot_id: u64, turn: bool) -> Option { + let name = self.state.bot(bot_id).map(|b| b.name.clone()).unwrap_or_default(); + let queued = self.pending_turns.iter().any(|(id, _)| *id == bot_id) || self.waiting_wakes.iter().any(|(id, _)| *id == bot_id) || self.group_next.contains(&bot_id) || self.reports.iter().any(|(id, _)| *id == bot_id); + if (turn && self.streams.contains_key(&bot_id)) || queued { + return Some(t("「{name}」正在工作。等它做完(或先按停止),再換對話。").replace("{name}", &name)); + } + // (One whose summary never came back — its thread gone — holds nothing after 10 minutes.) + if self.compacting.get(&bot_id).is_some_and(|t| t.elapsed() < std::time::Duration::from_secs(600)) { + return Some(t("「{name}」正在把較早的對話整理成摘要:整理好再換對話。").replace("{name}", &name)); + } + // (Running, or still to start: seeing whether it clashes, or waiting for the turn — it + // starts from the open conversation and reports there.) + if self.state.branch_bots.iter().any(|b| b.branch_of == bot_id) || self.state.bot(bot_id).is_some_and(|b| b.branches.iter().any(|r| r.state.open())) { + return Some(t("「{name}」還有支線在做,做完會回報到這段:等它做完(或在支線卡上停止),再換對話。").replace("{name}", &name)); + } + // A colleague working now on what this bot handed it: its report comes here when its turn + // ends — said by name, with the way out (stopping it there reports 「沒有做完」 at once). + // (One still waiting behind the colleague's other work doesn't hold the conversation: it + // could be any time.) + let handed = |m: &Message| m.from_bot == bot_id && !m.asked; + let colleague = self.streams.keys().filter(|id| **id != bot_id).find(|id| self.state.bot(**id).and_then(|b| b.messages.iter().rev().find(|m| m.role == Role::User && !m.steer && !m.interrupted)).is_some_and(handed)); + if let Some(c) = colleague.and_then(|c| self.state.bot(*c)) { + return Some(t("「{name}」交辦給「{other}」的事正在做,做完會回報到這段:等它回報(或到「{other}」按停止),再換對話。").replace("{name}", &name).replace("{other}", &c.name)); + } + None + } + + /// The open conversation is put aside (開始新對話) or another opened in its place: its + /// 目標 and 計畫 were about it and stop — said in it first, so going back to it shows what + /// was left and how to go on (they used to carry on in the other conversation, or go + /// without a word). A 換對話 the bot was asked for and hasn't done yet is off too. + pub(super) fn leave_conversation(&mut self, bot_id: u64) { + let Some(b) = self.state.bot(bot_id) else { return }; + let mut what = vec![]; + if let Some(g) = &b.goal { + what.push(format!("目標「{}」", crate::model::first_line(&g.condition, 40))); + } + if let Some(p) = &b.plan { + what.push(format!("計畫「{}」(做到 {}/{} 步)", crate::model::first_line(&p.task, 40), p.done(), p.steps.len())); + } + let unread = b.unread; + if !what.is_empty() && !b.messages.is_empty() { + self.goal_note(bot_id, &format!("換到另一段對話,這段的{}停了:它們只屬於這段對話。回到這裡要接著做,再打 /goal 或 /plan。", what.join("和"))); + } + if let Some(b) = self.state.bot_mut(bot_id) { + // (The line is in the conversation put aside: nothing new to read in the open one.) + b.unread = unread; + b.chat_after = None; + } + self.goal_drop(bot_id); + } + + /// 換對話 the bot was asked for in chat (switch_conversation): on a tick (tick_routines), + /// once its turn is over and nothing else is to follow in this conversation — a message + /// that came too late to steer, AnyBot's correction, a group's next member, a colleague's + /// report held for it — or those would run in the other one. Never from inside a turn's + /// end (settle): 停止 and the stall watchdog go on writing to the conversation after it. + /// 停止 and 清除聊天記錄 call it off (stop). + pub(super) fn chat_after_turn(&mut self, bot_id: u64) { + if self.state.bot(bot_id).is_none_or(|b| b.chat_after.is_none()) || self.chat_pending(bot_id, true).is_some() { + return; + } + let Some(to) = self.state.bot_mut(bot_id).and_then(|b| b.chat_after.take()) else { return }; + // A turn that didn't end well (an error, the stall watchdog): the person stays where its + // trouble is, not moved away from it. + if self.state.bot(bot_id).and_then(|b| b.last_turn.as_ref()).is_some_and(|t| t.outcome != crate::model::TurnOutcome::Success) { + self.goal_note(bot_id, "沒有換對話:這一輪沒有順利做完,留在這段。要換再說一次。"); + return; + } + let which = match &to { + crate::model::ChatAfter::New { .. } => Some(None), + crate::model::ChatAfter::Open { title, at, .. } => self.state.bot(bot_id).and_then(|b| b.find_thread(usize::MAX, *at, title)).map(Some), + }; + let Some(which) = which else { + if let crate::model::ChatAfter::Open { title, .. } = to { + self.goal_note(bot_id, &format!("沒有換到「{title}」:那段已經不在過去的對話裡了(換過、改了名,或被收掉)。")); + } + return; + }; + self.leave_conversation(bot_id); + if let Some(b) = self.state.bot_mut(bot_id) { + match which { + None => b.put_aside(), + Some(i) => { + b.open_thread(i); + } + } + let (crate::model::ChatAfter::New { name } | crate::model::ChatAfter::Open { name, .. }) = to; + if !name.is_empty() { + b.rename_chat(None, &name); + } + } + self.mark(); + } + /// 清除聊天記錄 / 開始新對話: the goal goes with the chat it was set in (Claude Code's /clear /// removes it too). Before the turn is stopped, so stopping doesn't leave a 「目標暫停」 line /// in the new chat. diff --git a/src/app/layout_audit.rs b/src/app/layout_audit.rs index 95148d8..d992d1d 100644 --- a/src/app/layout_audit.rs +++ b/src/app/layout_audit.rs @@ -310,6 +310,20 @@ fn scenes() -> Vec<(&'static str, Open)> { } }), ), + ( + "對話欄(長名字、改名中)", + Box::new(|a: &mut App| { + a.state.selected = 1; + a.panel = Some(panel_ui::PanelTab::Chats); + if let Some(b) = a.state.bot_mut(1) { + b.chat_title = "這是一個名字取得非常非常長的專案對話,看看會不會被切掉".into(); + let long = "第二季官網改版:首頁、產品頁、價格頁和部落格全部重新設計,還有後台".to_string(); + b.threads = vec![(long, vec![Message { at: crate::model::now_ms() - 3_600_000, ..Message::user("x") }]), ("報價單".into(), vec![Message { at: 5, ..Message::user("報價單") }])].into(); + } + // (Its last message's time, as a row being renamed is known by.) + a.chat_rename = Some(panel_ui::ChatRename { bot: 1, which: Some((1, 5)), shown: "報價單".into(), text: "Q3 報價(改名中)".into(), focused: true }); + }), + ), ( "右側面板 › 資料庫", Box::new(|a: &mut App| { @@ -638,6 +652,117 @@ fn a_connector_is_renamed_when_done_and_its_field_keeps_the_keyboard() { } +/// 對話欄: the title's 「對話」 opens it (and it is there again after a restart); ✎ names the +/// open conversation (Enter takes it, Esc doesn't); a click on a past one opens it, its name +/// with it — not while the bot works (that would stop it), and a name being typed is taken when +/// the person goes on. +#[test] +fn the_chats_column_names_and_switches_conversations() { + let ctx = egui::Context::default(); + crate::load_fonts(&ctx); + let mut app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-chats-column-test.png"))); + app.popup_hidden.extend(app.state.bots.iter().map(|b| b.id)); + app.state.selected = 1; + app.streams.clear(); + { + let b = app.state.bot_mut(1).unwrap(); + b.messages = vec![Message { at: 300, ..Message::user("現在這段") }].into(); + b.chat_title.clear(); + b.threads = vec![("網站改版".into(), vec![Message { at: 200, ..Message::user("首頁") }]), ("報價單".into(), vec![Message { at: 100, ..Message::user("報價單") }])].into(); + } + app.set_panel(Some(panel_ui::PanelTab::Chats)); + assert!(app.state.chats_column, "remembered on this computer"); + let size = vec2(1200.0, 800.0); + let shapes = draw(&mut app, &ctx, size); + let texts: Vec = words(&shapes).into_iter().map(|w| w.text).collect(); + for want in ["現在這段", "網站改版", "報價單"] { + assert!(texts.iter().any(|t| t == want), "{want} in {texts:?}"); + } + // Name the open one: typed, then Esc — nothing; typed, then Enter — named. + let type_name = |app: &mut App, words: &str, end: egui::Key| { + app.chat_rename = Some(panel_ui::ChatRename { bot: 1, which: None, shown: app.state.bot(1).unwrap().chat_name(), text: String::new(), focused: false }); + step(app, &ctx, size, vec![]); + step(app, &ctx, size, vec![egui::Event::Text(words.into())]); + step(app, &ctx, size, vec![key(end)]); + step(app, &ctx, size, vec![]); + }; + type_name(&mut app, "不要的名字", egui::Key::Escape); + assert_eq!(app.state.bot(1).unwrap().chat_title, ""); + assert!(app.chat_rename.is_none(), "the field is gone after Esc"); + type_name(&mut app, "官網專案", egui::Key::Enter); + assert_eq!(app.state.bot(1).unwrap().chat_title, "官網專案"); + assert!(app.chat_rename.is_none()); + let shapes = draw(&mut app, &ctx, size); + assert!(words(&shapes).iter().filter(|w| w.text == "官網專案").count() >= 2, "in the column and on the title's 對話"); + // A past one: its ✎ (shown under the pointer) is pressed — the row isn't opened — and + // the name typed is taken when the person then closes the column. + // (A press right after another reads as a double click: each click comes after a pause + // longer than that — frames without a time are 1/60 s apart.) + let press = |app: &mut App, at: egui::Pos2| { + step(app, &ctx, size, vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }]); + step(app, &ctx, size, vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }]); + }; + let click = |app: &mut App, at: egui::Pos2| { + for _ in 0..30 { + step(app, &ctx, size, vec![]); + } + step(app, &ctx, size, vec![egui::Event::PointerMoved(at)]); + step(app, &ctx, size, vec![egui::Event::PointerMoved(at)]); + step(app, &ctx, size, vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }]); + step(app, &ctx, size, vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }]); + }; + let row = |app: &mut App, name: &str| { + let shapes = draw(app, &ctx, size); + words(&shapes).into_iter().find(|w| w.text == name).map(|w| w.rect).expect("the row") + }; + // (✎ sits 20 px in from the row's right end; the row ends at the column's 16 px margin.) + let pen = egui::pos2(size.x - 16.0 - 20.0, row(&mut app, "報價單").center().y + 8.0); + click(&mut app, pen); + assert_eq!(app.state.bot(1).unwrap().messages[0].text, "現在這段", "✎ doesn't open the row"); + assert!(app.chat_rename.as_ref().is_some_and(|e| e.which == Some((1, 100))), "✎ starts naming that one"); + step(&mut app, &ctx, size, vec![]); + step(&mut app, &ctx, size, vec![key(egui::Key::End)]); + for _ in 0..3 { + step(&mut app, &ctx, size, vec![key(egui::Key::Backspace)]); + } + step(&mut app, &ctx, size, vec![egui::Event::Text("報價".into())]); + app.set_panel(None); + assert_eq!(app.state.bot(1).unwrap().threads[1].0, "報價"); + assert!(!app.state.chats_column, "closing the column itself forgets it"); + // The title's 對話 (it carries the open one's name) opens the column; the details opened + // over it and closed bring it back. + let pill = row(&mut app, "官網專案"); + click(&mut app, pill.center()); + assert_eq!(app.panel, Some(panel_ui::PanelTab::Chats)); + app.set_panel(Some(panel_ui::PanelTab::Activity)); + assert!(app.state.chats_column, "still remembered under the details"); + app.set_panel(None); + assert_eq!(app.panel, Some(panel_ui::PanelTab::Chats), "back when the details close"); + // Opening one while the bot works: refused, said why. + let now = Instant::now(); + app.streams.insert(1, Live { cancel: Arc::new(AtomicBool::new(false)), started: now, last: now, produced: true, status: None, paused: false, paused_at: None, unattended: false, steer: Arc::new(Mutex::new(vec![])), direct: Arc::new(AtomicBool::new(false)), turn_id: "t".into(), turn: 1 }); + let at = row(&mut app, "網站改版").center(); + click(&mut app, at); + assert_eq!(app.state.bot(1).unwrap().messages[0].text, "現在這段", "not while it works"); + assert!(app.notice.as_deref().is_some_and(|n| n.contains("正在工作")), "{:?}", app.notice); + // Done working: the click opens it; the open one goes to the top of the list with its name. + app.streams.clear(); + app.notice = None; + let at = row(&mut app, "網站改版").center(); + click(&mut app, at); + let b = app.state.bot(1).unwrap(); + assert_eq!((b.messages[0].text.as_str(), b.chat_title.as_str()), ("首頁", "網站改版")); + assert_eq!(b.threads.iter().map(|t| t.0.as_str()).collect::>(), ["官網專案", "報價"]); + // A double click on a past one opens it once: the second press lands on the row the list + // moved under it (the one just put aside), and isn't taken as opening that one again. + let at = row(&mut app, "報價").center(); + click(&mut app, at); + press(&mut app, at); + let b = app.state.bot(1).unwrap(); + assert_eq!((b.messages[0].text.as_str(), b.chat_title.as_str()), ("報價單", "報價"), "opened once"); + assert_eq!(b.threads.iter().map(|t| t.0.as_str()).collect::>(), ["網站改版", "官網專案"]); +} + /// Esc while typing a connector's new name puts the old one back. #[test] fn esc_puts_a_connectors_name_back() { diff --git a/src/app/mirror_ui.rs b/src/app/mirror_ui.rs index b340a62..ac304f3 100644 --- a/src/app/mirror_ui.rs +++ b/src/app/mirror_ui.rs @@ -17,7 +17,7 @@ use std::hash::{Hash, Hasher}; use std::sync::atomic::AtomicU64; /// Settings that belong to each computer, never to the brain. -const LOCAL_KEYS: &[&str] = &["remote", "theme", "accent", "sidebar_collapsed", "sidebar_width", "selected", "machine_label", "local_execution", "local_never", "messages_send", "messages_no_ask"]; +const LOCAL_KEYS: &[&str] = &["remote", "theme", "accent", "sidebar_collapsed", "sidebar_width", "chats_column", "selected", "machine_label", "local_execution", "local_never", "messages_send", "messages_no_ask"]; /// 外觀 (底色、強調色、對比、密度、慶祝動畫): kept in this computer's own file and put back over the /// brain's whenever the brain's settings come — an update restarted the screen on its copy of the /// brain's, and a brain that doesn't know these (an older one) answered with 紙 and its clay every @@ -34,6 +34,7 @@ fn copy_own(to: &mut State, from: &State) { to.accent = from.accent; to.sidebar_collapsed = from.sidebar_collapsed; to.sidebar_width = from.sidebar_width; + to.chats_column = from.chats_column; to.machine_label = from.machine_label.clone(); to.local_execution = from.local_execution; to.local_never = from.local_never; @@ -47,7 +48,7 @@ fn copy_own(to: &mut State, from: &State) { to.motion = from.motion.clone(); } /// Bot fields the brain alone changes (its chat, and what a turn leaves behind). -const BOT_RUNTIME: &[&str] = &["id", "messages", "threads", "unread", "last_turn", "tasks", "context_tokens", "goal", "plan", "regen_undo", "branches", "branch_of"]; +const BOT_RUNTIME: &[&str] = &["id", "messages", "threads", "chat_title", "unread", "last_turn", "tasks", "context_tokens", "goal", "plan", "regen_undo", "branches", "branch_of"]; /// Stands in for a key or token the brain doesn't hand out. pub const REDACTED: &str = "••••(已設定,在大腦上)"; @@ -1464,6 +1465,8 @@ impl App { let b = &mut self.state.bots[i]; let msgs = std::mem::take(&mut b.messages); let threads = std::mem::take(&mut b.threads); + // (Not saved, so not in the JSON: a 換對話 the bot promised isn't lost to a setting.) + let chat_after = b.chat_after.take(); let mut v = serde_json::to_value(&*b).unwrap_or(Value::Null); let mut value = value; unredact(&mut value, &v[key]); @@ -1486,6 +1489,7 @@ impl App { let b = &mut self.state.bots[i]; b.messages = msgs; b.threads = threads; + b.chat_after = chat_after; ok } @@ -3228,6 +3232,7 @@ mod tests { from.accent = crate::model::Accent::BotColor; from.sidebar_collapsed = !from.sidebar_collapsed; from.sidebar_width += 40.0; + from.chats_column = !from.chats_column; from.machine_label = "工作機".into(); from.local_execution = !from.local_execution; from.local_never = !from.local_never; diff --git a/src/app/panel_ui.rs b/src/app/panel_ui.rs index 7d019a1..93195e2 100644 --- a/src/app/panel_ui.rs +++ b/src/app/panel_ui.rs @@ -13,6 +13,20 @@ pub enum PanelTab { Activity, /// 資料庫 Library, + /// 對話欄: this bot's conversations, the open one and 過去的對話 (the chat's top 「對話」). + Chats, +} + +/// 重新命名 in the 對話欄: which conversation (None: the open one; Some: 過去的對話 number i, +/// with its last message's time, to find it if the list moved meanwhile) and the words so far. +pub struct ChatRename { + pub bot: u64, + pub which: Option<(usize, i64)>, + /// Its name when the person started (another device may open or rename another meanwhile: + /// then this one isn't renamed). + pub shown: String, + pub text: String, + pub focused: bool, } pub const PANEL_WIDTH: f32 = 280.0; @@ -30,7 +44,18 @@ impl App { // Next to the chat when the chat keeps its minimum width; otherwise it floats over the // chat, so a narrow window never squeezes the chat. let avail = root.available_width(); + // The 對話欄 remembered from last time, in a window too narrow to set it beside the + // chat: not floated over the chat at start (it covered the title's buttons and 送出); + // the title's 對話 opens it. + // (Still remembered for a wider window next time.) + if tab == PanelTab::Chats && self.chats_remembered && avail - PANEL_MIN_WIDTH < CHAT_MIN_WIDTH { + self.panel = None; + self.chats_remembered = false; + return; + } if avail - PANEL_MIN_WIDTH >= CHAT_MIN_WIDTH { + // (Shown beside the chat once: from here on it is simply open.) + self.chats_remembered = false; let w = (avail - CHAT_MIN_WIDTH).min(PANEL_WIDTH); egui::Panel::right("bot-panel").exact_size(w).resizable(false).frame(Frame::new().fill(p.pane).inner_margin(Margin { left: 16, right: 16, top: 10, bottom: 12 })).show(root, |ui| keep_width(ui, |ui| self.panel_contents(ui, &ctx, bot, tab))); } else { @@ -47,12 +72,15 @@ impl App { } fn panel_contents(&mut self, ui: &mut egui::Ui, ctx: &egui::Context, bot: &Bot, tab: PanelTab) { + if tab == PanelTab::Chats { + return self.chats_column(ui, bot); + } let p = self.pal; // ✕ at the top right (36 px round, like the original). ui.horizontal(|ui| { ui.with_layout(Layout::right_to_left(Align::Center), |ui| { if round_button(ui, p, 36.0).on_hover_text(t("關閉")).clicked() { - self.panel = None; + self.set_panel(None); } }); }); @@ -91,11 +119,186 @@ impl App { match tab { PanelTab::Activity => self.panel_activity(ui, ctx, bot), PanelTab::Library => self.panel_library(ui, bot), + PanelTab::Chats => {} } ui.add_space(16.0); }); } + /// The right panel open on `tab` (None: closed). The 對話欄 is remembered on this computer: + /// it is there again after a restart, for someone who moves between projects all day. + /// The details (動態、資料庫) open over a remembered 對話欄 for a while: closed, the column + /// is back; only closing the column itself forgets it. + pub(super) fn set_panel(&mut self, tab: Option) { + if tab != Some(PanelTab::Chats) { + self.finish_chat_rename(true); + } + let back = tab.is_none() && self.panel.is_some_and(|t| t != PanelTab::Chats) && self.state.chats_column; + let tab = if back { Some(PanelTab::Chats) } else { tab }; + // (Back by itself, not pressed: in a window too narrow it doesn't float over the chat.) + self.chats_remembered = back; + self.panel = tab; + let keep = match tab { + Some(PanelTab::Chats) => true, + None => false, + Some(_) => self.state.chats_column, + }; + if self.state.chats_column != keep { + self.state.chats_column = keep; + self.mark(); + } + } + + /// The name typed in the 對話欄 is done: taken (`keep`; Enter, a click elsewhere, leaving) + /// or not (Esc). It goes to the conversation it was typed for, found again by its time if + /// the list moved meanwhile (gone: nothing); the same name as before changes nothing. + pub(super) fn finish_chat_rename(&mut self, keep: bool) { + let Some(e) = self.chat_rename.take() else { return }; + let Some(bot) = self.state.bot(e.bot).filter(|_| keep) else { return }; + let which = match e.which { + None => (bot.chat_name() == e.shown).then_some(None), + Some((i, at)) => bot.find_thread(i, at, &e.shown).map(Some), + }; + let was = match which { + Some(None) => Some(bot.chat_title.clone()), + Some(Some(i)) => bot.threads.get(i).map(|t| t.0.clone()), + None => None, + }; + if let (Some(which), Some(was)) = (which, was) { + if crate::model::clean_title(&e.text) != was { + self.rename_chat(e.bot, which, &e.text); + } + } + } + + /// 對話欄: this bot's conversations, the open one on top (its name, or its first line), then + /// 過去的對話, newest first. A click opens one; + starts a new one; ✎, a double click on the + /// open one or the right-click menu names one. Not while the bot works: changing the + /// conversation would stop it (the same as 搜尋's hits in past conversations). + fn chats_column(&mut self, ui: &mut egui::Ui, bot: &Bot) { + let p = self.pal; + let mut new_chat = false; + ui.horizontal(|ui| { + ui.add_space(6.0); + ui.label(RichText::new(t("對話")).size(FONT_H3).strong().family(crate::bold()).color(p.text)); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + if round_button(ui, p, 36.0).on_hover_text(t("關閉")).clicked() { + self.set_panel(None); + } + ui.add_space(4.0); + // (+, not the pen: ✎ on the rows names one.) + new_chat = crate::icons::button(ui, crate::icons::Icon::Plus, 32.0, p.text2, p.hover).on_hover_text(t("開始新對話")).clicked(); + }); + }); + ui.add_space(10.0); + let now = crate::model::now_ms(); + let last_at = |m: &[Message]| m.last().map(|m| m.at).unwrap_or(0); + // (The rows: which, name, the grey line, the time to find it by.) + let mut rows: Vec<(Option, String, String, i64)> = vec![(None, bot.chat_name(), if bot.messages.is_empty() { t("還沒有訊息") } else { t("目前的對話") }, 0)]; + for (i, (title, msgs)) in bot.threads.iter().enumerate() { + let at = last_at(msgs); + rows.push((Some(i), title.clone(), if at > 0 { crate::pages::ago(at, now) } else { String::new() }, at)); + } + // A name being typed for another bot's conversation (the person went to another bot + // with the keyboard): taken now, not left to come back when that bot is opened again. + if self.chat_rename.as_ref().is_some_and(|e| e.bot != bot.id) { + self.finish_chat_rename(true); + } + let (mut open, mut rename, mut done): (Option, Option>, Option) = (None, None, None); + egui::ScrollArea::vertical().id_salt(("chats", bot.id)).auto_shrink([false, false]).show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 2.0; + for (which, title, sub, at) in &rows { + let key = which.map(|i| (i, *at)); + let editing = self.chat_rename.as_ref().is_some_and(|e| e.bot == bot.id && e.which == key); + if editing { + let e = self.chat_rename.as_mut().unwrap(); + let hint = if which.is_none() { crate::model::auto_title(&bot.messages) } else { title.clone() }; + let r = ui.add(egui::TextEdit::singleline(&mut e.text).hint_text(hint).desired_width(f32::INFINITY).margin(Margin::symmetric(10, 12))); + if !e.focused { + r.request_focus(); + e.focused = true; + } + if r.lost_focus() { + done = Some(!ui.input(|i| i.key_pressed(egui::Key::Escape))); + } + continue; + } + let current = which.is_none(); + let (rect, r) = ui.allocate_exact_size(vec2(ui.available_width(), 48.0), egui::Sense::click()); + // (By where the pointer is, not r.hovered(): over the ✎ the row isn't the hovered + // one, and a ✎ shown only while it was flickered and took no click.) + let hovered = ui.rect_contains_pointer(rect); + if current { + ui.painter().rect_filled(rect, R_M, p.active); + } else if hovered { + ui.painter().rect_filled(rect, R_M, p.hover); + } + // ✎ on the row under the pointer (and always on the open one: it is the one named most). + let pen = egui::Rect::from_center_size(egui::pos2(rect.right() - 20.0, rect.center().y), vec2(28.0, 28.0)); + let w = rect.width() - 20.0 - if hovered || current { 32.0 } else { 0.0 }; + let shown = super::sidebar_ui::shorten_width(ui, title, w, 13.0); + let cut = shown != *title; + ui.painter().text(rect.left_top() + vec2(10.0, 8.0), egui::Align2::LEFT_TOP, shown, egui::FontId::new(FONT_SM, if current { crate::bold() } else { egui::FontFamily::Proportional }), p.text); + ui.painter().text(rect.left_top() + vec2(10.0, 27.0), egui::Align2::LEFT_TOP, super::sidebar_ui::shorten_width(ui, sub, w, 12.0), egui::FontId::proportional(FONT_XS), p.text3); + let r = if cut { r.on_hover_text(title.as_str()) } else { r }; + let r = r.on_hover_cursor(egui::CursorIcon::PointingHand); + let mut pen_hit = false; + if hovered || current { + let pr = ui.interact(pen, egui::Id::unique(("chat-pen", bot.id, key)), egui::Sense::click()).on_hover_text(t("重新命名")); + if pr.hovered() { + ui.painter().rect_filled(pen, R_S, p.hover); + } + crate::icons::paint(ui.painter(), egui::Rect::from_center_size(pen.center(), vec2(14.0, 14.0)), crate::icons::Icon::Pencil, p.text2); + pen_hit = pr.clicked(); + } + if pen_hit || (current && r.double_clicked()) { + rename = Some(key); + // (Not a double click's second press: the first one opened that row, and the list + // moved — the second landed on the one just put aside and opened it again.) + } else if r.clicked() && !r.double_clicked() && !r.triple_clicked() { + if let Some(i) = which { + open = Some(*i); + } + } + r.context_menu(|ui| { + if let Some(i) = which { + if menu_ui::item(ui, p, crate::icons::Icon::Chat, "打開這段對話").clicked() { + open = Some(*i); + ui.close(); + } + } + if menu_ui::item(ui, p, crate::icons::Icon::Pencil, "重新命名").clicked() { + rename = Some(key); + ui.close(); + } + }); + } + ui.add_space(12.0); + }); + if let Some(keep) = done { + self.finish_chat_rename(keep); + } + if let Some(key) = rename { + self.finish_chat_rename(true); + let (shown, text) = match key { + None => (bot.chat_name(), bot.chat_title.clone()), + Some((i, _)) => bot.threads.get(i).map(|t| (t.0.clone(), t.0.clone())).unwrap_or_default(), + }; + self.chat_rename = Some(ChatRename { bot: bot.id, which: key, shown, text, focused: false }); + } + // (A name being typed is taken before the list changes under it.) + if open.is_some() || new_chat { + self.finish_chat_rename(true); + } + if let Some(why) = (open.is_some() || new_chat).then(|| self.chat_pending(bot.id, true)).flatten() { + self.notice = Some(why); + } else if let Some(i) = open { + self.open_thread(bot.id, i); + } else if new_chat { + self.new_chat(bot.id); + } + } + fn panel_activity(&mut self, ui: &mut egui::Ui, ctx: &egui::Context, bot: &Bot) { let p = self.pal; // What it is doing now (only while there is something). diff --git a/src/app/remote_ui.rs b/src/app/remote_ui.rs index a0a3f99..e6826c1 100644 --- a/src/app/remote_ui.rs +++ b/src/app/remote_ui.rs @@ -346,6 +346,11 @@ impl App { self.approvals.get(&b.id).map(|a| (a.call_id.clone(), self.ask_keys.get(&b.id).cloned())).hash(&mut h); // The phone's home and bot sheet: its model, computer, routines and past chats. (b.provider, &b.model, &b.default_computer, b.threads.len(), b.id == self.state.primary_bot).hash(&mut h); + // (Their names too: one renamed, or one opened in place of the open one, keeps the count.) + (&b.chat_title, b.threads.first().map(|t| t.1.len())).hash(&mut h); + for t in b.threads.iter().take(20) { + t.0.hash(&mut h); + } for r in &b.routines { (r.id, &r.title, r.paused, r.next_run).hash(&mut h); } @@ -473,7 +478,11 @@ impl App { "provider": serde_json::to_value(b.provider).unwrap_or_default(), "model": b.model, "computer": computer, "computers": computers, "routines": b.routines.iter().map(|r| json!({"id": r.id, "title": r.title, "paused": r.paused, "when": crate::appctl::routine_when(r)})).collect::>(), - "threads": b.threads.iter().enumerate().rev().take(20).map(|(i, (title, msgs))| json!({"index": i, "title": title, "count": msgs.len(), "at": msgs.last().map(|m| m.at).unwrap_or(0)})).collect::>(), + // 過去的對話, newest first (the newest 20; it gave the oldest 20, oldest first), and + // what the open one is called. + "threads": b.threads.iter().enumerate().take(20).map(|(i, (title, msgs))| json!({"index": i, "title": title, "count": msgs.len(), "at": msgs.last().map(|m| m.at).unwrap_or(0)})).collect::>(), + "threads_total": b.threads.len(), + "chat_title": b.chat_name(), "chat_named": !b.chat_title.is_empty(), // The sidebar's sections, the colour by name (the editor), what is queued while it works. "folder": b.folder, "color_key": b.color, "order": raw_order.get(&b.id).copied().unwrap_or(0), // 聊天的顏色 (設定 › 一般): how the phone draws your bubbles — the same choice. @@ -527,6 +536,14 @@ impl App { if self.state.bot(bot).is_none() { return; } + // A new message to an idle bot: the person goes on here — a 換對話 it promised + // (still waiting on a 支線 or a colleague) is off. (Words while it works are part of + // that turn.) + if !self.streams.contains_key(&bot) { + if let Some(b) = self.state.bot_mut(bot) { + b.chat_after = None; + } + } // Typed on one of the account's computers: that one is the person's now (for // 「我的電腦」 and the model on their network). The phone isn't a computer. if !from.is_empty() && !member { @@ -630,20 +647,30 @@ impl App { } } Cmd::Resume { bot } => self.resume_turn(ctx, bot), - Cmd::RestoreThread { bot, index } => { - self.stop(bot); - if let Some(b) = self.state.bot_mut(bot) { - if index < b.threads.len() { - let (_, msgs) = b.threads.remove(index); - if !b.messages.is_empty() { - let title = b.messages.iter().find(|m| m.role == Role::User).map(|m| first_line(&m.text, 24)).unwrap_or_else(|| "對話".into()); - let cur = std::mem::take(&mut b.messages); - b.threads.insert(0, (title, cur.into_inner())); - } - b.messages = msgs.into(); + Cmd::RestoreThread { bot, index, at, was } => { + // (One gone meanwhile — opened on another device — changes nothing here.) + // Not while it works (a page too old to know, or one that saw it idle a moment ago): + // that would stop it — said in the chat, where the phone shows it. + if let Some(why) = self.chat_pending(bot, true) { + self.goal_note(bot, &format!("沒有換對話:{why}")); + } else if let Some(i) = self.state.bot(bot).and_then(|b| b.find_thread(index, at, &was)) { + self.leave_conversation(bot); + if let Some(b) = self.state.bot_mut(bot) { + b.open_thread(i); } + self.mark(); + } + } + Cmd::RenameThread { bot, index, at, was, title } => { + let which = match index { + // (The open one only if it is still the one the device showed.) + None => self.state.bot(bot).filter(|b| was.is_empty() || b.chat_name() == was).map(|_| None), + Some(i) => self.state.bot(bot).and_then(|b| b.find_thread(i, at, &was)).map(Some), + }; + if let (Some(which), Some(b)) = (which, self.state.bot_mut(bot)) { + b.rename_chat(which, &title); + self.mark(); } - self.mark(); } Cmd::Answer { bot, answer, text, call, notice, screen } => { // Only the card it was given for: every answer from afar (the phone's card, a @@ -704,11 +731,17 @@ impl App { } } Cmd::Seen { bot, att, device, kind, why, trusted } => self.delivery_seen(ctx, bot, &att, &device, kind, &why, trusted), - Cmd::Clear { bot } => { + Cmd::Clear { bot, was } if !was.is_empty() && self.state.bot(bot).is_some_and(|b| b.chat_name() != was) => { + let now = self.state.bot(bot).map(|b| b.chat_name()).unwrap_or_default(); + self.goal_note(bot, &format!("沒有清除聊天記錄:開著的已經換成「{now}」了,不是你看到的「{was}」。要清這段,再按一次。")); + self.mark(); + } + Cmd::Clear { bot, .. } => { self.goal_drop(bot); self.stop(bot); if let Some(b) = self.state.bot_mut(bot) { b.messages.clear(); + b.chat_title.clear(); } self.mark(); } @@ -732,14 +765,14 @@ impl App { self.mark(); } Cmd::NewThread { bot } => { - self.goal_drop(bot); - self.stop(bot); - if let Some(b) = self.state.bot_mut(bot) { - if !b.messages.is_empty() { - let title = b.messages.iter().find(|m| m.role == Role::User).map(|m| first_line(&m.text, 24)).unwrap_or_else(|| "對話".into()); - let msgs = std::mem::take(&mut b.messages); - b.threads.insert(0, (title, msgs.into_inner())); - b.threads.truncate(50); + // (Its running turn is stopped, as on the desktop; what can't be is waited for.) + if let Some(why) = self.chat_pending(bot, false) { + self.goal_note(bot, &format!("沒有開始新對話:{why}")); + } else { + self.leave_conversation(bot); + self.stop(bot); + if let Some(b) = self.state.bot_mut(bot) { + b.put_aside(); } } self.mark(); @@ -1530,8 +1563,10 @@ impl App { .into_iter() .map(|h| { let bname = self.state.bot(h.bot).map(|x| x.name.clone()).unwrap_or_default(); - let tname = h.thread.and_then(|ti| self.state.bot(h.bot).and_then(|x| x.threads.get(ti)).map(|t| t.0.clone())); - json!({"bot": h.bot, "bot_name": bname, "thread": h.thread, "thread_title": tname, "index": h.index, "at": h.at, "mine": h.mine, "file": h.file, "snippet": h.snippet}) + let th = h.thread.and_then(|ti| self.state.bot(h.bot).and_then(|x| x.threads.get(ti))); + // (With that conversation's last time: 回到 finds it if the list moved.) + let (tname, tat) = (th.map(|t| t.0.clone()), th.and_then(|t| t.1.last()).map(|m| m.at).unwrap_or(0)); + json!({"bot": h.bot, "bot_name": bname, "thread": h.thread, "thread_title": tname, "thread_at": tat, "index": h.index, "at": h.at, "mine": h.mine, "file": h.file, "snippet": h.snippet}) }) .collect(); json!({"ok": true, "hits": items, "more": more}) @@ -1905,7 +1940,12 @@ impl App { done("繼續中…") } "clear" => { - self.remote_cmd(ctx, Cmd::Clear { bot }); + // (The conversation the phone showed: another opened meanwhile isn't wiped.) + let was = s("was"); + if let Some(now) = self.state.bot(bot).map(|b| b.chat_name()).filter(|now| !was.is_empty() && *now != was) { + return fail(&format!("開著的對話已經換成「{now}」了:重新整理再清除")); + } + self.remote_cmd(ctx, Cmd::Clear { bot, was }); done("已清除聊天記錄") } "delete_page" => { @@ -2318,7 +2358,7 @@ impl App { "runs": r.runs.iter().rev().take(5).map(|x| json!({"line": crate::routines::describe_run(x, &r.schedule.timezone), "bad": matches!(x.outcome, crate::routines::RunOutcome::Failed | crate::routines::RunOutcome::Interrupted), "sends": x.sends})).collect::>(), "target": crate::appctl::target_words(r), })).collect::>(), - "threads": b.threads.iter().enumerate().rev().map(|(i, (title, msgs))| json!({"index": i, "title": title, "count": msgs.len(), "at": msgs.last().map(|m| m.at).unwrap_or(0)})).collect::>(), + "threads": b.threads.iter().enumerate().map(|(i, (title, msgs))| json!({"index": i, "title": title, "count": msgs.len(), "at": msgs.last().map(|m| m.at).unwrap_or(0)})).collect::>(), "files": files, }) } @@ -2441,6 +2481,264 @@ mod phone_act_tests { (ctx, app) } + /// 對話 from a phone: 開始新對話, 命名 (the open one and a past one), 回到這段對話 by a list + /// that moved since (opened on another device meanwhile) — the one the phone showed, or + /// nothing. The phone's lists are newest first, and a new name reaches the phone. + #[test] + fn a_phone_names_and_switches_conversations() { + let (ctx, mut app) = demo(); + let bot = app.state.bots[0].id; + { + let b = app.state.bot_mut(bot).unwrap(); + b.threads = Vec::new().into(); + b.messages = vec![Message { at: 100, ..Message::user("網站首頁") }].into(); + } + let sig = app.remote_signature(); + // The open one, as the phone showed it: named. A phone that still showed another (one + // opened elsewhere meanwhile): nothing. + app.remote_cmd(&ctx, Cmd::RenameThread { bot, index: None, at: 0, was: "網站首頁".into(), title: "網站改版".into() }); + assert_eq!(app.state.bot(bot).unwrap().chat_title, "網站改版"); + app.remote_cmd(&ctx, Cmd::RenameThread { bot, index: None, at: 0, was: "別段".into(), title: "不該出現".into() }); + assert_eq!(app.state.bot(bot).unwrap().chat_title, "網站改版"); + assert_ne!(app.remote_signature(), sig, "the phone is sent the new name"); + app.remote_cmd(&ctx, Cmd::NewThread { bot }); + { + let b = app.state.bot_mut(bot).unwrap(); + assert_eq!((b.threads[0].0.as_str(), b.chat_title.as_str()), ("網站改版", "")); + b.messages = vec![Message { at: 200, ..Message::user("報價單") }].into(); + } + app.remote_cmd(&ctx, Cmd::NewThread { bot }); + let titles = |app: &App| app.state.bot(bot).unwrap().threads.iter().map(|t| t.0.clone()).collect::>(); + assert_eq!(titles(&app), ["報價單", "網站改版"]); + let detail = app.phone_detail(app.state.bot(bot).unwrap(), true); + assert_eq!(detail["threads"].as_array().unwrap().iter().map(|t| t["title"].as_str().unwrap()).collect::>(), ["報價單", "網站改版"], "newest first"); + // The phone's list said 網站改版 was number 1; meanwhile 報價單 was opened elsewhere and + // the list moved: 改名 and 回到 still reach 網站改版. + app.remote_cmd(&ctx, Cmd::RestoreThread { bot, index: 0, at: 200, was: "報價單".into() }); + assert_eq!(titles(&app), ["網站改版"]); + app.remote_cmd(&ctx, Cmd::RenameThread { bot, index: Some(1), at: 100, was: "網站改版".into(), title: "官網".into() }); + assert_eq!(titles(&app), ["官網"]); + app.remote_cmd(&ctx, Cmd::RestoreThread { bot, index: 1, at: 100, was: "官網".into() }); + let b = app.state.bot(bot).unwrap(); + assert_eq!((b.chat_title.as_str(), b.messages[0].text.as_str()), ("官網", "網站首頁")); + assert_eq!(titles(&app), ["報價單"]); + // One that is gone (opened already): nothing changes. + app.remote_cmd(&ctx, Cmd::RestoreThread { bot, index: 0, at: 100, was: "官網".into() }); + assert_eq!((app.state.bot(bot).unwrap().chat_title.as_str(), titles(&app)), ("官網", vec!["報價單".to_string()])); + // 清除聊天記錄 takes the name too. + app.remote_cmd(&ctx, Cmd::Clear { bot, was: String::new() }); + assert_eq!(app.state.bot(bot).unwrap().chat_title, ""); + } + + /// 目標 and 計畫 belong to the conversation they were set in: opening another one ends them + /// (they used to go on in the other conversation — a turn there ran with the first one's + /// plan), and a line in the one put aside says what stopped and how to go on. + #[test] + fn switching_conversations_ends_its_goal_and_plan_with_a_line() { + let (ctx, mut app) = demo(); + let bot = app.state.bots[0].id; + app.streams.remove(&bot); + { + let b = app.state.bot_mut(bot).unwrap(); + b.messages = vec![Message { at: 300, ..Message::user("專案甲") }].into(); + b.threads = vec![("專案乙".into(), vec![Message { at: 100, ..Message::user("乙") }])].into(); + b.goal = Some(crate::goal::Goal::new("測試都通過", 1)); + b.plan = Some(crate::plan::Plan::new("搬到新主機", 1)); + } + app.remote_cmd(&ctx, Cmd::RestoreThread { bot, index: 0, at: 100, was: "專案乙".into() }); + let b = app.state.bot(bot).unwrap(); + assert!(b.goal.is_none() && b.plan.is_none(), "not carried into 專案乙"); + assert_eq!(b.messages[0].text, "乙"); + let line = b.threads[0].1.iter().find(|m| m.note).map(|m| m.text.clone()).unwrap_or_default(); + assert!(line.contains("目標「測試都通過」") && line.contains("計畫「搬到新主機」") && line.contains("/goal"), "{line}"); + // Nothing set: no line. + app.remote_cmd(&ctx, Cmd::NewThread { bot }); + assert!(!app.state.bot(bot).unwrap().threads[0].1.iter().any(|m| m.note)); + } + + /// 「換到報價單那段」 asked of the bot (switch_conversation): done when its turn is over and + /// nothing else is to follow in this conversation — never under it; a target gone meanwhile + /// is said, not guessed. A phone's 回到 while the bot works changes nothing (a line says so). + #[test] + fn a_switch_asked_of_the_bot_waits_for_its_turn() { + let (ctx, mut app) = demo(); + let bot = app.state.bots[0].id; + app.streams.remove(&bot); + app.waiting_wakes.clear(); + app.pending_turns.clear(); + { + let b = app.state.bot_mut(bot).unwrap(); + b.messages = vec![Message { at: 300, ..Message::user("專案甲") }].into(); + b.threads = vec![("報價單".into(), vec![Message { at: 100, ..Message::user("報價") }])].into(); + b.plan = Some(crate::plan::Plan::new("搬家", 1)); + } + let r = crate::appctl::apply(&mut app.state, bot, "switch_conversation", r#"{"conversation":"報價"}"#); + assert!(r.ok && r.text.contains("「報價單」"), "{}", r.text); + assert_eq!(app.state.bot(bot).unwrap().messages[0].text, "專案甲", "not under the turn"); + // AnyBot's correction is still to run here: it waits. + app.waiting_wakes.push((bot, Message::user("更正"))); + app.chat_after_turn(bot); + assert_eq!(app.state.bot(bot).unwrap().messages[0].text, "專案甲"); + app.waiting_wakes.clear(); + app.chat_after_turn(bot); + let b = app.state.bot(bot).unwrap(); + assert_eq!((b.messages[0].text.as_str(), b.chat_title.as_str()), ("報價", "報價單")); + assert!(b.plan.is_none() && b.chat_after.is_none()); + assert!(b.threads[0].1.iter().any(|m| m.note && m.text.contains("計畫「搬家」"))); + // Asked for one that is gone by then: said, nothing switched. + crate::appctl::apply(&mut app.state, bot, "switch_conversation", r#"{"conversation":"專案甲"}"#); + app.state.bot_mut(bot).unwrap().threads[0].0 = "改了名".into(); + app.chat_after_turn(bot); + let b = app.state.bot(bot).unwrap(); + assert_eq!(b.messages[0].text, "報價"); + assert!(b.messages.iter().any(|m| m.note && m.text.contains("沒有換到「專案甲」"))); + // 開始新對話 called 網站改版, asked: the open one put aside with its name, the new one named. + crate::appctl::apply(&mut app.state, bot, "switch_conversation", r#"{"new":true,"name":"網站改版"}"#); + app.chat_after_turn(bot); + let b = app.state.bot(bot).unwrap(); + assert!(b.messages.is_empty() && b.threads[0].0 == "報價單" && b.chat_title == "網站改版"); + // Switch to 報價單, then rename it in the same turn: still found, by its new name. + app.state.bot_mut(bot).unwrap().messages = vec![Message { at: 500, ..Message::user("新的這段") }].into(); + assert!(crate::appctl::apply(&mut app.state, bot, "switch_conversation", r#"{"conversation":"報價單"}"#).ok); + assert!(crate::appctl::apply(&mut app.state, bot, "rename_conversation", r#"{"conversation":"報價單","name":"Q3 報價"}"#).ok); + app.chat_after_turn(bot); + assert_eq!(app.state.bot(bot).unwrap().chat_title, "Q3 報價"); + // Not understood: refused, nothing waits. + assert!(!crate::appctl::apply(&mut app.state, bot, "switch_conversation", "{}").ok); + assert!(!crate::appctl::apply(&mut app.state, bot, "switch_conversation", r#"{"conversation":"沒有這段"}"#).ok); + assert!(app.state.bot(bot).unwrap().chat_after.is_none()); + // A phone's 回到 while it works: not switched, said in the chat. + let now = Instant::now(); + app.state.bot_mut(bot).unwrap().messages = vec![Message { at: 400, ..Message::user("工作中") }].into(); + app.streams.insert(bot, Live { cancel: Arc::new(AtomicBool::new(false)), started: now, last: now, produced: true, status: None, paused: false, paused_at: None, unattended: false, steer: Arc::new(Mutex::new(vec![])), direct: Arc::new(AtomicBool::new(false)), turn_id: "t".into(), turn: 1 }); + app.remote_cmd(&ctx, Cmd::RestoreThread { bot, index: 0, at: 0, was: "報價單".into() }); + let b = app.state.bot(bot).unwrap(); + assert!(b.messages.iter().any(|m| m.text == "工作中") && b.messages.iter().any(|m| m.note && m.text.contains("沒有換對話"))); + app.streams.remove(&bot); + } + + /// A 換對話 the bot promised, then the person clears the chat (or stops it) while it works: + /// the switch is off and what is cleared is the conversation they were looking at — it used + /// to switch inside the stop and clear the other one. + #[test] + fn clearing_or_stopping_calls_off_a_switch_the_bot_promised() { + let (ctx, mut app) = demo(); + let bot = app.state.bots[0].id; + app.waiting_wakes.clear(); + app.pending_turns.clear(); + app.reports.clear(); + let live = || { + let now = Instant::now(); + Live { cancel: Arc::new(AtomicBool::new(false)), started: now, last: now, produced: true, status: None, paused: false, paused_at: None, unattended: false, steer: Arc::new(Mutex::new(vec![])), direct: Arc::new(AtomicBool::new(false)), turn_id: "t".into(), turn: 1 } + }; + { + let b = app.state.bot_mut(bot).unwrap(); + b.messages = vec![Message { at: 300, ..Message::user("這段要清掉") }].into(); + b.threads = vec![("報價單".into(), vec![Message { at: 100, ..Message::user("報價") }])].into(); + } + assert!(crate::appctl::apply(&mut app.state, bot, "switch_conversation", r#"{"conversation":"報價單"}"#).ok); + app.streams.insert(bot, live()); + app.remote_cmd(&ctx, Cmd::Clear { bot, was: "這段要清掉".into() }); + app.chat_after_turn(bot); + let b = app.state.bot(bot).unwrap(); + assert!(b.chat_after.is_none() && !b.messages.iter().any(|m| m.text == "報價"), "not switched"); + assert_eq!((b.threads[0].0.as_str(), b.threads[0].1[0].text.as_str()), ("報價單", "報價"), "報價單 kept whole"); + // 停止 too. + app.state.bot_mut(bot).unwrap().messages = vec![Message { at: 600, ..Message::user("做事中") }].into(); + assert!(crate::appctl::apply(&mut app.state, bot, "switch_conversation", r#"{"new":true}"#).ok); + app.streams.insert(bot, live()); + app.remote_cmd(&ctx, Cmd::Stop { bot }); + app.chat_after_turn(bot); + let b = app.state.bot(bot).unwrap(); + assert!(b.chat_after.is_none() && b.messages.iter().any(|m| m.text == "做事中")); + // A switch isn't done at a turn's end (settle) any more, only on a tick: here, none. + assert!(crate::appctl::apply(&mut app.state, bot, "switch_conversation", r#"{"new":true}"#).ok); + app.streams.insert(bot, live()); + app.settle(bot, TurnOutcome::Success); + assert!(app.state.bot(bot).unwrap().messages.iter().any(|m| m.text == "做事中"), "not inside settle"); + assert!(app.state.bot(bot).unwrap().chat_after.is_some()); + } + + /// What is still on its way to the open conversation keeps it open: a 「/compact」 being + /// written, a 支線 working, a colleague on what this bot handed it — opening another (or a + /// new one) then would have put the summary or the report there. Said in the chat. And a + /// switch the bot promised isn't done after a turn that went wrong. + #[test] + fn nothing_on_its_way_lands_in_another_conversation() { + let (ctx, mut app) = demo(); + let (bot, other) = (app.state.bots[0].id, app.state.bots[1].id); + app.streams.clear(); + app.waiting_wakes.clear(); + app.pending_turns.clear(); + app.reports.clear(); + app.group_next.clear(); + app.state.branch_bots.clear(); + let reset = |app: &mut App| { + let b = app.state.bot_mut(bot).unwrap(); + b.messages = vec![Message { at: 300, ..Message::user("專案甲") }].into(); + b.threads = vec![("報價單".into(), vec![Message { at: 100, ..Message::user("報價") }])].into(); + }; + let tried = |app: &mut App, why: &str| { + app.remote_cmd(&ctx, Cmd::RestoreThread { bot, index: 0, at: 100, was: "報價單".into() }); + app.remote_cmd(&ctx, Cmd::NewThread { bot }); + let b = app.state.bot(bot).unwrap(); + assert_eq!((b.messages[0].text.as_str(), b.threads.len()), ("專案甲", 1), "{why}: stayed"); + assert!(b.messages.iter().any(|m| m.note && m.text.contains("沒有換對話") && m.text.contains(why)), "{why}: said"); + assert!(b.messages.iter().any(|m| m.note && m.text.contains("沒有開始新對話") && m.text.contains(why)), "{why}: said for new"); + }; + reset(&mut app); + app.compacting.insert(bot, Instant::now()); + tried(&mut app, "整理成摘要"); + // (One whose summary never came back holds nothing after 10 minutes.) + app.compacting.insert(bot, Instant::now() - std::time::Duration::from_secs(601)); + assert!(app.chat_pending(bot, true).is_none()); + app.compacting.clear(); + reset(&mut app); + let mut br = app.state.bot(bot).unwrap().clone(); + br.id = 77; + br.branch_of = bot; + app.state.branch_bots.push(br); + tried(&mut app, "支線"); + app.state.branch_bots.clear(); + // One still to start (waiting for the main turn, or its clash check on the way) holds too: + // it would start from the conversation open then. + reset(&mut app); + app.state.bot_mut(bot).unwrap().branches = vec![crate::model::Branch { id: 78, task: "查匯率".into(), at: 1, state: crate::model::BranchState::Waiting, ..Default::default() }]; + tried(&mut app, "支線"); + app.state.bot_mut(bot).unwrap().branches[0].state = crate::model::BranchState::Done; + assert!(app.chat_pending(bot, true).is_none()); + reset(&mut app); + let now = Instant::now(); + app.state.bot_mut(other).unwrap().messages.push(Message { from_bot: bot, ..Message::user("幫我查價格") }); + app.streams.insert(other, Live { cancel: Arc::new(AtomicBool::new(false)), started: now, last: now, produced: true, status: None, paused: false, paused_at: None, unattended: false, steer: Arc::new(Mutex::new(vec![])), direct: Arc::new(AtomicBool::new(false)), turn_id: "t".into(), turn: 1 }); + tried(&mut app, "交辦"); + let other_name = app.state.bot(other).unwrap().name.clone(); + assert!(app.chat_pending(bot, true).is_some_and(|w| w.contains(&format!("到「{other_name}」按停止"))), "names the colleague and the way out"); + app.streams.clear(); + // Handed over but not started (waiting behind the colleague's other work): doesn't hold + // the conversation — that could be any time. + app.waiting_wakes.push((other, Message { from_bot: bot, ..Message::user("再查一次") })); + assert!(app.chat_pending(bot, true).is_none()); + app.waiting_wakes.clear(); + // Nothing on its way: it opens. + app.remote_cmd(&ctx, Cmd::RestoreThread { bot, index: 0, at: 100, was: "報價單".into() }); + assert_eq!(app.state.bot(bot).unwrap().messages[0].text, "報價"); + // 清除聊天記錄 from a screen that still showed another conversation: not cleared, said; + // from the phone: refused at once. + app.remote_cmd(&ctx, Cmd::Clear { bot, was: "專案甲".into() }); + let b = app.state.bot(bot).unwrap(); + assert!(b.messages.iter().any(|m| m.text == "報價") && b.messages.iter().any(|m| m.note && m.text.contains("沒有清除聊天記錄"))); + let r = app.phone_act(&ctx, "clear", &json!({"bot": bot, "was": "專案甲"}), "owner"); + assert!(r["error"].as_str().is_some_and(|e| e.contains("「報價單」")), "{r}"); + assert!(app.state.bot(bot).unwrap().messages.iter().any(|m| m.text == "報價")); + // A switch promised in a turn that then went wrong: not done, said. + assert!(crate::appctl::apply(&mut app.state, bot, "switch_conversation", r#"{"new":true}"#).ok); + app.state.bot_mut(bot).unwrap().last_turn = Some(TurnSettlement { turn_id: "t".into(), outcome: TurnOutcome::Error, settled_at_ms: 1 }); + app.chat_after_turn(bot); + let b = app.state.bot(bot).unwrap(); + assert!(b.chat_after.is_none() && b.messages[0].text == "報價" && b.messages.iter().any(|m| m.note && m.text.contains("沒有順利做完"))); + } + /// 允許/拒絕 on a phone notification answers only the request it showed: once that one /// is gone and another waits, the old banner answers nothing (a note says so). And only a /// request to allow that fits on the banner: never 我完成了, 略過 or 一律允許 from there. diff --git a/src/app/sidebar_ui.rs b/src/app/sidebar_ui.rs index aa615e2..20940d9 100644 --- a/src/app/sidebar_ui.rs +++ b/src/app/sidebar_ui.rs @@ -572,7 +572,11 @@ impl App { let when = if h.at > 0 { crate::pages::ago(h.at, now) } else { String::new() }; let when_w = painter.layout_no_wrap(when.clone(), egui::FontId::proportional(FONT_XS), p.text3).size().x; painter.text(inner.right_top() + vec2(0.0, 1.0), egui::Align2::RIGHT_TOP, &when, egui::FontId::proportional(FONT_XS), p.text3); - let name = if h.thread.is_some() { format!("{} · {}", b.name, t("過去的對話")) } else { b.name.clone() }; + // (Which past conversation: its name — a project's, when the person named it.) + let name = match h.thread { + Some(i) => format!("{} · {}", b.name, b.threads.get(i).map(|t| t.0.clone()).unwrap_or_else(|| t("過去的對話"))), + None => b.name.clone(), + }; let name = shorten_width(ui, &name, (inner.width() - when_w - 8.0).max(30.0), 13.0); painter.text(inner.left_top(), egui::Align2::LEFT_TOP, name, egui::FontId::new(FONT_SM, crate::bold()), p.text); let said = format!("{}{}", if h.file { t("檔案:") } else if h.mine { t("你:") } else { String::new() }, h.snippet); @@ -596,9 +600,8 @@ impl App { // conversation back first — not while the bot is working, which that would stop. if let Some(h) = open_hit.and_then(|i| hits.get(i)).cloned() { let ctx = ui.ctx().clone(); - if h.thread.is_some() && self.streams.contains_key(&h.bot) { - let name = self.state.bot(h.bot).map(|b| b.name.clone()).unwrap_or_default(); - self.notice = Some(t("「{name}」正在工作。等它做完,再打開過去的對話。").replace("{name}", &name)); + if let Some(why) = h.thread.and_then(|_| self.chat_pending(h.bot, true)) { + self.notice = Some(why); } else { if let Some(i) = h.thread { self.open_thread(h.bot, i); diff --git a/src/appctl.rs b/src/appctl.rs index 53c49db..ff5e6e6 100644 --- a/src/appctl.rs +++ b/src/appctl.rs @@ -9,7 +9,7 @@ use crate::model::{self, Bot, Message, State, Theme, Accent}; use crate::providers::{ProviderKind, ALL_PROVIDERS}; use crate::routines::{self, Routine, Schedule}; -pub const NAMES: [&str; 34] = [ +pub const NAMES: [&str; 37] = [ // 追進度: follow something long in the background (followup.rs; checks run on the brain). "follow_up", // 任務: the tasks and their states as AnyBot works them out (tasks.rs; read-only). @@ -22,6 +22,9 @@ pub const NAMES: [&str; 34] = [ // 問同事: ask another bot and wait for its answer (the window runs its turn, see app/asks.rs); // 教技能: give a colleague a skill this bot has (the person says yes first). "ask_bot", "teach_skill", + // 對話: the conversations as the person's 對話 list shows them, their names + // (Bot::rename_chat), and 換對話 — done when the turn is over, not under it (Bot::chat_after). + "list_conversations", "rename_conversation", "switch_conversation", "remember", "forget", "search_memory", "save_skill", "use_skill", "delete_skill", "skill_install", "skillify", "create_group", "move_to_group", "rename_group", "delete_group", "look_image", // 個人檔案: a bot looks at its own settings and changes them when the person asks (each change @@ -63,6 +66,9 @@ pub fn label(name: &str) -> &'static str { "update_settings" => "修改設定", "remember" => "記住", "forget" => "忘記", + "rename_conversation" => "為對話取名", + "list_conversations" => "查看對話", + "switch_conversation" => "換對話", "search_memory" => "翻記憶", "save_skill" => "存成技能", "use_skill" => "讀取技能", @@ -144,6 +150,17 @@ pub fn specs() -> Vec { "parameters": {"type": "object", "properties": {"name": {"type": "string"}, "bots": {"type": "array", "items": {"type": "string"}, "description": "Bot names to move into it"}}, "required": ["name"]}}), json!({"name": "move_to_group", "description": "Move bots into a sidebar section (分區; made if it doesn't exist). An empty group name moves them back to 未分區.", "parameters": {"type": "object", "properties": {"group": {"type": "string"}, "bots": {"type": "array", "items": {"type": "string"}}}, "required": ["group", "bots"]}}), + json!({"name": "list_conversations", "description": "List your conversations with the person as their 對話 list shows them (top right of the chat on a computer, 🕘 on the phone): the open one, then the past ones (過去的對話), newest first, with their names and when each was last used. Read-only. Rename them with rename_conversation; switch to one (or a new one) with switch_conversation when the person asks.", + "parameters": {"type": "object", "properties": {}}}), + json!({"name": "switch_conversation", "description": "Change which conversation is open in this chat, when the person asks: back to one of the past ones (by its name as list_conversations shows it), or a new empty one (new: true). It happens once this turn — and anything that follows it here — is over, so finish your reply first: it stays in the conversation open now. The open one goes to the person's 過去的對話 with its name; its /goal and /plan stop (a line there says so). If the person stops you or clears the chat first, it doesn't happen. To name the one you switch to (\"開個新對話叫網站改版\"), give `name` here: rename_conversation in this turn still names the one open now.", + "parameters": {"type": "object", "properties": { + "conversation": {"type": "string", "description": "A past conversation, by its name now as list_conversations shows it (or a part of it only that one has)."}, + "new": {"type": "boolean", "description": "true: start a new, empty conversation instead."}, + "name": {"type": "string", "description": "Name the conversation switched to: one line, at most 40 characters (left out: as it is)."}}}}), + json!({"name": "rename_conversation", "description": "Name one of your conversations as the person sees it in their 對話 list — e.g. a project's name, when they use you for several projects. Only when the person asks to name or rename a conversation. The open one unless `conversation` names a past one. An empty name shows its first line again. It changes nothing you know or remember: memories, instructions and files are shared by all your conversations.", + "parameters": {"type": "object", "properties": { + "name": {"type": "string", "description": "The new name: one line, at most 40 characters ('' = its first line again)."}, + "conversation": {"type": "string", "description": "A past conversation, by its name now as list_conversations shows it (or a part of it only that one has). Leave out for the open conversation."}}, "required": ["name"]}}), json!({"name": "rename_group", "description": "Rename a sidebar section (分區).", "parameters": {"type": "object", "properties": {"group": {"type": "string"}, "new_name": {"type": "string"}}, "required": ["group", "new_name"]}}), json!({"name": "delete_group", "description": "Delete a sidebar section (分區); its bots move to 未分區 (no bot is deleted).", "parameters": {"type": "object", "properties": {"group": {"type": "string"}}, "required": ["group"]}}), json!({"name": "message_bot", "description": "Hand work to another bot and don't wait: sends it a message and wakes it up. When it's done its answer is reported back into this chat by itself. When you need its answer to go on, use ask_bot.", @@ -225,6 +242,11 @@ pub fn describe(name: &str, args: &str) -> String { "look_image" => format!("#{}:{}", v.get("index").and_then(Value::as_u64).unwrap_or(0), s("question").chars().take(30).collect::()), "remember" => s("fact").chars().take(40).collect(), "forget" => s("what"), + "switch_conversation" => if v.get("new").and_then(Value::as_bool) == Some(true) { "開始新對話".into() } else { s("conversation") }, + "rename_conversation" => match s("conversation") { + c if c.trim().is_empty() => s("name"), + c => format!("「{c}」→「{}」", s("name")), + }, "search_memory" => s("query"), "update_my_profile" => v.as_object().map(|o| o.keys().map(|k| crate::profile::field_label(k)).collect::>().join("、")).unwrap_or_default(), n if crate::pages::NAMES.contains(&n) => crate::pages::describe(n, &v), @@ -806,6 +828,74 @@ pub fn apply(state: &mut State, bot_id: u64, name: &str, args: &str) -> Outcome Err(e) => err(e), } } + "rename_conversation" => { + // (A 支線's chat isn't in the person's list; the main one is theirs to name.) + if asker != bot_id { + return err("支線改不了對話的名字:回到主線再請它改。".into()); + } + // (Left out isn't 「back to its first line」: that is an empty name, given.) + let Some(name) = s("name") else { return err("給新名字(name;空字串=回到第一句話)".into()) }; + let Some(b) = state.bot_mut(bot_id) else { return err("找不到這個 Bot".into()) }; + // A past one: by its whole name, or a part of it only that one has. + if let Some(c) = s("conversation").map(|c| c.trim().to_string()).filter(|c| !c.is_empty()) { + let find = |whole: bool| b.threads.iter().enumerate().filter(|(_, t)| if whole { t.0 == c } else { t.0.contains(&c) }).map(|(i, _)| i).collect::>(); + let (whole, part) = (find(true), find(false)); + let i = match (whole.as_slice(), part.as_slice()) { + ([i], _) | ([], [i]) => *i, + ([], []) => return err(format!("過去的對話裡沒有叫「{c}」的:先用 list_conversations 看名字。")), + _ => return err(format!("不只一段過去的對話叫「{c}」:用 list_conversations 看完整的名字再指定。")), + }; + let was = b.threads[i].0.clone(); + b.rename_chat(Some(i), &name); + let now = b.threads[i].0.clone(); + // (The one a switch asked for this turn is waiting to open: it is found by its new name.) + if let Some(model::ChatAfter::Open { title, .. }) = b.chat_after.as_mut().filter(|c| matches!(c, model::ChatAfter::Open { title, .. } if *title == was)) { + *title = now.clone(); + } + return ok(format!("過去的對話「{was}」改叫「{now}」了。")); + } + b.rename_chat(None, &name); + let shown = b.chat_name(); + ok(if b.chat_title.is_empty() { format!("這段對話不另外取名了:清單上顯示它的第一句話「{shown}」。") } else { format!("這段對話叫「{shown}」了:使用者的對話清單和聊天上方的「對話」都是這個名字。") }) + } + "switch_conversation" => { + if asker != bot_id { + return err("支線換不了對話:回到主線再請它換。".into()); + } + let Some(b) = state.bot_mut(bot_id) else { return err("找不到這個 Bot".into()) }; + let name = model::clean_title(&s("name").unwrap_or_default()); + let called = if name.is_empty() { String::new() } else { format!(",叫「{name}」") }; + if v.get("new").and_then(Value::as_bool) == Some(true) { + b.chat_after = Some(model::ChatAfter::New { name }); + return ok(format!("這一輪做完就開始新對話{called}:你這則回覆留在現在這段,這段收進過去的對話。")); + } + let Some(c) = s("conversation").map(|c| c.trim().to_string()).filter(|c| !c.is_empty()) else { return err("說要換到哪一段(conversation,list_conversations 看名字),或 new: true 開始新對話".into()) }; + let find = |whole: bool| b.threads.iter().enumerate().filter(|(_, t)| if whole { t.0 == c } else { t.0.contains(&c) }).map(|(i, _)| i).collect::>(); + let i = match (find(true).as_slice(), find(false).as_slice()) { + ([i], _) | ([], [i]) => *i, + ([], []) => return err(format!("過去的對話裡沒有叫「{c}」的:先用 list_conversations 看名字。")), + _ => return err(format!("不只一段過去的對話叫「{c}」:用 list_conversations 看完整的名字再指定。")), + }; + let (title, at) = (b.threads[i].0.clone(), b.threads[i].1.last().map(|m| m.at).unwrap_or(0)); + b.chat_after = Some(model::ChatAfter::Open { title: title.clone(), at, name }); + ok(format!("這一輪做完就換到「{title}」{called}:你這則回覆留在現在這段,這段收進過去的對話。")) + } + "list_conversations" => { + let Some(b) = state.bot(bot_id) else { return err("找不到這個 Bot".into()) }; + let now_ms = crate::model::now_ms(); + let mut lines = vec![format!("目前的對話:「{}」({} 則{})", b.chat_name(), b.messages.len(), if b.chat_title.is_empty() { ";沒取名,顯示第一句話" } else { "" })]; + if b.threads.is_empty() { + lines.push("沒有過去的對話。".into()); + } else { + lines.push(format!("過去的對話({} 段,新的在前):", b.threads.len())); + for (t, msgs) in b.threads.iter() { + let at = msgs.last().map(|m| m.at).unwrap_or(0); + lines.push(format!("- 「{t}」{},{} 則", if at > 0 { format!(" {}", crate::pages::ago(at, now_ms)) } else { String::new() }, msgs.len())); + } + } + lines.push("使用者自己從聊天右上的「對話」(手機標題列 🕘)換;請你換時用 switch_conversation。".into()); + ok(lines.join("\n")) + } "forget" => { let what = s("what").unwrap_or_default(); let Some(b) = state.bot_mut(bot_id) else { return err("找不到這個 Bot".into()) }; @@ -962,6 +1052,8 @@ pub fn apply(state: &mut State, bot_id: u64, name: &str, args: &str) -> Outcome memories: vec![], members: vec![], threads: Default::default(), + chat_title: String::new(), + chat_after: None, context_tokens: model::default_context_tokens(), model_limits: Default::default(), follow_ups: vec![], @@ -1467,6 +1559,43 @@ mod tests { assert_eq!(st.timezone, "Asia/Tokyo"); } + /// 「這段對話叫網站改版」: the bot names the open conversation (what the 對話 list shows); an + /// empty name is its first line again; a 支線 can't (its chat isn't in the person's list). + #[test] + fn a_bot_names_the_open_conversation() { + let mut st = State::demo(); + let id = st.bots[0].id; + st.bots[0].messages = vec![Message::user("首頁要改")].into(); + let r = apply(&mut st, id, "rename_conversation", r#"{"name":"網站改版"}"#); + assert!(r.ok && r.text.contains("網站改版"), "{}", r.text); + assert_eq!(st.bots[0].chat_name(), "網站改版"); + assert!(apply(&mut st, id, "rename_conversation", r#"{"name":""}"#).text.contains("首頁要改")); + assert_eq!(st.bots[0].chat_title, ""); + assert!(NAMES.contains(&"rename_conversation") && specs().iter().any(|t| t["name"] == "rename_conversation")); + assert_eq!(label("rename_conversation"), "為對話取名"); + // A past one, by its name or a part only it has; the list shows them as the person does. + st.bots[0].threads = vec![("報價單".into(), vec![Message::user("報價單")]), ("第一季報價".into(), vec![Message::user("x")]), ("官網".into(), vec![Message::user("y")])].into(); + let r = apply(&mut st, id, "rename_conversation", r#"{"name":"Q3 報價","conversation":"報價單"}"#); + assert!(r.ok && st.bots[0].threads[0].0 == "Q3 報價", "{}", r.text); + assert!(apply(&mut st, id, "rename_conversation", r#"{"name":"官網改版","conversation":"官"}"#).ok); + assert_eq!(st.bots[0].threads[2].0, "官網改版"); + assert!(!apply(&mut st, id, "rename_conversation", r#"{"name":"x","conversation":"報價"}"#).ok, "two have it: not guessed"); + assert!(!apply(&mut st, id, "rename_conversation", r#"{"name":"x","conversation":"沒有這段"}"#).ok); + // No name given isn't 「back to its first line」: refused, the name stays. + assert!(!apply(&mut st, id, "rename_conversation", r#"{"conversation":"Q3 報價"}"#).ok); + assert_eq!(st.bots[0].threads[0].0, "Q3 報價"); + let list = apply(&mut st, id, "list_conversations", "{}").text; + assert!(list.contains("目前的對話:「首頁要改」") && list.contains("「Q3 報價」") && list.contains("「官網改版」") && list.contains("3 段"), "{list}"); + // A 支線 can't: its chat isn't one the person names. + let mut b = st.bots[0].clone(); + b.id = 99; + b.branch_of = id; + st.bots.push(b); + let r = apply(&mut st, 99, "rename_conversation", r#"{"name":"支線取的"}"#); + assert!(!r.ok && r.text.contains("支線"), "{}", r.text); + assert_eq!(st.bots[0].chat_name(), "首頁要改"); + } + #[test] fn groups_from_the_chat() { let mut st = State::samples(); diff --git a/src/featuremap.rs b/src/featuremap.rs index 8e8c920..f90084f 100644 --- a/src/featuremap.rs +++ b/src/featuremap.rs @@ -34,6 +34,7 @@ macro_rules! area { /// The areas, in the order of a full sweep. pub const AREAS: &[Area] = &[ area!("chat", "聊天"), + area!("threads", "對話:取名與切換"), area!("cards", "問題卡、生活卡片與表情"), area!("bots", "Bot 清單與選單"), area!("profile", "Bot 設定與能力"), diff --git a/src/i18n_table.rs b/src/i18n_table.rs index 6db9801..4b13eaa 100644 --- a/src/i18n_table.rs +++ b/src/i18n_table.rs @@ -18,7 +18,17 @@ pub const ROWS: &[(&str, &str, &str)] = &[ ("檔案:", "File: ", "ファイル:"), ("你:", "You: ", "あなた:"), ("只列出最新的 40 則,多打幾個字可以找得更準", "Only the newest 40 are listed; type more to narrow it down", "最新の 40 件だけ表示しています。もう少し入力すると絞り込めます"), - ("「{name}」正在工作。等它做完,再打開過去的對話。", "\"{name}\" is working. Open the past conversation once it has finished.", "「{name}」は作業中です。終わってから過去の会話を開いてください。"), + // 對話欄 (the chat's 「對話」 on the right). + ("對話", "Chats", "会話"), + ("這個 Bot 的對話", "This bot's conversations", "このボットの会話"), + ("這個 Bot 的對話(過去的 {n} 段)", "This bot's conversations ({n} past)", "このボットの会話(過去 {n} 件)"), + ("還沒有訊息", "No messages yet", "まだメッセージはありません"), + ("目前的對話", "Current conversation", "現在の会話"), + ("打開這段對話", "Open this conversation", "この会話を開く"), + ("「{name}」正在工作。等它做完(或先按停止),再換對話。", "\"{name}\" is working. Switch conversations once it has finished (or press Stop first).", "「{name}」は作業中です。終わってから(または先に停止して)会話を切り替えてください。"), + ("「{name}」正在把較早的對話整理成摘要:整理好再換對話。", "\"{name}\" is summarizing the earlier conversation. Switch once it is done.", "「{name}」は以前の会話を要約しています。終わってから切り替えてください。"), + ("「{name}」還有支線在做,做完會回報到這段:等它做完(或在支線卡上停止),再換對話。", "\"{name}\" has a side task running that reports here. Switch once it is done (or stop it on its card).", "「{name}」にはこの会話に報告するサブタスクが動いています。終わってから(またはカードで停止して)切り替えてください。"), + ("「{name}」交辦給「{other}」的事正在做,做完會回報到這段:等它回報(或到「{other}」按停止),再換對話。", "\"{name}\" handed work to \"{other}\", which is doing it and reports here. Switch once it has reported (or stop \"{other}\").", "「{name}」が「{other}」に任せた作業は進行中で、この会話に報告されます。報告が来てから(または「{other}」を停止して)切り替えてください。"), ("沒有相符的 Bot", "No matching bots", "一致する Bot はありません"), ("設定", "Settings", "設定"), ("設定(⌘,)", "Settings (⌘,)", "設定(⌘,)"), diff --git a/src/model.rs b/src/model.rs index 46c8396..0699dbf 100644 --- a/src/model.rs +++ b/src/model.rs @@ -459,9 +459,17 @@ pub struct Bot { /// 群組聊天: the bots that answer here, in order (empty = an ordinary bot). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub members: Vec, - /// 討論串: earlier conversations put aside with 「開始新對話」 (title, messages). + /// 討論串: earlier conversations put aside with 「開始新對話」 (title, messages), newest first. #[serde(default, skip_serializing_if = "threads_apart")] pub threads: crate::shared::Shared)>>, + /// The open conversation's name, given by the person (empty: its first line, auto_title). + /// It goes with the conversation into 過去的對話 and comes back with it. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub chat_title: String, + /// 換對話 asked of the bot in chat (switch_conversation): done once its turn, and what + /// follows it in this conversation, is over — never under a running turn. + #[serde(skip)] + pub chat_after: Option, /// 記憶: facts this bot keeps across chats. #[serde(default)] pub memories: Vec, @@ -562,7 +570,105 @@ pub fn default_computer() -> String { pub const INTERRUPTED_NOTE: &str = "(這次的回應被中斷了,可能是 App 關閉或重新啟動。按「重新產生」再試一次。)"; +/// A line of text, short: its first line with words in it (no heading or list marks), at most +/// `max` characters, … when cut. +pub fn first_line(s: &str, max: usize) -> String { + let line = s.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or(""); + let line = line.trim_start_matches(['#', '-', '*', ' ']); + let mut out: String = line.chars().take(max).collect(); + if line.chars().count() > max { + out.push('…'); + } + out +} + +/// What a conversation nobody named is called: the first thing the person wrote in it. +pub fn auto_title(msgs: &[Message]) -> String { + msgs.iter().find(|m| m.role == Role::User).map(|m| first_line(&m.text, 24)).filter(|t| !t.is_empty()).unwrap_or_else(|| "對話".into()) +} + +/// A name the person gave a conversation, as kept: one line, at most 40 characters. +pub fn clean_title(name: &str) -> String { + name.split_whitespace().collect::>().join(" ").chars().take(40).collect() +} + +/// Where a bot was asked to take the chat when its turn is over (Bot::chat_after). +#[derive(Clone, Debug, PartialEq)] +pub enum ChatAfter { + /// 開始新對話, called `name` ("" = unnamed). + New { name: String }, + /// One of 過去的對話, by its name and its last message's time (found again if the list + /// moved), renamed `name` once open ("" = as it is). + Open { title: String, at: i64, name: String }, +} + +/// At most this many conversations are kept in 過去的對話 (the oldest go). +pub const THREADS_KEPT: usize = 50; + impl Bot { + /// What the open conversation is called: the name given to it, or its first line. + pub fn chat_name(&self) -> String { + if self.chat_title.is_empty() { auto_title(&self.messages) } else { self.chat_title.clone() } + } + + /// 開始新對話: the open conversation goes to the top of 過去的對話 with its name (its words, + /// not the screenshots held in memory), and the chat is empty and nameless. + pub fn put_aside(&mut self) { + if !self.messages.is_empty() { + let title = self.chat_name(); + let mut msgs = std::mem::take(&mut self.messages).into_inner(); + msgs.iter_mut().for_each(|m| m.images.clear()); + self.threads.insert(0, (title, msgs)); + self.threads.truncate(THREADS_KEPT); + } + self.chat_title.clear(); + // (「還原上一個答案」 is this conversation's: in another one it put the old answer there.) + self.regen_undo.clear(); + } + + /// Which of 過去的對話 a device meant: number `index` as its list had it, checked by the + /// time of that conversation's last message (`at`) and the name it showed (`was`) — a list + /// that changed since (one put aside or opened on another device) moves the numbers, not the + /// times; the name tells apart copies that end at the same message (分岔). 0 and "" are not + /// sent (an older page): its number, as before. None: it isn't there any more. + pub fn find_thread(&self, index: usize, at: i64, was: &str) -> Option { + let fits = |t: &(String, Vec)| (at == 0 || t.1.last().map(|m| m.at).unwrap_or(0) == at) && (was.is_empty() || t.0 == was); + if at == 0 && was.is_empty() { + return (index < self.threads.len()).then_some(index); + } + if self.threads.get(index).is_some_and(fits) { + return Some(index); + } + self.threads.iter().position(fits) + } + + /// 過去的對話 number `i` becomes the open one, its name with it; the open one is put aside. + pub fn open_thread(&mut self, i: usize) -> bool { + if i >= self.threads.len() { + return false; + } + let (title, msgs) = self.threads.remove(i); + self.put_aside(); + // (A name that is only its first line stays unset: it follows the words, as before.) + self.chat_title = if title == auto_title(&msgs) { String::new() } else { title }; + self.messages = msgs.into(); + true + } + + /// 重新命名: the open conversation (`None`) or 過去的對話 number `i` is called `name`; an + /// empty name goes back to its first line. + pub fn rename_chat(&mut self, which: Option, name: &str) -> bool { + let name = clean_title(name); + match which { + None => self.chat_title = name, + Some(i) => match self.threads.get_mut(i) { + Some(t) => t.0 = if name.is_empty() { auto_title(&t.1) } else { name }, + None => return false, + }, + } + true + } + /// The key model_limits uses for this bot's model now. pub fn limit_key(&self) -> String { format!("{}/{}", self.provider.key(), self.model) @@ -595,6 +701,8 @@ impl Bot { pub fn take_edit(&mut self, mut from: Bot, mut edited: Bot) { use serde_json::Value; let messages = std::mem::take(&mut self.messages); + // (Not saved, so not in the JSON below: a 換對話 the bot promised stays.) + let chat_after = self.chat_after.take(); from.messages.clear(); edited.messages.clear(); let fields = |b: &Bot| serde_json::to_value(b).ok().and_then(|v| v.as_object().cloned()); @@ -631,6 +739,7 @@ impl Bot { serde_json::from_value::(Value::Object(now)).ok() })(); *self = merged.unwrap_or(edited); + self.chat_after = chat_after; self.messages = messages; } @@ -787,6 +896,9 @@ pub struct State { pub doc_folders: Vec, #[serde(default = "default_sidebar_width")] pub sidebar_width: f32, + /// 對話欄: the open bot's conversations in a column on the right, left open (this computer's). + #[serde(default)] + pub chats_column: bool, /// 允許在這台電腦上執行任務,而不只是在它自己的電腦上 (setting `local-execution`, ids fuUvu2/Hd1KB+). #[serde(default)] pub local_execution: bool, @@ -1376,6 +1488,8 @@ impl State { memories: vec![], members: vec![], threads: Default::default(), + chat_title: String::new(), + chat_after: None, context_tokens: default_context_tokens(), model_limits: Default::default(), follow_ups: vec![], @@ -1432,6 +1546,7 @@ impl State { embed_model: String::new(), doc_folders: vec![], sidebar_width: default_sidebar_width(), + chats_column: false, local_execution: false, remote_computers: vec![], auto_review: false, @@ -1642,6 +1757,12 @@ mod start_tests { let back = State::load_from(&p); assert_eq!(back.bot(a).unwrap().messages[1].text, "嗨,今天好嗎"); assert_eq!(back.bot(b).unwrap().threads[0].1[0].text, "之前說過"); + // 對話的名字: the open one's and a past one renamed are read back after a restart. + st.bots[0].rename_chat(None, "網站改版"); + st.bots[1].rename_chat(Some(0), "第一季"); + assert!(st.save_at(&p)); + let back = State::load_from(&p); + assert_eq!((back.bot(a).unwrap().chat_title.as_str(), back.bot(b).unwrap().threads[0].0.as_str()), ("網站改版", "第一季")); // A deleted bot's chat file goes; a save from before is read as it is and set apart. st.bots.retain(|x| x.id != b); assert!(st.save_at(&p)); @@ -1860,4 +1981,67 @@ mod start_tests { assert_eq!(State::load_from(&p).bots[0].name, "留著的"); let _ = std::fs::remove_dir_all(&d); } + + /// 對話的名字:沒取名的用第一句話;取了名的收進過去的對話、再打開都帶著;改成空白回到第一句話。 + #[test] + fn a_conversation_keeps_the_name_it_was_given() { + let mut b = State::demo().bots[0].clone(); + b.threads = Vec::new().into(); + b.chat_title.clear(); + let said = |text: &str, at: i64| Message { at, ..Message::user(text) }; + b.messages = vec![said("# 幫我看網站首頁\n第二行", 10), Message { at: 11, ..Message::assistant("好", "m") }].into(); + assert_eq!(b.chat_name(), "幫我看網站首頁"); + assert!(b.rename_chat(None, " 網站\n改版 ")); + assert_eq!(b.chat_name(), "網站 改版", "one line, spaces tidied"); + b.put_aside(); + assert!(b.messages.is_empty() && b.chat_title.is_empty(), "the new chat is nameless"); + assert_eq!(b.threads[0].0, "網站 改版"); + // Another one, not named: put aside under its first line. + b.messages = vec![said("報價單", 20)].into(); + b.put_aside(); + assert_eq!(b.threads.iter().map(|t| t.0.as_str()).collect::>(), ["報價單", "網站 改版"]); + // Opened again: the name comes back with it; one called by its first line stays unnamed. + assert!(b.open_thread(1)); + assert_eq!((b.chat_title.as_str(), b.messages.len()), ("網站 改版", 2)); + assert_eq!(b.threads.iter().map(|t| t.0.as_str()).collect::>(), ["報價單"]); + assert!(b.open_thread(0)); + assert_eq!((b.chat_title.as_str(), b.chat_name().as_str()), ("", "報價單")); + assert_eq!(b.threads[0].0, "網站 改版"); + // A past one renamed; empty goes back to its first line. + assert!(b.rename_chat(Some(0), "官網")); + assert_eq!(b.threads[0].0, "官網"); + assert!(b.rename_chat(Some(0), " ")); + assert_eq!(b.threads[0].0, "幫我看網站首頁"); + assert!(!b.rename_chat(Some(5), "x") && !b.open_thread(5)); + assert_eq!(clean_title(&"長".repeat(60)).chars().count(), 40); + // 「還原上一個答案」 stays with its conversation: put aside, there is none to put back. + b.regen_undo = vec![Message::assistant("舊的答案", "m")]; + b.messages = vec![said("再一段", 50)].into(); + b.put_aside(); + assert!(b.regen_undo.is_empty()); + b.threads.remove(0); + // An empty chat isn't put aside (nothing to keep), but its name goes. + b.messages = Vec::new().into(); + b.chat_title = "空的".into(); + b.put_aside(); + assert_eq!((b.threads.len(), b.chat_title.as_str()), (1, "")); + } + + /// A device's list moved since it was drawn (one opened or put aside elsewhere): the one it + /// meant is found by its last message's time, not taken by its old number. + #[test] + fn a_past_conversation_is_found_by_its_time() { + let mut b = State::demo().bots[0].clone(); + let conv = |title: &str, at: i64| (title.to_string(), vec![Message { at, ..Message::user(title) }]); + b.threads = vec![conv("新", 30), conv("中", 20), conv("舊", 10)].into(); + assert_eq!(b.find_thread(1, 20, "中"), Some(1)); + assert_eq!(b.find_thread(1, 10, "舊"), Some(2), "moved down one"); + assert_eq!(b.find_thread(2, 99, ""), None, "gone: nothing, not number 2"); + assert_eq!((b.find_thread(2, 0, ""), b.find_thread(3, 0, "")), (Some(2), None), "an older page sends neither"); + // Two forks of one point end at the same message: the name tells them apart. + b.threads.insert(0, ("分岔:甲".into(), vec![Message { at: 20, ..Message::user("x") }])); + assert_eq!(b.find_thread(0, 20, "中"), Some(2)); + assert_eq!(b.find_thread(1, 20, "分岔:甲"), Some(0)); + assert_eq!(b.find_thread(2, 20, "改過的名字"), None, "renamed meanwhile: not guessed"); + } } diff --git a/src/oplog.rs b/src/oplog.rs index ec77328..60353b3 100644 --- a/src/oplog.rs +++ b/src/oplog.rs @@ -401,6 +401,7 @@ pub fn replay_of(name: &str) -> Replay { "list_bots", "list_computers", "list_routines", + "list_conversations", crate::tasks::TOOL, "list_pages", "read_page", diff --git a/src/remote.rs b/src/remote.rs index b5aeb77..c99cf76 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -224,10 +224,19 @@ pub enum Cmd { Reply { bot: u64 }, /// 「繼續」 on the card a crash left: the cut-off turn goes on. Resume { bot: u64 }, - /// Bring back an earlier conversation (過去的對話). - RestoreThread { bot: u64, index: usize }, + /// Bring back an earlier conversation (過去的對話): number `index` in the list the device + /// had, `at` its last message's time and `was` the name it showed (0 and "": an older page + /// that doesn't send them; Bot::find_thread). + RestoreThread { bot: u64, index: usize, at: i64, was: String }, + /// 重新命名 a conversation: the open one (`index` None; `was`, the name the device showed, + /// must still be the open one's — another device may have opened another meanwhile) or 過去 + /// 的對話 number `index`, found as RestoreThread finds it; an empty `title` goes back to its + /// first line. + RenameThread { bot: u64, index: Option, at: i64, was: String, title: String }, /// 清除聊天記錄 from a screen of this brain (the chat lives here). - Clear { bot: u64 }, + /// `was`: the open conversation's name as the screen showed it ("" = not sent): another + /// one opened since (on another device, or a switch the bot promised) isn't cleared. + Clear { bot: u64, was: String }, /// 立即執行例行任務 from a screen of this brain. RunRoutine { bot: u64, routine: u64 }, /// 工作流 from a screen of this brain: 執行 (run), 停止 (stop), 等你確認的繼續 (go) or 停止 (halt). @@ -702,6 +711,10 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { if let Some(o) = c.as_object_mut() { o.insert("routines".into(), json!([])); o.insert("threads".into(), json!([])); + // (The owner's conversations, by name or count, aren't a member's.) + o.remove("threads_total"); + o.remove("chat_title"); + o.remove("chat_named"); o.insert("queued".into(), json!([])); o.remove("goal"); o.remove("plan"); @@ -1029,7 +1042,8 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { "new" => Cmd::NewThread { bot }, "regenerate" => Cmd::Regenerate { bot }, "restore_answer" => Cmd::RestoreAnswer { bot }, - "restore" => Cmd::RestoreThread { bot, index: b["index"].as_u64().unwrap_or(0) as usize }, + "restore" => Cmd::RestoreThread { bot, index: b["index"].as_u64().unwrap_or(0) as usize, at: b["at"].as_i64().unwrap_or(0), was: b["was"].as_str().unwrap_or("").to_string() }, + "rename" => Cmd::RenameThread { bot, index: b["index"].as_u64().map(|i| i as usize), at: b["at"].as_i64().unwrap_or(0), was: b["was"].as_str().unwrap_or("").to_string(), title: b["title"].as_str().unwrap_or("").to_string() }, "set" => Cmd::SetBot { bot, provider: b["provider"].as_str().unwrap_or("").to_string(), @@ -1186,8 +1200,9 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { "restore_answer" => Cmd::RestoreAnswer { bot }, "reply" => Cmd::Reply { bot }, "resume" => Cmd::Resume { bot }, - "restore" => Cmd::RestoreThread { bot, index: b["index"].as_u64().unwrap_or(0) as usize }, - "clear" => Cmd::Clear { bot }, + "restore" => Cmd::RestoreThread { bot, index: b["index"].as_u64().unwrap_or(0) as usize, at: b["at"].as_i64().unwrap_or(0), was: b["was"].as_str().unwrap_or("").to_string() }, + "rename" => Cmd::RenameThread { bot, index: b["index"].as_u64().map(|i| i as usize), at: b["at"].as_i64().unwrap_or(0), was: b["was"].as_str().unwrap_or("").to_string(), title: b["title"].as_str().unwrap_or("").to_string() }, + "clear" => Cmd::Clear { bot, was: b["was"].as_str().unwrap_or("").to_string() }, "run_routine" => Cmd::RunRoutine { bot, routine: b["routine"].as_u64().unwrap_or(0) }, "workflow" => Cmd::Workflow { wf: b["wf"].as_u64().unwrap_or(0), act: b["do"].as_str().unwrap_or("").to_string() }, "meeting" => Cmd::Meeting { bot, path: b["path"].as_str().unwrap_or("").to_string(), lang: b["lang"].as_str().unwrap_or("").to_string() }, @@ -4653,6 +4668,20 @@ mod tests { let cmds = hub().take_cmds(); assert!(cmds.iter().any(|c| matches!(c, Cmd::DeviceAdded(d) if d.name == "iPhone"))); assert!(cmds.contains(&Cmd::Send { bot: 1, text: "你好".into(), attachments: vec![], from: String::new(), memories: Some(vec![]), member: false, seen: String::new() }) || cmds.contains(&Cmd::Send { bot: 1, text: "你好".into(), attachments: vec![], from: String::new(), memories: None, member: false, seen: String::new() })); + // 對話: 命名 and 回到 from the phone carry what it showed (the name, the last time); a team + // member's are refused. + for (path, body, want) in [ + ("/api/bots/1/rename", r#"{"title":"網站改版","was":"首頁"}"#, Cmd::RenameThread { bot: 1, index: None, at: 0, was: "首頁".into(), title: "網站改版".into() }), + ("/api/bots/1/rename", r#"{"index":2,"at":99,"was":"舊","title":"新"}"#, Cmd::RenameThread { bot: 1, index: Some(2), at: 99, was: "舊".into(), title: "新".into() }), + ("/api/bots/1/restore", r#"{"index":2,"at":99,"was":"舊"}"#, Cmd::RestoreThread { bot: 1, index: 2, at: 99, was: "舊".into() }), + ("/api/bots/1/restore", r#"{"index":3}"#, Cmd::RestoreThread { bot: 1, index: 3, at: 0, was: String::new() }), + ] { + let mut r = Req { method: "POST".into(), path: path.into(), body: body.as_bytes().to_vec(), ..Default::default() }; + r.headers = req.headers.clone(); + assert_eq!(handle(r, false).status, 200, "{path}"); + assert!(hub().take_cmds().contains(&want), "{path} {body}"); + } + assert!(!role_allows("member", "POST", &["api", "bots", "1", "rename"]) && !role_allows("member", "POST", &["api", "bots", "1", "restore"])); // 「/always-approve」 typed on a direct connection is the 直接操作 switch in other words: // refused, nothing queued (it turned 直接操作 and 一律放行 on); status and off go through, // and so does the owner through the account. diff --git a/src/setup.rs b/src/setup.rs index 2896efb..35a8249 100644 --- a/src/setup.rs +++ b/src/setup.rs @@ -1161,6 +1161,8 @@ fn seed_first() -> i32 { allow_rules: vec![], members: vec![], threads: Default::default(), + chat_title: String::new(), + chat_after: None, memories: vec![], speak_replies: false, voice: String::new(), diff --git a/src/share.rs b/src/share.rs index aa5f424..80d7d48 100644 --- a/src/share.rs +++ b/src/share.rs @@ -41,7 +41,7 @@ pub fn export(b: &Bot) -> String { let mut v = serde_json::to_value(b).unwrap_or(Value::Null); if let Value::Object(m) = &mut v { // (Its 可以用的電腦 are this account's computers by name; its 草稿 is unsent words: neither travels.) - for k in ["messages", "threads", "allow_rules", "memories", "tools_enabled", "default_computer", "unread", "last_turn", "tasks", "goal", "plan", "workdir", "pinned", "id", "computers", "draft", "regen_undo", "branches", "branch_of", "team"] { + for k in ["messages", "threads", "chat_title", "allow_rules", "memories", "tools_enabled", "default_computer", "unread", "last_turn", "tasks", "goal", "plan", "workdir", "pinned", "id", "computers", "draft", "regen_undo", "branches", "branch_of", "team"] { m.remove(k); } if let Some(Value::Array(routines)) = m.get_mut("routines") {