AnyBot/src/workflow.rs

1215 lines
60 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 工作流: a few steps drawn on a canvas and run in order — a trigger (by hand, or on a schedule),
// then the steps it leads to along the lines: a bot does something (its chat shows it, as any
// question to it), the person confirms, a bot checks the last result against a condition, the
// result goes into a bot's chat, a notification. Each step hands its result on to the next.
// Beside them on the canvas: what the person drew and wrote (pen strokes, sticky notes, shapes,
// words) — notes for people, never run. Kept with the other settings (State.workflows); the
// brain runs them (app/workflow_ui.rs drives a run, turn by turn, like 問同事).
//
// A bot makes and changes them too, from the chat (the `workflow` tool, `tool` below): the
// person asks for a flow in words and watches the canvas beside the chat change as the bot
// works — steps in a tidy column, sticky notes beside the steps they are about.
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
/// How many earlier versions a workflow keeps (版本歷史).
pub const VERSIONS_KEPT: usize = 30;
/// How many runs a workflow remembers (執行紀錄).
pub const RUNS_KEPT: usize = 20;
/// The most of a step's result handed on to the next step (the whole stays in the bot's chat).
pub const HANDED_ON_CHARS: usize = 6_000;
/// A card's width on the canvas.
pub const CARD_W: f32 = 280.0;
/// Why a run AnyBot was closed during ended.
pub const INTERRUPTED: &str = "AnyBot 在執行中被關掉,這一步可能做到一半";
/// Laid out: one step below the other this far apart, side by side this far apart.
pub const ROW: f32 = 190.0;
pub const COLUMN: f32 = 340.0;
/// A sticky note's size.
pub const STICKY_W: f32 = 200.0;
pub const STICKY_H: f32 = 160.0;
/// Sticky note colours, and the names a bot gives them.
pub const STICKY_COLOURS: [&str; 6] = ["#f7c9b0", "#f6e3a1", "#bfe3c0", "#bcd7f2", "#f3c1d9", "#e2dfd8"];
pub const STICKY_NAMES: [&str; 6] = ["orange", "yellow", "green", "blue", "pink", "grey"];
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Default)]
pub struct Workflow {
pub id: u64,
pub name: String,
#[serde(default)]
pub nodes: Vec<Node>,
#[serde(default)]
pub edges: Vec<Edge>,
/// What people drew and wrote on the canvas (not run).
#[serde(default)]
pub notes: Vec<Note>,
/// Earlier versions, oldest first (at most VERSIONS_KEPT).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub versions: Vec<Version>,
/// The latest runs, oldest first (at most RUNS_KEPT).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub runs: Vec<Run>,
/// Seconds since 1970.
#[serde(default)]
pub created_at: i64,
#[serde(default)]
pub updated_at: i64,
/// A scheduled trigger's next time (seconds since 1970); None: by hand only.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub next_run: Option<i64>,
}
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
pub struct Node {
pub id: u64,
pub kind: NodeKind,
/// Where it is on the canvas (its top-left, in canvas points).
pub x: f32,
pub y: f32,
}
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum NodeKind {
/// Where a run starts: by hand (立即執行/執行工作流), or also on a schedule.
Trigger {
#[serde(default, skip_serializing_if = "Option::is_none")]
schedule: Option<crate::routines::Schedule>,
},
/// A bot does what it is asked (the last step's result goes with it).
Step { bot: u64, prompt: String },
/// The person says go on or stop.
Approve { prompt: String },
/// A bot reads the last result against a condition: 通過 goes on, otherwise the run stops.
Check { bot: u64, condition: String },
/// The last result goes into a bot's chat, for the person to read there.
Deliver { bot: u64 },
/// A notification (on this computer and the person's phones); 「{結果}」 is the last result.
Notify { text: String },
}
impl NodeKind {
/// Its name on the canvas.
pub fn label(&self) -> &'static str {
match self {
NodeKind::Trigger { .. } => "觸發器",
NodeKind::Step { .. } => "Bot 步驟",
NodeKind::Approve { .. } => "等你確認",
NodeKind::Check { .. } => "檢查",
NodeKind::Deliver { .. } => "交付",
NodeKind::Notify { .. } => "通知你",
}
}
/// The words it carries (search, the card).
pub fn words(&self) -> String {
match self {
NodeKind::Trigger { schedule } => schedule.as_ref().map(crate::routines::describe).unwrap_or_else(|| "手動".into()),
NodeKind::Step { prompt, .. } | NodeKind::Approve { prompt } => prompt.clone(),
NodeKind::Check { condition, .. } => condition.clone(),
NodeKind::Deliver { .. } => String::new(),
NodeKind::Notify { text } => text.clone(),
}
}
}
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
pub struct Edge {
pub from: u64,
pub to: u64,
}
/// Something drawn or written on the canvas.
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Default)]
pub struct Note {
pub id: u64,
pub kind: NoteKind,
/// The box it sits in (canvas points); a pen stroke's points are relative to x, y.
pub x: f32,
pub y: f32,
#[serde(default)]
pub w: f32,
#[serde(default)]
pub h: f32,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub text: String,
/// A colour name (avatar::COLORS, or "#rrggbb"); empty: the page's text colour.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub color: String,
/// Who put a sticky note there.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub author: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub points: Vec<[f32; 2]>,
}
#[derive(Clone, Copy, Serialize, Deserialize, Debug, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum NoteKind {
#[default]
Pen,
Sticky,
Shape,
Text,
}
/// An earlier version: what the canvas held then.
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
pub struct Version {
pub at: i64,
pub name: String,
pub nodes: Vec<Node>,
pub edges: Vec<Edge>,
pub notes: Vec<Note>,
}
#[derive(Clone, Copy, Serialize, Deserialize, Debug, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum RunState {
Running,
/// Waits for the person (等你確認).
Waiting,
Done,
Failed,
Stopped,
}
#[derive(Clone, Copy, Serialize, Deserialize, Debug, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum StepState {
Waiting,
Running,
Done,
Failed,
}
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
pub struct Run {
pub id: u64,
pub started: i64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ended: Option<i64>,
pub state: RunState,
/// 定時 or 手動.
#[serde(default)]
pub by: String,
/// The nodes in the order they run (fixed when it started).
pub order: Vec<u64>,
/// Where it is in `order`.
pub at: usize,
pub steps: Vec<RunStep>,
/// Why it stopped or failed.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub why: String,
}
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
pub struct RunStep {
pub node: u64,
pub state: StepState,
/// What it gave (handed on to the next step), in short.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub output: String,
/// The bot that worked on it, and when its question went into that chat (to find the
/// answer after it).
#[serde(default)]
pub bot: u64,
#[serde(default)]
pub asked_at: i64,
}
impl Run {
/// The step running or waiting now.
pub fn current(&self) -> Option<&RunStep> {
self.order.get(self.at).and_then(|n| self.steps.iter().find(|s| s.node == *n))
}
pub fn step_of(&self, node: u64) -> Option<&RunStep> {
self.steps.iter().find(|s| s.node == node)
}
pub fn live(&self) -> bool {
matches!(self.state, RunState::Running | RunState::Waiting)
}
/// The last result handed on (the latest step that gave one).
pub fn last_output(&self) -> String {
self.order.iter().take(self.at).rev().find_map(|n| self.step_of(*n).filter(|s| s.state == StepState::Done && !s.output.is_empty()).map(|s| s.output.clone())).unwrap_or_default()
}
}
impl Workflow {
pub fn new(id: u64, name: &str, now: i64) -> Workflow {
Workflow { id, name: name.to_string(), nodes: vec![Node { id: 1, kind: NodeKind::Trigger { schedule: None }, x: 0.0, y: 0.0 }], created_at: now, updated_at: now, ..Default::default() }
}
pub fn trigger(&self) -> Option<&Node> {
self.nodes.iter().find(|n| matches!(n.kind, NodeKind::Trigger { .. }))
}
pub fn schedule(&self) -> Option<&crate::routines::Schedule> {
self.trigger().and_then(|n| if let NodeKind::Trigger { schedule } = &n.kind { schedule.as_ref() } else { None })
}
pub fn node(&self, id: u64) -> Option<&Node> {
self.nodes.iter().find(|n| n.id == id)
}
pub fn node_mut(&mut self, id: u64) -> Option<&mut Node> {
self.nodes.iter_mut().find(|n| n.id == id)
}
/// A new id for a node or a note (one counter for both: a selection names either). Never one
/// a kept run or version names: a run going on after its step was removed stops there, it
/// doesn't run a new step that took the number.
pub fn next_id(&self) -> u64 {
let in_runs = self.runs.iter().flat_map(|r| r.order.iter().copied());
let in_versions = self.versions.iter().flat_map(|v| v.nodes.iter().map(|n| n.id).chain(v.notes.iter().map(|n| n.id)));
self.nodes.iter().map(|n| n.id).chain(self.notes.iter().map(|n| n.id)).chain(in_runs).chain(in_versions).max().unwrap_or(0) + 1
}
/// Runs AnyBot was closed during (found when it starts again): a bot's step may be half done
/// and its question was only in memory — the run ends as failed, saying so. One waiting for
/// the person stays: it can still be answered.
pub fn mark_interrupted(&mut self, now: i64) -> bool {
let mut cut = false;
for r in self.runs.iter_mut().filter(|r| r.state == RunState::Running) {
if let Some(s) = r.order.get(r.at).copied().and_then(|n| r.steps.iter_mut().find(|s| s.node == n)) {
s.state = StepState::Failed;
}
r.state = RunState::Failed;
r.ended = Some(now);
r.why = INTERRUPTED.into();
cut = true;
}
cut
}
/// The steps a run takes (what the trigger leads to): breadth first along the lines, the
/// ones below (then left) first where one leads to several; each once.
pub fn order(&self) -> Vec<u64> {
let Some(t) = self.trigger() else { return vec![] };
let mut out = vec![t.id];
let mut i = 0;
while i < out.len() {
let from = out[i];
let mut next: Vec<&Node> = self.edges.iter().filter(|e| e.from == from).filter_map(|e| self.node(e.to)).filter(|n| !out.contains(&n.id) && !matches!(n.kind, NodeKind::Trigger { .. })).collect();
next.sort_by(|a, b| a.y.total_cmp(&b.y).then(a.x.total_cmp(&b.x)));
for n in next {
if !out.contains(&n.id) {
out.push(n.id);
}
}
i += 1;
}
out
}
/// How many steps a run takes (the trigger not counted).
pub fn step_count(&self) -> usize {
self.order().len().saturating_sub(1)
}
pub fn live_run(&self) -> Option<&Run> {
self.runs.iter().rev().find(|r| r.live())
}
/// A line from `from` to `to`, unless it is there already, goes into the trigger, or would
/// close a circle.
pub fn connect(&mut self, from: u64, to: u64) -> bool {
if from == to || self.edges.iter().any(|e| e.from == from && e.to == to) || self.node(to).is_none_or(|n| matches!(n.kind, NodeKind::Trigger { .. })) || self.reaches(to, from) {
return false;
}
self.edges.push(Edge { from, to });
true
}
fn reaches(&self, from: u64, to: u64) -> bool {
let mut seen = vec![from];
let mut i = 0;
while i < seen.len() {
if seen[i] == to {
return true;
}
let at = seen[i];
for e in self.edges.iter().filter(|e| e.from == at) {
if !seen.contains(&e.to) {
seen.push(e.to);
}
}
i += 1;
}
false
}
pub fn remove(&mut self, id: u64) {
// (The trigger stays: a workflow always starts somewhere.)
if self.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Trigger { .. })) {
return;
}
self.nodes.retain(|n| n.id != id);
self.edges.retain(|e| e.from != id && e.to != id);
self.notes.retain(|n| n.id != id);
}
/// What the canvas holds now, as a version.
pub fn snapshot(&self, at: i64) -> Version {
Version { at, name: self.name.clone(), nodes: self.nodes.clone(), edges: self.edges.clone(), notes: self.notes.clone() }
}
/// Keep what it holds now as a version, if it differs from the last one kept.
pub fn keep_version(&mut self, at: i64) -> bool {
let v = self.snapshot(at);
if self.versions.last().is_some_and(|l| l.nodes == v.nodes && l.edges == v.edges && l.notes == v.notes && l.name == v.name) {
return false;
}
self.versions.push(v);
if self.versions.len() > VERSIONS_KEPT {
self.versions.remove(0);
}
true
}
/// Back to an earlier version (what it held just before is kept as one first).
pub fn restore(&mut self, i: usize, now: i64) {
let Some(v) = self.versions.get(i).cloned() else { return };
self.keep_version(now);
self.name = v.name;
self.nodes = v.nodes;
self.edges = v.edges;
self.notes = v.notes;
self.updated_at = now;
}
/// The same canvas under another name and id, without its runs or versions.
pub fn copy_as(&self, id: u64, now: i64) -> Workflow {
Workflow { id, name: format!("{} 的副本", self.name), nodes: self.nodes.clone(), edges: self.edges.clone(), notes: self.notes.clone(), created_at: now, updated_at: now, next_run: None, ..Default::default() }
}
/// Lay the steps out tidily: the trigger at the top, each step one row below the lowest of
/// the steps leading to it, side by side where one leads to several (left to right as they
/// were); what isn't connected goes in a column at the right. Notes stay where they are.
pub fn tidy(&mut self) {
let Some(t) = self.trigger().map(|n| n.id) else { return };
let mut depth: std::collections::HashMap<u64, usize> = [(t, 0)].into();
// (No circles, so the longest way in settles within one pass per node.)
for _ in 0..self.nodes.len() {
let mut moved = false;
for e in &self.edges {
if let Some(d) = depth.get(&e.from).copied() {
if depth.get(&e.to).is_none_or(|x| *x < d + 1) {
depth.insert(e.to, d + 1);
moved = true;
}
}
}
if !moved {
break;
}
}
let rows = depth.values().copied().max().unwrap_or(0);
let mut placed: Vec<(u64, f32, f32)> = vec![];
for row in 0..=rows {
let mut here: Vec<&Node> = self.nodes.iter().filter(|n| depth.get(&n.id) == Some(&row)).collect();
here.sort_by(|a, b| a.x.total_cmp(&b.x).then(a.id.cmp(&b.id)));
let k = here.len() as f32;
for (i, n) in here.iter().enumerate() {
placed.push((n.id, (i as f32 - (k - 1.0) / 2.0) * COLUMN, row as f32 * ROW));
}
}
let right = placed.iter().map(|p| p.1).fold(0.0_f32, f32::max) + COLUMN + 60.0;
let mut loose = 0.0;
for n in self.nodes.iter_mut() {
match placed.iter().find(|p| p.0 == n.id) {
Some(p) => (n.x, n.y) = (p.1, p.2),
None => {
(n.x, n.y) = (right, loose);
loose += ROW;
}
}
}
}
/// Laid out as `tidy` would (so a bot's change keeps it tidy; a canvas the person arranged
/// keeps their arrangement).
pub fn is_tidy(&self) -> bool {
let mut c = self.clone();
c.tidy();
c.nodes == self.nodes
}
/// The steps a node leads to.
pub fn next_of(&self, id: u64) -> Vec<u64> {
self.edges.iter().filter(|e| e.from == id).map(|e| e.to).collect()
}
/// The step at the end of the main line: the last in run order that leads nowhere.
pub fn end(&self) -> u64 {
let order = self.order();
order.iter().rev().find(|n| self.next_of(**n).is_empty()).or(order.last()).copied().unwrap_or(1)
}
/// A new run, from the start (the trigger is done at once).
pub fn start_run(&mut self, by: &str, now: i64) -> u64 {
let order = self.order();
let id = self.runs.iter().map(|r| r.id).max().unwrap_or(0) + 1;
let steps = order.iter().map(|n| RunStep { node: *n, state: StepState::Waiting, output: String::new(), bot: 0, asked_at: 0 }).collect();
let mut run = Run { id, started: now, ended: None, state: RunState::Running, by: by.to_string(), order, at: 0, steps, why: String::new() };
if let Some(s) = run.steps.first_mut() {
s.state = StepState::Done;
}
run.at = 1;
if run.order.len() <= 1 {
run.state = RunState::Done;
run.ended = Some(now);
run.why = "觸發器後面沒有連任何步驟".into();
}
self.runs.push(run);
if self.runs.len() > RUNS_KEPT {
self.runs.remove(0);
}
id
}
}
/// What a bot is asked in a step: which workflow and step, what to do, and the last result.
pub fn step_message(wf: &str, k: usize, of: usize, prompt: &str, last: &str) -> String {
let mut s = format!("[工作流「{wf}」第 {k}/{of} 步]{}", prompt.trim());
if !last.trim().is_empty() {
s.push_str(&format!("\n\n上一步的結果:\n{}", clip(last.trim(), HANDED_ON_CHARS)));
}
s
}
/// What a bot is asked in a 檢查 step.
pub fn check_message(wf: &str, k: usize, of: usize, condition: &str, last: &str) -> String {
format!(
"[工作流「{wf}」第 {k}/{of} 步・檢查]看下面這個結果有沒有做到:{}\n只回一行:做到了寫「通過」,沒做到寫「不通過:」加上原因。\n\n結果:\n{}",
condition.trim(),
if last.trim().is_empty() { "(上一步沒有結果)".to_string() } else { clip(last.trim(), HANDED_ON_CHARS) }
)
}
/// A 檢查's answer: passed, or why not.
pub fn check_passed(answer: &str) -> Result<(), String> {
let a = answer.trim().trim_start_matches(['「', '"', '*']).trim();
if a.starts_with("不通過") || a.starts_with("未通過") {
let why = a.trim_start_matches("不通過").trim_start_matches("未通過").trim_start_matches([':', ':', ' ']).trim();
return Err(if why.is_empty() { "檢查沒通過".into() } else { why.chars().take(300).collect() });
}
if a.starts_with("通過") {
return Ok(());
}
Err(format!("檢查的回答看不出有沒有通過:{}", a.chars().take(120).collect::<String>()))
}
/// A notification's words: 「{結果}」 becomes the last result's first line.
pub fn notify_text(text: &str, last: &str) -> String {
let first = last.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or("");
let t = if text.trim().is_empty() { "{結果}" } else { text.trim() };
t.replace("{結果}", &clip(first, 120))
}
fn clip(s: &str, max: usize) -> String {
if s.chars().count() <= max {
return s.to_string();
}
let mut out: String = s.chars().take(max).collect();
out.push('…');
out
}
/// The tool a bot makes, changes and runs workflows with (app/workflow_tool.rs runs it on the
/// brain; the canvas beside the chat shows each change).
pub const TOOL: &str = "workflow";
pub fn spec(schedule: Value) -> Value {
let step = json!({"type": "object", "properties": {
"kind": {"type": "string", "enum": ["step", "approve", "check", "deliver", "notify"], "description": "step: a bot does `prompt` (the last step's result goes with it); approve: the person says go on or stop (`prompt` is the question); check: a bot reads the last result against `condition` — not passing stops the run; deliver: the last result goes into `bot`'s chat; notify: a notification to the person, `text` (「{結果}」 is the last result's first line)."},
"bot": {"type": "string", "description": "step, check, deliver: the bot's name; empty = you."},
"prompt": {"type": "string"},
"condition": {"type": "string"},
"text": {"type": "string"},
"after": {"type": "integer", "description": "edit: the step it comes after (1 = the trigger); it goes in between that step and the ones it led to. Empty: at the end (several new steps in one call follow each other)."},
"branch": {"type": "boolean", "description": "edit: beside the steps `after` leads to (all of them run, the left one first) instead of in between."}},
"required": ["kind"]});
json!({"name": TOOL,
"description": "Make, change, look at and run the person's 工作流 (workflows): a canvas of cards joined by lines — a trigger (by hand, and on a schedule if it has one), then bot steps, 等你確認, 檢查, 交付 and 通知你; each step's result goes on to the next, and each bot step is a message in that bot's chat. Use it when the person wants a multi-step flow they can see and change — several steps or several bots, a confirmation or a check in between — or says 工作流, 流程. (One thing on a schedule by one bot is a routine: create_routine.) The person watches the canvas beside the chat change as you call this: create it with its steps, then change it in edits they can follow, and say in a sentence what you changed. Before changing one you didn't just make, `show` it: step ids come from there. Sticky notes (`notes`) are for people, never run: explain a step, leave a question.",
"parameters": {"type": "object", "properties": {
"action": {"type": "string", "enum": ["list", "show", "create", "edit", "run", "stop", "delete"], "description": "delete asks the person first."},
"id": {"type": "integer", "description": "The workflow (from list). Empty: the one on the person's canvas, else the one changed last."},
"name": {"type": "string", "description": "create: its name; edit: a new name."},
"schedule": schedule,
"manual_only": {"type": "boolean", "description": "edit: take the schedule away (it runs only when started)."},
"steps": {"type": "array", "items": step, "description": "create: the steps, one after the other from the trigger. edit: steps to add."},
"change": {"type": "array", "description": "edit: steps to change (only the fields given).", "items": {"type": "object", "properties": {
"step": {"type": "integer"}, "bot": {"type": "string"}, "prompt": {"type": "string"}, "condition": {"type": "string"}, "text": {"type": "string"}}, "required": ["step"]}},
"remove": {"type": "array", "items": {"type": "integer"}, "description": "edit: steps or notes to take away; the lines before and after a removed step join up."},
"connect": {"type": "array", "items": {"type": "array", "items": {"type": "integer"}}, "description": "edit: lines to add, each [from, to]."},
"disconnect": {"type": "array", "items": {"type": "array", "items": {"type": "integer"}}, "description": "edit: lines to take away, each [from, to]."},
"notes": {"type": "array", "description": "create, edit: sticky notes to put on the canvas.", "items": {"type": "object", "properties": {
"text": {"type": "string"}, "near": {"type": "integer", "description": "The step it sits beside."}, "color": {"type": "string", "enum": STICKY_NAMES}}, "required": ["text"]}},
"tidy": {"type": "boolean", "description": "edit: lay the steps out again in a tidy column (when the person asks to tidy it up)."}},
"required": ["action"]}})
}
/// Who is asking, and the bots a step can name.
pub struct Who<'a> {
pub me: u64,
pub bots: &'a [(u64, String)],
pub timezone: &'a str,
}
impl Who<'_> {
fn name(&self, id: u64) -> String {
self.bots.iter().find(|b| b.0 == id).map(|b| b.1.clone()).unwrap_or_else(|| "已刪除的 Bot".into())
}
fn bot(&self, name: Option<&str>) -> Result<u64, String> {
let n = name.unwrap_or("").trim();
if n.is_empty() {
return Ok(self.me);
}
self.bots.iter().find(|b| b.1.trim().eq_ignore_ascii_case(n)).map(|b| b.0).ok_or_else(|| format!("沒有叫「{n}」的 Bot:有 {}", self.bots.iter().map(|b| format!("「{}」", b.1)).collect::<Vec<_>>().join("、")))
}
}
/// What a call did.
#[derive(Debug, Default, PartialEq)]
pub struct Told {
pub text: String,
/// The workflow it was about (the canvas shows it).
pub wf: Option<u64>,
/// Steps and notes added or changed (lit up on the canvas for a moment).
pub touched: Vec<u64>,
/// Its steps, lines, notes or name changed.
pub changed: bool,
/// The window starts or stops its run.
pub run: bool,
pub stop: bool,
}
/// The workflow a call is about: its `id` (a number, or a number in words), else the one on the
/// person's canvas, else the one changed last. An id that isn't there is an error, not another one.
pub fn target(wfs: &[Workflow], v: &Value, showing: Option<u64>) -> Result<u64, String> {
let given = &v["id"];
if !given.is_null() {
let id = given.as_u64().or_else(|| given.as_str().and_then(|s| s.trim().trim_start_matches('#').parse().ok()));
return match id {
Some(id) if wfs.iter().any(|w| w.id == id) => Ok(id),
_ => Err(format!("沒有工作流 {}(list 看有哪些)", given.as_u64().map(|n| format!("#{n}")).unwrap_or_else(|| given.to_string()))),
};
}
showing.filter(|s| wfs.iter().any(|w| w.id == *s)).or_else(|| wfs.iter().max_by_key(|w| w.updated_at).map(|w| w.id)).ok_or_else(|| "還沒有工作流:用 create 做一個".into())
}
/// The call with the workflow it is about written in (settled when it is asked, so the card the
/// person answers names the one that changes, even if the canvas moves meanwhile).
pub fn pin_target(wfs: &[Workflow], args: &str, showing: Option<u64>) -> Result<String, String> {
let mut v: Value = serde_json::from_str(if args.trim().is_empty() { "{}" } else { args }).map_err(|_| "參數不是有效的 JSON".to_string())?;
let action = v["action"].as_str().unwrap_or("").trim().to_lowercase();
if matches!(action.as_str(), "list" | "create" | "") {
return Ok(v.to_string());
}
v["id"] = json!(target(wfs, &v, showing)?);
Ok(v.to_string())
}
/// The `workflow` tool on the workflows. `showing`: the workflow on the person's canvas.
pub fn tool(wfs: &mut Vec<Workflow>, who: &Who, v: &Value, showing: Option<u64>, now: i64) -> Result<Told, String> {
let action = v["action"].as_str().unwrap_or("").trim().to_lowercase();
if action == "list" {
if wfs.is_empty() {
return Ok(Told { text: "還沒有工作流。".into(), ..Default::default() });
}
return Ok(Told { text: wfs.iter().map(|w| list_line(w, who.timezone)).collect::<Vec<_>>().join("\n"), ..Default::default() });
}
if action == "create" {
let id = wfs.iter().map(|w| w.id).max().unwrap_or(0) + 1;
let name = v["name"].as_str().map(str::trim).filter(|n| !n.is_empty()).unwrap_or("未命名工作流");
let mut w = Workflow::new(id, name, now);
let mut touched = vec![1];
if let Some(s) = v.get("schedule").filter(|s| !s.is_null()) {
set_schedule(&mut w, s, who.timezone, now)?;
}
add_steps(&mut w, who, v, &mut touched)?;
w.tidy();
add_notes(&mut w, who, v, &mut touched)?;
w.keep_version(now);
let text = format!("已建立工作流 #{id}「{name}」(使用者的畫布上看得到)。\n{}", describe(&w, who));
wfs.push(w);
return Ok(Told { text, wf: Some(id), touched, changed: true, ..Default::default() });
}
// The others are about one workflow.
let id = target(wfs, v, showing)?;
let Some(i) = wfs.iter().position(|w| w.id == id) else { return Err(format!("沒有工作流 #{id}(list 看有哪些)")) };
let w = &mut wfs[i];
let id = w.id;
match action.as_str() {
"show" => Ok(Told { text: describe(w, who), wf: Some(id), ..Default::default() }),
"run" => {
if let Some(r) = w.live_run() {
return Err(format!("「{}」已經在跑了(第 {}/{} 步):等它跑完,或先 stop", w.name, r.at, r.order.len().saturating_sub(1)));
}
if w.step_count() == 0 {
return Err(format!("「{}」的觸發器後面還沒有連任何步驟", w.name));
}
Ok(Told { text: String::new(), wf: Some(id), run: true, ..Default::default() })
}
"stop" => {
if w.live_run().is_none() {
return Err(format!("「{}」現在沒有在跑", w.name));
}
Ok(Told { text: format!("已停止「{}」這次的執行。", w.name), wf: Some(id), stop: true, ..Default::default() })
}
"delete" => {
let name = w.name.clone();
wfs.remove(i);
Ok(Told { text: format!("已刪除工作流「{name}」。"), wf: Some(id), changed: true, ..Default::default() })
}
"edit" => {
let before = w.clone();
let tidy = w.is_tidy() || v["tidy"].as_bool() == Some(true);
w.keep_version(now);
let mut touched = vec![];
let mut said = vec![];
if let Some(n) = v["name"].as_str().map(str::trim).filter(|n| !n.is_empty()) {
w.name = n.to_string();
said.push(format!("名稱改成「{n}」"));
}
if let Some(s) = v.get("schedule").filter(|s| !s.is_null()) {
if let Err(e) = set_schedule(w, s, who.timezone, now) {
*w = before;
return Err(e);
}
touched.push(w.trigger().map(|t| t.id).unwrap_or(1));
said.push(format!("觸發改成{}", w.schedule().map(crate::routines::describe).unwrap_or_default()));
} else if v["manual_only"].as_bool() == Some(true) {
if let Some(NodeKind::Trigger { schedule }) = w.trigger().map(|t| t.id).and_then(|t| w.node_mut(t)).map(|n| &mut n.kind) {
*schedule = None;
}
w.next_run = None;
said.push("拿掉排程(只在按的時候跑)".into());
}
for r in v["remove"].as_array().into_iter().flatten().filter_map(Value::as_u64) {
if w.node(r).is_some_and(|n| matches!(n.kind, NodeKind::Trigger { .. })) {
*w = before;
return Err("觸發器不能刪:每個工作流都從它開始".into());
}
if w.node(r).is_some() {
// (What came before and after join up.)
let ins: Vec<u64> = w.edges.iter().filter(|e| e.to == r).map(|e| e.from).collect();
let outs = w.next_of(r);
w.remove(r);
for a in &ins {
for b in &outs {
w.connect(*a, *b);
}
}
said.push(format!("刪掉 #{r}"));
} else if w.notes.iter().any(|n| n.id == r) {
w.remove(r);
said.push(format!("刪掉便利貼 #{r}"));
} else {
*w = before;
return Err(format!("沒有 #{r} 這一步(show 看有哪些)"));
}
}
for pair in v["disconnect"].as_array().into_iter().flatten() {
let (a, b) = (pair[0].as_u64().unwrap_or(0), pair[1].as_u64().unwrap_or(0));
let n = w.edges.len();
w.edges.retain(|e| !(e.from == a && e.to == b));
if w.edges.len() == n {
*w = before;
return Err(format!("#{a} 和 #{b} 之間沒有線"));
}
said.push(format!("拿掉 #{a}→#{b} 的線"));
}
for c in v["change"].as_array().into_iter().flatten() {
let sid = c["step"].as_u64().unwrap_or(0);
let bot = match c["bot"].as_str() {
Some(b) => Some(who.bot(Some(b)).inspect_err(|_| *w = before.clone())?),
None => None,
};
let txt = |k: &str| c[k].as_str().map(str::to_string);
let Some(n) = w.node_mut(sid) else {
*w = before;
return Err(format!("沒有 #{sid} 這一步(show 看有哪些)"));
};
match &mut n.kind {
NodeKind::Step { bot: b, prompt } => {
if let Some(x) = bot {
*b = x;
}
if let Some(t) = txt("prompt") {
*prompt = t;
}
}
NodeKind::Check { bot: b, condition } => {
if let Some(x) = bot {
*b = x;
}
if let Some(t) = txt("condition").or_else(|| txt("prompt")) {
*condition = t;
}
}
NodeKind::Deliver { bot: b } => {
if let Some(x) = bot {
*b = x;
}
}
NodeKind::Approve { prompt } => {
if let Some(t) = txt("prompt").or_else(|| txt("text")) {
*prompt = t;
}
}
NodeKind::Notify { text } => {
if let Some(t) = txt("text").or_else(|| txt("prompt")) {
*text = t;
}
}
NodeKind::Trigger { .. } => {
*w = before;
return Err("觸發器用 schedule 或 manual_only 改".into());
}
}
touched.push(sid);
said.push(format!("改了 #{sid}"));
}
let added_from = touched.len();
if let Err(e) = add_steps(w, who, v, &mut touched) {
*w = before;
return Err(e);
}
if touched.len() > added_from {
said.push(format!("新增 {}", touched[added_from..].iter().map(|n| format!("#{n}")).collect::<Vec<_>>().join("、")));
}
for pair in v["connect"].as_array().into_iter().flatten() {
let (a, b) = (pair[0].as_u64().unwrap_or(0), pair[1].as_u64().unwrap_or(0));
if w.node(a).is_none() || w.node(b).is_none() {
*w = before;
return Err(format!("沒有 #{} 這一步(show 看有哪些)", if w.node(a).is_none() { a } else { b }));
}
if !w.connect(a, b) {
*w = before;
return Err(format!("#{a}→#{b} 連不起來:已經有了、連回觸發器,或會繞成一圈"));
}
said.push(format!("連起 #{a}→#{b}"));
}
if tidy {
w.tidy();
}
let notes_from = touched.len();
if let Err(e) = add_notes(w, who, v, &mut touched) {
*w = before;
return Err(e);
}
if touched.len() > notes_from {
said.push(format!("加了 {} 張便利貼", touched.len() - notes_from));
}
if said.is_empty() {
*w = before;
return Err("沒有要改的:給 name、schedule、manual_only、steps、change、remove、connect、disconnect、notes 或 tidy".into());
}
w.updated_at = now;
let mut text = format!("已修改工作流 #{id}「{}」:{}。", w.name, said.join(";"));
if w.live_run().is_some() {
text.push_str("(正在跑的那次照開始時的步驟走;刪掉的步驟輪到時會停下來。)");
}
text.push('\n');
text.push_str(&describe(w, who));
Ok(Told { text, wf: Some(id), touched, changed: true, ..Default::default() })
}
"" => Err("缺少 action:list、show、create、edit、run、stop 或 delete".into()),
other => Err(format!("不認得的 action「{other}」:list、show、create、edit、run、stop 或 delete")),
}
}
/// The workflow in words: its trigger, each step with its id and where it leads, the notes, the
/// last run.
pub fn describe(w: &Workflow, who: &Who) -> String {
let mut out = vec![format!("工作流 #{}「{}」:{}", w.id, w.name, w.schedule().map(|s| format!("{},也可以手動", crate::routines::describe(s))).unwrap_or_else(|| "手動執行".into()))];
let order = w.order();
let line = |n: &Node| {
let what = match &n.kind {
NodeKind::Trigger { .. } => "觸發器".to_string(),
NodeKind::Step { bot, prompt } => format!("Bot 步驟({}):{}", who.name(*bot), one_line(prompt)),
NodeKind::Approve { prompt } => format!("等你確認:{}", one_line(prompt)),
NodeKind::Check { bot, condition } => format!("檢查({}):{}", who.name(*bot), one_line(condition)),
NodeKind::Deliver { bot } => format!("交付到「{}」的聊天", who.name(*bot)),
NodeKind::Notify { text } => format!("通知你:{}", one_line(text)),
};
let next = w.next_of(n.id);
if next.is_empty() { format!("#{} {what}", n.id) } else { format!("#{} {what} → {}", n.id, next.iter().map(|x| format!("#{x}")).collect::<Vec<_>>().join("、")) }
};
for id in &order {
if let Some(n) = w.node(*id) {
out.push(line(n));
}
}
let loose: Vec<String> = w.nodes.iter().filter(|n| !order.contains(&n.id)).map(line).collect();
if !loose.is_empty() {
out.push(format!("沒接上觸發器的(不會執行):{}", loose.join(";")));
}
let notes: Vec<String> = w
.notes
.iter()
.filter(|n| matches!(n.kind, NoteKind::Sticky | NoteKind::Text) && !n.text.trim().is_empty())
.map(|n| format!("#{}「{}」{}", n.id, one_line(&n.text), if n.author.is_empty() { String::new() } else { format!("({})", n.author) }))
.collect();
if !notes.is_empty() {
out.push(format!("便利貼:{}", notes.join("、")));
}
let drawn = w.notes.iter().filter(|n| matches!(n.kind, NoteKind::Pen | NoteKind::Shape)).count();
if drawn > 0 {
out.push(format!("另外有 {drawn} 個手畫的線條或形狀"));
}
if let Some(r) = w.runs.last() {
out.push(format!("最近一次執行:{}", run_words(r)));
}
out.join("\n")
}
fn list_line(w: &Workflow, tz: &str) -> String {
let when = w.schedule().map(crate::routines::describe).unwrap_or_else(|| "手動".into());
let next = w.next_run.map(|t| format!("(下次 {})", crate::routines::describe_when(t, tz))).unwrap_or_default();
let last = w.runs.last().map(|r| format!(" · 最近一次:{}", run_words(r))).unwrap_or_default();
format!("#{}「{}」 {} 個步驟 · {when}{next}{last}", w.id, w.name, w.step_count())
}
/// How a run stands, in words.
pub fn describe_run(r: &Run) -> String {
run_words(r)
}
fn run_words(r: &Run) -> String {
let of = r.order.len().saturating_sub(1);
match r.state {
RunState::Running => format!("執行中(第 {}/{of} 步)", r.at.min(of)),
RunState::Waiting => format!("等你確認(第 {}/{of} 步)", r.at.min(of)),
RunState::Done => "完成".into(),
RunState::Failed => format!("失敗:{}", r.why),
RunState::Stopped => format!("停止了:{}", r.why),
}
}
fn one_line(s: &str) -> String {
clip(&s.split_whitespace().collect::<Vec<_>>().join(" "), 80)
}
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() {
raw["timezone"] = json!(tz);
}
let s = serde_json::from_value::<crate::routines::Schedule>(raw).map_err(|e| e.to_string()).and_then(crate::routines::validate).map_err(|e| format!("排程有問題:{e}"))?;
// (僅一次 counts from when it is set: counted from the day the workflow was made, its one
// time could be past already and it would never run.)
if s.once {
w.created_at = now;
}
if let Some(NodeKind::Trigger { schedule }) = w.trigger().map(|t| t.id).and_then(|t| w.node_mut(t)).map(|n| &mut n.kind) {
*schedule = Some(s);
}
w.next_run = None;
Ok(())
}
/// The `steps` of a call, each after the one named or at the end.
fn add_steps(w: &mut Workflow, who: &Who, v: &Value, touched: &mut Vec<u64>) -> Result<(), String> {
for st in v["steps"].as_array().into_iter().flatten() {
let txt = |k: &str| st[k].as_str().map(str::trim).unwrap_or("").to_string();
let kind = match st["kind"].as_str().unwrap_or("step").trim() {
"step" | "" => {
let prompt = txt("prompt");
if prompt.is_empty() {
return Err("Bot 步驟要有 prompt(要它做什麼)".into());
}
NodeKind::Step { bot: who.bot(st["bot"].as_str())?, prompt }
}
"approve" => NodeKind::Approve { prompt: Some(txt("prompt")).filter(|p| !p.is_empty()).unwrap_or_else(|| "要繼續嗎?".into()) },
"check" => {
let condition = Some(txt("condition")).filter(|c| !c.is_empty()).unwrap_or_else(|| txt("prompt"));
if condition.is_empty() {
return Err("檢查要有 condition(要做到什麼才算通過)".into());
}
NodeKind::Check { bot: who.bot(st["bot"].as_str())?, condition }
}
"deliver" => NodeKind::Deliver { bot: who.bot(st["bot"].as_str())? },
"notify" => NodeKind::Notify { text: Some(txt("text")).filter(|t| !t.is_empty()).unwrap_or_else(|| "{結果}".into()) },
other => return Err(format!("不認得的步驟種類「{other}」:step、approve、check、deliver 或 notify")),
};
let after = match st["after"].as_u64() {
Some(a) if w.node(a).is_some() => a,
Some(a) => return Err(format!("沒有 #{a} 這一步(show 看有哪些)")),
None => w.end(),
};
let id = w.next_id();
let branch = st["branch"].as_bool() == Some(true);
let outs = w.next_of(after);
let (ax, ay) = w.node(after).map(|n| (n.x, n.y)).unwrap_or((0.0, 0.0));
let x = if branch { outs.iter().filter_map(|o| w.node(*o)).map(|n| n.x).fold(ax, f32::max) + if outs.is_empty() { 0.0 } else { COLUMN } } else { ax };
if !branch {
// In between: what `after` led to comes after the new step, one row further down.
let below: Vec<u64> = w.nodes.iter().filter(|n| n.id != after && w.reaches(after, n.id)).map(|n| n.id).collect();
for n in w.nodes.iter_mut().filter(|n| below.contains(&n.id)) {
n.y += ROW;
}
w.edges.retain(|e| e.from != after);
}
w.nodes.push(Node { id, kind, x, y: ay + ROW });
w.edges.push(Edge { from: after, to: id });
if !branch {
for o in outs {
w.connect(id, o);
}
}
touched.push(id);
}
Ok(())
}
/// The `notes` of a call: a sticky note beside the step it is about (left of it), or at the
/// right of everything.
fn add_notes(w: &mut Workflow, who: &Who, v: &Value, touched: &mut Vec<u64>) -> Result<(), String> {
for n in v["notes"].as_array().into_iter().flatten() {
let text = n["text"].as_str().map(str::trim).unwrap_or("");
if text.is_empty() {
return Err("便利貼要有 text".into());
}
let color = n["color"].as_str().and_then(|c| STICKY_NAMES.iter().position(|x| x.eq_ignore_ascii_case(c.trim()))).map(|i| STICKY_COLOURS[i]).unwrap_or(STICKY_COLOURS[1]);
let (x, mut y) = match n["near"].as_u64() {
Some(s) => match w.node(s) {
Some(card) => (card.x - STICKY_W - 40.0, card.y),
None => return Err(format!("沒有 #{s} 這一步(便利貼要貼在哪一步旁邊)")),
},
None => (w.nodes.iter().map(|c| c.x).fold(0.0_f32, f32::max) + CARD_W + 60.0, w.nodes.iter().map(|c| c.y).fold(f32::INFINITY, f32::min).min(0.0)),
};
// (Not on top of another note.)
while w.notes.iter().any(|o| (o.x - x).abs() < STICKY_W * 0.5 && (o.y - y).abs() < STICKY_H * 0.5) {
y += STICKY_H + 16.0;
}
let id = w.next_id();
w.notes.push(Note { id, kind: NoteKind::Sticky, x, y, w: STICKY_W, h: STICKY_H, text: text.to_string(), color: color.into(), author: who.name(who.me), points: vec![] });
touched.push(id);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn call(wfs: &mut Vec<Workflow>, v: Value) -> Result<Told, String> {
let bots = vec![(1, "研究助理".to_string()), (2, "寫作夥伴".to_string())];
let who = Who { me: 1, bots: &bots, timezone: "Asia/Taipei" };
tool(wfs, &who, &v, None, 1_000)
}
/// 聊出來的工作流: create lays the steps out in a tidy column from the trigger, names the
/// bots, puts a sticky note beside the step it is about; show says it all with the ids.
#[test]
fn a_bot_makes_a_workflow_from_the_chat() {
let mut wfs = vec![];
let t = call(
&mut wfs,
json!({"action": "create", "name": "Threads 早報", "schedule": {"frequency": "daily", "time": "09:00"},
"steps": [{"kind": "step", "prompt": "找 5 則熱門育兒討論"}, {"kind": "check", "bot": "寫作夥伴", "condition": "每則都有連結"}, {"kind": "approve", "prompt": "要傳給你嗎?"}, {"kind": "notify", "text": "早報好了:{結果}"}],
"notes": [{"text": "週末改十點?", "near": 2}]}),
)
.unwrap();
let w = &wfs[0];
assert_eq!((t.wf, t.changed, w.order()), (Some(1), true, vec![1, 2, 3, 4, 5]));
assert_eq!(w.nodes.iter().map(|n| (n.x, n.y)).collect::<Vec<_>>(), (0..5).map(|i| (0.0, i as f32 * ROW)).collect::<Vec<_>>(), "one under the other");
assert!(matches!(&w.nodes[2].kind, NodeKind::Check { bot: 2, .. }), "named bot");
assert!(matches!(&w.nodes[1].kind, NodeKind::Step { bot: 1, .. }), "no name: the bot asking");
let note = &w.notes[0];
assert_eq!((note.kind, note.x < w.nodes[1].x, note.y, note.author.as_str()), (NoteKind::Sticky, true, w.nodes[1].y, "研究助理"));
assert!(w.schedule().is_some() && t.touched.contains(&note.id));
for words in ["工作流 #1「Threads 早報」:每天 09:00", "#2 Bot 步驟(研究助理):找 5 則熱門育兒討論 → #3", "#3 檢查(寫作夥伴):每則都有連結 → #4", "#5 通知你:早報好了:{結果}", "便利貼:#6「週末改十點?」(研究助理)"]
{
assert!(t.text.contains(words), "{words}\n{}", t.text);
}
assert_eq!(call(&mut wfs, json!({"action": "show"})).unwrap().text, describe(&wfs[0], &Who { me: 1, bots: &[(1, "研究助理".into()), (2, "寫作夥伴".into())], timezone: "" }));
assert!(call(&mut wfs, json!({"action": "list"})).unwrap().text.starts_with("#1「Threads 早報」 4 個步驟 · 每天 09:00"));
}
/// Edits the person can follow: a step in between pushes the rest down; a branch goes
/// beside; a removed step's lines join up; nothing half done when one part is wrong.
#[test]
fn a_bot_changes_a_workflow_step_by_step() {
let mut wfs = vec![];
call(&mut wfs, json!({"action": "create", "name": "早報", "steps": [{"prompt": "查新聞"}, {"kind": "deliver"}]})).unwrap();
// In between 2 and 3.
let t = call(&mut wfs, json!({"action": "edit", "steps": [{"kind": "check", "condition": "至少三則", "after": 2}]})).unwrap();
assert_eq!((wfs[0].order(), t.touched.clone()), (vec![1, 2, 4, 3], vec![4]));
assert!(wfs[0].is_tidy(), "still tidy: {:?}", wfs[0].nodes);
assert!(t.text.starts_with("已修改工作流 #1「早報」:新增 #4。"), "{}", t.text);
// A branch beside what 4 leads to: both run.
call(&mut wfs, json!({"action": "edit", "steps": [{"kind": "notify", "after": 4, "branch": true}]})).unwrap();
assert_eq!(wfs[0].next_of(4).len(), 2);
let (a, b) = (wfs[0].node(3).unwrap(), wfs[0].node(5).unwrap());
assert_eq!(a.y, b.y, "side by side");
// Removing 4: 2 leads to 3 and 5 again.
call(&mut wfs, json!({"action": "edit", "remove": [4]})).unwrap();
let mut next = wfs[0].next_of(2);
next.sort();
assert_eq!(next, vec![3, 5]);
// Change, rename, take the schedule away.
call(&mut wfs, json!({"action": "edit", "name": "晚報", "change": [{"step": 2, "prompt": "查晚間新聞", "bot": "寫作夥伴"}], "manual_only": true})).unwrap();
assert!(matches!(&wfs[0].node(2).unwrap().kind, NodeKind::Step { bot: 2, prompt } if prompt == "查晚間新聞"));
assert_eq!(wfs[0].name, "晚報");
// One wrong part: nothing of the call is kept.
let before = wfs[0].clone();
for bad in [
json!({"action": "edit", "name": "X", "remove": [99]}),
json!({"action": "edit", "name": "X", "remove": [1]}),
json!({"action": "edit", "name": "X", "connect": [[3, 2]]}),
json!({"action": "edit", "steps": [{"kind": "step", "prompt": "x", "bot": "沒這個"}], "name": "X"}),
json!({"action": "edit"}),
] {
assert!(call(&mut wfs, bad.clone()).is_err(), "{bad}");
assert_eq!(wfs[0].nodes, before.nodes, "{bad}");
assert_eq!((wfs[0].name.as_str(), wfs[0].edges.len()), ("晚報", before.edges.len()), "{bad}");
}
// Moved by the person: a bot's step goes below its step without tidying theirs.
wfs[0].node_mut(3).unwrap().x = 700.0;
call(&mut wfs, json!({"action": "edit", "steps": [{"kind": "notify", "after": 3}]})).unwrap();
let n = wfs[0].nodes.last().unwrap();
assert_eq!((n.x, wfs[0].node(3).unwrap().x), (700.0, 700.0));
// Each edit kept the one before as a version.
assert!(wfs[0].versions.len() >= 4);
}
/// run and stop are for the window (they need a bot to work); run says why not.
#[test]
fn run_and_stop_are_asked_of_the_window() {
let mut wfs = vec![];
call(&mut wfs, json!({"action": "create", "name": "空的"})).unwrap();
assert!(call(&mut wfs, json!({"action": "run"})).unwrap_err().contains("還沒有連任何步驟"));
call(&mut wfs, json!({"action": "edit", "steps": [{"prompt": "做事"}]})).unwrap();
assert!(call(&mut wfs, json!({"action": "run"})).unwrap().run);
assert!(call(&mut wfs, json!({"action": "stop"})).unwrap_err().contains("沒有在跑"));
wfs[0].start_run("手動", 5);
assert!(call(&mut wfs, json!({"action": "run"})).unwrap_err().contains("已經在跑了"));
assert!(call(&mut wfs, json!({"action": "stop"})).unwrap().stop);
assert!(call(&mut wfs, json!({"action": "show", "id": 9})).unwrap_err().contains("沒有工作流 #9"));
assert!(call(&mut wfs, json!({"action": "delete"})).unwrap().changed && wfs.is_empty());
}
/// Which one a call is about: the id given (a number in words too), else the canvas, else
/// the one changed last; an id that isn't there is an error, never another workflow. The card
/// is made from the call with that written in.
#[test]
fn a_call_names_one_workflow_and_keeps_it() {
let mut wfs = vec![];
call(&mut wfs, json!({"action": "create", "name": "A"})).unwrap();
call(&mut wfs, json!({"action": "create", "name": "B"})).unwrap();
wfs[1].updated_at = 9_999;
assert_eq!(target(&wfs, &json!({"action": "delete"}), Some(1)), Ok(1), "the canvas first");
assert_eq!(target(&wfs, &json!({"action": "delete"}), None), Ok(2), "then the one changed last");
assert_eq!(target(&wfs, &json!({"id": "#1"}), Some(2)), Ok(1));
for bad in [json!({"id": 0}), json!({"id": "x"}), json!({"id": 7})] {
assert!(target(&wfs, &bad, Some(1)).is_err(), "{bad}");
}
let pinned: Value = serde_json::from_str(&pin_target(&wfs, r#"{"action":"delete"}"#, Some(1)).unwrap()).unwrap();
assert_eq!(pinned["id"], 1);
assert_eq!(pin_target(&wfs, r#"{"action":"create","name":"C"}"#, Some(1)).unwrap(), json!({"action": "create", "name": "C"}).to_string());
}
/// A wrong schedule leaves nothing of the call; 僅一次 set later counts from then; numbers a
/// run still names never come back; a run AnyBot was closed during ends as interrupted (one
/// waiting for the person stays).
#[test]
fn edits_and_restarts_leave_no_half_state() {
let mut wfs = vec![];
call(&mut wfs, json!({"action": "create", "name": "早報", "steps": [{"prompt": "查"}]})).unwrap();
assert!(call(&mut wfs, json!({"action": "edit", "name": "X", "schedule": {"frequency": "daily", "time": "25:00"}})).is_err());
assert_eq!(wfs[0].name, "早報");
let bots = vec![(1, "研究助理".to_string())];
let who = Who { me: 1, bots: &bots, timezone: "Asia/Taipei" };
let later = 1_000 + 3 * 86_400;
tool(&mut wfs, &who, &json!({"action": "edit", "schedule": {"frequency": "daily", "time": "09:00", "once": true}}), None, later).unwrap();
assert_eq!(wfs[0].created_at, later);
assert!(crate::routines::next_run(wfs[0].schedule().unwrap(), wfs[0].created_at, later).is_some(), "its one time is ahead");
// Step 2 is in a run; removed, its number isn't given to the next step.
wfs[0].start_run("手動", 2_000);
call(&mut wfs, json!({"action": "edit", "remove": [2]})).unwrap();
let t = call(&mut wfs, json!({"action": "edit", "steps": [{"prompt": "新的"}]})).unwrap();
assert!(t.touched[0] > 2, "{:?}", t.touched);
// Closed while running: interrupted; while waiting for the person: kept.
assert!(wfs[0].mark_interrupted(3_000));
let r = wfs[0].runs.last().unwrap();
assert_eq!((r.state, r.why.as_str(), r.steps[1].state), (RunState::Failed, INTERRUPTED, StepState::Failed));
wfs[0].start_run("手動", 4_000);
wfs[0].runs.last_mut().unwrap().state = RunState::Waiting;
assert!(!wfs[0].mark_interrupted(5_000));
}
fn wf() -> Workflow {
let mut w = Workflow::new(1, "早報", 100);
for (id, x, y, kind) in [
(2, 0.0, 200.0, NodeKind::Step { bot: 1, prompt: "查今天的新聞".into() }),
(3, 0.0, 400.0, NodeKind::Check { bot: 1, condition: "至少三則".into() }),
(4, 300.0, 600.0, NodeKind::Notify { text: "早報好了:{結果}".into() }),
(5, 0.0, 600.0, NodeKind::Deliver { bot: 1 }),
(6, 900.0, 900.0, NodeKind::Approve { prompt: "沒連上".into() }),
] {
w.nodes.push(Node { id, kind, x, y });
}
assert!(w.connect(1, 2) && w.connect(2, 3) && w.connect(3, 4) && w.connect(3, 5));
w
}
/// A run goes from the trigger along the lines, the one higher up (then left) first where
/// a step leads to two; what isn't connected doesn't run.
#[test]
fn a_run_follows_the_lines_from_the_trigger() {
let w = wf();
assert_eq!(w.order(), vec![1, 2, 3, 5, 4]);
assert_eq!(w.step_count(), 4);
}
/// No line into the trigger, none twice, none closing a circle; removing a step takes its
/// lines; the trigger stays.
#[test]
fn lines_never_make_a_circle() {
let mut w = wf();
assert!(!w.connect(2, 1), "into the trigger");
assert!(!w.connect(1, 2), "twice");
assert!(!w.connect(4, 2), "a circle");
assert!(!w.connect(3, 3));
w.remove(3);
assert_eq!((w.order(), w.edges.len()), (vec![1, 2], 1));
w.remove(1);
assert!(w.trigger().is_some());
}
/// A run starts past the trigger; the last result is the newest step that gave one.
#[test]
fn a_run_hands_the_last_result_on() {
let mut w = wf();
let id = w.start_run("手動", 200);
let r = w.runs.iter_mut().find(|r| r.id == id).unwrap();
assert_eq!((r.at, r.state, r.current().map(|s| s.node)), (1, RunState::Running, Some(2)));
r.steps[1].state = StepState::Done;
r.steps[1].output = "三則新聞".into();
r.at = 2;
assert_eq!(r.last_output(), "三則新聞");
// Nothing after the trigger: done at once, and said why.
let mut lone = Workflow::new(2, "空的", 100);
let id = lone.start_run("手動", 200);
assert_eq!(lone.runs.iter().find(|r| r.id == id).map(|r| (r.state, r.why.as_str())), Some((RunState::Done, "觸發器後面沒有連任何步驟")));
}
#[test]
fn what_a_step_says_and_how_a_check_reads() {
let m = step_message("早報", 1, 3, "整理成三點", "新聞 A\n新聞 B");
assert!(m.starts_with("[工作流「早報」第 1/3 步]整理成三點") && m.ends_with("上一步的結果:\n新聞 A\n新聞 B"), "{m}");
assert!(!step_message("早報", 1, 3, "查", "").contains("上一步"));
assert_eq!(check_passed("通過"), Ok(()));
assert_eq!(check_passed("「通過」,三則都有"), Ok(()));
assert_eq!(check_passed("不通過:只有兩則"), Err("只有兩則".into()));
assert!(check_passed("好像可以").is_err());
assert_eq!(notify_text("早報好了:{結果}", "\n三則新聞\n第二行"), "早報好了:三則新聞");
assert_eq!(notify_text("", "結果在這"), "結果在這");
}
/// 版本歷史: a version only when something changed; restoring keeps what was there first;
/// at most VERSIONS_KEPT. A copy has no runs or versions.
#[test]
fn versions_are_kept_and_restored() {
let mut w = wf();
assert!(w.keep_version(1));
assert!(!w.keep_version(2), "nothing changed");
w.name = "晚報".into();
w.remove(4);
assert!(w.keep_version(3));
w.restore(0, 4);
assert_eq!((w.name.as_str(), w.node(4).is_some(), w.versions.len()), ("早報", true, 2), "the one before restoring was kept already");
for i in 0..40 {
w.name = format!("v{i}");
w.keep_version(10 + i);
}
assert_eq!(w.versions.len(), VERSIONS_KEPT);
w.start_run("手動", 5);
let c = w.copy_as(9, 6);
assert!(c.runs.is_empty() && c.versions.is_empty() && c.name.ends_with("的副本") && c.nodes == w.nodes);
}
}