From 79f528c3c4e3ca1e2b80321287b1ce7fe63eee42 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" Date: Sat, 7 Nov 2026 00:58:43 +0000 Subject: [PATCH 1/4] feat: agents ask people for their input with fctl ask An agent that needs a person to go on asks with fctl ask, offering answers to click (-o), and ends its turn. The call goes through fctl-agent and its host like fctl memory (AgentCall::Ask). SessionDO keeps the session's one open question (Session.question, written through to sessions.question by migration 0051), shows it to viewers and dashboards at once, and drops it when a person's message arrives. Followers hear of it as the turn ends, in a notification of its own: "shop#231 asks you", with the question and its answers. The session page shows the question above the composer with its answers as buttons; the transcript keeps a question_asked notice; the Agent Floor, project pages and the sidebar show sessions that ask in blue; fctl show and fctl sessions print the question. fctl-agent tells Claude about fctl ask where the sandbox's fctl has it, and fake-claude asks with 'ask / / ' (ADR 0078). --- crates/fake-claude/src/main.rs | 43 ++++++ crates/fctl-agent/src/prompt.rs | 114 ++++++++++++--- crates/fctl-agent/src/supervisor.rs | 27 ++++ .../migrations/0051_session_questions.sql | 5 + crates/fctl-control/src/api/calls.rs | 32 +++++ crates/fctl-control/src/delegations.rs | 1 + crates/fctl-control/src/do_session.rs | 64 ++++++++- crates/fctl-control/src/internal.rs | 8 ++ crates/fctl-control/src/model.rs | 124 +++++++++-------- crates/fctl-domain/src/notify.rs | 93 ++++++++++++- crates/fctl-domain/src/validate.rs | 91 ++++++++++++ crates/fctl-proto/src/api.rs | 20 ++- crates/fctl-proto/src/event.rs | 8 +- crates/fctl-proto/src/session.rs | 20 +++ crates/fctl/src/cmd/ask.rs | 131 ++++++++++++++++++ crates/fctl/src/cmd/mod.rs | 1 + crates/fctl/src/cmd/sessions.rs | 27 ++++ crates/fctl/src/main.rs | 11 ++ .../0078-agents-ask-people-with-fctl-ask.md | 57 ++++++++ docs/adr/README.md | 1 + docs/agents.md | 1 + docs/architecture.md | 30 +++- docs/cli.md | 2 +- docs/development.md | 5 +- docs/llms.txt | 4 +- web/src/components/session/question.test.tsx | 60 ++++++++ web/src/components/session/question.tsx | 91 ++++++++++++ web/src/components/session/row.tsx | 10 +- web/src/components/session/transcript.tsx | 33 +++++ web/src/components/shell/app-shell.tsx | 10 +- web/src/gen/Notice.ts | 11 +- web/src/gen/Session.ts | 9 +- web/src/gen/SessionQuestion.ts | 16 +++ web/src/gen/index.ts | 1 + web/src/routes/session.tsx | 18 +++ 35 files changed, 1076 insertions(+), 103 deletions(-) create mode 100644 crates/fctl-control/migrations/0051_session_questions.sql create mode 100644 crates/fctl/src/cmd/ask.rs create mode 100644 docs/adr/0078-agents-ask-people-with-fctl-ask.md create mode 100644 web/src/components/session/question.test.tsx create mode 100644 web/src/components/session/question.tsx create mode 100644 web/src/gen/SessionQuestion.ts diff --git a/crates/fake-claude/src/main.rs b/crates/fake-claude/src/main.rs index 1355ca8c..585ea6c7 100644 --- a/crates/fake-claude/src/main.rs +++ b/crates/fake-claude/src/main.rs @@ -29,6 +29,7 @@ //! | `look` | reads an image with `Read`, as agents look at a screenshot of what they changed: a small PNG it draws, or each image at the paths after the word (`look /tmp/before.png /tmp/after.png`), one call after another; the result holds the image, as Claude Code's does | //! | `remember ` | adds `` (to the end of its line) to the project's memory with `fctl memory add`, as agents do | //! | `recall` | lists the project's memory with `fctl memory` | +//! | `ask ` | asks the people who follow the session `` (to the end of its line) with `fctl ask`, offering the answers after each ` / ` in it to click (`ask Ship it today? / Yes / Not yet`), and ends its turn, as agents do when they need a person's input | //! | a line that starts with `fctl ticket` | runs it, as agents read and write their project's tickets (`fctl ticket view ENG-1`, `fctl ticket comment ENG-1 "On it"`) | //! | `printenv` | shows the `CLAUDE_CODE_…` variables it got, its Claude token among them, in a `Bash` call, as an agent that looks at its environment does, then says the token back in pieces of five characters, as Claude streams what it writes (the host keeps the token out of both) | //! | `retro` | records a retrospective of the turn's work with `fctl retro`, as agents do when they finish a piece of work: completed, or `partial` or `blocked` when the message says so | @@ -1412,6 +1413,18 @@ impl Session { if says(&lower, "recall") { self.fctl(&["memory"], "Read the project's memory"); } + if let Some(asked) = word_at_start(text, "ask ") { + let asked = asked.unwrap_or_else(|| "Shall I go on? / Yes / Not yet".into()); + let mut parts = asked.split(" / ").map(str::trim).filter(|p| !p.is_empty()); + let question = parts.next().unwrap_or("Shall I go on?").to_owned(); + let mut args = vec!["ask".to_owned(), question]; + for option in parts { + args.push("-o".into()); + args.push(option.to_owned()); + } + let args: Vec<&str> = args.iter().map(String::as_str).collect(); + self.fctl(&args, "Ask the people who follow the session"); + } // Lines that are `fctl ticket` commands run as they are, as agents // reach their project's tracker. for line in text @@ -1816,6 +1829,22 @@ fn after_word(text: &str, word: &str) -> Option> { Some((!rest.is_empty()).then(|| rest.to_owned())) } +/// What follows `word` where it starts a word (not "task " for "ask "), to +/// the end of its line, as [`after_word`] gives it. +fn word_at_start(text: &str, word: &str) -> Option> { + let at = text.char_indices().find_map(|(i, _)| { + let starts = text[..i] + .chars() + .next_back() + .is_none_or(|c| !c.is_alphanumeric()); + text.get(i..i + word.len()) + .filter(|w| starts && w.eq_ignore_ascii_case(word)) + .map(|_| i + word.len()) + })?; + let rest = text[at..].lines().next().unwrap_or_default().trim(); + Some((!rest.is_empty()).then(|| rest.to_owned())) +} + /// The title after `rename` (any case), to the end of its line. fn rename_to(text: &str) -> Option { let at = text.char_indices().find_map(|(i, _)| { @@ -2017,6 +2046,20 @@ fn main() { #[cfg(test)] mod tests { + + #[test] + fn asks_only_where_a_word_starts() { + assert_eq!( + super::word_at_start("Please ask Ship it? / Yes / No", "ask "), + Some(Some("Ship it? / Yes / No".into())) + ); + assert_eq!(super::word_at_start("Write a task list", "ask "), None); + assert_eq!(super::word_at_start("ask", "ask "), None); + assert_eq!( + super::word_at_start("(ask why)", "ask "), + Some(Some("why)".into())) + ); + } use super::{ CONTEXT_START, CONTEXT_WINDOW, adler32, asks_for_limit, background_for, context_for, crc32, effort_in, explorations, finding_titles, first_added_line, follow_up_parts, is_findings, diff --git a/crates/fctl-agent/src/prompt.rs b/crates/fctl-agent/src/prompt.rs index b43222f7..d0ba59db 100644 --- a/crates/fctl-agent/src/prompt.rs +++ b/crates/fctl-agent/src/prompt.rs @@ -282,7 +282,8 @@ screenshot shows. /// `paths` say where the other repositories go; `sandbox` what the sandbox /// is limited to, when its driver limits it; `tickets_cli` whether the -/// sandbox's fctl has `fctl ticket`, for a project whose tracker it reaches. +/// sandbox's fctl has `fctl ticket`, for a project whose tracker it reaches; +/// `asks_cli` whether it has `fctl ask`. pub fn system_prompt( spec: &SessionSpec, workdir: &str, @@ -290,6 +291,7 @@ pub fn system_prompt( sandbox: Option, cache: Option<&Ready>, tickets_cli: bool, + asks_cli: bool, ) -> String { let mut s = String::new(); s.push_str("You are running as an autonomous agent in fctl, a software factory. "); @@ -422,7 +424,11 @@ pub fn system_prompt( } s.push_str(&people(spec)); s.push_str("- Never print, log or commit secrets. Project secrets are available as environment variables.\n"); - s.push_str("- If you are blocked on a decision only a person can make, say so plainly and stop; someone will answer.\n"); + if asks_cli { + s.push_str("- When you need a person's input to go on (a decision only they can make, access, an answer), ask with `fctl ask \"…\"`, with `-o \"…\"` for each answer they could give, and end your turn: the people who follow the session see the question with those answers to click, and hear of it. Their answer comes as a message. Ask one question at a time, and only what you can't find out yourself.\n"); + } else { + s.push_str("- If you are blocked on a decision only a person can make, say so plainly and stop; someone will answer.\n"); + } let idle = tasks::idle_timeout(spec); s.push_str(&format!( "- When your turn ends, the session waits for a message, and after {} without one it stops, along with everything still running in the sandbox. Background work you start (a shell command with `run_in_background`, a subagent, a Monitor) keeps the session up while it runs, for up to {} after your turn ends: you can end your turn to wait for it, and you get its result in a new turn. Stop background processes you no longer need, like a dev server, so that the session can stop.\n", @@ -952,7 +958,7 @@ mod tests { "/var/cache/fctl/ms-playwright".into(), )], }; - let text = system_prompt(&spec(), "/work", &paths(), None, Some(&cache), false); + let text = system_prompt(&spec(), "/work", &paths(), None, Some(&cache), false, false); assert!( text.contains("- Package managers keep their downloads in /var/cache/fctl ($FCTL_CACHE_DIR), which this project's sessions on this runner share: npm, pnpm, Yarn, Bun, Cargo, uv, pip, Go and Playwright find there what earlier sessions fetched. Leave it in place; the runner empties it once it takes more than 10 GiB.\n"), "{text}" @@ -960,13 +966,13 @@ mod tests { // With an image that comes with browsers, as the default one does, // Playwright keeps its own. cache.env.clear(); - let text = system_prompt(&spec(), "/work", &paths(), None, Some(&cache), false); + let text = system_prompt(&spec(), "/work", &paths(), None, Some(&cache), false, false); assert!( text.contains("share: npm, pnpm, Yarn, Bun, Cargo, uv, pip and Go find there what earlier sessions fetched."), "{text}" ); assert!( - !system_prompt(&spec(), "/work", &paths(), None, None, false) + !system_prompt(&spec(), "/work", &paths(), None, None, false, false) .contains("$FCTL_CACHE_DIR") ); } @@ -977,11 +983,11 @@ mod tests { cpus: 4, memory_mb: 8192, }; - let text = system_prompt(&spec(), "/work", &paths(), Some(size), None, false); + let text = system_prompt(&spec(), "/work", &paths(), Some(size), None, false, false); assert!(text.contains("This sandbox has 4 CPUs and 8 GiB of memory")); assert!(text.contains("`make -j4`")); assert!( - !system_prompt(&spec(), "/work", &paths(), None, None, false) + !system_prompt(&spec(), "/work", &paths(), None, None, false, false) .contains("This sandbox has") ); assert_eq!( @@ -1003,13 +1009,14 @@ mod tests { None, None, false, + false, ); assert!(text.contains("after 10 minutes without one it stops")); assert!(text.contains( "for up to an hour after your turn ends: you can end your turn to wait for it" )); // A project that waits longer for messages waits as long for background work. - let text = system_prompt(&spec(), "/work", &paths(), None, None, false); + let text = system_prompt(&spec(), "/work", &paths(), None, None, false, false); assert!(text.contains("after 2 hours without one it stops")); assert!(text.contains("for up to 2 hours after your turn ends")); } @@ -1099,6 +1106,7 @@ mod tests { None, None, false, + false, ); assert!(text.contains("The repository acme/app is cloned at /home/agent/workspace")); assert!(text.contains( @@ -1129,6 +1137,7 @@ mod tests { None, None, false, + false, ); assert!(text.contains("into /home/agent/repos// (for example `git clone https://github.com/acme/lib /home/agent/repos/acme/lib`)")); assert!(text.contains(" - acme/lib (read and write)\n")); @@ -1150,6 +1159,7 @@ mod tests { None, None, false, + false, ); assert!(text.contains(" - any repository of acme (read only)\n")); assert!( @@ -1166,7 +1176,15 @@ mod tests { let mut spec = spec_with(serde_json::json!([{ "owner": "acme", "name": "lib", "access": "write" }])); spec.project.repo = None; - let text = system_prompt(&spec, "/home/agent/workspace", &paths(), None, None, false); + let text = system_prompt( + &spec, + "/home/agent/workspace", + &paths(), + None, + None, + false, + false, + ); assert!(text.contains( "- Your working directory is /home/agent/workspace, an empty git repository.\n" )); @@ -1177,7 +1195,15 @@ mod tests { assert!(text.contains("For another pull request, make its branch")); // Nowhere to open one. spec.project.repos = None; - let text = system_prompt(&spec, "/home/agent/workspace", &paths(), None, None, false); + let text = system_prompt( + &spec, + "/home/agent/workspace", + &paths(), + None, + None, + false, + false, + ); assert!(!text.contains("For another pull request")); } @@ -1201,6 +1227,7 @@ mod tests { None, None, false, + false, ); assert!(text.contains(" - acme/lib (read and comment)\n")); assert!(text.contains(" - acme/docs (read only)\n")); @@ -1219,7 +1246,15 @@ mod tests { let mut spec = spec_with(serde_json::Value::Null); spec.project.settings.pull_request_descriptions = level; spec.project.settings.instructions = Some("Run `npm test` before you commit.".into()); - system_prompt(&spec, "/home/agent/workspace", &paths(), None, None, false) + system_prompt( + &spec, + "/home/agent/workspace", + &paths(), + None, + None, + false, + false, + ) } #[test] @@ -1293,6 +1328,7 @@ mod tests { None, None, false, + false, ); // After how to describe pull requests, the tracker's lines, then // fctl's defaults, which agree with them; then the project's words. @@ -1316,6 +1352,7 @@ mod tests { None, None, false, + false, ); assert!(text.contains(&format!( "\n## Pull requests and issues\n\n- This project tracks its work in GitHub issues of acme/app.\n\n{OWN_RULES}Never write `Fixes`: we close issues as we deploy.\n" @@ -1331,6 +1368,7 @@ mod tests { None, None, false, + false, ); assert!(text.contains( "\n## Pull requests and issues\n\nNever write `Fixes`: we close issues as we deploy.\n" @@ -1344,6 +1382,7 @@ mod tests { None, None, false, + false, ); assert!(!text.contains("## Pull requests and issues")); assert!(text.contains("- This project tracks its work in GitHub issues of acme/app.\n")); @@ -1354,7 +1393,7 @@ mod tests { with_access(GithubAccess::Comment), with_access(GithubAccess::Read), ] { - let text = system_prompt(&none, "/work", &paths(), None, None, false); + let text = system_prompt(&none, "/work", &paths(), None, None, false, false); assert!(!text.contains("## Pull requests and issues")); assert!(!text.contains("`Refs #12`")); } @@ -1365,7 +1404,15 @@ mod tests { // People can still ask for one where the project doesn't. let mut asked = spec_with(serde_json::Value::Null); asked.project.settings.auto_pull_request = false; - let text = system_prompt(&asked, "/home/agent/workspace", &paths(), None, None, false); + let text = system_prompt( + &asked, + "/home/agent/workspace", + &paths(), + None, + None, + false, + false, + ); assert!(!text.contains("When the task is complete")); assert!(text.contains("## Pull request descriptions")); // Without a repository to push to, or the right to push, there are none. @@ -1374,7 +1421,7 @@ mod tests { with_access(GithubAccess::Comment), with_access(GithubAccess::Read), ] { - let text = system_prompt(&none, "/work", &paths(), None, None, false); + let text = system_prompt(&none, "/work", &paths(), None, None, false, false); assert!(!text.contains("Pull request descriptions")); assert!(!text.contains("[fctl session]")); } @@ -1391,7 +1438,15 @@ mod tests { ticket: None, instructions: "- This project tracks its work in GitHub issues of acme/app.\n".into(), }); - let text = system_prompt(&spec, "/home/agent/workspace", &paths(), None, None, true); + let text = system_prompt( + &spec, + "/home/agent/workspace", + &paths(), + None, + None, + true, + false, + ); assert!(text.contains(" - acme/lib (read only)\n")); assert!(text.contains("In this session you triage")); assert!(text.contains("all you write is labels and comments on the project's tickets")); @@ -1411,7 +1466,15 @@ mod tests { ticket: None, instructions: String::new(), }); - let text = system_prompt(&spec, "/home/agent/workspace", &paths(), None, None, true); + let text = system_prompt( + &spec, + "/home/agent/workspace", + &paths(), + None, + None, + true, + false, + ); assert!(text.contains("In this session you only read on GitHub")); assert!(!text.contains("you triage")); assert!(github_line(GithubAccess::Triage, false).is_some_and(|l| l.contains("only reads"))); @@ -1426,6 +1489,7 @@ mod tests { None, None, false, + false, ); assert!(text.contains(" - acme/lib (read only)\n")); assert!(text.contains("In this session you only read on GitHub")); @@ -1440,7 +1504,7 @@ mod tests { ..spec() }; assert!( - !system_prompt(&none, "/work", &paths(), None, None, false) + !system_prompt(&none, "/work", &paths(), None, None, false, false) .contains("only read on GitHub") ); } @@ -1703,7 +1767,7 @@ mod tests { #[test] fn says_who_started_the_session_and_what_to_call_them() { - let text = system_prompt(&spec(), "/work", &paths(), None, None, false); + let text = system_prompt(&spec(), "/work", &paths(), None, None, false, false); assert!(text.contains( "- Messages from people other than the session's starter begin with their name.\n" )); @@ -1711,13 +1775,13 @@ mod tests { let mut carl = spec(); carl.author.name = "Carl Oscar Aaro".into(); carl.author_called = Some("Carl Oscar".into()); - let text = system_prompt(&carl, "/work", &paths(), None, None, false); + let text = system_prompt(&carl, "/work", &paths(), None, None, false, false); assert!(text.contains( "- Carl Oscar Aaro started this session. Call them Carl Oscar, the whole name rather than a part of it, when you write to them or about them. Messages from other people begin with their name and what to call them.\n" )); assert!(!text.contains("the session's starter")); carl.author_called = Some("Bob".into()); - let text = system_prompt(&carl, "/work", &paths(), None, None, false); + let text = system_prompt(&carl, "/work", &paths(), None, None, false, false); assert!(text.contains( "- Carl Oscar Aaro started this session. Call them Bob when you write to them or about them." )); @@ -1785,4 +1849,14 @@ mod tests { assert!(REVIEW_AGENTS_MD.contains("fctl review submit review.json")); assert!(REVIEW_AGENTS_MD.contains("fctl review summarize summary.json")); } + + #[test] + fn agents_ask_people_with_fctl_ask_where_their_sandbox_has_it() { + let asks = system_prompt(&spec(), "/work", &paths(), None, None, false, true); + assert!(asks.contains("ask with `fctl ask"), "{asks}"); + assert!(!asks.contains("say so plainly and stop")); + let old = system_prompt(&spec(), "/work", &paths(), None, None, false, false); + assert!(!old.contains("fctl ask")); + assert!(old.contains("say so plainly and stop")); + } } diff --git a/crates/fctl-agent/src/supervisor.rs b/crates/fctl-agent/src/supervisor.rs index 5ba727c5..394b9f1b 100644 --- a/crates/fctl-agent/src/supervisor.rs +++ b/crates/fctl-agent/src/supervisor.rs @@ -622,6 +622,7 @@ impl Supervisor { review: None, summarized: None, follow_up: None, + question: None, })); } @@ -1570,6 +1571,9 @@ impl Supervisor { } _ => false, }; + // `fctl ask` asks people, where the sandbox's fctl has it. + let asks_cli = + spec.review.is_none() && self.session_socket.is_some() && fctl_can(&paths, "ask").await; let system = match &spec.review { Some(review) => { let previous_here = match review.previous_sha.as_deref() { @@ -1593,6 +1597,7 @@ impl Supervisor { config.sandbox, self.cache.as_ref(), tickets_cli, + asks_cli, ), }; let launch = LaunchSpec { @@ -2651,6 +2656,7 @@ fn published_notice(file: &PublishedFile, now: i64) -> Notice { review: None, summarized: None, follow_up: None, + question: None, } } @@ -2673,6 +2679,7 @@ fn kept_notices(answer: &AgentAnswer) -> Vec { review: None, summarized: None, follow_up: None, + question: None, }; match answer { AgentAnswer::Memories { .. } | AgentAnswer::Retrospectives { .. } => vec![], @@ -2725,6 +2732,26 @@ fn kept_notices(answer: &AgentAnswer) -> Vec { }], // The control plane adds what fctl did in the tracker itself. AgentAnswer::Ticket { .. } => vec![], + // What the agent asked people stays in the transcript, after the + // question itself is answered. + AgentAnswer::Asked { question: Some(q) } => vec![Notice { + question: Some(q.clone()), + ..notice("question_asked", asked_message(q)) + }], + AgentAnswer::Asked { question: None } => vec![notice( + "question_withdrawn", + "The agent took its question back.".into(), + )], + } +} + +/// What the transcript says the agent asked, for clients from before the +/// notice's `question`: the question, and the answers it offered. +fn asked_message(q: &fctl_proto::session::SessionQuestion) -> String { + if q.options.is_empty() { + format!("Asked: {}", q.text) + } else { + format!("Asked: {} ({})", q.text, q.options.join(" / ")) } } diff --git a/crates/fctl-control/migrations/0051_session_questions.sql b/crates/fctl-control/migrations/0051_session_questions.sql new file mode 100644 index 00000000..c26eb7c9 --- /dev/null +++ b/crates/fctl-control/migrations/0051_session_questions.sql @@ -0,0 +1,5 @@ +-- What a session's agent asked the people who follow it (fctl#850, `fctl +-- ask`), as JSON (`SessionQuestion`), until a person's message answers it. +-- NULL: it asks nothing. SessionDO keeps it and writes it through, so lists +-- show it without opening the session. +ALTER TABLE sessions ADD COLUMN question TEXT; diff --git a/crates/fctl-control/src/api/calls.rs b/crates/fctl-control/src/api/calls.rs index a3b5dd08..a36b8a94 100644 --- a/crates/fctl-control/src/api/calls.rs +++ b/crates/fctl-control/src/api/calls.rs @@ -258,6 +258,9 @@ pub async fn runner_call( AgentCall::Ticket { request } => AgentAnswer::Ticket { answer: crate::tickets::call(ctx, &session, request).await?, }, + AgentCall::Ask { question, options } => AgentAnswer::Asked { + question: ask(ctx, &session, &question, &options).await?, + }, AgentCall::SubmitReview { summary, findings, @@ -333,3 +336,32 @@ async fn resolve_thread( pull_request_url: found.pull_request_url, }) } + +/// `fctl ask`: the session's agent asks the people who follow it for their +/// input, or takes its question back. SessionDO keeps it, shows it where +/// people follow the session, and tells them as the turn ends (`crate:: +/// notify`); a person's next message answers it. A review agent waits for +/// nobody, so it asks nothing. +async fn ask( + ctx: &Ctx, + session: &RunnerSession, + text: &str, + options: &[String], +) -> AppResult> { + if session.review { + return Err(forbidden( + "Review agents ask nobody: say what you need in the review.", + )); + } + let question = fctl_domain::validate::question(text, options)?.map(|(text, options)| { + fctl_proto::session::SessionQuestion { + text, + options, + asked_at: ctx.now, + } + }); + let stub = crate::internal::session_stub(&ctx.env, &session.id)?; + let asked: crate::internal::Ask = + crate::internal::post(&stub, "/ask", &crate::internal::Ask { question }).await?; + Ok(asked.question) +} diff --git a/crates/fctl-control/src/delegations.rs b/crates/fctl-control/src/delegations.rs index 38e39ff7..2fe2478f 100644 --- a/crates/fctl-control/src/delegations.rs +++ b/crates/fctl-control/src/delegations.rs @@ -1392,6 +1392,7 @@ pub async fn notice( review: None, summarized: None, follow_up: None, + question: None, ticket: Some(ticket), }; let sent = async { diff --git a/crates/fctl-control/src/do_session.rs b/crates/fctl-control/src/do_session.rs index 1983b257..e117c23f 100644 --- a/crates/fctl-control/src/do_session.rs +++ b/crates/fctl-control/src/do_session.rs @@ -28,7 +28,9 @@ use fctl_proto::event::{ UserMessage, }; use fctl_proto::runner::RunnerDisk; -use fctl_proto::session::{PullRequestRef, RepoRef, Session, SessionRole, SessionStatus, UserRef}; +use fctl_proto::session::{ + PullRequestRef, RepoRef, Session, SessionQuestion, SessionRole, SessionStatus, UserRef, +}; use fctl_proto::uplink::{ AgentUnreachable, Delivery, DeliveryKind, FEATURE_ATTACHMENTS, FEATURE_SETTINGS, SandboxPaused, SessionState, UplinkDown, UplinkUp, @@ -343,6 +345,10 @@ impl DurableObject for SessionObject { Err(e) => Err(api_err(ErrorCode::BadRequest, &e.to_string())), } } + (worker::Method::Post, "/ask") => match req.json::().await { + Ok(b) => self.ask(b).await.map(|a| serde_json::json!(a)), + Err(e) => Err(api_err(ErrorCode::BadRequest, &e.to_string())), + }, (worker::Method::Post, "/drain-stop") => match req.json::().await { Ok(b) => self.drain_stop(b).await.map(|d| serde_json::json!(d)), Err(e) => Err(api_err(ErrorCode::BadRequest, &e.to_string())), @@ -894,6 +900,11 @@ impl SessionObject { self.end_reviews_in_a_row(now).await; self.delete_meta(CHECKS_IN_A_ROW); self.delete_meta(CONFLICTS_IN_A_ROW); + // It answers the agent's question. + if let Some(mut s) = self.summary().filter(|s| s.question.is_some()) { + s.question = None; + self.publish(&mut s, now).await; + } } if let Some(json) = self.append(now, &b.event, None) { self.broadcast_events(&[json]); @@ -1013,6 +1024,7 @@ impl SessionObject { review: None, summarized: None, follow_up: None, + question: None, }; if let Some(json) = self.append(now, &EventBody::Notice(notice), None) { self.broadcast_events(&[json]); @@ -1142,6 +1154,7 @@ impl SessionObject { review: None, summarized: None, follow_up: None, + question: None, }; if let Some(json) = self.append(now, &EventBody::Notice(notice), None) { self.broadcast_events(&[json]); @@ -1409,6 +1422,7 @@ impl SessionObject { events: f.events.iter().filter(|e| kind.of(e)).cloned().collect(), ..f.clone() }), + question: None, }; if let Some(json) = self.append(now, &EventBody::Notice(notice), None) { self.broadcast_events(&[json]); @@ -1510,6 +1524,27 @@ impl SessionObject { /// message for a while and none is on its way to the agent. Checking and /// marking it stopping happen together, so a message that comes after /// waits for the next run (`deliver`), which starts on the same runner. + /// The agent asks the people who follow the session something (`fctl + /// ask`), or takes its question back. Viewers and dashboards see it at + /// once; followers hear of it as the turn ends, or now when it already + /// has. A person's next message answers it (`deliver`). + async fn ask(&self, b: internal::Ask) -> std::result::Result { + let now = now_ms(); + let Some(mut s) = self.summary() else { + return Err(api_err(ErrorCode::NotFound, "Session not initialized")); + }; + if s.question != b.question { + s.question = b.question; + self.publish(&mut s, now).await; + if s.question.is_some() && matches!(s.status, SessionStatus::Idle) { + self.notify(&s, notify::Kind::Asking, now); + } + } + Ok(internal::Ask { + question: s.question, + }) + } + async fn drain_stop(&self, b: DrainStop) -> std::result::Result { let now = now_ms(); let meta_ms = |key: &str| self.meta(key).and_then(|v| v.parse::().ok()); @@ -1618,6 +1653,7 @@ impl SessionObject { review: None, summarized: None, follow_up: None, + question: None, }; if let Some(json) = self.append(now, &EventBody::Notice(notice), None) { self.broadcast_events(&[json]); @@ -1687,6 +1723,7 @@ impl SessionObject { review: None, summarized: None, follow_up: None, + question: None, }; if let Some(json) = self.append(now, &EventBody::Notice(notice), None) { self.broadcast_events(&[json]); @@ -1804,6 +1841,7 @@ impl SessionObject { review: None, summarized: None, follow_up: None, + question: None, }; if let Some(json) = self.append(now, &EventBody::Notice(notice), None) { self.broadcast_events(&[json]); @@ -2628,6 +2666,7 @@ impl SessionObject { review: None, summarized: None, follow_up: None, + question: None, }; if let Some(json) = self.append(now, &EventBody::Notice(notice), None) { self.broadcast_events(&[json]); @@ -3406,6 +3445,8 @@ impl SessionObject { } }); } + // Asked once the turn ended, whose end Linear heard of. + notify::Kind::Asking => {} notify::Kind::Paused | notify::Kind::Failed => { let status = s.status; let reason = s.status_reason.clone(); @@ -3480,15 +3521,21 @@ impl SessionObject { fn notify(&self, s: &Session, kind: notify::Kind, now: i64) { self.report_to_linear(s, kind); let mut except = self.watching(); - let detail = match kind { + let asked = |q: &SessionQuestion| notify::question_detail(&q.text, &q.options); + let (kind, detail) = match kind { notify::Kind::Waiting => { // Whoever interrupted the turn knows that it ended. except.extend(self.meta("interrupted_by")); self.delete_meta("interrupted_by"); - self.meta("last_reply") + // A turn that ends with a question open asks it. + match &s.question { + Some(q) => (notify::Kind::Asking, Some(asked(q))), + None => (kind, self.meta("last_reply")), + } } - notify::Kind::Paused => None, - notify::Kind::Failed => s.status_reason.clone(), + notify::Kind::Asking => (kind, s.question.as_ref().map(asked)), + notify::Kind::Paused => (kind, None), + notify::Kind::Failed => (kind, s.status_reason.clone()), }; let event = notify::Event { session_id: s.id.clone(), @@ -4126,11 +4173,15 @@ impl SessionObject { let prs = (!s.pull_requests.is_empty()) .then(|| serde_json::to_string(&s.pull_requests).ok()) .flatten(); + let question = s + .question + .as_ref() + .and_then(|q| serde_json::to_string(q).ok()); let res = crate::db::q( &db, "UPDATE sessions SET title = ?, description = ?, status = ?, status_reason = ?, resume_at = ?, model = COALESCE(?, model), \ claude_effort = ?, branch = COALESCE(?, branch), remote_control = ?, stats = ?, pr_number = ?, pr_url = ?, pr_title = ?, pr_state = ?, \ - pull_requests = ?, updated_at = ?, last_activity_at = ?, started_at = COALESCE(started_at, ?), ended_at = ? WHERE id = ?", + pull_requests = ?, question = ?, updated_at = ?, last_activity_at = ?, started_at = COALESCE(started_at, ?), ended_at = ? WHERE id = ?", &[ crate::db::s(&s.title), crate::db::os(s.description.as_deref()), @@ -4147,6 +4198,7 @@ impl SessionObject { crate::db::os(pr.as_ref().and_then(|p| p.title.as_deref())), crate::db::os(pr.as_ref().and_then(|p| p.state.as_deref())), crate::db::os(prs.as_deref()), + crate::db::os(question.as_deref()), crate::db::n(s.updated_at), crate::db::on(s.last_activity_at), crate::db::on(s.started_at), diff --git a/crates/fctl-control/src/internal.rs b/crates/fctl-control/src/internal.rs index d0c88ee9..0019b278 100644 --- a/crates/fctl-control/src/internal.rs +++ b/crates/fctl-control/src/internal.rs @@ -85,6 +85,14 @@ pub struct ControlState { pub disk: Option, } +/// The question a session's agent asks people now (`/ask`, from `fctl ask` +/// through `crate::api::calls`): none takes back the one it asked. +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +pub struct Ask { + #[serde(default)] + pub question: Option, +} + /// What the session's page shows of its runner's disk from now on. #[derive(Clone, Debug, Default, Serialize, Deserialize)] pub struct DiskNews { diff --git a/crates/fctl-control/src/model.rs b/crates/fctl-control/src/model.rs index 6d803519..60d8009e 100644 --- a/crates/fctl-control/src/model.rs +++ b/crates/fctl-control/src/model.rs @@ -685,6 +685,9 @@ pub struct SessionRow { /// The ticket it started from (JSON: `crate::delegations::TicketColumn`). #[serde(default)] pub ticket: Option, + /// Its agent's open question, as JSON (`SessionQuestion`). + #[serde(default)] + pub question: Option, #[serde(flatten)] pub workspace: WorkspaceCols, } @@ -760,66 +763,69 @@ impl SessionRow { } pub fn to_session(&self, role: Option) -> Session { - let mut s = Session { - id: self.session_id(), - project_id: ProjectId(self.project_id.clone()), - project_slug: self.project_slug.clone(), - workspace: self.workspace.to_ref(), - number: self.number.max(0) as u32, - title: self.title.clone(), - description: self.description.clone(), - status: self.status(), - status_reason: self.status_reason.clone(), - resume_at: self.resume_at, - created_by: self.creator_ref(), - created_at: self.created_at, - updated_at: self.updated_at, - started_at: self.started_at, - ended_at: self.ended_at, - last_activity_at: self.last_activity_at, - branch: self.branch.clone(), - base_branch: self.base_branch.clone(), - pull_request: match (self.pr_number, &self.pr_url) { - (Some(number), Some(url)) => Some(PullRequestRef { - number: number.max(0) as u64, - url: url.clone(), - title: self.pr_title.clone(), - state: self.pr_state.clone(), - ..Default::default() + let mut s = + Session { + id: self.session_id(), + project_id: ProjectId(self.project_id.clone()), + project_slug: self.project_slug.clone(), + workspace: self.workspace.to_ref(), + number: self.number.max(0) as u32, + title: self.title.clone(), + description: self.description.clone(), + status: self.status(), + status_reason: self.status_reason.clone(), + resume_at: self.resume_at, + created_by: self.creator_ref(), + created_at: self.created_at, + updated_at: self.updated_at, + started_at: self.started_at, + ended_at: self.ended_at, + last_activity_at: self.last_activity_at, + branch: self.branch.clone(), + base_branch: self.base_branch.clone(), + pull_request: match (self.pr_number, &self.pr_url) { + (Some(number), Some(url)) => Some(PullRequestRef { + number: number.max(0) as u64, + url: url.clone(), + title: self.pr_title.clone(), + state: self.pr_state.clone(), + ..Default::default() + }), + _ => None, + }, + pull_requests: self + .pull_requests + .as_deref() + .and_then(|j| serde_json::from_str::>(j).ok()) + .unwrap_or_default(), + runner: match (&self.runner_id, &self.runner_name) { + (Some(id), Some(name)) => Some(RunnerRef { + id: RunnerId(id.clone()), + name: name.clone(), + }), + _ => None, + }, + model: self.model.clone(), + effort: self.claude_effort.clone(), + github_access: Some(self.github_access()), + github_issues: self.github_issues.then_some(true), + remote_control: self + .remote_control + .as_deref() + .and_then(|s| serde_json::from_str::(s).ok()), + stats: serde_json::from_str::(&self.stats).unwrap_or_default(), + role, + archived: self.archived, + following: Some(self.following), + review: self.review(), + schedule: self.schedule(), + ticket: self.ticket.as_deref().and_then(|j| { + serde_json::from_str::(j).ok() }), - _ => None, - }, - pull_requests: self - .pull_requests - .as_deref() - .and_then(|j| serde_json::from_str::>(j).ok()) - .unwrap_or_default(), - runner: match (&self.runner_id, &self.runner_name) { - (Some(id), Some(name)) => Some(RunnerRef { - id: RunnerId(id.clone()), - name: name.clone(), + question: self.question.as_deref().and_then(|j| { + serde_json::from_str::(j).ok() }), - _ => None, - }, - model: self.model.clone(), - effort: self.claude_effort.clone(), - github_access: Some(self.github_access()), - github_issues: self.github_issues.then_some(true), - remote_control: self - .remote_control - .as_deref() - .and_then(|s| serde_json::from_str::(s).ok()), - stats: serde_json::from_str::(&self.stats).unwrap_or_default(), - role, - archived: self.archived, - following: Some(self.following), - review: self.review(), - schedule: self.schedule(), - ticket: self - .ticket - .as_deref() - .and_then(|j| serde_json::from_str::(j).ok()), - }; + }; fctl_domain::pulls::backfill(&mut s); s } @@ -837,7 +843,7 @@ pub const SESSION_SELECT: &str = "SELECT s.id, s.project_id, p.slug AS project_s s.created_at, s.updated_at, s.started_at, s.ended_at, s.last_activity_at, \ m.role AS member_role, sh.role AS share_role, f.user_id IS NOT NULL AS following, \ rv.repo AS review_repo, rv.number AS review_number, rv.url AS review_pr_url, rv.title AS review_title, \ - rv.head_sha AS review_sha, s.schedule_id, sc.name AS schedule_name, s.ticket, \ + rv.head_sha AS review_sha, s.schedule_id, sc.name AS schedule_name, s.ticket, s.question, \ w.id AS workspace_id, w.slug AS workspace_slug, w.name AS workspace_name, w.color AS workspace_color, \ w.avatar_updated_at AS workspace_avatar_at, w.base_role AS workspace_base_role, \ w.require_two_factor AS workspace_two_factor, wm.role AS workspace_role \ diff --git a/crates/fctl-domain/src/notify.rs b/crates/fctl-domain/src/notify.rs index 5dfabc72..9c472c54 100644 --- a/crates/fctl-domain/src/notify.rs +++ b/crates/fctl-domain/src/notify.rs @@ -28,6 +28,10 @@ const DIGEST_REPLACES: usize = 20; pub enum Kind { /// The agent finished its turn and waits for a reply. Waiting, + /// The agent asked a question (`fctl ask`) and waits for its answer: + /// a finished turn with a question open, or a question asked once the + /// turn ended. People who want to hear when it waits hear of it. + Asking, /// It paused on a Claude usage limit and continues when it resets. Paused, /// It failed. @@ -51,7 +55,7 @@ impl Kind { /// Whether `settings` ask for it. pub fn wanted(self, settings: &NotificationSettings) -> bool { match self { - Self::Waiting => settings.waiting, + Self::Waiting | Self::Asking => settings.waiting, Self::Paused => settings.paused, Self::Failed => settings.failed, } @@ -62,7 +66,7 @@ impl Kind { pub fn still(self, status: SessionStatus) -> bool { status == match self { - Self::Waiting => SessionStatus::Idle, + Self::Waiting | Self::Asking => SessionStatus::Idle, Self::Paused => SessionStatus::Paused, Self::Failed => SessionStatus::Failed, } @@ -169,9 +173,44 @@ pub fn excerpt(text: &str, max: usize) -> Option { Some(out) } +/// A question as a notification shows it: its text on one line, cut at a +/// word after [`QUESTION_CHARS`], and its answers to click on the next. +fn question_lines(detail: &str) -> String { + let (text, options) = detail + .split_once(QUESTION_OPTIONS_MARK) + .unwrap_or((detail, "")); + let text = excerpt(text, QUESTION_CHARS).unwrap_or_default(); + let options: Vec<&str> = options + .split('\n') + .map(str::trim) + .filter(|o| !o.is_empty()) + .collect(); + if options.is_empty() { + text + } else { + format!("{text}\n{}", options.join(" · ")) + } +} + +/// An agent's question in a notification, at most: more than its last words. +pub const QUESTION_CHARS: usize = 300; +/// Where a question's text ends and its answers to click begin, one a line, +/// in an [`Event`]'s detail ([`question_detail`]). +const QUESTION_OPTIONS_MARK: &str = "\n\u{1f}\n"; + +/// The detail of an [`Kind::Asking`] event: the question, then its answers. +pub fn question_detail(text: &str, options: &[String]) -> String { + if options.is_empty() { + text.to_owned() + } else { + format!("{text}{QUESTION_OPTIONS_MARK}{}", options.join("\n")) + } +} + fn says(kind: Kind) -> &'static str { match kind { Kind::Waiting => "waits for your reply", + Kind::Asking => "asks you", Kind::Paused => "paused on a usage limit", Kind::Failed => "failed", } @@ -191,6 +230,17 @@ pub fn compose(events: &[Event]) -> Option { let body = match (only.kind, detail) { (Kind::Waiting, Some(words)) => format!("{} waits for your reply\n{words}", only.reference), (Kind::Waiting, None) => format!("{} waits for your reply", only.reference), + // The question whole, as far as a notification shows it: it's what + // they answer. + (Kind::Asking, _) => match only + .detail + .as_deref() + .map(str::trim) + .filter(|q| !q.is_empty()) + { + Some(q) => format!("{} asks you\n{}", only.reference, question_lines(q)), + None => format!("{} asks you", only.reference), + }, (Kind::Paused, _) => format!( "{} paused on a Claude usage limit and continues when it resets", only.reference @@ -214,6 +264,7 @@ fn digest(events: &[Event], at: Millis) -> PushMessage { let same = events.iter().all(|e| Some(e.kind) == kind); let title = match kind { Some(Kind::Waiting) if same => format!("{n} sessions wait for your reply"), + Some(Kind::Asking) if same => format!("{n} sessions ask you"), Some(Kind::Paused) if same => format!("{n} sessions paused on a usage limit"), Some(Kind::Failed) if same => format!("{n} sessions failed"), _ => format!("{n} sessions need you"), @@ -295,6 +346,13 @@ mod tests { assert!(Kind::Waiting.still(Idle)); assert!(!Kind::Waiting.still(Running)); + assert!(Kind::Asking.still(Idle)); + assert!(!Kind::Asking.still(Running)); + assert!(Kind::Asking.wanted(&NotificationSettings::default())); + assert!(!Kind::Asking.wanted(&NotificationSettings { + waiting: false, + ..Default::default() + })); assert!(Kind::Failed.still(Failed)); assert!(!Kind::Paused.still(Queued)); } @@ -449,4 +507,35 @@ mod tests { } Ok(()) } + + #[test] + fn questions_say_what_they_ask_and_the_answers_to_click() { + let detail = question_detail( + "Round Danish prices to whole kroner, or keep øre?", + &["Round to whole kroner".into(), "Keep øre".into()], + ); + let asking = compose(&[event(231, Kind::Asking, Some(&detail))]); + assert_eq!( + asking.map(|m| m.body), + Some( + "my-app#231 asks you\nRound Danish prices to whole kroner, or keep øre?\nRound to whole kroner · Keep øre" + .into() + ) + ); + let plain = compose(&[event(7, Kind::Asking, Some("Which region?"))]); + assert_eq!( + plain.map(|m| m.body), + Some("my-app#7 asks you\nWhich region?".into()) + ); + let digest = compose(&[ + event(1, Kind::Asking, Some("A?")), + event(2, Kind::Asking, Some("B?")), + ]); + assert_eq!(digest.map(|m| m.title), Some("2 sessions ask you".into())); + let mixed = compose(&[ + event(1, Kind::Asking, Some("A?")), + event(2, Kind::Failed, None), + ]); + assert!(mixed.is_some_and(|m| m.body.contains("my-app#1 asks you · Task 1"))); + } } diff --git a/crates/fctl-domain/src/validate.rs b/crates/fctl-domain/src/validate.rs index 3abf1a10..47162355 100644 --- a/crates/fctl-domain/src/validate.rs +++ b/crates/fctl-domain/src/validate.rs @@ -291,6 +291,62 @@ pub fn slug_shape(input: &str) -> Result { Ok(s) } +/// The most answers a question offers. +pub const QUESTION_OPTIONS: usize = 6; + +/// A question an agent asks people (`fctl ask`): at most 500 characters, +/// and at most [`QUESTION_OPTIONS`] answers to click of at most 120 on one +/// line each, none twice. An empty question takes one back (`None`). It +/// comes from the sandbox, and shows in people's notifications. +pub fn question(text: &str, options: &[String]) -> Result)>> { + let text = text.trim(); + if text.is_empty() { + return Ok(None); + } + if text.chars().count() > 500 { + return Err(ApiError::validation( + "question", + "Ask in at most 500 characters: put the details in your message", + )); + } + if text + .chars() + .any(|c| c.is_control() && c != '\n' && c != '\t') + { + return Err(ApiError::validation( + "question", + "Remove control characters", + )); + } + if options.len() > QUESTION_OPTIONS { + return Err(ApiError::validation( + "options", + format!("Offer at most {QUESTION_OPTIONS} answers"), + )); + } + let mut out: Vec = Vec::with_capacity(options.len()); + for o in options { + let o = collapse_spaces(o); + if o.is_empty() { + return Err(ApiError::validation("options", "An answer can't be empty")); + } + if o.chars().count() > 120 { + return Err(ApiError::validation( + "options", + "Keep each answer to at most 120 characters", + )); + } + if o.chars().any(char::is_control) { + return Err(ApiError::validation("options", "Remove control characters")); + } + if out.iter().any(|x| x.eq_ignore_ascii_case(&o)) { + return Err(ApiError::validation("options", "Offer each answer once")); + } + out.push(o); + } + Ok(Some((text.to_owned(), out))) +} + /// A git branch name, following `git check-ref-format --branch`. pub fn branch(field: &str, input: &str) -> Result { let s = input.trim(); @@ -972,4 +1028,39 @@ mod tests { assert_eq!(effort("MAX").ok().as_deref(), Some("max")); assert!(effort("extreme").is_err()); } + + #[test] + fn questions() { + let ok = question( + " Round prices to whole kroner? ", + &["Yes, round".into(), " Keep øre ".into()], + ); + assert_eq!( + ok.ok().flatten(), + Some(( + "Round prices to whole kroner?".into(), + vec!["Yes, round".into(), "Keep øre".into()] + )) + ); + // Empty takes the question back. + assert_eq!(question(" ", &[]).ok(), Some(None)); + assert!(question(&"a".repeat(501), &[]).is_err()); + assert!(question("Which one?", &["A".into(), "a".into()]).is_err()); + assert!(question("Which one?", &["".into()]).is_err()); + assert!( + question( + "Which one?", + &vec!["x".to_owned(); 7] + .iter() + .enumerate() + .map(|(i, x)| format!("{x}{i}")) + .collect::>() + ) + .is_err() + ); + assert!(question("Which one?", &["a".repeat(121)]).is_err()); + assert!(question("Which\u{7} one?", &[]).is_err()); + // Lines are fine in the question itself. + assert!(question("Which one?\nThe first is faster.", &[]).is_ok()); + } } diff --git a/crates/fctl-proto/src/api.rs b/crates/fctl-proto/src/api.rs index 92c99dc6..8ca0769d 100644 --- a/crates/fctl-proto/src/api.rs +++ b/crates/fctl-proto/src/api.rs @@ -8,8 +8,8 @@ use crate::event::SessionEvent; use crate::runner::{ClaudeCredentialKind, DriverInfo, RunnerClaudeToken, SandboxLimits}; use crate::session::{ GithubAccess, InstanceRole, Memory, Project, ProjectRole, ProjectSettings, PullRequestRef, - RepoAccess, RepoRef, Retrospective, RetrospectiveOutcome, Session, SessionRef, SessionRole, - SessionStatus, UserRef, WorkspaceColor, WorkspaceRef, WorkspaceRole, + RepoAccess, RepoRef, Retrospective, RetrospectiveOutcome, Session, SessionQuestion, SessionRef, + SessionRole, SessionStatus, UserRef, WorkspaceColor, WorkspaceRef, WorkspaceRole, }; use crate::{ AccessRequestId, AllowId, AttachmentId, CredentialId, DeliveryId, EnrollmentTokenId, @@ -3656,6 +3656,17 @@ pub enum AgentCall { /// ([`ReviewAgents::description_summary`]); fctl-agents and control /// planes from before it refuse it. SummarizePullRequest { summary: PullRequestSummary }, + /// Asks the people who follow the session for their input (`fctl + /// ask`): the question, and answers they can give with a click. It + /// takes the place of one the agent asked before, and an empty + /// question takes that back. A person's next message answers it. + /// fctl-agents and control planes from before questions refuse it. + Ask { + question: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[cfg_attr(feature = "ts", ts(as = "Option>", optional))] + options: Vec, + }, /// Reads or writes the project's ticket tracker (`fctl ticket`): a /// [`crate::tickets::TicketRequest`], which hosts and fctl-agent pass /// on as it is, so that what `fctl ticket` does grows with the control @@ -3712,6 +3723,11 @@ pub enum AgentAnswer { PullRequestSummarized { summarized: SummarizedPullRequest, }, + /// The session's question as it is now: none once taken back. + Asked { + #[cfg_attr(feature = "ts", ts(optional))] + question: Option, + }, /// The tracker's answer to a [`AgentCall::Ticket`]: a /// [`crate::tickets::TicketAnswer`], passed on as it is. Ticket { diff --git a/crates/fctl-proto/src/event.rs b/crates/fctl-proto/src/event.rs index af13c82a..45a60705 100644 --- a/crates/fctl-proto/src/event.rs +++ b/crates/fctl-proto/src/event.rs @@ -548,7 +548,8 @@ pub struct Notice { /// `retrospective`, `review_posted`, `review_held`, `review_passed_on`, /// `pull_request_summarized`, `follow_up_held`, `ticket_created`, /// `ticket_commented`, `ticket_updated`, `ticket_replied`, - /// `ticket_moved`, `ticket_failed`. + /// `ticket_moved`, `ticket_failed`, `question_asked`, + /// `question_withdrawn`. pub code: String, pub message: String, /// When the condition clears (usage-limit resets). @@ -576,6 +577,9 @@ pub struct Notice { /// What the agent, or fctl for it, did in the project's ticket tracker, /// in a `ticket_*` notice. Clients from before it show the message. pub ticket: Option, + /// The question a `question_asked` notice is about (`fctl ask`), as the + /// agent asked it. Clients from before it show the message. + pub question: Option, } impl Notice { @@ -593,6 +597,7 @@ impl Notice { summarized: None, follow_up: None, ticket: None, + question: None, } } } @@ -746,6 +751,7 @@ mod tests { review: None, summarized: None, follow_up: None, + question: None, }; let json = serde_json::to_value(EventBody::Notice(shot.clone()))?; assert_eq!(json["kind"], "notice"); diff --git a/crates/fctl-proto/src/session.rs b/crates/fctl-proto/src/session.rs index 2891672b..0bd23097 100644 --- a/crates/fctl-proto/src/session.rs +++ b/crates/fctl-proto/src/session.rs @@ -1328,6 +1328,26 @@ pub struct Session { /// Absent for other sessions, and from control planes before ticket /// trackers. pub ticket: Option, + /// What its agent asked the people who follow it (`fctl ask`), until + /// someone answers: a person's next message does. Absent while it + /// asks nothing, and from control planes before questions. + pub question: Option, +} + +/// A question a session's agent asks people, when it needs their input to +/// go on: a decision only they can make, access, an answer. +#[skip_serializing_none] +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS), ts(optional_fields))] +pub struct SessionQuestion { + /// The question, in a sentence or two. + pub text: String, + /// Answers people can give with a click, each sent as their reply as + /// it is; they can always write their own instead. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[cfg_attr(feature = "ts", ts(as = "Option>", optional))] + pub options: Vec, + pub asked_at: Millis, } /// The schedule a session started from. diff --git a/crates/fctl/src/cmd/ask.rs b/crates/fctl/src/cmd/ask.rs new file mode 100644 index 00000000..c7b3704f --- /dev/null +++ b/crates/fctl/src/cmd/ask.rs @@ -0,0 +1,131 @@ +//! `fctl ask`: an agent asks the people who follow its session for their +//! input, in its sandbox, through fctl-agent (`AgentCall::Ask`). People see +//! the question where they follow the session, with answers to click, and +//! hear of it as the turn ends; a person's next message answers it. + +use crate::style; +use anyhow::{Context, Result, bail}; +use clap::Args; +use fctl_proto::SessionId; +use fctl_proto::agent::{SessionReply, SessionRequest}; +use fctl_proto::api::{AgentAnswer, AgentCall}; +use fctl_proto::session::SessionQuestion; +use std::time::Duration; + +#[derive(Args)] +pub struct AskArgs { + /// The question, in a sentence or two: what you need to know to go on. + /// Put the details in your message. + #[arg(required_unless_present = "withdraw", value_name = "QUESTION")] + pub question: Vec, + /// An answer people can give with a click (repeatable, up to 6), sent + /// as their reply as it is. They can always write their own. + #[arg(short, long = "option", value_name = "ANSWER")] + pub options: Vec, + /// Take back the question you asked: you found the answer yourself. + #[arg(long, conflicts_with_all = ["question", "options"])] + pub withdraw: bool, +} + +pub async fn run(args: AskArgs, json: bool) -> Result<()> { + let Some((socket, session)) = super::sessions::this_sandbox(None) else { + bail!( + "fctl ask asks the people who follow the session this sandbox runs, for its agent: run it in a session's sandbox. To answer a question, send the session a message (fctl send)." + ); + }; + let question = if args.withdraw { + String::new() + } else { + args.question.join(" ") + }; + if !args.withdraw && question.trim().is_empty() { + bail!("Ask something: fctl ask \"Should prices round to whole kroner?\""); + } + let request = SessionRequest::Call { + session_id: Some(SessionId(session)), + call: AgentCall::Ask { + question, + options: args.options, + }, + }; + // fctl-agent waits up to two minutes for the control plane. + let reply = tokio::time::timeout( + Duration::from_secs(180), + super::sessions::ask_agent(&socket, &request), + ) + .await + .context("fctl-agent did not answer in time")??; + let asked = match reply { + SessionReply::Answer { + answer: AgentAnswer::Asked { question }, + } => question, + SessionReply::Error { error } => bail!("{}", error.message), + _ => bail!( + "This sandbox's fctl-agent can't ask yet: its runner needs a newer fctl (`fctl self update` there). Ask in your message instead, and end your turn." + ), + }; + if json { + return style::print_json(&serde_json::json!({ "question": asked })); + } + match asked { + Some(q) => print_asked(&q), + None => println!("{} Took the question back", style::accent("✓")), + } + Ok(()) +} + +fn print_asked(q: &SessionQuestion) { + println!( + "{} Asked: {}", + style::accent("✓"), + style::terminal_safe(&q.text) + ); + for o in &q.options { + println!(" · {}", style::terminal_safe(o)); + } + println!( + "{}", + style::dim( + "People see it where they follow the session, and hear of it as your turn ends: end it now. Their answer comes as a message." + ) + ); +} + +#[cfg(test)] +mod tests { + use super::*; + use clap::Parser; + + #[derive(Parser)] + struct Fctl { + #[command(flatten)] + ask: AskArgs, + } + + fn parse(args: &[&str]) -> Option { + Fctl::try_parse_from(["fctl"].iter().chain(args).copied()) + .ok() + .map(|f| f.ask) + } + + #[test] + fn asks_with_answers_to_click() { + let Some(a) = parse(&[ + "Round", + "prices?", + "--option", + "Round to whole kroner", + "-o", + "Keep øre", + ]) else { + panic!("parses"); + }; + assert_eq!(a.question.join(" "), "Round prices?"); + assert_eq!(a.options, ["Round to whole kroner", "Keep øre"]); + assert!(!a.withdraw); + // Taking it back takes nothing else, and needs no question. + assert!(parse(&["--withdraw"]).is_some_and(|a| a.withdraw)); + assert!(parse(&["--withdraw", "Why?"]).is_none()); + assert!(parse(&[]).is_none()); + } +} diff --git a/crates/fctl/src/cmd/mod.rs b/crates/fctl/src/cmd/mod.rs index 0d9f64a2..658c03d8 100644 --- a/crates/fctl/src/cmd/mod.rs +++ b/crates/fctl/src/cmd/mod.rs @@ -1,5 +1,6 @@ pub mod account; pub mod admin; +pub mod ask; pub mod attach; pub mod auth; pub mod claude; diff --git a/crates/fctl/src/cmd/sessions.rs b/crates/fctl/src/cmd/sessions.rs index f0655b52..0125c0b0 100644 --- a/crates/fctl/src/cmd/sessions.rs +++ b/crates/fctl/src/cmd/sessions.rs @@ -379,6 +379,15 @@ pub async fn list(server: Option<&str>, args: ListArgs, json: bool) -> Result<() truncate(&style::plain(&s.title), 44), style::dim(&when) ); + // What its agent asks, under it: it waits on someone. + if let Some(q) = &s.question { + println!( + "{:<20} {} {}", + "", + style::accent("asks"), + truncate(&style::plain(&q.text), 60) + ); + } } Ok(()) } @@ -506,6 +515,24 @@ pub async fn show(server: Option<&str>, reference: &str, json: bool) -> Result<( .map(|r| style::dim(&format!(" — {}", style::terminal_safe(r)))) .unwrap_or_default() ); + // What its agent asks, and how to answer: first, as it waits on people. + if let Some(q) = &s.question { + println!( + "{} {}", + style::accent("asks:"), + style::bold(&style::terminal_safe(&q.text)) + ); + for o in &q.options { + println!(" · {}", style::terminal_safe(o)); + } + println!( + "{}", + style::dim(&format!( + " answer with: fctl send {}#{} \"…\"", + s.project_slug, s.number + )) + ); + } if let Some(t) = &s.ticket { println!( "ticket: {} {}{}", diff --git a/crates/fctl/src/main.rs b/crates/fctl/src/main.rs index cc48986c..e125b220 100644 --- a/crates/fctl/src/main.rs +++ b/crates/fctl/src/main.rs @@ -110,6 +110,16 @@ Examples: fctl publish --json after.png | jq -r '.published[].markdown'" )] Publish(cmd::publish::PublishArgs), + /// Ask the people who follow your session for their input (agents, in + /// its sandbox): a decision only they can make, access, an answer. They + /// see it where they follow the session, with the answers you offer to + /// click, and hear of it as your turn ends; end it then. Their answer + /// comes as a message. + #[command(after_help = "Examples: + fctl ask \"Round Danish prices to whole kroner, or keep øre?\" -o \"Round to whole kroner\" -o \"Keep øre\" + fctl ask \"Which Stripe account should the webhooks use?\" + fctl ask --withdraw # you found the answer yourself")] + Ask(cmd::ask::AskArgs), /// Resolve review threads of a pull request (agents that review and /// comment, in their session's sandbox): GitHub lets only tokens that /// can push resolve them, so fctl does it for them. @@ -454,6 +464,7 @@ async fn run(cli: Cli) -> anyhow::Result<()> { Command::Show { session } => cmd::sessions::show(server, &session, json).await, Command::Edit(args) => cmd::sessions::edit(server, args, json).await, Command::Publish(args) => cmd::publish::publish(args, json).await, + Command::Ask(args) => cmd::ask::run(args, json).await, Command::Unpublish { links } => cmd::publish::unpublish(server, &links, json).await, Command::Memory(args) => cmd::memory::run(server, args, json).await, Command::Retro(args) => cmd::retro::run(server, args, json).await, diff --git a/docs/adr/0078-agents-ask-people-with-fctl-ask.md b/docs/adr/0078-agents-ask-people-with-fctl-ask.md new file mode 100644 index 00000000..073e670c --- /dev/null +++ b/docs/adr/0078-agents-ask-people-with-fctl-ask.md @@ -0,0 +1,57 @@ +# 0078: Agents ask people with `fctl ask` + +2026-11-07 · accepted + +## Context + +An agent that needs a person to go on (a decision only they can make, +access, an answer) was told to say so plainly and stop. Its question then +sat at the end of its last message, and the session looked like any other +that waits for a reply: the Agent Floor, the sidebar and notifications +couldn't tell a session that finished its work from one that can't go on +without someone, and the person had to read the transcript to find what +was asked, then type an answer the agent had usually already spelled out +as choices. + +The person who started the session that built this asked for a way for +agents to say that they need input, shown where people look first. + +## Decision + +- **`fctl ask "…" -o "…" -o "…"`** in a sandbox asks the people who follow + the session: a question of at most 500 characters, and up to six answers + to click, of at most 120 characters each. It goes through fctl-agent and + the host to the control plane as `AgentCall::Ask`, like `fctl memory`, + so no credential enters the sandbox ([ADR 0007](0007-agents-name-their-sessions-through-fctl-agent.md)). + `fctl ask --withdraw` takes it back. A review agent asks nobody. +- **SessionDO keeps one open question** (`Session.question`), which it + writes through to D1's `sessions.question`, so session lists carry it, + and broadcasts it like any change to the session's summary. A newer one + takes its place. **A person's next message answers it**: SessionDO drops + it when it delivers a message with an author, whichever way the message + came (the page, the CLI, Linear). An answer to click is that message, + sent as it is. +- **Followers hear of it as the turn ends**, as a notification of its own + kind (`notify::Kind::Asking`): "shop#231 asks you" with the question and + its answers, in place of the last words of an ordinary finished turn. A + question asked after the turn ended notifies at once. People who turned + off notifications for sessions that wait for them don't get these + either: it's the same news, told better. +- **fctl-agent writes a `question_asked` notice** into the transcript with + the question, so that it stays there after it's answered, and tells + Claude about `fctl ask` in its instructions where the sandbox's fctl has + it, in place of "say so plainly and stop". + +## Consequences + +- The session page shows the question above the composer, with its + answers as buttons; the Agent Floor, project pages and the sidebar show + sessions that ask in blue, with the question; `fctl show` and `fctl + sessions` print it. +- The question is plain text: it shows in notifications and lists, where + Markdown wouldn't render. Details go in the agent's message. +- Hosts and fctl-agents from before it refuse the call, and `fctl ask` + says to update the runner's fctl. Their agents keep the old instruction, + since fctl-agent asks the sandbox's fctl whether it has `fctl ask`. +- One question at a time: an agent that asks again replaces its question, + so people answer what it asks now. diff --git a/docs/adr/README.md b/docs/adr/README.md index 69ae00ee..19758ac5 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -83,3 +83,4 @@ supersede an earlier one. Copy the newest record to start a new one. | [0075](0075-agents-that-triage-write-labels-and-comments-through-fctl-alone.md) | Agents that triage write labels and comments through fctl alone | | [0076](0076-sessions-hear-when-their-runner-runs-short-of-disk-and-vm-sandboxes-pause-before-it-fills.md) | Sessions hear when their runner runs short of disk, and VM sandboxes pause before it fills | | [0077](0077-sessions-wait-for-a-runner-whose-driver-is-ready.md) | Sessions wait for a runner whose driver is ready | +| [0078](0078-agents-ask-people-with-fctl-ask.md) | Agents ask people with `fctl ask` | diff --git a/docs/agents.md b/docs/agents.md index 84baefb8..c9b1c675 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -579,6 +579,7 @@ for its own session and project only. ```sh fctl edit --title "Fix the flaky login test" --description "Retries the redirect and tests it." +fctl ask "Round Danish prices to whole kroner, or keep øre?" -o "Round to whole kroner" -o "Keep øre" # then end the turn fctl memory # the project's notes, now fctl memory add "The e2e tests need Chromium: run npx playwright install chromium first." fctl memory stale mem_… --reason "The script moved to xtask" diff --git a/docs/architecture.md b/docs/architecture.md index a79e2b2d..d071c6ed 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -906,8 +906,8 @@ it's its person), device codes, workspaces invitations, GitHub accounts (and what GitHub sign-ins offer to connect, while admins choose) and runners, with their enrollment tokens, projects, their members and -repositories, sessions (summary rows, and whether the search index has -all of each), which sessions list which pull +repositories, sessions (summary rows with their agents' open questions, +and whether the search index has all of each), which sessions list which pull request, projects' review agents and their reviews, shares, who follows which session, notification settings and browsers (push subscriptions), runners, encrypted @@ -2328,6 +2328,27 @@ Older control planes and hosts send neither, and their agents see full names alone ([ADR 0064](adr/0064-agents-call-people-what-they-choose-or-all-their-first-names.md)). +### Questions + +An agent that needs a person to go on (a decision only they can make, +access, an answer) asks with `fctl ask "…"` in its sandbox, with `-o "…"` +for each answer people could give with a click, and ends its turn +([ADR 0078](adr/0078-agents-ask-people-with-fctl-ask.md)). fctl reaches +fctl-agent over the session socket, which asks the control plane through +its host (`AgentCall::Ask`), as for `fctl memory`. SessionDO keeps the +session's one open question (`Session.question`: at most 500 characters, +up to six answers of at most 120), writes it through to D1's +`sessions.question` so that session lists carry it, and shows it to +viewers and dashboards at once; a newer question takes its place, and +`fctl ask --withdraw` takes it back. A person's next message answers it: +SessionDO drops it as it delivers a message with an author, however it +came, and an answer clicked is that message, sent as it is. Followers hear +of it as the turn ends ([Notifications](#notifications)), and at once when +it comes after. fctl-agent writes a `question_asked` notice in the +transcript, so that the question stays there once answered, and tells +Claude about `fctl ask`, in place of saying so and stopping, where the +sandbox's fctl has it. Review agents ask nobody. + ### Titles A session's title starts as the first line of its task. Once the agent @@ -2915,7 +2936,10 @@ recorded. ## Notifications A session notifies the people who follow it when it waits for a reply (a -turn ends: `running` → `idle`), pauses on a usage limit, or fails. Starting +turn ends: `running` → `idle`), pauses on a usage limit, or fails. A turn +that ends with a [question](#questions) open says so instead ("my-app#12 +asks you", with the question and its answers), to those who want to hear +when it waits. Starting or resuming a session follows it, unless the person turned that off in Settings; anyone who can see a session can follow it (the bell on its page, `fctl follow`). Notifications are Web Push messages (RFC 8030) to the diff --git a/docs/cli.md b/docs/cli.md index e790de7c..cbdfa452 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -103,7 +103,7 @@ fctl search -p my-app "flaky test" --limit 50 fctl attach my-app#12 # stream it and type messages (Ctrl-C detaches) fctl attach --read-only my-app#12 -fctl send my-app#12 "Use the existing Button component" # a stopped session resumes for it +fctl send my-app#12 "Use the existing Button component" # a stopped session resumes for it, and it answers what its agent asks (fctl show prints the question) fctl send my-app#12 -a ci.log "This is what CI printed" fctl interrupt my-app#12 # stop the current turn fctl stop my-app#12 # end the session (its sandbox is kept for resuming) diff --git a/docs/development.md b/docs/development.md index 29fd4c36..f62079db 100644 --- a/docs/development.md +++ b/docs/development.md @@ -113,7 +113,10 @@ small PNG it draws, or each image at the paths after the word, one call after another: `look /tmp/before.png /tmp/after.png`), which the session keeps and its page shows under the calls, `remember ` adds the rest of its line to the project's memory with -`fctl memory add`, `recall` lists the memory with `fctl memory`, a line +`fctl memory add`, `ask ` asks the people who follow the session +the rest of its line with `fctl ask`, offering the answers after each ` / ` +to click (`ask Ship it today? / Yes / Not yet`), as agents do when they +need someone's input, `recall` lists the memory with `fctl memory`, a line that starts with `fctl ticket` runs as it is (`fctl ticket view ENG-1`), as agents reach their project's tracker, `printenv` shows the `CLAUDE_CODE_…` variables it got and says the token diff --git a/docs/llms.txt b/docs/llms.txt index a54757c0..6040c9c3 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -94,7 +94,7 @@ queued → provisioning → preparing → running ⇄ idle → stopping → stop - **GitHub tokens.** Installation tokens for the project's repositories only, valid an hour and refreshed through the host: one that writes as far as the session's GitHub access allows, one that only reads. git and `gh` are signed in. Changes to a project's repositories or GitHub access reach running sessions within the hour. - **Follow-ups** (webhook needed; new projects have all four on): a comment, review or line comment that mentions `@fctl` or `@agent` (or starts with `fctl:`/`agent:`) from someone who can write to the repository; a failed check of the newest commit (at most three in a row while nobody messages the agent); a conflict with the base branch, which the agent resolves by merging the base branch in (never rebasing), running the tests and pushing; a merge or close. Each arrives as a message from fctl that resumes the session on the subscription it ran on, and the agent answers in the threads on GitHub. - **Review agents** (per project, on an owner's subscription): each new commit of a pull request in the repositories the project writes to gets a review: an `eyes` reaction, an `fctl review` check, a summary comment and findings on the lines, posted as the instance's review app (`fctl-review` on app.fctl.sh) where it's installed on the account, else as its GitHub App (`fctl workspaces review-app` says which, and gives a workspace's admins the links that install it). Owners skip repositories another project reviews already (`fctl review settings --skip-repos acme/shared-lib`), whose pull requests then get no review in theirs; new ones are reviewed until skipped. Drafts get reviews too until owners turn them off (`--drafts off`): then a draft gets its review when it's marked ready for review, or when someone asks. With `--description-summary on`, the agent first sums each pull request up at the end of its description (how risky it looks, what it does, what deserves a closer look, in a GitHub alert between `` marks), in place of an earlier review's; fctl writes it and leaves the rest of the description as it is. Pull requests from people who can't write to the repository, and from apps other than the ones the owners chose (Dependabot by default), are reviewed only when someone asks (`fctl review start`). When an fctl agent opened the pull request, its session gets the findings to fix or answer (at most five reviews in a row while no person messages it; then the session's page, under the pull request, continues for five more rounds, the held findings first: `fctl review pass-on my-app#12`). Findings that went to no session, since none listed the pull request yet, go to the session that opened it once it lists it. -- **In-sandbox commands** (through fctl-agent, no sign-in): `fctl edit --title … --description …` (name the session), `fctl memory` / `fctl memory add|stale|duplicate`, `fctl retro` / `fctl retro update|list`, `fctl ticket …`, `fctl publish FILE` (screenshots for pull requests; `gh pr edit --attach` fails with the app's token), `fctl resolve PRRT_…` (resolve review threads, for agents that comment), and for review agents `fctl review threads`, `fctl review summarize FILE` and `fctl review submit FILE`. +- **In-sandbox commands** (through fctl-agent, no sign-in): `fctl edit --title … --description …` (name the session), `fctl ask "…" -o "…" -o "…"` (ask the people who follow the session for input, with answers to click, then end the turn; their next message answers it; `--withdraw` takes it back), `fctl memory` / `fctl memory add|stale|duplicate`, `fctl retro` / `fctl retro update|list`, `fctl ticket …`, `fctl publish FILE` (screenshots for pull requests; `gh pr edit --attach` fails with the app's token), `fctl resolve PRRT_…` (resolve review threads, for agents that comment), and for review agents `fctl review threads`, `fctl review summarize FILE` and `fctl review submit FILE`. - **What a sandbox has.** The project's environment variables and secrets, `CLAUDE_CODE_OAUTH_TOKEN`, `FCTL_SESSION_ID`, `FCTL_SESSION_URL`, `FCTL_SANDBOX_CPUS`, `FCTL_SANDBOX_MEMORY_MB`, outbound network, sudo. No fctl credentials, no API keys, no GitHub App key. ## Claude credentials and usage @@ -176,7 +176,7 @@ Each recipe says who does what: some steps take a person with a role in the proj 1. **Delegate a task and collect the result**: the core loop above. Add `--github read` for an answer without changes, `-a FILE` (up to 10 files of 20 MB) for screenshots or logs, `--model opus|sonnet|haiku|fable --effort low|medium|high|xhigh|max` to override the project's, `--base BRANCH` to start elsewhere, `--branch NAME` to choose the branch. 2. **Several independent tasks at once**: start one session per task with `fctl run -d`; each gets its own sandbox, branch and pull request. Watch them with `fctl sessions --active --json`. Runners take as many as their capacity allows (4 each by default); the rest queue. -3. **Steer or stop**: `fctl send "…"` (resumes a stopped session), `fctl interrupt `, `fctl stop `, `fctl resume "…"`. Its owner changes the model or effort level its agent works at from its next step, and its next run's: `fctl edit --effort medium` (plan at xhigh, build at medium) keeps Claude's prompt cache where Claude sends the level with each turn; `--model sonnet` makes its next step read the whole conversation again without the cache. +3. **Steer or stop**: `fctl send "…"` (resumes a stopped session, and answers what its agent asks: `fctl show` and `fctl sessions` print the question), `fctl interrupt `, `fctl stop `, `fctl resume "…"`. Its owner changes the model or effort level its agent works at from its next step, and its next run's: `fctl edit --effort medium` (plan at xhigh, build at medium) keeps Claude's prompt cache where Claude sends the level with each turn; `--model sonnet` makes its next step read the whole conversation again without the cache. 4. **From any tool (issue tracker, chat bot, deploy pipeline, n8n/Zapier/Make)**: a person sets up a schedule that runs when asked and a token that runs sessions in that project, then the tool posts what it knows: ```sh fctl schedules add "Triage an issue" -p my-app --when-asked --github triage \ diff --git a/web/src/components/session/question.test.tsx b/web/src/components/session/question.test.tsx new file mode 100644 index 00000000..4394f8d6 --- /dev/null +++ b/web/src/components/session/question.test.tsx @@ -0,0 +1,60 @@ +import { act } from "react"; +import { createRoot } from "react-dom/client"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import type * as G from "@/gen"; +import { QuestionCard } from "./question"; + +(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +const roots: (() => void)[] = []; +afterEach(() => { + for (const unmount of roots.splice(0)) unmount(); +}); + +const question: G.SessionQuestion = { + text: "Round Danish prices to whole kroner, or keep øre?", + options: ["Round to whole kroner", "Keep øre"], + asked_at: Date.now() - 4 * 60_000, +}; + +function setup(props: { canAnswer: boolean; question?: G.SessionQuestion }) { + const onAnswer = vi.fn<(text: string) => Promise>(() => Promise.resolve()); + const container = document.createElement("div"); + document.body.append(container); + const root = createRoot(container); + act(() => + root.render( + , + ), + ); + roots.push(() => { + act(() => root.unmount()); + container.remove(); + }); + const button = (name: string) => + [...container.querySelectorAll("button")].find((b) => b.textContent === name); + return { container, onAnswer, button }; +} + +describe("the agent's question", () => { + it("says what it asks, and sends an answer it offers as the reply", async () => { + const q = setup({ canAnswer: true }); + expect(q.container.textContent).toContain("The agent asks you"); + expect(q.container.textContent).toContain(question.text); + expect(q.container.textContent).toContain("Or write your own answer below"); + await act(async () => q.button("Keep øre")?.click()); + expect(q.onAnswer).toHaveBeenCalledWith("Keep øre"); + }); + + it("offers nothing to click to people who can't message the agent", () => { + const q = setup({ canAnswer: false }); + expect(q.button("Keep øre")).toBeUndefined(); + expect(q.container.textContent).toContain("The people who can message the agent answer it"); + }); + + it("asks for a reply when it offers no answers", () => { + const q = setup({ canAnswer: true, question: { ...question, options: undefined } }); + expect(q.container.querySelectorAll("button")).toHaveLength(0); + expect(q.container.textContent).toContain("Your next message answers it"); + }); +}); diff --git a/web/src/components/session/question.tsx b/web/src/components/session/question.tsx new file mode 100644 index 00000000..a21d3da0 --- /dev/null +++ b/web/src/components/session/question.tsx @@ -0,0 +1,91 @@ +// What a session's agent asks the people who follow it (`fctl ask`), above the composer until +// someone answers: the question, and the answers it offers to click, each sent as the reply as +// it is. Any message answers it, and it goes as the control plane says so. + +import { MessageCircleQuestion } from "lucide-react"; +import { useState } from "react"; +import { Spinner, toast } from "@/components/ui"; +import type * as G from "@/gen"; +import { cn } from "@/lib/cn"; +import { agoShort } from "@/lib/format"; + +export function QuestionCard({ + question, + canAnswer, + onAnswer, + className, +}: { + question: G.SessionQuestion; + /** The person may message the agent. */ + canAnswer: boolean; + /** Sends `text` as their reply. */ + onAnswer: (text: string) => Promise; + className?: string; +}) { + const [sending, setSending] = useState(); + const options = question.options ?? []; + const answer = async (text: string) => { + if (sending) return; + setSending(text); + try { + await onAnswer(text); + } catch (e) { + toast(e instanceof Error ? e.message : "Not sent", "error"); + } finally { + setSending(undefined); + } + }; + return ( +
+
+ + + +
+

