日程:每個 Bot 被設定要做的事放在同一個日曆上(照 OpenBot 日程的排版,風格是 AnyBot 自己的),不用一個個問 Bot「你今天要幹嘛」。另外修好獨立審查在工作流(351ce3f)找到的問題。

日程(schedule.rs 算資料、app/schedule_ui.rs 畫):
- 側邊欄最上面一排多了日曆按鈕(所有檔案、工作流、日程、任務…);「日/週/月」「‹ 今天 ›」、右上角寫時區。
- 例行任務(照排程的)和有排程的工作流:跑過的照執行紀錄(✓ 完成、✗ 失敗或中斷、■ 停止、圓點執行中),還沒到的用排程本身的 next_run 算(暫停的變灰帶 ‖);事件觸發的只看得到跑過的;每個一段期間最多 200 次。
- 週:每天一欄,時間+頭像,下面是名稱;月:每天三筆+「還有 N 個」,點那天換成日看法;日:照時間一列列。下面「即將執行」:所有 Bot 最先要跑的六筆。
- 點一筆打開卡片:時間、狀態、怎麼重複、最近一次、要它做什麼;打開聊天/立即執行/暫停繼續(工作流:打開工作流/立即執行)。「+ 新增例行任務」回到聊天、輸入框先放「每天早上 9 點幫我」。
- 功能地圖新的一區 schedule.md;library.md 的座標 76,30 → 32,30(最上面那排多了按鈕)。

工作流的審查(新開脈絡照 workflow.md 審 351ce3f,提了 6 個 P0/P1、3 個 P2,全修):
1. 停止時,還排在忙碌 Bot 後面的那步問題直接拿掉,不再停掉 Bot 手上不相干的那一輪(以前停掉了,排著的問題之後照樣送出)。
2. 交付遇到 Bot 正在回答:等那一輪結束才放進聊天(以前塞進去會被串流蓋掉)。
3. 重開 AnyBot:正在跑的那次標成失敗「AnyBot 在執行中被關掉…」(以前永遠卡住、排程從此不跑);等你確認的留著。
4. 刪除的允許卡片:要刪哪一個在問的當下就定下來寫進呼叫(以前卡片寫 B、按了刪 A);id 給錯(0、"x"、不存在)是錯誤,不會換成別的。
5. edit 設「僅一次」從設的那一刻算(以前可能永遠不跑)。
6. edit 的排程錯了,整次都不留(以前名字照樣改掉)。
另外:只有你正看著的那個 Bot 改工作流才會換畫布,換的時候放掉正在打字/拖的東西;新步驟不會用到執行或版本裡還有的編號;步驟的 Bot 被刪掉,那次停下來;螢幕電腦的選單不能新建、改名、還原、刪除。

已驗證: cargo test 860 過(新:schedule:: 一週的日曆(跑過/即將/暫停/事件觸發/工作流/上限)、日月週的範圍和標題;workflow:: 指定目標和釘住、改一半不留/僅一次/編號不重用/重開時中斷;app::workflow_run 停止拿掉排隊問題不停 Bot、交付等那一輪、Bot 被刪、別的 Bot 不換畫布;layout_audit 日程三景,窄視窗時標題不壓到日週月);clippy 沒有新的(bin 8)。scratch 真資料:手機聊天裡建兩個例行任務、立即執行一次,桌面:側邊欄日曆打開日程(✓ 今天那次、之後的圓點、即將執行六筆帶頭像),卡片、按暫停後變灰且 state 的 paused 是 true;月、日看法;所有檔案在 32,30 打得開。
未驗證: 這輪工作流的修正沒有再跑一次 workflow.md 的六步(單元測試有走每一條);重開 AnyBot 那條只有單元測試(scratch 的截圖模式不走啟動時的收尾)。刪工作流的卡片改在 app.rs 的 AppAction 分支先定目標:動到審批路徑,照規定要你看過再發佈。手機還沒有日程。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha2uBHmbnuWBhNzjbJm
This commit is contained in:
王性驊 2026-11-21 18:58:15 +08:00
parent 351ce3f005
commit b4408cce94
15 changed files with 1180 additions and 46 deletions

View File

@ -1943,6 +1943,16 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
- 在聊天裡做:跟 Bot 用一般的話說要什麼流程(「每天早上 9 點去 Threads 找 5 則熱門育兒討論,整理好先問我,我說可以再傳給我」),Bot 用 `workflow` 工具建立、看、改(加步驟、改內容、刪步驟、連線、貼便利貼、整理排版)、執行、停止、刪除(刪除先問)。你看著那個 Bot 的聊天時,畫布自動開在聊天旁邊(視窗夠寬時),它改到的卡片和便利貼亮一下,跑出畫面就縮到看得到全部;Bot 做的排成一欄,插在中間時後面的往下移,你自己排過的不重排。旁邊的聊天跟著側邊欄選的 Bot 換。 - 在聊天裡做:跟 Bot 用一般的話說要什麼流程(「每天早上 9 點去 Threads 找 5 則熱門育兒討論,整理好先問我,我說可以再傳給我」),Bot 用 `workflow` 工具建立、看、改(加步驟、改內容、刪步驟、連線、貼便利貼、整理排版)、執行、停止、刪除(刪除先問)。你看著那個 Bot 的聊天時,畫布自動開在聊天旁邊(視窗夠寬時),它改到的卡片和便利貼亮一下,跑出畫面就縮到看得到全部;Bot 做的排成一欄,插在中間時後面的往下移,你自己排過的不重排。旁邊的聊天跟著側邊欄選的 Bot 換。
- 手機沒有畫布:在聊天裡請 Bot 做、改、跑,它用文字說工作流的樣子;「等你確認」的通知會到手機,按「繼續」要在電腦上。螢幕電腦只能看。 - 手機沒有畫布:在聊天裡請 Bot 做、改、跑,它用文字說工作流的樣子;「等你確認」的通知會到手機,按「繼續」要在電腦上。螢幕電腦只能看。
### 日程(側邊欄最上面一排的日曆圖示)
照 OpenBot 日程的排版做的,風格是 AnyBot 自己的;功能地圖 schedule.md。不用一個個問 Bot「你今天要幹嘛」:每個 Bot 的例行任務(照排程的)和有排程的工作流放在同一個日曆上。
- 「日/週/月」三種看法,「‹ 今天 ›」往前往後;右上角寫時區(「時間以 Asia/Taipei 為準」)。週和月從週一開始,今天那格是強調色的框。
- 跑過的照執行紀錄:✓ 完成、✗ 失敗或中斷、■ 停止、圓點執行中;還沒到的照排程算出來(跟真的排程同一套算法),暫停的變灰帶 ‖。事件觸發的例行任務只看得到跑過的。週每筆是時間、Bot 的頭像和名稱;月每天最多三筆、多的「還有 N 個」,點那天換成日看法;日照時間一列列。
- 下面「即將執行」:所有 Bot 接下來最先要跑的六筆,帶頭像。
- 點任何一筆打開卡片:哪個 Bot、那次的時間和狀態、怎麼重複、最近一次怎麼樣、要它做什麼;「打開聊天」「立即執行」「暫停/繼續」(工作流:「打開工作流」「立即執行」)。
- 「+ 新增例行任務」回到 Bot 的聊天,輸入框先放好「每天早上 9 點幫我」,接著用一般的話說要做什麼。手機還沒有日程。
## 26. Bot 可以直接操作 App 的功能 ## 26. Bot 可以直接操作 App 的功能
你可以跟 Bot 說「每天早上 9 點幫我…」「把你換成 Claude」「切成深色模式」,它會自己操作 App。 你可以跟 Bot 說「每天早上 9 點幫我…」「把你換成 Claude」「切成深色模式」,它會自己操作 App。

View File

@ -89,6 +89,7 @@ Bot 讀得到的是開頭、子功能、使用者怎麼到、Bot 那一行和沒
### 自己會動 ### 自己會動
- [routines](routines.md):排程與事件觸發、執行紀錄、完成條件、自動暫停。 - [routines](routines.md):排程與事件觸發、執行紀錄、完成條件、自動暫停。
- [workflow](workflow.md):工作流:畫布上的步驟(Bot 步驟、等你確認、檢查、交付、通知)、畫和便利貼、執行與紀錄、版本歷史;在聊天裡請 Bot 做和改,畫布開在聊天旁邊。 - [workflow](workflow.md):工作流:畫布上的步驟(Bot 步驟、等你確認、檢查、交付、通知)、畫和便利貼、執行與紀錄、版本歷史;在聊天裡請 Bot 做和改,畫布開在聊天旁邊。
- [schedule](schedule.md):日程:所有 Bot 的例行任務和有排程的工作流放在日/週/月的日曆上,跑過的成功失敗、接下來的時間、即將執行、卡片上暫停或立即執行。
- [goal](goal.md):/goal:沒達成就繼續做、評審只看證據。 - [goal](goal.md):/goal:沒達成就繼續做、評審只看證據。
- [plan](plan.md):/plan:先查清楚、交計畫給你核准,核准後才動手、照步驟打勾。 - [plan](plan.md):/plan:先查清楚、交計畫給你核准,核准後才動手、照步驟打勾。
- [activity](activity.md):操作紀錄:每一輪誰發起、看了/寫了/執行了什麼、工具次數、失敗、花多久;電腦版右側「動態」、手機「稽核」。 - [activity](activity.md):操作紀錄:每一輪誰發起、看了/寫了/執行了什麼、工具次數、失敗、花多久;電腦版右側「動態」、手機「稽核」。

View File

@ -26,8 +26,8 @@
- 基本前提和「手機已登入」(README),開著 Bot 1 的聊天:`$CTL phone click '.row[data-bot="1"]'`。桌面的步驟要開視窗(`ABV_ALLOW_WINDOW=1`,先 `ctl stop`),座標照 1200×820。 - 基本前提和「手機已登入」(README),開著 Bot 1 的聊天:`$CTL phone click '.row[data-bot="1"]'`。桌面的步驟要開視窗(`ABV_ALLOW_WINDOW=1`,先 `ctl stop`),座標照 1200×820。
- **放七個檔案**(covers `library-gather`):從手機附上七個檔案送出,再刪掉其中一個存在 AnyBot 裡的那份。指令:`D=$(mktemp -d) && cp cat-1.png "$D/貓一.png" && cp cat-2.png "$D/貓二.png" && printf '# 發布計畫\n\n- 11/22 上線\n' > "$D/release-notes-v4.md" && printf '日期,用量\n11/20,3610\n' > "$D/用量.csv" && printf 'print("hello")\n' > "$D/hello.py" && printf 'x' > "$D/舊的.txt" && (cd "$D" && zip -q 封存.zip hello.py) && for f in 貓一.png 貓二.png release-notes-v4.md 用量.csv hello.py 舊的.txt 封存.zip; do $CTL phone upload '#file' "$D/$f" && $CTL phone wait-text "$f" --in '#chips' 20; done && $CTL phone send 這些檔案先放著 && $CTL phone wait-text 'FAKE-MODEL 回答:這些檔案先放著' --in '#msgs' && SCR=$(sed -n 's/^SCR=//p' target/verify-anybot/current/run.env) && rm -f "$(find "$SCR/data/attachments" -name '*舊的.txt' | head -1)" && $CTL api GET /api/bots/1 --jq '[.messages[].attachments[]?.name]'`。看到:API 列出七個檔名;舊的.txt 在 AnyBot 裡的那份刪掉了。 - **放七個檔案**(covers `library-gather`):從手機附上七個檔案送出,再刪掉其中一個存在 AnyBot 裡的那份。指令:`D=$(mktemp -d) && cp cat-1.png "$D/貓一.png" && cp cat-2.png "$D/貓二.png" && printf '# 發布計畫\n\n- 11/22 上線\n' > "$D/release-notes-v4.md" && printf '日期,用量\n11/20,3610\n' > "$D/用量.csv" && printf 'print("hello")\n' > "$D/hello.py" && printf 'x' > "$D/舊的.txt" && (cd "$D" && zip -q 封存.zip hello.py) && for f in 貓一.png 貓二.png release-notes-v4.md 用量.csv hello.py 舊的.txt 封存.zip; do $CTL phone upload '#file' "$D/$f" && $CTL phone wait-text "$f" --in '#chips' 20; done && $CTL phone send 這些檔案先放著 && $CTL phone wait-text 'FAKE-MODEL 回答:這些檔案先放著' --in '#msgs' && SCR=$(sed -n 's/^SCR=//p' target/verify-anybot/current/run.env) && rm -f "$(find "$SCR/data/attachments" -name '*舊的.txt' | head -1)" && $CTL api GET /api/bots/1 --jq '[.messages[].attachments[]?.name]'`。看到:API 列出七個檔名;舊的.txt 在 AnyBot 裡的那份刪掉了。
- **格子、分類、不見了**(covers `library-place`、`library-kinds`、`library-view`、`library-gone`):從側邊欄的資料夾按鈕打開。指令:`$CTL phone stop && $CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot library ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_SIZE=1200x820 ANYBOT_SHOT_FRAMES=520 'ANYBOT_SHOT_CLICK=76,30@440'`。看到:「所有檔案」視窗,左欄「所有檔案 7」「最近 7 天 7」、「Bot」下「驗證小幫手 7」;上面「全部 7、圖片 2、文件 2、程式碼 1、表格 1、其他 1」(沒有影音);三張一排撐滿,兩張貓是縮圖,其他寫 MD、CSV、PY、TXT、ZIP;舊的.txt 灰字、紅字「不見了(檔案已經刪掉或搬走)」。 - **格子、分類、不見了**(covers `library-place`、`library-kinds`、`library-view`、`library-gone`):從側邊欄的資料夾按鈕打開。指令:`$CTL phone stop && $CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot library ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_SIZE=1200x820 ANYBOT_SHOT_FRAMES=520 'ANYBOT_SHOT_CLICK=32,30@440'`。看到:「所有檔案」視窗,左欄「所有檔案 7」「最近 7 天 7」、「Bot」下「驗證小幫手 7」;上面「全部 7、圖片 2、文件 2、程式碼 1、表格 1、其他 1」(沒有影音);三張一排撐滿,兩張貓是縮圖,其他寫 MD、CSV、PY、TXT、ZIP;舊的.txt 灰字、紅字「不見了(檔案已經刪掉或搬走)」。
- **清單、打開**(covers `library-view`、`library-open`、`library-gone`):按「清單」,再按 release-notes-v4.md 那列。指令:`ABV_ALLOW_WINDOW=1 $CTL desktop-shot library-list ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_SIZE=1200x820 ANYBOT_SHOT_FRAMES=500 'ANYBOT_SHOT_CLICK=76,30@440;1033,127@470' && ABV_ALLOW_WINDOW=1 $CTL desktop-shot library-open ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_SIZE=1200x820 ANYBOT_SHOT_FRAMES=540 'ANYBOT_SHOT_CLICK=76,30@440;1033,127@470;450,267@500'`。看到:視窗沒有跳動;每列「名稱……驗證小幫手 · 今天 HH:MM · 31 B」,舊的.txt 右邊紅字「不見了」;release-notes-v4.md 在 AnyBot 的檢視器打開:「發布計畫」「11/22 上線」,右上「用其他 App 打開」、下載、關閉。帳戶選單的「所有檔案…」、搜尋、選某個 Bot:靠自動測試和版面檢查。 - **清單、打開**(covers `library-view`、`library-open`、`library-gone`):按「清單」,再按 release-notes-v4.md 那列。指令:`ABV_ALLOW_WINDOW=1 $CTL desktop-shot library-list ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_SIZE=1200x820 ANYBOT_SHOT_FRAMES=500 'ANYBOT_SHOT_CLICK=32,30@440;1033,127@470' && ABV_ALLOW_WINDOW=1 $CTL desktop-shot library-open ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_SIZE=1200x820 ANYBOT_SHOT_FRAMES=540 'ANYBOT_SHOT_CLICK=32,30@440;1033,127@470;450,267@500'`。看到:視窗沒有跳動;每列「名稱……驗證小幫手 · 今天 HH:MM · 31 B」,舊的.txt 右邊紅字「不見了」;release-notes-v4.md 在 AnyBot 的檢視器打開:「發布計畫」「11/22 上線」,右上「用其他 App 打開」、下載、關閉。帳戶選單的「所有檔案…」、搜尋、選某個 Bot:靠自動測試和版面檢查。
- 自動測試:`cargo test app::library_ui::`、`cargo test layout_audit::`(「所有檔案」這一景)。 - 自動測試:`cargo test app::library_ui::`、`cargo test layout_audit::`(「所有檔案」這一景)。
## 陷阱 ## 陷阱

