From 351ce3f0053a705555cfc344ab630244c5bd5223 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Sat, 21 Nov 2026 18:37:31 +0800 Subject: [PATCH] =?UTF-8?q?=E5=B7=A5=E4=BD=9C=E6=B5=81=EF=BC=9A=E7=85=A7?= =?UTF-8?q?=20OpenBot=20=E5=B7=A5=E4=BD=9C=E6=B5=81=E7=95=AB=E5=B8=83?= =?UTF-8?q?=E7=9A=84=E6=8E=92=E7=89=88=EF=BC=88=E5=AE=83=E5=85=AC=E9=96=8B?= =?UTF-8?q?=E7=9A=84=E7=A8=8B=E5=BC=8F=E6=B2=92=E6=9C=89=E7=95=AB=E5=B8=83?= =?UTF-8?q?=EF=BC=8C=E7=85=A7=E6=88=AA=E5=9C=96=E5=81=9A=EF=BC=89=EF=BC=8C?= =?UTF-8?q?=E9=A2=A8=E6=A0=BC=E6=98=AF=20AnyBot=20=E8=87=AA=E5=B7=B1?= =?UTF-8?q?=E7=9A=84=E3=80=82=E5=8F=AF=E4=BB=A5=E7=95=AB=E3=80=81=E5=8A=A0?= =?UTF-8?q?=E8=A8=BB=E8=A7=A3=E3=80=81=E5=9F=B7=E8=A1=8C=EF=BC=8C=E4=B9=9F?= =?UTF-8?q?=E5=8F=AF=E4=BB=A5=E5=9C=A8=E8=81=8A=E5=A4=A9=E8=A3=A1=E7=94=A8?= =?UTF-8?q?=E4=B8=80=E8=88=AC=E7=9A=84=E8=A9=B1=E8=AB=8B=20Bot=20=E5=81=9A?= =?UTF-8?q?=E5=92=8C=E6=94=B9=E2=80=94=E2=80=94=E7=95=AB=E5=B8=83=E9=96=8B?= =?UTF-8?q?=E5=9C=A8=E9=82=A3=E5=80=8B=20Bot=20=E7=9A=84=E8=81=8A=E5=A4=A9?= =?UTF-8?q?=E6=97=81=E9=82=8A=EF=BC=8C=E7=9C=8B=E8=91=97=E5=AE=83=E6=94=B9?= =?UTF-8?q?=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 畫布(側邊欄最上面一排的流程圖示):名稱選單(每個工作流和步驟數、新建、版本歷史、重新命名、建立副本、刪除)、右上「聊天/執行紀錄/▷ 執行工作流」、拖曳縮放、工具列(選取、拖曳|畫筆、便利貼、形狀、文字|搜尋|+ 新增節點)、縮放列、小地圖。窄視窗時縮放列移到工具列上面,等你確認那條橫跨上方。 - 卡片:觸發器(手動/排程、下次執行、立即執行)、Bot 步驟、等你確認、檢查、交付、通知你;從卡片底下的點拉線,不能連回觸發器、不能繞圈。 - 執行(workflow_run.rs):照線走;Bot 步驟是那個 Bot 聊天裡的一則問題,最後的回答交給下一步;檢查回「通過」才繼續;等你確認發通知;一次只跑一個;排程到了自動跑;執行紀錄 20 次、版本歷史 30 版。 - 聊出來:新工具 `workflow`(appctl;list/show/create/edit/run/stop/delete,刪除先問),屬於「例行任務與工作流」能力。Bot 做的排成一欄(tidy),插在中間時後面的往下移,使用者自己排過的不重排;改到的卡片和便利貼亮 2.6 秒,跑出畫面就縮到看得到全部。聊天抽成 chat_column,放在畫布旁邊(視窗 ≥ 900),跟著側邊欄選的 Bot 換。 - 修掉的:拖曳的起點用按下的位置(之前從點拉線會搬走卡片);搜尋打開時游標進搜尋框;一個步驟問的是正忙的 Bot(就是叫它開始的那一輪)時,那一輪結束不算這一步的回答(之前整個執行馬上失敗「做完了但沒有寫結果」);「要繼续嗎」簡體字。 - 側邊欄多了工作流按鈕,所有檔案往左一格:library.md 的座標 120,30 → 76,30。 - ctl desktop-shot:手機直接連線只聽 127.0.0.1(ANYBOT_SHOT_REAL=1 的視窗以前會聽區網和 Tailscale,有密碼、截完就關)。 已驗證: cargo test 855 過(新:workflow:: 3 個——聊天裡建立排整齊、一步步改(插中間、分支、刪掉接起來、錯一個整次不留)、run/stop;app::workflow_run 的 a_bots_workflow_call_shows_beside_its_chat,拿掉修正時會失敗;layout_audit 工作流四景;theme 設計檢查——浮在畫布上的改用 kit::floating,便利貼的字用淺色主題的字色);clippy 沒有新的(bin 8)。全新 scratch 照 workflow.md 六步逐字跑過:手機聊天裡建立、修改、執行(第 1 步在 Bot 聊天裡問、檢查「通過」、停在等你確認),桌面截圖:畫布+旁邊的聊天、在旁邊的聊天打字畫布跟著亮起來並縮到看得到全部、自己貼便利貼打字、拉線、搜尋。版本數、state 的步驟和位置另外看過。 未驗證: 真的模型聽一般的話做出工作流(scratch 只能用假模型);「等你確認」的通知真的跳出來(要 AnyBot.app/手機帳號);按「繼續」之後交付、通知你那兩步在真資料上(截圖模式按了會在這台 Mac 跳通知,沒按;單元測試有走)。動到 appctl 的 needs_approval(刪工作流先問,跟刪例行任務一樣):照規定要你看過再發佈。手機還沒有畫布。 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Uirha2uBHmbnuWBhNzjbJm --- .claude/skills/verify-anybot/scripts/ctl | 3 +- FEATURES.md | 14 +- docs/feature-map/README.md | 1 + docs/feature-map/library.md | 6 +- docs/feature-map/profile.md | 2 +- docs/feature-map/workflow.md | 44 + docs/plan-2026-11-openbot.md | 2 +- icons/lucide/bell.svg | 16 + icons/lucide/hand.svg | 18 + icons/lucide/map.svg | 17 + icons/lucide/mouse-pointer-2.svg | 15 + icons/lucide/scan.svg | 18 + icons/lucide/send.svg | 16 + icons/lucide/sticky-note.svg | 16 + icons/lucide/type.svg | 17 + icons/lucide/workflow.svg | 17 + src/app.rs | 205 +-- src/app/chat_ui.rs | 1 + src/app/kit.rs | 6 + src/app/layout_audit.rs | 35 + src/app/sidebar_ui.rs | 8 + src/app/workflow_run.rs | 528 +++++++ src/app/workflow_ui.rs | 1645 ++++++++++++++++++++++ src/appctl.rs | 41 +- src/featuremap.rs | 1 + src/icons.rs | 19 + src/main.rs | 1 + src/model.rs | 4 + src/profile.rs | 4 +- src/workflow.rs | 1114 +++++++++++++++ 30 files changed, 3739 insertions(+), 95 deletions(-) create mode 100644 docs/feature-map/workflow.md create mode 100644 icons/lucide/bell.svg create mode 100644 icons/lucide/hand.svg create mode 100644 icons/lucide/map.svg create mode 100644 icons/lucide/mouse-pointer-2.svg create mode 100644 icons/lucide/scan.svg create mode 100644 icons/lucide/send.svg create mode 100644 icons/lucide/sticky-note.svg create mode 100644 icons/lucide/type.svg create mode 100644 icons/lucide/workflow.svg create mode 100644 src/app/workflow_run.rs create mode 100644 src/app/workflow_ui.rs create mode 100644 src/workflow.rs diff --git a/.claude/skills/verify-anybot/scripts/ctl b/.claude/skills/verify-anybot/scripts/ctl index 90d704c..77346fd 100755 --- a/.claude/skills/verify-anybot/scripts/ctl +++ b/.claude/skills/verify-anybot/scripts/ctl @@ -439,7 +439,8 @@ cmd_desktop_shot() { local name=$1; shift if serve_alive; then die "--serve 開著:ANYBOT_SHOT_REAL=1 的圖要先 ctl stop(同一個資料夾)"; fi mkdir -p "$RUN/desktop" - "$SCRATCH_ENV" "$SCR" "$@" "$BIN" --screenshot "$RUN/desktop/$name.png" > "$RUN/desktop/$name.log" 2>&1 + # (ANYBOT_SHOT_REAL=1 的視窗也會開手機直接連線:一樣只聽 127.0.0.1,不出現在區網和 Tailscale 上。) + "$SCRATCH_ENV" "$SCR" "ANYBOT_PHONE_BIND=127.0.0.1" "$@" "$BIN" --screenshot "$RUN/desktop/$name.png" > "$RUN/desktop/$name.log" 2>&1 [ -s "$RUN/desktop/$name.png" ] || die "沒有畫出圖($RUN/desktop/$name.log)" echo "$RUN/desktop/$name.png" } diff --git a/FEATURES.md b/FEATURES.md index 5ae4fd7..fad3db5 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -1583,7 +1583,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) ### 所有檔案(側邊欄的資料夾按鈕) - 每個 Bot 交給你的、你傳給 Bot 的檔案,跨 Bot、跨對話放在一個視窗(照 OpenBot 檔案庫的排版)。從聊天(包括較早的對話)裡已經記下的附件來,不掃硬碟;同一個檔案只列一次,新的在前;視窗開著每 5 秒重讀。 -- 從哪裡開:側邊欄最上面一排第一個(資料夾圖示,任務按鈕左邊);左下角選單「所有檔案…」。截圖用 `ANYBOT_SHOT_VIEW=library`。 +- 從哪裡開:側邊欄最上面一排第一個(資料夾圖示,工作流按鈕左邊);左下角選單「所有檔案…」。截圖用 `ANYBOT_SHOT_VIEW=library`。 - 左欄:搜尋檔名、「所有檔案」、「最近 7 天」、每個有檔案的 Bot(顏色點、數量)。上面種類分頁帶數量:全部、圖片、文件、程式碼、表格、影音、其他(沒有的不列)。右上「格子/清單」:格子是縮圖或副檔名+檔名+「Bot · 日期」,一排幾張撐滿寬度;清單是「Bot · 日期 · 大小」。視窗高度固定,切種類、看法不跳。 - 檔案不在原處(刪掉或搬走):灰字、紅字「不見了」,點不開。其他點一下用 AnyBot 的檢視器打開(Markdown、表格、圖片、PDF、影音、程式碼;用其他 App 打開、下載)。 - 螢幕電腦看的是從大腦抓過來的副本。手機還沒有(只有每個對話的「資料庫」)。功能地圖新的一區 library.md。 @@ -1931,6 +1931,18 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 第一次連上時只記住目前狀態,不會把以前的事件當成新的。AnyBot 開著時才會檢查。 - 「例行任務」視窗顯示「⚡ 觸發條件」和連線狀態(例如「已連上 GitHub,等待事件」或錯誤原因)。暫停的不會檢查。 +### 工作流(側邊欄最上面一排的流程圖示) + +照 OpenBot 工作流畫布的排版做的(它公開的程式裡沒有畫布,照截圖的樣子做),風格是 AnyBot 自己的;功能地圖 workflow.md。 + +- 一個工作流是一張畫布:觸發器(手動,或也照排程:每天、每週…,寫下次執行,有「立即執行」),接著用線連起來的卡片:Bot 步驟(哪個 Bot、要它做什麼)、等你確認、檢查(哪個 Bot、要做到什麼才通過)、交付(結果放進哪個 Bot 的聊天)、通知你(「{結果}」換成上一步結果的第一行)。從卡片底下的點拉到另一張就連線;不能連回觸發器、不能繞圈。 +- 畫布:左上名稱和選單(每個工作流和步驟數、新建、版本歷史、重新命名、建立副本、刪除);右上「聊天」「執行紀錄」「▷ 執行工作流/■ 停止」;拖曳空白處移動、⌘+滾輪或捏合縮放;下面工具列「選取、拖曳|畫筆、便利貼、形狀、文字|搜尋|+ 新增節點」;左下縮放、符合畫面、小地圖。點卡片在右邊改設定,Delete 刪掉選到的。 +- 畫和註解:畫筆、便利貼(六色、寫誰貼的、雙擊改字)、形狀、文字,只給人看、不會執行。 +- 執行:照線從觸發器往下(一張接到好幾張時上面的先、再左邊)。Bot 步驟是那個 Bot 聊天裡的一則「[工作流「名稱」第 k/n 步]…」加上一步的結果,它這一輪最後的回答交給下一步(它正忙就排在後面)。檢查回「通過」才往下。等你確認在畫布上方一條「繼續/停止」,並發通知。一次只跑一個,排程到了自動跑;卡片標完成、進行中、等你確認、失敗;執行紀錄留 20 次。 +- 版本歷史:停手 20 秒、關畫布、每次執行前、Bot 每次改之前各留一版,最多 30 版,點一版就還原。 +- 在聊天裡做:跟 Bot 用一般的話說要什麼流程(「每天早上 9 點去 Threads 找 5 則熱門育兒討論,整理好先問我,我說可以再傳給我」),Bot 用 `workflow` 工具建立、看、改(加步驟、改內容、刪步驟、連線、貼便利貼、整理排版)、執行、停止、刪除(刪除先問)。你看著那個 Bot 的聊天時,畫布自動開在聊天旁邊(視窗夠寬時),它改到的卡片和便利貼亮一下,跑出畫面就縮到看得到全部;Bot 做的排成一欄,插在中間時後面的往下移,你自己排過的不重排。旁邊的聊天跟著側邊欄選的 Bot 換。 +- 手機沒有畫布:在聊天裡請 Bot 做、改、跑,它用文字說工作流的樣子;「等你確認」的通知會到手機,按「繼續」要在電腦上。螢幕電腦只能看。 + ## 26. Bot 可以直接操作 App 的功能 你可以跟 Bot 說「每天早上 9 點幫我…」「把你換成 Claude」「切成深色模式」,它會自己操作 App。 diff --git a/docs/feature-map/README.md b/docs/feature-map/README.md index 2553db5..ab64906 100644 --- a/docs/feature-map/README.md +++ b/docs/feature-map/README.md @@ -88,6 +88,7 @@ Bot 讀得到的是開頭、子功能、使用者怎麼到、Bot 那一行和沒 ### 自己會動 - [routines](routines.md):排程與事件觸發、執行紀錄、完成條件、自動暫停。 +- [workflow](workflow.md):工作流:畫布上的步驟(Bot 步驟、等你確認、檢查、交付、通知)、畫和便利貼、執行與紀錄、版本歷史;在聊天裡請 Bot 做和改,畫布開在聊天旁邊。 - [goal](goal.md):/goal:沒達成就繼續做、評審只看證據。 - [plan](plan.md):/plan:先查清楚、交計畫給你核准,核准後才動手、照步驟打勾。 - [activity](activity.md):操作紀錄:每一輪誰發起、看了/寫了/執行了什麼、工具次數、失敗、花多久;電腦版右側「動態」、手機「稽核」。 diff --git a/docs/feature-map/library.md b/docs/feature-map/library.md index c7b8e8f..5ca83ab 100644 --- a/docs/feature-map/library.md +++ b/docs/feature-map/library.md @@ -13,7 +13,7 @@ ## 使用者怎麼到 -- 側邊欄最上面一排第一個(資料夾圖示,滑過寫「所有檔案」),在任務按鈕左邊。 +- 側邊欄最上面一排第一個(資料夾圖示,滑過寫「所有檔案」),在工作流按鈕左邊。 - 左下角帳戶那一列的選單 ›「所有檔案…」。 - 只看這個對話的檔案:右側面板「資料庫」([deliver](deliver.md));手機在「對話詳細資訊 › 資料庫」。 @@ -26,8 +26,8 @@ - 基本前提和「手機已登入」(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-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=120,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=120,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=120,30@440;1033,127@470;450,267@500'`。看到:視窗沒有跳動;每列「名稱……驗證小幫手 · 今天 HH:MM · 31 B」,舊的.txt 右邊紅字「不見了」;release-notes-v4.md 在 AnyBot 的檢視器打開:「發布計畫」「11/22 上線」,右上「用其他 App 打開」、下載、關閉。帳戶選單的「所有檔案…」、搜尋、選某個 Bot:靠自動測試和版面檢查。 +- **格子、分類、不見了**(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-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:靠自動測試和版面檢查。 - 自動測試:`cargo test app::library_ui::`、`cargo test layout_audit::`(「所有檔案」這一景)。 ## 陷阱 diff --git a/docs/feature-map/profile.md b/docs/feature-map/profile.md index 5178e93..52ba8ad 100644 --- a/docs/feature-map/profile.md +++ b/docs/feature-map/profile.md @@ -6,7 +6,7 @@ - `profile-editor` 「Bot 設定」:「Bot 資料」(「Bot 名稱」「Bot 描述」和大頭像,同一張卡);「個人檔案」(Soul 與指示、擅長(什麼事找它)、不找它做的事);「頭像」(14 種形狀平均排成兩列;10 種顏色和「自訂」同一列;按「自訂」出現一格一格的色盤——12 個色相各四種深淺加一列灰階,直接點,沒有滑桿——和「色碼」欄,打完整的 #rrggbb 才換色);「AI 供應商與模型」(見 [models](models.md));接著「電腦操作」「能力」「技能」「記憶」四張預設收起,各只有一行:名稱、目前怎麼設(例如「11 / 11 類」「會 8 / 8」「還沒有」)和 ▸,點了才展開;最下面「釘選到側邊欄」「團隊成員可以使用這個 Bot」(「?」說明:團隊成員看得到它的聊天、頁面和檔案)。 - `profile-roster` Soul 與指示只有它自己讀;描述、擅長、不找它做的事、會的技能、在哪幾台電腦做事會寫進其他 Bot 的同事名冊。 -- `profile-abilities` 能力 11 類:「上網」「瀏覽器」「看螢幕與操作」「檔案與指令」「Mac App」「連接器」「電話、簡訊、X」「例行任務」「頁面」「和其他 Bot 合作」「管理 App」。沒勾的工具不提供給它,也不寫進說明。記憶、技能、問你問題、傳檔案到聊天、表情和卡片每個 Bot 都有。 +- `profile-abilities` 能力 11 類:「上網」「瀏覽器」「看螢幕與操作」「檔案與指令」「Mac App」「連接器」「電話、簡訊、X」「例行任務與工作流」「頁面」「和其他 Bot 合作」「管理 App」。沒勾的工具不提供給它,也不寫進說明。記憶、技能、問你問題、傳檔案到聊天、表情和卡片每個 Bot 都有。 - `profile-self` Bot 自己讀(`my_profile`)和改(`update_my_profile`)自己的個人檔案、能力、技能、電腦、模型、頭像;改之前先跳確認卡片列出每一項,按允許才生效。 ## 使用者怎麼到 diff --git a/docs/feature-map/workflow.md b/docs/feature-map/workflow.md new file mode 100644 index 0000000..e28c444 --- /dev/null +++ b/docs/feature-map/workflow.md @@ -0,0 +1,44 @@ +# 工作流 + +把好幾步串成一條流程,畫在畫布上:觸發器(手動,或也照排程)接著 Bot 步驟、等你確認、檢查、交付、通知你,每一步的結果交給下一步。可以自己在畫布上拉,也可以在聊天裡請 Bot 做、改、跑:畫布開在那個 Bot 的聊天旁邊,你看著它改。旁邊可以畫線、貼便利貼、寫字當註解(不會執行)。畫布只在電腦版。 + +## 子功能 + +- `workflow-canvas` 畫布:左上是名稱,按下去是選單(每個工作流和它的步驟數、新建工作流、版本歷史、重新命名、建立副本、刪除工作流);右上「聊天」(聊天放在旁邊或收起來)、「執行紀錄」、「▷ 執行工作流」(跑的時候變「■ 停止」)。點點底的畫布拖曳空白處移動、⌘+滾輪或捏合縮放;下面工具列「選取、拖曳|畫筆、便利貼、形狀、文字|搜尋|+ 新增節點」,左下「- 百分比 +|符合畫面|小地圖」。搜尋卡片和註解的字,Enter 跳到下一個。視窗窄時縮放列移到工具列上面。 +- `workflow-nodes` 卡片:觸發器(手動,或每天、每週…的排程,寫「下次執行」,有「立即執行」)、Bot 步驟(哪個 Bot、要它做什麼)、等你確認(問你的話)、檢查(哪個 Bot、要做到什麼才通過)、交付(結果放進哪個 Bot 的聊天)、通知你(「{結果}」換成上一步結果的第一行)。從卡片底下的點拉到另一張卡就連線;不能連回觸發器、不能繞成一圈。點卡片在右邊改設定;Delete 刪掉選到的卡片或線(觸發器刪不掉)。 +- `workflow-draw` 畫和註解:畫筆、便利貼(六種顏色,下面寫誰貼的,雙擊改字)、形狀、文字;點選後右邊換顏色、改文字、刪除。只是給人看,不會執行。 +- `workflow-run` 執行:照線從觸發器往下走(一張接到好幾張時,上面的先,再左邊)。Bot 步驟是那個 Bot 聊天裡的一則訊息「[工作流「名稱」第 k/n 步]…」加上上一步的結果,它這一輪最後的回答就是這一步的結果;它正忙就排在後面,等它做完手上那一輪。檢查要回「通過」才往下,否則停下並寫原因。等你確認:畫布上方一條「等你確認:…」,「繼續」/「停止」,並發通知(電腦和手機)。交付把結果放進那個 Bot 的聊天;通知你發通知。一次只跑一個;排程到了自動跑。卡片上標完成、進行中、等你確認、失敗;「執行紀錄」留最近 20 次(誰開始的、每一步的結果、為什麼停)。 +- `workflow-chat` 聊出來:在聊天裡請 Bot 做工作流,它用 `workflow` 工具建立、看、改(加步驟、改內容、刪步驟、連線、貼便利貼、整理排版)、執行、停止、刪除(刪除先問你)。你正看著那個 Bot 的聊天時,畫布自動開在聊天旁邊,跳到那個工作流,它改到的卡片和便利貼亮一下;跑出畫面就自動縮放到看得到全部。Bot 做的排成一欄,插在中間時後面的往下移;你自己排過的不重排。旁邊的聊天跟著側邊欄選的 Bot 換。 +- `workflow-versions` 版本歷史:改完停手 20 秒、關掉畫布、每次執行前、Bot 每次改之前,各留一版(一樣的不重複留),最多 30 版;選單 › 版本歷史點一版就還原,還原前先留目前的樣子。 + +## 使用者怎麼到 + +- 側邊欄最上面一排第二個(流程圖示,滑過寫「工作流」),在所有檔案和任務中間;再按一次回到聊天。左上「‹ 聊天」也回到聊天。 +- 在 Bot 的聊天裡說「幫我做一個…的工作流」:畫布開在聊天旁邊(視窗夠寬時;右上「聊天」收起或放回)。 +- 手機沒有畫布:在聊天裡請 Bot 做、改、跑,它用文字說工作流長怎樣;「等你確認」的通知會到手機,但要在電腦上按「繼續」。 + +## 怎麼操作(verify-anybot) + +- Bot:使用者要一套多步驟的流程(好幾步、好幾個 Bot、中間要確認或檢查),用 `workflow`:先 create 帶好 steps,之後一次一個 edit,每次用一句話說改了什麼;改不是自己剛做的先 show 看編號;解釋或提問就貼 notes。只是一件事照排程做,用 `create_routine`。 + +前提: + +- 基本前提和「手機已登入」(README),開著 Bot 1 的聊天:`$CTL phone click '.row[data-bot="1"]'`。桌面的步驟要開視窗(`ABV_ALLOW_WINDOW=1`,先 `ctl stop`),座標照 1400×900。 + +- **聊天裡建立**(covers `workflow-chat`、`workflow-nodes`、`workflow-draw`):請 Bot 做一個早報工作流。指令:`$CTL phone send '幫我做早報工作流 [[call workflow {"action":"create","name":"Threads 早報","schedule":{"frequency":"daily","time":"09:00"},"steps":[{"kind":"step","prompt":"找 5 則熱門育兒討論,每則附連結"},{"kind":"check","condition":"每則都有連結"},{"kind":"approve","prompt":"要把早報傳給你嗎?"},{"kind":"notify","text":"早報好了:{結果}"}],"notes":[{"text":"週末改十點?","near":2}]}]]' && $CTL phone wait-text '已建立工作流 #1' --in '#msgs' 60 && $CTL phone shot workflow-create && $CTL state '.workflows[0] | {name, nodes: [.nodes[] | {id, t: .kind.type, x, y}], edges, notes: [.notes[] | {text, author, x, y}]}'`。看到:聊天裡「工作流」那一步完成,回答列出 #1 觸發器 → #2 … #5 和便利貼;state 裡五張卡 x 都是 0、y 每張差 190,線 1→2→3→4→5,便利貼在 #2 左邊、作者「驗證小幫手」。 +- **聊天裡修改**(covers `workflow-chat`、`workflow-versions`):在「等你確認」後面插一步交付,再貼一張綠色便利貼。指令:`$CTL phone send '確認後也放到聊天 [[call workflow {"action":"edit","steps":[{"kind":"deliver","after":4}],"notes":[{"text":"交付會放進這個聊天","near":4,"color":"green"}]}]]' && $CTL phone wait-text '已修改工作流 #1' --in '#msgs' 60 && $CTL state '.workflows[0] | {order: [.edges[] | [.from, .to]], ys: [.nodes[] | [.id, .y]], versions: (.versions | length)}'`。看到:回答「新增 #7;加了 1 張便利貼」;線 4→7→5,#5 往下移到 950、#7 在 760;versions 是 1(改之前的樣子)。 +- **聊天裡執行**(covers `workflow-run`、`workflow-chat`):檢查的回答指定成「通過」,請 Bot 跑一次。指令:`$CTL model-reply '步・檢查' '通過' && $CTL phone send '跑一次 [[call workflow {"action":"run"}]]' && $CTL phone wait-text '已開始執行「Threads 早報」' --in '#msgs' 60 && $CTL phone wait-text '[工作流「Threads 早報」第 1/5 步]' --in '#msgs' 60 && $CTL phone wait-text '步・檢查' --in '#msgs' 60 && $CTL wait-api /api/bots/1 '.messages[-1].text == "通過"' 60 && $CTL phone shot workflow-run`。看到:同一個聊天裡先是第 1/5 步的問題和 Bot 的回答,再是第 2/5 步・檢查和最後一則「通過」。 +- **畫布在聊天旁邊**(covers `workflow-canvas`、`workflow-run`、`workflow-draw`):在電腦上打開畫布。指令:要開視窗——`$CTL phone stop && $CTL stop && $CTL state '.workflows[0].runs[-1] | {state, at, by, steps: [.steps[] | [.node, .state]]}' && ABV_ALLOW_WINDOW=1 $CTL desktop-shot workflow-beside ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_VIEW=workflow ANYBOT_SHOT_SIZE=1400x900 ANYBOT_SHOT_FRAMES=520`。看到:state 的 run 是 waiting、at 3、by「驗證小幫手」,#1–#3 done;左邊畫布「Threads 早報」,上方「等你確認:要把早報傳給你嗎? 繼續 停止」沒有蓋到卡片,觸發器、Bot 步驟、檢查標「完成」,等你確認是黃框;黃、綠便利貼在卡片左邊;右上「等你確認、執行紀錄、聊天、■ 停止」;右邊是驗證小幫手的聊天,最下面是「通過」。 +- **在旁邊聊、畫布跟著變**(covers `workflow-chat`、`workflow-canvas`):在旁邊的聊天打字請它加一步。指令:要開視窗——`ABV_ALLOW_WINDOW=1 $CTL desktop-shot workflow-live ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_VIEW=workflow ANYBOT_SHOT_SIZE=1400x900 ANYBOT_SHOT_FRAMES=600 'ANYBOT_SHOT_CLICK=1180,847@525' 'ANYBOT_SHOT_TYPE=通知前先檢查格式 [[call workflow {"action":"edit","steps":[{"kind":"check","condition":"是條列清單","after":7}],"notes":[{"text":"這步是在聊天裡加的","near":7,"color":"blue"}]}]]@530' 'ANYBOT_SHOT_KEYS=Enter@540'`。看到:聊天裡「已修改工作流 #1…新增 #9」;畫布上交付下面多一張「檢查 是條列清單」、左邊一張藍色便利貼,兩個都有黃色光圈;通知你往下移,整個縮到看得到。 +- **自己畫、拉線、搜尋**(covers `workflow-draw`、`workflow-nodes`、`workflow-canvas`):示範資料上貼便利貼打字、從交付底下的點拉線到通知你、搜尋「週末」。指令:要開視窗——`ABV_ALLOW_WINDOW=1 $CTL desktop-shot workflow-sticky ANYBOT_SHOT_VIEW=workflow ANYBOT_SHOT_SIZE=1400x900 ANYBOT_SHOT_FRAMES=44 'ANYBOT_SHOT_CLICK=720,860@20;450,600@26' 'ANYBOT_SHOT_TYPE=記得週末改時間@34' && ABV_ALLOW_WINDOW=1 $CTL desktop-shot workflow-link ANYBOT_SHOT_VIEW=workflow ANYBOT_SHOT_SIZE=1400x900 ANYBOT_SHOT_FRAMES=40 'ANYBOT_SHOT_DRAG=740,747>965,725@24' && ABV_ALLOW_WINDOW=1 $CTL desktop-shot workflow-search ANYBOT_SHOT_VIEW=workflow ANYBOT_SHOT_SIZE=1400x900 ANYBOT_SHOT_FRAMES=48 'ANYBOT_SHOT_CLICK=844,860@20' 'ANYBOT_SHOT_TYPE=週末@26' 'ANYBOT_SHOT_KEYS=Enter@32'`。看到:新的便利貼框著、裡面是「記得週末改時間」、作者 daniel,右邊便利貼的顏色和刪除;交付底下多一條線連到通知你(交付沒被拖走);搜尋框裡「週末」、旁邊「1/1」,畫面移到「週末改成十點」那張並選起來。版本歷史、選單、窄視窗:靠自動測試和版面檢查。 +- 自動測試:`cargo test workflow`、`cargo test layout_audit::`(「工作流」四景)、`cargo test theme::`。 + +## 陷阱 + +- 沒接上觸發器的卡片不會執行;Bot 的回答會寫「沒接上觸發器的(不會執行)」。 +- Bot 步驟用那個 Bot 自己的聊天:它正忙(例如就是它叫開始的那一輪),第一步排在後面,等那一輪結束才問。 +- 檢查的回答要以「通過」或「不通過:原因」開頭,看不出來算失敗。 +- 改正在跑的工作流:那次照開始時的步驟走,刪掉的步驟輪到時會停下來。 +- 螢幕電腦只能看:工作流在大腦上改和跑。 +- (驗證)有真資料的桌面截圖前 500 格左右是啟動畫面:`ANYBOT_SHOT_FRAMES` 至少 520。 +- (驗證)假模型的回答不是「通過」開頭:跑到檢查之前先 `$CTL model-reply '步・檢查' '通過'`。 diff --git a/docs/plan-2026-11-openbot.md b/docs/plan-2026-11-openbot.md index 55bc31f..467f179 100644 --- a/docs/plan-2026-11-openbot.md +++ b/docs/plan-2026-11-openbot.md @@ -176,7 +176,7 @@ - 動哪裡:`src/tools.rs` 的 `specs`(工具定義有鎖檔:`tool_specs_are_locked` 要刻意更新、要實機測試和你簽名)、`src/tasks.rs`。 - 做完:交接、逾時、重試、卡住四種情況各一個測試;任務頁看得到交接鏈。 -**D4. 工作流存成資料** +**D4. 工作流存成資料**——11/21 做了第一步:工作流畫布(觸發器、Bot 步驟、等你確認、檢查、交付、通知你;畫筆、便利貼、形狀、文字;執行紀錄、版本歷史),存成結構(State.workflows),執行時照開始那一刻的順序走、每一步記結果;Bot 用 `workflow` 工具在聊天裡做和改,畫布開在聊天旁邊(功能地圖 workflow.md)。每一步的嘗試次數、「不確定有沒有送到」、例行任務/目標/計畫改用這個結構、手機上的畫布還沒做。 - 現況:例行任務(排程+觸發+**一段 prompt 文字**)、計畫(模型寫的步驟標題)、目標(第二個模型評)、追進度(檢查指令)是四個分開的東西,沒有一條存下來的流程。 - 做什麼:流程存成結構,不靠 prompt 描述:觸發 → 計畫 → 步驟 → 允許 → 驗收 → 交付 → 通知。每次執行把當時的流程整份存下(之後改流程不影響已經在跑的)、 每一步記第幾次嘗試、輸入、輸出、結果;交付有「不確定有沒有送到」這個狀態(OpenBot 有);驗收步驟(OpenBot 沒有)。 diff --git a/icons/lucide/bell.svg b/icons/lucide/bell.svg new file mode 100644 index 0000000..511e256 --- /dev/null +++ b/icons/lucide/bell.svg @@ -0,0 +1,16 @@ + + + + + diff --git a/icons/lucide/hand.svg b/icons/lucide/hand.svg new file mode 100644 index 0000000..c6e7220 --- /dev/null +++ b/icons/lucide/hand.svg @@ -0,0 +1,18 @@ + + + + + + + diff --git a/icons/lucide/map.svg b/icons/lucide/map.svg new file mode 100644 index 0000000..3857a7c --- /dev/null +++ b/icons/lucide/map.svg @@ -0,0 +1,17 @@ + + + + + + diff --git a/icons/lucide/mouse-pointer-2.svg b/icons/lucide/mouse-pointer-2.svg new file mode 100644 index 0000000..c675bf8 --- /dev/null +++ b/icons/lucide/mouse-pointer-2.svg @@ -0,0 +1,15 @@ + + + + diff --git a/icons/lucide/scan.svg b/icons/lucide/scan.svg new file mode 100644 index 0000000..b732124 --- /dev/null +++ b/icons/lucide/scan.svg @@ -0,0 +1,18 @@ + + + + + + + diff --git a/icons/lucide/send.svg b/icons/lucide/send.svg new file mode 100644 index 0000000..60d415d --- /dev/null +++ b/icons/lucide/send.svg @@ -0,0 +1,16 @@ + + + + + diff --git a/icons/lucide/sticky-note.svg b/icons/lucide/sticky-note.svg new file mode 100644 index 0000000..9e5ea07 --- /dev/null +++ b/icons/lucide/sticky-note.svg @@ -0,0 +1,16 @@ + + + + + diff --git a/icons/lucide/type.svg b/icons/lucide/type.svg new file mode 100644 index 0000000..e5b2bdf --- /dev/null +++ b/icons/lucide/type.svg @@ -0,0 +1,17 @@ + + + + + + diff --git a/icons/lucide/workflow.svg b/icons/lucide/workflow.svg new file mode 100644 index 0000000..255e1e9 --- /dev/null +++ b/icons/lucide/workflow.svg @@ -0,0 +1,17 @@ + + + + + + diff --git a/src/app.rs b/src/app.rs index 2beab65..66f2a7f 100644 --- a/src/app.rs +++ b/src/app.rs @@ -46,6 +46,8 @@ mod me_ui; mod activity_ui; mod library_ui; mod market_ui; +mod workflow_run; +mod workflow_ui; mod settings_find; mod memory_ui; mod goal_ui; @@ -357,6 +359,8 @@ pub struct App { lib: library_ui::LibraryUi, /// 市集: connectors, skills and bot templates as cards (market_ui.rs). market: market_ui::MarketUi, + /// 工作流: the canvas and the runs it drives (workflow_ui.rs, workflow_run.rs). + wf: workflow_ui::WfUi, drop_last: String, nightly_checked: Option, /// Files and pictures waiting to go with the next message. @@ -629,6 +633,7 @@ impl App { act: Default::default(), lib: Default::default(), market: Default::default(), + wf: Default::default(), drop_last: String::new(), nightly_checked: None, att: Default::default(), @@ -757,6 +762,8 @@ impl App { Ok("library") => app.lib.open = true, // 市集. Ok("market") => app.market.open = true, + // 工作流: a sample on the canvas. + Ok("workflow") => app.wf_demo(), // 在哪一台 (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.) Ok("whose") => { @@ -1405,6 +1412,8 @@ impl App { Ok("library") => app.lib.open = true, // 市集. Ok("market") => app.market.open = true, + // 工作流: the real ones on the canvas (the chat beside it). + Ok("workflow") => app.wf_open(), Ok("computers") => { app.show_settings = true; app.settings_tab = SettingsTab::Computers; @@ -2367,6 +2376,8 @@ impl App { /// Record how a turn ended (success / cancelled / error) and clear its live state. fn settle(&mut self, bot_id: u64, outcome: TurnOutcome) { self.note_routine_run(bot_id, outcome); + // 工作流: a step this bot was working on has its result. + self.wf_turn_ended(bot_id, outcome); // 問同事: the question this turn answered gets its answer; the ones it put to others are // over (it can't wait any more). self.ask_answered(bot_id, outcome); @@ -2607,6 +2618,7 @@ impl App { self.last_tick = Instant::now(); self.tend_garden(); self.tend_screens(); + self.tick_workflows(ctx); self.resume_interrupted(ctx); let now = crate::routines::now(); let mut fire = vec![]; @@ -2676,6 +2688,11 @@ impl App { self.ask_bot(ctx, bot_id, call); return; } + // 工作流: on the workflows, with the canvas beside the chat (workflow_run.rs). + if call.name == crate::workflow::TOOL { + self.workflow_tool(ctx, bot_id, call); + return; + } // 管理連接器: answered once the connector has connected (or said why not). if call.name == crate::mcp::MANAGE_TOOL { self.manage_connectors(ctx, call); @@ -4067,100 +4084,119 @@ impl App { fn main_pane(&mut self, root: &mut egui::Ui) { let p = self.pal; - let ctx = &root.ctx().clone(); + // 工作流: 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. + if self.wf.open { + if self.wf_chat_beside(root.available_width()) { + let w = (root.available_width() * 0.36).clamp(340.0, 440.0); + egui::Panel::right("wf-chat").exact_size(w).resizable(false).frame(Frame::new().fill(p.pane)).show(root, |ui| { + let r = ui.max_rect(); + ui.painter().vline(r.left(), r.y_range(), Stroke::new(1.0, p.border)); + self.chat_column(ui); + }); + } + egui::CentralPanel::default().frame(Frame::new().fill(p.pane)).show(root, |ui| self.workflow_pane(ui)); + return; + } if let Some(bot) = self.state.bot(self.state.selected).cloned() { self.bot_panel(root, &bot); } - egui::CentralPanel::default().frame(Frame::new().fill(p.pane)).show(root, |ui| { - let id = self.state.selected; - if self.state.bots.is_empty() { - self.mirror_banner(ui); - self.welcome(ui); - return; - } - let Some(bot) = self.state.bot(id).cloned() else { - ui.centered_and_justified(|ui| ui.label(RichText::new(t("未選取 Bot")).color(p.text3))); - return; - }; - self.header(ui, &bot); + egui::CentralPanel::default().frame(Frame::new().fill(p.pane)).show(root, |ui| self.chat_column(ui)); + } + + /// The chat of the bot picked: its top, the messages, the input (in the middle, or beside + /// the 工作流 canvas). + fn chat_column(&mut self, ui: &mut egui::Ui) { + let p = self.pal; + let ctx = &ui.ctx().clone(); + let id = self.state.selected; + if self.state.bots.is_empty() { self.mirror_banner(ui); - // The composer grows with a long draft: keep room for last frame's height. - let h_id = egui::Id::unique("composer-height"); - let composer_h: f32 = ui.data(|d| d.get_temp(h_id)).unwrap_or(116.0); - let avail = ui.available_height() - composer_h; - let w = ui.available_width(); - let col_w = (w - 48.0).min(TRANSCRIPT_MAX_WIDTH); - let pad = ((w - col_w) / 2.0).max(0.0); - let jumping = self.jump_bottom.is_some(); - let out = egui::ScrollArea::vertical() - .id_salt(("transcript", id)) - .auto_shrink([false, false]) - .max_height(avail) - .stick_to_bottom(self.stick_bottom) - .show(ui, |ui| { - ui.horizontal(|ui| { - ui.add_space(pad); - ui.vertical(|ui| { - ui.set_width(col_w); - // 訊息堆的呼吸:一则和下一则之间留足空白(天眼下的节奏:块与块 - // 之间 14px,紧组内部才用 6~8)。 - ui.spacing_mut().item_spacing.y = if self.state.dense { 11.0 } else { 14.0 }; - ui.add_space(18.0); - if bot.messages.is_empty() { - self.empty_state(ui, &bot); - } - let n = bot.messages.len(); - for (i, m) in bot.messages.iter().enumerate() { - let last = i + 1 == n; - self.msg_index = i; - let top = ui.cursor().top(); - self.chat_message(ui, ctx, &bot, m, last); - // 搜尋 → 那則訊息: scroll to it and light it for a moment. - if let Some(g) = self.goto.filter(|g| g.is(bot.id, i, m.at)) { - let rect = egui::Rect::from_min_max(egui::pos2(ui.min_rect().left() - 8.0, top - 4.0), egui::pos2(ui.min_rect().right() + 8.0, ui.cursor().top() - 4.0)); - let age = g.since.elapsed().as_secs_f32(); - if age < crate::find::GOTO_SCROLL_SECS { - ui.scroll_to_rect(rect, Some(Align::Center)); - } - let k = (1.0 - age / crate::find::GOTO_LIGHT_SECS).clamp(0.0, 1.0); - ui.painter().rect_filled(rect, R_M, self.pal.attention.gamma_multiply(0.28 * k)); - if k > 0.0 { - ui.ctx().request_repaint_after(anim_after(50)); - } else { - self.goto = None; - } + self.welcome(ui); + return; + } + let Some(bot) = self.state.bot(id).cloned() else { + ui.centered_and_justified(|ui| ui.label(RichText::new(t("未選取 Bot")).color(p.text3))); + return; + }; + self.header(ui, &bot); + self.mirror_banner(ui); + // The composer grows with a long draft: keep room for last frame's height. + let h_id = egui::Id::unique("composer-height"); + let composer_h: f32 = ui.data(|d| d.get_temp(h_id)).unwrap_or(116.0); + let avail = ui.available_height() - composer_h; + let w = ui.available_width(); + let col_w = (w - 48.0).min(TRANSCRIPT_MAX_WIDTH); + let pad = ((w - col_w) / 2.0).max(0.0); + let jumping = self.jump_bottom.is_some(); + let out = egui::ScrollArea::vertical() + .id_salt(("transcript", id)) + .auto_shrink([false, false]) + .max_height(avail) + .stick_to_bottom(self.stick_bottom) + .show(ui, |ui| { + ui.horizontal(|ui| { + ui.add_space(pad); + ui.vertical(|ui| { + ui.set_width(col_w); + // 訊息堆的呼吸:一则和下一则之间留足空白(天眼下的节奏:块与块 + // 之间 14px,紧组内部才用 6~8)。 + ui.spacing_mut().item_spacing.y = if self.state.dense { 11.0 } else { 14.0 }; + ui.add_space(18.0); + if bot.messages.is_empty() { + self.empty_state(ui, &bot); + } + let n = bot.messages.len(); + for (i, m) in bot.messages.iter().enumerate() { + let last = i + 1 == n; + self.msg_index = i; + let top = ui.cursor().top(); + self.chat_message(ui, ctx, &bot, m, last); + // 搜尋 → 那則訊息: scroll to it and light it for a moment. + if let Some(g) = self.goto.filter(|g| g.is(bot.id, i, m.at)) { + let rect = egui::Rect::from_min_max(egui::pos2(ui.min_rect().left() - 8.0, top - 4.0), egui::pos2(ui.min_rect().right() + 8.0, ui.cursor().top() - 4.0)); + let age = g.since.elapsed().as_secs_f32(); + if age < crate::find::GOTO_SCROLL_SECS { + ui.scroll_to_rect(rect, Some(Align::Center)); + } + let k = (1.0 - age / crate::find::GOTO_LIGHT_SECS).clamp(0.0, 1.0); + ui.painter().rect_filled(rect, R_M, self.pal.attention.gamma_multiply(0.28 * k)); + if k > 0.0 { + ui.ctx().request_repaint_after(anim_after(50)); + } else { + self.goto = None; } } - self.sending_bubbles(ui, &bot); - self.mirror_queue_bubbles(ui, &bot); - // (What it is doing, and a request, sit above the input: see composer. - // A hand-off keeps its card here, with the live screen; so does a - // question — it scrolls with the chat instead of covering it.) - self.approval_card(ui, ctx, &bot); - ui.add_space(16.0); - // Last in the content, so no code block's own scroll area takes it. - if jumping { - ui.scroll_to_cursor(Some(Align::BOTTOM)); - } - }); + } + self.sending_bubbles(ui, &bot); + self.mirror_queue_bubbles(ui, &bot); + // (What it is doing, and a request, sit above the input: see composer. + // A hand-off keeps its card here, with the live screen; so does a + // question — it scrolls with the chat instead of covering it.) + self.approval_card(ui, ctx, &bot); + ui.add_space(16.0); + // Last in the content, so no code block's own scroll area takes it. + if jumping { + ui.scroll_to_cursor(Some(Align::BOTTOM)); + } }); }); - let from_bottom = (out.content_size.y - out.inner_rect.height() - out.state.clamped_offset().y).max(0.0); - self.jump_bottom_button(ui, out.inner_rect, from_bottom); - let top = ui.cursor().top(); - ui.horizontal(|ui| { - ui.add_space(pad); - ui.vertical(|ui| { - ui.set_width(col_w); - self.composer(ui, ctx, &bot); - }); }); - let used = ui.cursor().top() - top; - if (used - composer_h).abs() > 0.5 { - ui.data_mut(|d| d.insert_temp(h_id, used)); - ui.ctx().request_repaint(); - } + let from_bottom = (out.content_size.y - out.inner_rect.height() - out.state.clamped_offset().y).max(0.0); + self.jump_bottom_button(ui, out.inner_rect, from_bottom); + let top = ui.cursor().top(); + ui.horizontal(|ui| { + ui.add_space(pad); + ui.vertical(|ui| { + ui.set_width(col_w); + self.composer(ui, ctx, &bot); + }); }); + let used = ui.cursor().top() - top; + if (used - composer_h).abs() > 0.5 { + ui.data_mut(|d| d.insert_temp(h_id, used)); + ui.ctx().request_repaint(); + } } /// The top of the chat, like the original: no bar — the bot's name in a rounded pill in the @@ -7907,6 +7943,7 @@ fn system_prompt(b: &Bot, st: &State, computers: &[tools::Target], default_compu let mut app: Vec = Vec::new(); if has(b, "routines") { app.push("- 使用者想定期或在某個時間做事(每天、每週一、每月一號、提醒我…),就用 create_routine 設成例行任務;時間照使用者的時區。查看、修改、暫停、刪除用 list_routines / update_routine / delete_routine。".into()); + app.push("- 使用者要一套多步驟的流程(好幾步、好幾個 Bot、中間要他確認或要檢查結果),或說「工作流」「流程」,就用 workflow 做在畫布上:使用者在聊天旁邊看著畫布跟著你改。先 create 把步驟放好,再一次一個 edit 調整,每次用一句話說改了什麼;改別人做的先 show 看編號;要解釋或提問就貼便利貼(notes)。".into()); } if has(b, "admin") { app.push("- 換模型或供應商、改名字、建立新 Bot:update_bot / create_bot;看有哪些 Bot:list_bots。".into()); diff --git a/src/app/chat_ui.rs b/src/app/chat_ui.rs index f17ce11..4c7fae0 100644 --- a/src/app/chat_ui.rs +++ b/src/app/chat_ui.rs @@ -196,6 +196,7 @@ fn doing(name: &str, args: &str, place: Option<&str>) -> String { "ask_bot" => with("正在問另一個 Bot", s("bot")), "teach_skill" => with("正在教技能給", s("bot")), "list_routines" => "正在查看例行任務".into(), + crate::workflow::TOOL => "正在改工作流".into(), crate::tasks::TOOL => "正在查看任務".into(), "create_routine" | "update_routine" | "delete_routine" => "正在安排例行任務".into(), "run_routine_now" => "正在執行例行任務".into(), diff --git a/src/app/kit.rs b/src/app/kit.rs index c1f9ee1..a9c3c7b 100644 --- a/src/app/kit.rs +++ b/src/app/kit.rs @@ -299,6 +299,12 @@ pub(super) fn fold_title(ui: &mut egui::Ui, p: Palette, id: impl std::hash::Hash open } +/// Something floating over a canvas (工作流: the toolbar, the zoom, the settings at the right, +/// the 等你確認 bar): the raised fill, a thin edge, large corners. +pub(super) fn floating(ui: &mut egui::Ui, p: Palette, edge: Color32, margin: Margin, body: impl FnOnce(&mut egui::Ui) -> R) -> egui::InnerResponse { + Frame::new().fill(p.elevated).stroke(Stroke::new(1.0, edge)).corner_radius(R_L).inner_margin(margin).show(ui, body) +} + /// The card of something waiting for you — an approval, a question, a step handed to you on a /// computer: the one yellow (yellow means 「需要你」 everywhere), a soft tint and a thin edge. /// One look for all three (the hand-off card used to be outlined in the accent and read as red). diff --git a/src/app/layout_audit.rs b/src/app/layout_audit.rs index 7b57bc8..fb21a05 100644 --- a/src/app/layout_audit.rs +++ b/src/app/layout_audit.rs @@ -173,6 +173,41 @@ fn scenes() -> Vec<(&'static str, Open)> { a.market.open = true; }), ), + // 工作流: the canvas waiting at its confirm; a step's side panel; the run log; a very long + // name with long words in every card. + ("工作流", Box::new(|a: &mut App| a.wf_demo())), + ( + "工作流 › 一個 Bot 步驟", + Box::new(|a: &mut App| { + a.wf_demo(); + a.wf.selected = Some(2); + }), + ), + ( + "工作流 › 執行紀錄", + Box::new(|a: &mut App| { + a.wf_demo(); + a.wf.runs_open = true; + }), + ), + ( + "工作流(很長的名字和內容)", + Box::new(|a: &mut App| { + a.wf_demo(); + let w = &mut a.state.workflows[0]; + w.name = "客戶服務部三樓每天早上九點要先看過的 Threads 育兒討論整理和週報".into(); + for n in &mut w.nodes { + match &mut n.kind { + crate::workflow::NodeKind::Step { prompt, .. } => { + *prompt = "到 Threads 找今天熱門的五則育兒討論https://www.threads.net/search?q=%E8%82%B2%E5%85%92&serp_type=default,整理成清單,每則附連結和一句摘要,不要重複上週已經整理過的".into() + } + crate::workflow::NodeKind::Notify { text } => *text = "早報好了,請到聊天看完整的清單:{結果}".repeat(3), + _ => {} + } + } + a.wf.selected = Some(4); + }), + ), // A screen of a brain: each page says at its top whose settings it holds (the longest // sentences are these two). ("設定 › 一般(螢幕電腦)", screen_of_brain(SettingsTab::General)), diff --git a/src/app/sidebar_ui.rs b/src/app/sidebar_ui.rs index 123759f..509b22c 100644 --- a/src/app/sidebar_ui.rs +++ b/src/app/sidebar_ui.rs @@ -345,6 +345,14 @@ impl App { } // 任務: every bot's tasks and how each stands (tasks_ui.rs). self.tasks_button(ui); + // 工作流: the canvas (workflow_ui.rs); again closes it. + if pill_icon(ui, crate::icons::Icon::Workflow, p).on_hover_text(t("工作流")).clicked() { + if self.wf.open { + self.wf_close(); + } else { + self.wf_open(); + } + } // 所有檔案: every file of every bot (library_ui.rs). if pill_icon(ui, crate::icons::Icon::Folder, p).on_hover_text(t("所有檔案")).clicked() { self.lib.open = true; diff --git a/src/app/workflow_run.rs b/src/app/workflow_run.rs new file mode 100644 index 0000000..ca3f371 --- /dev/null +++ b/src/app/workflow_run.rs @@ -0,0 +1,528 @@ +// 工作流 runs (workflow.rs has the shapes): a run goes node by node in the order fixed when it +// started. A bot step (and a 檢查) is a question in that bot's chat, as 問同事 asks one — the +// person sees it there and the bot works with its own model, tools and memories; when that +// turn ends its last words are the step's result, handed on to the next step. 等你確認 waits +// for the person (a notification says so); 交付 puts the result into a bot's chat; 通知你 +// notifies. A step that fails stops the run, and says why. A scheduled trigger starts a run on +// time (checked with the routines, every second); a run that is on never starts twice. + +use super::*; +use crate::workflow::{NodeKind, RunState, StepState, check_message, check_passed, notify_text, step_message}; + +/// How long a 檢查 or a step's answer may be when kept as the step's result (the whole is in +/// the bot's chat). +const OUTPUT_KEPT: usize = crate::workflow::HANDED_ON_CHARS; + +impl App { + /// Start a run of this workflow (by 「手動」 or 「定時」); false when one is on already. + pub(super) fn wf_start(&mut self, ctx: &egui::Context, wf: u64, by: &str) -> bool { + let now = crate::routines::now(); + let Some(w) = self.state.workflows.iter_mut().find(|w| w.id == wf) else { return false }; + if w.live_run().is_some() { + return false; + } + // What was run is kept as a version (版本歷史 shows what each run ran). + w.keep_version(now); + w.start_run(by, now); + self.dirty = true; + self.wf_advance(ctx, wf); + true + } + + /// Stop this workflow's run (a bot working on its step is stopped too). + pub(super) fn wf_stop(&mut self, wf: u64) { + let now = crate::routines::now(); + let mut busy = None; + 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 s.state == StepState::Running { + busy = Some(s.bot).filter(|b| *b != 0); + } + s.state = StepState::Failed; + } + r.state = RunState::Stopped; + r.ended = Some(now); + r.why = "你停止了這次執行".into(); + } + if let Some(b) = busy { + if self.streams.contains_key(&b) { + self.stop(b); + } + } + self.dirty = true; + } + + /// 等你確認: the person's answer. + pub(super) fn wf_confirm(&mut self, ctx: &egui::Context, wf: u64, go: bool) { + let now = crate::routines::now(); + let Some(r) = self.state.workflows.iter_mut().find(|w| w.id == wf).and_then(|w| w.runs.iter_mut().rev().find(|r| r.state == RunState::Waiting)) else { return }; + let last = r.last_output(); + let Some(s) = r.order.get(r.at).copied().and_then(|n| r.steps.iter_mut().find(|s| s.node == n)) else { return }; + if go { + s.state = StepState::Done; + s.output = last; + r.at += 1; + r.state = RunState::Running; + } else { + s.state = StepState::Failed; + r.state = RunState::Stopped; + r.ended = Some(now); + r.why = "你在「等你確認」選了停止".into(); + } + self.dirty = true; + self.wf_advance(ctx, wf); + } + + /// Go on with this workflow's run until a step has to wait (a bot working, the person). + pub(super) fn wf_advance(&mut self, ctx: &egui::Context, wf: u64) { + let now = crate::routines::now(); + loop { + let Some(w) = self.state.workflows.iter().find(|w| w.id == wf) else { return }; + let name = w.name.clone(); + let Some(r) = w.runs.iter().rev().find(|r| r.state == RunState::Running) else { return }; + let (run_id, k, of) = (r.id, r.at, r.order.len().saturating_sub(1)); + let Some(node_id) = r.order.get(r.at).copied() else { + // Past the last step: done. + self.wf_run_mut(wf, run_id, |r| { + r.state = RunState::Done; + r.ended = Some(now); + }); + return; + }; + let state = r.step_of(node_id).map(|s| s.state).unwrap_or(StepState::Waiting); + if state != StepState::Waiting { + // A step underway (a bot is on it): its end moves the run on. + return; + } + let last = r.last_output(); + let Some(kind) = w.node(node_id).map(|n| n.kind.clone()) else { + self.wf_fail(wf, run_id, node_id, "這一步已經被刪掉了"); + return; + }; + match kind { + NodeKind::Trigger { .. } => self.wf_done(wf, run_id, node_id, last), + NodeKind::Step { bot, prompt } => { + if prompt.trim().is_empty() { + self.wf_fail(wf, run_id, node_id, "這一步還沒寫要 Bot 做什麼"); + return; + } + let text = step_message(&name, k, of, &prompt, &last); + self.wf_ask(ctx, wf, run_id, node_id, bot, text); + return; + } + NodeKind::Check { bot, condition } => { + if condition.trim().is_empty() { + self.wf_fail(wf, run_id, node_id, "檢查還沒寫要看什麼"); + return; + } + let text = check_message(&name, k, of, &condition, &last); + self.wf_ask(ctx, wf, run_id, node_id, bot, text); + return; + } + NodeKind::Approve { prompt } => { + self.wf_run_mut(wf, run_id, |r| { + r.state = RunState::Waiting; + if let Some(s) = r.steps.iter_mut().find(|s| s.node == node_id) { + s.state = StepState::Running; + } + }); + let words = if prompt.trim().is_empty() { "要繼續嗎?".to_string() } else { prompt.trim().to_string() }; + let body = format!("等你確認:{words}"); + if !self.headless && !self.demo { + notify::banner_for(&name, &body, true, None, None); + } + crate::remote::notify(crate::remote::Notice::Need, &name, &body, 0); + return; + } + NodeKind::Deliver { bot } => { + let selected = self.state.selected; + let Some(b) = self.state.bot_mut(bot) else { + self.wf_fail(wf, run_id, node_id, "要交付的 Bot 已經不在了"); + return; + }; + 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}」")) }); + if bot != selected { + b.unread = true; + } + self.save_now = true; + self.wf_done(wf, run_id, node_id, last); + } + NodeKind::Notify { text } => { + let words = notify_text(&text, &last); + if !self.headless && !self.demo { + notify::banner_for(&name, &words, true, None, None); + } + crate::remote::notify(crate::remote::Notice::Done, &name, &words, 0); + self.wf_done(wf, run_id, node_id, last); + } + } + } + } + + /// A question to a bot for this step; the step waits for that bot's turn to end. + fn wf_ask(&mut self, ctx: &egui::Context, wf: u64, run: u64, node: u64, bot: u64, text: String) { + if self.state.bot(bot).is_none() { + self.wf_fail(wf, run, node, "這一步選的 Bot 已經不在了"); + return; + } + let msg = Message { at: crate::model::now_ms(), ..Message::user(&text) }; + let at = msg.at; + self.wf_run_mut(wf, run, |r| { + if let Some(s) = r.steps.iter_mut().find(|s| s.node == node) { + s.state = StepState::Running; + s.bot = bot; + s.asked_at = at; + } + }); + // (A busy bot takes it when it is free: wake keeps it.) + self.wake(ctx, bot, msg); + self.dirty = true; + } + + fn wf_run_mut(&mut self, wf: u64, run: u64, f: impl FnOnce(&mut crate::workflow::Run)) { + if let Some(r) = self.state.workflows.iter_mut().find(|w| w.id == wf).and_then(|w| w.runs.iter_mut().find(|r| r.id == run)) { + f(r); + self.dirty = true; + } + } + + fn wf_done(&mut self, wf: u64, run: u64, node: u64, output: String) { + self.wf_run_mut(wf, run, |r| { + if let Some(s) = r.steps.iter_mut().find(|s| s.node == node) { + s.state = StepState::Done; + s.output = output; + } + r.at += 1; + }); + } + + fn wf_fail(&mut self, wf: u64, run: u64, node: u64, why: &str) { + let now = crate::routines::now(); + self.wf_run_mut(wf, run, |r| { + if let Some(s) = r.steps.iter_mut().find(|s| s.node == node) { + s.state = StepState::Failed; + } + r.state = RunState::Failed; + r.ended = Some(now); + r.why = why.to_string(); + }); + } + + /// A bot's turn ended: a workflow step it was working on gets its result (and the run goes + /// on at the next tick, which can start the next bot). + pub(super) fn wf_turn_ended(&mut self, bot: u64, outcome: TurnOutcome) { + let mut found: Vec<(u64, u64, u64, bool, i64)> = vec![]; + for w in &self.state.workflows { + for r in w.runs.iter().filter(|r| r.state == RunState::Running) { + // (Only the turn on the step's question: asked of a bot that was busy — the bot + // that started the run, say — the question waits in line, and the turn that + // ends first isn't the answer.) + let asked = |at: i64| self.state.bot(bot).is_some_and(|b| b.messages.iter().any(|m| m.role == Role::User && m.at == at)); + if let Some(s) = r.current().filter(|s| s.state == StepState::Running && s.bot == bot && asked(s.asked_at)) { + let check = matches!(w.node(s.node).map(|n| &n.kind), Some(NodeKind::Check { .. })); + found.push((w.id, r.id, s.node, check, s.asked_at)); + } + } + } + for (wf, run, node, check, asked_at) in found { + let (answer, ok) = self.wf_answer(bot, asked_at, outcome); + if !ok { + self.wf_fail(wf, run, node, &answer); + } else if check { + match check_passed(&answer) { + Ok(()) => { + // (A check hands on what it checked, not its 「通過」.) + let last = self.state.workflows.iter().find(|w| w.id == wf).and_then(|w| w.runs.iter().find(|r| r.id == run)).map(|r| r.last_output()).unwrap_or_default(); + self.wf_done(wf, run, node, last); + } + Err(why) => self.wf_fail(wf, run, node, &format!("檢查沒通過:{why}")), + } + } else { + self.wf_done(wf, run, node, answer); + } + self.wf.advance.push(wf); + } + } + + /// The bot's last words after the step's question (asked at `at`), or why there are none. + fn wf_answer(&self, bot: u64, at: i64, outcome: TurnOutcome) -> (String, bool) { + let Some(b) = self.state.bot(bot) else { return ("那個 Bot 已經不在了".into(), false) }; + let from = b.messages.iter().rposition(|m| m.role == Role::User && m.at == at).map(|i| i + 1).unwrap_or(b.messages.len()); + let last = b.messages[from..].iter().rev().find(|m| m.role == Role::Assistant && !m.note && !m.text.trim().is_empty()); + match outcome { + TurnOutcome::Success => match last { + Some(m) => (m.text.trim().chars().take(OUTPUT_KEPT).collect(), true), + None => (format!("「{}」做完了,但沒有寫結果", b.name), false), + }, + TurnOutcome::Cancelled => (format!("「{}」被停止了", b.name), false), + _ => (format!("「{}」沒有做完:{}", b.name, last.map(|m| m.text.trim().chars().take(200).collect::()).unwrap_or_default()).trim().to_string(), false), + } + } + + /// The `workflow` tool: a bot makes, changes, runs or stops a workflow from its chat. The + /// change is on the brain's workflows; the canvas opens beside that bot's chat (when the + /// person is looking at it) with what changed lit up. + pub(super) fn workflow_tool(&mut self, ctx: &egui::Context, bot_id: u64, call: AppCall) { + let me = self.state.home_of(bot_id); + let v: serde_json::Value = serde_json::from_str(if call.args.trim().is_empty() { "{}" } else { &call.args }).unwrap_or(serde_json::Value::Null); + let bots: Vec<(u64, String)> = self.state.bots.iter().filter(|b| b.branch_of == 0).map(|b| (b.id, b.name.clone())).collect(); + let tz = self.state.timezone.clone(); + let showing = self.wf.open.then_some(self.wf.current); + let who = crate::workflow::Who { me, bots: &bots, timezone: &tz }; + let (text, ok) = match crate::workflow::tool(&mut self.state.workflows, &who, &v, showing, crate::routines::now()) { + Err(e) => (e, false), + Ok(told) => { + let mut text = told.text; + let id = told.wf.unwrap_or(0); + let name = self.state.workflows.iter().find(|w| w.id == id).map(|w| w.name.clone()).unwrap_or_default(); + if told.run { + let by = self.state.bot(me).map(|b| b.name.clone()).unwrap_or_else(|| "Bot".into()); + text = if self.wf_start(ctx, id, &by) { + let first = self.state.workflows.iter().find(|w| w.id == id).and_then(|w| w.runs.last()).map(|r| format!("(現在:{})", crate::workflow::describe_run(r))).unwrap_or_default(); + format!("已開始執行「{name}」{first}。每個 Bot 步驟會出現在那個 Bot 的聊天裡;跑完、失敗或等使用者確認時會通知他。") + } else { + format!("「{name}」已經在跑了") + }; + } + if told.stop { + self.wf_stop(id); + } + if told.changed || told.run { + self.wf_show_change(bot_id, id, told.touched); + } + // Deleted: the canvas goes to another one (or back to the chat). + if !self.state.workflows.iter().any(|w| w.id == id) && self.wf.current == id { + match self.state.workflows.first().map(|w| w.id) { + Some(other) => self.wf.current = other, + None => self.wf.open = false, + } + } + (text, true) + } + }; + let _ = call.reply.send((text, ok)); + self.dirty = true; + } + + /// Every second (with the routines): runs that can go on, and scheduled triggers that are due. + pub(super) fn tick_workflows(&mut self, ctx: &egui::Context) { + for wf in std::mem::take(&mut self.wf.advance) { + self.wf_advance(ctx, wf); + } + if self.mir.on { + // (A screen shows the brain's; the brain runs them.) + return; + } + let now = crate::routines::now(); + let mut due = vec![]; + for w in self.state.workflows.iter_mut() { + let Some(s) = w.schedule().cloned() else { + w.next_run = None; + continue; + }; + match w.next_run { + None => { + w.next_run = crate::routines::next_run(&s, w.created_at, now); + self.dirty = true; + } + Some(t) if t <= now => { + w.next_run = crate::routines::next_run(&s, w.created_at, now); + self.dirty = true; + if w.live_run().is_none() { + due.push(w.id); + } + } + _ => {} + } + } + for wf in due { + self.wf_start(ctx, wf, "定時"); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::workflow::{Node, Workflow}; + + 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, + 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, + }, + ); + let mut w = Workflow::new(1, "早報", 0); + let mut prev = 1; + for (i, (id, kind)) in nodes.into_iter().enumerate() { + w.nodes.push(Node { id, kind, x: 0.0, y: 200.0 * (i as f32 + 1.0) }); + assert!(w.connect(prev, id)); + prev = id; + } + app.state.workflows.push(w); + (ctx, app, bot) + } + + /// The bot's turn on what the workflow asked: the question goes in, the answer after it. + fn answer(app: &mut App, bot: u64, said: &str) -> String { + let i = app.waiting_wakes.iter().position(|(b, _)| *b == bot).expect("a question for the bot"); + let (_, msg) = app.waiting_wakes.remove(i); + let asked = msg.text.clone(); + let b = app.state.bot_mut(bot).unwrap(); + b.messages.push(msg); + b.messages.push(Message::assistant(said, "m")); + app.wf_turn_ended(bot, TurnOutcome::Success); + asked + } + + fn run(app: &App) -> crate::workflow::Run { + app.state.workflows[0].runs.last().cloned().unwrap() + } + + /// A run goes step by step: the bot is asked in its own chat, its last words are handed + /// on, a check that passes hands on what it checked, the result goes into the chat, and it + /// ends done. One run at a time. + #[test] + fn a_run_goes_step_by_step_through_the_bots_turns() { + // (Bot 0 here: the nodes are given the bot the test made just below.) + let (ctx, mut app, bot) = + app_with(vec![(2, NodeKind::Step { bot: 0, prompt: "查今天的新聞".into() }), (3, NodeKind::Check { bot: 0, condition: "至少三則".into() }), (4, NodeKind::Deliver { bot: 0 }), (5, NodeKind::Notify { text: "早報好了:{結果}".into() })]); + let app = &mut app; + for n in app.state.workflows[0].nodes.iter_mut() { + match &mut n.kind { + NodeKind::Step { bot: b, .. } | NodeKind::Check { bot: b, .. } | NodeKind::Deliver { bot: b } => *b = bot, + _ => {} + } + } + assert!(app.wf_start(&ctx, 1, "手動")); + assert!(!app.wf_start(&ctx, 1, "手動"), "one run at a time"); + let asked = answer(app, bot, "三則新聞:A、B、C"); + assert!(asked.starts_with("[工作流「早報」第 1/4 步]查今天的新聞"), "{asked}"); + app.tick_workflows(&ctx); + let asked = answer(app, bot, "通過"); + assert!(asked.contains("至少三則") && asked.contains("三則新聞:A、B、C"), "{asked}"); + app.tick_workflows(&ctx); + let r = run(app); + assert_eq!(r.state, RunState::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"); + 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", "工作流「早報」")); + // What was run is kept as a version. + assert_eq!(app.state.workflows[0].versions.len(), 1); + } + + /// A check that doesn't pass stops the run and says why; a bot that fails too. + #[test] + fn a_failed_check_stops_the_run_and_says_why() { + let (ctx, mut app, bot) = app_with(vec![]); + let w = &mut app.state.workflows[0]; + w.nodes.push(Node { id: 2, kind: NodeKind::Check { bot, condition: "至少三則".into() }, x: 0.0, y: 200.0 }); + w.nodes.push(Node { id: 3, kind: NodeKind::Notify { text: "不該到這裡".into() }, x: 0.0, y: 400.0 }); + assert!(w.connect(1, 2) && w.connect(2, 3)); + app.wf_start(&ctx, 1, "手動"); + answer(&mut app, bot, "不通過:只有兩則"); + app.tick_workflows(&ctx); + let r = run(&app); + assert_eq!((r.state, r.why.as_str()), (RunState::Failed, "檢查沒通過:只有兩則")); + assert_eq!(r.step_of(3).map(|s| s.state), Some(StepState::Waiting), "nothing after it ran"); + // Again, the bot's turn failing. + app.wf_start(&ctx, 1, "手動"); + let i = app.waiting_wakes.iter().position(|(b, _)| *b == bot).unwrap(); + let (_, msg) = app.waiting_wakes.remove(i); + app.state.bot_mut(bot).unwrap().messages.push(msg); + app.wf_turn_ended(bot, TurnOutcome::Error); + assert_eq!(run(&app).state, RunState::Failed); + } + + /// 等你確認 waits for the person: go on, or stop; 停止 stops a run that is on. + #[test] + fn a_confirm_waits_for_the_person() { + let (ctx, mut app, _) = app_with(vec![(2, NodeKind::Approve { prompt: "要發出去嗎?".into() }), (3, NodeKind::Notify { text: "發了".into() })]); + app.wf_start(&ctx, 1, "手動"); + assert_eq!(run(&app).state, RunState::Waiting); + app.wf_confirm(&ctx, 1, true); + assert_eq!(run(&app).state, RunState::Done); + app.wf_start(&ctx, 1, "手動"); + app.wf_confirm(&ctx, 1, false); + assert_eq!((run(&app).state, run(&app).why.as_str()), (RunState::Stopped, "你在「等你確認」選了停止")); + app.wf_start(&ctx, 1, "手動"); + app.wf_stop(1); + assert_eq!(run(&app).state, RunState::Stopped); + assert!(app.wf_start(&ctx, 1, "手動"), "a stopped run doesn't block the next"); + } + + /// A scheduled trigger: its next time is worked out, and a run starts when it comes (by 定時). + #[test] + fn a_scheduled_trigger_starts_a_run_on_time() { + let (ctx, mut app, _) = app_with(vec![(2, NodeKind::Notify { text: "早安".into() })]); + let schedule: crate::routines::Schedule = serde_json::from_value(serde_json::json!({"frequency": "daily", "time": "09:00", "timezone": "Asia/Taipei"})).unwrap(); + if let NodeKind::Trigger { schedule: s } = &mut app.state.workflows[0].nodes[0].kind { + *s = Some(schedule); + } + app.tick_workflows(&ctx); + let next = app.state.workflows[0].next_run.expect("a next time"); + assert!(next > crate::routines::now() && app.state.workflows[0].runs.is_empty()); + app.state.workflows[0].next_run = Some(crate::routines::now() - 1); + app.tick_workflows(&ctx); + let r = run(&app); + assert_eq!((r.by.as_str(), r.state), ("定時", RunState::Done)); + assert!(app.state.workflows[0].next_run.unwrap() > crate::routines::now()); + } + + /// 聊出來的工作流: the bot's `workflow` call changes the brain's workflows; the person on + /// that chat sees the canvas open beside it, on that workflow, with what changed lit; run + /// starts it (its first step asks the bot, in line behind the turn it is in). + #[test] + fn a_bots_workflow_call_shows_beside_its_chat() { + let (ctx, mut app, bot) = app_with(vec![]); + app.state.selected = bot; + let call = |app: &mut App, args: serde_json::Value| { + let (tx, rx) = std::sync::mpsc::channel(); + app.workflow_tool(&ctx, bot, AppCall { call_id: "c".into(), name: crate::workflow::TOOL.into(), args: args.to_string(), reply: tx }); + rx.try_recv().unwrap() + }; + let (text, ok) = call(&mut app, serde_json::json!({"action": "create", "name": "週報", "steps": [{"prompt": "整理這週的進度"}]})); + assert!(ok && text.starts_with("已建立工作流 #2「週報」"), "{text}"); + assert!(app.wf.open && app.wf.current == 2 && !app.wf.chat_hidden && app.wf.reveal, "the canvas beside the chat"); + assert_eq!(app.wf.flash.as_ref().map(|f| (f.0, f.1.clone())), Some((2, vec![1, 2]))); + assert!(app.wf_chat_beside(1200.0) && !app.wf_chat_beside(800.0)); + // Not looking at that chat: nothing opens. + app.wf.open = false; + app.state.selected = 0; + let (_, ok) = call(&mut app, serde_json::json!({"action": "edit", "steps": [{"kind": "notify"}]})); + assert!(ok && !app.wf.open); + // Run: the first step waits for the bot's turn to end. + let (text, ok) = call(&mut app, serde_json::json!({"action": "run", "id": 2})); + assert!(ok && text.starts_with("已開始執行「週報」"), "{text}"); + assert!(app.waiting_wakes.iter().any(|(b, m)| *b == bot && m.text.contains("[工作流「週報」第 1/2 步]整理這週的進度"))); + // The turn that called run ends first: not the step's answer. + app.state.bot_mut(bot).unwrap().messages.push(Message::assistant("好,開始跑了", "m")); + app.wf_turn_ended(bot, TurnOutcome::Success); + assert_eq!(app.state.workflows[1].runs.last().map(|r| (r.state, r.at)), Some((RunState::Running, 1)), "still on its first step"); + let (text, ok) = call(&mut app, serde_json::json!({"action": "run", "id": 2})); + assert!(!ok && text.contains("已經在跑了"), "{text}"); + let (_, ok) = call(&mut app, serde_json::json!({"action": "stop", "id": 2})); + assert!(ok && app.state.workflows[1].runs.last().unwrap().state == RunState::Stopped); + } +} diff --git a/src/app/workflow_ui.rs b/src/app/workflow_ui.rs new file mode 100644 index 0000000..a5b92d7 --- /dev/null +++ b/src/app/workflow_ui.rs @@ -0,0 +1,1645 @@ +// 工作流的畫布 (workflow.rs: the shapes; workflow_run.rs: the runs). Laid out like the +// workflow canvases people know: the workflow's name and its menu at the top left (each one with +// its step count, 新建, 版本歷史, 重新命名, 建立副本, 刪除), 執行工作流 at the top right; a dotted +// canvas to pan and zoom; a toolbar at the bottom (選取、拖曳 | 畫筆、便利貼、形狀、文字 | 搜尋 | +// + 新增節點), the zoom at the bottom left (- 75% + | 符合畫面 | 小地圖). Steps are cards joined by +// lines from a card's bottom dot to the next one's top; the trigger card says when it runs and +// has 立即執行. A card picked opens its settings at the right; a run shows on the cards (✓, ✗, +// working, waiting for you). What is drawn and written is the person's, never run. + +use super::*; +use crate::icons::Icon; +use crate::workflow::{Node, NodeKind, Note, NoteKind, RunState, StepState, Workflow}; +use egui::{Rect, Shape}; + +/// What the canvas is doing with the pointer. +#[derive(Clone, Copy, PartialEq, Eq, Default, Debug)] +pub(super) enum Tool { + #[default] + Select, + Hand, + Pen, + Sticky, + Shape, + Text, +} + +#[derive(Default)] +pub(super) struct WfUi { + /// The canvas is showing (instead of the chat). + pub open: bool, + /// The workflow on the canvas. + pub current: u64, + /// Workflows whose run can go on (a bot's turn ended): moved on at the next tick. + pub advance: Vec, + pub tool: Tool, + /// The canvas point at the view's top-left, and screen points per canvas point. + pub pan: egui::Vec2, + pub zoom: f32, + /// What is picked: a node or a note (one id space), or a line. + pub selected: Option, + pub selected_edge: Option<(u64, u64)>, + /// A card or a note being moved. + pub moving: Option, + /// A pen stroke being drawn (canvas points). + pub stroke: Vec, + /// A line being drawn from a card's bottom dot. + pub linking: Option, + /// A shape being dragged out (its first corner, canvas points). + pub shaping: Option, + /// The note whose words are being typed on the canvas. + pub editing: Option, + pub minimap: bool, + pub runs_open: bool, + pub search: Option, + pub found: usize, + /// The view was fitted to this workflow (it fits when it first shows). + pub fitted: u64, + pub renaming: Option, + pub confirm_delete: bool, + /// Something changed since a version was last kept. + pub changed_since: Option, + /// The chat that was showing when the canvas opened (another one picked closes it, unless + /// the chat is beside the canvas: then that chat shows there). + pub chat_was: u64, + /// The chat beside the canvas is put away (聊天 in the top bar brings it back). + pub chat_hidden: bool, + /// What a bot just changed on this workflow: lit up for a moment. + pub flash: Option<(u64, Vec, Instant)>, + /// A bot changed it: show what changed if it is out of view. + pub reveal: bool, +} + +/// How long what a bot changed stays lit on the canvas. +const FLASH_SECS: f32 = 2.6; +/// The chat goes beside the canvas from this wide a window part. +const CHAT_BESIDE_FROM: f32 = 900.0; + +/// About how wide the zoom bar at the bottom left is. +const ZOOMBAR_W: f32 = 160.0; +const NODE_W: f32 = crate::workflow::CARD_W; +const GRID: f32 = 24.0; +const ZOOM_MIN: f32 = 0.2; +const ZOOM_MAX: f32 = 2.0; +const STICKY: egui::Vec2 = egui::vec2(crate::workflow::STICKY_W, crate::workflow::STICKY_H); +/// A version is kept this long after the last change (and when the canvas closes or a run starts). +const KEEP_AFTER_SECS: u64 = 20; +use crate::workflow::STICKY_COLOURS; +const INK_COLOURS: [&str; 6] = ["", "red", "orange", "green", "blue", "purple"]; + +fn node_h(kind: &NodeKind) -> f32 { + match kind { + NodeKind::Trigger { .. } => 150.0, + NodeKind::Step { .. } | NodeKind::Check { .. } => 118.0, + NodeKind::Approve { .. } | NodeKind::Notify { .. } => 96.0, + NodeKind::Deliver { .. } => 82.0, + } +} + +/// What the 等你確認 bar takes at the top of the canvas while a run waits. +fn wf_top_room(w: &Workflow) -> f32 { + if w.live_run().is_some_and(|r| r.state == RunState::Waiting) { 64.0 } else { 0.0 } +} + +fn node_rect(n: &Node) -> Rect { + Rect::from_min_size(egui::pos2(n.x, n.y), vec2(NODE_W, node_h(&n.kind))) +} + +fn kind_icon(kind: &NodeKind) -> Icon { + match kind { + NodeKind::Trigger { .. } => Icon::Zap, + NodeKind::Step { .. } => Icon::Bot, + NodeKind::Approve { .. } => Icon::CircleCheck, + NodeKind::Check { .. } => Icon::Shield, + NodeKind::Deliver { .. } => Icon::Send, + NodeKind::Notify { .. } => Icon::Bell, + } +} + +fn colour_of(name: &str, fallback: Color32) -> Color32 { + if name.is_empty() { fallback } else { crate::avatar::color(name) } +} + +/// The box a note takes on the canvas (a text note's height follows its words). +fn note_rect(n: &Note) -> Rect { + Rect::from_min_size(egui::pos2(n.x, n.y), vec2(n.w.max(8.0), n.h.max(8.0))) +} + +/// Canvas ↔ screen. +#[derive(Clone, Copy)] +struct View { + origin: egui::Pos2, + pan: egui::Vec2, + zoom: f32, +} + +impl View { + fn to_screen(self, c: egui::Pos2) -> egui::Pos2 { + self.origin + (c.to_vec2() - self.pan) * self.zoom + } + fn to_canvas(self, s: egui::Pos2) -> egui::Pos2 { + egui::pos2(0.0, 0.0) + (s - self.origin) / self.zoom + self.pan + } + fn rect(&self, r: Rect) -> Rect { + Rect::from_min_max(self.to_screen(r.min), self.to_screen(r.max)) + } +} + +/// Distance from p to the segment a–b. +fn to_segment(p: egui::Pos2, a: egui::Pos2, b: egui::Pos2) -> f32 { + let ab = b - a; + let t = if ab.length_sq() < 1e-6 { 0.0 } else { ((p - a).dot(ab) / ab.length_sq()).clamp(0.0, 1.0) }; + (a + ab * t - p).length() +} + +/// A line between two cards: from the bottom dot down, to the top dot. +fn edge_points(a: Rect, b: Rect, v: &View) -> [egui::Pos2; 4] { + let p0 = v.to_screen(egui::pos2(a.center().x, a.max.y)); + let p3 = v.to_screen(egui::pos2(b.center().x, b.min.y)); + let k = ((p3.y - p0.y).abs() * 0.5).max(40.0 * v.zoom); + [p0, p0 + vec2(0.0, k), p3 - vec2(0.0, k), p3] +} + +fn bezier_at(p: &[egui::Pos2; 4], t: f32) -> egui::Pos2 { + let u = 1.0 - t; + let w = [u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t]; + egui::pos2(p.iter().zip(w).map(|(q, k)| q.x * k).sum(), p.iter().zip(w).map(|(q, k)| q.y * k).sum()) +} + +impl App { + /// Open the canvas: on the workflow it showed last, or the first, or a new one. + pub(super) fn wf_open(&mut self) { + if self.state.workflows.is_empty() { + self.wf_new(); + } + if !self.state.workflows.iter().any(|w| w.id == self.wf.current) { + self.wf.current = self.state.workflows[0].id; + } + self.wf.open = true; + self.wf.chat_was = self.state.selected; + } + + /// The chat beside the canvas: a bot picked, the window wide enough, not put away. + pub(super) fn wf_chat_beside(&self, width: f32) -> bool { + !self.wf.chat_hidden && width >= CHAT_BESIDE_FROM && self.state.bot(self.state.selected).is_some() + } + + /// A bot changed this workflow from its chat: the person looking at that chat (or at the + /// 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) { + let home = self.state.home_of(bot_id); + let looking = self.wf.open || self.state.selected == bot_id || self.state.selected == home; + if !looking || !self.state.workflows.iter().any(|w| w.id == wf) { + return; + } + if self.wf.current != wf { + self.wf_keep_version(); + self.wf.current = wf; + self.wf.selected = None; + self.wf.selected_edge = None; + } + if !self.wf.open { + self.wf.open = true; + self.wf.chat_was = self.state.selected; + self.wf.fitted = 0; + } + self.wf.chat_hidden = false; + self.wf.flash = Some((wf, touched, Instant::now())); + self.wf.reveal = true; + } + + pub(super) fn wf_close(&mut self) { + self.wf_keep_version(); + self.wf.open = false; + self.wf.editing = None; + } + + fn wf_new(&mut self) { + let id = self.state.workflows.iter().map(|w| w.id).max().unwrap_or(0) + 1; + let n = self.state.workflows.len() + 1; + let name = if n == 1 { t("未命名工作流") } else { format!("{} {n}", t("未命名工作流")) }; + self.state.workflows.push(Workflow::new(id, &name, crate::routines::now())); + self.wf.current = id; + self.wf.fitted = 0; + self.wf.selected = None; + self.dirty = true; + } + + fn wf_index(&self) -> Option { + self.state.workflows.iter().position(|w| w.id == self.wf.current) + } + + /// The canvas changed: saved, and a version kept a little later. + fn wf_touch(&mut self) { + if let Some(i) = self.wf_index() { + self.state.workflows[i].updated_at = crate::routines::now(); + } + self.wf.changed_since.get_or_insert_with(Instant::now); + self.dirty = true; + } + + fn wf_keep_version(&mut self) { + if self.wf.changed_since.take().is_none() { + return; + } + let now = crate::routines::now(); + if let Some(i) = self.wf_index() { + self.state.workflows[i].keep_version(now); + self.dirty = true; + } + } + + /// The canvas, where the chat was. + pub(super) fn workflow_pane(&mut self, ui: &mut egui::Ui) { + let p = self.pal; + // Another chat picked in the sidebar: it shows beside the canvas; with no chat beside, + // back to the chats. + if self.state.selected != self.wf.chat_was { + if self.wf.chat_hidden || ui.ctx().content_rect().width() < CHAT_BESIDE_FROM { + self.wf_close(); + return; + } + self.wf.chat_was = self.state.selected; + } + if self.wf_index().is_none() { + self.wf_open(); + } + if self.wf.zoom <= 0.0 { + self.wf.zoom = 1.0; + } + if self.wf.changed_since.is_some_and(|t| t.elapsed().as_secs() >= KEEP_AFTER_SECS) { + self.wf_keep_version(); + } + let screen = self.mir.on; + let full = ui.available_rect_before_wrap(); + let top = Rect::from_min_size(full.min, vec2(full.width(), 52.0)); + let canvas = Rect::from_min_max(egui::pos2(full.min.x, top.max.y), full.max); + ui.scope_builder(egui::UiBuilder::new().max_rect(top.shrink2(vec2(16.0, 0.0))), |ui| self.wf_top_bar(ui, screen)); + ui.painter().hline(full.x_range(), top.max.y, Stroke::new(1.0, p.border)); + self.wf_canvas(ui, canvas, screen); + ui.allocate_rect(full, egui::Sense::hover()); + self.wf_dialogs(ui.ctx()); + } + + fn wf_top_bar(&mut self, ui: &mut egui::Ui, screen: bool) { + let p = self.pal; + let Some(i) = self.wf_index() else { return }; + let live = self.state.workflows[i].live_run().map(|r| r.state); + let name = self.state.workflows[i].name.clone(); + // (The right side first; the name in the room left, cut short.) + let left = |me: &mut App, ui: &mut egui::Ui| { + 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() { + me.wf_close(); + } + ui.add_space(6.0); + let r = ui.add(egui::Button::new(RichText::new(format!("{name} ▾")).size(FONT_BASE).family(crate::bold()).color(p.text)).frame(false).truncate()).on_hover_text(&name); + egui::Popup::menu(&r).show(|ui| me.wf_menu(ui)); + }); + }; + ui.horizontal_centered(|ui| { + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + if screen { + ui.add(egui::Label::new(RichText::new(t("這台是螢幕:工作流在大腦上編輯和執行")).size(FONT_SM).color(p.text3)).truncate()); + left(self, ui); + return; + } + match live { + Some(_) => { + if ui.add(danger_button("■ 停止", p)).clicked() { + let id = self.wf.current; + self.wf_stop(id); + } + } + None => { + if ui.add(primary_button("▷ 執行工作流", p)).clicked() { + let (ctx, id) = (ui.ctx().clone(), self.wf.current); + self.wf_keep_version(); + self.wf_start(&ctx, id, "手動"); + self.wf.runs_open = true; + } + } + } + if ui.ctx().content_rect().width() >= CHAT_BESIDE_FROM && self.state.bot(self.state.selected).is_some() { + let on = !self.wf.chat_hidden; + if ui + .add(egui::Button::new(RichText::new(t("聊天")).size(FONT_SM).color(if on { p.text } else { p.text2 })).fill(if on { p.active } else { Color32::TRANSPARENT })) + .on_hover_text(t("在旁邊和 Bot 聊:請它幫你改這個工作流")) + .clicked() + { + self.wf.chat_hidden = on; + } + } + let on = self.wf.runs_open; + if ui.add(egui::Button::new(RichText::new(t("執行紀錄")).size(FONT_SM).color(if on { p.text } else { p.text2 })).fill(if on { p.active } else { Color32::TRANSPARENT })).clicked() { + self.wf.runs_open = !on; + self.wf.selected = None; + } + // (Only when there is room: the name comes first.) + if ui.available_width() > 360.0 { + match live { + Some(RunState::Waiting) => { + ui.label(RichText::new(t("等你確認")).size(FONT_SM).color(p.attention)); + } + Some(_) => { + ui.label(RichText::new(t("執行中…")).size(FONT_SM).color(p.up)); + } + None => {} + } + } + left(self, ui); + }); + }); + } + + /// The workflow menu: each one, 新建, 版本歷史, 重新命名, 建立副本, 刪除. + fn wf_menu(&mut self, ui: &mut egui::Ui) { + let p = self.pal; + ui.set_min_width(300.0); + ui.label(RichText::new(t("工作流")).size(FONT_XS).color(p.text3)); + let list: Vec<(u64, String, usize)> = self.state.workflows.iter().map(|w| (w.id, w.name.clone(), w.step_count())).collect(); + for (id, name, n) in list { + let on = id == self.wf.current; + let r = menu_ui::item_text(ui, p, Some(if on { Icon::CircleCheck } else { Icon::Workflow }), &name); + ui.painter().text(r.rect.right_center() - vec2(12.0, 0.0), egui::Align2::RIGHT_CENTER, format!("{n} {}", t("個步驟")), egui::FontId::proportional(FONT_XS), p.text3); + if r.clicked() { + self.wf_keep_version(); + self.wf.current = id; + self.wf.fitted = 0; + self.wf.selected = None; + ui.close(); + } + } + if menu_ui::item(ui, p, Icon::Plus, "新建工作流").clicked() { + self.wf_keep_version(); + self.wf_new(); + ui.close(); + } + menu_ui::sep(ui, p); + let Some(i) = self.wf_index() else { return }; + let versions: Vec<(usize, String, usize)> = self.state.workflows[i] + .versions + .iter() + .enumerate() + .rev() + .map(|(k, v)| (k, crate::routines::describe_when(v.at, &self.state.timezone), Workflow { nodes: v.nodes.clone(), edges: v.edges.clone(), ..Default::default() }.step_count())) + .collect(); + menu_ui::sub(ui, p, Icon::History, "版本歷史", |ui| { + ui.set_min_width(260.0); + if versions.is_empty() { + ui.label(RichText::new(t("還沒有存過版本:改了以後、執行時會存一版")).size(FONT_XS).color(p.text3)); + } + for (k, when, n) in &versions { + if menu_ui::item_text(ui, p, None, &format!("{when} · {n} {}", t("個步驟"))).on_hover_text(t("換回這一版(現在的會先存成一版)")).clicked() { + let now = crate::routines::now(); + self.state.workflows[i].restore(*k, now); + self.wf.selected = None; + self.dirty = true; + ui.close(); + } + } + }); + if menu_ui::item(ui, p, Icon::Pencil, "重新命名").clicked() { + self.wf.renaming = Some(self.state.workflows[i].name.clone()); + ui.close(); + } + if menu_ui::item(ui, p, Icon::Copy, "建立副本").clicked() { + let id = self.state.workflows.iter().map(|w| w.id).max().unwrap_or(0) + 1; + let copy = self.state.workflows[i].copy_as(id, crate::routines::now()); + self.state.workflows.push(copy); + self.wf.current = id; + self.wf.fitted = 0; + self.dirty = true; + ui.close(); + } + if menu_ui::danger(ui, p, Icon::Trash, "刪除工作流").clicked() { + self.wf.confirm_delete = true; + ui.close(); + } + } + + fn wf_dialogs(&mut self, ctx: &egui::Context) { + let p = self.pal; + if let Some(mut name) = self.wf.renaming.take() { + let mut done = false; + let closed = dialog(ctx, "wf-rename", "重新命名", 420.0, true, p, |ui| { + dialog_body(ui, "wf-rename-body", 160.0, |ui| { + let r = ui.add(egui::TextEdit::singleline(&mut name).desired_width(f32::INFINITY)); + r.request_focus(); + if r.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter)) { + done = true; + } + }); + dialog_footer(ui, p, |ui| { + if ui.add(primary_button("好", p)).clicked() { + done = true; + } + }); + }); + if done && !name.trim().is_empty() { + if let Some(i) = self.wf_index() { + self.state.workflows[i].name = name.trim().to_string(); + self.wf_touch(); + } + } else if !closed && !done { + self.wf.renaming = Some(name); + } + } + if self.wf.confirm_delete { + let name = self.wf_index().map(|i| self.state.workflows[i].name.clone()).unwrap_or_default(); + let mut yes = false; + let closed = dialog(ctx, "wf-delete", "刪除工作流", 420.0, true, p, |ui| { + dialog_body(ui, "wf-delete-body", 120.0, |ui| { + ui.label(RichText::new(format!("{}「{name}」{}", t("刪除"), t("和它的版本、執行紀錄?此操作無法復原。"))).size(FONT_BASE).color(p.text)); + }); + dialog_footer(ui, p, |ui| { + if ui.add(danger_button("刪除", p)).clicked() { + yes = true; + } + }); + }); + if yes { + let id = self.wf.current; + if self.state.workflows.iter().any(|w| w.id == id && w.live_run().is_some()) { + self.wf_stop(id); + } + self.state.workflows.retain(|w| w.id != id); + self.wf.current = self.state.workflows.first().map(|w| w.id).unwrap_or(0); + self.wf.fitted = 0; + self.wf.selected = None; + self.dirty = true; + if self.state.workflows.is_empty() { + self.wf_close(); + } + } + if yes || closed { + self.wf.confirm_delete = false; + } + } + } + + /// Fit the view to everything on the canvas. + fn wf_fit(&mut self, view: Rect) { + let Some(i) = self.wf_index() else { return }; + let w = &self.state.workflows[i]; + let mut b = Rect::NOTHING; + for n in &w.nodes { + b = b.union(node_rect(n)); + } + for n in &w.notes { + b = b.union(note_rect(n)); + } + if !b.is_positive() { + b = Rect::from_min_size(egui::pos2(0.0, 0.0), vec2(NODE_W, 150.0)); + } + let b = b.expand(80.0); + // (Room for the toolbar at the bottom, and for the 等你確認 bar at the top when a run + // waits.) + let top = wf_top_room(w); + let usable = vec2((view.width() - 40.0).max(200.0), (view.height() - 110.0 - top).max(200.0)); + let z = (usable.x / b.width()).min(usable.y / b.height()).clamp(ZOOM_MIN, 1.0); + self.wf.zoom = z; + self.wf.pan = b.center().to_vec2() - vec2(view.width() / 2.0, top + (view.height() - 70.0 - top) / 2.0) / z; + } + + fn wf_canvas(&mut self, ui: &mut egui::Ui, rect: Rect, screen: bool) { + let p = self.pal; + let Some(i) = self.wf_index() else { return }; + if self.wf.fitted != self.wf.current { + self.wf.fitted = self.wf.current; + self.wf_fit(rect); + } + if std::mem::take(&mut self.wf.reveal) { + // (A bot changed it: when a step — or a note it put there — is out of view or under + // the toolbar, the whole shows. The steps it pushed down count too.) + let v = View { origin: rect.min, pan: self.wf.pan, zoom: self.wf.zoom }; + let w = &self.state.workflows[i]; + let touched: Vec = self.wf.flash.as_ref().filter(|f| f.0 == w.id).map(|f| f.1.clone()).unwrap_or_default(); + let room = Rect::from_min_max(rect.min + vec2(8.0, 8.0 + wf_top_room(w)), rect.max - vec2(8.0, 80.0)); + let out = |r: Rect| !room.contains_rect(v.rect(r)); + if w.nodes.iter().any(|n| out(node_rect(n))) || w.notes.iter().filter(|n| touched.contains(&n.id)).any(|n| out(note_rect(n))) { + self.wf_fit(rect); + } + } + let painter = ui.painter_at(rect); + painter.rect_filled(rect, 0.0, p.pane); + let resp = ui.interact(rect, egui::Id::unique(("wf-canvas", self.wf.current)), egui::Sense::click_and_drag()); + let ctx = ui.ctx().clone(); + let typing = ctx.memory(|m| m.focused().is_some()); + // Zoom (pinch, ⌘ + wheel) around the pointer; the wheel pans. + if resp.hovered() || resp.dragged() { + let (zoom_d, scroll, hover) = ui.input(|i| (i.zoom_delta(), i.smooth_scroll_delta, i.pointer.hover_pos())); + if (zoom_d - 1.0).abs() > 1e-4 { + let at = hover.unwrap_or(rect.center()); + let before = View { origin: rect.min, pan: self.wf.pan, zoom: self.wf.zoom }.to_canvas(at); + self.wf.zoom = (self.wf.zoom * zoom_d).clamp(ZOOM_MIN, ZOOM_MAX); + self.wf.pan = before.to_vec2() - (at - rect.min) / self.wf.zoom; + } else if scroll != egui::Vec2::ZERO { + self.wf.pan -= scroll / self.wf.zoom; + } + } + let view = View { origin: rect.min, pan: self.wf.pan, zoom: self.wf.zoom }; + // The dots. + let step = { + let mut s = GRID; + while s * view.zoom < 14.0 { + s *= 2.0; + } + s + }; + let c0 = view.to_canvas(rect.min); + let c1 = view.to_canvas(rect.max); + let mut y = (c0.y / step).floor() * step; + while y <= c1.y { + let mut x = (c0.x / step).floor() * step; + while x <= c1.x { + painter.circle_filled(view.to_screen(egui::pos2(x, y)), 1.0, p.border); + x += step; + } + y += step; + } + let run = self.state.workflows[i].runs.last().cloned(); + let w = self.state.workflows[i].clone(); + let pointer = resp.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.hover_pos())); + let at = pointer.map(|s| view.to_canvas(s)); + let ink = |n: &Note| colour_of(&n.color, p.text); + + // ── What people drew and wrote (under the cards) ── + for n in w.notes.iter().filter(|n| matches!(n.kind, NoteKind::Sticky | NoteKind::Shape)) { + let r = view.rect(note_rect(n)); + let picked = self.wf.selected == Some(n.id); + match n.kind { + NoteKind::Sticky => { + let fill = crate::avatar::color(if n.color.is_empty() { STICKY_COLOURS[0] } else { &n.color }); + painter.rect_filled(r, R_M as f32 * view.zoom, fill); + if self.wf.editing != Some(n.id) { + let g = painter.layout(n.text.clone(), egui::FontId::proportional(FONT_SM * view.zoom), crate::theme::LIGHT.text, (r.width() - 20.0 * view.zoom).max(10.0)); + painter.galley(r.min + vec2(10.0, 10.0) * view.zoom, g, Color32::BLACK); + } + if !n.author.is_empty() && view.zoom > 0.4 { + painter.text(r.left_bottom() + vec2(10.0, -8.0) * view.zoom, egui::Align2::LEFT_BOTTOM, &n.author, egui::FontId::proportional(FONT_XS * view.zoom), crate::theme::LIGHT.text2); + } + } + _ => { + painter.rect_filled(r, R_M as f32 * view.zoom, p.hover); + painter.rect_stroke(r, R_M as f32 * view.zoom, Stroke::new(1.5 * view.zoom.max(0.5), ink(n)), egui::StrokeKind::Inside); + } + } + if picked { + painter.rect_stroke(r.expand(3.0), R_M, Stroke::new(2.0, p.accent), egui::StrokeKind::Outside); + } + } + for n in w.notes.iter().filter(|n| n.kind == NoteKind::Pen) { + let pts: Vec = n.points.iter().map(|q| view.to_screen(egui::pos2(n.x + q[0], n.y + q[1]))).collect(); + painter.add(Shape::line(pts, Stroke::new(3.0 * view.zoom.max(0.3), ink(n)))); + if self.wf.selected == Some(n.id) { + painter.rect_stroke(view.rect(note_rect(n)).expand(4.0), R_M, Stroke::new(1.5, p.accent), egui::StrokeKind::Outside); + } + } + for n in w.notes.iter().filter(|n| n.kind == NoteKind::Text) { + let r = view.rect(note_rect(n)); + if self.wf.editing != Some(n.id) { + let g = painter.layout(n.text.clone(), egui::FontId::proportional(FONT_H3 * view.zoom), ink(n), r.width().max(10.0)); + painter.galley(r.min, g, ink(n)); + } + if self.wf.selected == Some(n.id) { + painter.rect_stroke(r.expand(4.0), R_M, Stroke::new(1.5, p.accent), egui::StrokeKind::Outside); + } + } + + // ── The lines ── + for e in &w.edges { + let (Some(a), Some(b)) = (w.node(e.from), w.node(e.to)) else { continue }; + let pts = edge_points(node_rect(a), node_rect(b), &view); + let picked = self.wf.selected_edge == Some((e.from, e.to)); + let done = run.as_ref().and_then(|r| r.step_of(e.to)).is_some_and(|s| s.state == StepState::Done); + let col = if picked { + p.accent + } else if done { + p.up + } else { + p.text3 + }; + painter.add(egui::epaint::CubicBezierShape::from_points_stroke(pts, false, Color32::TRANSPARENT, Stroke::new(if picked { 2.5 } else { 1.5 }, col))); + let tip = pts[3]; + painter.add(Shape::convex_polygon(vec![tip, tip + vec2(-5.0, -8.0), tip + vec2(5.0, -8.0)], col, Stroke::NONE)); + } + if let (Some(from), Some(s)) = (self.wf.linking, pointer) { + if let Some(a) = w.node(from) { + let a = node_rect(a); + let p0 = view.to_screen(egui::pos2(a.center().x, a.max.y)); + painter.add(egui::epaint::CubicBezierShape::from_points_stroke([p0, p0 + vec2(0.0, 50.0), s - vec2(0.0, 50.0), s], false, Color32::TRANSPARENT, Stroke::new(2.0, p.accent))); + } + } + + // ── The cards ── + let tz = self.state.timezone.clone(); + let names: HashMap = self.state.bots.iter().map(|b| (b.id, b.name.clone())).collect(); + let mut run_now: Option = None; + for n in &w.nodes { + let r = view.rect(node_rect(n)); + if !r.intersects(rect) { + continue; + } + let z = view.zoom; + let picked = self.wf.selected == Some(n.id); + let step = run.as_ref().and_then(|r| r.step_of(n.id)).map(|s| s.state); + let live = run.as_ref().is_some_and(|r| r.live()); + painter.rect_filled(r.translate(vec2(0.0, 2.0 * z)), R_L as f32 * z, p.border.gamma_multiply(0.7)); + painter.rect_filled(r, R_L as f32 * z, p.elevated); + let waiting = run.as_ref().is_some_and(|r| r.state == RunState::Waiting); + let edge_col = match step { + Some(StepState::Running) if live && waiting => p.attention, + Some(StepState::Running) if live => p.accent, + Some(StepState::Failed) => p.danger, + _ if picked => p.accent, + _ => p.border, + }; + painter.rect_stroke(r, R_L as f32 * z, Stroke::new(if picked || matches!(step, Some(StepState::Running | StepState::Failed)) { 2.0 } else { 1.0 }, edge_col), egui::StrokeKind::Inside); + // Header: what it is, how it stands. + let pad = 14.0 * z; + crate::icons::paint(&painter, Rect::from_min_size(r.min + vec2(pad, pad), vec2(16.0, 16.0) * z), kind_icon(&n.kind), p.text2); + painter.text(r.min + vec2(pad + 22.0 * z, pad + 8.0 * z), egui::Align2::LEFT_CENTER, t(n.kind.label()), egui::FontId::new(FONT_SM * z, crate::bold()), p.text); + let badge = match step { + Some(StepState::Done) => Some((t("完成"), p.up)), + Some(StepState::Failed) => Some((t("失敗"), p.danger)), + Some(StepState::Running) if live && run.as_ref().is_some_and(|r| r.state == RunState::Waiting) => Some((t("等你確認"), p.attention)), + Some(StepState::Running) if live => Some((t("進行中…"), p.accent)), + _ => None, + }; + if let Some((b, c)) = badge { + painter.text(egui::pos2(r.max.x - pad, r.min.y + pad + 8.0 * z), egui::Align2::RIGHT_CENTER, b, egui::FontId::proportional(FONT_XS * z), c); + } + if z > 0.35 { + let body_top = r.min.y + pad + 26.0 * z; + let line = |k: f32| egui::pos2(r.min.x + pad, body_top + k * 20.0 * z); + let small = egui::FontId::proportional(FONT_SM * z); + let wrap = |s: &str, rows: usize| { + let mut job = egui::text::LayoutJob::simple(s.to_string(), small.clone(), p.text2, r.width() - 2.0 * pad); + job.wrap = egui::text::TextWrapping { max_width: r.width() - 2.0 * pad, max_rows: rows, break_anywhere: true, overflow_character: Some('…') }; + painter.layout_job(job) + }; + match &n.kind { + NodeKind::Trigger { schedule } => { + let when = schedule.as_ref().map(crate::routines::describe).unwrap_or_else(|| t("手動:按「立即執行」或「執行工作流」")); + painter.galley(line(0.0), wrap(&when, 1), p.text2); + // (Not worked out yet — just set, or never ticked: worked out here.) + let next = w.next_run.or_else(|| schedule.as_ref().and_then(|s| crate::routines::next_run(s, w.created_at, crate::routines::now()))).map(|t| crate::routines::describe_when(t, &tz)).unwrap_or_else(|| t("只在按的時候")); + painter.text(line(1.3), egui::Align2::LEFT_TOP, format!("{} {next}", t("下次執行")), egui::FontId::proportional(FONT_XS * z), p.text3); + let btn = Rect::from_min_max(egui::pos2(r.min.x + pad, r.max.y - pad - 30.0 * z), egui::pos2(r.max.x - pad, r.max.y - pad)); + let can = !screen && !live; + let hot = pointer.is_some_and(|s| btn.contains(s)) && can; + painter.rect_filled(btn, R_M as f32 * z, if hot { p.active } else { p.hover }); + painter.text(btn.center(), egui::Align2::CENTER_CENTER, format!("{} ▷", t("立即執行")), egui::FontId::new(FONT_SM * z, crate::bold()), if can { p.text } else { p.text3 }); + if hot && resp.clicked() && !live { + run_now = Some(w.id); + } + } + NodeKind::Step { bot, prompt } | NodeKind::Check { bot, condition: prompt } => { + let who = names.get(bot).cloned().unwrap_or_else(|| t("(選一個 Bot)")); + painter.text(line(0.0), egui::Align2::LEFT_TOP, who, egui::FontId::new(FONT_SM * z, crate::bold()), p.accent); + painter.galley(line(1.0), wrap(if prompt.trim().is_empty() { "(還沒寫要做什麼)" } else { prompt.as_str() }, 2), p.text2); + } + NodeKind::Approve { prompt } => { + painter.galley(line(0.0), wrap(if prompt.trim().is_empty() { "要繼續嗎?" } else { prompt.as_str() }, 2), p.text2); + } + NodeKind::Deliver { bot } => { + let who = names.get(bot).cloned().unwrap_or_else(|| t("(選一個 Bot)")); + painter.galley(line(0.0), wrap(&format!("{} 「{who}」 {}", t("把結果放進"), t("的聊天")), 1), p.text2); + } + NodeKind::Notify { text } => { + painter.galley(line(0.0), wrap(if text.trim().is_empty() { "{結果}" } else { text.as_str() }, 2), p.text2); + } + } + } + // The dots a line leaves from and comes into. + let out = egui::pos2(r.center().x, r.max.y); + let near_out = pointer.is_some_and(|s| (s - out).length() < 12.0); + painter.circle_filled(out, if near_out { 6.0 } else { 4.0 }, if near_out { p.accent } else { p.text3 }); + if !matches!(n.kind, NodeKind::Trigger { .. }) { + painter.circle_filled(egui::pos2(r.center().x, r.min.y), 4.0, p.text3); + } + } + if let Some(stroke) = (!self.wf.stroke.is_empty()).then(|| self.wf.stroke.clone()) { + painter.add(Shape::line(stroke.iter().map(|c| view.to_screen(*c)).collect(), Stroke::new(3.0 * view.zoom.max(0.3), p.text))); + } + if let (Some(a), Some(b)) = (self.wf.shaping, at) { + painter.rect_stroke(view.rect(Rect::from_two_pos(a, b)), R_M, Stroke::new(1.5, p.accent), egui::StrokeKind::Inside); + } + // What a bot just changed: a glow that fades. + if let Some((wid, ids, at)) = self.wf.flash.as_ref() { + let age = at.elapsed().as_secs_f32(); + if *wid == w.id && age < FLASH_SECS { + let k = 1.0 - age / FLASH_SECS; + let boxes = w.nodes.iter().filter(|n| ids.contains(&n.id)).map(node_rect).chain(w.notes.iter().filter(|n| ids.contains(&n.id)).map(note_rect)); + for b in boxes { + let r = view.rect(b).expand(4.0 + 6.0 * (1.0 - k)); + painter.rect_stroke(r, R_L as f32 * view.zoom + 4.0, Stroke::new(3.0, p.attention.gamma_multiply(0.85 * k)), egui::StrokeKind::Outside); + } + ctx.request_repaint_after(anim_after(40)); + } else { + self.wf.flash = None; + } + } + if let Some(id) = run_now { + self.wf_keep_version(); + self.wf_start(&ctx, id, "手動"); + self.wf.runs_open = true; + } + + // ── The pointer ── + if !screen { + self.wf_pointer(ui, &resp, &view, rect, &w); + if !typing { + self.wf_keys(ui); + } + } + self.wf_text_edit(ui, &view); + + // ── What floats over the canvas ── + // (The tools in the middle at the bottom, the zoom at the left of them; when both don't + // fit in one row, the zoom goes above, at the left.) + let toolbar_w = 560.0_f32.min(rect.width() - 32.0); + let mut toolbar = Rect::from_center_size(egui::pos2(rect.center().x, rect.max.y - 40.0), vec2(toolbar_w, 52.0)); + let after_zoom = rect.min.x + 16.0 + ZOOMBAR_W + 12.0; + let one_row = rect.max.x - 16.0 - after_zoom >= toolbar_w; + if one_row && toolbar.min.x < after_zoom { + toolbar = toolbar.translate(vec2(after_zoom - toolbar.min.x, 0.0)); + } + ui.scope_builder(egui::UiBuilder::new().max_rect(toolbar), |ui| self.wf_toolbar(ui, screen)); + let rows_top = rect.max.y - if one_row { 66.0 } else { 122.0 }; + let zoombar = Rect::from_min_size(egui::pos2(rect.min.x + 16.0, rows_top), vec2(250.0, 44.0)); + ui.scope_builder(egui::UiBuilder::new().max_rect(zoombar), |ui| self.wf_zoombar(ui, rect)); + let mm = Rect::from_min_size(egui::pos2(rect.max.x - 16.0 - 220.0, rows_top - 150.0), vec2(220.0, 140.0)); + if self.wf.minimap { + self.wf_minimap(ui, mm, rect, &w); + } + // (The side panel at the right; the waiting bar in the room it leaves, or across the top + // above it when that room is too small.) + let waiting = run.as_ref().is_some_and(|r| r.state == RunState::Waiting); + let side_open = self.wf.selected.is_some() || self.wf.runs_open; + let side_w = 340.0_f32.min(rect.width() - 32.0); + let bar_across = waiting && side_open && rect.width() - 48.0 - side_w < 360.0; + let side_top = rect.min.y + if bar_across { 80.0 } else { 16.0 }; + let side_bottom = (if self.wf.minimap { mm.min.y } else { rows_top }) - 12.0; + let side = Rect::from_min_max(egui::pos2(rect.max.x - 16.0 - side_w, side_top), egui::pos2(rect.max.x - 16.0, side_bottom.max(side_top + 200.0))); + if let Some(sel) = self.wf.selected.filter(|s| w.node(*s).is_some()) { + ui.scope_builder(egui::UiBuilder::new().max_rect(side), |ui| self.wf_inspector(ui, sel, screen)); + } else if let Some(sel) = self.wf.selected.filter(|s| w.notes.iter().any(|n| n.id == *s)) { + ui.scope_builder(egui::UiBuilder::new().max_rect(Rect::from_min_size(side.min, vec2(side.width(), 150.0))), |ui| self.wf_note_inspector(ui, sel, screen)); + } else if self.wf.runs_open { + ui.scope_builder(egui::UiBuilder::new().max_rect(side), |ui| self.wf_runs(ui, screen)); + } + // Waiting for the person: a bar at the top of the canvas. + if let Some(r) = run.as_ref().filter(|r| r.state == RunState::Waiting) { + let prompt = r.current().and_then(|s| w.node(s.node)).map(|n| n.kind.words()).unwrap_or_default(); + let right = if side_open && !bar_across { side.min.x - 16.0 } else { rect.max.x - 16.0 }; + let room = right - rect.min.x - 16.0; + let bar = Rect::from_center_size(egui::pos2(rect.min.x + 16.0 + room / 2.0, rect.min.y + 40.0), vec2(520.0_f32.min(room), 48.0)); + let words = format!("{}:{}", t("等你確認"), if prompt.trim().is_empty() { t("要繼續嗎?") } else { prompt }); + ui.scope_builder(egui::UiBuilder::new().max_rect(bar), |ui| { + floating(ui, p, p.attention, Margin::symmetric(14, 8), |ui| { + ui.horizontal(|ui| { + // (The buttons first, at the right; the question in what is left, cut + // short with its whole text on hover.) + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + if !screen { + let id = self.wf.current; + if ui.add(secondary_button("停止")).clicked() { + self.wf_confirm(&ctx, id, false); + } + if ui.add(primary_button("繼續", p)).clicked() { + self.wf_confirm(&ctx, id, true); + } + } + ui.with_layout(Layout::left_to_right(Align::Center), |ui| { + ui.add(egui::Label::new(RichText::new(&words).size(FONT_SM).color(p.text)).truncate()).on_hover_text(&words); + }); + }); + }); + }); + }); + } + // Moving, drawing or a run on: keep drawing. + if self.wf.moving.is_some() || !self.wf.stroke.is_empty() || self.wf.linking.is_some() || run.as_ref().is_some_and(|r| r.live()) { + ctx.request_repaint_after(anim_after(100)); + } + } + + /// What the pointer does on the canvas, by tool. + fn wf_pointer(&mut self, ui: &mut egui::Ui, resp: &egui::Response, view: &View, rect: Rect, w: &Workflow) { + let ptr = resp.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.hover_pos())); + let Some(s) = ptr else { return }; + let c = view.to_canvas(s); + let (space, middle) = ui.input(|i| (i.key_down(Key::Space), i.pointer.middle_down())); + let hand = self.wf.tool == Tool::Hand || space || middle; + if resp.hovered() { + ui.ctx().set_cursor_icon(match self.wf.tool { + _ if hand => { + if resp.dragged() { + egui::CursorIcon::Grabbing + } else { + egui::CursorIcon::Grab + } + } + Tool::Pen | Tool::Shape => egui::CursorIcon::Crosshair, + Tool::Text => egui::CursorIcon::Text, + _ => egui::CursorIcon::Default, + }); + } + if hand { + if resp.dragged() { + self.wf.pan -= resp.drag_delta() / view.zoom; + } + return; + } + // What is under the pointer: a card's out dot, a card, a note, a line. + // A drag is only seen once the pointer has moved a little, so what it + // picks up is what was under the press, not where the pointer is now. + let out_dot_at = |s: egui::Pos2| { + w.nodes + .iter() + .rev() + .find(|n| { + let r = view.rect(node_rect(n)); + (s - egui::pos2(r.center().x, r.max.y)).length() < 12.0 + }) + .map(|n| n.id) + }; + let card_at = |s: egui::Pos2| { + let c = view.to_canvas(s); + w.nodes.iter().rev().find(|n| node_rect(n).contains(c)).map(|n| n.id) + }; + let note_at = |s: egui::Pos2| { + let c = view.to_canvas(s); + w.notes + .iter() + .rev() + .find(|n| match n.kind { + NoteKind::Pen => n.points.windows(2).any(|q| to_segment(s, view.to_screen(egui::pos2(n.x + q[0][0], n.y + q[0][1])), view.to_screen(egui::pos2(n.x + q[1][0], n.y + q[1][1]))) < 6.0), + _ => note_rect(n).contains(c), + }) + .map(|n| n.id) + }; + let pressed = ui.input(|i| i.pointer.press_origin()).unwrap_or(s); + let card = card_at(s); + let note = note_at(s); + let edge = w + .edges + .iter() + .find(|e| { + let (Some(a), Some(b)) = (w.node(e.from), w.node(e.to)) else { return false }; + let pts = edge_points(node_rect(a), node_rect(b), view); + (0..=24).map(|k| bezier_at(&pts, k as f32 / 24.0)).collect::>().windows(2).any(|q| to_segment(s, q[0], q[1]) < 6.0) + }) + .map(|e| (e.from, e.to)); + let editable_note = |id: u64| w.notes.iter().any(|n| n.id == id && matches!(n.kind, NoteKind::Sticky | NoteKind::Text)); + match self.wf.tool { + Tool::Select | Tool::Hand => { + if resp.double_clicked() { + if let Some(id) = note.filter(|id| editable_note(*id)) { + self.wf.editing = Some(id); + self.wf.selected = Some(id); + } + return; + } + if resp.drag_started() { + self.wf.editing = None; + if let Some(id) = out_dot_at(pressed) { + self.wf.linking = Some(id); + } else if let Some(id) = card_at(pressed).or_else(|| note_at(pressed)) { + self.wf.selected = Some(id); + self.wf.selected_edge = None; + self.wf.moving = Some(id); + } else { + // (Empty canvas dragged: it pans, as the hand would.) + self.wf.moving = None; + } + } + if resp.dragged() { + let d = resp.drag_delta() / view.zoom; + match self.wf.moving { + Some(id) => { + if let Some(wi) = self.wf_index() { + let wf = &mut self.state.workflows[wi]; + if let Some(n) = wf.node_mut(id) { + n.x += d.x; + n.y += d.y; + } else if let Some(n) = wf.notes.iter_mut().find(|n| n.id == id) { + n.x += d.x; + n.y += d.y; + } + } + } + None if self.wf.linking.is_none() => self.wf.pan -= d, + None => {} + } + } + if resp.drag_stopped() { + if let Some(from) = self.wf.linking.take() { + if let (Some(to), Some(wi)) = (card, self.wf_index()) { + if self.state.workflows[wi].connect(from, to) { + self.wf_touch(); + } + } + } + if self.wf.moving.take().is_some() { + self.wf_touch(); + } + } + if resp.clicked() { + self.wf.editing = None; + self.wf.selected = card.or(note); + self.wf.selected_edge = if card.or(note).is_none() { edge } else { None }; + if self.wf.selected.is_some() { + self.wf.runs_open = false; + } + } + } + Tool::Pen => { + if resp.drag_started() || (resp.dragged() && self.wf.stroke.is_empty()) { + self.wf.stroke = vec![view.to_canvas(pressed), c]; + } else if resp.dragged() && self.wf.stroke.last().is_none_or(|l| (*l - c).length() * view.zoom > 2.0) { + self.wf.stroke.push(c); + } + if resp.drag_stopped() && self.wf.stroke.len() > 1 { + let pts = std::mem::take(&mut self.wf.stroke); + let mut b = Rect::NOTHING; + for q in &pts { + b.extend_with(*q); + } + if let Some(wi) = self.wf_index() { + let id = self.state.workflows[wi].next_id(); + let points = pts.iter().map(|q| [q.x - b.min.x, q.y - b.min.y]).collect(); + self.state.workflows[wi].notes.push(Note { id, kind: NoteKind::Pen, x: b.min.x, y: b.min.y, w: b.width(), h: b.height(), points, ..Default::default() }); + self.wf_touch(); + } + } + } + Tool::Sticky | Tool::Text => { + if resp.clicked() { + if let Some(wi) = self.wf_index() { + let id = self.state.workflows[wi].next_id(); + let note = if self.wf.tool == Tool::Sticky { + Note { id, kind: NoteKind::Sticky, x: c.x - STICKY.x / 2.0, y: c.y - STICKY.y / 2.0, w: STICKY.x, h: STICKY.y, author: self.person_name(), color: STICKY_COLOURS[0].into(), ..Default::default() } + } else { + Note { id, kind: NoteKind::Text, x: c.x, y: c.y - 14.0, w: 260.0, h: 34.0, ..Default::default() } + }; + self.state.workflows[wi].notes.push(note); + self.wf.selected = Some(id); + self.wf.editing = Some(id); + self.wf.tool = Tool::Select; + self.wf_touch(); + } + } + } + Tool::Shape => { + if resp.drag_started() { + self.wf.shaping = Some(view.to_canvas(pressed)); + } + let made = if resp.drag_stopped() { + self.wf.shaping.take().map(|a| Rect::from_two_pos(a, c)).filter(|r| r.width() > 8.0 && r.height() > 8.0) + } else if resp.clicked() { + Some(Rect::from_center_size(c, vec2(200.0, 120.0))) + } else { + None + }; + if let (Some(r), Some(wi)) = (made, self.wf_index()) { + let id = self.state.workflows[wi].next_id(); + self.state.workflows[wi].notes.push(Note { id, kind: NoteKind::Shape, x: r.min.x, y: r.min.y, w: r.width(), h: r.height(), ..Default::default() }); + self.wf.selected = Some(id); + self.wf.tool = Tool::Select; + self.wf_touch(); + } + } + } + let _ = rect; + } + + /// Delete takes what is picked away; Esc lets go. + fn wf_keys(&mut self, ui: &mut egui::Ui) { + let (del, esc) = ui.input(|i| (i.key_pressed(Key::Delete) || i.key_pressed(Key::Backspace), i.key_pressed(Key::Escape))); + if esc { + self.wf.selected = None; + self.wf.selected_edge = None; + self.wf.linking = None; + self.wf.tool = Tool::Select; + } + if del { + let Some(wi) = self.wf_index() else { return }; + if let Some(id) = self.wf.selected.take() { + self.state.workflows[wi].remove(id); + self.wf_touch(); + } else if let Some((a, b)) = self.wf.selected_edge.take() { + self.state.workflows[wi].edges.retain(|e| !(e.from == a && e.to == b)); + self.wf_touch(); + } + } + } + + /// The words of a sticky note or a text note, typed where they are. + fn wf_text_edit(&mut self, ui: &mut egui::Ui, view: &View) { + let Some(id) = self.wf.editing else { return }; + let Some(wi) = self.wf_index() else { return }; + let Some(n) = self.state.workflows[wi].notes.iter_mut().find(|n| n.id == id) else { + self.wf.editing = None; + return; + }; + let sticky = n.kind == NoteKind::Sticky; + let r = view.rect(note_rect(n)); + let inner = if sticky { r.shrink(10.0 * view.zoom) } else { r }; + let size = if sticky { FONT_SM } else { FONT_H3 } * view.zoom; + let before = n.text.clone(); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(inner)); + let edit = child.add( + egui::TextEdit::multiline(&mut n.text) + .font(egui::FontId::proportional(size)) + .text_color(if sticky { crate::theme::LIGHT.text } else { colour_of(&n.color, self.pal.text) }) + .frame(Frame::NONE) + .desired_width(inner.width()) + .hint_text(t(if sticky { "寫點什麼…" } else { "文字" })), + ); + if !edit.has_focus() && !edit.lost_focus() { + edit.request_focus(); + } + if !sticky { + // A text note grows with its words. + let lines = n.text.lines().count().max(1) as f32; + n.h = lines * FONT_H3 * 1.4 + 6.0; + } + let changed = n.text != before; + let done = edit.lost_focus() || ui.input(|i| i.key_pressed(Key::Escape)); + if changed { + self.wf_touch(); + } + if done { + self.wf.editing = None; + // (An empty text note goes away.) + let empty = self.state.workflows[wi].notes.iter().any(|n| n.id == id && n.kind == NoteKind::Text && n.text.trim().is_empty()); + if empty { + self.state.workflows[wi].remove(id); + self.wf.selected = None; + } + } + } + + fn wf_toolbar(&mut self, ui: &mut egui::Ui, screen: bool) { + let p = self.pal; + floating(ui, p, p.border, Margin::symmetric(10, 6), |ui| { + ui.horizontal_centered(|ui| { + ui.spacing_mut().item_spacing.x = 6.0; + let mut tool = |ui: &mut egui::Ui, t_: Tool, icon: Icon, tip: &str| { + let on = self.wf.tool == t_; + let (rect, r) = ui.allocate_exact_size(vec2(34.0, 34.0), egui::Sense::click()); + if on || r.hovered() { + ui.painter().rect_filled(rect, R_M, if on { p.active } else { p.hover }); + } + crate::icons::paint(ui.painter(), Rect::from_center_size(rect.center(), vec2(18.0, 18.0)), icon, if on { p.text } else { p.text2 }); + if r.on_hover_text(t(tip)).clicked() { + self.wf.tool = t_; + self.wf.editing = None; + } + }; + tool(ui, Tool::Select, Icon::Pointer, "選取(拖曳卡片、從卡片底下的點拉線)"); + tool(ui, Tool::Hand, Icon::Hand, "拖曳畫布(也可以按住空白鍵)"); + ui.separator(); + if !screen { + tool(ui, Tool::Pen, Icon::Pencil, "畫筆"); + tool(ui, Tool::Sticky, Icon::StickyNote, "便利貼"); + tool(ui, Tool::Shape, Icon::Square, "形狀"); + tool(ui, Tool::Text, Icon::Type, "文字"); + ui.separator(); + } + let searching = self.wf.search.is_some(); + let toggled = crate::icons::button(ui, Icon::Search, 18.0, if searching { p.text } else { p.text2 }, p.hover).on_hover_text(t("搜尋卡片和註解")).clicked(); + let opened = toggled && !searching; + if toggled || (searching && ui.input(|i| i.key_pressed(Key::Escape))) { + self.wf.search = if searching { None } else { Some(String::new()) }; + self.wf.found = 0; + } + if let Some(mut q) = self.wf.search.take() { + let r = ui.add(egui::TextEdit::singleline(&mut q).hint_text(t("搜尋")).desired_width(110.0)); + if opened { + r.request_focus(); + } + if r.changed() { + self.wf.found = 0; + } + let enter = r.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter)); + let hits = self.wf_find(&q); + if !q.trim().is_empty() { + ui.label(RichText::new(if hits.is_empty() { t("沒有") } else { format!("{}/{}", self.wf.found.min(hits.len() - 1) + 1, hits.len()) }).size(FONT_XS).color(p.text3)); + } + if enter && !hits.is_empty() { + let id = hits[self.wf.found % hits.len()]; + self.wf.found = (self.wf.found + 1) % hits.len(); + self.wf_show(id); + r.request_focus(); + } + self.wf.search = Some(q); + } + if !screen { + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + // (Just + when the toolbar is narrow.) + let r = ui.add(primary_button(if ui.available_width() < 104.0 { "+" } else { "+ 新增節點" }, p)).on_hover_text(t("新增節點")); + egui::Popup::menu(&r).show(|ui| { + ui.set_min_width(220.0); + for (icon, label, which) in [(Icon::Bot, "Bot 步驟", "step"), (Icon::CircleCheck, "等你確認", "approve"), (Icon::Shield, "檢查", "check"), (Icon::Send, "交付", "deliver"), (Icon::Bell, "通知你", "notify")] { + if menu_ui::item(ui, p, icon, label).clicked() { + self.wf_add_node(which); + ui.close(); + } + } + }); + }); + } + }); + }); + } + + /// A new card after the picked one (or the last step), joined to it. + fn wf_add_node(&mut self, which: &str) { + let Some(wi) = self.wf_index() else { return }; + let bot = if self.state.bot(self.state.selected).is_some() { self.state.selected } else { self.state.bots.first().map(|b| b.id).unwrap_or(0) }; + let kind = match which { + "approve" => NodeKind::Approve { prompt: String::new() }, + "check" => NodeKind::Check { bot, condition: String::new() }, + "deliver" => NodeKind::Deliver { bot }, + "notify" => NodeKind::Notify { text: t("{結果}") }, + _ => NodeKind::Step { bot, prompt: String::new() }, + }; + let w = &mut self.state.workflows[wi]; + let after = self.wf.selected.filter(|s| w.node(*s).is_some()).or_else(|| w.order().last().copied()).and_then(|s| w.node(s)).cloned(); + let id = w.next_id(); + let (x, y) = match &after { + Some(a) => { + // Below it; beside the ones already below it. + let below = w.edges.iter().filter(|e| e.from == a.id).count() as f32; + (a.x + below * (NODE_W + 40.0), a.y + node_h(&a.kind) + 70.0) + } + None => (0.0, 220.0), + }; + w.nodes.push(Node { id, kind, x, y }); + if let Some(a) = after { + w.connect(a.id, id); + } + self.wf.selected = Some(id); + self.wf.runs_open = false; + self.wf_touch(); + } + + /// Cards and notes whose words have it. + fn wf_find(&self, q: &str) -> Vec { + let q = q.trim().to_lowercase(); + let Some(wi) = self.wf_index() else { return vec![] }; + if q.is_empty() { + return vec![]; + } + let w = &self.state.workflows[wi]; + let names: HashMap = self.state.bots.iter().map(|b| (b.id, b.name.to_lowercase())).collect(); + let mut out: Vec = w + .nodes + .iter() + .filter(|n| { + let bot = match &n.kind { + NodeKind::Step { bot, .. } | NodeKind::Check { bot, .. } | NodeKind::Deliver { bot } => names.get(bot).cloned().unwrap_or_default(), + _ => String::new(), + }; + n.kind.words().to_lowercase().contains(&q) || t(n.kind.label()).to_lowercase().contains(&q) || bot.contains(&q) + }) + .map(|n| n.id) + .collect(); + out.extend(w.notes.iter().filter(|n| n.text.to_lowercase().contains(&q) || n.author.to_lowercase().contains(&q)).map(|n| n.id)); + out + } + + /// The view moves to a card or note, and it is picked. + fn wf_show(&mut self, id: u64) { + let Some(wi) = self.wf_index() else { return }; + let w = &self.state.workflows[wi]; + let r = w.node(id).map(node_rect).or_else(|| w.notes.iter().find(|n| n.id == id).map(note_rect)); + if let Some(r) = r { + // (The view's size is last frame's; centred well enough.) + let view = egui::vec2(900.0, 560.0) / self.wf.zoom; + self.wf.pan = r.center().to_vec2() - view / 2.0; + self.wf.selected = Some(id); + } + } + + fn wf_zoombar(&mut self, ui: &mut egui::Ui, canvas: Rect) { + let p = self.pal; + floating(ui, p, p.border, Margin::symmetric(8, 4), |ui| { + ui.horizontal_centered(|ui| { + ui.spacing_mut().item_spacing.x = 4.0; + let zoom_by = |me: &mut App, k: f32| { + // Around the middle of the view. + let mid = vec2(canvas.width(), canvas.height()) / 2.0; + let at = me.wf.pan + mid / me.wf.zoom; + me.wf.zoom = (me.wf.zoom * k).clamp(ZOOM_MIN, ZOOM_MAX); + me.wf.pan = at - mid / me.wf.zoom; + }; + if crate::icons::button(ui, Icon::Minus, 16.0, p.text2, p.hover).on_hover_text(t("縮小")).clicked() { + zoom_by(self, 1.0 / 1.2); + } + if ui.add(egui::Button::new(RichText::new(format!("{:.0}%", self.wf.zoom * 100.0)).size(FONT_SM).color(p.text)).frame(false).min_size(vec2(48.0, 28.0))).on_hover_text(t("回到 100%")).clicked() { + zoom_by(self, 1.0 / self.wf.zoom); + } + if crate::icons::button(ui, Icon::Plus, 16.0, p.text2, p.hover).on_hover_text(t("放大")).clicked() { + zoom_by(self, 1.2); + } + ui.separator(); + if crate::icons::button(ui, Icon::Scan, 16.0, p.text2, p.hover).on_hover_text(t("符合畫面")).clicked() { + self.wf_fit(canvas); + } + let on = self.wf.minimap; + if crate::icons::button(ui, Icon::Map, 16.0, if on { p.text } else { p.text2 }, p.hover).on_hover_text(t("小地圖")).clicked() { + self.wf.minimap = !on; + } + }); + }); + } + + /// The whole canvas, small, with where the view is; a click moves the view there. + fn wf_minimap(&mut self, ui: &mut egui::Ui, mm: Rect, canvas: Rect, w: &Workflow) { + let p = self.pal; + let painter = ui.painter_at(mm); + painter.rect_filled(mm, R_L, p.elevated); + painter.rect_stroke(mm, R_L, Stroke::new(1.0, p.border), egui::StrokeKind::Inside); + let view_c = Rect::from_min_size(self.wf.pan.to_pos2(), vec2(canvas.width(), canvas.height()) / self.wf.zoom); + let mut b = view_c; + for n in &w.nodes { + b = b.union(node_rect(n)); + } + for n in &w.notes { + b = b.union(note_rect(n)); + } + let b = b.expand(40.0); + let inner = mm.shrink(8.0); + let k = (inner.width() / b.width()).min(inner.height() / b.height()); + let to = |c: egui::Pos2| inner.min + (c - b.min) * k; + let map = |r: Rect| Rect::from_min_max(to(r.min), to(r.max)); + for n in &w.notes { + painter.rect_filled(map(note_rect(n)), 1.0, if n.kind == NoteKind::Sticky { crate::avatar::color(if n.color.is_empty() { STICKY_COLOURS[0] } else { &n.color }) } else { p.hover }); + } + for n in &w.nodes { + painter.rect_filled(map(node_rect(n)), 2.0, p.text3); + } + painter.rect_stroke(map(view_c), 2.0, Stroke::new(1.5, p.accent), egui::StrokeKind::Inside); + let r = ui.interact(mm, egui::Id::unique(("wf-minimap", w.id)), egui::Sense::click_and_drag()); + if let Some(s) = r.interact_pointer_pos().filter(|_| r.clicked() || r.dragged()) { + let c = b.min + (s - inner.min) / k; + self.wf.pan = c.to_vec2() - vec2(canvas.width(), canvas.height()) / self.wf.zoom / 2.0; + } + } + + /// A picked card's settings. + fn wf_inspector(&mut self, ui: &mut egui::Ui, id: u64, screen: bool) { + let p = self.pal; + let Some(wi) = self.wf_index() else { return }; + let Some(node) = self.state.workflows[wi].node(id).cloned() else { return }; + let bots: Vec<(u64, String)> = self.state.bots.iter().map(|b| (b.id, b.name.clone())).collect(); + let mut kind = node.kind.clone(); + let mut remove = false; + let mut run_now = false; + floating(ui, p, p.border, Margin::same(16), |ui| { + ui.set_width(ui.available_width()); + ui.add_enabled_ui(!screen, |ui| { + ui.horizontal(|ui| { + crate::icons::paint(ui.painter(), Rect::from_min_size(ui.cursor().min + vec2(0.0, 2.0), vec2(16.0, 16.0)), kind_icon(&kind), p.text2); + ui.add_space(22.0); + ui.label(RichText::new(t(kind.label())).size(FONT_BASE).family(crate::bold()).color(p.text)); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + if crate::icons::button(ui, Icon::Close, 16.0, p.text3, p.hover).on_hover_text(t("關閉")).clicked() { + self.wf.selected = None; + } + }); + }); + ui.add_space(8.0); + let bot_pick = |ui: &mut egui::Ui, bot: &mut u64, salt: &str| { + field_label(ui, "哪個 Bot", p); + let shown = bots.iter().find(|b| b.0 == *bot).map(|b| b.1.clone()).unwrap_or_else(|| t("(選一個 Bot)")); + egui::ComboBox::from_id_salt((salt, id)).selected_text(shown).width(ui.available_width() - 8.0).show_ui(ui, |ui| { + for (b, n) in &bots { + ui.selectable_value(bot, *b, n); + } + }); + }; + let words = |ui: &mut egui::Ui, label: &str, text: &mut String, hint_: &str| { + field_label(ui, label, p); + ui.add(egui::TextEdit::multiline(text).hint_text(t(hint_)).desired_rows(4).desired_width(f32::INFINITY)); + }; + match &mut kind { + NodeKind::Trigger { schedule } => { + field_label(ui, "什麼時候執行", p); + let timed = schedule.is_some(); + if let Some(v) = segmented(ui, p, timed, &[(false, "手動"), (true, "定時")]) { + *schedule = if v { serde_json::from_value(serde_json::json!({"frequency": "daily", "time": "09:00", "timezone": self.state.timezone})).ok() } else { None }; + } + if let Some(s) = schedule.as_mut() { + ui.add_space(6.0); + ui.horizontal(|ui| { + use crate::routines::Frequency as F; + let names = [(F::Hourly, "每小時"), (F::Daily, "每天"), (F::Weekly, "每週"), (F::Monthly, "每月")]; + let shown = names.iter().find(|n| n.0 == s.frequency).map(|n| n.1).unwrap_or("每天"); + egui::ComboBox::from_id_salt(("wf-freq", id)).selected_text(t(shown)).width(90.0).show_ui(ui, |ui| { + for (f, n) in names { + if ui.selectable_label(s.frequency == f, t(n)).clicked() { + s.frequency = f; + if f == F::Weekly && s.days_of_week.is_empty() { + s.days_of_week = vec!["MO".into()]; + } + } + } + }); + ui.label(RichText::new(t("在")).size(FONT_SM).color(p.text3)); + ui.add(egui::TextEdit::singleline(&mut s.time).desired_width(64.0).hint_text("09:00")); + }); + if s.frequency == crate::routines::Frequency::Weekly { + ui.horizontal_wrapped(|ui| { + for (code, n) in [("MO", "一"), ("TU", "二"), ("WE", "三"), ("TH", "四"), ("FR", "五"), ("SA", "六"), ("SU", "日")] { + let on = s.days_of_week.iter().any(|d| d == code); + if ui.selectable_label(on, n).clicked() { + if on { + s.days_of_week.retain(|d| d != code); + } else { + s.days_of_week.push(code.into()); + } + } + } + }); + } + hint(ui, crate::routines::describe(s), p); + } + ui.add_space(8.0); + let live = self.state.workflows[wi].live_run().is_some(); + if ui.add_enabled(!live, primary_button("立即執行 ▷", p)).clicked() { + run_now = true; + } + } + NodeKind::Step { bot, prompt } => { + bot_pick(ui, bot, "wf-step-bot"); + words(ui, "要它做什麼", prompt, "例如:到 Threads 找今天熱門的 5 則討論,整理成清單。上一步的結果會一起給它。"); + } + NodeKind::Approve { prompt } => { + words(ui, "要你確認什麼", prompt, "例如:要把這篇貼出去嗎?(停在這裡等你按繼續或停止)"); + } + NodeKind::Check { bot, condition } => { + bot_pick(ui, bot, "wf-check-bot"); + words(ui, "要做到什麼", condition, "例如:至少三則,每則都有連結。沒做到就停下來,說原因。"); + } + NodeKind::Deliver { bot } => { + bot_pick(ui, bot, "wf-deliver-bot"); + hint(ui, "上一步的結果會放進這個 Bot 的聊天,你在那裡看。", p); + } + NodeKind::Notify { text } => { + words(ui, "通知寫什麼", text, "{結果} 會換成上一步結果的第一行"); + } + } + // What the last run did here. + if let Some(s) = self.state.workflows[wi].runs.last().and_then(|r| r.step_of(id)).filter(|s| s.state != StepState::Waiting) { + ui.add_space(10.0); + field_label(ui, "上一次執行", p); + let (words, col) = match s.state { + StepState::Done => (t("完成"), p.up), + StepState::Failed => (t("失敗"), p.danger), + StepState::Running => (t("進行中…"), p.accent), + StepState::Waiting => (String::new(), p.text3), + }; + ui.label(RichText::new(words).size(FONT_SM).color(col)); + if !s.output.is_empty() { + egui::ScrollArea::vertical().id_salt(("wf-out", id)).max_height(140.0).show(ui, |ui| { + ui.add(egui::Label::new(RichText::new(&s.output).size(FONT_SM).color(p.text2)).wrap()); + }); + } + } + if !matches!(kind, NodeKind::Trigger { .. }) { + ui.add_space(12.0); + if ui.add(egui::Button::new(RichText::new(t("刪除這一步")).size(FONT_SM).color(p.danger)).frame(false)).clicked() { + remove = true; + } + } + }); + }); + if kind != node.kind { + let schedule_changed = matches!((&kind, &node.kind), (NodeKind::Trigger { schedule: a }, NodeKind::Trigger { schedule: b }) if a != b); + if let Some(n) = self.state.workflows[wi].node_mut(id) { + n.kind = kind; + } + if schedule_changed { + // Worked out again at the next tick. + self.state.workflows[wi].next_run = None; + } + self.wf_touch(); + } + if remove { + self.state.workflows[wi].remove(id); + self.wf.selected = None; + self.wf_touch(); + } + if run_now { + let ctx = ui.ctx().clone(); + let wf = self.wf.current; + self.wf_keep_version(); + self.wf_start(&ctx, wf, "手動"); + self.wf.runs_open = true; + } + } + + /// A picked note: its colour, and taking it away. + fn wf_note_inspector(&mut self, ui: &mut egui::Ui, id: u64, screen: bool) { + let p = self.pal; + let Some(wi) = self.wf_index() else { return }; + let Some(note) = self.state.workflows[wi].notes.iter().find(|n| n.id == id).cloned() else { return }; + let mut colour = note.color.clone(); + let mut remove = false; + let mut edit = false; + floating(ui, p, p.border, Margin::same(14), |ui| { + ui.set_width(ui.available_width()); + ui.add_enabled_ui(!screen, |ui| { + let name = match note.kind { + NoteKind::Pen => "畫筆", + NoteKind::Sticky => "便利貼", + NoteKind::Shape => "形狀", + NoteKind::Text => "文字", + }; + ui.label(RichText::new(t(name)).size(FONT_BASE).family(crate::bold()).color(p.text)); + ui.add_space(6.0); + ui.horizontal(|ui| { + let set: &[&str] = if note.kind == NoteKind::Sticky { &STICKY_COLOURS } else { &INK_COLOURS }; + for c in set { + let (rect, r) = ui.allocate_exact_size(vec2(24.0, 24.0), egui::Sense::click()); + let fill = colour_of(c, p.text); + ui.painter().circle_filled(rect.center(), 9.0, fill); + if colour == *c || (colour.is_empty() && c.is_empty()) { + ui.painter().circle_stroke(rect.center(), 11.5, Stroke::new(2.0, p.text)); + } + if r.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() { + colour = c.to_string(); + } + } + }); + ui.add_space(8.0); + ui.horizontal(|ui| { + if matches!(note.kind, NoteKind::Sticky | NoteKind::Text) && ui.add(secondary_button("改文字")).clicked() { + edit = true; + } + if ui.add(egui::Button::new(RichText::new(t("刪除")).size(FONT_SM).color(p.danger)).frame(false)).clicked() { + remove = true; + } + }); + }); + }); + if colour != note.color { + if let Some(n) = self.state.workflows[wi].notes.iter_mut().find(|n| n.id == id) { + n.color = colour; + } + self.wf_touch(); + } + if edit { + self.wf.editing = Some(id); + } + if remove { + self.state.workflows[wi].remove(id); + self.wf.selected = None; + self.wf_touch(); + } + } + + /// 執行紀錄: the latest runs, the newest open — each step, what it gave, why it stopped. + fn wf_runs(&mut self, ui: &mut egui::Ui, screen: bool) { + let p = self.pal; + let Some(wi) = self.wf_index() else { return }; + let w = self.state.workflows[wi].clone(); + let tz = self.state.timezone.clone(); + floating(ui, p, p.border, Margin::same(16), |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + ui.label(RichText::new(t("執行紀錄")).size(FONT_BASE).family(crate::bold()).color(p.text)); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + if crate::icons::button(ui, Icon::Close, 16.0, p.text3, p.hover).clicked() { + self.wf.runs_open = false; + } + }); + }); + ui.add_space(6.0); + if w.runs.is_empty() { + hint(ui, if screen { "還沒有執行過" } else { "還沒有執行過:按右上角「執行工作流」,或觸發器的「立即執行」。" }, p); + return; + } + egui::ScrollArea::vertical().id_salt(("wf-runs", w.id)).auto_shrink([false, true]).show(ui, |ui| { + for (k, r) in w.runs.iter().rev().enumerate() { + let (state, col) = match r.state { + RunState::Running => (t("進行中"), p.accent), + RunState::Waiting => (t("等你確認"), p.attention), + RunState::Done => (t("完成"), p.up), + RunState::Failed => (t("失敗"), p.danger), + RunState::Stopped => (t("停止"), p.text3), + }; + ui.horizontal(|ui| { + ui.label(RichText::new(crate::routines::describe_when(r.started, &tz)).size(FONT_SM).color(p.text)); + ui.label(RichText::new(format!("· {}", r.by)).size(FONT_XS).color(p.text3)); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + ui.label(RichText::new(state).size(FONT_SM).color(col)); + }); + }); + if !r.why.is_empty() { + ui.add(egui::Label::new(RichText::new(&r.why).size(FONT_XS).color(if r.state == RunState::Failed { p.danger } else { p.text3 })).wrap()); + } + // The newest run, step by step. + if k == 0 { + for s in r.steps.iter().skip(1) { + let label = w.node(s.node).map(|n| t(n.kind.label())).unwrap_or_else(|| t("(已刪除的步驟)")); + let mark = match s.state { + StepState::Done => "✓", + StepState::Failed => "✗", + StepState::Running => "…", + StepState::Waiting => "·", + }; + ui.horizontal(|ui| { + ui.add_space(8.0); + ui.label(RichText::new(format!("{mark} {label}")).size(FONT_XS).color(p.text2)); + }); + if !s.output.is_empty() { + ui.horizontal(|ui| { + ui.add_space(22.0); + let first: String = s.output.lines().next().unwrap_or("").chars().take(80).collect(); + ui.add(egui::Label::new(RichText::new(first).size(FONT_XS).color(p.text3)).truncate()).on_hover_text(&s.output); + }); + } + } + } + ui.separator(); + } + }); + }); + } +} + +impl App { + /// A sample workflow on the canvas (ANYBOT_SHOT_VIEW=workflow and the layout check). + pub(super) fn wf_demo(&mut self) { + let bot = self.state.bots.first().map(|b| b.id).unwrap_or(0); + let mut w = Workflow::new(1, "每天早上的 Threads 早報", 0); + if let NodeKind::Trigger { schedule } = &mut w.nodes[0].kind { + *schedule = serde_json::from_value(serde_json::json!({"frequency": "daily", "time": "09:00", "timezone": "Asia/Taipei"})).ok(); + } + w.nodes[0].x = 0.0; + w.nodes[0].y = 0.0; + for (id, kind, x, y) in [ + (2, NodeKind::Step { bot, prompt: "到 Threads 找今天熱門的 5 則育兒討論,整理成清單,每則附連結。".into() }, 0.0, 220.0), + (3, NodeKind::Check { bot, condition: "至少三則,每則都有連結".into() }, 0.0, 408.0), + (4, NodeKind::Approve { prompt: "要把早報傳給你嗎?".into() }, 0.0, 596.0), + (5, NodeKind::Deliver { bot }, -170.0, 762.0), + (6, NodeKind::Notify { text: "早報好了:{結果}".into() }, 170.0, 762.0), + ] { + w.nodes.push(Node { id, kind, x, y }); + } + for (a, b) in [(1, 2), (2, 3), (3, 4), (4, 5), (4, 6)] { + w.connect(a, b); + } + w.notes.push(Note { id: 7, kind: NoteKind::Sticky, x: -330.0, y: 210.0, w: 200.0, h: 160.0, text: "週末改成十點".into(), author: "Jenny".into(), color: STICKY_COLOURS[0].into(), ..Default::default() }); + w.notes.push(Note { id: 8, kind: NoteKind::Shape, x: 330.0, y: 400.0, w: 200.0, h: 120.0, ..Default::default() }); + w.notes.push(Note { id: 9, kind: NoteKind::Text, x: 330.0, y: 540.0, w: 240.0, h: 34.0, text: "這段要人看過".into(), ..Default::default() }); + let pts: Vec<[f32; 2]> = (0..=40) + .map(|i| { + let a = i as f32 / 40.0 * 5.0; + [a * 30.0, (a * 1.7).sin() * 40.0 + 40.0] + }) + .collect(); + w.notes.push(Note { id: 10, kind: NoteKind::Pen, x: 330.0, y: 160.0, w: 150.0, h: 80.0, points: pts, ..Default::default() }); + // The last run: done up to the confirm, waiting for the person. + w.start_run("定時", 0); + if let Some(r) = w.runs.last_mut() { + for s in r.steps.iter_mut().take(3) { + s.state = StepState::Done; + s.output = "1. 寶寶夜醒…\n2. 副食品…\n3. 托嬰…".into(); + } + r.steps[3].state = StepState::Running; + r.at = 3; + r.state = RunState::Waiting; + } + self.state.workflows = vec![w]; + self.wf.current = 1; + self.wf.open = true; + self.wf.chat_was = self.state.selected; + // (The canvas alone, the whole width: the chat beside it shows with real data.) + self.wf.chat_hidden = true; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_view_maps_canvas_and_screen_both_ways() { + let v = View { origin: egui::pos2(100.0, 50.0), pan: vec2(-20.0, 10.0), zoom: 0.5 }; + let c = egui::pos2(300.0, 410.0); + let s = v.to_screen(c); + assert_eq!(s, egui::pos2(100.0 + 320.0 * 0.5, 50.0 + 400.0 * 0.5)); + assert!((v.to_canvas(s) - c).length() < 1e-3); + assert!((to_segment(egui::pos2(5.0, 3.0), egui::pos2(0.0, 0.0), egui::pos2(10.0, 0.0)) - 3.0).abs() < 1e-4); + let pts = [egui::pos2(0.0, 0.0), egui::pos2(0.0, 10.0), egui::pos2(10.0, 0.0), egui::pos2(10.0, 10.0)]; + assert_eq!((bezier_at(&pts, 0.0), bezier_at(&pts, 1.0)), (pts[0], pts[3])); + } +} diff --git a/src/appctl.rs b/src/appctl.rs index cc30bc5..198b65d 100644 --- a/src/appctl.rs +++ b/src/appctl.rs @@ -9,12 +9,15 @@ use crate::model::{self, Bot, Message, State, Theme, Accent}; use crate::providers::{ProviderKind, ALL_PROVIDERS}; use crate::routines::{self, Routine, Schedule}; -pub const NAMES: [&str; 33] = [ +pub const NAMES: [&str; 34] = [ // 追進度: follow something long in the background (followup.rs; checks run on the brain). "follow_up", // 任務: the tasks and their states as AnyBot works them out (tasks.rs; read-only). crate::tasks::TOOL, "list_routines", "create_routine", "update_routine", "delete_routine", "run_routine_now", + // 工作流: make, change and run the canvases of steps (the window runs it and shows the canvas + // beside the chat; workflow.rs). + crate::workflow::TOOL, "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); // 教技能: give a colleague a skill this bot has (the person says yes first). @@ -40,6 +43,7 @@ pub fn is_app_tool(name: &str) -> bool { pub fn label(name: &str) -> &'static str { match name { "list_routines" => "查看例行任務", + crate::workflow::TOOL => "工作流", crate::tasks::TOOL => "查看任務", crate::mcp::MANAGE_TOOL => "管理連接器", crate::hooks::MANAGE_TOOL => "管理 hook", @@ -77,7 +81,7 @@ pub fn label(name: &str) -> &'static str { } } -fn schedule_schema() -> Value { +pub(crate) fn schedule_schema() -> Value { json!({ "type": "object", "description": "When it repeats, in the person's words turned into fields.", @@ -123,6 +127,7 @@ pub fn specs() -> Vec { "id": {"type": "integer"}, "title": {"type": "string"}, "prompt": {"type": "string"}, "schedule": schedule_schema(), "trigger": crate::triggers::schema(), "paused": {"type": "boolean"}, "target_sends": target_sends_schema()}, "required": ["id"]}}), json!({"name": "delete_routine", "description": "Delete a routine. The person is asked first.", "parameters": {"type": "object", "properties": {"id": {"type": "integer"}}, "required": ["id"]}}), json!({"name": "run_routine_now", "description": "Run a routine once right away.", "parameters": {"type": "object", "properties": {"id": {"type": "integer"}}, "required": ["id"]}}), + crate::workflow::spec(schedule_schema()), json!({"name": "list_bots", "description": "List the person's bots with their provider, model and what they do.", "parameters": {"type": "object", "properties": {}}}), json!({"name": "create_bot", "description": "Create a new bot, optionally from a template (a ready role and instructions).", "parameters": {"type": "object", "properties": { @@ -192,6 +197,20 @@ pub fn describe(name: &str, args: &str) -> String { format!("{t} {when}").trim().to_string() } "delete_routine" | "run_routine_now" => format!("#{}", v.get("id").and_then(Value::as_u64).unwrap_or(0)), + crate::workflow::TOOL => { + let what = match s("action").as_str() { + "list" => "看有哪些", + "show" => "看", + "create" => "建立", + "edit" => "修改", + "run" => "執行", + "stop" => "停止", + "delete" => "刪除", + _ => "", + }; + let which = if s("name").is_empty() { v.get("id").and_then(Value::as_u64).map(|i| format!("#{i}")).unwrap_or_default() } else { format!("「{}」", s("name")) }; + format!("{what} {which}").trim().to_string() + } crate::mcp::MANAGE_TOOL => format!("{} {}", s("action"), s("name")).trim().to_string(), crate::hooks::MANAGE_TOOL => format!("{} {}", s("action"), s("event")).trim().to_string(), crate::chatgpt::TOOL => crate::chatgpt::describe(args), @@ -256,6 +275,12 @@ pub fn needs_approval(name: &str, args: &str, state: &State) -> Option { _ => None, }; } + // 刪工作流: its steps, notes, versions and runs go with it. + if name == crate::workflow::TOOL && v["action"].as_str().is_some_and(|a| a.trim().eq_ignore_ascii_case("delete")) { + let w = v["id"].as_u64().and_then(|id| state.workflows.iter().find(|w| w.id == id)).or_else(|| state.workflows.iter().max_by_key(|w| w.updated_at)); + let name = w.map(|w| format!("「{}」", w.name)).unwrap_or_else(|| "(找不到的那個)".into()); + return Some(format!("刪除工作流{name}:它的步驟、便利貼、版本歷史和執行紀錄都會刪掉,無法復原。")); + } if name == "delete_routine" { let id = v.get("id").and_then(Value::as_u64).unwrap_or(0); let title = state.bots.iter().flat_map(|b| b.routines.iter()).find(|r| r.id == id).map(|r| r.title.clone()).unwrap_or_else(|| format!("#{id}")); @@ -536,6 +561,18 @@ pub fn apply(state: &mut State, bot_id: u64, name: &str, args: &str) -> Outcome "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)), + // 工作流 (the window runs it — app/workflow_run.rs — with the canvas; here: the workflows + // alone, nothing started or stopped). + crate::workflow::TOOL => { + let bots: Vec<(u64, String)> = state.bots.iter().filter(|b| b.branch_of == 0).map(|b| (b.id, b.name.clone())).collect(); + let tz = state.timezone.clone(); + let who = crate::workflow::Who { me: bot_id, bots: &bots, timezone: &tz }; + match crate::workflow::tool(&mut state.workflows, &who, &v, None, now) { + Ok(t) if t.run || t.stop => err("執行和停止要在開著的 AnyBot 上做".into()), + Ok(t) => ok(t.text), + Err(e) => err(e), + } + } "list_routines" => { let Some(b) = state.bot(bot_id) else { return err("找不到這個 Bot".into()) }; if b.routines.is_empty() { diff --git a/src/featuremap.rs b/src/featuremap.rs index 2ea1f8f..7e6d111 100644 --- a/src/featuremap.rs +++ b/src/featuremap.rs @@ -46,6 +46,7 @@ pub const AREAS: &[Area] = &[ area!("pages", "頁面"), area!("pageview", "頁面的版面與圖表"), area!("routines", "例行任務"), + area!("workflow", "工作流"), area!("goal", "目標(/goal)"), area!("plan", "計畫(/plan)"), area!("tasks", "任務"), diff --git a/src/icons.rs b/src/icons.rs index a0f79dc..c52920e 100644 --- a/src/icons.rs +++ b/src/icons.rs @@ -86,6 +86,16 @@ pub enum Icon { Bookmark, Brain, Target, + // 工作流 (the canvas and its tools). + Workflow, + Hand, + Pointer, + StickyNote, + Square, + Type, + Map, + Scan, + Send, } impl Icon { @@ -178,6 +188,15 @@ impl Icon { Icon::Message => include_str!("../icons/lucide/message-circle.svg"), Icon::Alarm => include_str!("../icons/lucide/alarm-clock.svg"), Icon::Target => include_str!("../icons/lucide/target.svg"), + Icon::Workflow => include_str!("../icons/lucide/workflow.svg"), + Icon::Hand => include_str!("../icons/lucide/hand.svg"), + Icon::Pointer => include_str!("../icons/lucide/mouse-pointer-2.svg"), + Icon::StickyNote => include_str!("../icons/lucide/sticky-note.svg"), + Icon::Square => include_str!("../icons/lucide/square.svg"), + Icon::Type => include_str!("../icons/lucide/type.svg"), + Icon::Map => include_str!("../icons/lucide/map.svg"), + Icon::Scan => include_str!("../icons/lucide/scan.svg"), + Icon::Send => include_str!("../icons/lucide/send.svg"), Icon::CircleCheck => include_str!("../icons/lucide/circle-check.svg"), Icon::CircleX => include_str!("../icons/lucide/circle-x.svg"), Icon::Minus => include_str!("../icons/lucide/minus.svg"), diff --git a/src/main.rs b/src/main.rs index 06f932d..c15417f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -63,6 +63,7 @@ mod providers; mod publish; mod remote; mod routines; +mod workflow; mod setup; mod skills; mod teach; diff --git a/src/model.rs b/src/model.rs index dd7f98f..9ad1bb3 100644 --- a/src/model.rs +++ b/src/model.rs @@ -866,6 +866,9 @@ pub struct State { /// 頁面 the bots made and keep up to date. #[serde(default)] pub pages: Vec, + /// 工作流: steps on a canvas, run in order (workflow.rs). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub workflows: Vec, /// 待改進: AnyBot's own problems the bots ran into (garden.rs), for whoever fixes AnyBot. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub improvements: Vec, @@ -1447,6 +1450,7 @@ impl State { branch_bots: vec![], skills_seeded: false, pages: vec![], + workflows: vec![], improvements: vec![], garden_reports: true, garden_daily: 0, diff --git a/src/profile.rs b/src/profile.rs index ec2f5b7..382f2c1 100644 --- a/src/profile.rs +++ b/src/profile.rs @@ -20,7 +20,7 @@ pub const ABILITIES: [(&str, &str, &str); 11] = [ ("mac_apps", "Mac App", "提醒事項、行事曆、聯絡人、備忘錄、郵件、訊息"), ("connectors", "連接器", "你接上的 MCP 連接器"), ("phone", "電話、簡訊、X", "打電話、傳簡訊、在 X 發文"), - ("routines", "例行任務", "設定和管理定時要做的事"), + ("routines", "例行任務與工作流", "設定和管理定時要做的事、多步驟的工作流"), ("pages", "頁面", "寫和維護追蹤、報告頁面"), ("team", "和其他 Bot 合作", "把工作交給其他 Bot"), ("admin", "管理 App", "建立和修改 Bot、群組、技能,改 App 設定"), @@ -40,7 +40,7 @@ pub fn ability_of(tool: &str) -> Option<&'static str> { t if crate::macapps::is_mac_tool(t) => "mac_apps", t if crate::mcp::is_mcp_tool(t) || t == crate::mcp::FIND_TOOL || t == crate::mcp::USE_TOOL => "connectors", "place_call" | "send_sms" | "post_to_x" => "phone", - "create_routine" | "update_routine" | "delete_routine" | "list_routines" | "run_routine_now" => "routines", + "create_routine" | "update_routine" | "delete_routine" | "list_routines" | "run_routine_now" | crate::workflow::TOOL => "routines", "write_page" | "read_page" | "list_pages" => "pages", "message_bot" | "ask_bot" | "teach_skill" | "list_bots" => "team", "create_bot" | "update_bot" | "update_settings" | "create_group" | "move_to_group" | "rename_group" | "delete_group" | "delete_skill" | "skill_install" | crate::mcp::MANAGE_TOOL | crate::hooks::MANAGE_TOOL | crate::chatgpt::TOOL => "admin", diff --git a/src/workflow.rs b/src/workflow.rs new file mode 100644 index 0000000..f044031 --- /dev/null +++ b/src/workflow.rs @@ -0,0 +1,1114 @@ +// 工作流: a few steps drawn on a canvas and run in order — a trigger (by hand, or on a schedule), +// then the steps it leads to along the lines: a bot does something (its chat shows it, as any +// question to it), the person confirms, a bot checks the last result against a condition, the +// result goes into a bot's chat, a notification. Each step hands its result on to the next. +// Beside them on the canvas: what the person drew and wrote (pen strokes, sticky notes, shapes, +// words) — notes for people, never run. Kept with the other settings (State.workflows); the +// brain runs them (app/workflow_ui.rs drives a run, turn by turn, like 問同事). +// +// A bot makes and changes them too, from the chat (the `workflow` tool, `tool` below): the +// person asks for a flow in words and watches the canvas beside the chat change as the bot +// works — steps in a tidy column, sticky notes beside the steps they are about. + +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +/// How many earlier versions a workflow keeps (版本歷史). +pub const VERSIONS_KEPT: usize = 30; +/// How many runs a workflow remembers (執行紀錄). +pub const RUNS_KEPT: usize = 20; +/// The most of a step's result handed on to the next step (the whole stays in the bot's chat). +pub const HANDED_ON_CHARS: usize = 6_000; +/// A card's width on the canvas. +pub const CARD_W: f32 = 280.0; +/// Laid out: one step below the other this far apart, side by side this far apart. +pub const ROW: f32 = 190.0; +pub const COLUMN: f32 = 340.0; +/// A sticky note's size. +pub const STICKY_W: f32 = 200.0; +pub const STICKY_H: f32 = 160.0; +/// Sticky note colours, and the names a bot gives them. +pub const STICKY_COLOURS: [&str; 6] = ["#f7c9b0", "#f6e3a1", "#bfe3c0", "#bcd7f2", "#f3c1d9", "#e2dfd8"]; +pub const STICKY_NAMES: [&str; 6] = ["orange", "yellow", "green", "blue", "pink", "grey"]; + +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Default)] +pub struct Workflow { + pub id: u64, + pub name: String, + #[serde(default)] + pub nodes: Vec, + #[serde(default)] + pub edges: Vec, + /// What people drew and wrote on the canvas (not run). + #[serde(default)] + pub notes: Vec, + /// Earlier versions, oldest first (at most VERSIONS_KEPT). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub versions: Vec, + /// The latest runs, oldest first (at most RUNS_KEPT). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub runs: Vec, + /// Seconds since 1970. + #[serde(default)] + pub created_at: i64, + #[serde(default)] + pub updated_at: i64, + /// A scheduled trigger's next time (seconds since 1970); None: by hand only. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub next_run: Option, +} + +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)] +pub struct Node { + pub id: u64, + pub kind: NodeKind, + /// Where it is on the canvas (its top-left, in canvas points). + pub x: f32, + pub y: f32, +} + +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum NodeKind { + /// Where a run starts: by hand (立即執行/執行工作流), or also on a schedule. + Trigger { + #[serde(default, skip_serializing_if = "Option::is_none")] + schedule: Option, + }, + /// A bot does what it is asked (the last step's result goes with it). + Step { bot: u64, prompt: String }, + /// The person says go on or stop. + Approve { prompt: String }, + /// A bot reads the last result against a condition: 通過 goes on, otherwise the run stops. + Check { bot: u64, condition: String }, + /// The last result goes into a bot's chat, for the person to read there. + Deliver { bot: u64 }, + /// A notification (on this computer and the person's phones); 「{結果}」 is the last result. + Notify { text: String }, +} + +impl NodeKind { + /// Its name on the canvas. + pub fn label(&self) -> &'static str { + match self { + NodeKind::Trigger { .. } => "觸發器", + NodeKind::Step { .. } => "Bot 步驟", + NodeKind::Approve { .. } => "等你確認", + NodeKind::Check { .. } => "檢查", + NodeKind::Deliver { .. } => "交付", + NodeKind::Notify { .. } => "通知你", + } + } + /// The words it carries (search, the card). + pub fn words(&self) -> String { + match self { + NodeKind::Trigger { schedule } => schedule.as_ref().map(crate::routines::describe).unwrap_or_else(|| "手動".into()), + NodeKind::Step { prompt, .. } | NodeKind::Approve { prompt } => prompt.clone(), + NodeKind::Check { condition, .. } => condition.clone(), + NodeKind::Deliver { .. } => String::new(), + NodeKind::Notify { text } => text.clone(), + } + } +} + +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)] +pub struct Edge { + pub from: u64, + pub to: u64, +} + +/// Something drawn or written on the canvas. +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Default)] +pub struct Note { + pub id: u64, + pub kind: NoteKind, + /// The box it sits in (canvas points); a pen stroke's points are relative to x, y. + pub x: f32, + pub y: f32, + #[serde(default)] + pub w: f32, + #[serde(default)] + pub h: f32, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub text: String, + /// A colour name (avatar::COLORS, or "#rrggbb"); empty: the page's text colour. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub color: String, + /// Who put a sticky note there. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub author: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub points: Vec<[f32; 2]>, +} + +#[derive(Clone, Copy, Serialize, Deserialize, Debug, PartialEq, Eq, Default)] +#[serde(rename_all = "snake_case")] +pub enum NoteKind { + #[default] + Pen, + Sticky, + Shape, + Text, +} + +/// An earlier version: what the canvas held then. +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)] +pub struct Version { + pub at: i64, + pub name: String, + pub nodes: Vec, + pub edges: Vec, + pub notes: Vec, +} + +#[derive(Clone, Copy, Serialize, Deserialize, Debug, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum RunState { + Running, + /// Waits for the person (等你確認). + Waiting, + Done, + Failed, + Stopped, +} + +#[derive(Clone, Copy, Serialize, Deserialize, Debug, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum StepState { + Waiting, + Running, + Done, + Failed, +} + +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)] +pub struct Run { + pub id: u64, + pub started: i64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ended: Option, + pub state: RunState, + /// 定時 or 手動. + #[serde(default)] + pub by: String, + /// The nodes in the order they run (fixed when it started). + pub order: Vec, + /// Where it is in `order`. + pub at: usize, + pub steps: Vec, + /// Why it stopped or failed. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub why: String, +} + +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)] +pub struct RunStep { + pub node: u64, + pub state: StepState, + /// What it gave (handed on to the next step), in short. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub output: String, + /// The bot that worked on it, and when its question went into that chat (to find the + /// answer after it). + #[serde(default)] + pub bot: u64, + #[serde(default)] + pub asked_at: i64, +} + +impl Run { + /// The step running or waiting now. + pub fn current(&self) -> Option<&RunStep> { + self.order.get(self.at).and_then(|n| self.steps.iter().find(|s| s.node == *n)) + } + pub fn step_of(&self, node: u64) -> Option<&RunStep> { + self.steps.iter().find(|s| s.node == node) + } + pub fn live(&self) -> bool { + matches!(self.state, RunState::Running | RunState::Waiting) + } + /// The last result handed on (the latest step that gave one). + pub fn last_output(&self) -> String { + self.order.iter().take(self.at).rev().find_map(|n| self.step_of(*n).filter(|s| s.state == StepState::Done && !s.output.is_empty()).map(|s| s.output.clone())).unwrap_or_default() + } +} + +impl Workflow { + pub fn new(id: u64, name: &str, now: i64) -> Workflow { + Workflow { id, name: name.to_string(), nodes: vec![Node { id: 1, kind: NodeKind::Trigger { schedule: None }, x: 0.0, y: 0.0 }], created_at: now, updated_at: now, ..Default::default() } + } + pub fn trigger(&self) -> Option<&Node> { + self.nodes.iter().find(|n| matches!(n.kind, NodeKind::Trigger { .. })) + } + pub fn schedule(&self) -> Option<&crate::routines::Schedule> { + self.trigger().and_then(|n| if let NodeKind::Trigger { schedule } = &n.kind { schedule.as_ref() } else { None }) + } + pub fn node(&self, id: u64) -> Option<&Node> { + self.nodes.iter().find(|n| n.id == id) + } + pub fn node_mut(&mut self, id: u64) -> Option<&mut Node> { + 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). + 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 + } + /// 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. + pub fn order(&self) -> Vec { + let Some(t) = self.trigger() else { return vec![] }; + let mut out = vec![t.id]; + let mut i = 0; + while i < out.len() { + let from = out[i]; + let mut next: Vec<&Node> = self.edges.iter().filter(|e| e.from == from).filter_map(|e| self.node(e.to)).filter(|n| !out.contains(&n.id) && !matches!(n.kind, NodeKind::Trigger { .. })).collect(); + next.sort_by(|a, b| a.y.total_cmp(&b.y).then(a.x.total_cmp(&b.x))); + for n in next { + if !out.contains(&n.id) { + out.push(n.id); + } + } + i += 1; + } + out + } + /// How many steps a run takes (the trigger not counted). + pub fn step_count(&self) -> usize { + self.order().len().saturating_sub(1) + } + pub fn live_run(&self) -> Option<&Run> { + self.runs.iter().rev().find(|r| r.live()) + } + /// A line from `from` to `to`, unless it is there already, goes into the trigger, or would + /// close a circle. + pub fn connect(&mut self, from: u64, to: u64) -> bool { + if from == to || self.edges.iter().any(|e| e.from == from && e.to == to) || self.node(to).is_none_or(|n| matches!(n.kind, NodeKind::Trigger { .. })) || self.reaches(to, from) { + return false; + } + self.edges.push(Edge { from, to }); + true + } + fn reaches(&self, from: u64, to: u64) -> bool { + let mut seen = vec![from]; + let mut i = 0; + while i < seen.len() { + if seen[i] == to { + return true; + } + let at = seen[i]; + for e in self.edges.iter().filter(|e| e.from == at) { + if !seen.contains(&e.to) { + seen.push(e.to); + } + } + i += 1; + } + false + } + pub fn remove(&mut self, id: u64) { + // (The trigger stays: a workflow always starts somewhere.) + if self.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Trigger { .. })) { + return; + } + self.nodes.retain(|n| n.id != id); + self.edges.retain(|e| e.from != id && e.to != id); + self.notes.retain(|n| n.id != id); + } + /// What the canvas holds now, as a version. + pub fn snapshot(&self, at: i64) -> Version { + Version { at, name: self.name.clone(), nodes: self.nodes.clone(), edges: self.edges.clone(), notes: self.notes.clone() } + } + /// Keep what it holds now as a version, if it differs from the last one kept. + pub fn keep_version(&mut self, at: i64) -> bool { + let v = self.snapshot(at); + if self.versions.last().is_some_and(|l| l.nodes == v.nodes && l.edges == v.edges && l.notes == v.notes && l.name == v.name) { + return false; + } + self.versions.push(v); + if self.versions.len() > VERSIONS_KEPT { + self.versions.remove(0); + } + true + } + /// Back to an earlier version (what it held just before is kept as one first). + pub fn restore(&mut self, i: usize, now: i64) { + let Some(v) = self.versions.get(i).cloned() else { return }; + self.keep_version(now); + self.name = v.name; + self.nodes = v.nodes; + self.edges = v.edges; + self.notes = v.notes; + self.updated_at = now; + } + /// The same canvas under another name and id, without its runs or versions. + pub fn copy_as(&self, id: u64, now: i64) -> Workflow { + Workflow { id, name: format!("{} 的副本", self.name), nodes: self.nodes.clone(), edges: self.edges.clone(), notes: self.notes.clone(), created_at: now, updated_at: now, next_run: None, ..Default::default() } + } + /// Lay the steps out tidily: the trigger at the top, each step one row below the lowest of + /// the steps leading to it, side by side where one leads to several (left to right as they + /// were); what isn't connected goes in a column at the right. Notes stay where they are. + pub fn tidy(&mut self) { + let Some(t) = self.trigger().map(|n| n.id) else { return }; + let mut depth: std::collections::HashMap = [(t, 0)].into(); + // (No circles, so the longest way in settles within one pass per node.) + for _ in 0..self.nodes.len() { + let mut moved = false; + for e in &self.edges { + if let Some(d) = depth.get(&e.from).copied() { + if depth.get(&e.to).is_none_or(|x| *x < d + 1) { + depth.insert(e.to, d + 1); + moved = true; + } + } + } + if !moved { + break; + } + } + let rows = depth.values().copied().max().unwrap_or(0); + let mut placed: Vec<(u64, f32, f32)> = vec![]; + for row in 0..=rows { + let mut here: Vec<&Node> = self.nodes.iter().filter(|n| depth.get(&n.id) == Some(&row)).collect(); + here.sort_by(|a, b| a.x.total_cmp(&b.x).then(a.id.cmp(&b.id))); + let k = here.len() as f32; + for (i, n) in here.iter().enumerate() { + placed.push((n.id, (i as f32 - (k - 1.0) / 2.0) * COLUMN, row as f32 * ROW)); + } + } + let right = placed.iter().map(|p| p.1).fold(0.0_f32, f32::max) + COLUMN + 60.0; + let mut loose = 0.0; + for n in self.nodes.iter_mut() { + match placed.iter().find(|p| p.0 == n.id) { + Some(p) => (n.x, n.y) = (p.1, p.2), + None => { + (n.x, n.y) = (right, loose); + loose += ROW; + } + } + } + } + /// Laid out as `tidy` would (so a bot's change keeps it tidy; a canvas the person arranged + /// keeps their arrangement). + pub fn is_tidy(&self) -> bool { + let mut c = self.clone(); + c.tidy(); + c.nodes == self.nodes + } + /// The steps a node leads to. + pub fn next_of(&self, id: u64) -> Vec { + self.edges.iter().filter(|e| e.from == id).map(|e| e.to).collect() + } + /// The step at the end of the main line: the last in run order that leads nowhere. + pub fn end(&self) -> u64 { + let order = self.order(); + order.iter().rev().find(|n| self.next_of(**n).is_empty()).or(order.last()).copied().unwrap_or(1) + } + /// A new run, from the start (the trigger is done at once). + pub fn start_run(&mut self, by: &str, now: i64) -> u64 { + let order = self.order(); + let id = self.runs.iter().map(|r| r.id).max().unwrap_or(0) + 1; + let steps = order.iter().map(|n| RunStep { node: *n, state: StepState::Waiting, output: String::new(), bot: 0, asked_at: 0 }).collect(); + let mut run = Run { id, started: now, ended: None, state: RunState::Running, by: by.to_string(), order, at: 0, steps, why: String::new() }; + if let Some(s) = run.steps.first_mut() { + s.state = StepState::Done; + } + run.at = 1; + if run.order.len() <= 1 { + run.state = RunState::Done; + run.ended = Some(now); + run.why = "觸發器後面沒有連任何步驟".into(); + } + self.runs.push(run); + if self.runs.len() > RUNS_KEPT { + self.runs.remove(0); + } + id + } +} + +/// What a bot is asked in a step: which workflow and step, what to do, and the last result. +pub fn step_message(wf: &str, k: usize, of: usize, prompt: &str, last: &str) -> String { + let mut s = format!("[工作流「{wf}」第 {k}/{of} 步]{}", prompt.trim()); + if !last.trim().is_empty() { + s.push_str(&format!("\n\n上一步的結果:\n{}", clip(last.trim(), HANDED_ON_CHARS))); + } + s +} + +/// What a bot is asked in a 檢查 step. +pub fn check_message(wf: &str, k: usize, of: usize, condition: &str, last: &str) -> String { + format!( + "[工作流「{wf}」第 {k}/{of} 步・檢查]看下面這個結果有沒有做到:{}\n只回一行:做到了寫「通過」,沒做到寫「不通過:」加上原因。\n\n結果:\n{}", + condition.trim(), + if last.trim().is_empty() { "(上一步沒有結果)".to_string() } else { clip(last.trim(), HANDED_ON_CHARS) } + ) +} + +/// A 檢查's answer: passed, or why not. +pub fn check_passed(answer: &str) -> Result<(), String> { + let a = answer.trim().trim_start_matches(['「', '"', '*']).trim(); + if a.starts_with("不通過") || a.starts_with("未通過") { + let why = a.trim_start_matches("不通過").trim_start_matches("未通過").trim_start_matches([':', ':', ' ']).trim(); + return Err(if why.is_empty() { "檢查沒通過".into() } else { why.chars().take(300).collect() }); + } + if a.starts_with("通過") { + return Ok(()); + } + Err(format!("檢查的回答看不出有沒有通過:{}", a.chars().take(120).collect::())) +} + +/// A notification's words: 「{結果}」 becomes the last result's first line. +pub fn notify_text(text: &str, last: &str) -> String { + let first = last.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or(""); + let t = if text.trim().is_empty() { "{結果}" } else { text.trim() }; + t.replace("{結果}", &clip(first, 120)) +} + +fn clip(s: &str, max: usize) -> String { + if s.chars().count() <= max { + return s.to_string(); + } + let mut out: String = s.chars().take(max).collect(); + out.push('…'); + out +} + +/// The tool a bot makes, changes and runs workflows with (app/workflow_tool.rs runs it on the +/// brain; the canvas beside the chat shows each change). +pub const TOOL: &str = "workflow"; + +pub fn spec(schedule: Value) -> Value { + let step = json!({"type": "object", "properties": { + "kind": {"type": "string", "enum": ["step", "approve", "check", "deliver", "notify"], "description": "step: a bot does `prompt` (the last step's result goes with it); approve: the person says go on or stop (`prompt` is the question); check: a bot reads the last result against `condition` — not passing stops the run; deliver: the last result goes into `bot`'s chat; notify: a notification to the person, `text` (「{結果}」 is the last result's first line)."}, + "bot": {"type": "string", "description": "step, check, deliver: the bot's name; empty = you."}, + "prompt": {"type": "string"}, + "condition": {"type": "string"}, + "text": {"type": "string"}, + "after": {"type": "integer", "description": "edit: the step it comes after (1 = the trigger); it goes in between that step and the ones it led to. Empty: at the end (several new steps in one call follow each other)."}, + "branch": {"type": "boolean", "description": "edit: beside the steps `after` leads to (all of them run, the left one first) instead of in between."}}, + "required": ["kind"]}); + json!({"name": TOOL, + "description": "Make, change, look at and run the person's 工作流 (workflows): a canvas of cards joined by lines — a trigger (by hand, and on a schedule if it has one), then bot steps, 等你確認, 檢查, 交付 and 通知你; each step's result goes on to the next, and each bot step is a message in that bot's chat. Use it when the person wants a multi-step flow they can see and change — several steps or several bots, a confirmation or a check in between — or says 工作流, 流程. (One thing on a schedule by one bot is a routine: create_routine.) The person watches the canvas beside the chat change as you call this: create it with its steps, then change it in edits they can follow, and say in a sentence what you changed. Before changing one you didn't just make, `show` it: step ids come from there. Sticky notes (`notes`) are for people, never run: explain a step, leave a question.", + "parameters": {"type": "object", "properties": { + "action": {"type": "string", "enum": ["list", "show", "create", "edit", "run", "stop", "delete"], "description": "delete asks the person first."}, + "id": {"type": "integer", "description": "The workflow (from list). Empty: the one on the person's canvas, else the one changed last."}, + "name": {"type": "string", "description": "create: its name; edit: a new name."}, + "schedule": schedule, + "manual_only": {"type": "boolean", "description": "edit: take the schedule away (it runs only when started)."}, + "steps": {"type": "array", "items": step, "description": "create: the steps, one after the other from the trigger. edit: steps to add."}, + "change": {"type": "array", "description": "edit: steps to change (only the fields given).", "items": {"type": "object", "properties": { + "step": {"type": "integer"}, "bot": {"type": "string"}, "prompt": {"type": "string"}, "condition": {"type": "string"}, "text": {"type": "string"}}, "required": ["step"]}}, + "remove": {"type": "array", "items": {"type": "integer"}, "description": "edit: steps or notes to take away; the lines before and after a removed step join up."}, + "connect": {"type": "array", "items": {"type": "array", "items": {"type": "integer"}}, "description": "edit: lines to add, each [from, to]."}, + "disconnect": {"type": "array", "items": {"type": "array", "items": {"type": "integer"}}, "description": "edit: lines to take away, each [from, to]."}, + "notes": {"type": "array", "description": "create, edit: sticky notes to put on the canvas.", "items": {"type": "object", "properties": { + "text": {"type": "string"}, "near": {"type": "integer", "description": "The step it sits beside."}, "color": {"type": "string", "enum": STICKY_NAMES}}, "required": ["text"]}}, + "tidy": {"type": "boolean", "description": "edit: lay the steps out again in a tidy column (when the person asks to tidy it up)."}}, + "required": ["action"]}}) +} + +/// Who is asking, and the bots a step can name. +pub struct Who<'a> { + pub me: u64, + pub bots: &'a [(u64, String)], + pub timezone: &'a str, +} + +impl Who<'_> { + fn name(&self, id: u64) -> String { + self.bots.iter().find(|b| b.0 == id).map(|b| b.1.clone()).unwrap_or_else(|| "已刪除的 Bot".into()) + } + fn bot(&self, name: Option<&str>) -> Result { + let n = name.unwrap_or("").trim(); + if n.is_empty() { + return Ok(self.me); + } + self.bots.iter().find(|b| b.1.trim().eq_ignore_ascii_case(n)).map(|b| b.0).ok_or_else(|| format!("沒有叫「{n}」的 Bot:有 {}", self.bots.iter().map(|b| format!("「{}」", b.1)).collect::>().join("、"))) + } +} + +/// What a call did. +#[derive(Debug, Default, PartialEq)] +pub struct Told { + pub text: String, + /// The workflow it was about (the canvas shows it). + pub wf: Option, + /// Steps and notes added or changed (lit up on the canvas for a moment). + pub touched: Vec, + /// Its steps, lines, notes or name changed. + pub changed: bool, + /// The window starts or stops its run. + pub run: bool, + pub stop: bool, +} + +/// The `workflow` tool on the workflows. `showing`: the workflow on the person's canvas. +pub fn tool(wfs: &mut Vec, who: &Who, v: &Value, showing: Option, now: i64) -> Result { + let action = v["action"].as_str().unwrap_or("").trim().to_lowercase(); + if action == "list" { + if wfs.is_empty() { + return Ok(Told { text: "還沒有工作流。".into(), ..Default::default() }); + } + return Ok(Told { text: wfs.iter().map(|w| list_line(w, who.timezone)).collect::>().join("\n"), ..Default::default() }); + } + if action == "create" { + let id = wfs.iter().map(|w| w.id).max().unwrap_or(0) + 1; + let name = v["name"].as_str().map(str::trim).filter(|n| !n.is_empty()).unwrap_or("未命名工作流"); + let mut w = Workflow::new(id, name, now); + let mut touched = vec![1]; + if let Some(s) = v.get("schedule").filter(|s| !s.is_null()) { + set_schedule(&mut w, s, who.timezone)?; + } + add_steps(&mut w, who, v, &mut touched)?; + w.tidy(); + add_notes(&mut w, who, v, &mut touched)?; + w.keep_version(now); + let text = format!("已建立工作流 #{id}「{name}」(使用者的畫布上看得到)。\n{}", describe(&w, who)); + wfs.push(w); + return Ok(Told { text, wf: Some(id), touched, changed: true, ..Default::default() }); + } + // 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 Some(i) = id.and_then(|id| wfs.iter().position(|w| w.id == id)) else { + return Err(match v["id"].as_u64() { + Some(n) => format!("沒有工作流 #{n}(list 看有哪些)"), + None => "還沒有工作流:用 create 做一個".into(), + }); + }; + let w = &mut wfs[i]; + let id = w.id; + match action.as_str() { + "show" => Ok(Told { text: describe(w, who), wf: Some(id), ..Default::default() }), + "run" => { + if let Some(r) = w.live_run() { + return Err(format!("「{}」已經在跑了(第 {}/{} 步):等它跑完,或先 stop", w.name, r.at, r.order.len().saturating_sub(1))); + } + if w.step_count() == 0 { + return Err(format!("「{}」的觸發器後面還沒有連任何步驟", w.name)); + } + Ok(Told { text: String::new(), wf: Some(id), run: true, ..Default::default() }) + } + "stop" => { + if w.live_run().is_none() { + return Err(format!("「{}」現在沒有在跑", w.name)); + } + Ok(Told { text: format!("已停止「{}」這次的執行。", w.name), wf: Some(id), stop: true, ..Default::default() }) + } + "delete" => { + let name = w.name.clone(); + wfs.remove(i); + Ok(Told { text: format!("已刪除工作流「{name}」。"), wf: Some(id), changed: true, ..Default::default() }) + } + "edit" => { + let before = w.clone(); + let tidy = w.is_tidy() || v["tidy"].as_bool() == Some(true); + w.keep_version(now); + let mut touched = vec![]; + let mut said = vec![]; + if let Some(n) = v["name"].as_str().map(str::trim).filter(|n| !n.is_empty()) { + w.name = n.to_string(); + said.push(format!("名稱改成「{n}」")); + } + if let Some(s) = v.get("schedule").filter(|s| !s.is_null()) { + set_schedule(w, s, who.timezone)?; + touched.push(w.trigger().map(|t| t.id).unwrap_or(1)); + said.push(format!("觸發改成{}", w.schedule().map(crate::routines::describe).unwrap_or_default())); + } else if v["manual_only"].as_bool() == Some(true) { + 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 = None; + } + w.next_run = None; + said.push("拿掉排程(只在按的時候跑)".into()); + } + for r in v["remove"].as_array().into_iter().flatten().filter_map(Value::as_u64) { + if w.node(r).is_some_and(|n| matches!(n.kind, NodeKind::Trigger { .. })) { + *w = before; + return Err("觸發器不能刪:每個工作流都從它開始".into()); + } + if w.node(r).is_some() { + // (What came before and after join up.) + let ins: Vec = w.edges.iter().filter(|e| e.to == r).map(|e| e.from).collect(); + let outs = w.next_of(r); + w.remove(r); + for a in &ins { + for b in &outs { + w.connect(*a, *b); + } + } + said.push(format!("刪掉 #{r}")); + } else if w.notes.iter().any(|n| n.id == r) { + w.remove(r); + said.push(format!("刪掉便利貼 #{r}")); + } else { + *w = before; + return Err(format!("沒有 #{r} 這一步(show 看有哪些)")); + } + } + for pair in v["disconnect"].as_array().into_iter().flatten() { + let (a, b) = (pair[0].as_u64().unwrap_or(0), pair[1].as_u64().unwrap_or(0)); + let n = w.edges.len(); + w.edges.retain(|e| !(e.from == a && e.to == b)); + if w.edges.len() == n { + *w = before; + return Err(format!("#{a} 和 #{b} 之間沒有線")); + } + said.push(format!("拿掉 #{a}→#{b} 的線")); + } + for c in v["change"].as_array().into_iter().flatten() { + let sid = c["step"].as_u64().unwrap_or(0); + let bot = match c["bot"].as_str() { + Some(b) => Some(who.bot(Some(b)).inspect_err(|_| *w = before.clone())?), + None => None, + }; + let txt = |k: &str| c[k].as_str().map(str::to_string); + let Some(n) = w.node_mut(sid) else { + *w = before; + return Err(format!("沒有 #{sid} 這一步(show 看有哪些)")); + }; + match &mut n.kind { + NodeKind::Step { bot: b, prompt } => { + if let Some(x) = bot { + *b = x; + } + if let Some(t) = txt("prompt") { + *prompt = t; + } + } + NodeKind::Check { bot: b, condition } => { + if let Some(x) = bot { + *b = x; + } + if let Some(t) = txt("condition").or_else(|| txt("prompt")) { + *condition = t; + } + } + NodeKind::Deliver { bot: b } => { + if let Some(x) = bot { + *b = x; + } + } + NodeKind::Approve { prompt } => { + if let Some(t) = txt("prompt").or_else(|| txt("text")) { + *prompt = t; + } + } + NodeKind::Notify { text } => { + if let Some(t) = txt("text").or_else(|| txt("prompt")) { + *text = t; + } + } + NodeKind::Trigger { .. } => { + *w = before; + return Err("觸發器用 schedule 或 manual_only 改".into()); + } + } + touched.push(sid); + said.push(format!("改了 #{sid}")); + } + let added_from = touched.len(); + if let Err(e) = add_steps(w, who, v, &mut touched) { + *w = before; + return Err(e); + } + if touched.len() > added_from { + said.push(format!("新增 {}", touched[added_from..].iter().map(|n| format!("#{n}")).collect::>().join("、"))); + } + for pair in v["connect"].as_array().into_iter().flatten() { + let (a, b) = (pair[0].as_u64().unwrap_or(0), pair[1].as_u64().unwrap_or(0)); + if w.node(a).is_none() || w.node(b).is_none() { + *w = before; + return Err(format!("沒有 #{} 這一步(show 看有哪些)", if w.node(a).is_none() { a } else { b })); + } + if !w.connect(a, b) { + *w = before; + return Err(format!("#{a}→#{b} 連不起來:已經有了、連回觸發器,或會繞成一圈")); + } + said.push(format!("連起 #{a}→#{b}")); + } + if tidy { + w.tidy(); + } + let notes_from = touched.len(); + if let Err(e) = add_notes(w, who, v, &mut touched) { + *w = before; + return Err(e); + } + if touched.len() > notes_from { + said.push(format!("加了 {} 張便利貼", touched.len() - notes_from)); + } + if said.is_empty() { + *w = before; + return Err("沒有要改的:給 name、schedule、manual_only、steps、change、remove、connect、disconnect、notes 或 tidy".into()); + } + w.updated_at = now; + let mut text = format!("已修改工作流 #{id}「{}」:{}。", w.name, said.join(";")); + if w.live_run().is_some() { + text.push_str("(正在跑的那次照開始時的步驟走;刪掉的步驟輪到時會停下來。)"); + } + text.push('\n'); + text.push_str(&describe(w, who)); + Ok(Told { text, wf: Some(id), touched, changed: true, ..Default::default() }) + } + "" => Err("缺少 action:list、show、create、edit、run、stop 或 delete".into()), + other => Err(format!("不認得的 action「{other}」:list、show、create、edit、run、stop 或 delete")), + } +} + +/// The workflow in words: its trigger, each step with its id and where it leads, the notes, the +/// last run. +pub fn describe(w: &Workflow, who: &Who) -> String { + let mut out = vec![format!("工作流 #{}「{}」:{}", w.id, w.name, w.schedule().map(|s| format!("{},也可以手動", crate::routines::describe(s))).unwrap_or_else(|| "手動執行".into()))]; + let order = w.order(); + let line = |n: &Node| { + let what = match &n.kind { + NodeKind::Trigger { .. } => "觸發器".to_string(), + NodeKind::Step { bot, prompt } => format!("Bot 步驟({}):{}", who.name(*bot), one_line(prompt)), + NodeKind::Approve { prompt } => format!("等你確認:{}", one_line(prompt)), + NodeKind::Check { bot, condition } => format!("檢查({}):{}", who.name(*bot), one_line(condition)), + NodeKind::Deliver { bot } => format!("交付到「{}」的聊天", who.name(*bot)), + NodeKind::Notify { text } => format!("通知你:{}", one_line(text)), + }; + let next = w.next_of(n.id); + if next.is_empty() { format!("#{} {what}", n.id) } else { format!("#{} {what} → {}", n.id, next.iter().map(|x| format!("#{x}")).collect::>().join("、")) } + }; + for id in &order { + if let Some(n) = w.node(*id) { + out.push(line(n)); + } + } + let loose: Vec = w.nodes.iter().filter(|n| !order.contains(&n.id)).map(line).collect(); + if !loose.is_empty() { + out.push(format!("沒接上觸發器的(不會執行):{}", loose.join(";"))); + } + let notes: Vec = w + .notes + .iter() + .filter(|n| matches!(n.kind, NoteKind::Sticky | NoteKind::Text) && !n.text.trim().is_empty()) + .map(|n| format!("#{}「{}」{}", n.id, one_line(&n.text), if n.author.is_empty() { String::new() } else { format!("({})", n.author) })) + .collect(); + if !notes.is_empty() { + out.push(format!("便利貼:{}", notes.join("、"))); + } + let drawn = w.notes.iter().filter(|n| matches!(n.kind, NoteKind::Pen | NoteKind::Shape)).count(); + if drawn > 0 { + out.push(format!("另外有 {drawn} 個手畫的線條或形狀")); + } + if let Some(r) = w.runs.last() { + out.push(format!("最近一次執行:{}", run_words(r))); + } + out.join("\n") +} + +fn list_line(w: &Workflow, tz: &str) -> String { + let when = w.schedule().map(crate::routines::describe).unwrap_or_else(|| "手動".into()); + let next = w.next_run.map(|t| format!("(下次 {})", crate::routines::describe_when(t, tz))).unwrap_or_default(); + let last = w.runs.last().map(|r| format!(" · 最近一次:{}", run_words(r))).unwrap_or_default(); + format!("#{}「{}」 {} 個步驟 · {when}{next}{last}", w.id, w.name, w.step_count()) +} + +/// How a run stands, in words. +pub fn describe_run(r: &Run) -> String { + run_words(r) +} + +fn run_words(r: &Run) -> String { + let of = r.order.len().saturating_sub(1); + match r.state { + RunState::Running => format!("執行中(第 {}/{of} 步)", r.at.min(of)), + RunState::Waiting => format!("等你確認(第 {}/{of} 步)", r.at.min(of)), + RunState::Done => "完成".into(), + RunState::Failed => format!("失敗:{}", r.why), + RunState::Stopped => format!("停止了:{}", r.why), + } +} + +fn one_line(s: &str) -> String { + clip(&s.split_whitespace().collect::>().join(" "), 80) +} + +fn set_schedule(w: &mut Workflow, raw: &Value, tz: &str) -> Result<(), String> { + let mut raw = raw.clone(); + if raw.get("timezone").and_then(Value::as_str).unwrap_or("").is_empty() { + raw["timezone"] = json!(tz); + } + let s = serde_json::from_value::(raw).map_err(|e| e.to_string()).and_then(crate::routines::validate).map_err(|e| format!("排程有問題:{e}"))?; + 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); + } + w.next_run = None; + Ok(()) +} + +/// The `steps` of a call, each after the one named or at the end. +fn add_steps(w: &mut Workflow, who: &Who, v: &Value, touched: &mut Vec) -> Result<(), String> { + for st in v["steps"].as_array().into_iter().flatten() { + let txt = |k: &str| st[k].as_str().map(str::trim).unwrap_or("").to_string(); + let kind = match st["kind"].as_str().unwrap_or("step").trim() { + "step" | "" => { + let prompt = txt("prompt"); + if prompt.is_empty() { + return Err("Bot 步驟要有 prompt(要它做什麼)".into()); + } + NodeKind::Step { bot: who.bot(st["bot"].as_str())?, prompt } + } + "approve" => NodeKind::Approve { prompt: Some(txt("prompt")).filter(|p| !p.is_empty()).unwrap_or_else(|| "要繼續嗎?".into()) }, + "check" => { + let condition = Some(txt("condition")).filter(|c| !c.is_empty()).unwrap_or_else(|| txt("prompt")); + if condition.is_empty() { + return Err("檢查要有 condition(要做到什麼才算通過)".into()); + } + NodeKind::Check { bot: who.bot(st["bot"].as_str())?, condition } + } + "deliver" => NodeKind::Deliver { bot: who.bot(st["bot"].as_str())? }, + "notify" => NodeKind::Notify { text: Some(txt("text")).filter(|t| !t.is_empty()).unwrap_or_else(|| "{結果}".into()) }, + other => return Err(format!("不認得的步驟種類「{other}」:step、approve、check、deliver 或 notify")), + }; + let after = match st["after"].as_u64() { + Some(a) if w.node(a).is_some() => a, + Some(a) => return Err(format!("沒有 #{a} 這一步(show 看有哪些)")), + None => w.end(), + }; + let id = w.next_id(); + let branch = st["branch"].as_bool() == Some(true); + let outs = w.next_of(after); + let (ax, ay) = w.node(after).map(|n| (n.x, n.y)).unwrap_or((0.0, 0.0)); + let x = if branch { outs.iter().filter_map(|o| w.node(*o)).map(|n| n.x).fold(ax, f32::max) + if outs.is_empty() { 0.0 } else { COLUMN } } else { ax }; + if !branch { + // In between: what `after` led to comes after the new step, one row further down. + let below: Vec = w.nodes.iter().filter(|n| n.id != after && w.reaches(after, n.id)).map(|n| n.id).collect(); + for n in w.nodes.iter_mut().filter(|n| below.contains(&n.id)) { + n.y += ROW; + } + w.edges.retain(|e| e.from != after); + } + w.nodes.push(Node { id, kind, x, y: ay + ROW }); + w.edges.push(Edge { from: after, to: id }); + if !branch { + for o in outs { + w.connect(id, o); + } + } + touched.push(id); + } + Ok(()) +} + +/// The `notes` of a call: a sticky note beside the step it is about (left of it), or at the +/// right of everything. +fn add_notes(w: &mut Workflow, who: &Who, v: &Value, touched: &mut Vec) -> Result<(), String> { + for n in v["notes"].as_array().into_iter().flatten() { + let text = n["text"].as_str().map(str::trim).unwrap_or(""); + if text.is_empty() { + return Err("便利貼要有 text".into()); + } + let color = n["color"].as_str().and_then(|c| STICKY_NAMES.iter().position(|x| x.eq_ignore_ascii_case(c.trim()))).map(|i| STICKY_COLOURS[i]).unwrap_or(STICKY_COLOURS[1]); + let (x, mut y) = match n["near"].as_u64() { + Some(s) => match w.node(s) { + Some(card) => (card.x - STICKY_W - 40.0, card.y), + None => return Err(format!("沒有 #{s} 這一步(便利貼要貼在哪一步旁邊)")), + }, + None => (w.nodes.iter().map(|c| c.x).fold(0.0_f32, f32::max) + CARD_W + 60.0, w.nodes.iter().map(|c| c.y).fold(f32::INFINITY, f32::min).min(0.0)), + }; + // (Not on top of another note.) + while w.notes.iter().any(|o| (o.x - x).abs() < STICKY_W * 0.5 && (o.y - y).abs() < STICKY_H * 0.5) { + y += STICKY_H + 16.0; + } + let id = w.next_id(); + w.notes.push(Note { id, kind: NoteKind::Sticky, x, y, w: STICKY_W, h: STICKY_H, text: text.to_string(), color: color.into(), author: who.name(who.me), points: vec![] }); + touched.push(id); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn call(wfs: &mut Vec, v: Value) -> Result { + let bots = vec![(1, "研究助理".to_string()), (2, "寫作夥伴".to_string())]; + let who = Who { me: 1, bots: &bots, timezone: "Asia/Taipei" }; + tool(wfs, &who, &v, None, 1_000) + } + + /// 聊出來的工作流: create lays the steps out in a tidy column from the trigger, names the + /// bots, puts a sticky note beside the step it is about; show says it all with the ids. + #[test] + fn a_bot_makes_a_workflow_from_the_chat() { + let mut wfs = vec![]; + let t = call( + &mut wfs, + json!({"action": "create", "name": "Threads 早報", "schedule": {"frequency": "daily", "time": "09:00"}, + "steps": [{"kind": "step", "prompt": "找 5 則熱門育兒討論"}, {"kind": "check", "bot": "寫作夥伴", "condition": "每則都有連結"}, {"kind": "approve", "prompt": "要傳給你嗎?"}, {"kind": "notify", "text": "早報好了:{結果}"}], + "notes": [{"text": "週末改十點?", "near": 2}]}), + ) + .unwrap(); + let w = &wfs[0]; + assert_eq!((t.wf, t.changed, w.order()), (Some(1), true, vec![1, 2, 3, 4, 5])); + assert_eq!(w.nodes.iter().map(|n| (n.x, n.y)).collect::>(), (0..5).map(|i| (0.0, i as f32 * ROW)).collect::>(), "one under the other"); + assert!(matches!(&w.nodes[2].kind, NodeKind::Check { bot: 2, .. }), "named bot"); + assert!(matches!(&w.nodes[1].kind, NodeKind::Step { bot: 1, .. }), "no name: the bot asking"); + let note = &w.notes[0]; + assert_eq!((note.kind, note.x < w.nodes[1].x, note.y, note.author.as_str()), (NoteKind::Sticky, true, w.nodes[1].y, "研究助理")); + assert!(w.schedule().is_some() && t.touched.contains(¬e.id)); + for words in ["工作流 #1「Threads 早報」:每天 09:00", "#2 Bot 步驟(研究助理):找 5 則熱門育兒討論 → #3", "#3 檢查(寫作夥伴):每則都有連結 → #4", "#5 通知你:早報好了:{結果}", "便利貼:#6「週末改十點?」(研究助理)"] + { + assert!(t.text.contains(words), "{words}\n{}", t.text); + } + assert_eq!(call(&mut wfs, json!({"action": "show"})).unwrap().text, describe(&wfs[0], &Who { me: 1, bots: &[(1, "研究助理".into()), (2, "寫作夥伴".into())], timezone: "" })); + assert!(call(&mut wfs, json!({"action": "list"})).unwrap().text.starts_with("#1「Threads 早報」 4 個步驟 · 每天 09:00")); + } + + /// Edits the person can follow: a step in between pushes the rest down; a branch goes + /// beside; a removed step's lines join up; nothing half done when one part is wrong. + #[test] + fn a_bot_changes_a_workflow_step_by_step() { + let mut wfs = vec![]; + call(&mut wfs, json!({"action": "create", "name": "早報", "steps": [{"prompt": "查新聞"}, {"kind": "deliver"}]})).unwrap(); + // In between 2 and 3. + let t = call(&mut wfs, json!({"action": "edit", "steps": [{"kind": "check", "condition": "至少三則", "after": 2}]})).unwrap(); + assert_eq!((wfs[0].order(), t.touched.clone()), (vec![1, 2, 4, 3], vec![4])); + assert!(wfs[0].is_tidy(), "still tidy: {:?}", wfs[0].nodes); + assert!(t.text.starts_with("已修改工作流 #1「早報」:新增 #4。"), "{}", t.text); + // A branch beside what 4 leads to: both run. + call(&mut wfs, json!({"action": "edit", "steps": [{"kind": "notify", "after": 4, "branch": true}]})).unwrap(); + assert_eq!(wfs[0].next_of(4).len(), 2); + let (a, b) = (wfs[0].node(3).unwrap(), wfs[0].node(5).unwrap()); + assert_eq!(a.y, b.y, "side by side"); + // Removing 4: 2 leads to 3 and 5 again. + call(&mut wfs, json!({"action": "edit", "remove": [4]})).unwrap(); + let mut next = wfs[0].next_of(2); + next.sort(); + assert_eq!(next, vec![3, 5]); + // Change, rename, take the schedule away. + call(&mut wfs, json!({"action": "edit", "name": "晚報", "change": [{"step": 2, "prompt": "查晚間新聞", "bot": "寫作夥伴"}], "manual_only": true})).unwrap(); + assert!(matches!(&wfs[0].node(2).unwrap().kind, NodeKind::Step { bot: 2, prompt } if prompt == "查晚間新聞")); + assert_eq!(wfs[0].name, "晚報"); + // One wrong part: nothing of the call is kept. + let before = wfs[0].clone(); + for bad in [ + json!({"action": "edit", "name": "X", "remove": [99]}), + json!({"action": "edit", "name": "X", "remove": [1]}), + json!({"action": "edit", "name": "X", "connect": [[3, 2]]}), + json!({"action": "edit", "steps": [{"kind": "step", "prompt": "x", "bot": "沒這個"}], "name": "X"}), + json!({"action": "edit"}), + ] { + assert!(call(&mut wfs, bad.clone()).is_err(), "{bad}"); + assert_eq!(wfs[0].nodes, before.nodes, "{bad}"); + assert_eq!((wfs[0].name.as_str(), wfs[0].edges.len()), ("晚報", before.edges.len()), "{bad}"); + } + // Moved by the person: a bot's step goes below its step without tidying theirs. + wfs[0].node_mut(3).unwrap().x = 700.0; + call(&mut wfs, json!({"action": "edit", "steps": [{"kind": "notify", "after": 3}]})).unwrap(); + let n = wfs[0].nodes.last().unwrap(); + assert_eq!((n.x, wfs[0].node(3).unwrap().x), (700.0, 700.0)); + // Each edit kept the one before as a version. + assert!(wfs[0].versions.len() >= 4); + } + + /// run and stop are for the window (they need a bot to work); run says why not. + #[test] + fn run_and_stop_are_asked_of_the_window() { + let mut wfs = vec![]; + call(&mut wfs, json!({"action": "create", "name": "空的"})).unwrap(); + assert!(call(&mut wfs, json!({"action": "run"})).unwrap_err().contains("還沒有連任何步驟")); + call(&mut wfs, json!({"action": "edit", "steps": [{"prompt": "做事"}]})).unwrap(); + assert!(call(&mut wfs, json!({"action": "run"})).unwrap().run); + assert!(call(&mut wfs, json!({"action": "stop"})).unwrap_err().contains("沒有在跑")); + wfs[0].start_run("手動", 5); + assert!(call(&mut wfs, json!({"action": "run"})).unwrap_err().contains("已經在跑了")); + assert!(call(&mut wfs, json!({"action": "stop"})).unwrap().stop); + assert!(call(&mut wfs, json!({"action": "show", "id": 9})).unwrap_err().contains("沒有工作流 #9")); + assert!(call(&mut wfs, json!({"action": "delete"})).unwrap().changed && wfs.is_empty()); + } + + fn wf() -> Workflow { + let mut w = Workflow::new(1, "早報", 100); + for (id, x, y, kind) in [ + (2, 0.0, 200.0, NodeKind::Step { bot: 1, prompt: "查今天的新聞".into() }), + (3, 0.0, 400.0, NodeKind::Check { bot: 1, condition: "至少三則".into() }), + (4, 300.0, 600.0, NodeKind::Notify { text: "早報好了:{結果}".into() }), + (5, 0.0, 600.0, NodeKind::Deliver { bot: 1 }), + (6, 900.0, 900.0, NodeKind::Approve { prompt: "沒連上".into() }), + ] { + w.nodes.push(Node { id, kind, x, y }); + } + assert!(w.connect(1, 2) && w.connect(2, 3) && w.connect(3, 4) && w.connect(3, 5)); + w + } + + /// A run goes from the trigger along the lines, the one higher up (then left) first where + /// a step leads to two; what isn't connected doesn't run. + #[test] + fn a_run_follows_the_lines_from_the_trigger() { + let w = wf(); + assert_eq!(w.order(), vec![1, 2, 3, 5, 4]); + assert_eq!(w.step_count(), 4); + } + + /// No line into the trigger, none twice, none closing a circle; removing a step takes its + /// lines; the trigger stays. + #[test] + fn lines_never_make_a_circle() { + let mut w = wf(); + assert!(!w.connect(2, 1), "into the trigger"); + assert!(!w.connect(1, 2), "twice"); + assert!(!w.connect(4, 2), "a circle"); + assert!(!w.connect(3, 3)); + w.remove(3); + assert_eq!((w.order(), w.edges.len()), (vec![1, 2], 1)); + w.remove(1); + assert!(w.trigger().is_some()); + } + + /// A run starts past the trigger; the last result is the newest step that gave one. + #[test] + fn a_run_hands_the_last_result_on() { + let mut w = wf(); + let id = w.start_run("手動", 200); + let r = w.runs.iter_mut().find(|r| r.id == id).unwrap(); + assert_eq!((r.at, r.state, r.current().map(|s| s.node)), (1, RunState::Running, Some(2))); + r.steps[1].state = StepState::Done; + r.steps[1].output = "三則新聞".into(); + r.at = 2; + assert_eq!(r.last_output(), "三則新聞"); + // Nothing after the trigger: done at once, and said why. + let mut lone = Workflow::new(2, "空的", 100); + let id = lone.start_run("手動", 200); + assert_eq!(lone.runs.iter().find(|r| r.id == id).map(|r| (r.state, r.why.as_str())), Some((RunState::Done, "觸發器後面沒有連任何步驟"))); + } + + #[test] + fn what_a_step_says_and_how_a_check_reads() { + let m = step_message("早報", 1, 3, "整理成三點", "新聞 A\n新聞 B"); + assert!(m.starts_with("[工作流「早報」第 1/3 步]整理成三點") && m.ends_with("上一步的結果:\n新聞 A\n新聞 B"), "{m}"); + assert!(!step_message("早報", 1, 3, "查", "").contains("上一步")); + assert_eq!(check_passed("通過"), Ok(())); + assert_eq!(check_passed("「通過」,三則都有"), Ok(())); + assert_eq!(check_passed("不通過:只有兩則"), Err("只有兩則".into())); + assert!(check_passed("好像可以").is_err()); + assert_eq!(notify_text("早報好了:{結果}", "\n三則新聞\n第二行"), "早報好了:三則新聞"); + assert_eq!(notify_text("", "結果在這"), "結果在這"); + } + + /// 版本歷史: a version only when something changed; restoring keeps what was there first; + /// at most VERSIONS_KEPT. A copy has no runs or versions. + #[test] + fn versions_are_kept_and_restored() { + let mut w = wf(); + assert!(w.keep_version(1)); + assert!(!w.keep_version(2), "nothing changed"); + w.name = "晚報".into(); + w.remove(4); + assert!(w.keep_version(3)); + w.restore(0, 4); + assert_eq!((w.name.as_str(), w.node(4).is_some(), w.versions.len()), ("早報", true, 2), "the one before restoring was kept already"); + for i in 0..40 { + w.name = format!("v{i}"); + w.keep_version(10 + i); + } + assert_eq!(w.versions.len(), VERSIONS_KEPT); + w.start_run("手動", 5); + let c = w.copy_as(9, 6); + assert!(c.runs.is_empty() && c.versions.is_empty() && c.name.ends_with("的副本") && c.nodes == w.nodes); + } +}