diff --git a/PROTOCOL.md b/PROTOCOL.md index 5695090..79e0960 100644 --- a/PROTOCOL.md +++ b/PROTOCOL.md @@ -189,6 +189,9 @@ Quick Ask's `quick_shot` fails with `helper_failed` (the message is the helper's | `add_roles` | `projectId`, `paths?`, `shipped?`, `raise` | `{bots:[id]}`: a bot for each role, in the project (the `lead` role makes its bot the project's `lead` when the project has none of its own, and leaves one that is set); levels in `raises` are applied only with `raise: true`. All or none: `invalid_role` or `no_such_project` and no bot is created. Refused (`forbidden`) for a device on the network | | `list_skills` | `bot` | `{skills:[{name, description, author?, enabled}]}`, by name; `enabled` is false while the skill is switched off (see Skills) | | `discover_skills` | none | `{skills:[{name, description, author?, path, from}]}`: valid `SKILL.md` folders found in standard local skill directories on this Mac, deduplicated by real path and sorted by name; `path` can be passed to `preview_skill` and `install_skill`. Refused (`forbidden`) for a device on the network | +| `start_recording` | `bot`, `url?` | `{recording: true, bot}`: starts a browser skill-recording session on `bot`'s Chrome window using the isolated-world `bateUser` binding (optionally opening `url`), launching Chrome off the core thread; `bots_changed` follows with `recording: true`. Refused (`forbidden`) for a device on the network | +| `stop_recording` | `bot`, `name?`, `description?` | `{name, description, steps, markdown}`: stops recording on `bot`'s browser and drafts an editable `SKILL.md` from the captured navigations, clicks, selects, and typed inputs. Password inputs (`type="password"`) are never read, and any value matching a saved Secret of `bot` is replaced with `Secret: `; `bots_changed` follows. Refused (`forbidden`) for a device on the network | +| `save_recorded_skill` | `bot`, `markdown` | `{skill}`: validates `markdown` as a `SKILL.md` document and installs it into `bot`'s `skills//` folder via staging, turning it on (`skills_changed` follows). Refused (`forbidden`) for a device on the network | | `set_skill_enabled` | `bot`, `name`, `enabled` | `{}`: switches the installed skill `name` on or off for this bot (`no_such_skill`; `bad_request` when `enabled` is not true or false). `skills_changed` follows, and a running engine is sent `skills_off` | | `install_skill` | `bot`, `path` or `fromBot` and `name` | `{skill}`; copies the skill folder at `path`, or the skill `name` of the bot `fromBot` (`no_such_bot`), or `invalid_skill`. Refused (`forbidden`) for a device on the network (it names a path on this Mac) | | `preview_skill` | `path` or `fromBot` and `name` | `{skill, entries, bytes}` of the folder at `path`: what `install_skill` would copy in (files and folders, bytes), checked as it checks, to show before it is installed. Nothing is kept. `invalid_skill`. Refused (`forbidden`) for a device on the network | diff --git a/appd/src/browser.rs b/appd/src/browser.rs index f9ef909..0210b56 100644 --- a/appd/src/browser.rs +++ b/appd/src/browser.rs @@ -13,9 +13,9 @@ use std::os::fd::{FromRawFd, RawFd}; use std::os::unix::process::CommandExt; use std::path::{Path, PathBuf}; use std::process::{Child, Command, Stdio}; -use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender}; +use std::sync::{Arc, Mutex}; use std::thread; use std::time::Duration; @@ -44,14 +44,102 @@ const MAX_ELEMENTS: usize = 200; const MAX_TYPED: usize = 10_000; /// Most bytes of one message from Chrome. const MAX_MESSAGE: usize = 64 << 20; +/// Most recorded user actions kept in one browser recording session. +const MAX_RECORDED_STEPS: usize = 100; /// The name under which the page tells the service that the user clicked or typed. const BINDING: &str = "bateUser"; /// The page's isolated world, where the page's own scripts cannot see or call the binding. const WORLD: &str = "bate"; /// Runs in the isolated world of every page: input that a person made (not a script) is -/// the user taking over. -const WATCH: &str = "for (const t of ['pointerdown', 'mousedown', 'keydown', 'touchstart']) \ - addEventListener(t, e => { if (e.isTrusted) bateUser(t) }, true);"; +/// the user taking over, and while a skill recording is active, structured steps are sent +/// over the same isolated-world binding. Password fields never have their values read. +const WATCH: &str = r#"(() => { + if (globalThis.__bateWatched) return; + globalThis.__bateWatched = true; + for (const t of ['pointerdown', 'mousedown', 'keydown', 'touchstart']) { + addEventListener(t, e => { if (e.isTrusted) bateUser(t); }, true); + } + const clean = s => String(s || '').trim().replace(/\s+/g, ' ').slice(0, 120); + const isPw = el => el && el.tagName === 'INPUT' && (el.type === 'password' || el.autocomplete === 'one-time-code'); + const labelOf = el => { + if (!el) return ''; + if (el.id) { + const l = document.querySelector(`label[for="${CSS.escape(el.id)}"]`); + if (l && l.innerText) return clean(l.innerText); + } + const wrap = el.closest && el.closest('label'); + if (wrap && wrap.innerText) return clean(wrap.innerText); + return clean(el.getAttribute && (el.getAttribute('aria-label') || el.getAttribute('placeholder') || el.getAttribute('title') || el.getAttribute('name')) || (isPw(el) ? '' : el.innerText)); + }; + const selOf = el => { + if (!el || !el.tagName) return ''; + if (el.id) return '#' + el.id.slice(0, 60); + const tid = el.getAttribute && el.getAttribute('data-testid'); + if (tid) return `[data-testid="${tid.slice(0, 60)}"]`; + const name = el.getAttribute && el.getAttribute('name'); + if (name) return `${el.tagName.toLowerCase()}[name="${name.slice(0, 60)}"]`; + return el.tagName.toLowerCase(); + }; + const roleOf = el => { + if (!el || !el.tagName) return ''; + const r = el.getAttribute && el.getAttribute('role'); + if (r) return clean(r); + const tag = el.tagName.toLowerCase(); + if (tag === 'a') return 'link'; + if (tag === 'button') return 'button'; + if (tag === 'select') return 'select'; + if (tag === 'textarea') return 'field'; + if (tag === 'input') return isPw(el) ? 'password' : (el.type || 'field'); + return tag; + }; + const send = obj => { try { bateUser(JSON.stringify(obj)); } catch (_) {} }; + const noteOpen = () => { + if (location.protocol === 'http:' || location.protocol === 'https:') { + send({ kind: 'open', url: location.href.slice(0, 2000), title: clean(document.title) }); + } + }; + noteOpen(); + addEventListener('hashchange', noteOpen, true); + addEventListener('popstate', noteOpen, true); + addEventListener('click', e => { + if (!e.isTrusted || !(e.target instanceof Element)) return; + const el = e.target.closest('a,button,input,select,textarea,summary,[role=button],[role=link],label') || e.target; + send({ kind: 'click', role: roleOf(el), label: labelOf(el), selector: selOf(el), url: location.href.slice(0, 2000) }); + }, true); + addEventListener('change', e => { + if (!e.isTrusted || !(e.target instanceof Element)) return; + const el = e.target; + if (el.tagName === 'SELECT') { + const opt = el.selectedOptions && el.selectedOptions[0] ? clean(el.selectedOptions[0].text) : ''; + send({ kind: 'select', role: 'select', label: labelOf(el), selector: selOf(el), value: opt, url: location.href.slice(0, 2000) }); + return; + } + if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') { + const pw = isPw(el); + send({ kind: 'type', role: roleOf(el), label: labelOf(el), selector: selOf(el), value: pw ? '' : String(el.value || '').slice(0, 500), password: pw, url: location.href.slice(0, 2000) }); + } + }, true); +})();"#; + +/// One user action captured from the isolated-world `bateUser` binding during a skill recording. +#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Deserialize, serde::Serialize)] +pub struct RecordedStep { + pub kind: String, + #[serde(default)] + pub url: String, + #[serde(default)] + pub title: String, + #[serde(default)] + pub role: String, + #[serde(default)] + pub label: String, + #[serde(default)] + pub selector: String, + #[serde(default)] + pub value: String, + #[serde(default)] + pub password: bool, +} /// What a `type` action puts in a field. #[derive(Debug, PartialEq)] @@ -253,13 +341,20 @@ pub struct Job { enum Work { Act(Job), HandBack, + StartRecording { + url: Option, + reply: Sender>, + }, } /// The service's side of a bot's browser: the thread that drives it runs until the service /// stops. +#[derive(Clone)] pub struct Handle { work: Sender, taken: Arc, + recording: Arc, + steps: Arc>>, } impl Handle { @@ -268,16 +363,25 @@ impl Handle { pub fn start(bot: &str, profile: PathBuf, tx: Sender, proxy: Option) -> Handle { let (work, jobs) = mpsc::channel(); let taken = Arc::new(AtomicBool::new(false)); + let recording = Arc::new(AtomicBool::new(false)); + let steps = Arc::new(Mutex::new(Vec::new())); let mut browser = Browser { bot: bot.to_owned(), profile, tx, taken: taken.clone(), + recording: recording.clone(), + steps: steps.clone(), proxy, chrome: None, }; thread::spawn(move || browser.serve(jobs)); - Handle { work, taken } + Handle { + work, + taken, + recording, + steps, + } } pub fn act(&self, job: Job) { @@ -289,6 +393,34 @@ impl Handle { self.taken.load(Ordering::SeqCst) } + /// Whether a skill recording session is active on this browser. + pub fn recording(&self) -> bool { + self.recording.load(Ordering::SeqCst) + } + + /// Starts recording user actions in the bot's browser, launching and attaching Chrome if + /// needed (optionally navigating to `url`). Blocks on the browser thread's reply: call off + /// `Core::run`. + pub fn start_recording(&self, url: Option) -> Result<(), String> { + if let Some(ref u) = url + && !web(u) + { + return Err("`url` must be an http or https address".into()); + } + let (tx, rx) = mpsc::channel(); + self.work + .send(Work::StartRecording { url, reply: tx }) + .map_err(|_| "the browser stopped".to_owned())?; + rx.recv().map_err(|_| "the browser stopped".to_owned())? + } + + /// Stops recording and returns all captured steps since `start_recording`. + pub fn stop_recording(&self) -> Vec { + self.recording.store(false, Ordering::SeqCst); + let mut steps = self.steps.lock().unwrap_or_else(|e| e.into_inner()); + std::mem::take(&mut *steps) + } + /// The user hands the browser back: a waiting action goes on. pub fn hand_back(&self) { if self.taken.swap(false, Ordering::SeqCst) { @@ -297,6 +429,100 @@ impl Handle { } } +/// Formats recorded browser steps as a clean, editable `SKILL.md` draft. Password fields and any +/// values matching the bot's saved Secrets are replaced with `Secret: ` placeholders and +/// never appear in raw form. +pub fn draft_skill( + name: &str, + description: &str, + steps: &[RecordedStep], + secrets: &[Secret], +) -> String { + let mut out = format!( + "---\nname: {name}\ndescription: {description}\n---\n\n\ + Use the browser tool to repeat this workflow:\n\n" + ); + let mut lines = Vec::new(); + let mut last_url = String::new(); + for step in steps { + let clean_url = redact(&step.url, secrets); + let clean_label = redact(step.label.trim(), secrets); + let clean_selector = redact(step.selector.trim(), secrets); + let target = match (clean_label.is_empty(), clean_selector.is_empty()) { + (false, false) => format!("\"{clean_label}\" (`{clean_selector}`)"), + (false, true) => format!("\"{clean_label}\""), + (true, false) => format!("`{clean_selector}`"), + (true, true) => "the element".to_owned(), + }; + match step.kind.as_str() { + "open" if !clean_url.is_empty() => { + if clean_url == last_url { + continue; + } + last_url = clean_url.clone(); + lines.push(format!("Open `{clean_url}`.")); + } + "click" => { + let role = if step.role.is_empty() { + "element" + } else { + step.role.as_str() + }; + lines.push(format!("Click {role} {target}.")); + } + "select" => { + let opt = redact_step_value(&step.value, secrets); + lines.push(format!("Select `{opt}` in {target}.")); + } + "type" => { + if step.password { + let host = proto::secrets::host(&step.url); + let secret_ref = host + .as_deref() + .and_then(|h| secrets.iter().find(|s| s.site == h)) + .map(|s| format!("Secret: {}", s.name)) + .unwrap_or_else(|| "Secret: ".to_owned()); + lines.push(format!("Type `{secret_ref}` into password field {target}.")); + } else { + let val = redact_step_value(&step.value, secrets); + lines.push(format!("Type `{val}` into {target}.")); + } + } + _ => {} + } + } + if lines.is_empty() { + out.push_str("1. Open the target page in the browser and complete the task.\n"); + } else { + for (i, line) in lines.iter().enumerate() { + out.push_str(&format!("{}. {line}\n", i + 1)); + } + } + out +} + +/// Replaces any exact or embedded bot Secret value with `Secret: ` so recorded skill drafts +/// never contain raw secret values. +fn redact_step_value(value: &str, secrets: &[Secret]) -> String { + let mut longest_first: Vec<&Secret> = secrets.iter().filter(|s| !s.value.is_empty()).collect(); + longest_first.sort_by_key(|s| std::cmp::Reverse(s.value.len())); + let mut out = value.to_owned(); + for s in longest_first { + let placeholder = format!("Secret: {}", s.name); + for form in [ + s.value.clone(), + percent(&s.value, true), + percent(&s.value, false), + ] { + if out == form { + return placeholder; + } + out = out.replace(&form, &placeholder); + } + } + out +} + /// A running Chrome, and the page it is driven on. struct Chrome { child: Child, @@ -316,6 +542,8 @@ struct Browser { profile: PathBuf, tx: Sender, taken: Arc, + recording: Arc, + steps: Arc>>, proxy: Option, chrome: Option, } @@ -337,6 +565,10 @@ impl Browser { self.run(job); } } + Work::StartRecording { url, reply } => { + let result = self.begin_recording(url.as_deref()); + let _ = reply.send(result); + } } } if let Some(mut chrome) = self.chrome.take() { @@ -345,6 +577,41 @@ impl Browser { } } + fn begin_recording(&mut self, url: Option<&str>) -> Result<(), String> { + { + let mut steps = self.steps.lock().unwrap_or_else(|e| e.into_inner()); + steps.clear(); + } + let gone = self + .chrome + .as_ref() + .is_some_and(|c| c.gone.load(Ordering::SeqCst)); + if gone && let Some(mut chrome) = self.chrome.take() { + let _ = chrome.child.kill(); + let _ = chrome.child.wait(); + } + if self.chrome.is_none() { + self.chrome = Some(self.launch()?); + } + let chrome = self.chrome.as_mut().expect("launched above"); + let page = match chrome.page() { + Ok(page) => page, + Err(_) => { + chrome.page = None; + chrome.page()? + } + }; + self.recording.store(true, Ordering::SeqCst); + if let Some(u) = url { + let went = chrome.call(Some(&page), "Page.navigate", json!({"url": u}))?; + if let Some(error) = went["errorText"].as_str().filter(|e| !e.is_empty()) { + self.recording.store(false, Ordering::SeqCst); + return Err(format!("{u} did not open: {error}")); + } + } + Ok(()) + } + fn run(&mut self, job: Job) { if job.cancelled.load(Ordering::SeqCst) { return; @@ -449,8 +716,10 @@ impl Browser { let (replies_tx, replies) = mpsc::channel(); let gone = Arc::new(AtomicBool::new(false)); let acting = Arc::new(AtomicBool::new(false)); - let (taken, tx, bot, ended, quiet) = ( + let (taken, recording, steps, tx, bot, ended, quiet) = ( self.taken.clone(), + self.recording.clone(), + self.steps.clone(), self.tx.clone(), self.bot.clone(), gone.clone(), @@ -486,7 +755,22 @@ impl Browser { if message["method"] == "Runtime.bindingCalled" && message["params"]["name"] == BINDING { - if !quiet.load(Ordering::SeqCst) && !taken.swap(true, Ordering::SeqCst) { + let payload = message["params"]["payload"].as_str().unwrap_or(""); + if payload.starts_with('{') { + if recording.load(Ordering::SeqCst) + && !quiet.load(Ordering::SeqCst) + && let Ok(mut step) = serde_json::from_str::(payload) + { + // Never keep any value from a password field even if a caller sent one. + if step.password { + step.value.clear(); + } + let mut list = steps.lock().unwrap_or_else(|e| e.into_inner()); + if list.len() < MAX_RECORDED_STEPS { + list.push(step); + } + } + } else if !quiet.load(Ordering::SeqCst) && !taken.swap(true, Ordering::SeqCst) { let _ = tx.send(Msg::BrowserTaken { bot: bot.clone() }); } } else if message.get("id").is_some() && replies_tx.send(message).is_err() { @@ -1018,4 +1302,80 @@ mod tests { // A value that is empty hides nothing (and cannot loop). assert_eq!(redact("text", &[secret("none", "")]), "text"); } + + #[test] + fn recorded_steps_draft_a_skill_with_passwords_and_secrets_redacted() { + let secrets = [ + Secret { + name: "shop_login".into(), + site: "shop.example.com".into(), + value: "s3cr3t-pass!".into(), + }, + Secret { + name: "api_key".into(), + site: "api.example.com".into(), + value: "tok-998877".into(), + }, + ]; + let steps = vec![ + RecordedStep { + kind: "open".into(), + url: "https://shop.example.com/login".into(), + ..Default::default() + }, + // Consecutive duplicate open is collapsed. + RecordedStep { + kind: "open".into(), + url: "https://shop.example.com/login".into(), + ..Default::default() + }, + RecordedStep { + kind: "type".into(), + url: "https://shop.example.com/login".into(), + label: "Token".into(), + selector: "#token".into(), + value: "tok-998877".into(), + password: false, + ..Default::default() + }, + RecordedStep { + kind: "type".into(), + url: "https://shop.example.com/login".into(), + label: "Password".into(), + selector: "#pw".into(), + value: "should-never-appear".into(), + password: true, + ..Default::default() + }, + RecordedStep { + kind: "click".into(), + url: "https://shop.example.com/login".into(), + role: "button".into(), + label: "Sign in".into(), + selector: "button[name=\"go\"]".into(), + ..Default::default() + }, + ]; + let md = draft_skill("shop-signin", "Sign in to shop.", &steps, &secrets); + assert!(md.contains("name: shop-signin"), "{md}"); + assert!( + md.contains("1. Open `https://shop.example.com/login`."), + "{md}" + ); + assert!( + md.contains("2. Type `Secret: api_key` into \"Token\" (`#token`)."), + "{md}" + ); + assert!( + md.contains("3. Type `Secret: shop_login` into password field \"Password\" (`#pw`)."), + "{md}" + ); + assert!( + md.contains("4. Click button \"Sign in\" (`button[name=\"go\"]`)."), + "{md}" + ); + assert!(!md.contains("s3cr3t-pass!"), "{md}"); + assert!(!md.contains("tok-998877"), "{md}"); + assert!(!md.contains("should-never-appear"), "{md}"); + } } diff --git a/appd/src/core.rs b/appd/src/core.rs index 3ab98aa..51ee095 100644 --- a/appd/src/core.rs +++ b/appd/src/core.rs @@ -173,6 +173,13 @@ pub enum Msg { BrowserTaken { bot: String, }, + /// A browser skill-recording session finished starting off the core's thread. + RecordingStarted { + client: u64, + id: Value, + bot: String, + result: Result<(), String>, + }, /// What the helper app did for a bot. Desktopped { bot: String, @@ -1153,6 +1160,21 @@ impl Core { log!("bot {bot}: the user took over its browser"); self.broadcast(&json!({"type": "bots_changed"})); } + Msg::RecordingStarted { + client, + id, + bot, + result, + } => { + let reply = match result { + Ok(()) => { + self.broadcast(&json!({"type": "bots_changed"})); + Ok(json!({"recording": true, "bot": bot})) + } + Err(e) => Err(("browser_failed", e)), + }; + self.reply(client, &id, "start_recording", reply); + } Msg::Desktopped { bot, generation, @@ -2591,6 +2613,78 @@ impl Core { } Ok(Some(json!({}))) } + "start_recording" => { + let bot = self.bot_of(f)?; + let url = match f.get("url") { + None | Some(Value::Null) => None, + Some(v) => { + let s = v.as_str().ok_or(bad("`url` must be a string"))?.trim(); + if s.is_empty() { + None + } else { + Some(s.to_owned()) + } + } + }; + self.start_browser(&bot) + .map_err(|e| ("browser_failed", e))?; + let handle = self + .browsers + .get(&bot) + .expect("browser started above") + .clone(); + let (tx, id) = (self.tx.clone(), id.clone()); + thread::spawn(move || { + let result = handle.start_recording(url); + let _ = tx.send(Msg::RecordingStarted { + client, + id, + bot, + result, + }); + }); + Ok(None) + } + "stop_recording" => { + let bot = self.bot_of(f)?; + let steps = self + .browsers + .get(&bot) + .map(browser::Handle::stop_recording) + .unwrap_or_default(); + let secrets = self.secrets_of(&bot).map_err(|e| ("keychain_failed", e))?; + let name = f + .get("name") + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + .unwrap_or("recorded-workflow"); + let description = f + .get("description") + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + .unwrap_or("Repeatable browser workflow recorded in Bate."); + let markdown = browser::draft_skill(name, description, &steps, &secrets); + self.broadcast(&json!({"type": "bots_changed"})); + Ok(Some(json!({ + "name": name, + "description": description, + "steps": steps.len(), + "markdown": markdown, + }))) + } + "save_recorded_skill" => { + let bot = self.bot_of(f)?; + let markdown = str_field(f, "markdown")?; + let skill = + skills::install_markdown(&bot, markdown).map_err(|e| ("invalid_skill", e))?; + self.store + .set_skill_off(&bot, &skill.name, false) + .map_err(internal)?; + self.skills_changed(&bot); + Ok(Some(json!({"skill": skill}))) + } "get_helper" => Ok(Some(self.desktop.info())), "open_helper_settings" => { self.desktop @@ -3756,6 +3850,13 @@ impl Core { if self.browsers.get(bot).is_some_and(browser::Handle::taken) { row["browserTaken"] = json!(true); } + if self + .browsers + .get(bot) + .is_some_and(browser::Handle::recording) + { + row["recording"] = json!(true); + } if let Ok(Some(agent)) = self.store.agent(bot) { row["agent"] = json!(agent); } diff --git a/appd/src/lan.rs b/appd/src/lan.rs index 7f5962d..f1abbd9 100644 --- a/appd/src/lan.rs +++ b/appd/src/lan.rs @@ -1107,6 +1107,9 @@ mod tests { "preview_skill", "install_skill", "discover_skills", + "start_recording", + "stop_recording", + "save_recorded_skill", "preview_bot_file", "import_bot", "preview_workplace", diff --git a/appd/src/skills.rs b/appd/src/skills.rs index 14f7544..2eb1915 100644 --- a/appd/src/skills.rs +++ b/appd/src/skills.rs @@ -244,6 +244,16 @@ pub fn install_texts(bot: &str, name: &str, files: &[(&str, &str, bool)]) -> Res installed.map_err(failed) } +/// Validates a `SKILL.md` document and installs it into `bot`'s skills folder via the staging area. +pub fn install_markdown(bot: &str, markdown: &str) -> Result { + if markdown.len() > MAX_FILE as usize { + return Err(format!("{FILE} must be at most {} bytes", MAX_FILE)); + } + let skill = skills::parse(markdown)?; + install_texts(bot, &skill.name, &[(FILE, markdown, false)])?; + Ok(skill) +} + /// Copies a folder of plain files and folders to the new folder `to`. `seen` counts entries /// and bytes so far. pub fn copy( diff --git a/appd/tests/service.rs b/appd/tests/service.rs index 2da7236..36f3256 100644 --- a/appd/tests/service.rs +++ b/appd/tests/service.rs @@ -18470,6 +18470,7 @@ const ANSWERS_LATER: &[&str] = &[ "install_workplace", "list_catalog", "discover_skills", + "start_recording", "preview_skill_catalog", "install_skill_catalog", "preview_catalog", @@ -19119,6 +19120,7 @@ fn no_command_stops_the_service_whatever_its_frames_hold() { "APPD_HELPER", home.join("no-helper/Bate Helper.app/Contents/MacOS/bate-helper"), ) + .env("APPD_CHROME", home.join("no-chrome")) .env("APPD_OPEN", &opener) .env("APPD_TRASH", home.join("trash")) .env("HOME", &*home) @@ -20060,3 +20062,180 @@ fn channel_upgrades_routine_delivery_inline_approvals_typing_and_attachments() { let skipped = telegram.heard(7, 11); assert!(skipped.contains("over 10 MB"), "{skipped}"); } + +#[test] +fn record_skill_from_browser_redacts_passwords_and_secrets_and_refuses_devices() { + use std::os::unix::fs::PermissionsExt; + + let home = home("record-skill"); + // Minimal fake Chrome speaking NUL-delimited CDP over fd 3 (in) and fd 4 (out). + // When Page.navigate arrives, it emits recorded bateUser events (open, secret-valued field, + // password field, click) BEFORE replying to Page.navigate so the steps are guaranteed to be + // ingested before start_recording finishes. + let fake_chrome = home.join("fake-cdp-chrome"); + let script = r#"#!/usr/bin/env python3 +import json, os, sys + +r = os.fdopen(3, 'rb', buffering=0) +w = os.fdopen(4, 'wb', buffering=0) + +def send(obj): + w.write(json.dumps(obj).encode('utf-8') + b'\x00') + w.flush() + +buf = bytearray() +while True: + ch = r.read(1) + if not ch: + break + if ch != b'\x00': + buf.extend(ch) + continue + msg = json.loads(buf.decode('utf-8')) + buf.clear() + mid = msg.get('id') + method = msg.get('method') + if method == 'Target.getTargets': + send({'id': mid, 'result': {'targetInfos': [{'targetId': 't1', 'type': 'page'}]}}) + elif method == 'Target.attachToTarget': + send({'id': mid, 'result': {'sessionId': 's1'}}) + elif method == 'Page.getFrameTree': + send({'id': mid, 'result': {'frameTree': {'frame': {'id': 'f1'}}}}) + elif method == 'Page.createIsolatedWorld': + send({'id': mid, 'result': {'executionContextId': 1}}) + elif method == 'Page.navigate': + events = [ + {'kind': 'open', 'url': 'https://shop.example.com/login', 'title': 'Sign in'}, + {'kind': 'type', 'url': 'https://shop.example.com/login', 'label': 'API Token', 'selector': '#tok', 'value': 'top-secret-api-999', 'password': False}, + {'kind': 'type', 'url': 'https://shop.example.com/login', 'label': 'Password', 'selector': '#pw', 'value': 'raw-pw-must-not-appear', 'password': True}, + {'kind': 'click', 'url': 'https://shop.example.com/login', 'role': 'button', 'label': 'Sign in', 'selector': '#go'}, + ] + for ev in events: + send({ + 'method': 'Runtime.bindingCalled', + 'params': {'name': 'bateUser', 'payload': json.dumps(ev)}, + }) + send({'id': mid, 'result': {}}) + else: + send({'id': mid, 'result': {}}) +"#; + fs::write(&fake_chrome, script).unwrap(); + fs::set_permissions(&fake_chrome, fs::Permissions::from_mode(0o755)).unwrap(); + + let _service = Service::start_with(&home, |c| { + c.env("APPD_ENGINE", home.join("fake-engine")) + .env("APPD_CHROME", &fake_chrome) + .env("APPD_LAN_PORT", "0"); + }); + let mut w = Window::connect(&home); + let bot = w.create_bot(); + + // Save two Secrets for the bot via the normal secret-answer flow. + for (nonce, name, site, value) in [ + ("sec1", "shop_pass", "shop.example.com", "my-real-password"), + ("sec2", "api_token", "api.example.com", "top-secret-api-999"), + ] { + w.ok( + "prompt", + json!({"bot": bot, "nonce": nonce, "text": format!("secret {name} {site}")}), + ); + let q = w.wait_for(|f| f["type"] == "transcript" && f["entry"]["type"] == "question"); + let qid = q["entry"]["question"].as_str().unwrap().to_owned(); + w.ok( + "answer_secret", + json!({"bot": bot, "question": qid, "value": value}), + ); + w.wait_for(|f| f["type"] == "transcript" && f["entry"]["type"] == "turn_end"); + } + + // Start recording on the bot's browser. + let started = w.ok( + "start_recording", + json!({"bot": bot, "url": "https://shop.example.com/login"}), + ); + assert_eq!(started["recording"], true); + let listed = w.ok("list_bots", json!({})); + assert_eq!(listed["bots"][0]["recording"], true); + + // Stop recording and inspect the drafted SKILL.md. + let stopped = w.ok( + "stop_recording", + json!({"bot": bot, "name": "shop-signin", "description": "Sign in to shop."}), + ); + assert_eq!(stopped["steps"], 4, "{stopped}"); + let md = stopped["markdown"].as_str().unwrap(); + assert!(md.contains("name: shop-signin"), "{md}"); + assert!( + md.contains("1. Open `https://shop.example.com/login`."), + "{md}" + ); + assert!( + md.contains("2. Type `Secret: api_token` into \"API Token\" (`#tok`)."), + "{md}" + ); + assert!( + md.contains("3. Type `Secret: shop_pass` into password field \"Password\" (`#pw`)."), + "{md}" + ); + assert!(md.contains("4. Click button \"Sign in\" (`#go`)."), "{md}"); + assert!(!md.contains("top-secret-api-999"), "{md}"); + assert!(!md.contains("my-real-password"), "{md}"); + assert!(!md.contains("raw-pw-must-not-appear"), "{md}"); + + // Save the reviewed SKILL.md and confirm it is installed and enabled. + let saved = w.ok("save_recorded_skill", json!({"bot": bot, "markdown": md})); + assert_eq!(saved["skill"]["name"], "shop-signin"); + let skills = w.ok("list_skills", json!({"bot": bot})); + assert_eq!(skills["skills"][0]["name"], "shop-signin"); + assert_eq!(skills["skills"][0]["enabled"], true); + + // Paired LAN devices are refused all three recording commands. + let lan = w.ok("set_lan", json!({"on": true})); + let port = lan["port"].as_u64().unwrap(); + let lan_code = w.ok("pair_device", json!({}))["code"] + .as_str() + .unwrap() + .to_owned(); + let mut device = Device::new(port); + let (status, _, cookie) = device.call( + "POST", + "/api/pair", + &json!({"code": lan_code, "name": "Phone"}).to_string(), + true, + ); + assert_eq!(status, 200); + device.cookie = Some(cookie.unwrap().split(';').next().unwrap().to_owned()); + let (status, sess_body, _) = device.call("POST", "/api/session", "", true); + assert_eq!(status, 200); + let session = serde_json::from_str::(&sess_body).unwrap()["session"] + .as_str() + .unwrap() + .to_owned(); + let send_lan = |dev: &Device, frame: Value| -> Value { + assert_eq!( + dev.call( + "POST", + &format!("/api/send?session={session}"), + &frame.to_string(), + true + ) + .0, + 200 + ); + let (_, recv, _) = dev.call("GET", &format!("/api/recv?session={session}"), "", true); + let batch: Value = serde_json::from_str(&recv).unwrap(); + batch[0].clone() + }; + let _ = send_lan(&device, json!({"id": "h1", "type": "hello", "protocol": 1})); + for (idx, frame) in [ + json!({"id": "rec1", "type": "start_recording", "bot": bot}), + json!({"id": "rec2", "type": "stop_recording", "bot": bot}), + json!({"id": "rec3", "type": "save_recorded_skill", "bot": bot, "markdown": md}), + ] + .into_iter() + .enumerate() + { + let ans = send_lan(&device, frame); + assert_eq!(ans["code"], "forbidden", "case {idx}: {ans}"); + } +} diff --git a/native/src/addons_fixture.rs b/native/src/addons_fixture.rs index 0a5cfbb..8f1af24 100644 --- a/native/src/addons_fixture.rs +++ b/native/src/addons_fixture.rs @@ -304,6 +304,37 @@ pub fn answer( } "list_skills" => json!({"skills": a.skills.get(&bot).cloned().unwrap_or_default()}), "discover_skills" => json!({"skills": a.discovered.clone()}), + "start_recording" => { + if let Some(b) = data.bots.iter_mut().find(|b| b["id"] == bot) { + b["recording"] = json!(true); + } + frames.push(json!({"type": "bots_changed"})); + json!({"recording": true, "bot": bot}) + } + "stop_recording" => { + if let Some(b) = data.bots.iter_mut().find(|b| b["id"] == bot) { + b["recording"] = json!(false); + } + frames.push(json!({"type": "bots_changed"})); + json!({ + "name": "recorded-workflow", + "description": "Repeatable browser workflow recorded in Bate.", + "steps": 2, + "markdown": "---\nname: recorded-workflow\ndescription: Repeatable browser workflow recorded in Bate.\n---\n\n1. Open `https://example.com`.\n2. Click button \"Go\".\n" + }) + } + "save_recorded_skill" => { + let list = a.skills.entry(bot.clone()).or_default(); + if !list.iter().any(|s| s["name"] == "recorded-workflow") { + list.push(json!({ + "name": "recorded-workflow", + "description": "Repeatable browser workflow recorded in Bate.", + "enabled": true, + })); + } + frames.push(json!({"type": "skills_changed", "bot": bot})); + json!({"skill": {"name": "recorded-workflow", "description": "Repeatable browser workflow recorded in Bate."}}) + } "set_skill_enabled" => { match named(a.skills.entry(bot.clone()).or_default(), &name) { Some(s) => s["enabled"] = request["enabled"].clone(), diff --git a/native/src/skills.rs b/native/src/skills.rs index 6284550..997c470 100644 --- a/native/src/skills.rs +++ b/native/src/skills.rs @@ -17,6 +17,9 @@ type V = El; const ACT: &str = "addons:skills:act"; /// Where `discover_skills` results are watched. const DISCOVER: &str = "addons:skills:discover"; +/// Form field keys for browser skill recording and review. +const RECORD_URL: &str = "skills:record:url"; +const REVIEW_MD: &str = "skills:review:markdown"; /// What the panel that picks a folder with a skill in it is asked for (`App::file_chosen`). pub const FOLDER_PANEL: &str = "skills-folder"; @@ -25,7 +28,9 @@ pub struct Page { pub catalog: catalog::State, /// A preview that was asked for and has not come: the sheet opens when it does. looking: Option, - /// Why the last preview was refused. + /// A `stop_recording` request in flight: the review sheet opens when it answers. + stopping: Option<(String, String)>, + /// Why the last preview or recording stop was refused. look_error: Option, serial: u64, } @@ -107,6 +112,13 @@ pub enum Ask { Remove { name: String, }, + Record { + bot: String, + }, + Review { + bot: String, + steps: u64, + }, } /// A local skill folder found on this Mac (`discover_skills`). @@ -199,8 +211,20 @@ pub fn chosen(app: &mut App, folder: &std::path::Path) { ); } -/// A preview that was asked for has come, or was refused. +/// A preview or stopped recording that was asked for has come, or was refused. pub fn opened(app: &mut App) { + if let Some((key, bot)) = app.skills.stopping.clone() { + if let Some(value) = app.state.pages.get(&key).cloned() { + app.skills.stopping = None; + let steps = value["steps"].as_u64().unwrap_or(0); + let markdown = value["markdown"].as_str().unwrap_or_default().to_owned(); + app.forms.set(REVIEW_MD, &markdown); + sheet::open(app, sheet::Ask::Skill(Ask::Review { bot, steps })); + } else if let Some(why) = app.state.pages.error(&key) { + app.skills.look_error = Some(why.to_owned()); + app.skills.stopping = None; + } + } let Some(looking) = &app.skills.looking else { return; }; @@ -234,7 +258,7 @@ pub fn opened(app: &mut App) { } /// What the sheet of `ask` shows. -pub fn sheet(app: &App, _k: &Tokens, ask: &Ask) -> Option { +pub fn sheet(app: &App, k: &Tokens, ask: &Ask) -> Option { Some(match ask { Ask::Install { preview, @@ -365,6 +389,127 @@ pub fn sheet(app: &App, _k: &Tokens, ask: &Ask) -> Option { }), } } + Ask::Record { bot } => { + let url = app.forms.value(RECORD_URL, "").trim().to_owned(); + let field = weft::col() + .gap(SPACE_1) + .child(crate::controls::words( + "Starting address (optional)", + SIZE_SMALL, + LEADING, + k.fg_muted, + )) + .child( + forms::field(app, k, RECORD_URL, "Starting address (optional)", "") + .placeholder("https://example.com"), + ); + Content { + title: "Record a skill".to_owned(), + about: Some( + "Perform the workflow in the bot's Chrome window, then press Stop recording to review the drafted SKILL.md. Passwords and saved Secrets are never recorded in plain text." + .to_owned(), + ), + maker: None, + author: None, + facts: Vec::new(), + may: Vec::new(), + agree: None, + fields: vec![(SPACE_3, SPACE_3, field)], + who: Some(Who { + legend: "Bot browser", + items: app + .state + .bots + .iter() + .map(|b| Item { + id: b.id.clone(), + bot: Some(b.clone()), + label: b.name.clone(), + note: None, + off: false, + }) + .collect(), + ticked: vec![bot.clone()], + optional: false, + }), + action: "Start recording".to_owned(), + danger: false, + status: None, + blocked: None, + ready: true, + steps: Box::new(move |ids, _| { + let mut out = Vec::new(); + if let Some(bot) = ids.first() { + let mut fields = json!({"bot": bot}); + if !url.is_empty() { + fields["url"] = json!(url); + } + out.push(Step { + who: bot.clone(), + command: "start_recording", + fields, + then: Vec::new(), + }); + } + out + }), + } + } + Ask::Review { bot, steps } => { + let markdown = app.forms.value(REVIEW_MD, "").to_owned(); + let field = weft::col() + .gap(SPACE_1) + .child(crate::controls::words( + "SKILL.md", SIZE_SMALL, LEADING, k.fg_muted, + )) + .child(forms::area(app, k, REVIEW_MD, "SKILL.md", "", 12)); + let ready = !markdown.trim().is_empty(); + Content { + title: "Review recorded skill".to_owned(), + about: Some(format!( + "Captured {steps} {}. Edit the SKILL.md below before saving, or cancel to discard it. Passwords and saved Secrets are redacted as Secret: .", + if *steps == 1 { "step" } else { "steps" } + )), + maker: None, + author: None, + facts: Vec::new(), + may: Vec::new(), + agree: None, + fields: vec![(SPACE_3, SPACE_3, field)], + who: Some(Who { + legend: "Save for", + items: app + .state + .bots + .iter() + .map(|b| Item { + id: b.id.clone(), + bot: Some(b.clone()), + label: b.name.clone(), + note: None, + off: false, + }) + .collect(), + ticked: vec![bot.clone()], + optional: false, + }), + action: "Save skill".to_owned(), + danger: false, + status: None, + blocked: None, + ready, + steps: Box::new(move |ids, _| { + ids.iter() + .map(|bot| Step { + who: bot.clone(), + command: "save_recorded_skill", + fields: json!({"bot": bot, "markdown": markdown}), + then: vec![addons::list_key("skills", bot)], + }) + .collect() + }), + } + } }) } @@ -385,22 +530,56 @@ pub fn body(app: &App, cx: &Cx, k: &Tokens) -> V { let bots = app.state.bots.len(); let rows_of = addons::placed(&typed, |s| s.name.clone(), |s| s.name.clone()); let mut flow = Flow::new(); - addons::head( - &mut flow, - k, - "Installed", - vec![ - forms::action(k, "skills-choose", "Choose folder…", Kind::Fill, true, true) - .on_press_with(|_: &mut App, act| { - act.open_panel( - FOLDER_PANEL, - weft::OpenOptions::new() - .directories(true) - .title("Choose folder"), - ); - }), - ], + let mut head_buttons = Vec::new(); + if let Some(recording_bot) = app.state.bots.iter().find(|b| b.recording) { + let bot_id = recording_bot.id.clone(); + let label = format!("Stop recording ({})", recording_bot.name); + head_buttons.push( + forms::action(k, "skills-stop-record", &label, Kind::Primary, true, true).on_press( + move |app: &mut App| { + app.skills.serial += 1; + let key = format!("addons:skills:stop:{}", app.skills.serial); + app.skills.look_error = None; + app.skills.stopping = Some((key.clone(), bot_id.clone())); + app.read_now(&key, "stop_recording", json!({"bot": bot_id})); + }, + ), + ); + } else if let Some(first) = app.state.bots.first() { + let bot_id = first.id.clone(); + head_buttons.push( + forms::action( + k, + "skills-record", + "Record from browser…", + Kind::Fill, + true, + true, + ) + .on_press(move |app: &mut App| { + app.forms.set(RECORD_URL, ""); + sheet::open( + app, + sheet::Ask::Skill(Ask::Record { + bot: bot_id.clone(), + }), + ); + }), + ); + } + head_buttons.push( + forms::action(k, "skills-choose", "Choose folder…", Kind::Fill, true, true).on_press_with( + |_: &mut App, act| { + act.open_panel( + FOLDER_PANEL, + weft::OpenOptions::new() + .directories(true) + .title("Choose folder"), + ); + }, + ), ); + addons::head(&mut flow, k, "Installed", head_buttons); if rows_of.is_empty() { flow.p(addons::note( k, diff --git a/native/src/state.rs b/native/src/state.rs index 8a20574..14a93e2 100644 --- a/native/src/state.rs +++ b/native/src/state.rs @@ -41,6 +41,7 @@ pub struct Bot { pub network: Option>, pub agent: Option>, pub browser_taken: bool, + pub recording: bool, pub instructions: String, pub step_limit: u32, pub web_search: bool, diff --git a/native/tests/addons.rs b/native/tests/addons.rs index 9ffdd82..df02bf0 100644 --- a/native/tests/addons.rs +++ b/native/tests/addons.rs @@ -680,6 +680,36 @@ fn discovered_local_skills_appear_under_on_this_mac_and_open_the_install_sheet() assert_eq!(i["path"], "/Users/demo/.agents/skills/local-helper"); } +#[test] +fn record_skill_from_browser_and_review_sheet_saves_skill() { + let mut w = on_page("Skills"); + assert!(has_key(&mut w.rt, "skills-record")); + press(&mut w, "skills-record"); + assert!(shows(&mut w.rt, "Record a skill")); + confirm(&mut w); + quiet(&mut w); + let started = requests_of(&w.service, "start_recording").remove(0); + assert_eq!(started["bot"], "b1"); + assert!(has_key(&mut w.rt, "skills-stop-record")); + + press(&mut w, "skills-stop-record"); + quiet(&mut w); + assert!(shows(&mut w.rt, "Review recorded skill")); + assert!(shows(&mut w.rt, "Captured 2 steps.")); + assert!(has_key(&mut w.rt, "skills:review:markdown")); + confirm(&mut w); + quiet(&mut w); + let saved = requests_of(&w.service, "save_recorded_skill").remove(0); + assert_eq!(saved["bot"], "b1"); + assert!( + saved["markdown"] + .as_str() + .unwrap() + .contains("name: recorded-workflow") + ); + assert!(shows(&mut w.rt, "recorded-workflow")); +} + // ---- Workplaces ------------------------------------------------------------------------- #[test] diff --git a/native/tests/snapshots/native-addons-skills-add-dark.tree b/native/tests/snapshots/native-addons-skills-add-dark.tree index a03e379..76abb79 100644 --- a/native/tests/snapshots/native-addons-skills-add-dark.tree +++ b/native/tests/snapshots/native-addons-skills-add-dark.tree @@ -135,8 +135,10 @@ generic @0,0,1000,760 generic @288,46,680,682 generic @288,46,680,24 generic @288,70,680,26 - heading @288,74,561.37,18 t="Installed" - generic @861.37,70,106.63,26 + heading @288,74,406.35,18 t="Installed" + generic @706.35,70,261.65,26 + button #skills-record @706.35,70,147.02,26 lb="Record from browser…" tab + text @714.35,75,131.02,16 t="Record from browser…" button #skills-choose @861.37,70,106.63,26 lb="Choose folder…" tab text @869.37,75,90.63,16 t="Choose folder…" generic @288,96,680,8 diff --git a/native/tests/snapshots/native-addons-skills-add-light.tree b/native/tests/snapshots/native-addons-skills-add-light.tree index a03e379..76abb79 100644 --- a/native/tests/snapshots/native-addons-skills-add-light.tree +++ b/native/tests/snapshots/native-addons-skills-add-light.tree @@ -135,8 +135,10 @@ generic @0,0,1000,760 generic @288,46,680,682 generic @288,46,680,24 generic @288,70,680,26 - heading @288,74,561.37,18 t="Installed" - generic @861.37,70,106.63,26 + heading @288,74,406.35,18 t="Installed" + generic @706.35,70,261.65,26 + button #skills-record @706.35,70,147.02,26 lb="Record from browser…" tab + text @714.35,75,131.02,16 t="Record from browser…" button #skills-choose @861.37,70,106.63,26 lb="Choose folder…" tab text @869.37,75,90.63,16 t="Choose folder…" generic @288,96,680,8 diff --git a/native/tests/snapshots/native-addons-skills-catalog-dark.png b/native/tests/snapshots/native-addons-skills-catalog-dark.png index 62febcf..012d9b2 100644 Binary files a/native/tests/snapshots/native-addons-skills-catalog-dark.png and b/native/tests/snapshots/native-addons-skills-catalog-dark.png differ diff --git a/native/tests/snapshots/native-addons-skills-catalog-dark.tree b/native/tests/snapshots/native-addons-skills-catalog-dark.tree index 2019b92..e9da42b 100644 --- a/native/tests/snapshots/native-addons-skills-catalog-dark.tree +++ b/native/tests/snapshots/native-addons-skills-catalog-dark.tree @@ -135,8 +135,10 @@ generic @0,0,1000,760 generic @288,46,680,682 generic @288,46,680,24 generic @288,70,680,26 - heading @288,74,561.37,18 t="Installed" - generic @861.37,70,106.63,26 + heading @288,74,406.35,18 t="Installed" + generic @706.35,70,261.65,26 + button #skills-record @706.35,70,147.02,26 lb="Record from browser…" tab + text @714.35,75,131.02,16 t="Record from browser…" button #skills-choose @861.37,70,106.63,26 lb="Choose folder…" tab text @869.37,75,90.63,16 t="Choose folder…" generic @288,96,680,8 diff --git a/native/tests/snapshots/native-addons-skills-catalog-light.png b/native/tests/snapshots/native-addons-skills-catalog-light.png index 2e63821..3aa224c 100644 Binary files a/native/tests/snapshots/native-addons-skills-catalog-light.png and b/native/tests/snapshots/native-addons-skills-catalog-light.png differ diff --git a/native/tests/snapshots/native-addons-skills-catalog-light.tree b/native/tests/snapshots/native-addons-skills-catalog-light.tree index 2019b92..e9da42b 100644 --- a/native/tests/snapshots/native-addons-skills-catalog-light.tree +++ b/native/tests/snapshots/native-addons-skills-catalog-light.tree @@ -135,8 +135,10 @@ generic @0,0,1000,760 generic @288,46,680,682 generic @288,46,680,24 generic @288,70,680,26 - heading @288,74,561.37,18 t="Installed" - generic @861.37,70,106.63,26 + heading @288,74,406.35,18 t="Installed" + generic @706.35,70,261.65,26 + button #skills-record @706.35,70,147.02,26 lb="Record from browser…" tab + text @714.35,75,131.02,16 t="Record from browser…" button #skills-choose @861.37,70,106.63,26 lb="Choose folder…" tab text @869.37,75,90.63,16 t="Choose folder…" generic @288,96,680,8 diff --git a/native/tests/snapshots/native-addons-skills-dark.png b/native/tests/snapshots/native-addons-skills-dark.png index eab4bee..5d8a1ea 100644 Binary files a/native/tests/snapshots/native-addons-skills-dark.png and b/native/tests/snapshots/native-addons-skills-dark.png differ diff --git a/native/tests/snapshots/native-addons-skills-dark.tree b/native/tests/snapshots/native-addons-skills-dark.tree index d68e148..d7da6ad 100644 --- a/native/tests/snapshots/native-addons-skills-dark.tree +++ b/native/tests/snapshots/native-addons-skills-dark.tree @@ -135,8 +135,10 @@ generic @0,0,1000,760 generic @288,60,680,422 generic @288,60,680,24 generic @288,84,680,26 - heading @288,88,561.37,18 t="Installed" - generic @861.37,84,106.63,26 + heading @288,88,406.35,18 t="Installed" + generic @706.35,84,261.65,26 + button #skills-record @706.35,84,147.02,26 lb="Record from browser…" tab + text @714.35,89,131.02,16 t="Record from browser…" button #skills-choose @861.37,84,106.63,26 lb="Choose folder…" tab text @869.37,89,90.63,16 t="Choose folder…" generic @288,110,680,8 diff --git a/native/tests/snapshots/native-addons-skills-install-dark.tree b/native/tests/snapshots/native-addons-skills-install-dark.tree index e1a8308..2d39182 100644 --- a/native/tests/snapshots/native-addons-skills-install-dark.tree +++ b/native/tests/snapshots/native-addons-skills-install-dark.tree @@ -135,8 +135,10 @@ generic @0,0,1000,760 generic @288,46,680,682 generic @288,46,680,24 generic @288,70,680,26 - heading @288,74,561.37,18 t="Installed" - generic @861.37,70,106.63,26 + heading @288,74,406.35,18 t="Installed" + generic @706.35,70,261.65,26 + button #skills-record @706.35,70,147.02,26 lb="Record from browser…" tab + text @714.35,75,131.02,16 t="Record from browser…" button #skills-choose @861.37,70,106.63,26 lb="Choose folder…" tab text @869.37,75,90.63,16 t="Choose folder…" generic @288,96,680,8 diff --git a/native/tests/snapshots/native-addons-skills-install-light.tree b/native/tests/snapshots/native-addons-skills-install-light.tree index e1a8308..2d39182 100644 --- a/native/tests/snapshots/native-addons-skills-install-light.tree +++ b/native/tests/snapshots/native-addons-skills-install-light.tree @@ -135,8 +135,10 @@ generic @0,0,1000,760 generic @288,46,680,682 generic @288,46,680,24 generic @288,70,680,26 - heading @288,74,561.37,18 t="Installed" - generic @861.37,70,106.63,26 + heading @288,74,406.35,18 t="Installed" + generic @706.35,70,261.65,26 + button #skills-record @706.35,70,147.02,26 lb="Record from browser…" tab + text @714.35,75,131.02,16 t="Record from browser…" button #skills-choose @861.37,70,106.63,26 lb="Choose folder…" tab text @869.37,75,90.63,16 t="Choose folder…" generic @288,96,680,8 diff --git a/native/tests/snapshots/native-addons-skills-light.png b/native/tests/snapshots/native-addons-skills-light.png index 4af4265..8b9ff8b 100644 Binary files a/native/tests/snapshots/native-addons-skills-light.png and b/native/tests/snapshots/native-addons-skills-light.png differ diff --git a/native/tests/snapshots/native-addons-skills-light.tree b/native/tests/snapshots/native-addons-skills-light.tree index d68e148..d7da6ad 100644 --- a/native/tests/snapshots/native-addons-skills-light.tree +++ b/native/tests/snapshots/native-addons-skills-light.tree @@ -135,8 +135,10 @@ generic @0,0,1000,760 generic @288,60,680,422 generic @288,60,680,24 generic @288,84,680,26 - heading @288,88,561.37,18 t="Installed" - generic @861.37,84,106.63,26 + heading @288,88,406.35,18 t="Installed" + generic @706.35,84,261.65,26 + button #skills-record @706.35,84,147.02,26 lb="Record from browser…" tab + text @714.35,89,131.02,16 t="Record from browser…" button #skills-choose @861.37,84,106.63,26 lb="Choose folder…" tab text @869.37,89,90.63,16 t="Choose folder…" generic @288,110,680,8 diff --git a/native/tests/snapshots/native-addons-skills-open-dark.png b/native/tests/snapshots/native-addons-skills-open-dark.png index aa796fd..0aee7ee 100644 Binary files a/native/tests/snapshots/native-addons-skills-open-dark.png and b/native/tests/snapshots/native-addons-skills-open-dark.png differ diff --git a/native/tests/snapshots/native-addons-skills-open-dark.tree b/native/tests/snapshots/native-addons-skills-open-dark.tree index bf376b9..fd0e789 100644 --- a/native/tests/snapshots/native-addons-skills-open-dark.tree +++ b/native/tests/snapshots/native-addons-skills-open-dark.tree @@ -135,8 +135,10 @@ generic @0,0,1000,760 generic @288,60,680,502 generic @288,60,680,24 generic @288,84,680,26 - heading @288,88,561.37,18 t="Installed" - generic @861.37,84,106.63,26 + heading @288,88,406.35,18 t="Installed" + generic @706.35,84,261.65,26 + button #skills-record @706.35,84,147.02,26 lb="Record from browser…" tab + text @714.35,89,131.02,16 t="Record from browser…" button #skills-choose @861.37,84,106.63,26 lb="Choose folder…" tab text @869.37,89,90.63,16 t="Choose folder…" generic @288,110,680,8 diff --git a/native/tests/snapshots/native-addons-skills-open-light.png b/native/tests/snapshots/native-addons-skills-open-light.png index ce1dcdc..05fd1c2 100644 Binary files a/native/tests/snapshots/native-addons-skills-open-light.png and b/native/tests/snapshots/native-addons-skills-open-light.png differ diff --git a/native/tests/snapshots/native-addons-skills-open-light.tree b/native/tests/snapshots/native-addons-skills-open-light.tree index bf376b9..fd0e789 100644 --- a/native/tests/snapshots/native-addons-skills-open-light.tree +++ b/native/tests/snapshots/native-addons-skills-open-light.tree @@ -135,8 +135,10 @@ generic @0,0,1000,760 generic @288,60,680,502 generic @288,60,680,24 generic @288,84,680,26 - heading @288,88,561.37,18 t="Installed" - generic @861.37,84,106.63,26 + heading @288,88,406.35,18 t="Installed" + generic @706.35,84,261.65,26 + button #skills-record @706.35,84,147.02,26 lb="Record from browser…" tab + text @714.35,89,131.02,16 t="Record from browser…" button #skills-choose @861.37,84,106.63,26 lb="Choose folder…" tab text @869.37,89,90.63,16 t="Choose folder…" generic @288,110,680,8 diff --git a/native/tests/snapshots/native-addons-skills-remove-dark.png b/native/tests/snapshots/native-addons-skills-remove-dark.png index 14c82f8..269ea86 100644 Binary files a/native/tests/snapshots/native-addons-skills-remove-dark.png and b/native/tests/snapshots/native-addons-skills-remove-dark.png differ diff --git a/native/tests/snapshots/native-addons-skills-remove-dark.tree b/native/tests/snapshots/native-addons-skills-remove-dark.tree index 74fa14d..26346df 100644 --- a/native/tests/snapshots/native-addons-skills-remove-dark.tree +++ b/native/tests/snapshots/native-addons-skills-remove-dark.tree @@ -135,8 +135,10 @@ generic @0,0,1000,760 generic @288,46,680,682 generic @288,46,680,24 generic @288,70,680,26 - heading @288,74,561.37,18 t="Installed" - generic @861.37,70,106.63,26 + heading @288,74,406.35,18 t="Installed" + generic @706.35,70,261.65,26 + button #skills-record @706.35,70,147.02,26 lb="Record from browser…" tab + text @714.35,75,131.02,16 t="Record from browser…" button #skills-choose @861.37,70,106.63,26 lb="Choose folder…" tab text @869.37,75,90.63,16 t="Choose folder…" generic @288,96,680,8 diff --git a/native/tests/snapshots/native-addons-skills-remove-light.png b/native/tests/snapshots/native-addons-skills-remove-light.png index ec89697..b140fce 100644 Binary files a/native/tests/snapshots/native-addons-skills-remove-light.png and b/native/tests/snapshots/native-addons-skills-remove-light.png differ diff --git a/native/tests/snapshots/native-addons-skills-remove-light.tree b/native/tests/snapshots/native-addons-skills-remove-light.tree index 74fa14d..26346df 100644 --- a/native/tests/snapshots/native-addons-skills-remove-light.tree +++ b/native/tests/snapshots/native-addons-skills-remove-light.tree @@ -135,8 +135,10 @@ generic @0,0,1000,760 generic @288,46,680,682 generic @288,46,680,24 generic @288,70,680,26 - heading @288,74,561.37,18 t="Installed" - generic @861.37,70,106.63,26 + heading @288,74,406.35,18 t="Installed" + generic @706.35,70,261.65,26 + button #skills-record @706.35,70,147.02,26 lb="Record from browser…" tab + text @714.35,75,131.02,16 t="Record from browser…" button #skills-choose @861.37,70,106.63,26 lb="Choose folder…" tab text @869.37,75,90.63,16 t="Choose folder…" generic @288,96,680,8 diff --git a/window/ui/src/Skills.tsx b/window/ui/src/Skills.tsx index 9a43bf9..429d1ee 100644 --- a/window/ui/src/Skills.tsx +++ b/window/ui/src/Skills.tsx @@ -11,7 +11,11 @@ import { sizeText } from "./workplaces.ts"; /** Where a skill is copied from: a folder, the same skill on a bot that has it, or an entry of Bate's list (`sha256`: the archive that was shown). */ type Source = { path: string } | { fromBot: string; name: string } | { catalog: string; sha256: string }; -type Ask = { preview: SkillPreview; source: Source; maker: string } | { remove: string }; +type Ask = + | { preview: SkillPreview; source: Source; maker: string } + | { remove: string } + | { record: { bot: string; url: string } } + | { review: { bot: string; steps: number; markdown: string } }; /** The skills of every bot in one list: what each is, who has it, and one install for as many bots as chosen. */ export function Skills({ bots }: { bots: Bot[] }) { @@ -20,6 +24,8 @@ export function Skills({ bots }: { bots: Bot[] }) { const [ask, setAsk] = useState(); const [error, setError] = useState(""); const [discovered, setDiscovered] = useState([]); + const [recordingBot, setRecordingBot] = useState(); + const activeRecording = bots.find((b) => b.recording)?.id ?? recordingBot; useEffect(() => { if (!inShell) return; let gone = false; @@ -45,11 +51,34 @@ export function Skills({ bots }: { bots: Bot[] }) { (err: Error) => setError(err.message), ); + const stopRecording = (bot: string) => + request<{ steps: number; markdown: string }>("stop_recording", { bot }).then( + (draft) => { + setRecordingBot(undefined); + setError(""); + setAsk({ review: { bot, steps: draft.steps, markdown: draft.markdown } }); + }, + (e: Error) => setError(e.message), + ); + return (

Installed

- void look({ path }, madeBy.folder)} fail={setError} /> +
+ {inShell && bots.length > 0 && ( + activeRecording ? ( + + ) : ( + + ) + )} + void look({ path }, madeBy.folder)} fail={setError} /> +
{rows.length === 0 &&

No skills yet.{inShell ? " Choose a folder with a SKILL.md in it." : ""}

}
    @@ -150,6 +179,66 @@ export function Skills({ bots }: { bots: Bot[] }) { close={() => setAsk(undefined)} /> )} + {ask && "record" in ask && ( + { + const { bot, url } = ask.record; + await request("start_recording", { bot, url: url.trim() || undefined }); + setRecordingBot(bot); + setError(""); + }} + close={() => setAsk(undefined)} + > +
    + + +
    + +
    + )} + {ask && "review" in ask && ( + .`} + who={{ + legend: "Save for", + items: bots.map((b) => ({ id: b.id, bot: b, label: b.name })), + ticked: [ask.review.bot], + }} + action="Save skill" + go={(ids) => each(ids, (bot) => request("save_recorded_skill", { bot, markdown: ask.review.markdown }))} + close={() => setAsk(undefined)} + > +