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): set up new routines by asking the bot
leepokai1dc7aaba65bd
diff --git a/apps/linux/src/manage.rs b/apps/linux/src/manage.rsindex 47e9b0ec..2aaa23e8 100644--- a/apps/linux/src/manage.rs+++ b/apps/linux/src/manage.rs@@ -113,17 +113,21 @@ fn load_memory(ui: &App, bot: &str, list: >k::Box) {}pub fn routines(ui: &App, bot: &str) {- let (_, body) = dialog(ui, "Routines");+ let (window, body) = dialog(ui, "Routines");let actions = gtk::Box::new(gtk::Orientation::Horizontal, 8);- let add = icon_button("list-add-symbolic", "Set up a routine");+ let add = icon_button("list-add-symbolic", "Ask the bot for a routine");let refresh = icon_button("view-refresh-symbolic", "Refresh routines");actions.append(&add);actions.append(&refresh);body.append(&actions);let list = gtk::Box::new(gtk::Orientation::Vertical, 14);body.append(&list);- let (ui2, bot2, list2) = (ui.clone(), bot.to_owned(), list.clone());- add.connect_clicked(move |_| routine_editor(&ui2, &bot2, Value::Null, &list2));+ // New routines are set up by talking to the bot: start the ask in its chat.+ let ui2 = ui.clone();+ add.connect_clicked(move |_| {+ window.close();+ ui::insert_draft(&ui2, "I want a routine that ");+ });let (ui2, bot2, list2) = (ui.clone(), bot.to_owned(), list.clone());refresh.connect_clicked(move |_| load_routines(&ui2, &bot2, &list2));load_routines(ui, bot, &list);@@ -144,101 +148,63 @@ fn load_routines(ui: &App, bot: &str, list: >k::Box) {};let items = v["routines"].as_array().cloned().unwrap_or_default();if items.is_empty() {- list.append(&label("No routines yet", &["secondary"]));+ let empty = label(+ "No routines yet. Tell the bot what to run and when, and it sets one up.",+ &["secondary"],+ );+ empty.set_wrap(true);+ list.append(&empty);+ return;}+ let rows = gtk::ListBox::builder()+ .selection_mode(gtk::SelectionMode::None)+ .css_classes(["boxed-list"])+ .build();+ list.append(&rows);for item in items {- let card = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .spacing(8)- .css_classes(["details-box"])+ let active = v["runs"].as_array().into_iter().flatten().find(|run| {+ run["routineId"] == item["id"]+ && matches!(+ run["status"].as_str(),+ Some("pending" | "starting" | "running" | "recovering")+ )+ });+ // What's happening now, else when it runs.+ let summary = if let Some(run) = active {+ run_label(run["status"].as_str().unwrap_or(""))+ } else if item["lastError"].is_string() {+ "Schedule needs attention".to_owned()+ } else {+ item["triggerDescriptions"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(Value::as_str)+ .collect::<Vec<_>>()+ .join(" · ")+ };+ let row = adw::ActionRow::builder()+ .title(item["name"].as_str().unwrap_or("Routine"))+ .subtitle(summary)+ .tooltip_text(item["instruction"].as_str().unwrap_or("")).build();- card.append(&label(- item["name"].as_str().unwrap_or("Routine"),- &["headline"],- ));- let desc = item["triggerDescriptions"]- .as_array()- .into_iter()- .flatten()- .filter_map(Value::as_str)- .collect::<Vec<_>>()- .join(" · ");- let text = label(- &format!(- "{} · {desc}",- if item["enabled"] == true {- "Enabled"- } else {- "Paused"- }- ),- &["secondary"],- );- text.set_wrap(true);- card.append(&text);- let instruction = label(item["instruction"].as_str().unwrap_or(""), &[]);- instruction.set_wrap(true);- card.append(&instruction);- if let Some(error) = item["lastError"].as_str() {- card.append(&label(error, &["danger-text"]));- }- if let Some(at) = item["nextRunAt"].as_i64() {- card.append(&label(- &format!("Next: {}", schedule_time(at)),- &["secondary"],- ));- }- let actions = gtk::Box::new(gtk::Orientation::Horizontal, 6);- card.append(&actions);+ rows.append(&row);let edit = icon_button("document-edit-symbolic", "Edit routine");- actions.append(&edit);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);for (icon, title, method) in [("media-playback-start-symbolic", "Test run", "runRoutine"),- (- "media-playback-pause-symbolic",- if item["enabled"] == true {- "Pause"- } else {- "Resume"- },- "setRoutineEnabled",- ),("user-trash-symbolic", "Delete routine", "deleteRoutine"),] {let button = icon_button(icon, title);- actions.append(&button);- let active = v["runs"].as_array().into_iter().flatten().any(|run| {- run["routineId"] == item["id"]- && matches!(- run["status"].as_str(),- Some("pending" | "starting" | "running" | "recovering")- )- });- button.set_sensitive(method != "runRoutine" || !active);+ button.set_valign(gtk::Align::Center);+ button.set_sensitive(method != "runRoutine" || active.is_none());+ row.add_suffix(&button);let (ui, bot, item, list) = (ui.clone(), bot.clone(), item.clone(), list.clone());- button.connect_clicked(move |button| {- let (ui2, bot, list, item, button2) = (- ui.clone(),- bot.clone(),- list.clone(),- item.clone(),- button.clone(),- );- let run = move || {- button2.set_sensitive(false);- client::call(- method,- json!({"botId":bot,"id":item["id"],"enabled":item["enabled"] != true}),- move |r| {- if let Err(e) = r {- toast(&ui2, &e);- }- load_routines(&ui2, &bot, &list);- },- );- };+ 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);if method == "deleteRoutine" {crate::dialogs::confirm(&ui,@@ -253,59 +219,41 @@ fn load_routines(ui: &App, bot: &str, list: >k::Box) {}});}- if item["triggers"]- .as_array()- .into_iter()- .flatten()- .any(|t| matches!(t["type"].as_str(), Some("webhook" | "event")))- {- let copy = icon_button("edit-copy-symbolic", "Copy webhook URL and key");- actions.append(©);- let (ui, bot, id) = (ui.clone(), bot.clone(), item["id"].clone());- copy.connect_clicked(move |button| {- let (ui, button) = (ui.clone(), button.clone());- client::call(- "routineWebhook",- json!({"botId":bot,"id":id}),- move |r| match r {- Ok(v) => {- button.clipboard().set_text(&format!(- "{}\nAuthorization: Bearer {}",- v["url"].as_str().unwrap_or(""),- v["key"].as_str().unwrap_or("")- ));- toast(&ui, "Copied webhook URL and key");- }- Err(e) => toast(&ui, &e),- },- );- });- }- for run in v["runs"]- .as_array()- .into_iter()- .flatten()- .filter(|r| r["routineId"] == item["id"])- .take(10)- {- let text = format!(- "{} · {}{}",- schedule_time(run["createdAt"].as_i64().unwrap_or(0)),- run["status"].as_str().unwrap_or(""),- run["error"]- .as_str()- .map(|e| format!(" · {e}"))- .unwrap_or_default()- );- let text = label(&text, &["small", "secondary"]);- text.set_wrap(true);- card.append(&text);- }- list.append(&card);+ let on = gtk::Switch::builder()+ .active(item["enabled"] == true)+ .valign(gtk::Align::Center)+ .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);+ gtk::glib::Propagation::Proceed+ });+ }+ });+}++fn routine_call(ui: &App, method: &str, args: Value, bot: &str, list: >k::Box) {+ let (ui, bot, list) = (ui.clone(), bot.to_owned(), list.clone());+ client::call(method, args, move |r| {+ if let Err(e) = r {+ toast(&ui, &e);}+ load_routines(&ui, &bot, &list);});}+fn run_label(status: &str) -> String {+ match status {+ "pending" => "Queued",+ "starting" => "Starting",+ "running" => "Running",+ _ => "Resuming after restart",+ }+ .to_owned()+}+fn schedule_time(at: i64) -> String {gtk::glib::DateTime::from_unix_local(at / 1000).ok()@@ -324,14 +272,7 @@ 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,- if routine.is_null() {- "Set up a routine"- } else {- "Edit routine"- },- );+ let (window, body) = dialog(ui, "Edit routine");let name = entry(&body, "Name", routine["name"].as_str().unwrap_or(""));body.append(&label("Instruction", &["secondary"]));let instruction = gtk::TextView::builder()@@ -350,13 +291,9 @@ fn routine_editor(ui: &App, bot: &str, routine: Value, list: >k::Box) {.vexpand(false).build();body.append(&scroll);- let kinds = if routine.is_null() {- vec!["daily", "weekly", "monthly", "custom", "once", "webhook"]- } else {- vec![- "keep", "daily", "weekly", "monthly", "custom", "once", "webhook",- ]- };+ let kinds = vec![+ "keep", "daily", "weekly", "monthly", "custom", "once", "webhook",+ ];body.append(&label("Schedule", &["secondary"]));let labels: Vec<&str> = kinds.iter()@@ -511,7 +448,7 @@ fn routine_editor(ui: &App, bot: &str, routine: Value, list: >k::Box) {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}); if !routine.is_null() { args["id"] = routine["id"].clone(); } }+ 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());client::call(if save { "saveRoutine" } else { "routineSchedule" }, args, move |r| {button.set_sensitive(true);diff --git a/apps/linux/src/ui.rs b/apps/linux/src/ui.rsindex 9b661998..bf95c104 100644--- a/apps/linux/src/ui.rs+++ b/apps/linux/src/ui.rs@@ -1883,6 +1883,17 @@ fn update_composer_for(ui: &App, st: &State, chat: &Value, in_thread: bool) {c.mentions_rev.set_reveal_child(any);}+/// Puts text in the chat's message box (after what's already typed) and focuses it.+pub fn insert_draft(ui: &App, text: &str) {+ let view = &ui.composer(false).view;+ let buf = view.buffer();+ if buf.char_count() > 0 {+ buf.insert(&mut buf.end_iter(), "\n");+ }+ buf.insert(&mut buf.end_iter(), text);+ view.grab_focus();+}+fn send(ui: &App, in_thread: bool) {let buf = ui.composer(in_thread).view.buffer();let text = bufdiff --git a/apps/linux/src/ui_tests.rs b/apps/linux/src/ui_tests.rsindex 6024dcc4..5d267762 100644--- a/apps/linux/src/ui_tests.rs+++ b/apps/linux/src/ui_tests.rs@@ -200,25 +200,34 @@ fn native_ui_flows() {crate::manage::routines(&ui, "bot");let routines = ui.window.visible_dialog().unwrap();wait(|| text(&routines, "No routines yet"));- click(&routines, "Set up a routine");+ 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),+ );+ wait(|| saved.get());++ crate::manage::routines(&ui, "bot");+ let routines = ui.window.visible_dialog().unwrap();+ wait(|| text(&routines, "Morning review"));+ click(&routines, "Edit 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("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");+ wait(|| widgets(&editor).into_iter().filter_map(|w| w.downcast::<gtk::Entry>().ok()).any(|e| e.text() == "Morning review"));click(&editor, "Preview schedule");wait(|| text(&editor, "Daily at 09:00 UTC"));screenshot("linux-routine-editor");click(&editor, "Save");- wait(|| text(&routines, "Morning review"));- click(&routines, "Pause");- wait(|| text(&routines, "Paused"));+ wait(|| ui.window.visible_dialog().as_ref() == Some(&routines));+ 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()));screenshot("linux-routines");close(&ui);diff --git a/docs/design/ui-conventions.md b/docs/design/ui-conventions.mdindex ed39fb9e..35bd425b 100644--- a/docs/design/ui-conventions.md+++ b/docs/design/ui-conventions.md@@ -62,7 +62,7 @@ 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 use a short empty state with one setup action and an icon action for asking in chat. Populated lists move the add action into the section header. 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 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`.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.@@ -95,8 +95,9 @@ SwiftUI already supplies these actions and needs no duplicate implementation.send can be retried with Enter; it reuses the nonce. A late response must not erasea draft edited while the request was running.- GTK bot menus include **Memory** and **Routines**. Memory supports forgetting one or- all facts. Routines support creation, editing, schedule previews, pause/resume, test- runs, deletion, history and webhook credentials. The host validates schedules;+ all 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;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/docs/features/routines.md b/docs/features/routines.mdindex 175977c1..1c47b221 100644--- a/docs/features/routines.md+++ b/docs/features/routines.md@@ -1,13 +1,15 @@# Routines-Routines belong to an agent bot. **Set up a routine** opens a form for the name,-instruction, trigger and timeout; Save creates it immediately. Edit opens the same-form and preserves existing triggers by default. **Ask in chat** is a separate-option that inserts an explanatory draft; send it to ask the bot to configure the-routine. Every agent receives the built-in `routines` MCP server. The Mac conversation details-panel and the iPhone's **More → Routines** show the saved instruction, triggers,-pause/resume, edit, delete, test run and execution history. Creation/update notices-open the routine.+Routines belong to an agent bot and are created by talking to it ("I want a+routine that…"). Every agent receives the built-in `routines` MCP server. The Mac+conversation details panel and the iPhone's **More → Routines** show a compact list+(name, schedule, on/off switch); **+** puts "I want a routine that " in the chat+composer. A row opens details: instruction, triggers, pause/resume, edit (form that+preserves existing triggers by default), edit with bot, delete, test run and run+history. Linux (boxed list with switches) and the TUI (`n` asks the bot) match.+Webhook credentials are not shown in clients: the endpoint is host-loopback only,+so the bot hands them out through `routine_webhook` when a local sender needs them.+Creation/update notices open the routine.## Apple setup interface@@ -206,11 +208,8 @@ compound and provider-event triggers retain a lossless Keep existing triggersfallback. Expired one-shot timestamps are preserved when editing other fields.Saved definitions appear immediately. Paused schedules omit next-run deadlines.-List/details expose queued/running/recovery/failure states and empty run history.-Edit with bot includes the routine ID in a draft without sending it. Webhook-credentials have explicit copy controls, and the panel distinguishes testing the-task from verifying an external delivery. These changes do not configure public-ingress or claim a provider connection is working.+List rows and details expose queued/running/recovery/failure states.+Edit with bot includes the routine ID in a draft without sending it.Verification: shared Swift tests passed (46 tests; an unrelated offline-mailboxassertion failed on the first run, then passed both the targeted and full rerun).diff --git a/host/src/tui/manage.rs b/host/src/tui/manage.rsindex 5b1d65a8..493c3736 100644--- a/host/src/tui/manage.rs+++ b/host/src/tui/manage.rs@@ -9,7 +9,7 @@ use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};use serde_json::{Value, json};use std::str::FromStr as _;-use super::app::{After, App, Confirm, ConfirmAct, Editor, Overlay, Toggle, fuzzy};+use super::app::{After, App, Confirm, ConfirmAct, Editor, Focus, Overlay, Toggle, fuzzy};/// Quick reactions, as the other apps offer them.pub const REACTIONS: [&str; 6] = ["👍", "❤️", "😂", "🎉", "👀", "✅"];@@ -20,7 +20,6 @@ pub enum Reply {Memory(String),Routines(String),RoutineSaved,- Webhook,Registry {more: bool,},@@ -257,19 +256,15 @@ 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'), _) => {- 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,- })));+ // New routines are set up by talking to the bot: start the ask in its chat.+ let draft = self.drafts.entry(bot).or_default();+ if !draft.text.is_empty() {+ draft.insert("\n");+ }+ draft.insert("I want a routine that ");+ self.thread = None;+ self.focus = Focus::Chat;+ self.typing = true;return None;}(KeyCode::Enter | KeyCode::Char('e'), Some(r)) => {@@ -309,13 +304,6 @@ 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'), Some(r)) => {- if r["triggers"].as_array().into_iter().flatten().any(|t| t["type"] == "webhook") {- self.sheet("routineWebhook", json!({"botId": bot, "id": r["id"]}), Reply::Webhook);- } else {- self.flash("Only a routine whose When is webhook can be called");- }- }(KeyCode::Char('x'), Some(r)) => {let c = Confirm {title: format!("Delete the routine {}?", s(&r, "name")),@@ -968,12 +956,6 @@ impl App {}self.refresh_sheets();}- Reply::Webhook => {- let text =- format!("curl -X POST '{}' -H 'Authorization: Bearer {}' -d '{{}}'", s(&v, "url"), s(&v, "key"));- super::app::copy(&text);- self.flash("Copied a curl command that runs it (with its key)");- }Reply::Registry { more } => {if let Some(Overlay::Market(m)) =self.overlays.iter_mut().rev().find(|o| matches!(o, Overlay::Market(_)))diff --git a/host/src/tui/sheets.rs b/host/src/tui/sheets.rsindex bc527eb0..b63a41b8 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 makes one: the bot does something on a schedule or when called.",+ "No routines. n asks the bot for one: tell it what to run and when.",t.secondary.patch(t.panel),);}@@ -131,7 +131,7 @@ pub fn routines(buf: &mut Buffer, area: Rect, app: &App, l: &RoutineList) {}}}- footer(buf, inner, None, "n new · ↵ edit · space on/off · r run now · w copy webhook · x delete · esc");+ footer(buf, inner, None, "n ask the bot · ↵ edit · space on/off · r run now · 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 90c77e80..530f7247 100644--- a/kit/Sources/CodyncKit/Models/Routine.swift+++ b/kit/Sources/CodyncKit/Models/Routine.swift@@ -51,11 +51,6 @@ public struct RoutineListing: Codable, Sendable {public var runs: [RoutineRun]}-public struct RoutineWebhook: Codable, Sendable {- public var url: String- public var key: String-}-extension HostClient {public func routines(botId: String) async throws -> RoutineListing {struct Body: Encodable { let botId: String }@@ -66,11 +61,6 @@ 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))}-- public func routineWebhook(botId: String, id: String) async throws -> RoutineWebhook {- struct Body: Encodable { let botId: String; let id: String }- return try await call("routineWebhook", Body(botId: botId, id: id))- }}extension HostClient {diff --git a/kit/Sources/CodyncUI/Routines/RoutineEditorView.swift b/kit/Sources/CodyncUI/Routines/RoutineEditorView.swiftindex 243a0534..ed02bf49 100644--- a/kit/Sources/CodyncUI/Routines/RoutineEditorView.swift+++ b/kit/Sources/CodyncUI/Routines/RoutineEditorView.swift@@ -3,7 +3,7 @@ import SwiftUIstruct RoutineEditorView: View {let botId: String- let routine: Routine?+ let routine: Routinelet saved: (Routine) -> Void@Environment(BotStore.self) private var model@Environment(\.accessibilityReduceMotion) private var reduceMotion@@ -20,9 +20,8 @@ struct RoutineEditorView: View {@State private var checkedSchedule: RoutineScheduleDraft?private var options: [(String, String)] {- var values = [("cron", "Recurring schedule"),+ var values = [("keep", "Keep existing triggers"), ("cron", "Recurring schedule"),("once", "Run once"), ("webhook", "Webhook")]- if routine != nil { values.insert(("keep", "Keep existing triggers"), at: 0) }if schedule.original.contains(where: { $0.type == "interval" }) {values.append(("interval", "Existing interval"))}@@ -37,7 +36,7 @@ struct RoutineEditorView: View {var body: some View {VStack(spacing: 0) {- ModalHeader(routine == nil ? "Set up a routine" : "Edit routine")+ ModalHeader("Edit routine")ScrollView {VStack(alignment: .leading, spacing: 24) {VStack(alignment: .leading, spacing: 14) {@@ -89,11 +88,9 @@ struct RoutineEditorView: View {.foregroundStyle(Palette.text).background(Palette.background).task {- if let routine {- name = routine.name- instruction = routine.instruction- timeout = String(routine.timeoutSeconds ?? 3600)- }+ name = routine.name+ instruction = routine.instruction+ timeout = String(routine.timeoutSeconds ?? 3600)await loadSchedule()}.task(id: schedule) {@@ -125,7 +122,7 @@ 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.draftpreview = resultcheckedSchedule = result.draft@@ -215,7 +212,7 @@ struct RoutineEditorView: View {.frame(maxWidth: .infinity, alignment: .leading).padding(14).background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 12))default:- ForEach(routine?.triggerDescriptions ?? [], id: \.self) {+ ForEach(routine.triggerDescriptions, id: \.self) {Label($0, systemImage: "clock").font(.callout).foregroundStyle(Palette.secondary)}}@@ -278,7 +275,7 @@ struct RoutineEditorView: View {Button(action: save) {HStack(spacing: 8) {if busy { Spinner() }- Text(busy ? "Saving…" : routine == nil ? "Create routine" : "Save changes")+ Text(busy ? "Saving…" : "Save changes").fixedSize(horizontal: false, vertical: true)}#if os(iOS)@@ -297,7 +294,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/RoutinesView.swift b/kit/Sources/CodyncUI/Routines/RoutinesView.swiftindex c94dae2e..f9a06fd8 100644--- a/kit/Sources/CodyncUI/Routines/RoutinesView.swift+++ b/kit/Sources/CodyncUI/Routines/RoutinesView.swift@@ -15,12 +15,9 @@ struct RoutinesView: View {@State private var busy = false@State private var error: String?@State private var confirmDelete = false- @State private var webhook: RoutineWebhook?- @State private var showKey = false@State private var openRun: ThreadTarget?- @State private var showSetup = false+ @State private var showEditor = false@State private var loadError: String?- @State private var copied: String?private var routine: Routine? { routines.first { $0.id == selected } }@@ -28,14 +25,11 @@ struct RoutinesView: View {VStack(alignment: .leading, spacing: 16) {HStack {if selected != nil {- IconButton("Back to Routines", systemImage: "chevron.left") { animate { selected = nil; webhook = nil; showKey = false; copied = nil } }+ IconButton("Back to Routines", systemImage: "chevron.left") { animate { selected = nil } }}Text(routine?.name ?? "Routines").font(.system(size: 13, weight: .semibold))Spacer(minLength: 0)- if selected == nil && !routines.isEmpty {- IconButton("Set up a routine", systemImage: "plus") { animate { showSetup = true } }- .disabled(model.isOffline)- }+ if selected == nil { askInChat }if let close { IconButton("Close routines", systemImage: "xmark", action: close) }}if let loadError { Text(loadError).font(.caption).foregroundStyle(Palette.danger) }@@ -51,7 +45,7 @@ struct RoutinesView: View {.foregroundStyle(Palette.text).font(.system(size: 13)).onChange(of: initialId) { _, id in- animate { selected = id; webhook = nil; showKey = false; copied = nil }+ animate { selected = id }}.task(id: botId) {selected = initialId@@ -60,16 +54,17 @@ struct RoutinesView: View {do { try await Task.sleep(for: .seconds(3)) } catch { break }} while !Task.isCancelled}- .codyncSheet(isPresented: $showSetup) {- RoutineEditorView(botId: botId, routine: routine) { saved in- routines.removeAll { $0.id == saved.id }- routines.append(saved)- animate { selected = saved.id; showSetup = false; webhook = nil; showKey = false; copied = nil }- Task { await load() }+ .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 }+ animate { showEditor = false }+ Task { await load() }+ }+ #if os(macOS)+ .frame(width: 540, height: 700)+ #endif}- #if os(macOS)- .frame(width: 540, height: 700)- #endif}.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) {@@ -85,66 +80,57 @@ struct RoutinesView: View {}private var listing: some View {- VStack(alignment: .leading, spacing: 10) {+ VStack(alignment: .leading, spacing: 0) {if routines.isEmpty {- VStack(alignment: .leading, spacing: 12) {- Image(systemName: "clock.arrow.circlepath")- .font(.system(size: 22, weight: .light))- .foregroundStyle(Palette.secondary)- .accessibilityHidden(true)- VStack(alignment: .leading, spacing: 6) {- Text(loaded ? "No routines yet" : "Loading routines…")- .font(.system(size: 13, weight: .medium))- Text("Schedule a task, repeat it, or run it on an event.")- .font(.system(size: 12))- .foregroundStyle(Palette.secondary)- .fixedSize(horizontal: false, vertical: true)- .lineSpacing(2)- }- HStack(spacing: 8) {- Button("Set up a routine") { animate { showSetup = true } }- .buttonStyle(.primary)- .disabled(model.isOffline)- Spacer(minLength: 0)- askInChat+ Text(loaded ? "No routines yet. Tell the bot what to run and when, and it sets one up." : "Loading routines…")+ .font(.caption)+ .foregroundStyle(Palette.secondary)+ .fixedSize(horizontal: false, vertical: true)+ } else {+ VStack(spacing: 0) {+ ForEach(routines) { routine in+ if routine.id != routines.first?.id { Divider() }+ row(routine)}- .padding(.top, 2)}- .padding(16)- .frame(maxWidth: .infinity, alignment: .leading)+ .padding(.horizontal, 14).background(Palette.surface, in: RoundedRectangle(cornerRadius: 12))}- ForEach(routines) { routine in- Button { animate { selected = routine.id } } label: {- HStack(alignment: .top, spacing: 10) {- Image(systemName: routine.enabled ? "clock.arrow.circlepath" : "pause.circle")- .foregroundStyle(Palette.secondary)- VStack(alignment: .leading, spacing: 4) {- Text(routine.name).foregroundStyle(Palette.text)- Text(routine.enabled ? routine.triggerDescriptions.joined(separator: " · ") : "Paused")- .font(.caption).foregroundStyle(Palette.secondary)- Text(stateDescription(routine)).font(.caption).foregroundStyle(Palette.secondary)- }- Spacer(minLength: 0)- Image(systemName: "chevron.right").font(.caption).foregroundStyle(Palette.tertiary)- }- .padding(.vertical, 8)- .contentShape(Rectangle())- }- .buttonStyle(.plain)- }- if !routines.isEmpty {- HStack {- Spacer()- askInChat+ }+ }++ private func row(_ routine: Routine) -> some View {+ HStack(spacing: 12) {+ Button { animate { selected = routine.id } } label: {+ VStack(alignment: .leading, spacing: 3) {+ Text(routine.name).foregroundStyle(Palette.text)+ Text(summary(routine))+ .font(.caption)+ .foregroundStyle(routine.lastError == nil ? Palette.secondary : Palette.danger)}+ .padding(.vertical, 10)+ .frame(maxWidth: .infinity, alignment: .leading)+ .contentShape(Rectangle())}+ .buttonStyle(.plain)+ Toggle(isOn: Binding(get: { routine.enabled }, set: { action("setRoutineEnabled", routine, enabled: $0) })) { EmptyView() }+ .toggleStyle(.codync)+ .fixedSize()+ .accessibilityLabel(routine.name)+ .disabled(busy || model.isOffline)}}+ /// The row's second line: what's happening now, else when it runs.+ 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" }+ return routine.triggerDescriptions.joined(separator: " · ")+ }+private var askInChat: some View {- IconButton("Ask in chat", systemImage: "text.bubble") {- edit("Help me set up a routine. Ask me what task to run and when, then create it with the routines tool. ")+ IconButton("Ask the bot for a routine", systemImage: "plus") {+ edit("I want a routine that ")}.disabled(model.isOffline)}@@ -174,7 +160,7 @@ struct RoutinesView: View {IconButton(routine.enabled ? "Pause" : "Resume", systemImage: routine.enabled ? "pause" : "play") {action("setRoutineEnabled", routine, enabled: !routine.enabled)}- IconButton("Edit", systemImage: "pencil") { animate { showSetup = true } }+ 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()@@ -187,48 +173,8 @@ struct RoutinesView: View {.buttonStyle(.plain).foregroundStyle(Palette.secondary).disabled(model.isOffline)- if routine.triggers.contains(where: { $0.type == "webhook" || $0.type == "event" }) {- VStack(alignment: .leading, spacing: 8) {- Button("Webhook connection", systemImage: "link") {- Task {- do {- guard let client = model.client else { return }- let value = try await client.routineWebhook(botId: botId, id: routine.id)- animate { webhook = value }- } catch { self.error = error.localizedDescription }- }- }.buttonStyle(.plain)- if let webhook {- HStack {- Text("Local endpoint").fontWeight(.semibold)- Spacer()- IconButton(copied == "url" ? "URL copied" : "Copy URL", systemImage: copied == "url" ? "checkmark" : "doc.on.doc") {- Pasteboard.copy(webhook.url)- animate { copied = "url" }- }- }- Text(webhook.url).font(.caption.monospaced()).textSelection(.enabled)- Text("Send JSON with Authorization: Bearer <key>. This address is local to the host.").font(.caption).foregroundStyle(Palette.secondary)- Button(showKey ? "Hide key" : "Show key") { animate { showKey.toggle() } }.buttonStyle(.plain)- if showKey {- HStack(alignment: .top) {- Text(webhook.key).font(.caption.monospaced()).textSelection(.enabled)- IconButton(copied == "key" ? "Key copied" : "Copy key", systemImage: copied == "key" ? "checkmark" : "doc.on.doc") {- Pasteboard.copy(webhook.key)- animate { copied = "key" }- }- }- }- Text("For external senders, verify a real delivery. Test run only checks the task.")- .font(.caption).foregroundStyle(Palette.secondary)- }- }- }let history = runs.filter { $0.routineId == routine.id }- if history.isEmpty {- Text("No runs recorded yet. Use Test run to execute this task now, or wait for its trigger.")- .font(.caption).foregroundStyle(Palette.secondary)- } else {+ if !history.isEmpty {VStack(alignment: .leading, spacing: 10) {Text("Runs").fontWeight(.semibold)ForEach(history) { run in@@ -290,7 +236,7 @@ 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; webhook = nil } }+ if method == "deleteRoutine" { animate { selected = nil } }error = nilawait load()} catch { self.error = error.localizedDescription }