View File

@ -0,0 +1,38 @@
# 日程
每個 Bot 被設定要做的事放在同一個日曆上:例行任務(照排程的)和有排程的工作流。看得到已經跑過的(成功、失敗),也看得到接下來什麼時候跑、哪個 Bot 跑,不用一個個問 Bot「你今天要幹嘛」。時間照你的時區。只在電腦版。
## 子功能
- `schedule-views` 看法:右上「日/週/月」,左上「‹ 今天 ›」往前往後、回到今天,旁邊寫「2026年11月」「11月16日 – 22日」「11月21日 星期六」;右上角寫「時間以 Asia/Taipei 為準」(你的時區)。週和月從週一開始,今天那格是強調色的框。
- `schedule-entries` 每一筆:跑過的照它的執行紀錄(✓ 完成、✗ 失敗或中斷、■ 停止、圓點執行中),還沒到的照排程算出來(圓點;暫停的變灰、帶 ‖)。週:每天一欄,每筆是時間、Bot 的頭像,下面是名稱。月:每天最多三筆「時間 名稱」,多的寫「還有 N 個」;點那一天換成那天的日看法。日:照時間一列列,寫「名稱 · 時間 · 怎麼重複 · 啟用中/已暫停/完成」。事件觸發的例行任務沒有預定的時間,只看得到跑過的。一個每 5 分鐘跑的,一段期間最多列 200 次。
- `schedule-coming` 即將執行:所有 Bot 接下來兩週內最先要跑的六筆(暫停的不算),每筆「名稱 · 明天 08:30 · 每天 08:30」和 Bot 的頭像;沒有時說怎麼設一個。
- `schedule-card` 點任何一筆打開卡片:哪個 Bot、那一次的時間和狀態、怎麼重複、最近一次怎麼樣、要它做什麼;按鈕「打開聊天」「立即執行」「暫停/繼續」。工作流的是「打開工作流」「立即執行」。
- `schedule-new` 「+ 新增例行任務」:回到那個 Bot 的聊天,輸入框先放好「每天早上 9 點幫我」,接著說要做什麼;Bot 用 `create_routine` 設好,日程上就出現。
## 使用者怎麼到
- 側邊欄最上面一排第三個(日曆圖示,滑過寫「日程」),在工作流和任務中間;再按一次回到聊天。左上「‹ 聊天」也回到聊天;在側邊欄點別的 Bot 也回到聊天。
- 手機沒有日程:在聊天裡問 Bot「你有哪些例行任務」,它用 `list_routines` 回答(只有它自己的)。
## 怎麼操作(verify-anybot)
- Bot:沒有專門的工具;使用者問排程時,用 `list_routines` 說自己的、`workflow` 的 list 說工作流,並告訴他電腦版側邊欄的「日程」(日曆圖示)看得到所有 Bot 的。設定、暫停、刪除還是用 `create_routine`、`update_routine`、`delete_routine`。
前提:
- 基本前提和「手機已登入」(README),開著 Bot 1 的聊天:`$CTL phone click '.row[data-bot="1"]'`。桌面的步驟要開視窗(`ABV_ALLOW_WINDOW=1`,先 `ctl stop`),座標照 1400×900(打開日程那一步是 1200×820)。
- **在聊天裡設兩個例行任務、先跑一次**(covers `schedule-entries`、`schedule-new`):指令:`$CTL phone send '每天早上 8:30 掃競品 [[call create_routine {"title":"競品掃描","prompt":"找三則競品新聞","schedule":{"frequency":"daily","time":"08:30"}}]]' && $CTL phone wait-text '已建立例行任務' --in '#msgs' 60 && $CTL phone send '工作日 9 點晨報 [[call create_routine {"title":"晨間簡報","prompt":"整理今天要做的事","schedule":{"frequency":"weekly","daysOfWeek":["MO","TU","WE","TH","FR"],"time":"09:00"}}]]' && $CTL phone wait-text '晨間簡報' --in '#msgs' 60 && $CTL phone send '先跑一次競品 [[call run_routine_now {"id":1}]]' && $CTL wait-api /api/bots/1 '.messages[-1].role == "assistant" and ((.messages[-1].text // "") | contains("找三則競品新聞"))' 60 && $CTL phone stop && $CTL stop && $CTL state '[.bots[0].routines[] | {id, title, runs: [.runs[]? | .outcome]}]'`。看到:兩個都建立了;競品掃描的 runs 是 ["succeeded"],晨間簡報還沒有。
- **從側邊欄打開日程**(covers `schedule-views`、`schedule-entries`、`schedule-coming`):按側邊欄的日曆。指令:要開視窗——`ABV_ALLOW_WINDOW=1 $CTL desktop-shot schedule-open ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_SIZE=1200x820 ANYBOT_SHOT_FRAMES=520 'ANYBOT_SHOT_CLICK=120,30@440'`。看到:「日程」,週看法這一週,今天那格強調色框、裡面 ✓ 剛才的時間「競品掃描」,之後每天 08:30 圓點「競品掃描」;工作日 09:00「晨間簡報」從週一起;右上「時間以 Asia/Taipei 為準」;下面「即將執行」六筆照時間排、每筆有 Bot 的頭像。
- **月和日**(covers `schedule-views`、`schedule-entries`):指令:要開視窗——`ABV_ALLOW_WINDOW=1 $CTL desktop-shot schedule-month ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_VIEW=schedule ANYBOT_SHOT_TAB=month ANYBOT_SHOT_SIZE=1400x900 ANYBOT_SHOT_FRAMES=520 && ABV_ALLOW_WINDOW=1 $CTL desktop-shot schedule-day ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_VIEW=schedule ANYBOT_SHOT_TAB=day ANYBOT_SHOT_SIZE=1400x900 ANYBOT_SHOT_FRAMES=520`。看到:月:週一到週日的格子,這個月以外的日期灰字,工作日的格子兩筆(08:30、09:00),今天之前沒跑過的日子是空的;日:今天的「競品掃描 · 時間 · 每天 08:30 · 完成」,左邊寫幾時。
- **卡片和暫停**(covers `schedule-card`、`schedule-coming`):按即將執行第一筆,再按卡片上的「暫停」。指令:要開視窗——`ABV_ALLOW_WINDOW=1 $CTL desktop-shot schedule-card ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_VIEW=schedule ANYBOT_SHOT_SIZE=1400x900 ANYBOT_SHOT_FRAMES=560 'ANYBOT_SHOT_CLICK=700,439@530' && ABV_ALLOW_WINDOW=1 $CTL desktop-shot schedule-paused ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_VIEW=schedule ANYBOT_SHOT_SIZE=1400x900 ANYBOT_SHOT_FRAMES=580 'ANYBOT_SHOT_CLICK=700,439@530;705,558@545' && $CTL state '[.bots[0].routines[] | {title, paused}]'`。看到:卡片「競品掃描」:驗證小幫手的頭像和名字、「明天 08:30(啟用中)」「每天 08:30」、最近一次完成、「找三則競品新聞」,按鈕「打開聊天、立即執行、暫停」;暫停後之後的競品掃描變灰帶 ‖,即將執行只剩晨間簡報;state 裡競品掃描 paused 是 true。
- 自動測試:`cargo test schedule`、`cargo test layout_audit::`(「日程」週、月、日三景)。
## 陷阱
- 日程只是看:要新增或改,在聊天裡跟 Bot 說,或用卡片上的按鈕。
- 跑過的看執行紀錄:每個例行任務只留最近幾次,更早的日子是空的;AnyBot 沒開著的時候不會跑,那天也是空的。
- 「左右」的時間(flexible)每次差幾分鐘,日程上的時間是算出來的那一次。
- 工作流的頭像是它第一個 Bot 步驟的 Bot;沒有 Bot 步驟時畫工作流的圖示。
- (驗證)有真資料的桌面截圖前 500 格左右是啟動畫面:`ANYBOT_SHOT_FRAMES` 至少 520;側邊欄多了按鈕時,最上面那排的座標會往左移。

View File

