diff --git a/PROTOCOL.md b/PROTOCOL.md index b0c20c1..5695090 100644 --- a/PROTOCOL.md +++ b/PROTOCOL.md @@ -159,7 +159,7 @@ Quick Ask's `quick_shot` fails with `helper_failed` (the message is the helper's | `set_model` | `bot`, `model` (empty: back to the engine's default, with no `effort`), `effort?` (`minimal`, `low`, `medium`, `high`) | `{}`; kept for the bot, so each new engine of it starts with them; `bots_changed` follows | | `rewind` | `bot`, `conversation?`, `entry` (a prompt's `nonce`), `fork` | Without `fork`: `{}` once the engine went back; the service then removes that prompt and what followed from the conversation's history and sends `history_changed`. With `fork` ("fork from here"): `{conversation}` once the engine went on in a copy; the new conversation holds the old one's history up to, not with, that prompt, and is the bot's current one (`conversations_changed` follows). The old conversation and its engine session are left as they were, so nothing is taken away; `busy` while the bot works in another conversation. The removed prompts' nonces stay used in the ledger, so a late retry of one is answered `duplicate` and does not undo the rewind: send new prompts with new nonces. | | `list_routines` | `bot` | `{routines:[Routine]}` | -| `set_routine` | `bot`, `routine`, `keepPrecheck` (optional) | `{routine}`. No `routine.id`: create; with one: replace. `routine.precheck` is approved by this call: see "Before a run starts". `routine.watch` is checked by it: see "Watching a connector". Only Bate's own window sets a precheck or a watch: from a device on the network a frame whose `routine` has a `precheck` or a `watch` key (to add, change or clear one) is refused with `forbidden`, and any other `set_routine` from a device leaves the stored precheck and watch as they are: the network page adds `keepPrecheck: true`, which says "keep them, whatever `routine.precheck` and `routine.watch` say". A window sends no `keepPrecheck`; for it a routine without `precheck` or `watch` has none | +| `set_routine` | `bot`, `routine`, `keepPrecheck` (optional) | `{routine}`. No `routine.id`: create; with one: replace. `routine.precheck` is approved by this call: see "Before a run starts". `routine.watch` is checked by it: see "Watching a connector". `routine.deliverChannel` (`"telegram"` or `"discord"`) and `routine.deliverChat` (a currently paired chat id for that bot on that channel) optionally send the routine's final reply (capped and marked, never including secrets) to that chat when a run finishes `done`. Only Bate's own window sets a precheck, a watch, or channel delivery: from a device on the network a frame whose `routine` has a `precheck`, `watch`, `deliverChannel` or `deliverChat` key (to add, change or clear one) is refused with `forbidden`, and any other `set_routine` from a device leaves them as they are: the network page adds `keepPrecheck: true`. A window sends no `keepPrecheck` | | `run_routine` | `bot`, `routineId` | `{skipped}`: runs the routine once now, as a normal run recorded with `by` `user`; `skipped` is why it was not run (a sentence), else `null`. Allowed for a routine that is off and one held back by the back-off. `paused` and `busy` when the bot is paused or occupied (also by a precheck that runs), as a webhook is refused; `no_such_routine`; `engine_failed` when the engine could not be started. The answer comes when the start is settled, so after the precheck if there is one. See "Before a run starts" | | `delete_routine` | `bot`, `routineId` | `{}`. Its past runs go with it. | | `list_routine_runs` | `bot`, `routineId` | `{runs:[RoutineRun]}`, newest first, at most the last 50 | @@ -858,7 +858,7 @@ The same page is reachable from the user's own Tailscale network (no relay of Ba - Files (`botfile://`) and surfaces open in the pane of Bate's native window only and are not served to LAN devices. - A device cannot read, set or remove a secret: `answer_secret`, `list_secrets` and `remove_secret` are refused to it. It can only `answer` a secret card with `Deny` (the service refuses any other choice to a secret card, whoever sends it), and its card says that the value is typed in Bate's window on this Mac. - A device may not change a bot's check, in any form (`set_bot` with `check`, `checkModel` or `checkBot`, refused `forbidden`), as it may not change a precheck: only the person at the window decides whether answers are checked. -- A device may not set or change a routine's `watch` (a frame whose `routine` has a `watch` key, even `null`, is refused `forbidden`; the network page's `keepPrecheck: true` keeps the stored watch too): a watch makes the service call a connector tool on its own, which only the person at the window decides. +- A device may not set or change a routine's `watch`, `deliverChannel`, or `deliverChat` (a frame whose `routine` has any of those keys, even `null`, is refused `forbidden`; the network page's `keepPrecheck: true` keeps them as stored): a watch makes the service call a connector tool on its own, and channel pairing is local-only, so only the person at the window decides. ### Speech (the window, not the service) diff --git a/appd/src/botfile.rs b/appd/src/botfile.rs index faf04e9..10e0894 100644 --- a/appd/src/botfile.rs +++ b/appd/src/botfile.rs @@ -471,6 +471,8 @@ fn check(file: BotFile, now: u64) -> Result { last_run: None, precheck: None, watch: None, + deliver_channel: None, + deliver_chat: None, backoff: None, after: None, last_check: None, diff --git a/appd/src/channels.rs b/appd/src/channels.rs index a68971e..ba623d4 100644 --- a/appd/src/channels.rs +++ b/appd/src/channels.rs @@ -4,10 +4,15 @@ //! service's one thread. use crate::core::Msg; -use crate::sys::{log, now_ms}; +use crate::paths; +use crate::sys::{self, log, now_ms}; use serde_json::{Value, json}; -use std::io::{ErrorKind, Read}; +use std::fs::{self, OpenOptions}; +use std::io::{ErrorKind, Read, Write}; use std::net::{TcpStream, ToSocketAddrs}; +use std::os::unix::fs::OpenOptionsExt; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::mpsc::Sender; @@ -31,6 +36,18 @@ const POLL_S: u64 = 25; const UPDATES: u64 = 10; /// Most bytes read of any answer: more than `UPDATES` of them can be. const MAX_ANSWER: u64 = 4 << 20; +/// Largest inbound attachment saved from a paired chat (10 MiB). +pub const MAX_ATTACHMENT: u64 = 10 << 20; +/// Most attachments taken from one chat message. +pub const MAX_ATTACHMENTS: usize = 4; +/// Most bytes read from a local on-device voice transcription. +const MAX_TRANSCRIPT: usize = 8 * 1024; +/// How long an on-device transcription may run before falling back to the raw audio file. +const TRANSCRIBE_TIMEOUT: Duration = Duration::from_secs(15); +/// How often a typing action is refreshed while a bot turn is running. +const TYPING_EVERY: Duration = Duration::from_secs(4); +/// Safety cap on any single typing-indicator loop. +const TYPING_CAP: Duration = Duration::from_secs(10 * 60); /// A Telegram message older than this is not run: it was written while the service was /// off, and whoever wrote it no longer waits. (Discord keeps none.) const STALE_S: u64 = 120; @@ -66,14 +83,46 @@ impl Code { } } +/// Where an inbound attachment comes from; downloaded only after `Core` confirms the chat is paired. +#[derive(Clone, Debug)] +pub enum AttachmentSource { + TelegramFile(String), + DiscordUrl(String), +} + +/// Metadata for an attachment received in a chat message. +#[derive(Clone, Debug)] +pub struct Attachment { + pub source: AttachmentSource, + pub name: String, + pub size: Option, + pub voice: bool, +} + +/// An attachment that passed bounds checks and was saved into the bot's `inbox/` directory. +#[derive(Clone, Debug)] +pub struct SavedAttachment { + pub path: PathBuf, + pub voice: bool, + pub transcript: Option, +} + /// What a channel's reader tells the service. pub enum Note { /// Someone wrote to the bot. `chat` is where the answer goes; `name` is who wrote; `text` - /// is empty for what is no text (a photo, a file). + /// may be empty when only `attachments` were sent. Message { chat: String, name: String, text: String, + attachments: Vec, + }, + /// Someone pressed an inline approval button (`Allow once` or `Deny`) on a question card. + Callback { + chat: String, + callback_id: String, + callback_token: String, + data: String, }, /// The channel works (`None`), or why it does not. State(Option), @@ -185,7 +234,11 @@ fn answer( let mut body = response.into_body().into_reader().take(MAX_ANSWER); body.read_to_string(&mut text) .map_err(|e| clean(format!("no answer: {e}")))?; - let json: Value = serde_json::from_str(&text).unwrap_or(Value::Null); + let json: Value = if text.trim().is_empty() && status.is_success() { + json!({"ok": true}) + } else { + serde_json::from_str(&text).unwrap_or(Value::Null) + }; if status.is_success() && !json.is_null() && json["ok"] != false { return Ok(json); } @@ -194,13 +247,72 @@ fn answer( Err(clean(format!("refused ({status}): {}", why.unwrap_or("")))) } +fn telegram_attachments(message: &Value) -> Vec { + let mut out = Vec::new(); + if let Some(photos) = message["photo"].as_array() + && let Some(best) = photos + .iter() + .rev() + .find(|p| p["file_size"].as_u64().is_none_or(|s| s <= MAX_ATTACHMENT)) + .or_else(|| photos.last()) + && let Some(id) = best["file_id"].as_str() + { + out.push(Attachment { + source: AttachmentSource::TelegramFile(id.to_owned()), + name: "photo.jpg".to_owned(), + size: best["file_size"].as_u64(), + voice: false, + }); + } + if let Some(doc) = message["document"].as_object() + && let Some(id) = doc.get("file_id").and_then(Value::as_str) + { + out.push(Attachment { + source: AttachmentSource::TelegramFile(id.to_owned()), + name: doc + .get("file_name") + .and_then(Value::as_str) + .unwrap_or("file") + .to_owned(), + size: doc.get("file_size").and_then(Value::as_u64), + voice: false, + }); + } + if let Some(voice) = message["voice"].as_object() + && let Some(id) = voice.get("file_id").and_then(Value::as_str) + { + out.push(Attachment { + source: AttachmentSource::TelegramFile(id.to_owned()), + name: "voice.ogg".to_owned(), + size: voice.get("file_size").and_then(Value::as_u64), + voice: true, + }); + } + if let Some(audio) = message["audio"].as_object() + && let Some(id) = audio.get("file_id").and_then(Value::as_str) + { + out.push(Attachment { + source: AttachmentSource::TelegramFile(id.to_owned()), + name: audio + .get("file_name") + .and_then(Value::as_str) + .unwrap_or("audio.mp3") + .to_owned(), + size: audio.get("file_size").and_then(Value::as_u64), + voice: true, + }); + } + out.truncate(MAX_ATTACHMENTS); + out +} + fn telegram(mut r: Reader) { let api = api(TELEGRAM); let agent = agent(Duration::from_secs(POLL_S + 15)); let mut offset = 0; while !r.stopped() { let url = format!( - "{api}/bot{}/getUpdates?timeout={POLL_S}&limit={UPDATES}&offset={offset}&allowed_updates=%5B%22message%22%5D", + "{api}/bot{}/getUpdates?timeout={POLL_S}&limit={UPDATES}&offset={offset}&allowed_updates=%5B%22message%22%2C%22callback_query%22%5D", r.token ); let updates = match answer(agent.get(&url).call(), &r.token) { @@ -217,27 +329,67 @@ fn telegram(mut r: Reader) { let message = &update["message"]; let age_s = (now_ms() / 1000).saturating_sub(message["date"].as_u64().unwrap_or(u64::MAX)); - // shortcut: one-to-one chats and text only; groups are passed over, and of a - // photo or a file only that it came is told. Add them when a bot is to sit in - // a group or to be sent files. if let (Some(chat), Some("private"), true) = ( message["chat"]["id"].as_i64(), message["chat"]["type"].as_str(), age_s <= STALE_S, ) { - let text = message["text"].as_str().unwrap_or(""); + let text = message["text"] + .as_str() + .or_else(|| message["caption"].as_str()) + .unwrap_or(""); let from = &message["from"]; let name = from["first_name"].as_str().or(from["username"].as_str()); + let attachments = telegram_attachments(message); r.note(Note::Message { chat: chat.to_string(), name: name.unwrap_or("someone").to_owned(), text: text.to_owned(), + attachments, + }); + } + let cq = &update["callback_query"]; + if let (Some(callback_id), Some(data), Some(chat), Some("private")) = ( + cq["id"].as_str(), + cq["data"].as_str(), + cq["message"]["chat"]["id"].as_i64(), + cq["message"]["chat"]["type"].as_str(), + ) { + r.note(Note::Callback { + chat: chat.to_string(), + callback_id: callback_id.to_owned(), + callback_token: String::new(), + data: data.to_owned(), }); } } } } +fn discord_attachments(data: &Value) -> Vec { + let Some(items) = data["attachments"].as_array() else { + return Vec::new(); + }; + let mut out = Vec::new(); + for item in items.iter().take(MAX_ATTACHMENTS) { + let Some(url) = item["url"].as_str() else { + continue; + }; + let name = item["filename"].as_str().unwrap_or("file").to_owned(); + let size = item["size"].as_u64(); + let voice = item["content_type"] + .as_str() + .is_some_and(|ct| ct.starts_with("audio/")); + out.push(Attachment { + source: AttachmentSource::DiscordUrl(url.to_owned()), + name, + size, + voice, + }); + } + out +} + fn discord(mut r: Reader) { let api = api(DISCORD); let agent = agent(Duration::from_secs(30)); @@ -375,6 +527,26 @@ fn discord_session(r: &mut Reader, api: &str, agent: &ureq::Agent) -> Result<(), chat: chat.to_owned(), name: name.unwrap_or("someone").to_owned(), text: text.to_owned(), + attachments: discord_attachments(data), + }); + } + } + (Some(0), Some("INTERACTION_CREATE")) => { + // Message component button press in a direct message only. + if data["type"].as_u64() == Some(3) + && data["guild_id"].is_null() + && let (Some(chat), Some(callback_id), Some(callback_token), Some(custom_id)) = ( + data["channel_id"].as_str(), + data["id"].as_str(), + data["token"].as_str(), + data["data"]["custom_id"].as_str(), + ) + { + r.note(Note::Callback { + chat: chat.to_owned(), + callback_id: callback_id.to_owned(), + callback_token: callback_token.to_owned(), + data: custom_id.to_owned(), }); } } @@ -400,6 +572,428 @@ pub fn send(kind: &'static str, token: &str, chat: &str, text: &str) { }); } +/// Sends an interactive approval card with `Allow once` and `Deny` buttons only (never `Always`). +/// Never called for Secret prompts. Does not wait for the network. +pub fn send_question(kind: &'static str, token: &str, chat: &str, question_id: &str, text: &str) { + let (token, chat, question_id) = (token.to_owned(), chat.to_owned(), question_id.to_owned()); + let mut piece: String = text.chars().take(1900).collect(); + if text.chars().count() > 1900 { + piece.push('…'); + } + SENDING.fetch_add(1, Ordering::SeqCst); + thread::spawn(move || { + let agent = agent(Duration::from_secs(30)); + let approve_id = format!("approve:{question_id}"); + let deny_id = format!("deny:{question_id}"); + let sent = if kind == "telegram" { + let chat_id = chat.parse::().map_or(json!(chat), Value::from); + agent + .post(format!("{}/bot{token}/sendMessage", api(TELEGRAM))) + .header("Content-Type", "application/json") + .send( + json!({ + "chat_id": chat_id, + "text": piece, + "reply_markup": { + "inline_keyboard": [[ + {"text": "Allow once", "callback_data": approve_id}, + {"text": "Deny", "callback_data": deny_id}, + ]] + } + }) + .to_string() + .as_bytes(), + ) + } else { + if !chat.bytes().all(|b| b.is_ascii_digit()) { + SENDING.fetch_sub(1, Ordering::SeqCst); + return; + } + agent + .post(format!("{}/channels/{chat}/messages", api(DISCORD))) + .header("Authorization", format!("Bot {token}")) + .header("User-Agent", DISCORD_AGENT) + .header("Content-Type", "application/json") + .send( + json!({ + "content": piece, + "components": [{ + "type": 1, + "components": [ + {"type": 2, "style": 3, "label": "Allow once", "custom_id": approve_id}, + {"type": 2, "style": 4, "label": "Deny", "custom_id": deny_id}, + ] + }] + }) + .to_string() + .as_bytes(), + ) + }; + if let Err(e) = answer(sent, &token) { + log!("{kind}: an approval card was not sent: {e}"); + } + SENDING.fetch_sub(1, Ordering::SeqCst); + }); +} + +/// Acknowledges an inline button press (`answerCallbackQuery` for Telegram, interaction callback +/// for Discord). Does not wait for the network. +pub fn answer_callback( + kind: &'static str, + token: &str, + callback_id: &str, + callback_token: &str, + note: &str, +) { + let (token, callback_id, callback_token, note) = ( + token.to_owned(), + callback_id.to_owned(), + callback_token.to_owned(), + note.to_owned(), + ); + SENDING.fetch_add(1, Ordering::SeqCst); + thread::spawn(move || { + let agent = agent(Duration::from_secs(15)); + let sent = if kind == "telegram" { + agent + .post(format!("{}/bot{token}/answerCallbackQuery", api(TELEGRAM))) + .header("Content-Type", "application/json") + .send( + json!({"callback_query_id": callback_id, "text": note}) + .to_string() + .as_bytes(), + ) + } else { + if !callback_id.bytes().all(|b| b.is_ascii_digit()) + || callback_token.is_empty() + || callback_token.contains(['/', '?', '#', '\\']) + { + SENDING.fetch_sub(1, Ordering::SeqCst); + return; + } + agent + .post(format!( + "{}/interactions/{callback_id}/{callback_token}/callback", + api(DISCORD) + )) + .header("User-Agent", DISCORD_AGENT) + .header("Content-Type", "application/json") + .send( + json!({"type": 4, "data": {"content": note, "flags": 64}}) + .to_string() + .as_bytes(), + ) + }; + if let Err(e) = answer(sent, &token) { + log!("{kind}: callback acknowledgement failed: {e}"); + } + SENDING.fetch_sub(1, Ordering::SeqCst); + }); +} + +/// Sends periodic typing indicators to `chat` until the returned flag is set to `true` (or the +/// safety cap elapses). Runs off `Core::run`. +pub fn start_typing(kind: &'static str, token: &str, chat: &str) -> Arc { + let stop = Arc::new(AtomicBool::new(false)); + let flag = stop.clone(); + let (token, chat) = (token.to_owned(), chat.to_owned()); + thread::spawn(move || { + let agent = agent(Duration::from_secs(10)); + let started = Instant::now(); + while !flag.load(Ordering::SeqCst) && started.elapsed() < TYPING_CAP { + let sent = if kind == "telegram" { + let chat_id = chat.parse::().map_or(json!(chat), Value::from); + agent + .post(format!("{}/bot{token}/sendChatAction", api(TELEGRAM))) + .header("Content-Type", "application/json") + .send( + json!({"chat_id": chat_id, "action": "typing"}) + .to_string() + .as_bytes(), + ) + } else { + if !chat.bytes().all(|b| b.is_ascii_digit()) { + return; + } + agent + .post(format!("{}/channels/{chat}/typing", api(DISCORD))) + .header("Authorization", format!("Bot {token}")) + .header("User-Agent", DISCORD_AGENT) + .send(&[] as &[u8]) + }; + if let Err(e) = answer(sent, &token) { + log!("{kind}: typing indicator failed: {e}"); + return; + } + let next = Instant::now() + TYPING_EVERY; + while !flag.load(Ordering::SeqCst) && Instant::now() < next { + thread::sleep(Duration::from_millis(200)); + } + } + }); + stop +} + +/// Downloads bounded inbound attachments for a paired chat on a background thread, runs local-only +/// on-device transcription on voice notes, and delivers the result back to `Core` via +/// `Msg::ChannelAttachments`. +pub fn fetch_attachments( + bot: String, + kind: &'static str, + token: String, + chat: String, + text: String, + attachments: Vec, + tx: Sender, +) { + thread::spawn(move || { + let agent = agent(Duration::from_secs(30)); + let inbox = paths::bot_dir(&bot).join("inbox"); + let mut saved = Vec::new(); + let mut skipped = Vec::new(); + if let Err(e) = sys::create_private_dir(&inbox) { + skipped.push(format!("could not prepare inbox folder: {e}")); + } else { + for att in attachments.into_iter().take(MAX_ATTACHMENTS) { + let display_name = sanitize_name(&att.name); + if att.size.is_some_and(|s| s > MAX_ATTACHMENT) { + skipped.push(format!("{display_name} is over 10 MB")); + continue; + } + let bytes = match download_attachment(&agent, &token, &att.source) { + Ok(bytes) => bytes, + Err(why) => { + skipped.push(format!("{display_name}: {why}")); + continue; + } + }; + let filename = format!("{}-{display_name}", sys::random_hex(4)); + let path = inbox.join(&filename); + match write_private(&path, &bytes) { + Ok(()) => { + let transcript = if att.voice { + transcribe_offline(&path) + } else { + None + }; + saved.push(SavedAttachment { + path, + voice: att.voice, + transcript, + }); + } + Err(e) => skipped.push(format!("{display_name}: could not save ({e})")), + } + } + } + let _ = tx.send(Msg::ChannelAttachments { + bot, + kind, + chat, + text, + saved, + skipped, + }); + }); +} + +fn sanitize_name(raw: &str) -> String { + let base = Path::new(raw) + .file_name() + .and_then(|s| s.to_str()) + .unwrap_or("file"); + let cleaned: String = base + .chars() + .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_')) + .take(80) + .collect(); + let trimmed = cleaned.trim_start_matches('.'); + if trimmed.is_empty() { + "file".to_owned() + } else { + trimmed.to_owned() + } +} + +fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> { + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(path)?; + file.write_all(bytes) +} + +fn allowed_discord_url(url: &str) -> bool { + if url.starts_with("https://cdn.discordapp.com/") + || url.starts_with("https://media.discordapp.net/") + { + return true; + } + if let Ok(override_api) = std::env::var(DISCORD.0) { + let origin = override_api.trim_end_matches('/'); + if !origin.is_empty() && url.starts_with(origin) { + return true; + } + } + false +} + +fn download_attachment( + agent: &ureq::Agent, + token: &str, + source: &AttachmentSource, +) -> Result, String> { + let clean = |text: String| text.replace(token, "[removed]"); + let url = match source { + AttachmentSource::TelegramFile(file_id) => { + if file_id.is_empty() || file_id.contains(['/', '?', '#', '&', '\\']) { + return Err("invalid file id".into()); + } + let api = api(TELEGRAM); + let meta = answer( + agent + .get(format!("{api}/bot{token}/getFile?file_id={file_id}")) + .call(), + token, + )?; + let file_path = meta["result"]["file_path"] + .as_str() + .ok_or("no file path returned")?; + if file_path.is_empty() + || file_path.starts_with('/') + || file_path.contains("..") + || file_path.contains(['?', '#', '\\']) + { + return Err("invalid file path".into()); + } + format!("{api}/file/bot{token}/{file_path}") + } + AttachmentSource::DiscordUrl(url) => { + if !allowed_discord_url(url) { + return Err("attachment host not allowed".into()); + } + url.clone() + } + }; + let response = agent + .get(&url) + .call() + .map_err(|e| clean(format!("download failed: {e}")))?; + if !response.status().is_success() { + return Err(format!("refused ({})", response.status())); + } + let mut buf = Vec::new(); + response + .into_body() + .into_reader() + .take(MAX_ATTACHMENT + 1) + .read_to_end(&mut buf) + .map_err(|e| clean(format!("read failed: {e}")))?; + if buf.len() as u64 > MAX_ATTACHMENT { + return Err("is over 10 MB".into()); + } + Ok(buf) +} + +/// Transcribes a voice note strictly on-device (never calls a cloud speech API). +/// Uses `BATE_TRANSCRIBE_CMD` when configured (for offline testing or custom local transcribers), +/// otherwise attempts macOS on-device `SFSpeechRecognizer` (`requiresOnDeviceRecognition = true`). +fn transcribe_offline(path: &Path) -> Option { + if let Ok(cmd) = std::env::var("BATE_TRANSCRIBE_CMD") { + let trimmed = cmd.trim(); + if !trimmed.is_empty() { + return run_bounded_transcriber(trimmed, &[path.to_string_lossy().as_ref()]); + } + } + #[cfg(target_os = "macos")] + { + // Only runs strictly on-device when Speech recognition is already authorized on this Mac. + // Never uploads audio to any network service. + const SWIFT: &str = r#" +import Foundation +import Speech +guard CommandLine.arguments.count > 1 else { exit(2) } +guard SFSpeechRecognizer.authorizationStatus() == .authorized else { exit(3) } +guard let rec = SFSpeechRecognizer(), rec.isAvailable, rec.supportsOnDeviceRecognition else { exit(4) } +let url = URL(fileURLWithPath: CommandLine.arguments[1]) +let req = SFSpeechURLRecognitionRequest(url: url) +req.requiresOnDeviceRecognition = true +let sem = DispatchSemaphore(value: 0) +var out: String? = nil +rec.recognitionTask(with: req) { res, err in + if let r = res, r.isFinal { + out = r.bestTranscription.formattedString + sem.signal() + } else if err != nil { + sem.signal() + } +} +_ = sem.wait(timeout: .now() + 12) +if let text = out, !text.isEmpty { + print(text) + exit(0) +} +exit(5) +"#; + let path_arg = path.to_string_lossy().into_owned(); + if let Some(script) = write_temp_swift(SWIFT) { + let result = run_bounded_transcriber( + "/usr/bin/swift", + &[script.to_string_lossy().as_ref(), &path_arg], + ); + let _ = fs::remove_file(script); + return result; + } + } + None +} + +#[cfg(target_os = "macos")] +fn write_temp_swift(source: &str) -> Option { + let dir = paths::home().join("tmp"); + sys::create_private_dir(&dir).ok()?; + let path = dir.join(format!("transcribe-{}.swift", sys::random_hex(4))); + write_private(&path, source.as_bytes()).ok()?; + Some(path) +} + +fn run_bounded_transcriber(program: &str, args: &[&str]) -> Option { + let mut child = Command::new(program) + .args(args) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .ok()?; + let mut stdout = child.stdout.take()?; + let reader = thread::spawn(move || { + let mut buf = Vec::new(); + let _ = (&mut stdout) + .take(MAX_TRANSCRIPT as u64) + .read_to_end(&mut buf); + buf + }); + let deadline = Instant::now() + TRANSCRIBE_TIMEOUT; + let ok = loop { + match child.try_wait() { + Ok(Some(status)) => break status.success(), + Ok(None) if Instant::now() < deadline => thread::sleep(Duration::from_millis(50)), + _ => { + let _ = child.kill(); + let _ = child.wait(); + break false; + } + } + }; + let bytes = reader.join().ok().unwrap_or_default(); + if !ok { + return None; + } + let text = String::from_utf8_lossy(&bytes).trim().to_owned(); + if text.is_empty() { None } else { Some(text) } +} + fn deliver(kind: &str, token: &str, chat: &str, pieces: Vec) { { let agent = agent(Duration::from_secs(30)); diff --git a/appd/src/core.rs b/appd/src/core.rs index 6b07f06..3ab98aa 100644 --- a/appd/src/core.rs +++ b/appd/src/core.rs @@ -27,7 +27,7 @@ use ring::digest; use serde_json::{Value, json}; use crate::attach; -use crate::channels::{self, Note}; +use crate::channels::{self, Attachment, Note, SavedAttachment}; use crate::chatgpt; use crate::clients::ClientHandle; use crate::hooks::{self, Hit}; @@ -213,6 +213,15 @@ pub enum Msg { id: String, generation: u64, }, + /// Downloaded inbound attachments (and any offline voice transcripts) from a paired chat. + ChannelAttachments { + bot: String, + kind: &'static str, + chat: String, + text: String, + saved: Vec, + skipped: Vec, + }, /// The service was asked to stop. Shutdown, /// `event: None`: the engine closed its output (it exited or broke the protocol). @@ -590,6 +599,16 @@ enum Waiter { Quiet, /// The service's own `answer` to a question its permissions decided. Decision, + /// An inline `Allow once` / `Deny` answer from a paired channel chat. + ChannelAnswer { + question: String, + kind: &'static str, + chat: String, + callback_id: String, + callback_token: String, + label: &'static str, + approved: bool, + }, /// The service's own `call_tool`, for the watch of a routine; the answer, when it came. Watch { routine: String, @@ -651,6 +670,9 @@ struct Running { /// The browser action the running turn waits on: set when the turn ends, so that an /// action still waiting for the user's hand-back is not run. browsing: Option>, + /// The periodic typing indicator running for a channel-started turn: set when the turn ends + /// or pauses on a question. + typing: Option>, /// Steers sent to the running turn that it has not taken in yet. One still here when the /// turn ends never reached it, and goes to the bot as the next prompt. steered: Vec, @@ -1312,11 +1334,35 @@ impl Core { }; self.broadcast(&json!({"type": "channels_changed", "bot": key.0})); } - Note::Message { chat, name, text } => { - self.on_chat(&key.0, kind, &chat, &name, &text) - } + Note::Message { + chat, + name, + text, + attachments, + } => self.on_chat(&key.0, kind, &chat, &name, &text, attachments), + Note::Callback { + chat, + callback_id, + callback_token, + data, + } => self.on_chat_callback( + &key.0, + kind, + &chat, + &callback_id, + &callback_token, + &data, + ), } } + Msg::ChannelAttachments { + bot, + kind, + chat, + text, + saved, + skipped, + } => self.on_chat_attachments(&bot, kind, &chat, &text, saved, skipped), Msg::SignIn { client, id, result } => { let reply = match result { Ok((url, state, pending)) => { @@ -4124,6 +4170,7 @@ impl Core { depth: 0, said: String::new(), browsing: None, + typing: None, steered: Vec::new(), conversation: conversation.clone(), session_of: None, @@ -5726,10 +5773,107 @@ impl Core { } } + /// Sends an inline `Allow once` / `Deny` approval card to a paired chat. + fn ask_chat(&self, bot: &str, kind: &'static str, chat: &str, question: &str, text: &str) { + match self.store.channel(bot, kind) { + Ok(Some(token)) => channels::send_question(kind, &token, chat, question, text), + Ok(None) => {} + Err(e) => log!("bot {bot}: {kind} token not read: {e}"), + } + } + + /// Acknowledges an inline button press from a paired chat. + fn ack_chat( + &self, + bot: &str, + kind: &'static str, + callback_id: &str, + callback_token: &str, + note: &str, + ) { + match self.store.channel(bot, kind) { + Ok(Some(token)) => { + channels::answer_callback(kind, &token, callback_id, callback_token, note) + } + Ok(None) => {} + Err(e) => log!("bot {bot}: {kind} token not read: {e}"), + } + } + + /// Starts periodic typing actions for a chat while a turn runs. + fn start_typing(&self, bot: &str, kind: &'static str, chat: &str) -> Option> { + match self.store.channel(bot, kind) { + Ok(Some(token)) => Some(channels::start_typing(kind, &token, chat)), + Ok(None) => None, + Err(e) => { + log!("bot {bot}: {kind} token not read: {e}"); + None + } + } + } + + /// Returns a routine's paired delivery channel target if set and still paired. + fn routine_delivery(&self, bot: &str, routine_id: &str) -> Option<(&'static str, String)> { + let routine = self + .store + .routines(bot) + .ok()? + .into_iter() + .find(|r| r.id.as_deref() == Some(routine_id))?; + let kind = match routine.deliver_channel.as_deref()? { + "telegram" => "telegram", + "discord" => "discord", + _ => return None, + }; + let chat = routine.deliver_chat?; + let paired = self + .store + .chats(bot, kind) + .ok()? + .iter() + .any(|(known, _)| known == &chat); + paired.then_some((kind, chat)) + } + + /// Posts a finished routine's final reply to its paired delivery chat (capped and redacted; + /// never includes secrets). + fn deliver_routine_reply( + &self, + bot: &str, + routine_id: &str, + summary: &str, + already_sent_to: Option<(&'static str, &str)>, + ) { + let Some((kind, chat)) = self.routine_delivery(bot, routine_id) else { + return; + }; + if already_sent_to == Some((kind, chat.as_str())) { + return; + } + let body = summary.trim(); + if body.is_empty() { + return; + } + let marked = proto::reveal::mark_plain(body); + let mut out: String = marked.chars().take(3500).collect(); + if marked.chars().count() > 3500 { + out.push('…'); + } + self.say(bot, kind, &chat, &out); + } + /// Someone wrote to the bot on a channel. A chat that was let in has its message sent on /// as a prompt, and the reply follows when the turn ends; any other must send the code /// the window shows first. - fn on_chat(&mut self, bot: &str, kind: &'static str, chat: &str, name: &str, text: &str) { + fn on_chat( + &mut self, + bot: &str, + kind: &'static str, + chat: &str, + name: &str, + text: &str, + attachments: Vec, + ) { let known = match self.store.chats(bot, kind) { Ok(chats) => chats.iter().any(|(known, _)| known == chat), Err(e) => return log!("bot {bot}: chats not read: {e}"), @@ -5773,8 +5917,13 @@ impl Core { }; return self.say(bot, kind, chat, reply); } - if text.trim().is_empty() { - return self.say(bot, kind, chat, "Only text is read here."); + if text.trim().is_empty() && attachments.is_empty() { + return self.say( + bot, + kind, + chat, + "Only text, files, or voice notes are read here.", + ); } // `/run `: the lines after the first go along as data. let (first, data) = text.split_once('\n').unwrap_or((text, "")); @@ -5803,9 +5952,30 @@ impl Core { if let Some(name) = run { return self.run_from_chat(bot, kind, chat, name.trim(), data); } + if !attachments.is_empty() { + let token = match self.store.channel(bot, kind) { + Ok(Some(token)) => token, + Ok(None) => return, + Err(e) => return log!("bot {bot}: {kind} token not read: {e}"), + }; + channels::fetch_attachments( + bot.to_owned(), + kind, + token, + chat.to_owned(), + text.to_owned(), + attachments, + self.tx.clone(), + ); + return; + } + self.send_chat_prompt(bot, kind, chat, text.to_owned()); + } + + fn send_chat_prompt(&mut self, bot: &str, kind: &'static str, chat: &str, text: String) { let prompt = Outgoing { nonce: format!("chat-{}", sys::random_hex(6)), - text: text.to_owned(), + text, }; let caller = Caller::Chat { kind, @@ -5822,6 +5992,174 @@ impl Core { } } + /// Continues a paired chat message once its attachments have been downloaded (and any voice + /// notes transcribed locally on-device) off `Core::run`. + fn on_chat_attachments( + &mut self, + bot: &str, + kind: &'static str, + chat: &str, + text: &str, + saved: Vec, + skipped: Vec, + ) { + if self.store.bot(bot).ok().flatten().is_none() { + return; + } + if self.is_paused(bot) { + return self.say( + bot, + kind, + chat, + "The bot is paused. Write again when it is resumed.", + ); + } + if !self.free(bot) { + return self.say( + bot, + kind, + chat, + "The bot is busy. Write again when it is done.", + ); + } + if text.trim().is_empty() && saved.is_empty() { + let reason = if skipped.is_empty() { + "The attachment could not be read.".to_owned() + } else { + format!("Attachment skipped: {}", skipped.join("; ")) + }; + return self.say(bot, kind, chat, &reason); + } + let mut parts = Vec::new(); + if !text.trim().is_empty() { + parts.push(text.trim().to_owned()); + } + for item in &saved { + let path = item.path.display(); + match (&item.voice, &item.transcript) { + (true, Some(transcript)) => { + parts.push(format!( + "[Voice note transcript (saved at {path}; data from user): {transcript}]" + )); + } + (true, None) => { + parts.push(format!( + "[Voice note saved at {path} (on-device transcription unavailable)]" + )); + } + (false, _) => { + parts.push(format!("[Attached file saved at {path}]")); + } + } + } + for reason in &skipped { + parts.push(format!("[Attachment skipped: {reason}]")); + } + self.send_chat_prompt(bot, kind, chat, parts.join("\n")); + } + + /// Handles an inline `Allow once` / `Deny` button tap from a paired channel chat. + /// Never grants `Always` and never answers Secret prompts. + fn on_chat_callback( + &mut self, + bot: &str, + kind: &'static str, + chat: &str, + callback_id: &str, + callback_token: &str, + data: &str, + ) { + let known = match self.store.chats(bot, kind) { + Ok(chats) => chats.iter().any(|(known, _)| known == chat), + Err(e) => return log!("bot {bot}: chats not read: {e}"), + }; + if !known { + return; + } + let (choice, question, label, approved) = if let Some(q) = data.strip_prefix("approve:") { + (APPROVE, q, "Allowed once.", true) + } else if let Some(q) = data.strip_prefix("deny:") { + (DENY, q, "Denied.", false) + } else { + return self.ack_chat( + bot, + kind, + callback_id, + callback_token, + "Unsupported action.", + ); + }; + let Some(conversation) = self.engines.get(bot).map(|r| r.conversation.clone()) else { + return self.ack_chat( + bot, + kind, + callback_id, + callback_token, + "That question is no longer open.", + ); + }; + let open = match self.store.questions(&conversation) { + Ok(open) => open, + Err(e) => { + log!("bot {bot}: questions not read: {e}"); + return; + } + }; + let Some(asked) = open.iter().find(|q| q["question"] == question) else { + return self.ack_chat( + bot, + kind, + callback_id, + callback_token, + "That question is no longer open.", + ); + }; + // Secret prompts can never be answered from a chat channel. + if asked.get("secret").is_some() { + return self.ack_chat( + bot, + kind, + callback_id, + callback_token, + "Secrets can only be entered in Bate on your Mac.", + ); + } + if asked.get("handoff").is_some() { + return self.ack_chat( + bot, + kind, + callback_id, + callback_token, + "Open Bate on your Mac to review that hand-off.", + ); + } + let op = Op::Answer { + question: question.to_owned(), + choice: choice.to_owned(), + }; + if let Err((_, e)) = self.send_op( + bot, + op, + Waiter::ChannelAnswer { + question: question.to_owned(), + kind, + chat: chat.to_owned(), + callback_id: callback_id.to_owned(), + callback_token: callback_token.to_owned(), + label, + approved, + }, + ) { + self.ack_chat( + bot, + kind, + callback_id, + callback_token, + &format!("Could not answer: {e}"), + ); + } + } + /// Tells whoever sent a bot a message what came of it. A message that carries an acceptance /// command is answered once the command has run (`check_handoff`). fn answer_caller(&mut self, bot: &str, caller: Caller, reply: Result) { @@ -7114,6 +7452,11 @@ impl Core { if let Some(browsing) = r.browsing.take() { browsing.store(true, Ordering::SeqCst); } + if !r.busy + && let Some(typing) = r.typing.take() + { + typing.store(true, Ordering::SeqCst); + } let answered = if r.busy { None } else { r.call.take() }; let routine = if r.busy { None } else { r.routine.take() }; let used = if r.busy { None } else { r.used.take() }; @@ -7126,6 +7469,10 @@ impl Core { let conversation = r.conversation.clone(); self.close_questions(bot, &conversation); } + let already_sent_to = answered.as_ref().and_then(|c| match &c.caller { + Caller::Chat { kind, chat, .. } => Some((*kind, chat.clone())), + _ => None, + }); if let (Some(call), Event::TurnEnd { reason, error }) = (answered, &ev) { let reply = match (reason, call.reply.trim()) { (proto::TurnEnd::Done, "") => Err("it ended without a reply".into()), @@ -7170,6 +7517,14 @@ impl Core { &self.name_of(bot), summary, )); + self.deliver_routine_reply( + bot, + id, + summary, + already_sent_to + .as_ref() + .map(|(kind, chat)| (*kind, chat.as_str())), + ); } } self.broadcast(&json!({"type": "bots_changed"})); @@ -7189,22 +7544,72 @@ impl Core { } } Event::Question { - question, title, .. + question, + title, + options, + target, + secret, + .. } => { + if let Some(typing) = r.typing.take() { + typing.store(true, Ordering::SeqCst); + } let entry = with_context(&ev); let conversation = r.conversation.clone(); if let Err(e) = self.store.put_question(&conversation, question, &entry) { log!("bot {bot}: question not stored: {e}"); } - // The chat cannot answer it: whoever wrote there is told where to. - if let Some(Call { - caller: Caller::Chat { kind, chat, .. }, - .. - }) = &r.call - { - let (kind, chat) = (*kind, chat.clone()); - let note = format!("The bot waits for your answer in Bate: {title}"); - self.say(bot, kind, &chat, ¬e); + let chat_call = match &r.call { + Some(Call { + caller: Caller::Chat { kind, chat, .. }, + .. + }) => Some((*kind, chat.clone())), + _ => None, + }; + let routine_id = r.routine.clone(); + let notify_chat = chat_call.or_else(|| { + routine_id + .as_deref() + .and_then(|rid| self.routine_delivery(bot, rid)) + }); + if let Some((kind, chat)) = notify_chat { + if secret.is_some() { + // Secret prompts are never sent as approval cards and never name the secret. + self.say( + bot, + kind, + &chat, + "The bot needs a secret in Bate on your Mac.", + ); + } else if options.iter().any(|o| o == APPROVE) + && options.iter().any(|o| o == DENY) + { + let marked_title = proto::reveal::mark_plain(title); + let mut card = format!("Needs you: {marked_title}"); + if let Some(t) = target.as_deref().filter(|t| !t.trim().is_empty()) { + let marked_target = proto::reveal::mark_plain(t.trim()); + let mut truncated: String = marked_target.chars().take(500).collect(); + if marked_target.chars().count() > 500 { + truncated.push('…'); + } + card.push('\n'); + card.push_str(&truncated); + } + if proto::reveal::has_hidden( + [title.as_str()].into_iter().chain(target.as_deref()), + ) { + card.push_str( + "\n(Hidden or reordering characters are shown in brackets.)", + ); + } + self.ask_chat(bot, kind, &chat, question, &card); + } else { + let note = format!( + "The bot waits for your answer in Bate: {}", + proto::reveal::mark_plain(title) + ); + self.say(bot, kind, &chat, ¬e); + } } } _ => {} @@ -7543,12 +7948,22 @@ impl Core { | Caller::Answer { .. } | Caller::Room { .. } => None, }; + let typing = match &caller { + Caller::Chat { kind, chat, .. } => self.start_typing(bot, kind, chat), + _ => None, + }; if let Some(r) = self.engines.get_mut(bot) { + if let Some(prev) = r.typing.take() { + prev.store(true, Ordering::SeqCst); + } + r.typing = typing; r.routine = routine; r.call = Some(Call { caller, reply: String::new(), }); + } else if let Some(t) = typing { + t.store(true, Ordering::SeqCst); } } } @@ -7605,6 +8020,51 @@ impl Core { log!("bot {bot}: engine refused the decision: {e}"); } } + Waiter::ChannelAnswer { + question, + kind, + chat, + callback_id, + callback_token, + label, + approved, + } => match error { + None => { + match self.store.take_question(&conversation, &question) { + Ok(_) => { + self.broadcast(&json!({ + "type": "question_closed", + "bot": bot, + "conversation": conversation, + "question": question, + })); + self.broadcast(&json!({"type": "bots_changed"})); + } + Err(e) => log!("bot {bot}: question not closed: {e}"), + } + if approved { + let typing = self.start_typing(bot, kind, &chat); + if let Some(r) = self.engines.get_mut(bot) { + if let Some(prev) = r.typing.take() { + prev.store(true, Ordering::SeqCst); + } + r.typing = typing; + } else if let Some(t) = typing { + t.store(true, Ordering::SeqCst); + } + } + self.ack_chat(bot, kind, &callback_id, &callback_token, label); + } + Some(e) => { + self.ack_chat( + bot, + kind, + &callback_id, + &callback_token, + &format!("Could not answer: {e}"), + ); + } + }, Waiter::Open(opened) => { if let Some(r) = self.engines.get_mut(bot) { r.opening = r.opening.saturating_sub(1); @@ -7710,6 +8170,9 @@ impl Core { if let Some(browsing) = r.browsing.take() { browsing.store(true, Ordering::SeqCst); } + if let Some(typing) = r.typing.take() { + typing.store(true, Ordering::SeqCst); + } let _ = r.child.kill(); let status = r.child.wait(); log!("bot {bot}: engine stopped ({status:?})"); @@ -7791,6 +8254,18 @@ impl Core { Waiter::Watch { routine, watch, .. } => { self.on_watched(bot, &routine, &watch, Err("the engine stopped".into())) } + Waiter::ChannelAnswer { + kind, + callback_id, + callback_token, + .. + } => self.ack_chat( + bot, + kind, + &callback_id, + &callback_token, + "The bot stopped before answering.", + ), Waiter::Open(_) | Waiter::Connectors | Waiter::Decision @@ -7843,12 +8318,32 @@ impl Core { } None => None, }; - // What the service runs by itself, a precheck and a watch, is kept as it is. + // What the service runs by itself (precheck, watch) or sends to a local-only channel is + // kept as it is for paired devices. if keep_precheck { r.precheck = old.and_then(|o| o.precheck.clone()); r.watch = old.and_then(|o| o.watch.clone()); + r.deliver_channel = old.and_then(|o| o.deliver_channel.clone()); + r.deliver_chat = old.and_then(|o| o.deliver_chat.clone()); } clean_routine(&mut r).map_err(invalid)?; + let deliver_changed = r.deliver_channel != old.and_then(|o| o.deliver_channel.clone()) + || r.deliver_chat != old.and_then(|o| o.deliver_chat.clone()); + if let (true, Some(kind), Some(chat)) = ( + deliver_changed, + r.deliver_channel.as_deref(), + r.deliver_chat.as_deref(), + ) { + let paired = self + .store + .chats(bot, kind) + .map_err(internal)? + .iter() + .any(|(known, _)| known == chat); + if !paired { + return Err(invalid(format!("`{chat}` is not a paired {kind} chat"))); + } + } if let Some(after) = &r.after && self.store.bot(&after.bot).map_err(internal)?.is_none() { @@ -9239,6 +9734,20 @@ pub fn clean_routine(r: &mut Routine) -> Result<(), String> { if r.precheck.as_ref().is_some_and(|c| c.chars().count() > 500) { return Err("`precheck` must be at most 500 characters".into()); } + r.deliver_channel = r.deliver_channel.take().map(|c| c.trim().to_owned()); + r.deliver_channel.take_if(|c| c.is_empty()); + r.deliver_chat = r.deliver_chat.take().map(|c| c.trim().to_owned()); + r.deliver_chat.take_if(|c| c.is_empty()); + match (&r.deliver_channel, &r.deliver_chat) { + (None, None) => {} + (Some(ch), Some(_)) if channels::KINDS.contains(&ch.as_str()) => {} + (Some(_), Some(_)) => { + return Err("`deliverChannel` must be `telegram` or `discord`".into()); + } + _ => { + return Err("`deliverChannel` and `deliverChat` must both be set".into()); + } + } if let Some(w) = &mut r.watch { clean_watch(w)?; if r.schedule.is_some() || r.after.is_some() { diff --git a/appd/src/lan.rs b/appd/src/lan.rs index 3f274e2..7f5962d 100644 --- a/appd/src/lan.rs +++ b/appd/src/lan.rs @@ -636,12 +636,12 @@ fn send(s: &Session, body: &[u8]) -> Answer { let mut frame = serde_json::from_slice::(body).ok(); if let Some(f) = &frame && let Some(cmd) = f.get("type").and_then(Value::as_str) - // A routine's precheck is a command that runs on this computer, and its watch calls a - // connector by itself: only the person at its own window sets them, so a device may not - // add, change or clear one. + // A routine's precheck is a command that runs on this computer, its watch calls a + // connector by itself, and its delivery chat sends replies to a local-only channel: only + // the person at its own window sets them, so a device may not add, change or clear one. && (!ALLOWED_OVER_LAN.contains(&cmd) || cmd == "set_routine" - && ["precheck", "watch"] + && ["precheck", "watch", "deliverChannel", "deliverChat"] .iter() .any(|k| f.pointer(&format!("/routine/{k}")).is_some()) // The person at the window decides whether answers are checked: a device cannot turn it off. diff --git a/appd/tests/service.rs b/appd/tests/service.rs index bda588d..2da7236 100644 --- a/appd/tests/service.rs +++ b/appd/tests/service.rs @@ -188,6 +188,9 @@ while IFS= read -r line; do set -- $(printf '%s' "$line" | sed 's/.*"text":"secret \([^"]*\)".*/\1/') echo "$ok"; echo "{\"type\":\"turn_start\",\"nonce\":\"$nonce\"}" echo "{\"type\":\"question\",\"question\":\"s-$nonce\",\"title\":\"Sign in\",\"options\":[\"Deny\"],\"secret\":{\"name\":\"$1\",\"site\":\"$2\"}}" ;; + *'"text":"ask_hidden"'*) + echo "$ok"; echo "{\"type\":\"turn_start\",\"nonce\":\"$nonce\"}" + printf '{"type":"question","question":"q-hid","title":"Run rm\u200b -rf\u202ex","options":["Approve","Deny"]}\n' ;; *'"text":"ask"'*) echo "$ok"; echo "{\"type\":\"turn_start\",\"nonce\":\"$nonce\"}" echo '{"type":"question","question":"q1","title":"Write file?","options":["Approve","Deny"]}' ;; @@ -8302,10 +8305,17 @@ fn provider_configuration_and_models_listing() { /// Telegram's part: the Bot API for the bot with `TOKEN`. `say` is a person writing to the /// bot; `sent` is what the bot was made to send, as `(chat, text)`. +type TelegramFiles = + std::sync::Arc)>>>; + struct Telegram { base: String, updates: std::sync::Arc>>, sent: std::sync::Arc>>, + sent_raw: std::sync::Arc>>, + typing: std::sync::Arc>>, + callbacks_answered: std::sync::Arc>>, + files: TelegramFiles, /// The id of the next update. next: std::sync::atomic::AtomicI64, } @@ -8317,11 +8327,25 @@ impl Telegram { use std::sync::{Arc, Mutex}; let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); let base = format!("http://{}", listener.local_addr().unwrap()); - let (updates, sent) = ( + let (updates, sent, sent_raw, typing, callbacks_answered, files) = ( Arc::new(Mutex::new(Vec::::new())), Arc::new(Mutex::new(Vec::new())), + Arc::new(Mutex::new(Vec::new())), + Arc::new(Mutex::new(Vec::new())), + Arc::new(Mutex::new(Vec::new())), + Arc::new(Mutex::new(std::collections::HashMap::< + String, + (String, Vec), + >::new())), + ); + let (queue, log, log_raw, typing_log, cb_log, file_map) = ( + updates.clone(), + sent.clone(), + sent_raw.clone(), + typing.clone(), + callbacks_answered.clone(), + files.clone(), ); - let (queue, log) = (updates.clone(), sent.clone()); std::thread::spawn(move || { for mut stream in listener.incoming().flatten() { let mut reader = BufReader::new(stream.try_clone().unwrap()); @@ -8341,6 +8365,28 @@ impl Telegram { reader.read_exact(&mut body).unwrap(); let target = first.split(' ').nth(1).unwrap_or(""); let (path, query) = target.split_once('?').unwrap_or((target, "")); + if let Some(rel) = path.strip_prefix(&format!("/file/bot{}/", Telegram::TOKEN)) { + let found = file_map + .lock() + .unwrap() + .values() + .find(|(p, _)| p == rel) + .map(|(_, bytes)| bytes.clone()); + if let Some(bytes) = found { + let head = format!( + "HTTP/1.1 200 OK\r\ncontent-type: application/octet-stream\r\ncontent-length: {}\r\nconnection: close\r\n\r\n", + bytes.len() + ); + let _ = stream.write_all(head.as_bytes()); + let _ = stream.write_all(&bytes); + } else { + let _ = write!( + stream, + "HTTP/1.1 404 -\r\ncontent-length: 0\r\nconnection: close\r\n\r\n" + ); + } + continue; + } let method = path.strip_prefix(&format!("/bot{}/", Telegram::TOKEN)); if path == "/bot9:garbled/getUpdates" { let _ = write!( @@ -8380,8 +8426,42 @@ impl Telegram { log.lock() .unwrap() .push((message["chat_id"].as_i64().unwrap(), text)); + log_raw.lock().unwrap().push(message); (200, json!({"ok": true, "result": {}})) } + Some("sendChatAction") => { + let payload: Value = serde_json::from_slice(&body).unwrap(); + if payload["action"] == "typing" + && let Some(chat) = payload["chat_id"].as_i64() + { + typing_log.lock().unwrap().push(chat); + } + (200, json!({"ok": true, "result": true})) + } + Some("answerCallbackQuery") => { + let payload: Value = serde_json::from_slice(&body).unwrap(); + cb_log.lock().unwrap().push(( + payload["callback_query_id"] + .as_str() + .unwrap_or("") + .to_owned(), + payload["text"].as_str().unwrap_or("").to_owned(), + )); + (200, json!({"ok": true, "result": true})) + } + Some("getFile") => { + let file_id = query + .split('&') + .find_map(|pair| pair.strip_prefix("file_id=")) + .unwrap_or(""); + match file_map.lock().unwrap().get(file_id) { + Some((file_path, _)) => ( + 200, + json!({"ok": true, "result": {"file_id": file_id, "file_path": file_path}}), + ), + None => (404, json!({"ok": false, "description": "file not found"})), + } + } _ => (401, json!({"ok": false, "description": "Unauthorized"})), }; let answer = answer.to_string(); @@ -8396,10 +8476,38 @@ impl Telegram { base, updates, sent, + sent_raw, + typing, + callbacks_answered, + files, next: std::sync::atomic::AtomicI64::new(1000), } } + fn callback(&self, chat: i64, callback_id: &str, data: &str) { + let id = self.next.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let update = json!({ + "update_id": id, + "callback_query": { + "id": callback_id, + "from": {"id": chat, "is_bot": false, "first_name": format!("Person {chat}")}, + "message": { + "message_id": id, + "chat": {"id": chat, "type": "private"}, + }, + "data": data, + } + }); + self.updates.lock().unwrap().push(update); + } + + fn add_file(&self, file_id: &str, file_path: &str, bytes: Vec) { + self.files + .lock() + .unwrap() + .insert(file_id.to_owned(), (file_path.to_owned(), bytes)); + } + fn say(&self, chat: i64, text: &str) { self.message(chat, json!({"text": text}), 0); } @@ -8522,12 +8630,12 @@ fn a_bot_is_messaged_from_telegram_once_the_sender_has_paired_with_a_code() { !history.contains("hello?") && !history.contains(&code), "{history}" ); - // Only text is read, and the chat is told so. - telegram.message(7, json!({"photo": [{"file_id": "p1"}]}), 0); + // Messages with neither text nor supported attachments are answered plainly. + telegram.message(7, json!({"sticker": {"file_id": "s1"}}), 0); assert!(telegram.heard(7, 4).contains("text")); - // A turn that waits for the user says so in the chat. + // A turn that waits for the user sends an inline approval card in the chat. telegram.say(7, "ask"); - assert!(telegram.heard(7, 5).contains("Bate")); + assert!(telegram.heard(7, 5).contains("Needs you")); // The bot is busy with that turn: a second message is not queued behind it. telegram.say(7, "and another"); assert!(telegram.heard(7, 6).contains("busy")); @@ -8656,15 +8764,21 @@ impl Discord { let message = target .strip_prefix("POST /channels/") .and_then(|rest| rest.strip_suffix("/messages")); - let (status, answer) = match (allowed && named, target.as_str(), message) { - (false, _, _) => (401, json!({"message": "401: Unauthorized", "code": 0})), - (_, "GET /gateway/bot", _) => (200, json!({"url": gateway_url, "shards": 1})), - (_, _, Some(channel)) => { + let typing = target + .strip_prefix("POST /channels/") + .and_then(|rest| rest.strip_suffix("/typing")); + let (status, answer) = match (allowed && named, target.as_str(), message, typing) { + (false, _, _, _) => (401, json!({"message": "401: Unauthorized", "code": 0})), + (_, "GET /gateway/bot", _, _) => { + (200, json!({"url": gateway_url, "shards": 1})) + } + (_, _, Some(channel), _) => { let message: Value = serde_json::from_slice(&body).unwrap(); let text = message["content"].as_str().unwrap().to_owned(); log.lock().unwrap().push((channel.to_owned(), text)); (200, json!({"id": "1"})) } + (_, _, _, Some(_)) => (200, json!({})), _ => (404, json!({"message": "404: Not Found", "code": 0})), }; let answer = answer.to_string(); @@ -19678,3 +19792,271 @@ fn pwa_manifest_qr_pairing_and_web_push_subscription_lifecycle() { "removing device clears push subs: {saved:?}" ); } + +#[test] +fn channel_upgrades_routine_delivery_inline_approvals_typing_and_attachments() { + use std::os::unix::fs::PermissionsExt; + + let (home, telegram) = (home("channel-upgrades"), Telegram::start()); + // Offline mock speech transcriber script (local-only, zero network). + let transcriber = home.join("fake-transcribe.sh"); + fs::write(&transcriber, "#!/bin/sh\necho \"remind me at noon\"\n").unwrap(); + fs::set_permissions(&transcriber, fs::Permissions::from_mode(0o700)).unwrap(); + + let _service = Service::start_with(&home, |c| { + c.env("APPD_ENGINE", home.join("fake-engine")) + .env("BATE_TELEGRAM_API", &telegram.base) + .env("BATE_TRANSCRIBE_CMD", &transcriber) + .env("APPD_LAN_PORT", "0"); + }); + let mut w = Window::connect(&home); + let bot = w.create_bot(); + + // Configure Telegram token and pair chat 7. + w.ok( + "set_channel", + json!({"bot": bot, "kind": "telegram", "token": Telegram::TOKEN}), + ); + let code = w.ok("pair_channel", json!({"bot": bot, "kind": "telegram"}))["code"] + .as_str() + .unwrap() + .to_owned(); + telegram.say(7, &code); + assert!(telegram.heard(7, 1).contains("Paired")); + + // 1. Routine -> Channel delivery: rejects unpaired chat, accepts paired chat, posts final reply. + let bad_req = w.send( + "set_routine", + json!({ + "bot": bot, + "routine": { + "name": "Digest", + "prompt": "summarize", + "enabled": true, + "webhook": true, + "chat": false, + "deliverChannel": "telegram", + "deliverChat": "999", + } + }), + ); + let refused = w.wait_for(|f| f["type"] == "response" && f["id"] == bad_req); + assert_eq!(refused["code"], "invalid_routine", "{refused}"); + + let created = w.ok( + "set_routine", + json!({ + "bot": bot, + "routine": { + "name": "Digest", + "prompt": "summarize", + "enabled": true, + "webhook": true, + "chat": false, + "deliverChannel": "telegram", + "deliverChat": "7", + } + }), + ); + let routine_id = created["routine"]["id"].as_str().unwrap().to_owned(); + assert_eq!(created["routine"]["deliverChannel"], "telegram"); + assert_eq!(created["routine"]["deliverChat"], "7"); + + // A paired LAN device cannot add, change, or clear deliverChannel/deliverChat. + 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})); + let lan_refused = send_lan( + &device, + json!({ + "id": "r-lan", + "type": "set_routine", + "bot": bot, + "routine": { + "id": routine_id, + "name": "Digest", + "prompt": "summarize", + "enabled": true, + "webhook": true, + "chat": false, + "deliverChannel": null, + "deliverChat": null, + } + }), + ); + assert_eq!(lan_refused["code"], "forbidden", "{lan_refused}"); + + // Running the routine posts its final reply ("hello") to Telegram chat 7. + w.ok("run_routine", json!({"bot": bot, "routineId": routine_id})); + assert_eq!(telegram.heard(7, 2), "hello"); + + // 2. Inline approval card (Allow once / Deny only, hidden chars marked) + typing indicator. + telegram.say(7, "ask_hidden"); + let card_text = telegram.heard(7, 3); + assert!(card_text.contains("[U+200B]"), "{card_text}"); + assert!(card_text.contains("[U+202E]"), "{card_text}"); + assert!(card_text.contains("brackets"), "{card_text}"); + let card_raw = telegram.sent_raw.lock().unwrap().last().unwrap().clone(); + let buttons = card_raw["reply_markup"]["inline_keyboard"][0] + .as_array() + .unwrap(); + assert_eq!(buttons.len(), 2, "{card_raw}"); + assert_eq!(buttons[0]["text"], "Allow once"); + assert_eq!(buttons[0]["callback_data"], "approve:q-hid"); + assert_eq!(buttons[1]["text"], "Deny"); + assert_eq!(buttons[1]["callback_data"], "deny:q-hid"); + assert!(!card_raw.to_string().contains("Always"), "{card_raw}"); + eventually("typing indicator sent", || { + telegram.typing.lock().unwrap().contains(&7) + }); + + // Tapping Allow once answers the question via callback query and completes the turn. + telegram.callback(7, "cb-1", "approve:q-hid"); + assert_eq!(telegram.heard(7, 4), "chose Approve"); + eventually("callback acknowledged", || { + telegram + .callbacks_answered + .lock() + .unwrap() + .iter() + .any(|(id, text)| id == "cb-1" && text.contains("Allowed")) + }); + + // Tapping Deny rejects the action cleanly. + telegram.say(7, "ask"); + let _ = telegram.heard(7, 5); + telegram.callback(7, "cb-2", "deny:q1"); + assert_eq!(telegram.heard(7, 6), "chose Deny"); + eventually("deny callback acknowledged", || { + telegram + .callbacks_answered + .lock() + .unwrap() + .iter() + .any(|(id, text)| id == "cb-2" && text.contains("Denied")) + }); + + // 3. Secret prompt is NEVER sent as an approval card and NEVER includes secret details. + telegram.say(7, "secret github github.com"); + let secret_notice = telegram.heard(7, 7); + assert!( + secret_notice.contains("secret in Bate on your Mac"), + "{secret_notice}" + ); + assert!(!secret_notice.contains("github"), "{secret_notice}"); + let secret_raw = telegram.sent_raw.lock().unwrap().last().unwrap().clone(); + assert!( + secret_raw.get("reply_markup").is_none(), + "secret prompt must never have inline buttons: {secret_raw}" + ); + // Forged callback against the open secret question is refused and leaves the question open. + let open_secret_q = w.ok("open_bot", json!({"bot": bot}))["questions"][0]["question"] + .as_str() + .unwrap() + .to_owned(); + telegram.callback(7, "cb-secret", &format!("approve:{open_secret_q}")); + eventually("forged secret callback refused", || { + telegram + .callbacks_answered + .lock() + .unwrap() + .iter() + .any(|(id, text)| id == "cb-secret" && text.contains("Secrets can only")) + }); + // Deny the open secret question in the window so the bot is free for attachments. + w.ok( + "answer", + json!({"bot": bot, "question": open_secret_q, "choice": "Deny"}), + ); + assert_eq!(telegram.heard(7, 8), "chose Deny"); + + // 4. Bounded inbound attachments & local offline voice note transcription. + telegram.add_file("doc-1", "docs/report.txt", b"quarterly numbers".to_vec()); + telegram.message( + 7, + json!({ + "caption": "read this", + "document": {"file_id": "doc-1", "file_name": "../report.txt", "file_size": 17} + }), + 0, + ); + assert_eq!(telegram.heard(7, 9), "hello"); + let inbox = home.join("bots").join(&bot).join("inbox"); + let entries: Vec<_> = fs::read_dir(&inbox) + .unwrap() + .filter_map(Result::ok) + .collect(); + assert_eq!(entries.len(), 1, "saved sanitized document in inbox"); + assert!( + entries[0] + .file_name() + .to_string_lossy() + .ends_with("-report.txt"), + "{:?}", + entries[0].file_name() + ); + assert_eq!(fs::read(entries[0].path()).unwrap(), b"quarterly numbers"); + + // Voice note is transcribed locally via BATE_TRANSCRIBE_CMD. + telegram.add_file("voice-1", "voice/v1.ogg", b"OggS-fake".to_vec()); + telegram.message( + 7, + json!({"voice": {"file_id": "voice-1", "file_size": 9}}), + 0, + ); + assert_eq!(telegram.heard(7, 10), "hello"); + let history = w.ok("open_bot", json!({"bot": bot}))["history"].to_string(); + assert!( + history.contains("remind me at noon"), + "offline transcript missing from history: {history}" + ); + + // Oversized attachment (> 10 MiB) is rejected without downloading. + telegram.message( + 7, + json!({ + "document": { + "file_id": "too-big", + "file_name": "huge.bin", + "file_size": 11 * 1024 * 1024 + } + }), + 0, + ); + let skipped = telegram.heard(7, 11); + assert!(skipped.contains("over 10 MB"), "{skipped}"); +} diff --git a/native/src/reveal.rs b/native/src/reveal.rs index 43b2cc6..4d35e78 100644 --- a/native/src/reveal.rs +++ b/native/src/reveal.rs @@ -1,185 +1,4 @@ -//! Text that gets a person's yes, with every character they cannot see put in plain view. A piece -//! is either plain text or one character shown as its code point (`U+200B`), with what kind of -//! character it is. Only the display changes: what runs is the text the service has, as it is. -//! The page's rule is `window/ui/src/reveal.ts`. -//! -//! Not handled: a letter that only looks like another (a Cyrillic "а" for a Latin "a") is an -//! ordinary, visible character and is shown as it is. A grant is for the exact text, so a -//! lookalike never matches a command or path that was allowed before. +//! Text that gets a person's yes, with every character they cannot see put in plain view. +//! Shared implementation lives in `proto::reveal`; the page's rule is `window/ui/src/reveal.ts`. -/// What a piece of the text is. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum Piece { - Plain(String), - /// A character nobody can see, as `U+XXXX`, with the kind of character it is. - Hidden { - code: String, - kind: &'static str, - }, -} - -/// Each kind of character that is marked, by the ranges it covers (newline and tab are not among them). -const KINDS: [(&str, &[(u32, u32)]); 6] = [ - ( - "control character", - &[(0x0000, 0x0008), (0x000B, 0x001F), (0x007F, 0x009F)], - ), - ( - "zero-width or joining character", - &[ - (0x034F, 0x034F), - (0x180B, 0x180E), - (0x200B, 0x200D), - (0x2060, 0x2064), - (0xFE00, 0xFE0F), - (0xFEFF, 0xFEFF), - (0xE0100, 0xE01EF), - ], - ), - ( - "character that changes the reading order", - &[ - (0x061C, 0x061C), - (0x200E, 0x200F), - (0x202A, 0x202E), - (0x2066, 0x2069), - ], - ), - ( - "space that is not an ordinary space", - &[ - (0x00A0, 0x00A0), - (0x1680, 0x1680), - (0x2000, 0x200A), - (0x2028, 0x2029), - (0x202F, 0x202F), - (0x205F, 0x205F), - (0x3000, 0x3000), - (0x2800, 0x2800), - ], - ), - ( - "blank letter or soft hyphen", - &[ - (0x00AD, 0x00AD), - (0x115F, 0x1160), - (0x17B4, 0x17B5), - (0x3164, 0x3164), - (0xFFA0, 0xFFA0), - (0x2065, 0x2065), - (0x206A, 0x206F), - (0xFFF9, 0xFFFC), - ], - ), - ("tag character", &[(0xE0000, 0xE007F)]), -]; - -fn kind_of(c: char) -> Option<&'static str> { - let c = c as u32; - KINDS - .iter() - .find(|(_, ranges)| ranges.iter().any(|&(lo, hi)| (lo..=hi).contains(&c))) - .map(|(name, _)| *name) -} - -/// `text` as pieces; the pieces that are not marked, put together, are the text without them. -pub fn reveal(text: &str) -> Vec { - let mut pieces = Vec::new(); - let mut plain = String::new(); - for c in text.chars() { - match kind_of(c) { - None => plain.push(c), - Some(kind) => { - if !plain.is_empty() { - pieces.push(Piece::Plain(std::mem::take(&mut plain))); - } - pieces.push(Piece::Hidden { - code: format!("U+{:04X}", c as u32), - kind, - }); - } - } - } - if !plain.is_empty() { - pieces.push(Piece::Plain(plain)); - } - pieces -} - -/// Whether any of `texts` holds a character that is marked. -pub fn has_hidden<'a>(texts: impl IntoIterator) -> bool { - texts - .into_iter() - .any(|t| t.chars().any(|c| kind_of(c).is_some())) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn plain_text_is_one_piece() { - assert_eq!( - reveal("ls -la\n\tdone"), - [Piece::Plain("ls -la\n\tdone".into())] - ); - assert!(reveal("").is_empty()); - assert!(!has_hidden(["ls -la", "café 日本語"])); - } - - #[test] - fn a_character_nobody_can_see_is_shown_as_its_code_point_with_its_kind() { - let pieces = reveal("rm\u{200B} -rf\u{202E}x\u{00A0}y"); - assert_eq!( - pieces, - [ - Piece::Plain("rm".into()), - Piece::Hidden { - code: "U+200B".into(), - kind: "zero-width or joining character" - }, - Piece::Plain(" -rf".into()), - Piece::Hidden { - code: "U+202E".into(), - kind: "character that changes the reading order" - }, - Piece::Plain("x".into()), - Piece::Hidden { - code: "U+00A0".into(), - kind: "space that is not an ordinary space" - }, - Piece::Plain("y".into()), - ] - ); - assert!(has_hidden(["fine", "a\u{200B}b"])); - } - - #[test] - fn the_pieces_that_are_not_marked_are_the_text_without_the_marked() { - let text = "a\u{0007}b\u{E0041}c\u{FEFF}d\u{00AD}e"; - let plain: String = reveal(text) - .into_iter() - .filter_map(|p| match p { - Piece::Plain(s) => Some(s), - Piece::Hidden { .. } => None, - }) - .collect(); - assert_eq!(plain, "abcde"); - let kinds: Vec<_> = reveal(text) - .into_iter() - .filter_map(|p| match p { - Piece::Hidden { kind, .. } => Some(kind), - Piece::Plain(_) => None, - }) - .collect(); - assert_eq!( - kinds, - [ - "control character", - "tag character", - "zero-width or joining character", - "blank letter or soft hyphen" - ] - ); - } -} +pub use proto::reveal::{Piece, has_hidden, mark_plain, reveal}; diff --git a/native/src/routines.rs b/native/src/routines.rs index 939be85..687c3a0 100644 --- a/native/src/routines.rs +++ b/native/src/routines.rs @@ -66,6 +66,8 @@ pub struct Dialog { after_bot: String, after_outcome: String, connector: String, + /// `""` or `":"` for optional Routine → Channel delivery. + deliver: String, /// Why the last try was not sent: the person's own mistake, said before the service is asked. error: String, /// The save is on its way: the dialog closes when it went. @@ -345,6 +347,8 @@ pub struct Routine { pub chat: bool, pub precheck: Option, pub watch: Option, + pub deliver_channel: Option, + pub deliver_chat: Option, pub hook_url: Option, pub next_run_ms: Option, pub last_run: Option, @@ -382,6 +386,43 @@ fn connectors_of(app: &App, bot: &str) -> Vec { .unwrap_or_default() } +fn channel_label(kind: &str) -> &str { + match kind { + "telegram" => "Telegram", + "discord" => "Discord", + other => other, + } +} + +fn paired_chats_of(app: &App, bot: &str) -> Vec<(String, String)> { + let mut out = Vec::new(); + let Some(channels) = app + .state + .pages + .get(&key(bot, "channels")) + .and_then(|v| v["channels"].as_array()) + else { + return out; + }; + for ch in channels { + let Some(kind) = ch["kind"].as_str() else { + continue; + }; + let label = channel_label(kind); + for item in ch["chats"].as_array().into_iter().flatten() { + let Some(chat) = item["chat"].as_str() else { + continue; + }; + let name = item["name"] + .as_str() + .filter(|n| !n.trim().is_empty()) + .unwrap_or(chat); + out.push((format!("{kind}:{chat}"), format!("{label}: {name}"))); + } + } + out +} + // ---- Changes ---- /// A change the page makes at once. `done`: it says "Saved" when it went (the switch). @@ -458,6 +499,10 @@ fn open_dialog(app: &mut App, edit: Option) { .watch .as_ref() .map_or(String::new(), |w| w.connector.clone()), + deliver: match (&r.deliver_channel, &r.deliver_chat) { + (Some(ch), Some(chat)) => format!("{ch}:{chat}"), + _ => String::new(), + }, edit, error: String::new(), saving: false, @@ -475,6 +520,12 @@ fn open_dialog(app: &mut App, edit: Option) { json!({"bot": bot}), &["permissions_changed"], )); + app.watch(Resource::new( + key(&bot, "channels"), + "get_channels", + json!({"bot": bot}), + &["channels_changed"], + )); } fn close_dialog(app: &mut App) { @@ -542,6 +593,16 @@ fn routine_of(app: &App, d: &Dialog) -> Result { } else { r.insert("precheck".into(), json!(precheck)); } + if let Some((ch, chat)) = d.deliver.split_once(':') + && !ch.is_empty() + && !chat.is_empty() + { + r.insert("deliverChannel".into(), json!(ch)); + r.insert("deliverChat".into(), json!(chat)); + } else { + r.remove("deliverChannel"); + r.remove("deliverChat"); + } if d.scheduled { let mut schedule = r .get("schedule") @@ -882,6 +943,12 @@ fn row_of(app: &App, k: &Tokens, cx: &Cx, bot: &Bot, r: &Routine) -> V { &format!("From a paired chat: write /run {}", r.name), )); } + if let (Some(ch), Some(chat)) = (&r.deliver_channel, &r.deliver_chat) { + lines.push(addons::small( + k, + &format!("Sends reply to {} ({chat})", channel_label(ch)), + )); + } if let Some(url) = &r.hook_url { lines.push(code_line(k, "Web address: ", url)); } @@ -1465,6 +1532,39 @@ fn dialog(app: &App, cx: &Cx, k: &Tokens, bot: &Bot, d: &Dialog) -> V { "Runs before each run, without a model, in the bot's folder and under its limits. If it ends with 0, the bot runs and gets what it printed; any other end skips the run. Saving allows exactly this command for this routine, without asking again.", )); } + let paired = paired_chats_of(app, &bot.id); + if !paired.is_empty() || !d.deliver.is_empty() { + let mut owned: Vec<(String, String)> = + vec![(String::new(), "Nowhere (Bate only)".to_owned())]; + owned.extend(paired); + if !d.deliver.is_empty() && !owned.iter().any(|(v, _)| v == &d.deliver) { + owned.push((d.deliver.clone(), d.deliver.clone())); + } + let choices: Vec<(&str, &str)> = owned + .iter() + .map(|(v, l)| (v.as_str(), l.as_str())) + .collect(); + flow.push( + SPACE_3, + SPACE_3, + labelled( + k, + "Send final reply to", + forms::select( + app, + cx, + &field_key("deliver"), + "Nowhere (Bate only)", + &choices, + &d.deliver, + |app, v| { + let v = v.to_owned(); + edit(app, |d| d.deliver = v) + }, + ), + ), + ); + } let error = if d.error.is_empty() { app.state .pages diff --git a/native/tests/botpages.rs b/native/tests/botpages.rs index f0a976d..520f0fb 100644 --- a/native/tests/botpages.rs +++ b/native/tests/botpages.rs @@ -500,6 +500,26 @@ fn a_new_routine_needs_a_name_and_a_prompt_and_add_sends_it_without_an_id() { assert!(has_key(&mut w.rt, "routine-r-made-4")); } +#[test] +fn routine_delivery_selects_a_paired_channel_chat_and_sends_it() { + let mut w = routines(); + press(&mut w, "routines-new"); + quiet(&mut w); + type_into(&mut w, "routines:dialog:name", "Phone brief"); + type_into(&mut w, "routines:dialog:prompt", "Send a summary."); + assert_eq!( + chosen(&mut w.rt, "routines:dialog:deliver"), + "Nowhere (Bate only)" + ); + choose(&mut w, "routines:dialog:deliver", "Telegram: Sam's phone"); + press(&mut w, "routines-go"); + quiet(&mut w); + let sent = last(&w, "set_routine"); + assert_eq!(sent["routine"]["deliverChannel"], "telegram"); + assert_eq!(sent["routine"]["deliverChat"], "1001"); + assert!(said(&mut w, "Sends reply to Telegram (1001)")); +} + #[test] fn cancel_and_escape_close_the_dialog_and_send_nothing() { let mut w = routines(); diff --git a/native/tests/snapshots/native-botpages-routine-dialog-dark.png b/native/tests/snapshots/native-botpages-routine-dialog-dark.png index c12373c..e227507 100644 Binary files a/native/tests/snapshots/native-botpages-routine-dialog-dark.png and b/native/tests/snapshots/native-botpages-routine-dialog-dark.png differ diff --git a/native/tests/snapshots/native-botpages-routine-dialog-dark.tree b/native/tests/snapshots/native-botpages-routine-dialog-dark.tree index a7371b0..c508db7 100644 --- a/native/tests/snapshots/native-botpages-routine-dialog-dark.tree +++ b/native/tests/snapshots/native-botpages-routine-dialog-dark.tree @@ -253,67 +253,73 @@ generic @0,0,900,760 generic @288,660,580,8 generic @892,8,8,744 generic #routines-dialog-scrim @0,0,900,760 ovl - dialog #routines-dialog @90,40.5,720,679 lb="New routine" - generic #routines-dialog-body @90,40.5,720,625 sc=0,0,0,0 end - generic @114,40.5,672,625 - generic @114,40.5,672,24 - heading @114,64.5,672,18 t="New routine" - generic @114,82.5,672,12 - generic @114,94.5,672,52 - text @114,94.5,672,18 t="Name" - textbox #routines:dialog:name @114,116.5,672,30 lb="Name" v="Weekly tidy" sel=[11,11] caret=11 tab sc=0,0,0,0 end - generic @114,146.5,672,12 - generic @114,158.5,672,110 - text @114,158.5,672,18 t="Prompt" - textbox #routines:dialog:prompt @114,180.5,672,88 lb="Prompt" v="Tidy the notes and say what changed." sel=[36,36] caret=36 multi foc tab sc=0,0,0,0 end - generic @114,268.5,672,12 - heading @114,280.5,672,18 t="What starts it" - generic @114,298.5,672,12 - checkbox #routines-scheduled @114,310.5,672,19 lb="A schedule" ck tab - generic @114,310.5,20,19 - generic @118,313.5,13,13 - image @119,314.5,11,11 deco - text @142,311,67.09,18 t="A schedule" - generic @114,329.5,672,12 - generic @114,341.5,672,60 - text @114,341.5,672,18 t="Every" - generic @114,363.5,672,38 - textbox #routines:dialog:interval @114,367.5,552,30 lb="Every" v="1" sel=[1,1] caret=1 tab sc=0,0,0,0 end - combobox #routines:dialog:unit @674,367.5,112,30 lb="days" tab - text @686,373.5,72,18 t="days" - image @762,376.5,12,12 deco - generic @114,401.5,672,12 - generic @114,413.5,672,52 - text @114,413.5,672,18 t="From" - textbox #routines:dialog:time @114,435.5,672,30 lb="From" v="09:00" ph="09:00" sel=[5,5] caret=5 tab sc=0,0,0,0 end - generic @114,465.5,672,12 - checkbox #routines-after @114,477.5,672,19 lb="After another bot" ck=false tab - generic @114,477.5,20,19 - generic @118,480.5,13,13 - text @142,478,103.87,18 t="After another bot" - generic @114,496.5,672,12 - checkbox #routines-webhook @114,508.5,672,19 lb="A web address" ck=false tab - generic @114,508.5,20,19 - generic @118,511.5,13,13 - text @142,509,89.12,18 t="A web address" - generic @114,527.5,672,12 - checkbox #routines-chat @114,539.5,672,19 lb="A paired chat (Telegram, Discord), by writing /run and its name" ck=false tab - generic @114,539.5,20,19 - generic @118,542.5,13,13 - text @142,540,378.51,18 t="A paired chat (Telegram, Discord), by writing /run and its name" - generic @114,558.5,672,12 - checkbox #routines-watching @114,570.5,672,19 lb="A change in a connected app" ck=false tab - generic @114,570.5,20,19 - generic @118,573.5,13,13 - text @142,571,176.02,18 t="A change in a connected app" - generic @114,589.5,672,12 - generic @114,601.5,672,52 - text @114,601.5,672,18 t="Check first, with a command" - textbox #routines:dialog:precheck @114,623.5,672,30 lb="Check first, with a command" v="" tab sc=0,0,0,0 end - generic @114,653.5,672,12 - generic @90,665.5,720,54 - generic @114,673.5,123.33,30 - button #routines-go @114,673.5,48.75,30 lb="Add" tab - text @126,679.5,24.75,18 t="Add" - button #routines-cancel @170.75,673.5,66.58,30 lb="Cancel" tab - text @182.75,679.5,42.58,18 t="Cancel" + dialog #routines-dialog @90,16,720,728 lb="New routine" + generic #routines-dialog-body @90,16,720,674 sc=0,0,0,15 + generic @114,16,672,689 + generic @114,16,672,24 + heading @114,40,672,18 t="New routine" + generic @114,58,672,12 + generic @114,70,672,52 + text @114,70,672,18 t="Name" + textbox #routines:dialog:name @114,92,672,30 lb="Name" v="Weekly tidy" sel=[11,11] caret=11 tab sc=0,0,0,0 end + generic @114,122,672,12 + generic @114,134,672,110 + text @114,134,672,18 t="Prompt" + textbox #routines:dialog:prompt @114,156,672,88 lb="Prompt" v="Tidy the notes and say what changed." sel=[36,36] caret=36 multi foc tab sc=0,0,0,0 end + generic @114,244,672,12 + heading @114,256,672,18 t="What starts it" + generic @114,274,672,12 + checkbox #routines-scheduled @114,286,672,19 lb="A schedule" ck tab + generic @114,286,20,19 + generic @118,289,13,13 + image @119,290,11,11 deco + text @142,286.5,67.09,18 t="A schedule" + generic @114,305,672,12 + generic @114,317,672,60 + text @114,317,672,18 t="Every" + generic @114,339,672,38 + textbox #routines:dialog:interval @114,343,552,30 lb="Every" v="1" sel=[1,1] caret=1 tab sc=0,0,0,0 end + combobox #routines:dialog:unit @674,343,112,30 lb="days" tab + text @686,349,72,18 t="days" + image @762,352,12,12 deco + generic @114,377,672,12 + generic @114,389,672,52 + text @114,389,672,18 t="From" + textbox #routines:dialog:time @114,411,672,30 lb="From" v="09:00" ph="09:00" sel=[5,5] caret=5 tab sc=0,0,0,0 end + generic @114,441,672,12 + checkbox #routines-after @114,453,672,19 lb="After another bot" ck=false tab + generic @114,453,20,19 + generic @118,456,13,13 + text @142,453.5,103.87,18 t="After another bot" + generic @114,472,672,12 + checkbox #routines-webhook @114,484,672,19 lb="A web address" ck=false tab + generic @114,484,20,19 + generic @118,487,13,13 + text @142,484.5,89.12,18 t="A web address" + generic @114,503,672,12 + checkbox #routines-chat @114,515,672,19 lb="A paired chat (Telegram, Discord), by writing /run and its name" ck=false tab + generic @114,515,20,19 + generic @118,518,13,13 + text @142,515.5,378.51,18 t="A paired chat (Telegram, Discord), by writing /run and its name" + generic @114,534,672,12 + checkbox #routines-watching @114,546,672,19 lb="A change in a connected app" ck=false tab + generic @114,546,20,19 + generic @118,549,13,13 + text @142,546.5,176.02,18 t="A change in a connected app" + generic @114,565,672,12 + generic @114,577,672,52 + text @114,577,672,18 t="Check first, with a command" + textbox #routines:dialog:precheck @114,599,672,30 lb="Check first, with a command" v="" tab sc=0,0,0,0 end + generic @114,629,672,12 + generic @114,641,672,52 + text @114,641,672,18 t="Send final reply to" + combobox #routines:dialog:deliver @114,663,672,30 lb="Nowhere (Bate only)" tab + text @126,669,632,18 t="Nowhere (Bate only)" + image @762,672,12,12 deco + generic @114,693,672,12 + generic @90,690,720,54 + generic @114,698,123.33,30 + button #routines-go @114,698,48.75,30 lb="Add" tab + text @126,704,24.75,18 t="Add" + button #routines-cancel @170.75,698,66.58,30 lb="Cancel" tab + text @182.75,704,42.58,18 t="Cancel" diff --git a/native/tests/snapshots/native-botpages-routine-dialog-light.png b/native/tests/snapshots/native-botpages-routine-dialog-light.png index f64adc8..22e5f0a 100644 Binary files a/native/tests/snapshots/native-botpages-routine-dialog-light.png and b/native/tests/snapshots/native-botpages-routine-dialog-light.png differ diff --git a/native/tests/snapshots/native-botpages-routine-dialog-light.tree b/native/tests/snapshots/native-botpages-routine-dialog-light.tree index a7371b0..c508db7 100644 --- a/native/tests/snapshots/native-botpages-routine-dialog-light.tree +++ b/native/tests/snapshots/native-botpages-routine-dialog-light.tree @@ -253,67 +253,73 @@ generic @0,0,900,760 generic @288,660,580,8 generic @892,8,8,744 generic #routines-dialog-scrim @0,0,900,760 ovl - dialog #routines-dialog @90,40.5,720,679 lb="New routine" - generic #routines-dialog-body @90,40.5,720,625 sc=0,0,0,0 end - generic @114,40.5,672,625 - generic @114,40.5,672,24 - heading @114,64.5,672,18 t="New routine" - generic @114,82.5,672,12 - generic @114,94.5,672,52 - text @114,94.5,672,18 t="Name" - textbox #routines:dialog:name @114,116.5,672,30 lb="Name" v="Weekly tidy" sel=[11,11] caret=11 tab sc=0,0,0,0 end - generic @114,146.5,672,12 - generic @114,158.5,672,110 - text @114,158.5,672,18 t="Prompt" - textbox #routines:dialog:prompt @114,180.5,672,88 lb="Prompt" v="Tidy the notes and say what changed." sel=[36,36] caret=36 multi foc tab sc=0,0,0,0 end - generic @114,268.5,672,12 - heading @114,280.5,672,18 t="What starts it" - generic @114,298.5,672,12 - checkbox #routines-scheduled @114,310.5,672,19 lb="A schedule" ck tab - generic @114,310.5,20,19 - generic @118,313.5,13,13 - image @119,314.5,11,11 deco - text @142,311,67.09,18 t="A schedule" - generic @114,329.5,672,12 - generic @114,341.5,672,60 - text @114,341.5,672,18 t="Every" - generic @114,363.5,672,38 - textbox #routines:dialog:interval @114,367.5,552,30 lb="Every" v="1" sel=[1,1] caret=1 tab sc=0,0,0,0 end - combobox #routines:dialog:unit @674,367.5,112,30 lb="days" tab - text @686,373.5,72,18 t="days" - image @762,376.5,12,12 deco - generic @114,401.5,672,12 - generic @114,413.5,672,52 - text @114,413.5,672,18 t="From" - textbox #routines:dialog:time @114,435.5,672,30 lb="From" v="09:00" ph="09:00" sel=[5,5] caret=5 tab sc=0,0,0,0 end - generic @114,465.5,672,12 - checkbox #routines-after @114,477.5,672,19 lb="After another bot" ck=false tab - generic @114,477.5,20,19 - generic @118,480.5,13,13 - text @142,478,103.87,18 t="After another bot" - generic @114,496.5,672,12 - checkbox #routines-webhook @114,508.5,672,19 lb="A web address" ck=false tab - generic @114,508.5,20,19 - generic @118,511.5,13,13 - text @142,509,89.12,18 t="A web address" - generic @114,527.5,672,12 - checkbox #routines-chat @114,539.5,672,19 lb="A paired chat (Telegram, Discord), by writing /run and its name" ck=false tab - generic @114,539.5,20,19 - generic @118,542.5,13,13 - text @142,540,378.51,18 t="A paired chat (Telegram, Discord), by writing /run and its name" - generic @114,558.5,672,12 - checkbox #routines-watching @114,570.5,672,19 lb="A change in a connected app" ck=false tab - generic @114,570.5,20,19 - generic @118,573.5,13,13 - text @142,571,176.02,18 t="A change in a connected app" - generic @114,589.5,672,12 - generic @114,601.5,672,52 - text @114,601.5,672,18 t="Check first, with a command" - textbox #routines:dialog:precheck @114,623.5,672,30 lb="Check first, with a command" v="" tab sc=0,0,0,0 end - generic @114,653.5,672,12 - generic @90,665.5,720,54 - generic @114,673.5,123.33,30 - button #routines-go @114,673.5,48.75,30 lb="Add" tab - text @126,679.5,24.75,18 t="Add" - button #routines-cancel @170.75,673.5,66.58,30 lb="Cancel" tab - text @182.75,679.5,42.58,18 t="Cancel" + dialog #routines-dialog @90,16,720,728 lb="New routine" + generic #routines-dialog-body @90,16,720,674 sc=0,0,0,15 + generic @114,16,672,689 + generic @114,16,672,24 + heading @114,40,672,18 t="New routine" + generic @114,58,672,12 + generic @114,70,672,52 + text @114,70,672,18 t="Name" + textbox #routines:dialog:name @114,92,672,30 lb="Name" v="Weekly tidy" sel=[11,11] caret=11 tab sc=0,0,0,0 end + generic @114,122,672,12 + generic @114,134,672,110 + text @114,134,672,18 t="Prompt" + textbox #routines:dialog:prompt @114,156,672,88 lb="Prompt" v="Tidy the notes and say what changed." sel=[36,36] caret=36 multi foc tab sc=0,0,0,0 end + generic @114,244,672,12 + heading @114,256,672,18 t="What starts it" + generic @114,274,672,12 + checkbox #routines-scheduled @114,286,672,19 lb="A schedule" ck tab + generic @114,286,20,19 + generic @118,289,13,13 + image @119,290,11,11 deco + text @142,286.5,67.09,18 t="A schedule" + generic @114,305,672,12 + generic @114,317,672,60 + text @114,317,672,18 t="Every" + generic @114,339,672,38 + textbox #routines:dialog:interval @114,343,552,30 lb="Every" v="1" sel=[1,1] caret=1 tab sc=0,0,0,0 end + combobox #routines:dialog:unit @674,343,112,30 lb="days" tab + text @686,349,72,18 t="days" + image @762,352,12,12 deco + generic @114,377,672,12 + generic @114,389,672,52 + text @114,389,672,18 t="From" + textbox #routines:dialog:time @114,411,672,30 lb="From" v="09:00" ph="09:00" sel=[5,5] caret=5 tab sc=0,0,0,0 end + generic @114,441,672,12 + checkbox #routines-after @114,453,672,19 lb="After another bot" ck=false tab + generic @114,453,20,19 + generic @118,456,13,13 + text @142,453.5,103.87,18 t="After another bot" + generic @114,472,672,12 + checkbox #routines-webhook @114,484,672,19 lb="A web address" ck=false tab + generic @114,484,20,19 + generic @118,487,13,13 + text @142,484.5,89.12,18 t="A web address" + generic @114,503,672,12 + checkbox #routines-chat @114,515,672,19 lb="A paired chat (Telegram, Discord), by writing /run and its name" ck=false tab + generic @114,515,20,19 + generic @118,518,13,13 + text @142,515.5,378.51,18 t="A paired chat (Telegram, Discord), by writing /run and its name" + generic @114,534,672,12 + checkbox #routines-watching @114,546,672,19 lb="A change in a connected app" ck=false tab + generic @114,546,20,19 + generic @118,549,13,13 + text @142,546.5,176.02,18 t="A change in a connected app" + generic @114,565,672,12 + generic @114,577,672,52 + text @114,577,672,18 t="Check first, with a command" + textbox #routines:dialog:precheck @114,599,672,30 lb="Check first, with a command" v="" tab sc=0,0,0,0 end + generic @114,629,672,12 + generic @114,641,672,52 + text @114,641,672,18 t="Send final reply to" + combobox #routines:dialog:deliver @114,663,672,30 lb="Nowhere (Bate only)" tab + text @126,669,632,18 t="Nowhere (Bate only)" + image @762,672,12,12 deco + generic @114,693,672,12 + generic @90,690,720,54 + generic @114,698,123.33,30 + button #routines-go @114,698,48.75,30 lb="Add" tab + text @126,704,24.75,18 t="Add" + button #routines-cancel @170.75,698,66.58,30 lb="Cancel" tab + text @182.75,704,42.58,18 t="Cancel" diff --git a/native/tests/snapshots/native-botpages-routine-watch-dark.tree b/native/tests/snapshots/native-botpages-routine-watch-dark.tree index 22193fe..cb5e9a6 100644 --- a/native/tests/snapshots/native-botpages-routine-watch-dark.tree +++ b/native/tests/snapshots/native-botpages-routine-watch-dark.tree @@ -254,8 +254,8 @@ generic @0,0,900,760 generic @892,8,8,744 generic #routines-dialog-scrim @0,0,900,760 ovl dialog #routines-dialog @90,16,720,728 lb="Edit routine" - generic #routines-dialog-body @90,16,720,674 sc=0,0,0,177 - generic @114,16,672,851 + generic #routines-dialog-body @90,16,720,674 sc=0,0,0,241 + generic @114,16,672,915 generic @114,16,672,24 heading @114,40,672,18 t="Edit routine" generic @114,58,672,12 @@ -321,6 +321,12 @@ generic @0,0,900,760 text @114,803,672,18 t="Check first, with a command" textbox #routines:dialog:precheck @114,825,672,30 lb="Check first, with a command" v="" tab sc=0,0,0,0 end generic @114,855,672,12 + generic @114,867,672,52 + text @114,867,672,18 t="Send final reply to" + combobox #routines:dialog:deliver @114,889,672,30 lb="Nowhere (Bate only)" tab + text @126,895,632,18 t="Nowhere (Bate only)" + image @762,898,12,12 deco + generic @114,919,672,12 generic @90,690,720,54 generic @114,698,128.37,30 button #routines-go @114,698,53.79,30 lb="Save" tab diff --git a/native/tests/snapshots/native-botpages-routine-watch-light.tree b/native/tests/snapshots/native-botpages-routine-watch-light.tree index 22193fe..cb5e9a6 100644 --- a/native/tests/snapshots/native-botpages-routine-watch-light.tree +++ b/native/tests/snapshots/native-botpages-routine-watch-light.tree @@ -254,8 +254,8 @@ generic @0,0,900,760 generic @892,8,8,744 generic #routines-dialog-scrim @0,0,900,760 ovl dialog #routines-dialog @90,16,720,728 lb="Edit routine" - generic #routines-dialog-body @90,16,720,674 sc=0,0,0,177 - generic @114,16,672,851 + generic #routines-dialog-body @90,16,720,674 sc=0,0,0,241 + generic @114,16,672,915 generic @114,16,672,24 heading @114,40,672,18 t="Edit routine" generic @114,58,672,12 @@ -321,6 +321,12 @@ generic @0,0,900,760 text @114,803,672,18 t="Check first, with a command" textbox #routines:dialog:precheck @114,825,672,30 lb="Check first, with a command" v="" tab sc=0,0,0,0 end generic @114,855,672,12 + generic @114,867,672,52 + text @114,867,672,18 t="Send final reply to" + combobox #routines:dialog:deliver @114,889,672,30 lb="Nowhere (Bate only)" tab + text @126,895,632,18 t="Nowhere (Bate only)" + image @762,898,12,12 deco + generic @114,919,672,12 generic @90,690,720,54 generic @114,698,128.37,30 button #routines-go @114,698,53.79,30 lb="Save" tab diff --git a/proto/src/lib.rs b/proto/src/lib.rs index c6bc02e..c2fddfb 100644 --- a/proto/src/lib.rs +++ b/proto/src/lib.rs @@ -19,6 +19,7 @@ pub mod permissions; pub mod projects; pub mod qr; pub mod quick; +pub mod reveal; pub mod routines; pub mod secrets; #[cfg(target_os = "macos")] diff --git a/proto/src/reveal.rs b/proto/src/reveal.rs new file mode 100644 index 0000000..a44e24c --- /dev/null +++ b/proto/src/reveal.rs @@ -0,0 +1,207 @@ +//! Text that gets a person's yes, with every character they cannot see put in plain view. A piece +//! is either plain text or one character shown as its code point (`U+200B`), with what kind of +//! character it is. Only the display changes: what runs is the text the service has, as it is. +//! The page's rule is `window/ui/src/reveal.ts`. +//! +//! Not handled: a letter that only looks like another (a Cyrillic "а" for a Latin "a") is an +//! ordinary, visible character and is shown as it is. A grant is for the exact text, so a +//! lookalike never matches a command or path that was allowed before. + +/// What a piece of the text is. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Piece { + Plain(String), + /// A character nobody can see, as `U+XXXX`, with the kind of character it is. + Hidden { + code: String, + kind: &'static str, + }, +} + +/// Each kind of character that is marked, by the ranges it covers (newline and tab are not among them). +const KINDS: [(&str, &[(u32, u32)]); 6] = [ + ( + "control character", + &[(0x0000, 0x0008), (0x000B, 0x001F), (0x007F, 0x009F)], + ), + ( + "zero-width or joining character", + &[ + (0x034F, 0x034F), + (0x180B, 0x180E), + (0x200B, 0x200D), + (0x2060, 0x2064), + (0xFE00, 0xFE0F), + (0xFEFF, 0xFEFF), + (0xE0100, 0xE01EF), + ], + ), + ( + "character that changes the reading order", + &[ + (0x061C, 0x061C), + (0x200E, 0x200F), + (0x202A, 0x202E), + (0x2066, 0x2069), + ], + ), + ( + "space that is not an ordinary space", + &[ + (0x00A0, 0x00A0), + (0x1680, 0x1680), + (0x2000, 0x200A), + (0x2028, 0x2029), + (0x202F, 0x202F), + (0x205F, 0x205F), + (0x3000, 0x3000), + (0x2800, 0x2800), + ], + ), + ( + "blank letter or soft hyphen", + &[ + (0x00AD, 0x00AD), + (0x115F, 0x1160), + (0x17B4, 0x17B5), + (0x3164, 0x3164), + (0xFFA0, 0xFFA0), + (0x2065, 0x2065), + (0x206A, 0x206F), + (0xFFF9, 0xFFFC), + ], + ), + ("tag character", &[(0xE0000, 0xE007F)]), +]; + +fn kind_of(c: char) -> Option<&'static str> { + let c = c as u32; + KINDS + .iter() + .find(|(_, ranges)| ranges.iter().any(|&(lo, hi)| (lo..=hi).contains(&c))) + .map(|(name, _)| *name) +} + +/// `text` as pieces; the pieces that are not marked, put together, are the text without them. +pub fn reveal(text: &str) -> Vec { + let mut pieces = Vec::new(); + let mut plain = String::new(); + for c in text.chars() { + match kind_of(c) { + None => plain.push(c), + Some(kind) => { + if !plain.is_empty() { + pieces.push(Piece::Plain(std::mem::take(&mut plain))); + } + pieces.push(Piece::Hidden { + code: format!("U+{:04X}", c as u32), + kind, + }); + } + } + } + if !plain.is_empty() { + pieces.push(Piece::Plain(plain)); + } + pieces +} + +/// Whether any of `texts` holds a character that is marked. +pub fn has_hidden<'a>(texts: impl IntoIterator) -> bool { + texts + .into_iter() + .any(|t| t.chars().any(|c| kind_of(c).is_some())) +} + +/// Plain-text representation where every hidden or reordering character is replaced with `[U+XXXX]`. +/// Used in channel messages (Telegram, Discord) where styled spans cannot be rendered. +pub fn mark_plain(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + for piece in reveal(text) { + match piece { + Piece::Plain(s) => out.push_str(&s), + Piece::Hidden { code, .. } => { + out.push('['); + out.push_str(&code); + out.push(']'); + } + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn plain_text_is_one_piece() { + assert_eq!( + reveal("ls -la\n\tdone"), + [Piece::Plain("ls -la\n\tdone".into())] + ); + assert!(reveal("").is_empty()); + assert!(!has_hidden(["ls -la", "café 日本語"])); + assert_eq!(mark_plain("ls -la"), "ls -la"); + } + + #[test] + fn a_character_nobody_can_see_is_shown_as_its_code_point_with_its_kind() { + let pieces = reveal("rm\u{200B} -rf\u{202E}x\u{00A0}y"); + assert_eq!( + pieces, + [ + Piece::Plain("rm".into()), + Piece::Hidden { + code: "U+200B".into(), + kind: "zero-width or joining character" + }, + Piece::Plain(" -rf".into()), + Piece::Hidden { + code: "U+202E".into(), + kind: "character that changes the reading order" + }, + Piece::Plain("x".into()), + Piece::Hidden { + code: "U+00A0".into(), + kind: "space that is not an ordinary space" + }, + Piece::Plain("y".into()), + ] + ); + assert!(has_hidden(["fine", "a\u{200B}b"])); + assert_eq!( + mark_plain("rm\u{200B} -rf\u{202E}x"), + "rm[U+200B] -rf[U+202E]x" + ); + } + + #[test] + fn the_pieces_that_are_not_marked_are_the_text_without_the_marked() { + let text = "a\u{0007}b\u{E0041}c\u{FEFF}d\u{00AD}e"; + let plain: String = reveal(text) + .into_iter() + .filter_map(|p| match p { + Piece::Plain(s) => Some(s), + Piece::Hidden { .. } => None, + }) + .collect(); + assert_eq!(plain, "abcde"); + let kinds: Vec<_> = reveal(text) + .into_iter() + .filter_map(|p| match p { + Piece::Hidden { kind, .. } => Some(kind), + Piece::Plain(_) => None, + }) + .collect(); + assert_eq!( + kinds, + [ + "control character", + "tag character", + "zero-width or joining character", + "blank letter or soft hyphen", + ] + ); + } +} diff --git a/proto/src/routines.rs b/proto/src/routines.rs index 5e76fb9..cc87528 100644 --- a/proto/src/routines.rs +++ b/proto/src/routines.rs @@ -196,6 +196,13 @@ pub struct Routine { /// sets it, as it does a precheck. #[serde(default, skip_serializing_if = "Option::is_none")] pub watch: Option, + /// Paired channel (`"telegram"` or `"discord"`) to post the routine's final reply to. + /// Only Bate's own window sets it, as it does a precheck or watch. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub deliver_channel: Option, + /// Paired chat id on `deliver_channel` to post the routine's final reply to. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub deliver_chat: Option, /// Daemon-made secret, kept while `webhook` stays on; turn it off and on for a new one. #[serde(default, skip_serializing_if = "Option::is_none")] pub hook_token: Option, diff --git a/window/ui/src/Routines.tsx b/window/ui/src/Routines.tsx index f45828c..cb74da8 100644 --- a/window/ui/src/Routines.tsx +++ b/window/ui/src/Routines.tsx @@ -9,13 +9,20 @@ import type { After, Bot, Connector, Frequency, Permissions, Routine, RoutineRun import { useLater } from "./useLater.ts"; const OUTCOME: Record = { sent: "Sent", failed: "Failed", missed: "Missed", limit: "Stopped", skipped: "Skipped" }; +const CHANNEL_NAME: Record = { telegram: "Telegram", discord: "Discord" }; +type PairedChat = { kind: string; chat: string; name: string }; +const deliverKey = (channel?: string, chat?: string) => (channel && chat ? `${channel}:${chat}` : ""); +const splitDeliver = (value: string): { deliverChannel?: string; deliverChat?: string } => { + const i = value.indexOf(":"); + return i > 0 ? { deliverChannel: value.slice(0, i), deliverChat: value.slice(i + 1) } : { deliverChannel: undefined, deliverChat: undefined }; +}; /** The fields of the dialog; a routine with no schedule starts only from its web address or a chat. */ -const blank = { name: "", prompt: "", scheduled: true, frequency: "daily" as Frequency, interval: 1, time: "09:00", after: false, afterBot: "", afterOutcome: "done" as After["outcome"], webhook: false, chat: false, precheck: "", watching: false, connector: "", tool: "", args: "{}", every: 5 }; -const formOf = (r: Routine): typeof blank => ({ name: r.name, prompt: r.prompt, scheduled: !!r.schedule, frequency: r.schedule?.frequency ?? blank.frequency, interval: r.schedule?.interval ?? 1, time: r.schedule?.time ?? blank.time, after: !!r.after, afterBot: r.after?.bot ?? "", afterOutcome: r.after?.outcome ?? blank.afterOutcome, webhook: r.webhook, chat: r.chat, precheck: r.precheck ?? "", watching: !!r.watch, connector: r.watch?.connector ?? "", tool: r.watch?.tool ?? "", args: JSON.stringify(r.watch?.arguments ?? {}), every: r.watch?.every ?? blank.every }); +const blank = { name: "", prompt: "", scheduled: true, frequency: "daily" as Frequency, interval: 1, time: "09:00", after: false, afterBot: "", afterOutcome: "done" as After["outcome"], webhook: false, chat: false, precheck: "", watching: false, connector: "", tool: "", args: "{}", every: 5, deliver: "" }; +const formOf = (r: Routine): typeof blank => ({ name: r.name, prompt: r.prompt, scheduled: !!r.schedule, frequency: r.schedule?.frequency ?? blank.frequency, interval: r.schedule?.interval ?? 1, time: r.schedule?.time ?? blank.time, after: !!r.after, afterBot: r.after?.bot ?? "", afterOutcome: r.after?.outcome ?? blank.afterOutcome, webhook: r.webhook, chat: r.chat, precheck: r.precheck ?? "", watching: !!r.watch, connector: r.watch?.connector ?? "", tool: r.watch?.tool ?? "", args: JSON.stringify(r.watch?.arguments ?? {}), every: r.watch?.every ?? blank.every, deliver: deliverKey(r.deliverChannel, r.deliverChat) }); -/** A device on the network may not set a precheck or a watch: its frames leave them out and the service keeps the ones there are. */ -const frame = (r: Routine): Routine => (inShell ? r : { ...r, precheck: undefined, watch: undefined }); +/** A device on the network may not set a precheck, a watch, or a delivery chat: its frames leave them out and the service keeps the ones there are. */ +const frame = (r: Routine): Routine => (inShell ? r : { ...r, precheck: undefined, watch: undefined, deliverChannel: undefined, deliverChat: undefined }); /** How a run ended: a quiet badge when it went well, a plain one when the person should look. */ const Outcome = ({ run }: { run: RoutineRun }) => {OUTCOME[run.outcome]}; @@ -72,6 +79,7 @@ export function Routines({ bot }: { bot: string }) { const { later } = useLater(bot); const [connectors, setConnectors] = useState([]); const [permissions, setPermissions] = useState(); + const [pairedChats, setPairedChats] = useState([]); const tools = watchTools(connectors.find((c) => c.name === form.connector), form.tool, permissions); useEffect(() => { @@ -87,11 +95,15 @@ export function Routines({ bot }: { bot: string }) { request<{ bots: Bot[] }>("list_bots").then((d) => setBots(d.bots), () => {}); }, []); - /** The bot's connectors, for the dialog's choice of what to watch. */ + /** The bot's connectors and paired channel chats, for the dialog's choices. */ useEffect(() => { if (ask && inShell) { void request<{ connectors: Connector[] }>("list_connectors", { bot }).then((d) => setConnectors(d.connectors), () => setConnectors([])); void request("get_permissions", { bot }).then(setPermissions, () => setPermissions(undefined)); + void request<{ channels: { kind: string; chats: { chat: string; name: string }[] }[] }>("get_channels", { bot }).then( + (d) => setPairedChats(d.channels.flatMap((c) => c.chats.map((ch) => ({ kind: c.kind, chat: ch.chat, name: ch.name })))), + () => setPairedChats([]), + ); } }, [ask, bot]); @@ -101,12 +113,13 @@ export function Routines({ bot }: { bot: string }) { const open = (edit?: Routine) => (setForm(edit ? formOf(edit) : blank), setAsk({ edit })); const save = async () => { const { edit } = ask!; - const { name, prompt, scheduled, frequency, interval, time, after, afterBot, afterOutcome, webhook, chat, precheck, watching, connector, tool, args, every } = form; + const { name, prompt, scheduled, frequency, interval, time, after, afterBot, afterOutcome, webhook, chat, precheck, watching, connector, tool, args, every, deliver } = form; if (!scheduled && !after && !watching && !webhook && !chat) throw new Error("Choose what starts it: a schedule, another bot, a change in a connected app, a web address or a chat."); if (after && !afterBot) throw new Error("Choose the bot it follows."); + const { deliverChannel, deliverChat } = splitDeliver(deliver); await request("set_routine", { bot, - routine: frame({ ...edit, name, prompt, enabled: edit?.enabled ?? true, webhook, chat, precheck: precheck.trim() || undefined, schedule: scheduled ? { ...edit?.schedule, frequency, interval, time } : undefined, after: after ? { bot: afterBot, outcome: afterOutcome } : undefined, watch: watching ? { connector, tool: tool.trim(), arguments: watchArguments(args), every } : undefined }), + routine: frame({ ...edit, name, prompt, enabled: edit?.enabled ?? true, webhook, chat, precheck: precheck.trim() || undefined, deliverChannel, deliverChat, schedule: scheduled ? { ...edit?.schedule, frequency, interval, time } : undefined, after: after ? { bot: afterBot, outcome: afterOutcome } : undefined, watch: watching ? { connector, tool: tool.trim(), arguments: watchArguments(args), every } : undefined }), }); setError(""); setSaved(true); @@ -142,6 +155,7 @@ export function Routines({ bot }: { bot: string }) { {r.lastRun?.reason === "signed_out" && r.lastRun.detail && } {r.precheck && Checks first: {r.precheck}} {r.chat && From a paired chat: write /run {r.name}} + {r.deliverChannel && r.deliverChat && Sends reply to {CHANNEL_NAME[r.deliverChannel] ?? r.deliverChannel} ({r.deliverChat})} {r.hookUrl && Web address: {r.hookUrl}}
@@ -267,9 +281,27 @@ export function Routines({ bot }: { bot: string }) { <> {form.precheck.trim() &&

Runs before each run, without a model, in the bot's folder and under its limits. If it ends with 0, the bot runs and gets what it printed; any other end skips the run. Saving allows exactly this command for this routine, without asking again.

} + {(pairedChats.length > 0 || form.deliver) && ( +
+ + +
+ )} ) : ( - form.precheck &&

Checks first: {form.precheck}. Only Bate's own window can change it.

+ <> + {form.precheck &&

Checks first: {form.precheck}. Only Bate's own window can change it.

} + {form.deliver &&

Sends reply to a paired channel chat. Only Bate's own window can change it.

} + )} diff --git a/window/ui/src/types.ts b/window/ui/src/types.ts index b76ef03..ec1c256 100644 --- a/window/ui/src/types.ts +++ b/window/ui/src/types.ts @@ -76,6 +76,8 @@ export type Routine = { chat: boolean; precheck?: string; watch?: Watch; + deliverChannel?: string; + deliverChat?: string; hookUrl?: string; nextRunMs?: number; lastRun?: RoutineRun;