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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion crates/tinycomputer-engine/src/task/browser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::sync::{Arc, Mutex};

use tinycomputer_browser::{ActionContext, Browser, BrowserSurface, SessionOptions};
use tinycomputer_bus::agent::{PaymentMode, TaskConstraints, TaskId};
use tinycomputer_bus::browser::ScreenshotRequest;
use tinycomputer_bus::browser::{ScreenshotRequest, SessionId};
use tinycomputer_bus::{DesktopResponse, RunFlowRequest};
use tinycomputer_core::surface::{Depth, Surface};

Expand Down Expand Up @@ -61,6 +61,12 @@ impl BrowserRunner {
self
}

/// The browser session this task runner opened, once it is prepared.
#[must_use]
pub fn session_id(&self, task: &TaskId) -> Option<SessionId> {
self.surfaces.lock().ok()?.get(task)?.session()
}

/// Uses `options` as the host defaults for sessions this runner opens.
#[must_use]
pub fn with_session_options(mut self, options: SessionOptions) -> Self {
Expand Down
2 changes: 2 additions & 0 deletions crates/tinycomputer-engine/src/task/browser_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,7 @@ async fn runner_hooks_share_the_task_surface_and_release_its_session()
let task = tinycomputer_bus::agent::TaskId::new("t-hooks");
let constraints = TaskConstraints::default();
runner.prepare(&task, &constraints).await;
assert!(runner.session_id(&task).is_some());
runner
.open_page(&task, "http://127.0.0.1:8765/index.html")
.await;
Expand All @@ -337,6 +338,7 @@ async fn runner_hooks_share_the_task_surface_and_release_its_session()
runner.journal(None, "test", &|| json!({"phase":"host"}));
runner.journal(Some(&task), "test", &|| json!({"phase":"task"}));
runner.release(&task);
assert!(runner.session_id(&task).is_none());
assert!(runner.capture(&task).await.is_none());
runner
.open_page(
Expand Down
178 changes: 178 additions & 0 deletions crates/tinycomputer-engine/src/task/cancel.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
//! Awaited task cancellation for hosts that must finish browser cleanup.

use tinycomputer_bus::agent::{AgentResponse, TaskId, TaskStatus, TaskView};

use super::{Tasks, errors::no_such_task};

impl Tasks {
/// Cancels a task and waits for its worker future to be dropped before
/// returning. The runner's release callback is repeated after the join so
/// adapters can defer resource teardown until the worker is quiescent.
pub async fn cancel_and_wait(&self, id: &TaskId) -> AgentResponse<TaskView> {
let Some(cell) = self.find(id) else {
return no_such_task(id);
};
let unfinished = !cell.view.borrow().status.is_final();
let done = if let Ok(worker) = cell.worker.lock() {
if unfinished && let Some(worker) = worker.as_ref() {
worker.abort.abort();
}
worker.as_ref().map(|worker| worker.done.clone())
} else {
None
};
if unfinished {
super::publish::publish(&cell, TaskStatus::Cancelled, "The task was cancelled.");
}

if let Some(mut done) = done {
wait_for_worker(&mut done).await;
}

self.runner.release(id);
AgentResponse::ok(cell.current_view())
}
}

async fn wait_for_worker(done: &mut tokio::sync::watch::Receiver<bool>) {
while !*done.borrow() {
if done.changed().await.is_err() {
break;
}
}
}

#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]

use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
};
use std::time::Duration;

use tinycomputer_bus::agent::{StartTaskRequest, SurfaceKind, TaskConstraints};

use crate::task::{FlowFuture, FlowRunner, Tasks};

struct DropSignal {
notify: Arc<tokio::sync::Notify>,
dropped: Arc<AtomicBool>,
}

impl Drop for DropSignal {
fn drop(&mut self) {
self.dropped.store(true, Ordering::SeqCst);
self.notify.notify_one();
}
}

struct PendingRunner {
started: Arc<tokio::sync::Notify>,
dropped: Arc<tokio::sync::Notify>,
dropped_flag: Arc<AtomicBool>,
released: Arc<AtomicBool>,
}

impl FlowRunner for PendingRunner {
fn run(
&self,
_task: &tinycomputer_bus::agent::TaskId,
_constraints: &TaskConstraints,
_request: tinycomputer_bus::RunFlowRequest,
) -> FlowFuture {
let started = self.started.clone();
let dropped = self.dropped.clone();
let dropped_flag = self.dropped_flag.clone();
Box::pin(async move {
started.notify_one();
let _signal = DropSignal {
notify: dropped,
dropped: dropped_flag,
};
std::future::pending().await
})
}

fn release(&self, _task: &tinycomputer_bus::agent::TaskId) {
self.released
.store(self.dropped_flag.load(Ordering::SeqCst), Ordering::SeqCst);
}
}

#[tokio::test]
async fn cancel_and_wait_joins_worker_before_releasing_runner() {
let started = Arc::new(tokio::sync::Notify::new());
let dropped = Arc::new(tokio::sync::Notify::new());
let dropped_flag = Arc::new(AtomicBool::new(false));
let released = Arc::new(AtomicBool::new(false));
let tasks = Arc::new(Tasks::new(Arc::new(PendingRunner {
started: started.clone(),
dropped: dropped.clone(),
dropped_flag,
released: released.clone(),
})));
let flow = serde_json::from_value(serde_json::json!({
"app": "browser",
"steps": [{"browse": "https://shop.example.com"}]
}))
.unwrap();
let task = tasks
.start(&StartTaskRequest {
flow: Some(flow),
constraints: TaskConstraints {
surfaces: vec![SurfaceKind::Browser],
..Default::default()
},
..Default::default()
})
.data
.unwrap();
tokio::time::timeout(Duration::from_secs(2), started.notified())
.await
.unwrap();

let first = {
let tasks = tasks.clone();
let task = task.id.clone();
tokio::spawn(async move { tasks.cancel_and_wait(&task).await })
};
tokio::time::sleep(Duration::from_millis(10)).await;
first.abort();
let _ = first.await;
let cancelled =
tokio::time::timeout(Duration::from_secs(2), tasks.cancel_and_wait(&task.id))
.await
.unwrap();

assert!(cancelled.data.is_some());
assert!(released.load(Ordering::SeqCst));
}

#[tokio::test]
async fn a_previous_generation_cannot_complete_the_current_worker_wait() {
let (old_tx, old_rx) = tokio::sync::watch::channel(false);
let (current_tx, mut current_rx) = tokio::sync::watch::channel(false);
let (finished, mut finished_rx) = tokio::sync::oneshot::channel();
let waiter = tokio::spawn(async move {
super::wait_for_worker(&mut current_rx).await;
let _ = finished.send(());
});

old_tx.send_replace(true);
assert!(
tokio::time::timeout(Duration::from_millis(20), &mut finished_rx)
.await
.is_err(),
"the previous generation must not wake the current worker waiter"
);
current_tx.send_replace(true);
tokio::time::timeout(Duration::from_secs(1), finished_rx)
.await
.unwrap()
.unwrap();
waiter.await.unwrap();
drop(old_rx);
}
}
6 changes: 4 additions & 2 deletions crates/tinycomputer-engine/src/task/controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -323,8 +323,10 @@ impl Tasks {
return no_such_task(id);
};
if !cell.view.borrow().status.is_final() {
if let Some(worker) = cell.worker.lock().ok().and_then(|mut worker| worker.take()) {
worker.abort();
if let Ok(worker) = cell.worker.lock()
&& let Some(worker) = worker.as_ref()
{
worker.abort.abort();
}
publish(&cell, TaskStatus::Cancelled, "The task was cancelled.");
}
Expand Down
1 change: 1 addition & 0 deletions crates/tinycomputer-engine/src/task/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ mod artifact;
mod brief;
mod browser;
mod budget;
mod cancel;
mod controller;
mod describe;
mod drive;
Expand Down
51 changes: 40 additions & 11 deletions crates/tinycomputer-engine/src/task/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,18 @@ use crate::shape::Shaper;
pub(super) struct Cell {
pub(super) view: watch::Sender<TaskView>,
pub(super) state: Mutex<State>,
pub(super) worker: Mutex<Option<tokio::task::AbortHandle>>,
pub(super) worker: Mutex<Option<WorkerSlot>>,
/// Who a failed step is handed to before the task fails.
pub(super) rescuer: Option<Rescuer>,
/// Who turns what a finished task read into the shape it asked for.
pub(super) shaper: Option<Shaper>,
}

pub(super) struct WorkerSlot {
pub(super) abort: tokio::task::AbortHandle,
pub(super) done: watch::Receiver<bool>,
}

impl Cell {
/// The latest published state with usage accumulated since that update.
pub(super) fn current_view(&self) -> TaskView {
Expand Down Expand Up @@ -207,24 +212,40 @@ impl Tasks {
return too_many();
};
publish(&cell, TaskStatus::Running, "Planning the task.");
let worker = tokio::spawn(plan_then_drive(
cell.clone(),
self.runner.clone(),
planner,
task.to_owned(),
request.constraints.surfaces.clone(),
));
let (done, done_rx) = watch::channel(false);
let running_cell = cell.clone();
let runner = self.runner.clone();
let task = task.to_owned();
let surfaces = request.constraints.surfaces.clone();
let completion = WorkerCompletion(done);
let worker = tokio::spawn(async move {
let _completion = completion;
plan_then_drive(running_cell, runner, planner, task, surfaces).await;
});
if let Ok(mut slot) = cell.worker.lock() {
*slot = Some(worker.abort_handle());
*slot = Some(WorkerSlot {
abort: worker.abort_handle(),
done: done_rx,
});
}
AgentResponse::ok(cell.current_view())
}

pub(super) fn spawn(&self, cell: &Arc<Cell>, runs: Vec<Run>) {
publish(cell, TaskStatus::Running, "The task is running.");
let worker = tokio::spawn(drive(cell.clone(), self.runner.clone(), runs));
let (done, done_rx) = watch::channel(false);
let running_cell = cell.clone();
let runner = self.runner.clone();
let completion = WorkerCompletion(done);
let worker = tokio::spawn(async move {
let _completion = completion;
drive(running_cell, runner, runs).await;
});
if let Ok(mut slot) = cell.worker.lock() {
*slot = Some(worker.abort_handle());
*slot = Some(WorkerSlot {
abort: worker.abort_handle(),
done: done_rx,
});
}
}

Expand All @@ -233,3 +254,11 @@ impl Tasks {
self.cells.lock().ok()?.get(&number).cloned()
}
}

struct WorkerCompletion(watch::Sender<bool>);

impl Drop for WorkerCompletion {
fn drop(&mut self) {
self.0.send_replace(true);
}
}
Loading