@ -7,13 +7,13 @@
- `workflow-canvas` 畫布:左上是名稱,按下去是選單(每個工作流和它的步驟數、新建工作流、版本歷史、重新命名、建立副本、刪除工作流);右上「聊天」(聊天放在旁邊或收起來)、「執行紀錄」、「▷ 執行工作流」(跑的時候變「■ 停止」)。點點底的畫布拖曳空白處移動、⌘+滾輪或捏合縮放;下面工具列「選取、拖曳|畫筆、便利貼、形狀、文字|搜尋|+ 新增節點」,左下「- 百分比 +|符合畫面|小地圖」。搜尋卡片和註解的字,Enter 跳到下一個。視窗窄時縮放列移到工具列上面。 - `workflow-canvas` 畫布:左上是名稱,按下去是選單(每個工作流和它的步驟數、新建工作流、版本歷史、重新命名、建立副本、刪除工作流);右上「聊天」(聊天放在旁邊或收起來)、「執行紀錄」、「▷ 執行工作流」(跑的時候變「■ 停止」)。點點底的畫布拖曳空白處移動、⌘+滾輪或捏合縮放;下面工具列「選取、拖曳|畫筆、便利貼、形狀、文字|搜尋|+ 新增節點」,左下「- 百分比 +|符合畫面|小地圖」。搜尋卡片和註解的字,Enter 跳到下一個。視窗窄時縮放列移到工具列上面。
- `workflow-nodes` 卡片:觸發器(手動,或每天、每週…的排程,寫「下次執行」,有「立即執行」)、Bot 步驟(哪個 Bot、要它做什麼)、等你確認(問你的話)、檢查(哪個 Bot、要做到什麼才通過)、交付(結果放進哪個 Bot 的聊天)、通知你(「{結果}」換成上一步結果的第一行)。從卡片底下的點拉到另一張卡就連線;不能連回觸發器、不能繞成一圈。點卡片在右邊改設定;Delete 刪掉選到的卡片或線(觸發器刪不掉)。 - `workflow-nodes` 卡片:觸發器(手動,或每天、每週…的排程,寫「下次執行」,有「立即執行」)、Bot 步驟(哪個 Bot、要它做什麼)、等你確認(問你的話)、檢查(哪個 Bot、要做到什麼才通過)、交付(結果放進哪個 Bot 的聊天)、通知你(「{結果}」換成上一步結果的第一行)。從卡片底下的點拉到另一張卡就連線;不能連回觸發器、不能繞成一圈。點卡片在右邊改設定;Delete 刪掉選到的卡片或線(觸發器刪不掉)。
- `workflow-draw` 畫和註解:畫筆、便利貼(六種顏色,下面寫誰貼的,雙擊改字)、形狀、文字;點選後右邊換顏色、改文字、刪除。只是給人看,不會執行。 - `workflow-draw` 畫和註解:畫筆、便利貼(六種顏色,下面寫誰貼的,雙擊改字)、形狀、文字;點選後右邊換顏色、改文字、刪除。只是給人看,不會執行。
- `workflow-run` 執行:照線從觸發器往下走(一張接到好幾張時,上面的先,再左邊)。Bot 步驟是那個 Bot 聊天裡的一則訊息「[工作流「名稱」第 k/n 步]…」加上上一步的結果,它這一輪最後的回答就是這一步的結果;它正忙就排在後面,等它做完手上那一輪。檢查要回「通過」才往下,否則停下並寫原因。等你確認:畫布上方一條「等你確認:…」,「繼續」/「停止」,並發通知(電腦和手機)。交付把結果放進那個 Bot 的聊天;通知你發通知。一次只跑一個;排程到了自動跑。卡片上標完成、進行中、等你確認、失敗;「執行紀錄」留最近 20 次(誰開始的、每一步的結果、為什麼停)。 - `workflow-run` 執行:照線從觸發器往下走(一張接到好幾張時,上面的先,再左邊)。Bot 步驟是那個 Bot 聊天裡的一則訊息「[工作流「名稱」第 k/n 步]…」加上上一步的結果,它這一輪最後的回答就是這一步的結果;它正忙就排在後面,等它做完手上那一輪。檢查要回「通過」才往下,否則停下並寫原因。等你確認:畫布上方一條「等你確認:…」,「繼續」/「停止」,並發通知(電腦和手機)。交付把結果放進那個 Bot 的聊天(它正在回答時,等這一輪結束才放);通知你發通知。一次只跑一個;排程到了自動跑。停止時,還排在 Bot 後面的那一步問題直接拿掉,不會停掉 Bot 手上別的事。卡片上標完成、進行中、等你確認、失敗;「執行紀錄」留最近 20 次(誰開始的、每一步的結果、為什麼停)。
- `workflow-chat` 聊出來:在聊天裡請 Bot 做工作流,它用 `workflow` 工具建立、看、改(加步驟、改內容、刪步驟、連線、貼便利貼、整理排版)、執行、停止、刪除(刪除先問你)。你正看著那個 Bot 的聊天時,畫布自動開在聊天旁邊,跳到那個工作流,它改到的卡片和便利貼亮一下;跑出畫面就自動縮放到看得到全部。Bot 做的排成一欄,插在中間時後面的往下移;你自己排過的不重排。旁邊的聊天跟著側邊欄選的 Bot 換。 - `workflow-chat` 聊出來:在聊天裡請 Bot 做工作流,它用 `workflow` 工具建立、看、改(加步驟、改內容、刪步驟、連線、貼便利貼、整理排版)、執行、停止、刪除(刪除先問你)。你正看著那個 Bot 的聊天時(只有它),畫布自動開在聊天旁邊,跳到那個工作流,它改到的卡片和便利貼亮一下;跑出畫面就自動縮放到看得到全部。Bot 做的排成一欄,插在中間時後面的往下移;你自己排過的不重排。要刪除時,允許卡片寫的就是會刪的那一個(沒指定時是畫布上開著的)。旁邊的聊天跟著側邊欄選的 Bot 換。
- `workflow-versions` 版本歷史:改完停手 20 秒、關掉畫布、每次執行前、Bot 每次改之前,各留一版(一樣的不重複留),最多 30 版;選單 › 版本歷史點一版就還原,還原前先留目前的樣子。 - `workflow-versions` 版本歷史:改完停手 20 秒、關掉畫布、每次執行前、Bot 每次改之前,各留一版(一樣的不重複留),最多 30 版;選單 › 版本歷史點一版就還原,還原前先留目前的樣子。
## 使用者怎麼到 ## 使用者怎麼到
- 側邊欄最上面一排第二個(流程圖示,滑過寫「工作流」),在所有檔案和任務中間;再按一次回到聊天。左上「‹ 聊天」也回到聊天。 - 側邊欄最上面一排第二個(流程圖示,滑過寫「工作流」),在所有檔案和日程中間;再按一次回到聊天。左上「‹ 聊天」也回到聊天。
- 在 Bot 的聊天裡說「幫我做一個…的工作流」:畫布開在聊天旁邊(視窗夠寬時;右上「聊天」收起或放回)。 - 在 Bot 的聊天裡說「幫我做一個…的工作流」:畫布開在聊天旁邊(視窗夠寬時;右上「聊天」收起或放回)。
- 手機沒有畫布:在聊天裡請 Bot 做、改、跑,它用文字說工作流長怎樣;「等你確認」的通知會到手機,但要在電腦上按「繼續」。 - 手機沒有畫布:在聊天裡請 Bot 做、改、跑,它用文字說工作流長怎樣;「等你確認」的通知會到手機,但要在電腦上按「繼續」。
@ -38,7 +38,9 @@
- 沒接上觸發器的卡片不會執行;Bot 的回答會寫「沒接上觸發器的(不會執行)」。 - 沒接上觸發器的卡片不會執行;Bot 的回答會寫「沒接上觸發器的(不會執行)」。
- Bot 步驟用那個 Bot 自己的聊天:它正忙(例如就是它叫開始的那一輪),第一步排在後面,等那一輪結束才問。 - Bot 步驟用那個 Bot 自己的聊天:它正忙(例如就是它叫開始的那一輪),第一步排在後面,等那一輪結束才問。
- 檢查的回答要以「通過」或「不通過:原因」開頭,看不出來算失敗。 - 檢查的回答要以「通過」或「不通過:原因」開頭,看不出來算失敗。
- 改正在跑的工作流:那次照開始時的步驟走,刪掉的步驟輪到時會停下來。 - 改正在跑的工作流:那次照開始時的步驟走,刪掉的步驟輪到時會停下來(新加的步驟不會用到刪掉的編號)。
- AnyBot 關掉時正在跑的那次:再開時標成失敗「AnyBot 在執行中被關掉,這一步可能做到一半」;停在等你確認的那次留著。還在等你確認時排程到了,不會再開一次。
- 步驟的 Bot 在做的時候被刪掉:那次停下來,寫「這一步的 Bot 已經不在了」。
- 螢幕電腦只能看:工作流在大腦上改和跑。 - 螢幕電腦只能看:工作流在大腦上改和跑。
- (驗證)有真資料的桌面截圖前 500 格左右是啟動畫面:`ANYBOT_SHOT_FRAMES` 至少 520。 - (驗證)有真資料的桌面截圖前 500 格左右是啟動畫面:`ANYBOT_SHOT_FRAMES` 至少 520。
- (驗證)假模型的回答不是「通過」開頭:跑到檢查之前先 `$CTL model-reply '步・檢查' '通過'`。 - (驗證)假模型的回答不是「通過」開頭:跑到檢查之前先 `$CTL model-reply '步・檢查' '通過'`。

View File

