From dc0b35d0d1f1e88a1bf2608c1c36471cdf671399 Mon Sep 17 00:00:00 2001 From: Chiziaruhoma Ogbonda Date: Mon, 26 Oct 2026 00:30:32 +0100 Subject: [PATCH 1/4] fix(remote): show approval previews whole and the same way in every chat The policy no longer cuts a command at 200 bytes in an approval preview, only in a refusal sentence, and Telegram, iMessage and Photon no longer cut it at 3000 or 800. Every channel shows the command alone, or the file with what is done to it, and the rule that asked on a line of its own. Telegram sends a long preview over several messages with the buttons under the last, denies the request if any part fails to send, and clears the extra messages once it is answered. --- crates/aster-policy/src/policy.rs | 25 ++-- crates/aster-policy/src/tests/policy_test.rs | 23 ++++ crates/aster-remote/src/channel.rs | 109 ++++++++++++++++++ crates/aster-remote/src/imessage.rs | 10 +- crates/aster-remote/src/photon.rs | 10 +- crates/aster-remote/src/spectrum/state.rs | 4 +- crates/aster-remote/src/spectrum/text.rs | 76 ++---------- crates/aster-remote/src/telegram.rs | 85 +++++++++++--- crates/aster-remote/src/tests/channel_test.rs | 39 +++++++ .../aster-remote/src/tests/spectrum_test.rs | 3 +- .../aster-remote/src/tests/telegram_test.rs | 21 ---- 11 files changed, 277 insertions(+), 128 deletions(-) diff --git a/crates/aster-policy/src/policy.rs b/crates/aster-policy/src/policy.rs index adeb52b7..3edb77d1 100644 --- a/crates/aster-policy/src/policy.rs +++ b/crates/aster-policy/src/policy.rs @@ -158,7 +158,21 @@ impl Policy { fn subject(action: &Action) -> String { match action { Action::Edit { path } | Action::Read { path } => format!("`{path}`"), - Action::Exec { binary, args } => format!("`{}`", command_line(binary, args)), + Action::Exec { binary, args } => { + // A refusal names the command inside one sentence, so a long one + // is cut there. A preview never is: the person says yes to all of it. + const SUBJECT_LIMIT: usize = 200; + let mut line = command_line(binary, args); + if line.len() > SUBJECT_LIMIT { + let mut cut = SUBJECT_LIMIT; + while !line.is_char_boundary(cut) { + cut -= 1; + } + line.truncate(cut); + line.push('…'); + } + format!("`{line}`") + } } } @@ -175,7 +189,6 @@ fn bare_preview(action: &Action) -> String { } fn command_line(binary: &str, args: &[&str]) -> String { - const PREVIEW_LIMIT: usize = 200; let mut line = binary.to_string(); for arg in args { line.push(' '); @@ -187,14 +200,6 @@ fn command_line(binary: &str, args: &[&str]) -> String { line.push_str(arg); } } - if line.len() > PREVIEW_LIMIT { - let mut cut = PREVIEW_LIMIT; - while !line.is_char_boundary(cut) { - cut -= 1; - } - line.truncate(cut); - line.push('…'); - } line } diff --git a/crates/aster-policy/src/tests/policy_test.rs b/crates/aster-policy/src/tests/policy_test.rs index 2bc1c266..2663a297 100644 --- a/crates/aster-policy/src/tests/policy_test.rs +++ b/crates/aster-policy/src/tests/policy_test.rs @@ -278,3 +278,26 @@ fn a_deny_reason_names_the_rule_that_matched() { other => panic!("expected a deny, got {other:?}"), } } + +#[test] +fn an_approval_preview_shows_the_whole_command() { + let script = "echo step; ".repeat(60); + let args = ["-c", script.as_str()]; + + let mut c = cfg(); + c.ask = vec!["Bash(bash:*)".into()]; + match policy(c).evaluate(&exec("bash", &args)) { + Decision::Prompt { preview } => { + assert!(preview.contains(script.as_str()), "{preview}"); + assert!(!preview.contains('…'), "{preview}"); + } + other => panic!("expected a prompt, got {other:?}"), + } + + let mut c = cfg(); + c.deny = vec!["Bash(bash:*)".into()]; + match policy(c).evaluate(&exec("bash", &args)) { + Decision::Deny { reason } => assert!(reason.contains('…'), "{reason}"), + other => panic!("expected a refusal, got {other:?}"), + } +} diff --git a/crates/aster-remote/src/channel.rs b/crates/aster-remote/src/channel.rs index 76f5715a..19d68837 100644 --- a/crates/aster-remote/src/channel.rs +++ b/crates/aster-remote/src/channel.rs @@ -246,6 +246,115 @@ pub fn get_override( chat_state(chats, channel, chat_id, |state| read(state)) } +/// An approval preview as a chat shows it: the command alone, or the file +/// with what is done to it, and apart from it the rule that asked. A preview +/// that is not the policy's own passes through as written. +pub struct ApprovalView { + pub subject: String, + pub rule: Option, +} + +impl ApprovalView { + pub fn new(preview: &str) -> Self { + let preview = preview.trim(); + let (head, rule) = match preview + .strip_suffix(')') + .and_then(|rest| rest.rsplit_once(" (")) + { + Some((head, rule)) => (head, Some(rule.to_string())), + None => (preview, None), + }; + if let Some(command) = head.strip_prefix("run `").and_then(|c| c.strip_suffix('`')) { + return Self { + subject: command.to_string(), + rule, + }; + } + if head.starts_with("edit ") || head.starts_with("read ") { + return Self { + subject: head.to_string(), + rule, + }; + } + Self { + subject: preview.to_string(), + rule: None, + } + } + + /// The view as plain text, the rule on a line of its own. + pub fn text(&self) -> String { + match &self.rule { + Some(rule) => format!("{}\nRule: {rule}", self.subject), + None => self.subject.clone(), + } + } +} + +/// Text as messages of at most `limit` bytes, every line kept as written. +/// Approvals and questions go this way: what the person agrees to has to be +/// exactly what runs, fences, asterisks and indentation included. +pub(crate) fn verbatim_chunks(text: &str, limit: usize) -> Vec { + if text.trim().is_empty() { + return Vec::new(); + } + pack_lines(text.lines().map(str::to_string), limit) +} + +/// Lines packed into chunks of at most `limit` bytes with nothing dropped: +/// joining the chunks with newlines gives the lines back, except that a line +/// longer than a chunk is split across several. +pub(crate) fn pack_lines(lines: impl Iterator, limit: usize) -> Vec { + let mut chunks = Vec::new(); + let mut current: Option = None; + for line in lines { + if line.len() > limit { + chunks.extend(current.take()); + chunks.extend(split_long(&line, limit)); + continue; + } + current = match current.take() { + Some(mut chunk) if chunk.len() + 1 + line.len() <= limit => { + chunk.push('\n'); + chunk.push_str(&line); + Some(chunk) + } + Some(chunk) => { + chunks.push(chunk); + Some(line) + } + None => Some(line), + }; + } + chunks.extend(current); + chunks +} + +/// A line cut into pieces of at most `limit` bytes that concatenate back to +/// it, each cut just after a space where one follows the indentation. +fn split_long(line: &str, limit: usize) -> Vec { + let mut pieces = Vec::new(); + let mut rest = line; + while rest.len() > limit { + let mut cut = limit; + while !rest.is_char_boundary(cut) { + cut -= 1; + } + if let Some(space) = rest[..cut] + .rfind(' ') + .filter(|at| !rest[..*at].trim().is_empty()) + { + cut = space + 1; + } + pieces.push(rest[..cut].to_string()); + rest = &rest[cut..]; + } + if !rest.is_empty() { + pieces.push(rest.to_string()); + } + pieces +} + pub fn truncate(text: &str, limit: usize) -> String { if text.len() <= limit { return text.to_string(); diff --git a/crates/aster-remote/src/imessage.rs b/crates/aster-remote/src/imessage.rs index cdbf7fec..b7147667 100644 --- a/crates/aster-remote/src/imessage.rs +++ b/crates/aster-remote/src/imessage.rs @@ -12,9 +12,9 @@ use tokio::sync::mpsc; use crate::bridge::{Answer, Turn, TurnEvent, WireMessage}; use crate::channel::{ - Chats, MODES, Pending, Skills, WORKER_NOTE, abort_workers, chat_state, claim_worker_slot, - clear_worker_slot, console_text, console_tool, discover_skill_commands, get_override, - next_free_slot, set_override, skill_prompt, truncate, + ApprovalView, Chats, MODES, Pending, Skills, WORKER_NOTE, abort_workers, chat_state, + claim_worker_slot, clear_worker_slot, console_text, console_tool, discover_skill_commands, + get_override, next_free_slot, set_override, skill_prompt, truncate, }; const IMESSAGE_SYSTEM: &str = "You are Aster, running remotely over iMessage. \ @@ -395,8 +395,8 @@ async fn start_turn( api.send_text( &chat_id, &format!( - "Approval needed: {}\nReply yes, always, or no.", - truncate(&preview, 800) + "Needs your go-ahead:\n{}\nReply yes, always, or no.", + ApprovalView::new(&preview).text() ), ) .await; diff --git a/crates/aster-remote/src/photon.rs b/crates/aster-remote/src/photon.rs index 62279d4d..c721763e 100644 --- a/crates/aster-remote/src/photon.rs +++ b/crates/aster-remote/src/photon.rs @@ -14,9 +14,9 @@ use tokio::sync::mpsc; use crate::bridge::{Answer, Turn, TurnEvent, WireMessage}; use crate::channel::{ - Chats, MODES, Pending, Skills, WORKER_NOTE, abort_workers, chat_state, claim_worker_slot, - clear_worker_slot, console_text, console_tool, discover_skill_commands, get_override, - next_free_slot, set_override, skill_prompt, truncate, + ApprovalView, Chats, MODES, Pending, Skills, WORKER_NOTE, abort_workers, chat_state, + claim_worker_slot, clear_worker_slot, console_text, console_tool, discover_skill_commands, + get_override, next_free_slot, set_override, skill_prompt, truncate, }; const PHOTON_SYSTEM: &str = "You are Aster, running remotely over iMessage via Photon. \ @@ -468,8 +468,8 @@ async fn start_turn( api.send_text( &chat_id, &format!( - "Approval needed: {}\nReply yes, always, or no.", - truncate(&preview, 800) + "Needs your go-ahead:\n{}\nReply yes, always, or no.", + ApprovalView::new(&preview).text() ), ) .await; diff --git a/crates/aster-remote/src/spectrum/state.rs b/crates/aster-remote/src/spectrum/state.rs index c7270c10..b2a4b5ff 100644 --- a/crates/aster-remote/src/spectrum/state.rs +++ b/crates/aster-remote/src/spectrum/state.rs @@ -16,10 +16,10 @@ use ulid::Ulid; use super::api::Api; use super::cursor::{Cursor, LastChat}; use super::inbound::Inbound; -use super::text::{plain_chunks, verbatim_chunks}; +use super::text::plain_chunks; use super::{ChatKey, SpectrumConfig}; use crate::bridge::{Agent, Answer}; -use crate::channel::Skills; +use crate::channel::{Skills, verbatim_chunks}; use crate::telegram::is_stop_request; pub(super) const CHUNK_LIMIT: usize = 3500; diff --git a/crates/aster-remote/src/spectrum/text.rs b/crates/aster-remote/src/spectrum/text.rs index 661ca69d..334d07d2 100644 --- a/crates/aster-remote/src/spectrum/text.rs +++ b/crates/aster-remote/src/spectrum/text.rs @@ -2,6 +2,7 @@ //! size, approvals and questions as plain text, and the answers to them. use crate::bridge::Answer; +use crate::channel::{ApprovalView, pack_lines}; /// A reply as plain-text messages of at most `limit` bytes. The chat apps on /// this bridge show markdown as typed, so the markers that only make sense @@ -15,45 +16,6 @@ pub(crate) fn plain_chunks(text: &str, limit: usize) -> Vec { .collect() } -/// Text as messages of at most `limit` bytes, every line kept as written. -/// Approvals and questions go this way: what the person agrees to has to be -/// exactly what runs, fences, asterisks and indentation included. -pub(crate) fn verbatim_chunks(text: &str, limit: usize) -> Vec { - if text.trim().is_empty() { - return Vec::new(); - } - pack_lines(text.lines().map(str::to_string), limit) -} - -/// Lines packed into chunks of at most `limit` bytes with nothing dropped: -/// joining the chunks with newlines gives the lines back, except that a line -/// longer than a chunk is split across several. -fn pack_lines(lines: impl Iterator, limit: usize) -> Vec { - let mut chunks = Vec::new(); - let mut current: Option = None; - for line in lines { - if line.len() > limit { - chunks.extend(current.take()); - chunks.extend(split_long(&line, limit)); - continue; - } - current = match current.take() { - Some(mut chunk) if chunk.len() + 1 + line.len() <= limit => { - chunk.push('\n'); - chunk.push_str(&line); - Some(chunk) - } - Some(chunk) => { - chunks.push(chunk); - Some(line) - } - None => Some(line), - }; - } - chunks.extend(current); - chunks -} - /// One markdown line as it should read unrendered; None for a code fence. fn plain_line(line: &str) -> Option { if line.trim_start().starts_with("```") { @@ -69,36 +31,14 @@ fn plain_line(line: &str) -> Option { Some(line.replace("**", "")) } -/// A line cut into pieces of at most `limit` bytes that concatenate back to -/// it, each cut just after a space where one follows the indentation. -fn split_long(line: &str, limit: usize) -> Vec { - let mut pieces = Vec::new(); - let mut rest = line; - while rest.len() > limit { - let mut cut = limit; - while !rest.is_char_boundary(cut) { - cut -= 1; - } - if let Some(space) = rest[..cut] - .rfind(' ') - .filter(|at| !rest[..*at].trim().is_empty()) - { - cut = space + 1; - } - pieces.push(rest[..cut].to_string()); - rest = &rest[cut..]; - } - if !rest.is_empty() { - pieces.push(rest.to_string()); - } - pieces -} - -/// An approval as a text message, with the three words that answer it last. -/// A yes allows the whole request, so the preview goes in whole and is split -/// across as many messages as it takes rather than cut. +/// An approval as a text message. A yes allows the whole request, so the +/// preview goes in whole and is split across as many messages as it takes +/// rather than cut. pub(crate) fn approval_text(preview: &str, scope: Option<&str>) -> String { - let mut text = format!("Needs your go-ahead:\n{}", preview.trim()); + let mut text = format!( + "Needs your go-ahead:\n{}", + ApprovalView::new(preview).text() + ); if let Some(scope) = scope.filter(|scope| !scope.trim().is_empty()) { text.push_str(&format!("\nScope: {scope}")); } diff --git a/crates/aster-remote/src/telegram.rs b/crates/aster-remote/src/telegram.rs index 1225896a..65b60af6 100644 --- a/crates/aster-remote/src/telegram.rs +++ b/crates/aster-remote/src/telegram.rs @@ -18,11 +18,15 @@ use tokio::task::AbortHandle; use ulid::Ulid; use crate::bridge::{Agent, Answer, Turn, TurnEvent, TurnOutcome, WireMessage}; +use crate::channel::{ApprovalView, verbatim_chunks}; use crate::markdown; mod alerts; const CHUNK_LIMIT: usize = 4000; +/// Telegram takes 4,096 characters a message; this leaves room for the +/// heading, the rule and the scope around a slice of an approval preview. +const PREVIEW_CHUNK_LIMIT: usize = 3500; const ACTIVITY_WINDOW: usize = 4; @@ -87,6 +91,9 @@ Under 40 lines, paste inline."; enum Pending { Approval { subject: String, + /// The messages a long preview took before the one with the buttons, + /// cleared away with it once the request is answered. + preview_ids: Vec, respond: oneshot::Sender, }, Question(oneshot::Sender>), @@ -2121,11 +2128,43 @@ async fn drive_turn( } => { activity.say_out().await; activity.flush(true).await; - let subject = approval_subject(&preview); - let mut text = format!( - "Needs your go-ahead\n
{}
", - markdown::escape(&truncate(&subject, 3000)) - ); + // A yes allows all of it, so a long preview goes out over + // several messages rather than cut, with the buttons under the + // last. If any part fails to arrive, the request is denied. + let view = ApprovalView::new(&preview); + let mut chunks = verbatim_chunks(&view.subject, PREVIEW_CHUNK_LIMIT); + let last = chunks.pop().unwrap_or_default(); + let mut preview_ids = Vec::new(); + for chunk in &chunks { + let head = if preview_ids.is_empty() { + "Needs your go-ahead\n" + } else { + "" + }; + let html = format!("{head}
{}
", markdown::escape(chunk)); + match api.send_html_reply(chat_id, &html, Some(reply_to)).await { + Some(id) => preview_ids.push(id), + None => break, + } + } + if preview_ids.len() < chunks.len() { + let _ = respond.send(Answer::Deny); + for id in preview_ids { + api.delete_message(chat_id, id).await; + } + api.send_text(chat_id, "Denied: the whole request could not be shown.") + .await; + continue; + } + let mut text = if chunks.is_empty() { + "Needs your go-ahead\n".to_string() + } else { + String::new() + }; + text.push_str(&format!("
{}
", markdown::escape(&last))); + if let Some(rule) = &view.rule { + text.push_str(&format!("\nRule: {}", markdown::escape(rule))); + } if let Some(scope) = scope { text.push_str(&format!("\n{}", markdown::escape(&scope))); } @@ -2138,9 +2177,18 @@ async fn drive_turn( .await; eprintln!( "[{chat_id}] ⏸ approval needed: {}", - console_text(&subject, 120) + console_text(&view.subject, 120) + ); + let subject = console_text(&view.subject, 200); + set_pending( + chats, + chat_id, + Pending::Approval { + subject, + preview_ids, + respond, + }, ); - set_pending(chats, chat_id, Pending::Approval { subject, respond }); } TurnEvent::Question { header, @@ -2474,6 +2522,14 @@ async fn handle_callback( let mut chats = chats.lock().expect("chats lock"); chats.entry(chat_id).or_default().pending.take() }; + // A long preview's other messages go with the buttons once it is answered. + if let Some(Pending::Approval { preview_ids, .. }) = &pending + && matches!(data, "a:allow" | "a:always" | "a:deny") + { + for id in preview_ids { + api.delete_message(chat_id, *id).await; + } + } // An answered approval is deleted rather than settled: the activity list // already shows the step, so a second message would just repeat it. let (toast, answered) = match (pending, data) { @@ -2485,7 +2541,12 @@ async fn handle_callback( let _ = respond.send(Answer::AlwaysAllow); ("Always allowed", true) } - (Some(Pending::Approval { subject, respond }), "a:deny") => { + ( + Some(Pending::Approval { + subject, respond, .. + }), + "a:deny", + ) => { let _ = respond.send(Answer::Deny); // A denial has no step to show, so it leaves a line behind. api.settle_callback_message(callback, &format!("Denied · {subject}")) @@ -3563,14 +3624,6 @@ fn is_gif_url(url: &str) -> bool { || url.contains("media.tenor.com")) } -fn approval_subject(preview: &str) -> String { - let subject = preview.strip_prefix("run ").unwrap_or(preview).trim(); - match subject.strip_prefix('`').and_then(|s| s.split_once('`')) { - Some((command, rest)) => format!("{command}{rest}"), - None => subject.to_string(), - } -} - fn short_path(path: &str) -> String { path.trim_end_matches('/') .rsplit('/') diff --git a/crates/aster-remote/src/tests/channel_test.rs b/crates/aster-remote/src/tests/channel_test.rs index 0c730e32..583cd608 100644 --- a/crates/aster-remote/src/tests/channel_test.rs +++ b/crates/aster-remote/src/tests/channel_test.rs @@ -23,3 +23,42 @@ fn the_home_prefix_folds_to_a_tilde() { fn a_path_outside_home_stays_whole() { assert_eq!(workspace_name(std::path::Path::new("/srv/api")), "/srv/api"); } + +#[test] +fn approval_view_unwraps_the_run_preview() { + let view = ApprovalView::new("run `git status`"); + assert_eq!(view.subject, "git status"); + assert_eq!(view.rule, None); + assert_eq!(view.text(), "git status"); +} + +#[test] +fn approval_view_puts_the_rule_on_its_own_line() { + let view = ApprovalView::new("run `rm -rf dist` (risky command)"); + assert_eq!(view.subject, "rm -rf dist"); + assert_eq!(view.rule.as_deref(), Some("risky command")); + assert_eq!(view.text(), "rm -rf dist\nRule: risky command"); +} + +#[test] +fn approval_view_keeps_the_verb_on_a_path() { + let view = ApprovalView::new("edit src/lib.rs (protected path)"); + assert_eq!(view.text(), "edit src/lib.rs\nRule: protected path"); +} + +#[test] +fn approval_view_keeps_a_long_script_whole() { + let script = (0..300) + .map(|n| format!("echo step {n}")) + .collect::>() + .join("\n"); + let view = ApprovalView::new(&format!("run `bash -c \"{script}\"` (git push*)")); + assert_eq!(view.subject, format!("bash -c \"{script}\"")); + assert_eq!(view.rule.as_deref(), Some("git push*")); +} + +#[test] +fn approval_view_passes_other_previews_through() { + let preview = "`cat` needs to read credentials outside the repository:\n ~/.ssh (keys)"; + assert_eq!(ApprovalView::new(preview).text(), preview); +} diff --git a/crates/aster-remote/src/tests/spectrum_test.rs b/crates/aster-remote/src/tests/spectrum_test.rs index ce29a40f..128e482d 100644 --- a/crates/aster-remote/src/tests/spectrum_test.rs +++ b/crates/aster-remote/src/tests/spectrum_test.rs @@ -14,11 +14,12 @@ use super::inbound::{Inbound, Part, is_allowed, normalize_handle, parse_inbound, use super::state::{Admission, Bridge, CHUNK_LIMIT, ChatState}; use super::text::{ APPROVAL_ASK, approval_text, parse_approval, plain_chunks, question_text, resolve_choice, - shot_paths, verbatim_chunks, + shot_paths, }; use super::turn::{finish_turn, merge_queued}; use super::{ChatKey, SpectrumConfig, dispatch, page_ids}; use crate::bridge::Answer; +use crate::channel::verbatim_chunks; const AGENT: &str = "pho_usr_00000000000000000000000001"; const HUMAN: &str = "pho_usr_00000000000000000000000002"; diff --git a/crates/aster-remote/src/tests/telegram_test.rs b/crates/aster-remote/src/tests/telegram_test.rs index 104a2e95..8d8de40c 100644 --- a/crates/aster-remote/src/tests/telegram_test.rs +++ b/crates/aster-remote/src/tests/telegram_test.rs @@ -62,27 +62,6 @@ fn tool_line_escapes_html_in_arguments() { assert!(line.contains("a<b>.rs")); } -#[test] -fn approval_subject_unwraps_the_run_preview() { - assert_eq!(super::approval_subject("run `git status`"), "git status"); -} - -#[test] -fn approval_subject_keeps_trailing_notes() { - assert_eq!( - super::approval_subject("run `rm -rf dist` (risky command)"), - "rm -rf dist (risky command)" - ); -} - -#[test] -fn approval_subject_passes_through_edit_previews() { - assert_eq!( - super::approval_subject("edit src/lib.rs (protected path)"), - "edit src/lib.rs (protected path)" - ); -} - #[test] fn plan_message_marks_the_step_in_flight() { let args = r#"{"steps":[ From 8233309674257f50725d1786a5abcdca299713f6 Mon Sep 17 00:00:00 2001 From: Chiziaruhoma Ogbonda Date: Mon, 26 Oct 2026 01:05:09 +0100 Subject: [PATCH 2/4] fix(remote): make every part of an approval arrive before it is answered Telegram keeps the button message within its 4096-character limit, denies the request when the button message fails to send, ignores a tap on an older prompt's buttons, and clears a long preview when the turn ends unanswered. iMessage and Photon send a long approval in chunks and ask for the answer in a message of its own. --- crates/aster-remote/src/imessage.rs | 20 +++--- crates/aster-remote/src/photon.rs | 20 +++--- crates/aster-remote/src/telegram.rs | 99 ++++++++++++++++++++--------- 3 files changed, 92 insertions(+), 47 deletions(-) diff --git a/crates/aster-remote/src/imessage.rs b/crates/aster-remote/src/imessage.rs index b7147667..5d70e809 100644 --- a/crates/aster-remote/src/imessage.rs +++ b/crates/aster-remote/src/imessage.rs @@ -14,7 +14,7 @@ use crate::bridge::{Answer, Turn, TurnEvent, WireMessage}; use crate::channel::{ ApprovalView, Chats, MODES, Pending, Skills, WORKER_NOTE, abort_workers, chat_state, claim_worker_slot, clear_worker_slot, console_text, console_tool, discover_skill_commands, - get_override, next_free_slot, set_override, skill_prompt, truncate, + get_override, next_free_slot, set_override, skill_prompt, truncate, verbatim_chunks, }; const IMESSAGE_SYSTEM: &str = "You are Aster, running remotely over iMessage. \ @@ -392,17 +392,19 @@ async fn start_turn( TurnEvent::ApprovalRequest { preview, respond, .. } => { - api.send_text( - &chat_id, - &format!( - "Needs your go-ahead:\n{}\nReply yes, always, or no.", - ApprovalView::new(&preview).text() - ), - ) - .await; + // The whole preview goes out, over as many messages as it + // takes, before the question that a reply answers. + let text = format!( + "Needs your go-ahead:\n{}", + ApprovalView::new(&preview).text() + ); + for chunk in verbatim_chunks(&text, CHUNK_LIMIT) { + api.send_text(&chat_id, &chunk).await; + } chat_state(&chats, "imessage", 0, |state| { state.pending = Some(Pending::Approval { respond }) }); + api.send_text(&chat_id, "Reply yes, always, or no.").await; } TurnEvent::Question { header, diff --git a/crates/aster-remote/src/photon.rs b/crates/aster-remote/src/photon.rs index c721763e..553b8215 100644 --- a/crates/aster-remote/src/photon.rs +++ b/crates/aster-remote/src/photon.rs @@ -16,7 +16,7 @@ use crate::bridge::{Answer, Turn, TurnEvent, WireMessage}; use crate::channel::{ ApprovalView, Chats, MODES, Pending, Skills, WORKER_NOTE, abort_workers, chat_state, claim_worker_slot, clear_worker_slot, console_text, console_tool, discover_skill_commands, - get_override, next_free_slot, set_override, skill_prompt, truncate, + get_override, next_free_slot, set_override, skill_prompt, truncate, verbatim_chunks, }; const PHOTON_SYSTEM: &str = "You are Aster, running remotely over iMessage via Photon. \ @@ -465,17 +465,19 @@ async fn start_turn( TurnEvent::ApprovalRequest { preview, respond, .. } => { - api.send_text( - &chat_id, - &format!( - "Needs your go-ahead:\n{}\nReply yes, always, or no.", - ApprovalView::new(&preview).text() - ), - ) - .await; + // The whole preview goes out, over as many messages as it + // takes, before the question that a reply answers. + let text = format!( + "Needs your go-ahead:\n{}", + ApprovalView::new(&preview).text() + ); + for chunk in verbatim_chunks(&text, CHUNK_LIMIT) { + api.send_text(&chat_id, &chunk).await; + } chat_state(&chats, "photon", 0, |state| { state.pending = Some(Pending::Approval { respond }) }); + api.send_text(&chat_id, "Reply yes, always, or no.").await; } TurnEvent::Question { header, diff --git a/crates/aster-remote/src/telegram.rs b/crates/aster-remote/src/telegram.rs index 65b60af6..3dbed3d1 100644 --- a/crates/aster-remote/src/telegram.rs +++ b/crates/aster-remote/src/telegram.rs @@ -24,9 +24,13 @@ use crate::markdown; mod alerts; const CHUNK_LIMIT: usize = 4000; -/// Telegram takes 4,096 characters a message; this leaves room for the -/// heading, the rule and the scope around a slice of an approval preview. +/// Telegram takes 4,096 characters a message, counted as shown. +const MESSAGE_CHARS: usize = 4096; +/// A slice of an approval preview, leaving room in its message for the +/// heading, the rule and the scope. const PREVIEW_CHUNK_LIMIT: usize = 3500; +const APPROVAL_HEAD: &str = "Needs your go-ahead\n"; +const APPROVAL_HEAD_CHARS: usize = "Needs your go-ahead\n".len(); const ACTIVITY_WINDOW: usize = 4; @@ -91,6 +95,9 @@ Under 40 lines, paste inline."; enum Pending { Approval { subject: String, + /// The message with the buttons, so a tap on an older prompt's + /// buttons cannot answer this one. + message_id: i64, /// The messages a long preview took before the one with the buttons, /// cleared away with it once the request is answered. preview_ids: Vec, @@ -2132,12 +2139,28 @@ async fn drive_turn( // several messages rather than cut, with the buttons under the // last. If any part fails to arrive, the request is denied. let view = ApprovalView::new(&preview); + let mut tail = String::new(); + let mut tail_chars = 0; + if let Some(rule) = &view.rule { + tail.push_str(&format!("\nRule: {}", markdown::escape(rule))); + tail_chars += "\nRule: ".len() + rule.chars().count(); + } + if let Some(scope) = &scope { + tail.push_str(&format!("\n{}", markdown::escape(scope))); + tail_chars += 1 + scope.chars().count(); + } let mut chunks = verbatim_chunks(&view.subject, PREVIEW_CHUNK_LIMIT); - let last = chunks.pop().unwrap_or_default(); + // The last slice shares the buttons' message only when it fits + // there beside the rule and the scope. + let last = chunks + .pop_if(|last| { + APPROVAL_HEAD_CHARS + last.chars().count() + tail_chars <= MESSAGE_CHARS + }) + .unwrap_or_default(); let mut preview_ids = Vec::new(); for chunk in &chunks { let head = if preview_ids.is_empty() { - "Needs your go-ahead\n" + APPROVAL_HEAD } else { "" }; @@ -2147,34 +2170,35 @@ async fn drive_turn( None => break, } } - if preview_ids.len() < chunks.len() { - let _ = respond.send(Answer::Deny); - for id in preview_ids { - api.delete_message(chat_id, id).await; - } - api.send_text(chat_id, "Denied: the whole request could not be shown.") - .await; - continue; - } let mut text = if chunks.is_empty() { - "Needs your go-ahead\n".to_string() + APPROVAL_HEAD.to_string() } else { String::new() }; - text.push_str(&format!("
{}
", markdown::escape(&last))); - if let Some(rule) = &view.rule { - text.push_str(&format!("\nRule: {}", markdown::escape(rule))); - } - if let Some(scope) = scope { - text.push_str(&format!("\n{}", markdown::escape(&scope))); + if !last.is_empty() { + text.push_str(&format!("
{}
", markdown::escape(&last))); } + text.push_str(&tail); let keyboard = json!([[ {"text": "Allow once", "callback_data": "a:allow"}, {"text": "Always allow", "callback_data": "a:always"}, {"text": "Deny", "callback_data": "a:deny"}, ]]); - api.send_keyboard_reply(chat_id, &text, keyboard, Some(reply_to)) - .await; + let shown = if preview_ids.len() == chunks.len() { + api.send_keyboard_reply(chat_id, text.trim(), keyboard, Some(reply_to)) + .await + } else { + None + }; + let Some(message_id) = shown else { + let _ = respond.send(Answer::Deny); + for id in preview_ids { + api.delete_message(chat_id, id).await; + } + api.send_text(chat_id, "Denied: the whole request could not be shown.") + .await; + continue; + }; eprintln!( "[{chat_id}] ⏸ approval needed: {}", console_text(&view.subject, 120) @@ -2185,6 +2209,7 @@ async fn drive_turn( chat_id, Pending::Approval { subject, + message_id, preview_ids, respond, }, @@ -2297,19 +2322,26 @@ async fn finish_turn( result: Result, said: usize, ) -> bool { - let (result, stopped) = { + let (result, stopped, unanswered) = { let mut chats = chats.lock().expect("chats lock"); let state = chats.entry(chat_id).or_default(); state.running = None; - state.pending = None; + let unanswered = match state.pending.take() { + Some(Pending::Approval { preview_ids, .. }) => preview_ids, + _ => Vec::new(), + }; let stopped = std::mem::take(&mut state.stopped); if let Ok(outcome) = &result { state .history .push(WireMessage::assistant(outcome.reply.clone())); } - (result, stopped) + (result, stopped, unanswered) }; + // A turn that ends with a prompt open takes the long preview with it. + for id in unanswered { + api.delete_message(chat_id, id).await; + } let ok = result.is_ok(); match result { Ok(outcome) => { @@ -2518,9 +2550,14 @@ async fn handle_callback( return; } + let tapped = callback_message_ids(callback).map(|(_, id)| id); let pending = { let mut chats = chats.lock().expect("chats lock"); - chats.entry(chat_id).or_default().pending.take() + let state = chats.entry(chat_id).or_default(); + // A late tap on an older prompt's buttons must not answer this one. + let stale = data.starts_with("a:") + && matches!(&state.pending, Some(Pending::Approval { message_id, .. }) if Some(*message_id) != tapped); + if stale { None } else { state.pending.take() } }; // A long preview's other messages go with the buttons once it is answered. if let Some(Pending::Approval { preview_ids, .. }) = &pending @@ -4446,7 +4483,7 @@ impl Api { html: &str, keyboard: Value, reply_to: Option, - ) { + ) -> Option { let mut payload = json!({ "chat_id": chat_id, "text": html, @@ -4454,8 +4491,12 @@ impl Api { "reply_markup": { "inline_keyboard": keyboard }, }); add_reply(&mut payload, reply_to); - if let Err(e) = self.call("sendMessage", payload).await { - tracing::warn!("sendMessage failed: {e:#}"); + match self.call("sendMessage", payload).await { + Ok(message) => message.get("message_id").and_then(Value::as_i64), + Err(e) => { + tracing::warn!("sendMessage failed: {e:#}"); + None + } } } From 74f45ac625b67007fe88c76ae7250bcd8d28a577 Mon Sep 17 00:00:00 2001 From: Chiziaruhoma Ogbonda Date: Mon, 26 Oct 2026 01:06:58 +0100 Subject: [PATCH 3/4] fix(remote): answer telegram approvals before cleaning up their previews The agent hears the answer before the extra preview messages are deleted, a replaced prompt takes its preview with it, an outsized rule or scope is cut so the buttons still arrive, and a chunk limit narrower than one character no longer loops. --- crates/aster-remote/src/channel.rs | 4 ++ crates/aster-remote/src/telegram.rs | 43 +++++++++++++------ crates/aster-remote/src/tests/channel_test.rs | 5 +++ 3 files changed, 38 insertions(+), 14 deletions(-) diff --git a/crates/aster-remote/src/channel.rs b/crates/aster-remote/src/channel.rs index 19d68837..8f327014 100644 --- a/crates/aster-remote/src/channel.rs +++ b/crates/aster-remote/src/channel.rs @@ -340,6 +340,10 @@ fn split_long(line: &str, limit: usize) -> Vec { while !rest.is_char_boundary(cut) { cut -= 1; } + // A limit narrower than one character still moves on by one. + if cut == 0 { + cut = rest.chars().next().map_or(rest.len(), char::len_utf8); + } if let Some(space) = rest[..cut] .rfind(' ') .filter(|at| !rest[..*at].trim().is_empty()) diff --git a/crates/aster-remote/src/telegram.rs b/crates/aster-remote/src/telegram.rs index 3dbed3d1..bc1f718c 100644 --- a/crates/aster-remote/src/telegram.rs +++ b/crates/aster-remote/src/telegram.rs @@ -31,6 +31,8 @@ const MESSAGE_CHARS: usize = 4096; const PREVIEW_CHUNK_LIMIT: usize = 3500; const APPROVAL_HEAD: &str = "Needs your go-ahead\n"; const APPROVAL_HEAD_CHARS: usize = "Needs your go-ahead\n".len(); +/// The most of a rule or a scope an approval shows. +const LABEL_CHARS: usize = 500; const ACTIVITY_WINDOW: usize = 4; @@ -2141,12 +2143,14 @@ async fn drive_turn( let view = ApprovalView::new(&preview); let mut tail = String::new(); let mut tail_chars = 0; - if let Some(rule) = &view.rule { - tail.push_str(&format!("\nRule: {}", markdown::escape(rule))); + // The rule and the scope are labels, not what runs, so an + // outsized one is cut to keep the buttons' message deliverable. + if let Some(rule) = view.rule.as_deref().map(|rule| truncate(rule, LABEL_CHARS)) { + tail.push_str(&format!("\nRule: {}", markdown::escape(&rule))); tail_chars += "\nRule: ".len() + rule.chars().count(); } - if let Some(scope) = &scope { - tail.push_str(&format!("\n{}", markdown::escape(scope))); + if let Some(scope) = scope.as_deref().map(|scope| truncate(scope, LABEL_CHARS)) { + tail.push_str(&format!("\n{}", markdown::escape(&scope))); tail_chars += 1 + scope.chars().count(); } let mut chunks = verbatim_chunks(&view.subject, PREVIEW_CHUNK_LIMIT); @@ -2204,7 +2208,7 @@ async fn drive_turn( console_text(&view.subject, 120) ); let subject = console_text(&view.subject, 200); - set_pending( + let replaced = set_pending( chats, chat_id, Pending::Approval { @@ -2214,6 +2218,11 @@ async fn drive_turn( respond, }, ); + if let Some(Pending::Approval { preview_ids, .. }) = replaced { + for id in preview_ids { + api.delete_message(chat_id, id).await; + } + } } TurnEvent::Question { header, @@ -2372,9 +2381,10 @@ async fn finish_turn( ok } -fn set_pending(chats: &Chats, chat_id: i64, pending: Pending) { +/// Store the prompt the chat is waiting on, handing back any it replaces. +fn set_pending(chats: &Chats, chat_id: i64, pending: Pending) -> Option { let mut chats = chats.lock().expect("chats lock"); - chats.entry(chat_id).or_default().pending = Some(pending); + chats.entry(chat_id).or_default().pending.replace(pending) } async fn handle_callback( @@ -2559,14 +2569,16 @@ async fn handle_callback( && matches!(&state.pending, Some(Pending::Approval { message_id, .. }) if Some(*message_id) != tapped); if stale { None } else { state.pending.take() } }; - // A long preview's other messages go with the buttons once it is answered. - if let Some(Pending::Approval { preview_ids, .. }) = &pending - && matches!(data, "a:allow" | "a:always" | "a:deny") - { - for id in preview_ids { - api.delete_message(chat_id, *id).await; + // A long preview's other messages go with the buttons once it is + // answered, after the answer, so the turn never waits on the cleanup. + let leftover = match &pending { + Some(Pending::Approval { preview_ids, .. }) + if matches!(data, "a:allow" | "a:always" | "a:deny") => + { + preview_ids.clone() } - } + _ => Vec::new(), + }; // An answered approval is deleted rather than settled: the activity list // already shows the step, so a second message would just repeat it. let (toast, answered) = match (pending, data) { @@ -2601,6 +2613,9 @@ async fn handle_callback( if answered { api.delete_callback_message(callback).await; } + for id in leftover { + api.delete_message(chat_id, id).await; + } } struct Activity { diff --git a/crates/aster-remote/src/tests/channel_test.rs b/crates/aster-remote/src/tests/channel_test.rs index 583cd608..af17152f 100644 --- a/crates/aster-remote/src/tests/channel_test.rs +++ b/crates/aster-remote/src/tests/channel_test.rs @@ -62,3 +62,8 @@ fn approval_view_passes_other_previews_through() { let preview = "`cat` needs to read credentials outside the repository:\n ~/.ssh (keys)"; assert_eq!(ApprovalView::new(preview).text(), preview); } + +#[test] +fn verbatim_chunks_move_on_when_the_limit_is_under_one_character() { + assert_eq!(verbatim_chunks("éé", 1), vec!["é", "é"]); +} From 10a4079f6b8d2e3b5525c48fe85da243e186d73b Mon Sep 17 00:00:00 2001 From: Chiziaruhoma Ogbonda Date: Mon, 26 Oct 2026 01:33:33 +0100 Subject: [PATCH 4/4] fix(remote): read a run preview's rule after the command's closing backtick --- crates/aster-remote/src/channel.rs | 22 ++++++++++++++----- crates/aster-remote/src/tests/channel_test.rs | 7 ++++++ 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/crates/aster-remote/src/channel.rs b/crates/aster-remote/src/channel.rs index 8f327014..76f9133c 100644 --- a/crates/aster-remote/src/channel.rs +++ b/crates/aster-remote/src/channel.rs @@ -257,6 +257,22 @@ pub struct ApprovalView { impl ApprovalView { pub fn new(preview: &str) -> Self { let preview = preview.trim(); + // A command ends at its closing backtick, so a rule with brackets of + // its own cannot be mistaken for part of it. + if let Some((command, rest)) = preview + .strip_prefix("run `") + .and_then(|body| body.rsplit_once('`')) + { + let rule = rest + .strip_prefix(" (") + .and_then(|rule| rule.strip_suffix(')')); + if rest.is_empty() || rule.is_some() { + return Self { + subject: command.to_string(), + rule: rule.map(str::to_string), + }; + } + } let (head, rule) = match preview .strip_suffix(')') .and_then(|rest| rest.rsplit_once(" (")) @@ -264,12 +280,6 @@ impl ApprovalView { Some((head, rule)) => (head, Some(rule.to_string())), None => (preview, None), }; - if let Some(command) = head.strip_prefix("run `").and_then(|c| c.strip_suffix('`')) { - return Self { - subject: command.to_string(), - rule, - }; - } if head.starts_with("edit ") || head.starts_with("read ") { return Self { subject: head.to_string(), diff --git a/crates/aster-remote/src/tests/channel_test.rs b/crates/aster-remote/src/tests/channel_test.rs index af17152f..1bb06a4f 100644 --- a/crates/aster-remote/src/tests/channel_test.rs +++ b/crates/aster-remote/src/tests/channel_test.rs @@ -67,3 +67,10 @@ fn approval_view_passes_other_previews_through() { fn verbatim_chunks_move_on_when_the_limit_is_under_one_character() { assert_eq!(verbatim_chunks("éé", 1), vec!["é", "é"]); } + +#[test] +fn approval_view_keeps_brackets_inside_the_rule() { + let view = ApprovalView::new("run `git push` (Bash(git push (any):*))"); + assert_eq!(view.subject, "git push"); + assert_eq!(view.rule.as_deref(), Some("Bash(git push (any):*)")); +}