wip: 任務系統(可觀測)——tasks.rs 狀態機+證據分級、list_tasks、手機/電腦任務頁

This commit is contained in:
王性驊 2026-11-20 16:16:43 +08:00
parent 2d90e5decd
commit ca7f801e10
21 changed files with 1881 additions and 13 deletions

View File

@ -138,6 +138,24 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。
- 點一筆:打開那個 Bot,聊天捲到那則訊息,並用黃色亮一下(約 1.8 秒淡掉)。在過去的對話裡的,會先把那段對話換回來(目前的對話收進「過去的對話」最上面);那個 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 選單(右鍵選單和聊天頂部的「⋯」共用) ## 3. Bot 選單(右鍵選單和聊天頂部的「⋯」共用)
@ -1942,6 +1960,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
- 可讀長度(預設 128,000) - 可讀長度(預設 128,000)
- 例行任務 - 例行任務
- 上一回合的結果 - 上一回合的結果
- 任務紀錄(每次狀態改變一筆,留最近 40 筆,第 2 節「任務」)
- 預設電腦(預設「Bot 的電腦」) - 預設電腦(預設「Bot 的電腦」)
- **每則訊息記錄**: - **每則訊息記錄**:
- 誰說的、文字、思考內容 - 誰說的、文字、思考內容

View File

@ -89,6 +89,7 @@ Bot 讀得到的是開頭、子功能、使用者怎麼到、Bot 那一行和沒
- [routines](routines.md):排程與事件觸發、執行紀錄、完成條件、自動暫停。 - [routines](routines.md):排程與事件觸發、執行紀錄、完成條件、自動暫停。
- [goal](goal.md):/goal:沒達成就繼續做、評審只看證據。 - [goal](goal.md):/goal:沒達成就繼續做、評審只看證據。
- [plan](plan.md):/plan:先查清楚、交計畫給你核准,核准後才動手、照步驟打勾。 - [plan](plan.md):/plan:先查清楚、交計畫給你核准,核准後才動手、照步驟打勾。
- [tasks](tasks.md):任務:每件交代的事一張卡,狀態由系統算(等你、追進度、驗收、已交付、你已確認…)、證據等級、清掉聊天也留著。
### 在電腦上做事 ### 在電腦上做事
- [computers](computers.md):大腦與手腳、這台電腦、SSH、帳號裡的其他電腦、傳到別的裝置。 - [computers](computers.md):大腦與手腳、這台電腦、SSH、帳號裡的其他電腦、傳到別的裝置。

51
docs/feature-map/tasks.md Normal file
View File

@ -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'` 對不到)。
- (驗證)從卡片進聊天,返回回到任務頁(不是首頁):步驟照這個順序寫。

View File

