feat(claw): pause, resume and abort a key's dispatch
The inventory could show a key's queue and delete the key, and nothing
in between: a key wedged on a long turn, or a queue filling from a
source the operator wanted stopped, had no control short of a restart.
Three routes now sit beside the delete.
Pause is an operator's hold, not a dispatcher state: rhema-rsd has
idle, leased and re-acquire, and none of them means "keep the events,
run nothing". So the hold lives beside the store, a set of keys the
drivers' ownership predicates decline, persisted as `paused:<key>` rows
in the settings table and reloaded at boot. A held key ingests as
always, its inbox accumulates, `admit` offers it, and every driver
passes it by until resume lifts the hold. Deleting a key drops its
hold with it, so a name created again starts clean.
Abort stops what a pause cannot: a live turn is a dispatch minutes deep
in tool rounds, and only the dispatch itself can end it. An abort
registry carries the signal to the handler's own select, which drops
the turn future at its current await — a streaming request, or a
running shell command whose child dies with the drop. What the turn
committed is already the session (the commit hook), so the handler
repairs the dangling calls and releases as superseded rather than
failed: the work is no longer wanted. The chat closes on an `aborted`
end marker, the forge thread gets no half-answer, and a coding job's
row lands failed with `aborted`. An idle key's queued work is drained
and dropped under a throwaway lease instead, and a job row moves with
the queue it lost, or it would sit queued forever with nothing left to
run it.
The jobs handler arms its listener at dispatch entry rather than after
the agent is built: the route signals the moment it sees the lease, and
a listener arriving later would let an early abort fall through as a
no-op. Signalling a key with no listener stays a no-op, which is what
lets the route call it unconditionally before its idle path.
GET /v1/sessions carries `paused` beside the state, and the abort
answer says which shape it took: `{"key", "cut", "dropped"}`.
Verified with fmt, clippy -D warnings and the suite (266 lib, 40 http,
including a surface test for the three routes and one proving a dropped
queued job key lands its row aborted). The three sandbox deps still pin
unpublished 0.4.2, so the gates ran against a temporary 0.4.1 pin with
the one 0.4.2 call stubbed, then reverted.
This commit is contained in:
1 parent
cbd52b3b3f
commit
38292b6344
11 files changed
+1187
-35
No files matched your search
@@ -146,6 +146,9 @@ POST /v1/sessions/{key}/messages {"text": "...", "images"?, "pastes"?}
|
||||
GET /v1/sessions/{key}/events SSE turn events (see below); ?since=<seq> resumes a cursor
|
||||
GET /v1/sessions/{key}/history one page of older turns: ?before=<seq>&limit=<n>
|
||||
DELETE /v1/sessions/{key} drop a session and its turn history
|
||||
POST /v1/sessions/{key}/pause hold the key's dispatch; queued work waits
|
||||
POST /v1/sessions/{key}/resume lift the hold
|
||||
POST /v1/sessions/{key}/abort cut the live turn, or drop the queued work
|
||||
GET /v1/watches POST /v1/watches DELETE /v1/watches/{forge}/{repo}
|
||||
GET /v1/bootstrap {"soul": bool, "user": bool}
|
||||
POST /v1/ingest {"source","key","payload"} -> 202
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
//! The abort registry: a running turn the operator cut — the kill that
|
||||
//! pairs with the pause gate ([`crate::pause`]).
|
||||
//!
|
||||
//! Pause holds what has not started; abort stops what has. A live turn
|
||||
//! is minutes of tool rounds deep in a dispatch nobody watches, and the
|
||||
//! only thing that can end it early is the dispatch itself: the turn's
|
||||
//! own future, dropped at its current await — a streaming request, or a
|
||||
//! running shell command, whose child dies with the drop. So each
|
||||
//! handler holds a listener for its key across the dispatch (the lease
|
||||
//! guarantees at most one dispatch per key, so entries never collide),
|
||||
//! and the abort route signals through this registry; the handler
|
||||
//! repairs the dangling calls, stashes what the turn committed, and
|
||||
//! releases the lease as superseded.
|
||||
//!
|
||||
//! The mechanics are [`crate::steer`]'s — the same per-key channel, the
|
||||
//! same signal-after-ingest ordering logic — with a different contract
|
||||
//! on the far side: a steer signal loops the dispatch onto its next
|
||||
//! round, an abort signal ends it. Signalling a key with no live
|
||||
//! dispatch is a no-op (`false`), which makes the route's call
|
||||
//! unconditional: the route's own idle path drains whatever is queued,
|
||||
//! and the signal covers only the turn that runs.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
/// The per-key abort registry. The daemon builds one and shares it with
|
||||
/// the HTTP surface; every handler listens on it.
|
||||
#[derive(Default)]
|
||||
pub struct AbortRegistry {
|
||||
/// One sender per key with a dispatch in flight; the guard's `Drop`
|
||||
/// removes its own.
|
||||
live: Mutex<HashMap<String, mpsc::Sender<()>>>,
|
||||
}
|
||||
|
||||
impl AbortRegistry {
|
||||
/// An empty registry.
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Aborts the live dispatch on `key`, if there is one. `true` when a
|
||||
/// listener took the signal; `false` when no dispatch runs (or its
|
||||
/// channel is already full — one pending abort is enough; the turn
|
||||
/// ends either way).
|
||||
pub fn signal(&self, key: &str) -> bool {
|
||||
let listener = self
|
||||
.live
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.get(key)
|
||||
.cloned();
|
||||
match listener {
|
||||
Some(sender) => sender.try_send(()).is_ok(),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Arms a listener for `key`. The guard is the dispatch's side: hold
|
||||
/// it across the whole dispatch chain, drop it to unregister.
|
||||
pub fn listen(self: &Arc<Self>, key: &str) -> AbortGuard {
|
||||
let (sender, receiver) = mpsc::channel(1);
|
||||
self.live
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.insert(key.to_owned(), sender.clone());
|
||||
AbortGuard {
|
||||
registry: Arc::clone(self),
|
||||
key: key.to_owned(),
|
||||
sender,
|
||||
receiver: Some(receiver),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One dispatch's listener: the receiver the select waits on, plus
|
||||
/// enough identity to unregister only its own entry. The receiver sits
|
||||
/// in an `Option` because `recv` consumes it; the borrow hands it back
|
||||
/// after every await, so the guard stays the one object the dispatch
|
||||
/// carries from round to round.
|
||||
pub struct AbortGuard {
|
||||
registry: Arc<AbortRegistry>,
|
||||
key: String,
|
||||
/// The guard's own sender, kept only so `Drop` can tell its entry
|
||||
/// from a later dispatch's.
|
||||
sender: mpsc::Sender<()>,
|
||||
receiver: Option<mpsc::Receiver<()>>,
|
||||
}
|
||||
|
||||
impl AbortGuard {
|
||||
/// Whether an abort is pending. The dispatch checks this between
|
||||
/// rounds: an abort carries no inbox message of its own, so unlike
|
||||
/// steer's stale-signal clear, a pending abort here is honored, not
|
||||
/// dropped.
|
||||
pub fn take(&mut self) -> bool {
|
||||
match self.receiver.as_mut() {
|
||||
Some(receiver) => receiver.try_recv().is_ok(),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves once an abort arrives. A closed channel — impossible
|
||||
/// while this guard lives, since its own sender sits in the
|
||||
/// registry — parks forever rather than resolving empty, so the
|
||||
/// select's abort arm goes silent instead of spinning.
|
||||
pub async fn wait(&mut self) {
|
||||
loop {
|
||||
let received = match self.receiver.as_mut() {
|
||||
Some(receiver) => receiver.recv().await,
|
||||
None => std::future::pending::<Option<()>>().await,
|
||||
};
|
||||
if received.is_some() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for AbortGuard {
|
||||
fn drop(&mut self) {
|
||||
// Only remove the entry this guard inserted: a same-key entry
|
||||
// from a later dispatch must survive (it cannot coexist with a
|
||||
// live one — the lease forbids it — but a defensive check keeps
|
||||
// the registry honest regardless of caller discipline).
|
||||
let mut live = self
|
||||
.registry
|
||||
.live
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
if live
|
||||
.get(&self.key)
|
||||
.is_some_and(|entry| entry.same_channel(&self.sender))
|
||||
{
|
||||
live.remove(&self.key);
|
||||
}
|
||||
self.receiver = None;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_signal_with_no_listener_is_a_no_op() {
|
||||
let registry = Arc::new(AbortRegistry::new());
|
||||
assert!(!registry.signal("job:rhema#7"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_listener_takes_the_signal_and_unregisters_on_drop() {
|
||||
let registry = Arc::new(AbortRegistry::new());
|
||||
let mut guard = registry.listen("job:rhema#7");
|
||||
|
||||
assert!(registry.signal("job:rhema#7"));
|
||||
guard.wait().await;
|
||||
// A second signal fills the capacity-one channel and reports as
|
||||
// not taken — one pending abort is enough.
|
||||
assert!(registry.signal("job:rhema#7"));
|
||||
assert!(!registry.signal("job:rhema#7"));
|
||||
assert!(guard.take());
|
||||
|
||||
drop(guard);
|
||||
assert!(!registry.signal("job:rhema#7"), "the entry is gone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keys_abort_independently() {
|
||||
let registry = Arc::new(AbortRegistry::new());
|
||||
let _guard = registry.listen("job:rhema#7");
|
||||
assert!(!registry.signal("job:rhema#8"));
|
||||
assert!(registry.signal("job:rhema#7"));
|
||||
}
|
||||
}
|
||||
@@ -365,6 +365,12 @@ impl Daemon {
|
||||
// persona is shared, the workspaces are not. The environment
|
||||
// report lands in the store's directory at boot, below.
|
||||
let bootstrap = Arc::new(crate::bootstrap::Bootstrap::new(config.bootstrap_dir()?)?);
|
||||
// The pause gate: the keys the drivers hold, loaded from the
|
||||
// settings table, shared with the HTTP surface's pause route.
|
||||
let pause = Arc::new(crate::pause::PauseSet::load(settings.clone())?);
|
||||
// The abort registry: the per-key cut the handlers listen on,
|
||||
// shared with the HTTP surface's abort route.
|
||||
let abort = Arc::new(crate::abort::AbortRegistry::new());
|
||||
let forge_handler = ClawHandler::new(
|
||||
backends.clone(),
|
||||
workspace_root,
|
||||
@@ -374,18 +380,25 @@ impl Daemon {
|
||||
config.transcript_enabled(),
|
||||
tool_env.clone(),
|
||||
)
|
||||
.with_sandbox(sandbox.clone());
|
||||
.with_sandbox(sandbox.clone())
|
||||
.with_abort(abort.clone());
|
||||
// Three drivers over one store admit from the same table, so
|
||||
// each owns its slice of the key space: a forge pass must never
|
||||
// pick up a resident or job event (it would fail it, and
|
||||
// consume it), and the others likewise.
|
||||
// consume it), and the others likewise. Paused keys belong to
|
||||
// no driver: every predicate declines them, pass after pass,
|
||||
// until resume lifts the hold.
|
||||
let forge_driver = Arc::new(
|
||||
Driver::new(forge_dispatcher.clone(), Arc::new(forge_handler))
|
||||
.with_holder("rhema-claw")
|
||||
.owning(Arc::new(|key: &ResourceKey| {
|
||||
!crate::interactive::is_resident_key(key.as_str())
|
||||
&& !crate::jobs::is_job_key(key.as_str())
|
||||
})),
|
||||
.owning({
|
||||
let pause = pause.clone();
|
||||
Arc::new(move |key: &ResourceKey| {
|
||||
!crate::interactive::is_resident_key(key.as_str())
|
||||
&& !crate::jobs::is_job_key(key.as_str())
|
||||
&& !pause.is_paused(key.as_str())
|
||||
})
|
||||
}),
|
||||
);
|
||||
|
||||
// The consent table and its wake bridge: the `ask_secret` tool
|
||||
@@ -475,6 +488,7 @@ impl Daemon {
|
||||
config.transcript_enabled(),
|
||||
)
|
||||
.with_steer(steer.clone())
|
||||
.with_abort(abort.clone())
|
||||
.with_sandbox(sandbox.clone());
|
||||
let interactive_driver = Arc::new(
|
||||
Driver::new(
|
||||
@@ -482,9 +496,13 @@ impl Daemon {
|
||||
Arc::new(interactive_handler),
|
||||
)
|
||||
.with_holder("rhema-claw-interactive")
|
||||
.owning(Arc::new(|key: &ResourceKey| {
|
||||
crate::interactive::is_resident_key(key.as_str())
|
||||
})),
|
||||
.owning({
|
||||
let pause = pause.clone();
|
||||
Arc::new(move |key: &ResourceKey| {
|
||||
crate::interactive::is_resident_key(key.as_str())
|
||||
&& !pause.is_paused(key.as_str())
|
||||
})
|
||||
}),
|
||||
);
|
||||
// The coding jobs: one handler, one driver, one source. The
|
||||
// final text of a job's turn notifies the user's device, so the
|
||||
@@ -496,13 +514,17 @@ impl Daemon {
|
||||
config.max_turn_steps,
|
||||
config.transcript_enabled(),
|
||||
)
|
||||
.with_sandbox(sandbox.clone());
|
||||
.with_sandbox(sandbox.clone())
|
||||
.with_abort(abort.clone());
|
||||
let jobs_driver = Arc::new(
|
||||
Driver::new(jobs_dispatcher.clone(), Arc::new(jobs_handler))
|
||||
.with_holder("rhema-claw-jobs")
|
||||
.owning(Arc::new(|key: &ResourceKey| {
|
||||
crate::jobs::is_job_key(key.as_str())
|
||||
})),
|
||||
.owning({
|
||||
let pause = pause.clone();
|
||||
Arc::new(move |key: &ResourceKey| {
|
||||
crate::jobs::is_job_key(key.as_str()) && !pause.is_paused(key.as_str())
|
||||
})
|
||||
}),
|
||||
);
|
||||
crate::interactive::register_user(&interactive_dispatcher);
|
||||
|
||||
@@ -517,6 +539,9 @@ impl Daemon {
|
||||
bootstrap,
|
||||
hub,
|
||||
steer,
|
||||
pause,
|
||||
abort,
|
||||
jobs,
|
||||
backends.clone(),
|
||||
settings.clone(),
|
||||
identity,
|
||||
|
||||
@@ -87,6 +87,13 @@ pub struct ClawHandler {
|
||||
/// Where commands run: this host when absent, a remote sandbox when
|
||||
/// the surface selected one. Read per dispatch.
|
||||
sandbox: Option<Arc<SandboxState>>,
|
||||
/// The abort registry the sessions' abort route signals: a live
|
||||
/// turn cut at its await stashes what it committed and ends the
|
||||
/// dispatch as superseded, its comment never posted (see
|
||||
/// [`crate::abort`]). Private by default — a handler nobody shared
|
||||
/// a registry with never receives a signal — and shared through
|
||||
/// [`ClawHandler::with_abort`].
|
||||
abort: Arc<crate::abort::AbortRegistry>,
|
||||
clients: Mutex<HashMap<String, Arc<WatchClient>>>,
|
||||
}
|
||||
|
||||
@@ -111,6 +118,7 @@ impl ClawHandler {
|
||||
bootstrap,
|
||||
tool_env,
|
||||
sandbox: None,
|
||||
abort: Arc::new(crate::abort::AbortRegistry::new()),
|
||||
clients: Mutex::new(HashMap::new()),
|
||||
}
|
||||
}
|
||||
@@ -122,6 +130,14 @@ impl ClawHandler {
|
||||
self
|
||||
}
|
||||
|
||||
/// Shares the abort registry with the HTTP surface: the abort route
|
||||
/// signals it, and every forge dispatch this handler runs listens
|
||||
/// on it.
|
||||
pub fn with_abort(mut self, abort: Arc<crate::abort::AbortRegistry>) -> Self {
|
||||
self.abort = abort;
|
||||
self
|
||||
}
|
||||
|
||||
/// The forge client a dispatch key answers to:
|
||||
/// `"github:issue:acme/widgets#7"` resolves its watch record from the
|
||||
/// table at dispatch time — the table is the source of truth, not a
|
||||
@@ -308,10 +324,28 @@ impl ClawHandler {
|
||||
|
||||
let prompt = build_prompt(&key, &snapshot, &news, workspace.as_path(), role);
|
||||
let mut sink = TurnSink;
|
||||
let output = agent
|
||||
.turn(prompt, &mut sink)
|
||||
.await
|
||||
.map_err(|err| format!("turn for {key} failed: {err}"))?;
|
||||
// The abort listener rides the turn: a signal drops the future
|
||||
// at its current await — a streaming request, or a running
|
||||
// shell command, whose child dies with the drop. What the turn
|
||||
// committed so far is already the session (the commit hook),
|
||||
// so the stash below hands it to the next dispatch.
|
||||
let mut abort = self.abort.listen(&key);
|
||||
let turned = tokio::select! {
|
||||
output = agent.turn(prompt, &mut sink) => {
|
||||
Some(output.map_err(|err| format!("turn for {key} failed: {err}")))
|
||||
}
|
||||
_ = abort.wait() => None,
|
||||
};
|
||||
let output = match turned {
|
||||
Some(output) => output?,
|
||||
None => {
|
||||
// Cut, not failed: the thread gets no half-answer, and
|
||||
// the session keeps whatever the turn committed.
|
||||
ctx.session.core.driver_state = serde_json::to_value(agent.session())
|
||||
.map_err(|err| format!("session for {key} does not serialize: {err}"))?;
|
||||
return Ok(Outcome::Superseded);
|
||||
}
|
||||
};
|
||||
|
||||
// Stash before posting: the turn's work survives a failed comment.
|
||||
ctx.session.core.driver_state = serde_json::to_value(agent.session())
|
||||
|
||||
@@ -47,7 +47,7 @@ use rhema_claw_tools_contract::CONTRACT_HEADER;
|
||||
use rhema_claw_tools_contract::CONTRACT_VERSION;
|
||||
use rhema_core::ImageMediaType;
|
||||
use rhema_rsd::{
|
||||
Conflict, DispatchError, Dispatcher, IngestResult, KeyRecord, KeyState, ResourceKey,
|
||||
Conflict, DispatchError, Dispatcher, IngestResult, KeyRecord, KeyState, Outcome, ResourceKey,
|
||||
SqliteStore, Store,
|
||||
};
|
||||
use serde::{Deserialize, Deserializer};
|
||||
@@ -55,11 +55,13 @@ use serde_json::{Value, json};
|
||||
use tokio::sync::broadcast::error::RecvError;
|
||||
use tokio_stream::wrappers::ReceiverStream;
|
||||
|
||||
use crate::abort::AbortRegistry;
|
||||
use crate::backends::BackendRegistry;
|
||||
use crate::bootstrap::Bootstrap;
|
||||
use crate::hub::{EventHub, TurnEvent};
|
||||
use crate::interactive::WireImage;
|
||||
use crate::notifications::NotificationStore;
|
||||
use crate::pause::PauseSet;
|
||||
use crate::steer::SteerRegistry;
|
||||
use crate::task_store::TaskStore;
|
||||
use crate::watch_store::{ClawStore, validate_watch};
|
||||
@@ -106,6 +108,17 @@ pub struct ClawState {
|
||||
/// a chat message into a key whose turn is live cuts that turn
|
||||
/// short (see [`crate::steer`]).
|
||||
steer: Arc<SteerRegistry>,
|
||||
/// The pause gate the pause/resume routes write and every driver's
|
||||
/// ownership predicate reads: the keys whose dispatch is held (see
|
||||
/// [`crate::pause`]).
|
||||
pause: Arc<PauseSet>,
|
||||
/// The abort registry the abort route signals: the live turn it
|
||||
/// cuts ends as superseded (see [`crate::abort`]).
|
||||
abort: Arc<AbortRegistry>,
|
||||
/// The coding-job table the abort route reads when an idle
|
||||
/// `job:` key's queue is dropped: the row is the jobs' truth, so
|
||||
/// the row moves with the abort.
|
||||
jobs: Arc<crate::job_store::CodingJobStore>,
|
||||
backends: Arc<BackendRegistry>,
|
||||
settings: Arc<crate::settings::SettingsStore>,
|
||||
identity: Arc<crate::identity::IdentityStore>,
|
||||
@@ -162,6 +175,9 @@ impl ClawState {
|
||||
bootstrap: Arc<Bootstrap>,
|
||||
hub: Arc<EventHub>,
|
||||
steer: Arc<SteerRegistry>,
|
||||
pause: Arc<PauseSet>,
|
||||
abort: Arc<AbortRegistry>,
|
||||
jobs: Arc<crate::job_store::CodingJobStore>,
|
||||
backends: Arc<BackendRegistry>,
|
||||
settings: Arc<crate::settings::SettingsStore>,
|
||||
identity: Arc<crate::identity::IdentityStore>,
|
||||
@@ -186,6 +202,9 @@ impl ClawState {
|
||||
bootstrap,
|
||||
hub,
|
||||
steer,
|
||||
pause,
|
||||
abort,
|
||||
jobs,
|
||||
backends,
|
||||
settings,
|
||||
identity,
|
||||
@@ -203,7 +222,8 @@ impl ClawState {
|
||||
}
|
||||
|
||||
/// Every dispatch key with a record — interactive and forge alike,
|
||||
/// both dispatchers share one store — with its status.
|
||||
/// both dispatchers share one store — with its status and whether
|
||||
/// the pause gate holds it.
|
||||
pub fn sessions(&self) -> Result<Vec<Value>, DispatchError> {
|
||||
let mut sessions = Vec::new();
|
||||
for key in self.store.keys()? {
|
||||
@@ -214,6 +234,7 @@ impl ClawState {
|
||||
"revision": status.revision,
|
||||
"inbox_depth": status.inbox_depth,
|
||||
"last_outcome": status.last_outcome,
|
||||
"paused": self.pause.is_paused(status.key.as_str()),
|
||||
}));
|
||||
}
|
||||
Ok(sessions)
|
||||
@@ -234,6 +255,12 @@ impl ClawState {
|
||||
// leaves the transcript alone: the purge below is the one step this
|
||||
// side cannot undo, and it must never run for a session the 409 kept.
|
||||
let existed = self.dispatcher.forget(key)?;
|
||||
// The pause hold goes with the record: a key re-created under
|
||||
// the same name starts unpaused. Best-effort — the record and
|
||||
// the transcript are already gone, so a settings-row failure
|
||||
// here must not pretend the delete failed; a leftover row only
|
||||
// holds a session that does not exist.
|
||||
let _ = self.pause.resume(key.as_str());
|
||||
// Then the history, unconditionally — including the `Ok(false)` path,
|
||||
// where a record already gone left the transcript behind. Deleting
|
||||
// that transcript is the repair: a retried DELETE finishes a half-done
|
||||
@@ -263,6 +290,17 @@ impl ClawState {
|
||||
&self.steer
|
||||
}
|
||||
|
||||
/// The pause gate: the pause/resume routes write it, the sessions
|
||||
/// listing reads it.
|
||||
pub fn pause(&self) -> &PauseSet {
|
||||
&self.pause
|
||||
}
|
||||
|
||||
/// The abort registry: the abort route signals it.
|
||||
pub fn aborts(&self) -> &AbortRegistry {
|
||||
&self.abort
|
||||
}
|
||||
|
||||
/// The configured model — the shim's echo default.
|
||||
/// The backend registry: the provider list and the active pair.
|
||||
pub fn backends(&self) -> &BackendRegistry {
|
||||
@@ -307,6 +345,9 @@ pub fn router(state: ClawState) -> Router {
|
||||
let v1 = Router::new()
|
||||
.route("/sessions", get(sessions).post(sessions_create))
|
||||
.route("/sessions/{key}", delete(session_delete))
|
||||
.route("/sessions/{key}/pause", post(session_pause))
|
||||
.route("/sessions/{key}/resume", post(session_resume))
|
||||
.route("/sessions/{key}/abort", post(session_abort))
|
||||
.route(
|
||||
"/sessions/{key}/messages",
|
||||
post(messages).layer(axum::extract::DefaultBodyLimit::max(MAX_MESSAGE_BODY_BYTES)),
|
||||
@@ -633,6 +674,201 @@ async fn session_delete(State(state): State<ClawState>, Path(key): Path<String>)
|
||||
}
|
||||
}
|
||||
|
||||
/// The shared shape of the pause/resume routes' answer.
|
||||
fn pause_answer(key: &ResourceKey, paused: bool) -> Response {
|
||||
(
|
||||
StatusCode::OK,
|
||||
Json(json!({ "key": key.as_str(), "paused": paused })),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
/// `POST /v1/sessions/{key}/pause`: hold the key's dispatch. Queued
|
||||
/// work stays in the inbox, new work ingests as always, and every
|
||||
/// driver passes the key by until resume lifts the hold — a live turn
|
||||
/// is not cut by this (the lease predates the hold); the abort route
|
||||
/// is what cuts one. 404 when the inventory has no such key.
|
||||
async fn session_pause(State(state): State<ClawState>, Path(key): Path<String>) -> Response {
|
||||
// The key path's shape: one segment is the whole key, trimmed — a
|
||||
// key carrying `/` arrives only percent-encoded, which is what
|
||||
// every client of this surface sends. Empty after the trim is the
|
||||
// 400 the delete route answers too.
|
||||
let key = key.trim();
|
||||
if key.is_empty() {
|
||||
return (
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(json!({"error": "key is required"})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
let key = ResourceKey::from(key);
|
||||
match state.store.load(&key) {
|
||||
Ok(Some(_)) => {}
|
||||
Ok(None) => {
|
||||
return (
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(json!({"error": format!("no session {:?}", key.as_str())})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
Err(err) => return internal_error(err).into_response(),
|
||||
}
|
||||
match state.pause.pause(key.as_str()) {
|
||||
Ok(_) => pause_answer(&key, true),
|
||||
Err(err) => internal_error(err).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `POST /v1/sessions/{key}/resume`: lift the hold. The key's pending
|
||||
/// work dispatches on the first driver pass after this — the debounce
|
||||
/// window it may still owe runs first, as it always did. Idempotent:
|
||||
/// resuming an unheld key answers `{"paused": false}`, and 404s only
|
||||
/// when the inventory has no such key at all.
|
||||
async fn session_resume(State(state): State<ClawState>, Path(key): Path<String>) -> Response {
|
||||
// The key path's shape: one segment is the whole key, trimmed — a
|
||||
// key carrying `/` arrives only percent-encoded, which is what
|
||||
// every client of this surface sends. Empty after the trim is the
|
||||
// 400 the delete route answers too.
|
||||
let key = key.trim();
|
||||
if key.is_empty() {
|
||||
return (
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(json!({"error": "key is required"})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
let key = ResourceKey::from(key);
|
||||
match state.store.load(&key) {
|
||||
Ok(Some(_)) => {}
|
||||
Ok(None) => {
|
||||
return (
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(json!({"error": format!("no session {:?}", key.as_str())})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
Err(err) => return internal_error(err).into_response(),
|
||||
}
|
||||
match state.pause.resume(key.as_str()) {
|
||||
Ok(_) => pause_answer(&key, false),
|
||||
Err(err) => internal_error(err).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `POST /v1/sessions/{key}/abort`: stop the key's work now. Two shapes,
|
||||
/// one route:
|
||||
///
|
||||
/// - a live lease: the dispatch is signalled through the abort registry
|
||||
/// and its turn is dropped at its current await — the handler repairs
|
||||
/// the dangling calls, stashes what it committed, and releases the
|
||||
/// lease as superseded. Work that sat behind the turn in the inbox
|
||||
/// stays there, still queued.
|
||||
/// - an idle key with a queue: the queue is drained and dropped under
|
||||
/// a throwaway lease, so nothing dispatches; a `job:` key's row moves
|
||||
/// to failed/`aborted` with it, the row being the jobs' truth.
|
||||
///
|
||||
/// The answer carries what happened: `{"key", "cut", "dropped"}`. A
|
||||
/// `cut` of `false` with a zero `dropped` is the idempotent no-op —
|
||||
/// nothing was running and nothing was queued. The whole route is
|
||||
/// race-tolerant by construction: a key that leaves the leased state
|
||||
/// between the read and the signal drains through the idle path, and a
|
||||
/// key that enters it lands in the dispatcher's own conflicts below.
|
||||
async fn session_abort(State(state): State<ClawState>, Path(key): Path<String>) -> Response {
|
||||
// The key path's shape: one segment is the whole key, trimmed — a
|
||||
// key carrying `/` arrives only percent-encoded, which is what
|
||||
// every client of this surface sends. Empty after the trim is the
|
||||
// 400 the delete route answers too.
|
||||
let key = key.trim();
|
||||
if key.is_empty() {
|
||||
return (
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(json!({"error": "key is required"})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
let key = ResourceKey::from(key);
|
||||
let record = match state.store.load(&key) {
|
||||
Ok(Some(record)) => record,
|
||||
Ok(None) => {
|
||||
return (
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(json!({"error": format!("no session {:?}", key.as_str())})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
Err(err) => return internal_error(err).into_response(),
|
||||
};
|
||||
let leased = record.lease.is_some();
|
||||
if leased && state.aborts().signal(key.as_str()) {
|
||||
// A job row moves with its cut: the handler's own abort path
|
||||
// lands it, so nothing to do here but the answer.
|
||||
return (
|
||||
StatusCode::OK,
|
||||
Json(json!({ "key": key.as_str(), "cut": true, "dropped": 0 })),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
// Idle, or leased-but-unsignalable (the turn released between the
|
||||
// read and the signal, or the lease lapsed unswept — `acquire`
|
||||
// sweeps both). Whatever is queued drains and drops; nothing runs.
|
||||
if record.inbox.is_empty() {
|
||||
return (
|
||||
StatusCode::OK,
|
||||
Json(json!({ "key": key.as_str(), "cut": false, "dropped": 0 })),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
let (lease, _session) = match state.dispatcher.acquire(key.clone(), "claw-abort") {
|
||||
Ok(acquired) => acquired,
|
||||
// The key went busy between the read and the acquire: a turn
|
||||
// holds it now, and that turn is what a retry aborts.
|
||||
Err(DispatchError::Conflict(_)) | Err(DispatchError::AtCapacity { .. }) => {
|
||||
return (
|
||||
StatusCode::CONFLICT,
|
||||
Json(json!({"error": format!(
|
||||
"session {:?} took a lease mid-abort; retry to cut it",
|
||||
key.as_str()
|
||||
)})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
Err(err) => return internal_error(err).into_response(),
|
||||
};
|
||||
let dropped = match state.dispatcher.poll_inbox(&lease) {
|
||||
Ok(items) => items.len(),
|
||||
Err(err) => return internal_error(err).into_response(),
|
||||
};
|
||||
if let Err(err) = state.dispatcher.release(&lease, Outcome::Superseded) {
|
||||
return internal_error(err).into_response();
|
||||
}
|
||||
// The jobs' truth moves with the queue it lost: a row whose
|
||||
// delivery was just dropped is failed, not queued, or it would sit
|
||||
// live forever with nothing to run it. Quietly — the operator who
|
||||
// aborted it is the one being told.
|
||||
if let Some((instance, job_id)) = crate::jobs::parse_job_key(&key)
|
||||
&& let Ok(Some(job)) = state.jobs.job(job_id)
|
||||
&& job.status.is_live()
|
||||
&& let Err(err) = state.jobs.fail(job_id, "aborted")
|
||||
{
|
||||
eprintln!("[claw] abort: job {job_id} on {instance:?} could not be failed: {err}");
|
||||
}
|
||||
// The transcript shows the cut: the dropped questions are already
|
||||
// recorded, and without this marker they read as questions the
|
||||
// daemon ignored.
|
||||
state.hub.emit(
|
||||
&key,
|
||||
TurnEvent::TurnDone {
|
||||
reply: None,
|
||||
outcome: "aborted".to_owned(),
|
||||
},
|
||||
);
|
||||
(
|
||||
StatusCode::OK,
|
||||
Json(json!({ "key": key.as_str(), "cut": false, "dropped": dropped })),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
/// The setup badge: which of SOUL.md and USER.md exist, read live — a
|
||||
/// UI badges first-run setup from it while the onboarding offer is
|
||||
/// still open.
|
||||
|
||||
@@ -129,7 +129,8 @@ pub enum TurnEvent {
|
||||
/// The turn's final assistant text, when it produced one.
|
||||
reply: Option<String>,
|
||||
/// `handled` or `failed` — or `steered`, when a chat message
|
||||
/// cut the turn short and a next turn runs instead of it.
|
||||
/// cut the turn short and a next turn runs instead of it — or
|
||||
/// `aborted`, when the operator cut it and nothing follows.
|
||||
outcome: String,
|
||||
},
|
||||
/// The agent asked the human something only they can answer: a
|
||||
|
||||
@@ -62,6 +62,14 @@
|
||||
//! the conversation shows the question, the cut, and the answer that
|
||||
//! replaced the rest of the interrupted work, exactly the shape
|
||||
//! rhema-code's UI draws for a steered turn.
|
||||
//!
|
||||
//! **Aborting** rides the same interrupt and ends instead of looping:
|
||||
//! a signal from the abort registry ([`crate::abort`]) drops the turn
|
||||
//! future at its await, the dangling calls close, the session stashes,
|
||||
//! and the dispatch releases as superseded with the `aborted` outcome
|
||||
//! on the stream. Unlike a steer signal, an abort carries no inbox
|
||||
//! message, so a pending abort is honored between rounds, not cleared
|
||||
//! with the stale steer signals.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::num::NonZeroU32;
|
||||
@@ -81,6 +89,7 @@ use rhema_memory::{MemoryResolver, MemoryStore, Scope};
|
||||
use rhema_rsd::{Dispatcher, Event, KeyFn, Outcome, ResourceKey};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::abort::{AbortGuard, AbortRegistry};
|
||||
use crate::backends::BackendRegistry;
|
||||
use crate::bootstrap::{Bootstrap, DEFAULT_SYSTEM_MD, render_system};
|
||||
use crate::hub::{EventHub, TurnEvent, UserImage};
|
||||
@@ -238,6 +247,12 @@ pub struct InteractiveHandler {
|
||||
/// registry with never receives a signal — and shared with the
|
||||
/// HTTP surface through [`InteractiveHandler::with_steer`].
|
||||
steer: Arc<SteerRegistry>,
|
||||
/// The abort registry the sessions' abort route signals: a live
|
||||
/// turn cut at its await ends the dispatch as superseded (see
|
||||
/// [`crate::abort`]). Built private by
|
||||
/// [`InteractiveHandler::new`], shared through
|
||||
/// [`InteractiveHandler::with_abort`].
|
||||
abort: Arc<AbortRegistry>,
|
||||
/// The notification table: the `notify` tool writes it, and
|
||||
/// non-interactive replies auto-notify through it.
|
||||
notifications: Arc<NotificationStore>,
|
||||
@@ -307,6 +322,7 @@ impl InteractiveHandler {
|
||||
bootstrap_resolver,
|
||||
hub,
|
||||
steer: Arc::new(SteerRegistry::new()),
|
||||
abort: Arc::new(AbortRegistry::new()),
|
||||
notifications,
|
||||
attachments,
|
||||
max_turn_steps,
|
||||
@@ -387,6 +403,15 @@ impl InteractiveHandler {
|
||||
self
|
||||
}
|
||||
|
||||
/// Shares `abort` with the HTTP surface: the abort route signals it,
|
||||
/// and every dispatch chain this handler runs listens on it.
|
||||
/// Without this call the handler keeps the constructor's private
|
||||
/// registry, which no route can reach.
|
||||
pub fn with_abort(mut self, abort: Arc<AbortRegistry>) -> Self {
|
||||
self.abort = abort;
|
||||
self
|
||||
}
|
||||
|
||||
/// The workspace the prompt names: the host path locally, the
|
||||
/// sandbox root when commands run elsewhere.
|
||||
fn workspace(&self) -> PathBuf {
|
||||
@@ -432,13 +457,16 @@ impl InteractiveHandler {
|
||||
}
|
||||
|
||||
/// One round: drain, restore, turn, stash, reply. The turn runs
|
||||
/// under the steer select, so a round that was interrupted comes
|
||||
/// back as [`Round::Steered`] with the session stashed and the
|
||||
/// dangling calls closed.
|
||||
/// under the steer/abort select, so a round that was interrupted
|
||||
/// comes back as [`Round::Steered`] or [`Round::Aborted`] with the
|
||||
/// session stashed and the dangling calls closed — steered, the
|
||||
/// caller owes the inbox another round; aborted, the caller ends
|
||||
/// the chain.
|
||||
async fn dispatch(
|
||||
&self,
|
||||
ctx: &mut SessionContext,
|
||||
steer: &mut SteerGuard,
|
||||
abort: &mut AbortGuard,
|
||||
round: usize,
|
||||
) -> Result<Round, String> {
|
||||
let key = ctx.key.as_str().to_owned();
|
||||
@@ -658,6 +686,7 @@ impl InteractiveHandler {
|
||||
&tools,
|
||||
self.max_turn_steps,
|
||||
));
|
||||
let mut aborted = false;
|
||||
let finished = tokio::select! {
|
||||
result = &mut turn => match steer.take() {
|
||||
// A message that raced the completion steers the next
|
||||
@@ -668,6 +697,13 @@ impl InteractiveHandler {
|
||||
),
|
||||
},
|
||||
_ = steer.wait() => None,
|
||||
_ = abort.wait() => {
|
||||
// The operator cut the turn: no next round's input is
|
||||
// coming, so the caller ends the chain rather than
|
||||
// looping.
|
||||
aborted = true;
|
||||
None
|
||||
}
|
||||
};
|
||||
drop(turn);
|
||||
// An interrupted turn can leave committed calls without
|
||||
@@ -684,6 +720,7 @@ impl InteractiveHandler {
|
||||
match finished {
|
||||
Some(Ok(output)) => Ok(Round::Done(Ok(final_text(&output.message)))),
|
||||
Some(Err(reason)) => Err(reason),
|
||||
None if aborted => Ok(Round::Aborted),
|
||||
None => Ok(Round::Steered),
|
||||
}
|
||||
}
|
||||
@@ -693,19 +730,27 @@ impl InteractiveHandler {
|
||||
impl Handler for InteractiveHandler {
|
||||
async fn handle(&self, ctx: &mut SessionContext) -> Outcome {
|
||||
let key = ctx.key.clone();
|
||||
// The listener lives across the whole chain: one lease, one
|
||||
// listener, every steered round under it. `Drop` unregisters
|
||||
// before the outcome releases the lease, so no signal can
|
||||
// address a turn that no longer runs.
|
||||
// The listeners live across the whole chain: one lease, one
|
||||
// listener each, every steered round under them. `Drop`
|
||||
// unregisters before the outcome releases the lease, so no
|
||||
// signal can address a turn that no longer runs.
|
||||
let mut steer = self.steer.listen(key.as_str());
|
||||
let mut abort = self.abort.listen(key.as_str());
|
||||
let mut round = 1;
|
||||
let mut aborted = false;
|
||||
let finished = loop {
|
||||
// Stale signals first: the route signals only after its
|
||||
// ingest, so anything pending here is already in the inbox
|
||||
// waiting for this round's drain — a signal must never cut
|
||||
// the round it precedes.
|
||||
// the round it precedes. An abort is the opposite: it
|
||||
// carries no inbox message, so a pending one is honored
|
||||
// here, not cleared.
|
||||
steer.clear();
|
||||
match self.dispatch(ctx, &mut steer, round).await {
|
||||
if abort.take() {
|
||||
aborted = true;
|
||||
break Ok(None);
|
||||
}
|
||||
match self.dispatch(ctx, &mut steer, &mut abort, round).await {
|
||||
Ok(Round::Done(reply)) => break reply,
|
||||
// A steered round that drained nothing: the interrupt
|
||||
// already happened, the chain just ends instead of
|
||||
@@ -723,10 +768,29 @@ impl Handler for InteractiveHandler {
|
||||
);
|
||||
round += 1;
|
||||
}
|
||||
Ok(Round::Aborted) => {
|
||||
aborted = true;
|
||||
break Ok(None);
|
||||
}
|
||||
Err(reason) => break Err(reason),
|
||||
}
|
||||
};
|
||||
drop(steer);
|
||||
drop(abort);
|
||||
if aborted {
|
||||
// The end marker matters most when the run was cut: a
|
||||
// stream that just goes quiet is indistinguishable from a
|
||||
// hang. Superseded, not failed — the work is no longer
|
||||
// wanted, exactly the outcome's own words.
|
||||
self.hub.emit(
|
||||
&key,
|
||||
TurnEvent::TurnDone {
|
||||
reply: None,
|
||||
outcome: "aborted".to_owned(),
|
||||
},
|
||||
);
|
||||
return Outcome::Superseded;
|
||||
}
|
||||
match finished {
|
||||
Ok(reply) => {
|
||||
self.auto_notify(&key, reply.as_deref());
|
||||
@@ -777,14 +841,17 @@ impl InteractiveHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/// One dispatch round's shape. A steered round ended in an interrupt:
|
||||
/// One dispatch round's shape. A steered or aborted round ended in an
|
||||
/// interrupt: the session stashed, the dangling calls closed — steered,
|
||||
/// the caller owes the inbox another round on the same lease, same
|
||||
/// session, same stream.
|
||||
/// session, same stream; aborted, the caller ends the chain.
|
||||
enum Round {
|
||||
/// The turn ran to its end; the final reply text.
|
||||
Done(Result<Option<String>, String>),
|
||||
/// A steered message cut the turn short.
|
||||
Steered,
|
||||
/// The operator's abort cut the turn short.
|
||||
Aborted,
|
||||
/// A steered round whose inbox drained empty — the belt-and-braces
|
||||
/// exit for a signal whose message raced the previous round's
|
||||
/// drain: end the chain quietly, fail nothing.
|
||||
@@ -1936,6 +2003,127 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// An abort signal cuts a live turn and ends the chain: the turn
|
||||
/// closes on the stream with the `aborted` outcome, the dispatch
|
||||
/// releases as superseded, and nothing follows — unlike the steer,
|
||||
/// which loops onto its next round.
|
||||
#[tokio::test]
|
||||
async fn an_abort_signal_cuts_the_live_turn_and_ends_the_chain() {
|
||||
let gate = Arc::new(Gate::default());
|
||||
let registry = Arc::new(crate::abort::AbortRegistry::new());
|
||||
let hub = Arc::new(EventHub::default());
|
||||
let workspace = tempfile::tempdir().expect("tempdir");
|
||||
let notifications = notifications();
|
||||
let extensions = test_extensions(
|
||||
hub.clone(),
|
||||
Arc::new(ClawStore::in_memory().expect("store opens")),
|
||||
notifications.clone(),
|
||||
tasks(),
|
||||
jobs(),
|
||||
accounts(),
|
||||
consents(),
|
||||
bridge(),
|
||||
attachments(),
|
||||
phone(),
|
||||
identity(),
|
||||
&workspace.path().join("interactive"),
|
||||
);
|
||||
let handler = InteractiveHandler::new(
|
||||
test_registry(Arc::new(GatedProvider::new(gate.clone()))),
|
||||
workspace.path().join("interactive"),
|
||||
Arc::new(rhema_memory::VolatileStore::new()),
|
||||
Arc::new(Bootstrap::new(workspace.path().join("bootstrap")).expect("store opens")),
|
||||
hub.clone(),
|
||||
notifications.clone(),
|
||||
attachments(),
|
||||
crate::config::DEFAULT_MAX_TURN_STEPS,
|
||||
extensions,
|
||||
true,
|
||||
)
|
||||
.with_abort(registry.clone());
|
||||
|
||||
let volatile = Arc::new(VolatileStore::new());
|
||||
let dispatcher = Arc::new(Dispatcher::new(
|
||||
DispatcherConfig {
|
||||
debounce_window_millis: 0,
|
||||
..DispatcherConfig::default()
|
||||
},
|
||||
Arc::new(rhema_rsd::SystemClock),
|
||||
volatile.clone(),
|
||||
));
|
||||
register_user(&dispatcher);
|
||||
let key = Key::from("interactive:web");
|
||||
let mut receiver = hub.subscribe(&key);
|
||||
dispatcher
|
||||
.ingest(user_event(key.as_str(), "hello", &[], &[]))
|
||||
.expect("ingests");
|
||||
let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler))
|
||||
.with_holder("test");
|
||||
|
||||
// The pass runs off the test task; the generation parks in the
|
||||
// gate once it is in flight — the turn the abort cuts.
|
||||
let pass = tokio::spawn(async move { driver.run_once().await });
|
||||
let mut in_flight = gate.in_flight_rx();
|
||||
while !*in_flight.borrow_and_update() {
|
||||
in_flight
|
||||
.changed()
|
||||
.await
|
||||
.expect("the in-flight sender lives");
|
||||
}
|
||||
|
||||
assert!(registry.signal(key.as_str()));
|
||||
|
||||
// Superseded, not handled: the work is no longer wanted.
|
||||
assert_eq!(
|
||||
pass.await.expect("the pass joins").expect("the pass runs"),
|
||||
vec![RsdOutcome::Superseded]
|
||||
);
|
||||
|
||||
// Stream order: the question, then the abort, and nothing
|
||||
// after it — no steered round, no answer.
|
||||
assert_eq!(
|
||||
receiver.try_recv().unwrap(),
|
||||
TurnEvent::UserMessage {
|
||||
text: "hello".into(),
|
||||
images: Vec::new(),
|
||||
pastes: Vec::new()
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
receiver.try_recv().unwrap(),
|
||||
TurnEvent::TurnDone {
|
||||
reply: None,
|
||||
outcome: "aborted".into()
|
||||
}
|
||||
);
|
||||
assert!(
|
||||
receiver.try_recv().is_err(),
|
||||
"the chain ended: nothing follows the cut"
|
||||
);
|
||||
|
||||
// The key is back to idle with an empty inbox, and the
|
||||
// conversation keeps the question the turn never answered.
|
||||
assert_eq!(
|
||||
dispatcher.status(&key).expect("status reads").state,
|
||||
KeyState::Idle
|
||||
);
|
||||
let record = rhema_rsd::Store::load(volatile.as_ref(), &key)
|
||||
.expect("the record loads")
|
||||
.expect("the key has a record");
|
||||
let stashed: Session =
|
||||
serde_json::from_value(record.session.expect("a session").core.driver_state)
|
||||
.expect("the stash parses");
|
||||
let turns: Vec<(CoreRole, &str)> = stashed
|
||||
.history
|
||||
.iter()
|
||||
.filter_map(|message| match &message.content[0] {
|
||||
Content::Text(text) => Some((message.role, text.as_str())),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(turns, [(CoreRole::User, "hello")]);
|
||||
}
|
||||
|
||||
/// The steer test's synchronization: the provider announces the
|
||||
/// generation's arrival.
|
||||
struct Gate {
|
||||
|
||||
@@ -147,6 +147,12 @@ pub struct CodingJobHandler {
|
||||
/// Where commands run: this host when absent, a remote sandbox when
|
||||
/// the surface selected one. Read per job.
|
||||
sandbox: Option<Arc<SandboxState>>,
|
||||
/// The abort registry the sessions' abort route signals: a live job
|
||||
/// turn cut at its await stashes the conversation and lands the row
|
||||
/// as failed with `aborted` (see [`crate::abort`]). Private by
|
||||
/// default — a handler nobody shared a registry with never receives
|
||||
/// a signal — and shared through [`CodingJobHandler::with_abort`].
|
||||
abort: Arc<crate::abort::AbortRegistry>,
|
||||
}
|
||||
|
||||
impl CodingJobHandler {
|
||||
@@ -167,6 +173,7 @@ impl CodingJobHandler {
|
||||
max_turn_steps,
|
||||
transcript,
|
||||
sandbox: None,
|
||||
abort: Arc::new(crate::abort::AbortRegistry::new()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,10 +184,24 @@ impl CodingJobHandler {
|
||||
self
|
||||
}
|
||||
|
||||
/// Shares the abort registry with the HTTP surface: the abort route
|
||||
/// signals it, and every job dispatch this handler runs listens on
|
||||
/// it.
|
||||
pub fn with_abort(mut self, abort: Arc<crate::abort::AbortRegistry>) -> Self {
|
||||
self.abort = abort;
|
||||
self
|
||||
}
|
||||
|
||||
/// One dispatch, failed with a reason on any step; every failure
|
||||
/// lands in the job row before it lands in the outcome, so the
|
||||
/// model's `status` read and the user's notification agree.
|
||||
async fn dispatch(&self, ctx: &mut SessionContext) -> Result<Outcome, String> {
|
||||
// The abort listener arms first, before any of the lookups and
|
||||
// file work below: the route signals the moment it sees the
|
||||
// lease, and a listener that arrives after the agent is built
|
||||
// would let an early abort fall through as a no-op. One listener
|
||||
// per dispatch is enough — the lease forbids a second one.
|
||||
let mut abort = self.abort.listen(ctx.key.as_str());
|
||||
// Poll to live, as every handler does — and here the poll is also
|
||||
// what closes the dispatch. A job key carries exactly one kind of
|
||||
// item, the row's own delivery, and those items are drained and
|
||||
@@ -281,16 +302,37 @@ impl CodingJobHandler {
|
||||
agent.set_commit_hook(Some(ctx.commit_hook()));
|
||||
|
||||
let mut sink = JobSink;
|
||||
let output = match agent.turn(&job.prompt, &mut sink).await {
|
||||
Ok(output) => output,
|
||||
Err(err) => {
|
||||
let reason = format!("the coding turn for {instance_name:?} failed: {err}");
|
||||
// The abort listener rides the turn: a signal drops the future
|
||||
// at its current await — a streaming request, or a running
|
||||
// shell command, whose child dies with the drop. Armed at
|
||||
// dispatch entry, above.
|
||||
let turned = tokio::select! {
|
||||
output = agent.turn(&job.prompt, &mut sink) => {
|
||||
Some(output.map_err(|err| {
|
||||
format!("the coding turn for {instance_name:?} failed: {err}")
|
||||
}))
|
||||
}
|
||||
_ = abort.wait() => None,
|
||||
};
|
||||
let output = match turned {
|
||||
Some(Ok(output)) => output,
|
||||
Some(Err(err)) => {
|
||||
let reason = err;
|
||||
// The conversation up to the failure is still the
|
||||
// instance's: saved, so a follow-up run continues it.
|
||||
self.save_session(&instance_name, &agent);
|
||||
self.fail(job_id, &instance_name, &reason);
|
||||
return Ok(Outcome::Failed(reason));
|
||||
}
|
||||
None => {
|
||||
// Cut, not failed: the row says `aborted`, the
|
||||
// conversation keeps whatever the turn committed, and
|
||||
// the outcome is superseded — the work is no longer
|
||||
// wanted, exactly the outcome's own words.
|
||||
self.save_session(&instance_name, &agent);
|
||||
self.fail(job_id, &instance_name, "aborted");
|
||||
return Ok(Outcome::Superseded);
|
||||
}
|
||||
};
|
||||
self.save_session(&instance_name, &agent);
|
||||
let reply = final_text(&output.message).ok_or_else(|| {
|
||||
@@ -397,6 +439,73 @@ mod tests {
|
||||
)
|
||||
}
|
||||
|
||||
/// A provider whose one generation parks forever — the request an
|
||||
/// abort interrupts, released only by the drop.
|
||||
struct ParkingProvider;
|
||||
|
||||
#[rhema_autonomous_agent::async_trait]
|
||||
impl rhema_core::ModelProvider for ParkingProvider {
|
||||
async fn complete(
|
||||
&self,
|
||||
_request: rhema_core::ModelRequest,
|
||||
_sink: &mut dyn rhema_core::EventSink,
|
||||
) -> Result<rhema_core::ModelOutput, rhema_core::ProviderError> {
|
||||
std::future::pending::<()>().await;
|
||||
unreachable!("the pending future never resolves")
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_abort_signal_cuts_the_running_job_and_fails_the_row() {
|
||||
let workspace = tempdir();
|
||||
let store = Arc::new(CodingJobStore::in_memory().unwrap());
|
||||
store
|
||||
.add_instance("rhema", workspace.to_str().unwrap())
|
||||
.unwrap();
|
||||
let job = store.enqueue("rhema", "fix the lint").unwrap();
|
||||
let notifications = Arc::new(NotificationStore::in_memory().unwrap());
|
||||
let provider: Arc<dyn rhema_core::ModelProvider> = Arc::new(ParkingProvider);
|
||||
let backends = Arc::new(
|
||||
BackendRegistry::new(vec![Backend::headless("mock", provider)], None)
|
||||
.expect("a single mock backend always constructs"),
|
||||
);
|
||||
let abort = Arc::new(crate::abort::AbortRegistry::new());
|
||||
let handler = CodingJobHandler::new(
|
||||
backends,
|
||||
store.clone(),
|
||||
notifications.clone(),
|
||||
NonZeroU32::new(16).unwrap(),
|
||||
true,
|
||||
)
|
||||
.with_abort(abort.clone());
|
||||
let (source, driver, _dispatcher) = harness(store.clone(), handler);
|
||||
assert_eq!(source.detect().await.unwrap(), 1);
|
||||
|
||||
// The job runs off the test task; the abort lands while the
|
||||
// generation is parked.
|
||||
let pass = tokio::spawn(async move { driver.run_once().await });
|
||||
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
|
||||
while store.job(job.id).unwrap().unwrap().status != JobStatus::Running {
|
||||
assert!(
|
||||
tokio::time::Instant::now() < deadline,
|
||||
"the job never started"
|
||||
);
|
||||
tokio::time::sleep(std::time::Duration::from_millis(5)).await;
|
||||
}
|
||||
assert!(abort.signal(&job_key("rhema", job.id)));
|
||||
|
||||
// Superseded, not failed-and-retried: the work is no longer
|
||||
// wanted, and the row — the jobs' truth — says aborted.
|
||||
assert_eq!(pass.await.unwrap().unwrap(), vec![Outcome::Superseded]);
|
||||
let row = store.job(job.id).unwrap().unwrap();
|
||||
assert_eq!(row.status, JobStatus::Failed);
|
||||
assert_eq!(row.result.as_deref(), Some("aborted"));
|
||||
// The user still hears about it.
|
||||
let pending = notifications.pending(DEFAULT_DEVICE, 0).unwrap();
|
||||
assert_eq!(pending.len(), 1);
|
||||
assert!(pending[0].body.contains("aborted"));
|
||||
}
|
||||
|
||||
fn reply(text: &str) -> ModelOutput {
|
||||
ModelOutput {
|
||||
message: CoreMessage::text(Role::Assistant, text),
|
||||
|
||||
@@ -70,6 +70,7 @@
|
||||
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
pub mod abort;
|
||||
pub mod accounts_tools;
|
||||
pub mod attachments;
|
||||
pub mod backends;
|
||||
@@ -95,6 +96,7 @@ pub mod mock;
|
||||
pub mod notifications;
|
||||
pub mod notify_tools;
|
||||
pub mod openai;
|
||||
pub mod pause;
|
||||
pub mod phone;
|
||||
pub mod sandbox;
|
||||
pub mod settings;
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
//! The pause gate: dispatch keys the drivers hold — the inventory's
|
||||
//! pause/resume, wired through the HTTP surface.
|
||||
//!
|
||||
//! Pausing is an operator's hold, not a dispatcher state: rhema-rsd's
|
||||
//! state machine has idle, leased and re-acquire, and none of them means
|
||||
//! "keep the events, run nothing". So the hold lives beside the store:
|
||||
//! a set of keys, persisted in the settings table (`paused:<key>` rows,
|
||||
//! the same table the active backend pair lives in), checked by every
|
||||
//! driver's ownership predicate. A paused key ingests as always — its
|
||||
//! inbox accumulates, its debounce opens, `admit` offers it — and every
|
||||
//! driver declines it, pass after pass, until resume lifts the hold.
|
||||
//! Nothing is dropped and nothing runs; the pending work dispatches on
|
||||
//! the first pass after the resume.
|
||||
//!
|
||||
//! The in-memory set is the read side (a predicate call is a lock and a
|
||||
//! contains); the settings rows are the truth a restart reloads. A live
|
||||
//! turn is not paused by this — the lease it holds was granted before
|
||||
//! the hold, and it runs to its end; the abort surface is what cuts a
|
||||
//! running turn (see [`crate::abort`]).
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
use crate::settings::{SettingsError, SettingsStore};
|
||||
|
||||
/// The settings-row prefix one paused key lives under: `paused:<key>`,
|
||||
/// value `1`. The prefix is stripped back off on load.
|
||||
const SETTINGS_PREFIX: &str = "paused:";
|
||||
|
||||
/// The keys whose dispatch is on hold, in memory over the settings
|
||||
/// table. Shareable: every method takes `&self`, the set serializes on
|
||||
/// its mutex, and the whole thing rides an `Arc` through the daemon and
|
||||
/// the HTTP surface.
|
||||
pub struct PauseSet {
|
||||
settings: Arc<SettingsStore>,
|
||||
live: Mutex<BTreeSet<String>>,
|
||||
}
|
||||
|
||||
impl PauseSet {
|
||||
/// Loads the set over `settings`: every `paused:` row becomes one
|
||||
/// held key. The daemon calls this once at assembly; a restart
|
||||
/// resumes holding whatever was held.
|
||||
pub fn load(settings: Arc<SettingsStore>) -> Result<Self, SettingsError> {
|
||||
let rows = settings.rows_by_prefix(SETTINGS_PREFIX)?;
|
||||
let live = rows
|
||||
.into_iter()
|
||||
.map(|(key, _)| key[SETTINGS_PREFIX.len()..].to_owned())
|
||||
.collect::<BTreeSet<_>>();
|
||||
Ok(Self {
|
||||
settings,
|
||||
live: Mutex::new(live),
|
||||
})
|
||||
}
|
||||
|
||||
/// Holds `key`'s dispatch. `Ok(true)` when the hold is new, `Ok(false)`
|
||||
/// when the key was already held — the route can answer idempotent.
|
||||
pub fn pause(&self, key: &str) -> Result<bool, SettingsError> {
|
||||
let fresh = self
|
||||
.live
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.insert(key.to_owned());
|
||||
if fresh && let Err(err) = self.settings.set(&format!("{SETTINGS_PREFIX}{key}"), "1") {
|
||||
// The hold is one fact in two places: a row that cannot be
|
||||
// written takes the in-memory half back with it, so a
|
||||
// restart cannot disagree with what the caller was told.
|
||||
self.live
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.remove(key);
|
||||
return Err(err);
|
||||
}
|
||||
Ok(fresh)
|
||||
}
|
||||
|
||||
/// Lifts `key`'s hold. `Ok(true)` when a hold was lifted, `Ok(false)`
|
||||
/// when the key was not held.
|
||||
pub fn resume(&self, key: &str) -> Result<bool, SettingsError> {
|
||||
let lifted = self
|
||||
.live
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.remove(key);
|
||||
if lifted && let Err(err) = self.settings.delete(&format!("{SETTINGS_PREFIX}{key}")) {
|
||||
// Same agreement as `pause`: a row that cannot be deleted
|
||||
// puts the hold back, where it was.
|
||||
self.live
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.insert(key.to_owned());
|
||||
return Err(err);
|
||||
}
|
||||
Ok(lifted)
|
||||
}
|
||||
|
||||
/// Whether `key` is held — the drivers' predicate check, one lock
|
||||
/// and a contains.
|
||||
pub fn is_paused(&self, key: &str) -> bool {
|
||||
self.live
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.contains(key)
|
||||
}
|
||||
|
||||
/// Every held key, ascending — the ops view.
|
||||
pub fn keys(&self) -> Vec<String> {
|
||||
self.live
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.iter()
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn store() -> Arc<SettingsStore> {
|
||||
Arc::new(SettingsStore::in_memory().expect("in-memory settings"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pause_persists_and_reloads() {
|
||||
let settings = store();
|
||||
let pause = PauseSet::load(settings.clone()).unwrap();
|
||||
assert!(pause.pause("job:rhema#7").unwrap());
|
||||
assert!(pause.is_paused("job:rhema#7"));
|
||||
assert!(!pause.is_paused("interactive:web"));
|
||||
|
||||
// A fresh set over the same table starts where the last left off.
|
||||
let reloaded = PauseSet::load(settings).unwrap();
|
||||
assert!(reloaded.is_paused("job:rhema#7"));
|
||||
assert_eq!(reloaded.keys(), vec!["job:rhema#7".to_owned()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resume_lifts_the_hold_and_clears_the_row() {
|
||||
let settings = store();
|
||||
let pause = PauseSet::load(settings.clone()).unwrap();
|
||||
pause.pause("interactive:web").unwrap();
|
||||
assert!(pause.resume("interactive:web").unwrap());
|
||||
assert!(!pause.is_paused("interactive:web"));
|
||||
assert!(!pause.resume("interactive:web").unwrap(), "already lifted");
|
||||
assert!(
|
||||
PauseSet::load(settings).unwrap().keys().is_empty(),
|
||||
"nothing lingers in the table"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pausing_twice_is_one_hold() {
|
||||
let settings = store();
|
||||
let pause = PauseSet::load(settings).unwrap();
|
||||
assert!(pause.pause("gitea:acme/widgets#3").unwrap());
|
||||
assert!(!pause.pause("gitea:acme/widgets#3").unwrap());
|
||||
assert_eq!(pause.keys().len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -514,6 +514,225 @@ async fn a_message_into_a_live_turn_steers_it() {
|
||||
);
|
||||
}
|
||||
|
||||
/// The session controls: pause holds a key's dispatch (its queued work
|
||||
/// waits, the inventory says held), resume lifts the hold and the work
|
||||
/// drains, and abort cuts what runs or drops what waits. The three
|
||||
/// routes answer the shape the sidebar reads, and none of them reaches
|
||||
/// into the transcript beyond the cut's own `aborted` marker.
|
||||
#[tokio::test]
|
||||
async fn sessions_pause_resume_and_abort_over_http() {
|
||||
let gate = Arc::new(WireGate::default());
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let daemon = Daemon::build(
|
||||
&config(&dir, None),
|
||||
mock_registry(Arc::new(GatedProvider::new(gate.clone()))),
|
||||
rhema_rsd::DispatcherConfig::default(),
|
||||
)
|
||||
.expect("the daemon assembles");
|
||||
let base = serve(&daemon).await;
|
||||
let client = reqwest::Client::new();
|
||||
|
||||
// The key exists first: the create route is what puts it in the
|
||||
// inventory, and the controls 404 on a key that is not there.
|
||||
let created = client
|
||||
.post(format!("{base}/v1/sessions"))
|
||||
.json(&json!({"name": "web"}))
|
||||
.send()
|
||||
.await
|
||||
.expect("the create posts");
|
||||
assert_eq!(created.status(), 201, "the session is created");
|
||||
|
||||
let paused = client
|
||||
.post(format!("{base}/v1/sessions/interactive:web/pause"))
|
||||
.send()
|
||||
.await
|
||||
.expect("the pause posts");
|
||||
assert_eq!(paused.status(), 200);
|
||||
assert_eq!(
|
||||
paused.json::<Value>().await.expect("the answer parses"),
|
||||
json!({"key": "interactive:web", "paused": true})
|
||||
);
|
||||
|
||||
// Two messages into the held key: accepted, queued, dispatched by
|
||||
// nobody, and the inventory says so.
|
||||
for text in ["first", "second"] {
|
||||
let accepted = client
|
||||
.post(format!("{base}/v1/sessions/interactive:web/messages"))
|
||||
.json(&json!({"text": text}))
|
||||
.send()
|
||||
.await
|
||||
.expect("the message posts");
|
||||
assert_eq!(accepted.status(), 202);
|
||||
}
|
||||
let listed = client
|
||||
.get(format!("{base}/v1/sessions"))
|
||||
.send()
|
||||
.await
|
||||
.expect("the listing reads");
|
||||
let sessions: Vec<Value> = listed.json().await.expect("the listing parses");
|
||||
let web = sessions
|
||||
.iter()
|
||||
.find(|row| row["key"] == "interactive:web")
|
||||
.expect("the key is listed");
|
||||
assert_eq!(web["paused"], json!(true));
|
||||
assert_eq!(web["state"], json!("idle"), "held work does not dispatch");
|
||||
|
||||
// Abort with nothing running drains the queue and says how much it
|
||||
// dropped; a second abort is the idempotent no-op.
|
||||
let aborted = client
|
||||
.post(format!("{base}/v1/sessions/interactive:web/abort"))
|
||||
.send()
|
||||
.await
|
||||
.expect("the abort posts");
|
||||
assert_eq!(aborted.status(), 200);
|
||||
assert_eq!(
|
||||
aborted.json::<Value>().await.expect("the answer parses"),
|
||||
json!({"key": "interactive:web", "cut": false, "dropped": 2})
|
||||
);
|
||||
let again = client
|
||||
.post(format!("{base}/v1/sessions/interactive:web/abort"))
|
||||
.send()
|
||||
.await
|
||||
.expect("the second abort posts");
|
||||
assert_eq!(
|
||||
again.json::<Value>().await.expect("the answer parses"),
|
||||
json!({"key": "interactive:web", "cut": false, "dropped": 0})
|
||||
);
|
||||
let quiet = client
|
||||
.get(format!("{base}/v1/sessions"))
|
||||
.send()
|
||||
.await
|
||||
.expect("the listing reads");
|
||||
let sessions: Vec<Value> = quiet.json().await.expect("the listing parses");
|
||||
let web = sessions
|
||||
.iter()
|
||||
.find(|row| row["key"] == "interactive:web")
|
||||
.expect("the key is listed");
|
||||
assert_eq!(web["inbox_depth"], json!(0));
|
||||
|
||||
// Resume, then a fresh message runs: the hold is gone.
|
||||
let resumed = client
|
||||
.post(format!("{base}/v1/sessions/interactive:web/resume"))
|
||||
.send()
|
||||
.await
|
||||
.expect("the resume posts");
|
||||
assert_eq!(
|
||||
resumed.json::<Value>().await.expect("the answer parses"),
|
||||
json!({"key": "interactive:web", "paused": false})
|
||||
);
|
||||
|
||||
// A live turn, and the abort that cuts it: the stream closes on the
|
||||
// `aborted` marker and the answer reports the cut.
|
||||
let events = client
|
||||
.get(format!("{base}/v1/sessions/interactive:web/events"))
|
||||
.send()
|
||||
.await
|
||||
.expect("the events request goes out");
|
||||
let mut stream = sse_body(events).await;
|
||||
let mut seen = String::new();
|
||||
let accepted = client
|
||||
.post(format!("{base}/v1/sessions/interactive:web/messages"))
|
||||
.json(&json!({"text": "hello"}))
|
||||
.send()
|
||||
.await
|
||||
.expect("the message posts");
|
||||
assert_eq!(accepted.status(), 202);
|
||||
let mut in_flight = gate.in_flight_rx();
|
||||
while !*in_flight.borrow_and_update() {
|
||||
in_flight
|
||||
.changed()
|
||||
.await
|
||||
.expect("the in-flight sender lives");
|
||||
}
|
||||
let cut = client
|
||||
.post(format!("{base}/v1/sessions/interactive:web/abort"))
|
||||
.send()
|
||||
.await
|
||||
.expect("the abort posts");
|
||||
assert_eq!(
|
||||
cut.json::<Value>().await.expect("the answer parses"),
|
||||
json!({"key": "interactive:web", "cut": true, "dropped": 0})
|
||||
);
|
||||
read_until(&mut stream, &mut seen, "\"aborted\"").await;
|
||||
assert!(seen.contains("\"outcome\":\"aborted\""), "seen: {seen}");
|
||||
|
||||
// Unknown keys are 404 on all three, and the inventory survives.
|
||||
for verb in ["pause", "resume", "abort"] {
|
||||
let missing = client
|
||||
.post(format!("{base}/v1/sessions/nope:gone/{verb}"))
|
||||
.send()
|
||||
.await
|
||||
.expect("the route answers");
|
||||
assert_eq!(missing.status(), 404, "{verb} on an unknown key");
|
||||
}
|
||||
}
|
||||
|
||||
/// An abort on an idle `job:` key drops the queued delivery *and*
|
||||
/// lands the row: the coding job's table is the jobs' truth, so a row
|
||||
/// whose only delivery was dropped must not sit queued forever — it
|
||||
/// fails with `aborted`, the same word the handler's own cut uses.
|
||||
#[tokio::test]
|
||||
async fn an_abort_on_a_queued_job_key_fails_its_row() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let daemon = Daemon::build(
|
||||
&config(&dir, Some("sekrit")),
|
||||
mock_registry(Arc::new(MockProvider::new(Vec::new()))),
|
||||
rhema_rsd::DispatcherConfig::default(),
|
||||
)
|
||||
.expect("the daemon assembles");
|
||||
let base = serve(&daemon).await;
|
||||
let client = reqwest::Client::new();
|
||||
let auth = |request: reqwest::RequestBuilder| {
|
||||
request.header(reqwest::header::AUTHORIZATION, "Bearer sekrit")
|
||||
};
|
||||
|
||||
// The row the job's table holds — enqueued through the store the
|
||||
// daemon reads, quiet: nothing runs, the daemon's own loop is not
|
||||
// started in this test.
|
||||
let jobs = rhema_claw::job_store::CodingJobStore::open(dir.path().join("dispatch.db"))
|
||||
.expect("the job store opens");
|
||||
jobs.add_instance("rhema", "/tmp")
|
||||
.expect("the instance lands");
|
||||
let job = jobs
|
||||
.enqueue("rhema", "tidy the crate")
|
||||
.expect("the job queues");
|
||||
assert_eq!(job.status, rhema_claw::job_store::JobStatus::Queued);
|
||||
|
||||
// Whatever would dispatch it sits on the key: the jobs source's own
|
||||
// delivery, stood in for by the external ingest door.
|
||||
let ingested = auth(client.post(format!("{base}/v1/ingest")))
|
||||
.json(&json!({
|
||||
"source": "phone",
|
||||
"key": format!("job:rhema#{}", job.id),
|
||||
"payload": {"job_id": job.id},
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.expect("the event posts");
|
||||
assert_eq!(ingested.status(), 202);
|
||||
|
||||
let aborted: Value =
|
||||
auth(client.post(format!("{base}/v1/sessions/job:rhema%23{}/abort", job.id)))
|
||||
.send()
|
||||
.await
|
||||
.expect("the abort posts")
|
||||
.json()
|
||||
.await
|
||||
.expect("the answer parses");
|
||||
assert_eq!(
|
||||
aborted,
|
||||
json!({"key": format!("job:rhema#{}", job.id), "cut": false, "dropped": 1}),
|
||||
"{aborted}"
|
||||
);
|
||||
|
||||
let row = jobs
|
||||
.job(job.id)
|
||||
.expect("the row reads")
|
||||
.expect("the row is there");
|
||||
assert_eq!(row.status, rhema_claw::job_store::JobStatus::Failed);
|
||||
assert_eq!(row.result.as_deref(), Some("aborted"));
|
||||
}
|
||||
|
||||
/// A chat message with images: the route enforces the budget (media
|
||||
/// type, non-empty body, decoded size, count), the transcript's
|
||||
/// user_message card names the stored ids and media types, and each id
|
||||
|
||||
Reference in new issue
Block a user