diff --git a/FEATURES.md b/FEATURES.md index 2cacfb7..5b06769 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -138,6 +138,24 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 - 點一筆:打開那個 Bot,聊天捲到那則訊息,並用黃色亮一下(約 1.8 秒淡掉)。在過去的對話裡的,會先把那段對話換回來(目前的對話收進「過去的對話」最上面);那個 Bot 正在工作時不換,改提示「「(名字)」正在工作。等它做完,再打開過去的對話。」 - 連到別台大腦的電腦上也能用(找的是大腦的聊天)。手機版還沒有。 +### 任務(2026-11-20) + +交代給 Bot 的每一件事都是一個任務:你或團隊成員的一句話、例行任務的一次執行、目標、追進度和訊息管道開的那一輪。狀態由大腦從已經有的紀錄算出來,不是 Bot 說了算(規格「程式優先」)。 + +- **入口**:側邊欄上面、搜尋左邊的圓鈕(打勾的圓);有進行中、等你或 24 小時內失敗的任務時,右上角一個小數字。點了打開「任務」視窗。手機是首頁捷徑列最前面的「任務」(有要看的帶數字),點進去是「任務」頁。聊天裡不多任何東西。 +- **清單**:所有 Bot 的任務放一起,最後有動靜的在上面,最多 60 件。每張卡:頭像和 Bot 名字、誰開的、開頭那句話(一行)、狀態、在哪台電腦(步驟指定的電腦,沒有就是 Bot 的預設電腦)、步驟數和失敗數、最後動靜、現在在做什麼或最後一步、卡住或失敗的原因、產物和 ✓/✓✓/! 記號、證據等級。點卡片:打開那個 Bot 的聊天,捲到開頭那則訊息亮一下(手機上太早、手機沒存的訊息就停在最新,跳一句提示)。 +- **一件事怎麼算**:你的一句話開一件;Bot 工作中你插的話算同一件;目標的「[目標]」下一輪、追進度好了叫醒它(「[追進度 #N]」)、監看印出東西(「[監看 #N]」)、檔案沒顯示叫醒它重交(「[交付]」)都接回開這件事的那一件。任務的編號是「Bot 編號-開頭那則訊息的時間」,不會變。 +- **狀態**(各自分開,不用一個「完成」帶過): + - 進行中、等你(允許卡、問題卡、目標停下來問你)、追進度中(它登記的追進度還在跑)、驗收中(目標還開著,另一個模型在檢查或準備下一輪)。 + - 已產出(有檔案,還沒有你的裝置回報顯示)、已交付(你的某台裝置顯示了)、你已確認(你點開了,或對那則回答按了 👍)。團隊成員的裝置不算你的。 + - 已回覆(系統看到步驟做完,沒有檔案要交)、已驗收(目標的檢查說達成)。 + - 失敗(模型或步驟出錯、AnyBot 關掉時中斷、訊息送到後 15 秒還沒開始回覆、目標做不到;原因寫在卡上)、已停止(你按了停止)、結束但未驗證(輪結束了,但沒有系統看得到的結果,或只有別的 Bot 的轉述)。 + - 判斷是純函式、用表格測試:每個狀態都要有它的證據才進得去(沒有裝置回報不算已交付、沒有點開或 👍 不算你已確認);記下的狀態只往前走(已產出 → 已交付 → 你已確認),按掉 👍 不會退回;接著做時回到進行中。 +- **證據等級**:A=系統自己看到的步驟結果(幾步做完、送出了什麼);C=別的 Bot 的回答(`ask_bot`),系統沒驗證;未驗=都沒有。 +- **留存**:每次結束、等你或狀態往前走,大腦在那個 Bot 身上記一筆精簡紀錄(`state.json` 的 `tasks`,只加不改,每個 Bot 留最近 40 筆,空的不寫)。清掉聊天、整理成摘要、開新對話後,最近的任務照紀錄還在(卡上寫「照紀錄」),紀錄裡還在進行的改成「結束但未驗證」。匯出、匯入 Bot 不帶這份紀錄。 +- **每台一樣**:大腦每 3 秒(回合一結束就立刻)算一份,手機(`api/state` 的 `tasks`,跟著狀態存在手機上,沒網路先畫上次的並寫「離線中」)、螢幕電腦(`api/sync`,變了才送;還沒收到時用自己的副本算並標明)讀的都是這一份。團隊成員只拿得到分享給團隊的 Bot 的任務。 +- **Bot 讀得到**:唯讀工具 `list_tasks`(`all` 看所有 Bot、`limit` 最多 30;步驟名「查看任務」,不用允許),每件一行〔狀態〕、誰開的、在哪、步驟、開始和最後動靜,下面是現在在做什麼、原因、證據和產物。系統提示要 Bot 被問「在跑什麼/做完了沒/收到了嗎」時照它回答。團隊成員或訊息管道開的那一輪只列得到同一個人交代的任務,`all` 不算數。 + --- ## 3. Bot 選單(右鍵選單和聊天頂部的「⋯」共用) @@ -1949,6 +1967,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 可讀長度(預設 128,000) - 例行任務 - 上一回合的結果 + - 任務紀錄(每次狀態改變一筆,留最近 40 筆,第 2 節「任務」) - 預設電腦(預設「Bot 的電腦」) - **每則訊息記錄**: - 誰說的、文字、思考內容 diff --git a/docs/feature-map/README.md b/docs/feature-map/README.md index 71e1d87..9b7d77b 100644 --- a/docs/feature-map/README.md +++ b/docs/feature-map/README.md @@ -89,6 +89,7 @@ Bot 讀得到的是開頭、子功能、使用者怎麼到、Bot 那一行和沒 - [routines](routines.md):排程與事件觸發、執行紀錄、完成條件、自動暫停。 - [goal](goal.md):/goal:沒達成就繼續做、評審只看證據。 - [plan](plan.md):/plan:先查清楚、交計畫給你核准,核准後才動手、照步驟打勾。 +- [tasks](tasks.md):任務:每件交代的事一張卡,狀態由系統算(等你、追進度、驗收、已交付、你已確認…)、證據等級、清掉聊天也留著。 ### 在電腦上做事 - [computers](computers.md):大腦與手腳、這台電腦、SSH、帳號裡的其他電腦、傳到別的裝置。 diff --git a/docs/feature-map/tasks.md b/docs/feature-map/tasks.md new file mode 100644 index 0000000..fd08917 --- /dev/null +++ b/docs/feature-map/tasks.md @@ -0,0 +1,51 @@ +# 任務 + +交代給 Bot 的每一件事都是一個任務:你或團隊成員的一句話、例行任務的一次執行、目標、追進度和訊息管道開的那一輪。任務的狀態由 AnyBot 從已經有的紀錄算出來(步驟的結果、回合怎麼結束、在等你的卡片、追進度、目標的檢查、檔案在哪台裝置顯示過),不是 Bot 說了算;聊天裡不多任何東西,清單在獨立的「任務」頁。 + +## 子功能 + +- `tasks-list` 任務清單:每個 Bot 的任務放在一起,最新的(最後有動靜的)在上面,最多 60 件。每張卡:Bot 頭像和名字、誰開的(你、團隊成員、例行任務、觸發、目標、計畫、訊息管道、其他 Bot)、開頭那句話、狀態、在哪台電腦、步驟數和失敗數、最後動靜、現在在做什麼或最後一步、卡住或失敗的原因、產物和它的交付記號、證據等級。點一下打開那個 Bot 的聊天,捲到開頭那則訊息亮一下。 +- `tasks-status` 狀態,各自分開:進行中、等你(允許或問題卡、目標停下來問你)、追進度中、驗收中(目標還開著,另一個模型在檢查)、已產出(有檔案,還沒有你的裝置回報顯示)、已交付(你的某台裝置顯示了)、你已確認(你點開了,或對那則回答按了 👍)、已回覆(有系統看到的步驟結果,沒有檔案要交)、已驗收(目標的檢查說達成)、失敗(出錯、AnyBot 關掉時中斷、沒開始回覆、目標做不到)、已停止、結束但未驗證(輪結束了,但沒有系統看得到的結果,或只有別的 Bot 的轉述)。 + - 沒有證據就到不了那一格:沒有裝置回報就不算已交付,沒有點開或 👍 就不算你已確認;團隊成員的裝置不算你的。 + - 記下的狀態只往前走(已產出 → 已交付 → 你已確認);按掉 👍 不會退回去。任務接著做時(目標的下一輪、追進度好了叫醒它、檔案沒顯示叫醒它重交)回到進行中,算同一件。 +- `tasks-evidence` 證據:A=系統自己看到的步驟結果(幾步做完、送出了什麼);C=別的 Bot 的回答(`ask_bot`),系統沒有驗證;未驗=沒有系統看得到的結果。只有 C 的任務是「結束但未驗證」。 +- `tasks-keep` 留存:任務從聊天算出來;每次結束、等你或狀態往前走,大腦在那個 Bot 身上記一筆精簡的紀錄(只加不改,每個 Bot 留最近 40 筆)。聊天清掉、整理成摘要或開新對話後,最近的任務照紀錄還在(標「照紀錄」),紀錄裡還在進行的改成結束但未驗證。重開 AnyBot 還在;舊版的資料讀得進來。 +- `tasks-devices` 每台一樣:大腦算一份,手機、螢幕電腦、Bot 讀的都是這一份。手機的任務頁跟著狀態存在手機上,沒網路也先畫上次的;螢幕電腦還沒收到大腦的那份時,用自己存的副本算並標明。團隊成員在手機上只拿得到分享給團隊的 Bot 的任務。 +- `tasks-bot` Bot 讀得到:`list_tasks` 照系統算的狀態和證據列出任務,使用者問「現在在跑什麼」「那件事做完了沒」「收到了嗎」時照它回答,不靠記憶。只能看,不能改。 + +## 使用者怎麼到 + +- 側邊欄上面,搜尋左邊的圓鈕(打勾的圓):點一下打開「任務」視窗;有進行中、等你或今天失敗的任務時,圓鈕右上角一個小數字。 +- 手機:首頁上方那排捷徑最前面的「任務」(有要看的會帶數字),點進去是「任務」頁([phone](phone.md))。 +- 聊天裡不另外顯示任務。 + +## 怎麼操作(verify-anybot) + +- Bot:使用者問現在在跑什麼、那件事做完了沒、檔案收到沒,用 `list_tasks`(`all`=true 看所有 Bot,只有在使用者自己開的對話裡;`limit` 最多 30)照狀態和證據回答;狀態沒說交付、確認或驗收的,不要說已經完成或收到。別人(團隊成員、訊息管道)開的那一輪只列得到同一個人交代的任務。 + +前提: + +- 基本前提和「手機已登入」(README)。 +- 任務頁和首頁的「任務」都在首頁:`$CTL phone wait '#quick [data-q="tasks"]'`。 + +- **空的清單**(covers `tasks-list`):還沒交代任何事時打開任務頁。指令:`$CTL phone click '#quick [data-q="tasks"]' && $CTL phone wait-text 還沒有任務 --in '#list' && $CTL phone shot tasks-empty && $CTL phone click '[data-back]'`。看到:「還沒有任務。交代 Bot 做一件事,它就會出現在這裡。」;首頁「任務」沒有數字。 +- **已回覆、有證據 A**(covers `tasks-list`、`tasks-status`、`tasks-evidence`):請 Bot 建一個檔案。指令:`$CTL phone click '.row[data-bot="1"]' && $CTL phone send '建檔 [[call edit_file {"path":"hello.txt","old_text":"","new_text":"hi"}]]' && $CTL phone wait-text 'FAKE-MODEL 收到工具結果' --in '#msgs' && $CTL phone click '[data-back]' && $CTL phone click '#quick [data-q="tasks"]' && $CTL phone wait '.tk[data-status="answered"]' && $CTL phone shot tasks-answered && $CTL api GET '/api/state?since=0' --jq '.tasks[0] | {status, evidence, steps, proof, source, computer}'`。看到:卡片「驗證小幫手 · 你開的」「已回覆」「建檔 …」「在 驗證小幫手 的電腦 · 1 步 · 最後動靜 剛剛」「最後一步:修改檔案 hello.txt」「證據 A 系統看到」;API 是 answered、evidence a、steps 1、proof「系統看到 1 步做完」。 +- **等你,再拒絕**(covers `tasks-status`):請 Bot 改名,卡片在等時看任務頁,再拒絕。指令:`$CTL phone click '[data-back]' && $CTL phone click '.row[data-bot="1"]' && $CTL phone send '改名 [[call update_bot {"name":"不要的名字"}]]' && $CTL phone wait '#ask .ask' && $CTL phone click '[data-back]' && $CTL phone wait-text 1 --in '#quick [data-q="tasks"] b' && $CTL phone shot tasks-badge && $CTL phone click '#quick [data-q="tasks"]' && $CTL phone wait '.tk[data-status="waiting"]' && $CTL phone wait-text '等你允許:修改 Bot' --in '#list' && $CTL phone shot tasks-waiting && $CTL phone click '.tk[data-status="waiting"]' && $CTL phone wait '#ask .ask' && $CTL phone wait '.m.lit' && $CTL phone shot tasks-jump && $CTL phone click '#ask button[data-a="reject"]' && $CTL phone wait-text '使用者拒絕了這個操作' --in '#msgs' && $CTL wait-api '/api/state?since=0' '.tasks[0].status == "unverified" and .tasks[0].failed == 1'`。看到:首頁「任務」旁邊一個 1;任務頁上面「1 件進行中、等你或今天失敗」,卡片「等你」、「現在:等你允許:修改 Bot」;點卡片回到聊天、捲到「改名 …」那則並亮一圈;拒絕後那件事「結束但未驗證」(被拒的那步算失敗:「1 步(1 步失敗)」,沒有做完的步驟)。 +- **交付記號、你已確認**(covers `tasks-status`、`tasks-evidence`):接著在聊天裡請 Bot 傳一張圖,回任務頁看,從卡片回聊天點開圖。指令:`$CTL phone send '畫 [[call shell {"command":"printf iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg== | base64 -d > dot.png"}]]' && $CTL phone wait-text '(完成,沒有輸出)' --in '#msgs' && $CTL phone send '傳給我 [[call send_file {"path":"dot.png"}]]' && $CTL phone wait '.attimg[data-name="dot.png"] + .dlv.shown' && $CTL phone click '[data-back]' && $CTL phone wait '.tk[data-status="delivered"]' && $CTL phone shot tasks-delivered && $CTL phone click '.tk[data-status="delivered"]' && $CTL phone click '.attimg[data-name="dot.png"]' && $CTL phone wait '#filebody img' && $CTL phone click '[data-back]' && $CTL wait-api '/api/state?since=0' '.tasks[0].status == "confirmed"' && $CTL phone click '[data-back]' && $CTL phone wait '.tk[data-status="confirmed"]' && $CTL phone shot tasks-confirmed && $CTL api GET '/api/state?since=0' --jq '.tasks[0] | {status, artifacts, evidence}'`。看到:(聊天返回的是任務頁:剛剛從那裡進來)「傳給我 …」那件「已交付」,產物「dot.png ✓✓」;「畫 …」那件是另一件「已回覆」;點開圖之後變「你已確認」,✓✓ 是強調色;API 的產物 delivery opened、device iPhone。 +- **別的 Bot 轉述**(covers `tasks-evidence`):建第二個 Bot,請 Bot 1 問它。指令:`$CTL api POST /api/act/app '{"bot":1,"name":"create_bot","args":{"name":"同事"}}' && $CTL phone click '[data-back]' && $CTL phone wait '.row[data-bot="1"]' && $CTL phone click '.row[data-bot="1"]' && $CTL phone send '問同事 [[call ask_bot {"bot":"同事","question":"好了沒"}]]' && $CTL phone wait-text 'FAKE-MODEL 收到工具結果' --in '#msgs' 60 && $CTL wait-api '/api/state?since=0' '[.tasks[] | select(.bot == 1)][0].evidence == "c"' && $CTL api GET '/api/state?since=0' --jq '[.tasks[] | {bot, status, evidence, proof, from, text}][0:2]'`。看到:那件事「結束但未驗證」、證據 c、proof「別的 Bot 回答了 1 次(轉述,系統沒有驗證)」;同事(Bot 2)多一件「其他 Bot」開的「「驗證小幫手」問你:好了沒」。 +- **Bot 照系統的狀態回答**(covers `tasks-bot`):問 Bot 現在有什麼任務。指令:`$CTL phone send '現在有哪些任務 [[call list_tasks {"limit":3}]]' && $CTL phone wait-text 'FAKE-MODEL 收到工具結果:任務' --in '#msgs' && $CTL phone shot tasks-bot-reads && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | select(.name == "list_tasks") | {label, status, result}]'`。看到:那一步是「查看任務」、done,沒有卡片要允許;結果開頭「任務(AnyBot 從聊天、步驟和交付回報算出的狀態,不是記憶;最新的在上面)」,1.〔進行中〕這一件(現在:查看任務)、2.〔結束但未驗證〕問同事那件(證據 C)、3.〔你已確認〕傳圖那件,每件寫誰開的、在哪、步驟、開始和最後動靜。 +- **清掉聊天還在、重開還在**(covers `tasks-keep`):清掉 Bot 1 的聊天、重開 AnyBot。指令:`$CTL api POST /api/bots/1/new '{}' && $CTL wait-api '/api/state?since=0' '[.tasks[] | select(.bot == 1 and .kept)] | length >= 3' && $CTL restart && $CTL phone open --listed && $CTL phone wait '#quick [data-q="tasks"]' && $CTL phone click '#quick [data-q="tasks"]' && $CTL phone wait-text 照紀錄 --in '#list' && $CTL phone shot tasks-kept && $CTL state '.bots[0].tasks | length'`。看到:聊天換成新對話,任務頁還是那幾件,Bot 1 的卡片寫「照紀錄(聊天裡已經沒有)」,狀態跟清掉前一樣(已回覆、結束但未驗證、你已確認…);`state.json` 的 Bot 1 有 9 筆左右的 `tasks`(每次結束、等你、往前走各一筆)。 +- **沒網路先畫上次的**(covers `tasks-devices`):停掉 AnyBot,手機重新打開。指令:`$CTL phone click '[data-back]' && $CTL stop && $CTL phone open --listed && $CTL phone wait '#quick [data-q="tasks"]' 5 && $CTL phone wait-text '離線中' --in '#net' 15 && $CTL phone click '#quick [data-q="tasks"]' && $CTL phone wait-text 離線中 --in '#list' && $CTL phone shot tasks-offline && $CTL serve`。看到:「離線中:顯示的是上次存在這支手機上的任務」,下面是上次那幾張卡。 +- **電腦版的任務視窗、螢幕電腦**(covers `tasks-list`、`tasks-devices`):指令:要開視窗——`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot tasks ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_VIEW=tasks`;螢幕電腦走不到——要另一台登入同帳號的 AnyBot。看到:任務視窗(側邊欄搜尋左邊的圓鈕打開)列出同樣的卡片;最接近的真路是自動測試:`layout_audit` 在行程裡畫任務視窗、字不出框;大腦算的那份經 `api/sync` 交給螢幕電腦、沒變不再送,螢幕電腦照它顯示。 +- 自動測試:`cargo test tasks::`、`cargo test app::tasks_ui::`、`cargo test a_screen_gets_the_brains_task_list`、`cargo test layout_audit::`(「任務」那一頁)。 + +## 陷阱 + +- 「已回覆」只表示系統看到步驟做完,不表示答案對;要確定就看產物,或對答案按 👍。 +- 「結束但未驗證」不是失敗:聊天、問答本來就沒有東西可驗;要它有證據,就請 Bot 用工具做、把結果傳進聊天。 +- 你只是還沒打開 App,檔案就停在「已產出」,不算失敗。 +- 一則訊息送到時 Bot 沒開始回覆,約 15 秒後那件算失敗(「Bot 沒有開始回覆」);重送一次就好。 +- 每個 Bot 只留最近 40 筆紀錄,很舊的任務在聊天清掉後就不見了。 +- (驗證)假模型對 `[[call …]]` 只叫那一步,`ask_bot` 的同事回的是「FAKE-MODEL 回答:…」,一樣算 C。 +- (驗證)首頁的「任務」數字只算進行中、等你和 24 小時內失敗的;已回覆、已交付不算,所以前兩步看不到數字是對的。數字在 `#quick [data-q="tasks"] b` 裡(按鈕的字中間是換行,`wait-text '任務 1'` 對不到)。 +- (驗證)從卡片進聊天,返回回到任務頁(不是首頁):步驟照這個順序寫。 diff --git a/mobile/index.html b/mobile/index.html index ef88889..ea77925 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -388,6 +388,20 @@ details.dt>.dt-in{padding-left:var(--sp-4);margin-top:var(--sp-2)} .gt button{margin-left:auto;font-weight:500;color:var(--accent-ink);font-size:var(--fs-small)} .item{display:flex;align-items:center;gap:12px;padding:11px 14px;min-height:48px;border-top:.5px solid var(--line2);width:100%;text-align:left} .item:first-child{border-top:0} +/* 任務: one card per task (the bot, its words, its state, where, the last sign of life, files, evidence) */ +.tk{display:flex;gap:12px;align-items:flex-start;padding:12px 14px;border-top:.5px solid var(--line2);width:100%;text-align:left} +.tk:first-child{border-top:0} +.tk:active{background:var(--hover)} +.tk .mid{flex:1;min-width:0} +.tk .hd{display:flex;align-items:center;gap:8px;font-size:var(--fs-caption);color:var(--text3)} +.tk .hd .who{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.tk .st{flex:none;font-size:var(--fs-caption);font-weight:600;padding:2px 8px;border-radius:999px;background:var(--hover);color:var(--text2)} +.tk .st.go{color:var(--accent-ink)}.tk .st.wait{color:var(--warn);background:var(--attention-bg)}.tk .st.bad{color:var(--danger)}.tk .st.good{color:var(--up)} +.tk .tx{font-size:var(--fs-ui);color:var(--text);margin:3px 0 2px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.tk .ln{font-size:var(--fs-caption);color:var(--text3);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;line-height:1.6} +.tk .ln.why{color:var(--text2)}.tk .ln.why.bad{color:var(--danger)} +.tk .ln .dlv{padding:0 2px;min-height:0;margin:0;vertical-align:-2px}.tk .ln .dlv.failed{color:var(--danger);font-weight:700} +.m.lit .bub{box-shadow:0 0 0 2px var(--accent)} button.item:active,.item.tap:active{background:var(--hover)} .item .ic{color:var(--text2)} .item .mid{flex:1;min-width:0} @@ -897,7 +911,7 @@ try { matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () = const S = { voice: {}, relay: localStorage.getItem("anybot.relay") === "1", token: localStorage.getItem("anybot.token") || "", host: localStorage.getItem("anybot.host") || "", - version: 0, bots: [], approvals: [], pages: [], models: [], hostName: "", mac: false, box: "", boxOn: false, role: "owner", + version: 0, bots: [], approvals: [], pages: [], tasks: [], jumpAt: 0, models: [], hostName: "", mac: false, box: "", boxOn: false, role: "owner", prevShown: 0, prevFirst: "", answer: null, sc: "", open: 0, msgs: [], pending: [], quote: null, unfold: {}, openSteps: {}, detail: {}, detailNew: {}, audit: {}, settings: null, polling: false, entered: false, chatSig: "", file: null, @@ -1098,7 +1112,7 @@ document.querySelectorAll("[data-back]").forEach((b) => { b.innerHTML = ic("chev function draw(v, arg) { show(v); if (v === "home") renderHome(); - else if (v === "chat") openChat(arg.bot); + else if (v === "chat") openChat(arg.bot, arg.at); else if (v === "details") renderDetails(arg.bot, arg.tab); else if (v === "botset") renderBotset(arg.bot); else if (v === "list") renderList(arg); @@ -1372,7 +1386,7 @@ function mergeState(prev, v) { } function apply(v) { S.bots = v.bots || []; S.approvals = v.approvals || []; S.hostName = v.host || ""; S.mac = !!v.mac; - S.box = v.box || ""; S.boxOn = !!v.box_available; S.pages = v.pages || []; S.models = v.models || []; S.sections = v.sections || null; S.role = v.role || "owner"; + S.box = v.box || ""; S.boxOn = !!v.box_available; S.pages = v.pages || []; S.tasks = v.tasks || []; S.models = v.models || []; S.sections = v.sections || null; S.role = v.role || "owner"; S.voice = v.voice || {}; micShown(); appBadge(); // The computer's 外觀 (an older brain sends neither: the built-in look stays). if (v.palettes) applyPalette(v.palettes); @@ -1413,6 +1427,7 @@ function apply(v) { } else if (t.v === "details" && S.tab !== "memory" && Date.now() - (S.detailAt || 0) > 1500) renderDetails(t.arg.bot, S.tab, isNew(t.arg.bot)); else if (t.v === "botset" && !isNew(t.arg.bot)) renderBotset(t.arg.bot); + else if (t.v === "list" && t.arg.kind === "tasks") listTasks($("list")); settingsChanged(); } @@ -1443,7 +1458,9 @@ function renderHome() { const main = S.bots.find((b) => b.primary) || S.bots[0]; const comps = (main && main.computers) || []; const on = comps.filter((c) => c.online).length; + const tn = taskAttention(); $("quick").innerHTML = owner() ? [ + ``, ``, ``, ``, @@ -1657,7 +1674,8 @@ function keepChat(id, msgs, sig) { CHATS.delete(k); CHATS.set(k, was && was.sig === sig && Date.now() - (was.t || 0) <= 3600000 ? was : c); while (CHATS.size > 12) { const old = CHATS.keys().next().value; CHATS.delete(old); KEEP.del("chat:" + old); } } -function openChat(id) { +function openChat(id, at) { + S.jumpAt = at || 0; if (S.open !== id) { keepChat(S.open, S.msgs, S.chatSig); S.msgs = []; S.pending = []; S.quote = null; S.unfold = {}; S.openSteps = {}; S.chatSig = ""; S.prevShown = 0; S.prevFirst = ""; MODE_OPEN = ""; $("msgs").innerHTML = ""; @@ -1675,7 +1693,8 @@ function openChat(id) { else { chat.style.removeProperty("--bot"); chat.style.removeProperty("--bot-ink"); } chatHead(); renderChips(); renderQuote(); renderMsgs(); $("scroller").scrollTop = $("scroller").scrollHeight; atEnd = true; - loadChat(true); renderDock(); + jumpTo(); + loadChat(!at); renderDock(); api(base() + `api/bots/${id}/read`, {json: {}}).catch(() => {}); } let loading = false, again = false; @@ -1699,11 +1718,14 @@ async function loadChat(jump) { mergeDeliveries(msgs, v.deliveries); S.msgs = msgs; S.chatSig = v.sig || ""; S.chatLoaded = true; renderMsgs(); keepSoon(); if (jump || near) sc.scrollTop = sc.scrollHeight; + jumpTo(); } else { S.chatSig = ""; again = true; } } } catch (e) { toast(e.message); if (S.open === id && !S.chatLoaded && S.view === "chat") renderMsgs(); } loading = false; if (again) { again = false; loadChat(); } + // 任務 → a message older than what the phone keeps of the chat: the chat stays at its end. + else if (S.jumpAt && S.chatLoaded && S.open === id && !jumpTo()) { S.jumpAt = 0; toast("那件事開頭的訊息太早了,手機上只留最近的訊息"); } } // 載入更早:開頁只拿最新 30 條,這裡一次往回補 60 條(序號去重,接在上方)。 async function loadOlder() { @@ -1727,6 +1749,7 @@ function applyChat(msgs, sig, deliveries) { S.msgs = msgs; renderMsgs(); keepSoon(); if (near) sc.scrollTop = sc.scrollHeight; + jumpTo(); } // 交付確認(✓ mark)與訊息分開送(服务端也分開放:别的装置回報檔案不該改到聊天指紋): // 蓋在持有的那批 attachment 上;動過的回 true(要重畫)。 @@ -3025,13 +3048,14 @@ async function settingsChanged() { } let listTimer = null; function stopListTimer() { clearInterval(listTimer); listTimer = null; } -const TITLES = {routines: "例行任務", pages: "頁面", computers: "電腦", settings: "設定", general: "一般", models: "模型", perms: "權限", integrations: "整合", vault: "保險庫", account: "手機與帳號", updates: "更新"}; +const TITLES = {tasks: "任務", routines: "例行任務", pages: "頁面", computers: "電腦", settings: "設定", general: "一般", models: "模型", perms: "權限", integrations: "整合", vault: "保險庫", account: "手機與帳號", updates: "更新"}; async function renderList(arg) { const kind = arg.kind; $("list-title").textContent = TITLES[kind] || ""; $("list-act").innerHTML = ""; const el = $("list"); stopListTimer(); + if (kind === "tasks") return listTasks(el); if (kind === "routines") return listRoutines(el); if (kind === "pages") return listPages(el); if (SETTINGS_PAGES.includes(kind)) { @@ -3044,6 +3068,52 @@ async function renderList(arg) { if (["computers", "integrations"].includes(kind)) listTimer = setInterval(async () => { await loadSettings(); if (cur().v === "list" && cur().arg.kind === kind) drawSettings(kind, true); }, 4000); } } +// ---------- 任務 ---------- +// Every bot's tasks as the brain works them out — from the steps, the turn's end, the follow-ups, +// the goal checks and whether a device showed the files, never from what a bot says. They come +// with the state (kept on this phone with the rest: the list draws from it offline too). Nothing +// in the chat: a quiet 任務 among the home's shortcuts, with how many need a look. +const TASK_CLS = {running: "go", following: "go", verifying: "go", waiting: "wait", failed: "bad", delivered: "good", confirmed: "good", verified: "good"}; +const TASK_ACTIVE = ["running", "waiting", "following", "verifying"]; +function taskAttention() { + const day = Date.now() - 864e5; + return (S.tasks || []).filter((t) => TASK_ACTIVE.includes(t.status) || (t.status === "failed" && Math.max(t.finished || 0, t.heartbeat || 0) > day)).length; +} +function since(ms) { const a = ago(ms); return /(分鐘|小時|天)$/.test(a) ? a + "前" : a; } +function taskFile(a) { + const d = {in_chat: "chat", shown: "shown", opened: "opened", failed: "failed"}[a.delivery] || "chat"; + const mark = d === "failed" ? "!" : ic("check", 12) + (d !== "chat" ? ic("check", 12) : ""); + return `${esc(a.name)}${mark}`; +} +function taskCard(t) { + const b = bot(t.bot); + const facts = ["在 " + (t.computer || "—"), t.steps ? `${t.steps} 步${t.failed ? `(${t.failed} 步失敗)` : ""}` : "", "最後動靜 " + (since(Math.max(t.heartbeat || 0, t.at || 0)) || "剛剛")].filter(Boolean).join(" · "); + const active = TASK_ACTIVE.includes(t.status); + const doing = t.doing ? `
${active ? "現在" : "最後一步"}:${esc(t.doing)}
` : ""; + const why = t.why && t.why !== t.doing ? `
${esc(t.why)}
` : ""; + const files = (t.artifacts || []).map(taskFile).join("、"); + const foot = `${files ? "產物:" + files + " · " : ""}證據 ${esc(t.level || "")}${t.kept ? " · 照紀錄(聊天裡已經沒有)" : ""}`; + return ``; +} +function listTasks(el) { + const list = S.tasks || [], n = taskAttention(); + const head = S.stale ? "離線中:顯示的是上次存在這支手機上的任務" : n ? `${n} 件進行中、等你或今天失敗` : ""; + el.innerHTML = list.length + ? `${head ? `
${esc(head)}
` : ""}
${list.map(taskCard).join("")}
狀態由 AnyBot 從步驟、回合結束和交付回報算出,不是 Bot 說的。證據 A:系統自己看到;C:別的 Bot 轉述;未驗:沒有系統看得到的結果。
` + : `
還沒有任務。
交代 Bot 做一件事,它就會出現在這裡。
`; + el.querySelectorAll("[data-task]").forEach((x) => x.onclick = () => { const [b, at] = x.dataset.task.split(":").map(Number); if (bot(b)) go("chat", {bot: b, at}); else toast("這個 Bot 已經刪除了"); }); +} +// 任務 → 那則訊息: the chat at where the task began, lit a moment (once that message is here). +function jumpTo() { + if (!S.jumpAt || S.view !== "chat") return false; + const i = S.msgs.findIndex((m) => m.at === S.jumpAt && m.role === "user"); + const el = i < 0 ? null : document.querySelector(`#msgs [data-msg="${i}"]`); + if (!el) return false; + S.jumpAt = 0; + el.scrollIntoView({block: "center"}); atEnd = false; + el.classList.add("lit"); setTimeout(() => el.classList.remove("lit"), 1800); + return true; +} async function listRoutines(el, again) { // (Every bot's details asked at once, not one after the other; what this phone has is drawn first.) const missing = again ? [] : S.bots.filter((b) => !isNew(b.id)); diff --git a/src/agent.rs b/src/agent.rs index 6e2520e..0743fa3 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -337,7 +337,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" | "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"); 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). @@ -1647,7 +1647,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" | "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" | 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 5166e83..8a44827 100644 --- a/src/app.rs +++ b/src/app.rs @@ -41,6 +41,7 @@ mod mirror_ui; mod pages_ui; mod voice_ui; mod drops_ui; +mod tasks_ui; mod memory_ui; mod goal_ui; mod context_ui; @@ -299,6 +300,8 @@ pub struct App { slash: chat_ui::Slash, /// 傳送到其他裝置, when its dialog is open; and the device chosen last time. drop_page: Option, + /// 任務: the list the brain works out, and its dialog. + tk: tasks_ui::TasksUi, drop_last: String, nightly_checked: Option, /// Files and pictures waiting to go with the next message. @@ -563,6 +566,7 @@ impl App { mem_page: None, slash: Default::default(), drop_page: None, + tk: Default::default(), drop_last: String::new(), nightly_checked: None, att: Default::default(), @@ -1313,6 +1317,11 @@ impl App { app.show_settings = true; app.settings_tab = SettingsTab::Computers; } + // 任務: the dialog, with the list worked out from that data. + Ok("tasks") => { + app.tasks_tick(true); + app.tk.open = true; + } _ => {} } } @@ -2292,6 +2301,8 @@ impl App { if self.state.branch_bots.iter().any(|b| b.id == bot_id) { self.branch_settled(bot_id, outcome); } + // 任務: how this turn ended is noted on its task now (a chat cleared next keeps it). + self.tasks_tick(true); } /// Wake a bot with a message: a new turn now when idle; when it is working, a turn of its own @@ -2547,6 +2558,9 @@ impl App { appctl::Outcome { text, ok: true, wake: vec![], theme_changed: false, page: None } } else if call.name == "my_profile" { appctl::Outcome { text: self.my_profile_text(bot_id), ok: true, wake: vec![], theme_changed: false, page: None } + } else if call.name == crate::tasks::TOOL { + // 任務: with what runs and waits now (only the window knows). + appctl::Outcome { text: self.list_tasks_text(bot_id, &call.args), ok: true, wake: vec![], theme_changed: false, page: None } } else if call.name == "update_my_profile" { self.apply_profile_change(bot_id, &call.args) } else if call.name == "update_bot" && serde_json::from_str::(&call.args).map(|v| v["default_computer"].is_string()).unwrap_or(false) { @@ -3624,6 +3638,7 @@ impl App { follow_ups: vec![], routines: vec![], last_turn: None, + tasks: vec![], goal: None, plan: None, draft: String::new(), @@ -6468,6 +6483,8 @@ impl App { self.tick_routines(ctx); self.monitor_tick(ctx); self.followup_tick(ctx); + // 任務: what each task stands at, worked out again (and what changed, noted on its bot). + self.tasks_tick(false); self.tick_asks(ctx); self.tick_branches(ctx); self.watchdog(); @@ -7044,6 +7061,7 @@ impl eframe::App for App { self.bot_editor(ctx); self.memory_page(ctx); self.drops_page(ctx); + self.tasks_window(ctx); self.settings(ctx); } self.delete_dialog(ctx); @@ -7691,6 +7709,7 @@ fn system_prompt(b: &Bot, st: &State, computers: &[tools::Target], default_compu s.push_str("\n\n使用者要看某台電腦的畫面(截圖給我看、讓我看看)時,用 computer(action=show):畫面會直接出現在聊天裡。"); } s.push_str("\n\n做好的檔案(試算表、文件、Markdown、網頁、圖片)用 send_file 傳進聊天,使用者點一下就能預覽;不要只說檔案放在哪裡。傳了不等於使用者看到了:不要說他已經看到,以 send_file 結果後面的〔交付狀態〕為準;使用者問收到沒、傳到手機了沒,照那個狀態回答。適合的時候可以用 react 對使用者的訊息按個表情(例如謝謝你時按 ❤️),不用每次都按。"); + s.push_str("\n使用者問現在在跑什麼、那件事做完了沒、檔案收到沒:用 list_tasks(all=true 看所有 Bot)照系統算的任務狀態和證據回答,不要憑記憶;狀態沒說交付、確認或驗收的,就不要說已經完成或收到。"); s.push_str("\n\n"); s.push_str(&crate::i18n::reply_instruction(&st.language)); // Its soul and the person's 指示 (one text) last and under a heading: dropped bare into the diff --git a/src/app/chat_ui.rs b/src/app/chat_ui.rs index 7cab1dc..7fda1e7 100644 --- a/src/app/chat_ui.rs +++ b/src/app/chat_ui.rs @@ -196,6 +196,7 @@ fn doing(name: &str, args: &str, place: Option<&str>) -> String { "ask_bot" => with("正在問另一個 Bot", s("bot")), "teach_skill" => with("正在教技能給", s("bot")), "list_routines" => "正在查看例行任務".into(), + crate::tasks::TOOL => "正在查看任務".into(), "create_routine" | "update_routine" | "delete_routine" => "正在安排例行任務".into(), "run_routine_now" => "正在執行例行任務".into(), "list_bots" | "create_bot" | "update_bot" => "正在設定 Bot".into(), diff --git a/src/app/layout_audit.rs b/src/app/layout_audit.rs index 01bc9e8..647bd2f 100644 --- a/src/app/layout_audit.rs +++ b/src/app/layout_audit.rs @@ -101,6 +101,13 @@ fn scenes() -> Vec<(&'static str, Open)> { }) }; vec![ + ( + "任務", + Box::new(|a: &mut App| { + a.tasks_tick(true); + a.tk.open = true; + }), + ), ("設定 › 一般", tab(SettingsTab::General)), ("設定 › 手機與帳號", tab(SettingsTab::Remote)), ("設定 › 模型", tab(SettingsTab::Providers)), diff --git a/src/app/mirror_ui.rs b/src/app/mirror_ui.rs index 78b0bae..d0ba749 100644 --- a/src/app/mirror_ui.rs +++ b/src/app/mirror_ui.rs @@ -46,7 +46,7 @@ fn copy_own(to: &mut State, from: &State) { to.celebrate = from.celebrate; } /// Bot fields the brain alone changes (its chat, and what a turn leaves behind). -const BOT_RUNTIME: &[&str] = &["id", "messages", "threads", "unread", "last_turn", "context_tokens", "goal", "plan", "regen_undo", "branches", "branch_of"]; +const BOT_RUNTIME: &[&str] = &["id", "messages", "threads", "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 = "••••(已設定,在大腦上)"; @@ -432,6 +432,8 @@ pub struct Screens { struct Seen { version: u64, config: u64, + /// 任務: the fingerprint of the list it was sent last. + tasks: u64, bots: HashMap>, threads: HashMap, at: Option, @@ -782,6 +784,8 @@ pub struct Mirror { pub(super) computers: HashMap, /// The connectors at the brain, as [`App::mcp_state`] gives them. pub(super) mcp_state: Value, + /// 任務: the list the brain worked out (None until it sends one). + pub(super) tasks: Option>, /// When each bot's last turn ended, as last heard (a newer one ending well is read aloud). settled: HashMap, /// The brain's key for each card waiting here (by bot id): an answer from this screen names @@ -1024,6 +1028,11 @@ impl App { } } seen.bots.retain(|id, _| self.state.bots.iter().any(|b| b.id == *id)); + // 任務: the brain's list, when it changed since the screen was sent it. + if self.tk.sig != 0 && seen.tasks != self.tk.sig { + seen.tasks = self.tk.sig; + out["tasks"] = serde_json::to_value(&self.tk.list).unwrap_or_default(); + } out["bots"] = Value::Array(bots); out["threads"] = Value::Array(threads); out["live"] = self.streams.iter().map(|(id, l)| (id.to_string(), json!({"status": l.status, "paused": l.paused}))).collect::>().into(); @@ -1781,6 +1790,10 @@ impl App { if v["box"].is_object() { self.mir.box_state = v["box"].clone(); } + // 任務: the brain's list, as it worked it out. + if v["tasks"].is_array() { + self.mir.tasks = serde_json::from_value(v["tasks"].clone()).ok(); + } if v["mcp"].is_object() { self.mir.mcp_state = v["mcp"].clone(); } @@ -2699,6 +2712,26 @@ mod tests { assert!(app.state.bot(bot).unwrap().messages.iter().all(|m| m.attachments.iter().all(|a| a.seen.is_empty()))); } + /// 任務: a screen shows the list its brain worked out — sent when it changes, not again. + #[test] + fn a_screen_gets_the_brains_task_list() { + let ctx = egui::Context::default(); + let mut brain = App::new(&ctx, Some(std::env::temp_dir().join("anybot-screen-tasks-brain.png"))); + let id = brain.state.bots[0].id; + brain.state.bot_mut(id).unwrap().messages = vec![Message { at: 1_000, ..Message::user("整理報表") }].into(); + brain.streams.insert(id, Live { cancel: Arc::new(AtomicBool::new(false)), started: Instant::now(), last: Instant::now(), produced: true, status: None, paused: false, paused_at: None, unattended: false, steer: Default::default(), direct: Arc::new(AtomicBool::new(false)), turn_id: "t".into(), turn: 0 }); + brain.tasks_tick(true); + let pulled = brain.brain_pull_at(5, "screen-tasks", 0, false, false); + let mine = pulled["tasks"].as_array().unwrap().iter().find(|t| t["bot"] == id).cloned().unwrap(); + assert_eq!((mine["status"].as_str(), mine["text"].as_str()), (Some("running"), Some("整理報表"))); + assert!(brain.brain_pull_at(6, "screen-tasks", 5, false, false).get("tasks").is_none(), "an unchanged list isn't sent again"); + let mut screen = App::new(&ctx, Some(std::env::temp_dir().join("anybot-screen-tasks.png"))); + screen.mir.on = true; + screen.mirror_apply(json!({"tasks": pulled["tasks"].clone()})); + assert_eq!(screen.tasks_list().len(), pulled["tasks"].as_array().unwrap().len()); + assert!(screen.tasks_list().iter().any(|t| t.bot == id && t.status == crate::tasks::Status::Running)); + } + /// 螢幕電腦上回答的卡帶著大腦給那張卡的 key(.claude/skills/verify-approval-routing 的 /// ScreenRefreshes → YouAnswerOnScreen → BrainTakesAnswer):大腦只把它交給那張卡。以前 /// 不帶,大腦交給那時候在等的卡(F1)。 diff --git a/src/app/remote_ui.rs b/src/app/remote_ui.rs index 362edd3..fc5b62c 100644 --- a/src/app/remote_ui.rs +++ b/src/app/remote_ui.rs @@ -327,6 +327,8 @@ impl App { self.approvals.get(&br.id).map(|a| (br.id, a.call_id.clone(), self.ask_keys.get(&br.id).cloned())).hash(&mut h); } crate::cloudbox::run_state().label().hash(&mut h); + // 任務: the list the brain worked out (the phone's 任務 page and its count). + self.tk.sig.hash(&mut h); // A connector connected or failing: screens and phones hear of it now, not at the next // long poll's end. let mut up: Vec<(String, usize)> = crate::mcp::status().into_iter().collect(); @@ -527,6 +529,7 @@ impl App { view.approvals.extend(self.phone_cards(b)); } view.pages = self.state.pages.clone(); + view.tasks = self.tk.list.iter().map(crate::tasks::json).collect(); // The models a bot can be switched to from the phone: each provider that is ready. view.models = crate::providers::ALL_PROVIDERS .iter() diff --git a/src/app/sidebar_ui.rs b/src/app/sidebar_ui.rs index 9645ea1..1d309ea 100644 --- a/src/app/sidebar_ui.rs +++ b/src/app/sidebar_ui.rs @@ -293,6 +293,8 @@ impl App { ui.data_mut(|d| d.insert_temp(egui::Id::unique(SEARCH_FOCUS), frame)); } } + // 任務: every bot's tasks and how each stands (tasks_ui.rs). + self.tasks_button(ui); }); }); if self.search_open || !self.search.is_empty() { diff --git a/src/app/tasks_ui.rs b/src/app/tasks_ui.rs new file mode 100644 index 0000000..6d8def2 --- /dev/null +++ b/src/app/tasks_ui.rs @@ -0,0 +1,310 @@ +// 任務 in the window. The brain works the list out (tasks.rs) every few seconds and at each +// turn's end, notes on the bots what changed, and hands the same list to the phone (remote_ui), +// the screens (mirror_ui) and the bots' `list_tasks`. A screen shows the list its brain sent. +// +// The list itself stays out of the chat: a quiet 任務 button at the top of the sidebar (a small +// number on it while something goes on or failed today) opens a dialog with every bot's tasks, +// the newest first; a click opens that chat at the task's first message. + +use super::*; +use crate::tasks::{self, Dlv, Status, Task}; +use std::hash::{Hash, Hasher}; + +/// How often the brain works the list out again (ms; a turn's end does it at once). +const EVERY_MS: u128 = 3_000; + +#[derive(Default)] +pub struct TasksUi { + /// The list as last worked out (on the brain): what every screen shows. + pub(super) list: Vec, + /// Its fingerprint: the phone and the screens get it again when it changes. + pub(super) sig: u64, + at: Option, + /// The dialog is open. + pub(super) open: bool, + /// A screen without its brain's list yet: worked out from its own copy (no live state). + copy: Option>, +} + +/// The colour a state is drawn in: going on in the accent, waiting for the person in the +/// attention colour, failed in red, there and confirmed in green, the rest quiet. +fn status_color(s: Status, p: Palette) -> Color32 { + match s { + Status::Waiting => p.attention, + Status::Running | Status::Following | Status::Verifying => p.accent, + Status::Failed => p.danger, + Status::Delivered | Status::Confirmed | Status::Verified => p.up, + Status::Produced | Status::Answered | Status::Stopped | Status::Unverified => p.text2, + } +} + +/// A file's mark, as under it in the chat: ✓ in the chat, ✓✓ shown, ✓✓ opened, ! not shown. +fn mark(d: Dlv) -> &'static str { + match d { + Dlv::InChat => "✓", + Dlv::Shown | Dlv::Opened => "✓✓", + Dlv::Failed => "!", + } +} + +impl App { + /// What runs and waits now, as tasks.rs takes it. + fn tasks_live(&self) -> tasks::Live { + let mut l = tasks::Live::default(); + for id in self.streams.keys() { + let step = self + .state + .bot(*id) + .and_then(|b| b.messages.iter().rev().take(8).filter(|m| m.role == Role::Assistant).flat_map(|m| m.tool_calls.iter()).find(|c| matches!(c.status, ToolStatus::Running | ToolStatus::Waiting)).map(|c| crate::evidence::step_line(&c.name, &c.args))) + .unwrap_or_default(); + l.running.insert(*id, step); + } + for (id, a) in &self.approvals { + let Some(b) = self.state.bot(*id) else { continue }; + let what = match a.kind { + ApprovalKind::Question => format!("等你回答:{}", first_line(&crate::ask::describe(&a.reason), 80)), + ApprovalKind::Handoff => format!("等你處理:{}", first_line(&a.reason, 80)), + ApprovalKind::EnableTools => "等你允許使用電腦工具".into(), + ApprovalKind::EnableThisComputer => "等你允許在你的電腦上執行".into(), + ApprovalKind::Action => format!("等你允許:{}", remote_ui::card_what(b, a)), + }; + l.waiting.insert(*id, what); + } + l.checking = self.goal_checking.iter().copied().chain(self.goal_due.iter().map(|(b, _)| *b)).collect(); + l + } + + /// The brain: the list again (every few seconds, or `now`), and on each bot what changed. + pub(super) fn tasks_tick(&mut self, now: bool) { + if self.mir.on || (!now && self.tk.at.is_some_and(|t| t.elapsed().as_millis() < EVERY_MS)) { + return; + } + self.tk.at = Some(Instant::now()); + let live = self.tasks_live(); + let ms = crate::model::now_ms(); + let per: Vec> = self.state.bots.iter().map(|b| tasks::of_bot(b, &live, ms)).collect(); + if !self.demo { + let mut added = false; + for (b, ts) in self.state.bots.iter_mut().zip(&per) { + added |= tasks::note(b, ts, ms); + } + if added { + self.mark(); + } + } + let list = tasks::newest(per.into_iter().flatten().collect()); + let mut h = std::collections::hash_map::DefaultHasher::new(); + serde_json::to_string(&list).unwrap_or_default().hash(&mut h); + self.tk.sig = h.finish(); + self.tk.list = list; + } + + /// The list every screen of this AnyBot shows: the brain's own, or (a screen) the one its + /// brain sent. + pub(super) fn tasks_list(&self) -> &[Task] { + if self.mir.on { + self.mir.tasks.as_deref().or(self.tk.copy.as_deref()).unwrap_or(&[]) + } else { + &self.tk.list + } + } + + /// `list_tasks`: the list in words, as tasks::answer filters it for who started this turn. + pub(super) fn list_tasks_text(&mut self, bot_id: u64, args: &str) -> String { + self.tasks_tick(true); + let home = self.state.home_of(bot_id); + let v = crate::tools::args_of(args); + crate::tasks::answer(&self.tk.list, &self.state.bots, home, &v, &self.state.timezone) + } + + /// The sidebar's 任務 button (beside 搜尋), with how many need a look. + pub(super) fn tasks_button(&mut self, ui: &mut egui::Ui) { + let p = self.pal; + let n = tasks::attention(self.tasks_list(), crate::model::now_ms()); + let r = pill_icon(ui, crate::icons::Icon::CircleCheck, p); + if n > 0 { + let c = r.rect.right_top() + vec2(-9.0, 9.0); + let label = if n > 9 { "9+".to_string() } else { n.to_string() }; + let font = egui::FontId::proportional(FONT_XS * 0.85); + let w = ui.painter().layout_no_wrap(label.clone(), font.clone(), p.on_primary).size().x.max(8.0); + ui.painter().rect_filled(egui::Rect::from_center_size(c, vec2(w + 6.0, 14.0)), 7.0, p.accent); + ui.painter().text(c, egui::Align2::CENTER_CENTER, label, font, p.on_primary); + } + let tip = if n > 0 { format!("{}({n} {})", t("任務"), t("件要看")) } else { t("任務") }; + if r.on_hover_text(tip).clicked() { + self.tk.open = true; + // A screen without its brain's list: its own copy, said as such. + if self.mir.on && self.mir.tasks.is_none() { + self.tk.copy = Some(tasks::all(&self.state.bots, &tasks::Live::default(), crate::model::now_ms())); + } + } + } + + /// The 任務 dialog: every bot's tasks, the newest first. + pub(super) fn tasks_window(&mut self, ctx: &egui::Context) { + if !self.tk.open { + return; + } + let p = self.pal; + let list: Vec = self.tasks_list().to_vec(); + let from_copy = self.mir.on && self.mir.tasks.is_none(); + let body_h = dialog_max_height(ctx) - 48.0; + let mut open_at: Option<(u64, i64)> = None; + let now = crate::model::now_ms(); + let closed = dialog(ctx, "tasks", "任務", 560.0, true, p, |ui| { + dialog_body(ui, "tasks-body", body_h, |ui| { + let n = tasks::attention(&list, now); + let head = if from_copy { + t("還沒連上大腦:這是這台電腦存的副本算的,不知道現在在跑什麼。") + } else if list.is_empty() { + t("還沒有任務。交代 Bot 做一件事,它就會出現在這裡。") + } else if n > 0 { + format!("{n} {}", t("件進行中、等你或今天失敗。狀態由 AnyBot 從步驟和交付回報算出,不是 Bot 說的。")) + } else { + t("狀態由 AnyBot 從步驟和交付回報算出,不是 Bot 說的。") + }; + hint(ui, head, p); + ui.add_space(10.0); + for task in &list { + if self.task_card(ui, task, now) { + open_at = Some((task.bot, task.at)); + } + } + }); + }); + if closed { + self.tk.open = false; + self.tk.copy = None; + } + if let Some((bot, at)) = open_at { + self.tk.open = false; + self.open_task(ctx, bot, at); + } + } + + /// That chat, scrolled to the task's first message (when the chat still has it). + pub(super) fn open_task(&mut self, ctx: &egui::Context, bot: u64, at: i64) { + if self.state.bot(bot).is_none() { + return; + } + self.show_settings = false; + self.select_bot(ctx, bot); + if let Some(index) = self.state.bot(bot).and_then(|b| b.messages.iter().position(|m| m.at == at && m.role == Role::User)) { + self.goto = Some(crate::find::Goto { bot, index, at, since: Instant::now() }); + } + } + + /// One task's card; true when clicked. + fn task_card(&mut self, ui: &mut egui::Ui, task: &Task, now: i64) -> bool { + let p = self.pal; + let name = self.state.bot(task.bot).map(|b| b.name.clone()).unwrap_or_else(|| t("已刪除的 Bot")); + // (The kit's card: its content's rect, out to the card's edge, is what a click lands on.) + let card = setting_card(ui, p, |ui| { + ui.spacing_mut().item_spacing.y = 3.0; + ui.horizontal(|ui| { + let (face, _) = ui.allocate_exact_size(vec2(22.0, 22.0), egui::Sense::hover()); + if self.state.bot(task.bot).is_some() { + self.live_face(ui, task.bot, face, false); + } + let from = task.source.label(); + let gap = if from.ends_with(|c: char| c.is_ascii_alphabetic()) { " " } else { "" }; + // The state's chip keeps its room on the right; a long bot name is cut before it. + let label = t(task.status.label()); + let chip_w = ui.painter().layout_no_wrap(label.clone(), egui::FontId::new(FONT_XS, crate::bold()), p.text).size().x + 16.0; + let who_w = (ui.available_width() - chip_w - 8.0).max(40.0); + ui.allocate_ui_with_layout(vec2(who_w, 22.0), Layout::left_to_right(Align::Center), |ui| { + ui.set_max_width(who_w); + ui.add(egui::Label::new(RichText::new(format!("{name} · {from}{gap}{}", t("開的"))).size(FONT_SM).color(p.text2)).truncate()); + }); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + let c = status_color(task.status, p); + Frame::new().fill(c.gamma_multiply(0.14)).corner_radius(R_M).inner_margin(Margin::symmetric(8, 2)).show(ui, |ui| { + ui.label(RichText::new(label).size(FONT_XS).color(c).strong()); + }); + }); + }); + ui.add(egui::Label::new(RichText::new(&task.text).size(FONT_BASE).color(p.text)).truncate()); + let mut facts = vec![format!("{} {}", t("在"), task.computer)]; + if task.steps > 0 { + facts.push(if task.failed > 0 { format!("{} {}({} {})", task.steps, t("步"), task.failed, t("步失敗")) } else { format!("{} {}", task.steps, t("步")) }); + } + facts.push(format!("{} {}", t("最後動靜"), crate::pages::ago(task.heartbeat.max(task.at), now))); + ui.add(egui::Label::new(RichText::new(facts.join(" · ")).size(FONT_XS).color(p.text3)).truncate()); + if !task.doing.is_empty() { + let lead = if task.status.active() { t("現在:") } else { t("最後一步:") }; + ui.add(egui::Label::new(RichText::new(format!("{lead}{}", task.doing)).size(FONT_XS).color(p.text2)).truncate()); + } + if !task.why.is_empty() && task.why != task.doing { + let c = if task.status == Status::Failed { p.danger } else { p.text2 }; + ui.add(egui::Label::new(RichText::new(&task.why).size(FONT_XS).color(c)).truncate()); + } + let files: Vec = task.artifacts.iter().map(|a| format!("{} {}", a.name, mark(a.delivery))).collect(); + let level = format!("{} {}", t("證據"), t(task.evidence.label())); + let foot = if files.is_empty() { level } else { format!("{}:{} · {level}", t("產物"), files.join("、")) }; + let r = ui.add(egui::Label::new(RichText::new(foot).size(FONT_XS).color(p.text3)).truncate()); + let mut tip: Vec = task.artifacts.iter().map(|a| a.line()).collect(); + tip.extend(task.proof.iter().cloned()); + if !tip.is_empty() { + r.on_hover_text(tip.join("\n")); + } + ui.min_rect().expand2(vec2(16.0, 14.0)) + }); + let r = ui.interact(card, egui::Id::new(("task-card", &task.id)), egui::Sense::click()); + if r.hovered() { + ui.painter().rect_stroke(card, R_L, Stroke::new(1.0, p.text3), egui::StrokeKind::Inside); + } + r.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn test_app(ctx: &egui::Context, name: &str) -> App { + App::new(ctx, Some(std::env::temp_dir().join(format!("anybot-tasks-{name}.png")))) + } + + /// The deliver wake tasks.rs follows is the one deliver_ui writes: the turn it starts goes on + /// with the task that handed the file over. + #[test] + fn a_deliver_wake_goes_on_with_the_task_that_sent_the_file() { + let ctx = egui::Context::default(); + let mut app = test_app(&ctx, "deliver"); + let id = app.state.bots[0].id; + let wake = super::super::deliver_ui::wake_text("a.png", "att9", "iPhone", "這台裝置讀不出這個檔案"); + let b = app.state.bot_mut(id).unwrap(); + b.messages = vec![ + Message { at: 1_000, ..Message::user("畫一張圖") }, + Message { at: 1_100, attachments: vec![crate::attach::Attachment { name: "a.png".into(), id: "att9".into(), ..Default::default() }], ..Message::assistant("好了", "") }, + Message { at: 2_000, wake: true, ..Message::user(&wake) }, + Message { at: 2_100, ..Message::assistant("換成 JPG 再傳一次", "") }, + ] + .into(); + app.tasks_tick(true); + let mine: Vec<&Task> = app.tk.list.iter().filter(|t| t.bot == id).collect(); + assert_eq!(mine.len(), 1, "{mine:?}"); + assert_eq!((mine[0].text.as_str(), mine[0].heartbeat), ("畫一張圖", 2_100)); + } + + /// What waits on the brain reaches the task and the bots' list_tasks. + #[test] + fn a_card_waiting_makes_its_task_wait_and_the_bot_reads_it() { + let ctx = egui::Context::default(); + let mut app = test_app(&ctx, "wait"); + let id = app.state.bots[0].id; + app.state.bot_mut(id).unwrap().messages = vec![ + Message { at: 1_000, ..Message::user("整理報表") }, + Message { at: 1_100, tool_calls: vec![crate::model::ToolCall { id: "c1".into(), name: "shell".into(), args: r#"{"command":"ls"}"#.into(), status: ToolStatus::Waiting }], ..Message::assistant("", "") }, + ] + .into(); + let (tx, _rx) = channel(); + app.approvals.insert(id, Approval { call_id: "c1".into(), tool: "shell".into(), reason: "執行指令:ls".into(), grant: "ls".into(), reply: tx, kind: ApprovalKind::Action }); + app.tasks_tick(true); + let t = app.tk.list.iter().find(|t| t.bot == id).unwrap(); + assert_eq!((t.status, t.why.as_str()), (Status::Waiting, "等你允許:執行指令")); + assert!(tasks::attention(&app.tk.list, crate::model::now_ms()) >= 1); + let text = app.list_tasks_text(id, "{}"); + assert!(text.contains("〔等你〕") && text.contains("整理報表") && text.contains("等你允許:執行指令"), "{text}"); + } +} diff --git a/src/appctl.rs b/src/appctl.rs index bf600f9..3e9b15c 100644 --- a/src/appctl.rs +++ b/src/appctl.rs @@ -9,9 +9,11 @@ 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; 32] = [ +pub const NAMES: [&str; 33] = [ // 追進度: 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). + crate::tasks::TOOL, "list_routines", "create_routine", "update_routine", "delete_routine", "run_routine_now", "list_bots", "create_bot", "update_bot", "message_bot", "list_computers", "update_settings", // 問同事: ask another bot and wait for its answer (the window runs its turn, see app/asks.rs); @@ -38,6 +40,7 @@ pub fn is_app_tool(name: &str) -> bool { pub fn label(name: &str) -> &'static str { match name { "list_routines" => "查看例行任務", + crate::tasks::TOOL => "查看任務", crate::mcp::MANAGE_TOOL => "管理連接器", crate::hooks::MANAGE_TOOL => "管理 hook", crate::chatgpt::TOOL => "ChatGPT 方案登入", @@ -97,6 +100,7 @@ fn schedule_schema() -> Value { pub fn specs() -> Vec { vec![ crate::followup::spec(), + crate::tasks::spec(), json!({"name": "list_routines", "description": "List this bot's routines (scheduled, repeating tasks).", "parameters": {"type": "object", "properties": {}}}), json!({"name": "look_image", "description": "Look at an earlier picture in this chat again, for one specific question. Older attachments and screenshots are carried in the chat as a short caption only; when that caption is not enough (small text, exact numbers, details), use this. It asks a model that sees pictures for a fresh answer about that one picture. index counts pictures back from the newest (0 = the newest picture in the chat, attachments and screenshots together).", "parameters": {"type": "object", "properties": { @@ -525,6 +529,8 @@ pub fn apply(state: &mut State, bot_id: u64, name: &str, args: &str) -> Outcome Err(e) => err(e), }, "list_pages" => ok(crate::pages::list(&state.pages, bot_id, |id| state.bot(id).map(|b| b.name.clone()).unwrap_or_else(|| "已刪除的 Bot".into()))), + // 任務 (the window answers it with what runs now: app/tasks_ui.rs; this is the chats alone). + crate::tasks::TOOL => ok(crate::tasks::answer(&crate::tasks::all(&state.bots, &crate::tasks::Live::default(), model::now_ms()), &state.bots, bot_id, &v, &state.timezone)), "list_routines" => { let Some(b) = state.bot(bot_id) else { return err("找不到這個 Bot".into()) }; if b.routines.is_empty() { @@ -901,6 +907,7 @@ pub fn apply(state: &mut State, bot_id: u64, name: &str, args: &str) -> Outcome follow_ups: vec![], routines: vec![], last_turn: None, + tasks: vec![], goal: None, plan: None, draft: String::new(), diff --git a/src/featuremap.rs b/src/featuremap.rs index 79a3255..a5b62ab 100644 --- a/src/featuremap.rs +++ b/src/featuremap.rs @@ -48,6 +48,7 @@ pub const AREAS: &[Area] = &[ area!("routines", "例行任務"), area!("goal", "目標(/goal)"), area!("plan", "計畫(/plan)"), + area!("tasks", "任務"), area!("computers", "電腦:大腦與手腳"), area!("box", "Bot 的電腦"), area!("files", "檔案與指令"), diff --git a/src/main.rs b/src/main.rs index db81919..c8f40c1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -73,6 +73,7 @@ mod tools; mod triggers; mod embed; mod evidence; +mod tasks; mod featuremap; mod garden; mod goal; diff --git a/src/model.rs b/src/model.rs index 5f9bbb5..d83bc06 100644 --- a/src/model.rs +++ b/src/model.rs @@ -421,6 +421,11 @@ pub struct Bot { pub routines: Vec, #[serde(default)] pub last_turn: Option, + /// 任務: each change of a task's state as AnyBot noted it (appended, never changed; the + /// newest tasks::KEEP), so the recent ones outlive a cleared or folded chat. The brain's + /// alone; see tasks.rs. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub tasks: Vec, /// 目標 (/goal): what it keeps working toward, turn after turn, until a check says it holds. /// The brain's alone (a turn's end changes it); see goal.rs. #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1240,6 +1245,7 @@ impl State { follow_ups: vec![], routines: vec![], last_turn: None, + tasks: vec![], goal: None, plan: None, default_computer: default_computer(), diff --git a/src/oplog.rs b/src/oplog.rs index 90e1700..ec77328 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", + crate::tasks::TOOL, "list_pages", "read_page", "mac_read_mail", diff --git a/src/remote.rs b/src/remote.rs index 91ef778..74d7c18 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -253,6 +253,8 @@ pub struct View { pub deliveries: HashMap>, /// 頁面, for the phone's page view. pub pages: Vec, + /// 任務: every bot's tasks as the brain worked them out (tasks::json), the newest first. + pub tasks: Vec, /// The models the phone can switch a bot to: each ready provider with its known models. pub models: Vec, /// The sidebar's 分區 in order (None = 未分區), empty ones too, as the desktop shows them. @@ -681,9 +683,11 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { } else { v.bots.clone() }; + // 任務: a teammate sees only the tasks of the bots shared with the team. + let tasks: Vec<&Value> = v.tasks.iter().filter(|t| shared(t["bot"].as_u64().unwrap_or(0))).collect(); let out = json!({ "version": v.version, "host": v.host, "person": v.person, "accent": v.accent, - "pin_order": v.pin_order, "newer": v.newer, "bots": bots, + "pin_order": v.pin_order, "newer": v.newer, "bots": bots, "tasks": tasks, "approvals": if role == "member" { vec![] } else { v.approvals.clone() }, "box": crate::cloudbox::run_state().label(), "box_available": crate::cloudbox::available(), diff --git a/src/setup.rs b/src/setup.rs index d86621e..e6f4dd2 100644 --- a/src/setup.rs +++ b/src/setup.rs @@ -1167,6 +1167,7 @@ fn seed_first() -> i32 { follow_ups: vec![], routines: vec![], last_turn: None, + tasks: vec![], goal: None, plan: None, draft: String::new(), diff --git a/src/share.rs b/src/share.rs index 0fc41f6..aa5f424 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", "goal", "plan", "workdir", "pinned", "id", "computers", "draft", "regen_undo", "branches", "branch_of", "team"] { + 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"] { m.remove(k); } if let Some(Value::Array(routines)) = m.get_mut("routines") { @@ -82,7 +82,7 @@ pub fn import(text: &str, new_id: u64, next_routine: &mut u64, now: i64) -> Resu m.insert("messages".into(), Value::Array(vec![])); // Never import another person's grants, local workdir, threads or memories — nor its // sharing with a team (a file carrying 「team」 shared the new bot at once). - for k in ["goal", "plan", "allow_rules", "tools_enabled", "workdir", "default_computer", "threads", "members", "memories", "unread", "last_turn", "team", "branches", "branch_of"] { + for k in ["goal", "plan", "allow_rules", "tools_enabled", "workdir", "default_computer", "threads", "members", "memories", "unread", "last_turn", "tasks", "team", "branches", "branch_of"] { m.remove(k); } } diff --git a/src/tasks.rs b/src/tasks.rs new file mode 100644 index 0000000..bf60b19 --- /dev/null +++ b/src/tasks.rs @@ -0,0 +1,1331 @@ +//! 任務: everything handed to a bot — the owner's or a teammate's words, a routine's run, a goal, +//! a message from a channel or another bot — as one task, whose state the program works out from +//! what is already kept: the chat's messages and steps, how the turn ended (Bot::last_turn), what +//! runs now and what waits for the person, the follow-ups, the goal and the plan, the steps' +//! evidence (evidence::tally) and each file's 交付確認 (attach.rs). Never from what the bot says. +//! +//! The chat is where a task is read from. A chat cleared, or folded into a summary, would lose +//! the recent ones: so each change of a finished (or waiting) task's state is kept on its bot as a +//! small event (Bot::tasks: appended, never changed, the newest KEEP), and a task the chat no +//! longer has is shown as its last event says. +//! +//! The brain works the list out (app/tasks_ui.rs); the phone, the screens and the bots' +//! `list_tasks` all read that one list. + +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::collections::{HashMap, HashSet}; + +use crate::model::{Bot, Message, Role, ToolStatus, TurnOutcome}; + +/// Events kept on each bot (the oldest go first). +pub const KEEP: usize = 40; +/// Tasks in the list, every bot together (the newest first). +pub const SHOWN: usize = 60; +/// Tasks read from each chat (its newest). +const RECENT: usize = 30; +/// A task's opening words, at most. +const TEXT_CHARS: usize = 60; +/// A person's message nobody started on yet is still on its way this long (ms); after that it +/// had no reply. +const START_GRACE_MS: i64 = 15_000; +/// The read-only tool a bot answers 「現在在跑什麼」 with. +pub const TOOL: &str = "list_tasks"; +/// The reaction that says the person has it (the 「你已確認」 signal, with a file opened). +pub const CONFIRM_REACTION: &str = "👍"; + +/// Where a task is. Each says something the others don't: started, a file there, shown on a +/// device, opened by the person — never one `done` for all of them. +#[derive(Clone, Copy, Serialize, Deserialize, Debug, PartialEq, Eq, Hash, Default)] +#[serde(rename_all = "snake_case")] +pub enum Status { + /// A turn of it runs now. + Running, + /// Waiting for the person: a request to allow, a question card, a goal stopped to ask. + Waiting, + /// 追進度: a follow-up it registered is still being checked. + Following, + /// 目標: its goal is still on; the second model checks whether it holds. + Verifying, + /// Over; it handed over a file no device of the person's has shown yet. + Produced, + /// A device of the person's showed a file it handed over. + Delivered, + /// The person opened a file it handed over, or put 👍 on its answer. + Confirmed, + /// Over with steps the system saw go through, nothing to hand over. + Answered, + /// The goal's checker (a second model) said it holds. + Verified, + Failed, + /// The person stopped it. + Stopped, + /// Over, and nothing the system saw backs it (only words, or only another bot's). + #[default] + Unverified, +} + +impl Status { + pub fn label(self) -> &'static str { + match self { + Status::Running => "進行中", + Status::Waiting => "等你", + Status::Following => "追進度中", + Status::Verifying => "驗收中", + Status::Produced => "已產出", + Status::Delivered => "已交付", + Status::Confirmed => "你已確認", + Status::Answered => "已回覆", + Status::Verified => "已驗收", + Status::Failed => "失敗", + Status::Stopped => "已停止", + Status::Unverified => "結束但未驗證", + } + } + + /// Still going (a turn, the person, a follow-up or a goal check is pending). + pub fn active(self) -> bool { + matches!(self, Status::Running | Status::Waiting | Status::Following | Status::Verifying) + } +} + +/// Who handed it over. +#[derive(Clone, Copy, Serialize, Deserialize, Debug, PartialEq, Eq, Default)] +#[serde(rename_all = "snake_case")] +pub enum Source { + #[default] + Owner, + Member, + Routine, + Trigger, + Goal, + Plan, + FollowUp, + Monitor, + Channel, + Bot, + Delivery, +} + +impl Source { + pub fn label(self) -> &'static str { + match self { + Source::Owner => "你", + Source::Member => "團隊成員", + Source::Routine => "例行任務", + Source::Trigger => "觸發", + Source::Goal => "目標", + Source::Plan => "計畫", + Source::FollowUp => "追進度", + Source::Monitor => "監看", + Source::Channel => "訊息管道", + Source::Bot => "其他 Bot", + Source::Delivery => "交付", + } + } +} + +/// How good the backing is (規格 §6): A the system saw it itself (a step's result), C another +/// bot said so (ask_bot's answer: not checked here), Nothing none at all (未驗). +#[derive(Clone, Copy, Serialize, Deserialize, Debug, PartialEq, Eq, Default)] +pub enum Level { + #[serde(rename = "a")] + A, + #[serde(rename = "c")] + C, + #[default] + #[serde(rename = "none")] + Nothing, +} + +impl Level { + pub fn label(self) -> &'static str { + match self { + Level::A => "A 系統看到", + Level::C => "C 別的 Bot 轉述", + Level::Nothing => "未驗", + } + } +} + +/// How the task's last turn ended. +#[derive(Clone, Copy, Serialize, Deserialize, Debug, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum End { + Success, + Cancelled, + Error, + /// AnyBot stopped while it ran (the 「繼續」 card). + Interrupted, + /// Nothing started on it. + NoReply, +} + +/// How far a file it handed over got with the person (attach::Delivery, and a failure). +#[derive(Clone, Copy, Serialize, Deserialize, Debug, PartialEq, Eq, Default)] +#[serde(rename_all = "snake_case")] +pub enum Dlv { + #[default] + InChat, + Shown, + Opened, + /// A device of the person's couldn't show it, and none has. + Failed, +} + +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Default)] +pub struct Artifact { + pub name: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub id: String, + #[serde(default)] + pub delivery: Dlv, + /// The device it got furthest on (or failed on). + #[serde(default, skip_serializing_if = "String::is_empty")] + pub device: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub why: String, +} + +impl Artifact { + fn of(a: &crate::attach::Attachment) -> Artifact { + use crate::attach::{Delivery, SeenKind}; + let owner = |k: SeenKind| a.seen.iter().find(|s| !s.guest && s.kind == k); + let (delivery, at) = match a.delivery() { + Delivery::Opened => (Dlv::Opened, owner(SeenKind::Opened)), + Delivery::Shown => (Dlv::Shown, owner(SeenKind::Shown)), + Delivery::InChat => match a.first_failure_unseen() { + Some(f) => (Dlv::Failed, Some(f)), + None => (Dlv::InChat, None), + }, + }; + Artifact { name: a.name.clone(), id: a.id.clone(), delivery, device: at.map(|s| s.device.clone()).unwrap_or_default(), why: at.filter(|_| delivery == Dlv::Failed).map(|s| s.why.clone()).unwrap_or_default() } + } + + /// In words: 「a.png:已在 iPhone 顯示」. + pub fn line(&self) -> String { + let how = match self.delivery { + Dlv::InChat => "已在聊天裡,還沒有裝置回報顯示".to_string(), + Dlv::Shown => format!("已在{}顯示", self.device), + Dlv::Opened => format!("{}點開了", self.device), + Dlv::Failed => format!("{}顯示失敗:{}", self.device, self.why), + }; + format!("{}:{how}", self.name) + } +} + +fn is_zero(n: &u32) -> bool { + *n == 0 +} +fn is_zero_i64(n: &i64) -> bool { + *n == 0 +} + +/// One task as every screen shows it. +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Default)] +pub struct Task { + /// Its own name, never changed: the bot and when its opening message was written. + pub id: String, + pub bot: u64, + /// The opening message's time (ms): when it started, and where the chat jumps to. + pub at: i64, + /// The opening words, one line. + pub text: String, + #[serde(default)] + pub source: Source, + #[serde(default)] + pub status: Status, + /// What it does now (running), or the last step it took. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub doing: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub computer: String, + #[serde(default, skip_serializing_if = "is_zero")] + pub steps: u32, + #[serde(default, skip_serializing_if = "is_zero")] + pub failed: u32, + /// Its last sign of life (ms): the newest message or step of it. + #[serde(default, skip_serializing_if = "is_zero_i64")] + pub heartbeat: i64, + /// When it ended (ms; 0 while it goes on). + #[serde(default, skip_serializing_if = "is_zero_i64")] + pub finished: i64, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub artifacts: Vec, + #[serde(default)] + pub evidence: Level, + /// What the system saw, a line each. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub proof: Vec, + /// Why it is stuck, waits or failed. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub why: String, + /// How its last turn ended (a record keeps it once the chat is gone). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ended: Option, + /// Shown from its record: the chat no longer has it. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub kept: bool, +} + +/// A task's state as the system noted it (Bot::tasks). Appended, never changed. +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Default)] +pub struct Event { + /// When it was noted (ms). + pub noted: i64, + #[serde(flatten)] + pub task: Task, +} + +/// What runs and waits now, from the brain (nothing on a copy). +#[derive(Clone, Debug, Default)] +pub struct Live { + /// Bots with a turn running: the step it is on, in words (empty while it thinks). + pub running: HashMap, + /// Bots waiting for the person: for what, in words. + pub waiting: HashMap, + /// Bots whose goal is being checked (or is about to be). + pub checking: HashSet, +} + +/// The goal's checker's last word on a task, from its line in the chat. +#[derive(Clone, Debug, PartialEq)] +pub enum GoalEnd { + Met, + Impossible(String), +} + +/// What a task's state is worked out from. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Facts { + pub running: bool, + pub waiting: bool, + pub following: bool, + /// Its goal is on the bot and going. + pub goal_active: bool, + /// …and stopped to ask the person. + pub goal_paused: bool, + pub goal: Option, + pub ended: Option, + pub evidence: Level, + pub artifacts: usize, + /// A device of the owner's showed one of its files. + pub shown: bool, + /// The person opened one. + pub opened: bool, + /// The person put 👍 on its answer. + pub thumbs: bool, +} + +/// The task's state: the first that holds, in this order. A pure function, tested as a table. +pub fn status(f: &Facts) -> Status { + if f.waiting || f.goal_paused { + return Status::Waiting; + } + if f.running { + return Status::Running; + } + if f.following { + return Status::Following; + } + if f.goal_active { + return Status::Verifying; + } + if matches!(f.goal, Some(GoalEnd::Impossible(_))) { + return Status::Failed; + } + match f.ended { + Some(End::Error | End::Interrupted | End::NoReply) => return Status::Failed, + Some(End::Cancelled) => return Status::Stopped, + Some(End::Success) => {} + None => return Status::Unverified, + } + if f.opened || f.thumbs { + Status::Confirmed + } else if f.shown { + Status::Delivered + } else if f.artifacts > 0 { + Status::Produced + } else if f.goal == Some(GoalEnd::Met) { + Status::Verified + } else if f.evidence == Level::A { + Status::Answered + } else { + Status::Unverified + } +} + +/// Whether the facts back a state: what each one needs before a task may be in it (no +/// 「已交付」 without a device that showed it, no 「你已確認」 without the person's signal…). +pub fn backed(s: Status, f: &Facts) -> bool { + match s { + Status::Running => f.running, + Status::Waiting => f.waiting || f.goal_paused, + Status::Following => f.following, + Status::Verifying => f.goal_active, + Status::Produced => f.artifacts > 0 && f.ended == Some(End::Success), + Status::Delivered => f.shown && f.ended == Some(End::Success), + Status::Confirmed => (f.opened || f.thumbs) && f.ended == Some(End::Success), + Status::Answered => f.evidence == Level::A && f.ended == Some(End::Success), + Status::Verified => f.goal == Some(GoalEnd::Met), + Status::Failed => matches!(f.ended, Some(End::Error | End::Interrupted | End::NoReply)) || matches!(f.goal, Some(GoalEnd::Impossible(_))), + Status::Stopped => f.ended == Some(End::Cancelled), + Status::Unverified => !f.running && !f.waiting, + } +} + +/// Whether a task may go from one state to the next. It can always take up again (a goal's next +/// turn, a follow-up waking it); once over it only goes further along the way to the person +/// (產出 → 交付 → 確認) — a record never slides back (a chat cleared, a mark taken off). +pub fn legal(from: Status, to: Status) -> bool { + use Status::*; + if from == to || to.active() || from.active() { + return true; + } + match from { + Produced => matches!(to, Delivered | Confirmed), + Delivered | Answered | Verified | Unverified => to == Confirmed, + Confirmed | Failed | Stopped => false, + Running | Waiting | Following | Verifying => true, + } +} + +/// A task's own name: its bot and the time of its opening message. +pub fn task_id(bot: u64, m: &Message) -> String { + if m.at > 0 { + format!("{bot}-{}", m.at) + } else { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + m.text.hash(&mut h); + format!("{bot}-h{:x}", h.finish()) + } +} + +/// Whether a message starts a turn of its own (a steer joins the running one; AnyBot's own lines, +/// a summary, a 支線's card or report and the 「繼續」 card don't start one). +fn starts_turn(m: &Message) -> bool { + m.role == Role::User && !m.steer && m.branch == 0 && !m.note && !m.summary && !m.interrupted +} + +/// What a woken message goes on with: a goal's next turn, a follow-up or a watched command +/// reporting back, a file a device couldn't show. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +enum Key { + Goal(String), + Follow(u64), + Monitor(u64), + Attach(String), +} + +fn number(s: &str) -> Option { + s.chars().take_while(char::is_ascii_digit).collect::().parse().ok() +} + +/// The tag a deliver wake starts with (app/deliver_ui.rs WAKE_TAG; the test ties the two). +const DELIVER_WAKE: &str = "[交付]你傳的附件 "; + +fn continues(m: &Message) -> Option { + if !m.wake { + return None; + } + let t = m.text.as_str(); + if t.starts_with(crate::goal::TAG) && !m.goal.is_empty() { + return Some(Key::Goal(m.goal.clone())); + } + if let Some(r) = t.strip_prefix("[追進度 #") { + return number(r).map(Key::Follow); + } + if let Some(r) = t.strip_prefix("[監看 #") { + return number(r).map(Key::Monitor); + } + if let Some(r) = t.strip_prefix(DELIVER_WAKE) { + let id: String = r.chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_').collect(); + return (!id.is_empty()).then_some(Key::Attach(id)); + } + None +} + +fn source_of(m: &Message) -> Source { + let t = m.text.as_str(); + let tag = |a: &str, b: &str| t.starts_with(a) || t.starts_with(b); + if m.routine != 0 || tag("[例行任務]", "⏰ ") { + Source::Routine + } else if tag("[觸發]", "⚡ ") { + Source::Trigger + } else if tag("[訊息管道]", "💬 ") { + Source::Channel + } else if m.from_bot != 0 || tag("[來自 Bot]", "📨 ") { + Source::Bot + } else if t.starts_with("[追進度") { + Source::FollowUp + } else if t.starts_with("[監看") { + Source::Monitor + } else if t.starts_with("[交付]") { + Source::Delivery + } else if !m.goal.is_empty() || t.starts_with(crate::goal::TAG) { + Source::Goal + } else if m.untrusted_sender { + Source::Member + } else if t.starts_with("/plan") { + Source::Plan + } else { + Source::Owner + } +} + +/// The opening words in one line, without the tag a woken message carries. +fn opening(m: &Message) -> String { + let mut t = m.text.trim(); + if t.starts_with('[') { + if let Some((_, rest)) = t.split_once(']') { + t = rest.trim_start(); + } + } + for tag in ["⏰ ", "⚡ ", "💬 ", "📨 "] { + t = t.strip_prefix(tag).unwrap_or(t); + } + let line = t.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or(""); + let mut out: String = line.chars().take(TEXT_CHARS).collect(); + if line.chars().count() > TEXT_CHARS { + out.push('…'); + } + if out.is_empty() && !m.attachments.is_empty() { + out = m.attachments.iter().map(|a| a.name.as_str()).collect::>().join("、"); + } + out +} + +/// How a turn ended, from what it left in the chat (a turn ended before AnyBot kept its record). +fn ended_by_chat(turn: &[Message]) -> End { + match turn.iter().rev().find(|m| m.interrupted || (m.role == Role::Assistant && !m.note)) { + None => End::NoReply, + Some(m) if m.interrupted => End::Interrupted, + Some(m) if m.error => End::Error, + Some(m) if m.text.trim() == "(已停止)" => End::Cancelled, + Some(_) => End::Success, + } +} + +fn clip(s: &str, n: usize) -> String { + let line = s.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or(""); + let mut out: String = line.chars().take(n).collect(); + if line.chars().count() > n { + out.push('…'); + } + out +} + +/// The follow-up a step registered (its result: 「已登記追進度 #N…」). +fn registered_follow(m: &Message) -> Option { + (m.tool_name == crate::followup::TOOL).then(|| m.text.strip_prefix("已登記追進度 #").and_then(number)).flatten() +} + +/// The watched command a step started (shell's result: 「已開始監看(背景指令 #N)…」). +fn registered_monitor(m: &Message) -> Option { + m.text.strip_prefix("已開始監看(背景指令 #").and_then(number) +} + +/// One task, worked out from its turns (each a range of the chat). +struct Read<'a> { + bot: &'a Bot, + head: usize, + turns: Vec<(usize, usize)>, + /// This task's goal is the bot's goal now. + goal_here: bool, +} + +fn work_out(r: &Read, newest_turn: Option, live: &Live, records: &[Event], now: i64) -> Task { + let (bot, msgs) = (r.bot, &r.bot.messages[..]); + let m0 = &msgs[r.head]; + let id = task_id(bot.id, m0); + let (mut steps, mut failed, mut done_a, mut done_c) = (0u32, 0u32, 0u32, 0u32); + let mut sends: Vec = vec![]; + let mut computer: Option = None; + let mut last_step: Option<(&str, &str)> = None; + let mut heartbeat = m0.at; + let mut artifacts: Vec = vec![]; + let mut thumbs = false; + let mut goal_end: Option = None; + let mut follows: Vec = vec![]; + for &(s, e) in &r.turns { + let turn = &msgs[s..e]; + let t = crate::evidence::tally(turn); + steps += t.steps; + failed += t.failed; + sends.extend(t.sends); + for m in turn { + heartbeat = heartbeat.max(m.at); + match m.role { + Role::Assistant if m.note => { + if m.text.starts_with("目標達成") { + goal_end = Some(GoalEnd::Met); + } else if let Some(rest) = m.text.strip_prefix("目標做不到,已清除:") { + goal_end = Some(GoalEnd::Impossible(clip(rest.lines().nth(1).unwrap_or(rest), 120))); + } + } + Role::Assistant => { + thumbs |= m.reactions.iter().any(|x| x == CONFIRM_REACTION); + for c in &m.tool_calls { + last_step = Some((c.name.as_str(), c.args.as_str())); + if c.status == ToolStatus::Done { + match c.name.as_str() { + "ask_bot" => done_c += 1, + "react" | "show_card" => {} + _ => done_a += 1, + } + } + if let Some(n) = crate::tools::args_of(&c.args)["computer"].as_str().filter(|n| !n.trim().is_empty()) { + computer = Some(n.to_string()); + } + } + artifacts.extend(m.attachments.iter().map(Artifact::of)); + } + Role::Tool => follows.extend(registered_follow(m)), + Role::User => {} + } + } + } + let last = r.turns.last().copied().unwrap_or((r.head, r.head + 1)); + let newest = Some(last.0) == newest_turn; + let record = records.iter().rev().find(|e| e.task.id == id).map(|e| &e.task); + let mut f = Facts { running: newest && live.running.contains_key(&bot.id), waiting: newest && live.waiting.contains_key(&bot.id), ..Default::default() }; + let follow = bot.follow_ups.iter().find(|x| follows.contains(&x.id)); + f.following = follow.is_some(); + let goal = bot.goal.as_ref().filter(|_| r.goal_here); + f.goal_active = goal.is_some_and(|g| g.active()); + f.goal_paused = goal.is_some_and(|g| !g.active()); + f.goal = goal_end; + let turn_at = msgs[last.0].at; + let settled = bot.last_turn.as_ref().filter(|t| newest && t.settled_at_ms >= turn_at); + if !f.running && !f.waiting { + f.ended = Some(match settled { + Some(t) => match t.outcome { + TurnOutcome::Success => End::Success, + TurnOutcome::Cancelled => End::Cancelled, + TurnOutcome::Error if t.turn_id == "interrupted" => End::Interrupted, + TurnOutcome::Error => End::Error, + }, + None => match record.and_then(|t| t.ended) { + Some(e) => e, + None => ended_by_chat(&msgs[last.0..last.1]), + }, + }); + // Just sent, not yet started on: on its way, not unanswered. + if f.ended == Some(End::NoReply) && newest && now - turn_at < START_GRACE_MS { + f.ended = None; + f.running = true; + } + } + f.evidence = if done_a > 0 { + Level::A + } else if done_c > 0 { + Level::C + } else { + Level::Nothing + }; + f.artifacts = artifacts.len(); + f.shown = artifacts.iter().any(|a| a.delivery == Dlv::Shown); + f.opened = artifacts.iter().any(|a| a.delivery == Dlv::Opened); + f.thumbs = thumbs; + let status = status(&f); + debug_assert!(backed(status, &f), "{status:?} not backed by {f:?}"); + // What it does, and why it waits, stopped or failed. + let step = last_step.map(|(n, a)| crate::evidence::step_line(n, a)).unwrap_or_default(); + let plan = bot.plan.as_ref().filter(|p| p.since == m0.at && p.stage == crate::plan::Stage::Doing).and_then(|p| p.current().map(|s| format!("計畫第 {}/{} 步:{}", p.done() + 1, p.steps.len(), s.title))); + let mut why = String::new(); + let doing = match status { + Status::Running => plan.unwrap_or_else(|| live.running.get(&bot.id).filter(|s| !s.is_empty()).cloned().unwrap_or_else(|| if f.running && !live.running.contains_key(&bot.id) { "準備開始".into() } else { "思考中".into() })), + Status::Waiting => { + why = match (live.waiting.get(&bot.id).filter(|_| f.waiting), goal) { + (Some(w), _) => w.clone(), + (None, Some(g)) => format!("目標暫停:{},傳一句話就接著做", if g.paused.is_empty() { "等你回覆" } else { &g.paused }), + _ => "等你".into(), + }; + why.clone() + } + Status::Following => { + let x = follow.expect("following"); + why = format!("追進度 #{}「{}」:{}", x.id, x.what, clip(x.last.lines().last().unwrap_or("還沒檢查"), 80)); + format!("追進度 #{}「{}」", x.id, x.what) + } + Status::Verifying => { + if let Some(g) = goal.filter(|g| !g.reason.is_empty()) { + why = format!("上次檢查:{}", clip(&g.reason, 120)); + } + if live.checking.contains(&bot.id) { "另一個模型正在檢查目標達成沒".into() } else { "目標還沒達成,準備下一輪".into() } + } + _ => step, + }; + if why.is_empty() { + why = match status { + Status::Failed => match (&f.goal, f.ended) { + (Some(GoalEnd::Impossible(w)), _) => format!("目標做不到:{w}"), + (_, Some(End::Interrupted)) => "AnyBot 關掉時中斷了(按聊天裡的「繼續」接著做)".into(), + (_, Some(End::NoReply)) => "Bot 沒有開始回覆".into(), + _ => msgs[last.0..last.1].iter().rev().find(|m| m.error).map(|m| clip(&m.text, 120)).filter(|s| !s.is_empty()).unwrap_or_else(|| "出錯了".into()), + }, + Status::Stopped => "被停止了".into(), + Status::Produced => artifacts.iter().find(|a| a.delivery == Dlv::Failed).map(|a| format!("{}顯示失敗:{}", a.device, a.why)).unwrap_or_default(), + Status::Unverified if f.evidence == Level::C => "只有別的 Bot 的轉述,系統沒有驗證".into(), + Status::Unverified => "這輪沒有系統看得到的結果".into(), + _ => String::new(), + }; + } + let mut proof = vec![]; + if done_a > 0 { + proof.push(if failed > 0 { format!("系統看到 {done_a} 步做完、{failed} 步失敗或被拒絕") } else { format!("系統看到 {done_a} 步做完") }); + } else if failed > 0 { + proof.push(format!("{failed} 步失敗或被拒絕")); + } + proof.extend(sends.iter().take(2).map(|s| format!("送出:{}", clip(s, 80)))); + if done_c > 0 { + proof.push(format!("別的 Bot 回答了 {done_c} 次(轉述,系統沒有驗證)")); + } + if f.goal == Some(GoalEnd::Met) { + proof.push("目標由另一個模型檢查,判定達成".into()); + } + let computer = computer.unwrap_or_else(|| match bot.default_computer.as_str() { + crate::model::BOT_COMPUTER_NAME | "" => crate::model::own_computer_name(&bot.name), + n => n.to_string(), + }); + let finished = if status.active() { 0 } else { settled.map(|t| t.settled_at_ms).unwrap_or(heartbeat).max(heartbeat) }; + Task { + id, + bot: bot.id, + at: m0.at, + text: opening(m0), + source: source_of(m0), + status, + doing, + computer, + steps, + failed, + heartbeat, + finished, + artifacts, + evidence: f.evidence, + proof, + why, + ended: f.ended, + kept: false, + } +} + +/// The tasks a bot's chat holds (its newest RECENT), oldest first. +pub fn from_chat(bot: &Bot, live: &Live, now: i64) -> Vec { + let msgs = &bot.messages[..]; + let starts: Vec = (0..msgs.len()).filter(|&i| starts_turn(&msgs[i])).collect(); + let mut reads: Vec = vec![]; + let mut owner: HashMap = HashMap::new(); + for (k, &s) in starts.iter().enumerate() { + let e = starts.get(k + 1).copied().unwrap_or(msgs.len()); + let t = match continues(&msgs[s]).and_then(|key| owner.get(&key).copied()) { + Some(t) => t, + None => { + reads.push(Read { bot, head: s, turns: vec![], goal_here: false }); + reads.len() - 1 + } + }; + reads[t].turns.push((s, e)); + // What this turn set going: later wakes about it go on with this task. + if !msgs[s].goal.is_empty() { + owner.insert(Key::Goal(msgs[s].goal.clone()), t); + } + for m in &msgs[s..e] { + if let Some(n) = registered_follow(m) { + owner.insert(Key::Follow(n), t); + } + if let Some(n) = registered_monitor(m).filter(|_| m.role == Role::Tool) { + owner.insert(Key::Monitor(n), t); + } + if m.role == Role::Assistant { + for a in m.attachments.iter().filter(|a| !a.id.is_empty()) { + owner.insert(Key::Attach(a.id.clone()), t); + } + } + } + } + if let Some(g) = &bot.goal { + if let Some(&t) = owner.get(&Key::Goal(g.condition.clone())) { + reads[t].goal_here = true; + } + } + let newest = starts.last().copied(); + let from = reads.len().saturating_sub(RECENT); + reads[from..].iter().map(|r| work_out(r, newest, live, &bot.tasks, now)).collect() +} + +fn last_event<'a>(events: &'a [Event], id: &str) -> Option<&'a Event> { + events.iter().rev().find(|e| e.task.id == id) +} + +/// Whether a task may be in `t`'s state after its record `e`: a legal move, or it ran again +/// since (a message after the record: it went through 進行中, which isn't noted). +fn may_follow(e: &Event, t: &Task) -> bool { + legal(e.task.status, t.status) || t.heartbeat > e.noted +} + +/// A bot's tasks: from its chat, and from its record the ones the chat no longer has. A state the +/// record has gone past is kept (a record never slides back: see `legal`). +pub fn of_bot(bot: &Bot, live: &Live, now: i64) -> Vec { + let mut out = from_chat(bot, live, now); + for t in out.iter_mut() { + if let Some(e) = last_event(&bot.tasks, &t.id) { + if !may_follow(e, t) { + t.status = e.task.status; + t.why = e.task.why.clone(); + } + } + } + let have: HashSet = out.iter().map(|t| t.id.clone()).collect(); + let mut seen: HashSet<&str> = HashSet::new(); + for e in bot.tasks.iter().rev() { + if have.contains(&e.task.id) || !seen.insert(e.task.id.as_str()) { + continue; + } + let mut t = e.task.clone(); + t.bot = bot.id; + t.kept = true; + // Going when last noted, and the chat that would say how it went is gone. + if t.status.active() { + t.status = Status::Unverified; + t.why = "聊天裡已經沒有它,系統沒看到它後來怎樣".into(); + t.doing.clear(); + t.finished = t.finished.max(e.noted); + } + out.push(t); + } + out +} + +/// Every bot's tasks, the newest (last sign of life) first. +pub fn all(bots: &[Bot], live: &Live, now: i64) -> Vec { + newest(bots.iter().flat_map(|b| of_bot(b, live, now)).collect()) +} + +/// The newest SHOWN, by their last sign of life. +pub fn newest(mut v: Vec) -> Vec { + v.sort_by_key(|t| std::cmp::Reverse((t.heartbeat.max(t.at), t.at))); + v.truncate(SHOWN); + v +} + +/// Note on `bot` each of its tasks whose state changed since its last event (appended; past KEEP +/// the oldest go). A running task isn't noted: its end is. True when something was added. +pub fn note(bot: &mut Bot, tasks: &[Task], now: i64) -> bool { + let mut added = false; + for t in tasks.iter().filter(|t| t.bot == bot.id && !t.kept && t.at > 0 && t.status != Status::Running) { + let new = match last_event(&bot.tasks, &t.id) { + None => true, + Some(e) => (e.task.status != t.status && may_follow(e, t)) || (e.task.ended.is_none() && t.ended.is_some()) || e.task.artifacts != t.artifacts, + }; + if new { + let mut task = t.clone(); + task.proof.truncate(4); + bot.tasks.push(Event { noted: now, task }); + added = true; + } + } + if bot.tasks.len() > KEEP { + let cut = bot.tasks.len() - KEEP; + bot.tasks.drain(..cut); + } + added +} + +/// What needs a look: going on, or failed in the last day. +pub fn attention(tasks: &[Task], now: i64) -> usize { + tasks.iter().filter(|t| t.status.active() || (t.status == Status::Failed && now - t.finished.max(t.heartbeat) < 86_400_000)).count() +} + +/// A task as the phone takes it: the task, and its words. +pub fn json(t: &Task) -> Value { + let mut v = serde_json::to_value(t).unwrap_or(Value::Null); + v["label"] = json!(t.status.label()); + v["from"] = json!(t.source.label()); + v["level"] = json!(t.evidence.label()); + v +} + +/// The tool a bot reads the list with: read-only, the system's own states. +pub fn spec() -> Value { + json!({"name": TOOL, + "description": "List the tasks handed to you (or, with all=true, to every bot): each one's state as AnyBot itself works it out from the chat's steps, the turn's end, the follow-ups, the goal checks and whether a device showed the files — not from memory. States: 進行中, 等你 (a request or question waits for the person), 追進度中, 驗收中 (a goal being checked), 已產出 (a file there, no device showed it yet), 已交付 (a device showed it), 你已確認 (the person opened it or put 👍), 已回覆, 已驗收, 失敗, 已停止, 結束但未驗證. Use it when the person asks what is running, whether something is done, or where a file is: answer from these states and their evidence, and never call a task done, delivered or seen when its state doesn't say so.", + "parameters": {"type": "object", "properties": { + "all": {"type": "boolean", "description": "Every bot's tasks, not only yours (only in the owner's own conversations)."}, + "limit": {"type": "integer", "description": "How many, newest first (default 10, at most 30)."}}}}) +} + +fn when(ms: i64, tz: &str) -> String { + use chrono::TimeZone; + crate::routines::tz_of(tz).timestamp_millis_opt(ms).single().map(|t| t.format("%m/%d %H:%M").to_string()).unwrap_or_default() +} + +/// The list in words, for a bot (`name`: each bot's name). +pub fn describe(tasks: &[Task], name: &dyn Fn(u64) -> String, tz: &str) -> String { + if tasks.is_empty() { + return "目前沒有任務紀錄。".into(); + } + let mut out = vec!["任務(AnyBot 從聊天、步驟和交付回報算出的狀態,不是記憶;最新的在上面):".to_string()]; + for (i, t) in tasks.iter().enumerate() { + let steps = if t.steps > 0 { format!(" · {} 步({} 步失敗)", t.steps, t.failed) } else { String::new() }; + let end = if t.finished > 0 { format!(" · 結束 {}", when(t.finished, tz)) } else { String::new() }; + out.push(format!( + "{}. 〔{}〕{}:「{}」— {}{}開的 · 在「{}」{steps} · 開始 {} · 最後動靜 {}{end}{}", + i + 1, + t.status.label(), + name(t.bot), + t.text, + t.source.label(), + if t.source.label().ends_with(|c: char| c.is_ascii_alphabetic()) { " " } else { "" }, + t.computer, + when(t.at, tz), + when(t.heartbeat.max(t.at), tz), + if t.kept { "(聊天裡已經沒有,照紀錄)" } else { "" } + )); + if !t.doing.is_empty() { + out.push(format!(" {}:{}", if t.status.active() { "現在" } else { "最後一步" }, t.doing)); + } + if !t.why.is_empty() && t.why != t.doing { + out.push(format!(" 原因:{}", t.why)); + } + out.push(format!(" 證據 {}{}", t.evidence.label(), if t.proof.is_empty() { String::new() } else { format!(":{}", t.proof.join(";")) })); + for a in &t.artifacts { + out.push(format!(" 產物 {}", a.line())); + } + } + out.join("\n") +} + +/// Who a task's opening words say sent it, as far as telling outsiders apart goes: a teammate's +/// 「【名字】」, a channel's 「Slack「…」的 amy」. +fn sender(source: Source, text: &str) -> String { + match source { + Source::Member => text.strip_prefix('【').and_then(|r| r.split_once('】')).map(|(n, _)| n.to_string()).unwrap_or_default(), + Source::Channel => text.split_once(':').map(|(h, _)| h.to_string()).unwrap_or_default(), + _ => String::new(), + } +} + +/// `list_tasks` for bot `asker`: its own tasks, or every bot's with `all` — only in a turn the +/// owner started. A turn someone else started (a teammate, a channel) lists only the tasks that +/// same sender handed this bot: the owner's words are not theirs to read. +pub fn answer(tasks: &[Task], bots: &[Bot], asker: u64, args: &Value, tz: &str) -> String { + let Some(b) = bots.iter().find(|b| b.id == asker) else { return "找不到這個 Bot".into() }; + let start = b.messages.iter().rev().find(|m| starts_turn(m)); + let outsider = start.is_some_and(|m| m.untrusted_sender); + let limit = args["limit"].as_u64().unwrap_or(10).clamp(1, 30) as usize; + let every = args["all"].as_bool().unwrap_or(false) && !outsider; + let mine: Vec = match start.filter(|_| outsider) { + Some(m) => { + let (src, who) = (source_of(m), sender(source_of(m), &opening(m))); + tasks.iter().filter(|t| t.bot == asker && t.source == src && !who.is_empty() && sender(t.source, &t.text) == who).take(limit).cloned().collect() + } + None => tasks.iter().filter(|t| every || t.bot == asker).take(limit).cloned().collect(), + }; + let name = |id: u64| bots.iter().find(|b| b.id == id).map(|b| b.name.clone()).unwrap_or_else(|| "已刪除的 Bot".into()); + describe(&mine, &name, tz) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::attach::{Attachment, SeenKind}; + use crate::model::{Message, ToolCall, TurnSettlement}; + + fn f() -> Facts { + Facts { ended: Some(End::Success), ..Default::default() } + } + + /// The states, as a table: the facts → the state, and that state is backed by them. + #[test] + fn the_state_follows_the_facts() { + let a = Level::A; + let rows: Vec<(&str, Facts, Status)> = vec![ + ("a turn runs", Facts { running: true, ..Default::default() }, Status::Running), + ("a card waits", Facts { running: true, waiting: true, ..Default::default() }, Status::Waiting), + ("a goal stopped to ask", Facts { goal_paused: true, ended: Some(End::Success), ..Default::default() }, Status::Waiting), + ("a follow-up checks", Facts { following: true, ..f() }, Status::Following), + ("a goal is checked", Facts { goal_active: true, ..f() }, Status::Verifying), + ("running beats following", Facts { running: true, following: true, ..Default::default() }, Status::Running), + ("a file, nobody showed it", Facts { artifacts: 1, evidence: a, ..f() }, Status::Produced), + ("a device showed it", Facts { artifacts: 1, shown: true, evidence: a, ..f() }, Status::Delivered), + ("the person opened it", Facts { artifacts: 1, shown: true, opened: true, evidence: a, ..f() }, Status::Confirmed), + ("👍 on the answer", Facts { thumbs: true, ..f() }, Status::Confirmed), + ("steps went through", Facts { evidence: a, ..f() }, Status::Answered), + ("only another bot's word", Facts { evidence: Level::C, ..f() }, Status::Unverified), + ("only words", f(), Status::Unverified), + ("the goal holds", Facts { goal: Some(GoalEnd::Met), ..f() }, Status::Verified), + ("the goal can't be done", Facts { goal: Some(GoalEnd::Impossible("x".into())), evidence: a, ..f() }, Status::Failed), + ("the turn errored", Facts { ended: Some(End::Error), artifacts: 1, ..Default::default() }, Status::Failed), + ("AnyBot stopped meanwhile", Facts { ended: Some(End::Interrupted), ..Default::default() }, Status::Failed), + ("nothing started", Facts { ended: Some(End::NoReply), ..Default::default() }, Status::Failed), + ("the person stopped it", Facts { ended: Some(End::Cancelled), evidence: a, ..Default::default() }, Status::Stopped), + ("no turn known", Facts::default(), Status::Unverified), + ]; + for (what, facts, want) in rows { + let got = status(&facts); + assert_eq!(got, want, "{what}"); + assert!(backed(got, &facts), "{what}: {got:?} isn't backed by its facts"); + } + } + + /// What each state needs before a task can be in it: never 「已交付」 without a device that + /// showed it, never 「你已確認」 without the person's signal, never 「已回覆」 on words alone. + #[test] + fn a_state_needs_its_evidence() { + let a = Level::A; + assert!(!backed(Status::Delivered, &Facts { artifacts: 1, evidence: a, ..f() })); + assert!(!backed(Status::Confirmed, &Facts { artifacts: 1, shown: true, ..f() })); + assert!(!backed(Status::Produced, &Facts { evidence: a, ..f() })); + assert!(!backed(Status::Answered, &Facts { evidence: Level::C, ..f() })); + assert!(!backed(Status::Verified, &Facts { evidence: a, ..f() })); + assert!(!backed(Status::Answered, &Facts { evidence: a, ended: Some(End::Error), ..Default::default() })); + assert!(!backed(Status::Running, &f())); + assert!(!backed(Status::Failed, &f())); + } + + #[test] + fn a_record_only_goes_forward() { + use Status::*; + let rows = [ + (Produced, Delivered, true), + (Delivered, Confirmed, true), + (Answered, Confirmed, true), + (Unverified, Confirmed, true), + (Running, Answered, true), + (Verifying, Verified, true), + (Failed, Running, true), + (Confirmed, Running, true), + (Delivered, Produced, false), + (Confirmed, Delivered, false), + (Confirmed, Answered, false), + (Answered, Produced, false), + (Failed, Answered, false), + (Stopped, Confirmed, false), + (Unverified, Delivered, false), + ]; + for (from, to, ok) in rows { + assert_eq!(legal(from, to), ok, "{from:?} → {to:?}"); + } + } + + fn bot(msgs: Vec) -> Bot { + let mut b: Bot = serde_json::from_value(json!({"id": 1, "name": "小幫手", "shape": "", "color": "", "provider": "Xai", "model": "m", "instructions": "", "messages": []})).unwrap(); + b.messages = msgs.into(); + b + } + + fn user(text: &str, at: i64) -> Message { + Message { at, ..Message::user(text) } + } + + fn said(text: &str, at: i64, calls: &[(&str, &str, ToolStatus)]) -> Message { + let tool_calls = calls.iter().enumerate().map(|(i, (n, a, s))| ToolCall { id: format!("c{at}{i}"), name: n.to_string(), args: a.to_string(), status: *s }).collect(); + Message { at, tool_calls, ..Message::assistant(text, "") } + } + + fn result(id: &str, name: &str, text: &str, at: i64) -> Message { + Message { at, ..Message::tool_result(id, name, text) } + } + + fn settled(b: &mut Bot, outcome: TurnOutcome, at: i64) { + b.last_turn = Some(TurnSettlement { turn_id: "t".into(), outcome, settled_at_ms: at }); + } + + #[test] + fn each_message_of_the_person_is_a_task_and_steers_join_it() { + let mut b = bot(vec![ + user("查一下天氣", 1_000), + said("", 1_100, &[("web_fetch", r#"{"url":"https://example.com"}"#, ToolStatus::Done)]), + result("c11000", "web_fetch", "晴", 1_200), + Message { steer: true, ..user("順便看明天", 1_250) }, + said("晴天", 1_300, &[]), + user("你好", 2_000), + said("你好!", 2_100, &[]), + ]); + settled(&mut b, TurnOutcome::Success, 2_200); + let t = from_chat(&b, &Live::default(), 10_000); + assert_eq!(t.len(), 2); + assert_eq!((t[0].id.as_str(), t[0].text.as_str(), t[0].status, t[0].evidence, t[0].steps), ("1-1000", "查一下天氣", Status::Answered, Level::A, 1)); + assert_eq!(t[0].heartbeat, 1_300); + assert_eq!(t[0].computer, "小幫手 的電腦"); + // Small talk: over, and nothing backs it. + assert_eq!((t[1].status, t[1].evidence), (Status::Unverified, Level::Nothing)); + assert_eq!(t[1].finished, 2_200); + } + + #[test] + fn running_waiting_and_failed_come_from_the_live_state_and_the_turns_end() { + let mut b = bot(vec![user("整理報表", 1_000), said("", 1_100, &[("shell", r#"{"command":"ls","computer":"工作室"}"#, ToolStatus::Running)])]); + let mut live = Live::default(); + live.running.insert(1, "執行指令 ls".into()); + let t = &from_chat(&b, &live, 5_000)[0]; + assert_eq!((t.status, t.doing.as_str(), t.computer.as_str()), (Status::Running, "執行指令 ls", "工作室")); + live.waiting.insert(1, "等你允許:執行指令".into()); + let t = &from_chat(&b, &live, 5_000)[0]; + assert_eq!((t.status, t.why.as_str()), (Status::Waiting, "等你允許:執行指令")); + // The model service failed: 失敗, with its words as the reason. + b.messages.push(Message { error: true, at: 1_200, ..Message::assistant("模型服務沒有回應", "") }); + settled(&mut b, TurnOutcome::Error, 1_300); + let t = &from_chat(&b, &Live::default(), 5_000)[0]; + assert_eq!((t.status, t.why.as_str(), t.ended), (Status::Failed, "模型服務沒有回應", Some(End::Error))); + // Stopped. + settled(&mut b, TurnOutcome::Cancelled, 1_300); + assert_eq!(from_chat(&b, &Live::default(), 5_000)[0].status, Status::Stopped); + } + + #[test] + fn a_message_nobody_answered_fails_after_a_moment() { + let b = bot(vec![user("在嗎", 1_000)]); + assert_eq!(from_chat(&b, &Live::default(), 2_000)[0].status, Status::Running); + let t = &from_chat(&b, &Live::default(), 1_000 + START_GRACE_MS + 1)[0]; + assert_eq!((t.status, t.why.as_str()), (Status::Failed, "Bot 沒有開始回覆")); + } + + fn file(seen: &[(&str, SeenKind, &str)]) -> Attachment { + let mut a = Attachment { name: "a.png".into(), id: "att1".into(), image: true, ..Default::default() }; + for (d, k, why) in seen { + a.note_seen(d, *k, why, 5); + } + a + } + + #[test] + fn a_file_goes_produced_delivered_confirmed_by_what_the_devices_said() { + let turn = |a: Attachment| { + let mut b = bot(vec![user("畫一張圖", 1_000), Message { attachments: vec![a], ..said("好了", 1_100, &[("send_file", "{}", ToolStatus::Done)]) }]); + settled(&mut b, TurnOutcome::Success, 1_200); + from_chat(&b, &Live::default(), 9_000).remove(0) + }; + let t = turn(file(&[])); + assert_eq!((t.status, t.artifacts[0].delivery), (Status::Produced, Dlv::InChat)); + let t = turn(file(&[("iPhone", SeenKind::Failed, "這台裝置讀不出這個檔案")])); + assert_eq!((t.status, t.why.as_str()), (Status::Produced, "iPhone顯示失敗:這台裝置讀不出這個檔案")); + let t = turn(file(&[("iPhone", SeenKind::Shown, "")])); + assert_eq!((t.status, t.artifacts[0].line()), (Status::Delivered, "a.png:已在iPhone顯示".to_string())); + let t = turn(file(&[("iPhone", SeenKind::Shown, ""), ("iPhone", SeenKind::Opened, "")])); + assert_eq!(t.status, Status::Confirmed); + // A teammate's device says nothing about whether the owner has it. + let mut a = Attachment { name: "a.png".into(), id: "att1".into(), ..Default::default() }; + a.note_seen_by("小明的 iPhone", SeenKind::Opened, "", 5, true); + assert_eq!(turn(a).status, Status::Produced); + } + + #[test] + fn a_thumbs_up_on_the_answer_confirms() { + let mut b = bot(vec![user("記一下", 1_000), Message { reactions: vec!["👍".into()], ..said("記好了", 1_100, &[]) }]); + settled(&mut b, TurnOutcome::Success, 1_200); + assert_eq!(from_chat(&b, &Live::default(), 9_000)[0].status, Status::Confirmed); + // The bot's own reaction sits on the person's message: not the person's signal. + let mut b = bot(vec![Message { reactions: vec!["👍".into()], ..user("記一下", 1_000) }, said("記好了", 1_100, &[])]); + settled(&mut b, TurnOutcome::Success, 1_200); + assert_eq!(from_chat(&b, &Live::default(), 9_000)[0].status, Status::Unverified); + } + + #[test] + fn another_bots_answer_is_hearsay() { + let mut b = bot(vec![user("問小明那份報告好了沒", 1_000), said("", 1_100, &[("ask_bot", r#"{"bot":"小明","question":"好了沒"}"#, ToolStatus::Done)]), said("小明說好了", 1_200, &[])]); + settled(&mut b, TurnOutcome::Success, 1_300); + let t = &from_chat(&b, &Live::default(), 9_000)[0]; + assert_eq!((t.status, t.evidence), (Status::Unverified, Level::C)); + assert!(t.proof.iter().any(|p| p.contains("轉述")), "{:?}", t.proof); + } + + #[test] + fn a_goal_is_one_task_over_its_turns() { + let cond = "建立 hello.txt"; + let mut b = bot(vec![ + Message { goal: cond.into(), ..user("/goal 建立 hello.txt", 1_000) }, + said("", 1_100, &[("edit_file", r#"{"path":"x"}"#, ToolStatus::Failed)]), + Message { wake: true, goal: cond.into(), ..user("[目標]還沒達成:沒有檔案", 2_000) }, + said("", 2_100, &[("edit_file", r#"{"path":"hello.txt"}"#, ToolStatus::Done)]), + ]); + b.goal = Some(crate::goal::Goal::new(cond, 1_000)); + settled(&mut b, TurnOutcome::Success, 2_200); + let t = from_chat(&b, &Live::default(), 9_000); + assert_eq!(t.len(), 1, "{t:?}"); + assert_eq!((t[0].source, t[0].status, t[0].steps, t[0].failed), (Source::Goal, Status::Verifying, 2, 1)); + let mut live = Live::default(); + live.checking.insert(1); + assert_eq!(from_chat(&b, &live, 9_000)[0].doing, "另一個模型正在檢查目標達成沒"); + // Stopped to ask. + b.goal.as_mut().unwrap().paused = "已經做了 20 輪".into(); + let t = &from_chat(&b, &Live::default(), 9_000)[0]; + assert_eq!((t.status, t.why.as_str()), (Status::Waiting, "目標暫停:已經做了 20 輪,傳一句話就接著做")); + // Met: the goal is gone, its line stays. + b.goal = None; + b.messages.push(Message { note: true, at: 2_300, ..Message::assistant("目標達成:建立 hello.txt\n有了(2 輪 · 1 分)", "") }); + let t = &from_chat(&b, &Live::default(), 9_000)[0]; + assert_eq!(t.status, Status::Verified); + // Impossible. + b.messages.pop(); + b.messages.push(Message { note: true, at: 2_300, ..Message::assistant("目標做不到,已清除:建立 hello.txt\n沒有權限(2 輪 · 1 分)", "") }); + let t = &from_chat(&b, &Live::default(), 9_000)[0]; + assert_eq!((t.status, t.why.as_str()), (Status::Failed, "目標做不到:沒有權限(2 輪 · 1 分)")); + } + + #[test] + fn a_follow_up_keeps_its_task_and_its_wake_goes_on_with_it() { + let reg = crate::followup::FollowUp { id: 3, what: "下載模型".into(), last: "5G".into(), ..Default::default() }; + let mut b = bot(vec![ + user("下載模型", 1_000), + said("", 1_100, &[(crate::followup::TOOL, "{}", ToolStatus::Done)]), + result("c11000", crate::followup::TOOL, &crate::followup::started_text(®, "Bot 的電腦"), 1_150), + said("我在追了", 1_200, &[]), + user("你好", 1_500), + said("嗨", 1_600, &[]), + ]); + b.follow_ups = vec![reg.clone()]; + settled(&mut b, TurnOutcome::Success, 1_700); + let t = from_chat(&b, &Live::default(), 9_000); + assert_eq!((t[0].status, t[0].doing.as_str()), (Status::Following, "追進度 #3「下載模型」")); + assert!(t[0].why.ends_with("5G"), "{}", t[0].why); + // Done: AnyBot wakes the bot, and that turn is the same task. + b.follow_ups.clear(); + let wake = crate::followup::wake_text(®, &crate::followup::Verdict::Done, 3_000).unwrap(); + b.messages.push(Message { wake: true, ..user(&wake, 3_000) }); + b.messages.push(said("", 3_100, &[("shell", r#"{"command":"ls"}"#, ToolStatus::Done)])); + b.messages.push(said("下載好了", 3_200, &[])); + settled(&mut b, TurnOutcome::Success, 3_300); + let t = from_chat(&b, &Live::default(), 9_000); + assert_eq!(t.len(), 2, "{t:?}"); + assert_eq!((t[0].text.as_str(), t[0].status, t[0].steps, t[0].heartbeat), ("下載模型", Status::Answered, 2, 3_200)); + } + + #[test] + fn who_handed_it_over() { + let src = |m: Message| source_of(&m); + assert_eq!(src(user("幫我", 1)), Source::Owner); + assert_eq!(src(Message { untrusted_sender: true, ..user("【小明】我也要", 1) }), Source::Member); + assert_eq!(src(Message { wake: true, routine: 4, ..user("[例行任務]早報", 1) }), Source::Routine); + assert_eq!(src(Message { wake: true, untrusted_sender: true, ..user("[訊息管道]Slack「x」的 amy:hi", 1) }), Source::Channel); + assert_eq!(src(Message { from_bot: 2, ..user("[來自 Bot]幫我查", 1) }), Source::Bot); + assert_eq!(src(user("/plan 搬家", 1)), Source::Plan); + assert_eq!(opening(&Message { wake: true, routine: 4, ..user("[例行任務]整理今天的新聞\n細節", 1) }), "整理今天的新聞"); + assert_eq!(sender(Source::Member, &opening(&user("【小明】我也要", 1))), "小明"); + } + + #[test] + fn a_cleared_chat_keeps_its_recent_tasks_from_the_record() { + let mut b = bot(vec![user("查一下天氣", 1_000), said("", 1_100, &[("web_fetch", "{}", ToolStatus::Done)]), said("晴", 1_200, &[])]); + settled(&mut b, TurnOutcome::Success, 1_300); + let live = Live::default(); + let tasks = of_bot(&b, &live, 9_000); + assert!(note(&mut b, &tasks, 9_000)); + // Nothing changed: nothing more is noted. + let again = of_bot(&b, &live, 9_100); + assert!(!note(&mut b, &again, 9_100)); + assert_eq!(b.tasks.len(), 1); + // The chat is cleared: the task is still there, as its record says. + b.messages.clear(); + let t = of_bot(&b, &live, 9_200); + assert_eq!(t.len(), 1); + assert_eq!((t[0].status, t[0].kept, t[0].text.as_str()), (Status::Answered, true, "查一下天氣")); + // The record keeps at most KEEP events, the newest. + for i in 0..(KEEP as i64 + 5) { + b.tasks.push(Event { noted: i, task: Task { id: format!("1-{i}"), ..Default::default() } }); + } + note(&mut b, &[], 9_300); + assert_eq!(b.tasks.len(), KEEP); + assert_eq!(b.tasks.last().unwrap().task.id, format!("1-{}", KEEP as i64 + 4)); + } + + #[test] + fn a_record_never_slides_back() { + let mut b = bot(vec![user("記一下", 1_000), Message { reactions: vec!["👍".into()], ..said("記好了", 1_100, &[]) }]); + settled(&mut b, TurnOutcome::Success, 1_200); + let live = Live::default(); + let t = of_bot(&b, &live, 9_000); + note(&mut b, &t, 9_000); + // The 👍 taken off: what the person said once stays said. + b.messages[1].reactions.clear(); + let t = of_bot(&b, &live, 9_100); + assert_eq!(t[0].status, Status::Confirmed); + assert!(!note(&mut b, &t, 9_100)); + } + + /// AnyBot stopped mid-turn (失敗, noted), then 「繼續」 finished it: running again in between + /// isn't noted, and the record doesn't hold it back at 失敗. + #[test] + fn a_task_that_ran_again_moves_on_from_its_record() { + let mut b = bot(vec![user("整理報表", 1_000), said("", 1_100, &[("shell", "{}", ToolStatus::Done)]), Message { interrupted: true, at: 1_200, ..Message::assistant("中斷了", "") }]); + b.last_turn = Some(TurnSettlement { turn_id: "interrupted".into(), outcome: TurnOutcome::Error, settled_at_ms: 1_300 }); + let live = Live::default(); + let t = of_bot(&b, &live, 2_000); + assert_eq!(t[0].status, Status::Failed); + note(&mut b, &t, 2_000); + b.messages.push(said("整理好了", 3_000, &[])); + settled(&mut b, TurnOutcome::Success, 3_100); + let t = of_bot(&b, &live, 4_000); + assert_eq!(t[0].status, Status::Answered); + assert!(note(&mut b, &t, 4_000)); + assert_eq!(b.tasks.last().unwrap().task.status, Status::Answered); + } + + #[test] + fn records_from_before_read_in_and_old_bots_have_none() { + // A bot saved before tasks were kept. + let b = bot(vec![]); + assert!(b.tasks.is_empty()); + let v = serde_json::to_value(&b).unwrap(); + assert!(v.get("tasks").is_none(), "an empty record isn't written"); + // An event as written, read back. + let e: Event = serde_json::from_value(json!({"noted": 5, "id": "1-1000", "bot": 1, "at": 1000, "text": "查", "status": "delivered", "evidence": "a", "artifacts": [{"name": "a.png", "delivery": "shown", "device": "iPhone"}]})).unwrap(); + assert_eq!((e.task.status, e.task.evidence, e.task.artifacts[0].delivery), (Status::Delivered, Level::A, Dlv::Shown)); + // Small on disk: what is empty isn't written. + let s = serde_json::to_string(&Event { noted: 1, task: Task { id: "1-1".into(), bot: 1, at: 1, text: "查".into(), ..Default::default() } }).unwrap(); + assert!(s.len() < 110, "{s}"); + } + + #[test] + fn the_bot_reads_states_and_evidence_in_words() { + let mut b = bot(vec![user("畫一張圖", 1_000), Message { attachments: vec![file(&[("iPhone", SeenKind::Shown, "")])], ..said("好了", 1_100, &[("send_file", "{}", ToolStatus::Done)]) }]); + settled(&mut b, TurnOutcome::Success, 1_200); + let tasks = all(std::slice::from_ref(&b), &Live::default(), 9_000); + let text = describe(&tasks, &|_| "小幫手".into(), "Asia/Taipei"); + assert!(text.contains("〔已交付〕小幫手:「畫一張圖」— 你開的"), "{text}"); + assert!(text.contains("證據 A 系統看到:系統看到 1 步做完"), "{text}"); + assert!(text.contains("產物 a.png:已在iPhone顯示"), "{text}"); + assert_eq!(attention(&tasks, 9_000), 0); + let v = json(&tasks[0]); + assert_eq!((v["label"].as_str(), v["status"].as_str(), v["from"].as_str()), (Some("已交付"), Some("delivered"), Some("你"))); + } + + #[test] + fn an_outsiders_turn_lists_only_what_that_sender_handed_over() { + let mut b = bot(vec![ + user("我的私事", 1_000), + said("好", 1_100, &[("web_fetch", "{}", ToolStatus::Done)]), + Message { untrusted_sender: true, ..user("【小明】幫我查", 2_000) }, + said("查好了", 2_100, &[]), + Message { untrusted_sender: true, ..user("【阿華】那件事好了沒", 3_000) }, + ]); + settled(&mut b, TurnOutcome::Success, 2_200); + let mut other = bot(vec![user("另一個 Bot 的事", 500), said("好", 600, &[])]); + other.id = 2; + let bots = vec![b, other]; + let tasks = all(&bots, &Live::default(), 3_100); + // 阿華's turn: none of the owner's, none of 小明's — and no other bot's, even asked. + let text = answer(&tasks, &bots, 1, &json!({"all": true}), "Asia/Taipei"); + assert!(!text.contains("我的私事") && !text.contains("幫我查") && !text.contains("另一個 Bot"), "{text}"); + assert!(text.contains("那件事好了沒"), "{text}"); + // The owner's turn: this bot's, or every bot's with all. + let mut bots = bots; + bots[0].messages.push(user("現在在跑什麼", 4_000)); + let tasks = all(&bots, &Live::default(), 4_100); + let mine = answer(&tasks, &bots, 1, &json!({}), "Asia/Taipei"); + assert!(mine.contains("我的私事") && !mine.contains("另一個 Bot"), "{mine}"); + assert!(answer(&tasks, &bots, 1, &json!({"all": true}), "Asia/Taipei").contains("另一個 Bot 的事")); + } + + #[test] + fn the_wakes_it_follows_are_the_ones_anybot_writes() { + let f = crate::followup::FollowUp { id: 12, what: "x".into(), ..Default::default() }; + let w = crate::followup::wake_text(&f, &crate::followup::Verdict::Stuck, 0).unwrap(); + assert_eq!(continues(&Message { wake: true, ..user(&w, 1) }), Some(Key::Follow(12))); + assert_eq!(registered_follow(&result("c", crate::followup::TOOL, &crate::followup::started_text(&f, "x"), 1)), Some(12)); + assert_eq!(continues(&Message { wake: true, goal: "c".into(), ..user(&format!("{}還沒達成:x", crate::goal::TAG), 1) }), Some(Key::Goal("c".into()))); + } +}