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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions crates/fctl-client/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -830,19 +830,23 @@ 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<String>,
attachments: Vec<AttachmentId>,
wake_autopilot: bool,
) -> Result<SendMessageResponse> {
self.post(
&format!("/sessions/{}/messages", enc(session)),
&SendMessageRequest {
text: text.to_owned(),
client_id,
attachments,
wake_autopilot: wake_autopilot.then_some(true),
},
)
.await
Expand Down
29 changes: 29 additions & 0 deletions crates/fctl-control/migrations/0080_autopilot_pauser.sql
Original file line number Diff line number Diff line change
@@ -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';
141 changes: 122 additions & 19 deletions crates/fctl-control/src/api/autopilots.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::*;
Expand Down Expand Up @@ -178,6 +178,9 @@ async fn view(
paused_reason: row.paused_reason.clone(),
paused_by: row.paused_by_ref(),
paused_at: row.paused_at,
pauser: row
.pauser()
.filter(|_| row.state() == AutopilotState::Paused),
owner: row.owner_ref(),
keep_owner: row.keep_owner,
direction: row.direction.clone(),
Expand Down Expand Up @@ -855,7 +858,7 @@ pub async fn put(ctx: &mut Ctx, req: &mut Request, id: &str) -> AppResult<Respon
failures, created_by, created_at, updated_at) \
VALUES (?1, ?2, ?3, 'on', ?4, ?12, ?5, ?4, ?6, 0, ?7, ?8, ?9, ?10, ?11, ?13, ?6, 'started', 0, ?4, ?6, ?6) \
ON CONFLICT (project_id) DO UPDATE SET workspace_id = excluded.workspace_id, scope = excluded.scope, \
state = 'on', paused_reason = NULL, paused_by = NULL, paused_at = NULL, owner_id = excluded.owner_id, \
state = 'on', paused_reason = NULL, paused_by = NULL, paused_at = NULL, pauser = NULL, owner_id = excluded.owner_id, \
keep_owner = excluded.keep_owner, \
direction = excluded.direction, direction_by = CASE WHEN autopilots.direction = excluded.direction \
THEN autopilots.direction_by ELSE excluded.direction_by END, \
Expand Down Expand Up @@ -1243,7 +1246,7 @@ pub async fn off(ctx: &mut Ctx, req: &mut Request, id: &str) -> AppResult<Respon
let me = ctx.user()?.clone();
q(
&ctx.db,
"UPDATE autopilots SET state = 'off', paused_reason = NULL, paused_by = ?, paused_at = ?, wake_at = NULL, \
"UPDATE autopilots SET state = 'off', paused_reason = NULL, paused_by = ?, paused_at = ?, pauser = NULL, wake_at = NULL, \
wake_reasons = '', asked_wake_at = NULL, updated_at = ? WHERE project_id = ?",
&[s(&me.id), n(ctx.now), n(ctx.now), s(&row.project_id)],
)?
Expand Down Expand Up @@ -1339,7 +1342,14 @@ pub async fn pause(ctx: &mut Ctx, req: &mut Request, id: &str) -> AppResult<Resp
let reason = ap::reason(body.reason.as_deref()).map_err(AppError)?;
if ctx.autopilot().is_some() {
require_pilot(ctx, &l)?;
engine::pause(&ctx.db, &row.project_id, reason.as_deref(), None, ctx.now).await?;
engine::pause(
&ctx.db,
&row.project_id,
reason.as_deref(),
engine::PausedBy::Itself,
ctx.now,
)
.await?;
engine::log(
&ctx.db,
&row.project_id,
Expand All @@ -1364,7 +1374,7 @@ pub async fn pause(ctx: &mut Ctx, req: &mut Request, id: &str) -> AppResult<Resp
&ctx.db,
&row.project_id,
reason.as_deref(),
Some(&me.id),
engine::PausedBy::Person(&me.id),
ctx.now,
)
.await?;
Expand Down Expand Up @@ -1395,11 +1405,76 @@ pub async fn pause(ctx: &mut Ctx, req: &mut Request, id: &str) -> AppResult<Resp
/// `POST …/autopilot/resume`: it wakes at once, on the resumer's
/// subscription from now on when it ran on someone else's.
pub async fn resume(ctx: &mut Ctx, id: &str) -> AppResult<Response> {
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 {
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<Result<engine::Owner, String>> {
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<Option<Resuming>> {
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(
Expand All @@ -1414,17 +1489,37 @@ pub async fn resume(ctx: &mut Ctx, id: &str) -> AppResult<Response> {
.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. Not
/// when it changed meanwhile, and why.
pub async fn resumed(ctx: &Ctx, r: &Resuming, message: bool) -> AppResult<Result<(), NotResumed>> {
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, pauser = NULL, 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",
Expand All @@ -1441,42 +1536,50 @@ pub async fn resume(ctx: &mut Ctx, id: &str) -> AppResult<Response> {
.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
},
));
}
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),
ctx.now,
)
.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(Ok(()))
}

/// `POST …/autopilot/wake`: a person wakes it now, with `fresh` in a fresh
Expand Down
Loading
Loading