diff --git a/FEATURES.md b/FEATURES.md index 5c5bca1..6a923be 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -1952,7 +1952,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 執行:照線從觸發器往下(一張接到好幾張時上面的先、再左邊);觸發器後面還沒有步驟時不跑,說「這個工作流還沒有步驟,沒有執行:…」(以前馬上記一次「完成」,日程、執行紀錄、Bot 看到的「最近一次」都是假的)。Bot 步驟是那個 Bot 聊天裡的一則「[工作流「名稱」第 k/n 步]…」加上一步的結果(聊天裡泡泡上面一行小標、淡色泡泡,結果只顯示前三行,滑過看全文;以前看起來像你自己打的),它這一輪最後的回答交給下一步(它正忙就排在後面)。檢查回「通過」才往下。等你確認在畫布上方一條「繼續/停止」,並發通知。一次只跑一個,排程到了自動跑;卡片標完成、進行中、等你確認、失敗;執行紀錄留 20 次。 - 版本歷史:停手 20 秒、關畫布、每次執行前、Bot 每次改之前各留一版,最多 30 版,點一版就還原。 - 在聊天裡做:跟 Bot 用一般的話說要什麼流程(「每天早上 9 點去 Threads 找 5 則熱門育兒討論,整理好先問我,我說可以再傳給我」),Bot 用 `workflow` 工具建立、看、改(加步驟、改內容、刪步驟、連線、貼便利貼、整理排版)、執行、停止、刪除(刪除先問)。你看著那個 Bot 的聊天時,畫布自動開在聊天旁邊(視窗夠寬時),它改到的卡片和便利貼亮一下,跑出畫面就縮到看得到全部;Bot 做的排成一欄,插在中間時後面的往下移,你自己排過的不重排。旁邊的聊天跟著側邊欄選的 Bot 換。 -- 手機沒有畫布:在聊天裡請 Bot 做、改、跑,它用文字說工作流的樣子;「等你確認」的通知會到手機,按「繼續」要在電腦上。螢幕電腦(看著帳號裡大腦的那台)一樣能新增、修改、刪除、畫和註解,執行、停止、繼續交給大腦做;執行紀錄以大腦的為準。螢幕上的修改一張卡片、一個欄位地傳給大腦(舊版大腦收到的是整個工作流,跟以前一樣):你在螢幕上搬卡片、改名,Bot 同時在大腦上加的步驟和線都留著;兩邊同時新建、編號一樣的工作流各留一個,螢幕那個換新編號。同一張卡片兩邊都改了,後到的為準;線整組一起傳,兩邊同時拉線時後到的為準。 +- 手機沒有畫布(改要在電腦上或請 Bot 改),但首頁上面一排有「工作流」:每個一張卡(名字、觸發和下次、步驟數、這次或最近一次怎麼了、右邊 ▷ 執行/■ 停止),等你確認時卡下面直接有「繼續」「停止」;點進去看步驟由上到下和每一步這次(或最近一次)的狀態、Bot 的結果前三行、最近 10 次執行紀錄(點一次看每一步)。跑的時候每 3 秒更新。手機按的執行算「手動」,不上日程。大腦的路是 `api/act/workflows`(讀)和 `api/act/workflow`(run/stop/go/halt);同一個網路直接連的手機也可以(不放寬任何權限)。螢幕電腦(看著帳號裡大腦的那台)一樣能新增、修改、刪除、畫和註解,執行、停止、繼續交給大腦做;執行紀錄以大腦的為準。螢幕上的修改一張卡片、一個欄位地傳給大腦(舊版大腦收到的是整個工作流,跟以前一樣):你在螢幕上搬卡片、改名,Bot 同時在大腦上加的步驟和線都留著;兩邊同時新建、編號一樣的工作流各留一個,螢幕那個換新編號。同一張卡片兩邊都改了,後到的為準;線整組一起傳,兩邊同時拉線時後到的為準。 - 側邊欄最左邊一條直欄(照 OpenBot 的排版):上面「聊天、工作流、日程、任務、所有檔案」,下面「傳送、市集、設定」,現在在哪一個就亮哪一個,滑過寫名字;從 Mac 視窗左上角的紅黃綠按鈕下面開始。Bot 那一欄最上面只剩「搜尋」「+」,最下面是你的名字和 Bot 在哪一台(整個寬度)。以前這些全擠在最上面一排,側邊欄一窄就被切掉、或被紅黃綠按鈕壓到。 ### 日程(側邊欄最左邊那一欄的日曆圖示) diff --git a/docs/feature-map/workflow.md b/docs/feature-map/workflow.md index 6fdaa2f..66bf1a9 100644 --- a/docs/feature-map/workflow.md +++ b/docs/feature-map/workflow.md @@ -11,11 +11,12 @@ - `workflow-chat` 聊出來:在聊天裡請 Bot 做工作流,它用 `workflow` 工具建立、看、改(加步驟、改內容、刪步驟、連線、貼便利貼、整理排版)、執行、停止、刪除(刪除先問你)。你正看著那個 Bot 的聊天時(只有它),畫布自動開在聊天旁邊,跳到那個工作流,它改到的卡片和便利貼亮一下;跑出畫面就自動縮放到看得到全部。Bot 做的排成一欄,插在中間時後面的往下移;你自己排過的不重排。要刪除時,允許卡片寫的就是會刪的那一個(沒指定時是畫布上開著的)。旁邊的聊天跟著側邊欄選的 Bot 換。Bot 知道有哪些工作流(說明裡列著),你在畫布旁邊打的每一則都帶著「開著工作流「X」(#1)的畫布」,所以「這個」「畫布上」它知道是哪一個。 - `workflow-versions` 版本歷史:改完停手 20 秒、關掉畫布、每次執行前、Bot 每次改之前,各留一版(一樣的不重複留),最多 30 版;選單 › 版本歷史點一版就還原,還原前先留目前的樣子。 +- `workflow-phone` 手機的工作流:每個一張卡(名字、觸發和下次、幾個步驟、這次或最近一次怎麼了,右邊 ▷ 執行/■ 停止),等你確認時卡下面一條「等你確認:…」和「繼續」「停止」;點卡片看步驟由上到下(每一步這次或最近一次:完成、進行中、等你確認、失敗、略過,還沒到的變淡,Bot 的結果前三行)和最近 10 次執行紀錄。手機按的執行算「手動」,不上日程。跑的時候每 3 秒更新。 ## 使用者怎麼到 - 側邊欄最左邊那一欄第二個(流程圖示,滑過寫「工作流」),在聊天和日程中間;再按一次、按那一欄的「聊天」、或左上「‹ 聊天」都回到聊天。 - 在 Bot 的聊天裡說「幫我做一個…的工作流」:畫布開在聊天旁邊(視窗夠寬時;右上「聊天」收起或放回)。 -- 手機沒有畫布:在聊天裡請 Bot 做、改、跑,它用文字說工作流長怎樣;「等你確認」的通知會到手機,但要在電腦上按「繼續」。 +- 手機:首頁上面一排的「工作流」(`workflow-phone`)。手機沒有畫布,改要在電腦上或請 Bot 改。 ## 怎麼操作(verify-anybot) @@ -32,6 +33,7 @@ - **在旁邊聊、畫布跟著變**(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。 +- **手機的工作流**(covers `workflow-phone`、`workflow-run`):接著上面建好的早報(檢查指定「通過」)。指令:`$CTL model-reply '步・檢查' '通過' && $CTL phone click '[data-back]' && $CTL phone click '#quick [data-q="workflows"]' && $CTL phone wait '[data-wfopen="1"]' && $CTL phone click '[data-wfdo="run"]' && $CTL phone wait '.wf-ask' 150 && $CTL phone click '[data-wfopen="1"] .k' && $CTL phone wait '.wf-steps' && $CTL phone shot wf-phone && $CTL phone click '.wf-ask [data-wfdo="go"]' && $CTL wait-api '/api/state?since=0' 'true' 2 && $CTL state '.workflows[0].runs[-1] | {state, by}'`。看到:卡上「等你確認」和「繼續」「停止」;步驟觸發器、助手、條件「完成」,審批黃色「等你確認」,輸出變淡;按繼續後最後一次 state done、by「手動」。 - 自動測試:`cargo test workflow`、`cargo test layout_audit::`(「工作流」四景)、`cargo test theme::`。 ## 陷阱 diff --git a/mobile/index.html b/mobile/index.html index 3b0b2e4..681d3ba 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -580,6 +580,33 @@ textarea.field{min-height:96px;line-height:1.5} .tools .btn.once{background:color-mix(in srgb,var(--accent) 18%,transparent);color:var(--accent-ink)} .tools .btn.lock{background:var(--accent);color:var(--on-color)} .tools .btn.on{background:var(--primary);color:var(--on-primary)} +/* 工作流: a card each (run / stop at the right, the 等你確認 under it); one opened: its steps as a + line from top to bottom, each with how this run (or the last) went there. */ +.wf-card{padding:12px 16px;border-bottom:1px solid var(--line2);cursor:pointer} +.wf-card:last-child{border-bottom:0} +.wf-row{display:flex;align-items:center;gap:12px} +.wf-row .mid{flex:1;min-width:0}.wf-row .k{font-size:var(--fs-ui);font-weight:500}.wf-row .v{font-size:var(--fs-small);color:var(--text3);line-height:1.5} +.wf-i{width:30px;height:30px;border-radius:var(--r-m);background:var(--hover);display:grid;place-items:center;flex:none;color:var(--text2)} +.wf-i.big{width:36px;height:36px} +.wf-ask{display:flex;align-items:center;gap:8px;margin-top:10px;padding:10px 12px;border-radius:var(--r-m);background:var(--attention-bg);font-size:var(--fs-small)} +.wf-ask span{flex:1;min-width:0} +.wf-head{display:flex;align-items:center;gap:12px;margin:var(--sp-3) var(--sp-4) 0} +.wf-head .v{flex:1;min-width:0;font-size:var(--fs-small);color:var(--text3)} +.wf-head + .wf-ask{margin:var(--sp-3) var(--sp-4) 0} +.wf-steps{margin:0 var(--sp-4);padding:4px 0;background:var(--elev);border-radius:var(--r-l)} +.wf-step{display:flex;gap:12px;padding:10px 14px;position:relative} +.wf-step:not(:last-child)::after{content:"";position:absolute;left:28px;top:44px;bottom:-6px;width:2px;background:var(--line)} +.wf-step .mid{flex:1;min-width:0}.wf-step .k{font-size:var(--fs-ui);font-weight:500}.wf-step .v{font-size:var(--fs-small);color:var(--text2);line-height:1.5;white-space:pre-line;overflow:hidden;display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical} +.wf-step .v.out{color:var(--text3);margin-top:4px;padding-left:8px;border-left:2px solid var(--line)} +.wf-step.good .wf-i{background:color-mix(in srgb,var(--ok) 16%,transparent);color:var(--ok)} +.wf-step.go .wf-i{background:color-mix(in srgb,var(--accent) 16%,transparent);color:var(--accent-ink)} +.wf-step.wait .wf-i{background:var(--attention-bg);color:var(--warn)} +.wf-step.bad .wf-i{background:color-mix(in srgb,var(--danger) 14%,transparent);color:var(--danger)} +.wf-step.skip,.wf-step.todo{opacity:.5} +.pill.good{background:color-mix(in srgb,var(--ok) 16%,transparent);color:var(--ok)} +.pill.go{background:color-mix(in srgb,var(--accent) 16%,transparent);color:var(--accent-ink)} +.pill.wait{background:var(--attention-bg);color:var(--warn)} +.pill.bad{background:color-mix(in srgb,var(--danger) 14%,transparent);color:var(--danger)} /* 個人資料與用量: one strip of big numbers, the year's dots, a big number and bars. */ .me-figs{display:grid;grid-template-columns:repeat(4,1fr);gap:4px;margin:var(--sp-3) var(--sp-4) 0;padding:var(--sp-3) var(--sp-2);background:var(--elev);border-radius:var(--r-l)} .me-figs div{display:flex;flex-direction:column;align-items:center;gap:2px;min-width:0} @@ -1554,6 +1581,7 @@ function renderHome() { const tn = taskAttention(); $("quick").innerHTML = owner() ? [ ``, + ``, ``, ``, ``, @@ -3271,7 +3299,7 @@ async function settingsChanged() { } let listTimer = null; function stopListTimer() { clearInterval(listTimer); listTimer = null; } -const TITLES = {tasks: "任務", routines: "例行任務", pages: "頁面", computers: "電腦", settings: "設定", general: "一般", me: "個人資料與用量", models: "模型", perms: "權限", integrations: "整合", vault: "保險庫", account: "手機與帳號", updates: "更新"}; +const TITLES = {tasks: "任務", workflows: "工作流", routines: "例行任務", pages: "頁面", computers: "電腦", settings: "設定", general: "一般", me: "個人資料與用量", models: "模型", perms: "權限", integrations: "整合", vault: "保險庫", account: "手機與帳號", updates: "更新"}; async function renderList(arg) { const kind = arg.kind; $("list-title").textContent = TITLES[kind] || ""; @@ -3282,6 +3310,7 @@ async function renderList(arg) { if (kind === "routines") return listRoutines(el); if (kind === "pages") return listPages(el); if (kind === "me") return listMe(el); + if (kind === "workflows") return listWorkflows(el, arg.wf); if (SETTINGS_PAGES.includes(kind)) { // (Drawn from what this phone has at once; read again behind it when it may be old.) if (!S.settings) { el.innerHTML = `
載入中…
`; await loadSettings(); } @@ -3292,6 +3321,73 @@ async function renderList(arg) { if (["computers", "integrations"].includes(kind)) listTimer = setInterval(async () => { await loadSettings(); if (cur().v === "list" && cur().arg.kind === kind) drawSettings(kind, true); }, 4000); } } +// ---------- 工作流 ---------- +// The workflows on the brain: what starts each, its steps in order, how its runs went — run it, +// stop it, answer the 等你確認 a 審批 step waits on. (Drawing and editing are on the computer's +// canvas, or by asking a bot in the chat.) +const WF_ICON = {"觸發器": "zap", "提示詞": "text-cursor", "素材": "paperclip", "助手": "bot", "LLM": "sparkles", "圖片": "image", "影片": "play", "審批": "hand", "條件": "list-checks", "輸出": "send"}; +const WF_STATE = {running: ["go", "執行中"], waiting: ["wait", "等你確認"], done: ["good", "完成"], failed: ["bad", "失敗"], stopped: ["", "停止了"]}; +// A step's own state: not reached yet is just dimmed; the one a waiting run stands on waits for you. +const WF_STEP = {waiting: ["todo", ""], running: ["go", "進行中"], done: ["good", "完成"], failed: ["bad", "失敗"], skipped: ["skip", "略過"]}; +const stepLook = (s, run, id) => !s ? ["", ""] : s.state === "running" && run && run.state === "waiting" && (run.steps || []).find((x) => x.state === "running") === s ? ["wait", "等你確認"] : WF_STEP[s.state] || ["", ""]; +async function listWorkflows(el, wf) { + const here = () => cur().v === "list" && cur().arg.kind === "workflows" && cur().arg.wf === wf; + if (S.wfs) drawWorkflows(el, wf); else el.innerHTML = `
載入中…
`; + const v = await act("workflows", {}, false); + if (!here()) return; + S.wfs = (v && v.workflows) || S.wfs || []; + drawWorkflows(el, wf); + // (While one runs, how it goes is read again every few seconds.) + stopListTimer(); + if (S.wfs.some((w) => w.live)) listTimer = setInterval(async () => { const v = await act("workflows", {}, false); if (!here()) return stopListTimer(); if (v) { S.wfs = v.workflows || []; drawWorkflows(el, wf); if (!S.wfs.some((w) => w.live)) stopListTimer(); } }, 3000); +} +function wfLine(w) { + const r = w.live || w.runs[0]; + return [w.when, w.step_count + " 個步驟", w.next ? "下次 " + w.next : ""].filter(Boolean).join(" · ") + (r ? `\n${w.live ? "" : "最近一次:"}${r.words}${w.live ? "" : " · " + ago((r.ended || r.started) * 1000)}` : ""); +} +function wfWaiting(w) { + const r = w.live; + if (!r || r.state !== "waiting" || !isOwner()) return ""; + return `
${ic("hand", 15)}等你確認:${esc(r.asks || "要繼續嗎?")}
`; +} +function drawWorkflows(el, wf) { + const list = S.wfs || []; + if (wf) { + const w = list.find((x) => x.id === wf); + if (!w) { el.innerHTML = `
找不到這個工作流(可能刪掉了)
`; return; } + $("list-title").textContent = w.name; + const r = w.live || w.runs[0]; + const stepOf = (id) => r && (r.steps || []).find((s) => s.node === id); + let h = `
${esc(w.when)}${w.next ? " · 下次 " + esc(w.next) : ""}
${isOwner() ? (w.live ? `` : ``) : ""}
`; + h += wfWaiting(w); + h += `
步驟${r ? `(${w.live ? "這一次" : "最近一次"}:${esc(r.words)})` : ""}
${w.steps.map((st, i) => { + const s = stepOf(st.id), [cls, word] = stepLook(s, r, st.id); + return `
${ic(WF_ICON[st.kind] || "circle-dot", 15)}
${esc(st.kind)}${st.bot ? ` · ${esc(st.bot)}` : ""}${word ? ` ${esc(word)}` : ""}
${st.words ? `
${esc(st.words)}
` : ""}${s && s.output ? `
${esc(s.output.split("\n").slice(0, 3).join("\n"))}
` : ""}
`; + }).join("")}
`; + h += group("執行紀錄", (w.runs || []).map((x, i) => item({icon: x.state === "done" ? "circle-check" : x.state === "failed" ? "circle-x" : x.state === "waiting" ? "hand" : x.state === "running" ? "loader" : "minus", k: x.words, v: (x.by || "") + " · " + ago(x.started * 1000), tap: 1, data: `data-wfrun="${i}"`})).join("") || `
還沒有跑過
`); + h += `
畫布在電腦上改;或在聊天裡請 Bot 改這個工作流。
`; + el.innerHTML = h; + el.querySelectorAll("[data-wfout]").forEach((x) => x.onclick = () => { const s = stepOf(+x.dataset.wfout); if (s) sheet("這一步的結果", [{group: s.output.slice(0, 600)}, {icon: "copy", label: "複製", on: () => copyText(s.output)}]); }); + el.querySelectorAll("[data-wfrun]").forEach((x) => x.onclick = () => { + const run = w.runs[+x.dataset.wfrun]; + sheet(run.words, (run.steps || []).map((s) => { const st = w.steps.find((y) => y.id === s.node) || {kind: "步驟"}; return {icon: WF_ICON[st.kind] || "circle-dot", label: st.kind + ":" + (stepLook(s, run, s.node)[1] || "還沒到"), x: (s.output || "").slice(0, 24), on: () => s.output && copyText(s.output)}; })); + }); + } else { + el.innerHTML = list.length ? `
${list.map((w) => { + const st = w.live ? WF_STATE[w.live.state] || ["", ""] : null; + return `
${ic("workflow", 18)}
${esc(w.name)}${st ? ` ${st[1]}` : ""}
${esc(wfLine(w))}
${isOwner() ? (w.live ? `` : ``) : ""}
${wfWaiting(w)}
`; + }).join("")}
` : `
還沒有工作流。
在聊天裡請 Bot「做一個每天早上整理新聞的工作流」,或在電腦上畫。
`; + el.querySelectorAll("[data-wfopen]").forEach((x) => x.onclick = (e) => { if (e.target.closest("button")) return; go("list", {kind: "workflows", wf: +x.dataset.wfopen}); }); + } + el.querySelectorAll("[data-wfdo]").forEach((b) => b.onclick = async (e) => { + e.stopPropagation(); + const what = b.dataset.wfdo, id = +b.dataset.wf; + if (what === "stop" && !await confirmSheet("停止這次執行?", "已經做完的步驟不會復原。", "停止")) return; + b.disabled = true; + if (await act("workflow", {wf: id, do: what})) setTimeout(() => listWorkflows(el, wf), 600); + else b.disabled = false; + }); +} // ---------- 個人資料與用量(設定)---------- // The year in figures, a heat map of its days, and 用量 by period — as on the computer // (設定 › 個人資料): big numbers and bars instead of lines of words; the fine print in a tap. diff --git a/src/app/remote_ui.rs b/src/app/remote_ui.rs index 7cac7ce..5cc4855 100644 --- a/src/app/remote_ui.rs +++ b/src/app/remote_ui.rs @@ -1271,6 +1271,56 @@ pub(super) fn remote_legs(relay: &str, brain_online: Option, brain: &str, out } +impl App { + /// One workflow as the phone shows it (it is edited on the computer or by asking a bot; here + /// it is looked at and run). + fn workflow_json(&self, w: &crate::workflow::Workflow) -> serde_json::Value { + use crate::workflow::{NodeKind as K, RunState, StepState}; + let bot_name = |id: u64| self.state.bot(id).map(|b| b.name.clone()).unwrap_or_default(); + let state = |s: &RunState| match s { + RunState::Running => "running", + RunState::Waiting => "waiting", + RunState::Done => "done", + RunState::Failed => "failed", + RunState::Stopped => "stopped", + }; + let step_state = |s: StepState| match s { + StepState::Waiting => "waiting", + StepState::Running => "running", + StepState::Done => "done", + StepState::Failed => "failed", + StepState::Skipped => "skipped", + }; + let steps: Vec = w + .order() + .iter() + .filter_map(|id| w.node(*id)) + .map(|n| { + let who = match &n.kind { + K::Step { bot, .. } | K::Media { bot, .. } | K::Check { bot, .. } | K::Deliver { bot } | K::Output { bot, .. } => bot_name(*bot), + _ => String::new(), + }; + json!({"id": n.id, "kind": n.kind.label(), "words": clip(&n.kind.words(), 240), "bot": who}) + }) + .collect(); + let run = |r: &crate::workflow::Run| { + // (What a 審批 step asks, while the run waits on it.) + let asks = (r.state == RunState::Waiting).then(|| r.order.get(r.at).and_then(|id| w.node(*id))).flatten().map(|n| n.kind.words()).unwrap_or_default(); + json!({ + "id": r.id, "state": state(&r.state), "words": crate::workflow::describe_run(r), "by": r.by, "started": r.started, "ended": r.ended, "why": r.why, "asks": asks, + "steps": r.steps.iter().map(|s| json!({"node": s.node, "state": step_state(s.state), "output": clip(&s.output, 600)})).collect::>(), + }) + }; + let trigger = w.trigger().map(|t| t.kind.words()).unwrap_or_else(|| "手動".into()); + json!({ + "id": w.id, "name": w.name, "when": trigger, "steps": steps, "step_count": w.step_count(), + "next": w.next_run.map(|t| crate::routines::describe_when(t, &self.state.timezone)), + "live": w.live_run().map(run), + "runs": w.runs.iter().rev().take(10).map(run).collect::>(), + }) + } +} + #[cfg(test)] mod phone_tests { use super::*; @@ -1456,7 +1506,7 @@ impl App { // model and computer, a new chat, regenerate) plus looking and small chat things; making, // changing or deleting bots, routines, memories, pages and settings stays the owner's. let admin_ok = match action { - "detail" | "settings" | "pages" | "search" | "export_bot" | "export_transcript" | "restart_bot" | "react" | "reply" | "resume" | "older" => true, + "detail" | "settings" | "pages" | "search" | "export_bot" | "export_transcript" | "restart_bot" | "react" | "reply" | "resume" | "older" | "workflows" => true, "bot" => b["key"].as_str() == Some("unread"), "box" => matches!(b["op"].as_str(), Some("wake" | "disk")), _ => false, @@ -1478,6 +1528,32 @@ impl App { .collect(); json!({"ok": true, "hits": items, "more": more}) } + // 工作流 on the phone: each one's steps in order, what starts it, how its runs went, and + // the question it waits on — read here; run, stop, 繼續 and 停止 below. + "workflows" => json!({"ok": true, "workflows": self.state.workflows.iter().map(|w| self.workflow_json(w)).collect::>()}), + "workflow" => { + let wf = b["wf"].as_u64().unwrap_or(0); + let what = b["do"].as_str().unwrap_or(""); + let Some(w) = self.state.workflows.iter().find(|w| w.id == wf) else { return fail("找不到這個工作流") }; + if !["run", "stop", "go", "halt"].contains(&what) { + return fail("不認得的操作"); + } + if what == "run" && !w.has_steps() { + return fail(crate::workflow::NO_STEPS); + } + if what == "run" && w.live_run().is_some() { + return fail("這個工作流正在執行"); + } + let name = w.name.clone(); + self.wf_do(ctx, wf, what); + self.mark(); + done(&match what { + "run" => format!("開始執行「{name}」"), + "stop" => format!("已停止「{name}」"), + "go" => "好,繼續".to_string(), + _ => "停下來了".to_string(), + }) + } "export_bot" => match self.state.bot(bot) { Some(x) => json!({"ok": true, "filename": format!("{}.anybot", x.name), "content": crate::share::export(x)}), None => fail("找不到這個 Bot"), @@ -2725,6 +2801,23 @@ mod phone_act_tests { assert!(!d.contains(key) && d.contains("\"memories\""), "{d}"); } + /// 工作流 on the phone: the list carries each one's steps in order and its runs; a workflow + /// with no steps is not run (no fake 完成); a run started there is 手動, and a member can't. + #[test] + fn the_phone_reads_and_runs_workflows() { + let (ctx, mut app) = demo(); + app.wf_demo(); + let list = app.phone_act(&ctx, "workflows", &json!({}), "admin"); + let first = &list["workflows"][0]; + assert!(first["steps"][0]["kind"] == "觸發器" && first["steps"].as_array().unwrap().len() > 2, "{first}"); + let empty = crate::workflow::Workflow::new(99, "空的", 0); + app.state.workflows.push(empty); + assert_eq!(app.phone_act(&ctx, "workflow", &json!({"wf": 99, "do": "run"}), "owner")["error"], crate::workflow::NO_STEPS); + assert!(app.state.workflows.iter().find(|w| w.id == 99).unwrap().runs.is_empty()); + assert!(app.phone_act(&ctx, "workflow", &json!({"wf": 99, "do": "run"}), "member")["error"].is_string()); + assert!(app.phone_act(&ctx, "workflow", &json!({"wf": 99, "do": "explode"}), "owner")["error"].is_string()); + } + #[test] fn web_client_search_export_import_and_pin_order() { let (ctx, mut app) = demo(); diff --git a/src/remote.rs b/src/remote.rs index 86392bf..d56c03d 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -1283,8 +1283,9 @@ pub(crate) fn lan_guard(action: &str, body: &Value, now: impl FnOnce() -> Value, }, // Looking; chats, pages and memories; bots made, imported (with no tools, grants, team or // running routines), deleted or restarted; models and keys; skills; signing in to ChatGPT; - // signing a phone out — none of these moves a guard. - "search" | "detail" | "settings" | "pages" | "export_bot" | "export_transcript" | "import_bot" | "section_move" | "memory" | "app" | "group_chat" | "delete_bot" | "restart_bot" | "react" | "reply" | "resume" | "clear" | "delete_page" | "provider" | "device_remove" | "skill" | "chatgpt" => Guard::Keeps, + // signing a phone out; a workflow looked at, run, stopped or answered (its steps run with + // the bots' own settings, as when its schedule starts it) — none of these moves a guard. + "search" | "detail" | "settings" | "pages" | "export_bot" | "export_transcript" | "import_bot" | "section_move" | "memory" | "app" | "group_chat" | "delete_bot" | "restart_bot" | "react" | "reply" | "resume" | "clear" | "delete_page" | "provider" | "device_remove" | "skill" | "chatgpt" | "workflows" | "workflow" => Guard::Keeps, // An action this list doesn't name is refused, not let through (import_bot slipped by // that way with a file's 「team」). A new one has to be put on one side or the other. _ => Guard::Unknown,