Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 15 additions & 10 deletions crates/aster-policy/src/policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}`")
}
}
}

Expand All @@ -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(' ');
Expand All @@ -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
}

Expand Down
23 changes: 23 additions & 0 deletions crates/aster-policy/src/tests/policy_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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:?}"),
}
}
123 changes: 123 additions & 0 deletions crates/aster-remote/src/channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,129 @@ pub fn get_override<T>(
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<String>,
}

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(" ("))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ApprovalView splits the rule at the last " (" which can be inside the rule itself — low/correctness · 85% confident

If a file or rule name includes a space and parenthesis, the chat shows a broken command and a nonsense rule line, misleading the user about what they are approving.

Fix: Parse the rule only when the head is a well-formed quoted subject (require the trailing backtick for run/edit/read and strip from the known policy format), rather than splitting on the last " (" in the whole string.

{
Some((head, rule)) => (head, Some(rule.to_string())),
None => (preview, None),
};
if head.starts_with("edit ") || head.starts_with("read ") {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ApprovalView mis-splits non-policy previews starting with read /edit — low/correctness · 75% confident

A preview that is not part of the approval policy but happens to start with the words "read" or "edit" and ends with a note in parentheses gets its parenthetical note cut off and shown as a rule, so the user sees a changed instruction instead of the original text.

Fix: Only recognize the rule suffix/prefix forms that the policy crate actually emits (e.g. require the backtick-wrapped subject forms like run …/`read `…/edit …``) before splitting, otherwise fall through to verbatim passthrough.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving this, the policy doesn't backtick paths so there is nothing to tell them apart by. No text is lost.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ApprovalView mis-parses plain previews that start with 'read '/'edit ' and end in ')' — low/correctness · 75% confident

A plain message like 'read the docs (please)' is shown as 'read the docs' with 'please' displayed as a separate rule, so the parenthetical note disappears and a rule appears that wasn't really there.

Fix: Only treat the edit/read branch as structured when the path token is actually backticked (e.g. contains a ...), otherwise pass the preview through verbatim.

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<String> {
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<Item = String>, limit: usize) -> Vec<String> {
let mut chunks = Vec::new();
let mut current: Option<String> = 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<String> {
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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

split_long can loop forever when limit is smaller than the first character — low/correctness · 97% confident

If the allowed message length is smaller than a single letter or symbol, the code keeps trying to split the same text without making progress, so the program freezes in an endless loop instead of sending the message.

Fix: Guard against cut == 0 (advance by at least one char or split at the next char boundary) before pushing a piece.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed, it moves on by one character now.

}
// 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())
{
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();
Expand Down
24 changes: 13 additions & 11 deletions crates/aster-remote/src/imessage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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, verbatim_chunks,
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

truncate import likely now unused after removing its only use — low/error-handling · 90% confident

After switching the approval message to a different formatter, the code still imports a helper it no longer uses. In strict builds this unused import is treated as an error, so the project can fail to build even though the program itself would work.

Fix: Remove truncate from the import list (same for photon.rs) if it is no longer referenced.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's still used for the chat key, line 227 here and 295 in photon.


const IMESSAGE_SYSTEM: &str = "You are Aster, running remotely over iMessage. \
Expand Down Expand Up @@ -392,17 +392,19 @@ async fn start_turn(
TurnEvent::ApprovalRequest {
preview, respond, ..
} => {
api.send_text(
&chat_id,
&format!(
"Approval needed: {}\nReply yes, always, or no.",
truncate(&preview, 800)
),
)
.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) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CHUNK_LIMIT referenced but not defined in imessage module — high/correctness · 90% confident

The program won't build, so the iMessage bridge can't start or handle approval requests at all.

Fix: Define a local const CHUNK_LIMIT: usize = ...; in imessage.rs (or import/share a crate-level constant) before using it.

api.send_text(&chat_id, &chunk).await;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unbounded number of chat messages per approval (no cap on total size/chunk count) — medium/perf · 80% confident

When a tool requests approval, the app now sends the entire request text as many separate messages, with no limit. A very large tool command can turn into hundreds of texts, flooding the conversation and delaying the actual yes/no question.

Fix: Cap the total preview bytes (or number of chunks) before sending, and/or handle send failures when a chunk is rejected.

}
chat_state(&chats, "imessage", 0, |state| {
state.pending = Some(Pending::Approval { respond })

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pending approval set after awaiting several preview sends widens the lost-reply race — low/concurrency · 85% confident

If someone answers yes as soon as the first part of a long approval message appears, the app is not yet waiting for that answer, so the yes can be treated like a brand-new message and the approval question is effectively ignored.

Fix: Set Pending::Approval before sending the preview chunks so a reply arriving mid-send is routed to respond.

});
api.send_text(&chat_id, "Reply yes, always, or no.").await;
}
TurnEvent::Question {
header,
Expand Down
24 changes: 13 additions & 11 deletions crates/aster-remote/src/photon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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, verbatim_chunks,
};

const PHOTON_SYSTEM: &str = "You are Aster, running remotely over iMessage via Photon. \
Expand Down Expand Up @@ -465,17 +465,19 @@ async fn start_turn(
TurnEvent::ApprovalRequest {
preview, respond, ..
} => {
api.send_text(
&chat_id,
&format!(
"Approval needed: {}\nReply yes, always, or no.",
truncate(&preview, 800)
),
)
.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) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CHUNK_LIMIT referenced but not defined in photon module — high/correctness · 80% confident

The Photon bridge won't compile at all, so the remote-messaging feature cannot be built or used until the missing size value is supplied.

Fix: Add a const CHUNK_LIMIT to photon.rs or import a shared constant.

api.send_text(&chat_id, &chunk).await;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CHUNK_LIMIT referenced but not imported/defined in this module — medium/correctness · 90% confident

The remote messaging component will not build because the named limit used when splitting long messages was left out of the list of things this file knows about, so users cannot run the application until that missing setting is added.

Fix: Define/import an appropriate CHUNK_LIMIT for the Photon transport.

}
chat_state(&chats, "photon", 0, |state| {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pending approval installed after awaited chunk sends — medium/concurrency · 85% confident

If a user answers while the app is still sending a long approval preview, their answer is treated as a new request instead of permission, so the tool waiting for approval never gets a response and stalls.

Fix: Register Pending::Approval before the send loop.

state.pending = Some(Pending::Approval { respond })
});
api.send_text(&chat_id, "Reply yes, always, or no.").await;
}
TurnEvent::Question {
header,
Expand Down
4 changes: 2 additions & 2 deletions crates/aster-remote/src/spectrum/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
76 changes: 8 additions & 68 deletions crates/aster-remote/src/spectrum/text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -15,45 +16,6 @@ pub(crate) fn plain_chunks(text: &str, limit: usize) -> Vec<String> {
.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<String> {
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<Item = String>, limit: usize) -> Vec<String> {
let mut chunks = Vec::new();
let mut current: Option<String> = 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<String> {
if line.trim_start().starts_with("```") {
Expand All @@ -69,36 +31,14 @@ fn plain_line(line: &str) -> Option<String> {
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<String> {
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}"));
}
Expand Down
Loading
Loading