@ -47,6 +47,7 @@ mod activity_ui;
mod library_ui; mod library_ui;
mod market_ui; mod market_ui;
mod workflow_run; mod workflow_run;
mod schedule_ui;
mod workflow_ui; mod workflow_ui;
mod settings_find; mod settings_find;
mod memory_ui; mod memory_ui;
@ -361,6 +362,8 @@ pub struct App {
market: market_ui::MarketUi, market: market_ui::MarketUi,
/// 工作流: the canvas and the runs it drives (workflow_ui.rs, workflow_run.rs). /// 工作流: the canvas and the runs it drives (workflow_ui.rs, workflow_run.rs).
wf: workflow_ui::WfUi, wf: workflow_ui::WfUi,
/// 日程 (schedule_ui.rs).
sched: schedule_ui::SchedUi,
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.
@ -516,6 +519,12 @@ impl App {
cut = true; cut = true;
} }
} }
// 工作流: a run with a bot's step underway ends as interrupted (its question was only
// in memory; left as it was it never ended, and its schedule never ran again).
let now = crate::routines::now();
for w in state.workflows.iter_mut() {
cut |= w.mark_interrupted(now);
}
if found.changed || cut { if found.changed || cut {
state.save(); state.save();
} }
@ -634,6 +643,7 @@ impl App {
lib: Default::default(), lib: Default::default(),
market: Default::default(), market: Default::default(),
wf: Default::default(), wf: Default::default(),
sched: Default::default(),
drop_last: String::new(), drop_last: String::new(),
nightly_checked: None, nightly_checked: None,
att: Default::default(), att: Default::default(),
@ -764,6 +774,15 @@ impl App {
Ok("market") => app.market.open = true, Ok("market") => app.market.open = true,
// 工作流: a sample on the canvas. // 工作流: a sample on the canvas.
Ok("workflow") => app.wf_demo(), Ok("workflow") => app.wf_demo(),
// 日程: a sample week (ANYBOT_SHOT_TAB=day|month for the other views).
Ok("schedule") => {
app.sched_demo();
app.sched.span = match std::env::var("ANYBOT_SHOT_TAB").as_deref() {
Ok("day") => schedule_ui::Span::Day,
Ok("month") => schedule_ui::Span::Month,
_ => schedule_ui::Span::Week,
};
}
// 在哪一台 (bottom left): signed in, a screen of 雲端大腦, another brain off. (An // 在哪一台 (bottom left): signed in, a screen of 雲端大腦, another brain off. (An
// account server that refuses at once; the screen's copy in a temp folder.) // account server that refuses at once; the screen's copy in a temp folder.)
Ok("whose") => { Ok("whose") => {
@ -1414,6 +1433,15 @@ impl App {
Ok("market") => app.market.open = true, Ok("market") => app.market.open = true,
// 工作流: the real ones on the canvas (the chat beside it). // 工作流: the real ones on the canvas (the chat beside it).
Ok("workflow") => app.wf_open(), Ok("workflow") => app.wf_open(),
// 日程: the real routines and workflows.
Ok("schedule") => {
app.sched_open();
app.sched.span = match std::env::var("ANYBOT_SHOT_TAB").as_deref() {
Ok("day") => schedule_ui::Span::Day,
Ok("month") => schedule_ui::Span::Month,
_ => schedule_ui::Span::Week,
};
}
Ok("computers") => { Ok("computers") => {
app.show_settings = true; app.show_settings = true;
app.settings_tab = SettingsTab::Computers; app.settings_tab = SettingsTab::Computers;
@ -3334,6 +3362,19 @@ impl App {
continue; continue;
} }
} }
} else if call.name == crate::workflow::TOOL {
// 工作流: which one the call is about is settled now — the card names the one
// that changes, even if the canvas moves while it waits.
match crate::workflow::pin_target(&self.state.workflows, &call.args, self.wf.open.then_some(self.wf.current)) {
Ok(args) => {
call.args = args;
appctl::needs_approval(&call.name, &call.args, &self.state)
}
Err(e) => {
let _ = call.reply.send((e, false));
continue;
}
}
} else if call.name == crate::hooks::MANAGE_TOOL { } else if call.name == crate::hooks::MANAGE_TOOL {
// Hooks: run outside the sandbox as the person — every change shown and asked. // Hooks: run outside the sandbox as the person — every change shown and asked.
match crate::hooks::parse_change(&call.args) { match crate::hooks::parse_change(&call.args) {
@ -4084,6 +4125,11 @@ impl App {
fn main_pane(&mut self, root: &mut egui::Ui) { fn main_pane(&mut self, root: &mut egui::Ui) {
let p = self.pal; let p = self.pal;
// 日程: every bot's routines and scheduled workflows on a calendar (schedule_ui.rs).
if self.sched.open {
egui::CentralPanel::default().frame(Frame::new().fill(p.pane)).show(root, |ui| self.schedule_pane(ui));
return;
}
// 工作流: the canvas where the chat is (workflow_ui.rs), with the chat beside it — what // 工作流: the canvas where the chat is (workflow_ui.rs), with the chat beside it — what
// the person asks the bot there, they see change on the canvas. // the person asks the bot there, they see change on the canvas.
if self.wf.open { if self.wf.open {

View File

@ -176,6 +176,23 @@ fn scenes() -> Vec<(&'static str, Open)> {
// 工作流: the canvas waiting at its confirm; a step's side panel; the run log; a very long // 工作流: the canvas waiting at its confirm; a step's side panel; the run log; a very long
// name with long words in every card. // name with long words in every card.
("工作流", Box::new(|a: &mut App| a.wf_demo())), ("工作流", Box::new(|a: &mut App| a.wf_demo())),
// 日程: a week, a month, a day of a sample with runs, a paused one and a workflow.
("日程 › 週", Box::new(|a: &mut App| a.sched_demo())),
(
"日程 › 月",
Box::new(|a: &mut App| {
a.sched_demo();
a.sched.span = schedule_ui::Span::Month;
}),
),
(
"日程 › 日",
Box::new(|a: &mut App| {
a.sched_demo();
a.sched.span = schedule_ui::Span::Day;
a.sched.day = Some(crate::schedule::day_of(crate::routines::now() + 86_400, &a.state.timezone.clone()));
}),
),
( (
"工作流 › 一個 Bot 步驟", "工作流 › 一個 Bot 步驟",
Box::new(|a: &mut App| { Box::new(|a: &mut App| {

572
src/app/schedule_ui.rs Normal file
View File

@ -0,0 +1,572 @@
// 日程 (laid out like OpenBot's 日程, in AnyBot's own look): what every bot is set to do, on a
// calendar — 日/週/月, ‹ 今天 › to move — with what ran and how it went (✓, ✗) and what is
// coming (a dot; paused ones greyed), and 即將執行 under it: the next few across every bot, each
// with the bot's face. One picked opens a card: when, how it repeats, how it last went, and
// 打開聊天, 立即執行, 暫停/繼續 (a workflow: 打開工作流, 立即執行). New ones are made by asking
// a bot in its chat (+ puts a start in the message box). The times are the person's time zone.
use super::*;
use crate::icons::Icon;
use crate::schedule::{self, Item, Status, What};
use chrono::{Datelike, Duration, NaiveDate};
use egui::Rect;
#[derive(Default, Clone, Copy, PartialEq, Eq, Debug)]
pub(super) enum Span {
Day,
#[default]
Week,
Month,
}
#[derive(Default)]
pub(super) struct SchedUi {
pub open: bool,
pub span: Span,
/// The day in view (None: today).
pub day: Option<NaiveDate>,
/// The entry whose card is open.
pub picked: Option<Item>,
/// The chat that showed when it opened (another one picked goes back to the chats).
pub chat_was: u64,
}
/// How many entries a day of the month shows before 「還有 N 個」.
const MONTH_SHOWN: usize = 3;
const GAP: f32 = 8.0;
const COMING_SHOWN: usize = 6;
const WEEKDAYS: [&str; 7] = ["週一", "週二", "週三", "週四", "週五", "週六", "週日"];
fn monday_of(d: NaiveDate) -> NaiveDate {
d - Duration::days(d.weekday().num_days_from_monday() as i64)
}
/// The days a view shows: its first day and how many.
pub(super) fn span_days(span: Span, day: NaiveDate) -> (NaiveDate, i64) {
match span {
Span::Day => (day, 1),
Span::Week => (monday_of(day), 7),
Span::Month => {
let first = day.with_day(1).unwrap_or(day);
let next = if first.month() == 12 { NaiveDate::from_ymd_opt(first.year() + 1, 1, 1) } else { NaiveDate::from_ymd_opt(first.year(), first.month() + 1, 1) }.unwrap_or(first);
let start = monday_of(first);
let weeks = ((next - start).num_days() + 6) / 7;
(start, weeks * 7)
}
}
}
/// The view's name: 「2026年11月」, 「11月16日 – 22日」, 「11月21日 星期六」.
pub(super) fn span_title(span: Span, day: NaiveDate) -> String {
match span {
Span::Day => format!("{}月{}日 {}", day.month(), day.day(), ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"][day.weekday().num_days_from_monday() as usize]),
Span::Week => {
let a = monday_of(day);
let b = a + Duration::days(6);
match (a.year() == b.year(), a.month() == b.month()) {
(true, true) => format!("{}月{}日 – {}日", a.month(), a.day(), b.day()),
(true, false) => format!("{}月{}日 – {}月{}日", a.month(), a.day(), b.month(), b.day()),
_ => format!("{}年{}月{}日 – {}年{}月{}日", a.year(), a.month(), a.day(), b.year(), b.month(), b.day()),
}
}
Span::Month => format!("{}年{}月", day.year(), day.month()),
}
}
/// Where the view goes with ‹ and ›.
fn step(span: Span, day: NaiveDate, by: i64) -> NaiveDate {
match span {
Span::Day => day + Duration::days(by),
Span::Week => day + Duration::days(7 * by),
Span::Month => {
let m = day.year() * 12 + day.month0() as i32 + by as i32;
NaiveDate::from_ymd_opt(m.div_euclid(12), m.rem_euclid(12) as u32 + 1, 1).unwrap_or(day)
}
}
}
/// How an entry stands, in words.
fn status_words(s: Status) -> &'static str {
match s {
Status::Done => "完成",
Status::Failed => "失敗",
Status::Stopped => "停止了",
Status::Running => "執行中",
Status::Coming => "啟用中",
Status::Paused => "已暫停",
}
}
impl App {
pub(super) fn sched_open(&mut self) {
if self.wf.open {
self.wf_close();
}
self.sched.open = true;
self.sched.day = None;
self.sched.chat_was = self.state.selected;
}
/// The mark before an entry: ✓ done, ✗ failed, a dot coming or running, ‖ paused.
fn sched_mark(&self, painter: &egui::Painter, at: egui::Pos2, s: Status) {
let p = self.pal;
let r = Rect::from_center_size(at, vec2(13.0, 13.0));
match s {
Status::Done => crate::icons::paint(painter, r, Icon::Check, p.up),
Status::Failed => crate::icons::paint(painter, r, Icon::Close, p.danger),
Status::Stopped => crate::icons::paint(painter, r, Icon::Stop, p.text3),
Status::Paused => crate::icons::paint(painter, r, Icon::Pause, p.text3),
Status::Coming | Status::Running => {
painter.circle_filled(at, 4.0, p.accent);
}
}
}
fn sched_avatar(&self, painter: &egui::Painter, rect: Rect, bot: u64) {
if let Some(b) = self.state.bot(bot) {
crate::avatar::paint(painter, rect, &b.shape, self.bot_color(b));
} else {
crate::icons::paint(painter, rect.shrink(2.0), Icon::Workflow, self.pal.text2);
}
}
/// One entry as a line (a day of the month, 即將執行, a day): mark, time, title; the bot's face
/// at the right when there is room. A press opens its card.
fn sched_line(&mut self, ui: &mut egui::Ui, rect: Rect, it: &Item, words: &str, size: f32, face: bool) {
let p = self.pal;
let resp = ui.interact(rect, egui::Id::unique(("sched-line", it.what, it.at, rect.min.y as i32, rect.min.x as i32)), egui::Sense::click());
if resp.hovered() {
ui.painter().rect_filled(rect, R_M, p.hover);
ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
}
self.sched_mark(ui.painter(), egui::pos2(rect.min.x + 12.0, rect.center().y), it.status);
let face_w = if face { rect.height().min(26.0) + 8.0 } else { 0.0 };
let colour = if matches!(it.status, Status::Paused | Status::Stopped) { p.text3 } else { p.text };
let room = rect.width() - 26.0 - face_w - 6.0;
let text = sidebar_ui::shorten_width(ui, words, room.max(10.0), size);
ui.painter().text(egui::pos2(rect.min.x + 24.0, rect.center().y), egui::Align2::LEFT_CENTER, text, egui::FontId::proportional(size), colour);
if face {
let s = rect.height().min(26.0) - 4.0;
self.sched_avatar(ui.painter(), Rect::from_center_size(egui::pos2(rect.max.x - 6.0 - s / 2.0, rect.center().y), vec2(s, s)), it.bot);
}
if resp.on_hover_text(format!("{} · {} · {}", it.title, it.when, t(status_words(it.status)))).clicked() {
self.sched.picked = Some(it.clone());
}
}
/// One entry in a day of the week: the mark, its time and the bot's face; its title under them.
fn sched_block(&mut self, ui: &mut egui::Ui, rect: Rect, it: &Item, tz: &str) {
let p = self.pal;
let resp = ui.interact(rect, egui::Id::unique(("sched-block", it.what, it.at)), egui::Sense::click());
if resp.hovered() {
ui.painter().rect_filled(rect, R_M, p.hover);
ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
}
let top = rect.min.y + 13.0;
self.sched_mark(ui.painter(), egui::pos2(rect.min.x + 12.0, top), it.status);
ui.painter().text(egui::pos2(rect.min.x + 24.0, top), egui::Align2::LEFT_CENTER, schedule::clock(it.at, tz), egui::FontId::proportional(FONT_XS), p.text2);
if rect.width() > 90.0 {
self.sched_avatar(ui.painter(), Rect::from_center_size(egui::pos2(rect.max.x - 13.0, top), vec2(18.0, 18.0)), it.bot);
}
let colour = if matches!(it.status, Status::Paused | Status::Stopped) { p.text3 } else { p.text };
let title = sidebar_ui::shorten_width(ui, &it.title, (rect.width() - 20.0).max(10.0), FONT_SM);
ui.painter().text(egui::pos2(rect.min.x + 8.0, rect.min.y + 34.0), egui::Align2::LEFT_CENTER, title, egui::FontId::proportional(FONT_SM), colour);
if resp.on_hover_text(format!("{} · {} · {}", it.title, it.when, t(status_words(it.status)))).clicked() {
self.sched.picked = Some(it.clone());
}
}
/// 日程: where the chat was.
pub(super) fn schedule_pane(&mut self, ui: &mut egui::Ui) {
let p = self.pal;
// Another chat picked in the sidebar: back to the chats.
if self.state.selected != self.sched.chat_was {
self.sched.open = false;
return;
}
let ctx = ui.ctx().clone();
let tz = self.state.timezone.clone();
let now = crate::routines::now();
let today = schedule::day_of(now, &tz);
let day = self.sched.day.unwrap_or(today);
let span = self.sched.span;
let (first, n) = span_days(span, day);
let (from, to) = (schedule::day_start(first, &tz), schedule::day_start(first + Duration::days(n), &tz));
let items = schedule::items(&self.state, from, to, now);
// ── The top: back, 日程, the time zone ──
let full = ui.available_rect_before_wrap();
let top = Rect::from_min_size(full.min, vec2(full.width(), 52.0));
ui.scope_builder(egui::UiBuilder::new().max_rect(top.shrink2(vec2(16.0, 0.0))), |ui| {
ui.horizontal_centered(|ui| {
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
ui.add(egui::Label::new(RichText::new(format!("{} {tz} {}", t("時間以"), t("為準"))).size(FONT_SM).color(p.text3)).truncate());
ui.with_layout(Layout::left_to_right(Align::Center), |ui| {
if ui.add(egui::Button::new(RichText::new(format!("‹ {}", t("聊天"))).size(FONT_SM).color(p.text2)).frame(false)).on_hover_text(t("回到聊天")).clicked() {
self.sched.open = false;
}
ui.add_space(6.0);
ui.label(RichText::new(t("日程")).size(FONT_BASE).family(crate::bold()).color(p.text));
});
});
});
});
ui.painter().hline(full.x_range(), top.max.y, Stroke::new(1.0, p.border));
let body = Rect::from_min_max(egui::pos2(full.min.x, top.max.y + 1.0), full.max);
ui.scope_builder(egui::UiBuilder::new().max_rect(body), |ui| {
egui::ScrollArea::vertical().id_salt("schedule").auto_shrink([false, false]).show(ui, |ui| {
// (Room at the left and right: 留天地.)
let side = if ui.available_width() > 900.0 { 32.0 } else { 20.0 };
ui.add_space(16.0);
ui.horizontal(|ui| {
ui.add_space(side);
ui.vertical(|ui| {
ui.set_width(ui.available_width() - side);
self.sched_bar(ui, span, day, today);
ui.add_space(12.0);
match span {
Span::Month => self.sched_month(ui, first, n, day, today, &items, &tz),
Span::Week => self.sched_week(ui, first, today, &items, &tz),
Span::Day => self.sched_day(ui, &items, &tz),
}
ui.add_space(18.0);
self.sched_coming(ui, now, &tz);
ui.add_space(24.0);
});
});
});
});
ui.allocate_rect(full, egui::Sense::hover());
self.sched_card(&ctx);
}
/// ‹ 今天 › and the view's name; 日/週/月 at the right.
fn sched_bar(&mut self, ui: &mut egui::Ui, span: Span, day: NaiveDate, today: NaiveDate) {
let p = self.pal;
ui.horizontal(|ui| {
if ui.add(egui::Button::new(RichText::new("‹").size(FONT_H3).color(p.text2)).frame(false).min_size(vec2(28.0, 28.0))).on_hover_text(t("往前")).clicked() {
self.sched.day = Some(step(span, day, -1));
}
let on_today = span_days(span, day) == span_days(span, today);
if ui.add_enabled(!on_today, secondary_button("今天")).clicked() {
self.sched.day = None;
}
if ui.add(egui::Button::new(RichText::new("›").size(FONT_H3).color(p.text2)).frame(false).min_size(vec2(28.0, 28.0))).on_hover_text(t("往後")).clicked() {
self.sched.day = Some(step(span, day, 1));
}
// (日/週/月 first, at the right; the view's name in what is left, cut short.)
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if let Some(s) = segmented(ui, p, span, &[(Span::Day, "日"), (Span::Week, "週"), (Span::Month, "月")]) {
self.sched.span = s;
}
ui.with_layout(Layout::left_to_right(Align::Center), |ui| {
ui.add_space(8.0);
ui.add(egui::Label::new(RichText::new(span_title(span, day)).size(FONT_H3).family(crate::bold()).color(p.text)).truncate());
});
});
});
}
/// 月: a grid of the weeks, a few entries a day and 「還有 N 個」 (a press on the day opens it).
#[allow(clippy::too_many_arguments)]
fn sched_month(&mut self, ui: &mut egui::Ui, first: NaiveDate, n: i64, day: NaiveDate, today: NaiveDate, items: &[Item], tz: &str) {
let p = self.pal;
let w = ui.available_width();
let col = ((w - GAP * 6.0) / 7.0).max(40.0);
let (head, _) = ui.allocate_exact_size(vec2(w, 22.0), egui::Sense::hover());
for (i, d) in WEEKDAYS.iter().enumerate() {
ui.painter().text(egui::pos2(head.min.x + i as f32 * (col + GAP) + 10.0, head.center().y), egui::Align2::LEFT_CENTER, t(d), egui::FontId::proportional(FONT_XS), p.text3);
}
let line_h = 22.0;
let cell_h = 34.0 + MONTH_SHOWN as f32 * line_h + 32.0;
for week in 0..(n / 7) {
let (row, _) = ui.allocate_exact_size(vec2(w, cell_h), egui::Sense::hover());
for i in 0..7 {
let d = first + Duration::days(week * 7 + i);
let cell = Rect::from_min_size(egui::pos2(row.min.x + i as f32 * (col + GAP), row.min.y), vec2(col, cell_h - GAP));
let ours = d.month() == day.month();
let is_today = d == today;
let resp = ui.interact(cell, egui::Id::unique(("sched-day", d)), egui::Sense::click());
ui.painter().rect_filled(cell, R_L, if resp.hovered() { p.hover } else { p.elevated });
ui.painter().rect_stroke(cell, R_L, Stroke::new(if is_today { 1.5 } else { 1.0 }, if is_today { p.accent } else { p.border }), egui::StrokeKind::Inside);
let num = format!("{}{}", d.day(), t("日"));
ui.painter().text(
cell.min + vec2(12.0, 17.0),
egui::Align2::LEFT_CENTER,
num,
egui::FontId::new(FONT_SM, crate::bold()),
if is_today {
p.accent
} else if ours {
p.text
} else {
p.text3
},
);
let todays: Vec<&Item> = items.iter().filter(|x| schedule::day_of(x.at, tz) == d).collect();
for (k, it) in todays.iter().take(MONTH_SHOWN).enumerate() {
let r = Rect::from_min_size(egui::pos2(cell.min.x + 4.0, cell.min.y + 32.0 + k as f32 * line_h), vec2(col - 8.0, line_h - 2.0));
let words = format!("{} {}", schedule::clock(it.at, tz), it.title);
self.sched_line(ui, r, it, &words, FONT_XS, false);
}
if todays.len() > MONTH_SHOWN {
let more = format!("{} {} {}", t("還有"), todays.len() - MONTH_SHOWN, t("個"));
ui.painter().text(egui::pos2(cell.min.x + 12.0, cell.min.y + 32.0 + MONTH_SHOWN as f32 * line_h + 8.0), egui::Align2::LEFT_CENTER, more, egui::FontId::proportional(FONT_XS), p.text3);
}
if resp.clicked() {
self.sched.day = Some(d);
self.sched.span = Span::Day;
}
}
}
}
/// 週: seven columns, each entry its time, the bot's face and its title.
fn sched_week(&mut self, ui: &mut egui::Ui, first: NaiveDate, today: NaiveDate, items: &[Item], tz: &str) {
let p = self.pal;
let w = ui.available_width();
let col = ((w - GAP * 6.0) / 7.0).max(40.0);
let per = 50.0;
let most = (0..7).map(|i| items.iter().filter(|x| schedule::day_of(x.at, tz) == first + Duration::days(i)).count()).max().unwrap_or(0);
let h = (48.0 + most as f32 * per + 12.0).max(220.0);
let (row, _) = ui.allocate_exact_size(vec2(w, h), egui::Sense::hover());
for i in 0..7 {
let d = first + Duration::days(i);
let cell = Rect::from_min_size(egui::pos2(row.min.x + i as f32 * (col + GAP), row.min.y), vec2(col, h));
let is_today = d == today;
ui.painter().rect_filled(cell, R_L, p.elevated);
ui.painter().rect_stroke(cell, R_L, Stroke::new(if is_today { 1.5 } else { 1.0 }, if is_today { p.accent } else { p.border }), egui::StrokeKind::Inside);
let head = sidebar_ui::shorten_width(ui, &format!("{} {}{}", t(WEEKDAYS[i as usize]), d.day(), t("日")), col - 20.0, FONT_SM);
ui.painter().text(cell.min + vec2(12.0, 22.0), egui::Align2::LEFT_CENTER, head, egui::FontId::new(FONT_SM, crate::bold()), if is_today { p.accent } else { p.text });
let head_r = Rect::from_min_size(cell.min, vec2(col, 40.0));
if ui.interact(head_r, egui::Id::unique(("sched-week-day", d)), egui::Sense::click()).on_hover_text(t("看這一天")).clicked() {
self.sched.day = Some(d);
self.sched.span = Span::Day;
}
for (k, it) in items.iter().filter(|x| schedule::day_of(x.at, tz) == d).enumerate() {
let r = Rect::from_min_size(egui::pos2(cell.min.x + 4.0, cell.min.y + 44.0 + k as f32 * per), vec2(col - 8.0, per - 4.0));
self.sched_block(ui, r, it, tz);
}
}
}
/// 日: the day's entries by the hour, with how each repeats.
fn sched_day(&mut self, ui: &mut egui::Ui, items: &[Item], tz: &str) {
let p = self.pal;
if items.is_empty() {
ui.label(RichText::new(t("這一天沒有排定的事。")).size(FONT_SM).color(p.text2));
}
let w = ui.available_width();
for it in items {
let (row, _) = ui.allocate_exact_size(vec2(w, 52.0), egui::Sense::hover());
ui.painter().hline(row.x_range(), row.max.y, Stroke::new(1.0, p.border));
let hour = format!("{} {}", schedule::clock(it.at, tz).split(':').next().unwrap_or(""), t("時"));
ui.painter().text(egui::pos2(row.min.x + 4.0, row.center().y), egui::Align2::LEFT_CENTER, hour, egui::FontId::proportional(FONT_SM), p.text3);
let r = Rect::from_min_max(egui::pos2(row.min.x + 70.0, row.min.y + 4.0), egui::pos2(row.max.x, row.max.y - 4.0));
let words = format!("{} · {} · {} · {}", it.title, schedule::clock(it.at, tz), it.when, t(status_words(it.status)));
self.sched_line(ui, r, it, &words, FONT_SM, true);
}
}
/// +: new ones are made by asking a bot (its message box gets a start).
fn sched_new(&mut self, ui: &mut egui::Ui) {
let p = self.pal;
if ui.add(egui::Button::new(RichText::new(format!("+ {}", t("新增例行任務"))).size(FONT_SM).color(p.text2)).frame(false)).on_hover_text(t("在聊天裡告訴 Bot 什麼時候要做什麼")).clicked() {
let bot = if self.state.bot(self.state.selected).is_some() { self.state.selected } else { self.state.primary_bot };
self.drafts.entry(bot).or_default().push_str(&t("每天早上 9 點幫我"));
self.state.selected = bot;
self.sched.open = false;
}
}
/// 即將執行: the next few across every bot.
fn sched_coming(&mut self, ui: &mut egui::Ui, now: i64, tz: &str) {
let p = self.pal;
let next = schedule::coming(&self.state, now, COMING_SHOWN);
setting_card(ui, p, |ui| {
ui.label(RichText::new(t("即將執行")).size(FONT_SM).color(p.text2));
ui.add_space(4.0);
if next.is_empty() {
ui.label(RichText::new(t("接下來兩週沒有排定的事。在聊天裡請 Bot 設一個例行任務,例如「每個工作日早上 9 點整理新聞給我」。")).size(FONT_SM).color(p.text3));
}
let w = ui.available_width();
for it in &next {
let (row, _) = ui.allocate_exact_size(vec2(w, 40.0), egui::Sense::hover());
let words = format!("{} · {} · {}", it.title, crate::routines::describe_when(it.at, tz), it.when);
self.sched_line(ui, row, it, &words, FONT_SM, true);
}
});
self.sched_new(ui);
}
/// The card of the entry picked: when, how it repeats, how it last went; what can be done.
fn sched_card(&mut self, ctx: &egui::Context) {
let Some(it) = self.sched.picked.clone() else { return };
let p = self.pal;
let tz = self.state.timezone.clone();
let mut act: Option<&str> = None;
let routine = match it.what {
What::Routine { bot, id } => self.state.bot(bot).and_then(|b| b.routines.iter().find(|r| r.id == id)).cloned(),
What::Workflow { .. } => None,
};
let workflow = match it.what {
What::Workflow { id } => self.state.workflows.iter().find(|w| w.id == id).cloned(),
What::Routine { .. } => None,
};
if routine.is_none() && workflow.is_none() {
self.sched.picked = None;
return;
}
let who = self.state.bot(it.bot).map(|b| b.name.clone()).unwrap_or_default();
let body_h = dialog_max_height(ctx) - 48.0;
let dismissed = dialog(ctx, "sched-card", &it.title, 440.0, true, p, |ui| {
dialog_body(ui, "sched-card-body", body_h, |ui| {
ui.horizontal(|ui| {
let (r, _) = ui.allocate_exact_size(vec2(28.0, 28.0), egui::Sense::hover());
self.sched_avatar(ui.painter(), r, it.bot);
ui.label(RichText::new(if workflow.is_some() { format!("{} · {}", t("工作流"), who) } else { who.clone() }).size(FONT_SM).color(p.text2));
});
ui.add_space(6.0);
let when = format!("{}({})", crate::routines::describe_when(it.at, &tz), t(status_words(it.status)));
ui.label(RichText::new(when).size(FONT_BASE).color(p.text));
ui.label(RichText::new(&it.when).size(FONT_SM).color(p.text2));
if let Some(r) = &routine {
if r.paused && !r.paused_why.is_empty() {
ui.label(RichText::new(&r.paused_why).size(FONT_XS).color(p.attention));
}
if let Some(last) = r.runs.last() {
ui.label(RichText::new(format!("{}{}", t("最近:"), crate::routines::describe_run(last, &tz))).size(FONT_XS).color(p.text3));
}
hint(ui, r.prompt.clone(), p);
}
if let Some(w) = &workflow {
ui.label(RichText::new(format!("{} {}", w.step_count(), t("個步驟"))).size(FONT_SM).color(p.text2));
if let Some(r) = w.runs.last() {
ui.label(RichText::new(format!("{}{}", t("最近:"), crate::workflow::describe_run(r))).size(FONT_XS).color(p.text3));
}
}
ui.add_space(8.0);
ui.horizontal(|ui| {
if workflow.is_some() {
if ui.add(primary_button("打開工作流", p)).clicked() {
act = Some("open");
}
} else if ui.add(primary_button("打開聊天", p)).clicked() {
act = Some("chat");
}
if ui.add(secondary_button("立即執行")).clicked() {
act = Some("run");
}
if let Some(r) = &routine {
if r.trigger.is_none() && ui.add(secondary_button(if r.paused { "繼續" } else { "暫停" })).clicked() {
act = Some("toggle");
}
}
});
})
});
if dismissed {
self.sched.picked = None;
}
let Some(a) = act else { return };
self.sched.picked = None;
match (it.what, a) {
(What::Routine { bot, .. }, "chat") => {
self.state.selected = bot;
self.sched.open = false;
}
(What::Routine { bot, id }, "run" | "toggle") => self.routine_action(ctx, bot, Some((if a == "run" { "run" } else { "toggle" }, id))),
(What::Workflow { id }, "open") => {
self.sched.open = false;
self.wf.current = id;
self.wf.fitted = 0;
self.wf_open();
}
(What::Workflow { id }, "run") => {
self.wf_start(ctx, id, "手動");
}
_ => {}
}
self.dirty = true;
}
/// A sample week for the picture (ANYBOT_SHOT_VIEW=schedule) and the layout check: a few
/// routines on several bots with how their runs went, a paused one, a scheduled workflow.
pub(super) fn sched_demo(&mut self) {
let tz = self.state.timezone.clone();
let now = crate::routines::now();
let created = now - 20 * 86_400;
let sched = |v: serde_json::Value| -> Option<crate::routines::Schedule> {
let mut v = v;
v["timezone"] = serde_json::json!(tz);
serde_json::from_value(v).ok().and_then(|s| crate::routines::validate(s).ok())
};
let ids: Vec<u64> = self.state.bots.iter().filter(|b| b.branch_of == 0).map(|b| b.id).take(3).collect();
let specs = [
("競品掃描", serde_json::json!({"frequency": "daily", "time": "08:30"}), false),
("晨間發布簡報", serde_json::json!({"frequency": "weekly", "daysOfWeek": ["MO", "TU", "WE", "TH", "FR"], "time": "09:00"}), false),
("週報整理", serde_json::json!({"frequency": "weekly", "daysOfWeek": ["FR"], "time": "17:30"}), true),
];
for (k, (title, s, paused)) in specs.into_iter().enumerate() {
let Some(bot) = ids.get(k % ids.len().max(1)).copied() else { break };
let Some(s) = sched(s) else { continue };
// (What ran these past days, and how.)
let mut runs = vec![];
let mut at = created;
let mut i = 0;
while let Some(t) = crate::routines::next_run(&s, created, at) {
if t >= now {
break;
}
if t > now - 6 * 86_400 {
let outcome = if i % 5 == 3 { crate::routines::RunOutcome::Failed } else { crate::routines::RunOutcome::Succeeded };
runs.push(crate::routines::RoutineRun { started: t, ended: t + 300, outcome, note: String::new(), steps: 4, failed_steps: 0, sent: 0, sends: vec![] });
i += 1;
}
at = t;
}
let id = self.state.next_routine_id;
self.state.next_routine_id += 1;
if let Some(b) = self.state.bot_mut(bot) {
let mut r: crate::routines::Routine = match serde_json::from_value(serde_json::json!({"id": id, "title": title, "prompt": "整理成三點,附來源。", "schedule": s, "created_at": created})) {
Ok(r) => r,
Err(_) => continue,
};
r.paused = paused;
r.runs = runs;
b.routines.push(r);
}
}
self.wf_demo();
self.wf.open = false;
if let Some(w) = self.state.workflows.first_mut() {
w.created_at = created;
w.runs.clear();
}
self.sched_open();
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The days each view shows, its name, and where ‹ › go (a month from Monday to Sunday,
/// whole weeks; a week across two months; December into January).
#[test]
fn the_views_cover_their_days() {
let d = |y, m, dd| NaiveDate::from_ymd_opt(y, m, dd).unwrap();
assert_eq!(span_days(Span::Week, d(2026, 11, 21)), (d(2026, 11, 16), 7));
assert_eq!(span_days(Span::Day, d(2026, 11, 21)), (d(2026, 11, 21), 1));
// (1 Nov 2026 is a Sunday and 30 Nov a Monday: six whole weeks, 26 Oct to 6 Dec.)
assert_eq!(span_days(Span::Month, d(2026, 11, 21)), (d(2026, 10, 26), 42));
assert_eq!(span_days(Span::Month, d(2027, 2, 10)), (d(2027, 2, 1), 28), "February 2027 starts on a Monday");
assert_eq!(span_title(Span::Month, d(2026, 11, 21)), "2026年11月");
assert_eq!(span_title(Span::Week, d(2026, 11, 21)), "11月16日 – 22日");
assert_eq!(span_title(Span::Week, d(2026, 12, 1)), "11月30日 – 12月6日");
assert_eq!(span_title(Span::Day, d(2026, 11, 21)), "11月21日 星期六");
assert_eq!(step(Span::Month, d(2026, 12, 15), 1), d(2027, 1, 1));
assert_eq!(step(Span::Month, d(2026, 1, 31), -1), d(2025, 12, 1));
assert_eq!(step(Span::Week, d(2026, 11, 21), 1), d(2026, 11, 28));
}
}

View File

@ -345,11 +345,20 @@ impl App {
} }
// 任務: every bot's tasks and how each stands (tasks_ui.rs). // 任務: every bot's tasks and how each stands (tasks_ui.rs).
self.tasks_button(ui); self.tasks_button(ui);
// 日程: what every bot is set to do, on a calendar (schedule_ui.rs); again closes it.
if pill_icon(ui, crate::icons::Icon::Calendar, p).on_hover_text(t("日程")).clicked() {
if self.sched.open {
self.sched.open = false;
} else {
self.sched_open();
}
}
// 工作流: the canvas (workflow_ui.rs); again closes it. // 工作流: the canvas (workflow_ui.rs); again closes it.
if pill_icon(ui, crate::icons::Icon::Workflow, p).on_hover_text(t("工作流")).clicked() { if pill_icon(ui, crate::icons::Icon::Workflow, p).on_hover_text(t("工作流")).clicked() {
if self.wf.open { if self.wf.open {
self.wf_close(); self.wf_close();
} else { } else {
self.sched.open = false;
self.wf_open(); self.wf_open();
} }
} }

View File

@ -32,12 +32,21 @@ impl App {
/// Stop this workflow's run (a bot working on its step is stopped too). /// Stop this workflow's run (a bot working on its step is stopped too).
pub(super) fn wf_stop(&mut self, wf: u64) { pub(super) fn wf_stop(&mut self, wf: u64) {
let now = crate::routines::now(); let now = crate::routines::now();
// The step a bot is on: its question still in line comes out of the line (the bot's turn
// now is something else — the person's chat, or the turn that asked to stop); a bot
// working on the question itself is stopped.
let on = self.state.workflows.iter().find(|w| w.id == wf).and_then(|w| w.runs.iter().rev().find(|r| r.live())).and_then(|r| r.current().filter(|s| s.state == StepState::Running && s.bot != 0).map(|s| (s.bot, s.asked_at)));
let mut busy = None; let mut busy = None;
if let Some((bot, at)) = on {
let before = self.waiting_wakes.len();
self.waiting_wakes.retain(|(b, m)| !(*b == bot && m.at == at));
let in_chat = self.state.bot(bot).is_some_and(|b| b.messages.iter().any(|m| m.role == Role::User && m.at == at));
if self.waiting_wakes.len() == before && in_chat {
busy = Some(bot);
}
}
if let Some(r) = self.state.workflows.iter_mut().find(|w| w.id == wf).and_then(|w| w.runs.iter_mut().rev().find(|r| r.live())) { if let Some(r) = self.state.workflows.iter_mut().find(|w| w.id == wf).and_then(|w| w.runs.iter_mut().rev().find(|r| r.live())) {
if let Some(s) = r.order.get(r.at).copied().and_then(|n| r.steps.iter_mut().find(|s| s.node == n)) { if let Some(s) = r.order.get(r.at).copied().and_then(|n| r.steps.iter_mut().find(|s| s.node == n)) {
if s.state == StepState::Running {
busy = Some(s.bot).filter(|b| *b != 0);
}
s.state = StepState::Failed; s.state = StepState::Failed;
} }
r.state = RunState::Stopped; r.state = RunState::Stopped;
@ -141,11 +150,18 @@ impl App {
return; return;
}; };
let text = if last.trim().is_empty() { format!("工作流「{name}」跑完了(前面的步驟沒有結果)。") } else { format!("工作流「{name}」的結果:\n\n{last}") }; let text = if last.trim().is_empty() { format!("工作流「{name}」跑完了(前面的步驟沒有結果)。") } else { format!("工作流「{name}」的結果:\n\n{last}") };
b.messages.push(Message { at: crate::model::now_ms(), ..Message::assistant(&text, &format!("工作流「{name}」")) }); let msg = Message { at: crate::model::now_ms(), ..Message::assistant(&text, &format!("工作流「{name}」")) };
// (A bot answering right now: its reply streams into its last message — the
// result goes in once that turn is over, not in the middle of it.)
if self.streams.contains_key(&bot) {
self.wf.deliveries.push((bot, msg));
} else {
b.messages.push(msg);
if bot != selected { if bot != selected {
b.unread = true; b.unread = true;
} }
self.save_now = true; self.save_now = true;
}
self.wf_done(wf, run_id, node_id, last); self.wf_done(wf, run_id, node_id, last);
} }
NodeKind::Notify { text } => { NodeKind::Notify { text } => {
@ -310,6 +326,31 @@ impl App {
for wf in std::mem::take(&mut self.wf.advance) { for wf in std::mem::take(&mut self.wf.advance) {
self.wf_advance(ctx, wf); self.wf_advance(ctx, wf);
} }
// 交付 that waited for a bot's turn to end.
let selected = self.state.selected;
for (bot, msg) in std::mem::take(&mut self.wf.deliveries) {
if self.streams.contains_key(&bot) {
self.wf.deliveries.push((bot, msg));
} else if let Some(b) = self.state.bot_mut(bot) {
b.messages.push(msg);
if bot != selected {
b.unread = true;
}
self.save_now = true;
}
}
// A step whose bot was deleted while it worked never ends: the run stops, saying why.
let gone: Vec<(u64, u64, u64)> = self
.state
.workflows
.iter()
.flat_map(|w| w.runs.iter().filter(|r| r.state == RunState::Running).filter_map(move |r| r.current().filter(|s| s.state == StepState::Running && s.bot != 0).map(|s| (w.id, r.id, s.node, s.bot))))
.filter(|(_, _, _, bot)| self.state.bot(*bot).is_none())
.map(|(w, r, n, _)| (w, r, n))
.collect();
for (wf, run, node) in gone {
self.wf_fail(wf, run, node, "這一步的 Bot 已經不在了");
}
if self.mir.on { if self.mir.on {
// (A screen shows the brain's; the brain runs them.) // (A screen shows the brain's; the brain runs them.)
return; return;
@ -347,16 +388,8 @@ mod tests {
use super::*; use super::*;
use crate::workflow::{Node, Workflow}; use crate::workflow::{Node, Workflow};
fn app_with(nodes: Vec<(u64, NodeKind)>) -> (egui::Context, App, u64) { /// A turn going on (no model is called here).
let ctx = egui::Context::default(); fn busy() -> Live {
let mut app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-wf.png")));
// (No banners on the machine running the tests.)
app.headless = true;
let bot = app.state.bots[0].id;
// The bot is busy: what a step asks waits in line (no model is called here); the test
// plays the bot's turns.
app.streams.insert(
bot,
Live { Live {
cancel: Arc::new(AtomicBool::new(false)), cancel: Arc::new(AtomicBool::new(false)),
started: Instant::now(), started: Instant::now(),
@ -370,8 +403,18 @@ mod tests {
direct: Arc::new(AtomicBool::new(false)), direct: Arc::new(AtomicBool::new(false)),
turn_id: "t".into(), turn_id: "t".into(),
turn: 0, turn: 0,
}, }
); }
fn app_with(nodes: Vec<(u64, NodeKind)>) -> (egui::Context, App, u64) {
let ctx = egui::Context::default();
let mut app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-wf.png")));
// (No banners on the machine running the tests.)
app.headless = true;
let bot = app.state.bots[0].id;
// The bot is busy: what a step asks waits in line (no model is called here); the test
// plays the bot's turns.
app.streams.insert(bot, busy());
let mut w = Workflow::new(1, "早報", 0); let mut w = Workflow::new(1, "早報", 0);
let mut prev = 1; let mut prev = 1;
for (i, (id, kind)) in nodes.into_iter().enumerate() { for (i, (id, kind)) in nodes.into_iter().enumerate() {
@ -426,6 +469,9 @@ mod tests {
assert_eq!(r.state, RunState::Done, "{r:?}"); assert_eq!(r.state, RunState::Done, "{r:?}");
assert!(r.steps.iter().all(|s| s.state == StepState::Done), "{r:?}"); assert!(r.steps.iter().all(|s| s.state == StepState::Done), "{r:?}");
assert_eq!(r.step_of(3).map(|s| s.output.as_str()), Some("三則新聞:A、B、C"), "a check hands on what it checked"); assert_eq!(r.step_of(3).map(|s| s.output.as_str()), Some("三則新聞:A、B、C"), "a check hands on what it checked");
// (The bot is still answering in this test: the result goes in once that turn is over.)
app.streams.remove(&bot);
app.tick_workflows(&ctx);
let last = app.state.bot(bot).unwrap().messages.last().unwrap(); let last = app.state.bot(bot).unwrap().messages.last().unwrap();
assert_eq!((last.text.as_str(), last.via.as_str()), ("工作流「早報」的結果:\n\n三則新聞:A、B、C", "工作流「早報」")); assert_eq!((last.text.as_str(), last.via.as_str()), ("工作流「早報」的結果:\n\n三則新聞:A、B、C", "工作流「早報」"));
// What was run is kept as a version. // What was run is kept as a version.
@ -525,4 +571,54 @@ mod tests {
let (_, ok) = call(&mut app, serde_json::json!({"action": "stop", "id": 2})); let (_, ok) = call(&mut app, serde_json::json!({"action": "stop", "id": 2}));
assert!(ok && app.state.workflows[1].runs.last().unwrap().state == RunState::Stopped); assert!(ok && app.state.workflows[1].runs.last().unwrap().state == RunState::Stopped);
} }
/// Stopping a run whose question still waits in line for a busy bot takes the question out
/// of the line and leaves the bot's own turn alone; a 交付 while the bot answers waits for
/// that turn; a step whose bot was deleted ends the run; a bot the person isn't looking at
/// doesn't move the canvas.
#[test]
fn stop_deliver_and_gone_bots_leave_the_chats_alone() {
let (ctx, mut app, bot) = app_with(vec![(2, NodeKind::Step { bot: 0, prompt: "查".into() }), (3, NodeKind::Deliver { bot: 0 })]);
for n in app.state.workflows[0].nodes.iter_mut() {
match &mut n.kind {
NodeKind::Step { bot: b, .. } | NodeKind::Deliver { bot: b } => *b = bot,
_ => {}
}
}
assert!(app.wf_start(&ctx, 1, "手動"));
assert!(app.waiting_wakes.iter().any(|(b, _)| *b == bot), "in line behind the bot's turn");
app.wf_stop(1);
assert!(!app.waiting_wakes.iter().any(|(b, _)| *b == bot), "taken out of the line");
assert!(app.streams.contains_key(&bot), "the bot's own turn goes on");
assert_eq!(run(&app).state, RunState::Stopped);
// Again; the bot answers; the 交付 comes while it is still busy with something else.
assert!(app.wf_start(&ctx, 1, "手動"));
let n = app.state.bot(bot).unwrap().messages.len();
answer(&mut app, bot, "三則新聞");
app.tick_workflows(&ctx);
assert_eq!(run(&app).state, RunState::Done);
assert_eq!(app.state.bot(bot).unwrap().messages.len(), n + 2, "the question and the answer only: the result waits");
app.streams.remove(&bot);
app.tick_workflows(&ctx);
assert!(app.state.bot(bot).unwrap().messages.last().unwrap().text.starts_with("工作流「早報」的結果"));
// A bot deleted while on its step.
app.state.bots.push(app.state.bots[0].clone());
let other = app.state.bots.iter().map(|b| b.id).max().unwrap() + 1;
app.state.bots.last_mut().unwrap().id = other;
if let NodeKind::Step { bot: b, .. } = &mut app.state.workflows[0].node_mut(2).unwrap().kind {
*b = other;
}
app.streams.insert(other, busy());
assert!(app.wf_start(&ctx, 1, "手動"));
app.state.bots.retain(|b| b.id != other);
app.streams.remove(&other);
app.tick_workflows(&ctx);
assert_eq!((run(&app).state, run(&app).why.as_str()), (RunState::Failed, "這一步的 Bot 已經不在了"));
// The canvas on workflow 1 beside another bot's chat: a change by this bot doesn't move it.
app.state.selected = other;
app.wf.open = true;
app.wf.current = 1;
app.wf_show_change(bot, 99, vec![]);
assert_eq!(app.wf.current, 1);
}
} }

View File

@ -68,6 +68,8 @@ pub(super) struct WfUi {
pub flash: Option<(u64, Vec<u64>, Instant)>, pub flash: Option<(u64, Vec<u64>, Instant)>,
/// A bot changed it: show what changed if it is out of view. /// A bot changed it: show what changed if it is out of view.
pub reveal: bool, pub reveal: bool,
/// 交付 waiting for its bot's turn to end (its reply streams into its last message).
pub deliveries: Vec<(u64, Message)>,
} }
/// How long what a bot changed stays lit on the canvas. /// How long what a bot changed stays lit on the canvas.
@ -188,15 +190,16 @@ impl App {
/// canvas) sees the canvas beside it, on that workflow, with what changed lit up. /// canvas) sees the canvas beside it, on that workflow, with what changed lit up.
pub(super) fn wf_show_change(&mut self, bot_id: u64, wf: u64, touched: Vec<u64>) { pub(super) fn wf_show_change(&mut self, bot_id: u64, wf: u64, touched: Vec<u64>) {
let home = self.state.home_of(bot_id); let home = self.state.home_of(bot_id);
let looking = self.wf.open || self.state.selected == bot_id || self.state.selected == home; // (Only the bot whose chat the person is looking at — beside the canvas or on its own;
// on the 日程 they are looking at that.)
let looking = !self.sched.open && (self.state.selected == bot_id || self.state.selected == home);
if !looking || !self.state.workflows.iter().any(|w| w.id == wf) { if !looking || !self.state.workflows.iter().any(|w| w.id == wf) {
return; return;
} }
if self.wf.current != wf { if self.wf.current != wf {
self.wf_keep_version(); self.wf_keep_version();
self.wf.current = wf; self.wf.current = wf;
self.wf.selected = None; self.wf_let_go();
self.wf.selected_edge = None;
} }
if !self.wf.open { if !self.wf.open {
self.wf.open = true; self.wf.open = true;
@ -208,6 +211,18 @@ impl App {
self.wf.reveal = true; self.wf.reveal = true;
} }
/// Another workflow on the canvas: nothing picked, typed, moved or drawn carries over (ids
/// start from 1 in each one).
fn wf_let_go(&mut self) {
self.wf.selected = None;
self.wf.selected_edge = None;
self.wf.editing = None;
self.wf.moving = None;
self.wf.linking = None;
self.wf.shaping = None;
self.wf.stroke.clear();
}
pub(super) fn wf_close(&mut self) { pub(super) fn wf_close(&mut self) {
self.wf_keep_version(); self.wf_keep_version();
self.wf.open = false; self.wf.open = false;
@ -370,13 +385,18 @@ impl App {
ui.close(); ui.close();
} }
} }
if menu_ui::item(ui, p, Icon::Plus, "新建工作流").clicked() { if !self.mir.on && menu_ui::item(ui, p, Icon::Plus, "新建工作流").clicked() {
self.wf_keep_version(); self.wf_keep_version();
self.wf_new(); self.wf_new();
ui.close(); ui.close();
} }
menu_ui::sep(ui, p); menu_ui::sep(ui, p);
let Some(i) = self.wf_index() else { return }; let Some(i) = self.wf_index() else { return };
if self.mir.on {
// (A screen shows the brain's: made, renamed, restored and deleted there.)
ui.label(RichText::new(t("這台是螢幕:在大腦上新建、改名、還原或刪除")).size(FONT_XS).color(p.text3));
return;
}
let versions: Vec<(usize, String, usize)> = self.state.workflows[i] let versions: Vec<(usize, String, usize)> = self.state.workflows[i]
.versions .versions
.iter() .iter()

View File

@ -47,6 +47,7 @@ pub const AREAS: &[Area] = &[
area!("pageview", "頁面的版面與圖表"), area!("pageview", "頁面的版面與圖表"),
area!("routines", "例行任務"), area!("routines", "例行任務"),
area!("workflow", "工作流"), area!("workflow", "工作流"),
area!("schedule", "日程"),
area!("goal", "目標(/goal)"), area!("goal", "目標(/goal)"),
area!("plan", "計畫(/plan)"), area!("plan", "計畫(/plan)"),
area!("tasks", "任務"), area!("tasks", "任務"),

View File

@ -63,6 +63,7 @@ mod providers;
mod publish; mod publish;
mod remote; mod remote;
mod routines; mod routines;
mod schedule;
mod workflow; mod workflow;
mod setup; mod setup;
mod skills; mod skills;

221
src/schedule.rs Normal file
View File

@ -0,0 +1,221 @@
// 日程 (laid out like OpenBot's 日程): every time a bot is set to do something — each bot's
// routines on a schedule and the workflows with a scheduled trigger — on one calendar: what ran
// and how it went (from their run records), and what is coming (from their schedules, the same
// way the scheduler works it out), so the person sees what each bot will do without asking it.
// Routines started by an event (a trigger) have no times ahead: only their runs show.
use crate::model::State;
use crate::routines::{self, RunOutcome};
use crate::workflow::{NodeKind, RunState};
/// What an entry is about.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub enum What {
Routine { bot: u64, id: u64 },
Workflow { id: u64 },
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Status {
Done,
Failed,
Stopped,
Running,
/// Will run then.
Coming,
/// Would run then, but it is paused.
Paused,
}
/// One time on the calendar.
#[derive(Clone, PartialEq, Debug)]
pub struct Item {
/// Seconds since 1970.
pub at: i64,
pub what: What,
/// The bot it belongs to (a workflow: the bot of its first step; 0 when it has none).
pub bot: u64,
pub title: String,
/// How it repeats (「每天 09:00」), or what starts it.
pub when: String,
pub status: Status,
}
/// At most this many times of one routine or workflow in one range (one every 5 minutes would
/// fill a month).
pub const MAX_PER_THING: usize = 200;
/// Everything on the calendar from `from` up to `to` (seconds), oldest first: the runs that
/// started then, and — from `now` on — the times still to come.
pub fn items(state: &State, from: i64, to: i64, now: i64) -> Vec<Item> {
let mut out = vec![];
for b in &state.bots {
for r in &b.routines {
let what = What::Routine { bot: b.id, id: r.id };
let when = match &r.trigger {
Some(t) => t.describe(),
None => routines::describe(&r.schedule),
};
for run in r.runs.iter().filter(|x| x.started >= from && x.started < to) {
let status = match run.outcome {
RunOutcome::Succeeded => Status::Done,
RunOutcome::Failed | RunOutcome::Interrupted => Status::Failed,
RunOutcome::Stopped => Status::Stopped,
RunOutcome::Running => Status::Running,
};
out.push(Item { at: run.started, what, bot: b.id, title: r.title.clone(), when: when.clone(), status });
}
if r.trigger.is_none() {
let status = if r.paused { Status::Paused } else { Status::Coming };
for at in times(&r.schedule, r.created_at, from.max(now), to) {
out.push(Item { at, what, bot: b.id, title: r.title.clone(), when: when.clone(), status });
}
}
}
}
for w in &state.workflows {
let what = What::Workflow { id: w.id };
let bot = w.order().iter().find_map(|n| match w.node(*n).map(|n| &n.kind) {
Some(NodeKind::Step { bot, .. } | NodeKind::Check { bot, .. } | NodeKind::Deliver { bot }) => Some(*bot),
_ => None,
});
let bot = bot.unwrap_or(0);
let when = w.schedule().map(routines::describe).unwrap_or_else(|| "手動".into());
for run in w.runs.iter().filter(|x| x.started >= from && x.started < to) {
let status = match run.state {
RunState::Done => Status::Done,
RunState::Failed => Status::Failed,
RunState::Stopped => Status::Stopped,
RunState::Running | RunState::Waiting => Status::Running,
};
out.push(Item { at: run.started, what, bot, title: w.name.clone(), when: when.clone(), status });
}
if let Some(s) = w.schedule() {
for at in times(s, w.created_at, from.max(now), to) {
out.push(Item { at, what, bot, title: w.name.clone(), when: when.clone(), status: Status::Coming });
}
}
}
out.sort_by(|a, b| a.at.cmp(&b.at).then(a.title.cmp(&b.title)));
out
}
/// The next few times coming, across everything (即將執行): paused ones left out.
pub fn coming(state: &State, now: i64, n: usize) -> Vec<Item> {
let mut out: Vec<Item> = items(state, now, now + 14 * 86_400, now).into_iter().filter(|i| i.status == Status::Coming).collect();
out.truncate(n);
out
}
/// The times a schedule runs after `from` and before `to`.
fn times(s: &routines::Schedule, created: i64, from: i64, to: i64) -> Vec<i64> {
let mut out = vec![];
let mut after = from - 1;
while out.len() < MAX_PER_THING {
match routines::next_run(s, created, after) {
Some(t) if t < to && t > after => {
out.push(t);
after = t;
}
_ => break,
}
}
out
}
/// Midnight of a day in a time zone, as seconds (the calendar's days are the person's days).
pub fn day_start(day: chrono::NaiveDate, timezone: &str) -> i64 {
use chrono::TimeZone;
let tz = routines::tz_of(timezone);
let midnight = day.and_hms_opt(0, 0, 0).unwrap_or_default();
match tz.from_local_datetime(&midnight) {
chrono::LocalResult::Single(t) | chrono::LocalResult::Ambiguous(t, _) => t.timestamp(),
// (A day that starts in a summer-time gap: an hour later.)
chrono::LocalResult::None => tz.from_local_datetime(&(midnight + chrono::Duration::hours(1))).earliest().map(|t| t.timestamp()).unwrap_or(0),
}
}
/// The day (in a time zone) a moment falls on.
pub fn day_of(at: i64, timezone: &str) -> chrono::NaiveDate {
use chrono::TimeZone;
chrono::Utc.timestamp_opt(at, 0).single().map(|t| t.with_timezone(&routines::tz_of(timezone)).date_naive()).unwrap_or_default()
}
/// 「21:11」 in a time zone.
pub fn clock(at: i64, timezone: &str) -> String {
use chrono::TimeZone;
chrono::Utc.timestamp_opt(at, 0).single().map(|t| t.with_timezone(&routines::tz_of(timezone)).format("%H:%M").to_string()).unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::routines::{Routine, RoutineRun, Schedule};
fn sched(v: serde_json::Value) -> Schedule {
routines::validate(serde_json::from_value(v).unwrap()).unwrap()
}
fn routine(id: u64, title: &str, s: Schedule, created: i64) -> Routine {
serde_json::from_value(serde_json::json!({"id": id, "title": title, "prompt": "做事", "schedule": s, "created_at": created})).unwrap()
}
/// A week in Taipei: the daily one each day at its time, the workday one Monday to Friday,
/// the paused one as paused; what ran before now shows how it went; an event one only its
/// runs; a scheduled workflow with the bot of its first step.
#[test]
fn the_calendar_shows_what_ran_and_what_is_coming() {
let tz = "Asia/Taipei";
let mut st = State::demo();
st.workflows.clear();
for b in st.bots.iter_mut() {
b.routines.clear();
}
let mon = chrono::NaiveDate::from_ymd_opt(2026, 11, 16).unwrap();
let from = day_start(mon, tz);
let to = day_start(mon + chrono::Duration::days(7), tz);
let created = from - 30 * 86_400;
// Now: Saturday 21 at 12:00.
let now = day_start(mon + chrono::Duration::days(5), tz) + 12 * 3600;
let mut daily = routine(1, "競品掃描", sched(serde_json::json!({"frequency": "daily", "time": "08:30", "timezone": tz})), created);
daily.runs.push(RoutineRun { started: day_start(mon + chrono::Duration::days(4), tz) + 8 * 3600 + 1800, ended: 0, outcome: RunOutcome::Succeeded, note: String::new(), steps: 3, failed_steps: 0, sent: 0, sends: vec![] });
daily.runs.push(RoutineRun { started: day_start(mon + chrono::Duration::days(5), tz) + 8 * 3600 + 1800, ended: 0, outcome: RunOutcome::Failed, note: "沒網路".into(), steps: 1, failed_steps: 1, sent: 0, sends: vec![] });
let workdays = routine(2, "晨報", sched(serde_json::json!({"frequency": "weekly", "daysOfWeek": ["MO", "TU", "WE", "TH", "FR"], "time": "09:00", "timezone": tz})), created);
let mut paused = routine(3, "週報", sched(serde_json::json!({"frequency": "daily", "time": "18:00", "timezone": tz})), created);
paused.paused = true;
let mut event = routine(4, "PR 合併", sched(serde_json::json!({"frequency": "daily", "time": "09:00", "timezone": tz})), created);
event.trigger = Some(crate::triggers::Trigger::Webhook { secret: "s".into() });
st.bots[0].routines = vec![daily, workdays, paused, event];
let bot = st.bots[0].id;
let mut w = crate::workflow::Workflow::new(1, "Threads 早報", created);
if let NodeKind::Trigger { schedule } = &mut w.nodes[0].kind {
*schedule = Some(sched(serde_json::json!({"frequency": "daily", "time": "07:00", "timezone": tz})));
}
w.nodes.push(crate::workflow::Node { id: 2, kind: NodeKind::Step { bot, prompt: "找".into() }, x: 0.0, y: 190.0 });
w.connect(1, 2);
st.workflows.push(w);
let all = items(&st, from, to, now);
let of = |title: &str| all.iter().filter(|i| i.title == title).map(|i| (day_of(i.at, tz).format("%d").to_string(), clock(i.at, tz), i.status)).collect::<Vec<_>>();
// Before now only what ran; from now on the times coming (Saturday 08:30 is past).
assert_eq!(of("競品掃描"), vec![("20".into(), "08:30".into(), Status::Done), ("21".into(), "08:30".into(), Status::Failed), ("22".into(), "08:30".into(), Status::Coming)]);
assert!(of("晨報").is_empty(), "Saturday and Sunday: no workdays left this week");
assert_eq!(of("週報"), vec![("21".into(), "18:00".into(), Status::Paused), ("22".into(), "18:00".into(), Status::Paused)]);
assert!(of("PR 合併").is_empty(), "an event one has no times ahead");
assert_eq!(of("Threads 早報"), vec![("22".into(), "07:00".into(), Status::Coming)]);
assert!(all.iter().filter(|i| i.title == "Threads 早報").all(|i| i.bot == bot && i.what == What::Workflow { id: 1 }));
assert!(all.windows(2).all(|w| w[0].at <= w[1].at), "oldest first");
// 即將執行: across everything, paused left out.
let next = coming(&st, now, 4);
let day = |i: &Item| day_of(i.at, tz).format("%d").to_string();
assert_eq!(
next.iter().map(|i| (day(i), clock(i.at, tz), i.title.as_str())).collect::<Vec<_>>(),
vec![("22".into(), "07:00".into(), "Threads 早報"), ("22".into(), "08:30".into(), "競品掃描"), ("23".into(), "07:00".into(), "Threads 早報"), ("23".into(), "08:30".into(), "競品掃描")]
);
assert!(next.iter().all(|i| i.status == Status::Coming && i.title != "週報"));
assert!(next.windows(2).all(|w| w[0].at <= w[1].at));
// One every 5 minutes: capped.
st.bots[0].routines.push(routine(5, "盯盤", sched(serde_json::json!({"frequency": "minutely", "interval": 5, "time": "00:00", "timezone": tz})), created));
assert_eq!(items(&st, from, to, now).iter().filter(|i| i.title == "盯盤").count(), MAX_PER_THING);
}
}

View File

@ -21,6 +21,8 @@ pub const RUNS_KEPT: usize = 20;
pub const HANDED_ON_CHARS: usize = 6_000; pub const HANDED_ON_CHARS: usize = 6_000;
/// A card's width on the canvas. /// A card's width on the canvas.
pub const CARD_W: f32 = 280.0; pub const CARD_W: f32 = 280.0;
/// Why a run AnyBot was closed during ended.
pub const INTERRUPTED: &str = "AnyBot 在執行中被關掉,這一步可能做到一半";
/// Laid out: one step below the other this far apart, side by side this far apart. /// Laid out: one step below the other this far apart, side by side this far apart.
pub const ROW: f32 = 190.0; pub const ROW: f32 = 190.0;
pub const COLUMN: f32 = 340.0; pub const COLUMN: f32 = 340.0;
@ -249,9 +251,29 @@ impl Workflow {
pub fn node_mut(&mut self, id: u64) -> Option<&mut Node> { pub fn node_mut(&mut self, id: u64) -> Option<&mut Node> {
self.nodes.iter_mut().find(|n| n.id == id) self.nodes.iter_mut().find(|n| n.id == id)
} }
/// A new id for a node or a note (one counter for both: a selection names either). /// A new id for a node or a note (one counter for both: a selection names either). Never one
/// a kept run or version names: a run going on after its step was removed stops there, it
/// doesn't run a new step that took the number.
pub fn next_id(&self) -> u64 { pub fn next_id(&self) -> u64 {
self.nodes.iter().map(|n| n.id).chain(self.notes.iter().map(|n| n.id)).max().unwrap_or(0) + 1 let in_runs = self.runs.iter().flat_map(|r| r.order.iter().copied());
let in_versions = self.versions.iter().flat_map(|v| v.nodes.iter().map(|n| n.id).chain(v.notes.iter().map(|n| n.id)));
self.nodes.iter().map(|n| n.id).chain(self.notes.iter().map(|n| n.id)).chain(in_runs).chain(in_versions).max().unwrap_or(0) + 1
}
/// Runs AnyBot was closed during (found when it starts again): a bot's step may be half done
/// and its question was only in memory — the run ends as failed, saying so. One waiting for
/// the person stays: it can still be answered.
pub fn mark_interrupted(&mut self, now: i64) -> bool {
let mut cut = false;
for r in self.runs.iter_mut().filter(|r| r.state == RunState::Running) {
if let Some(s) = r.order.get(r.at).copied().and_then(|n| r.steps.iter_mut().find(|s| s.node == n)) {
s.state = StepState::Failed;
}
r.state = RunState::Failed;
r.ended = Some(now);
r.why = INTERRUPTED.into();
cut = true;
}
cut
} }
/// The steps a run takes (what the trigger leads to): breadth first along the lines, the /// The steps a run takes (what the trigger leads to): breadth first along the lines, the
/// ones below (then left) first where one leads to several; each once. /// ones below (then left) first where one leads to several; each once.
@ -542,6 +564,32 @@ pub struct Told {
pub stop: bool, pub stop: bool,
} }
/// The workflow a call is about: its `id` (a number, or a number in words), else the one on the
/// person's canvas, else the one changed last. An id that isn't there is an error, not another one.
pub fn target(wfs: &[Workflow], v: &Value, showing: Option<u64>) -> Result<u64, String> {
let given = &v["id"];
if !given.is_null() {
let id = given.as_u64().or_else(|| given.as_str().and_then(|s| s.trim().trim_start_matches('#').parse().ok()));
return match id {
Some(id) if wfs.iter().any(|w| w.id == id) => Ok(id),
_ => Err(format!("沒有工作流 {}(list 看有哪些)", given.as_u64().map(|n| format!("#{n}")).unwrap_or_else(|| given.to_string()))),
};
}
showing.filter(|s| wfs.iter().any(|w| w.id == *s)).or_else(|| wfs.iter().max_by_key(|w| w.updated_at).map(|w| w.id)).ok_or_else(|| "還沒有工作流:用 create 做一個".into())
}
/// The call with the workflow it is about written in (settled when it is asked, so the card the
/// person answers names the one that changes, even if the canvas moves meanwhile).
pub fn pin_target(wfs: &[Workflow], args: &str, showing: Option<u64>) -> Result<String, String> {
let mut v: Value = serde_json::from_str(if args.trim().is_empty() { "{}" } else { args }).map_err(|_| "參數不是有效的 JSON".to_string())?;
let action = v["action"].as_str().unwrap_or("").trim().to_lowercase();
if matches!(action.as_str(), "list" | "create" | "") {
return Ok(v.to_string());
}
v["id"] = json!(target(wfs, &v, showing)?);
Ok(v.to_string())
}
/// The `workflow` tool on the workflows. `showing`: the workflow on the person's canvas. /// The `workflow` tool on the workflows. `showing`: the workflow on the person's canvas.
pub fn tool(wfs: &mut Vec<Workflow>, who: &Who, v: &Value, showing: Option<u64>, now: i64) -> Result<Told, String> { pub fn tool(wfs: &mut Vec<Workflow>, who: &Who, v: &Value, showing: Option<u64>, now: i64) -> Result<Told, String> {
let action = v["action"].as_str().unwrap_or("").trim().to_lowercase(); let action = v["action"].as_str().unwrap_or("").trim().to_lowercase();
@ -557,7 +605,7 @@ pub fn tool(wfs: &mut Vec<Workflow>, who: &Who, v: &Value, showing: Option<u64>,
let mut w = Workflow::new(id, name, now); let mut w = Workflow::new(id, name, now);
let mut touched = vec![1]; let mut touched = vec![1];
if let Some(s) = v.get("schedule").filter(|s| !s.is_null()) { if let Some(s) = v.get("schedule").filter(|s| !s.is_null()) {
set_schedule(&mut w, s, who.timezone)?; set_schedule(&mut w, s, who.timezone, now)?;
} }
add_steps(&mut w, who, v, &mut touched)?; add_steps(&mut w, who, v, &mut touched)?;
w.tidy(); w.tidy();
@ -568,13 +616,8 @@ pub fn tool(wfs: &mut Vec<Workflow>, who: &Who, v: &Value, showing: Option<u64>,
return Ok(Told { text, wf: Some(id), touched, changed: true, ..Default::default() }); return Ok(Told { text, wf: Some(id), touched, changed: true, ..Default::default() });
} }
// The others are about one workflow. // The others are about one workflow.
let id = v["id"].as_u64().filter(|i| *i > 0).or(showing.filter(|s| wfs.iter().any(|w| w.id == *s))).or_else(|| wfs.iter().max_by_key(|w| w.updated_at).map(|w| w.id)); let id = target(wfs, v, showing)?;
let Some(i) = id.and_then(|id| wfs.iter().position(|w| w.id == id)) else { let Some(i) = wfs.iter().position(|w| w.id == id) else { return Err(format!("沒有工作流 #{id}(list 看有哪些)")) };
return Err(match v["id"].as_u64() {
Some(n) => format!("沒有工作流 #{n}(list 看有哪些)"),
None => "還沒有工作流:用 create 做一個".into(),
});
};
let w = &mut wfs[i]; let w = &mut wfs[i];
let id = w.id; let id = w.id;
match action.as_str() { match action.as_str() {
@ -610,7 +653,10 @@ pub fn tool(wfs: &mut Vec<Workflow>, who: &Who, v: &Value, showing: Option<u64>,
said.push(format!("名稱改成「{n}」")); said.push(format!("名稱改成「{n}」"));
} }
if let Some(s) = v.get("schedule").filter(|s| !s.is_null()) { if let Some(s) = v.get("schedule").filter(|s| !s.is_null()) {
set_schedule(w, s, who.timezone)?; if let Err(e) = set_schedule(w, s, who.timezone, now) {
*w = before;
return Err(e);
}
touched.push(w.trigger().map(|t| t.id).unwrap_or(1)); touched.push(w.trigger().map(|t| t.id).unwrap_or(1));
said.push(format!("觸發改成{}", w.schedule().map(crate::routines::describe).unwrap_or_default())); said.push(format!("觸發改成{}", w.schedule().map(crate::routines::describe).unwrap_or_default()));
} else if v["manual_only"].as_bool() == Some(true) { } else if v["manual_only"].as_bool() == Some(true) {
@ -826,12 +872,17 @@ fn one_line(s: &str) -> String {
clip(&s.split_whitespace().collect::<Vec<_>>().join(" "), 80) clip(&s.split_whitespace().collect::<Vec<_>>().join(" "), 80)
} }
fn set_schedule(w: &mut Workflow, raw: &Value, tz: &str) -> Result<(), String> { fn set_schedule(w: &mut Workflow, raw: &Value, tz: &str, now: i64) -> Result<(), String> {
let mut raw = raw.clone(); let mut raw = raw.clone();
if raw.get("timezone").and_then(Value::as_str).unwrap_or("").is_empty() { if raw.get("timezone").and_then(Value::as_str).unwrap_or("").is_empty() {
raw["timezone"] = json!(tz); raw["timezone"] = json!(tz);
} }
let s = serde_json::from_value::<crate::routines::Schedule>(raw).map_err(|e| e.to_string()).and_then(crate::routines::validate).map_err(|e| format!("排程有問題:{e}"))?; let s = serde_json::from_value::<crate::routines::Schedule>(raw).map_err(|e| e.to_string()).and_then(crate::routines::validate).map_err(|e| format!("排程有問題:{e}"))?;
// (僅一次 counts from when it is set: counted from the day the workflow was made, its one
// time could be past already and it would never run.)
if s.once {
w.created_at = now;
}
if let Some(NodeKind::Trigger { schedule }) = w.trigger().map(|t| t.id).and_then(|t| w.node_mut(t)).map(|n| &mut n.kind) { if let Some(NodeKind::Trigger { schedule }) = w.trigger().map(|t| t.id).and_then(|t| w.node_mut(t)).map(|n| &mut n.kind) {
*schedule = Some(s); *schedule = Some(s);
} }
@ -1021,6 +1072,55 @@ mod tests {
assert!(call(&mut wfs, json!({"action": "delete"})).unwrap().changed && wfs.is_empty()); assert!(call(&mut wfs, json!({"action": "delete"})).unwrap().changed && wfs.is_empty());
} }
/// Which one a call is about: the id given (a number in words too), else the canvas, else
/// the one changed last; an id that isn't there is an error, never another workflow. The card
/// is made from the call with that written in.
#[test]
fn a_call_names_one_workflow_and_keeps_it() {
let mut wfs = vec![];
call(&mut wfs, json!({"action": "create", "name": "A"})).unwrap();
call(&mut wfs, json!({"action": "create", "name": "B"})).unwrap();
wfs[1].updated_at = 9_999;
assert_eq!(target(&wfs, &json!({"action": "delete"}), Some(1)), Ok(1), "the canvas first");
assert_eq!(target(&wfs, &json!({"action": "delete"}), None), Ok(2), "then the one changed last");
assert_eq!(target(&wfs, &json!({"id": "#1"}), Some(2)), Ok(1));
for bad in [json!({"id": 0}), json!({"id": "x"}), json!({"id": 7})] {
assert!(target(&wfs, &bad, Some(1)).is_err(), "{bad}");
}
let pinned: Value = serde_json::from_str(&pin_target(&wfs, r#"{"action":"delete"}"#, Some(1)).unwrap()).unwrap();
assert_eq!(pinned["id"], 1);
assert_eq!(pin_target(&wfs, r#"{"action":"create","name":"C"}"#, Some(1)).unwrap(), json!({"action": "create", "name": "C"}).to_string());
}
/// A wrong schedule leaves nothing of the call; 僅一次 set later counts from then; numbers a
/// run still names never come back; a run AnyBot was closed during ends as interrupted (one
/// waiting for the person stays).
#[test]
fn edits_and_restarts_leave_no_half_state() {
let mut wfs = vec![];
call(&mut wfs, json!({"action": "create", "name": "早報", "steps": [{"prompt": "查"}]})).unwrap();
assert!(call(&mut wfs, json!({"action": "edit", "name": "X", "schedule": {"frequency": "daily", "time": "25:00"}})).is_err());
assert_eq!(wfs[0].name, "早報");
let bots = vec![(1, "研究助理".to_string())];
let who = Who { me: 1, bots: &bots, timezone: "Asia/Taipei" };
let later = 1_000 + 3 * 86_400;
tool(&mut wfs, &who, &json!({"action": "edit", "schedule": {"frequency": "daily", "time": "09:00", "once": true}}), None, later).unwrap();
assert_eq!(wfs[0].created_at, later);
assert!(crate::routines::next_run(wfs[0].schedule().unwrap(), wfs[0].created_at, later).is_some(), "its one time is ahead");
// Step 2 is in a run; removed, its number isn't given to the next step.
wfs[0].start_run("手動", 2_000);
call(&mut wfs, json!({"action": "edit", "remove": [2]})).unwrap();
let t = call(&mut wfs, json!({"action": "edit", "steps": [{"prompt": "新的"}]})).unwrap();
assert!(t.touched[0] > 2, "{:?}", t.touched);
// Closed while running: interrupted; while waiting for the person: kept.
assert!(wfs[0].mark_interrupted(3_000));
let r = wfs[0].runs.last().unwrap();
assert_eq!((r.state, r.why.as_str(), r.steps[1].state), (RunState::Failed, INTERRUPTED, StepState::Failed));
wfs[0].start_run("手動", 4_000);
wfs[0].runs.last_mut().unwrap().state = RunState::Waiting;
assert!(!wfs[0].mark_interrupted(5_000));
}
fn wf() -> Workflow { fn wf() -> Workflow {
let mut w = Workflow::new(1, "早報", 100); let mut w = Workflow::new(1, "早報", 100);
for (id, x, y, kind) in [ for (id, x, y, kind) in [