+ The agent asks you + {agoShort(question.asked_at)} +

+

+ {question.text} +

+ {canAnswer && options.length > 0 && ( +
+ {options.map((o) => ( + + ))} +
+ )} +

+ {canAnswer + ? options.length > 0 + ? "Or write your own answer below. Any reply answers it." + : "Your next message answers it." + : "The people who can message the agent answer it."} +

+
+
+
+ ); +} diff --git a/web/src/components/session/row.tsx b/web/src/components/session/row.tsx index 2f71d262..52a7bef8 100644 --- a/web/src/components/session/row.tsx +++ b/web/src/components/session/row.tsx @@ -3,7 +3,7 @@ // last moved. import { Link } from "@tanstack/react-router"; -import { ArrowRight, Repeat } from "lucide-react"; +import { ArrowRight, MessageCircleQuestion, Repeat } from "lucide-react"; import { Fragment } from "react"; import { Avatar, GithubIcon, LinearIcon, StatusDot } from "@/components/ui"; import { WorkspaceAvatar } from "@/components/workspace/avatar"; @@ -21,6 +21,14 @@ export function SessionRow({ s, workspace }: { s: G.Session; workspace?: G.Works
+ {s.question && ( + // What its agent asks: it waits on someone. +

+

+ )}
{workspace && ( // On a phone its avatar says which one, and the reference keeps the room. diff --git a/web/src/components/session/transcript.tsx b/web/src/components/session/transcript.tsx index a9c77260..c5798b01 100644 --- a/web/src/components/session/transcript.tsx +++ b/web/src/components/session/transcript.tsx @@ -14,6 +14,7 @@ import { Hourglass, ImageUp, Info, + MessageCircleQuestion, Radio, Repeat, ScrollText, @@ -154,6 +155,37 @@ function LongText({ text, findKey }: { text: string; findKey: string }) { * duplicate too), as it was then, with a link to it in the project's Memory * tab. */ +/** What the agent asked people (`fctl ask`), as it asked it: the answers it offered, and the reply that follows. */ +function QuestionNotice({ question, findKey }: { question: G.SessionQuestion; findKey: string }) { + return ( +
+ } tone="info"> + Asked you + + +

+ {question.text} +

+ {(question.options?.length ?? 0) > 0 && ( +
    + {question.options?.map((o) => ( +
  • + {o} +
  • + ))} +
+ )} +
+
+ ); +} + function MemoryNotice({ memory, stale, @@ -553,6 +585,7 @@ const ItemView = memo(function ItemView({ if (item.notice.summarized) return ; if (item.notice.follow_up) return ; if (item.notice.ticket) return ; + if (item.notice.question) return ; if (item.notice.memory) return ( {s.title} - : {statusLabel(s.status)} + : {s.question ? "asks you something" : statusLabel(s.status)} + {s.question && ( +