工作流多了 OpenBot 那些節點和觸發器:觸發器可以是手動、定時、Webhook、GitHub(和例行任務的事件觸發同一套);新增節點可以搜尋、分三組——輸入:提示詞、素材;步驟:LLM、助手、圖片、影片;流程:條件(是/否兩條路)、審批、輸出。重複的併掉:檢查就是條件,交付和通知你併成一個輸出。
- 觸發器:event(triggers::Trigger)跟排程二選一。Webhook 給呼叫網址(/hooks/<1000000+工作流 id>)和密碼、可複製、換一組;GitHub 給存放庫、事件(PR 合併、CI 失敗…)、Token;其他事件(Slack、新信、行事曆…)用 workflow 工具的 trigger 設,格式跟 create_routine 一樣。監看共用 channels_ui 的 triggers_poll(Watch 的 bot 0、id 1000000+工作流 id);發生了什麼放進那次執行的 input,交給第一步。 - 節點:提示詞(一段話當成上一步的結果)、素材(檔案,下一個 Bot 步驟收到附件;從聊天裡的檔案挑,大腦這台也可以選檔案)、LLM(直接呼叫模型,不用 Bot、不用工具,可選「供應商:模型」和系統提示詞,在背景執行緒跑,回來時下一次 tick 接著走)、助手(原本的 Bot 步驟)、圖片/影片(請 Bot 用自己的工具做出檔案、send_file 交出來)、條件(原本的檢查:是/否兩個點各拉線,邊帶 port;不成立而「否」沒接就停下說原因;沒走的那條路標成「沒走這條路」)、審批(原本的等你確認)、輸出(放進哪個聊天、要不要通知;舊的交付和通知你照樣跑、在右邊改時變成輸出)。 - 選到的卡片上面有「複製」「刪除」;助手、LLM、圖片、影片、條件有「試跑這一步」(只跑這一步,用前一步上次的結果,螢幕電腦也是交給大腦跑)。 - workflow 工具:kind 多了 prompt、material、llm、image、video、condition、output(deliver、notify、check、step 照舊收),trigger、files、model、system、notify、port(after 一個條件時走是或否)、connect 可以帶第三個值 yes/no;show 寫出「是:#5;否:#6」。 - 示範資料多一個工作流(ANYBOT_SHOT_TAB=2);功能地圖 workflow 補新的節點、觸發器和一步驗證,FEATURES 同步。 已驗證: cargo test 865 過(新:a_bot_builds_branches_and_the_new_kinds——工具建出提示詞、LLM、條件、圖片、輸出、Webhook 觸發,是/否 的邊和跳過的步驟,錯的觸發整次不留,舊名字變輸出;a_run_goes_through_the_new_kinds——事件的內容進第一步、提示詞交出去、素材變成附件、條件成立時跳過「否」那條、連不到的模型讓 LLM 那步失敗並說原因);clippy 沒有新的。截圖:新工作流的卡片(GitHub 觸發、提示詞、LLM、條件的是/否、圖片、審批、輸出)、可搜尋分三組的新增節點、觸發器右邊的 GitHub 設定、條件右邊的設定和卡片上的複製/刪除。 未驗證: 真的 GitHub/Webhook 觸發一次(要 token 和真的事件)、真的模型回答 LLM 步驟、Bot 真的做出圖片或影片(scratch 只有假模型);workflow.md 前五步這次沒重跑(指令沒變,只改了看到的名稱)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha2uBHmbnuWBhNzjbJm
This commit is contained in:
parent
6f67439164
commit
f72c164d34
|
|
@ -1937,7 +1937,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
|
|||
|
||||
照 OpenBot 工作流畫布的排版做的(它公開的程式裡沒有畫布,照截圖的樣子做),風格是 AnyBot 自己的;功能地圖 workflow.md。
|
||||
|
||||
- 一個工作流是一張畫布:觸發器(手動,或也照排程:每天、每週…,寫下次執行,有「立即執行」),接著用線連起來的卡片:Bot 步驟(哪個 Bot、要它做什麼)、等你確認、檢查(哪個 Bot、要做到什麼才通過)、交付(結果放進哪個 Bot 的聊天)、通知你(「{結果}」換成上一步結果的第一行)。從卡片底下的點拉到另一張就連線;不能連回觸發器、不能繞圈。
|
||||
- 一個工作流是一張畫布:觸發器(手動、定時、Webhook、GitHub;Slack、新信等在聊天裡請 Bot 設,跟例行任務的事件觸發同一套,發生了什麼交給第一步),接著用線連起來的卡片。「+ 新增節點」可以搜尋,分三組:輸入(提示詞、素材)、步驟(LLM:直接問模型;助手:Bot 做;圖片、影片:請 Bot 做檔案)、流程(條件:是/否兩條路;審批;輸出:放進聊天和/或通知你)。原本的「檢查」就是條件,「交付」「通知你」併成一個輸出。選到的卡片上面有複製、刪除;助手、LLM、圖片、影片、條件有「試跑這一步」。從卡片底下的點拉到另一張就連線;不能連回觸發器、不能繞圈。
|
||||
- 畫布:左上名稱和選單(每個工作流和步驟數、新建、版本歷史、重新命名、建立副本、刪除);右上「聊天」「執行紀錄」「▷ 執行工作流/■ 停止」;拖曳空白處移動、⌘+滾輪或捏合縮放;下面工具列「選取、拖曳|畫筆、便利貼、形狀、文字|搜尋|+ 新增節點」;左下縮放、符合畫面、小地圖。點卡片在右邊改設定,Delete 刪掉選到的。
|
||||
- 畫和註解:畫筆、便利貼(六色、寫誰貼的、雙擊改字)、形狀、文字,只給人看、不會執行。
|
||||
- 執行:照線從觸發器往下(一張接到好幾張時上面的先、再左邊)。Bot 步驟是那個 Bot 聊天裡的一則「[工作流「名稱」第 k/n 步]…」加上一步的結果,它這一輪最後的回答交給下一步(它正忙就排在後面)。檢查回「通過」才往下。等你確認在畫布上方一條「繼續/停止」,並發通知。一次只跑一個,排程到了自動跑;卡片標完成、進行中、等你確認、失敗;執行紀錄留 20 次。
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@
|
|||
## 子功能
|
||||
|
||||
- `workflow-canvas` 畫布:左上是名稱,按下去是選單(每個工作流和它的步驟數、新建工作流、版本歷史、重新命名、建立副本、刪除工作流);右上「聊天」(聊天放在旁邊或收起來)、「執行紀錄」、「▷ 執行工作流」(跑的時候變「■ 停止」)。點點底的畫布拖曳空白處移動、⌘+滾輪或捏合縮放;下面工具列「選取、拖曳|畫筆、便利貼、形狀、文字|搜尋|+ 新增節點」,左下「- 百分比 +|符合畫面|小地圖」。搜尋卡片和註解的字,Enter 跳到下一個。視窗窄時縮放列移到工具列上面。
|
||||
- `workflow-nodes` 卡片:觸發器(手動,或每天、每週…的排程,寫「下次執行」,有「立即執行」)、Bot 步驟(哪個 Bot、要它做什麼)、等你確認(問你的話)、檢查(哪個 Bot、要做到什麼才通過)、交付(結果放進哪個 Bot 的聊天)、通知你(「{結果}」換成上一步結果的第一行)。從卡片底下的點拉到另一張卡就連線;不能連回觸發器、不能繞成一圈。點卡片在右邊改設定;Delete 刪掉選到的卡片或線(觸發器刪不掉)。
|
||||
- `workflow-nodes` 卡片:觸發器(手動、定時(每天、每週…,寫「下次執行」)、Webhook(給一個呼叫網址和密碼)、GitHub(存放庫和事件:PR 合併、CI 失敗…);Slack、新信這些在聊天裡請 Bot 設,跟例行任務的事件觸發是同一套;事情發生時,發生了什麼交給第一步;都有「立即執行」)。「+ 新增節點」可以搜尋,分三組——輸入:提示詞(一段話交給下一步)、素材(檔案,Bot 收到附件);步驟:LLM(直接問模型,選模型、系統提示詞,不用 Bot)、助手(Bot 用它的工具做)、圖片、影片(請 Bot 做出檔案);流程:條件(成立走「是」、不成立走「否」,兩個點各拉一條線;「否」沒接就停下來說原因)、審批(停下來等你按繼續)、輸出(放進哪個 Bot 的聊天,和/或通知你,「{結果}」換成上一步結果的第一行)。舊的「檢查」就是條件,「交付」「通知你」併成輸出。從卡片底下的點拉到另一張卡就連線;不能連回觸發器、不能繞成一圈。點卡片在右邊改設定,選到的卡片上面有「複製」「刪除」;助手、LLM、圖片、影片、條件有「試跑這一步」(只跑這一步,用前一步上次的結果)。Delete 刪掉選到的卡片或線(觸發器刪不掉)。
|
||||
- `workflow-draw` 畫和註解:畫筆、便利貼(六種顏色,下面寫誰貼的,雙擊改字)、形狀、文字;點選後右邊換顏色、改文字、刪除。只是給人看,不會執行。
|
||||
- `workflow-run` 執行:照線從觸發器往下走(一張接到好幾張時,上面的先,再左邊)。Bot 步驟是那個 Bot 聊天裡的一則訊息「[工作流「名稱」第 k/n 步]…」加上上一步的結果,它這一輪最後的回答就是這一步的結果;它正忙就排在後面,等它做完手上那一輪。檢查要回「通過」才往下,否則停下並寫原因。等你確認:畫布上方一條「等你確認:…」,「繼續」/「停止」,並發通知(電腦和手機)。交付把結果放進那個 Bot 的聊天(它正在回答時,等這一輪結束才放);通知你發通知。一次只跑一個;排程到了自動跑。停止時,還排在 Bot 後面的那一步問題直接拿掉,不會停掉 Bot 手上別的事。卡片上標完成、進行中、等你確認、失敗;「執行紀錄」留最近 20 次(誰開始的、每一步的結果、為什麼停)。
|
||||
- `workflow-chat` 聊出來:在聊天裡請 Bot 做工作流,它用 `workflow` 工具建立、看、改(加步驟、改內容、刪步驟、連線、貼便利貼、整理排版)、執行、停止、刪除(刪除先問你)。你正看著那個 Bot 的聊天時(只有它),畫布自動開在聊天旁邊,跳到那個工作流,它改到的卡片和便利貼亮一下;跑出畫面就自動縮放到看得到全部。Bot 做的排成一欄,插在中間時後面的往下移;你自己排過的不重排。要刪除時,允許卡片寫的就是會刪的那一個(沒指定時是畫布上開著的)。旁邊的聊天跟著側邊欄選的 Bot 換。Bot 知道有哪些工作流(說明裡列著),你在畫布旁邊打的每一則都帶著「開著工作流「X」(#1)的畫布」,所以「這個」「畫布上」它知道是哪一個。
|
||||
|
|
@ -28,9 +28,10 @@
|
|||
- **聊天裡建立**(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-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 早報」,上方「等你確認:要把早報傳給你嗎? 繼續 停止」沒有蓋到卡片,觸發器、助手、條件標「完成」,審批是黃框;黃、綠便利貼在卡片左邊;右上「等你確認、執行紀錄、聊天、■ 停止」;右邊是驗證小幫手的聊天,最下面是「通過」。
|
||||
- **在旁邊聊、畫布跟著變**(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」,畫面移到「週末改成十點」那張並選起來。版本歷史、選單、窄視窗:靠自動測試和版面檢查。
|
||||
- **新的節點和觸發器**(covers `workflow-nodes`):示範資料的第二個工作流。指令:要開視窗——`ABV_ALLOW_WINDOW=1 $CTL desktop-shot workflow-kinds ANYBOT_SHOT_VIEW=workflow ANYBOT_SHOT_TAB=2 ANYBOT_SHOT_SIZE=1400x900 ANYBOT_SHOT_FRAMES=30 && ABV_ALLOW_WINDOW=1 $CTL desktop-shot workflow-palette ANYBOT_SHOT_VIEW=workflow ANYBOT_SHOT_TAB=2 ANYBOT_SHOT_SIZE=1400x900 ANYBOT_SHOT_FRAMES=30 'ANYBOT_SHOT_CLICK=1060,860@18' && ABV_ALLOW_WINDOW=1 $CTL desktop-shot workflow-trigger ANYBOT_SHOT_VIEW=workflow ANYBOT_SHOT_TAB=2 ANYBOT_SHOT_SIZE=1400x900 ANYBOT_SHOT_FRAMES=30 'ANYBOT_SHOT_CLICK=942,135@18'`。看到:「PR 合併後的發布貼文」:觸發器寫「GitHub anybot/app:pr_merged」「事情發生時」,下面提示詞、LLM(主要 Bot 的模型)、條件(下面「是」「否」兩個點),是→圖片→審批→輸出、否→輸出(通知);新增節點是搜尋框和「輸入/步驟/流程」三組;點觸發器右邊是「GitHub」、存放庫、事件(PR 合併亮著)、Token。
|
||||
- 自動測試:`cargo test workflow`、`cargo test layout_audit::`(「工作流」四景)、`cargo test theme::`。
|
||||
|
||||
## 陷阱
|
||||
|
|
|
|||
|
|
@ -0,0 +1,18 @@
|
|||
<!-- @license lucide-static v1.67.0 - ISC -->
|
||||
<svg
|
||||
class="lucide lucide-split"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M16 3h5v5" />
|
||||
<path d="M8 3H3v5" />
|
||||
<path d="M12 22v-8.3a4 4 0 0 0-1.172-2.872L3 3" />
|
||||
<path d="m15 9 6-6" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 411 B |
|
|
@ -774,8 +774,13 @@ impl App {
|
|||
Ok("library") => app.lib.open = true,
|
||||
// 市集.
|
||||
Ok("market") => app.market.open = true,
|
||||
// 工作流: a sample on the canvas.
|
||||
Ok("workflow") => app.wf_demo(),
|
||||
// 工作流: a sample on the canvas (ANYBOT_SHOT_TAB=2: the one with the newer kinds).
|
||||
Ok("workflow") => {
|
||||
app.wf_demo();
|
||||
if let Some(id) = std::env::var("ANYBOT_SHOT_TAB").ok().and_then(|v| v.parse::<u64>().ok()) {
|
||||
app.wf.current = id;
|
||||
}
|
||||
}
|
||||
// 日程: a sample week (ANYBOT_SHOT_TAB=day|month for the other views).
|
||||
Ok("schedule") => {
|
||||
app.sched_demo();
|
||||
|
|
|
|||
|
|
@ -120,6 +120,11 @@ impl App {
|
|||
.bots
|
||||
.iter()
|
||||
.flat_map(|b| b.routines.iter().filter(|r| !r.paused).filter_map(move |r| r.trigger.clone().map(|t| crate::triggers::Watch { bot_id: b.id, routine_id: r.id, trigger: t })))
|
||||
// 工作流 started by an event: the same watchers (bot 0, an id of their own).
|
||||
.chain(self.state.workflows.iter().filter_map(|w| match w.trigger().map(|n| &n.kind) {
|
||||
Some(crate::workflow::NodeKind::Trigger { event: Some(t), .. }) if t.validate().is_ok() => Some(crate::triggers::Watch { bot_id: 0, routine_id: crate::workflow::WATCH_BASE + w.id, trigger: t.clone() }),
|
||||
_ => None,
|
||||
}))
|
||||
.collect();
|
||||
let sig = watches.iter().map(|w| format!("{}:{}:{:?}", w.bot_id, w.routine_id, w.trigger)).collect::<Vec<_>>().join("|");
|
||||
if sig != self.ch.trig_sig {
|
||||
|
|
@ -129,6 +134,12 @@ impl App {
|
|||
crate::triggers::restart(watches, slack, self.ch.trig_tx.clone(), Arc::new(move || c.request_repaint()));
|
||||
}
|
||||
while let Ok(f) = self.ch.trig_rx.try_recv() {
|
||||
// A workflow's event: a run, with what happened handed to its first step.
|
||||
if f.bot_id == 0 && f.routine_id > crate::workflow::WATCH_BASE {
|
||||
let wf = f.routine_id - crate::workflow::WATCH_BASE;
|
||||
self.wf_start_with(ctx, wf, "觸發", &f.what);
|
||||
continue;
|
||||
}
|
||||
let Some(b) = self.state.bot_mut(f.bot_id) else { continue };
|
||||
let Some(r) = b.routines.iter_mut().find(|r| r.id == f.routine_id) else { continue };
|
||||
if r.paused {
|
||||
|
|
|
|||
|
|
@ -16,6 +16,11 @@ 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 {
|
||||
self.wf_start_with(ctx, wf, by, "")
|
||||
}
|
||||
|
||||
/// A run that starts with `input` (what happened, for an event trigger) as the last result.
|
||||
pub(super) fn wf_start_with(&mut self, ctx: &egui::Context, wf: u64, by: &str, input: &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() {
|
||||
|
|
@ -24,6 +29,9 @@ impl App {
|
|||
// What was run is kept as a version (版本歷史 shows what each run ran).
|
||||
w.keep_version(now);
|
||||
w.start_run(by, now);
|
||||
if let Some(r) = w.runs.last_mut() {
|
||||
r.input = input.chars().take(crate::workflow::HANDED_ON_CHARS).collect();
|
||||
}
|
||||
self.dirty = true;
|
||||
self.wf_advance(ctx, wf);
|
||||
true
|
||||
|
|
@ -43,6 +51,19 @@ impl App {
|
|||
"stop" => self.wf_stop(wf),
|
||||
"go" => self.wf_confirm(ctx, wf, true),
|
||||
"halt" => self.wf_confirm(ctx, wf, false),
|
||||
// 試跑這一步: just that step, with what the step before it last gave.
|
||||
t if t.starts_with("try:") => {
|
||||
let node = t.trim_start_matches("try:").parse().unwrap_or(0);
|
||||
let now = crate::routines::now();
|
||||
let Some(w) = self.state.workflows.iter_mut().find(|w| w.id == wf) else { return };
|
||||
if w.live_run().is_some() || w.node(node).is_none() {
|
||||
return;
|
||||
}
|
||||
let input = w.input_for(node);
|
||||
w.start_single(node, &input, now);
|
||||
self.dirty = true;
|
||||
self.wf_advance(ctx, wf);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
|
@ -136,33 +157,82 @@ impl App {
|
|||
return;
|
||||
};
|
||||
let state = r.step_of(node_id).map(|s| s.state).unwrap_or(StepState::Waiting);
|
||||
if state == StepState::Skipped {
|
||||
// (On the way a 條件 didn't take.)
|
||||
self.wf_run_mut(wf, run_id, |r| r.at += 1);
|
||||
continue;
|
||||
}
|
||||
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 files = r.last_files();
|
||||
let Some(kind) = w.node(node_id).map(|n| n.kind.clone()) else {
|
||||
self.wf_fail(wf, run_id, node_id, "這一步已經被刪掉了");
|
||||
return;
|
||||
};
|
||||
// (交付 and 通知你 run as the one 輸出 they are now.)
|
||||
let kind = match kind {
|
||||
NodeKind::Deliver { bot } => NodeKind::Output { bot, notify: false, text: String::new() },
|
||||
NodeKind::Notify { text } => NodeKind::Output { bot: 0, notify: true, text },
|
||||
k => k,
|
||||
};
|
||||
match kind {
|
||||
NodeKind::Trigger { .. } => self.wf_done(wf, run_id, node_id, last),
|
||||
NodeKind::Prompt { text } => {
|
||||
if text.trim().is_empty() {
|
||||
self.wf_fail(wf, run_id, node_id, "提示詞還是空的");
|
||||
return;
|
||||
}
|
||||
self.wf_done(wf, run_id, node_id, text.trim().to_string());
|
||||
}
|
||||
NodeKind::Material { files, note } => {
|
||||
if files.is_empty() {
|
||||
self.wf_fail(wf, run_id, node_id, "素材還沒選檔案");
|
||||
return;
|
||||
}
|
||||
let words = NodeKind::Material { files: files.clone(), note }.words();
|
||||
self.wf_run_mut(wf, run_id, |r| {
|
||||
if let Some(s) = r.steps.iter_mut().find(|s| s.node == node_id) {
|
||||
s.files = files;
|
||||
}
|
||||
});
|
||||
self.wf_done(wf, run_id, node_id, format!("素材:{words}"));
|
||||
}
|
||||
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);
|
||||
self.wf_ask(ctx, wf, run_id, node_id, bot, text, &files);
|
||||
return;
|
||||
}
|
||||
NodeKind::Media { bot, prompt, video } => {
|
||||
if prompt.trim().is_empty() {
|
||||
self.wf_fail(wf, run_id, node_id, "還沒寫要做出什麼");
|
||||
return;
|
||||
}
|
||||
let text = crate::workflow::media_message(&name, k, of, &prompt, &last, video);
|
||||
self.wf_ask(ctx, wf, run_id, node_id, bot, text, &files);
|
||||
return;
|
||||
}
|
||||
NodeKind::Llm { model, prompt, system } => {
|
||||
if prompt.trim().is_empty() {
|
||||
self.wf_fail(wf, run_id, node_id, "LLM 還沒寫提示詞");
|
||||
return;
|
||||
}
|
||||
self.wf_llm(ctx, wf, run_id, node_id, &model, &system, crate::workflow::llm_message(&prompt, &last));
|
||||
return;
|
||||
}
|
||||
NodeKind::Check { bot, condition } => {
|
||||
if condition.trim().is_empty() {
|
||||
self.wf_fail(wf, run_id, node_id, "檢查還沒寫要看什麼");
|
||||
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);
|
||||
self.wf_ask(ctx, wf, run_id, node_id, bot, text, &[]);
|
||||
return;
|
||||
}
|
||||
NodeKind::Approve { prompt } => {
|
||||
|
|
@ -180,54 +250,66 @@ impl App {
|
|||
crate::remote::notify(crate::remote::Notice::Need, &name, &body, 0);
|
||||
return;
|
||||
}
|
||||
NodeKind::Deliver { bot } => {
|
||||
if self.state.bot(bot).is_none() {
|
||||
self.wf_fail(wf, run_id, node_id, "要交付的 Bot 已經不在了");
|
||||
return;
|
||||
}
|
||||
// (A bot answering right now: its reply streams into its last message — the
|
||||
// step waits, on the run's record (saved: a restart still delivers it), and
|
||||
// the result goes in once that turn is over.)
|
||||
if self.streams.contains_key(&bot) {
|
||||
self.wf_run_mut(wf, run_id, |r| {
|
||||
if let Some(s) = r.steps.iter_mut().find(|s| s.node == node_id) {
|
||||
s.state = StepState::Running;
|
||||
s.bot = bot;
|
||||
s.asked_at = 0;
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
let selected = self.state.selected;
|
||||
let text = if last.trim().is_empty() { format!("工作流「{name}」跑完了(前面的步驟沒有結果)。") } else { format!("工作流「{name}」的結果:\n\n{last}") };
|
||||
if let Some(b) = self.state.bot_mut(bot) {
|
||||
b.messages.push(Message { at: crate::model::now_ms(), ..Message::assistant(&text, &format!("工作流「{name}」")) });
|
||||
if bot != selected {
|
||||
b.unread = true;
|
||||
NodeKind::Output { bot, notify, text } => {
|
||||
if bot != 0 {
|
||||
if self.state.bot(bot).is_none() {
|
||||
self.wf_fail(wf, run_id, node_id, "要放進聊天的那個 Bot 已經不在了");
|
||||
return;
|
||||
}
|
||||
// (A bot answering right now: its reply streams into its last message —
|
||||
// the step waits, on the run's record (saved: a restart still delivers
|
||||
// it), and the result goes in once that turn is over.)
|
||||
if self.streams.contains_key(&bot) {
|
||||
self.wf_run_mut(wf, run_id, |r| {
|
||||
if let Some(s) = r.steps.iter_mut().find(|s| s.node == node_id) {
|
||||
s.state = StepState::Running;
|
||||
s.bot = bot;
|
||||
s.asked_at = 0;
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
let selected = self.state.selected;
|
||||
let words = if last.trim().is_empty() { format!("工作流「{name}」跑完了(前面的步驟沒有結果)。") } else { format!("工作流「{name}」的結果:\n\n{last}") };
|
||||
if let Some(b) = self.state.bot_mut(bot) {
|
||||
b.messages.push(Message { at: crate::model::now_ms(), ..Message::assistant(&words, &format!("工作流「{name}」")) });
|
||||
if bot != selected {
|
||||
b.unread = true;
|
||||
}
|
||||
}
|
||||
self.save_now = true;
|
||||
}
|
||||
if notify {
|
||||
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.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);
|
||||
}
|
||||
NodeKind::Deliver { .. } | NodeKind::Notify { .. } => unreachable!("made into an Output above"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn wf_ask(&mut self, ctx: &egui::Context, wf: u64, run: u64, node: u64, bot: u64, text: String, files: &[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) };
|
||||
// (素材 before it go along as attachments.)
|
||||
let attachments = files
|
||||
.iter()
|
||||
.filter_map(|f| {
|
||||
let meta = std::fs::metadata(f).ok()?;
|
||||
let name = std::path::Path::new(f).file_name()?.to_string_lossy().to_string();
|
||||
Some(crate::attach::Attachment { image: crate::attach::is_image_name(&name), name, path: f.clone(), bytes: meta.len(), ..Default::default() })
|
||||
})
|
||||
.collect();
|
||||
let msg = Message { at: crate::model::now_ms(), attachments, ..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) {
|
||||
|
|
@ -241,6 +323,50 @@ impl App {
|
|||
self.dirty = true;
|
||||
}
|
||||
|
||||
/// LLM: the model answers on a thread (no bot, no tools); the answer comes back at a tick.
|
||||
/// `model`: 「供應商:模型」 (empty: the main bot's).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn wf_llm(&mut self, ctx: &egui::Context, wf: u64, run: u64, node: u64, model: &str, system: &str, text: String) {
|
||||
let main = self.state.bot(self.state.primary_bot).or(self.state.bots.first()).map(|b| (b.provider, b.model.clone()));
|
||||
let (kind, model) = match model.split_once(':') {
|
||||
Some((k, m)) if crate::appctl::provider_of(k).is_some() => (crate::appctl::provider_of(k).unwrap_or(ProviderKind::Custom), m.trim().to_string()),
|
||||
_ => match main {
|
||||
Some((k, m)) => (k, if model.trim().is_empty() { m } else { model.trim().to_string() }),
|
||||
None => {
|
||||
self.wf_fail(wf, run, node, "沒有可以用的模型:先設一個 Bot");
|
||||
return;
|
||||
}
|
||||
},
|
||||
};
|
||||
let ps = self.state.provider(kind);
|
||||
let req = ChatRequest {
|
||||
kind,
|
||||
base_url: providers::resolve_base(kind, &ps.base_url),
|
||||
api_key: providers::resolve_key_for(kind, &ps.api_key, &ps.base_url),
|
||||
model,
|
||||
system: if system.trim().is_empty() { "你是工作流裡的一個步驟。照提示詞做,只回結果,用繁體中文。".into() } else { system.to_string() },
|
||||
history: vec![Message::user(&text)],
|
||||
tools: vec![],
|
||||
session: format!("anybot-wf-{wf}"),
|
||||
effort: String::new(),
|
||||
};
|
||||
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 = 0;
|
||||
s.asked_at = crate::model::now_ms();
|
||||
}
|
||||
});
|
||||
let (out, ctx) = (self.wf.llm.clone(), ctx.clone());
|
||||
std::thread::spawn(move || {
|
||||
let cancel = AtomicBool::new(false);
|
||||
let r = providers::run_step(&req, &cancel, &|_| {}).map(|o| o.text);
|
||||
out.lock().unwrap_or_else(|e| e.into_inner()).push((wf, run, node, r));
|
||||
ctx.request_repaint();
|
||||
});
|
||||
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);
|
||||
|
|
@ -291,13 +417,21 @@ impl App {
|
|||
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();
|
||||
// 條件: 是 goes on along 是, 否 along 否 (the other way's steps are skipped); 否
|
||||
// with nothing on 否 stops the run. Either way it hands on what it checked.
|
||||
let passed = check_passed(&answer);
|
||||
let w = self.state.workflows.iter().find(|w| w.id == wf);
|
||||
let last = w.and_then(|w| w.runs.iter().find(|r| r.id == run)).map(|r| r.last_output()).unwrap_or_default();
|
||||
match w.and_then(|w| w.branch_skips(node, passed.is_ok())) {
|
||||
Some(skips) => {
|
||||
self.wf_run_mut(wf, run, |r| {
|
||||
for s in r.steps.iter_mut().filter(|s| skips.contains(&s.node) && s.state == StepState::Waiting) {
|
||||
s.state = StepState::Skipped;
|
||||
}
|
||||
});
|
||||
self.wf_done(wf, run, node, last);
|
||||
}
|
||||
Err(why) => self.wf_fail(wf, run, node, &format!("檢查沒通過:{why}")),
|
||||
None => self.wf_fail(wf, run, node, &format!("條件不成立:{}", passed.err().unwrap_or_default())),
|
||||
}
|
||||
} else {
|
||||
self.wf_done(wf, run, node, answer);
|
||||
|
|
@ -381,6 +515,19 @@ impl App {
|
|||
for wf in std::mem::take(&mut self.wf.advance) {
|
||||
self.wf_advance(ctx, wf);
|
||||
}
|
||||
// LLM answers back from their threads.
|
||||
let answers: Vec<(u64, u64, u64, Result<String, String>)> = std::mem::take(&mut *self.wf.llm.lock().unwrap_or_else(|e| e.into_inner()));
|
||||
for (wf, run, node, r) in answers {
|
||||
let still = self.state.workflows.iter().find(|w| w.id == wf).and_then(|w| w.runs.iter().find(|x| x.id == run)).is_some_and(|x| x.state == RunState::Running && x.current().is_some_and(|s| s.node == node && s.state == StepState::Running));
|
||||
if !still {
|
||||
continue;
|
||||
}
|
||||
match r {
|
||||
Ok(text) => self.wf_done(wf, run, node, text.trim().chars().take(OUTPUT_KEPT).collect()),
|
||||
Err(e) => self.wf_fail(wf, run, node, &format!("模型沒有回答:{}", e.chars().take(200).collect::<String>())),
|
||||
}
|
||||
self.wf_advance(ctx, wf);
|
||||
}
|
||||
// Runs that can go on: a 交付 whose bot is free now (or whose step was deleted while it
|
||||
// waited), and a step not started yet — after a restart nothing else moves those on.
|
||||
let ready: Vec<(u64, Option<u64>)> = self
|
||||
|
|
@ -390,7 +537,7 @@ impl App {
|
|||
.flat_map(|w| {
|
||||
w.runs.iter().filter(|r| r.state == RunState::Running).filter_map(move |r| match r.current() {
|
||||
None => Some((w.id, None, 0)),
|
||||
Some(s) if s.state == StepState::Waiting => Some((w.id, None, 0)),
|
||||
Some(s) if matches!(s.state, StepState::Waiting | StepState::Skipped) => Some((w.id, None, 0)),
|
||||
Some(s) if s.state == StepState::Running && s.asked_at == 0 && s.bot != 0 => Some((w.id, Some(s.node), s.bot)),
|
||||
_ => None,
|
||||
})
|
||||
|
|
@ -564,7 +711,7 @@ mod tests {
|
|||
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.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, "手動");
|
||||
|
|
@ -597,7 +744,7 @@ mod tests {
|
|||
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 {
|
||||
if let NodeKind::Trigger { schedule: s, .. } = &mut app.state.workflows[0].nodes[0].kind {
|
||||
*s = Some(schedule);
|
||||
}
|
||||
app.tick_workflows(&ctx);
|
||||
|
|
@ -751,4 +898,65 @@ mod tests {
|
|||
app.wf.chat_hidden = true;
|
||||
assert_eq!(app.wf_seen(), "");
|
||||
}
|
||||
|
||||
/// A run through the new kinds: an event's words reach the first step; 提示詞 hands its
|
||||
/// words on; 素材 arrives as attachments; a 條件 that holds skips the 否 way; an LLM whose
|
||||
/// model can't be reached fails the step and says so.
|
||||
#[test]
|
||||
fn a_run_goes_through_the_new_kinds() {
|
||||
let (ctx, mut app, bot) = app_with(vec![]);
|
||||
let file = std::env::temp_dir().join("anybot-wf-material.txt");
|
||||
std::fs::write(&file, "上週的週報").unwrap();
|
||||
let w = &mut app.state.workflows[0];
|
||||
for (id, kind, y) in [
|
||||
(2, NodeKind::Prompt { text: "照這個格式寫".into() }, 1.0),
|
||||
(3, NodeKind::Material { files: vec![file.display().to_string()], note: String::new() }, 2.0),
|
||||
(4, NodeKind::Step { bot, prompt: "寫週報".into() }, 3.0),
|
||||
(5, NodeKind::Check { bot, condition: "有三點".into() }, 4.0),
|
||||
(6, NodeKind::Output { bot, notify: false, text: String::new() }, 5.0),
|
||||
(7, NodeKind::Approve { prompt: "不夠".into() }, 5.0),
|
||||
] {
|
||||
w.nodes.push(Node { id, kind, x: 0.0, y: y * 200.0 });
|
||||
}
|
||||
for (a, b, port) in [(1, 2, ""), (2, 3, ""), (3, 4, ""), (4, 5, ""), (5, 6, "yes"), (5, 7, "no")] {
|
||||
assert!(w.connect_port(a, b, port));
|
||||
}
|
||||
assert!(app.wf_start_with(&ctx, 1, "觸發", "有人留言了"));
|
||||
// 提示詞 and 素材 went by at once; the bot's question carries the file.
|
||||
let i = app.waiting_wakes.iter().position(|(b, _)| *b == bot).unwrap();
|
||||
assert_eq!(app.waiting_wakes[i].1.attachments.iter().map(|a| a.name.as_str()).collect::<Vec<_>>(), vec!["anybot-wf-material.txt"]);
|
||||
assert!(app.waiting_wakes[i].1.text.contains("上一步的結果:\n素材:anybot-wf-material.txt"), "{}", app.waiting_wakes[i].1.text);
|
||||
assert_eq!(run(&app).step_of(2).map(|s| s.output.as_str()), Some("照這個格式寫"));
|
||||
answer(&mut app, bot, "1. 2. 3.");
|
||||
app.tick_workflows(&ctx);
|
||||
answer(&mut app, bot, "通過");
|
||||
app.streams.remove(&bot);
|
||||
app.tick_workflows(&ctx);
|
||||
let r = run(&app);
|
||||
assert_eq!((r.state, r.step_of(6).map(|s| s.state), r.step_of(7).map(|s| s.state)), (RunState::Done, Some(StepState::Done), Some(StepState::Skipped)), "{r:?}");
|
||||
// The event's words reach the first step when nothing came before.
|
||||
let w = &mut app.state.workflows[0];
|
||||
w.nodes.retain(|n| n.id <= 1);
|
||||
w.edges.clear();
|
||||
w.nodes.push(Node { id: 8, kind: NodeKind::Step { bot, prompt: "回覆".into() }, x: 0.0, y: 200.0 });
|
||||
w.connect(1, 8);
|
||||
app.streams.insert(bot, busy());
|
||||
assert!(app.wf_start_with(&ctx, 1, "觸發", "有人留言了"));
|
||||
assert!(app.waiting_wakes.iter().any(|(_, m)| m.text.contains("上一步的結果:\n有人留言了")));
|
||||
app.wf_stop(1);
|
||||
// An LLM whose model can't be reached: the step fails, saying so.
|
||||
app.state.provider_mut(ProviderKind::Custom).base_url = "http://127.0.0.1:9/v1".into();
|
||||
let w = &mut app.state.workflows[0];
|
||||
w.nodes.push(Node { id: 9, kind: NodeKind::Llm { model: "custom:m".into(), prompt: "摘要".into(), system: String::new() }, x: 0.0, y: 400.0 });
|
||||
w.edges.clear();
|
||||
w.connect(1, 9);
|
||||
assert!(app.wf_start(&ctx, 1, "手動"));
|
||||
let deadline = Instant::now() + std::time::Duration::from_secs(20);
|
||||
while run(&app).state == RunState::Running && Instant::now() < deadline {
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
app.tick_workflows(&ctx);
|
||||
}
|
||||
let r = run(&app);
|
||||
assert!(r.state == RunState::Failed && r.why.starts_with("模型沒有回答"), "{r:?}");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -44,7 +44,7 @@ pub(super) struct WfUi {
|
|||
/// A pen stroke being drawn (canvas points).
|
||||
pub stroke: Vec<egui::Pos2>,
|
||||
/// A line being drawn from a card's bottom dot.
|
||||
pub linking: Option<u64>,
|
||||
pub linking: Option<(u64, String)>,
|
||||
/// A shape being dragged out (its first corner, canvas points).
|
||||
pub shaping: Option<egui::Pos2>,
|
||||
/// The note whose words are being typed on the canvas.
|
||||
|
|
@ -68,6 +68,12 @@ pub(super) struct WfUi {
|
|||
pub flash: Option<(u64, Vec<u64>, Instant)>,
|
||||
/// A bot changed it: show what changed if it is out of view.
|
||||
pub reveal: bool,
|
||||
/// What is typed in 新增節點's search.
|
||||
pub palette_q: String,
|
||||
/// The selected card's 複製 and 刪除 (screen rects), this frame.
|
||||
pub card_tools: Option<(u64, Rect, Rect)>,
|
||||
/// LLM steps' answers from their threads: (workflow, run, node, answer).
|
||||
pub llm: LlmAnswers,
|
||||
}
|
||||
|
||||
/// How long what a bot changed stays lit on the canvas.
|
||||
|
|
@ -75,6 +81,20 @@ 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;
|
||||
|
||||
/// 新增節點, in three groups: (group, [(icon, name, kind, what it does)]).
|
||||
type PaletteItem = (Icon, &'static str, &'static str, &'static str);
|
||||
const PALETTE: [(&str, &[PaletteItem]); 3] = [
|
||||
("輸入", &[(Icon::FileText, "提示詞", "prompt", "寫好的一段話,交給下一步"), (Icon::File, "素材", "material", "檔案,交給下一步(Bot 會收到附件)")]),
|
||||
(
|
||||
"步驟",
|
||||
&[(Icon::Sparkle, "LLM", "llm", "直接問模型,不用 Bot、不用工具"), (Icon::Bot, "助手", "step", "交給一個 Bot 用它的工具去做"), (Icon::FileImage, "圖片", "image", "請 Bot 做一張圖"), (Icon::FileVideo, "影片", "video", "請 Bot 做一段影片")],
|
||||
),
|
||||
("流程", &[(Icon::Split, "條件", "check", "成立走「是」,不成立走「否」"), (Icon::Person, "審批", "approve", "停下來等你按繼續"), (Icon::Send, "輸出", "output", "放進聊天,或通知你")]),
|
||||
];
|
||||
|
||||
/// LLM steps' answers from their threads: (workflow, run, node, answer).
|
||||
pub(super) type LlmAnswers = std::sync::Arc<std::sync::Mutex<Vec<(u64, u64, u64, Result<String, String>)>>>;
|
||||
|
||||
/// 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;
|
||||
|
|
@ -90,12 +110,30 @@ 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::Step { .. } | NodeKind::Llm { .. } | NodeKind::Media { .. } => 118.0,
|
||||
// (Room for 是 and 否 under the words.)
|
||||
NodeKind::Check { .. } => 132.0,
|
||||
NodeKind::Approve { .. } | NodeKind::Notify { .. } | NodeKind::Prompt { .. } | NodeKind::Material { .. } | NodeKind::Output { .. } => 96.0,
|
||||
NodeKind::Deliver { .. } => 82.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a line leaves a card (canvas points): the middle of its bottom; a 條件's 是 at the left,
|
||||
/// 否 at the right.
|
||||
fn out_dot(n: &Node, port: &str) -> egui::Pos2 {
|
||||
let r = node_rect(n);
|
||||
match (&n.kind, port) {
|
||||
(NodeKind::Check { .. }, "no") => egui::pos2(r.min.x + r.width() * 0.72, r.max.y),
|
||||
(NodeKind::Check { .. }, _) => egui::pos2(r.min.x + r.width() * 0.28, r.max.y),
|
||||
_ => egui::pos2(r.center().x, r.max.y),
|
||||
}
|
||||
}
|
||||
|
||||
/// The ways out of a card.
|
||||
fn ports(n: &Node) -> &'static [&'static str] {
|
||||
if matches!(n.kind, NodeKind::Check { .. }) { &["yes", "no"] } else { &[""] }
|
||||
}
|
||||
|
||||
/// 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 }
|
||||
|
|
@ -108,11 +146,15 @@ fn node_rect(n: &Node) -> Rect {
|
|||
fn kind_icon(kind: &NodeKind) -> Icon {
|
||||
match kind {
|
||||
NodeKind::Trigger { .. } => Icon::Zap,
|
||||
NodeKind::Prompt { .. } => Icon::FileText,
|
||||
NodeKind::Material { .. } => Icon::File,
|
||||
NodeKind::Step { .. } => Icon::Bot,
|
||||
NodeKind::Approve { .. } => Icon::CircleCheck,
|
||||
NodeKind::Check { .. } => Icon::Shield,
|
||||
NodeKind::Deliver { .. } => Icon::Send,
|
||||
NodeKind::Notify { .. } => Icon::Bell,
|
||||
NodeKind::Llm { .. } => Icon::Sparkle,
|
||||
NodeKind::Media { video: false, .. } => Icon::FileImage,
|
||||
NodeKind::Media { video: true, .. } => Icon::FileVideo,
|
||||
NodeKind::Approve { .. } => Icon::Person,
|
||||
NodeKind::Check { .. } => Icon::Split,
|
||||
NodeKind::Deliver { .. } | NodeKind::Notify { .. } | NodeKind::Output { .. } => Icon::Send,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -153,8 +195,8 @@ fn to_segment(p: egui::Pos2, a: egui::Pos2, b: egui::Pos2) -> f32 {
|
|||
}
|
||||
|
||||
/// 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));
|
||||
fn edge_points(from: egui::Pos2, b: Rect, v: &View) -> [egui::Pos2; 4] {
|
||||
let p0 = v.to_screen(from);
|
||||
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]
|
||||
|
|
@ -636,13 +678,16 @@ impl App {
|
|||
// ── 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 pts = edge_points(out_dot(a, &e.port), 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 skipped = run.as_ref().and_then(|r| r.step_of(e.to)).is_some_and(|s| s.state == StepState::Skipped);
|
||||
let col = if picked {
|
||||
p.accent
|
||||
} else if done {
|
||||
p.up
|
||||
} else if skipped {
|
||||
p.border
|
||||
} else {
|
||||
p.text3
|
||||
};
|
||||
|
|
@ -650,10 +695,9 @@ impl App {
|
|||
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((from, port)), Some(s)) = (self.wf.linking.clone(), 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));
|
||||
let p0 = view.to_screen(out_dot(a, &port));
|
||||
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)));
|
||||
}
|
||||
}
|
||||
|
|
@ -662,6 +706,7 @@ impl App {
|
|||
let tz = self.state.timezone.clone();
|
||||
let names: HashMap<u64, String> = self.state.bots.iter().map(|b| (b.id, b.name.clone())).collect();
|
||||
let mut run_now: Option<u64> = None;
|
||||
let mut card_tools = None;
|
||||
for n in &w.nodes {
|
||||
let r = view.rect(node_rect(n));
|
||||
if !r.intersects(rect) {
|
||||
|
|
@ -706,11 +751,15 @@ impl App {
|
|||
painter.layout_job(job)
|
||||
};
|
||||
match &n.kind {
|
||||
NodeKind::Trigger { schedule } => {
|
||||
let when = schedule.as_ref().map(crate::routines::describe).unwrap_or_else(|| t("手動:按「立即執行」或「執行工作流」"));
|
||||
NodeKind::Trigger { schedule, event } => {
|
||||
let when = if schedule.is_none() && event.is_none() { t("手動:按「立即執行」或「執行工作流」") } else { NodeKind::trigger_words(schedule, event) };
|
||||
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("只在按的時候"));
|
||||
let next = if event.is_some() {
|
||||
t("事情發生時")
|
||||
} else {
|
||||
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;
|
||||
|
|
@ -721,10 +770,39 @@ impl App {
|
|||
run_now = Some(w.id);
|
||||
}
|
||||
}
|
||||
NodeKind::Step { bot, prompt } | NodeKind::Check { bot, condition: prompt } => {
|
||||
NodeKind::Step { bot, prompt } | NodeKind::Check { bot, condition: prompt } | NodeKind::Media { bot, 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);
|
||||
if matches!(n.kind, NodeKind::Check { .. }) {
|
||||
// (是 and 否 over their dots.)
|
||||
for (port, word) in [("yes", "是"), ("no", "否")] {
|
||||
let at = view.to_screen(out_dot(n, port)) - vec2(0.0, 12.0 * z);
|
||||
painter.text(at, egui::Align2::CENTER_CENTER, t(word), egui::FontId::new(FONT_XS * z, crate::bold()), p.text2);
|
||||
}
|
||||
}
|
||||
}
|
||||
NodeKind::Llm { model, prompt, .. } => {
|
||||
painter.text(line(0.0), egui::Align2::LEFT_TOP, if model.is_empty() { t("主要 Bot 的模型") } else { model.clone() }, 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::Prompt { text } => {
|
||||
painter.galley(line(0.0), wrap(if text.trim().is_empty() { "(寫要交給下一步的話)" } else { text.as_str() }, 2), p.text2);
|
||||
}
|
||||
NodeKind::Material { files, .. } => {
|
||||
let words = if files.is_empty() { t("(選檔案)") } else { n.kind.words() };
|
||||
painter.galley(line(0.0), wrap(&words, 2), p.text2);
|
||||
}
|
||||
NodeKind::Output { bot, notify, text } => {
|
||||
let mut ways = vec![];
|
||||
if *bot != 0 {
|
||||
ways.push(format!("{} 「{}」 {}", t("放進"), names.get(bot).cloned().unwrap_or_default(), t("的聊天")));
|
||||
}
|
||||
if *notify {
|
||||
ways.push(format!("{}:{}", t("通知"), if text.trim().is_empty() { "{結果}" } else { text.as_str() }));
|
||||
}
|
||||
let words = if ways.is_empty() { t("(選放進哪個聊天,或通知你)") } else { ways.join(";") };
|
||||
painter.galley(line(0.0), wrap(&words, 2), p.text2);
|
||||
}
|
||||
NodeKind::Approve { prompt } => {
|
||||
painter.galley(line(0.0), wrap(if prompt.trim().is_empty() { "要繼續嗎?" } else { prompt.as_str() }, 2), p.text2);
|
||||
|
|
@ -738,10 +816,28 @@ impl App {
|
|||
}
|
||||
}
|
||||
}
|
||||
// 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 });
|
||||
// The selected card: 複製 and 刪除 above its top-right corner (not the trigger).
|
||||
if self.wf.selected == Some(n.id) && !screen && !matches!(n.kind, NodeKind::Trigger { .. }) {
|
||||
let del = Rect::from_min_size(egui::pos2(r.max.x - 30.0, r.min.y - 36.0), vec2(30.0, 30.0));
|
||||
let copy = del.translate(vec2(-34.0, 0.0));
|
||||
let bar = copy.union(del).expand(3.0);
|
||||
painter.rect_filled(bar, R_M, p.elevated);
|
||||
painter.rect_stroke(bar, R_M, Stroke::new(1.0, p.border), egui::StrokeKind::Inside);
|
||||
for (b, icon) in [(copy, Icon::Copy), (del, Icon::Trash)] {
|
||||
let hot = pointer.is_some_and(|s| b.contains(s));
|
||||
if hot {
|
||||
painter.rect_filled(b, R_M, p.hover);
|
||||
}
|
||||
crate::icons::paint(&painter, Rect::from_center_size(b.center(), vec2(16.0, 16.0)), icon, if icon == Icon::Trash && hot { p.danger } else { p.text2 });
|
||||
}
|
||||
card_tools = Some((n.id, copy, del));
|
||||
}
|
||||
// The dots a line leaves from (a 條件: 是 and 否) and comes into.
|
||||
for port in ports(n) {
|
||||
let out = view.to_screen(out_dot(n, port));
|
||||
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);
|
||||
}
|
||||
|
|
@ -767,6 +863,7 @@ impl App {
|
|||
self.wf.flash = None;
|
||||
}
|
||||
}
|
||||
self.wf.card_tools = card_tools;
|
||||
if let Some(id) = run_now {
|
||||
self.wf_keep_version();
|
||||
self.wf_do(&ctx, id, "run");
|
||||
|
|
@ -882,16 +979,7 @@ impl App {
|
|||
// 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 out_dot_at = |s: egui::Pos2| w.nodes.iter().rev().find_map(|n| ports(n).iter().find(|port| (s - view.to_screen(out_dot(n, port))).length() < 12.0).map(|port| (n.id, port.to_string())));
|
||||
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)
|
||||
|
|
@ -915,11 +1003,31 @@ impl App {
|
|||
.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);
|
||||
let pts = edge_points(out_dot(a, &e.port), node_rect(b), view);
|
||||
(0..=24).map(|k| bezier_at(&pts, k as f32 / 24.0)).collect::<Vec<_>>().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));
|
||||
// 複製 / 刪除 over the selected card.
|
||||
if let Some((id, copy, del)) = self.wf.card_tools {
|
||||
if copy.contains(s) || del.contains(s) {
|
||||
if resp.clicked() {
|
||||
if let Some(wi) = self.wf_index() {
|
||||
if del.contains(s) {
|
||||
self.state.workflows[wi].remove(id);
|
||||
self.wf.selected = None;
|
||||
} else if let Some(n) = self.state.workflows[wi].node(id).cloned() {
|
||||
let nid = self.state.workflows[wi].next_id();
|
||||
self.state.workflows[wi].nodes.push(Node { id: nid, kind: n.kind, x: n.x + 40.0, y: n.y + 40.0 });
|
||||
self.wf.selected = Some(nid);
|
||||
}
|
||||
self.wf_touch();
|
||||
}
|
||||
}
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
|
||||
return;
|
||||
}
|
||||
}
|
||||
match self.wf.tool {
|
||||
Tool::Select | Tool::Hand => {
|
||||
if resp.double_clicked() {
|
||||
|
|
@ -931,8 +1039,8 @@ impl App {
|
|||
}
|
||||
if resp.drag_started() {
|
||||
self.wf.editing = None;
|
||||
if let Some(id) = out_dot_at(pressed) {
|
||||
self.wf.linking = Some(id);
|
||||
if let Some(dot) = out_dot_at(pressed) {
|
||||
self.wf.linking = Some(dot);
|
||||
} else if let Some(id) = card_at(pressed).or_else(|| note_at(pressed)) {
|
||||
self.wf.selected = Some(id);
|
||||
self.wf.selected_edge = None;
|
||||
|
|
@ -962,9 +1070,9 @@ impl App {
|
|||
}
|
||||
}
|
||||
if resp.drag_stopped() {
|
||||
if let Some(from) = self.wf.linking.take() {
|
||||
if let Some((from, port)) = self.wf.linking.take() {
|
||||
if let (Some(to), Some(wi)) = (card, self.wf_index()) {
|
||||
if self.state.workflows[wi].connect(from, to) {
|
||||
if self.state.workflows[wi].connect_port(from, to, &port) {
|
||||
self.wf_touch();
|
||||
}
|
||||
}
|
||||
|
|
@ -1168,13 +1276,31 @@ impl App {
|
|||
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();
|
||||
egui::Popup::menu(&r).width(260.0).show(|ui| {
|
||||
ui.set_min_width(240.0);
|
||||
ui.set_max_width(260.0);
|
||||
// (Search, then the kinds in three groups — 輸入、步驟、流程.)
|
||||
let q = &mut self.wf.palette_q;
|
||||
ui.add(egui::TextEdit::singleline(q).hint_text(t("搜尋節點")).desired_width(f32::INFINITY));
|
||||
let q = q.trim().to_lowercase();
|
||||
let mut chose = None;
|
||||
for (group, items) in PALETTE {
|
||||
let shown: Vec<&(Icon, &str, &str, &str)> = items.iter().filter(|(_, label, which, about)| q.is_empty() || label.to_lowercase().contains(&q) || which.contains(&q) || about.contains(&q)).collect();
|
||||
if shown.is_empty() {
|
||||
continue;
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
ui.label(RichText::new(t(group)).size(FONT_XS).color(p.text3));
|
||||
for (icon, label, which, about) in shown {
|
||||
if menu_ui::item(ui, p, *icon, label).on_hover_text(t(about)).clicked() {
|
||||
chose = Some(*which);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(which) = chose {
|
||||
self.wf.palette_q.clear();
|
||||
self.wf_add_node(which);
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
@ -1188,10 +1314,13 @@ impl App {
|
|||
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 {
|
||||
"prompt" => NodeKind::Prompt { text: String::new() },
|
||||
"material" => NodeKind::Material { files: vec![], note: String::new() },
|
||||
"llm" => NodeKind::Llm { model: String::new(), prompt: String::new(), system: String::new() },
|
||||
"image" | "video" => NodeKind::Media { bot, prompt: String::new(), video: which == "video" },
|
||||
"approve" => NodeKind::Approve { prompt: String::new() },
|
||||
"check" => NodeKind::Check { bot, condition: String::new() },
|
||||
"deliver" => NodeKind::Deliver { bot },
|
||||
"notify" => NodeKind::Notify { text: t("{結果}") },
|
||||
"output" => NodeKind::Output { bot, notify: false, text: String::new() },
|
||||
_ => NodeKind::Step { bot, prompt: String::new() },
|
||||
};
|
||||
let w = &mut self.state.workflows[wi];
|
||||
|
|
@ -1327,6 +1456,7 @@ impl App {
|
|||
let mut kind = node.kind.clone();
|
||||
let mut remove = false;
|
||||
let mut run_now = false;
|
||||
let mut try_now = false;
|
||||
floating(ui, p, p.border, Margin::same(16), |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
ui.add_enabled_ui(!screen, |ui| {
|
||||
|
|
@ -1354,12 +1484,40 @@ impl App {
|
|||
field_label(ui, label, p);
|
||||
ui.add(egui::TextEdit::multiline(text).hint_text(t(hint_)).desired_rows(4).desired_width(f32::INFINITY));
|
||||
};
|
||||
// (交付 and 通知你 are one 輸出 now: edited as one.)
|
||||
kind = match kind.clone() {
|
||||
NodeKind::Deliver { bot } => NodeKind::Output { bot, notify: false, text: String::new() },
|
||||
NodeKind::Notify { text } => NodeKind::Output { bot: 0, notify: true, text },
|
||||
k => k,
|
||||
};
|
||||
let watch = crate::workflow::WATCH_BASE + self.wf.current;
|
||||
match &mut kind {
|
||||
NodeKind::Trigger { schedule } => {
|
||||
NodeKind::Trigger { schedule, event } => {
|
||||
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 };
|
||||
use crate::triggers::Trigger as T;
|
||||
let cur = match (&*schedule, &*event) {
|
||||
(_, Some(T::Webhook { .. })) => 2,
|
||||
(_, Some(T::Github { .. })) => 3,
|
||||
(_, Some(_)) => 4,
|
||||
(Some(_), None) => 1,
|
||||
(None, None) => 0,
|
||||
};
|
||||
let names = ["手動", "定時", "Webhook", "GitHub", "其他事件"];
|
||||
let mut pick = cur;
|
||||
egui::ComboBox::from_id_salt(("wf-trigger-kind", id)).selected_text(t(names[cur])).width(ui.available_width() - 8.0).show_ui(ui, |ui| {
|
||||
for (k, n) in names.iter().enumerate().take(4) {
|
||||
ui.selectable_value(&mut pick, k, t(n));
|
||||
}
|
||||
});
|
||||
if pick != cur {
|
||||
*schedule = None;
|
||||
*event = None;
|
||||
match pick {
|
||||
1 => *schedule = serde_json::from_value(serde_json::json!({"frequency": "daily", "time": "09:00", "timezone": self.state.timezone})).ok(),
|
||||
2 => *event = Some(T::Webhook { secret: crate::workflow::new_secret() }),
|
||||
3 => *event = serde_json::from_value(serde_json::json!({"type": "github", "repo": "", "events": ["pr_merged"]})).ok(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let Some(s) = schedule.as_mut() {
|
||||
ui.add_space(6.0);
|
||||
|
|
@ -1396,29 +1554,184 @@ impl App {
|
|||
}
|
||||
hint(ui, crate::routines::describe(s), p);
|
||||
}
|
||||
match event {
|
||||
Some(T::Webhook { secret }) => {
|
||||
ui.add_space(6.0);
|
||||
let port = crate::triggers::webhook_port().unwrap_or(crate::triggers::WEBHOOK_PORT);
|
||||
let url = format!("http://127.0.0.1:{port}/hooks/{watch}");
|
||||
field_label(ui, "呼叫這個網址就執行(POST,內容交給第一步)", p);
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(egui::Label::new(RichText::new(&url).size(FONT_XS).family(egui::FontFamily::Monospace).color(p.text)).truncate());
|
||||
if ui.small_button(t("複製")).clicked() {
|
||||
ui.ctx().copy_text(url.clone());
|
||||
}
|
||||
});
|
||||
field_label(ui, "Authorization: Bearer", p);
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(egui::Label::new(RichText::new(secret.as_str()).size(FONT_XS).family(egui::FontFamily::Monospace).color(p.text2)).truncate());
|
||||
if ui.small_button(t("複製")).clicked() {
|
||||
ui.ctx().copy_text(secret.clone());
|
||||
}
|
||||
if ui.small_button(t("換一組")).clicked() {
|
||||
*secret = crate::workflow::new_secret();
|
||||
}
|
||||
});
|
||||
}
|
||||
Some(T::Github { repo, token, events, .. }) => {
|
||||
ui.add_space(6.0);
|
||||
field_label(ui, "存放庫(owner/repo)", p);
|
||||
ui.add(egui::TextEdit::singleline(repo).hint_text("anthropics/anybot").desired_width(f32::INFINITY));
|
||||
field_label(ui, "什麼事發生時", p);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
for (code, n) in [
|
||||
("pr_opened", "PR 建立"),
|
||||
("pr_merged", "PR 合併"),
|
||||
("pr_comment", "PR 留言"),
|
||||
("review_approved", "審查核准"),
|
||||
("ci_failed", "CI 失敗"),
|
||||
("ci_passed", "CI 通過"),
|
||||
("issue_opened", "議題建立"),
|
||||
("push", "推送"),
|
||||
] {
|
||||
let on = events.iter().any(|e| e == code);
|
||||
if ui.selectable_label(on, t(n)).clicked() {
|
||||
if on {
|
||||
events.retain(|e| e != code);
|
||||
} else {
|
||||
events.push(code.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
field_label(ui, "GitHub Token(看得到這個存放庫)", p);
|
||||
ui.add(egui::TextEdit::singleline(token).password(true).desired_width(f32::INFINITY));
|
||||
}
|
||||
Some(other) => {
|
||||
ui.add_space(6.0);
|
||||
note(ui, format!("{}{}", other.describe(), t("。要改,在聊天裡請 Bot 用 workflow 改。")), p);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
if let Some(e) = event.as_ref() {
|
||||
if let Err(why) = e.validate() {
|
||||
ui.label(RichText::new(why).size(FONT_XS).color(p.attention));
|
||||
} else if let Some(st) = crate::triggers::statuses().lock().unwrap_or_else(|e| e.into_inner()).get(&watch).cloned() {
|
||||
ui.label(RichText::new(st).size(FONT_XS).color(p.text3));
|
||||
}
|
||||
}
|
||||
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::Prompt { text } => {
|
||||
words(ui, "提示詞", text, "要交給下一步的話:下一步會把它當成「上一步的結果」。");
|
||||
}
|
||||
NodeKind::Material { files, note } => {
|
||||
field_label(ui, "檔案", p);
|
||||
let mut drop = None;
|
||||
for (k, f) in files.iter().enumerate() {
|
||||
ui.horizontal(|ui| {
|
||||
let name = f.rsplit(['/', '\\']).next().unwrap_or(f);
|
||||
ui.add(egui::Label::new(RichText::new(name).size(FONT_SM).color(p.text)).truncate()).on_hover_text(f);
|
||||
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
||||
if crate::icons::button(ui, Icon::Close, 14.0, p.text3, p.hover).on_hover_text(t("拿掉")).clicked() {
|
||||
drop = Some(k);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
if let Some(k) = drop {
|
||||
files.remove(k);
|
||||
}
|
||||
// (From the files the chats already have — they are on the brain — or this
|
||||
// computer's own, when this window is the brain.)
|
||||
let recent: Vec<(String, String)> = {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
self.state.bots.iter().flat_map(|b| b.messages.iter().rev().flat_map(|m| m.attachments.iter())).filter(|a| !a.path.is_empty() && seen.insert(a.path.clone())).take(30).map(|a| (a.name.clone(), a.path.clone())).collect()
|
||||
};
|
||||
ui.horizontal(|ui| {
|
||||
egui::ComboBox::from_id_salt(("wf-material", id)).selected_text(t("從聊天裡的檔案加…")).width(170.0).show_ui(ui, |ui| {
|
||||
if recent.is_empty() {
|
||||
ui.label(RichText::new(t("聊天裡還沒有檔案")).size(FONT_XS).color(p.text3));
|
||||
}
|
||||
for (name, path) in &recent {
|
||||
if ui.selectable_label(false, name).clicked() && !files.contains(path) {
|
||||
files.push(path.clone());
|
||||
}
|
||||
}
|
||||
});
|
||||
if !self.mir.on && ui.button(t("選檔案…")).clicked() {
|
||||
for f in crate::attach::pick_files() {
|
||||
let f = f.display().to_string();
|
||||
if !files.contains(&f) {
|
||||
files.push(f);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
words(ui, "說明(選填)", note, "例如:這是上週的週報,照它的格式寫。");
|
||||
}
|
||||
NodeKind::Step { bot, prompt } => {
|
||||
bot_pick(ui, bot, "wf-step-bot");
|
||||
words(ui, "要它做什麼", prompt, "例如:到 Threads 找今天熱門的 5 則討論,整理成清單。上一步的結果會一起給它。");
|
||||
words(ui, "告訴助手要做什麼", prompt, "例如:到 Threads 找今天熱門的 5 則討論,整理成清單。上一步的結果會一起給它。");
|
||||
}
|
||||
NodeKind::Llm { model, prompt, system } => {
|
||||
field_label(ui, "模型", p);
|
||||
let mut used: Vec<String> = self.state.bots.iter().map(|b| format!("{}:{}", b.provider.key(), b.model)).collect();
|
||||
used.sort();
|
||||
used.dedup();
|
||||
egui::ComboBox::from_id_salt(("wf-llm-model", id)).selected_text(if model.is_empty() { t("主要 Bot 的模型") } else { model.clone() }).width(ui.available_width() - 8.0).show_ui(ui, |ui| {
|
||||
ui.selectable_value(model, String::new(), t("主要 Bot 的模型"));
|
||||
for m in &used {
|
||||
ui.selectable_value(model, m.clone(), m);
|
||||
}
|
||||
});
|
||||
ui.add(egui::TextEdit::singleline(model).hint_text(t("或寫「供應商:模型」,例如 openai:gpt-5")).desired_width(f32::INFINITY));
|
||||
words(ui, "提示詞", prompt, "直接問模型,不用 Bot、不用工具。上一步的結果會接在後面。");
|
||||
field_label(ui, "系統提示詞(選填)", p);
|
||||
ui.add(egui::TextEdit::multiline(system).desired_rows(2).desired_width(f32::INFINITY));
|
||||
}
|
||||
NodeKind::Media { bot, prompt, video } => {
|
||||
if let Some(v) = segmented(ui, p, *video, &[(false, "圖片"), (true, "影片")]) {
|
||||
*video = v;
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
bot_pick(ui, bot, "wf-media-bot");
|
||||
words(ui, "要做出什麼", prompt, "例如:一張 1080×1080 的封面,標題「本週育兒話題」。Bot 用自己的工具做出檔案交給你。");
|
||||
}
|
||||
NodeKind::Approve { prompt } => {
|
||||
words(ui, "要你確認什麼", prompt, "例如:要把這篇貼出去嗎?(停在這裡等你按繼續或停止)");
|
||||
words(ui, "要你審批什麼", prompt, "例如:要把這篇貼出去嗎?(停在這裡等你按繼續或停止,並通知你)");
|
||||
}
|
||||
NodeKind::Check { bot, condition } => {
|
||||
bot_pick(ui, bot, "wf-check-bot");
|
||||
words(ui, "要做到什麼", condition, "例如:至少三則,每則都有連結。沒做到就停下來,說原因。");
|
||||
words(ui, "什麼情況走「是」", condition, "例如:至少三則,每則都有連結。");
|
||||
note(ui, "從卡片下面的「是」「否」各拉一條線;「否」沒接,不成立時就停在這裡並說原因。", p);
|
||||
}
|
||||
NodeKind::Deliver { bot } => {
|
||||
bot_pick(ui, bot, "wf-deliver-bot");
|
||||
hint(ui, "上一步的結果會放進這個 Bot 的聊天,你在那裡看。", p);
|
||||
NodeKind::Output { bot, notify, text } => {
|
||||
field_label(ui, "放進哪個聊天", p);
|
||||
let shown = if *bot == 0 { t("(不放進聊天)") } else { bots.iter().find(|b| b.0 == *bot).map(|b| b.1.clone()).unwrap_or_else(|| t("(選一個 Bot)")) };
|
||||
egui::ComboBox::from_id_salt(("wf-output-bot", id)).selected_text(shown).width(ui.available_width() - 8.0).show_ui(ui, |ui| {
|
||||
ui.selectable_value(bot, 0, t("(不放進聊天)"));
|
||||
for (b, n) in &bots {
|
||||
ui.selectable_value(bot, *b, n);
|
||||
}
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
ui.checkbox(notify, t("也通知我(這台電腦和手機)"));
|
||||
if *notify {
|
||||
words(ui, "通知寫什麼", text, "{結果} 會換成上一步結果的第一行");
|
||||
}
|
||||
}
|
||||
NodeKind::Notify { text } => {
|
||||
words(ui, "通知寫什麼", text, "{結果} 會換成上一步結果的第一行");
|
||||
NodeKind::Deliver { .. } | NodeKind::Notify { .. } => {}
|
||||
}
|
||||
// 試跑這一步: just this step, with what the step before it last gave.
|
||||
if matches!(kind, NodeKind::Step { .. } | NodeKind::Llm { .. } | NodeKind::Media { .. } | NodeKind::Check { .. }) {
|
||||
ui.add_space(8.0);
|
||||
let live = self.state.workflows[wi].live_run().is_some();
|
||||
if ui.add_enabled(!live, secondary_button("試跑這一步 ▷")).on_hover_text(t("只跑這一步,用前一步上次的結果;跑完看「上一次執行」")).clicked() {
|
||||
try_now = true;
|
||||
}
|
||||
}
|
||||
// What the last run did here.
|
||||
|
|
@ -1429,6 +1742,7 @@ impl App {
|
|||
StepState::Done => (t("完成"), p.up),
|
||||
StepState::Failed => (t("失敗"), p.danger),
|
||||
StepState::Running => (t("進行中…"), p.accent),
|
||||
StepState::Skipped => (t("沒走這條路(條件走了另一邊)"), p.text3),
|
||||
StepState::Waiting => (String::new(), p.text3),
|
||||
};
|
||||
ui.label(RichText::new(words).size(FONT_SM).color(col));
|
||||
|
|
@ -1447,7 +1761,7 @@ impl App {
|
|||
});
|
||||
});
|
||||
if kind != node.kind {
|
||||
let schedule_changed = matches!((&kind, &node.kind), (NodeKind::Trigger { schedule: a }, NodeKind::Trigger { schedule: b }) if a != b);
|
||||
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;
|
||||
}
|
||||
|
|
@ -1469,6 +1783,12 @@ impl App {
|
|||
self.wf_do(&ctx, wf, "run");
|
||||
self.wf.runs_open = true;
|
||||
}
|
||||
if try_now {
|
||||
let ctx = ui.ctx().clone();
|
||||
let wf = self.wf.current;
|
||||
self.wf_keep_version();
|
||||
self.wf_do(&ctx, wf, &format!("try:{id}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// A picked note: its colour, and taking it away.
|
||||
|
|
@ -1579,6 +1899,7 @@ impl App {
|
|||
StepState::Done => "✓",
|
||||
StepState::Failed => "✗",
|
||||
StepState::Running => "…",
|
||||
StepState::Skipped => "↷",
|
||||
StepState::Waiting => "·",
|
||||
};
|
||||
ui.horizontal(|ui| {
|
||||
|
|
@ -1606,7 +1927,7 @@ impl App {
|
|||
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 {
|
||||
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;
|
||||
|
|
@ -1644,7 +1965,37 @@ impl App {
|
|||
r.at = 3;
|
||||
r.state = RunState::Waiting;
|
||||
}
|
||||
self.state.workflows = vec![w];
|
||||
// A second one with the newer kinds: a GitHub trigger, 提示詞, LLM, 條件 with 是 and 否,
|
||||
// 圖片, 審批, 輸出 (ANYBOT_SHOT_TAB=2 shows it).
|
||||
let mut v = Workflow::new(2, "PR 合併後的發布貼文", 0);
|
||||
if let NodeKind::Trigger { event, .. } = &mut v.nodes[0].kind {
|
||||
*event = serde_json::from_value(serde_json::json!({"type": "github", "repo": "anybot/app", "events": ["pr_merged"]})).ok();
|
||||
}
|
||||
for (id, kind) in [
|
||||
(2, NodeKind::Prompt { text: "用溫暖的語氣,三句以內,結尾附連結。".into() }),
|
||||
(3, NodeKind::Llm { model: String::new(), prompt: "把合併的內容寫成一則發布貼文".into(), system: String::new() }),
|
||||
(4, NodeKind::Check { bot, condition: "是使用者看得到的改動".into() }),
|
||||
(5, NodeKind::Media { bot, prompt: "做一張 1080×1080 的封面".into(), video: false }),
|
||||
(6, NodeKind::Output { bot: 0, notify: true, text: "這次的合併不用發文".into() }),
|
||||
(7, NodeKind::Approve { prompt: "要發出去嗎?".into() }),
|
||||
(8, NodeKind::Output { bot, notify: true, text: "貼文好了:{結果}".into() }),
|
||||
] {
|
||||
v.nodes.push(Node { id, kind, x: 0.0, y: 0.0 });
|
||||
}
|
||||
for (a, b, port) in [(1, 2, ""), (2, 3, ""), (3, 4, ""), (4, 5, "yes"), (4, 6, "no"), (5, 7, ""), (7, 8, "")] {
|
||||
v.connect_port(a, b, port);
|
||||
}
|
||||
// (是 at the left, 否 at the right.)
|
||||
v.tidy();
|
||||
if let (Some(y5), Some(y6)) = (v.node(5).map(|n| n.x), v.node(6).map(|n| n.x)) {
|
||||
if y5 > y6 {
|
||||
for n in v.nodes.iter_mut().filter(|n| n.id == 5 || n.id == 6) {
|
||||
n.x = -n.x;
|
||||
}
|
||||
}
|
||||
}
|
||||
v.notes.push(Note { id: 9, kind: NoteKind::Sticky, x: -560.0, y: 560.0, w: 200.0, h: 160.0, text: "否:內部重構就不發".into(), author: "Jenny".into(), color: STICKY_COLOURS[1].into(), ..Default::default() });
|
||||
self.state.workflows = vec![w, v];
|
||||
self.wf.current = 1;
|
||||
self.wf.open = true;
|
||||
self.wf.chat_was = self.state.selected;
|
||||
|
|
|
|||
|
|
@ -88,6 +88,7 @@ pub enum Icon {
|
|||
Target,
|
||||
// 工作流 (the canvas and its tools).
|
||||
Workflow,
|
||||
Split,
|
||||
Hand,
|
||||
Pointer,
|
||||
StickyNote,
|
||||
|
|
@ -189,6 +190,7 @@ impl Icon {
|
|||
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::Split => include_str!("../icons/lucide/split.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"),
|
||||
|
|
|
|||
|
|
@ -194,7 +194,7 @@ mod tests {
|
|||
st.bots[0].routines = vec![daily, workdays, paused, event];
|
||||
let bot = st.bots[0].id;
|
||||
let mut w = crate::workflow::Workflow::new(1, "Threads 早報", created);
|
||||
if let NodeKind::Trigger { schedule } = &mut w.nodes[0].kind {
|
||||
if let NodeKind::Trigger { schedule, .. } = &mut w.nodes[0].kind {
|
||||
*schedule = Some(sched(serde_json::json!({"frequency": "daily", "time": "07:00", "timezone": tz})));
|
||||
}
|
||||
w.nodes.push(crate::workflow::Node { id: 2, kind: NodeKind::Step { bot, prompt: "找".into() }, x: 0.0, y: 190.0 });
|
||||
|
|
|
|||
410
src/workflow.rs
410
src/workflow.rs
|
|
@ -72,21 +72,61 @@ pub struct Node {
|
|||
#[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.
|
||||
/// 觸發器: where a run starts — by hand (立即執行/執行工作流), and also on a schedule or
|
||||
/// when something happens (Webhook, GitHub, Slack, a new mail…: the same event triggers a
|
||||
/// routine has, triggers.rs; what happened goes on to the first step).
|
||||
Trigger {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
schedule: Option<crate::routines::Schedule>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
event: Option<crate::triggers::Trigger>,
|
||||
},
|
||||
/// A bot does what it is asked (the last step's result goes with it).
|
||||
/// 提示詞: words handed on to the next step (written once, used by what follows).
|
||||
Prompt { text: String },
|
||||
/// 素材: files handed on to the next step (a bot's step gets them as attachments).
|
||||
Material {
|
||||
#[serde(default)]
|
||||
files: Vec<String>,
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
note: String,
|
||||
},
|
||||
/// 助手: a bot does what it is asked, with its own tools (the last step's result goes with it).
|
||||
Step { bot: u64, prompt: String },
|
||||
/// The person says go on or stop.
|
||||
/// LLM: a model answers directly — no bot, no tools. `model`: 「供應商:模型」, empty: the
|
||||
/// main bot's.
|
||||
Llm {
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
model: String,
|
||||
prompt: String,
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
system: String,
|
||||
},
|
||||
/// 圖片/影片: a bot makes one with its own tools and hands the file over.
|
||||
Media {
|
||||
bot: u64,
|
||||
prompt: String,
|
||||
#[serde(default)]
|
||||
video: bool,
|
||||
},
|
||||
/// 審批: 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.
|
||||
/// 條件: a bot reads the last result against a condition — 是 goes one way, 否 the other
|
||||
/// (with nothing on 否, the run stops there and says why).
|
||||
Check { bot: u64, condition: String },
|
||||
/// The last result goes into a bot's chat, for the person to read there.
|
||||
/// (Older 輸出 to a chat; made as Output now.)
|
||||
Deliver { bot: u64 },
|
||||
/// A notification (on this computer and the person's phones); 「{結果}」 is the last result.
|
||||
/// (Older 輸出 as a notification; made as Output now.)
|
||||
Notify { text: String },
|
||||
/// 輸出: the result into a bot's chat (`bot`, 0: none) and/or a notification (`notify`, the
|
||||
/// words in `text` — 「{結果}」 is the last result's first line).
|
||||
Output {
|
||||
#[serde(default)]
|
||||
bot: u64,
|
||||
#[serde(default)]
|
||||
notify: bool,
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
text: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl NodeKind {
|
||||
|
|
@ -94,21 +134,38 @@ impl NodeKind {
|
|||
pub fn label(&self) -> &'static str {
|
||||
match self {
|
||||
NodeKind::Trigger { .. } => "觸發器",
|
||||
NodeKind::Step { .. } => "Bot 步驟",
|
||||
NodeKind::Approve { .. } => "等你確認",
|
||||
NodeKind::Check { .. } => "檢查",
|
||||
NodeKind::Deliver { .. } => "交付",
|
||||
NodeKind::Notify { .. } => "通知你",
|
||||
NodeKind::Prompt { .. } => "提示詞",
|
||||
NodeKind::Material { .. } => "素材",
|
||||
NodeKind::Step { .. } => "助手",
|
||||
NodeKind::Llm { .. } => "LLM",
|
||||
NodeKind::Media { video: false, .. } => "圖片",
|
||||
NodeKind::Media { video: true, .. } => "影片",
|
||||
NodeKind::Approve { .. } => "審批",
|
||||
NodeKind::Check { .. } => "條件",
|
||||
NodeKind::Deliver { .. } | NodeKind::Notify { .. } | NodeKind::Output { .. } => "輸出",
|
||||
}
|
||||
}
|
||||
/// What starts it, in words (a trigger).
|
||||
pub fn trigger_words(schedule: &Option<crate::routines::Schedule>, event: &Option<crate::triggers::Trigger>) -> String {
|
||||
match (schedule, event) {
|
||||
(_, Some(e)) => e.describe(),
|
||||
(Some(s), None) => crate::routines::describe(s),
|
||||
(None, None) => "手動".into(),
|
||||
}
|
||||
}
|
||||
/// 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::Trigger { schedule, event } => Self::trigger_words(schedule, event),
|
||||
NodeKind::Prompt { text } => text.clone(),
|
||||
NodeKind::Material { files, note } => {
|
||||
let names: Vec<&str> = files.iter().map(|f| f.rsplit(['/', '\\']).next().unwrap_or(f)).collect();
|
||||
format!("{}{}", names.join("、"), if note.is_empty() { String::new() } else { format!("({note})") })
|
||||
}
|
||||
NodeKind::Step { prompt, .. } | NodeKind::Approve { prompt } | NodeKind::Llm { prompt, .. } | NodeKind::Media { prompt, .. } => prompt.clone(),
|
||||
NodeKind::Check { condition, .. } => condition.clone(),
|
||||
NodeKind::Deliver { .. } => String::new(),
|
||||
NodeKind::Notify { text } => text.clone(),
|
||||
NodeKind::Notify { text } | NodeKind::Output { text, .. } => text.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -117,6 +174,9 @@ impl NodeKind {
|
|||
pub struct Edge {
|
||||
pub from: u64,
|
||||
pub to: u64,
|
||||
/// Which way out of a 條件 it leaves: 「yes」 (是) or 「no」 (否); empty: the one way out.
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub port: String,
|
||||
}
|
||||
|
||||
/// Something drawn or written on the canvas.
|
||||
|
|
@ -181,6 +241,8 @@ pub enum StepState {
|
|||
Running,
|
||||
Done,
|
||||
Failed,
|
||||
/// On the way a 條件 didn't take.
|
||||
Skipped,
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
|
||||
|
|
@ -201,6 +263,10 @@ pub struct Run {
|
|||
/// Why it stopped or failed.
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub why: String,
|
||||
/// What it started with: what happened (an event trigger), or the input of a step tried on
|
||||
/// its own. The first step gets it as the last result.
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub input: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
|
||||
|
|
@ -216,6 +282,9 @@ pub struct RunStep {
|
|||
pub bot: u64,
|
||||
#[serde(default)]
|
||||
pub asked_at: i64,
|
||||
/// Files it hands on (素材; a bot's step attaches them).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub files: Vec<String>,
|
||||
}
|
||||
|
||||
impl Run {
|
||||
|
|
@ -229,21 +298,25 @@ impl Run {
|
|||
pub fn live(&self) -> bool {
|
||||
matches!(self.state, RunState::Running | RunState::Waiting)
|
||||
}
|
||||
/// The last result handed on (the latest step that gave one).
|
||||
/// The last result handed on (the latest step that gave one; else what the run started with).
|
||||
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()
|
||||
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_else(|| self.input.clone())
|
||||
}
|
||||
/// The files handed on (the latest 素材 before this step).
|
||||
pub fn last_files(&self) -> Vec<String> {
|
||||
self.order.iter().take(self.at).rev().find_map(|n| self.step_of(*n).filter(|s| s.state == StepState::Done && !s.files.is_empty()).map(|s| s.files.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() }
|
||||
Workflow { id, name: name.to_string(), nodes: vec![Node { id: 1, kind: NodeKind::Trigger { schedule: None, event: 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 })
|
||||
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)
|
||||
|
|
@ -309,12 +382,59 @@ impl Workflow {
|
|||
/// 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 {
|
||||
self.connect_port(from, to, "")
|
||||
}
|
||||
/// A line out of one way of a 條件 (「yes」 是, 「no」 否); the same rules.
|
||||
pub fn connect_port(&mut self, from: u64, to: u64, port: &str) -> 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 });
|
||||
// (Only a 條件 has two ways out.)
|
||||
let port = if self.node(from).is_some_and(|n| matches!(n.kind, NodeKind::Check { .. })) && matches!(port, "yes" | "no") { port } else { "" };
|
||||
self.edges.push(Edge { from, to, port: port.into() });
|
||||
true
|
||||
}
|
||||
/// A 條件 decided: the steps only the way it didn't take leads to (left out of this run).
|
||||
/// `None`: it said 否 and nothing is on 否 — the run stops there.
|
||||
pub fn branch_skips(&self, check: u64, passed: bool) -> Option<Vec<u64>> {
|
||||
let out: Vec<&Edge> = self.edges.iter().filter(|e| e.from == check).collect();
|
||||
let yes = |e: &&Edge| e.port != "no";
|
||||
let (taken, other): (Vec<&Edge>, Vec<&Edge>) = out.into_iter().partition(|e| yes(e) == passed);
|
||||
if !passed && taken.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let reach = |starts: Vec<u64>| {
|
||||
let mut seen = starts;
|
||||
let mut i = 0;
|
||||
while i < seen.len() {
|
||||
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;
|
||||
}
|
||||
seen
|
||||
};
|
||||
let keep = reach(taken.iter().map(|e| e.to).collect());
|
||||
Some(reach(other.iter().map(|e| e.to).collect()).into_iter().filter(|n| !keep.contains(n) && *n != check).collect())
|
||||
}
|
||||
/// A run of one step on its own (試跑這一步), with `input` as the last result.
|
||||
pub fn start_single(&mut self, node: u64, input: &str, now: i64) -> u64 {
|
||||
let id = self.runs.iter().map(|r| r.id).max().unwrap_or(0) + 1;
|
||||
let steps = vec![RunStep { node, state: StepState::Waiting, output: String::new(), bot: 0, asked_at: 0, files: vec![] }];
|
||||
self.runs.push(Run { id, started: now, ended: None, state: RunState::Running, by: "試跑這一步".into(), order: vec![node], at: 0, steps, why: String::new(), input: input.to_string() });
|
||||
if self.runs.len() > RUNS_KEPT {
|
||||
self.runs.remove(0);
|
||||
}
|
||||
id
|
||||
}
|
||||
/// What the step before `node` last gave (the input of a step tried on its own).
|
||||
pub fn input_for(&self, node: u64) -> String {
|
||||
let parents: Vec<u64> = self.edges.iter().filter(|e| e.to == node).map(|e| e.from).collect();
|
||||
self.runs.iter().rev().find_map(|r| parents.iter().find_map(|p| r.step_of(*p).filter(|s| s.state == StepState::Done && !s.output.is_empty()).map(|s| s.output.clone()))).unwrap_or_default()
|
||||
}
|
||||
fn reaches(&self, from: u64, to: u64) -> bool {
|
||||
let mut seen = vec![from];
|
||||
let mut i = 0;
|
||||
|
|
@ -434,8 +554,8 @@ impl Workflow {
|
|||
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() };
|
||||
let steps = order.iter().map(|n| RunStep { node: *n, state: StepState::Waiting, output: String::new(), bot: 0, asked_at: 0, files: vec![] }).collect();
|
||||
let mut run = Run { id, started: now, ended: None, state: RunState::Running, by: by.to_string(), order, at: 0, steps, why: String::new(), input: String::new() };
|
||||
if let Some(s) = run.steps.first_mut() {
|
||||
s.state = StepState::Done;
|
||||
}
|
||||
|
|
@ -462,6 +582,21 @@ pub fn step_message(wf: &str, k: usize, of: usize, prompt: &str, last: &str) ->
|
|||
s
|
||||
}
|
||||
|
||||
/// What a bot is asked in a 圖片/影片 step: make it with its own tools, hand the file over.
|
||||
pub fn media_message(wf: &str, k: usize, of: usize, prompt: &str, last: &str, video: bool) -> String {
|
||||
let (what, one) = if video { ("影片", "一段影片") } else { ("圖片", "一張圖") };
|
||||
let mut s = format!("[工作流「{wf}」第 {k}/{of} 步・{what}]做{one}:{}\n用你自己的工具做出檔案,用 send_file 交出來;最後一句寫檔名。", prompt.trim());
|
||||
if !last.trim().is_empty() {
|
||||
s.push_str(&format!("\n\n上一步的結果:\n{}", clip(last.trim(), HANDED_ON_CHARS)));
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// What a model is asked in an LLM step: the prompt, and the last result after it.
|
||||
pub fn llm_message(prompt: &str, last: &str) -> String {
|
||||
if last.trim().is_empty() { prompt.trim().to_string() } else { format!("{}\n\n上一步的結果:\n{}", prompt.trim(), clip(last.trim(), HANDED_ON_CHARS)) }
|
||||
}
|
||||
|
||||
/// What a bot is asked in a 檢查 step.
|
||||
pub fn check_message(wf: &str, k: usize, of: usize, condition: &str, last: &str) -> String {
|
||||
format!(
|
||||
|
|
@ -500,33 +635,55 @@ fn clip(s: &str, max: usize) -> String {
|
|||
out
|
||||
}
|
||||
|
||||
/// A workflow's event trigger is watched as routine `WATCH_BASE + its id` (triggers.rs keys its
|
||||
/// watchers, statuses and webhook addresses by a routine's id; routines' ids stay far below).
|
||||
pub const WATCH_BASE: u64 = 1_000_000;
|
||||
|
||||
/// A new webhook secret (24 hex characters).
|
||||
pub fn new_secret() -> String {
|
||||
use std::hash::{BuildHasher, Hasher};
|
||||
let mut s = String::new();
|
||||
for _ in 0..2 {
|
||||
let mut h = std::collections::hash_map::RandomState::new().build_hasher();
|
||||
h.write_u128(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0));
|
||||
s.push_str(&format!("{:012x}", h.finish() & 0xffff_ffff_ffff));
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// 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."},
|
||||
"kind": {"type": "string", "enum": ["prompt", "material", "llm", "step", "image", "video", "condition", "approve", "output"], "description": "Inputs — prompt: words handed on (`text`); material: files handed on (`files`: paths from the chat's attachments). Steps — llm: a model answers `prompt` directly, no bot, no tools (`model` 「供應商:模型」, empty: the main bot's; `system` optional); step (助手): a bot does `prompt` with its tools; image / video: a bot makes one and hands the file over. Flow — condition (條件): a bot reads the last result against `condition`; 是 goes one way, 否 the other (lines from it carry a port; with nothing on 否 the run stops when it doesn't hold); approve (審批): the person says go on or stop (`prompt` is the question); output (輸出): the last result into `bot`'s chat and/or a notification (`notify`: true, `text` with 「{結果}」 for the last result's first line). Each step's result goes on to the next."},
|
||||
"bot": {"type": "string", "description": "step, image, video, condition, output: the bot's name; empty = you. output without a bot and with notify only: no chat."},
|
||||
"prompt": {"type": "string"},
|
||||
"condition": {"type": "string"},
|
||||
"text": {"type": "string"},
|
||||
"files": {"type": "array", "items": {"type": "string"}},
|
||||
"model": {"type": "string"},
|
||||
"system": {"type": "string"},
|
||||
"notify": {"type": "boolean"},
|
||||
"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)."},
|
||||
"port": {"type": "string", "enum": ["yes", "no"], "description": "When `after` is a condition: which way — yes (是) or no (否)."},
|
||||
"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.",
|
||||
"description": "Make, change, look at and run the person's 工作流 (workflows): a canvas of cards joined by lines — a trigger (by hand; also on a schedule, or when something happens: Webhook, GitHub, Slack, mail… — the same `trigger` as create_routine), then inputs (提示詞, 素材), steps (LLM, 助手, 圖片, 影片) and flow (條件 with 是/否, 審批, 輸出); 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 decision, a confirmation 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)."},
|
||||
"trigger": crate::triggers::schema(),
|
||||
"manual_only": {"type": "boolean", "description": "edit: take the schedule and the event trigger 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"]}},
|
||||
"step": {"type": "integer"}, "bot": {"type": "string"}, "prompt": {"type": "string"}, "condition": {"type": "string"}, "text": {"type": "string"}, "files": {"type": "array", "items": {"type": "string"}}, "model": {"type": "string"}, "system": {"type": "string"}, "notify": {"type": "boolean"}}, "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]."},
|
||||
"connect": {"type": "array", "items": {"type": "array"}, "description": "edit: lines to add, each [from, to], or [from, to, \"yes\"|\"no\"] out of a condition."},
|
||||
"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"]}},
|
||||
|
|
@ -612,6 +769,9 @@ pub fn tool(wfs: &mut Vec<Workflow>, who: &Who, v: &Value, showing: Option<u64>,
|
|||
if let Some(s) = v.get("schedule").filter(|s| !s.is_null()) {
|
||||
set_schedule(&mut w, s, who.timezone, now)?;
|
||||
}
|
||||
if let Some(t) = v.get("trigger").filter(|t| !t.is_null()) {
|
||||
set_event(&mut w, t)?;
|
||||
}
|
||||
add_steps(&mut w, who, v, &mut touched)?;
|
||||
w.tidy();
|
||||
add_notes(&mut w, who, v, &mut touched)?;
|
||||
|
|
@ -665,11 +825,20 @@ pub fn tool(wfs: &mut Vec<Workflow>, who: &Who, v: &Value, showing: Option<u64>,
|
|||
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) {
|
||||
if let Some(NodeKind::Trigger { schedule, event }) = w.trigger().map(|t| t.id).and_then(|t| w.node_mut(t)).map(|n| &mut n.kind) {
|
||||
*schedule = None;
|
||||
*event = None;
|
||||
}
|
||||
w.next_run = None;
|
||||
said.push("拿掉排程(只在按的時候跑)".into());
|
||||
said.push("拿掉排程和觸發(只在按的時候跑)".into());
|
||||
}
|
||||
if let Some(t) = v.get("trigger").filter(|t| !t.is_null()) {
|
||||
if let Err(e) = set_event(w, t) {
|
||||
*w = before;
|
||||
return Err(e);
|
||||
}
|
||||
touched.push(w.trigger().map(|t| t.id).unwrap_or(1));
|
||||
said.push(format!("觸發改成{}", w.trigger().map(|n| n.kind.words()).unwrap_or_default()));
|
||||
}
|
||||
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 { .. })) {
|
||||
|
|
@ -748,9 +917,52 @@ pub fn tool(wfs: &mut Vec<Workflow>, who: &Who, v: &Value, showing: Option<u64>,
|
|||
*text = t;
|
||||
}
|
||||
}
|
||||
NodeKind::Prompt { text } => {
|
||||
if let Some(t) = txt("text").or_else(|| txt("prompt")) {
|
||||
*text = t;
|
||||
}
|
||||
}
|
||||
NodeKind::Material { files, note } => {
|
||||
if let Some(f) = c["files"].as_array() {
|
||||
*files = f.iter().filter_map(|x| x.as_str().map(str::to_string)).collect();
|
||||
}
|
||||
if let Some(t) = txt("text") {
|
||||
*note = t;
|
||||
}
|
||||
}
|
||||
NodeKind::Llm { model, prompt, system } => {
|
||||
if let Some(t) = txt("prompt") {
|
||||
*prompt = t;
|
||||
}
|
||||
if let Some(t) = txt("model") {
|
||||
*model = t;
|
||||
}
|
||||
if let Some(t) = txt("system") {
|
||||
*system = t;
|
||||
}
|
||||
}
|
||||
NodeKind::Media { bot: b, prompt, .. } => {
|
||||
if let Some(x) = bot {
|
||||
*b = x;
|
||||
}
|
||||
if let Some(t) = txt("prompt") {
|
||||
*prompt = t;
|
||||
}
|
||||
}
|
||||
NodeKind::Output { bot: b, notify, text } => {
|
||||
if let Some(x) = bot {
|
||||
*b = x;
|
||||
}
|
||||
if let Some(x) = c["notify"].as_bool() {
|
||||
*notify = x;
|
||||
}
|
||||
if let Some(t) = txt("text") {
|
||||
*text = t;
|
||||
}
|
||||
}
|
||||
NodeKind::Trigger { .. } => {
|
||||
*w = before;
|
||||
return Err("觸發器用 schedule 或 manual_only 改".into());
|
||||
return Err("觸發器用 schedule、trigger 或 manual_only 改".into());
|
||||
}
|
||||
}
|
||||
touched.push(sid);
|
||||
|
|
@ -770,7 +982,7 @@ pub fn tool(wfs: &mut Vec<Workflow>, who: &Who, v: &Value, showing: Option<u64>,
|
|||
*w = before;
|
||||
return Err(format!("沒有 #{} 這一步(show 看有哪些)", if w.node(a).is_none() { a } else { b }));
|
||||
}
|
||||
if !w.connect(a, b) {
|
||||
if !w.connect_port(a, b, pair[2].as_str().unwrap_or("")) {
|
||||
*w = before;
|
||||
return Err(format!("#{a}→#{b} 連不起來:已經有了、連回觸發器,或會繞成一圈"));
|
||||
}
|
||||
|
|
@ -808,19 +1020,48 @@ pub fn tool(wfs: &mut Vec<Workflow>, who: &Who, v: &Value, showing: Option<u64>,
|
|||
/// 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 starts = match w.trigger().map(|t| &t.kind) {
|
||||
Some(NodeKind::Trigger { schedule, event }) if schedule.is_some() || event.is_some() => format!("{},也可以手動", NodeKind::trigger_words(schedule, event)),
|
||||
_ => "手動執行".into(),
|
||||
};
|
||||
let mut out = vec![format!("工作流 #{}「{}」:{starts}", w.id, w.name)];
|
||||
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)),
|
||||
NodeKind::Prompt { text } => format!("提示詞:{}", one_line(text)),
|
||||
NodeKind::Material { .. } => format!("素材:{}", one_line(&n.kind.words())),
|
||||
NodeKind::Step { bot, prompt } => format!("助手({}):{}", who.name(*bot), one_line(prompt)),
|
||||
NodeKind::Llm { model, prompt, .. } => format!("LLM({}):{}", if model.is_empty() { "主要 Bot 的模型" } else { model }, one_line(prompt)),
|
||||
NodeKind::Media { bot, prompt, video } => format!("{}({}):{}", if *video { "影片" } else { "圖片" }, 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)),
|
||||
NodeKind::Output { bot, notify, text } => {
|
||||
let mut ways = vec![];
|
||||
if *bot != 0 {
|
||||
ways.push(format!("放進「{}」的聊天", who.name(*bot)));
|
||||
}
|
||||
if *notify {
|
||||
ways.push(format!("通知你「{}」", one_line(if text.is_empty() { "{結果}" } else { text })));
|
||||
}
|
||||
format!("輸出:{}", if ways.is_empty() { "(還沒選放哪裡)".into() } else { ways.join("、") })
|
||||
}
|
||||
};
|
||||
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::<Vec<_>>().join("、")) }
|
||||
let outs: Vec<&Edge> = w.edges.iter().filter(|e| e.from == n.id).collect();
|
||||
let to = |port: &str| outs.iter().filter(|e| e.port == port).map(|e| format!("#{}", e.to)).collect::<Vec<_>>().join("、");
|
||||
let next = if matches!(n.kind, NodeKind::Check { .. }) {
|
||||
let (yes, no) = (outs.iter().filter(|e| e.port != "no").map(|e| format!("#{}", e.to)).collect::<Vec<_>>().join("、"), to("no"));
|
||||
match (yes.is_empty(), no.is_empty()) {
|
||||
(true, true) => String::new(),
|
||||
(false, true) => yes,
|
||||
_ => format!("是:{};否:{}", if yes.is_empty() { "(停)".into() } else { yes }, no),
|
||||
}
|
||||
} else {
|
||||
to("")
|
||||
};
|
||||
if next.is_empty() { format!("#{} {what}", n.id) } else { format!("#{} {what} → {next}", n.id) }
|
||||
};
|
||||
for id in &order {
|
||||
if let Some(n) = w.node(*id) {
|
||||
|
|
@ -899,6 +1140,17 @@ fn one_line(s: &str) -> String {
|
|||
clip(&s.split_whitespace().collect::<Vec<_>>().join(" "), 80)
|
||||
}
|
||||
|
||||
/// An event trigger (the same as a routine's): run when it happens; the schedule goes.
|
||||
fn set_event(w: &mut Workflow, raw: &Value) -> Result<(), String> {
|
||||
let t = serde_json::from_value::<crate::triggers::Trigger>(raw.clone()).map_err(|e| e.to_string()).and_then(|t| t.validate().map(|_| t)).map_err(|e| format!("觸發條件有問題:{e}"))?;
|
||||
if let Some(NodeKind::Trigger { schedule, event }) = w.trigger().map(|t| t.id).and_then(|t| w.node_mut(t)).map(|n| &mut n.kind) {
|
||||
*schedule = None;
|
||||
*event = Some(t);
|
||||
}
|
||||
w.next_run = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_schedule(w: &mut Workflow, raw: &Value, tz: &str, now: i64) -> Result<(), String> {
|
||||
let mut raw = raw.clone();
|
||||
if raw.get("timezone").and_then(Value::as_str).unwrap_or("").is_empty() {
|
||||
|
|
@ -910,8 +1162,9 @@ fn set_schedule(w: &mut Workflow, raw: &Value, tz: &str, now: i64) -> Result<(),
|
|||
if s.once {
|
||||
w.created_at = now;
|
||||
}
|
||||
if let Some(NodeKind::Trigger { schedule }) = w.trigger().map(|t| t.id).and_then(|t| w.node_mut(t)).map(|n| &mut n.kind) {
|
||||
if let Some(NodeKind::Trigger { schedule, event }) = w.trigger().map(|t| t.id).and_then(|t| w.node_mut(t)).map(|n| &mut n.kind) {
|
||||
*schedule = Some(s);
|
||||
*event = None;
|
||||
}
|
||||
w.next_run = None;
|
||||
Ok(())
|
||||
|
|
@ -922,24 +1175,50 @@ fn add_steps(w: &mut Workflow, who: &Who, v: &Value, touched: &mut Vec<u64>) ->
|
|||
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" | "" => {
|
||||
"step" | "assistant" | "" => {
|
||||
let prompt = txt("prompt");
|
||||
if prompt.is_empty() {
|
||||
return Err("Bot 步驟要有 prompt(要它做什麼)".into());
|
||||
return Err("助手要有 prompt(要它做什麼)".into());
|
||||
}
|
||||
NodeKind::Step { bot: who.bot(st["bot"].as_str())?, prompt }
|
||||
}
|
||||
"prompt" => {
|
||||
let text = Some(txt("text")).filter(|t| !t.is_empty()).unwrap_or_else(|| txt("prompt"));
|
||||
if text.is_empty() {
|
||||
return Err("提示詞要有 text".into());
|
||||
}
|
||||
NodeKind::Prompt { text }
|
||||
}
|
||||
"material" => NodeKind::Material { files: st["files"].as_array().into_iter().flatten().filter_map(|x| x.as_str().map(str::to_string)).collect(), note: txt("text") },
|
||||
"llm" => {
|
||||
let prompt = txt("prompt");
|
||||
if prompt.is_empty() {
|
||||
return Err("LLM 要有 prompt".into());
|
||||
}
|
||||
NodeKind::Llm { model: txt("model"), prompt, system: txt("system") }
|
||||
}
|
||||
"image" | "video" => {
|
||||
let prompt = txt("prompt");
|
||||
if prompt.is_empty() {
|
||||
return Err("圖片/影片要有 prompt(要做出什麼)".into());
|
||||
}
|
||||
NodeKind::Media { bot: who.bot(st["bot"].as_str())?, prompt, video: st["kind"].as_str() == Some("video") }
|
||||
}
|
||||
"approve" => NodeKind::Approve { prompt: Some(txt("prompt")).filter(|p| !p.is_empty()).unwrap_or_else(|| "要繼續嗎?".into()) },
|
||||
"check" => {
|
||||
"condition" | "check" => {
|
||||
let condition = Some(txt("condition")).filter(|c| !c.is_empty()).unwrap_or_else(|| txt("prompt"));
|
||||
if condition.is_empty() {
|
||||
return Err("檢查要有 condition(要做到什麼才算通過)".into());
|
||||
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")),
|
||||
// (交付 and 通知你 are one 輸出 now.)
|
||||
"output" | "deliver" | "notify" => {
|
||||
let to_chat = st["kind"].as_str() != Some("notify") && (st["bot"].is_string() || st["kind"].as_str() == Some("deliver") || st["notify"].as_bool() != Some(true));
|
||||
let notify = st["kind"].as_str() == Some("notify") || st["notify"].as_bool() == Some(true);
|
||||
NodeKind::Output { bot: if to_chat { who.bot(st["bot"].as_str())? } else { 0 }, notify, text: Some(txt("text")).filter(|t| !t.is_empty()).unwrap_or_else(|| if notify { "{結果}".into() } else { String::new() }) }
|
||||
}
|
||||
other => return Err(format!("不認得的步驟種類「{other}」:prompt、material、llm、step、image、video、condition、approve 或 output")),
|
||||
};
|
||||
let after = match st["after"].as_u64() {
|
||||
Some(a) if w.node(a).is_some() => a,
|
||||
|
|
@ -960,7 +1239,7 @@ fn add_steps(w: &mut Workflow, who: &Who, v: &Value, touched: &mut Vec<u64>) ->
|
|||
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 });
|
||||
w.edges.push(Edge { from: after, to: id, port: st["port"].as_str().filter(|p| matches!(*p, "yes" | "no")).filter(|_| w.node(after).is_some_and(|n| matches!(n.kind, NodeKind::Check { .. }))).unwrap_or("").into() });
|
||||
if !branch {
|
||||
for o in outs {
|
||||
w.connect(id, o);
|
||||
|
|
@ -1028,7 +1307,7 @@ mod tests {
|
|||
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「週末改十點?」(研究助理)"]
|
||||
for words in ["工作流 #1「Threads 早報」:每天 09:00", "#2 助手(研究助理):找 5 則熱門育兒討論 → #3", "#3 條件(寫作夥伴):每則都有連結 → #4", "#5 輸出:通知你「早報好了:{結果}」", "便利貼:#6「週末改十點?」(研究助理)"]
|
||||
{
|
||||
assert!(t.text.contains(words), "{words}\n{}", t.text);
|
||||
}
|
||||
|
|
@ -1153,6 +1432,39 @@ mod tests {
|
|||
assert!(!wfs[0].mark_interrupted(5_000));
|
||||
}
|
||||
|
||||
/// The new kinds from the chat: 提示詞、素材、LLM、圖片、條件 with 是/否、輸出; an event
|
||||
/// trigger (the same as a routine's). A 條件 decides which way: the other way's steps are
|
||||
/// left out; 否 with nothing on it stops the run.
|
||||
#[test]
|
||||
fn a_bot_builds_branches_and_the_new_kinds() {
|
||||
let mut wfs = vec![];
|
||||
let t = call(
|
||||
&mut wfs,
|
||||
json!({"action": "create", "name": "審稿", "trigger": {"type": "webhook", "secret": "s3cret-123"},
|
||||
"steps": [{"kind": "prompt", "text": "寫一段開場"}, {"kind": "llm", "prompt": "潤稿", "model": "openai:gpt-5"}, {"kind": "condition", "condition": "超過 100 字"}]}),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(t.text.contains("工作流 #1「審稿」:Webhook 呼叫,也可以手動"), "{}", t.text);
|
||||
// 是: a picture; 否: a notification.
|
||||
call(&mut wfs, json!({"action": "edit", "steps": [{"kind": "image", "prompt": "做封面", "after": 4, "port": "yes", "branch": true}, {"kind": "output", "notify": true, "text": "太短了", "after": 4, "port": "no", "branch": true}]})).unwrap();
|
||||
let w = &wfs[0];
|
||||
assert!(matches!(w.node(5).map(|n| &n.kind), Some(NodeKind::Media { video: false, .. })));
|
||||
assert!(matches!(w.node(6).map(|n| &n.kind), Some(NodeKind::Output { bot: 0, notify: true, .. })));
|
||||
assert_eq!(w.edges.iter().filter(|e| e.from == 4).map(|e| (e.to, e.port.as_str())).collect::<Vec<_>>(), vec![(5, "yes"), (6, "no")]);
|
||||
assert_eq!((w.branch_skips(4, true), w.branch_skips(4, false)), (Some(vec![6]), Some(vec![5])));
|
||||
let shown = call(&mut wfs, json!({"action": "show"})).unwrap().text;
|
||||
assert!(shown.contains("#4 條件(研究助理):超過 100 字 → 是:#5;否:#6") && shown.contains("#2 提示詞:寫一段開場") && shown.contains("#3 LLM(openai:gpt-5):潤稿"), "{shown}");
|
||||
// Without 否: it stops there.
|
||||
call(&mut wfs, json!({"action": "edit", "remove": [6]})).unwrap();
|
||||
assert_eq!(wfs[0].branch_skips(4, false), None);
|
||||
// A port only out of a 條件; a wrong trigger leaves nothing.
|
||||
assert!(!wfs[0].connect_port(2, 5, "no") || wfs[0].edges.iter().any(|e| e.from == 2 && e.port.is_empty()));
|
||||
assert!(call(&mut wfs, json!({"action": "edit", "trigger": {"type": "webhook", "secret": "x"}})).is_err());
|
||||
// 交付 and 通知你 asked by their old names are one 輸出.
|
||||
call(&mut wfs, json!({"action": "edit", "steps": [{"kind": "deliver"}, {"kind": "notify", "text": "好了"}]})).unwrap();
|
||||
assert!(wfs[0].nodes.iter().rev().take(2).all(|n| matches!(n.kind, NodeKind::Output { .. })));
|
||||
}
|
||||
|
||||
fn wf() -> Workflow {
|
||||
let mut w = Workflow::new(1, "早報", 100);
|
||||
for (id, x, y, kind) in [
|
||||
|
|
|
|||
Loading…
Reference in New Issue