diff --git a/crates/fctl-client/src/api.rs b/crates/fctl-client/src/api.rs index 6c133965..32342465 100644 --- a/crates/fctl-client/src/api.rs +++ b/crates/fctl-client/src/api.rs @@ -1791,6 +1791,16 @@ impl Api { .await } + /// Moves a session off the runner it runs on, to another that would + /// run it (`POST /sessions/{id}/move`). + pub async fn move_off(&self, session: &str) -> Result { + self.post( + &format!("/sessions/{}/move", enc(session)), + &serde_json::json!({}), + ) + .await + } + pub async fn resume( &self, session: &str, diff --git a/crates/fctl-control/src/api/autopilots.rs b/crates/fctl-control/src/api/autopilots.rs index 892d4ed3..03b010e5 100644 --- a/crates/fctl-control/src/api/autopilots.rs +++ b/crates/fctl-control/src/api/autopilots.rs @@ -196,7 +196,7 @@ async fn view( handoff_at: row.handoff_at(), fresh_asked: row.state() == AutopilotState::On && row.reasons().contains(&AutopilotWakeReason::Fresh), - session: row.session(), + session: row.session(ctx.now), wake_at: row.wake_at.filter(|_| row.state() == AutopilotState::On), wake_reason: row .wake_reason() diff --git a/crates/fctl-control/src/api/sessions.rs b/crates/fctl-control/src/api/sessions.rs index 9c5c1896..78bd487f 100644 --- a/crates/fctl-control/src/api/sessions.rs +++ b/crates/fctl-control/src/api/sessions.rs @@ -977,6 +977,38 @@ pub async fn stop(ctx: &mut Ctx, id: &str) -> AppResult { get(ctx, id).await } +/// `POST /sessions/{id}/move`: the session leaves the runner it runs on, +/// which doesn't get it back, and starts on another that would run it, as +/// a resume there does (FleetDO's `move_session`). For a runner that went +/// quiet, or sleeps but for a moment now and then, which a session waits +/// for otherwise. +pub async fn move_off(ctx: &mut Ctx, id: &str) -> AppResult { + let a = access::session(ctx, id).await?; + a.require_owner()?; + refuse_review(&a.row)?; + if status_now(ctx, &a.row).await.is_terminal() { + return Err(conflict( + "It isn't running: a resume starts it on any runner that would run it.", + )); + } + let fleet = internal::fleet_stub(&ctx.env)?; + let moved: internal::Moved = internal::post( + &fleet, + "/move", + &internal::Move { + session_id: id.to_owned(), + }, + ) + .await?; + ctx.audit_in( + Some(a.workspace_id()), + "session.moved", + Some(id), + Some(serde_json::json!({ "from": moved.from })), + ); + get(ctx, id).await +} + pub async fn resume(ctx: &mut Ctx, req: &mut Request, id: &str) -> AppResult { let body: ResumeSessionRequest = if http::header(req, "Content-Type").is_some() { http::body(req).await? diff --git a/crates/fctl-control/src/autopilots.rs b/crates/fctl-control/src/autopilots.rs index af1ea49a..e627b512 100644 --- a/crates/fctl-control/src/autopilots.rs +++ b/crates/fctl-control/src/autopilots.rs @@ -130,6 +130,14 @@ pub struct AutopilotRow { pub session_messaged_at: Option, #[serde(deserialize_with = "opt_int", default)] pub session_updated_at: Option, + /// The runner its own session runs on, and when D1 last heard from it + /// (each of its heartbeats, while it is enabled). + #[serde(default)] + pub session_runner_id: Option, + #[serde(default)] + pub session_runner_name: Option, + #[serde(deserialize_with = "opt_int", default)] + pub session_runner_seen_at: Option, } pub const AUTOPILOT_SELECT: &str = "SELECT a.project_id, a.workspace_id, a.scope, a.state, a.paused_reason, \ @@ -140,12 +148,15 @@ pub const AUTOPILOT_SELECT: &str = "SELECT a.project_id, a.workspace_id, a.scope 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.messaged_at AS session_messaged_at, ps.updated_at AS session_updated_at \ + ps.messaged_at AS session_messaged_at, ps.updated_at AS session_updated_at, \ + ps.runner_id AS session_runner_id, psr.name AS session_runner_name, \ + CASE WHEN psr.enabled = 1 THEN psr.last_seen_at END AS session_runner_seen_at \ FROM autopilots a \ LEFT JOIN users ou ON ou.id = a.owner_id \ LEFT JOIN users pu ON pu.id = a.paused_by \ LEFT JOIN users du ON du.id = a.direction_by \ - LEFT JOIN sessions ps ON ps.id = a.session_id"; + LEFT JOIN sessions ps ON ps.id = a.session_id \ + LEFT JOIN runners psr ON psr.id = ps.runner_id"; impl AutopilotRow { pub fn scope(&self) -> AutopilotScope { @@ -181,8 +192,8 @@ impl AutopilotRow { self.session_context.and_then(|t| u64::try_from(t).ok()) } - /// Its own session as people and the API see it. - pub fn session(&self) -> Option { + /// Its own session as people and the API see it, as of `now`. + pub fn session(&self, now: i64) -> Option { match ( &self.session_id, self.session_number, @@ -196,6 +207,17 @@ impl AutopilotRow { status, started_at, context_tokens: self.session_context(), + runner: match (&self.session_runner_id, &self.session_runner_name) { + (Some(id), Some(name)) => Some(fctl_proto::session::RunnerRef { + id: fctl_proto::ids::RunnerId(id.clone()), + name: name.clone(), + }), + _ => None, + }, + // Only while it runs there: a stopped session's runner + // keeps its sandbox, but holds up nothing. + runner_away_since: ap::away_since(self.session_runner_seen_at, now) + .filter(|_| ap::on_runner(status)), }) } _ => None, @@ -975,13 +997,36 @@ async fn take_up(env: &Env, db: &D1Database, row: &AutopilotRow, now: i64) -> Ap } // One a person just messaged works already (`ap::own_status`). let status = row.session_status_now(now); + // Where its own session's sandbox is, as the fleet has it, while it + // has one or may resume into one: should the fleet not say, it + // carries on as before. + let sandbox = match (row.session_id.as_deref(), status) { + (Some(id), Some(st)) if st != SessionStatus::Failed => { + match sandbox_of(env, id).await { + Ok(at) => Some(at), + Err(e) => { + worker::console_error!( + "autopilot {}: where its session's sandbox is: {}", + row.project_id, + e.0.message + ); + None + } + } + } + _ => None, + }; + let view = sandbox.as_ref().map(sandbox_view).unwrap_or_default(); + // Stranded where its runner went away, it works no more, and the + // wake moves it to a fresh session on a runner that can be reached. + let stranded = status.is_some_and(|st| ap::stranded(st, view)); // 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. 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) { + if ap::holds(&reasons, status, view) { let again = row.message_on_its_way(now).unwrap_or(now); q( db, @@ -1013,7 +1058,7 @@ async fn take_up(env: &Env, db: &D1Database, row: &AutopilotRow, now: i64) -> Ap ); } let news = News::gather(db, row, now).await?; - let working = status.is_some_and(ap::at_work); + let working = status.is_some_and(ap::at_work) && !stranded; // At work already: a check-in can wait; news reaches it at its next // step. let only_time = reasons @@ -1043,29 +1088,13 @@ async fn take_up(env: &Env, db: &D1Database, row: &AutopilotRow, now: i64) -> Ap } _ => Some(ap::Fresh::Failed), }; - // Between its turns, where its sandbox is counts too: off a runner - // that drains, and rather than resume without its conversation on - // another runner, it moves to a fresh session (`ap::moves`). Should - // the fleet not say, it carries on as before. - let mut sandbox = None; - let fresh = match (fresh, row.session_id.as_deref(), status) { - (None, Some(id), Some(st)) if ap::between_turns(st) => match sandbox_of(env, id).await - { - Ok(at) => { - let moved = ap::moves(st, sandbox_view(&at)); - sandbox = Some(at); - moved - } - Err(e) => { - worker::console_error!( - "autopilot {}: where its session's sandbox is: {}", - row.project_id, - e.0.message - ); - None - } - }, - (f, ..) => f, + // Where its sandbox is counts too: off a runner that went away, or + // between its turns off one that drains, and rather than resume + // without its conversation on another runner, it moves to a fresh + // session (`ap::moves`). + let fresh = match (fresh, status) { + (None, Some(st)) if sandbox.is_some() => ap::moves(st, view), + (f, _) => f, }; let carries_on = fresh.is_none(); // Near where it hands off, it hears so, to write down what its next @@ -1159,12 +1188,14 @@ async fn take_up(env: &Env, db: &D1Database, row: &AutopilotRow, now: i64) -> Ap .await?; let mut line = woke_line(&reasons, &wake); if let Some(why) = fresh.filter(|_| row.session_id.is_some()) - && let Some(said) = ap::fresh_why( - why, - sandbox.as_ref().map(sandbox_view).unwrap_or_default(), - ) + && let Some(said) = ap::fresh_why(why, view) { - line.push_str(&format!(", in a fresh session: {said}")); + // Its runner went away, alone: the fresh session says it all. + if reasons == [AutopilotWakeReason::Away] { + line = format!("Woke in a fresh session: {said}"); + } else { + line.push_str(&format!(", in a fresh session: {said}")); + } } log( db, @@ -1396,6 +1427,8 @@ fn retrying(db: &D1Database, project_id: &str, at: i64) -> AppResult { /// What [`woke_line`] says of [`AutopilotWakeReason::Fresh`], alone. const FRESH_ASKED: &str = "someone asked for a fresh session"; +/// What [`woke_line`] says of [`AutopilotWakeReason::Away`]. +const AWAY: &str = "its session's runner went away"; /// What a wake says in the log: "Woke for its check-in", "Woke: Ada's /// note, shop#41". @@ -1439,13 +1472,19 @@ fn woke_line(reasons: &[AutopilotWakeReason], wake: &AutopilotWake) -> String { [] => "people's sessions".into(), many => format!("{} of people's sessions", many.len()), }, + AutopilotWakeReason::Away => AWAY.into(), AutopilotWakeReason::Other => continue, }); } match parts.as_slice() { [] => "Woke".into(), // "Woke as it was put on", alone; "being put on" among others. - [one] if one.starts_with("it was ") || one == "someone woke it" || one == FRESH_ASKED => { + [one] + if one.starts_with("it was ") + || one == "someone woke it" + || one == FRESH_ASKED + || one == AWAY => + { format!("Woke as {one}") } [one] => format!("Woke for {one}"), @@ -1457,6 +1496,7 @@ fn woke_line(reasons: &[AutopilotWakeReason], wake: &AutopilotWake) -> String { Some(was) => format!("being {was}"), None if p == "someone woke it" => "someone waking it".to_owned(), None if p == FRESH_ASKED => "someone asking for a fresh session".to_owned(), + None if p == AWAY => "its session's runner going away".to_owned(), None => p.clone(), }) .collect::>() @@ -1648,6 +1688,7 @@ fn sandbox_view(at: &crate::internal::SandboxAt) -> ap::Sandbox<'_> { online: at.runner.as_ref().is_some_and(|r| r.online), draining: at.runner.as_ref().is_some_and(|r| r.draining), elsewhere: at.elsewhere, + away: at.runner.as_ref().is_some_and(|r| r.away), } } @@ -2589,6 +2630,28 @@ pub async fn session_moved( Ok(()) } +/// Its own session `session_id` was cut off: fctl stopped it as its runner +/// stayed away (`do_fleet`'s `expire_offline_runners`), in the middle of +/// its turn or before it took up a message. Nothing else may wake it +/// before its check-in, so it wakes now, and carries on in a fresh +/// session on a runner that can be reached (`ap::moves`). +pub async fn own_cut_off(env: &Env, autopilot: &str, session_id: &str, now: i64) -> AppResult<()> { + let db = env.d1("DB")?; + let woke = nudging( + &db, + autopilot, + AutopilotWakeReason::Away, + now, + Some(("session_id = ?4", vec![s(session_id)])), + )? + .run() + .await?; + if woke > 0 { + ring(env).await; + } + Ok(()) +} + /// What a session people started that moved means to the autopilot that /// manages it, if one does ([`manager`]; from SessionObject, which tells /// it only of what would wake the autopilot for one of its own, @@ -4422,7 +4485,8 @@ mod tests { ); assert!(ap::holds( &[AutopilotWakeReason::Fresh], - r.session_status_now(NOW) + r.session_status_now(NOW), + ap::Sandbox::default() )); Ok(()) } diff --git a/crates/fctl-control/src/do_fleet.rs b/crates/fctl-control/src/do_fleet.rs index 0ead9300..2cce54fa 100644 --- a/crates/fctl-control/src/do_fleet.rs +++ b/crates/fctl-control/src/do_fleet.rs @@ -58,6 +58,14 @@ struct Credentials { const MAX_ATTEMPTS: i64 = 5; /// A runner that stays away this long loses its sessions. const RUNNER_GRACE_MS: i64 = 10 * 60 * 1000; +/// A runner whose control connection carried nothing for this long, four +/// of its heartbeats, is offline, whatever its socket says: a laptop gone +/// to sleep, or a network that dropped without closing the connection, +/// can leave the socket open for a long time. +const SILENT_MS: i64 = fctl_domain::autopilot::RUNNER_SILENT_MS; +/// The close code of a runner's connection FleetObject gave up on for its +/// silence: its host connects again once it can. +const CLOSE_SILENT: u16 = 4008; /// How long a resumed session waits for the runner that has its sandbox, /// while that runner is busy, before it starts on another one in a new /// sandbox (without its conversation). @@ -140,6 +148,11 @@ struct RunnerSocket { /// connections an older Worker accepted. #[serde(default, skip_serializing_if = "Option::is_none")] token_hash: Option, + /// FleetObject closed it, as nothing came through it for a while + /// ([`SILENT_MS`]): what still comes through it as it closes changes + /// nothing, and its host says hello again on a new one. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + silent: bool, } #[derive(Deserialize)] @@ -234,9 +247,20 @@ struct LiveRow { } impl LiveRow { - /// Whether FleetObject has its control connection now. + /// Whether FleetObject has its control connection now, and heard from + /// it lately: one that went silent is offline ([`SILENT_MS`]). fn online(&self, fleet: &FleetObject) -> bool { - self.connected > 0.0 && fleet.runner_socket(&self.id).is_some() + self.connected > 0.0 && !self.silent(now_ms()) && fleet.runner_socket(&self.id).is_some() + } + + /// Nothing came from it for [`SILENT_MS`] as of `now`. + fn silent(&self, now: i64) -> bool { + self.last_seen.is_some_and(|t| now - t as i64 >= SILENT_MS) + } + + /// How long before `now` it was last heard from. + fn heard_ago(&self, now: i64) -> i64 { + now - self.last_seen.map_or(now, |t| t as i64) } } @@ -528,6 +552,9 @@ impl DurableObject for FleetObject { // Sessions stopped because their runner stayed away: they carry // on if it comes back with them. "CREATE TABLE IF NOT EXISTS stopped_away (session_id TEXT PRIMARY KEY, runner_id TEXT NOT NULL, since INTEGER NOT NULL)", + // Sessions people moved off a runner (`move_session`): they + // start on any other, until they have. + "CREATE TABLE IF NOT EXISTS moved_off (session_id TEXT PRIMARY KEY, runner_id TEXT NOT NULL, since INTEGER NOT NULL)", // When the alarm last ticked, and since when it has ticked // without a gap: the time a runner that may be removed counts // as offline (`fctl_domain::enrollment::watching_since`). @@ -561,6 +588,12 @@ impl DurableObject for FleetObject { // queue's, and the run's, for a decline to add to. add_column(&sql, "queue", "tried", "TEXT"); add_column(&sql, "assignments", "tried", "TEXT"); + // Its session heard that its runner has been away a minute + // (`ControlState::runner_away`): when. + add_column(&sql, "assignments", "away_told", "INTEGER"); + // When FleetDO first asked its runner to stop the session: one whose + // runner hasn't stopped it a minute later is let go (`stop_overdue`). + add_column(&sql, "assignments", "stopping_at", "INTEGER"); add_column(&sql, "runners", "memory_available_mb", "INTEGER"); add_column(&sql, "runners", "disk_available_mb", "INTEGER"); // Set while the runner drains: since when, and the admin who drained @@ -611,6 +644,13 @@ impl DurableObject for FleetObject { Ok(b) => self.stop(b).await, Err(e) => Err(ApiError::bad_request(e.to_string())), }, + (worker::Method::Post, "/move") => match req.json::().await { + Ok(b) => self + .move_session(&b.session_id) + .await + .map(|m| serde_json::json!(m)), + Err(e) => Err(ApiError::bad_request(e.to_string())), + }, (worker::Method::Post, "/workspaces-changed") => { match req.json::().await { Ok(b) => { @@ -789,6 +829,9 @@ impl DurableObject for FleetObject { } } } else if let Ok(Some(rs)) = ws.deserialize_attachment::() { + if rs.silent { + return Ok(()); + } match serde_json::from_str::(&text) { Ok(msg) => self.on_runner(&ws, &rs, msg).await, Err(e) => worker::console_error!("bad runner message: {e}"), @@ -815,8 +858,10 @@ impl DurableObject for FleetObject { async fn alarm(&self) -> Result { let now = now_ms(); + self.drop_silent(now).await; self.remove_gone_runners(now).await; self.expire_offline_runners(now).await; + self.let_go_of_moves(now).await; self.dispatch().await; // Keep ticking while there is something to wait for. if self.has_pending_work() { @@ -828,7 +873,11 @@ impl DurableObject for FleetObject { impl FleetObject { async fn on_close(&self, ws: &WebSocket) { - if let Ok(Some(rs)) = ws.deserialize_attachment::() { + // One closed for its silence is offline already, since it was + // last heard from (`drop_silent`). + if let Ok(Some(rs)) = ws.deserialize_attachment::() + && !rs.silent + { let still = self .state .get_websockets_with_tag(&runner_tag(&rs.id)) @@ -870,6 +919,7 @@ impl FleetObject { since: now_ms(), pending: ident.pending.clone(), token_hash: ident.token_hash.clone(), + silent: false, })?; let _ = self.sql.exec( "INSERT INTO runners (id, name, connected, last_seen, remove_after_ms) VALUES (?, ?, 1, ?, ?) \ @@ -937,7 +987,7 @@ impl FleetObject { fn live_runners(&self) -> LiveRunners { let mut out = LiveRunners::default(); for r in self.live_rows() { - if r.connected > 0.0 && self.runner_socket(&r.id).is_some() { + if r.online(self) { out.online.push(r.id.clone()); out.free.insert( r.id.clone(), @@ -1018,9 +1068,8 @@ impl FleetObject { .unwrap_or(0.0) }; count("SELECT COUNT(*) AS n FROM queue") > 0.0 - || count( - "SELECT COUNT(*) AS n FROM assignments a JOIN runners r ON r.id = a.runner_id WHERE r.connected = 0", - ) > 0.0 + // Sessions on runners that are offline, or that may go silent. + || count("SELECT COUNT(*) AS n FROM assignments") > 0.0 // A runner that goes once offline long enough, while it is. || self .live_rows() @@ -1283,6 +1332,8 @@ impl FleetObject { "UPDATE runners SET last_seen = ?, connected = 1 WHERE id = ?", Some(vec![iv(now), sv(&rs.id)]), ); + // Each runner's heartbeats notice the others that went silent. + self.drop_silent(now).await; match msg { HostToFleet::Hello(hello) => self.on_hello(ws, rs, *hello, now).await, HostToFleet::Heartbeat(hb) => { @@ -1331,6 +1382,10 @@ impl FleetObject { return; } self.stop_idle_if_draining(&rs.id, &hb.sessions).await; + // The alarm notices should this runner go silent with them. + if !hb.sessions.is_empty() { + self.ensure_alarm().await; + } let token_changed = self.note_claude_token(&rs.id, hb.claude_token).await; let drivers_changed = self.note_drivers(&rs.id, hb.drivers).await; let store_changed = self.note_snapshot_store(&rs.id, hb.snapshot_store).await; @@ -1492,6 +1547,11 @@ impl FleetObject { } async fn on_hello(&self, ws: &WebSocket, rs: &RunnerSocket, hello: HostHello, now: i64) { + // Back: should it go away again, its sessions hear of it again. + let _ = self.sql.exec( + "UPDATE assignments SET away_told = NULL WHERE runner_id = ?", + Some(vec![sv(&rs.id)]), + ); let info = serde_json::to_string(&hello).unwrap_or_default(); let sessions = serde_json::to_string(&hello.sessions).unwrap_or_else(|_| "[]".into()); let _ = self.sql.exec( @@ -1590,13 +1650,9 @@ impl FleetObject { ); self.close_uplink(&a.session_id, runner_id).await; if !self.queued(&a.session_id) { - self.session_control( + self.runner_gone( &SessionId(a.session_id.clone()), - Some(SessionStatus::Stopped), - Some(format!( - "{reason} A message or a resume starts it on another runner." - )), - true, + format!("{reason} A message or a resume starts it on another runner."), ) .await; } @@ -2349,7 +2405,8 @@ impl FleetObject { }; self.load_runner_workspaces(&db).await; let labels = want.labels_at(now, now); - match self.pick_runner(&want, labels, None, false, tried) { + let off = self.moved_off(session_id); + match self.pick_runner(&want, labels, None, false, tried, off.as_deref()) { Ok(_) => false, Err(wait) => wait.rules_out(labels_fall_back(&want, labels)), } @@ -2379,14 +2436,70 @@ impl FleetObject { .await; } + /// Takes the runners whose connection is open but carried nothing for + /// [`SILENT_MS`] offline, as of when they were last heard from, as if + /// it had closed then: their sessions stop once that was ten minutes + /// ago, or a minute for those someone stopped (`expire_offline_runners`). + /// The connection closes, so that a host that comes back says hello on + /// a new one, and what was decided about its sessions meanwhile holds + /// (`reconcile`). + async fn drop_silent(&self, now: i64) { + #[derive(Deserialize)] + struct R { + id: String, + name: String, + } + let silent: Vec = self + .sql + .exec( + "SELECT id, name FROM runners WHERE connected = 1 AND last_seen <= ?", + Some(vec![iv(now - SILENT_MS)]), + ) + .and_then(|c| c.to_array::()) + .unwrap_or_default(); + if silent.is_empty() { + return; + } + for r in &silent { + for ws in self.state.get_websockets_with_tag(&runner_tag(&r.id)) { + if let Ok(Some(mut rs)) = ws.deserialize_attachment::() { + rs.silent = true; + let _ = ws.serialize_attachment(&rs); + } + let _ = ws.close( + Some(CLOSE_SILENT), + Some("nothing came from the runner for a minute"), + ); + } + let _ = self.sql.exec( + "UPDATE runners SET connected = 0 WHERE id = ?", + Some(vec![sv(&r.id)]), + ); + worker::console_log!("runner {} went silent: it is offline", r.name); + } + let ids: Vec<&str> = silent.iter().map(|r| r.id.as_str()).collect(); + self.feed_runners(&ids).await; + self.ensure_alarm().await; + } + + /// Whether the runner is online now ([`LiveRow::online`]). + fn reachable(&self, runner_id: &str) -> bool { + self.live_rows() + .iter() + .any(|r| r.id == runner_id && r.online(self)) + } + /// Runners offline for longer than the grace period lose their sessions, /// which carry on if the runner comes back with them before they run - /// anywhere else. + /// anywhere else. Those someone stopped stop once it has been offline + /// a minute. async fn expire_offline_runners(&self, now: i64) { - let _ = self.sql.exec( + for sql in [ "DELETE FROM stopped_away WHERE since < ?", - Some(vec![iv(now - HOME_KEEP_MS)]), - ); + "DELETE FROM moved_off WHERE since < ?", + ] { + let _ = self.sql.exec(sql, Some(vec![iv(now - HOME_KEEP_MS)])); + } // A runner that was removed while away, and FleetObject wasn't told // (`api::runners::removed` failed): its sessions stop as a removed // runner's do, rather than waiting for it to come back. @@ -2403,40 +2516,95 @@ impl FleetObject { if !away.is_empty() { self.forget_removed(&away).await; } + #[derive(Deserialize)] + struct Assigned { + session_id: String, + #[serde(default)] + stopping: Option, + #[serde(default)] + away_told: Option, + } for r in self.live_rows() { - let offline_for = now - r.last_seen.map_or(now, |t| t as i64); - if r.connected > 0.0 || offline_for < RUNNER_GRACE_MS { + let offline_for = r.heard_ago(now); + if r.connected > 0.0 || offline_for < SILENT_MS { continue; } - let assigned: Vec = self + let assigned: Vec = self .sql .exec( - "SELECT session_id, runner_id, accepted FROM assignments WHERE runner_id = ?", + "SELECT session_id, stopping, away_told FROM assignments WHERE runner_id = ?", Some(vec![sv(&r.id)]), ) - .and_then(|c| c.to_array::()) + .and_then(|c| c.to_array::()) .unwrap_or_default(); for a in assigned { + // Someone stopped it, or fctl did: it stops once its runner + // has been away a minute, rather than wait for one that may + // not come back. Its host stops the sandbox if it does. + let stopping = a.stopping.is_some_and(|s| s > 0.0); + if !stopping && offline_for < RUNNER_GRACE_MS { + // Once, that its runner has been away a minute: an + // autopilot's own session with a message its agent + // didn't take wakes its autopilot, which carries on in + // a fresh session elsewhere. + if a.away_told.is_none() { + let _ = self.sql.exec( + "UPDATE assignments SET away_told = ? WHERE session_id = ?", + Some(vec![iv(now), sv(&a.session_id)]), + ); + self.session_control_with( + &SessionId(a.session_id), + ControlState { + runner_away: true, + ..Default::default() + }, + ) + .await; + } + continue; + } let _ = self.sql.exec( "DELETE FROM assignments WHERE session_id = ?", Some(vec![sv(&a.session_id)]), ); - // Queued again meanwhile: it starts elsewhere. + // Queued again meanwhile (resumed, or moved off it): it starts + // elsewhere. Without this runner, which would otherwise take + // it back as its own as it reconnects with the run. if self.queued(&a.session_id) { + self.let_go(&a.session_id, &r.id).await; + self.session_control_with( + &SessionId(a.session_id), + ControlState { + clear_runner: true, + ..Default::default() + }, + ) + .await; + continue; + } + if stopping { + self.session_control( + &SessionId(a.session_id), + Some(SessionStatus::Stopped), + Some(format!( + "Stopped while runner {} is offline: its host stops the sandbox when it connects again.", + r.name + )), + true, + ) + .await; continue; } let _ = self.sql.exec( "INSERT OR REPLACE INTO stopped_away (session_id, runner_id, since) VALUES (?, ?, ?)", Some(vec![sv(&a.session_id), sv(&r.id), iv(now)]), ); - self.session_control( + self.runner_gone( &SessionId(a.session_id), - Some(SessionStatus::Stopped), - Some(format!( + format!( "Runner {} has been offline for 10 minutes. If it comes back with the agent still running, the session carries on there; a message resumes it on another runner.", r.name - )), - true, + ), ) .await; } @@ -2502,7 +2670,8 @@ impl FleetObject { ) .and_then(|c| c.to_array::()) .unwrap_or_default(); - let online = self.runner_socket(runner_id).is_some(); + self.drop_silent(now_ms()).await; + let online = self.reachable(runner_id); for a in assigned { let session_id = SessionId(a.session_id); if online { @@ -2528,13 +2697,11 @@ impl FleetObject { Some(vec![sv(session_id.as_str())]), ); if !self.queued(session_id.as_str()) { - self.session_control( + self.runner_gone( &session_id, - Some(SessionStatus::Stopped), - Some(format!( + format!( "Stopped: {runner_name} was uninstalled. A message resumes the session on another runner." - )), - true, + ), ) .await; } @@ -2814,12 +2981,18 @@ impl FleetObject { // Two runs of a session never overlap: a resume while the last // run still stops starts once it has. if self.still_stopping(&item.session_id) { - self.note_waiting( - &item, - "Starting again once the last run has stopped".into(), - "stopping", - ) - .await; + // Moved off a runner, which it waits a minute for at most. + let reason = match self + .moved_off(&item.session_id) + .and_then(|id| self.live_rows().into_iter().find(|r| r.id == id)) + { + Some(r) => format!( + "Moving off runner {}: it starts on another once it has stopped there, in a minute at most", + r.name + ), + None => "Starting again once the last run has stopped".into(), + }; + self.note_waiting(&item, reason, "stopping").await; continue; } let want = wants.get(&item.session_id).cloned().unwrap_or_default(); @@ -2836,9 +3009,18 @@ impl FleetObject { self.home_of(&item.session_id) }; let wait = now - (item.enqueued_at as i64) < HOME_WAIT_MS; - // Not on the runners that couldn't start it since it was queued. + // Not on the runners that couldn't start it since it was queued, + // nor on the one people moved it off. let tried = item.tried(); - let picked = self.pick_runner(&want, &labels, home.as_deref(), wait, &tried); + let off = self.moved_off(&item.session_id); + let picked = self.pick_runner( + &want, + &labels, + home.as_deref(), + wait, + &tried, + off.as_deref(), + ); let (runner_id, runner_name) = match picked { Ok(r) => r, // Nor could any other now, busy or not: it fails, saying @@ -2933,10 +3115,12 @@ impl FleetObject { ) { let _ = q.run().await; } - let _ = self.sql.exec( + for sql in [ "DELETE FROM queue WHERE session_id = ?", - Some(vec![sv(&item.session_id)]), - ); + "DELETE FROM moved_off WHERE session_id = ?", + ] { + let _ = self.sql.exec(sql, Some(vec![sv(&item.session_id)])); + } let run_id = spec.run_id.clone().unwrap_or_default(); // With the attempts so far and the runners that couldn't start // it, for a decline to count on, and the runner that has its @@ -3014,7 +3198,7 @@ impl FleetObject { .unwrap_or_default(); self.live_rows() .into_iter() - .filter(|r| r.connected > 0.0 && self.runner_socket(&r.id).is_some()) + .filter(|r| r.online(self)) .filter_map(|r| { let hello: HostHello = serde_json::from_str(r.hello.as_deref()?).ok()?; let n = active @@ -3129,29 +3313,51 @@ impl FleetObject { }) } - /// Where a session's sandbox is, and whether a resume now would start - /// the session on another runner, in a new sandbox without its + /// Where a session's sandbox is (on the runner that runs it, or else + /// the one that last did), and whether a resume now would start the + /// session on another runner, in a new sandbox without its /// conversation: its runner can't take it back (offline, its driver /// not ready, or it no longer runs the session or gives it its size) /// and another runner online, that neither drains nor is low on disk, /// would run it, busy or not. An autopilot's wake starts a fresh /// session instead (`fctl_domain::autopilot::moves`), as it does, - /// without asking that, while the runner drains. + /// without asking that, while the runner drains, and when the runner + /// that runs it has been away a minute. async fn sandbox_at( &self, session_id: &str, ) -> std::result::Result { - let home = self.home_of(session_id); + let now = now_ms(); + self.drop_silent(now).await; + #[derive(Deserialize)] + struct On { + runner_id: String, + } + let on = self + .sql + .exec( + "SELECT runner_id FROM assignments WHERE session_id = ?", + Some(vec![sv(session_id)]), + ) + .and_then(|c| c.to_array::()) + .ok() + .and_then(|r| r.into_iter().next()) + .map(|o| o.runner_id); + let home = on.or_else(|| self.home_of(session_id)); let runner = home .as_deref() .and_then(|id| self.live_rows().into_iter().find(|r| r.id == id)) - .map(|r| internal::SandboxRunner { - online: r.online(self), - draining: r.draining_since.is_some(), - id: r.id, - name: r.name, + .map(|r| { + let online = r.online(self); + internal::SandboxRunner { + online, + away: !online && r.heard_ago(now) >= SILENT_MS, + draining: r.draining_since.is_some(), + id: r.id, + name: r.name, + } }); - if runner.as_ref().is_some_and(|r| r.draining) { + if runner.as_ref().is_some_and(|r| r.draining && !r.away) { return Ok(internal::SandboxAt { runner, elsewhere: false, @@ -3456,7 +3662,8 @@ impl FleetObject { /// pool places sessions (`fctl_domain::schedule::pick`), or why there /// is none. `home`, the runner that has the session's sandbox, comes /// first, and with `wait` the session waits for it while it is busy. - /// The runners that couldn't start it (`tried`) don't take it. + /// The runners that couldn't start it (`tried`) don't take it, nor the + /// one people moved it off (`off`). fn pick_runner( &self, want: &spec::SessionWants, @@ -3464,17 +3671,248 @@ impl FleetObject { home: Option<&str>, wait: bool, tried: &[Tried], + off: Option<&str>, ) -> std::result::Result<(String, String), Wait> { - pick_runner(&untried(self.candidates(), tried), want, labels, home, wait) + let mut candidates = untried(self.candidates(), tried); + candidates.retain(|c| Some(c.id.as_str()) != off); + pick_runner(&candidates, want, labels, home, wait) } - async fn stop(&self, b: Stop) -> std::result::Result { - // Stopped by a person, or deleted: it doesn't carry on when a runner - // that was away comes back with it. + /// The runner people moved the session off, until it starts on another. + fn moved_off(&self, session_id: &str) -> Option { + #[derive(Deserialize)] + struct Off { + runner_id: String, + } + self.sql + .exec( + "SELECT runner_id FROM moved_off WHERE session_id = ?", + Some(vec![sv(session_id)]), + ) + .and_then(|c| c.to_array::()) + .ok()? + .into_iter() + .next() + .map(|o| o.runner_id) + } + + /// Whether FleetDO asked the session's runner to stop it a minute ago or + /// more ([`SILENT_MS`]), and it hasn't: a laptop that wakes now and then + /// for a moment, say, which doesn't get as far. + fn stop_overdue(&self, session_id: &str, now: i64) -> bool { + #[derive(Deserialize)] + struct At { + #[serde(default)] + stopping_at: Option, + } + self.sql + .exec( + "SELECT stopping_at FROM assignments WHERE session_id = ? AND stopping = 1", + Some(vec![sv(session_id)]), + ) + .and_then(|c| c.to_array::()) + .ok() + .and_then(|r| r.into_iter().next()) + .and_then(|a| a.stopping_at) + .is_some_and(|at| now - at as i64 >= SILENT_MS) + } + + /// Lets go of the session's run on `runner_id`, without waiting for its + /// runner: its host stops the sandbox when it gets the word, or when it + /// connects again and finds the session gone or elsewhere. + async fn let_go(&self, session_id: &str, runner_id: &str) { + let _ = self.sql.exec( + "DELETE FROM assignments WHERE session_id = ? AND runner_id = ?", + Some(vec![sv(session_id), sv(runner_id)]), + ); + self.close_uplink(session_id, runner_id).await; + } + + /// Whether a runner online other than `not` would run the session. + async fn another_would_run( + &self, + session_id: &str, + not: &str, + ) -> std::result::Result { + let db = self + .env + .d1("DB") + .map_err(|e| ApiError::internal(e.to_string()))?; + let Some(want) = spec::session_wants(&db, &[session_id], now_ms()) + .await + .map_err(|e| e.0)? + .remove(session_id) + else { + return Ok(false); + }; + self.load_runner_workspaces(&db).await; + Ok(self.candidates().iter().any(|c| { + c.id != not + && fctl_domain::schedule::could_run( + &c.slot(&want), + &want.labels, + want.size, + &want.image, + want.review, + false, + ) + })) + } + + /// Moves a session off the runner it runs on, at people's word: its + /// runner doesn't get it back, and it starts on another that would run + /// it, as a resume does there, with what its snapshot holds, else from + /// its branch. A runner online stops it first, saving its snapshot, for + /// a minute at most; one offline, or whose stop is overdue already, is + /// let go at once. + async fn move_session( + &self, + session_id: &str, + ) -> std::result::Result { + let now = now_ms(); + self.drop_silent(now).await; + #[derive(Deserialize)] + struct On { + runner_id: String, + #[serde(default)] + stopping: Option, + } + let Some(on) = self + .sql + .exec( + "SELECT runner_id, stopping FROM assignments WHERE session_id = ?", + Some(vec![sv(session_id)]), + ) + .and_then(|c| c.to_array::()) + .ok() + .and_then(|r| r.into_iter().next()) + else { + return Err(ApiError::conflict( + "It isn't on a runner now: it starts on one that would run it as it resumes.", + )); + }; + let from = self + .live_rows() + .into_iter() + .find(|r| r.id == on.runner_id) + .map(|r| r.name) + .unwrap_or_default(); + if !self.another_would_run(session_id, &on.runner_id).await? { + return Err(ApiError::conflict(format!( + "No runner online but {from} would run it now: it stays there." + ))); + } + let _ = self.sql.exec( + "INSERT OR REPLACE INTO moved_off (session_id, runner_id, since) VALUES (?, ?, ?)", + Some(vec![sv(session_id), sv(&on.runner_id), iv(now)]), + ); + // Not back to the sandbox there, nor carrying on there if the runner + // comes back with it. let _ = self.sql.exec( "DELETE FROM stopped_away WHERE session_id = ?", - Some(vec![sv(b.session_id.as_str())]), + Some(vec![sv(session_id)]), + ); + let _ = self.sql.exec( + "DELETE FROM sandboxes WHERE session_id = ? AND runner_id = ?", + Some(vec![sv(session_id), sv(&on.runner_id)]), + ); + let _ = self.sql.exec( + "INSERT OR REPLACE INTO queue (session_id, enqueued_at, attempts, not_before) VALUES (?, ?, 0, 0)", + Some(vec![sv(session_id), iv(now)]), ); + let id = SessionId(session_id.to_owned()); + let already = on.stopping.is_some_and(|s| s > 0.0); + let stopping = self.reachable(&on.runner_id) && !self.stop_overdue(session_id, now); + if stopping { + let _ = self.sql.exec( + "UPDATE assignments SET stopping = 1, stopping_at = COALESCE(stopping_at, ?) WHERE session_id = ?", + Some(vec![iv(now), sv(session_id)]), + ); + self.session_control_with( + &id, + ControlState { + status: Some(SessionStatus::Queued), + reason: Some(format!( + "Moving off runner {from}: it starts on another once it has stopped there, in a minute at most" + )), + drop_question: true, + ..Default::default() + }, + ) + .await; + if !already { + self.send_runner( + &on.runner_id, + &FleetToHost::StopSession { + session_id: id.clone(), + reason: StopReason::User, + destroy: false, + }, + ); + } + } else { + self.let_go(session_id, &on.runner_id).await; + self.session_control_with( + &id, + ControlState { + status: Some(SessionStatus::Queued), + reason: Some(format!("Moving off runner {from}")), + clear_runner: true, + drop_question: true, + ..Default::default() + }, + ) + .await; + } + worker::console_log!("moving {session_id} off runner {from}"); + self.dispatch().await; + self.ensure_alarm().await; + Ok(internal::Moved { from, stopping }) + } + + /// Lets go of the sessions people moved off a runner that hasn't + /// stopped them a minute after it was asked to: they start elsewhere. + async fn let_go_of_moves(&self, now: i64) { + #[derive(Deserialize)] + struct Moving { + session_id: String, + runner_id: String, + } + let moving: Vec = self + .sql + .exec( + "SELECT a.session_id, a.runner_id FROM assignments a \ + JOIN moved_off m ON m.session_id = a.session_id AND m.runner_id = a.runner_id \ + WHERE a.stopping = 1 AND a.stopping_at <= ?", + Some(vec![iv(now - SILENT_MS)]), + ) + .and_then(|c| c.to_array::()) + .unwrap_or_default(); + for m in moving { + self.let_go(&m.session_id, &m.runner_id).await; + self.session_control_with( + &SessionId(m.session_id), + ControlState { + clear_runner: true, + ..Default::default() + }, + ) + .await; + } + } + + async fn stop(&self, b: Stop) -> std::result::Result { + // Its runner gone silent is offline, which stops it now. + let now = now_ms(); + self.drop_silent(now).await; + // Stopped by a person, or deleted: it doesn't carry on when a runner + // that was away comes back with it, nor move. + for sql in [ + "DELETE FROM stopped_away WHERE session_id = ?", + "DELETE FROM moved_off WHERE session_id = ?", + ] { + let _ = self.sql.exec(sql, Some(vec![sv(b.session_id.as_str())])); + } let removed_from_queue = self .sql .exec( @@ -3492,11 +3930,14 @@ impl FleetObject { ) .and_then(|c| c.to_array::()) .unwrap_or_default(); + // Asked to stop again a minute after its runner was, which hasn't: + // it doesn't wait for that runner any longer. + let overdue = self.stop_overdue(b.session_id.as_str(), now); match assigned.first() { - Some(a) if self.runner_socket(&a.runner_id).is_some() => { + Some(a) if self.reachable(&a.runner_id) && !overdue => { let _ = self.sql.exec( - "UPDATE assignments SET stopping = 1 WHERE session_id = ?", - Some(vec![sv(b.session_id.as_str())]), + "UPDATE assignments SET stopping = 1, stopping_at = COALESCE(stopping_at, ?) WHERE session_id = ?", + Some(vec![iv(now), sv(b.session_id.as_str())]), ); // Stopping first: from then on the session keeps messages for // its next run instead of handing them to an agent that stops. @@ -3520,17 +3961,27 @@ impl FleetObject { }, ); } - Some(_) => { - // The runner is offline; it stops the sandbox when it reconnects. - let _ = self.sql.exec( - "DELETE FROM assignments WHERE session_id = ?", - Some(vec![sv(b.session_id.as_str())]), - ); + Some(a) => { + // The runner is offline, or hasn't stopped it: its host stops + // the sandbox when it gets to it. + self.let_go(b.session_id.as_str(), &a.runner_id).await; + let reason = if overdue { + let name = self + .live_rows() + .into_iter() + .find(|r| r.id == a.runner_id) + .map_or_else(|| "its runner".to_owned(), |r| format!("runner {}", r.name)); + format!( + "Stopped without waiting for {name}, which hadn't stopped it a minute after it was asked to: its host stops the sandbox when it gets to it." + ) + } else { + "Stopped".to_owned() + }; self.session_control_with( &b.session_id, ControlState { status: Some(SessionStatus::Stopped), - reason: Some("Stopped".into()), + reason: Some(reason), clear_runner: true, drop_question: true, ..Default::default() @@ -3580,6 +4031,22 @@ impl FleetObject { .await; } + /// Stops a session as its runner went away, saying `reason` + /// (`ControlState::runner_gone`). + async fn runner_gone(&self, session_id: &SessionId, reason: String) { + self.session_control_with( + session_id, + ControlState { + status: Some(SessionStatus::Stopped), + reason: Some(reason), + clear_runner: true, + runner_gone: true, + ..Default::default() + }, + ) + .await; + } + /// Tells SessionDO what changed, as `control` takes it, and D1 that the /// session has no runner when it says so. async fn session_control_with(&self, session_id: &SessionId, control: ControlState) { diff --git a/crates/fctl-control/src/do_session.rs b/crates/fctl-control/src/do_session.rs index 4cd811bf..3ff9a8e9 100644 --- a/crates/fctl-control/src/do_session.rs +++ b/crates/fctl-control/src/do_session.rs @@ -1184,11 +1184,38 @@ impl SessionObject { if message { self.wake(now).await?; } + // A person's message to an autopilot's own session whose runner + // has been away a minute: its autopilot carries on elsewhere rather + // than wait for it. Not fctl's wakes, which the autopilot's wake + // sent here as the fleet saw its runner. + if let DeliveryKind::Message { + author: Some(_), .. + } = &b.delivery.kind + && !by_autopilot + && let Some(s) = self + .summary() + .filter(|s| fctl_domain::autopilot::on_runner(s.status)) + && self.runner_away_since(now).is_some() + { + self.pilot_elsewhere(&s, now); + } Ok(Delivered { delivery_id: b.delivery.id, }) } + /// Since when its runner hasn't been heard from, once that is + /// [`QUIET_MS`] or more, as its viewers see it (`runner_view`): its + /// uplink went quiet, or closed. Its uplink is marked quiet first, as a + /// viewer's ping would: a message from the CLI or the API may come + /// while no page is open to have done it. + fn runner_away_since(&self, now: i64) -> Option { + self.check_quiet(now); + let view = self.runner_view(None); + view.last_seen_at + .filter(|at| !view.connected && now - at >= QUIET_MS) + } + /// The delivery an idempotency key went with, when it came before. fn keyed(&self, key: &str) -> Option { #[derive(Deserialize)] @@ -2300,6 +2327,15 @@ impl SessionObject { return Err(api_err(ErrorCode::NotFound, "Session not initialized")); }; let now = now_ms(); + // Its runner has been away a minute: nothing about it changes, but + // a message its agent didn't take goes on elsewhere, should it be + // an autopilot's own session's. + if b.runner_away { + if fctl_domain::autopilot::on_runner(s.status) && self.messages_waiting() { + self.pilot_elsewhere(&s, now); + } + return Ok(serde_json::json!({ "ok": true })); + } let before = s.status; let mut described = false; if let Some(t) = b.title { @@ -2378,9 +2414,66 @@ impl SessionObject { } self.notify_fleet(&s); self.notify_followers(&s, before, now); + if b.runner_gone && status_changed && s.status == SessionStatus::Stopped { + self.runner_went(&s, before, now).await; + } Ok(serde_json::json!({ "ok": true })) } + /// The fleet stopped the session as its runner went away + /// (`ControlState::runner_gone`), from `before`: what waited for its + /// agent goes on elsewhere. An autopilot's own session cut off in the + /// middle of its turn, or before it took up a message, wakes its + /// autopilot, which carries on in a fresh session; another one resumes + /// on another runner for the messages that wait. + async fn runner_went(&self, s: &Session, before: SessionStatus, now: i64) { + let waiting = self.messages_waiting(); + match &s.autopilot { + Some(a) if a.role == fctl_proto::autopilot::AutopilotRole::Pilot => { + // In the middle of its turn, or with a message it didn't take. + if (fctl_domain::autopilot::on_runner(before) && before != SessionStatus::Idle) + || waiting + { + self.pilot_elsewhere(s, now); + } + } + _ if waiting => { + if let Err(e) = self.wake(now).await { + worker::console_error!( + "resuming for a waiting message after its runner went: {}", + e.message + ); + } + } + _ => {} + } + } + + /// Wakes the autopilot whose own session this is, while it still is, + /// as its runner went away with what its agent was doing or was sent: + /// it carries on in a fresh session on a runner that can be reached + /// (`crate::autopilots::own_cut_off`), rather than wait for this one. + fn pilot_elsewhere(&self, s: &Session, now: i64) { + let Some(a) = s + .autopilot + .as_ref() + .filter(|a| a.role == fctl_proto::autopilot::AutopilotRole::Pilot) + else { + return; + }; + let env = self.env.clone(); + let autopilot = a.project_id.as_str().to_owned(); + let id = s.id.0.clone(); + self.state.wait_until(async move { + if let Err(e) = crate::autopilots::own_cut_off(&env, &autopilot, &id, now).await { + worker::console_error!( + "waking autopilot {autopilot} as its session's runner went away: {}", + e.0.message + ); + } + }); + } + /// Keeps how short of disk the session's runner is, for its pages /// (`runner_disk`). fn runner_disk(&self, news: internal::DiskNews) { diff --git a/crates/fctl-control/src/internal.rs b/crates/fctl-control/src/internal.rs index b98f54b1..392c1f08 100644 --- a/crates/fctl-control/src/internal.rs +++ b/crates/fctl-control/src/internal.rs @@ -102,6 +102,17 @@ pub struct ControlState { /// autopilot's wakes take its sessions that changed for news. #[serde(default)] pub keep_updated_at: bool, + /// FleetObject stopped the session as its runner went away (offline + /// for ten minutes, removed or uninstalled), not because anyone asked: + /// a message that waits for its agent resumes it on another runner, + /// and an autopilot's own one cut off wakes its autopilot. + #[serde(default)] + pub runner_gone: bool, + /// The session's runner has been away a minute, its sockets closed or + /// silent, and FleetObject tells it once: an autopilot's own session + /// with a message its agent didn't take wakes its autopilot. + #[serde(default)] + pub runner_away: bool, } /// The question a session's agent asks people now (`/ask`, from `fctl ask` @@ -325,6 +336,22 @@ pub struct PoolChanged { pub token_id: String, } +/// Asks FleetDO to move a session off the runner it runs on, to another +/// that would run it (`POST /move`): it answers [`Moved`]. +#[derive(Serialize, Deserialize)] +pub struct Move { + pub session_id: String, +} + +/// A session FleetDO moves off a runner: the runner's name, and whether +/// its host was asked to stop it first, which the session waits a minute +/// for at most. +#[derive(Serialize, Deserialize, Default)] +pub struct Moved { + pub from: String, + pub stopping: bool, +} + /// Asks FleetDO where a session's sandbox is, and whether a resume now /// would leave it (`POST /sandbox`). #[derive(Serialize, Deserialize)] @@ -343,7 +370,7 @@ pub struct SandboxAt { /// sandbox without its conversation: its runner can't take it back /// (offline, its driver not ready, or it no longer runs the session) /// and another runner online would run it. Unasked while its runner - /// drains. + /// drains, unless it went away too. #[serde(default)] pub elsewhere: bool, } @@ -354,6 +381,10 @@ pub struct SandboxRunner { pub id: String, pub name: String, pub online: bool, + /// It is offline, and was last heard from a minute ago or more: no + /// host that restarts, but one that went away, or silent. + #[serde(default)] + pub away: bool, pub draining: bool, } diff --git a/crates/fctl-control/src/lib.rs b/crates/fctl-control/src/lib.rs index fd08dbd5..9a3e9179 100644 --- a/crates/fctl-control/src/lib.rs +++ b/crates/fctl-control/src/lib.rs @@ -678,6 +678,7 @@ async fn dispatch_rest( api::sessions::pass_on(ctx, id, review).await } (Post, ["sessions", id, "stop"]) => api::sessions::stop(ctx, id).await, + (Post, ["sessions", id, "move"]) => api::sessions::move_off(ctx, id).await, (Post, ["sessions", id, "resume"]) => api::sessions::resume(ctx, req, id).await, (Post, ["sessions", id, "take-over"]) => api::sessions::take_over(ctx, id).await, (Get, ["sessions", id, "events"]) => api::sessions::events(ctx, req, id).await, diff --git a/crates/fctl-control/src/model.rs b/crates/fctl-control/src/model.rs index 15d26fb5..c16a1755 100644 --- a/crates/fctl-control/src/model.rs +++ b/crates/fctl-control/src/model.rs @@ -609,8 +609,10 @@ impl ProjectRow { number: u32::try_from(number).unwrap_or(0), status, started_at, - // The sidebar's summary doesn't show it. + // The sidebar's summary doesn't show them. context_tokens: None, + runner: None, + runner_away_since: None, }) } _ => None, diff --git a/crates/fctl-domain/src/autopilot.rs b/crates/fctl-domain/src/autopilot.rs index e6563063..8cd364f6 100644 --- a/crates/fctl-domain/src/autopilot.rs +++ b/crates/fctl-domain/src/autopilot.rs @@ -728,6 +728,46 @@ pub struct Sandbox<'a> { /// (it is offline, its driver isn't ready, or it no longer runs the /// session) and another runner online would run it. pub elsewhere: bool, + /// That runner is offline, and was last heard from a minute ago or + /// more: a laptop gone to sleep, a machine that went away, rather than + /// a host that restarts. What runs there doesn't go on until it's back. + pub away: bool, +} + +/// How long fctl may hear nothing from a runner, four of its heartbeats, +/// before it counts it offline, whatever its connection says: a laptop +/// gone to sleep can leave that open for a long time. +pub const RUNNER_SILENT_MS: i64 = 60_000; + +/// When a runner last heard from at `seen` went away, as of `now`: `seen`, +/// once that was [`RUNNER_SILENT_MS`] ago or more. +pub fn away_since(seen: Option, now: i64) -> Option { + seen.filter(|&t| now - t >= RUNNER_SILENT_MS) +} + +/// Whether its own session is stranded on a runner that went away +/// ([`Sandbox::away`]) while another runner online would run it: its +/// sandbox is there, at work, waiting for a message or for a usage limit +/// to reset, or about to start, and nothing a wake says reaches it until +/// that runner comes back, which it may never do. A wake moves it then +/// ([`moves`]), at work or not: a fresh session takes over on a runner +/// that can be reached, rather than wait for this one. +pub fn stranded(status: SessionStatus, sandbox: Sandbox<'_>) -> bool { + on_runner(status) && sandbox.away && sandbox.elsewhere +} + +/// Whether a session in `status` runs on a runner, about to start there, +/// at work, waiting for a message or for a usage limit to reset: what it +/// does goes on only while that runner is there. +pub fn on_runner(status: SessionStatus) -> bool { + matches!( + status, + SessionStatus::Provisioning + | SessionStatus::Preparing + | SessionStatus::Running + | SessionStatus::Idle + | SessionStatus::Paused + ) } /// Whether its own session rests between turns in its sandbox: it waits @@ -742,17 +782,21 @@ pub fn between_turns(status: SessionStatus) -> bool { /// Whether a wake that would carry on in its own session as it is /// ([`fresh`] said so) goes to a fresh session instead, for where that -/// session's sandbox is. Only one between its turns ([`between_turns`]) -/// moves: off a runner that drains ([`Fresh::Drains`]), so that the -/// runner empties, as the session there stops; and out of a sandbox its -/// runner can't take it back to, when another runner would resume it -/// without its conversation ([`Fresh::Away`]), as a fresh session starts -/// from its briefing, plan and log instead. One waiting for a message is -/// still up in its sandbox and takes the wake there, unless its runner -/// drains. One at work, or paused on a usage limit, stays where it is: its -/// runner may come back with it, and should it not, fctl stops it ten -/// minutes later, and the next wake moves. +/// session's sandbox is. One [`stranded`] on a runner that went away +/// moves, whatever it does there ([`Fresh::Away`]). Otherwise only one +/// between its turns ([`between_turns`]) moves: off a runner that drains +/// ([`Fresh::Drains`]), so that the runner empties, as the session there +/// stops; and out of a sandbox its runner can't take it back to, when +/// another runner would resume it without its conversation +/// ([`Fresh::Away`]), as a fresh session starts from its briefing, plan +/// and log instead. One waiting for a message is still up in its sandbox +/// and takes the wake there, unless its runner drains or went away. One +/// at work, or paused on a usage limit, stays where it is while its runner +/// is there, or gone for less than a minute, as a host that restarts is. pub fn moves(status: SessionStatus, sandbox: Sandbox<'_>) -> Option { + if stranded(status, sandbox) { + return Some(Fresh::Away); + } if !between_turns(status) { return None; } @@ -798,9 +842,16 @@ pub fn wakes_in_own( /// reach it now: people asked for a fresh session to take over from it /// (`reasons` has [`AutopilotWakeReason::Fresh`]) while it works. All it /// woke for then goes to the fresh session, which the turn's end wakes at -/// once, rather than to the one about to leave. -pub fn holds(reasons: &[AutopilotWakeReason], status: Option) -> bool { - reasons.contains(&AutopilotWakeReason::Fresh) && status.is_some_and(at_work) +/// once, rather than to the one about to leave. Not while it is +/// [`stranded`] where its sandbox is: that turn may never end, and the +/// fresh session takes over now. +pub fn holds( + reasons: &[AutopilotWakeReason], + status: Option, + sandbox: Sandbox<'_>, +) -> bool { + reasons.contains(&AutopilotWakeReason::Fresh) + && status.is_some_and(|st| at_work(st) && !stranded(st, sandbox)) } /// How near its own session is to handing off, for the wake message that @@ -853,7 +904,7 @@ pub fn takes_over_from(why: Fresh, from: &str, handoff_at: Option) -> Optio "You take over from your last session, {from}: the runner that kept its sandbox drains, to be emptied for maintenance or shut down, so fctl stopped it there and started you rather than wake it there again." ), Fresh::Away => format!( - "You take over from your last session, {from}: the runner that kept its sandbox can't take it back (it is offline or gone, or can't run it now), so fctl started you rather than resume it on another runner without its conversation. Its runner may have gone in the middle of its work: `fctl logs {from} --last-turn` shows what it was doing." + "You take over from your last session, {from}: the runner that kept its sandbox can't take it back (it is offline or gone, or can't run it now), so fctl started you rather than resume it on another runner without its conversation. Its runner may have gone in the middle of its work, or before it took up a message people sent it: `fctl logs {from} --last-turn` shows which." ), }; Some(format!( @@ -3024,6 +3075,9 @@ pub fn wake_message(news: &News<'_>) -> String { "the checks on the base branch ended after your sessions' pull requests merged" } AutopilotWakeReason::Others => "people's sessions you manage moved on", + AutopilotWakeReason::Away => { + "your last session's runner went away before it finished its turn" + } AutopilotWakeReason::Other => "something needs you", }) .collect(); @@ -3100,6 +3154,18 @@ pub fn wake_message(news: &News<'_>) -> String { mod tests { use super::*; + #[test] + fn a_runner_is_away_once_unheard_for_a_minute() { + let now = 10 * 60_000; + assert_eq!(away_since(None, now), None); + assert_eq!(away_since(Some(now - 59_999), now), None); + assert_eq!(away_since(Some(now - 60_000), now), Some(now - 60_000)); + assert_eq!( + away_since(Some(now - 11 * 60_000), now), + Some(now - 11 * 60_000) + ); + } + #[test] fn changes_by_others_take_it_over_unless_its_owner_keeps_it() { let by_other = Change { @@ -3727,7 +3793,8 @@ mod tests { }; assert_eq!(moves(SessionStatus::Stopped, only_one), None); // Waiting for a message, it is still up in its sandbox, which - // takes the wake should its runner come back. + // takes the wake should its runner come back within the minute a + // host takes to restart. assert_eq!(moves(SessionStatus::Idle, offline), None); // At work, paused mid-turn or failed, it stays where it is. for status in [ @@ -3744,6 +3811,80 @@ mod tests { } } + #[test] + fn a_wake_moves_off_a_runner_that_went_away_whatever_its_session_does() { + // Not heard from for a minute or more, a laptop asleep, say, while + // another runner would run it. + let away = Sandbox { + runner: Some("laptop"), + online: false, + elsewhere: true, + away: true, + ..Sandbox::default() + }; + for status in [ + SessionStatus::Provisioning, + SessionStatus::Preparing, + SessionStatus::Running, + SessionStatus::Idle, + SessionStatus::Paused, + ] { + assert!(stranded(status, away), "{status:?}"); + assert_eq!(moves(status, away), Some(Fresh::Away), "{status:?}"); + } + // Stopping or stopped, it moved already; queued, it starts on + // another runner by itself; failed, `fresh` says so. + for status in [SessionStatus::Stopping, SessionStatus::Stopped] { + assert!(!stranded(status, away), "{status:?}"); + assert_eq!(moves(status, away), Some(Fresh::Away), "{status:?}"); + } + for status in [SessionStatus::Queued, SessionStatus::Failed] { + assert!(!stranded(status, away), "{status:?}"); + assert_eq!(moves(status, away), None, "{status:?}"); + } + // No other runner would run it: it waits for that one. + let only_one = Sandbox { + elsewhere: false, + ..away + }; + assert!(!stranded(SessionStatus::Running, only_one)); + assert_eq!(moves(SessionStatus::Idle, only_one), None); + // Offline for seconds, as a host that restarts is: it stays. + let restarting = Sandbox { + away: false, + ..away + }; + assert!(!stranded(SessionStatus::Running, restarting)); + assert_eq!(moves(SessionStatus::Running, restarting), None); + } + + #[test] + fn a_fresh_session_people_ask_for_waits_for_a_turn_only_where_it_can_end() { + let fresh = [AutopilotWakeReason::Fresh]; + let here = Sandbox { + runner: Some("studio-mac"), + online: true, + ..Sandbox::default() + }; + let away = Sandbox { + online: false, + elsewhere: true, + away: true, + ..here + }; + assert!(holds(&fresh, Some(SessionStatus::Running), here)); + assert!(!holds(&fresh, Some(SessionStatus::Running), away)); + assert!(!holds(&fresh, Some(SessionStatus::Idle), here)); + assert!(!holds( + &[AutopilotWakeReason::CheckIn], + Some(SessionStatus::Running), + here + )); + // Still stopping where it can't: the stop finishes it within a + // minute of its runner going away, which wakes it then. + assert!(holds(&fresh, Some(SessionStatus::Stopping), away)); + } + #[test] fn a_wake_in_a_fresh_session_says_why_in_the_log() { let kept = Sandbox { @@ -3849,13 +3990,15 @@ mod tests { // At work, the wake waits for its turn's end, all it woke for with it. assert_eq!(fresh(own(SessionStatus::Running), None, true, now), None); let asked = [AutopilotWakeReason::Crew, AutopilotWakeReason::Fresh]; - assert!(holds(&asked, Some(SessionStatus::Running))); - assert!(holds(&asked, Some(SessionStatus::Queued))); - assert!(!holds(&asked, Some(SessionStatus::Idle))); - assert!(!holds(&asked, None)); + let here = Sandbox::default(); + assert!(holds(&asked, Some(SessionStatus::Running), here)); + assert!(holds(&asked, Some(SessionStatus::Queued), here)); + assert!(!holds(&asked, Some(SessionStatus::Idle), here)); + assert!(!holds(&asked, None, here)); assert!(!holds( &[AutopilotWakeReason::Crew], - Some(SessionStatus::Running) + Some(SessionStatus::Running), + here )); } @@ -3957,7 +4100,7 @@ mod tests { ))); let away = takes_over_from(Fresh::Away, "shop#12", None); assert!(away.as_deref().is_some_and(|t| t.starts_with( - "You take over from your last session, shop#12: the runner that kept its sandbox can't take it back (it is offline or gone, or can't run it now), so fctl started you rather than resume it on another runner without its conversation. Its runner may have gone in the middle of its work: `fctl logs shop#12 --last-turn` shows what it was doing. Go on from your plan" + "You take over from your last session, shop#12: the runner that kept its sandbox can't take it back (it is offline or gone, or can't run it now), so fctl started you rather than resume it on another runner without its conversation. Its runner may have gone in the middle of its work, or before it took up a message people sent it: `fctl logs shop#12 --last-turn` shows which. Go on from your plan" ))); for t in [drains, away] { assert!(t.is_some_and(|t| t.contains( diff --git a/crates/fctl-proto/src/autopilot.rs b/crates/fctl-proto/src/autopilot.rs index 46e2e925..fd60bf5c 100644 --- a/crates/fctl-proto/src/autopilot.rs +++ b/crates/fctl-proto/src/autopilot.rs @@ -19,7 +19,7 @@ use crate::Millis; use crate::ids::{ProjectId, SessionId}; -use crate::session::{SessionRef, SessionSchedule, SessionStatus, UserRef}; +use crate::session::{RunnerRef, SessionRef, SessionSchedule, SessionStatus, UserRef}; use serde::{Deserialize, Serialize}; use serde_with::skip_serializing_none; @@ -252,7 +252,8 @@ pub struct Autopilot { pub handoff_at: Option, /// Someone asked for a fresh session to take over from its own /// (`WakeAutopilotRequest.fresh`), and none has yet: it does as fctl - /// next wakes it, once that one's turn ends while it works. Control + /// next wakes it, once that one's turn ends while it works, unless its + /// runner went away (`AutopilotSession.runner_away_since`). Control /// planes before it leave it out. #[serde(default)] pub fresh_asked: bool, @@ -324,6 +325,16 @@ pub struct AutopilotSession { /// hands off at `Autopilot.handoff_at`. Absent until it has, and from /// control planes before it. pub context_tokens: Option, + /// The runner it runs on, while it has one. Control planes before it + /// leave it out. + pub runner: Option, + /// When its runner was last heard from, once that was a minute ago or + /// more while it runs there: a laptop asleep, a machine gone. fctl + /// doesn't wait for it: as something next wakes the autopilot, or + /// people ask for a fresh session, a fresh one takes over on another + /// runner, where one online would run it. Absent while its runner is + /// heard from, and from control planes before it. + pub runner_away_since: Option, } /// Why fctl wakes an autopilot. @@ -354,7 +365,8 @@ pub enum AutopilotWakeReason { Moved, /// Someone asked for a fresh session of its own to take over from the /// one it works in (`fctl autopilot wake --fresh`): the wake starts - /// one, once that one's turn ends. + /// one, once that one's turn ends, or at once while its runner is + /// away. Fresh, /// The checks of a commit on the base branch that holds a pull request /// of its sessions' that merged all ended, passed or not. @@ -363,6 +375,10 @@ pub enum AutopilotWakeReason { /// ([`AutopilotPower::Others`]) finished a turn, asks something or /// failed. Others, + /// Its own session's runner went away in the middle of its turn, or + /// before it took up a message, and fctl stopped that session: it + /// carries on in a fresh one, on a runner that can be reached. + Away, /// A reason a newer control plane gives. #[serde(other)] Other, @@ -384,6 +400,7 @@ impl AutopilotWakeReason { Self::Fresh => "fresh", Self::MergeChecks => "merge_checks", Self::Others => "others", + Self::Away => "away", Self::Other => "other", } } @@ -403,6 +420,7 @@ impl AutopilotWakeReason { Self::Fresh, Self::MergeChecks, Self::Others, + Self::Away, ] .into_iter() .find(|r| r.as_str() == s) @@ -910,7 +928,8 @@ pub struct PauseAutopilotRequest { /// `POST …/autopilot/wake`: a person wakes it now, with `fresh` in a /// fresh session of its own, which takes over from the one it works in -/// (once that one's turn ends, while it works); the autopilot says when it +/// (once that one's turn ends, while it works, unless its runner went +/// away); the autopilot says when it /// wakes next, unless something wakes it sooner: in `in_minutes` (5 to /// 1,440), or at `at`. #[skip_serializing_none] diff --git a/crates/fctl/src/cmd/autopilot.rs b/crates/fctl/src/cmd/autopilot.rs index 70893dcc..6f976331 100644 --- a/crates/fctl/src/cmd/autopilot.rs +++ b/crates/fctl/src/cmd/autopilot.rs @@ -141,8 +141,9 @@ pub enum AutopilotCmd { after: Option, /// In a fresh session of its own, which takes over from the one it /// works in, starting from its plan and log, and stops that one: at - /// once between its turns, else once its turn ends. Its briefing - /// and sandbox are fctl's as they are now. + /// once between its turns, or while that one's runner has gone + /// away, else once its turn ends. Its briefing and sandbox are + /// fctl's as they are now. #[arg(long)] fresh: bool, }, @@ -489,20 +490,26 @@ pub async fn run(server: Option<&str>, args: AutopilotArgs, json: bool) -> Resul "The control plane is older than --fresh: it woke the autopilot in the session it works in, and no fresh session takes over" ); } - // Its session at work finishes its turn first. - let working = serde_json::from_value::(answer) - .ok() - .and_then(|a| { - let s = a.session?; - fctl_domain::autopilot::at_work(s.status) - .then(|| format!("{}#{}", a.project_slug, s.number)) - }); - match working { - Some(s) => println!( - "{} A fresh session takes over from {s} once its turn ends", - style::accent("✓") - ), - None => println!("{} A fresh session takes over now", style::accent("✓")), + let a = serde_json::from_value::(answer).ok(); + let s = a.as_ref().and_then(|a| { + let s = a.session.as_ref()?; + Some((format!("{}#{}", a.project_slug, s.number), s)) + }); + let ok = style::accent("✓"); + match s { + // It doesn't wait for a runner that went away. + Some((name, s)) if let Some(since) = s.runner_away_since => { + let runner = s.runner.as_ref().map_or("its runner", |r| r.name.as_str()); + println!( + "{ok} A fresh session takes over from {name} on another runner, as soon as one online would run it: {runner} was last heard from {}", + style::ago(since) + ); + } + // Its session at work finishes its turn first. + Some((name, s)) if fctl_domain::autopilot::at_work(s.status) => { + println!("{ok} A fresh session takes over from {name} once its turn ends"); + } + _ => println!("{ok} A fresh session takes over now"), } return Ok(()); } @@ -1209,6 +1216,27 @@ fn block(text: &str) -> String { fn state_line(a: &Autopilot) -> String { match a.state { + // Its session's runner went away: fctl doesn't wait for it. + AutopilotState::On + if let Some(s) = a.session.as_ref() + && let Some(since) = s.runner_away_since => + { + let runner = s + .runner + .as_ref() + .map_or_else(|| "its runner".to_owned(), |r| format!("runner {}", r.name)); + let next = if a.fresh_asked { + "a fresh session takes over on another runner as soon as one online would run it" + } else { + "as something next wakes it, a fresh session takes over on another runner, where one online would run it" + }; + style::blue(&format!( + "○ Runner away · {}#{} is on {runner}, last heard from {}: {next}", + a.project_slug, + s.number, + style::ago(since) + )) + } AutopilotState::On => { let at_work = a.session.as_ref().is_some_and(|s| { matches!( diff --git a/crates/fctl/src/cmd/sessions.rs b/crates/fctl/src/cmd/sessions.rs index b6f2c357..0adc137a 100644 --- a/crates/fctl/src/cmd/sessions.rs +++ b/crates/fctl/src/cmd/sessions.rs @@ -1535,6 +1535,26 @@ pub async fn stop(server: Option<&str>, reference: &str, json: bool) -> Result<( Ok(()) } +pub async fn move_off(server: Option<&str>, reference: &str, json: bool) -> Result<()> { + let api = config::api(server)?; + let s = resolve(&api, reference).await?; + let from = s + .runner + .as_ref() + .map_or_else(|| "its runner".to_owned(), |r| format!("runner {}", r.name)); + let s = api.move_off(&s.id.0).await?; + if json { + return style::print_json(&s); + } + println!( + "{} Moving {}#{} off {from}, to another runner", + style::accent("✓"), + s.project_slug, + s.number + ); + Ok(()) +} + pub async fn resume( server: Option<&str>, reference: &str, diff --git a/crates/fctl/src/main.rs b/crates/fctl/src/main.rs index 87ad13e3..dbd70a5e 100644 --- a/crates/fctl/src/main.rs +++ b/crates/fctl/src/main.rs @@ -369,6 +369,20 @@ Examples: /// A session: its id (ses_…), its URL, or project#number. session: String, }, + /// Move a session off its runner, to another that would run it: for a + /// runner that went quiet, or sleeps but for a moment now and then. + #[command( + name = "move", + after_help = "It doesn't wait for that runner: one online stops the session first, for a minute at most. +It carries on as a resume on another runner does: from its snapshot, if it has one, else from its branch with a new conversation. + +Examples: + fctl move my-app#12" + )] + Move { + /// A session: its id (ses_…), its URL, or project#number. + session: String, + }, /// Resume a stopped or failed session on your Claude subscription, /// optionally with a new message. Resume { @@ -648,6 +662,7 @@ async fn run(cli: Cli) -> anyhow::Result<()> { } Command::Interrupt { session } => cmd::sessions::interrupt(server, &session).await, Command::Stop { session } => cmd::sessions::stop(server, &session, json).await, + Command::Move { session } => cmd::sessions::move_off(server, &session, json).await, Command::Resume { session, message, diff --git a/docs/adr/0108-sessions-dont-wait-for-a-runner-that-went-silent.md b/docs/adr/0108-sessions-dont-wait-for-a-runner-that-went-silent.md new file mode 100644 index 00000000..7cc51111 --- /dev/null +++ b/docs/adr/0108-sessions-dont-wait-for-a-runner-that-went-silent.md @@ -0,0 +1,82 @@ +# 0108: Sessions don't wait for a runner that went silent + +2026-12-03 · accepted + +## Context + +A runner on a laptop that went to sleep kept its control connection open: +nothing closed it, and nothing came through it. FleetDO counted a runner +online for as long as its socket was open, so for that laptop it did for +as long as anyone watched. The runners list said "online" 11 minutes +after its last heartbeat. Dispatch passed it over only because it never +answered. And the ten minutes after which a runner that went away loses +its sessions never began counting. SessionDO already counted an uplink +that went quiet for a minute as away, for the session page, but FleetDO, +which decides, didn't. + +An autopilot's own session was on that laptop. A follow-up woke the +autopilot, and the wake went to that session, as it rested between its +turns, and stayed in its outbox. *Stop* sent the host a stop it never got, +and the session stayed "Stopping". *Hand off to a fresh session* waited for +the session's turn to end, which it never did. Carl Oscar asked that the +autopilot carry on, seamlessly, on a runner that can be reached. + +## Decision + +- **A runner silent for a minute is offline.** Once FleetDO has heard + nothing from a runner for a minute (four 15-second heartbeats, as + SessionDO's uplinks), it counts the runner offline as of when it last + heard from it, as if its connection had closed then, and closes the + connection. A host that comes back says hello on a new one, and its + sessions are reconciled with what was decided meanwhile. Runners' + heartbeats notice each other's silence, and the alarm ticks while any + session is assigned, for a runner that goes silent alone. +- **A stop doesn't wait for a runner that is offline.** A session someone + stops then stops at once, as it did when the socket had closed. One + whose stop was on its way as the runner went stops once the runner has + been offline a minute, rather than ten. Its host stops the sandbox if + it comes back. +- **An autopilot's own session doesn't wait either.** Once its runner has + been offline a minute, and another runner online would run it, a wake + moves it, whatever it was doing, waiting for a message or mid-turn + (`fctl_domain::autopilot::stranded`). fctl stops it and starts a fresh + session on another runner, as it does off a runner that drains. A hand-off + people ask for doesn't wait for its turn to end. A wake that reached the + session in the minute before FleetDO knew, or a person's message to it + after, wakes the autopilot again, with the new wake reason `away`. A + turn cut off, which nothing else would wake it for, wakes it once the + ten minutes have stopped the session. +- **Other sessions keep the ten minutes**, as their conversation is in the + sandbox on that runner, which may come back. Messages sent to them + meanwhile now resume them on another runner once the ten minutes are + up, rather than wait for one more message. +- **People can move a session off its runner** (`fctl move`, *Move to + another runner*). A laptop with its lid closed wakes for a moment now + and then, says hello and sleeps again: it is online for those moments, + which keeps its sessions from stopping, but gets no further with them, + and a stop sent to it isn't carried out. The move doesn't wait for it: + FleetDO keeps the session off that runner until it has started on + another, asks a runner online to stop it first, for a minute at most, + so that its agent saves a snapshot, and lets one offline go at once. + A second stop, a minute after a first that wasn't carried out, lets go + of the runner too, rather than leave the session "Stopping". + +## Consequences + +- A laptop that sleeps shows as offline within a minute, and its + sessions stop ten minutes after its last heartbeat, as they did for a + runner whose connection closed. +- An autopilot whose runner went away carries on elsewhere within about a + minute of something waking it. It starts from its plan, log and files, + without the conversation of the session it leaves, which `fctl logs` + still shows. +- A host stalled for a minute (a frozen process, a network that drops + everything for a minute) is offline for that while. It reconnects as + soon as it can, and its sessions carry on there, but an autopilot woken + meanwhile has moved on, and stops the one it left once the host is back. +- FleetDO's alarm ticks every 30 seconds while any session runs, rather + than only while one waits or a runner is offline. +- A session moved off a runner whose agent saved no snapshot of its last + run starts again from its branch with a new conversation, as one does + after ten minutes away: what it hadn't pushed stays on that runner, + whose host removes it with its other stopped sandboxes. diff --git a/docs/api.md b/docs/api.md index d4ddcc9c..c4ea0acd 100644 --- a/docs/api.md +++ b/docs/api.md @@ -142,7 +142,8 @@ It answers with the session, `queued`. A session is: | `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 | +| `POST /api/v1/sessions/{id}/stop` | | ends the session; its sandbox stays for a resume. Asked again a minute after its runner was, which hasn't stopped it, it ends without waiting for that runner | +| `POST /api/v1/sessions/{id}/move` | | moves the session off the runner it runs on, which doesn't get it back, to another that would run it: a runner online stops it first, for a minute at most, and one offline is let go at once; it carries on there as a resume on another runner does, from its snapshot where that holds its last run, else from its branch with a new conversation. For its owner; `409` for one that isn't on a runner (queued, stopped or failed: a resume starts it on any runner), a review agent's, and while no other runner online would run it | | `POST /api/v1/sessions/{id}/resume` | `{"prompt": "…", "attachments": [...]}` | starts a stopped or failed session again, on the caller's subscription; `409` while it runs | | `POST /api/v1/sessions/{id}/take-over` | | moves the session to the caller's Claude connection for its workspace (who may message it): one that waits for its subscription's limit to reset, or for a message, stops its run and starts again there, where Claude continues the same conversation; a stopped one resumes on it. `409` while its agent works, for a failed one (resume it), an autopilot's own session (take the autopilot over), a review agent's, one that runs on that connection already, and while the caller's plan is at its limit too | | `PATCH /api/v1/sessions/{id}` | `{"title": "…", "description": "…", "archived": true, "model": "sonnet", "effort": "medium"}` | renames, describes or archives it (`""` clears the description); `model` (an alias or a model's ID) and `effort` (`low` … `max`) change what its agent works on from its next step, and what its next run starts on: a new model reads the whole conversation again without Claude's prompt cache, a new effort level keeps it where Claude sends the level with each turn ([Model and effort](architecture.md#model-and-effort)). For its owner; `409` for a review agent's session, and while it runs on a runner whose fctl can't change them | @@ -374,7 +375,7 @@ session calls the endpoints marked *autopilot*, through its sandbox's | `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 | -| `POST …/autopilot/wake` | wakes it now; `{"fresh": true}`, in a fresh session of its own that takes over from the one it works in, at once between its turns, else once its turn ends (`fresh_asked` meanwhile); *autopilot*: `{"in_minutes": 30}` or `{"at": …}`, when it wakes next unless something needs it sooner | +| `POST …/autopilot/wake` | wakes it now; `{"fresh": true}`, in a fresh session of its own that takes over from the one it works in, at once between its turns or while its runner has been away a minute (`session.runner_away_since`), else once its turn ends (`fresh_asked` meanwhile); *autopilot*: `{"in_minutes": 30}` or `{"at": …}`, when it wakes next unless something needs it sooner | | `POST …/autopilot/notes`, `DELETE …/autopilot/notes/{note}` | `{"text"}` (Markdown, at most 2,000 characters): steers it, at once | | `POST …/autopilot/asks/{ask}/answer` | `{"answer", "attachments"}`, or `{"secret"}` for a secret it asked for, which goes into the project's secrets. `attachments`, uploaded to the session a question is about (`about`), go to it in a message from the caller with the answer as its text; for a question about none, uploaded to its session that asked (`session`), which keeps them without a message, and the autopilot hears with the answer how to download them; the answer may then be empty. A question whose session is gone takes no files (`about_gone` once the one it asked about is) | | `POST …/autopilot/asks/{ask}/decline` | `{"reason"}` | diff --git a/docs/architecture.md b/docs/architecture.md index 853a6b59..43797e7b 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1753,13 +1753,30 @@ other runner from it A host that stops answering (a laptop gone to sleep, a host that hangs or crashed, a network that dropped) leaves its agents at work in their sandboxes, journaling what they do, and the session page says since when -the runner hasn't been heard from ([Viewers](#viewers)). Once its control -connection has been closed for ten minutes, FleetDO marks its sessions -stopped, so that a message resumes them on another runner, and remembers -which ones it stopped this way (`stopped_away`, in its storage). Their -sandboxes saved no snapshot as the runner went, so a resume on another -runner restores none of the run that was cut off: one saved before it is -older than the run, and isn't used ([Session snapshots](#session-snapshots)). +the runner hasn't been heard from ([Viewers](#viewers)). Its control +connection may close, or stay open for a long time with nothing coming +through it, as a sleeping laptop's does: once FleetDO has heard nothing +from a runner for a minute (four of its 15-second heartbeats), it is +offline, whatever its socket says (`SILENT_MS`). FleetDO closes that +socket, so that a host that comes back says hello on a new one, and its +sessions are reconciled with what was decided meanwhile +([ADR 0108](adr/0108-sessions-dont-wait-for-a-runner-that-went-silent.md)). +An offline runner takes no sessions, the runners list says when it was +last heard from, and a resume whose sandbox is there starts elsewhere. + +- **A stop doesn't wait for it.** A session someone stops while its + runner is offline stops at once, and one whose stop was on its way as + the runner went stops once the runner has been offline a minute: its + host stops the sandbox if it comes back (`fctl_domain::reconcile`). +- **Its sessions stop after ten minutes.** Ten minutes after the runner + was last heard from, FleetDO marks its sessions stopped + (`ControlState::runner_gone`), so that a message resumes them on + another runner, and remembers which ones it stopped this way + (`stopped_away`, in its storage). Messages people sent meanwhile, which + wait in the session's outbox, resume it then, at once. Their sandboxes + saved no snapshot as the runner went, so a resume on another runner + restores none of the run that was cut off: one saved before it is older + than the run, and isn't used ([Session snapshots](#session-snapshots)). When the runner comes back and its hello reports one of them still running, and no other run of it has started since, the session carries @@ -1769,17 +1786,56 @@ and the transcript says the runner is back. That includes a session resumed meanwhile that no runner took: the agent that still runs gets the messages. A session that runs on another runner by then, that someone stopped or archived, or whose project was deleted, stops instead, with a -reason that says which (`fctl_domain::reconcile`). - -An autopilot whose own session such a runner had starts a fresh session -at its next wake once that session is stopped (ten minutes after the -runner went away, or at once when it was uninstalled or removed), if -another runner would otherwise resume it in a new sandbox -([Autopilots](#autopilots)). The earlier session doesn't -carry on should its runner come back with it (`Known.superseded`): the -fresh one has taken over. Where no other runner would run it (the -workspace has only that one, say), the wake resumes it as a message -would, and the resume waits for its runner. +reason that says which (`fctl_domain::reconcile`). One that was still +there before the ten minutes carries on with whatever it was sent. + +An autopilot doesn't wait for a runner that went away with its own +session ([Autopilots](#autopilots)). Once the runner has been offline a +minute, and another runner online would run the session, a wake moves it, +whatever it was doing (`fctl_domain::autopilot::stranded`): fctl stops it +there, at once, and starts a fresh session on another runner, which takes +over from its plan, log and files. Nothing that would wake it is lost on +the way: + +- **A wake that reached it first.** One that came in the minute before + FleetDO knew the runner was gone waits in the session's outbox. FleetDO + tells each session on a runner once it has been offline a minute + (`ControlState::runner_away`), and an autopilot's own one with a message + its agent didn't take wakes the autopilot again then (the wake reason + `away`, `autopilots::own_cut_off`). +- **A person's message.** One sent to its own session while the runner + has been away a minute, as its page sees it, wakes the autopilot too. +- **A turn cut off.** One that was at work as the runner went, which + nothing else wakes, wakes it once the ten minutes have stopped it + (`SessionObject::runner_went`). +- **A fresh session people ask for** (*Hand off to a fresh session*) + doesn't wait for a turn that can't end there: it starts now + (`fctl_domain::autopilot::holds`). + +The earlier session doesn't carry on should its runner come back with it +(it was stopped, or `Known.superseded`): the fresh one has taken over. +Where no other runner would run it (the workspace has only that one, +say), the wake goes to it as a message would, and waits for its runner. + +A runner that sleeps but for a moment now and then (a laptop with its +lid closed, whose host wakes to say hello and sleeps again) is online +for those moments, which keeps its sessions from stopping, but gets no +further with them. People don't wait for it: + +- **Move to another runner** (`fctl move`, `POST /sessions/{id}/move`, + the session page's menu and its notice that the work isn't coming + through, the Autopilot tab's menu for its own session) moves a session + off its runner to another that would run it (FleetDO's + `move_session`). FleetDO keeps it off that runner (`moved_off`) until + it starts elsewhere, and queues it. A runner online is asked to stop it + first, so that its agent saves a snapshot to carry on from, but only + for a minute (`let_go_of_moves`); one offline, or whose stop is overdue + already, is let go at once, and the session starts from its branch + with a new conversation. Its host stops the run when it gets the word, + or as it reconnects and finds the session elsewhere. +- **A second stop** a minute after the first, which its runner didn't + carry out, stops the session without waiting for that runner any + longer (`stop_overdue`). ### Session snapshots @@ -3025,11 +3081,13 @@ sessions to do it, and sets up what the work needs, as far as they let it which resumes it if it stopped, while that started less than 12 hours ago (`fctl_domain::autopilot::SHIFT_MS`), holds less context than where people want it to hand off, didn't fail and people didn't ask for a - fresh one, or works now (`fctl_domain::autopilot::fresh`). Between its - turns, where that session's sandbox is counts too (FleetDO's - `POST /sandbox`, `fctl_domain::autopilot::moves`): not on a runner that - drains ([Draining a runner](#draining-a-runner)), and, once it stops, - not where its runner can't take it back (offline, or uninstalled) while + fresh one, or works now (`fctl_domain::autopilot::fresh`). Where that + session's sandbox is counts too (FleetDO's `POST /sandbox`, + `fctl_domain::autopilot::moves`): not on a runner that has been offline + a minute while another runner would run it, whatever the session does + there (`stranded`), and between its turns not on a runner that drains + ([Draining a runner](#draining-a-runner)), and, once it stops, not + where its runner can't take it back (offline, or uninstalled) while another runner would resume it in a new sandbox, without its conversation ([A runner that goes away](#a-runner-that-goes-away)); its log names the runner. Otherwise it stops that one and @@ -3106,7 +3164,8 @@ sessions to do it, and sets up what the work needs, as far as they let it fresh session*, `fctl autopilot wake --fresh`, the wake reason `fresh`), so that it starts from what fctl and its briefing say now, after a release for one: between its turns at once, else once its - turn ends. That wake waits for the turn's end + turn ends, or at once where its runner went away and the turn can't + end. That wake waits for the turn's end (`fctl_domain::autopilot::holds`), which wakes it again at once (`autopilots::session_moved`), and all it woke for meanwhile goes to the fresh session rather than the one leaving (`Autopilot.fresh_asked` diff --git a/docs/cli.md b/docs/cli.md index 40957b5d..8b9ed446 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -123,6 +123,7 @@ fctl files get my-app#12 model.3mf # writes ./model.3mf (the newest of that fctl files get my-app#12 --all --dir in/ # every file, the newest of each name fctl interrupt my-app#12 # stop the current turn fctl stop my-app#12 # end the session (its sandbox is kept for resuming) +fctl move my-app#12 # off its runner, to another that would run it (a laptop asleep, say) fctl resume my-app#12 "Now add tests" # also a failed one, on your Claude subscription fctl take-over my-app#12 # one that waits for someone else's limit (or rests) continues on your subscription fctl follow my-app#12 # get its notifications (see Notifications) @@ -928,7 +929,7 @@ fctl autopilot set -p crm --check-in 2h --direction-file direction.md # how it fctl autopilot set -p crm --handoff-at 250k # a fresh session takes over once its own holds 250K tokens of context (never: only after 12 hours) fctl autopilot set -p crm --powers merge,settings,others # it manages the sessions people start in crm too 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 wake -p crm --fresh # in a fresh session, which starts from its plan and log (once its turn ends, while it works, unless its runner went away) 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 diff --git a/docs/getting-started.md b/docs/getting-started.md index 9aae0e7a..c8e6281e 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -602,6 +602,8 @@ the runner gets through, and messages you send wait for it. After ten minutes away the session shows as stopped, and a message resumes it on another runner. If the runner comes back with the agent still running before the session runs anywhere else, the session carries on there. +Rather than wait, its owner can move it with *Move to another runner* +(`fctl move`): it starts on another runner, from where its branch is. When the agent finishes a turn, the session waits for you. After the project's idle timeout (ten minutes unless its settings say otherwise) it diff --git a/docs/llms.txt b/docs/llms.txt index d913699f..40ca0fb4 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -91,7 +91,7 @@ queued → provisioning → preparing → running ⇄ idle → stopping → stop - `paused`: the person's plan hit a usage limit (or the turn would have drawn on paid extra usage); it continues by itself when the limit resets (`resume_at`). - `failed`: something went wrong (`status_reason` says what). Only a resume (`fctl resume`, on the resumer's subscription) restarts a failed session; a message doesn't. - A message keeps a session on the subscription it ran on, a paused one too. `fctl take-over SESSION` (**Continue on my subscription**) moves one that is paused, idle or stopped to your Claude connection for its workspace (another of your own connections too): it starts again there, in the same conversation. An autopilot moves its own sessions to its owner's connection as it wakes, once someone takes it over or its owner chooses or connects another. -- A runner that goes away leaves its agents working; after ten minutes the session shows as stopped and a message resumes it elsewhere, unless the runner comes back first. +- A runner that goes away leaves its agents working. It is offline once its connection closes, or once nothing has come from it for a minute (a laptop asleep keeps its connection open): it takes no sessions, and a session stopped there stops at once. Ten minutes after it was last heard from, its sessions show as stopped and a message resumes them elsewhere (one sent meanwhile does then), unless the runner comes back first. An autopilot doesn't wait for it: once its own session's runner has been offline a minute, the next wake (a wake that reached that session first, or a message to it, wakes it again then) starts a fresh session on another runner, even mid-turn, and `fctl autopilot wake --fresh` doesn't wait for that turn to end. A runner that wakes but for a moment now and then (a laptop with its lid closed) stays online for those moments without getting further: `fctl move ` (`POST /api/v1/sessions/{id}/move`; *Move to another runner* on the session page) moves a session off it to another runner that would run it, which it isn't given back; a runner online is asked to stop it first, for a minute at most, so that it carries on from its snapshot, and one offline is let go at once (from its branch, with a new conversation). A second `fctl stop` a minute after the first, which the runner didn't carry out, stops the session without waiting for it. - A runner short of disk tells its sessions in notices (`fctl logs --json`: `kind` `notice`, `.data.code`): `runner_low_on_disk` (`warn`) below the floor its host keeps (`min_free_disk_gb`, 20 GiB by default), `runner_out_of_disk` (`error`) below 2 GiB, when the agent's writes are about to fail, and `runner_disk_ok` (`info`) once it has had room for ten minutes. On Firecracker runners the host then pauses the sandbox (`sandbox_paused`) and resumes it once there is room (`sandbox_resumed`): the agent waits, losing nothing, and its status doesn't change. `agent_restarted` says the host started fctl-agent again while the disk was short. A session stuck on a full runner needs someone to free space there: report it rather than wait. - A sandbox short of memory says so in notices too: `memory_nearly_out` (`warn`) when it is 85% full while the agent works, naming what holds the most, and `memory_killed` (`warn`) when the kernel killed one of its processes for want of memory (a browser, a build); the agent hears of both from fctl-agent at its next step. `claude_restarted` says Claude Code itself was killed, and the agent carries on with its turn. Sessions that keep getting these run too much at once for their sandbox's size. - Review agents' sessions take no messages, stop as soon as their review is posted, and stay off the Agent Floor and session lists. Their page links the session whose agent opened the pull request when it is in the same project (`opened_by` in `fctl review --json`). @@ -194,7 +194,7 @@ Each recipe says who does what: some steps take a person with a role in the proj 1. **Delegate a task and collect the result**: the core loop above. Add `--github read` for an answer without changes, `-a FILE` (up to 10 files of 20 MB) for screenshots or logs, `--model opus|sonnet|haiku|fable --effort low|medium|high|xhigh|max` to override the project's, `--base BRANCH` to start elsewhere, `--branch NAME` to choose the branch. 2. **Several independent tasks at once**: start one session per task with `fctl run -d`; each gets its own sandbox, branch and pull request. Watch them with `fctl sessions --active --json`. Runners take as many as their capacity allows (4 each by default); the rest queue. -3. **Steer or stop**: `fctl send "…"` (resumes a stopped session, and answers what its agent asks: `fctl show` and `fctl sessions` print the question), `fctl interrupt `, `fctl stop `, `fctl resume "…"`. Its owner changes the model or effort level its agent works at from its next step, and its next run's: `fctl edit --effort medium` (plan at xhigh, build at medium) keeps Claude's prompt cache where Claude sends the level with each turn; `--model sonnet` makes its next step read the whole conversation again without the cache. +3. **Steer or stop**: `fctl send "…"` (resumes a stopped session, and answers what its agent asks: `fctl show` and `fctl sessions` print the question), `fctl interrupt `, `fctl stop `, `fctl resume "…"`, `fctl move ` (to another runner, off one that went quiet). Its owner changes the model or effort level its agent works at from its next step, and its next run's: `fctl edit --effort medium` (plan at xhigh, build at medium) keeps Claude's prompt cache where Claude sends the level with each turn; `--model sonnet` makes its next step read the whole conversation again without the cache. 4. **From any tool (issue tracker, chat bot, deploy pipeline, n8n/Zapier/Make)**: a person sets up a schedule that runs when asked and a token that runs sessions in that project, then the tool posts what it knows: ```sh fctl schedules add "Triage an issue" -p my-app --when-asked --github triage \ @@ -213,7 +213,7 @@ Each recipe says who does what: some steps take a person with a role in the proj 9. **GitHub Issues as the tracker**: the default; agents use `gh issue` in the repositories they write to. `fctl projects set -p my-app --tickets github --tickets-repo owner/name` keeps them to one repository's issues (through `fctl ticket` when they write to other repositories too); `--tickets none` keeps them away from trackers. A maintainer can start a session that reaches GitHub's issues whatever the tracker says, to move them into Linear, say (`fctl run --github-issues`). 10. **Plan or review without changes**: `fctl run -p my-app -d --github read "Plan the move to Postgres: what changes, in what order, what can break."` or a project-wide cap: `fctl projects set -p my-app --github comment`. 11. **Set up a project** (a workspace admin): `fctl projects create "My app" --repo my-org/my-app -w acme`, then `fctl projects set -p my-app --setup-script 'npm ci' --idle-timeout 30 --pr-descriptions balanced`, more repositories with `fctl projects repos add my-org/my-lib --write -p my-app`, an image with `--image ghcr.io/acme/agent:1` or `--build Dockerfile`, size with `--cpus 8 --memory 16g`, shared package caches with `--package-caches on`, its agents' instructions, model and effort with `--instructions-file agents.md --model opus --effort high`, the context size Claude compacts their sessions near with `--compact-window 400k` (100k to 1m; `default` for Claude's, near the model's whole window), opening pull requests when they finish with `--auto-pull-request on|off`, how they handle pull requests and issues with `--pr-instructions-file prs.md` (`fctl projects show my-app --pr-instructions` prints fctl's rules to start from), Remote Control and claude.ai connectors with `--remote-control on|off --connectors on|off`, its name, description and default branch with `--name "Web app" --description "The storefront" --default-branch develop`, and its icon in the sidebar and on its page with `--icon store --icon-color yellow --icon-style duotone` (an [IconMCP](https://iconmcp.com) glyph's name; ink, yellow, pink, blue or a color of its own as `'#rrggbb'`; outline, duotone or solid; `--icon ""` for the one that fits its name). Secrets: `fctl projects secrets set STRIPE_KEY -p my-app`, the value typed at its prompt or piped in; `fctl projects secrets -p my-app` lists their names. People: `fctl projects members add grace@example.com --role maintainer -p my-app` (`viewer`, `editor`, `maintainer`, `owner`), `fctl projects members role …`, `fctl projects members remove …`. -12. **Bring a machine online** (its owner, at its terminal): install Apple's `container` (macOS 26+, `container system start`; a host on the apple driver starts it again after the Mac restarts, stops a sandbox whose VM stops answering, which would hold up every other: its session fails and resumes in it, and restarts Apple's `container` when its sandboxes lose the network while the Mac has it, at most every 30 minutes: sessions wait meanwhile rather than fail), Lima, or Docker (on Linux, Docker Engine with `sudo systemctl enable --now docker`; `fctl host install` offers to add the user to the `docker` group, and fctl takes the group itself, with no new login), or on Linux with KVM `passt` and `e2fsprogs` for `--driver firecracker`; then `fctl login`, `fctl host install --workspace acme` (or `--token fctl_rt_…` from the workspace's Runners tab), `fctl host doctor`, `fctl host status`. Maintenance: `fctl host drain --wait` (`--timeout 60s` stops what still runs after that long, as a cloud takes the machine; give it a minute less than the notice), `fctl host undrain`; a machine that should go once idle: `fctl host install --retire-when-idle 20m --retire-command '…'`; an autopilot whose own session's sandbox is on a draining runner moves off at its next wake once its turn has ended, in a fresh session on another runner, as it does while the machine is away and another runner would run it, and `fctl host status` lists the autopilots that wake there, with when each wakes. Many machines, or ones autoscaling starts: a workspace admin makes an enrollment token (`fctl runners enrollment-tokens create "Build fleet" -w acme --max-runners 20 --remove-offline-after 5m`, `--approval` to approve each), or any member one for their own sessions (`--personal`), and each machine's boot script runs `FCTL_SERVER=https://app.fctl.sh FCTL_ENROLL_TOKEN=fctl_et_… fctl host install` with no sign-in (and, for someone who keeps their Claude token on their runners, `fctl host claude set-token < /run/secrets/claude-token`); `fctl runners --pending`, `fctl runners approve `, `fctl runners reject `, `fctl runners remove `. Pools: `--labels aws,large` on the token, `fctl runners enrollment-tokens set "AWS large" -w acme --placement packed --max-runners 40`, `fctl projects set -p ml --runners large` (in the web app: Pools on the Runners tab, and a pool by its name in a project's Settings → Runners); an autoscaler reads `GET /api/v1/runner/enroll/demand` with the enrollment token (KEDA: `valueLocation: wanted`), or `fctl runners demand -w acme --pool "AWS large" --json`. +12. **Bring a machine online** (its owner, at its terminal): install Apple's `container` (macOS 26+, `container system start`; a host on the apple driver starts it again after the Mac restarts, stops a sandbox whose VM stops answering, which would hold up every other: its session fails and resumes in it, and restarts Apple's `container` when its sandboxes lose the network while the Mac has it, at most every 30 minutes: sessions wait meanwhile rather than fail), Lima, or Docker (on Linux, Docker Engine with `sudo systemctl enable --now docker`; `fctl host install` offers to add the user to the `docker` group, and fctl takes the group itself, with no new login), or on Linux with KVM `passt` and `e2fsprogs` for `--driver firecracker`; then `fctl login`, `fctl host install --workspace acme` (or `--token fctl_rt_…` from the workspace's Runners tab), `fctl host doctor`, `fctl host status`. Maintenance: `fctl host drain --wait` (`--timeout 60s` stops what still runs after that long, as a cloud takes the machine; give it a minute less than the notice), `fctl host undrain`; a machine that should go once idle: `fctl host install --retire-when-idle 20m --retire-command '…'`; an autopilot whose own session's sandbox is on a draining runner moves off at its next wake once its turn has ended, in a fresh session on another runner, as it does, mid-turn too, once the machine has been away a minute and another runner would run it, and `fctl host status` lists the autopilots that wake there, with when each wakes. Many machines, or ones autoscaling starts: a workspace admin makes an enrollment token (`fctl runners enrollment-tokens create "Build fleet" -w acme --max-runners 20 --remove-offline-after 5m`, `--approval` to approve each), or any member one for their own sessions (`--personal`), and each machine's boot script runs `FCTL_SERVER=https://app.fctl.sh FCTL_ENROLL_TOKEN=fctl_et_… fctl host install` with no sign-in (and, for someone who keeps their Claude token on their runners, `fctl host claude set-token < /run/secrets/claude-token`); `fctl runners --pending`, `fctl runners approve `, `fctl runners reject `, `fctl runners remove `. Pools: `--labels aws,large` on the token, `fctl runners enrollment-tokens set "AWS large" -w acme --placement packed --max-runners 40`, `fctl projects set -p ml --runners large` (in the web app: Pools on the Runners tab, and a pool by its name in a project's Settings → Runners); an autoscaler reads `GET /api/v1/runner/enroll/demand` with the enrollment token (KEDA: `valueLocation: wanted`), or `fctl runners demand -w acme --pool "AWS large" --json`. 13. **Dashboards and reports**: a token with `--access read` lists sessions, transcripts, memory and retrospectives and starts nothing: `fctl sessions --active --json`, `fctl sessions --since 1d --json` (at work in the last day, those that ended in it too), `fctl pulls --json` (the open pull requests agents opened, each once with the sessions that list it; `-p my-app`, `--state merged|closed|all`, `--mine`; archived sessions' too, a session marked `(asks you)` or `(archived)`, `archived` and `question` in its JSON; the app's `/pulls` page sorts the open ones by what each needs next: waiting for your answer, ready for review, checks failing, agents at work, merge queue, drafts), `fctl retro list -p my-app --json`, `fctl search "flaky test" --json`, `fctl logs my-app#12 --json`, `fctl diff my-app#12` (the branch's changes as git prints them; `--json` for each file's patch). 14. **Keep agents informed**: `fctl memory add -p my-app "Deploys happen on Thursdays: merge migrations by Tuesday."`; delete every stale note at once with `fctl memory delete --stale -p my-app` (a project keeps 1,000 notes, stale ones included), or have fctl delete notes once they have been stale a number of days with `fctl projects set -p my-app --stale-note-days 7` (1 to 365; `never` by default); read what they learned with `fctl memory -p my-app` and `fctl retro list -p my-app --outcome blocked`. 15. **Hand a session to someone** (its owners): `fctl share grace@example.com` lets someone in its workspace view it and message its agent (`--role viewer` only views it, `--role owner` also stops, resumes, archives and shares it), `fctl share ` lists who it is shared with, `fctl unshare grace@example.com` takes it back. Anyone who can message the agent can have it hand over the sandbox's secrets and tokens. `fctl archive ` takes a finished session out of the lists and stops follow-ups reaching it (`fctl unarchive`, `fctl sessions --archived`). diff --git a/web/src/components/project/autopilot.tsx b/web/src/components/project/autopilot.tsx index 08af86da..0281b6f0 100644 --- a/web/src/components/project/autopilot.tsx +++ b/web/src/components/project/autopilot.tsx @@ -35,6 +35,7 @@ import { Power, RefreshCw, Repeat, + Route, Send, Settings2, ShieldCheck, @@ -52,6 +53,7 @@ import { Markdown } from "@/components/markdown"; import { ProjectMark } from "@/components/project/project-icon"; import { AttachButton, DraftTray, DropHint, useAttachments } from "@/components/session/attachments"; import { ScheduleNamed } from "@/components/session/autopilot"; +import { ON_RUNNER, useMoveOff } from "@/components/session/move-off"; import { AutopilotIcon, Avatar, @@ -96,6 +98,7 @@ import { POWERS, phase, planDone, + runnerAway, wakeWords, } from "@/lib/autopilot"; import { connectionIn } from "@/lib/claude"; @@ -972,6 +975,7 @@ function Header({ project, a }: { project: G.Project; a: G.Autopilot }) { const me = useMe().data; const mine = !!me && a.owner?.id === me.user.id; const { fresh } = useMoves(a); + const moveOff = useMoveOff(a.session?.id ?? ""); return (
)} + {a.session?.runner && ON_RUNNER.has(a.session.status) && ( + } + onClick={() => { + close(); + moveOff.mutate(); + }} + > + Move its session to another runner + + )} api.wakeAutopilot(a.project_id, { fresh: true }), onSuccess: (x) => { patched(x); - toast(atWork(x) ? "A fresh session takes over once this turn ends" : "A fresh session takes over now"); + toast( + runnerAway(x) + ? "A fresh session takes over on another runner as soon as one would run it" + : atWork(x) + ? "A fresh session takes over once this turn ends" + : "A fresh session takes over now", + ); }, onError: (e) => failed(e, "No fresh session took over"), }); diff --git a/web/src/components/session/move-off.test.ts b/web/src/components/session/move-off.test.ts new file mode 100644 index 00000000..686eb221 --- /dev/null +++ b/web/src/components/session/move-off.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from "vitest"; +import { moveOffWords, ON_RUNNER } from "./move-off"; + +describe("moving a session off its runner", () => { + const base = { runner: "laptop", status: "running" as const, since: 0, showFrom: 0 }; + + it("says what it starts from on another runner", () => { + expect(moveOffWords({ ...base, kind: "away" })).toBe( + "It starts again on another runner from its branch, with a new conversation: what it hasn't pushed stays on runner laptop.", + ); + expect(moveOffWords({ ...base, kind: "unreachable", reason: "x" })).toContain("stays on runner laptop"); + // A runner that paused its sandbox for want of disk is there to stop it. + expect(moveOffWords({ ...base, kind: "paused", reason: "x" })).toBe( + "Runner laptop stops it first, then it starts again on another runner.", + ); + expect(moveOffWords({ ...base, runner: undefined, kind: "away" })).toContain("stays on its runner"); + }); + + it("is offered while it runs on a runner, stopping included", () => { + expect(ON_RUNNER.has("stopping")).toBe(true); + expect(ON_RUNNER.has("idle")).toBe(true); + expect(ON_RUNNER.has("queued")).toBe(false); + expect(ON_RUNNER.has("stopped")).toBe(false); + }); +}); diff --git a/web/src/components/session/move-off.tsx b/web/src/components/session/move-off.tsx new file mode 100644 index 00000000..90e9936c --- /dev/null +++ b/web/src/components/session/move-off.tsx @@ -0,0 +1,59 @@ +// Moving a session off its runner, to another that would run it: for a runner that went quiet, or +// sleeps but for a moment now and then, which the session would wait for otherwise +// (`POST /sessions/{id}/move`). + +import { useMutation } from "@tanstack/react-query"; +import { Route } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { toast } from "@/components/ui/feedback"; +import type * as G from "@/gen"; +import { api } from "@/lib/api"; +import { patchSession, queryClient } from "@/lib/queries"; +import type { Stall } from "@/lib/stall"; + +/** Statuses in which a session runs on a runner, which people may move it off: stopping too, which may not get done. */ +export const ON_RUNNER = new Set([ + "provisioning", + "preparing", + "running", + "idle", + "paused", + "stopping", +]); + +/** Moves session `id` off its runner. */ +export function useMoveOff(id: string) { + return useMutation({ + mutationFn: () => api.moveOff(id), + onSuccess: (s) => { + patchSession(queryClient, s); + toast(s.runner ? "Moving to another runner" : "It starts on another runner"); + }, + onError: (e) => toast(e.message, "error"), + }); +} + +/** What moving it off a runner whose work doesn't come through keeps: only what that runner said last. */ +export function moveOffWords(stall: Stall): string { + if (stall.kind === "paused") + return `${stall.runner ? `Runner ${stall.runner}` : "Its runner"} stops it first, then it starts again on another runner.`; + return `It starts again on another runner from its branch, with a new conversation: what it hasn't pushed stays on ${stall.runner ? `runner ${stall.runner}` : "its runner"}.`; +} + +/** The stall notice's way out: moves the session to another runner, rather than wait for this one. */ +export function MoveOff({ sessionId, stall }: { sessionId: string; stall: Stall }) { + const move = useMoveOff(sessionId); + return ( +
+ +

{moveOffWords(stall)}

+
+ ); +} diff --git a/web/src/components/session/transcript.tsx b/web/src/components/session/transcript.tsx index 87578ba4..06250d5f 100644 --- a/web/src/components/session/transcript.tsx +++ b/web/src/components/session/transcript.tsx @@ -59,6 +59,7 @@ import { useRevealed } from "./find"; import { FindingsMessage } from "./findings"; import { FollowUpMessage, HeldFollowUp } from "./follow-up"; import { Busy, Milestone, MilestoneButton, RailIcon, Thread } from "./lines"; +import { MoveOff } from "./move-off"; import { RetrospectiveCard } from "./retrospective"; import { SlackMessageView, SlackNoticeView } from "./slack"; import { TicketMessageView, TicketNoticeView } from "./ticket"; @@ -687,8 +688,11 @@ function LiveText({ text, writing, className }: { text: string; writing: boolean ); } -/** The agent's work isn't coming through: says why, in place of work in progress. */ -function StallNotice({ stall }: { stall: Stall }) { +/** + * The agent's work isn't coming through: says why, in place of work in progress, and offers its people to move + * the session to another runner rather than wait (`moves`, the session's id). + */ +function StallNotice({ stall, moves }: { stall: Stall; moves?: string }) { const { title, detail } = stallText(stall); return (
@@ -698,6 +702,7 @@ function StallNotice({ stall }: { stall: Stall }) {

{title}

{detail}

+ {moves && }
); @@ -729,10 +734,13 @@ export function LiveTurnView({ live, stall, disk, + moves, textClassName, }: { live: LiveTurn; stall?: Stall; + /** The session's id, where the reader may move it to another runner while its work doesn't come through. */ + moves?: string; /** How short of disk the session's runner is. */ disk?: DiskShort; /** For the words it writes as they come, which the transcript sets in from its thread. */ @@ -745,7 +753,7 @@ export function LiveTurnView({ ) : null, )} - {stall && } + {stall && } {disk && } ); diff --git a/web/src/components/session/turns.tsx b/web/src/components/session/turns.tsx index d4193a5e..ecae187f 100644 --- a/web/src/components/session/turns.tsx +++ b/web/src/components/session/turns.tsx @@ -373,7 +373,13 @@ export const TurnTranscript = memo(function TurnTranscript({ rows.push( // The thread trails off under the newest step, where the next comes.
- +
, ); } @@ -409,7 +415,7 @@ export const TurnTranscript = memo(function TurnTranscript({ // The agent went on after the last turn ended, without a message yet: what streams in. rows.push(
- +
, ); } diff --git a/web/src/gen/Autopilot.ts b/web/src/gen/Autopilot.ts index 472029c7..456b9796 100644 --- a/web/src/gen/Autopilot.ts +++ b/web/src/gen/Autopilot.ts @@ -93,7 +93,8 @@ handoff_at?: number, /** * Someone asked for a fresh session to take over from its own * (`WakeAutopilotRequest.fresh`), and none has yet: it does as fctl - * next wakes it, once that one's turn ends while it works. Control + * next wakes it, once that one's turn ends while it works, unless its + * runner went away (`AutopilotSession.runner_away_since`). Control * planes before it leave it out. */ fresh_asked: boolean, diff --git a/web/src/gen/AutopilotSession.ts b/web/src/gen/AutopilotSession.ts index 5cdbfb45..fa5d4b24 100644 --- a/web/src/gen/AutopilotSession.ts +++ b/web/src/gen/AutopilotSession.ts @@ -1,4 +1,5 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { RunnerRef } from "./RunnerRef"; import type { SessionId } from "./SessionId"; import type { SessionStatus } from "./SessionStatus"; @@ -11,4 +12,18 @@ export type AutopilotSession = { id: SessionId, number: number, status: SessionS * hands off at `Autopilot.handoff_at`. Absent until it has, and from * control planes before it. */ -context_tokens?: number, }; +context_tokens?: number, +/** + * The runner it runs on, while it has one. Control planes before it + * leave it out. + */ +runner?: RunnerRef, +/** + * When its runner was last heard from, once that was a minute ago or + * more while it runs there: a laptop asleep, a machine gone. fctl + * doesn't wait for it: as something next wakes the autopilot, or + * people ask for a fresh session, a fresh one takes over on another + * runner, where one online would run it. Absent while its runner is + * heard from, and from control planes before it. + */ +runner_away_since?: number, }; diff --git a/web/src/gen/AutopilotWakeReason.ts b/web/src/gen/AutopilotWakeReason.ts index 3d3cdf69..18348e31 100644 --- a/web/src/gen/AutopilotWakeReason.ts +++ b/web/src/gen/AutopilotWakeReason.ts @@ -3,4 +3,4 @@ /** * Why fctl wakes an autopilot. */ -export type AutopilotWakeReason = "started" | "resumed" | "check_in" | "asked" | "woken" | "steered" | "answered" | "crew" | "retry" | "moved" | "fresh" | "merge_checks" | "others" | "other"; +export type AutopilotWakeReason = "started" | "resumed" | "check_in" | "asked" | "woken" | "steered" | "answered" | "crew" | "retry" | "moved" | "fresh" | "merge_checks" | "others" | "away" | "other"; diff --git a/web/src/gen/WakeAutopilotRequest.ts b/web/src/gen/WakeAutopilotRequest.ts index f0758772..b8344870 100644 --- a/web/src/gen/WakeAutopilotRequest.ts +++ b/web/src/gen/WakeAutopilotRequest.ts @@ -3,7 +3,8 @@ /** * `POST …/autopilot/wake`: a person wakes it now, with `fresh` in a * fresh session of its own, which takes over from the one it works in - * (once that one's turn ends, while it works); the autopilot says when it + * (once that one's turn ends, while it works, unless its runner went + * away); the autopilot says when it * wakes next, unless something wakes it sooner: in `in_minutes` (5 to * 1,440), or at `at`. */ diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index 5d9dcadd..97e07206 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -528,6 +528,8 @@ export const api = { passOnReview: (id: string, review: string) => request("POST", `/sessions/${enc(id)}/reviews/${enc(review)}/pass-on`, {}), stop: (id: string) => request("POST", `/sessions/${enc(id)}/stop`, {}), + /** Moves a session off its runner, to another that would run it. */ + moveOff: (id: string) => request("POST", `/sessions/${enc(id)}/move`, {}), /** Moves a session to your Claude subscription: it starts again there, or resumes on it. */ takeOver: (id: string) => request("POST", `/sessions/${enc(id)}/take-over`, {}), resume: (id: string, prompt?: string, attachments?: G.AttachmentId[]) => diff --git a/web/src/lib/audit.test.ts b/web/src/lib/audit.test.ts index 2f51f6f4..e85ddf39 100644 --- a/web/src/lib/audit.test.ts +++ b/web/src/lib/audit.test.ts @@ -47,6 +47,9 @@ describe("an audit log entry in words", () => { "stopped [shop#231](session)", ); expect(said(describeAudit(entry("session.stopped", "ses_2")))).toBe("stopped [a session](session)"); + expect(said(describeAudit(entry("session.moved", "ses_2", { from: "laptop" })))).toBe( + "moved [a session](session) off runner laptop", + ); }); it("says fctl started what a schedule or an autopilot's wake started, and whose autopilot started the rest", () => { diff --git a/web/src/lib/audit.ts b/web/src/lib/audit.ts index 5f4f25d6..f94b2106 100644 --- a/web/src/lib/audit.ts +++ b/web/src/lib/audit.ts @@ -145,6 +145,8 @@ function sentence(e: G.AuditEntry, names: AuditNames): AuditPart[] { return ["stopped ", session()]; case "session.resumed": return ["resumed ", session()]; + case "session.moved": + return ["moved ", session(), str(d.from) ? ` off runner ${String(d.from)}` : " to another runner"]; case "session.archived": return ["archived ", session()]; case "session.unarchived": diff --git a/web/src/lib/autopilot.test.ts b/web/src/lib/autopilot.test.ts index 5ac5a6a3..0a2760bf 100644 --- a/web/src/lib/autopilot.test.ts +++ b/web/src/lib/autopilot.test.ts @@ -15,6 +15,7 @@ import { pausedHere, phase, planDone, + runnerAway, sentence, sessionWord, splitBriefing, @@ -24,6 +25,7 @@ import { wakeText, wokeLine, } from "./autopilot"; +import { clock } from "./format"; const NOW = Date.UTC(2026, 10, 9, 14, 0); @@ -88,6 +90,32 @@ describe("where an autopilot stands", () => { expect(phase({ ...resting, wake_reason: "crew" }, NOW).line).toBe("A fresh session takes over now."); }); + it("says when its session's runner went away, and that it doesn't wait for it", () => { + const away = NOW - 12 * 60_000; + const session = { + id: "ses_1", + number: 7, + status: "running" as const, + started_at: NOW - 3_600_000, + runner: { id: "rnr_1", name: "laptop" }, + runner_away_since: away, + }; + const a = autopilot({ session }); + expect(runnerAway(a)).toBe(away); + expect(phase(a, NOW)).toEqual({ + tone: "blue", + word: "Runner away", + line: `Its session #7 is on runner laptop, which hasn't been heard from since ${clock(away)}. It doesn't wait for it: as something next wakes it, a fresh session takes over on another runner, where one online would run it.`, + }); + // A fresh session people asked for doesn't wait for its turn to end. + expect(phase(autopilot({ session, fresh_asked: true }), NOW, "ses_1").line).toBe( + `This session is on runner laptop, which hasn't been heard from since ${clock(away)}. A fresh session takes over on another runner as soon as one online would run it.`, + ); + // Paused, it wakes for nothing: that comes first. + expect(runnerAway(autopilot({ session, state: "paused" }))).toBeUndefined(); + expect(phase(autopilot({ session, state: "paused", paused_at: NOW }), NOW).word).toBe("Paused"); + }); + it("wakes, and starts, in its session", () => { const a = autopilot({ session: { id: "ses_1", number: 7, status: "provisioning", started_at: NOW } }); expect(phase(a, NOW)).toMatchObject({ word: "Waking", line: "Its session #7 is starting." }); @@ -267,6 +295,11 @@ describe("what woke it", () => { ), ).toBe("Woke for its sessions and people's session #38"); expect(wakeText(wake({ reasons: ["others"] }))).toBe("people's sessions"); + // Its own session's runner went away before its turn ended. + expect(wokeLine(wake({ reasons: ["away"] }))).toBe("Woke as its session's runner went away"); + expect(wokeLine(wake({ reasons: ["crew", "away"] }))).toBe( + "Woke for its sessions and its session's runner going away", + ); }); it("says a start or a resume alone as its log does", () => { diff --git a/web/src/lib/autopilot.ts b/web/src/lib/autopilot.ts index 6e23ea4c..70a82cb9 100644 --- a/web/src/lib/autopilot.ts +++ b/web/src/lib/autopilot.ts @@ -5,6 +5,7 @@ import type * as G from "@/gen"; import { ago, clock, day, num } from "./format"; import { splitRunNote } from "./schedules"; +import { since } from "./stall"; /** How long it goes without waking, at most, as people choose it (the control plane's CHECK_INS). */ export const CHECK_INS: { minutes: number; label: string }[] = [ @@ -112,6 +113,14 @@ export function atWork(a: Pick): boolean { ); } +/** + * Since when its own session's runner hasn't been heard from, while the session runs there and the autopilot is + * on: fctl doesn't wait for that runner. + */ +export function runnerAway(a: Pick): number | undefined { + return a.state === "on" ? a.session?.runner_away_since : undefined; +} + /** How far its plan's checklist is ticked off ("9 of 15"); none for a plan without one. */ export function planDone(plan?: string): { checked: number; of: number } | undefined { const items = plan?.match(/^\s*[-*+] \[( |x|X)\]/gm) ?? []; @@ -148,6 +157,21 @@ export function phase(a: G.Autopilot, now = Date.now(), here?: G.SessionId): Pha line: `${p.who}${p.when ? ` ${p.when}` : ""}${p.reason ? `: ${sentence(p.reason)}` : "."} It wakes again once someone resumes it.`, }; } + // Its own session's runner went away: the next wake moves it rather than wait (autopilot::stranded). + const away = runnerAway(a); + if (away) { + const inIt = !!here && a.session?.id === here; + const where = inIt ? "This session" : `Its session #${a.session?.number}`; + const runner = a.session?.runner?.name ? `runner ${a.session.runner.name}` : "a runner"; + const next = a.fresh_asked + ? "A fresh session takes over on another runner as soon as one online would run it." + : "It doesn't wait for it: as something next wakes it, a fresh session takes over on another runner, where one online would run it."; + return { + tone: "blue", + word: "Runner away", + line: `${where} is on ${runner}, which hasn't been heard from ${since(away, now)}. ${next}${waiting}`, + }; + } if (atWork(a)) { const starting = a.session?.status === "queued" || @@ -361,6 +385,8 @@ export function wakeWords( return `Its last session failed: it tries again ${when}.`; case "fresh": return `A fresh session takes over ${when}.`; + case "away": + return `Its session's runner went away: it wakes ${when} to carry on.`; default: return `It wakes ${when} for what's new.`; } @@ -374,6 +400,7 @@ export function wokeLine(w: G.AutopilotWake): string { if (!more && only === "woken") return "Woke as someone woke it"; if (!more && only === "moved") return "Woke as it was moved to another Claude subscription"; if (!more && only === "fresh") return "Woke as someone asked for a fresh session"; + if (!more && only === "away") return "Woke as its session's runner went away"; return `Woke for ${wakeText(w)}`; } @@ -438,6 +465,9 @@ export function wakeText(w: G.AutopilotWake): string { ); break; } + case "away": + parts.push("its session's runner going away"); + break; case "others": { const others = w.others ?? []; parts.push( diff --git a/web/src/lib/stall.test.ts b/web/src/lib/stall.test.ts index 7a147474..fe22c50e 100644 --- a/web/src/lib/stall.test.ts +++ b/web/src/lib/stall.test.ts @@ -30,9 +30,33 @@ describe("stalls", () => { expect(st?.showFrom).toBe(now + AWAY_GRACE_MS); expect(stallText(must(st), now)).toEqual({ title: `Runner now hasn't been heard from since ${clock(now - 20_000)}.`, - detail: "The agent's work shows up here when it's back, and messages you send reach the agent then.", + detail: `The agent's work shows up here when it's back, and messages you send reach the agent then. If it isn't back by ${clock(now - 20_000 + 10 * minute)}, the session stops, and a message resumes it on another runner.`, }); expect(stallLabel(must(st), now)).toBe(`Runner not heard from since ${clock(now - 20_000)}`); + // One that stops already says nothing of messages, nor of stopping. + expect(stallText(must(stallOf(session("stopping"), away)), now).detail).toBe( + "The agent's work shows up here when it's back.", + ); + }); + + it("say that an autopilot carries on elsewhere rather than wait for its runner", () => { + const own = { + ...session("idle"), + autopilot: { role: "pilot", project_id: "prj_1", project_slug: "shop" }, + } as G.Session; + const st = must( + stallOf(own, { + connection: "live", + runnerConnected: false, + runnerAway: { lastSeenAt: now - 2 * minute, noticedAt: now }, + }), + ); + expect(st.pilot).toBe(true); + expect(stallText(st, now)).toEqual({ + title: `Runner now hasn't been heard from since ${clock(now - 2 * minute)}.`, + detail: + "The autopilot doesn't wait for it: the next time something wakes it, a message you send here included, it carries on in a fresh session on another runner, where one online would run it.", + }); }); it("show a runner gone for long at once", () => { diff --git a/web/src/lib/stall.ts b/web/src/lib/stall.ts index 820308ac..0de58ef1 100644 --- a/web/src/lib/stall.ts +++ b/web/src/lib/stall.ts @@ -20,6 +20,11 @@ import type { LiveState } from "./live"; export const AWAY_GRACE_MS = 10_000; /** A runner gone this long when the page learns of it is reported at once. */ const LONG_GONE_MS = 60_000; +/** + * How long after a runner was last heard from fctl stops its sessions, so that a message resumes + * them on another runner (do_fleet.rs, `RUNNER_GRACE_MS`). + */ +export const RUNNER_GRACE_MS = 10 * 60_000; /** Sessions that have a runner working for them. */ const ACTIVE = new Set([ @@ -39,6 +44,8 @@ export type Stall = { since: number; /** When the page may say so. */ showFrom: number; + /** An autopilot's own session, which carries on in a fresh one elsewhere rather than wait. */ + pilot?: boolean; } & ({ kind: "away" } | { kind: "unreachable"; reason: string } | { kind: "paused"; reason: string }); type RunnerState = Pick< @@ -55,7 +62,8 @@ export function stallOf(session: G.Session | undefined, s: RunnerState): Stall | const away = s.runnerAway; if (!away) return undefined; const showFrom = Math.min(away.noticedAt + AWAY_GRACE_MS, away.lastSeenAt + LONG_GONE_MS); - return { kind: "away", runner, status: session.status, since: away.lastSeenAt, showFrom }; + const pilot = session.autopilot?.role === "pilot"; + return { kind: "away", runner, status: session.status, since: away.lastSeenAt, showFrom, pilot }; } // Its host paused the sandbox until it has room on its disk. const p = s.sandboxPaused; @@ -106,10 +114,19 @@ export function stallText(st: Stall, now = Date.now()): { title: string; detail: const who = st.runner ? `Runner ${st.runner}` : "The runner"; const messages = TAKES_MESSAGES.has(st.status) ? ", and messages you send reach the agent then" : ""; if (st.kind === "away") { - return { - title: `${who} hasn't been heard from ${since(st.since, now)}.`, - detail: `The agent's work shows up here when it's back${messages}.`, - }; + const title = `${who} hasn't been heard from ${since(st.since, now)}.`; + // An autopilot's own session doesn't wait for it: the next wake moves it (autopilot::stranded). + if (st.pilot && TAKES_MESSAGES.has(st.status)) + return { + title, + detail: + "The autopilot doesn't wait for it: the next time something wakes it, a message you send here included, it carries on in a fresh session on another runner, where one online would run it.", + }; + // Ten minutes after it was last heard from, the session stops, and a message resumes it elsewhere. + const stops = TAKES_MESSAGES.has(st.status) + ? ` If it isn't back by ${clock(st.since + RUNNER_GRACE_MS)}, the session stops, and a message resumes it on another runner.` + : ""; + return { title, detail: `The agent's work shows up here when it's back${messages}.${stops}` }; } const reason = st.reason.replace(/[.\s]+$/, ""); if (st.kind === "paused") { diff --git a/web/src/routes/session.tsx b/web/src/routes/session.tsx index 0675e1a8..9c2c4579 100644 --- a/web/src/routes/session.tsx +++ b/web/src/routes/session.tsx @@ -22,6 +22,7 @@ import { Moon, PanelRight, Play, + Route, Search, Share2, Square, @@ -51,6 +52,7 @@ import { useRetrospectives, useSessionMemory, } from "@/components/session/kept"; +import { ON_RUNNER, useMoveOff } from "@/components/session/move-off"; import { useMovedOn } from "@/components/session/moved-on"; import { JumpPill, NowLine, toBottom, useAtBottom } from "@/components/session/now-line"; import { AgentOrb } from "@/components/session/orb"; @@ -294,6 +296,7 @@ export function SessionPage() { onSuccess: () => toast("Stopping the session"), onError: (e) => toast(e.message, "error"), }); + const moveOff = useMoveOff(id); // Live updates go to everyone watching and leave out whether *you* follow it. const following = initial.data?.following ?? false; const follow = useMutation({ @@ -738,6 +741,17 @@ export function SessionPage() { {session?.review ? "Stop the review" : "Stop the session"}
)} + {isOwner && !session?.review && session?.runner && status && ON_RUNNER.has(status) && ( + } + onClick={() => { + close(); + moveOff.mutate(); + }} + > + Move to another runner + + )} {isOwner && !session?.review && (status === "stopped" || status === "failed") && ( }