From 7621f2888f966af26d1fb81a465fe8801a813391 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 07:47:42 +0000 Subject: [PATCH 1/4] feat(web): ask to wake a paused autopilot when you message its session A message to the session a paused autopilot works in reached its agent alone: its fctl is refused while paused, so it did the work in that one session instead of planning and delegating. The message box now asks first, in a card over it, whether to wake the autopilot with the message (first, focused) or send it without waking it; the earlier session's card wakes it too. POST /sessions/{id}/messages takes wake_autopilot, which checks what a resume does, moves the session to the connection it runs on, delivers the message and then resumes the autopilot. Its wake treats a session a person just messaged as at work, so it carries on there rather than hand off to a fresh session under the message. Autopilots that paused themselves say so (paused_itself, migration 0080). fctl send --wake does the same from the CLI. --- crates/fctl-client/src/api.rs | 4 + .../0080_autopilot_paused_itself.sql | 14 + crates/fctl-control/src/api/autopilots.rs | 110 ++++++-- crates/fctl-control/src/api/sessions.rs | 86 ++++++ crates/fctl-control/src/autopilots.rs | 167 ++++++++++- crates/fctl-domain/src/autopilot.rs | 69 +++++ crates/fctl-proto/src/api.rs | 13 + crates/fctl-proto/src/autopilot.rs | 5 + crates/fctl/src/cmd/sessions.rs | 86 +++++- crates/fctl/src/main.rs | 8 + web/src/components/project/autopilot.test.tsx | 1 + web/src/components/session/composer.tsx | 42 ++- web/src/components/session/moved-on.test.tsx | 18 ++ web/src/components/session/moved-on.tsx | 208 +++++--------- web/src/components/session/now-line.tsx | 13 + .../components/session/paused-pilot.test.tsx | 265 ++++++++++++++++++ web/src/components/session/paused-pilot.tsx | 166 +++++++++++ web/src/components/session/ways.tsx | 172 ++++++++++++ web/src/gen/Autopilot.ts | 6 + web/src/gen/SendMessageRequest.ts | 12 +- web/src/gen/SendMessageResponse.ts | 8 +- web/src/lib/autopilot.test.ts | 39 ++- web/src/lib/autopilot.ts | 54 +++- web/src/lib/live.ts | 26 +- web/src/routes/session.test.tsx | 1 + web/src/routes/session.tsx | 18 +- 26 files changed, 1410 insertions(+), 201 deletions(-) create mode 100644 crates/fctl-control/migrations/0080_autopilot_paused_itself.sql create mode 100644 web/src/components/session/paused-pilot.test.tsx create mode 100644 web/src/components/session/paused-pilot.tsx create mode 100644 web/src/components/session/ways.tsx diff --git a/crates/fctl-client/src/api.rs b/crates/fctl-client/src/api.rs index 0d66f9140..6c1339656 100644 --- a/crates/fctl-client/src/api.rs +++ b/crates/fctl-client/src/api.rs @@ -830,12 +830,15 @@ impl Api { .await } + /// Sends a message to a session; with `wake_autopilot`, to the session + /// a paused autopilot works in, resumes the autopilot to take it up. pub async fn send_message( &self, session: &str, text: &str, client_id: Option, attachments: Vec, + wake_autopilot: bool, ) -> Result { self.post( &format!("/sessions/{}/messages", enc(session)), @@ -843,6 +846,7 @@ impl Api { text: text.to_owned(), client_id, attachments, + wake_autopilot: wake_autopilot.then_some(true), }, ) .await diff --git a/crates/fctl-control/migrations/0080_autopilot_paused_itself.sql b/crates/fctl-control/migrations/0080_autopilot_paused_itself.sql new file mode 100644 index 000000000..f30cd573c --- /dev/null +++ b/crates/fctl-control/migrations/0080_autopilot_paused_itself.sql @@ -0,0 +1,14 @@ +-- An autopilot that paused itself (`fctl autopilot pause`), done or +-- waiting for people, rather than one fctl paused: both leave paused_by +-- NULL, and people read them differently. Its own session's message box +-- asks whether a message wakes it (`SendMessageRequest.wake_autopilot`). +ALTER TABLE autopilots ADD COLUMN paused_itself INTEGER NOT NULL DEFAULT 0; + +-- Those paused now that paused themselves, as their log says: the entry +-- has the pause's time. +UPDATE autopilots SET paused_itself = 1 +WHERE state = 'paused' AND paused_by IS NULL AND EXISTS ( + SELECT 1 FROM autopilot_log l + WHERE l.project_id = autopilots.project_id AND l.kind = 'state' + AND l.at = autopilots.paused_at AND l.text LIKE 'It paused itself%' +); diff --git a/crates/fctl-control/src/api/autopilots.rs b/crates/fctl-control/src/api/autopilots.rs index f6493403a..08196b5b0 100644 --- a/crates/fctl-control/src/api/autopilots.rs +++ b/crates/fctl-control/src/api/autopilots.rs @@ -25,7 +25,7 @@ use crate::ctx::Ctx; use crate::db::{int, n, on, opt_int, os, q, s}; use crate::error::{AppError, AppResult, conflict, forbidden, not_found, validation}; use crate::http; -use crate::model::{PROJECT_SELECT, PROJECT_VISIBLE, ProjectRow}; +use crate::model::{PROJECT_SELECT, PROJECT_VISIBLE, ProjectRow, UserRow}; use fctl_domain::autopilot as ap; use fctl_domain::verify::Sensitive; use fctl_proto::autopilot::*; @@ -178,6 +178,7 @@ async fn view( paused_reason: row.paused_reason.clone(), paused_by: row.paused_by_ref(), paused_at: row.paused_at, + paused_itself: row.paused_itself && row.state() == AutopilotState::Paused, owner: row.owner_ref(), keep_owner: row.keep_owner, direction: row.direction.clone(), @@ -855,7 +856,7 @@ pub async fn put(ctx: &mut Ctx, req: &mut Request, id: &str) -> AppResult AppResult AppResult AppResult AppResult AppResult { + if let Some(r) = resuming(ctx, id).await? { + resumed(ctx, &r, false).await?; + } + get(ctx, id).await +} + +/// A resume of a paused autopilot that its checks let through +/// ([`resuming`]), for [`resumed`] to make. +pub struct Resuming { + p: ProjectAccess, + row: AutopilotRow, + me: UserRow, + mine: bool, + /// It runs on the resumer's subscription from now on. + take_over: bool, +} + +impl Resuming { + /// The Claude connection it runs on once resumed, and as whom it acts: + /// the resumer's when they take it over, else its owner's; or why it + /// can't run, which pauses it again at its next wake. + pub async fn runs_on(&self, ctx: &Ctx) -> AppResult> { + if !self.take_over { + return engine::owner(&ctx.db, &self.p.row, &self.row).await; + } + Ok( + crate::api::sessions::credential_for(&ctx.db, &self.me, self.p.workspace_id()) + .await? + .map(|credential| engine::Owner { + user: self.me.clone(), + credential, + }) + .ok_or_else(|| TAKE_OVER_CONNECT.to_owned()), + ) + } +} + +/// Why someone who takes the autopilot over as they resume it can't. +const TAKE_OVER_CONNECT: &str = "Connect your Claude subscription first (Settings → Claude): from now on the autopilot runs on it."; + +/// Checks that the caller may resume the autopilot of project `id` now, +/// and whether that takes it over: `None` when it is on already. +pub async fn resuming(ctx: &Ctx, id: &str) -> AppResult> { let l = load(ctx, id).await?; let row = require(l.row.clone())?; require_steer(&l)?; if row.state() == AutopilotState::On { - return get(ctx, id).await; + return Ok(None); } if !engine::workspace_allows(&ctx.db, l.p.workspace_id()).await? { return Err(forbidden( @@ -1414,17 +1465,36 @@ pub async fn resume(ctx: &mut Ctx, id: &str) -> AppResult { .await? .is_none() { - return Err(conflict( - "Connect your Claude subscription first (Settings → Claude): from now on the autopilot runs on it.", - )); + return Err(conflict(TAKE_OVER_CONNECT)); } ctx.verified(Sensitive::PutOnAutopilot)?; } + Ok(Some(Resuming { + p: l.p, + row, + me, + mine, + take_over, + })) +} + +/// 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. +pub async fn resumed(ctx: &Ctx, r: &Resuming, message: bool) -> AppResult<()> { + let Resuming { + p, + row, + me, + mine, + take_over, + } = r; + let take_over = *take_over; // Only one still paused: one taken off meanwhile stays off. Taken // over, it's no longer kept: its new owner chooses that for theirs. let resumed = q( &ctx.db, - "UPDATE autopilots SET state = 'on', paused_reason = NULL, paused_by = NULL, paused_at = NULL, failures = 0, \ + "UPDATE autopilots SET state = 'on', paused_reason = NULL, paused_by = NULL, paused_at = NULL, paused_itself = 0, failures = 0, \ wake_at = ?1, wake_reasons = 'resumed', asked_wake_at = NULL, owner_id = CASE WHEN ?2 THEN ?3 ELSE owner_id END, \ keep_owner = CASE WHEN ?2 THEN 0 ELSE keep_owner END, updated_at = ?1 \ WHERE project_id = ?4 AND state = 'paused' AND owner_id IS ?5 AND keep_owner = ?6", @@ -1449,20 +1519,28 @@ pub async fn resume(ctx: &mut Ctx, id: &str) -> AppResult { }, )); } + let with = if message { + " with a message to its session" + } else { + "" + }; engine::log( &ctx.db, &row.project_id, Entry::new( AutopilotEntryKind::State, if take_over { - format!("{} resumed it, on their subscription from now on", ap::WHO) + format!( + "{} resumed it{with}, on their subscription from now on", + ap::WHO + ) } else if !mine { format!( - "{} resumed it, on its owner's subscription, as they keep it", + "{} resumed it{with}, on its owner's subscription, as they keep it", ap::WHO ) } else { - format!("{} resumed it", ap::WHO) + format!("{} resumed it{with}", ap::WHO) }, ) .by(&me.id), @@ -1470,13 +1548,13 @@ pub async fn resume(ctx: &mut Ctx, id: &str) -> AppResult { ) .await; ctx.audit_in( - Some(l.p.workspace_id()), + Some(p.workspace_id()), "autopilot.resumed", Some(&row.project_id), - Some(serde_json::json!({ "taken_over": take_over })), + Some(serde_json::json!({ "taken_over": take_over, "message": message })), ); crate::schedules::wake(&ctx.env).await; - get(ctx, id).await + Ok(()) } /// `POST …/autopilot/wake`: a person wakes it now, with `fresh` in a fresh diff --git a/crates/fctl-control/src/api/sessions.rs b/crates/fctl-control/src/api/sessions.rs index 68efe2973..e7b0cb467 100644 --- a/crates/fctl-control/src/api/sessions.rs +++ b/crates/fctl-control/src/api/sessions.rs @@ -630,6 +630,12 @@ pub async fn send_message(ctx: &mut Ctx, req: &mut Request, id: &str) -> AppResu if !status.accepts_messages() && !status.resumes_for_messages() { return Err(conflict("The session failed. Resume it to continue.")); } + // The paused autopilot whose own session this is, which the message + // resumes: checked before anything goes. + let waking = match body.wake_autopilot { + Some(true) => wakes(ctx, &a.row).await?, + _ => None, + }; let author = ctx.user()?.clone(); let attachments = internal::claim_files( &ctx.env, @@ -657,6 +663,24 @@ pub async fn send_message(ctx: &mut Ctx, req: &mut Request, id: &str) -> AppResu { return http::ok(&held); } + // On the Claude connection the autopilot runs on once resumed, as its + // wake would move it, should someone take it over as they resume it. + if let Some((_, on)) = &waking + && a.row.credential_id.as_deref() != Some(on.credential.id.as_str()) + && let Ok(way) = fctl_domain::claude::moving(status) + { + move_to( + &ctx.env, + &ctx.db, + &a.row.session_id(), + way, + &on.credential, + &on.user.to_ref(), + false, + ctx.now, + ) + .await?; + } let delivery_id = deliver_message( ctx, id, @@ -667,12 +691,71 @@ pub async fn send_message(ctx: &mut Ctx, req: &mut Request, id: &str) -> AppResu attachments, ) .await?; + // Then the autopilot: its wake finds the session about to take the + // message up (`ap::own_status`) and reaches it there, at its next step, + // rather than in a fresh session. + let mut woke_autopilot = false; + if let Some((r, _)) = &waking { + woke_autopilot = true; + crate::api::autopilots::resumed(ctx, r, true).await.or_else(|e| { + // Resumed by someone else meanwhile: it takes the message up + // all the same. + if e.0.message.starts_with("It isn't paused any more") { + Ok(()) + } else { + Err(AppError(ApiError::new( + ErrorCode::Conflict, + format!( + "The message went to the session, but the autopilot is still paused: {}", + e.0.message + ), + ))) + } + })?; + } http::ok(&SendMessageResponse { delivery_id, held: None, + woke_autopilot, }) } +/// The resume of the paused autopilot whose own session `row` is, for a +/// message to it that wakes it (`SendMessageRequest::wake_autopilot`), with +/// the Claude connection it runs on then: `None` when it is on already, +/// and the message goes as it is. +async fn wakes( + ctx: &Ctx, + row: &SessionRow, +) -> AppResult> { + let (true, Some(home)) = (row.is_pilot(), row.autopilot_id.as_deref()) else { + return Err(validation( + "wake_autopilot", + "Only a message to an autopilot's own session wakes it.", + )); + }; + match crate::autopilots::by_pilot(&ctx.db, &row.id).await? { + None => { + return Err(conflict( + "The autopilot works in a newer session of its own now: send the message there, where it wakes.", + )); + } + Some(a) if a.state() == fctl_proto::autopilot::AutopilotState::Off => { + return Err(conflict( + "This project is off autopilot: send the message without waking it, or put the project on autopilot again on its Autopilot tab.", + )); + } + Some(_) => {} + } + let Some(r) = crate::api::autopilots::resuming(ctx, home).await? else { + return Ok(None); + }; + // One that couldn't run would pause again at its wake, its message + // taken up alone. + let on = r.runs_on(ctx).await?.map_err(|why| conflict(&why))?; + Ok(Some((r, on))) +} + /// The autopilot whose request this is, as a message's author shows it. fn message_autopilot(ctx: &Ctx) -> Option { ctx.autopilot().map(|a| a.author()) @@ -784,6 +867,7 @@ pub async fn interrupt(ctx: &mut Ctx, id: &str) -> AppResult { http::ok(&SendMessageResponse { delivery_id: out.delivery_id, held: None, + woke_autopilot: false, }) } @@ -817,6 +901,7 @@ pub async fn pass_on(ctx: &mut Ctx, id: &str, review: &str) -> AppResult AppResult, #[serde(deserialize_with = "opt_int", default)] pub paused_at: Option, + /// It paused itself, rather than fctl pausing it. + #[serde(deserialize_with = "int_bool", default)] + pub paused_itself: bool, pub owner_id: Option, #[serde(deserialize_with = "int_bool", default)] pub keep_owner: bool, @@ -121,16 +124,23 @@ pub struct AutopilotRow { /// The tokens in its own session's context, as it last said. #[serde(deserialize_with = "opt_int", default)] pub session_context: Option, + /// When a person last messaged its own session, and when that session + /// last changed: a message since says it is about to work. + #[serde(deserialize_with = "opt_int", default)] + pub session_messaged_at: Option, + #[serde(deserialize_with = "opt_int", default)] + pub session_updated_at: Option, } pub const AUTOPILOT_SELECT: &str = "SELECT a.project_id, a.workspace_id, a.scope, a.state, a.paused_reason, \ - a.paused_by, a.paused_at, a.owner_id, a.keep_owner, a.direction, a.direction_by, a.direction_at, a.direction_new, a.plan, \ + a.paused_by, a.paused_at, a.paused_itself, a.owner_id, a.keep_owner, a.direction, a.direction_by, a.direction_at, a.direction_new, a.plan, \ a.plan_at, a.powers, a.check_in_minutes, a.crew_max, a.model, a.effort, a.handoff_at, a.session_id, a.wake_at, a.wake_reasons, \ a.asked_wake_at, a.woken_at, a.check_ins, a.failures, a.created_at, a.updated_at, \ ou.name AS owner_name, ou.avatar_url AS owner_avatar, pu.name AS paused_by_name, pu.avatar_url AS paused_by_avatar, \ du.name AS direction_by_name, du.avatar_url AS direction_by_avatar, \ ps.number AS session_number, ps.status AS session_status, ps.created_at AS session_created_at, \ - ps.credential_id AS session_credential_id, json_extract(ps.stats, '$.context_tokens') AS session_context \ + ps.credential_id AS session_credential_id, json_extract(ps.stats, '$.context_tokens') AS session_context, \ + ps.messaged_at AS session_messaged_at, ps.updated_at AS session_updated_at \ FROM autopilots a \ LEFT JOIN users ou ON ou.id = a.owner_id \ LEFT JOIN users pu ON pu.id = a.paused_by \ @@ -223,6 +233,13 @@ impl AutopilotRow { .and_then(SessionStatus::parse) } + /// Its own session's status as a wake weighs it: at work once a + /// person's message is on its way to it ([`ap::own_status`]). + pub fn session_status_now(&self, now: i64) -> Option { + self.session_status() + .map(|st| ap::own_status(st, self.session_messaged_at, self.session_updated_at, now)) + } + pub fn owner_ref(&self) -> Option { user_ref( self.owner_id.as_deref(), @@ -776,20 +793,41 @@ pub async fn run_due(env: &Env, now: i64) -> AppResult { Ok(woke) } -/// Pauses an autopilot fctl can't run, or that paused itself, saying why; -/// `by` the person who did. +/// Who pauses an autopilot ([`pause`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PausedBy<'a> { + /// fctl, which can't run it. + Fctl, + /// The autopilot itself, done or waiting for people. + Itself, + /// A person, by id. + Person(&'a str), +} + +/// Pauses an autopilot, saying why. pub async fn pause( db: &D1Database, project_id: &str, why: Option<&str>, - by: Option<&str>, + by: PausedBy<'_>, now: i64, ) -> AppResult { + let person = match by { + PausedBy::Person(id) => Some(id), + PausedBy::Fctl | PausedBy::Itself => None, + }; let paused = q( db, - "UPDATE autopilots SET state = 'paused', paused_reason = ?, paused_by = ?, paused_at = ?, wake_at = NULL, \ - wake_reasons = '', asked_wake_at = NULL, updated_at = ? WHERE project_id = ? AND state = 'on'", - &[os(why), os(by), n(now), n(now), s(project_id)], + "UPDATE autopilots SET state = 'paused', paused_reason = ?, paused_by = ?, paused_at = ?, paused_itself = ?, \ + wake_at = NULL, wake_reasons = '', asked_wake_at = NULL, updated_at = ? WHERE project_id = ? AND state = 'on'", + &[ + os(why), + os(person), + n(now), + crate::db::b(by == PausedBy::Itself), + n(now), + s(project_id), + ], )? .run() .await?; @@ -817,7 +855,7 @@ pub async fn pause_workspace( .await?; let why = "Its workspace's admins turned autopilots off."; for a in on { - if pause(db, &a.project_id, Some(why), Some(by), now).await? { + if pause(db, &a.project_id, Some(why), PausedBy::Person(by), now).await? { log( db, &a.project_id, @@ -913,7 +951,8 @@ async fn take_up(env: &Env, db: &D1Database, row: &AutopilotRow, now: i64) -> Ap .await?; return Ok(true); } - let status = row.session_status(); + // One a person just messaged works already (`ap::own_status`). + let status = row.session_status_now(now); // People asked for a fresh session while its own works: the wake // waits for that one's turn to end, which wakes it again at once // (`session_moved`; here, should it have ended since it was read), @@ -1404,7 +1443,7 @@ fn woke_line(reasons: &[AutopilotWakeReason], wake: &AutopilotWake) -> String { /// Pauses an autopilot fctl can no longer run, saying why, in its log and /// the workspace's audit log. async fn stop_for(db: &D1Database, row: &AutopilotRow, why: &str, now: i64) -> AppResult<()> { - if pause(db, &row.project_id, Some(why), None, now).await? { + if pause(db, &row.project_id, Some(why), PausedBy::Fctl, now).await? { log( db, &row.project_id, @@ -2808,6 +2847,7 @@ pub async fn hold( return Ok(Some(SendMessageResponse { delivery_id: DeliveryId(h.delivery_id.clone()), held: Some(h.view(ahead)), + woke_autopilot: false, })); } let Some(row) = row(db, &caller.project_id).await? else { @@ -2862,6 +2902,7 @@ pub async fn hold( return Ok(Some(SendMessageResponse { delivery_id, held: None, + woke_autopilot: false, })); } Ok(_) => {} @@ -2877,7 +2918,11 @@ pub async fn hold( .enumerate() .find(|(_, h)| h.id == id) .map(|(ahead, h)| h.view(ahead)); - Ok(Some(SendMessageResponse { delivery_id, held })) + Ok(Some(SendMessageResponse { + delivery_id, + held, + woke_autopilot: false, + })) } /// Whether a message of the autopilot `row`'s to its session `session_id` @@ -4295,6 +4340,104 @@ mod tests { Ok(()) } + /// Its own session a person just messaged, as it waited, is at work to + /// a wake, which then reaches it rather than a fresh session, however + /// long its shift: a message that resumed the autopilot goes first. + #[wasm_bindgen_test] + async fn a_wake_finds_its_session_about_to_take_a_message_up() -> AppResult<()> { + let db = testing::database(); + autopilot(&db).await?; + q( + &db, + "INSERT INTO sessions (id, project_id, number, title, prompt, status, created_by, credential_id, \ + claude_session_id, created_at, updated_at, autopilot_id, autopilot_role) \ + VALUES ('ses_1', 'prj_web', 1, 'Autopilot', 'You are…', 'idle', 'usr_ada', 'crd_old', 'ses_1', ?1, ?2, \ + 'prj_web', 'pilot')", + &[n(NOW - 20 * HOUR), n(NOW - 2 * HOUR)], + )? + .run() + .await?; + q( + &db, + "UPDATE autopilots SET session_id = 'ses_1' WHERE project_id = 'prj_web'", + &[], + )? + .run() + .await?; + let own = |r: &AutopilotRow| ap::OwnSession { + status: r.session_status_now(NOW).unwrap_or(SessionStatus::Failed), + started_at: r.session_created_at.unwrap_or(0), + context_tokens: None, + }; + // Resting past its shift: a wake hands off. + let r = row_of(&db).await?; + assert_eq!(r.session_status_now(NOW), Some(SessionStatus::Idle)); + assert_eq!(ap::fresh(own(&r), None, false, NOW), Some(ap::Fresh::Shift)); + // A person's message, as SessionDO writes it through: the wake + // carries on in it. + q( + &db, + "UPDATE sessions SET messaged_at = ?1, updated_at = ?1 WHERE id = 'ses_1'", + &[n(NOW - 1_000)], + )? + .run() + .await?; + let r = row_of(&db).await?; + assert_eq!(r.session_status(), Some(SessionStatus::Idle)); + assert_eq!(r.session_status_now(NOW), Some(SessionStatus::Running)); + assert_eq!(ap::fresh(own(&r), None, false, NOW), None); + Ok(()) + } + + /// Whether it paused itself, as people read it: not when fctl or a + /// person did, and no more once it is on again. + #[wasm_bindgen_test] + async fn it_says_when_it_paused_itself() -> AppResult<()> { + let db = testing::database(); + autopilot(&db).await?; + let on_again = |db: &D1Database| { + q( + db, + "UPDATE autopilots SET state = 'on' WHERE project_id = 'prj_web'", + &[], + ) + }; + assert!( + pause( + &db, + "prj_web", + Some("Waiting for the Stripe keys."), + PausedBy::Itself, + NOW + ) + .await? + ); + let r = row_of(&db).await?; + assert!(r.paused_itself); + assert_eq!(r.paused_by, None); + // Paused already: nothing changes. + assert!(!pause(&db, "prj_web", None, PausedBy::Fctl, NOW).await?); + assert!(row_of(&db).await?.paused_itself); + on_again(&db)?.run().await?; + assert!( + pause( + &db, + "prj_web", + Some("Its project is archived."), + PausedBy::Fctl, + NOW + ) + .await? + ); + assert!(!row_of(&db).await?.paused_itself); + on_again(&db)?.run().await?; + assert!(pause(&db, "prj_web", None, PausedBy::Person("usr_ada"), NOW).await?); + let r = row_of(&db).await?; + assert!(!r.paused_itself); + assert_eq!(r.paused_by.as_deref(), Some("usr_ada")); + Ok(()) + } + /// Adds `count` notes to a project's memory, stale since `stale_at` /// when it says so. async fn notes( diff --git a/crates/fctl-domain/src/autopilot.rs b/crates/fctl-domain/src/autopilot.rs index d9bc3b0c4..6e3f8768e 100644 --- a/crates/fctl-domain/src/autopilot.rs +++ b/crates/fctl-domain/src/autopilot.rs @@ -611,6 +611,33 @@ pub fn failing(failures: u32, why: &str, waking: bool) -> String { } } +/// How long a person's message to its own session that waits for one +/// counts as setting it to work ([`own_status`]): its runner reports the +/// turn within seconds, unless it is offline. +pub const MESSAGE_ON_ITS_WAY_MS: Millis = 10 * 60_000; + +/// Its own session's status as a wake weighs it: one waiting for a message +/// (`Idle`) that a person messaged since it last changed, less than +/// [`MESSAGE_ON_ITS_WAY_MS`] ago, is at work (`Running`) already, as its +/// runner reports only once its agent takes the message up. A wake that +/// comes meanwhile then reaches it at its next step, rather than hand off +/// to a fresh session and stop it under the message: one that resumed the +/// autopilot with it (`SendMessageRequest.wake_autopilot`) among them. A +/// stopped one that a message resumes is `Queued` already. +pub fn own_status( + status: SessionStatus, + messaged_at: Option, + updated_at: Option, + now: Millis, +) -> SessionStatus { + match (status, messaged_at, updated_at) { + (SessionStatus::Idle, Some(m), Some(u)) if m >= u && now - m < MESSAGE_ON_ITS_WAY_MS => { + SessionStatus::Running + } + _ => status, + } +} + /// Its own session, as a wake finds it. #[derive(Clone, Copy, Debug)] pub struct OwnSession { @@ -3815,6 +3842,48 @@ mod tests { )); } + #[test] + fn a_message_on_its_way_keeps_a_wake_in_its_session() { + let now = 100 * HOUR_MS; + let messaged = Some(now - 2_000); + // A person wrote to it as it waited: the wake carries on in it, at + // its next step, however long its shift has run. + let st = own_status(SessionStatus::Idle, messaged, messaged, now); + assert_eq!(st, SessionStatus::Running); + let old = OwnSession { + status: st, + started_at: now - 20 * HOUR_MS, + context_tokens: None, + }; + assert_eq!(fresh(old, None, false, now), None); + assert!(!between_turns(st)); + // Before the message, or once the session changed since (its turn + // began, or ended), it is as it says. + assert_eq!( + own_status(SessionStatus::Idle, Some(now - 5_000), messaged, now), + SessionStatus::Idle + ); + assert_eq!( + own_status(SessionStatus::Idle, None, messaged, now), + SessionStatus::Idle + ); + // A message its runner never took up, offline say, counts no more. + let long_ago = Some(now - MESSAGE_ON_ITS_WAY_MS); + assert_eq!( + own_status(SessionStatus::Idle, long_ago, long_ago, now), + SessionStatus::Idle + ); + // Others are as they say: a stopped one a message resumes is queued. + assert_eq!( + own_status(SessionStatus::Stopped, messaged, messaged, now), + SessionStatus::Stopped + ); + assert_eq!( + own_status(SessionStatus::Queued, messaged, messaged, now), + SessionStatus::Queued + ); + } + #[test] fn people_choose_where_it_hands_off_within_claudes_bounds() { assert_eq!(handoff_at(0), Ok(None)); diff --git a/crates/fctl-proto/src/api.rs b/crates/fctl-proto/src/api.rs index 97de3cd18..a354360a4 100644 --- a/crates/fctl-proto/src/api.rs +++ b/crates/fctl-proto/src/api.rs @@ -3902,6 +3902,14 @@ pub struct SendMessageRequest { #[serde(default, skip_serializing_if = "Vec::is_empty")] #[cfg_attr(feature = "ts", ts(as = "Option>", optional))] pub attachments: Vec, + /// To the session an autopilot works in now, while it is paused: + /// resume the autopilot with the message, for those who steer it, so + /// that its agent takes it up as the autopilot (its `fctl` reaches the + /// API again: it plans, starts and steers sessions) rather than alone. + /// The message goes first, and fctl then wakes the autopilot in that + /// session with what is new. One that is on already takes the message + /// as it is. Control planes from before it ignore it. + pub wake_autopilot: Option, } #[skip_serializing_none] @@ -3915,6 +3923,11 @@ pub struct SendMessageResponse { /// sends it once one of them makes room. Absent for one that went. #[serde(default)] pub held: Option, + /// It resumed the paused autopilot whose own session it went to + /// (`SendMessageRequest::wake_autopilot`): false when that autopilot + /// was on already, and from control planes before it. + #[serde(default)] + pub woke_autopilot: bool, } /// A file sent in a session, with a message or as it started. diff --git a/crates/fctl-proto/src/autopilot.rs b/crates/fctl-proto/src/autopilot.rs index e0da17088..0a18a276f 100644 --- a/crates/fctl-proto/src/autopilot.rs +++ b/crates/fctl-proto/src/autopilot.rs @@ -171,6 +171,11 @@ pub struct Autopilot { /// Who paused or took it off; absent when fctl or the autopilot did. pub paused_by: Option, pub paused_at: Option, + /// It paused itself (`fctl autopilot pause`), done or waiting for + /// people, rather than fctl pausing it: absent (false) when fctl or a + /// person did, and from control planes before it. + #[serde(default)] + pub paused_itself: bool, /// Whose Claude subscription it runs on, and as whom it acts: who put /// the project on autopilot, or took it over since. Absent once their /// account is gone. diff --git a/crates/fctl/src/cmd/sessions.rs b/crates/fctl/src/cmd/sessions.rs index e1ce13a0b..08e461076 100644 --- a/crates/fctl/src/cmd/sessions.rs +++ b/crates/fctl/src/cmd/sessions.rs @@ -1243,6 +1243,7 @@ pub async fn send( message: &str, attach: &[PathBuf], key: Option<&str>, + wake: bool, json: bool, ) -> Result<()> { let given = key.map(send_key).transpose()?; @@ -1264,9 +1265,15 @@ pub async fn send( .clone() .unwrap_or_else(|| fctl_domain::ids::new_id("cli", style::now_ms())); let client_id = fingerprint.key(&key); - let r = deliver(&api, &s.id.0, &text, attachments, client_id, |e, wait| { - trying_again("Sending", e, wait) - }) + let r = deliver( + &api, + &s.id.0, + &text, + attachments, + client_id, + wake, + |e, wait| trying_again("Sending", e, wait), + ) .await .map_err(|n| { let session = format!("{}#{}", s.project_slug, s.number); @@ -1295,6 +1302,15 @@ pub async fn send( ); return Ok(()); } + if r.woke_autopilot { + println!( + "{} Sent to {}#{}, and resumed its autopilot: it takes the message up as the autopilot, with what's new since it paused", + style::accent("✓"), + s.project_slug, + s.number + ); + return Ok(()); + } let resumes = if s.status.resumes_for_messages() { "; the session resumes for it" } else { @@ -1306,9 +1322,32 @@ pub async fn send( s.project_slug, s.number ); + // To the session a paused autopilot works in, its agent takes the + // message up alone: say so, and how to wake it next time. + if !wake && let Some(why) = paused_pilot(&api, &s).await { + eprintln!("{}", style::dim(&why)); + } Ok(()) } +/// What a message to `s` misses when it is the session a paused autopilot +/// works in: the autopilot doesn't take it up. +async fn paused_pilot(api: &Api, s: &fctl_proto::session::Session) -> Option { + use fctl_proto::autopilot::{AutopilotRole, AutopilotState}; + let home = s + .autopilot + .as_ref() + .filter(|a| a.role == AutopilotRole::Pilot)?; + let a = api.autopilot(&home.project_id.0).await.ok()?; + let here = a.session.as_ref().is_some_and(|own| own.id == s.id); + (a.state == AutopilotState::Paused && here).then(|| { + format!( + "Its autopilot is paused, so the session's agent takes this up alone: it can't start or steer sessions, or keep the plan. fctl send --wake {}#{} \"…\" resumes the autopilot with a message.", + s.project_slug, s.number + ) + }) +} + /// What went wrong, as the server said it. fn why(e: &fctl_client::Error) -> String { e.api().map_or_else(|| e.to_string(), |e| e.message.clone()) @@ -1429,17 +1468,27 @@ const SEND_KEY_CHARS: usize = 100; /// answers again with the first delivery for a day, so that a try whose /// answer was lost, or that failed after the message was kept, doesn't /// deliver it twice. `retried` hears of each error tried again. +#[allow(clippy::too_many_arguments)] async fn deliver( api: &Api, session: &str, text: &str, attachments: Vec, client_id: String, + wake: bool, mut retried: impl FnMut(&fctl_client::Error, Duration), ) -> std::result::Result { let mut maybe_kept = false; fctl_client::http::retrying( - || api.send_message(session, text, Some(client_id.clone()), attachments.clone()), + || { + api.send_message( + session, + text, + Some(client_id.clone()), + attachments.clone(), + wake, + ) + }, |e, wait| { maybe_kept = true; retried(e, wait); @@ -1821,6 +1870,7 @@ mod tests { "Also add a test", Vec::new(), "cli_01ABC:5e1f".into(), + false, |e, wait| { retried.push((e.api().map(|e| e.code), wait)); }, @@ -1836,7 +1886,32 @@ mod tests { assert!(first.iter().all(|(method, path, b)| method == "POST" && path == "/api/v1/sessions/ses_01ABC/messages" && b["client_id"] == "cli_01ABC:5e1f" - && b["text"] == "Also add a test")); + && b["text"] == "Also add a test" + && b.get("wake_autopilot").is_none())); + } + + #[tokio::test(start_paused = true)] + async fn a_message_that_wakes_its_autopilot_says_so_each_try() { + use fctl_proto::ErrorCode::Internal; + let (api, sent) = relayed(vec![Some(Internal)]); + let r = deliver( + &api, + "ses_01ABC", + "The keys are in the project's secrets now", + Vec::new(), + "cli_01ABC:77aa".into(), + true, + |_, _| {}, + ) + .await; + assert!(r.is_ok()); + let tries = got(&sent); + assert_eq!(tries.len(), 2); + assert!( + tries + .iter() + .all(|(_, _, b)| b["wake_autopilot"] == true && b["client_id"] == "cli_01ABC:77aa") + ); } #[test] @@ -1881,6 +1956,7 @@ mod tests { "Also add a test", Vec::new(), "cli_01ABC:5e1f".into(), + false, |_, _| {}, ) .await; diff --git a/crates/fctl/src/main.rs b/crates/fctl/src/main.rs index 2ba68df7c..87ad13e3d 100644 --- a/crates/fctl/src/main.rs +++ b/crates/fctl/src/main.rs @@ -341,6 +341,12 @@ Examples: /// failed send names the key it used. #[arg(long, value_name = "KEY")] key: Option, + /// To the session a paused autopilot works in: resume the + /// autopilot with the message, so that it takes it up as the + /// autopilot (planning, starting and steering sessions) rather + /// than its agent alone. Takes steering the autopilot. + #[arg(long)] + wake: bool, }, /// The files sent in a session, with its messages or as it started: /// list them, and download them. @@ -627,6 +633,7 @@ async fn run(cli: Cli) -> anyhow::Result<()> { message, attach, key, + wake, } => { cmd::sessions::send( server, @@ -634,6 +641,7 @@ async fn run(cli: Cli) -> anyhow::Result<()> { &message.join(" "), &attach, key.as_deref(), + wake, json, ) .await diff --git a/web/src/components/project/autopilot.test.tsx b/web/src/components/project/autopilot.test.tsx index 2d634255b..eab92921d 100644 --- a/web/src/components/project/autopilot.test.tsx +++ b/web/src/components/project/autopilot.test.tsx @@ -133,6 +133,7 @@ const on = (more: Partial = {}): G.Autopilot => ({ owner: { id: "usr_ada", name: "Ada" }, keep_owner: false, fresh_asked: false, + paused_itself: false, direction: "Ship the **checkout**.", direction_at: Date.now() - 3_600_000, powers: ["settings"], diff --git a/web/src/components/session/composer.tsx b/web/src/components/session/composer.tsx index df871cf18..c27f48a87 100644 --- a/web/src/components/session/composer.tsx +++ b/web/src/components/session/composer.tsx @@ -2,7 +2,8 @@ // the box for the page's keys, and r, on the page, comes back to it. Files come // along with the paperclip, a paste, or a drop anywhere on the page. In an // earlier session of an autopilot's own, a message asks first whether it goes -// to the session the autopilot works in now (moved-on.tsx). +// to the session the autopilot works in now (moved-on.tsx); in the session a +// paused autopilot works in, whether it wakes the autopilot (paused-pilot.tsx). import { ArrowUp, Square } from "lucide-react"; import { type KeyboardEvent, type ReactNode, useRef, useState } from "react"; @@ -22,6 +23,10 @@ import { } from "./attachments"; import { SignInHint } from "./claude-refused"; import { type MovedOn, MovedOnCard, MovedOnLine } from "./moved-on"; +import { PausedCard, PausedLine, type PausedPilot } from "./paused-pilot"; + +/** Where a message goes: here, to where the autopilot works now, or here waking the autopilot. */ +type Way = "here" | "there" | "wake"; export function Composer({ status, @@ -37,6 +42,7 @@ export function Composer({ onTakeOver, limitOf, movedOn, + paused, suspended, refused, onConnectClaude, @@ -46,7 +52,8 @@ export function Composer({ viewers: G.Presence[]; meId?: string; sessionId: string; - onSend: (text: string, files: SentFiles) => Promise; + /** Sends it here; with `wakeAutopilot`, resumes the paused autopilot whose session this is too. */ + onSend: (text: string, files: SentFiles, opts?: { wakeAutopilot?: boolean }) => Promise; onInterrupt: () => void; onTyping: () => void; onResume: (text: string, files: SentFiles) => Promise; @@ -61,6 +68,8 @@ export function Composer({ limitOf?: string; /** An earlier session of an autopilot's own: where it works now, which a message goes to instead. */ movedOn?: MovedOn; + /** The session a paused autopilot works in: a message asks first whether it wakes it. */ + paused?: PausedPilot; /** Its microVM is suspended: a message resumes it first. */ suspended?: boolean; /** @@ -72,7 +81,7 @@ export function Composer({ onConnectClaude?: () => void; }) { const [text, setText] = useState(""); - const [sending, setSending] = useState<"here" | "there">(); + const [sending, setSending] = useState(); // The session whose earlier-session card is open, and the one sent to anyway: the page stays as // it goes to another session, and they are this one's. const [asking, setAsking] = useState(); @@ -100,15 +109,18 @@ export function Composer({ // a message typed afresh asks afresh. Sent here anyway, it asks no more until the reader leaves. if (asking !== undefined && ((!ready && !sending) || asking !== sessionId)) setAsking(undefined); if (anyway !== undefined && anyway !== sessionId) setAnyway(undefined); - const asks = !!movedOn && anyway !== sessionId; + const asks = (!!movedOn || !!paused) && anyway !== sessionId; const askOpen = asks && asking === sessionId; const keepEditing = () => { setAsking(undefined); ref.current?.focus(); }; - /** Sends it here, or, from an earlier session of the autopilot's, where it works now. */ - const submit = async (to?: "here" | "there") => { + /** + * Sends it here; from an earlier session of the autopilot's, where it works now; or here, waking + * the paused autopilot whose session this is. + */ + const submit = async (to?: Way) => { const t = text.trim(); if (!ready || sending) return; if (asks && !to) { @@ -125,9 +137,10 @@ export function Composer({ restore = taken.restore; setText(""); if (where === "there" && movedOn) await movedOn.send(t, taken.files); + else if (where === "wake" && paused) await onSend(t, taken.files, { wakeAutopilot: true }); else if (failed) await onResume(t, taken.files); else await onSend(t, taken.files); - if (where === "here" && movedOn) setAnyway(sessionId); + if (where === "here" && (movedOn || paused)) setAnyway(sessionId); setAsking(undefined); } catch (e) { setText(t); @@ -168,13 +181,24 @@ export function Composer({ void submit("there")} onHere={() => void submit("here")} onClose={keepEditing} /> )} + {askOpen && paused && !movedOn && ( + void submit("wake")} + onHere={() => void submit("here")} + onClose={keepEditing} + /> + )}
{typing.length > 0 ? ( @@ -182,6 +206,8 @@ export function Composer({ ) : movedOn && !askOpen ? ( + ) : paused && !askOpen && anyway !== sessionId ? ( + ) : signIn ? ( ) : refused ? ( diff --git a/web/src/components/session/moved-on.test.tsx b/web/src/components/session/moved-on.test.tsx index 0e78aae8d..aa5b91698 100644 --- a/web/src/components/session/moved-on.test.tsx +++ b/web/src/components/session/moved-on.test.tsx @@ -35,6 +35,7 @@ function movedOn(more: Partial = {}): MovedOn { return { session: { id: "ses_20", number: 20, status: "running", started_at: NOW - 2 * 3_600_000 }, paused: false, + wakes: false, word: { tone: "accent", word: "At work" }, send: vi.fn(async () => {}), ...more, @@ -222,6 +223,20 @@ describe("a message in an earlier session of the autopilot's own", () => { expect(c.card()?.textContent).toContain("acts again once someone resumes it"); }); + it("wakes a paused autopilot there, for those who steer it", async () => { + const to = movedOn({ paused: true, wakes: true, word: { tone: "pink", word: "Paused" } }); + const c = composer(to); + c.type("The keys are in the project's secrets"); + await c.enter(); + expect(document.activeElement).toBe(c.way("Wake it and send to #20")); + expect(c.card()?.textContent).toContain("it resumes, and takes your message up there as the autopilot"); + await c.click(c.way("Wake it and send to #20")); + expect(to.send).toHaveBeenCalledWith("The keys are in the project's secrets", { + attachments: [], + previews: {}, + }); + }); + it("says why a message can't go where it works now", () => { const running = { status: "running" as const }; expect(blockedOf(running, "editor", null)).toBeUndefined(); @@ -230,6 +245,9 @@ describe("a message in an earlier session of the autopilot's own", () => { expect(blockedOf({ status: "failed" }, "owner", null)).toBe( "It failed: fctl starts the autopilot a fresh session at its next wake.", ); + expect(blockedOf({ status: "failed" }, "owner", null, true)).toBe( + "It failed: fctl starts the autopilot a fresh session once someone resumes it.", + ); expect(blockedOf(running, "viewer", null)).toMatch(/^You can follow it, but not message it/); expect(blockedOf(running, undefined, new ApiFailure(404, {}))).toBe( "You can't open that session, so you can't message it.", diff --git a/web/src/components/session/moved-on.tsx b/web/src/components/session/moved-on.tsx index 6f6f059a9..f1adf0827 100644 --- a/web/src/components/session/moved-on.tsx +++ b/web/src/components/session/moved-on.tsx @@ -4,14 +4,13 @@ // autopilot: its `fctl` reaches nothing, so a message there gets the work done in that session // alone, rather than planned and handed to sessions. Above the box a line says where the autopilot // works now, and a message asks first, in a card over the box: send it there, and go with it, or -// here anyway. Once sent here anyway, the page asks no more. +// here anyway. Once sent here anyway, the page asks no more. While the autopilot is paused, sending +// it there wakes it too, for those who steer it (paused-pilot.tsx). import { useQuery } from "@tanstack/react-query"; import { Link, useNavigate } from "@tanstack/react-router"; -import { ArrowUp, X } from "lucide-react"; -import { forwardRef, type KeyboardEvent, type ReactNode, useEffect, useId, useRef } from "react"; import { useAutopilot, useNow } from "@/components/project/autopilot"; -import { AutopilotIcon, IconButton, Spinner, toast } from "@/components/ui"; +import { AutopilotIcon, toast } from "@/components/ui"; import type * as G from "@/gen"; import { ApiFailure, api } from "@/lib/api"; import { movedOn, sessionWord } from "@/lib/autopilot"; @@ -19,6 +18,8 @@ import { cn } from "@/lib/cn"; import { agoShortWords, stamp } from "@/lib/format"; import { keys } from "@/lib/queries"; import type { SentFiles } from "./attachments"; +import { refreshAutopilot } from "./paused-pilot"; +import { WaysCard } from "./ways"; /** Where the autopilot works now, for an earlier session of its own: what its message box needs. */ export interface MovedOn { @@ -26,6 +27,8 @@ export interface MovedOn { session: G.AutopilotSession; /** The autopilot is paused: it acts again once someone resumes it. */ paused: boolean; + /** Paused, and the reader steers it: the message there resumes it. */ + wakes: boolean; /** How that session stands, beside its dot. */ word: ReturnType; /** Why the message can't go there, when it can't; until that session loads, the reader may try. */ @@ -48,19 +51,28 @@ export function useMovedOn(session: G.Session | undefined): MovedOn | undefined staleTime: 30_000, }); if (!a || !to) return; + const paused = a.state === "paused"; + const wakes = paused && a.can.steer; return { session: to, - paused: a.state === "paused", + paused, + wakes, word: sessionWord(a), - blocked: blockedOf(to, there.data?.role, there.error), + blocked: blockedOf(to, there.data?.role, there.error, paused), send: async (text, files) => { - await api.sendMessage(to.id, { + const r = await api.sendMessage(to.id, { text, client_id: `web-${Date.now().toString(36)}-moved`, attachments: files.attachments.map((f) => f.id), + wake_autopilot: wakes || undefined, }); for (const url of Object.values(files.previews)) URL.revokeObjectURL(url); - toast(`Sent to #${to.number}, where the autopilot works now`); + if (r.woke_autopilot) refreshAutopilot(a); + toast( + r.woke_autopilot + ? `Woke the autopilot in #${to.number} with your message` + : `Sent to #${to.number}, where the autopilot works now`, + ); void navigate({ to: "/s/$id", params: { id: to.id } }); }, }; @@ -71,8 +83,12 @@ export function blockedOf( to: Pick, role: G.SessionRole | undefined, error: unknown, + paused?: boolean, ): string | undefined { - if (to.status === "failed") return "It failed: fctl starts the autopilot a fresh session at its next wake."; + if (to.status === "failed") + return paused + ? "It failed: fctl starts the autopilot a fresh session once someone resumes it." + : "It failed: fctl starts the autopilot a fresh session at its next wake."; if (error instanceof ApiFailure && (error.status === 403 || error.status === 404)) return "You can't open that session, so you can't message it."; if (role && role !== "editor" && role !== "owner") @@ -108,8 +124,8 @@ export function MovedOnLine({ to }: { to: MovedOn }) { /** * Asks before a message goes to an earlier session of the autopilot's own: send it to the one it - * works in now (first, and focused: Enter again sends it there), or here anyway. Escape, or ×, - * goes back to the message, as it was. + * works in now (first, and focused: Enter again sends it there), waking the autopilot when it is + * paused and the reader may, or here anyway. Escape, or ×, goes back to the message, as it was. */ export function MovedOnCard({ to, @@ -132,73 +148,35 @@ export function MovedOnCard({ onClose: () => void; }) { const now = useNow(30_000); - const title = useId(); - const text = useId(); - const first = useRef(null); - const second = useRef(null); - // As it opens, and as people send again, the way to where the autopilot is has the focus. - // biome-ignore lint/correctness/useExhaustiveDependencies: nudge is what brings it back. - useEffect(() => { - (first.current?.disabled ? second.current : first.current)?.focus(); - }, [nudge]); const n = `#${to.session.number}`; - const onKey = (e: KeyboardEvent) => { - if (e.key === "Escape") { - e.preventDefault(); - e.stopPropagation(); - onClose(); - } else if (e.key === "ArrowDown" || e.key === "ArrowUp") { - const ways = [first.current, second.current].filter((b): b is HTMLButtonElement => !!b && !b.disabled); - const at = ways.indexOf(document.activeElement as HTMLButtonElement); - const next = ways[(at + (e.key === "ArrowDown" ? 1 : ways.length - 1)) % ways.length]; - if (!next) return; - e.preventDefault(); - next.focus(); - } - }; const there = to.blocked ? to.blocked - : to.paused - ? "The autopilot is paused, and acts again once someone resumes it. You go with your message." - : "The autopilot takes it up there, and you go with your message."; + : to.wakes + ? "The autopilot is paused: it resumes, and takes your message up there as the autopilot. You go with your message." + : to.paused + ? "The autopilot is paused, and acts again once someone resumes it. You go with your message." + : "The autopilot takes it up there, and you go with your message."; return ( -
-
- - - -
-

An earlier session of the autopilot

-

- The autopilot works in {n} now -

-

- This session's agent no longer acts as the autopilot: it can't start sessions or steer them, so it - would take your message on alone. -

-
- - - -
-
- } + eyebrow="An earlier session of the autopilot" + title={ + <> + The autopilot works in {n} now + + } + nudge={nudge} + onClose={onClose} + ways={[ + { + key: "there", + primary: true, + disabled: !!to.blocked || !!sending, + busy: sending === "there", + onClick: onThere, + title: to.wakes && !to.blocked ? `Wake it and send to ${n}` : `Send to ${n}`, + meta: ( {to.word.word} @@ -206,71 +184,21 @@ export function MovedOnCard({ · started {agoShortWords(to.session.started_at, now)} - } - line={there} - /> - -
-

- ↑↓ choose · ↵ send · esc back to your message -

-
- ); -} - -/** One way the message can go: what it does, a line of what follows, and the send circle. */ -const Way = forwardRef< - HTMLButtonElement, - { - primary?: boolean; - disabled?: boolean; - busy?: boolean; - onClick: () => void; - title: string; - meta?: ReactNode; - line: string; - } ->(function Way({ primary, disabled, busy, onClick, title, meta, line }, ref) { - return ( - + This session's agent no longer acts as the autopilot: it can't start sessions or steer them, so it would + take your message on alone. + ); -}); +} diff --git a/web/src/components/session/now-line.tsx b/web/src/components/session/now-line.tsx index 1a6c04a43..5261b1f95 100644 --- a/web/src/components/session/now-line.tsx +++ b/web/src/components/session/now-line.tsx @@ -371,6 +371,7 @@ export function NowLine({ background, autopilot, movedTo, + pausedPilot, }: { now?: Now; /** @@ -380,6 +381,11 @@ export function NowLine({ autopilot?: G.SessionAutopilot; /** In an earlier session of its own: the number of the one it works in now, which fctl wakes. */ movedTo?: number; + /** + * In the session a paused autopilot works in: fctl doesn't wake it, but a message from the reader + * can (`canWake`). + */ + pausedPilot?: { canWake: boolean }; /** The plan of the turn the agent works on. */ plan?: Plan; /** It's the reader's turn while the agent does nothing: the line says so, and goes to their reply. */ @@ -508,6 +514,13 @@ export function NowLine({ Handed over The autopilot works in #{movedTo} now + ) : autopilot?.role === "pilot" && pausedPilot ? ( + <> + Paused + + {pausedPilot.canWake ? "A message from you can wake it" : "It wakes once someone resumes it"} + + ) : autopilot?.role === "pilot" ? ( <> Resting diff --git a/web/src/components/session/paused-pilot.test.tsx b/web/src/components/session/paused-pilot.test.tsx new file mode 100644 index 000000000..eca872981 --- /dev/null +++ b/web/src/components/session/paused-pilot.test.tsx @@ -0,0 +1,265 @@ +import { QueryClientProvider } from "@tanstack/react-query"; +import { act, type ReactNode } from "react"; +import { createRoot } from "react-dom/client"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import type * as G from "@/gen"; +import { paused as pausedOf } from "@/lib/autopilot"; +import { queryClient } from "@/lib/queries"; +import type { SentFiles } from "./attachments"; +import { Composer } from "./composer"; +import { type PausedPilot, runsOnWhenWoken, wakeBlocked } from "./paused-pilot"; + +vi.mock("@/lib/api", async (original) => ({ + ...(await original()), + api: new Proxy({} as Record, { get: () => () => new Promise(() => {}) }), +})); +vi.mock("@tanstack/react-router", () => ({ + Link: ({ to, children }: { to: string; children: ReactNode }) => {children}, + useNavigate: () => () => {}, +})); + +(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +const roots: (() => void)[] = []; +afterEach(() => { + for (const unmount of roots.splice(0)) unmount(); + queryClient.clear(); +}); + +const NOW = Date.now(); +const HOUR = 3_600_000; +const OWNER: G.SessionRole = "owner"; + +/** A project's autopilot that paused itself two hours ago, waiting for keys, in session #7. */ +function autopilot(more: Partial = {}): G.Autopilot { + return { + project_id: "prj_shop", + project_slug: "shop", + scope: "project", + state: "paused", + paused_itself: true, + paused_reason: "Waiting for the Stripe keys before checkout.", + paused_at: NOW - 2 * HOUR, + owner: { id: "usr_noor", name: "Noor Haddad" }, + keep_owner: false, + fresh_asked: false, + direction: "Run the shop.", + direction_at: 0, + powers: [], + check_in_minutes: 60, + crew_max: 3, + session: { id: "ses_7", number: 7, status: "idle", started_at: NOW - 3 * HOUR }, + check_ins: 4, + notes: [], + asks: [], + crew: [], + crew_total: 0, + can: { steer: true, secrets: true, read: true }, + created_at: 0, + updated_at: 0, + ...more, + }; +} + +function pausedPilot(a = autopilot(), more: Partial = {}): PausedPilot { + return { autopilot: a, paused: pausedOf(a, NOW), ...more }; +} + +/** The composer of session #7, which the paused autopilot `to` works in. */ +function composer(to?: PausedPilot, status: G.SessionStatus = "idle", sending?: () => Promise) { + const container = document.createElement("div"); + document.body.append(container); + const root = createRoot(container); + const sent: { text: string; wake: boolean }[] = []; + const resumed: string[] = []; + const onSend = vi.fn(async (text: string, _files: SentFiles, opts?: { wakeAutopilot?: boolean }) => { + await sending?.(); + sent.push({ text, wake: !!opts?.wakeAutopilot }); + }); + act(() => + root.render( + + {}} + onTyping={() => {}} + onResume={async (text) => { + resumed.push(text); + }} + paused={to} + /> + , + ), + ); + roots.push(() => { + act(() => root.unmount()); + container.remove(); + }); + const box = () => container.querySelector("textarea") as HTMLTextAreaElement; + const way = (name: string) => + [...container.querySelectorAll("[role=alertdialog] button")].find((b) => + b.textContent?.startsWith(name), + ); + return { + container, + sent, + resumed, + box, + way, + card: () => container.querySelector("[role=alertdialog]"), + type(text: string) { + act(() => { + Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")?.set?.call(box(), text); + box().dispatchEvent(new Event("input", { bubbles: true })); + }); + }, + async enter() { + await act(async () => { + box().dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + }); + }, + async click(b?: HTMLElement) { + await act(async () => b?.click()); + }, + }; +} + +describe("a message to the session of a paused autopilot", () => { + it("says it is paused, and that a message can wake it, above the box", () => { + const c = composer(pausedPilot()); + expect(c.container.textContent).toContain("The autopilot is paused· your message can wake it"); + }); + + it("asks first: who paused it and why, with waking it focused", async () => { + const c = composer(pausedPilot()); + c.type("The keys are in the project's secrets now"); + await c.enter(); + expect(c.sent).toEqual([]); + const card = c.card()?.textContent ?? ""; + expect(card).toContain("The autopilot is paused"); + expect(card).toContain("It paused itself 2 hours ago"); + expect(card).toContain("Waiting for the Stripe keys before checkout."); + expect(card).toContain("can't start or steer sessions, or keep the plan and log"); + expect(card).toContain("as what it waited for"); + expect(document.activeElement).toBe(c.way("Wake it and send")); + // The card says it, so the line above the box steps aside. + expect(c.container.textContent).not.toContain("your message can wake it"); + expect(c.box().value).toBe("The keys are in the project's secrets now"); + }); + + it("wakes it with the message", async () => { + const c = composer(pausedPilot()); + c.type("The keys are in the project's secrets now"); + await c.enter(); + await c.click(c.way("Wake it and send")); + expect(c.sent).toEqual([{ text: "The keys are in the project's secrets now", wake: true }]); + expect(c.box().value).toBe(""); + expect(c.card()).toBeNull(); + }); + + it("keeps the message, and the card, should waking fail", async () => { + const c = composer(pausedPilot(), "idle", async () => { + throw new Error("Connect your Claude subscription first"); + }); + c.type("Go on"); + await c.enter(); + await c.click(c.way("Wake it and send")); + expect(c.box().value).toBe("Go on"); + expect(c.card()).not.toBeNull(); + }); + + it("sends it without waking it, and then asks no more", async () => { + const c = composer(pausedPilot()); + c.type("Why did you pause?"); + await c.enter(); + await c.click(c.way("Send without waking it")); + expect(c.sent).toEqual([{ text: "Why did you pause?", wake: false }]); + expect(c.card()).toBeNull(); + c.type("Thanks"); + await c.enter(); + expect(c.sent).toEqual([ + { text: "Why did you pause?", wake: false }, + { text: "Thanks", wake: false }, + ]); + expect(c.card()).toBeNull(); + }); + + it("says who else paused it", async () => { + const a = autopilot({ + paused_itself: false, + paused_by: { id: "usr_bo", name: "Bo Lind" }, + paused_reason: "Launch week", + }); + const c = composer(pausedPilot(a)); + c.type("Go on"); + await c.enter(); + expect(c.card()?.textContent).toContain("Bo Lind paused it 2 hours ago"); + expect(c.card()?.textContent).not.toContain("as what it waited for"); + }); + + it("says when waking it runs it on the reader's subscription", async () => { + const c = composer( + pausedPilot(autopilot(), { runsOn: "From now on it runs on your Claude subscription." }), + ); + c.type("Go on"); + await c.enter(); + expect(c.card()?.textContent).toContain("From now on it runs on your Claude subscription."); + }); + + it("offers only sending without waking to those who can't wake it, and says why", async () => { + const a = autopilot({ can: { steer: false, secrets: false, read: true } }); + const c = composer(pausedPilot(a, { blocked: wakeBlocked(a, "idle") })); + expect(c.container.textContent).toContain("it acts again once someone resumes it"); + c.type("Go on"); + await c.enter(); + expect(c.way("Wake it and send")?.disabled).toBe(true); + expect(c.card()?.textContent).toContain("Only the project's maintainers and owners resume its autopilot"); + expect(document.activeElement).toBe(c.way("Send without waking it")); + }); + + it("resumes a failed session without waking it", async () => { + const a = autopilot({ session: { id: "ses_7", number: 7, status: "failed", started_at: 0 } }); + const c = composer(pausedPilot(a, { blocked: wakeBlocked(a, "failed") }), "failed"); + c.type("Try again"); + await c.enter(); + expect(c.way("Wake it and send")?.disabled).toBe(true); + await c.click(c.way("Resume here without waking it")); + expect(c.resumed).toEqual(["Try again"]); + }); + + it("asks nothing once it is on", async () => { + const c = composer(); + c.type("Go on"); + await c.enter(); + expect(c.sent).toEqual([{ text: "Go on", wake: false }]); + expect(c.card()).toBeNull(); + }); +}); + +describe("waking a paused autopilot", () => { + it("is for those who steer it, in a session that can take a message", () => { + const a = autopilot(); + expect(wakeBlocked(a, "idle")).toBeUndefined(); + expect(wakeBlocked(a, "stopped")).toBeUndefined(); + expect(wakeBlocked(a, "failed")).toMatch(/^This session failed/); + expect(wakeBlocked({ ...a, can: { steer: false, secrets: false, read: true } }, "idle")).toMatch( + /^Only the project's maintainers and owners/, + ); + expect( + wakeBlocked({ ...a, scope: "workspace", can: { steer: false, secrets: false, read: true } }, "idle"), + ).toMatch(/^Only the workspace's admins/); + }); + + it("says whose subscription it runs on, as resuming it on its tab does", () => { + const a = autopilot(); + expect(runsOnWhenWoken(a, "usr_noor")).toBeUndefined(); + expect(runsOnWhenWoken(a, "usr_bo")).toBe("From now on it runs on your Claude subscription."); + expect(runsOnWhenWoken({ ...a, keep_owner: true }, "usr_bo")).toBe( + "It runs on Noor Haddad's Claude subscription, as they keep it.", + ); + }); +}); diff --git a/web/src/components/session/paused-pilot.tsx b/web/src/components/session/paused-pilot.tsx new file mode 100644 index 000000000..a557b4a9f --- /dev/null +++ b/web/src/components/session/paused-pilot.tsx @@ -0,0 +1,166 @@ +// The session a paused autopilot works in, at its message box. While an autopilot is paused, its +// agent's `fctl` reaches nothing, so a message there reaches the agent alone: it can't start or +// steer sessions, or keep the plan and log, and does the work in that one session itself ("Because +// the autopilot is paused, fctl won't let me start a session or update the plan and log, so I'm +// doing it directly in this session."). An autopilot often pauses itself to wait for people, and +// what they send next is what it waited for. So above the box a line says it is paused, and a +// message asks first, in a card over the box: wake it with the message (first, and focused), which +// resumes it as the message goes (`SendMessageRequest.wake_autopilot`), or send it without waking +// it. Once sent without, the page asks no more until the reader leaves. + +import { useAutopilot, useNow } from "@/components/project/autopilot"; +import { AutopilotIcon } from "@/components/ui"; +import type * as G from "@/gen"; +import { type Paused, pausedHere, paused as pausedOf } from "@/lib/autopilot"; +import { keys, queryClient, useMe } from "@/lib/queries"; +import { WaysCard } from "./ways"; + +/** A paused autopilot's own session, at its message box: what the box needs to ask. */ +export interface PausedPilot { + autopilot: G.Autopilot; + /** Who paused it, when and why. */ + paused: Paused; + /** Why the reader can't wake it with a message, when they can't. */ + blocked?: string; + /** Whose Claude subscription it runs on once woken, when the reader should know: a sentence. */ + runsOn?: string; +} + +/** The paused autopilot `session` is the session of, while it works in it. */ +export function usePausedPilot(session: G.Session | undefined): PausedPilot | undefined { + const pilot = session?.autopilot?.role === "pilot"; + const a = useAutopilot(session?.autopilot?.project_slug ?? "", pilot).data; + const me = useMe().data?.user.id; + useNow(60_000); + if (!a || !session || !pilot || !pausedHere(a, session.id)) return; + return { + autopilot: a, + paused: pausedOf(a), + blocked: wakeBlocked(a, session.status), + runsOn: runsOnWhenWoken(a, me), + }; +} + +/** Why the reader can't wake `a` with a message to its session, of `status`, when they can't. */ +export function wakeBlocked( + a: Pick, + status: G.SessionStatus | undefined, +): string | undefined { + if (!a.can.steer) + return a.scope === "workspace" + ? "Only the workspace's admins resume its autopilot: ask one of them to wake it." + : "Only the project's maintainers and owners resume its autopilot: ask one of them to wake it."; + if (status === "failed") + return "This session failed: resume the autopilot from its details, and fctl starts it a fresh session."; +} + +/** + * Whose Claude subscription `a` runs on once the reader (`me`) wakes it, when it isn't theirs + * already: as resuming it does on its tab. + */ +export function runsOnWhenWoken( + a: Pick, + me: G.UserId | undefined, +): string | undefined { + if (!me || a.owner?.id === me) return; + if (a.keep_owner && a.owner) return `It runs on ${a.owner.name}'s Claude subscription, as they keep it.`; + return "From now on it runs on your Claude subscription."; +} + +/** What changed once a message woke it: its tab, its mark in the lists, its details. */ +export function refreshAutopilot(a: Pick) { + void queryClient.invalidateQueries({ queryKey: keys.autopilot(a.project_id) }); + void queryClient.invalidateQueries({ queryKey: keys.autopilot(a.project_slug) }); + void queryClient.invalidateQueries({ queryKey: keys.projects }); + void queryClient.invalidateQueries({ queryKey: ["project"] }); +} + +/** The line above the message box: the autopilot is paused, and a message can wake it. */ +export function PausedLine({ to }: { to: PausedPilot }) { + return ( + + + The autopilot is paused + + {to.blocked ? "· it acts again once someone resumes it" : "· your message can wake it"} + + + ); +} + +/** + * Asks before a message goes to the session of a paused autopilot: wake it and send (first, and + * focused: Enter again sends it so), or send without waking it. Escape, or ×, goes back to the + * message, as it was. + */ +export function PausedCard({ + to, + nudge, + sending, + resume, + onWake, + onHere, + onClose, +}: { + to: PausedPilot; + /** Changes as people send again while it asks: the focus comes back to it. */ + nudge?: number; + /** How the message is on its way. */ + sending?: "wake" | "here"; + /** Sending it without waking resumes this failed session. */ + resume?: boolean; + onWake: () => void; + onHere: () => void; + onClose: () => void; +}) { + const p = to.paused; + const wake = to.blocked + ? to.blocked + : [ + p.itself + ? "It resumes and takes your message up as the autopilot, as what it waited for: it plans, starts and steers sessions, and hears what happened while it was paused." + : "It resumes and takes your message up as the autopilot: it plans, starts and steers sessions, and hears what happened while it was paused.", + to.runsOn, + ] + .filter(Boolean) + .join(" "); + return ( + } + eyebrow="The autopilot is paused" + title={`${p.who}${p.when ? ` ${p.when}` : ""}`} + nudge={nudge} + onClose={onClose} + ways={[ + { + key: "wake", + primary: true, + disabled: !!to.blocked || !!sending, + busy: sending === "wake", + onClick: onWake, + title: "Wake it and send", + line: wake, + }, + { + key: "here", + disabled: !!sending, + busy: sending === "here", + onClick: onHere, + title: resume ? "Resume here without waking it" : "Send without waking it", + line: "This session's agent takes it up on its own, and the autopilot stays paused.", + }, + ]} + > + {p.reason && ( +
+ {p.reason} +
+ )} +

+ While it's paused, this session's agent can't start or steer sessions, or keep the plan and log: it + would take your message up on its own, here. +

+
+ ); +} diff --git a/web/src/components/session/ways.tsx b/web/src/components/session/ways.tsx new file mode 100644 index 000000000..57c4ebbea --- /dev/null +++ b/web/src/components/session/ways.tsx @@ -0,0 +1,172 @@ +// A card over the message box that asks where, or how, a message goes before it does: an earlier +// session of an autopilot's own (moved-on.tsx), or the session of an autopilot that is paused +// (paused-pilot.tsx). Its ways are full-width rows, each what it does over a line of what follows, +// with a round send arrow at its end. The first way that can go takes the focus as it opens and as +// people send again, so Enter, then Enter again, takes it; ↑↓ move between the ways, and Escape, +// or ×, goes back to the message as it was. + +import { ArrowUp, X } from "lucide-react"; +import { type KeyboardEvent, type ReactNode, useEffect, useId, useRef } from "react"; +import { IconButton, Spinner } from "@/components/ui"; +import { cn } from "@/lib/cn"; + +/** One way a message can go. */ +export interface Way { + key: string; + /** What it does: "Send to #20", "Wake it and send". */ + title: string; + /** Beside the title: how the session it goes to stands. */ + meta?: ReactNode; + /** What follows. */ + line: ReactNode; + /** The first, raised, its arrow in an ink circle as the composer's Send is. */ + primary?: boolean; + disabled?: boolean; + /** On its way. */ + busy?: boolean; + onClick: () => void; +} + +/** The card's colors: amber for caution, pink for an autopilot that is paused. */ +const TONES = { + amber: { + card: "border-amber/30 bg-[linear-gradient(to_bottom,var(--c-amber-soft),transparent_70%)]", + tile: "bg-amber-soft text-amber", + eyebrow: "text-amber", + }, + pink: { + card: "border-pink/30 bg-[linear-gradient(to_bottom,var(--c-pink-soft),transparent_70%)]", + tile: "bg-pink-soft text-pink", + eyebrow: "text-pink", + }, +} as const; + +export function WaysCard({ + tone, + icon, + eyebrow, + title, + children, + ways, + nudge, + onClose, +}: { + tone: keyof typeof TONES; + /** In the round tile at its start. */ + icon: ReactNode; + eyebrow: ReactNode; + title: ReactNode; + /** What happened, and why it matters, under the title. */ + children: ReactNode; + ways: Way[]; + /** Changes as people send again while it asks: the focus comes back to it. */ + nudge?: number; + onClose: () => void; +}) { + const titleId = useId(); + const textId = useId(); + const refs = useRef<(HTMLButtonElement | null)[]>([]); + // As it opens, and as people send again, the first way that can go has the focus. + // biome-ignore lint/correctness/useExhaustiveDependencies: nudge is what brings it back. + useEffect(() => { + refs.current.find((b) => b && !b.disabled)?.focus(); + }, [nudge]); + const onKey = (e: KeyboardEvent) => { + if (e.key === "Escape") { + e.preventDefault(); + e.stopPropagation(); + onClose(); + } else if (e.key === "ArrowDown" || e.key === "ArrowUp") { + const open = refs.current.filter((b): b is HTMLButtonElement => !!b && !b.disabled); + const at = open.indexOf(document.activeElement as HTMLButtonElement); + const next = open[(at + (e.key === "ArrowDown" ? 1 : open.length - 1)) % open.length]; + if (!next) return; + e.preventDefault(); + next.focus(); + } + }; + const t = TONES[tone]; + return ( +
+
+ + {icon} + +
+

{eyebrow}

+

+ {title} +

+
+ {children} +
+
+ + + +
+
+ {ways.map((w, i) => ( + { + refs.current[i] = b; + }} + way={w} + /> + ))} +
+

+ ↑↓ choose · ↵ send · esc back to your message +

+
+ ); +} + +/** One way the message can go: what it does, a line of what follows, and the send circle. */ +function WayRow({ way: w, ref }: { way: Way; ref: (b: HTMLButtonElement | null) => void }) { + return ( + + ); +} diff --git a/web/src/gen/Autopilot.ts b/web/src/gen/Autopilot.ts index 65e8d05b6..240fcc8db 100644 --- a/web/src/gen/Autopilot.ts +++ b/web/src/gen/Autopilot.ts @@ -30,6 +30,12 @@ paused_reason?: string, * Who paused or took it off; absent when fctl or the autopilot did. */ paused_by?: UserRef, paused_at?: number, +/** + * It paused itself (`fctl autopilot pause`), done or waiting for + * people, rather than fctl pausing it: absent (false) when fctl or a + * person did, and from control planes before it. + */ +paused_itself: boolean, /** * Whose Claude subscription it runs on, and as whom it acts: who put * the project on autopilot, or took it over since. Absent once their diff --git a/web/src/gen/SendMessageRequest.ts b/web/src/gen/SendMessageRequest.ts index 305cc9ade..941b89287 100644 --- a/web/src/gen/SendMessageRequest.ts +++ b/web/src/gen/SendMessageRequest.ts @@ -13,4 +13,14 @@ client_id?: string, /** * Files to send with it: ids from `POST /api/v1/sessions/{id}/attachments`. */ -attachments?: Array, }; +attachments?: Array, +/** + * To the session an autopilot works in now, while it is paused: + * resume the autopilot with the message, for those who steer it, so + * that its agent takes it up as the autopilot (its `fctl` reaches the + * API again: it plans, starts and steers sessions) rather than alone. + * The message goes first, and fctl then wakes the autopilot in that + * session with what is new. One that is on already takes the message + * as it is. Control planes from before it ignore it. + */ +wake_autopilot?: boolean, }; diff --git a/web/src/gen/SendMessageResponse.ts b/web/src/gen/SendMessageResponse.ts index a598015ef..843ab2ea1 100644 --- a/web/src/gen/SendMessageResponse.ts +++ b/web/src/gen/SendMessageResponse.ts @@ -12,4 +12,10 @@ delivery_id: DeliveryId, * many of its sessions work as its people allow: fctl holds it, and * sends it once one of them makes room. Absent for one that went. */ -held?: HeldMessage, }; +held?: HeldMessage, +/** + * It resumed the paused autopilot whose own session it went to + * (`SendMessageRequest::wake_autopilot`): false when that autopilot + * was on already, and from control planes before it. + */ +woke_autopilot: boolean, }; diff --git a/web/src/lib/autopilot.test.ts b/web/src/lib/autopilot.test.ts index 07ccf59d9..87c8152c8 100644 --- a/web/src/lib/autopilot.test.ts +++ b/web/src/lib/autopilot.test.ts @@ -11,8 +11,11 @@ import { handoffWords, hasPlaceholders, movedOn, + paused, + pausedHere, phase, planDone, + sentence, sessionWord, splitBriefing, splitCrewNote, @@ -33,6 +36,7 @@ function autopilot(more: Partial = {}): G.Autopilot { owner: { id: "usr_noor", name: "Noor Haddad" }, keep_owner: false, fresh_asked: false, + paused_itself: false, direction: "Ship the checkout.", direction_at: NOW - 86_400_000, powers: ["settings", "schedules"], @@ -130,9 +134,42 @@ describe("where an autopilot stands", () => { }); expect(phase(a, NOW)).toMatchObject({ tone: "pink", word: "Paused" }); expect(phase(a, NOW).line).toBe( - "Noor Haddad paused it 2 minutes ago: Launch week It wakes again once someone resumes it.", + "Noor Haddad paused it 2 minutes ago: Launch week. It wakes again once someone resumes it.", ); }); + + it("tells a pause of its own from fctl's", () => { + const at = { state: "paused" as const, paused_at: NOW - 2 * 3_600_000 }; + const itself = autopilot({ ...at, paused_itself: true, paused_reason: "Waiting for the Stripe keys." }); + expect(paused(itself, NOW)).toEqual({ + who: "It paused itself", + when: "2 hours ago", + reason: "Waiting for the Stripe keys.", + itself: true, + }); + expect(phase(itself, NOW).line).toBe( + "It paused itself 2 hours ago: Waiting for the Stripe keys. It wakes again once someone resumes it.", + ); + const fctl = autopilot({ ...at, paused_reason: "Its project is archived." }); + expect(paused(fctl, NOW).who).toBe("fctl paused it"); + // Without a reason, or a person, it can't tell. + expect(paused(autopilot(at), NOW).who).toBe("It paused"); + }); + + it("is paused here only in the session it works in", () => { + const session = { id: "ses_2", number: 20, status: "idle" as const, started_at: NOW }; + expect(pausedHere(autopilot({ session, state: "paused" }), "ses_2")).toBe(true); + expect(pausedHere(autopilot({ session, state: "paused" }), "ses_1")).toBe(false); + expect(pausedHere(autopilot({ session }), "ses_2")).toBe(false); + expect(pausedHere(autopilot({ session, state: "off" }), "ses_2")).toBe(false); + expect(pausedHere(undefined, "ses_2")).toBe(false); + }); + + it("ends a reason as a sentence", () => { + expect(sentence("Launch week")).toBe("Launch week."); + expect(sentence("Done!")).toBe("Done!"); + expect(sentence(" Waiting for the keys. ")).toBe("Waiting for the keys."); + }); }); describe("an earlier session of its own", () => { diff --git a/web/src/lib/autopilot.ts b/web/src/lib/autopilot.ts index 833b02c86..4fc1c65b2 100644 --- a/web/src/lib/autopilot.ts +++ b/web/src/lib/autopilot.ts @@ -141,12 +141,11 @@ export function phase(a: G.Autopilot, now = Date.now(), here?: G.SessionId): Pha : ""; if (a.state === "off") return { tone: "ink", word: "Off", line: "The project is off autopilot." }; if (a.state === "paused") { - const who = a.paused_by ? `${a.paused_by.name} paused it` : "It paused"; - const why = a.paused_reason ? `: ${a.paused_reason}` : "."; + const p = paused(a, now); return { tone: "pink", word: "Paused", - line: `${who}${a.paused_at ? ` ${ago(a.paused_at, now)}` : ""}${why} It wakes again once someone resumes it.`, + line: `${p.who}${p.when ? ` ${p.when}` : ""}${p.reason ? `: ${sentence(p.reason)}` : "."} It wakes again once someone resumes it.`, }; } if (atWork(a)) { @@ -180,6 +179,55 @@ export function phase(a: G.Autopilot, now = Date.now(), here?: G.SessionId): Pha }; } +/** Who paused an autopilot, how long ago and why, as people read it. */ +export interface Paused { + /** "It paused itself", "fctl paused it", "Noor Haddad paused it", or "It paused" when unknown. */ + who: string; + /** "2 hours ago", when known. */ + when?: string; + /** Why, in its own words or fctl's, when it said. */ + reason?: string; + /** It paused itself: done, or waiting for people. */ + itself: boolean; +} + +/** Who paused `a`, how long ago and why. A pause with no person is the autopilot's own or fctl's. */ +export function paused( + a: Pick, + now = Date.now(), +): Paused { + const itself = !!a.paused_itself; + return { + who: a.paused_by + ? `${a.paused_by.name} paused it` + : itself + ? "It paused itself" + : a.paused_reason + ? "fctl paused it" + : "It paused", + when: a.paused_at ? ago(a.paused_at, now) : undefined, + reason: a.paused_reason?.trim() || undefined, + itself, + }; +} + +/** `text`, ending as a sentence does. */ +export function sentence(text: string): string { + const t = text.trim(); + return /[.!?…:)"'”’]$/.test(t) ? t : `${t}.`; +} + +/** + * Whether `here` is the session a paused autopilot works in, where a message reaches its agent + * alone unless it wakes the autopilot: its `fctl` reaches nothing while it is paused. + */ +export function pausedHere( + a: Pick | null | undefined, + here: G.SessionId, +): boolean { + return !!a && a.state === "paused" && a.session?.id === here; +} + /** * The session an autopilot works in now, when `here` is an earlier session of its own: fctl wakes * it there, and only there does its agent act as the autopilot (its `fctl` reaches the API), so a diff --git a/web/src/lib/live.ts b/web/src/lib/live.ts index df6bb2488..2751167aa 100644 --- a/web/src/lib/live.ts +++ b/web/src/lib/live.ts @@ -343,12 +343,15 @@ export class LiveSession { /** * Sends a message with its uploaded files; shows it right away (images - * from their local previews) and resolves once it is stored. + * from their local previews) and resolves once it is stored. With + * `wakeAutopilot`, to the session a paused autopilot works in, it resumes + * the autopilot too, over HTTP: the socket sends messages alone. */ send( text: string, author?: G.UserRef, files?: { attachments: G.Attachment[]; previews: Record }, + opts?: { wakeAutopilot?: boolean }, ): Promise { const client_id = `web-${Date.now().toString(36)}-${++this.counter}`; const attachments = files?.attachments ?? []; @@ -371,8 +374,9 @@ export class LiveSession { this.outbox = this.outbox.filter((i) => i.key !== optimistic.key); this.set({ items: this.show(this.builder.items) }); }; + const wake = !!opts?.wakeAutopilot; return new Promise((resolve, reject) => { - if (this.ws?.readyState === WebSocket.OPEN) { + if (this.ws?.readyState === WebSocket.OPEN && !wake) { this.pending.set(client_id, { resolve, reject: (e) => { @@ -382,14 +386,16 @@ export class LiveSession { }); this.raw({ type: "send", client_id, text, attachments: ids }); } else { - // Not connected: fall back to HTTP (idempotent by client id). - api.sendMessage(this.id, { text, client_id, attachments: ids }).then( - () => resolve(), - (e) => { - drop(); - reject(e); - }, - ); + // Not connected, or waking its autopilot: HTTP (idempotent by client id). + api + .sendMessage(this.id, { text, client_id, attachments: ids, wake_autopilot: wake || undefined }) + .then( + () => resolve(), + (e) => { + drop(); + reject(e); + }, + ); } }); } diff --git a/web/src/routes/session.test.tsx b/web/src/routes/session.test.tsx index a057b5c94..d7f8f7154 100644 --- a/web/src/routes/session.test.tsx +++ b/web/src/routes/session.test.tsx @@ -340,6 +340,7 @@ describe("the session page", () => { owner: { id: "usr_ada", name: "Ada Lovelace" }, keep_owner: false, fresh_asked: false, + paused_itself: false, direction: "Ship the checkout.", direction_at: 0, plan: "- [x] Cart\n- [ ] Apple Pay", diff --git a/web/src/routes/session.tsx b/web/src/routes/session.tsx index 66023630d..7708124e3 100644 --- a/web/src/routes/session.tsx +++ b/web/src/routes/session.tsx @@ -54,6 +54,7 @@ import { import { useMovedOn } from "@/components/session/moved-on"; import { JumpPill, NowLine, toBottom, useAtBottom } from "@/components/session/now-line"; import { AgentOrb } from "@/components/session/orb"; +import { refreshAutopilot, usePausedPilot } from "@/components/session/paused-pilot"; import { PilotDetails } from "@/components/session/pilot"; import { PlanList } from "@/components/session/plan"; import { @@ -176,6 +177,8 @@ export function SessionPage() { const review = useSessionReview(session); // An earlier session of an autopilot's own: where it works now, which messages go to instead. const movedOn = useMovedOn(session); + // The session a paused autopilot works in: a message asks whether it wakes it. + const pausedPilot = usePausedPilot(session); const [rail, setRail] = useState(true); const [clock] = useHourCycle(); // The details sheet, where the rail doesn't fit. @@ -930,6 +933,7 @@ export function SessionPage() { onReply={yourTurn ? focusReply : undefined} autopilot={session?.autopilot} movedTo={movedOn?.session.number} + pausedPilot={pausedPilot && { canWake: !pausedPilot.blocked }} background={ waiting && { waiting, @@ -961,20 +965,26 @@ export function SessionPage() { viewers={s.viewers} meId={me?.user.id} sessionId={id} - onSend={(t, files) => - store.send( + onSend={async (t, files, opts) => { + await store.send( t, me?.user ? { id: me.user.id, name: me.user.name, avatar_url: me.user.avatar_url } : undefined, files, - ) - } + opts, + ); + if (opts?.wakeAutopilot && pausedPilot) { + refreshAutopilot(pausedPilot.autopilot); + toast("Woke the autopilot: it takes your message up as the autopilot"); + } + }} onInterrupt={() => store.interrupt()} onTyping={() => store.typing()} onTakeOver={takeOver?.waits ? () => setMoving(true) : undefined} limitOf={takeOver?.whose} movedOn={movedOn} + paused={pausedPilot} suspended={!!s.sandboxSuspended} refused={refusal && refusalActions ? : undefined} onConnectClaude={fix?.canAct ? () => setConnecting(true) : undefined} From 3650331fedcb7427c54c3441d89d3c830fa06790 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 07:55:35 +0000 Subject: [PATCH 2/4] docs: waking a paused autopilot with a message; say who paused it The now line in a paused autopilot's session says who paused it and why, rather than that fctl wakes it; fctl autopilot says whether it paused itself; autopilots hear that people may resume them with a message to their session. --- crates/fctl-domain/src/autopilot.rs | 2 +- crates/fctl/src/cmd/autopilot.rs | 18 +++++++++++++---- ...wn-through-the-api-their-session-relays.md | 11 +++++++++- docs/agents.md | 12 ++++++++++- docs/api.md | 4 ++-- docs/cli.md | 11 ++++++++++ docs/llms.txt | 2 +- web/src/components/session/now-line.tsx | 11 +++++----- .../components/session/paused-pilot.test.tsx | 20 ++++++++++++++++++- web/src/components/session/paused-pilot.tsx | 7 ++++++- web/src/routes/session.tsx | 4 ++-- 11 files changed, 83 insertions(+), 19 deletions(-) diff --git a/crates/fctl-domain/src/autopilot.rs b/crates/fctl-domain/src/autopilot.rs index 6e3f8768e..9627db85f 100644 --- a/crates/fctl-domain/src/autopilot.rs +++ b/crates/fctl-domain/src/autopilot.rs @@ -1595,7 +1595,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 \"…\"`: people resume you when they have more.\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.\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/src/cmd/autopilot.rs b/crates/fctl/src/cmd/autopilot.rs index 6d3930073..60df1a24a 100644 --- a/crates/fctl/src/cmd/autopilot.rs +++ b/crates/fctl/src/cmd/autopilot.rs @@ -1242,10 +1242,20 @@ fn state_line(a: &Autopilot) -> String { } } } - AutopilotState::Paused => match &a.paused_reason { - Some(why) => style::amber(&format!("◍ Paused: {why}")), - None => style::amber("◍ Paused"), - }, + AutopilotState::Paused => { + // Whose pause it is: a person's, its own (done, or waiting for + // people: `fctl send --wake` resumes it with a message), or fctl's. + let who = match (&a.paused_by, a.paused_itself, &a.paused_reason) { + (Some(p), ..) => format!(" by {}", p.name), + (None, true, _) => " itself".to_owned(), + (None, false, Some(_)) => " by fctl".to_owned(), + (None, false, None) => String::new(), + }; + match &a.paused_reason { + Some(why) => style::amber(&format!("◍ Paused{who}: {why}")), + None => style::amber(&format!("◍ Paused{who}")), + } + } AutopilotState::Off => style::dim("○ Off"), } } 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 c2a9012ba..ea15a65ea 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 @@ -105,7 +105,16 @@ agent that manages a project needs most of the API besides. (screenshots of two designs), or for a secret, which people type in on its tab and which goes into the project's secrets: the autopilot hears only that it's set. Asks notify the people who follow its session, its - owner among them, and show in *Needs you*. + owner among them, and show in *Needs you*. A message to its session + while it's paused wakes it, as people choose (added later): its `fctl` + reaches nothing while paused, and an autopilot that paused itself to + wait for people, given what it waited for in its session, did the work + there alone ("fctl won't let me start a session or update the plan and + log, so I'm doing it directly in this session"). The web app asks + 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. - **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 d45082ff3..d3c497657 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -785,4 +785,14 @@ again the background scripts its plan names, which stopped with the last one's sandbox. People who steer it also start one when they choose (`fctl autopilot wake --fresh`), say to pick up what's new in fctl after a release: at once between its turns, else once its turn -ends. +ends. A wake that finds its session about to take up a message a person +just sent it reaches it there, at its next step, rather than hand off. + +Paused (by people, by fctl, or by itself once the direction is done or +it waits for people), it wakes no more, and its `fctl` reaches nothing: +a message people send to its session then reaches that session's agent +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. diff --git a/docs/api.md b/docs/api.md index 1f989eea7..27c2b1018 100644 --- a/docs/api.md +++ b/docs/api.md @@ -139,7 +139,7 @@ It answers with the session, `queued`. A session is: | Request | Body | What it does | |---|---|---| -| `POST /api/v1/sessions/{id}/messages` | `{"text": "…", "client_id": "…", "attachments": [...]}` | reaches the agent at its next step; resumes a stopped session on the subscription it ran on; `409` for a failed one. Answers `{"delivery_id": "dlv_…"}`, with `"held": {"id": "aph_…", "ahead"…}` for an autopilot's message to one of its sessions that rests while as many of them work as its people allow: it goes out as that delivery once one of them makes room | +| `POST /api/v1/sessions/{id}/messages` | `{"text": "…", "client_id": "…", "attachments": [...], "wake_autopilot": true}` | reaches the agent at its next step; resumes a stopped session on the subscription it ran on; `409` for a failed one. `wake_autopilot`, to the session a paused autopilot works in, from someone who steers it: resumes the autopilot too, as `…/autopilot/resume` does (on their subscription unless its owner keeps it), so that its agent takes the message up as the autopilot rather than alone; the message goes first, then fctl wakes it there with what's new (`409` in an earlier session of its own, or one fctl couldn't run). Answers `{"delivery_id": "dlv_…", "woke_autopilot": true}` (`false` when the autopilot was on already), with `"held": {"id": "aph_…", "ahead"…}` for an autopilot's message to one of its sessions that rests while as many of them work as its people allow: it goes out as that delivery once one of them makes room | | `POST /api/v1/sessions/{id}/interrupt` | | stops the current turn | | `POST /api/v1/sessions/{id}/reviews/{review}/pass-on` | | passes on the findings of review `{review}` (its `session_id`) that fctl held back from the agent (`held_after`), or that went to no session (`unsent`) where the session lists the review's pull request: the agent gets them as it would have, a stopped session resumes on the subscription it ran on, and it gets those of as many reviews in a row again as the review's project's review agents pass on (`rounds`), these included; `409` when fctl holds none of that review's back (the agent got them, someone wrote to it since, or a newer review of its pull request came), the session doesn't list the pull request of findings that went to no session, the pull request is merged or closed, a newer review of it posted, its agent only reads on GitHub, or the session failed. Answers `{"delivery_id": "dlv_…"}` | | `POST /api/v1/sessions/{id}/stop` | | ends the session; its sandbox stays for a resume | @@ -370,7 +370,7 @@ session calls the endpoints marked *autopilot*, through its sandbox's | Request | What it does | |---|---| -| `GET /api/v1/projects/{project}/autopilot` | `{"state": "on" \| "paused" \| "off", "scope", "direction", "plan", "powers", "check_in_minutes", "crew_max", "owner", "keep_owner", "session", "fresh_asked", "wake_at", "wake_reason", "problem", "notes", "asks", "crew", "held", "can"…}`; 404 for a project that never had one. `held`: the messages it sent its sessions that wait for room, in the order they go out | +| `GET /api/v1/projects/{project}/autopilot` | `{"state": "on" \| "paused" \| "off", "paused_reason", "paused_by", "paused_itself", "scope", "direction", "plan", "powers", "check_in_minutes", "crew_max", "owner", "keep_owner", "session", "fresh_asked", "wake_at", "wake_reason", "problem", "notes", "asks", "crew", "held", "can"…}`; 404 for a project that never had one. `held`: the messages it sent its sessions that wait for room, in the order they go out | | `PUT /api/v1/projects/{project}/autopilot` | `{"direction", "scope": "project" \| "workspace", "powers": ["merge", "settings", "secrets", "repos", "schedules", "projects", "others"], "check_in_minutes", "crew_max", "model", "effort", "handoff_at", "take_over": true, "keep_owner": true}`: puts it on (a [sensitive action](architecture.md#confirming-its-you); `direction` needed the first time; without `powers`, every power its scope has but `others`, managing the sessions people start in its places as its own, which people name), or changes it (absent fields stay; `handoff_at`, the context size from 100,000 to 1,000,000 tokens at which a fresh session of its own takes over, `0` for only after 12 hours). Someone else who changes how much it works (`others` among it) runs it on their subscription from then on, unless its owner keeps it (`keep_owner`, which only its owner, or who puts it on or takes it over, sets; turning it on is a sensitive action too); `take_over` always does | | `POST …/autopilot/off` | `{"stop_sessions": true}`: takes it off, and with that stops the sessions it started that still work | | `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 | diff --git a/docs/cli.md b/docs/cli.md index 2409e2a98..40957b5d7 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -117,6 +117,7 @@ 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, 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 send crm#20 --wake "The Stripe keys are in the secrets" # to the session a paused autopilot works in: resumes it with the message fctl files list my-app#12 # the files sent in it (with messages or its task), oldest first fctl files get my-app#12 model.3mf # writes ./model.3mf (the newest of that name, or by id: att_…); --force to write over one there fctl files get my-app#12 --all --dir in/ # every file, the newest of each name @@ -930,6 +931,7 @@ fctl autopilot wake -p crm # now, with what's new fctl autopilot wake -p crm --fresh # in a fresh session, which starts from its plan and log (once its turn ends, while it works) fctl autopilot pause -p crm --reason "Launch week" fctl autopilot resume -p crm # on your subscription, if it ran on someone else's (unless they keep it) +fctl send crm#20 --wake "The keys are set" # resume it with a message to the session it works in fctl autopilot set -p crm --keep-owner on # its owner: others' changes and resumes run on your plan too fctl autopilot set -p crm --mine # run it on your subscription from now on fctl autopilot off -p crm --stop-sessions # its direction, notes, plan, files, log and asks stay @@ -959,6 +961,15 @@ project whose people you all trust: everyone who steers it (its maintainers and owners, or a workspace's admins) then runs it on your Claude plan, as you. +While it's paused, its `fctl` reaches nothing, so a message to the session +it works in reaches that session's agent alone: it can't start or steer +sessions, or keep the plan and log, and does what it can in that session +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. + 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 project, the default for `-p`): `fctl run`, `fctl sessions`, `fctl show`, diff --git a/docs/llms.txt b/docs/llms.txt index b80b4b7ff..ce5ddcb7c 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_…`). 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: `paused_itself`), 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. - **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/session/now-line.tsx b/web/src/components/session/now-line.tsx index 5261b1f95..7a4be3154 100644 --- a/web/src/components/session/now-line.tsx +++ b/web/src/components/session/now-line.tsx @@ -382,10 +382,11 @@ export function NowLine({ /** In an earlier session of its own: the number of the one it works in now, which fctl wakes. */ movedTo?: number; /** - * In the session a paused autopilot works in: fctl doesn't wake it, but a message from the reader - * can (`canWake`). + * In the session a paused autopilot works in, which fctl doesn't wake: who paused it, when and why + * ("It paused itself 2 minutes ago: Waiting for the keys."), as the line above the message box + * says what a message does. */ - pausedPilot?: { canWake: boolean }; + pausedPilot?: { said: string }; /** The plan of the turn the agent works on. */ plan?: Plan; /** It's the reader's turn while the agent does nothing: the line says so, and goes to their reply. */ @@ -517,8 +518,8 @@ export function NowLine({ ) : autopilot?.role === "pilot" && pausedPilot ? ( <> Paused - - {pausedPilot.canWake ? "A message from you can wake it" : "It wakes once someone resumes it"} + + {pausedPilot.said} ) : autopilot?.role === "pilot" ? ( diff --git a/web/src/components/session/paused-pilot.test.tsx b/web/src/components/session/paused-pilot.test.tsx index eca872981..33443c6d9 100644 --- a/web/src/components/session/paused-pilot.test.tsx +++ b/web/src/components/session/paused-pilot.test.tsx @@ -7,7 +7,7 @@ import { paused as pausedOf } from "@/lib/autopilot"; import { queryClient } from "@/lib/queries"; import type { SentFiles } from "./attachments"; import { Composer } from "./composer"; -import { type PausedPilot, runsOnWhenWoken, wakeBlocked } from "./paused-pilot"; +import { type PausedPilot, pausedSaid, runsOnWhenWoken, wakeBlocked } from "./paused-pilot"; vi.mock("@/lib/api", async (original) => ({ ...(await original()), @@ -254,6 +254,24 @@ describe("waking a paused autopilot", () => { ).toMatch(/^Only the workspace's admins/); }); + it("says who paused it, when and why, in a sentence", () => { + expect(pausedSaid(pausedOf(autopilot(), NOW))).toBe( + "It paused itself 2 hours ago: Waiting for the Stripe keys before checkout.", + ); + expect( + pausedSaid( + pausedOf( + autopilot({ + paused_reason: "Launch week", + paused_itself: false, + paused_by: { id: "usr_bo", name: "Bo Lind" }, + }), + NOW, + ), + ), + ).toBe("Bo Lind paused it 2 hours ago: Launch week."); + }); + it("says whose subscription it runs on, as resuming it on its tab does", () => { const a = autopilot(); expect(runsOnWhenWoken(a, "usr_noor")).toBeUndefined(); diff --git a/web/src/components/session/paused-pilot.tsx b/web/src/components/session/paused-pilot.tsx index a557b4a9f..cdb5a8f85 100644 --- a/web/src/components/session/paused-pilot.tsx +++ b/web/src/components/session/paused-pilot.tsx @@ -11,7 +11,7 @@ import { useAutopilot, useNow } from "@/components/project/autopilot"; import { AutopilotIcon } from "@/components/ui"; import type * as G from "@/gen"; -import { type Paused, pausedHere, paused as pausedOf } from "@/lib/autopilot"; +import { type Paused, pausedHere, paused as pausedOf, sentence } from "@/lib/autopilot"; import { keys, queryClient, useMe } from "@/lib/queries"; import { WaysCard } from "./ways"; @@ -67,6 +67,11 @@ export function runsOnWhenWoken( return "From now on it runs on your Claude subscription."; } +/** Who paused it, when and why, in a sentence: "It paused itself 2 minutes ago: Waiting for the keys." */ +export function pausedSaid(p: Paused): string { + return `${p.who}${p.when ? ` ${p.when}` : ""}${p.reason ? `: ${sentence(p.reason)}` : ""}`; +} + /** What changed once a message woke it: its tab, its mark in the lists, its details. */ export function refreshAutopilot(a: Pick) { void queryClient.invalidateQueries({ queryKey: keys.autopilot(a.project_id) }); diff --git a/web/src/routes/session.tsx b/web/src/routes/session.tsx index 7708124e3..807ade93b 100644 --- a/web/src/routes/session.tsx +++ b/web/src/routes/session.tsx @@ -54,7 +54,7 @@ import { import { useMovedOn } from "@/components/session/moved-on"; import { JumpPill, NowLine, toBottom, useAtBottom } from "@/components/session/now-line"; import { AgentOrb } from "@/components/session/orb"; -import { refreshAutopilot, usePausedPilot } from "@/components/session/paused-pilot"; +import { pausedSaid, refreshAutopilot, usePausedPilot } from "@/components/session/paused-pilot"; import { PilotDetails } from "@/components/session/pilot"; import { PlanList } from "@/components/session/plan"; import { @@ -933,7 +933,7 @@ export function SessionPage() { onReply={yourTurn ? focusReply : undefined} autopilot={session?.autopilot} movedTo={movedOn?.session.number} - pausedPilot={pausedPilot && { canWake: !pausedPilot.blocked }} + pausedPilot={pausedPilot && { said: pausedSaid(pausedPilot.paused) }} background={ waiting && { waiting, From 48b16e9840d4634cff0b6cbd480164f293307c97 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 08:02:02 +0000 Subject: [PATCH 3/4] refactor(control): say why a resume didn't happen with a type, not its message --- crates/fctl-control/src/api/autopilots.rs | 39 ++++++++++++++++++----- crates/fctl-control/src/api/sessions.rs | 27 ++++++++-------- 2 files changed, 44 insertions(+), 22 deletions(-) diff --git a/crates/fctl-control/src/api/autopilots.rs b/crates/fctl-control/src/api/autopilots.rs index 08196b5b0..000774d2a 100644 --- a/crates/fctl-control/src/api/autopilots.rs +++ b/crates/fctl-control/src/api/autopilots.rs @@ -1403,12 +1403,34 @@ pub async fn pause(ctx: &mut Ctx, req: &mut Request, id: &str) -> AppResult AppResult { - if let Some(r) = resuming(ctx, id).await? { - resumed(ctx, &r, false).await?; + if let Some(r) = resuming(ctx, id).await? + && let Err(why) = resumed(ctx, &r, false).await? + { + return Err(conflict(why.message())); } get(ctx, id).await } +/// Why a resume [`resuming`] checked didn't happen: what changed meanwhile. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NotResumed { + /// Someone resumed it, or took it off autopilot. + NotPaused, + /// Whose subscription it runs on changed. + MovedOn, +} + +impl NotResumed { + pub fn message(self) -> &'static str { + match self { + Self::NotPaused => { + "It isn't paused any more: someone resumed it, or took it off autopilot, meanwhile." + } + Self::MovedOn => MOVED_ON, + } + } +} + /// A resume of a paused autopilot that its checks let through /// ([`resuming`]), for [`resumed`] to make. pub struct Resuming { @@ -1480,8 +1502,9 @@ 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. -pub async fn resumed(ctx: &Ctx, r: &Resuming, message: bool) -> AppResult<()> { +/// (`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> { let Resuming { p, row, @@ -1511,11 +1534,11 @@ pub async fn resumed(ctx: &Ctx, r: &Resuming, message: bool) -> AppResult<()> { .await?; if resumed == 0 { let now = engine::row(&ctx.db, &row.project_id).await?; - return Err(conflict( + return Ok(Err( if now.is_some_and(|n| n.state() == AutopilotState::Paused) { - MOVED_ON + NotResumed::MovedOn } else { - "It isn't paused any more: someone resumed it, or took it off autopilot, meanwhile." + NotResumed::NotPaused }, )); } @@ -1554,7 +1577,7 @@ pub async fn resumed(ctx: &Ctx, r: &Resuming, message: bool) -> AppResult<()> { Some(serde_json::json!({ "taken_over": take_over, "message": message })), ); crate::schedules::wake(&ctx.env).await; - Ok(()) + Ok(Ok(())) } /// `POST …/autopilot/wake`: a person wakes it now, with `fresh` in a fresh diff --git a/crates/fctl-control/src/api/sessions.rs b/crates/fctl-control/src/api/sessions.rs index e7b0cb467..93aac6d01 100644 --- a/crates/fctl-control/src/api/sessions.rs +++ b/crates/fctl-control/src/api/sessions.rs @@ -694,25 +694,24 @@ pub async fn send_message(ctx: &mut Ctx, req: &mut Request, id: &str) -> AppResu // Then the autopilot: its wake finds the session about to take the // message up (`ap::own_status`) and reaches it there, at its next step, // rather than in a fresh session. - let mut woke_autopilot = false; - if let Some((r, _)) = &waking { - woke_autopilot = true; - crate::api::autopilots::resumed(ctx, r, true).await.or_else(|e| { - // Resumed by someone else meanwhile: it takes the message up - // all the same. - if e.0.message.starts_with("It isn't paused any more") { - Ok(()) - } else { - Err(AppError(ApiError::new( + let woke_autopilot = match &waking { + None => false, + Some((r, _)) => match crate::api::autopilots::resumed(ctx, r, true).await? { + Ok(()) => true, + // Resumed, or taken off, by someone else meanwhile: the + // message went as it is. + Err(crate::api::autopilots::NotResumed::NotPaused) => false, + Err(why) => { + return Err(AppError(ApiError::new( ErrorCode::Conflict, format!( "The message went to the session, but the autopilot is still paused: {}", - e.0.message + why.message() ), - ))) + ))); } - })?; - } + }, + }; http::ok(&SendMessageResponse { delivery_id, held: None, From 3309e0ce971a12974aac4b03d37c56b9623fa962 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 08:20:00 +0000 Subject: [PATCH 4/4] fix: answer the review of the wake with a message - A wake for a fresh session that a message on its way holds tries again when the message stops counting, not at once in a loop. - A resume that fails once the message went answers success, with not_woken saying why it stays paused, rather than a 409 that clients read as "not sent". - The web app's toast says what the server did (woke, still paused, or neither), the paused line yields to the sign-in, refused and limit hints, and only a paused autopilot's session ticks each minute. - autopilots.pauser (itself, fctl or person; migration 0080 rewritten, unshipped) replaces paused_itself, so a pause by someone whose account is gone, or one the log doesn't explain, isn't called fctl's. --- .../0080_autopilot_paused_itself.sql | 14 ---- .../migrations/0080_autopilot_pauser.sql | 29 +++++++ crates/fctl-control/src/api/autopilots.rs | 10 ++- crates/fctl-control/src/api/sessions.rs | 35 +++++---- crates/fctl-control/src/autopilots.rs | 78 +++++++++++++++---- crates/fctl-domain/src/autopilot.rs | 30 ++++++- crates/fctl-proto/src/api.rs | 6 ++ crates/fctl-proto/src/autopilot.rs | 42 +++++++++- crates/fctl/src/cmd/autopilot.rs | 11 +-- crates/fctl/src/cmd/sessions.rs | 10 +++ docs/api.md | 4 +- docs/llms.txt | 2 +- web/src/components/project/autopilot.test.tsx | 1 - web/src/components/project/autopilot.tsx | 3 +- web/src/components/session/composer.tsx | 31 ++++---- web/src/components/session/moved-on.tsx | 10 +-- .../components/session/paused-pilot.test.tsx | 67 ++++++++++++++-- web/src/components/session/paused-pilot.tsx | 33 +++++++- web/src/gen/Autopilot.ts | 9 ++- web/src/gen/Pauser.ts | 7 ++ web/src/gen/SendMessageResponse.ts | 9 ++- web/src/gen/index.ts | 1 + web/src/lib/autopilot.test.ts | 18 +++-- web/src/lib/autopilot.ts | 21 +++-- web/src/lib/live.ts | 22 +++--- web/src/routes/session.test.tsx | 1 - web/src/routes/session.tsx | 17 ++-- 27 files changed, 384 insertions(+), 137 deletions(-) delete mode 100644 crates/fctl-control/migrations/0080_autopilot_paused_itself.sql create mode 100644 crates/fctl-control/migrations/0080_autopilot_pauser.sql create mode 100644 web/src/gen/Pauser.ts diff --git a/crates/fctl-control/migrations/0080_autopilot_paused_itself.sql b/crates/fctl-control/migrations/0080_autopilot_paused_itself.sql deleted file mode 100644 index f30cd573c..000000000 --- a/crates/fctl-control/migrations/0080_autopilot_paused_itself.sql +++ /dev/null @@ -1,14 +0,0 @@ --- An autopilot that paused itself (`fctl autopilot pause`), done or --- waiting for people, rather than one fctl paused: both leave paused_by --- NULL, and people read them differently. Its own session's message box --- asks whether a message wakes it (`SendMessageRequest.wake_autopilot`). -ALTER TABLE autopilots ADD COLUMN paused_itself INTEGER NOT NULL DEFAULT 0; - --- Those paused now that paused themselves, as their log says: the entry --- has the pause's time. -UPDATE autopilots SET paused_itself = 1 -WHERE state = 'paused' AND paused_by IS NULL AND EXISTS ( - SELECT 1 FROM autopilot_log l - WHERE l.project_id = autopilots.project_id AND l.kind = 'state' - AND l.at = autopilots.paused_at AND l.text LIKE 'It paused itself%' -); diff --git a/crates/fctl-control/migrations/0080_autopilot_pauser.sql b/crates/fctl-control/migrations/0080_autopilot_pauser.sql new file mode 100644 index 000000000..a8658a219 --- /dev/null +++ b/crates/fctl-control/migrations/0080_autopilot_pauser.sql @@ -0,0 +1,29 @@ +-- Who paused an autopilot: 'itself' (`fctl autopilot pause`, done or +-- waiting for people), 'fctl' (which can't run it, saying why) or 'person' +-- (paused_by, NULL once their account is gone). People read them +-- differently, and its own session's message box asks whether a message +-- wakes it (`SendMessageRequest.wake_autopilot`). NULL for pauses whose +-- log didn't say. +ALTER TABLE autopilots ADD COLUMN pauser TEXT; + +-- Those paused now, as their log says: the entry has the pause's time. +UPDATE autopilots SET pauser = CASE + WHEN paused_by IS NOT NULL THEN 'person' + WHEN EXISTS ( + SELECT 1 FROM autopilot_log l + WHERE l.project_id = autopilots.project_id AND l.kind = 'state' + AND l.at = autopilots.paused_at AND l.text LIKE 'It paused itself%' + ) THEN 'itself' + WHEN EXISTS ( + SELECT 1 FROM autopilot_log l + WHERE l.project_id = autopilots.project_id AND l.kind = 'state' + AND l.at = autopilots.paused_at AND l.text LIKE 'fctl paused it%' + ) THEN 'fctl' + WHEN EXISTS ( + SELECT 1 FROM autopilot_log l + WHERE l.project_id = autopilots.project_id AND l.kind = 'state' + AND l.at = autopilots.paused_at + AND (l.text LIKE '{who} paused it%' OR l.text LIKE 'Paused: %') + ) THEN 'person' +END +WHERE state = 'paused'; diff --git a/crates/fctl-control/src/api/autopilots.rs b/crates/fctl-control/src/api/autopilots.rs index 000774d2a..892d4ed3c 100644 --- a/crates/fctl-control/src/api/autopilots.rs +++ b/crates/fctl-control/src/api/autopilots.rs @@ -178,7 +178,9 @@ async fn view( paused_reason: row.paused_reason.clone(), paused_by: row.paused_by_ref(), paused_at: row.paused_at, - paused_itself: row.paused_itself && row.state() == AutopilotState::Paused, + pauser: row + .pauser() + .filter(|_| row.state() == AutopilotState::Paused), owner: row.owner_ref(), keep_owner: row.keep_owner, direction: row.direction.clone(), @@ -856,7 +858,7 @@ pub async fn put(ctx: &mut Ctx, req: &mut Request, id: &str) -> AppResult AppResult AppResult AppResu .await?; // Then the autopilot: its wake finds the session about to take the // message up (`ap::own_status`) and reaches it there, at its next step, - // rather than in a fresh session. - let woke_autopilot = match &waking { - None => false, - Some((r, _)) => match crate::api::autopilots::resumed(ctx, r, true).await? { - Ok(()) => true, + // rather than in a fresh session. The message went, whatever happens + // 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. - Err(crate::api::autopilots::NotResumed::NotPaused) => false, - Err(why) => { - return Err(AppError(ApiError::new( - ErrorCode::Conflict, - format!( - "The message went to the session, but the autopilot is still paused: {}", - why.message() + 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(), ), - ))); + ) } }, }; @@ -716,6 +721,7 @@ pub async fn send_message(ctx: &mut Ctx, req: &mut Request, id: &str) -> AppResu delivery_id, held: None, woke_autopilot, + not_woken, }) } @@ -867,6 +873,7 @@ pub async fn interrupt(ctx: &mut Ctx, id: &str) -> AppResult { delivery_id: out.delivery_id, held: None, woke_autopilot: false, + not_woken: None, }) } @@ -901,6 +908,7 @@ pub async fn pass_on(ctx: &mut Ctx, id: &str, review: &str) -> AppResult AppResult, #[serde(deserialize_with = "opt_int", default)] pub paused_at: Option, - /// It paused itself, rather than fctl pausing it. - #[serde(deserialize_with = "int_bool", default)] - pub paused_itself: bool, + /// Who paused it: `itself`, `fctl` or `person` ([`Pauser`]), and none + /// for pauses whose log didn't say. + pub pauser: Option, pub owner_id: Option, #[serde(deserialize_with = "int_bool", default)] pub keep_owner: bool, @@ -133,7 +133,7 @@ pub struct AutopilotRow { } pub const AUTOPILOT_SELECT: &str = "SELECT a.project_id, a.workspace_id, a.scope, a.state, a.paused_reason, \ - a.paused_by, a.paused_at, a.paused_itself, a.owner_id, a.keep_owner, a.direction, a.direction_by, a.direction_at, a.direction_new, a.plan, \ + a.paused_by, a.paused_at, a.pauser, a.owner_id, a.keep_owner, a.direction, a.direction_by, a.direction_at, a.direction_new, a.plan, \ a.plan_at, a.powers, a.check_in_minutes, a.crew_max, a.model, a.effort, a.handoff_at, a.session_id, a.wake_at, a.wake_reasons, \ a.asked_wake_at, a.woken_at, a.check_ins, a.failures, a.created_at, a.updated_at, \ ou.name AS owner_name, ou.avatar_url AS owner_avatar, pu.name AS paused_by_name, pu.avatar_url AS paused_by_avatar, \ @@ -227,6 +227,10 @@ impl AutopilotRow { }) } + pub fn pauser(&self) -> Option { + self.pauser.as_deref().and_then(Pauser::parse) + } + pub fn session_status(&self) -> Option { self.session_status .as_deref() @@ -240,6 +244,14 @@ impl AutopilotRow { .map(|st| ap::own_status(st, self.session_messaged_at, self.session_updated_at, now)) } + /// Until when a person's message on its way keeps its own session at + /// work for a wake, as its status doesn't ([`ap::message_on_its_way`]). + pub fn message_on_its_way(&self, now: i64) -> Option { + self.session_status().and_then(|st| { + ap::message_on_its_way(st, self.session_messaged_at, self.session_updated_at, now) + }) + } + pub fn owner_ref(&self) -> Option { user_ref( self.owner_id.as_deref(), @@ -804,6 +816,16 @@ pub enum PausedBy<'a> { Person(&'a str), } +impl PausedBy<'_> { + pub fn pauser(self) -> Pauser { + match self { + Self::Fctl => Pauser::Fctl, + Self::Itself => Pauser::Itself, + Self::Person(_) => Pauser::Person, + } + } +} + /// Pauses an autopilot, saying why. pub async fn pause( db: &D1Database, @@ -818,13 +840,13 @@ pub async fn pause( }; let paused = q( db, - "UPDATE autopilots SET state = 'paused', paused_reason = ?, paused_by = ?, paused_at = ?, paused_itself = ?, \ + "UPDATE autopilots SET state = 'paused', paused_reason = ?, paused_by = ?, paused_at = ?, pauser = ?, \ wake_at = NULL, wake_reasons = '', asked_wake_at = NULL, updated_at = ? WHERE project_id = ? AND state = 'on'", &[ os(why), os(person), n(now), - crate::db::b(by == PausedBy::Itself), + s(by.pauser().as_str()), n(now), s(project_id), ], @@ -956,8 +978,11 @@ async fn take_up(env: &Env, db: &D1Database, row: &AutopilotRow, now: i64) -> Ap // People asked for a fresh session while its own works: the wake // waits for that one's turn to end, which wakes it again at once // (`session_moved`; here, should it have ended since it was read), - // and all it woke for goes to the fresh session. + // and all it woke for goes to the fresh session. One a message is on + // its way to waits for the turn as long as the message keeps it at + // work, and goes on without it then: its status says idle meanwhile. if ap::holds(&reasons, status) { + let again = row.message_on_its_way(now).unwrap_or(now); q( db, &format!( @@ -969,7 +994,7 @@ async fn take_up(env: &Env, db: &D1Database, row: &AutopilotRow, now: i64) -> Ap ), &[ s(&reasons.iter().map(|r| r.as_str()).collect::>().join(",")), - n(now), + n(again), s(&row.project_id), ], )? @@ -2848,6 +2873,7 @@ pub async fn hold( delivery_id: DeliveryId(h.delivery_id.clone()), held: Some(h.view(ahead)), woke_autopilot: false, + not_woken: None, })); } let Some(row) = row(db, &caller.project_id).await? else { @@ -2903,6 +2929,7 @@ pub async fn hold( delivery_id, held: None, woke_autopilot: false, + not_woken: None, })); } Ok(_) => {} @@ -2922,6 +2949,7 @@ pub async fn hold( delivery_id, held, woke_autopilot: false, + not_woken: None, })) } @@ -4386,13 +4414,23 @@ mod tests { assert_eq!(r.session_status(), Some(SessionStatus::Idle)); assert_eq!(r.session_status_now(NOW), Some(SessionStatus::Running)); assert_eq!(ap::fresh(own(&r), None, false, NOW), None); + // A wake for a fresh session waits for its turn until then, rather + // than try again at once while its status says idle. + assert_eq!( + r.message_on_its_way(NOW), + Some(NOW - 1_000 + ap::MESSAGE_ON_ITS_WAY_MS) + ); + assert!(ap::holds( + &[AutopilotWakeReason::Fresh], + r.session_status_now(NOW) + )); Ok(()) } - /// Whether it paused itself, as people read it: not when fctl or a - /// person did, and no more once it is on again. + /// Who paused it, as people read it: itself, fctl or a person, whose + /// pause stays theirs once their account is gone. #[wasm_bindgen_test] - async fn it_says_when_it_paused_itself() -> AppResult<()> { + async fn it_says_who_paused_it() -> AppResult<()> { let db = testing::database(); autopilot(&db).await?; let on_again = |db: &D1Database| { @@ -4413,11 +4451,11 @@ mod tests { .await? ); let r = row_of(&db).await?; - assert!(r.paused_itself); + assert_eq!(r.pauser(), Some(Pauser::Itself)); assert_eq!(r.paused_by, None); // Paused already: nothing changes. assert!(!pause(&db, "prj_web", None, PausedBy::Fctl, NOW).await?); - assert!(row_of(&db).await?.paused_itself); + assert_eq!(row_of(&db).await?.pauser(), Some(Pauser::Itself)); on_again(&db)?.run().await?; assert!( pause( @@ -4429,12 +4467,20 @@ mod tests { ) .await? ); - assert!(!row_of(&db).await?.paused_itself); + assert_eq!(row_of(&db).await?.pauser(), Some(Pauser::Fctl)); on_again(&db)?.run().await?; assert!(pause(&db, "prj_web", None, PausedBy::Person("usr_ada"), NOW).await?); let r = row_of(&db).await?; - assert!(!r.paused_itself); + assert_eq!(r.pauser(), Some(Pauser::Person)); assert_eq!(r.paused_by.as_deref(), Some("usr_ada")); + q( + &db, + "UPDATE autopilots SET paused_by = NULL WHERE project_id = 'prj_web'", + &[], + )? + .run() + .await?; + assert_eq!(row_of(&db).await?.pauser(), Some(Pauser::Person)); Ok(()) } diff --git a/crates/fctl-domain/src/autopilot.rs b/crates/fctl-domain/src/autopilot.rs index 9627db85f..e65630634 100644 --- a/crates/fctl-domain/src/autopilot.rs +++ b/crates/fctl-domain/src/autopilot.rs @@ -630,11 +630,28 @@ pub fn own_status( updated_at: Option, now: Millis, ) -> SessionStatus { + if message_on_its_way(status, messaged_at, updated_at, now).is_some() { + SessionStatus::Running + } else { + status + } +} + +/// Until when a person's message on its way keeps its own session at work +/// for a wake ([`own_status`]), as its status says no such thing: a wake +/// that waits for its turn to end ([`holds`]) tries again then, should the +/// turn not have come. +pub fn message_on_its_way( + status: SessionStatus, + messaged_at: Option, + updated_at: Option, + now: Millis, +) -> Option { match (status, messaged_at, updated_at) { (SessionStatus::Idle, Some(m), Some(u)) if m >= u && now - m < MESSAGE_ON_ITS_WAY_MS => { - SessionStatus::Running + Some(m + MESSAGE_ON_ITS_WAY_MS) } - _ => status, + _ => None, } } @@ -3867,6 +3884,15 @@ mod tests { own_status(SessionStatus::Idle, None, messaged, now), SessionStatus::Idle ); + // Until its runner had long enough to take it up. + assert_eq!( + message_on_its_way(SessionStatus::Idle, messaged, messaged, now), + messaged.map(|m| m + MESSAGE_ON_ITS_WAY_MS) + ); + assert_eq!( + message_on_its_way(SessionStatus::Running, messaged, messaged, now), + None + ); // A message its runner never took up, offline say, counts no more. let long_ago = Some(now - MESSAGE_ON_ITS_WAY_MS); assert_eq!( diff --git a/crates/fctl-proto/src/api.rs b/crates/fctl-proto/src/api.rs index a354360a4..ad0795ed1 100644 --- a/crates/fctl-proto/src/api.rs +++ b/crates/fctl-proto/src/api.rs @@ -3928,6 +3928,12 @@ pub struct SendMessageResponse { /// was on already, and from control planes before it. #[serde(default)] pub woke_autopilot: bool, + /// Why the paused autopilot stays paused although + /// `SendMessageRequest::wake_autopilot` asked to resume it: the message + /// went all the same. Absent when it woke, or someone resumed it, or took + /// it off autopilot, meanwhile. + #[serde(default)] + pub not_woken: Option, } /// A file sent in a session, with a message or as it started. diff --git a/crates/fctl-proto/src/autopilot.rs b/crates/fctl-proto/src/autopilot.rs index 0a18a276f..46e2e9256 100644 --- a/crates/fctl-proto/src/autopilot.rs +++ b/crates/fctl-proto/src/autopilot.rs @@ -154,6 +154,40 @@ impl AutopilotState { } } +/// Who paused an autopilot, which people read differently: it waits for +/// them, or for what fctl says, or a person decided. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +#[serde(rename_all = "snake_case")] +pub enum Pauser { + /// It paused itself (`fctl autopilot pause`), done or waiting for people. + Itself, + /// fctl did, saying why: its project was archived, its workspace turned + /// autopilots off, nobody's subscription can run it. + Fctl, + /// A person did. + Person, +} + +impl Pauser { + pub fn as_str(self) -> &'static str { + match self { + Self::Itself => "itself", + Self::Fctl => "fctl", + Self::Person => "person", + } + } + + pub fn parse(s: &str) -> Option { + match s { + "itself" => Some(Self::Itself), + "fctl" => Some(Self::Fctl), + "person" => Some(Self::Person), + _ => None, + } + } +} + /// A project's autopilot, as its people see it (`GET /// /api/v1/projects/{id}/autopilot`). #[skip_serializing_none] @@ -171,11 +205,11 @@ pub struct Autopilot { /// Who paused or took it off; absent when fctl or the autopilot did. pub paused_by: Option, pub paused_at: Option, - /// It paused itself (`fctl autopilot pause`), done or waiting for - /// people, rather than fctl pausing it: absent (false) when fctl or a - /// person did, and from control planes before it. + /// Who paused it: itself, fctl or a person (`paused_by`, absent once + /// their account is gone). Absent while it isn't paused, for pauses + /// whose log doesn't say, and from control planes before it. #[serde(default)] - pub paused_itself: bool, + pub pauser: Option, /// Whose Claude subscription it runs on, and as whom it acts: who put /// the project on autopilot, or took it over since. Absent once their /// account is gone. diff --git a/crates/fctl/src/cmd/autopilot.rs b/crates/fctl/src/cmd/autopilot.rs index 60df1a24a..70893dcc5 100644 --- a/crates/fctl/src/cmd/autopilot.rs +++ b/crates/fctl/src/cmd/autopilot.rs @@ -1245,11 +1245,12 @@ fn state_line(a: &Autopilot) -> String { AutopilotState::Paused => { // Whose pause it is: a person's, its own (done, or waiting for // people: `fctl send --wake` resumes it with a message), or fctl's. - let who = match (&a.paused_by, a.paused_itself, &a.paused_reason) { - (Some(p), ..) => format!(" by {}", p.name), - (None, true, _) => " itself".to_owned(), - (None, false, Some(_)) => " by fctl".to_owned(), - (None, false, None) => String::new(), + let who = match (&a.paused_by, a.pauser) { + (Some(p), _) => format!(" by {}", p.name), + (None, Some(Pauser::Person)) => " by someone".to_owned(), + (None, Some(Pauser::Itself)) => " itself".to_owned(), + (None, Some(Pauser::Fctl)) => " by fctl".to_owned(), + (None, None) => String::new(), }; match &a.paused_reason { Some(why) => style::amber(&format!("◍ Paused{who}: {why}")), diff --git a/crates/fctl/src/cmd/sessions.rs b/crates/fctl/src/cmd/sessions.rs index 08e461076..b6f2c357e 100644 --- a/crates/fctl/src/cmd/sessions.rs +++ b/crates/fctl/src/cmd/sessions.rs @@ -1322,6 +1322,16 @@ pub async fn send( s.project_slug, s.number ); + // Sent, but its autopilot stays paused after all: its agent takes the + // message up alone. Don't send it again. + if let Some(why) = &r.not_woken { + eprintln!( + "{} Its autopilot is still paused: {}", + style::amber("!"), + style::terminal_safe(why) + ); + return Ok(()); + } // To the session a paused autopilot works in, its agent takes the // message up alone: say so, and how to wake it next time. if !wake && let Some(why) = paused_pilot(&api, &s).await { diff --git a/docs/api.md b/docs/api.md index 27c2b1018..d4ddcc9cf 100644 --- a/docs/api.md +++ b/docs/api.md @@ -139,7 +139,7 @@ It answers with the session, `queued`. A session is: | Request | Body | What it does | |---|---|---| -| `POST /api/v1/sessions/{id}/messages` | `{"text": "…", "client_id": "…", "attachments": [...], "wake_autopilot": true}` | reaches the agent at its next step; resumes a stopped session on the subscription it ran on; `409` for a failed one. `wake_autopilot`, to the session a paused autopilot works in, from someone who steers it: resumes the autopilot too, as `…/autopilot/resume` does (on their subscription unless its owner keeps it), so that its agent takes the message up as the autopilot rather than alone; the message goes first, then fctl wakes it there with what's new (`409` in an earlier session of its own, or one fctl couldn't run). Answers `{"delivery_id": "dlv_…", "woke_autopilot": true}` (`false` when the autopilot was on already), with `"held": {"id": "aph_…", "ahead"…}` for an autopilot's message to one of its sessions that rests while as many of them work as its people allow: it goes out as that delivery once one of them makes room | +| `POST /api/v1/sessions/{id}/messages` | `{"text": "…", "client_id": "…", "attachments": [...], "wake_autopilot": true}` | reaches the agent at its next step; resumes a stopped session on the subscription it ran on; `409` for a failed one. `wake_autopilot`, to the session a paused autopilot works in, from someone who steers it: resumes the autopilot too, as `…/autopilot/resume` does (on their subscription unless its owner keeps it), so that its agent takes the message up as the autopilot rather than alone; the message goes first, then fctl wakes it there with what's new (`409` in an earlier session of its own, or one fctl couldn't run). Answers `{"delivery_id": "dlv_…", "woke_autopilot": true}` (`false` when the autopilot was on already; with `"not_woken": "…"`, why it stays paused after all, while the message went, so it isn't to be sent again), with `"held": {"id": "aph_…", "ahead"…}` for an autopilot's message to one of its sessions that rests while as many of them work as its people allow: it goes out as that delivery once one of them makes room | | `POST /api/v1/sessions/{id}/interrupt` | | stops the current turn | | `POST /api/v1/sessions/{id}/reviews/{review}/pass-on` | | passes on the findings of review `{review}` (its `session_id`) that fctl held back from the agent (`held_after`), or that went to no session (`unsent`) where the session lists the review's pull request: the agent gets them as it would have, a stopped session resumes on the subscription it ran on, and it gets those of as many reviews in a row again as the review's project's review agents pass on (`rounds`), these included; `409` when fctl holds none of that review's back (the agent got them, someone wrote to it since, or a newer review of its pull request came), the session doesn't list the pull request of findings that went to no session, the pull request is merged or closed, a newer review of it posted, its agent only reads on GitHub, or the session failed. Answers `{"delivery_id": "dlv_…"}` | | `POST /api/v1/sessions/{id}/stop` | | ends the session; its sandbox stays for a resume | @@ -370,7 +370,7 @@ session calls the endpoints marked *autopilot*, through its sandbox's | Request | What it does | |---|---| -| `GET /api/v1/projects/{project}/autopilot` | `{"state": "on" \| "paused" \| "off", "paused_reason", "paused_by", "paused_itself", "scope", "direction", "plan", "powers", "check_in_minutes", "crew_max", "owner", "keep_owner", "session", "fresh_asked", "wake_at", "wake_reason", "problem", "notes", "asks", "crew", "held", "can"…}`; 404 for a project that never had one. `held`: the messages it sent its sessions that wait for room, in the order they go out | +| `GET /api/v1/projects/{project}/autopilot` | `{"state": "on" \| "paused" \| "off", "paused_reason", "paused_by", "pauser": "itself" \| "fctl" \| "person", "scope", "direction", "plan", "powers", "check_in_minutes", "crew_max", "owner", "keep_owner", "session", "fresh_asked", "wake_at", "wake_reason", "problem", "notes", "asks", "crew", "held", "can"…}`; 404 for a project that never had one. `held`: the messages it sent its sessions that wait for room, in the order they go out | | `PUT /api/v1/projects/{project}/autopilot` | `{"direction", "scope": "project" \| "workspace", "powers": ["merge", "settings", "secrets", "repos", "schedules", "projects", "others"], "check_in_minutes", "crew_max", "model", "effort", "handoff_at", "take_over": true, "keep_owner": true}`: puts it on (a [sensitive action](architecture.md#confirming-its-you); `direction` needed the first time; without `powers`, every power its scope has but `others`, managing the sessions people start in its places as its own, which people name), or changes it (absent fields stay; `handoff_at`, the context size from 100,000 to 1,000,000 tokens at which a fresh session of its own takes over, `0` for only after 12 hours). Someone else who changes how much it works (`others` among it) runs it on their subscription from then on, unless its owner keeps it (`keep_owner`, which only its owner, or who puts it on or takes it over, sets; turning it on is a sensitive action too); `take_over` always does | | `POST …/autopilot/off` | `{"stop_sessions": true}`: takes it off, and with that stops the sessions it started that still work | | `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 | diff --git a/docs/llms.txt b/docs/llms.txt index ce5ddcb7c..d913699f0 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: `paused_itself`), 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. 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 eab92921d..2d634255b 100644 --- a/web/src/components/project/autopilot.test.tsx +++ b/web/src/components/project/autopilot.test.tsx @@ -133,7 +133,6 @@ const on = (more: Partial = {}): G.Autopilot => ({ owner: { id: "usr_ada", name: "Ada" }, keep_owner: false, fresh_asked: false, - paused_itself: false, direction: "Ship the **checkout**.", direction_at: Date.now() - 3_600_000, powers: ["settings"], diff --git a/web/src/components/project/autopilot.tsx b/web/src/components/project/autopilot.tsx index 8124b82c1..08af86da3 100644 --- a/web/src/components/project/autopilot.tsx +++ b/web/src/components/project/autopilot.tsx @@ -1204,9 +1204,10 @@ export function MoveButtons({ a }: { a: G.Autopilot }) { } /** Now, every `every` milliseconds, for what says how long ago or until. */ -export function useNow(every: number): number { +export function useNow(every: number | undefined): number { const [now, setNow] = useState(() => Date.now()); useEffect(() => { + if (!every) return; const t = window.setInterval(() => setNow(Date.now()), every); return () => window.clearInterval(t); }, [every]); diff --git a/web/src/components/session/composer.tsx b/web/src/components/session/composer.tsx index c27f48a87..7f88f955b 100644 --- a/web/src/components/session/composer.tsx +++ b/web/src/components/session/composer.tsx @@ -206,27 +206,26 @@ export function Composer({ ) : movedOn && !askOpen ? ( - ) : paused && !askOpen && anyway !== sessionId ? ( - ) : signIn ? ( ) : refused ? ( refused - ) : ( - onTakeOver && ( - - - {limitOf ? `${limitOf}'s` : "This"} subscription is at its limit. - - + ) : onTakeOver ? ( + + + {limitOf ? `${limitOf}'s` : "This"} subscription is at its limit. - ) + + + ) : ( + // What stands in the way of the session comes first: the card still asks as it sends. + paused && !askOpen && anyway !== sessionId && )}
({ ...(await original()), api: new Proxy({} as Record, { get: () => () => new Promise(() => {}) }), })); +vi.mock("@/components/ui", async (original) => ({ + ...(await original()), + toast: vi.fn(), +})); vi.mock("@tanstack/react-router", () => ({ Link: ({ to, children }: { to: string; children: ReactNode }) => {children}, useNavigate: () => () => {}, @@ -24,6 +29,7 @@ const roots: (() => void)[] = []; afterEach(() => { for (const unmount of roots.splice(0)) unmount(); queryClient.clear(); + vi.mocked(toast).mockClear(); }); const NOW = Date.now(); @@ -37,7 +43,7 @@ function autopilot(more: Partial = {}): G.Autopilot { project_slug: "shop", scope: "project", state: "paused", - paused_itself: true, + pauser: "itself", paused_reason: "Waiting for the Stripe keys before checkout.", paused_at: NOW - 2 * HOUR, owner: { id: "usr_noor", name: "Noor Haddad" }, @@ -66,7 +72,12 @@ function pausedPilot(a = autopilot(), more: Partial = {}): PausedPi } /** The composer of session #7, which the paused autopilot `to` works in. */ -function composer(to?: PausedPilot, status: G.SessionStatus = "idle", sending?: () => Promise) { +function composer( + to?: PausedPilot, + status: G.SessionStatus = "idle", + sending?: () => Promise, + more: Partial> = {}, +) { const container = document.createElement("div"); document.body.append(container); const root = createRoot(container); @@ -91,6 +102,7 @@ function composer(to?: PausedPilot, status: G.SessionStatus = "idle", sending?: resumed.push(text); }} paused={to} + {...more} /> , ), @@ -190,7 +202,7 @@ describe("a message to the session of a paused autopilot", () => { it("says who else paused it", async () => { const a = autopilot({ - paused_itself: false, + pauser: "person", paused_by: { id: "usr_bo", name: "Bo Lind" }, paused_reason: "Launch week", }); @@ -240,6 +252,49 @@ describe("a message to the session of a paused autopilot", () => { }); }); +describe("what stands in the session's way", () => { + it("has the line above the box, and the card still asks", async () => { + const c = composer(pausedPilot(), "idle", undefined, { + refused: Claude refused this session's connection., + }); + expect(c.container.textContent).toContain("Claude refused this session's connection."); + expect(c.container.textContent).not.toContain("The autopilot is paused"); + c.type("The keys are in."); + await c.enter(); + expect(c.card()?.textContent).toContain("Wake it and send"); + }); +}); + +describe("what a message that asked to wake it did", () => { + const a = autopilot(); + it("says it woke the autopilot", () => { + sayWoke({ woke_autopilot: true }, a); + expect(toast).toHaveBeenCalledWith("Woke the autopilot: it takes your message up as the autopilot"); + }); + it("says the message went while the autopilot stays paused, and why", () => { + sayWoke( + { woke_autopilot: false, not_woken: "Resuming it failed: resume it on its project's Autopilot tab." }, + a, + ); + expect(toast).toHaveBeenCalledWith( + "Sent, but the autopilot is still paused: Resuming it failed: resume it on its project's Autopilot tab.", + "error", + ); + }); + it("says nothing more when someone resumed it meanwhile", () => { + sayWoke({ woke_autopilot: false }, a); + expect(toast).not.toHaveBeenCalled(); + }); + it("names the session it went to from an earlier one", () => { + sayWoke({ woke_autopilot: true }, a, 8); + sayWoke({ woke_autopilot: false }, a, 8); + expect(vi.mocked(toast).mock.calls).toEqual([ + ["Woke the autopilot in #8 with your message"], + ["Sent to #8, where the autopilot works now"], + ]); + }); +}); + describe("waking a paused autopilot", () => { it("is for those who steer it, in a session that can take a message", () => { const a = autopilot(); @@ -263,7 +318,7 @@ describe("waking a paused autopilot", () => { pausedOf( autopilot({ paused_reason: "Launch week", - paused_itself: false, + pauser: "person", paused_by: { id: "usr_bo", name: "Bo Lind" }, }), NOW, diff --git a/web/src/components/session/paused-pilot.tsx b/web/src/components/session/paused-pilot.tsx index cdb5a8f85..e06b52f15 100644 --- a/web/src/components/session/paused-pilot.tsx +++ b/web/src/components/session/paused-pilot.tsx @@ -9,7 +9,7 @@ // it. Once sent without, the page asks no more until the reader leaves. import { useAutopilot, useNow } from "@/components/project/autopilot"; -import { AutopilotIcon } from "@/components/ui"; +import { AutopilotIcon, toast } from "@/components/ui"; import type * as G from "@/gen"; import { type Paused, pausedHere, paused as pausedOf, sentence } from "@/lib/autopilot"; import { keys, queryClient, useMe } from "@/lib/queries"; @@ -31,8 +31,10 @@ export function usePausedPilot(session: G.Session | undefined): PausedPilot | un const pilot = session?.autopilot?.role === "pilot"; const a = useAutopilot(session?.autopilot?.project_slug ?? "", pilot).data; const me = useMe().data?.user.id; - useNow(60_000); - if (!a || !session || !pilot || !pausedHere(a, session.id)) return; + const here = !!a && !!session && pilot && pausedHere(a, session.id); + // "paused it 2 minutes ago" moves on, in its session alone: the page re-renders with it. + useNow(here ? 60_000 : undefined); + if (!a || !session || !here) return; return { autopilot: a, paused: pausedOf(a), @@ -80,6 +82,31 @@ export function refreshAutopilot(a: Pick | undefined, + a: Pick, + there?: number, +) { + refreshAutopilot(a); + if (r?.woke_autopilot) + toast( + there === undefined + ? "Woke the autopilot: it takes your message up as the autopilot" + : `Woke the autopilot in #${there} with your message`, + ); + else if (r?.not_woken) + toast( + `Sent${there === undefined ? "" : ` to #${there}`}, but the autopilot is still paused: ${r.not_woken}`, + "error", + ); + else if (there !== undefined) toast(`Sent to #${there}, where the autopilot works now`); +} + /** The line above the message box: the autopilot is paused, and a message can wake it. */ export function PausedLine({ to }: { to: PausedPilot }) { return ( diff --git a/web/src/gen/Autopilot.ts b/web/src/gen/Autopilot.ts index 240fcc8db..472029c7a 100644 --- a/web/src/gen/Autopilot.ts +++ b/web/src/gen/Autopilot.ts @@ -9,6 +9,7 @@ import type { AutopilotSession } from "./AutopilotSession"; import type { AutopilotState } from "./AutopilotState"; import type { AutopilotWakeReason } from "./AutopilotWakeReason"; import type { HeldMessage } from "./HeldMessage"; +import type { Pauser } from "./Pauser"; import type { ProjectId } from "./ProjectId"; import type { UserRef } from "./UserRef"; @@ -31,11 +32,11 @@ paused_reason?: string, */ paused_by?: UserRef, paused_at?: number, /** - * It paused itself (`fctl autopilot pause`), done or waiting for - * people, rather than fctl pausing it: absent (false) when fctl or a - * person did, and from control planes before it. + * Who paused it: itself, fctl or a person (`paused_by`, absent once + * their account is gone). Absent while it isn't paused, for pauses + * whose log doesn't say, and from control planes before it. */ -paused_itself: boolean, +pauser?: Pauser, /** * Whose Claude subscription it runs on, and as whom it acts: who put * the project on autopilot, or took it over since. Absent once their diff --git a/web/src/gen/Pauser.ts b/web/src/gen/Pauser.ts new file mode 100644 index 000000000..b4519dfe5 --- /dev/null +++ b/web/src/gen/Pauser.ts @@ -0,0 +1,7 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * Who paused an autopilot, which people read differently: it waits for + * them, or for what fctl says, or a person decided. + */ +export type Pauser = "itself" | "fctl" | "person"; diff --git a/web/src/gen/SendMessageResponse.ts b/web/src/gen/SendMessageResponse.ts index 843ab2ea1..e6b463c17 100644 --- a/web/src/gen/SendMessageResponse.ts +++ b/web/src/gen/SendMessageResponse.ts @@ -18,4 +18,11 @@ held?: HeldMessage, * (`SendMessageRequest::wake_autopilot`): false when that autopilot * was on already, and from control planes before it. */ -woke_autopilot: boolean, }; +woke_autopilot: boolean, +/** + * Why the paused autopilot stays paused although + * `SendMessageRequest::wake_autopilot` asked to resume it: the message + * went all the same. Absent when it woke, or someone resumed it, or took + * it off autopilot, meanwhile. + */ +not_woken?: string, }; diff --git a/web/src/gen/index.ts b/web/src/gen/index.ts index d84393c10..0b48d78b5 100644 --- a/web/src/gen/index.ts +++ b/web/src/gen/index.ts @@ -276,6 +276,7 @@ export type { PasskeyRp } from "./PasskeyRp"; export type { PasskeySignInRequest } from "./PasskeySignInRequest"; export type { PasskeyUser } from "./PasskeyUser"; export type { PauseAutopilotRequest } from "./PauseAutopilotRequest"; +export type { Pauser } from "./Pauser"; export type { Placement } from "./Placement"; export type { PlanLimit } from "./PlanLimit"; export type { PoolDemand } from "./PoolDemand"; diff --git a/web/src/lib/autopilot.test.ts b/web/src/lib/autopilot.test.ts index 87c8152c8..5ac5a6a37 100644 --- a/web/src/lib/autopilot.test.ts +++ b/web/src/lib/autopilot.test.ts @@ -36,7 +36,6 @@ function autopilot(more: Partial = {}): G.Autopilot { owner: { id: "usr_noor", name: "Noor Haddad" }, keep_owner: false, fresh_asked: false, - paused_itself: false, direction: "Ship the checkout.", direction_at: NOW - 86_400_000, powers: ["settings", "schedules"], @@ -138,9 +137,9 @@ describe("where an autopilot stands", () => { ); }); - it("tells a pause of its own from fctl's", () => { + it("tells a pause of its own from fctl's and a person's", () => { const at = { state: "paused" as const, paused_at: NOW - 2 * 3_600_000 }; - const itself = autopilot({ ...at, paused_itself: true, paused_reason: "Waiting for the Stripe keys." }); + const itself = autopilot({ ...at, pauser: "itself", paused_reason: "Waiting for the Stripe keys." }); expect(paused(itself, NOW)).toEqual({ who: "It paused itself", when: "2 hours ago", @@ -150,9 +149,16 @@ describe("where an autopilot stands", () => { expect(phase(itself, NOW).line).toBe( "It paused itself 2 hours ago: Waiting for the Stripe keys. It wakes again once someone resumes it.", ); - const fctl = autopilot({ ...at, paused_reason: "Its project is archived." }); - expect(paused(fctl, NOW).who).toBe("fctl paused it"); - // Without a reason, or a person, it can't tell. + const fctl = autopilot({ ...at, pauser: "fctl", paused_reason: "Its project is archived." }); + expect(paused(fctl, NOW)).toMatchObject({ who: "fctl paused it", itself: false }); + // A person whose account is gone. + expect(paused(autopilot({ ...at, pauser: "person", paused_reason: "Launch week" }), NOW).who).toBe( + "Someone paused it", + ); + // A pause from before fctl said who, with or without a reason. + expect(paused(autopilot({ ...at, paused_reason: "Its project is archived." }), NOW).who).toBe( + "It paused", + ); expect(paused(autopilot(at), NOW).who).toBe("It paused"); }); diff --git a/web/src/lib/autopilot.ts b/web/src/lib/autopilot.ts index 4fc1c65b2..6e23ea4cf 100644 --- a/web/src/lib/autopilot.ts +++ b/web/src/lib/autopilot.ts @@ -191,20 +191,25 @@ export interface Paused { itself: boolean; } -/** Who paused `a`, how long ago and why. A pause with no person is the autopilot's own or fctl's. */ +/** + * Who paused `a`, how long ago and why: a person (someone, once their account is gone), the + * autopilot itself or fctl, as `pauser` says; "It paused" where it doesn't. + */ export function paused( - a: Pick, + a: Pick, now = Date.now(), ): Paused { - const itself = !!a.paused_itself; + const itself = a.pauser === "itself"; return { who: a.paused_by ? `${a.paused_by.name} paused it` - : itself - ? "It paused itself" - : a.paused_reason - ? "fctl paused it" - : "It paused", + : a.pauser === "person" + ? "Someone paused it" + : itself + ? "It paused itself" + : a.pauser === "fctl" + ? "fctl paused it" + : "It paused", when: a.paused_at ? ago(a.paused_at, now) : undefined, reason: a.paused_reason?.trim() || undefined, itself, diff --git a/web/src/lib/live.ts b/web/src/lib/live.ts index 2751167aa..14ca2c1c2 100644 --- a/web/src/lib/live.ts +++ b/web/src/lib/live.ts @@ -343,16 +343,17 @@ export class LiveSession { /** * Sends a message with its uploaded files; shows it right away (images - * from their local previews) and resolves once it is stored. With - * `wakeAutopilot`, to the session a paused autopilot works in, it resumes - * the autopilot too, over HTTP: the socket sends messages alone. + * from their local previews) and resolves once it is stored: with the + * server's answer when it went over HTTP. With `wakeAutopilot`, to the + * session a paused autopilot works in, it resumes the autopilot too, over + * HTTP: the socket sends messages alone. */ send( text: string, author?: G.UserRef, files?: { attachments: G.Attachment[]; previews: Record }, opts?: { wakeAutopilot?: boolean }, - ): Promise { + ): Promise { const client_id = `web-${Date.now().toString(36)}-${++this.counter}`; const attachments = files?.attachments ?? []; const optimistic: Item = { @@ -378,7 +379,7 @@ export class LiveSession { return new Promise((resolve, reject) => { if (this.ws?.readyState === WebSocket.OPEN && !wake) { this.pending.set(client_id, { - resolve, + resolve: () => resolve(undefined), reject: (e) => { drop(); reject(e); @@ -389,13 +390,10 @@ export class LiveSession { // Not connected, or waking its autopilot: HTTP (idempotent by client id). api .sendMessage(this.id, { text, client_id, attachments: ids, wake_autopilot: wake || undefined }) - .then( - () => resolve(), - (e) => { - drop(); - reject(e); - }, - ); + .then(resolve, (e) => { + drop(); + reject(e); + }); } }); } diff --git a/web/src/routes/session.test.tsx b/web/src/routes/session.test.tsx index d7f8f7154..a057b5c94 100644 --- a/web/src/routes/session.test.tsx +++ b/web/src/routes/session.test.tsx @@ -340,7 +340,6 @@ describe("the session page", () => { owner: { id: "usr_ada", name: "Ada Lovelace" }, keep_owner: false, fresh_asked: false, - paused_itself: false, direction: "Ship the checkout.", direction_at: 0, plan: "- [x] Cart\n- [ ] Apple Pay", diff --git a/web/src/routes/session.tsx b/web/src/routes/session.tsx index 807ade93b..0675e1a8d 100644 --- a/web/src/routes/session.tsx +++ b/web/src/routes/session.tsx @@ -54,7 +54,7 @@ import { import { useMovedOn } from "@/components/session/moved-on"; import { JumpPill, NowLine, toBottom, useAtBottom } from "@/components/session/now-line"; import { AgentOrb } from "@/components/session/orb"; -import { pausedSaid, refreshAutopilot, usePausedPilot } from "@/components/session/paused-pilot"; +import { pausedSaid, sayWoke, usePausedPilot } from "@/components/session/paused-pilot"; import { PilotDetails } from "@/components/session/pilot"; import { PlanList } from "@/components/session/plan"; import { @@ -504,13 +504,13 @@ export function SessionPage() { key={session.question.asked_at} question={session.question} canAnswer={(role === "editor" || role === "owner") && status !== "failed"} - onAnswer={(t) => - store.send( + onAnswer={async (t) => { + await store.send( t, me?.user ? { id: me.user.id, name: me.user.name, avatar_url: me.user.avatar_url } : undefined, { attachments: [], previews: {} }, - ) - } + ); + }} floating={questionFloats} className={questionFloats ? "mb-3" : "mt-6"} /> @@ -966,7 +966,7 @@ export function SessionPage() { meId={me?.user.id} sessionId={id} onSend={async (t, files, opts) => { - await store.send( + const r = await store.send( t, me?.user ? { id: me.user.id, name: me.user.name, avatar_url: me.user.avatar_url } @@ -974,10 +974,7 @@ export function SessionPage() { files, opts, ); - if (opts?.wakeAutopilot && pausedPilot) { - refreshAutopilot(pausedPilot.autopilot); - toast("Woke the autopilot: it takes your message up as the autopilot"); - } + if (opts?.wakeAutopilot && pausedPilot) sayWoke(r, pausedPilot.autopilot); }} onInterrupt={() => store.interrupt()} onTyping={() => store.typing()}