@ -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)} .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{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} .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)} button.item:active,.item.tap:active{background:var(--hover)}
.item .ic{color:var(--text2)} .item .ic{color:var(--text2)}
.item .mid{flex:1;min-width:0} .item .mid{flex:1;min-width:0}
@ -897,7 +911,7 @@ try { matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () =
const S = { voice: {}, const S = { voice: {},
relay: localStorage.getItem("anybot.relay") === "1", token: localStorage.getItem("anybot.token") || "", host: localStorage.getItem("anybot.host") || "", 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: "", prevShown: 0, prevFirst: "", answer: null, sc: "",
open: 0, msgs: [], pending: [], quote: null, unfold: {}, openSteps: {}, detail: {}, detailNew: {}, audit: {}, settings: null, polling: false, entered: false, open: 0, msgs: [], pending: [], quote: null, unfold: {}, openSteps: {}, detail: {}, detailNew: {}, audit: {}, settings: null, polling: false, entered: false,
chatSig: "", file: null, chatSig: "", file: null,
@ -1098,7 +1112,7 @@ document.querySelectorAll("[data-back]").forEach((b) => { b.innerHTML = ic("chev
function draw(v, arg) { function draw(v, arg) {
show(v); show(v);
if (v === "home") renderHome(); 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 === "details") renderDetails(arg.bot, arg.tab);
else if (v === "botset") renderBotset(arg.bot); else if (v === "botset") renderBotset(arg.bot);
else if (v === "list") renderList(arg); else if (v === "list") renderList(arg);
@ -1369,7 +1383,7 @@ function mergeState(prev, v) {
} }
function apply(v) { function apply(v) {
S.bots = v.bots || []; S.approvals = v.approvals || []; S.hostName = v.host || ""; S.mac = !!v.mac; 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(); S.voice = v.voice || {}; micShown(); appBadge();
// The computer's 外觀 (an older brain sends neither: the built-in look stays). // The computer's 外觀 (an older brain sends neither: the built-in look stays).
if (v.palettes) applyPalette(v.palettes); if (v.palettes) applyPalette(v.palettes);
@ -1407,6 +1421,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 === "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 === "botset" && !isNew(t.arg.bot)) renderBotset(t.arg.bot);
else if (t.v === "list" && t.arg.kind === "tasks") listTasks($("list"));
settingsChanged(); settingsChanged();
} }
@ -1437,7 +1452,9 @@ function renderHome() {
const main = S.bots.find((b) => b.primary) || S.bots[0]; const main = S.bots.find((b) => b.primary) || S.bots[0];
const comps = (main && main.computers) || []; const comps = (main && main.computers) || [];
const on = comps.filter((c) => c.online).length; const on = comps.filter((c) => c.online).length;
const tn = taskAttention();
$("quick").innerHTML = owner() ? [ $("quick").innerHTML = owner() ? [
`<button data-q="tasks" aria-label="任務${tn ? `,${tn} 件要看` : ""}">${ic("circle-check", 15)} 任務${tn ? ` <b>${tn}</b>` : ""}</button>`,
`<button data-q="routines">${ic("alarm-clock", 15)} 例行任務 <b>${routines}</b></button>`, `<button data-q="routines">${ic("alarm-clock", 15)} 例行任務 <b>${routines}</b></button>`,
`<button data-q="pages">${ic("file-text", 15)} 頁面 <b>${S.pages.length}</b></button>`, `<button data-q="pages">${ic("file-text", 15)} 頁面 <b>${S.pages.length}</b></button>`,
`<button data-q="computers"><span class="st" style="background:${on ? "var(--ok)" : "var(--text4)"}"></span> 電腦 <b>${on}/${comps.length}</b></button>`, `<button data-q="computers"><span class="st" style="background:${on ? "var(--ok)" : "var(--text4)"}"></span> 電腦 <b>${on}/${comps.length}</b></button>`,
@ -1651,7 +1668,8 @@ function keepChat(id, msgs, sig) {
CHATS.delete(k); CHATS.set(k, was && was.sig === sig && Date.now() - (was.t || 0) <= 3600000 ? was : c); 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); } 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) { if (S.open !== id) {
keepChat(S.open, S.msgs, S.chatSig); 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 = ""; S.msgs = []; S.pending = []; S.quote = null; S.unfold = {}; S.openSteps = {}; S.chatSig = ""; S.prevShown = 0; S.prevFirst = ""; MODE_OPEN = ""; $("msgs").innerHTML = "";
@ -1669,7 +1687,8 @@ function openChat(id) {
else { chat.style.removeProperty("--bot"); chat.style.removeProperty("--bot-ink"); } else { chat.style.removeProperty("--bot"); chat.style.removeProperty("--bot-ink"); }
chatHead(); renderChips(); renderQuote(); chatHead(); renderChips(); renderQuote();
renderMsgs(); $("scroller").scrollTop = $("scroller").scrollHeight; atEnd = true; renderMsgs(); $("scroller").scrollTop = $("scroller").scrollHeight; atEnd = true;
loadChat(true); renderDock(); jumpTo();
loadChat(!at); renderDock();
api(base() + `api/bots/${id}/read`, {json: {}}).catch(() => {}); api(base() + `api/bots/${id}/read`, {json: {}}).catch(() => {});
} }
let loading = false, again = false; let loading = false, again = false;
@ -1688,11 +1707,14 @@ async function loadChat(jump) {
const sc = $("scroller"); const near = sc.scrollHeight - sc.scrollTop - sc.clientHeight < 140; const sc = $("scroller"); const near = sc.scrollHeight - sc.scrollTop - sc.clientHeight < 140;
S.msgs = msgs; S.chatSig = v.sig || ""; S.chatLoaded = true; renderMsgs(); keepSoon(); S.msgs = msgs; S.chatSig = v.sig || ""; S.chatLoaded = true; renderMsgs(); keepSoon();
if (jump || near) sc.scrollTop = sc.scrollHeight; if (jump || near) sc.scrollTop = sc.scrollHeight;
jumpTo();
} else { S.chatSig = ""; again = true; } } else { S.chatSig = ""; again = true; }
} }
} catch (e) { toast(e.message); if (S.open === id && !S.chatLoaded && S.view === "chat") renderMsgs(); } } catch (e) { toast(e.message); if (S.open === id && !S.chatLoaded && S.view === "chat") renderMsgs(); }
loading = false; loading = false;
if (again) { again = false; loadChat(); } 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("那件事開頭的訊息太早了,手機上只留最近的訊息"); }
} }
// The state poll carried the open chat's messages along (single trip): take them as-is. // The state poll carried the open chat's messages along (single trip): take them as-is.
function applyChat(msgs, sig) { function applyChat(msgs, sig) {
@ -1702,6 +1724,7 @@ function applyChat(msgs, sig) {
S.msgs = msgs; S.msgs = msgs;
renderMsgs(); keepSoon(); renderMsgs(); keepSoon();
if (near) sc.scrollTop = sc.scrollHeight; if (near) sc.scrollTop = sc.scrollHeight;
jumpTo();
} }
// What a new chat offers (the desktop's 建議): the everyday jobs, one tap to start writing them. // What a new chat offers (the desktop's 建議): the everyday jobs, one tap to start writing them.
const SUGGEST = [ const SUGGEST = [
@ -2968,13 +2991,14 @@ async function settingsChanged() {
} }
let listTimer = null; let listTimer = null;
function stopListTimer() { clearInterval(listTimer); 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) { async function renderList(arg) {
const kind = arg.kind; const kind = arg.kind;
$("list-title").textContent = TITLES[kind] || ""; $("list-title").textContent = TITLES[kind] || "";
$("list-act").innerHTML = ""; $("list-act").innerHTML = "";
const el = $("list"); const el = $("list");
stopListTimer(); stopListTimer();
if (kind === "tasks") return listTasks(el);
if (kind === "routines") return listRoutines(el); if (kind === "routines") return listRoutines(el);
if (kind === "pages") return listPages(el); if (kind === "pages") return listPages(el);
if (SETTINGS_PAGES.includes(kind)) { if (SETTINGS_PAGES.includes(kind)) {
@ -2987,6 +3011,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); 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)}<span class="dlv ${d}" title="${esc(d === "failed" ? (a.device || "") + "顯示失敗:" + (a.why || "") : DLV_TITLE[d] || "")}">${mark}</span>`;
}
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 ? `<div class="ln">${active ? "現在" : "最後一步"}:${esc(t.doing)}</div>` : "";
const why = t.why && t.why !== t.doing ? `<div class="ln why ${t.status === "failed" ? "bad" : ""}">${esc(t.why)}</div>` : "";
const files = (t.artifacts || []).map(taskFile).join("、");
const foot = `${files ? "產物:" + files + " · " : ""}證據 <b class="lv">${esc(t.level || "")}</b>${t.kept ? " · 照紀錄(聊天裡已經沒有)" : ""}`;
return `<button class="tk" data-task="${t.bot}:${t.at}" data-status="${esc(t.status)}"><div class="av sm">${b ? avatarSvg(b.shape, b.color) : ""}</div><div class="mid"><div class="hd"><span class="who">${esc(b ? b.name : "已刪除的 Bot")} · ${esc(t.from || "")}${/[A-Za-z]$/.test(t.from || "") ? " " : ""}開的</span><span class="st ${TASK_CLS[t.status] || ""}">${esc(t.label || t.status)}</span></div><div class="tx">${esc(t.text || "")}</div><div class="ln">${esc(facts)}</div>${doing}${why}<div class="ln">${foot}</div></div></button>`;
}
function listTasks(el) {
const list = S.tasks || [], n = taskAttention();
const head = S.stale ? "離線中:顯示的是上次存在這支手機上的任務" : n ? `${n} 件進行中、等你或今天失敗` : "";
el.innerHTML = list.length
? `${head ? `<div class="gt">${esc(head)}</div>` : ""}<div class="group" id="tasks">${list.map(taskCard).join("")}</div><div class="note">狀態由 AnyBot 從步驟、回合結束和交付回報算出,不是 Bot 說的。證據 A:系統自己看到;C:別的 Bot 轉述;未驗:沒有系統看得到的結果。</div>`
: `<div class="empty">還沒有任務。<br>交代 Bot 做一件事,它就會出現在這裡。</div>`;
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) { async function listRoutines(el, again) {
// (Every bot's details asked at once, not one after the other; what this phone has is drawn first.) // (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)); const missing = again ? [] : S.bots.filter((b) => !isNew(b.id));

View File

@ -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.) /// 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 { 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 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 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). /// 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 { fn only_looks(name: &str) -> bool {
matches!( matches!(
name, 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"
) )
} }

View File

@ -41,6 +41,7 @@ mod mirror_ui;
mod pages_ui; mod pages_ui;
mod voice_ui; mod voice_ui;
mod drops_ui; mod drops_ui;
mod tasks_ui;
mod memory_ui; mod memory_ui;
mod goal_ui; mod goal_ui;
mod context_ui; mod context_ui;
@ -299,6 +300,8 @@ pub struct App {
slash: chat_ui::Slash, slash: chat_ui::Slash,
/// 傳送到其他裝置, when its dialog is open; and the device chosen last time. /// 傳送到其他裝置, when its dialog is open; and the device chosen last time.
drop_page: Option<drops_ui::DropPage>, drop_page: Option<drops_ui::DropPage>,
/// 任務: the list the brain works out, and its dialog.
tk: tasks_ui::TasksUi,
drop_last: String, drop_last: String,
nightly_checked: Option<Instant>, nightly_checked: Option<Instant>,
/// Files and pictures waiting to go with the next message. /// Files and pictures waiting to go with the next message.
@ -563,6 +566,7 @@ impl App {
mem_page: None, mem_page: None,
slash: Default::default(), slash: Default::default(),
drop_page: None, drop_page: None,
tk: Default::default(),
drop_last: String::new(), drop_last: String::new(),
nightly_checked: None, nightly_checked: None,
att: Default::default(), att: Default::default(),
@ -1313,6 +1317,11 @@ impl App {
app.show_settings = true; app.show_settings = true;
app.settings_tab = SettingsTab::Computers; 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) { if self.state.branch_bots.iter().any(|b| b.id == bot_id) {
self.branch_settled(bot_id, outcome); 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 /// 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 } appctl::Outcome { text, ok: true, wake: vec![], theme_changed: false, page: None }
} else if call.name == "my_profile" { } else if call.name == "my_profile" {
appctl::Outcome { text: self.my_profile_text(bot_id), ok: true, wake: vec![], theme_changed: false, page: None } 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" { } else if call.name == "update_my_profile" {
self.apply_profile_change(bot_id, &call.args) self.apply_profile_change(bot_id, &call.args)
} else if call.name == "update_bot" && serde_json::from_str::<serde_json::Value>(&call.args).map(|v| v["default_computer"].is_string()).unwrap_or(false) { } else if call.name == "update_bot" && serde_json::from_str::<serde_json::Value>(&call.args).map(|v| v["default_computer"].is_string()).unwrap_or(false) {
@ -3624,6 +3638,7 @@ impl App {
follow_ups: vec![], follow_ups: vec![],
routines: vec![], routines: vec![],
last_turn: None, last_turn: None,
tasks: vec![],
goal: None, goal: None,
plan: None, plan: None,
draft: String::new(), draft: String::new(),
@ -6468,6 +6483,8 @@ impl App {
self.tick_routines(ctx); self.tick_routines(ctx);
self.monitor_tick(ctx); self.monitor_tick(ctx);
self.followup_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_asks(ctx);
self.tick_branches(ctx); self.tick_branches(ctx);
self.watchdog(); self.watchdog();
@ -7044,6 +7061,7 @@ impl eframe::App for App {
self.bot_editor(ctx); self.bot_editor(ctx);
self.memory_page(ctx); self.memory_page(ctx);
self.drops_page(ctx); self.drops_page(ctx);
self.tasks_window(ctx);
self.settings(ctx); self.settings(ctx);
} }
self.delete_dialog(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使用者要看某台電腦的畫面(截圖給我看、讓我看看)時,用 computer(action=show):畫面會直接出現在聊天裡。");
} }
s.push_str("\n\n做好的檔案(試算表、文件、Markdown、網頁、圖片)用 send_file 傳進聊天,使用者點一下就能預覽;不要只說檔案放在哪裡。傳了不等於使用者看到了:不要說他已經看到,以 send_file 結果後面的〔交付狀態〕為準;使用者問收到沒、傳到手機了沒,照那個狀態回答。適合的時候可以用 react 對使用者的訊息按個表情(例如謝謝你時按 ❤️),不用每次都按。"); 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("\n\n");
s.push_str(&crate::i18n::reply_instruction(&st.language)); 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 // Its soul and the person's 指示 (one text) last and under a heading: dropped bare into the

View File

@ -196,6 +196,7 @@ fn doing(name: &str, args: &str, place: Option<&str>) -> String {
"ask_bot" => with("正在問另一個 Bot", s("bot")), "ask_bot" => with("正在問另一個 Bot", s("bot")),
"teach_skill" => with("正在教技能給", s("bot")), "teach_skill" => with("正在教技能給", s("bot")),
"list_routines" => "正在查看例行任務".into(), "list_routines" => "正在查看例行任務".into(),
crate::tasks::TOOL => "正在查看任務".into(),
"create_routine" | "update_routine" | "delete_routine" => "正在安排例行任務".into(), "create_routine" | "update_routine" | "delete_routine" => "正在安排例行任務".into(),
"run_routine_now" => "正在執行例行任務".into(), "run_routine_now" => "正在執行例行任務".into(),
"list_bots" | "create_bot" | "update_bot" => "正在設定 Bot".into(), "list_bots" | "create_bot" | "update_bot" => "正在設定 Bot".into(),

View File

@ -101,6 +101,13 @@ fn scenes() -> Vec<(&'static str, Open)> {
}) })
}; };
vec![ vec![
(
"任務",
Box::new(|a: &mut App| {
a.tasks_tick(true);
a.tk.open = true;
}),
),
("設定 › 一般", tab(SettingsTab::General)), ("設定 › 一般", tab(SettingsTab::General)),
("設定 › 手機與帳號", tab(SettingsTab::Remote)), ("設定 › 手機與帳號", tab(SettingsTab::Remote)),
("設定 › 模型", tab(SettingsTab::Providers)), ("設定 › 模型", tab(SettingsTab::Providers)),

View File

@ -46,7 +46,7 @@ fn copy_own(to: &mut State, from: &State) {
to.celebrate = from.celebrate; to.celebrate = from.celebrate;
} }
/// Bot fields the brain alone changes (its chat, and what a turn leaves behind). /// 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. /// Stands in for a key or token the brain doesn't hand out.
pub const REDACTED: &str = "••••(已設定,在大腦上)"; pub const REDACTED: &str = "••••(已設定,在大腦上)";
@ -432,6 +432,8 @@ pub struct Screens {
struct Seen { struct Seen {
version: u64, version: u64,
config: u64, config: u64,
/// 任務: the fingerprint of the list it was sent last.
tasks: u64,
bots: HashMap<u64, Vec<u64>>, bots: HashMap<u64, Vec<u64>>,
threads: HashMap<u64, u64>, threads: HashMap<u64, u64>,
at: Option<Instant>, at: Option<Instant>,
@ -782,6 +784,8 @@ pub struct Mirror {
pub(super) computers: HashMap<u64, Value>, pub(super) computers: HashMap<u64, Value>,
/// The connectors at the brain, as [`App::mcp_state`] gives them. /// The connectors at the brain, as [`App::mcp_state`] gives them.
pub(super) mcp_state: Value, pub(super) mcp_state: Value,
/// 任務: the list the brain worked out (None until it sends one).
pub(super) tasks: Option<Vec<crate::tasks::Task>>,
/// When each bot's last turn ended, as last heard (a newer one ending well is read aloud). /// When each bot's last turn ended, as last heard (a newer one ending well is read aloud).
settled: HashMap<u64, i64>, settled: HashMap<u64, i64>,
/// The brain's key for each card waiting here (by bot id): an answer from this screen names /// 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)); 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["bots"] = Value::Array(bots);
out["threads"] = Value::Array(threads); out["threads"] = Value::Array(threads);
out["live"] = self.streams.iter().map(|(id, l)| (id.to_string(), json!({"status": l.status, "paused": l.paused}))).collect::<serde_json::Map<_, _>>().into(); out["live"] = self.streams.iter().map(|(id, l)| (id.to_string(), json!({"status": l.status, "paused": l.paused}))).collect::<serde_json::Map<_, _>>().into();
@ -1781,6 +1790,10 @@ impl App {
if v["box"].is_object() { if v["box"].is_object() {
self.mir.box_state = v["box"].clone(); 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() { if v["mcp"].is_object() {
self.mir.mcp_state = v["mcp"].clone(); 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()))); 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 的 /// 螢幕電腦上回答的卡帶著大腦給那張卡的 key(.claude/skills/verify-approval-routing 的
/// ScreenRefreshes → YouAnswerOnScreen → BrainTakesAnswer):大腦只把它交給那張卡。以前 /// ScreenRefreshes → YouAnswerOnScreen → BrainTakesAnswer):大腦只把它交給那張卡。以前
/// 不帶,大腦交給那時候在等的卡(F1)。 /// 不帶,大腦交給那時候在等的卡(F1)。

View File

@ -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); 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); 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 // A connector connected or failing: screens and phones hear of it now, not at the next
// long poll's end. // long poll's end.
let mut up: Vec<(String, usize)> = crate::mcp::status().into_iter().collect(); let mut up: Vec<(String, usize)> = crate::mcp::status().into_iter().collect();
@ -512,6 +514,7 @@ impl App {
view.approvals.extend(self.phone_cards(b)); view.approvals.extend(self.phone_cards(b));
} }
view.pages = self.state.pages.clone(); 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. // The models a bot can be switched to from the phone: each provider that is ready.
view.models = crate::providers::ALL_PROVIDERS view.models = crate::providers::ALL_PROVIDERS
.iter() .iter()

View File

@ -293,6 +293,8 @@ impl App {
ui.data_mut(|d| d.insert_temp(egui::Id::unique(SEARCH_FOCUS), frame)); 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() { if self.search_open || !self.search.is_empty() {

310
src/app/tasks_ui.rs Normal file
View File

@ -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<Task>,
/// Its fingerprint: the phone and the screens get it again when it changes.
pub(super) sig: u64,
at: Option<Instant>,
/// 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<Vec<Task>>,
}
/// 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<Vec<Task>> = 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<Task> = 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<String> = 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<String> = 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}");
}
}

View File

@ -9,9 +9,11 @@ use crate::model::{self, Bot, Message, State, Theme, Accent};
use crate::providers::{ProviderKind, ALL_PROVIDERS}; use crate::providers::{ProviderKind, ALL_PROVIDERS};
use crate::routines::{self, Routine, Schedule}; 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 something long in the background (followup.rs; checks run on the brain).
"follow_up", "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_routines", "create_routine", "update_routine", "delete_routine", "run_routine_now",
"list_bots", "create_bot", "update_bot", "message_bot", "list_computers", "update_settings", "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); // 問同事: 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 { pub fn label(name: &str) -> &'static str {
match name { match name {
"list_routines" => "查看例行任務", "list_routines" => "查看例行任務",
crate::tasks::TOOL => "查看任務",
crate::mcp::MANAGE_TOOL => "管理連接器", crate::mcp::MANAGE_TOOL => "管理連接器",
crate::hooks::MANAGE_TOOL => "管理 hook", crate::hooks::MANAGE_TOOL => "管理 hook",
crate::chatgpt::TOOL => "ChatGPT 方案登入", crate::chatgpt::TOOL => "ChatGPT 方案登入",
@ -97,6 +100,7 @@ fn schedule_schema() -> Value {
pub fn specs() -> Vec<Value> { pub fn specs() -> Vec<Value> {
vec![ vec![
crate::followup::spec(), 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": "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).", 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": { "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), 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()))), "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" => { "list_routines" => {
let Some(b) = state.bot(bot_id) else { return err("找不到這個 Bot".into()) }; let Some(b) = state.bot(bot_id) else { return err("找不到這個 Bot".into()) };
if b.routines.is_empty() { 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![], follow_ups: vec![],
routines: vec![], routines: vec![],
last_turn: None, last_turn: None,
tasks: vec![],
goal: None, goal: None,
plan: None, plan: None,
draft: String::new(), draft: String::new(),

View File

@ -48,6 +48,7 @@ pub const AREAS: &[Area] = &[
area!("routines", "例行任務"), area!("routines", "例行任務"),
area!("goal", "目標(/goal)"), area!("goal", "目標(/goal)"),
area!("plan", "計畫(/plan)"), area!("plan", "計畫(/plan)"),
area!("tasks", "任務"),
area!("computers", "電腦:大腦與手腳"), area!("computers", "電腦:大腦與手腳"),
area!("box", "Bot 的電腦"), area!("box", "Bot 的電腦"),
area!("files", "檔案與指令"), area!("files", "檔案與指令"),

View File

@ -73,6 +73,7 @@ mod tools;
mod triggers; mod triggers;
mod embed; mod embed;
mod evidence; mod evidence;
mod tasks;
mod featuremap; mod featuremap;
mod garden; mod garden;
mod goal; mod goal;

View File

@ -421,6 +421,11 @@ pub struct Bot {
pub routines: Vec<crate::routines::Routine>, pub routines: Vec<crate::routines::Routine>,
#[serde(default)] #[serde(default)]
pub last_turn: Option<TurnSettlement>, pub last_turn: Option<TurnSettlement>,
/// 任務: 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<crate::tasks::Event>,
/// 目標 (/goal): what it keeps working toward, turn after turn, until a check says it holds. /// 目標 (/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. /// The brain's alone (a turn's end changes it); see goal.rs.
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
@ -1240,6 +1245,7 @@ impl State {
follow_ups: vec![], follow_ups: vec![],
routines: vec![], routines: vec![],
last_turn: None, last_turn: None,
tasks: vec![],
goal: None, goal: None,
plan: None, plan: None,
default_computer: default_computer(), default_computer: default_computer(),

View File

@ -401,6 +401,7 @@ pub fn replay_of(name: &str) -> Replay {
"list_bots", "list_bots",
"list_computers", "list_computers",
"list_routines", "list_routines",
crate::tasks::TOOL,
"list_pages", "list_pages",
"read_page", "read_page",
"mac_read_mail", "mac_read_mail",

View File

@ -248,6 +248,8 @@ pub struct View {
pub messages: HashMap<u64, Vec<Value>>, pub messages: HashMap<u64, Vec<Value>>,
/// 頁面, for the phone's page view. /// 頁面, for the phone's page view.
pub pages: Vec<crate::pages::Page>, pub pages: Vec<crate::pages::Page>,
/// 任務: every bot's tasks as the brain worked them out (tasks::json), the newest first.
pub tasks: Vec<Value>,
/// The models the phone can switch a bot to: each ready provider with its known models. /// The models the phone can switch a bot to: each ready provider with its known models.
pub models: Vec<Value>, pub models: Vec<Value>,
/// The sidebar's 分區 in order (None = 未分區), empty ones too, as the desktop shows them. /// The sidebar's 分區 in order (None = 未分區), empty ones too, as the desktop shows them.
@ -634,9 +636,11 @@ pub fn handle(req: Req, via_relay: bool) -> Resp {
} else { } else {
v.bots.clone() 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!({ let out = json!({
"version": v.version, "host": v.host, "person": v.person, "accent": v.accent, "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() }, "approvals": if role == "member" { vec![] } else { v.approvals.clone() },
"box": crate::cloudbox::run_state().label(), "box": crate::cloudbox::run_state().label(),
"box_available": crate::cloudbox::available(), "box_available": crate::cloudbox::available(),

View File

@ -1167,6 +1167,7 @@ fn seed_first() -> i32 {
follow_ups: vec![], follow_ups: vec![],
routines: vec![], routines: vec![],
last_turn: None, last_turn: None,
tasks: vec![],
goal: None, goal: None,
plan: None, plan: None,
draft: String::new(), draft: String::new(),

View File

@ -41,7 +41,7 @@ pub fn export(b: &Bot) -> String {
let mut v = serde_json::to_value(b).unwrap_or(Value::Null); let mut v = serde_json::to_value(b).unwrap_or(Value::Null);
if let Value::Object(m) = &mut v { if let Value::Object(m) = &mut v {
// (Its 可以用的電腦 are this account's computers by name; its 草稿 is unsent words: neither travels.) // (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); m.remove(k);
} }
if let Some(Value::Array(routines)) = m.get_mut("routines") { 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![])); m.insert("messages".into(), Value::Array(vec![]));
// Never import another person's grants, local workdir, threads or memories — nor its // 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). // 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); m.remove(k);
} }
} }

1331
src/tasks.rs Normal file

File diff suppressed because it is too large Load Diff