Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
feat(kit): edit routines in one form with a schedule or a webhook
leepokai33ad45a265da
diff --git a/apps/linux/src/manage.rs b/apps/linux/src/manage.rsindex 2aaa23e8..88f536f6 100644--- a/apps/linux/src/manage.rs+++ b/apps/linux/src/manage.rs@@ -6,6 +6,7 @@ use crate::{};use adw::prelude::*;use serde_json::{Value, json};+use std::{cell::RefCell, rc::Rc};pub fn dialog(ui: &App, title: &str) -> (adw::Dialog, gtk::Box) {let body = gtk::Box::builder()@@ -115,16 +116,20 @@ fn load_memory(ui: &App, bot: &str, list: >k::Box) {pub fn routines(ui: &App, bot: &str) {let (window, body) = dialog(ui, "Routines");let actions = gtk::Box::new(gtk::Orientation::Horizontal, 8);- let add = icon_button("list-add-symbolic", "Ask the bot for a routine");+ let add = icon_button("list-add-symbolic", "Set up a routine");+ let ask = icon_button("chat-message-new-symbolic", "Ask the bot for a routine");let refresh = icon_button("view-refresh-symbolic", "Refresh routines");actions.append(&add);+ actions.append(&ask);actions.append(&refresh);body.append(&actions);let list = gtk::Box::new(gtk::Orientation::Vertical, 14);body.append(&list);- // New routines are set up by talking to the bot: start the ask in its chat.+ let (ui2, bot2, list2) = (ui.clone(), bot.to_owned(), list.clone());+ add.connect_clicked(move |_| routine_editor(&ui2, &bot2, Value::Null, &list2));+ // Or ask the bot to set one up: start the ask in its chat.let ui2 = ui.clone();- add.connect_clicked(move |_| {+ ask.connect_clicked(move |_| {window.close();ui::insert_draft(&ui2, "I want a routine that ");});@@ -149,7 +154,7 @@ fn load_routines(ui: &App, bot: &str, list: >k::Box) {let items = v["routines"].as_array().cloned().unwrap_or_default();if items.is_empty() {let empty = label(- "No routines yet. Tell the bot what to run and when, and it sets one up.",+ "No routines yet. Ask the bot for one, or set it up yourself with +.",&["secondary"],);empty.set_wrap(true);@@ -189,10 +194,10 @@ fn load_routines(ui: &App, bot: &str, list: >k::Box) {.tooltip_text(item["instruction"].as_str().unwrap_or("")).build();rows.append(&row);- let edit = icon_button("document-edit-symbolic", "Edit routine");+ // A row opens the same form as a new routine, filled in.+ row.set_activatable(true);let (ui2, bot2, item2, list2) = (ui.clone(), bot.clone(), item.clone(), list.clone());- edit.connect_clicked(move |_| routine_editor(&ui2, &bot2, item2.clone(), &list2));- row.add_suffix(&edit);+ row.connect_activated(move |_| routine_editor(&ui2, &bot2, item2.clone(), &list2));for (icon, title, method) in [("media-playback-start-symbolic", "Test run", "runRoutine"),("user-trash-symbolic", "Delete routine", "deleteRoutine"),@@ -203,8 +208,11 @@ fn load_routines(ui: &App, bot: &str, list: >k::Box) {row.add_suffix(&button);let (ui, bot, item, list) = (ui.clone(), bot.clone(), item.clone(), list.clone());button.connect_clicked(move |_| {- let (ui2, bot, list, id) = (ui.clone(), bot.clone(), list.clone(), item["id"].clone());- let run = move || routine_call(&ui2, method, json!({"botId":bot,"id":id}), &bot, &list);+ let (ui2, bot, list, id) =+ (ui.clone(), bot.clone(), list.clone(), item["id"].clone());+ let run = move || {+ routine_call(&ui2, method, json!({"botId":bot,"id":id}), &bot, &list)+ };if method == "deleteRoutine" {crate::dialogs::confirm(&ui,@@ -222,12 +230,22 @@ fn load_routines(ui: &App, bot: &str, list: >k::Box) {let on = gtk::Switch::builder().active(item["enabled"] == true).valign(gtk::Align::Center)- .tooltip_text(if item["enabled"] == true { "Pause" } else { "Resume" })+ .tooltip_text(if item["enabled"] == true {+ "Pause"+ } else {+ "Resume"+ }).build();row.add_suffix(&on);let (ui, bot, id, list) = (ui.clone(), bot.clone(), item["id"].clone(), list.clone());on.connect_state_set(move |_, enabled| {- routine_call(&ui, "setRoutineEnabled", json!({"botId":bot,"id":id,"enabled":enabled}), &bot, &list);+ routine_call(+ &ui,+ "setRoutineEnabled",+ json!({"botId":bot,"id":id,"enabled":enabled}),+ &bot,+ &list,+ );gtk::glib::Propagation::Proceed});}@@ -272,7 +290,14 @@ fn entry(body: >k::Box, title: &str, value: &str) -> gtk::Entry {}fn routine_editor(ui: &App, bot: &str, routine: Value, list: >k::Box) {- let (window, body) = dialog(ui, "Edit routine");+ let (window, body) = dialog(+ ui,+ if routine.is_null() {+ "Set up a routine"+ } else {+ "Edit routine"+ },+ );let name = entry(&body, "Name", routine["name"].as_str().unwrap_or(""));body.append(&label("Instruction", &["secondary"]));let instruction = gtk::TextView::builder()@@ -291,84 +316,94 @@ fn routine_editor(ui: &App, bot: &str, routine: Value, list: >k::Box) {.vexpand(false).build();body.append(&scroll);- let kinds = vec![- "keep", "daily", "weekly", "monthly", "custom", "once", "webhook",- ];- body.append(&label("Schedule", &["secondary"]));+ // Schedule or webhook, as in Claude Code routines. Anything else the bot set up+ // (a one-off time, an interval, events, several triggers) stays until replaced.+ let triggers = routine["triggers"].as_array().cloned().unwrap_or_default();+ let mut kinds = vec!["cron", "webhook"];+ let keeps = match triggers.as_slice() {+ [] => false,+ [t] => !matches!(t["type"].as_str(), Some("cron" | "webhook")),+ _ => true,+ };+ if keeps {+ kinds.insert(0, "keep");+ } else if triggers.first().is_some_and(|t| t["type"] == "webhook") {+ kinds.reverse();+ }+ let current = routine["triggerDescriptions"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(Value::as_str)+ .collect::<Vec<_>>()+ .join(" · ");+ body.append(&label("When to run", &["secondary"]));let labels: Vec<&str> = kinds.iter().map(|k| match *k {- "keep" => "Keep existing triggers",- "daily" => "Daily",- "weekly" => "Weekly",- "monthly" => "Monthly",- "custom" => "Custom cron",- "once" => "Run once",+ "keep" => current.as_str(),+ "cron" => "Schedule",_ => "Webhook",}).collect();let kind = gtk::DropDown::from_strings(&labels);body.append(&kind);- let hour = entry(&body, "Hour (0–23)", "9");- let minute = entry(&body, "Minute (0–59)", "0");- let day = entry(- &body,- "Weekly: weekday (0 = Sunday); monthly: day (1–31)",- "1",- );- let zone_name = gtk::glib::TimeZone::local().identifier().to_string();- let zone = entry(&body, "Time zone", &zone_name);+ // An existing cron trigger fills the fields, so switching to Cron edits it.+ let cron = routine["triggers"]+ .as_array()+ .into_iter()+ .flatten()+ .find(|t| t["type"] == "cron");let expression = entry(&body,- "Custom cron (minute hour day month weekday)",- "0 9 * * *",+ "Cron (minute hour day month weekday)",+ cron.and_then(|t| t["expression"].as_str())+ .unwrap_or("0 9 * * *"),);- let once = entry(+ let local_zone = gtk::glib::TimeZone::local().identifier().to_string();+ let zone = entry(&body,- "Run once: date and time (ISO 8601, include time zone)",- "",+ "Time zone",+ cron.and_then(|t| t["timeZone"].as_str())+ .unwrap_or(&local_zone),);let existing = label(- &routine["triggerDescriptions"]- .as_array()- .into_iter()- .flatten()- .filter_map(Value::as_str)- .collect::<Vec<_>>()- .join(" · "),+ "Set up by the bot. Pick Schedule or Webhook to replace it.",&["secondary"],);existing.set_wrap(true);body.append(&existing);+ let saved_hook = triggers+ .iter()+ .any(|t| matches!(t["type"].as_str(), Some("webhook" | "event")));+ let hook = if saved_hook {+ webhook_panel(ui, bot, routine["id"].as_str().unwrap_or_default())+ } else {+ let note = label(+ "Runs each time something is posted to its URL. Save to get the URL and key.",+ &["secondary"],+ );+ note.set_wrap(true);+ note.upcast()+ };+ body.append(&hook);let update_fields = {- let (kinds, hour, minute, day, zone, expression, once, existing) = (+ let (kinds, zone, expression, existing, hook) = (kinds.clone(),- hour.clone(),- minute.clone(),- day.clone(),zone.clone(),expression.clone(),- once.clone(),existing.clone(),+ hook.clone(),);move |kind: >k::DropDown| {let style = kinds[kind.selected() as usize];- for (field, visible) in [- (&hour, matches!(style, "daily" | "weekly" | "monthly")),- (&minute, matches!(style, "daily" | "weekly" | "monthly")),- (&day, matches!(style, "weekly" | "monthly")),- (- &zone,- matches!(style, "daily" | "weekly" | "monthly" | "custom"),- ),- (&expression, style == "custom"),- (&once, style == "once"),- ] {+ for (field, visible) in [(&expression, style == "cron"), (&zone, style == "cron")] {if let Some(group) = field.parent() {group.set_visible(visible);}}existing.set_visible(style == "keep");+ hook.set_visible(style == "webhook");}};update_fields(&kind);@@ -411,12 +446,8 @@ fn routine_editor(ui: &App, bot: &str, routine: Value, list: >k::Box) {instruction,kind,kinds,- hour,- minute,- day,zone,expression,- once,timeout,status,) = (@@ -429,31 +460,31 @@ fn routine_editor(ui: &App, bot: &str, routine: Value, list: >k::Box) {instruction.clone(),kind.clone(),kinds.clone(),- hour.clone(),- minute.clone(),- day.clone(),zone.clone(),expression.clone(),- once.clone(),timeout.clone(),status.clone(),);button.connect_clicked(move |button| {let style = kinds[kind.selected() as usize];- let draft = schedule_draft(style, &hour.text(), &minute.text(), &day.text(), &zone.text(), &expression.text(), &once.text(), &routine["triggers"]);- let draft = match draft { Ok(d) => d, Err(e) => { status.set_label(&e); return; } };+ let draft = schedule_draft(style, &zone.text(), &expression.text(), &routine["triggers"]);let buffer = instruction.buffer();let text = buffer.text(&buffer.start_iter(), &buffer.end_iter(), false).to_string();let timeout = match timeout.text().parse::<u64>() { Ok(v) if (1..=86400).contains(&v) => v, _ => { status.set_label("Timeout must be between 1 and 86400 seconds."); return; } };if save && (name.text().trim().is_empty() || text.trim().is_empty()) { status.set_label("Enter a name and instruction."); return; }button.set_sensitive(false);let mut args = json!({"draft":draft});- if save { args = json!({"botId":bot,"name":name.text().as_str(),"instruction":text,"schedule":draft,"timeoutSeconds":timeout}); args["id"] = routine["id"].clone(); }- let (ui, bot, list, window, status, button) = (ui.clone(), bot.clone(), list.clone(), window.clone(), status.clone(), button.clone());+ if save { args = json!({"botId":bot,"name":name.text().as_str(),"instruction":text,"schedule":draft,"timeoutSeconds":timeout}); if !routine.is_null() { args["id"] = routine["id"].clone(); } }+ let (ui, bot, list, window, status, button, routine) = (ui.clone(), bot.clone(), list.clone(), window.clone(), status.clone(), button.clone(), routine.clone());client::call(if save { "saveRoutine" } else { "routineSchedule" }, args, move |r| {button.set_sensitive(true);match r {- Ok(v) if save => { let _ = v; window.close(); load_routines(&ui, &bot, &list); }+ Ok(v) if save => {+ window.close();+ load_routines(&ui, &bot, &list);+ // A new webhook routine reopens on its URL and key, which exist only now.+ if routine.is_null() && style == "webhook" { routine_editor(&ui, &bot, v["routine"].clone(), &list); }+ }Ok(v) => status.set_label(&format!("{}{}{}", v["summary"].as_str().unwrap_or(""),v["nextRunAt"].as_i64().map(|at| format!("\nNext: {}", schedule_time(at))).unwrap_or_default(),v["warning"].as_str().map(|w| format!("\n{w}")).unwrap_or_default())),@@ -464,46 +495,172 @@ fn routine_editor(ui: &App, bot: &str, routine: Value, list: >k::Box) {}}-#[allow(clippy::too_many_arguments)]-fn schedule_draft(- style: &str,- hour: &str,- minute: &str,- day: &str,- zone: &str,- expression: &str,- once: &str,- original: &Value,-) -> Result<Value, String> {- let mut draft = json!({"kind": if matches!(style, "keep" | "once" | "webhook") { style } else { "cron" }, "zone":zone,"original":original.as_array().cloned().unwrap_or_default()});- if draft["kind"] == "cron" {- draft["calendarStyle"] = style.into();- draft["expression"] = expression.into();- if style != "custom" {- draft["hour"] = hour.parse::<u8>().map_err(|_| "Enter a valid hour")?.into();- draft["minute"] = minute- .parse::<u8>()- .map_err(|_| "Enter a valid minute")?- .into();- if style == "weekly" {- draft["weekday"] = day- .parse::<u8>()- .map_err(|_| "Enter a weekday from 0 to 6")?- .into();- }- if style == "monthly" {- draft["monthDay"] = day- .parse::<u8>()- .map_err(|_| "Enter a day from 1 to 31")?- .into();- }+/// A saved webhook routine's URL and key, each with a copy button; the key can be shown and+/// replaced. Same as the Apple editor's webhook panel.+fn webhook_panel(ui: &App, bot: &str, id: &str) -> gtk::Widget {+ let panel = gtk::Box::new(gtk::Orientation::Vertical, 8);+ let url_title = label("URL", &["secondary"]);+ let url = label("Loading webhook…", &["monospace"]);+ url.set_wrap(true);+ url.set_wrap_mode(gtk::pango::WrapMode::Char);+ url.set_selectable(true);+ url.set_hexpand(true);+ let copy_url = icon_button("edit-copy-symbolic", "Copy URL");+ let url_row = gtk::Box::new(gtk::Orientation::Horizontal, 6);+ url_row.append(&url);+ url_row.append(©_url);+ let key = label("", &["monospace"]);+ key.set_hexpand(true);+ key.set_selectable(true);+ let show = icon_button("view-reveal-symbolic", "Show key");+ let rotate = icon_button("view-refresh-symbolic", "Replace key");+ let copy_key = icon_button("edit-copy-symbolic", "Copy key");+ let key_row = gtk::Box::new(gtk::Orientation::Horizontal, 6);+ for w in [+ key.upcast_ref::<gtk::Widget>(),+ show.upcast_ref(),+ rotate.upcast_ref(),+ copy_key.upcast_ref(),+ ] {+ key_row.append(w);+ }+ let note = label("", &["secondary"]);+ note.set_wrap(true);+ panel.append(&url_title);+ panel.append(&url_row);+ panel.append(&label("Key", &["secondary"]));+ panel.append(&key_row);+ panel.append(¬e);++ let state: Rc<RefCell<Value>> = Rc::new(RefCell::new(Value::Null));+ let shown = Rc::new(std::cell::Cell::new(false));+ let render = {+ let (state, shown, url_title, url, key, show, note) = (+ state.clone(),+ shown.clone(),+ url_title.clone(),+ url.clone(),+ key.clone(),+ show.clone(),+ note.clone(),+ );+ move || {+ let v = state.borrow();+ let public = v["url"].as_str();+ url_title.set_label(if public.is_some() { "URL" } else { "Local URL" });+ url.set_label(+ public+ .or_else(|| v["localUrl"].as_str())+ .unwrap_or_default(),+ );+ let secret = v["key"].as_str().unwrap_or_default();+ key.set_label(&if shown.get() {+ secret.to_owned()+ } else {+ "•".repeat(24)+ });+ show.set_icon_name(if shown.get() {+ "view-conceal-symbolic"+ } else {+ "view-reveal-symbolic"+ });+ show.set_tooltip_text(Some(if shown.get() { "Hide key" } else { "Show key" }));+ note.set_label(if public.is_some() {+ "POST with Authorization: Bearer <key>. For GitHub, use content type application/json and the key as the secret. Deliveries wait up to 72 hours while this computer is off. They pass through the Codync cloud, which can read them."+ } else {+ "The Codync cloud is off, so only this computer can send to it."+ });}- } else if style == "once" {- let date = gtk::glib::DateTime::from_iso8601(once, None)- .map_err(|_| "Enter an ISO 8601 date with a time zone")?;- draft["at"] = (date.to_unix() * 1000).into();+ };+ let load = {+ let (ui, bot, id, state, shown, render, note) = (+ ui.clone(),+ bot.to_owned(),+ id.to_owned(),+ state.clone(),+ shown.clone(),+ render.clone(),+ note.clone(),+ );+ Rc::new(move |rotate: bool| {+ let (ui, state, shown, render, note) = (+ ui.clone(),+ state.clone(),+ shown.clone(),+ render.clone(),+ note.clone(),+ );+ client::call(+ "routineWebhook",+ json!({"botId": bot, "id": id, "rotate": rotate}),+ move |r| match r {+ Ok(v) => {+ *state.borrow_mut() = v;+ if rotate {+ shown.set(true);+ toast(&ui, "Key replaced");+ }+ render();+ }+ Err(e) => note.set_label(&e),+ },+ );+ })+ };+ load(false);+ {+ let (shown, render) = (shown.clone(), render.clone());+ show.connect_clicked(move |_| {+ shown.set(!shown.get());+ render();+ });+ }+ {+ let (ui, load) = (ui.clone(), load.clone());+ rotate.connect_clicked(move |_| {+ let load = load.clone();+ crate::dialogs::confirm(+ &ui,+ "Replace the key?",+ "Senders using the current key stop working until they get the new one.",+ "Replace key",+ true,+ move || load(true),+ );+ });+ }+ for (button, field) in [(©_url, "url"), (©_key, "key")] {+ let (ui, state) = (ui.clone(), state.clone());+ button.connect_clicked(move |b| {+ let v = state.borrow();+ let text = match field {+ "key" => v["key"].as_str(),+ _ => v["url"].as_str().or_else(|| v["localUrl"].as_str()),+ };+ if let Some(text) = text {+ b.clipboard().set_text(text);+ toast(+ &ui,+ if field == "key" {+ "Copied the key"+ } else {+ "Copied the URL"+ },+ );+ }+ });+ }+ panel.upcast()+}++/// The form as the host's schedule draft: cron is sent as written, the host checks it.+fn schedule_draft(style: &str, zone: &str, expression: &str, original: &Value) -> Value {+ let mut draft = json!({"kind":style,"zone":zone,"original":original.as_array().cloned().unwrap_or_default()});+ if style == "cron" {+ draft["calendarStyle"] = "custom".into();+ draft["expression"] = expression.into();}- Ok(draft)+ draft}#[cfg(test)]@@ -512,25 +669,15 @@ mod tests {#[test]fn edits_preserve_existing_event_triggers() {let original = json!([{"type":"event","source":"github","event":"pull_request.opened","filters":{"repo":"a/b"}}]);- let draft = schedule_draft("keep", "", "", "", "Asia/Taipei", "", "", &original).unwrap();+ let draft = schedule_draft("keep", "Asia/Taipei", "", &original);assert_eq!(draft["original"], original);assert_eq!(draft["kind"], "keep");}#[test]- fn once_requires_a_date_and_weekly_carries_the_selected_zone() {- assert!(schedule_draft("once", "", "", "", "UTC", "", "bad", &Value::Null).is_err());- let draft = schedule_draft(- "weekly",- "14",- "20",- "0",- "Asia/Taipei",- "",- "",- &Value::Null,- )- .unwrap();- assert_eq!(draft["weekday"], 0);+ fn cron_is_sent_as_written() {+ let draft = schedule_draft("cron", "Asia/Taipei", "20 14 * * 0", &Value::Null);+ assert_eq!(draft["calendarStyle"], "custom");+ assert_eq!(draft["expression"], "20 14 * * 0");assert_eq!(draft["zone"], "Asia/Taipei");}}diff --git a/apps/linux/src/ui_tests.rs b/apps/linux/src/ui_tests.rsindex 5d267762..c948ef00 100644--- a/apps/linux/src/ui_tests.rs+++ b/apps/linux/src/ui_tests.rs@@ -203,32 +203,75 @@ fn native_ui_flows() {click(&routines, "Ask the bot for a routine");wait(|| ui.window.visible_dialog().is_none());let buf = ui.compose.view.buffer();- assert!(buf.text(&buf.start_iter(), &buf.end_iter(), false).contains("I want a routine that"));- buf.set_text("");- let saved = Rc::new(std::cell::Cell::new(false));- let saved2 = saved.clone();- crate::client::call(- "saveRoutine",- serde_json::json!({"botId": "bot", "name": "Morning review", "instruction": "Review the latest changes"}),- move |_| saved2.set(true),+ assert!(+ buf.text(&buf.start_iter(), &buf.end_iter(), false)+ .contains("I want a routine that"));- wait(|| saved.get());+ buf.set_text("");crate::manage::routines(&ui, "bot");let routines = ui.window.visible_dialog().unwrap();- wait(|| text(&routines, "Morning review"));- click(&routines, "Edit routine");+ click(&routines, "Set up a routine");let editor = ui.window.visible_dialog().unwrap();- wait(|| widgets(&editor).into_iter().filter_map(|w| w.downcast::<gtk::Entry>().ok()).any(|e| e.text() == "Morning review"));+ let entries: Vec<_> = widgets(&editor)+ .into_iter()+ .filter_map(|w| w.downcast::<gtk::Entry>().ok())+ .collect();+ entries[0].set_text("Morning review");+ let instruction = widgets(&editor)+ .into_iter()+ .find_map(|w| w.downcast::<gtk::TextView>().ok())+ .unwrap();+ instruction.buffer().set_text("Review the latest changes");click(&editor, "Preview schedule");wait(|| text(&editor, "Daily at 09:00 UTC"));screenshot("linux-routine-editor");click(&editor, "Save");- wait(|| ui.window.visible_dialog().as_ref() == Some(&routines));- let switch = widgets(&routines).into_iter().find_map(|w| w.downcast::<gtk::Switch>().ok()).unwrap();+ wait(|| text(&routines, "Morning review"));+ let switch = widgets(&routines)+ .into_iter()+ .find_map(|w| w.downcast::<gtk::Switch>().ok())+ .unwrap();switch.set_active(false);- wait(|| widgets(&routines).into_iter().filter_map(|w| w.downcast::<gtk::Switch>().ok()).any(|s| !s.is_active()));+ wait(|| {+ widgets(&routines)+ .into_iter()+ .filter_map(|w| w.downcast::<gtk::Switch>().ok())+ .any(|s| !s.is_active())+ });screenshot("linux-routines");++ // A new webhook routine reopens on its public URL and key.+ click(&routines, "Set up a routine");+ let editor = ui.window.visible_dialog().unwrap();+ let entries: Vec<_> = widgets(&editor)+ .into_iter()+ .filter_map(|w| w.downcast::<gtk::Entry>().ok())+ .collect();+ entries[0].set_text("Deploy hook");+ widgets(&editor)+ .into_iter()+ .find_map(|w| w.downcast::<gtk::TextView>().ok())+ .unwrap()+ .buffer()+ .set_text("Summarize the deploy");+ widgets(&editor)+ .into_iter()+ .find_map(|w| w.downcast::<gtk::DropDown>().ok())+ .unwrap()+ .set_selected(1);+ click(&editor, "Save");+ wait(|| {+ ui.window.visible_dialog().is_some_and(|d| {+ d != editor && d != routines && text(&d, "https://cloud.example/v1/hooks/c/hook")+ })+ });+ let hook = ui.window.visible_dialog().unwrap();+ assert!(!text(&hook, "fixture-key"), "the key starts hidden");+ click(&hook, "Show key");+ wait(|| text(&hook, "fixture-key-0123456789abcdef0123456789"));+ screenshot("linux-routine-webhook");+ close(&ui);close(&ui);crate::market::open(&ui);diff --git a/apps/linux/tests/ui_fixture.py b/apps/linux/tests/ui_fixture.pyindex c78d880f..8a7e3029 100644--- a/apps/linux/tests/ui_fixture.py+++ b/apps/linux/tests/ui_fixture.py@@ -65,16 +65,25 @@ class Host(BaseHTTPRequestHandler):if method == "routines":return self.send_json(dict(routines=cls.routines, runs=[]))if method == "saveRoutine":- assert body["schedule"]["kind"] == "cron"+ kind = body["schedule"]["kind"]+ assert kind in ("cron", "webhook")assert body["timeoutSeconds"] == 3600- routine = dict(id="routine", name=body["name"], instruction=body["instruction"], enabled=True, triggers=[dict(type="cron", expression="0 9 * * *", timeZone="UTC")], triggerDescriptions=["Daily at 09:00 UTC"], nextRunAt=1820000000000)- cls.routines = [routine]- return self.send_json(routine)+ if kind == "cron":+ routine = dict(id="routine", name=body["name"], instruction=body["instruction"], enabled=True, triggers=[dict(type="cron", expression="0 9 * * *", timeZone="UTC")], triggerDescriptions=["Daily at 09:00 UTC"], nextRunAt=1820000000000)+ else:+ routine = dict(id="hook", name=body["name"], instruction=body["instruction"], enabled=True, triggers=[dict(type="webhook")], triggerDescriptions=["When a webhook fires"], nextRunAt=None)+ cls.routines = [r for r in cls.routines if r["id"] != routine["id"]] + [routine]+ return self.send_json(dict(routine=routine))+ if method == "routineWebhook":+ key = "rotated-key-0123456789abcdef0123456789" if body.get("rotate") else "fixture-key-0123456789abcdef0123456789"+ return self.send_json(dict(url="https://cloud.example/v1/hooks/c/" + body["id"], localUrl="http://127.0.0.1:19222/hooks/routines/" + body["id"], key=key, connected=True))if method == "routineSchedule":return self.send_json(dict(summary="Daily at 09:00 UTC", nextRunAt=1820000000000))if method == "setRoutineEnabled":- cls.routines[0]["enabled"] = body["enabled"]- cls.routines[0]["nextRunAt"] = 1820000000000 if body["enabled"] else None+ for r in cls.routines:+ if r["id"] == body["id"]:+ r["enabled"] = body["enabled"]+ r["nextRunAt"] = 1820000000000 if body["enabled"] and r["id"] == "routine" else Noneif method == "deleteRoutine":cls.routines = []if method == "skills":diff --git a/docs/design/ui-conventions.md b/docs/design/ui-conventions.mdindex 35bd425b..806b2404 100644--- a/docs/design/ui-conventions.md+++ b/docs/design/ui-conventions.md@@ -62,9 +62,9 @@ Model discovery keeps loading and refresh in one fixed-size slot beside the ModeThe details inspector uses a compact device summary instead of an empty screen preview. Keep the computer name, remote-screen state, and iPhone hint together; show the hint only when screen capture is ready. Use 16-point horizontal insets, 28-point section gaps, and 12-point corner radii on flat surfaces, without borders.-Routines are a compact grouped list: name, a one-line schedule (or the live run state), and an on/off switch per row; tapping a row opens its details. New routines are set up by asking the bot: the header's + puts "I want a routine that " in the chat's composer. The empty state is one line of text. Agent metadata uses Runtime and Workspace labels for personal bots, or Project folder for explicitly configured projects; project paths remain selectable and wrap. Personal workspace paths stay out of the default details UI. Keep status and section headings readable in both appearances through `Palette`.+Routines are a compact grouped list: name, a one-line schedule (or the live run state), and an on/off switch per row; tapping a row opens the same form as +, filled in, with delete and test run beside Save. On the Mac the form card fits its content. The header's chat button asks the bot (puts "I want a routine that " in the composer); + opens the form, where When to run is a type choice and cron is typed directly. The empty state is one line of text. A saved webhook routine's form shows the public URL and key as filled monospaced rows with copy, show/hide and replace-key (confirmed) icon buttons, and one caption on how to send and that deliveries pass through the Codync cloud. Agent metadata uses Runtime and Workspace labels for personal bots, or Project folder for explicitly configured projects; project paths remain selectable and wrap. Personal workspace paths stay out of the default details UI. Keep status and section headings readable in both appearances through `Palette`.-On iPhone, the routine editor uses a single column of trigger choices so titles and descriptions can wrap at larger text sizes. Keep the execution environment note in the scrollable form and the full-width save action in a fixed footer on the sheet background. When required fields are empty, the footer explains why saving is unavailable.+On iPhone, the routine editor keeps the full-width save action in a fixed footer on the sheet background. When required fields are empty, the footer explains why saving is unavailable.New bots use automatically allocated personal workspaces. Settings offer Personal or an optional project folder; see [bot workspaces](../features/bot-workspaces.md).@@ -96,8 +96,8 @@ SwiftUI already supplies these actions and needs no duplicate implementation.a draft edited while the request was running.- GTK bot menus include **Memory** and **Routines**. Memory supports forgetting one orall facts. Routines are a boxed list with an on/off switch,- edit (schedule previews), test run and delete per row; + asks the bot for a new one- in the chat composer. The host validates schedules;+ edit, test run and delete per row; + opens the form (type + raw cron, host+ preview) and the chat button asks the bot in the composer. The host validates schedules;editing can preserve existing event, interval and multiple triggers.- GTK **Marketplace** includes agents, connectors and skills. Agent setup supportsinstall/login terminals, browser authentication and masked credential fields.diff --git a/host/src/routines/schedule.rs b/host/src/routines/schedule.rsindex 68f45a4c..04d327c0 100644--- a/host/src/routines/schedule.rs+++ b/host/src/routines/schedule.rs@@ -104,7 +104,8 @@ impl Trigger {.map_or_else(|| "Once".into(), |d| format!("Once at {}", d.to_rfc3339())),Self::Cron { expression, time_zone } => format!("{} · {time_zone}",- Cron::from_str(expression).map_or_else(|_| expression.clone(), |cron| cron.describe())+ Cron::from_str(expression)+ .map_or_else(|_| expression.clone(), |cron| cron.describe().trim_end_matches('.').to_owned())),Self::Webhook => "When a webhook fires".into(),Self::Event { source, event, .. } => format!("{source} · {event}"),diff --git a/host/src/tui/app.rs b/host/src/tui/app.rsindex 4513aff4..459ba604 100644--- a/host/src/tui/app.rs+++ b/host/src/tui/app.rs@@ -464,6 +464,7 @@ pub enum ConfirmAct {NewSession(String),ClearMemory(String),DeleteRoutine(String, String),+ RotateRoutineKey(String, String),RemoveConnector(String),RemoveSkill(String),}@@ -1997,6 +1998,11 @@ impl App {ConfirmAct::DeleteRoutine(bot, id) => {self.call("deleteRoutine", json!({"botId": bot, "id": id}), changed);}+ ConfirmAct::RotateRoutineKey(bot, id) => self.call(+ "routineWebhook",+ json!({"botId": bot, "id": id, "rotate": true}),+ After::Sheet(Reply::Webhook),+ ),ConfirmAct::RemoveConnector(id) => self.call("removeConnector", json!({"id": id}), changed),ConfirmAct::RemoveSkill(id) => self.call("removeSkill", json!({"id": id}), changed),}diff --git a/host/src/tui/manage.rs b/host/src/tui/manage.rsindex 493c3736..d5c5d1d7 100644--- a/host/src/tui/manage.rs+++ b/host/src/tui/manage.rs@@ -20,6 +20,8 @@ pub enum Reply {Memory(String),Routines(String),RoutineSaved,+ /// A routine's webhook URL and key: copied as a ready-to-run curl.+ Webhook,Registry {more: bool,},@@ -256,7 +258,23 @@ impl App {(KeyCode::Down | KeyCode::Char('j'), _) => l.cursor = (l.cursor + 1).min(n.saturating_sub(1)),(KeyCode::Up | KeyCode::Char('k'), _) => l.cursor = l.cursor.saturating_sub(1),(KeyCode::Char('n'), _) => {- // New routines are set up by talking to the bot: start the ask in its chat.+ self.overlays.push(Overlay::Routines(l));+ self.overlays.push(Overlay::Routine(Box::new(RoutineForm {+ bot,+ id: None,+ name: Editor::default(),+ instruction: Editor::default(),+ when: Editor::default(),+ original: Value::Null,+ original_text: String::new(),+ field: RoutineField::Name,+ error: None,+ saving: false,+ })));+ return None;+ }+ (KeyCode::Char('c'), _) => {+ // Or ask the bot to set one up: start the ask in its chat.let draft = self.drafts.entry(bot).or_default();if !draft.text.is_empty() {draft.insert("\n");@@ -304,6 +322,24 @@ impl App {self.sheet("runRoutine", json!({"botId": bot, "id": r["id"]}), Reply::Routines(bot.clone()));self.flash(&format!("Running {} now", s(&r, "name")));}+ (KeyCode::Char('w' | 'W'), Some(r)) if !has_webhook(&r) => {+ self.flash("Only a routine that runs on a webhook has a URL and key");+ }+ (KeyCode::Char('w'), Some(r)) => {+ self.sheet("routineWebhook", json!({"botId": bot, "id": r["id"]}), Reply::Webhook);+ }+ (KeyCode::Char('W'), Some(r)) => {+ let c = Confirm {+ title: format!("Replace the webhook key of {}?", s(&r, "name")),+ detail: "Senders using the current key stop working.".into(),+ note: "The new one is copied in a curl command.".into(),+ button: "Replace",+ act: ConfirmAct::RotateRoutineKey(bot, s(&r, "id")),+ };+ self.overlays.push(Overlay::Routines(l));+ self.overlays.push(Overlay::Confirm(c));+ return None;+ }(KeyCode::Char('x'), Some(r)) => {let c = Confirm {title: format!("Delete the routine {}?", s(&r, "name")),@@ -956,6 +992,19 @@ impl App {}self.refresh_sheets();}+ Reply::Webhook => {+ let url = v["url"].as_str().or_else(|| v["localUrl"].as_str()).unwrap_or_default();+ let text = format!(+ "curl -X POST '{url}' -H 'Authorization: Bearer {}' -H 'Content-Type: application/json' -d '{{}}'",+ s(&v, "key")+ );+ super::app::copy(&text);+ self.flash(if v["url"].is_string() {+ "Copied a curl command for the public URL (with its key)"+ } else {+ "Copied a curl command (the cloud is off: this computer only)"+ });+ }Reply::Registry { more } => {if let Some(Overlay::Market(m)) =self.overlays.iter_mut().rev().find(|o| matches!(o, Overlay::Market(_)))@@ -1236,6 +1285,11 @@ pub fn key_bytes(k: KeyEvent) -> Vec<u8> {out}+/// A routine with a webhook (or event) trigger, which has a URL and key.+fn has_webhook(r: &Value) -> bool {+ r["triggers"].as_array().into_iter().flatten().any(|t| matches!(t["type"].as_str(), Some("webhook" | "event")))+}+/// This computer's IANA time zone (routines run on the host's clock in it).pub fn local_zone() -> String {let valid = |z: &str| chrono_tz::Tz::from_str(z).is_ok();diff --git a/host/src/tui/sheets.rs b/host/src/tui/sheets.rsindex b63a41b8..ca3a1867 100644--- a/host/src/tui/sheets.rs+++ b/host/src/tui/sheets.rs@@ -100,7 +100,7 @@ pub fn routines(buf: &mut Buffer, area: Rect, app: &App, l: &RoutineList) {inner.x,inner.y + 1,inner.width,- "No routines. n asks the bot for one: tell it what to run and when.",+ "No routines. c asks the bot for one; n sets one up here.",t.secondary.patch(t.panel),);}@@ -131,7 +131,12 @@ pub fn routines(buf: &mut Buffer, area: Rect, app: &App, l: &RoutineList) {}}}- footer(buf, inner, None, "n ask the bot · ↵ edit · space on/off · r run now · x delete · esc");+ footer(+ buf,+ inner,+ None,+ "n new · c ask the bot · ↵ edit · space on/off · r run now · w copy webhook · W new key · x delete · esc",+ );}pub fn routine(buf: &mut Buffer, area: Rect, f: &RoutineForm) {diff --git a/kit/Sources/CodyncKit/Models/Routine.swift b/kit/Sources/CodyncKit/Models/Routine.swiftindex 530f7247..e067544a 100644--- a/kit/Sources/CodyncKit/Models/Routine.swift+++ b/kit/Sources/CodyncKit/Models/Routine.swift@@ -51,6 +51,15 @@ public struct RoutineListing: Codable, Sendable {public var runs: [RoutineRun]}+/// A routine's webhook: `url` is public through the Codync cloud (nil while the cloud is off),+/// `localUrl` works on the host itself.+public struct RoutineWebhook: Codable, Sendable, Equatable {+ public var url: String?+ public var localUrl: String+ public var key: String+ public var connected: Bool+}+extension HostClient {public func routines(botId: String) async throws -> RoutineListing {struct Body: Encodable { let botId: String }@@ -61,6 +70,12 @@ extension HostClient {struct Body: Encodable { let botId: String; let id: String; let enabled: Bool? }let _: Empty = try await call(method, Body(botId: botId, id: id, enabled: enabled))}++ /// `rotate` replaces the key first; senders using the old one stop working.+ public func routineWebhook(botId: String, id: String, rotate: Bool = false) async throws -> RoutineWebhook {+ struct Body: Encodable { let botId: String; let id: String; let rotate: Bool }+ return try await call("routineWebhook", Body(botId: botId, id: id, rotate: rotate))+ }}extension HostClient {diff --git a/kit/Sources/CodyncUI/Routines/RoutineEditorView.swift b/kit/Sources/CodyncUI/Routines/RoutineEditorView.swiftindex ed02bf49..3a424b2e 100644--- a/kit/Sources/CodyncUI/Routines/RoutineEditorView.swift+++ b/kit/Sources/CodyncUI/Routines/RoutineEditorView.swift@@ -3,8 +3,9 @@ import SwiftUIstruct RoutineEditorView: View {let botId: String- let routine: Routine- let saved: (Routine) -> Void+ let routine: Routine?+ /// Called after a save (the routine) or a delete (nil).+ let saved: (Routine?) -> Void@Environment(BotStore.self) private var model@Environment(\.accessibilityReduceMotion) private var reduceMotion@State private var name = ""@@ -18,16 +19,24 @@ struct RoutineEditorView: View {@State private var preview: RoutineSchedulePreview?@State private var previewError: String?@State private var checkedSchedule: RoutineScheduleDraft?+ @State private var confirmDelete = false+ @State private var started = false+ /// Schedule or webhook, as in Claude Code routines. Anything else the bot set up+ /// (a one-off time, an interval, events, several triggers) stays as it is until replaced.private var options: [(String, String)] {- var values = [("keep", "Keep existing triggers"), ("cron", "Recurring schedule"),- ("once", "Run once"), ("webhook", "Webhook")]- if schedule.original.contains(where: { $0.type == "interval" }) {- values.append(("interval", "Existing interval"))+ var values = [("cron", "Schedule"), ("webhook", "Webhook")]+ if let routine, keepsOriginal {+ values.insert(("keep", routine.triggerDescriptions.joined(separator: " · ")), at: 0)}return values}+ private var keepsOriginal: Bool {+ guard let routine, routine.triggers.count == 1 else { return routine != nil && !(routine?.triggers.isEmpty ?? true) }+ return !["cron", "webhook"].contains(routine.triggers[0].type)+ }+private var canSave: Bool {!name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty &&!instruction.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && !model.isOffline && !busy &&@@ -36,50 +45,14 @@ struct RoutineEditorView: View {var body: some View {VStack(spacing: 0) {- ModalHeader("Edit routine")- ScrollView {- VStack(alignment: .leading, spacing: 24) {- VStack(alignment: .leading, spacing: 14) {- Field("Name") {- TextField("Name", text: $name, prompt: Text("e.g. Morning summary").foregroundStyle(Palette.text.opacity(0.7))).routineInput()- }- Field("Instruction") {- TextField("Instruction", text: $instruction, prompt: Text("Describe what this bot should do each time it runs.").foregroundStyle(Palette.text.opacity(0.7)), axis: .vertical)- .lineLimit(3...8).routineInput()- }- }- VStack(alignment: .leading, spacing: 14) {- Text("When to run").font(.subheadline.weight(.semibold))- triggerChoices- if loaded { triggerFields }- else { Label("Loading schedule…", systemImage: "clock").foregroundStyle(Palette.secondary) }- }- VStack(alignment: .leading, spacing: 12) {- Button {- withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { advanced.toggle() }- } label: {- HStack {- Text("Run settings").font(.subheadline.weight(.medium))- Spacer()- Text("Timeout: \(timeout)s").font(.caption).foregroundStyle(Palette.secondary)- Image(systemName: advanced ? "chevron.up" : "chevron.down").font(.caption)- }- .contentShape(Rectangle())- }- .buttonStyle(.plain)- .accessibilityValue(advanced ? "Expanded" : "Collapsed")- if advanced {- Field("Run timeout (seconds)") { TextField("3600", text: $timeout).routineInput() }- Text("Stop a run if it exceeds this limit. Between 1 second and 24 hours.")- .font(.caption).foregroundStyle(Palette.secondary)- }- }- #if os(iOS)- executionNote- #endif- }- .padding(20)- .frame(maxWidth: .infinity, alignment: .leading)+ ModalHeader(routine == nil ? "Set up a routine" : "Edit routine")+ Group {+ #if os(macOS)+ // The card fits the form; it scrolls only when taller than the window allows.+ ViewThatFits(in: .vertical) { form; ScrollView { form } }+ #else+ ScrollView { form }+ #endif}.disabled(busy || !loaded)footer@@ -87,10 +60,23 @@ struct RoutineEditorView: View {.font(.system(size: InterfaceMetrics.value(mac: 13, mobile: 16))).foregroundStyle(Palette.text).background(Palette.background)+ .codyncDialog("Delete routine?", isPresented: $confirmDelete, message: "This deletes the routine and stops its future runs. This can't be undone.") {+ [DialogAction("Delete routine", destructive: true) {+ guard let routine else { return }+ Task {+ do {+ try await model.client?.routineAction("deleteRoutine", botId: botId, id: routine.id)+ saved(nil)+ } catch { self.error = error.localizedDescription }+ }+ }]+ }.task {- name = routine.name- instruction = routine.instruction- timeout = String(routine.timeoutSeconds ?? 3600)+ if let routine {+ name = routine.name+ instruction = routine.instruction+ timeout = String(routine.timeoutSeconds ?? 3600)+ }await loadSchedule()}.task(id: schedule) {@@ -101,6 +87,53 @@ struct RoutineEditorView: View {}}+ private var form: some View {+ VStack(alignment: .leading, spacing: 24) {+ VStack(alignment: .leading, spacing: 14) {+ Field("Name") {+ TextField("Name", text: $name, prompt: Text("e.g. Morning summary").foregroundStyle(Palette.secondary)).routineInput()+ }+ Field("Instruction") {+ TextField("Instruction", text: $instruction, prompt: Text("Describe what this bot should do each time it runs.").foregroundStyle(Palette.secondary), axis: .vertical)+ .lineLimit(3...8).routineInput()+ }+ }+ VStack(alignment: .leading, spacing: 14) {+ Field("When to run") {+ ChoicePicker(selection: $schedule.kind, options: options.map { (id: $0.0, label: $0.1) }, fitsAvailableWidth: true)+ }+ if loaded { triggerFields }+ else { Label("Loading schedule…", systemImage: "clock").foregroundStyle(Palette.secondary) }+ }+ VStack(alignment: .leading, spacing: 12) {+ Button {+ withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { advanced.toggle() }+ } label: {+ HStack(spacing: 6) {+ Text("Run settings")+ Image(systemName: "chevron.down").font(.caption2.weight(.semibold))+ .rotationEffect(.degrees(advanced ? 180 : 0))+ Spacer()+ if !advanced { Text("Timeout \(timeout)s").foregroundStyle(Palette.tertiary) }+ }+ .font(InterfaceMetrics.secondary)+ .foregroundStyle(Palette.secondary)+ .padding(.leading, 4)+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .accessibilityValue(advanced ? "Expanded" : "Collapsed")+ if advanced {+ Field("Timeout (seconds)") { TextField("3600", text: $timeout).routineInput() }+ Text("A run is stopped after this long. 1 second to 24 hours.")+ .font(.caption).foregroundStyle(Palette.secondary).padding(.leading, 4)+ }+ }+ }+ .padding(20)+ .frame(maxWidth: .infinity, alignment: .leading)+ }+private func checkSchedule() async {let requested = schedulepreview = nil@@ -122,8 +155,10 @@ struct RoutineEditorView: View {private func loadSchedule() async {guard let client = model.client else { error = "Connect to this computer to load the schedule."; return }do {- let result = try await client.routineSchedule(triggers: routine.triggers, timeZone: TimeZone.current.identifier)+ let result = try await client.routineSchedule(triggers: routine?.triggers ?? [], timeZone: TimeZone.current.identifier)schedule = result.draft+ schedule.calendarStyle = "custom"+ if !["cron", "webhook"].contains(schedule.kind) { schedule.kind = "keep" }preview = resultcheckedSchedule = result.draftloaded = true@@ -131,90 +166,69 @@ struct RoutineEditorView: View {} catch { self.error = error.localizedDescription }}- private func selectFrequency(_ style: String) {- guard style == "custom" else { schedule.calendarStyle = style; return }- let requested = schedule- Task {- do {- guard let client = model.client else { return }- let result = try await client.routineSchedule(draft: requested)- guard requested == schedule else { return }- schedule.expression = result.triggers.first?.expression ?? ""- schedule.calendarStyle = style- } catch { previewError = error.localizedDescription }+ @ViewBuilder private var triggerFields: some View {+ switch schedule.kind {+ case "cron":+ cronFields+ case "webhook":+ if let routine, routine.triggers.contains(where: { $0.type == "webhook" || $0.type == "event" }) {+ RoutineWebhookPanel(botId: botId, routineId: routine.id)+ } else {+ Text("Runs each time something is posted to its URL. Save to get the URL and key.")+ .font(.caption).foregroundStyle(Palette.secondary).padding(.leading, 4)+ .fixedSize(horizontal: false, vertical: true)+ }+ default:+ Text("Set up by the bot. Pick Schedule or Webhook to replace it.")+ .font(.caption).foregroundStyle(Palette.secondary).padding(.leading, 4)}}- @ViewBuilder private var triggerChoices: some View {- #if os(iOS)- VStack(spacing: 8) {- ForEach(options, id: \.0) { option in triggerChoice(option) }+ /// Cron is written directly; the host checks it and describes when it runs.+ private var cronFields: some View {+ VStack(alignment: .leading, spacing: 8) {+ ViewThatFits(in: .horizontal) {+ HStack(alignment: .top, spacing: 10) { expressionField; zoneField.frame(width: 170) }+ VStack(alignment: .leading, spacing: 14) { expressionField; zoneField }+ }+ schedulePreview.padding(.leading, 4)}- #else- LazyVGrid(columns: [GridItem(.adaptive(minimum: 180), spacing: 8)], spacing: 8) {- ForEach(options, id: \.0) { option in triggerChoice(option) }+ }++ private var expressionField: some View {+ Field("Cron") {+ TextField("Cron", text: $schedule.expression, prompt: Text("0 9 * * 1-5").foregroundStyle(Palette.secondary))+ .font(.body.monospaced()).autocorrectionDisabled().routineInput()+ .frame(minWidth: 220)}- #endif}- private func triggerChoice(_ option: (String, String)) -> some View {- let selected = schedule.kind == option.0- let symbols = ["interval": "arrow.clockwise", "cron": "calendar",- "once": "clock", "webhook": "link", "keep": "checklist"]- let details = ["interval": "Repeat at a fixed interval", "cron": "Choose days and times",- "once": "At a specific date and time", "webhook": "When an event arrives",- "keep": "Preserve the current schedule"]- return Button {- withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { schedule.kind = option.0 }- } label: {- HStack(alignment: .top, spacing: 10) {- Image(systemName: symbols[option.0] ?? "clock")- .font(.system(size: 15)).frame(width: 20).padding(.top, 2)- VStack(alignment: .leading, spacing: 4) {- Text(option.1).font(.subheadline.weight(.medium))- Text(details[option.0] ?? "").font(.caption).foregroundStyle(selected ? Palette.text.opacity(0.75) : Palette.secondary)- }- .fixedSize(horizontal: false, vertical: true)- .frame(maxWidth: .infinity, alignment: .leading)- Image(systemName: "checkmark").font(.caption.weight(.semibold)).opacity(selected ? 1 : 0)- }- .padding(12)- .frame(maxWidth: .infinity, minHeight: 70, alignment: .topLeading)- .background(selected ? Palette.bubbleUser : Palette.bubbleAgent,- in: RoundedRectangle(cornerRadius: 12))- .contentShape(RoundedRectangle(cornerRadius: 12))+ private var zoneField: some View {+ Field("Time zone") {+ TextField("Time zone", text: $schedule.zone, prompt: Text("Asia/Taipei").foregroundStyle(Palette.secondary))+ .autocorrectionDisabled().routineInput()}- .buttonStyle(.plain)- .accessibilityAddTraits(selected ? .isSelected : [])}- @ViewBuilder private var triggerFields: some View {- switch schedule.kind {- case "interval":- Text("This saved interval keeps its original cadence. Choose Recurring schedule to replace it with a clock-based schedule.")- .font(.caption).foregroundStyle(Palette.secondary)- Field("Repeat every") {- TextField("Interval", text: $schedule.amount).routineInput()- SegmentedChoice(selection: $schedule.unit, options: [(1, "Seconds"), (60, "Minutes"), (3600, "Hours"), (86400, "Days")])- }- case "cron":- RoutineCalendarFields(schedule: $schedule, preview: checkedSchedule == schedule ? preview : nil, previewError: previewError, selectFrequency: selectFrequency)- case "once":- DatePicker("Run at", selection: $schedule.date)- .padding(12).background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 12))- Text("Time zone: \(TimeZone.current.identifier)").font(.caption).foregroundStyle(Palette.secondary)- case "webhook":- VStack(alignment: .leading, spacing: 6) {- Label("Local connection", systemImage: "desktopcomputer").font(.subheadline.weight(.medium))- Text("Save to get a URL and secret key. External services need a public forwarding connection, configured separately.")- .font(.caption).foregroundStyle(Palette.secondary)- }- .frame(maxWidth: .infinity, alignment: .leading)- .padding(14).background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 12))- default:- ForEach(routine.triggerDescriptions, id: \.self) {- Label($0, systemImage: "clock").font(.callout).foregroundStyle(Palette.secondary)+ /// One quiet line under the fields: what the host read, or why it can't.+ @ViewBuilder private var schedulePreview: some View {+ let preview = checkedSchedule == schedule ? preview : nil+ if let previewError {+ Text(previewError).font(.caption).foregroundStyle(Palette.danger)+ .fixedSize(horizontal: false, vertical: true)+ } else if let preview {+ VStack(alignment: .leading, spacing: 2) {+ Text(preview.summary).font(.caption.weight(.medium))+ if let next = preview.nextRunAt {+ Text("Next \(Date(milliseconds: next).formatted(date: .abbreviated, time: .shortened))")+ .font(.caption).foregroundStyle(Palette.secondary)+ }+ if let warning = preview.warning {+ Text(warning).font(.caption).foregroundStyle(Palette.secondary)+ }}+ } else {+ Text("minute hour day month weekday").font(.caption.monospaced()).foregroundStyle(Palette.tertiary)}}@@ -245,12 +259,9 @@ struct RoutineEditorView: View {Text("Enter a name and instruction above to save.").font(.caption).foregroundStyle(Palette.secondary)}- saveButton+ HStack(spacing: 16) { routineActions; saveButton }#else- ViewThatFits(in: .horizontal) {- HStack(spacing: 16) { executionNote; Spacer(minLength: 0); saveButton }- VStack(alignment: .leading, spacing: 12) { executionNote; saveButton }- }+ HStack(spacing: 16) { routineActions; Spacer(minLength: 0); saveButton }#endif}.padding(20)@@ -258,16 +269,22 @@ struct RoutineEditorView: View {#if os(iOS).padding(.bottom, 16).background(Palette.background)- #else- .background(Palette.bubbleAgent)#endif}- private var executionNote: some View {- VStack(alignment: .leading, spacing: 3) {- Label("Runs on the bot’s computer", systemImage: "desktopcomputer").font(.caption.weight(.medium))- Text("Keep the host running and computer awake.")- .font(.caption).foregroundStyle(Palette.secondary)+ /// An existing routine's own actions: delete and run it now.+ @ViewBuilder private var routineActions: some View {+ if let routine {+ IconButton("Delete routine", systemImage: "trash") { confirmDelete = true }+ IconButton(started ? "Started" : "Test run", systemImage: started ? "checkmark" : "play.circle") {+ Task {+ do {+ try await model.client?.routineAction("runRoutine", botId: botId, id: routine.id)+ withAnimation(Motion.reduced(Motion.hover, reduceMotion)) { started = true }+ } catch { self.error = error.localizedDescription }+ }+ }+ .disabled(started || model.isOffline)}}@@ -275,7 +292,7 @@ struct RoutineEditorView: View {Button(action: save) {HStack(spacing: 8) {if busy { Spinner() }- Text(busy ? "Saving…" : "Save changes")+ Text(busy ? "Saving…" : routine == nil ? "Create routine" : "Save changes").fixedSize(horizontal: false, vertical: true)}#if os(iOS)@@ -294,7 +311,7 @@ struct RoutineEditorView: View {Task {defer { busy = false }do {- let result = try await client.saveRoutine(botId: botId, id: routine.id, name: name,+ let result = try await client.saveRoutine(botId: botId, id: routine?.id, name: name,instruction: instruction, schedule: schedule, timeoutSeconds: timeout)saved(result)} catch { self.error = error.localizedDescription }diff --git a/kit/Sources/CodyncUI/Routines/RoutineWebhookPanel.swift b/kit/Sources/CodyncUI/Routines/RoutineWebhookPanel.swiftnew file mode 100644index 00000000..7794b7ca--- /dev/null+++ b/kit/Sources/CodyncUI/Routines/RoutineWebhookPanel.swift@@ -0,0 +1,91 @@+import CodyncKit+import SwiftUI++/// A saved webhook routine's address and key: copy either, reveal or replace the key.+struct RoutineWebhookPanel: View {+ let botId: String+ let routineId: String+ @Environment(BotStore.self) private var model+ @Environment(\.accessibilityReduceMotion) private var reduceMotion+ @State private var webhook: RoutineWebhook?+ @State private var error: String?+ @State private var showKey = false+ @State private var copied: String?+ @State private var confirmRotate = false+ @State private var rotating = false++ var body: some View {+ VStack(alignment: .leading, spacing: 14) {+ if let webhook {+ Field(webhook.url == nil ? "Local URL" : "URL") {+ value(webhook.url ?? webhook.localUrl, copy: "url")+ }+ Field("Key") {+ value(showKey ? webhook.key : String(repeating: "•", count: 24), copy: "key") {+ IconButton(showKey ? "Hide key" : "Show key", systemImage: showKey ? "eye.slash" : "eye") {+ withAnimation(Motion.reduced(Motion.hover, reduceMotion)) { showKey.toggle() }+ }+ IconButton("Replace key", systemImage: "arrow.triangle.2.circlepath") { confirmRotate = true }+ .disabled(rotating || model.isOffline)+ }+ }+ Text(note(webhook))+ .font(.caption).foregroundStyle(Palette.secondary).padding(.leading, 4)+ .fixedSize(horizontal: false, vertical: true)+ } else if let error {+ Text(error).font(.caption).foregroundStyle(Palette.danger).padding(.leading, 4)+ } else {+ Text("Loading webhook…").font(.caption).foregroundStyle(Palette.secondary).padding(.leading, 4)+ }+ }+ .task(id: routineId) { await load(rotate: false) }+ .codyncDialog("Replace the key?", isPresented: $confirmRotate,+ message: "Senders using the current key stop working until they get the new one.") {+ [DialogAction("Replace key", destructive: true) { Task { await load(rotate: true) } }]+ }+ }++ private func note(_ webhook: RoutineWebhook) -> String {+ guard webhook.url != nil else {+ return "The Codync cloud is off, so only this computer can send to it."+ }+ return "POST with Authorization: Bearer <key>. For GitHub, use content type application/json and the key as the secret. "+ + "Deliveries wait up to 72 hours while this computer is off. They pass through the Codync cloud, which can read them."+ }++ /// A selectable monospaced value with a copy button, plus any extra buttons.+ private func value(_ text: String, copy: String, @ViewBuilder extra: () -> some View = { EmptyView() }) -> some View {+ HStack(alignment: .center, spacing: 8) {+ Text(text)+ .font(.callout.monospaced())+ .lineLimit(2)+ .truncationMode(.middle)+ .textSelection(.enabled)+ .frame(maxWidth: .infinity, alignment: .leading)+ extra()+ IconButton(copied == copy ? "Copied" : "Copy", systemImage: copied == copy ? "checkmark" : "doc.on.doc") {+ guard let webhook else { return }+ Pasteboard.copy(copy == "key" ? webhook.key : webhook.url ?? webhook.localUrl)+ withAnimation(Motion.reduced(Motion.hover, reduceMotion)) { copied = copy }+ }+ }+ .padding(.vertical, 8)+ .padding(.leading, 12)+ .padding(.trailing, 6)+ .background(Palette.bubbleUser, in: RoundedRectangle(cornerRadius: 12))+ }++ private func load(rotate: Bool) async {+ guard let client = model.client else { error = "Connect to this computer to see the webhook."; return }+ rotating = rotate+ defer { rotating = false }+ do {+ let value = try await client.routineWebhook(botId: botId, id: routineId, rotate: rotate)+ withAnimation(Motion.reduced(Motion.hover, reduceMotion)) {+ webhook = value+ if rotate { copied = nil; showKey = true }+ }+ error = nil+ } catch { self.error = error.localizedDescription }+ }+}diff --git a/kit/Sources/CodyncUI/Routines/RoutinesView.swift b/kit/Sources/CodyncUI/Routines/RoutinesView.swiftindex f9a06fd8..3146c6f2 100644--- a/kit/Sources/CodyncUI/Routines/RoutinesView.swift+++ b/kit/Sources/CodyncUI/Routines/RoutinesView.swift@@ -1,7 +1,7 @@import CodyncKitimport SwiftUI-/// The same routine list and details in the Mac sidebar and the phone's modal.+/// The same routine list in the Mac sidebar and the phone's modal; a row opens its editor.struct RoutinesView: View {let botId: Stringvar initialId: String?@@ -10,79 +10,63 @@ struct RoutinesView: View {@Environment(\.accessibilityReduceMotion) private var reduceMotion@State private var routines: [Routine] = []@State private var runs: [RoutineRun] = []- @State private var selected: String?+ /// The routine the editor is open on; nil with `showEditor` sets up a new one.+ @State private var editingId: String?@State private var loaded = false@State private var busy = false@State private var error: String?- @State private var confirmDelete = false- @State private var openRun: ThreadTarget?@State private var showEditor = false@State private var loadError: String?- private var routine: Routine? { routines.first { $0.id == selected } }-var body: some View {VStack(alignment: .leading, spacing: 16) {HStack {- if selected != nil {- IconButton("Back to Routines", systemImage: "chevron.left") { animate { selected = nil } }- }- Text(routine?.name ?? "Routines").font(.system(size: 13, weight: .semibold))+ Text("Routines").font(.system(size: 13, weight: .semibold))Spacer(minLength: 0)- if selected == nil { askInChat }+ askInChat+ IconButton("Set up a routine", systemImage: "plus") { open(nil) }+ .disabled(model.isOffline)if let close { IconButton("Close routines", systemImage: "xmark", action: close) }}if let loadError { Text(loadError).font(.caption).foregroundStyle(Palette.danger) }if let error { Text(error).font(.caption).foregroundStyle(.red).textSelection(.enabled) }- if let routine {- detail(routine)- } else if selected != nil && loaded {- Text("This routine was deleted.").foregroundStyle(Palette.secondary)- } else {- listing- }+ listing}.foregroundStyle(Palette.text).font(.system(size: 13)).onChange(of: initialId) { _, id in- animate { selected = id }+ if let id { open(id) }}.task(id: botId) {- selected = initialId+ if let initialId { open(initialId) }repeat {await load()do { try await Task.sleep(for: .seconds(3)) } catch { break }} while !Task.isCancelled}.codyncSheet(isPresented: $showEditor) {- if let routine {- RoutineEditorView(botId: botId, routine: routine) { saved in- if let i = routines.firstIndex(where: { $0.id == saved.id }) { routines[i] = saved }+ RoutineEditorView(botId: botId, routine: routines.first { $0.id == editingId }) { saved in+ let created = editingId == nil+ if let i = routines.firstIndex(where: { $0.id == saved?.id }), let saved { routines[i] = saved }+ else if let saved { routines.append(saved) }+ // A new webhook routine stays open: its URL and key exist only now.+ if created, let saved, saved.triggers.contains(where: { $0.type == "webhook" }) {+ animate { editingId = saved.id }+ } else {animate { showEditor = false }- Task { await load() }}- #if os(macOS)- .frame(width: 540, height: 700)- #endif+ Task { await load() }}- }- .codyncDialog("Delete routine?", isPresented: $confirmDelete, message: "This deletes the routine and stops its future runs. This can't be undone.") {- [DialogAction("Delete routine", destructive: true) {- if let routine { action("deleteRoutine", routine) }- }]- }- .codyncSheet(item: $openRun) { run in- RepliesView(botId: botId, rootId: run.id) { animate { openRun = nil } }- #if os(macOS)- .frame(width: 520, height: 580)- #endif+ #if os(macOS)+ .frame(width: 540).frame(maxHeight: 700)+ #endif}}private var listing: some View {VStack(alignment: .leading, spacing: 0) {if routines.isEmpty {- Text(loaded ? "No routines yet. Tell the bot what to run and when, and it sets one up." : "Loading routines…")+ Text(loaded ? "No routines yet. Ask the bot for one, or set it up yourself with +." : "Loading routines…").font(.caption).foregroundStyle(Palette.secondary).fixedSize(horizontal: false, vertical: true)@@ -101,7 +85,7 @@ struct RoutinesView: View {private func row(_ routine: Routine) -> some View {HStack(spacing: 12) {- Button { animate { selected = routine.id } } label: {+ Button { open(routine.id) } label: {VStack(alignment: .leading, spacing: 3) {Text(routine.name).foregroundStyle(Palette.text)Text(summary(routine))@@ -125,104 +109,33 @@ struct RoutinesView: View {private func summary(_ routine: Routine) -> String {if let active = runs.first(where: { $0.routineId == routine.id && $0.isActive }) { return runLabel(active) }if routine.lastError != nil { return "Schedule needs attention" }+ if let last = runs.first(where: { $0.routineId == routine.id }), ["failed", "interrupted"].contains(last.status) {+ return "Last run \(runLabel(last).lowercased())"+ }return routine.triggerDescriptions.joined(separator: " · ")}private var askInChat: some View {- IconButton("Ask the bot for a routine", systemImage: "plus") {+ IconButton("Ask the bot for a routine", systemImage: "text.bubble") {edit("I want a routine that ")}.disabled(model.isOffline)}- private func detail(_ routine: Routine) -> some View {- VStack(alignment: .leading, spacing: 18) {- Label(stateDescription(routine), systemImage: routine.enabled ? "clock" : "pause.circle")- .font(.subheadline.weight(.medium))- if let error = routine.lastError {- Text(error).font(.caption).foregroundStyle(.red).textSelection(.enabled)- }- VStack(alignment: .leading, spacing: 8) {- Text("Instruction").fontWeight(.semibold)- Text(routine.instruction).textSelection(.enabled)- }- VStack(alignment: .leading, spacing: 8) {- Text("When to run").fontWeight(.semibold)- ForEach(Array(routine.triggerDescriptions.enumerated()), id: \.offset) { _, text in- Label(text, systemImage: "clock").foregroundStyle(Palette.secondary)- }- if routine.enabled, let next = routine.nextRunAt {- Text("Next: \(Date(milliseconds: next).formatted(date: .abbreviated, time: .shortened))")- .font(.caption).foregroundStyle(Palette.tertiary)- }- }- HStack(spacing: 16) {- IconButton(routine.enabled ? "Pause" : "Resume", systemImage: routine.enabled ? "pause" : "play") {- action("setRoutineEnabled", routine, enabled: !routine.enabled)- }- IconButton("Edit", systemImage: "pencil") { animate { showEditor = true } }- IconButton("Test run", systemImage: "play.circle") { action("runRoutine", routine) }- .disabled(runs.contains { $0.routineId == routine.id && $0.isActive })- Spacer()- IconButton("Delete routine", systemImage: "trash") { animate { confirmDelete = true } }- }- .disabled(busy || model.isOffline)- Button("Edit with bot", systemImage: "text.bubble") {- edit("Help me edit routine \(routine.name) (ID: \(routine.id)). Read its current settings with list_routines and ask what I want to change. Update this routine instead of creating a duplicate. ")- }- .buttonStyle(.plain)- .foregroundStyle(Palette.secondary)- .disabled(model.isOffline)- let history = runs.filter { $0.routineId == routine.id }- if !history.isEmpty {- VStack(alignment: .leading, spacing: 10) {- Text("Runs").fontWeight(.semibold)- ForEach(history) { run in- VStack(alignment: .leading, spacing: 3) {- HStack {- Text(runLabel(run))- Spacer()- Text(Date(milliseconds: run.createdAt), style: .relative).foregroundStyle(Palette.tertiary)- if let root = run.rootId {- IconButton("Open run conversation", systemImage: "text.bubble") { animate { openRun = ThreadTarget(id: root) } }- }- }- if let detail = run.detail { Text(detail).font(.caption).foregroundStyle(Palette.secondary) }- }- }- }- }- }- }-private func runLabel(_ run: RoutineRun) -> String {switch run.status {case "pending": "Queued"case "starting": "Starting"case "running": "Running"case "recovering": "Resuming after restart"- case "succeeded": "Completed"case "failed": "Failed"case "interrupted": "Interrupted"- case "cancelled": "Cancelled"default: run.status.capitalized}}- private func stateDescription(_ routine: Routine) -> String {- let history = runs.filter { $0.routineId == routine.id }- if let active = history.first(where: \.isActive) { return runLabel(active) }- if routine.lastError != nil { return "Schedule needs attention" }- if !routine.enabled { return "Paused" }- if let last = history.first, ["failed", "interrupted"].contains(last.status) { return "Last run: \(runLabel(last).lowercased())" }- if let next = routine.nextRunAt {- return "Next: \(Date(milliseconds: next).formatted(date: .abbreviated, time: .shortened))"- }- if routine.triggers.contains(where: { $0.type == "webhook" || $0.type == "event" }) { return "Waiting for an event" }- return "Schedule completed"- }-private func animate(_ change: () -> Void) { withAnimation(Motion.reduced(Motion.layout, reduceMotion), change) }+ private func open(_ id: String?) { animate { editingId = id; showEditor = true } }private func edit(_ text: String) {animate {model.routineDrafts[botId] = text@@ -236,7 +149,6 @@ struct RoutinesView: View {defer { busy = false }do {try await client.routineAction(method, botId: botId, id: routine.id, enabled: enabled)- if method == "deleteRoutine" { animate { selected = nil } }error = nilawait load()} catch { self.error = error.localizedDescription }diff --git a/kit/Tests/CodyncKitTests/RoutineTests.swift b/kit/Tests/CodyncKitTests/RoutineTests.swiftindex 54665eb0..f29828fb 100644--- a/kit/Tests/CodyncKitTests/RoutineTests.swift+++ b/kit/Tests/CodyncKitTests/RoutineTests.swift@@ -36,3 +36,12 @@ import Testingdraft.date = date#expect(draft.at == 1_779_000_000_001)}++@Test func routineWebhookDecodesWithAndWithoutTheCloud() throws {+ let cloud = Data(#"{"url":"https://api.codync.dev/v1/hooks/c/r","localUrl":"http://127.0.0.1:19222/hooks/routines/r","key":"k","connected":true}"#.utf8)+ let local = Data(#"{"url":null,"localUrl":"http://127.0.0.1:19222/hooks/routines/r","key":"k","connected":false}"#.utf8)+ #expect(try JSONDecoder().decode(RoutineWebhook.self, from: cloud).url == "https://api.codync.dev/v1/hooks/c/r")+ let off = try JSONDecoder().decode(RoutineWebhook.self, from: local)+ #expect(off.url == nil)+ #expect(off.localUrl.hasSuffix("/hooks/routines/r"))+}