diff --git a/crates/fctl-control/src/api/autopilots.rs b/crates/fctl-control/src/api/autopilots.rs index 03b010e5..cfc16018 100644 --- a/crates/fctl-control/src/api/autopilots.rs +++ b/crates/fctl-control/src/api/autopilots.rs @@ -1406,7 +1406,7 @@ pub async fn pause(ctx: &mut Ctx, req: &mut Request, id: &str) -> AppResult AppResult { if let Some(r) = resuming(ctx, id).await? - && let Err(why) = resumed(ctx, &r, false).await? + && let Err(why) = resumed(ctx, &r, With::Nothing).await? { return Err(conflict(why.message())); } @@ -1502,11 +1502,24 @@ pub async fn resuming(ctx: &Ctx, id: &str) -> AppResult> { })) } -/// Resumes the autopilot [`resuming`] checked: it wakes at once, with -/// `message` for one a person's message to its own session resumed -/// (`SendMessageRequest::wake_autopilot`), which went to it first. Not -/// when it changed meanwhile, and why. -pub async fn resumed(ctx: &Ctx, r: &Resuming, message: bool) -> AppResult> { +/// What resumed the autopilot, besides the resume: what went to it first, +/// which its log and audit say. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum With { + /// A resume alone. + Nothing, + /// A person's message to its own session + /// (`SendMessageRequest::wake_autopilot`). + Message, + /// A person's answer to what it asked, or their no + /// (`AnswerAutopilotAskRequest::wake_autopilot`). + Answer, +} + +/// Resumes the autopilot [`resuming`] checked: it wakes at once, after +/// what `with` says went to it first. Not when it changed meanwhile, and +/// why. +pub async fn resumed(ctx: &Ctx, r: &Resuming, with: With) -> AppResult> { let Resuming { p, row, @@ -1544,10 +1557,11 @@ pub async fn resumed(ctx: &Ctx, r: &Resuming, message: bool) -> AppResult "", + With::Message => " with a message to its session", + With::Answer => " with their answer", }; engine::log( &ctx.db, @@ -1576,7 +1590,7 @@ pub async fn resumed(ctx: &Ctx, r: &Resuming, message: bool) -> AppResult AppResult AppResult { let body: AnswerAutopilotAskRequest = http::body(req).await?; let l = load(ctx, id).await?; @@ -2066,6 +2082,7 @@ pub async fn answer(ctx: &mut Ctx, req: &mut Request, id: &str, ask: &str) -> Ap } let me = ctx.user()?.clone(); let files = fctl_domain::validate::attachment_ids(&body.attachments)?; + let waking = waking(ctx, id, &row, body.wake_autopilot).await?; // A secret, and where it goes; else the answer. let (answer, secret) = match (found.kind(), &found.secret_name, &found.secret_project_id) { (AutopilotAskKind::Secret, Some(name), Some(project)) => { @@ -2191,7 +2208,71 @@ pub async fn answer(ctx: &mut Ctx, req: &mut Request, id: &str, ask: &str) -> Ap .about(about.as_deref()); entry.other_project = elsewhere.as_deref(); engine::log(&ctx.db, &row.project_id, entry, ctx.now).await; - if row.state() == AutopilotState::On { + heard(ctx, id, &row, waking).await +} + +/// The resume an answer to an ask, or a no, asks for with +/// `wake_autopilot` while the autopilot is paused: checked before anything +/// goes, as `POST …/autopilot/resume` checks it, so that an answer it +/// refuses stays unsent. `None` when none was asked, or it is on already +/// and hears the answer as it is. +async fn waking( + ctx: &Ctx, + id: &str, + row: &AutopilotRow, + wake: Option, +) -> AppResult> { + if wake != Some(true) { + return Ok(None); + } + if row.state() == AutopilotState::Off { + return Err(conflict( + "This project is off autopilot: answer without waking it, or put the project on autopilot again.", + )); + } + let Some(r) = resuming(ctx, id).await? else { + return Ok(None); + }; + // One that couldn't run would pause again at its wake, the answer + // unheard. + r.runs_on(ctx).await?.map_err(|why| conflict(&why))?; + Ok(Some(r)) +} + +/// After an answer or a no went: resumes the paused autopilot when +/// `waking`, then wakes it with what people answered while it's on, and +/// answers with it as it now stands. The answer went whatever happens +/// here: a failed resume is no refusal, which people would answer again +/// (they can't: it's closed), so the autopilot comes back paused, and +/// people resume it. +async fn heard( + ctx: &mut Ctx, + id: &str, + row: &AutopilotRow, + waking: Option, +) -> AppResult { + let mut on = row.state() == AutopilotState::On; + if let Some(r) = &waking { + match resumed(ctx, r, With::Answer).await { + Ok(Ok(())) => on = true, + // Someone resumed it meanwhile, which the nudge finds on, or + // took it off. + Ok(Err(NotResumed::NotPaused)) => on = true, + Ok(Err(why)) => worker::console_log!( + "autopilot {}: not resumed with an answer: {}", + row.project_id, + why.message() + ), + Err(e) => worker::console_error!( + "autopilot {}: resuming it with an answer: {}", + row.project_id, + e.0.message + ), + } + } + // Only one that is on moves: the resume woke it at once, and the + // reason joins it. + if on { engine::nudge( &ctx.env, &ctx.db, @@ -2380,6 +2461,7 @@ pub async fn decline(ctx: &mut Ctx, req: &mut Request, id: &str, ask: &str) -> A require_steer(&l)?; let reason = ap::reason(body.reason.as_deref()).map_err(AppError)?; let me = ctx.user()?.clone(); + let waking = waking(ctx, id, &row, body.wake_autopilot).await?; let done = q( &ctx.db, "UPDATE autopilot_asks SET status = 'declined', answer = ?, answered_by = ?, answered_at = ? WHERE id = ? \ @@ -2407,17 +2489,7 @@ pub async fn decline(ctx: &mut Ctx, req: &mut Request, id: &str, ask: &str) -> A ctx.now, ) .await; - if row.state() == AutopilotState::On { - engine::nudge( - &ctx.env, - &ctx.db, - &row.project_id, - AutopilotWakeReason::Answered, - ctx.now + ap::PEOPLE_GATHER_MS, - ) - .await?; - } - get(ctx, id).await + heard(ctx, id, &row, waking).await } /// At most a line of what someone wrote, for the log. diff --git a/crates/fctl-control/src/api/sessions.rs b/crates/fctl-control/src/api/sessions.rs index 78bd487f..a3fece8b 100644 --- a/crates/fctl-control/src/api/sessions.rs +++ b/crates/fctl-control/src/api/sessions.rs @@ -697,25 +697,30 @@ pub async fn send_message(ctx: &mut Ctx, req: &mut Request, id: &str) -> AppResu // here: a failure is no refusal, which people would send again. let (woke_autopilot, not_woken) = match &waking { None => (false, None), - Some((r, _)) => match crate::api::autopilots::resumed(ctx, r, true).await { - Ok(Ok(())) => (true, None), - // Resumed, or taken off, by someone else meanwhile: the - // message went as it is. - Ok(Err(crate::api::autopilots::NotResumed::NotPaused)) => (false, None), - Ok(Err(why)) => (false, Some(why.message().to_owned())), - Err(e) => { - worker::console_error!( - "session {id}: resuming its autopilot after a message: {}", - e.0.message - ); - ( - false, - Some( - "Resuming it failed: resume it on its project's Autopilot tab.".to_owned(), - ), - ) + Some((r, _)) => { + match crate::api::autopilots::resumed(ctx, r, crate::api::autopilots::With::Message) + .await + { + Ok(Ok(())) => (true, None), + // Resumed, or taken off, by someone else meanwhile: the + // message went as it is. + Ok(Err(crate::api::autopilots::NotResumed::NotPaused)) => (false, None), + Ok(Err(why)) => (false, Some(why.message().to_owned())), + Err(e) => { + worker::console_error!( + "session {id}: resuming its autopilot after a message: {}", + e.0.message + ); + ( + false, + Some( + "Resuming it failed: resume it on its project's Autopilot tab." + .to_owned(), + ), + ) + } } - }, + } }; http::ok(&SendMessageResponse { delivery_id, diff --git a/crates/fctl-domain/src/autopilot.rs b/crates/fctl-domain/src/autopilot.rs index 8cd364f6..56984569 100644 --- a/crates/fctl-domain/src/autopilot.rs +++ b/crates/fctl-domain/src/autopilot.rs @@ -1663,7 +1663,7 @@ pub fn briefing(place: Place<'_>, rules: Rules<'_>, direction: &str) -> String { "- fctl wakes you at least every {}, and sooner when something needs you. Each wake says the time (UTC): later in a turn, run `date` before you write a time rather than work it out. Before you end your turn, say when to wake you if not then: `fctl autopilot wake --in 30m` (from 5 minutes to 24 hours), say when a session should be done, or in an hour or two while you wait only for people.\n", duration(rules.check_in_minutes) )); - s.push_str("- When the direction is done and nothing is left to do, write it down and pause yourself with `fctl autopilot pause --reason \"…\"`, the reason saying what you'd need to go on, if anything: people read it as they write to you, and resume you when they have more, often with a message to this session, which then comes before fctl's wake.\n"); + s.push_str("- When the direction is done and nothing is left to do, write it down and pause yourself with `fctl autopilot pause --reason \"…\"`, the reason saying what you'd need to go on, if anything: people read it as they write to you, and resume you when they have more, often with a message to this session, which then comes before fctl's wake, or with their answer to what you asked.\n"); s.push_str("\n## Getting good work from your sessions\n\n"); for line in work_lines(rules.powers) { s.push_str(&format!("- {line}\n")); diff --git a/crates/fctl-proto/src/autopilot.rs b/crates/fctl-proto/src/autopilot.rs index fd60bf5c..a184d19f 100644 --- a/crates/fctl-proto/src/autopilot.rs +++ b/crates/fctl-proto/src/autopilot.rs @@ -993,6 +993,14 @@ pub struct AnswerAutopilotAskRequest { #[serde(default, skip_serializing_if = "Vec::is_empty")] #[cfg_attr(feature = "ts", ts(as = "Option>", optional))] pub attachments: Vec, + /// While the autopilot is paused: resume it with the answer, for those + /// who steer it, as `POST …/autopilot/resume` does (on the caller's + /// subscription from then on, unless its owner keeps it). Checked + /// before anything goes; the answer goes first, and the autopilot + /// wakes with it. Without it, a paused autopilot hears the answer once + /// someone resumes it. One that is on hears it as it is. Control planes + /// from before it ignore it. + pub wake_autopilot: Option, } /// `POST …/autopilot/asks/{ask}/decline`. @@ -1001,6 +1009,9 @@ pub struct AnswerAutopilotAskRequest { #[cfg_attr(feature = "ts", derive(ts_rs::TS), ts(optional_fields))] pub struct DeclineAutopilotAskRequest { pub reason: Option, + /// While the autopilot is paused: resume it as it hears the no, as + /// `AnswerAutopilotAskRequest::wake_autopilot` does with an answer. + pub wake_autopilot: Option, } /// `POST …/autopilot/log`: the autopilot writes down what it did, decided diff --git a/crates/fctl/src/cmd/autopilot.rs b/crates/fctl/src/cmd/autopilot.rs index 6f976331..92839a96 100644 --- a/crates/fctl/src/cmd/autopilot.rs +++ b/crates/fctl/src/cmd/autopilot.rs @@ -173,6 +173,7 @@ pub enum AutopilotCmd { /// none, its own session that asked keeps them for it. #[command(after_help = "Examples: fctl autopilot answer apa_… \"Stripe\" + fctl autopilot answer apa_… --wake \"Stripe\" # resumes it, paused, with the answer fctl autopilot answer apa_… --attach hotdog.3mf --attach hotdog-v2.3mf \"The v2 one is newer\"")] Answer { /// What it asked (its id, apa_…). @@ -183,6 +184,12 @@ pub enum AutopilotCmd { /// to 10). #[arg(short, long = "attach", value_name = "FILE")] attach: Vec, + /// While the autopilot is paused, resume it with this: it takes it + /// up at once, as fctl autopilot resume does (on your Claude + /// subscription from then on, unless its owner keeps it on theirs). + /// Without it, a paused autopilot hears it once someone resumes it. + #[arg(long)] + wake: bool, }, /// Give it the secret it asked for: asked without showing what you /// type, or read from stdin. It goes into the project's secrets; the @@ -190,6 +197,12 @@ pub enum AutopilotCmd { Secret { /// What it asked (its id, apa_…). ask: String, + /// While the autopilot is paused, resume it with this: it takes it + /// up at once, as fctl autopilot resume does (on your Claude + /// subscription from then on, unless its owner keeps it on theirs). + /// Without it, a paused autopilot hears it once someone resumes it. + #[arg(long)] + wake: bool, }, /// Decline what it asked. Decline { @@ -198,6 +211,12 @@ pub enum AutopilotCmd { /// Why, for the autopilot. #[arg(long)] reason: Option, + /// While the autopilot is paused, resume it with this: it takes it + /// up at once, as fctl autopilot resume does (on your Claude + /// subscription from then on, unless its owner keeps it on theirs). + /// Without it, a paused autopilot hears it once someone resumes it. + #[arg(long)] + wake: bool, }, /// Its log, newest first. In its sandbox, with text (`-` to read it /// from stdin), the autopilot writes down what it did, decided or plans. @@ -570,6 +589,7 @@ pub async fn run(server: Option<&str>, args: AutopilotArgs, json: bool) -> Resul ask, answer, attach, + wake, } => { let text = match attach.is_empty() { true => words_or_stdin( @@ -580,6 +600,7 @@ pub async fn run(server: Option<&str>, args: AutopilotArgs, json: bool) -> Resul }; // Files go to the session it asks about, or else to its own // session that asked, which keeps them for it. + let was = paused_before(&api, p, wake).await?; let (attachments, to) = match attach.is_empty() { true => (Vec::new(), None), false => { @@ -619,26 +640,23 @@ pub async fn run(server: Option<&str>, args: AutopilotArgs, json: bool) -> Resul answer: Some(text).filter(|t| !t.is_empty()), secret: None, attachments, + wake_autopilot: wake.then_some(true), }, ) .await?; if json { return style::print_json(&a); } - match to { - Some(Some(to)) => println!( - "{} Answered, and sent {to} the files: the autopilot hears now", - style::accent("✓") - ), - Some(None) => println!( - "{} Answered, with the files: the autopilot hears now", - style::accent("✓") - ), - None => println!("{} Answered: it hears now", style::accent("✓")), - } + let done = match to { + Some(Some(to)) => format!("Answered, and sent {to} the files"), + Some(None) => "Answered, with the files".to_owned(), + None => "Answered".to_owned(), + }; + say_heard(&a, &done, "", wake, was); } - AutopilotCmd::Secret { ask } => { + AutopilotCmd::Secret { ask, wake } => { let a = api.autopilot(p).await?; + let was = a.state == AutopilotState::Paused; let Some(asked) = a.asks.iter().find(|x| x.id == ask) else { bail!("It asks nothing by that id: fctl autopilot asks -p {p} lists what it asks"); }; @@ -654,27 +672,41 @@ pub async fn run(server: Option<&str>, args: AutopilotArgs, json: bool) -> Resul answer: None, secret: Some(value), attachments: Vec::new(), + wake_autopilot: wake.then_some(true), }, ) .await?; if json { return style::print_json(&a); } - println!( - "{} Set {} in {}'s secrets: the autopilot hears it's set, and sessions that start from now on have it", - style::accent("✓"), - style::bold(&secret.name), - secret.project_slug + say_heard( + &a, + &format!( + "Set {} in {}'s secrets", + style::bold(&secret.name), + secret.project_slug + ), + ", and sessions that start from now on have it", + wake, + was, ); } - AutopilotCmd::Decline { ask, reason } => { + AutopilotCmd::Decline { ask, reason, wake } => { + let was = paused_before(&api, p, wake).await?; let a = api - .decline_ask(p, &ask, &DeclineAutopilotAskRequest { reason }) + .decline_ask( + p, + &ask, + &DeclineAutopilotAskRequest { + reason, + wake_autopilot: wake.then_some(true), + }, + ) .await?; if json { return style::print_json(&a); } - println!("{} Declined: it hears now", style::accent("✓")); + say_heard(&a, "Declined", "", wake, was); } AutopilotCmd::Log { text, limit } => { // Text writes an entry (`-` reads it from stdin); none lists them. @@ -1053,6 +1085,53 @@ fn write_file(to: &std::path::Path, content: &str) -> Result<()> { Ok(()) } +/// Whether the autopilot of `p` is paused before an answer that would +/// wake it (`wake`) goes, to say whether the answer resumed it. +async fn paused_before(api: &fctl_client::Api, p: &str, wake: bool) -> Result { + Ok(wake && api.autopilot(p).await?.state == AutopilotState::Paused) +} + +/// Says what an answer to what the autopilot asked did (`done`, then +/// `and`), as the autopilot `a` it came back with stands: whether it hears +/// it now, and how it will while paused. `wake` asked to resume it, and it +/// was paused before when `was`. +fn say_heard(a: &Autopilot, done: &str, and: &str, wake: bool, was: bool) { + let p = &a.project_slug; + match a.state { + AutopilotState::On if wake && was => println!( + "{} {done}, and resumed the autopilot: it takes it up now{and}", + style::accent("✓") + ), + AutopilotState::On => println!( + "{} {done}: the autopilot hears now{and}", + style::accent("✓") + ), + AutopilotState::Paused => { + println!("{} {done}{and}", style::accent("✓")); + if wake { + eprintln!( + "{} The autopilot is still paused: it hears once resumed (fctl autopilot resume -p {p})", + style::amber("!") + ); + } else { + eprintln!( + "{}", + style::dim(&format!( + "The autopilot is paused: it hears once someone resumes it (fctl autopilot resume -p {p}). --wake resumes it with what you send." + )) + ); + } + } + AutopilotState::Off => { + println!("{} {done}{and}", style::accent("✓")); + eprintln!( + "{}", + style::dim("The project is off autopilot: it hears if someone puts it on again.") + ); + } + } +} + /// Whether this runs in an autopilot's own session's sandbox. fn in_its_sandbox() -> bool { std::env::var(AUTOPILOT_ENV).is_ok_and(|p| !p.is_empty()) @@ -1643,6 +1722,7 @@ mod tests { ask, answer, attach, + wake, }) = parse(&["answer", "apa_1", "-a", "a.3mf", "--attach", "b.3mf"]) else { panic!("parses"); @@ -1650,6 +1730,26 @@ mod tests { assert_eq!(ask, "apa_1"); assert!(answer.is_empty()); assert_eq!(attach, [PathBuf::from("a.3mf"), PathBuf::from("b.3mf")]); + assert!(!wake); + } + + #[test] + fn answers_wake_a_paused_autopilot_when_asked() { + let Some(AutopilotCmd::Answer { answer, wake, .. }) = + parse(&["answer", "apa_1", "--wake", "Stripe"]) + else { + panic!("parses"); + }; + assert_eq!(answer, ["Stripe"]); + assert!(wake); + assert!(matches!( + parse(&["secret", "apa_1", "--wake"]), + Some(AutopilotCmd::Secret { wake: true, .. }) + )); + assert!(matches!( + parse(&["decline", "apa_1", "--wake", "--reason", "Not now"]), + Some(AutopilotCmd::Decline { wake: true, .. }) + )); } #[test] diff --git a/docs/adr/0080-autopilots-run-a-project-on-their-own-through-the-api-their-session-relays.md b/docs/adr/0080-autopilots-run-a-project-on-their-own-through-the-api-their-session-relays.md index ea15a65e..a74c47c6 100644 --- a/docs/adr/0080-autopilots-run-a-project-on-their-own-through-the-api-their-session-relays.md +++ b/docs/adr/0080-autopilots-run-a-project-on-their-own-through-the-api-their-session-relays.md @@ -114,7 +114,12 @@ agent that manages a project needs most of the API besides. those who steer it whether to wake it with the message, and the API takes `wake_autopilot` with it: the message goes first, then the autopilot resumes, and its wake, which finds the session about to take - the message up, reaches it there rather than in a fresh session. + the message up, reaches it there rather than in a fresh session. An + answer to what it asked, a secret or a no, given while it's paused, + likewise waits for a resume: those who answer choose whether it wakes + it (`wake_autopilot` on the answer, *Wake it and answer* on its tab), + rather than have every answer resume it, as a resume may move it to + their Claude subscription. - **What it does shows where people look**: its tab (where it stands, what it asks, notes, direction, plan, its sessions live, its log), its own transcript (a card for each wake, a live card for each session it diff --git a/docs/agents.md b/docs/agents.md index d3c49765..7c68a5d2 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -795,4 +795,6 @@ alone, which can't start or steer sessions, or keep the plan and log. So the web app asks those who steer it, as they send one there, whether to wake it with the message, and `fctl send --wake` does: the message goes first, then it resumes, as people's resume does, and fctl wakes it -in that session with what's new since it paused. +in that session with what's new since it paused. An answer to what it +asked waits for a resume too: those who answer choose whether it wakes +it (`fctl autopilot answer --wake`, *Wake it and answer* on its tab). diff --git a/docs/api.md b/docs/api.md index c4ea0acd..c2680798 100644 --- a/docs/api.md +++ b/docs/api.md @@ -377,8 +377,8 @@ session calls the endpoints marked *autopilot*, through its sandbox's | `POST …/autopilot/pause`, `…/resume` | `{"reason"}`: pauses it (*autopilot* too: it pauses itself); resuming wakes it at once, on the resumer's subscription unless its owner keeps it and can still run it | | `POST …/autopilot/wake` | wakes it now; `{"fresh": true}`, in a fresh session of its own that takes over from the one it works in, at once between its turns or while its runner has been away a minute (`session.runner_away_since`), else once its turn ends (`fresh_asked` meanwhile); *autopilot*: `{"in_minutes": 30}` or `{"at": …}`, when it wakes next unless something needs it sooner | | `POST …/autopilot/notes`, `DELETE …/autopilot/notes/{note}` | `{"text"}` (Markdown, at most 2,000 characters): steers it, at once | -| `POST …/autopilot/asks/{ask}/answer` | `{"answer", "attachments"}`, or `{"secret"}` for a secret it asked for, which goes into the project's secrets. `attachments`, uploaded to the session a question is about (`about`), go to it in a message from the caller with the answer as its text; for a question about none, uploaded to its session that asked (`session`), which keeps them without a message, and the autopilot hears with the answer how to download them; the answer may then be empty. A question whose session is gone takes no files (`about_gone` once the one it asked about is) | -| `POST …/autopilot/asks/{ask}/decline` | `{"reason"}` | +| `POST …/autopilot/asks/{ask}/answer` | `{"answer", "attachments"}`, or `{"secret"}` for a secret it asked for, which goes into the project's secrets. `attachments`, uploaded to the session a question is about (`about`), go to it in a message from the caller with the answer as its text; for a question about none, uploaded to its session that asked (`session`), which keeps them without a message, and the autopilot hears with the answer how to download them; the answer may then be empty. A question whose session is gone takes no files (`about_gone` once the one it asked about is). While it's paused, it hears the answer once someone resumes it; `"wake_autopilot": true` resumes it with the answer, as `POST …/autopilot/resume` does (checked before anything goes; the autopilot comes back still `paused` should the resume fail once the answer went) | +| `POST …/autopilot/asks/{ask}/decline` | `{"reason"}`; `"wake_autopilot": true` resumes it, paused, with the no, as an answer does | | `GET …/autopilot/log` | `{"entries": […], "has_more"}`, newest first (`?before=` an entry's id, `?limit=` up to 200) | | `GET …/autopilot/brief` | `{"brief"}`: where things stand, as Markdown for its session; `?only=sessions,asks` gives only the parts named (`direction`, `notes`, `asks`, `sessions`, its own, `people`, people's sessions, `plan`, `files`, its files by name, `log`), after its lines on where it runs. The autopilot has then heard of the notes and answers among them | | `POST …/autopilot/log` | *autopilot*: `{"text"}`, what it did, decided or plans | diff --git a/docs/cli.md b/docs/cli.md index 8b9ed446..c71d6e7b 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -921,6 +921,7 @@ fctl autopilot steer -p crm "Focus on the pipeline board this week." fctl autopilot asks --all # what autopilots ask you, across your workspaces fctl autopilot answer -p crm apa_01JC… "Stripe" fctl autopilot answer -p crm apa_01JC… --attach logo.svg "The dark one" # files go to the session it asks about, else to it +fctl autopilot answer -p crm apa_01JC… --wake "Stripe" # paused, it resumes with the answer fctl autopilot secret -p crm apa_01JC… # the value it asked for, without showing it (or from stdin) fctl autopilot decline -p crm apa_01JC… --reason "Not yet: after launch" fctl autopilot log -p crm --limit 100 @@ -969,7 +970,11 @@ itself. An autopilot often pauses itself to wait for people, and what they send next is what it waited for: `fctl send --wake "…"` resumes it with the message, as `fctl autopilot resume` does, which goes first, and fctl then wakes it there with what's new. `fctl send` without -`--wake` says when the autopilot is paused. +`--wake` says when the autopilot is paused. An answer to what it asked +waits the same way: a paused autopilot hears it once someone resumes it, +and `fctl autopilot answer --wake` (`secret --wake`, `decline --wake`) +resumes it with the answer, which goes first; the web app asks, as you +answer on its tab, whether to wake it. In its own session's sandbox, the autopilot's `fctl` reaches the API as the person it acts for, without signing in (`FCTL_AUTOPILOT` names its diff --git a/docs/llms.txt b/docs/llms.txt index 40ca0fb4..f205754f 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -57,7 +57,7 @@ web app · fctl CLI · HTTP API · Claude apps · Linear · Slack · GitHub webh - **Follow-up**: a message from fctl that brings an agent back to a pull request its session opened: `comments`, `checks`, `conflicts`, `closed`. - **Webhook** (`whk_…`, events `evt_…`, deliveries `whd_…`): an `https://` address fctl posts a workspace's events to (for all its projects or some; a project's own for its events), with the events it wants, whose sessions' (`started_by`), and a `whsec_…` secret that signs each request (`webhook-id`, `webhook-timestamp`, `webhook-signature`); each request names its `workspace` and `project` by id. - **Schedule** (`sch_…`, runs `srn_…`): a task fctl starts sessions for on its own: on a cron expression in a time zone, once at a time, each time an event happens on GitHub in the project's repositories (`issue_opened`, `issue_labeled`, `pull_request_opened`, `pull_request_merged`, `release_published`, `checks_failed`), or only when asked (by a person or a tool). -- **Autopilot** (experimental): an agent that runs a project, or its whole workspace, on its own, from a direction people give it and change at any time, on the subscription of whoever put it on, as whom it acts; someone else who changes how much it works, or resumes it, runs it on theirs from then on, unless its owner keeps it on their own (`fctl autopilot set --keep-owner on`, for a project whose people they all trust). It works in sessions of its own in its project (a fresh one, which starts from its plan, log and files, after 12 hours, once its context holds as many tokens as people choose: `fctl autopilot set --handoff-at 250k`, when people ask: `fctl autopilot wake --fresh`, or when the runner that keeps its sandbox drains or is gone), starts sessions to do the work (as many at once as people allow, counting those queued, starting, working, paused on a usage limit or still stopping and one it just messaged, not one that ended its turn to wait for its background work; at the limit, `fctl send` to one that rests holds the message, `aph_…`, and fctl sends it as soon as one of its sessions ends its turn, stops or fails, those held in the order sent, listed and taken back with `fctl autopilot held`; each wake says the start of what each said as its turn ended, or why it ended its turn without a word where fctl knows (Claude Code cut off twice, an interrupt, a message mid-turn), and what people wrote to them, which doesn't wake it itself; a pull request of one merging or closing wakes it, and once one merged, the checks on its base branch ending wake it again with how they went, so that it needs no script to wait for main to go green), attaches files to their tasks and messages (`fctl run --attach`, `fctl send --attach`: one people sent it, one it made, or one sent in another of its sessions, which `fctl files get ` downloads; an older sandbox image's `fctl` can't, and it passes screenshots on as links it publishes with `fctl publish` instead), looks after the sessions people start there (asking them before it helps get a pull request of theirs merged, with a session of its own; or, with the power people give it, `--powers …,others`, managing them as its own: woken as one ends its turn, asks or fails, it messages them and resumes one that failed to see their work merged and shipped, on their people's subscriptions, never interrupting or stopping one nor writing to one its people stopped, while what their people ask wins), keeps a plan and a log, and files that its next sessions get back in their new sandbox (`fctl autopilot files put/get/rm`: text such as the scripts it relies on, templates and a draft until it sends it, as fctl keeps the text it sent, 256 KB each and 4 MB in all, which people read on its tab; its brief and `fctl autopilot files` mark those its plan doesn't name, and a fresh session of its own goes through them, as it does once it keeps more than 25), keeps the project's memory as its sessions do and deletes its notes stale for over a day itself, without asking, once its brief says they crowd the memory (900 of the 1,000 notes a project keeps, stale ones included: `fctl memory delete --stale`), reads where things stand in its brief (`fctl autopilot brief`, or parts of it: `--only sessions,people,asks`), asks people questions and for secrets (`fctl autopilot ask`, `apa_…`; a question about one of its sessions, `--session crm#12`, links to it, and the files people attach to their answer, `fctl autopilot answer --attach`, go to that session; those attached to an answer about none stay in its session that asked, which `fctl files get` downloads them from) and takes their notes (`apn_…`). Paused (by people, by fctl, or by itself, done or waiting for people: `pauser`), its `fctl` reaches nothing, so a message to the session it works in reaches that session's agent alone, which can't start or steer sessions: `fctl send --wake "…"` (the web app's *Wake it and send*) resumes it with the message, which goes first, and fctl then wakes it there with what's new. Its workspace's admins let projects have one. It is token hungry: several sessions at once, kept going on their own, drain a Claude plan's usage quickly, so a fresh build on Pro can reach the five-hour limit, where its sessions pause until the limit resets; Max and Ultra plans are usually enough, as the Autopilot tab and the workspace's setting say. +- **Autopilot** (experimental): an agent that runs a project, or its whole workspace, on its own, from a direction people give it and change at any time, on the subscription of whoever put it on, as whom it acts; someone else who changes how much it works, or resumes it, runs it on theirs from then on, unless its owner keeps it on their own (`fctl autopilot set --keep-owner on`, for a project whose people they all trust). It works in sessions of its own in its project (a fresh one, which starts from its plan, log and files, after 12 hours, once its context holds as many tokens as people choose: `fctl autopilot set --handoff-at 250k`, when people ask: `fctl autopilot wake --fresh`, or when the runner that keeps its sandbox drains or is gone), starts sessions to do the work (as many at once as people allow, counting those queued, starting, working, paused on a usage limit or still stopping and one it just messaged, not one that ended its turn to wait for its background work; at the limit, `fctl send` to one that rests holds the message, `aph_…`, and fctl sends it as soon as one of its sessions ends its turn, stops or fails, those held in the order sent, listed and taken back with `fctl autopilot held`; each wake says the start of what each said as its turn ended, or why it ended its turn without a word where fctl knows (Claude Code cut off twice, an interrupt, a message mid-turn), and what people wrote to them, which doesn't wake it itself; a pull request of one merging or closing wakes it, and once one merged, the checks on its base branch ending wake it again with how they went, so that it needs no script to wait for main to go green), attaches files to their tasks and messages (`fctl run --attach`, `fctl send --attach`: one people sent it, one it made, or one sent in another of its sessions, which `fctl files get ` downloads; an older sandbox image's `fctl` can't, and it passes screenshots on as links it publishes with `fctl publish` instead), looks after the sessions people start there (asking them before it helps get a pull request of theirs merged, with a session of its own; or, with the power people give it, `--powers …,others`, managing them as its own: woken as one ends its turn, asks or fails, it messages them and resumes one that failed to see their work merged and shipped, on their people's subscriptions, never interrupting or stopping one nor writing to one its people stopped, while what their people ask wins), keeps a plan and a log, and files that its next sessions get back in their new sandbox (`fctl autopilot files put/get/rm`: text such as the scripts it relies on, templates and a draft until it sends it, as fctl keeps the text it sent, 256 KB each and 4 MB in all, which people read on its tab; its brief and `fctl autopilot files` mark those its plan doesn't name, and a fresh session of its own goes through them, as it does once it keeps more than 25), keeps the project's memory as its sessions do and deletes its notes stale for over a day itself, without asking, once its brief says they crowd the memory (900 of the 1,000 notes a project keeps, stale ones included: `fctl memory delete --stale`), reads where things stand in its brief (`fctl autopilot brief`, or parts of it: `--only sessions,people,asks`), asks people questions and for secrets (`fctl autopilot ask`, `apa_…`; a question about one of its sessions, `--session crm#12`, links to it, and the files people attach to their answer, `fctl autopilot answer --attach`, go to that session; those attached to an answer about none stay in its session that asked, which `fctl files get` downloads them from) and takes their notes (`apn_…`). Paused (by people, by fctl, or by itself, done or waiting for people: `pauser`), its `fctl` reaches nothing, so a message to the session it works in reaches that session's agent alone, which can't start or steer sessions: `fctl send --wake "…"` (the web app's *Wake it and send*) resumes it with the message, which goes first, and fctl then wakes it there with what's new; an answer to what it asks waits for a resume too, and `fctl autopilot answer --wake` (`secret`, `decline` too; on its tab, *Wake it and answer*) resumes it with the answer. Its workspace's admins let projects have one. It is token hungry: several sessions at once, kept going on their own, drain a Claude plan's usage quickly, so a fresh build on Pro can reach the five-hour limit, where its sessions pause until the limit resets; Max and Ultra plans are usually enough, as the Autopilot tab and the workspace's setting say. - **Ticket tracker**: where a project's agents read and write tickets: GitHub Issues (of every repository they write to, or one), Linear teams (one or several, each optionally narrowed to one of its Linear projects), or none. In a sandbox, `fctl ticket` reaches it. - **Memory** (`mem_…`): a project's notes for the agents of later sessions. **Retrospective** (`rtr_…`): how a piece of work ended (`completed`, `partial`, `blocked`), what was done, the approach, what got in the way, and what a future agent should know. - **Agent Floor**: the web app's home page: the task box and every active session. diff --git a/web/src/components/project/autopilot.test.tsx b/web/src/components/project/autopilot.test.tsx index 2d634255..cb5d4928 100644 --- a/web/src/components/project/autopilot.test.tsx +++ b/web/src/components/project/autopilot.test.tsx @@ -6,19 +6,31 @@ import type * as G from "@/gen"; import { keys, queryClient } from "@/lib/queries"; import { AutopilotTab } from "./autopilot"; -const { answer, autopilot, autopilotFile, autopilotFiles, autopilotLog, put, resume, toast, upload, wake } = - vi.hoisted(() => ({ - answer: vi.fn(), - autopilot: vi.fn(), - autopilotFile: vi.fn(), - autopilotFiles: vi.fn(), - autopilotLog: vi.fn(), - put: vi.fn(), - resume: vi.fn(), - toast: vi.fn(), - upload: vi.fn(), - wake: vi.fn(), - })); +const { + answer, + autopilot, + autopilotFile, + autopilotFiles, + autopilotLog, + decline, + put, + resume, + toast, + upload, + wake, +} = vi.hoisted(() => ({ + answer: vi.fn(), + decline: vi.fn(), + autopilot: vi.fn(), + autopilotFile: vi.fn(), + autopilotFiles: vi.fn(), + autopilotLog: vi.fn(), + put: vi.fn(), + resume: vi.fn(), + toast: vi.fn(), + upload: vi.fn(), + wake: vi.fn(), +})); // The autopilot, its log and files, answering, uploading, changing, resuming and waking it are // answered; other requests wait. const answered: Record = { @@ -27,6 +39,7 @@ const answered: Record = { autopilotFiles, autopilotLog, answerAutopilot: answer, + declineAutopilot: decline, uploadAttachment: upload, putAutopilot: put, resumeAutopilot: resume, @@ -659,6 +672,249 @@ describe("a project's Autopilot tab", () => { expect(toast).toHaveBeenCalledWith("Resumed, on your subscription: it wakes now"); }); + it("asks whether an answer wakes it while it's paused, and wakes it with the answer first", async () => { + signIn("usr_ada"); + const paused = on({ + state: "paused", + pauser: "itself", + paused_at: Date.now() - 60_000, + paused_reason: "Waiting for the payment provider", + asks: [ + { + id: "apa_1", + kind: "question", + text: "Which payment provider?", + options: ["Stripe", "Adyen"], + status: "open", + created_at: Date.now(), + }, + ], + }); + autopilot.mockResolvedValue(paused); + answer.mockResolvedValue(on()); + queryClient.setQueryData(keys.autopilot("prj_1"), paused); + const page = render(); + await settle(); + expect(page.textContent).toContain( + "It's paused, so it hears your answer once resumed: sending asks whether to wake it now.", + ); + await click("Stripe"); + // Nothing went: it asks first, with waking it focused, so Enter again wakes it. + expect(answer).not.toHaveBeenCalled(); + const card = page.querySelector("[role=alertdialog]"); + expect(card?.textContent).toContain("The autopilot is paused"); + expect(card?.textContent).toContain("It paused itself"); + expect(card?.textContent).toContain("Waiting for the payment provider"); + expect(card?.textContent).toContain( + "It resumes and takes your answer up at once, as what it waited for.", + ); + expect(card?.textContent).toContain("esc back to your answer"); + expect(document.activeElement?.textContent).toContain("Wake it and answer"); + expect(page.querySelector("[aria-pressed=true]")?.textContent).toBe("Stripe"); + await click("Wake it and answerIt resumes and takes your answer up at once, as what it waited for."); + expect(answer).toHaveBeenCalledWith("prj_1", "apa_1", { answer: "Stripe", wake_autopilot: true }); + expect(toast).toHaveBeenCalledWith("Answered, and woke the autopilot: it takes it up now"); + }); + + it("answers a paused autopilot without waking it, or goes back to the answer", async () => { + signIn("usr_bo"); + const paused = on({ + state: "paused", + paused_by: { id: "usr_ada", name: "Ada" }, + pauser: "person", + paused_at: Date.now() - 60_000, + asks: [ + { + id: "apa_1", + kind: "question", + text: "Which payment provider?", + status: "open", + created_at: Date.now(), + }, + ], + }); + autopilot.mockResolvedValue(paused); + answer.mockResolvedValue(paused); + queryClient.setQueryData(keys.autopilot("prj_1"), paused); + const page = render(); + await settle(); + const box = page.querySelector("textarea[aria-label='Your answer']"); + expect(box).toBeTruthy(); + if (!box) return; + const type = (text: string) => + act(() => { + Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")?.set?.call(box, text); + box.dispatchEvent(new Event("input", { bubbles: true })); + }); + const key = (init: KeyboardEventInit, on: Element) => + act(() => { + on.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, ...init })); + }); + type("Stripe"); + await key({ key: "Enter", metaKey: true }, box); + const card = () => page.querySelector("[role=alertdialog]"); + // Waking it would run it on the reader's subscription: the card says so. + expect(card()?.textContent).toContain("Ada paused it"); + expect(card()?.textContent).toContain("From now on it runs on your Claude subscription."); + // Escape goes back to the answer, as it was. + const focused = document.activeElement; + expect(focused?.textContent).toContain("Wake it and answer"); + if (focused) await key({ key: "Escape" }, focused); + expect(card()).toBeNull(); + expect(box.value).toBe("Stripe"); + // An answer changed while the card shows asks afresh, rather than send the one it opened for. + await key({ key: "Enter", metaKey: true }, box); + expect(card()).not.toBeNull(); + type("Adyen"); + expect(card()).toBeNull(); + type("Stripe"); + await key({ key: "Enter", metaKey: true }, box); + await click("Answer without waking itIt stays paused, and hears your answer once someone resumes it."); + expect(answer).toHaveBeenCalledWith("prj_1", "apa_1", { answer: "Stripe" }); + expect(answer.mock.calls[0]?.[2]?.wake_autopilot).toBeUndefined(); + expect(toast).toHaveBeenCalledWith("Answered: it hears once it's resumed"); + }); + + it("keeps the card while an answer goes, and after it failed unless the answer changed meanwhile", async () => { + const paused = on({ + state: "paused", + pauser: "itself", + asks: [{ id: "apa_1", kind: "question", text: "Which?", status: "open", created_at: Date.now() }], + }); + autopilot.mockResolvedValue(paused); + let refuse: (e: Error) => void = () => {}; + answer.mockImplementation(() => new Promise((_, no) => (refuse = no))); + queryClient.setQueryData(keys.autopilot("prj_1"), paused); + const page = render(); + await settle(); + const box = page.querySelector("textarea[aria-label='Your answer']"); + if (!box) throw new Error("no box"); + const type = (text: string) => + act(() => { + Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")?.set?.call(box, text); + box.dispatchEvent(new Event("input", { bubbles: true })); + }); + type("Stripe"); + act(() => { + box.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", metaKey: true, bubbles: true })); + }); + await click("Wake it and answerIt resumes and takes your answer up at once, as what it waited for."); + expect(answer).toHaveBeenCalledTimes(1); + // Typing while it goes leaves the card, which shows how it goes. + type("Stripe, please"); + const card = () => page.querySelector("[role=alertdialog]"); + expect(card()).not.toBeNull(); + await act(async () => refuse(new Error("You appear to be offline."))); + await settle(); + // Failed, the card goes, as the answer changed meanwhile: it would send the old one. + expect(card()).toBeNull(); + expect(box.value).toBe("Stripe, please"); + // Unchanged, a failed answer keeps its card, to try again. + act(() => { + box.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", metaKey: true, bubbles: true })); + }); + await click("Wake it and answerIt resumes and takes your answer up at once, as what it waited for."); + await act(async () => refuse(new Error("You appear to be offline."))); + await settle(); + expect(card()).not.toBeNull(); + }); + + it("says when a wake asked with an answer left it paused", async () => { + const paused = on({ + state: "paused", + pauser: "itself", + asks: [ + { + id: "apa_1", + kind: "question", + text: "Which?", + options: ["Stripe"], + status: "open", + created_at: Date.now(), + }, + ], + }); + autopilot.mockResolvedValue(paused); + answer.mockResolvedValue(on({ state: "paused" })); + queryClient.setQueryData(keys.autopilot("prj_1"), paused); + render(); + await settle(); + await click("Stripe"); + await click("Wake it and answerIt resumes and takes your answer up at once, as what it waited for."); + expect(toast).toHaveBeenCalledWith( + "Answered, but the autopilot is still paused: resume it to wake it", + "error", + ); + }); + + it("declines what a paused autopilot asks with or without waking it", async () => { + const paused = on({ + state: "paused", + pauser: "itself", + asks: [{ id: "apa_1", kind: "question", text: "Which?", status: "open", created_at: Date.now() }], + }); + autopilot.mockResolvedValue(paused); + decline.mockResolvedValue(on()); + queryClient.setQueryData(keys.autopilot("prj_1"), paused); + render(); + await settle(); + await click("Decline…"); + expect(document.body.textContent).toContain("It's paused, so it hears your no"); + expect([...document.body.querySelectorAll("button")].some((b) => b.textContent === "Cancel")).toBe(false); + await click("Wake it and decline"); + expect(decline).toHaveBeenCalledWith("prj_1", "apa_1", { wake_autopilot: true }); + expect(toast).toHaveBeenCalledWith("Declined, and woke the autopilot: it takes it up now"); + }); + + it("asks whether a secret saved while it's paused wakes it", async () => { + const paused = on({ + state: "paused", + pauser: "itself", + asks: [ + { + id: "apa_2", + kind: "secret", + text: "To charge cards in tests", + secret: { name: "STRIPE_KEY", project_id: "prj_1", project_slug: "shop", exists: false }, + status: "open", + created_at: Date.now(), + }, + ], + }); + autopilot.mockResolvedValue(paused); + answer.mockResolvedValue(paused); + queryClient.setQueryData(keys.autopilot("prj_1"), paused); + const page = render(); + await settle(); + const field = page.querySelector("input[aria-label='The value of STRIPE_KEY']"); + if (!field) throw new Error("no field"); + act(() => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(field, "sk_test_1"); + field.dispatchEvent(new Event("input", { bubbles: true })); + }); + await click("Save secret"); + expect(answer).not.toHaveBeenCalled(); + expect(page.querySelector("[role=alertdialog]")?.textContent).toContain( + "The secret is saved either way.", + ); + // Cleared while the card shows, the card goes, and nothing empty is sent. + act(() => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(field, ""); + field.dispatchEvent(new Event("input", { bubbles: true })); + }); + expect(page.querySelector("[role=alertdialog]")).toBeNull(); + act(() => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(field, "sk_test_1"); + field.dispatchEvent(new Event("input", { bubbles: true })); + }); + await click("Save secret"); + await click( + "Save without waking itThe secret is saved, and it stays paused: it hears that it's set once someone resumes it.", + ); + expect(answer).toHaveBeenCalledWith("prj_1", "apa_2", { secret: "sk_test_1" }); + expect(toast).toHaveBeenCalledWith("STRIPE_KEY is set: it hears once it's resumed"); + }); + it("shows its plan's progress, and that it's paused, and by whom", async () => { const paused = on({ state: "paused", diff --git a/web/src/components/project/autopilot.tsx b/web/src/components/project/autopilot.tsx index 0281b6f0..10f867c3 100644 --- a/web/src/components/project/autopilot.tsx +++ b/web/src/components/project/autopilot.tsx @@ -50,10 +50,12 @@ import { } from "lucide-react"; import { type DragEvent, type ReactNode, useEffect, useMemo, useRef, useState } from "react"; import { Markdown } from "@/components/markdown"; +import { asksToWake, PausedHint, sayHeard, WakeOrNot } from "@/components/project/paused-answer"; import { ProjectMark } from "@/components/project/project-icon"; import { AttachButton, DraftTray, DropHint, useAttachments } from "@/components/session/attachments"; import { ScheduleNamed } from "@/components/session/autopilot"; import { ON_RUNNER, useMoveOff } from "@/components/session/move-off"; +import { runsOnWhenWoken } from "@/components/session/paused-pilot"; import { AutopilotIcon, Avatar, @@ -1677,20 +1679,48 @@ function AskDetail({ text }: { text: string }) { function QuestionAnswer({ a, ask }: { a: G.Autopilot; ask: G.AutopilotAsk }) { const [text, setText] = useState(""); - // What is on its way: the option clicked, or what was typed. - const [sending, setSending] = useState<{ value: string }>(); + // What is on its way, and whether it wakes it: the option clicked, or what was typed. + const [sending, setSending] = useState<{ value: string; wake?: boolean }>(); + // While it's paused, what waits for the reader to choose whether it wakes it; `nudge` brings the + // focus back to the card as they send again. + const [choosing, setChoosing] = useState<{ value: string; nudge: number }>(); const [declining, setDeclining] = useState(false); + const box = useRef(null); + const asks = asksToWake(a); // Files go with the answer: to the session it asks about, in a message from you, or else to its // own session that asked, which keeps them for it. Asked about a session that is gone since, // the answer takes words alone. const about = ask.about; const to = about ?? (ask.about_gone ? undefined : ask.session); const files = useAttachments(to ? { session: to.id } : undefined); - const drop = useCardDrop(files.add, !!to); - const send = async (value: string) => { + // What the reader changes in the answer, its words or files, asks afresh as it goes: the card + // would send the answer it opened for. Not while one is on its way, whose card shows how it goes; + // nor as a failed send puts its files back, which the card then sends again. + // Changed while one is on its way, the card goes should it fail, rather than send it again. + const edited = useRef(false); + const changed = () => { + if (sending) edited.current = true; + else setChoosing(undefined); + }; + const addFiles = (added: File[], opts?: { pasted?: boolean }) => { + changed(); + files.add(added, opts); + }; + const removeFile = (key: string) => { + changed(); + files.remove(key); + }; + const drop = useCardDrop(addFiles, !!to); + const send = async (value: string, wake?: boolean) => { const answer = value.trim(); if (sending || (!answer && !files.drafts.length)) return; - setSending({ value }); + // Paused, it asks first whether the answer wakes it. + if (asks && wake === undefined) { + setChoosing((c) => ({ value, nudge: (c?.nudge ?? 0) + 1 })); + return; + } + setSending({ value, wake }); + edited.current = false; let restore: (() => void) | undefined; try { // Waits for files still uploading. @@ -1700,19 +1730,24 @@ function QuestionAnswer({ a, ask }: { a: G.Autopilot; ask: G.AutopilotAsk }) { const x = await api.answerAutopilot(a.project_id, ask.id, { answer: answer || undefined, attachments: attachments.length ? attachments : undefined, + wake_autopilot: wake || undefined, }); for (const url of Object.values(taken.files.previews)) URL.revokeObjectURL(url); + setChoosing(undefined); patched(x); const these = attachments.length === 1 ? "the file" : `the ${attachments.length} files`; - toast( + sayHeard( + x, + !!wake, !attachments.length - ? "Answered: it hears now" + ? "Answered" : about - ? `Sent ${aboutRef(about)} ${these}: it hears now` - : `Answered, with ${these}: it hears now`, + ? `Sent ${aboutRef(about)} ${these}` + : `Answered, with ${these}`, ); } catch (e) { restore?.(); + if (edited.current) setChoosing(undefined); failed(e, "Not answered"); } finally { setSending(undefined); @@ -1730,9 +1765,10 @@ function QuestionAnswer({ a, ask }: { a: G.Autopilot; ask: G.AutopilotAsk }) { type="button" disabled={!!sending} onClick={() => void send(o)} + aria-pressed={choosing ? choosing.value === o : undefined} className={cn( "inline-flex min-h-8 max-w-full items-center gap-2 rounded-full border px-3.5 py-1 text-left text-[13px] transition-[background-color,border-color,color,transform] duration-150 active:scale-[0.97]", - sending?.value === o + (sending ?? choosing)?.value === o ? "border-blue/50 bg-blue-soft text-ink" : "border-line-strong bg-raised text-ink-2 hover:border-blue/45 hover:bg-blue-soft hover:text-ink disabled:opacity-60", )} @@ -1743,7 +1779,7 @@ function QuestionAnswer({ a, ask }: { a: G.Autopilot; ask: G.AutopilotAsk }) { ))} )} - +
{ @@ -1752,8 +1788,12 @@ function QuestionAnswer({ a, ask }: { a: G.Autopilot; ask: G.AutopilotAsk }) { }} >