From aaaa8fd24af7af3f2e5c3cbd4fe742261d34b99d Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Mon, 19 Oct 2026 08:16:31 +0300 Subject: [PATCH 01/48] feat: add host computer trace sink --- crates/tinycomputer-bus/README.md | 16 ++ crates/tinycomputer-bus/src/lib.rs | 1 + crates/tinycomputer-bus/src/trace_sink/mod.rs | 113 ++++++++ .../src/trace_sink/trace_sink_tests.rs | 54 ++++ crates/tinycomputer-bus/src/version/mod.rs | 2 +- .../src/version/version_tests.rs | 4 +- .../tinycomputer-desktop/src/desktop/mod.rs | 60 ++++- .../src/desktop/trace_sink_tests.rs | 61 +++++ crates/tinycomputer-desktop/src/lib.rs | 5 + .../tinycomputer/src/tinybus_module/README.md | 6 +- .../tinycomputer/src/tinybus_module/config.rs | 15 ++ .../src/tinybus_module/dispatch/mod.rs | 16 +- .../src/tinybus_module/dispatch/service.rs | 35 ++- crates/tinycomputer/src/tinybus_module/mod.rs | 5 +- .../tinybus_module_tests/config_tests.rs | 10 + .../src/tinybus_module/trace_sink/mod.rs | 241 ++++++++++++++++++ .../trace_sink/trace_sink_tests.rs | 194 ++++++++++++++ .../specs/desktop-module-contract.md | 15 +- 18 files changed, 837 insertions(+), 16 deletions(-) create mode 100644 crates/tinycomputer-bus/src/trace_sink/mod.rs create mode 100644 crates/tinycomputer-bus/src/trace_sink/trace_sink_tests.rs create mode 100644 crates/tinycomputer-desktop/src/desktop/trace_sink_tests.rs create mode 100644 crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs create mode 100644 crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs diff --git a/crates/tinycomputer-bus/README.md b/crates/tinycomputer-bus/README.md index a556aec41..1ef0e16c4 100644 --- a/crates/tinycomputer-bus/README.md +++ b/crates/tinycomputer-bus/README.md @@ -166,3 +166,19 @@ The joined shutdown barrier must succeed before unloading the native artifact. See the [Globe contract](src/accessibility/README.md). Reliable Globe callers require a released 2.12-compatible artifact with a verified digest. + +Contract 2.20 adds the optional confidential `TraceSinkHost` callback. When a +host sets `trace_sink: true`, TinyComputer sends sanitized desktop trace events, +trace artifacts, and requested task reports to `Append`, `StoreArtifact`, and +`WriteReport`. Event delivery is ordered and acknowledged; strict trace mode +propagates sink failures, best-effort mode keeps the existing warning behavior, +and a selected sink never falls back to local trace files. Task report writes +are acknowledged before the report returns. Artifact writes carry the existing +engine limits and return an opaque host reference; the host enforces byte and +count limits atomically and must reject storage it cannot provide. The +confidential module caller is the sole scope authority: hosts derive the user +and storage scope from that trusted identity and ignore payload fields when +choosing a scope. Sink callbacks must not call back into TinyComputer. Event +and artifact acknowledgements are bounded by the engine's operation deadline; +report calls have a ten-second transport timeout. A host that does not opt in +keeps the existing desktop file/session trace behavior. diff --git a/crates/tinycomputer-bus/src/lib.rs b/crates/tinycomputer-bus/src/lib.rs index c35f152c5..c5086810e 100644 --- a/crates/tinycomputer-bus/src/lib.rs +++ b/crates/tinycomputer-bus/src/lib.rs @@ -131,6 +131,7 @@ pub mod notifications; pub mod observation; pub mod site_memory; pub mod system; +pub mod trace_sink; pub mod version; pub mod vocabulary; pub mod waiting; diff --git a/crates/tinycomputer-bus/src/trace_sink/mod.rs b/crates/tinycomputer-bus/src/trace_sink/mod.rs new file mode 100644 index 000000000..9002b95f9 --- /dev/null +++ b/crates/tinycomputer-bus/src/trace_sink/mod.rs @@ -0,0 +1,113 @@ +//! The optional confidential host callback for desktop trace events, trace +//! artifacts, and task reports. The module never chooses a persistence path. +//! +//! A host opts in explicitly through module configuration. Once selected, the +//! module sends events in order and does not fall back to a local file. An +//! acknowledged event is committed by the host; a failed acknowledgment is +//! reported using the desktop trace's strict/best-effort setting. Task report +//! writes are acknowledged before `TaskReport` returns to its caller. The +//! confidential caller identity is the only authority for the host's user and +//! scope; hosts must ignore payload fields when choosing that scope. A sink +//! callback must not call back into this module, which may be waiting for its +//! acknowledgment; both sides enforce bounded calls so a broken callback +//! fails instead of waiting forever. + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::agent::TaskReport; + +/// The interface the host serves for trace and report persistence. +pub const INTERFACE: &str = "ai.tinyhumans.tinycomputer.TraceSinkHost"; + +/// The object path the host serves [`INTERFACE`] at. +pub const OBJECT_PATH: &str = "/ai/tinyhumans/tinycomputer/TraceSinkHost"; + +/// One constant per member of [`INTERFACE`]. +pub mod methods { + /// Commits one already-sanitized desktop trace event. + pub const APPEND: &str = "Append"; + /// Commits one desktop trace artifact and returns its opaque reference. + pub const STORE_ARTIFACT: &str = "StoreArtifact"; + /// Persists one task report. + pub const WRITE_REPORT: &str = "WriteReport"; +} + +/// The members exposed by [`INTERFACE`], in dispatch order. +pub const METHODS: [&str; 3] = [ + methods::APPEND, + methods::STORE_ARTIFACT, + methods::WRITE_REPORT, +]; + +/// An acknowledgment with no additional result. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct SinkAck {} + +/// One sanitized, complete event emitted by agent-desktop. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct TraceEvent { + /// The exact event object written by the desktop trace format. + pub record: Value, + /// Remaining milliseconds in the engine's synchronous sink deadline. + pub deadline_ms: u64, + /// Maximum cumulative JSONL bytes allowed for this trace scope. + pub byte_budget: u64, +} + +/// Which aggregate artifact budget applies to one trace artifact. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum TraceArtifactKind { + /// A screenshot image. + Screenshot, + /// A saved accessibility reference map. + RefMap, +} + +/// Aggregate artifact limits for the active trace scope. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct TraceArtifactLimits { + /// Maximum total screenshot bytes. + pub screenshot_bytes: u64, + /// Maximum screenshot count. + pub screenshot_count: u32, + /// Maximum total reference-map bytes. + pub refmap_bytes: u64, +} + +/// One trace artifact sent to the host. The bytes may contain screen content +/// and therefore this member is confidential. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct TraceArtifact { + /// Whether the bytes are a screenshot or a reference map. + pub kind: TraceArtifactKind, + /// Producer-generated name, scoped to the host's trace sink. + pub name: String, + /// Artifact content. + pub bytes: Vec, + /// Remaining milliseconds in the engine's admission deadline. + pub deadline_ms: u64, + /// Limits the host must enforce atomically for this trace scope. + pub limits: TraceArtifactLimits, +} + +/// The host's committed opaque reference for an artifact. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct TraceArtifactRef { + /// A bounded, opaque reference used in trace events. + pub reference: String, +} + +/// A report emitted after the caller explicitly requests `TaskReport`. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct TaskReportRecord { + /// Task whose report is being persisted. + pub task_id: String, + /// Complete report returned to the caller. + pub report: TaskReport, +} + +#[cfg(test)] +#[path = "trace_sink_tests.rs"] +mod tests; diff --git a/crates/tinycomputer-bus/src/trace_sink/trace_sink_tests.rs b/crates/tinycomputer-bus/src/trace_sink/trace_sink_tests.rs new file mode 100644 index 000000000..7341a1477 --- /dev/null +++ b/crates/tinycomputer-bus/src/trace_sink/trace_sink_tests.rs @@ -0,0 +1,54 @@ +use super::*; + +#[test] +fn sink_records_keep_their_wire_shapes() { + let event = TraceEvent { + record: serde_json::json!({ + "event": "command.end", "seq": 4, "session_id": "s1" + }), + deadline_ms: 900, + byte_budget: 4096, + }; + let wire = serde_json::to_value(event).unwrap(); + assert_eq!(wire["record"]["event"], "command.end"); + assert_eq!(wire["deadline_ms"], 900); + assert_eq!(wire["byte_budget"], 4096); + + let artifact = TraceArtifact { + kind: TraceArtifactKind::RefMap, + name: "snapshot.json".into(), + bytes: vec![1, 2], + deadline_ms: 700, + limits: TraceArtifactLimits { + screenshot_bytes: 10, + screenshot_count: 2, + refmap_bytes: 20, + }, + }; + let wire = serde_json::to_value(artifact).unwrap(); + assert_eq!(wire["kind"], "ref_map"); + assert_eq!(wire["bytes"], serde_json::json!([1, 2])); + assert_eq!(wire["limits"]["refmap_bytes"], 20); +} + +#[test] +fn report_record_reuses_the_agent_report_contract() { + let report = TaskReportRecord { + task_id: "task-1".into(), + report: serde_json::from_value(serde_json::json!({ + "view": {"id": "task-1"}, + "steps": [], "records": {}, "artifacts": [], "learned": [], "trace": [] + })) + .unwrap(), + }; + let wire = serde_json::to_value(report).unwrap(); + assert_eq!(wire["task_id"], "task-1"); + assert_eq!(wire["report"]["trace"], serde_json::json!([])); +} + +#[test] +fn the_host_interface_is_separate_and_has_stable_member_names() { + assert_ne!(INTERFACE, crate::names::INTERFACE); + assert_eq!(METHODS, ["Append", "StoreArtifact", "WriteReport"]); + assert_eq!(SinkAck {}, serde_json::from_str("{}").unwrap()); +} diff --git a/crates/tinycomputer-bus/src/version/mod.rs b/crates/tinycomputer-bus/src/version/mod.rs index ad675d3e4..38aa7f10b 100644 --- a/crates/tinycomputer-bus/src/version/mod.rs +++ b/crates/tinycomputer-bus/src/version/mod.rs @@ -8,7 +8,7 @@ //! release workflow bumps, which tracks the shipped artifact. /// The wire contract version this crate defines. -pub const CONTRACT_VERSION: (u32, u32) = (2, 19); +pub const CONTRACT_VERSION: (u32, u32) = (2, 20); /// Returns whether a host holding [`CONTRACT_VERSION`] can bind to a module /// reporting `module`. diff --git a/crates/tinycomputer-bus/src/version/version_tests.rs b/crates/tinycomputer-bus/src/version/version_tests.rs index 1be61cc7d..cbeb3be9f 100644 --- a/crates/tinycomputer-bus/src/version/version_tests.rs +++ b/crates/tinycomputer-bus/src/version/version_tests.rs @@ -6,7 +6,7 @@ use super::{CONTRACT_VERSION, binds, is_compatible}; #[test] fn the_shipped_contract_version_is_pinned() { - assert_eq!(CONTRACT_VERSION, (2, 19)); + assert_eq!(CONTRACT_VERSION, (2, 20)); } #[test] @@ -35,6 +35,8 @@ fn a_newer_minor_on_the_module_side_binds() { // 2.19 adds the ConsequenceHost host-callback interface (Review): a 2.19 // host serves it, which a 2.18 module does not call, so its approvals // would never reach the host's policy. + // 2.20 adds TraceSinkHost so desktop events and task reports can be + // committed by the host without using a module-local trace file. assert!(!is_compatible((2, 18))); assert!(!is_compatible((2, 17))); assert!(!is_compatible((2, 16))); diff --git a/crates/tinycomputer-desktop/src/desktop/mod.rs b/crates/tinycomputer-desktop/src/desktop/mod.rs index d4ca162cf..d510226ee 100644 --- a/crates/tinycomputer-desktop/src/desktop/mod.rs +++ b/crates/tinycomputer-desktop/src/desktop/mod.rs @@ -80,13 +80,31 @@ use permission::Need; /// assert!(reply.ok); /// assert!(reply.data.is_some()); /// ``` -#[derive(Debug, Clone, Default)] +#[derive(Clone, Default)] pub struct Desktop { session_id: Option, trace_path: Option, trace_strict: bool, headed: bool, cursor: Option>, + trace_sink: Option>, +} + +impl std::fmt::Debug for Desktop { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("Desktop") + .field("session_id", &self.session_id) + .field("trace_path", &self.trace_path) + .field("trace_strict", &self.trace_strict) + .field("headed", &self.headed) + .field("cursor", &self.cursor) + .field( + "trace_sink", + &self.trace_sink.as_ref().map(|_| "configured"), + ) + .finish() + } } impl Desktop { @@ -145,6 +163,19 @@ impl Desktop { self } + /// Returns this `Desktop` sending desktop trace events to `sink`. + /// + /// The selected sink takes precedence over `trace_path` and session trace + /// files. Its synchronous methods are called in event order; strict mode + /// returns sink failures to the command, and best-effort mode warns and + /// continues, matching the local trace writer. The sink's authority stays + /// outside event data. + #[must_use] + pub fn with_trace_sink(mut self, sink: Arc) -> Self { + self.trace_sink = Some(sink); + self + } + /// Returns this `Desktop` in headed or headless mode. /// /// Headed mode lets a ref action take focus and move the real cursor when @@ -236,6 +267,7 @@ impl Desktop { trace_strict: flag(object.get("trace_strict"), "trace_strict")?, headed: flag(object.get("headed"), "headed")?, cursor: None, + trace_sink: None, }) } @@ -262,7 +294,7 @@ impl Desktop { /// ``` #[must_use] pub fn is_tracing(&self) -> bool { - self.trace_path.is_some() + self.trace_path.is_some() || self.trace_sink.is_some() } /// Where commands write their trace, if anywhere. @@ -295,12 +327,20 @@ impl Desktop { /// Builds the engine context every command runs under. fn context(&self) -> std::result::Result { - CommandContext::new( - self.session_id.clone(), - self.trace_path.clone(), - self.trace_strict, - ) - .map(|context| context.with_headed(self.headed)) + let context = match &self.trace_sink { + Some(sink) => CommandContext::new_with_trace_sink( + self.session_id.clone(), + sink.clone(), + self.trace_strict, + true, + ), + None => CommandContext::new( + self.session_id.clone(), + self.trace_path.clone(), + self.trace_strict, + ), + }; + context.map(|context| context.with_headed(self.headed)) } /// Runs `command` under a fresh adapter and context, and wraps whatever it @@ -396,3 +436,7 @@ fn platform_adapter() -> impl PlatformAdapter { #[cfg(test)] mod desktop_tests; + +#[cfg(test)] +#[path = "trace_sink_tests.rs"] +mod trace_sink_tests; diff --git a/crates/tinycomputer-desktop/src/desktop/trace_sink_tests.rs b/crates/tinycomputer-desktop/src/desktop/trace_sink_tests.rs new file mode 100644 index 000000000..a6eca8053 --- /dev/null +++ b/crates/tinycomputer-desktop/src/desktop/trace_sink_tests.rs @@ -0,0 +1,61 @@ +use super::*; +use crate::{ + TraceSink, TraceSinkArtifact, TraceSinkArtifactLimits, TraceSinkDeadline, TraceSinkError, +}; +use serde_json::Value; +use std::sync::{Arc, Mutex}; + +#[derive(Debug, Default)] +struct RecordingSink { + events: Mutex>, +} + +impl TraceSink for RecordingSink { + fn append( + &self, + event: &Value, + _deadline: TraceSinkDeadline, + _byte_budget: u64, + ) -> std::result::Result<(), TraceSinkError> { + self.events.lock().unwrap().push(event.clone()); + Ok(()) + } + + fn store_artifact( + &self, + _artifact: TraceSinkArtifact<'_>, + _limits: TraceSinkArtifactLimits, + ) -> std::result::Result { + Ok("opaque:test".into()) + } +} + +#[test] +fn opted_in_sink_receives_events_without_opening_the_configured_trace_path() { + let nonce = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("system clock is after the Unix epoch") + .as_nanos(); + let path = std::env::temp_dir().join(format!( + "tinycomputer-native-trace-{}-{nonce}.jsonl", + std::process::id(), + )); + let _ = std::fs::remove_file(&path); + let sink = Arc::new(RecordingSink::default()); + let desktop = Desktop::new() + .with_trace(path.clone(), true) + .with_trace_sink(sink.clone()); + + let reply = desktop.version(); + + assert!(reply.ok, "a committed trace event lets the command succeed"); + assert!(desktop.is_tracing()); + assert!(!path.exists(), "sink mode must not create the legacy file"); + assert!( + sink.events + .lock() + .unwrap() + .iter() + .any(|event| event["event"] == "command.end") + ); +} diff --git a/crates/tinycomputer-desktop/src/lib.rs b/crates/tinycomputer-desktop/src/lib.rs index c7b9ae541..182f2e662 100644 --- a/crates/tinycomputer-desktop/src/lib.rs +++ b/crates/tinycomputer-desktop/src/lib.rs @@ -73,6 +73,11 @@ mod desktop; mod error; mod surface; +pub use agent_desktop_core::{ + AppError as TraceSinkError, Deadline as TraceSinkDeadline, TraceArtifact as TraceSinkArtifact, + TraceArtifactKind as TraceSinkArtifactKind, TraceArtifactLimits as TraceSinkArtifactLimits, + TraceSink, +}; pub use desktop::Desktop; pub use error::{Error, Result}; pub use tinycomputer_bus; diff --git a/crates/tinycomputer/src/tinybus_module/README.md b/crates/tinycomputer/src/tinybus_module/README.md index 65ec251e3..5972de77a 100644 --- a/crates/tinycomputer/src/tinybus_module/README.md +++ b/crates/tinycomputer/src/tinybus_module/README.md @@ -54,7 +54,11 @@ against a scripted engine, so no browser is launched. The module takes its configuration from the loader as a JSON object, parsed into `Desktop` by `Desktop::from_config`: `session_id` and `trace_path` as strings, -`trace_strict` and `headed` as booleans. `browser` sets how every browser +`trace_strict`, `trace_sink`, and `headed` as booleans. Setting `trace_sink` to +`true` opts into the host's confidential `TraceSinkHost` interface for ordered +desktop trace events, trace artifacts, and requested task reports; selected +sink mode never writes local trace files. Leaving it absent or `false` retains +the existing `trace_path` and session behavior. `browser` sets how every browser launches — `executable`, `user_agent`, `args`, a task's page `perception`, how a page `settle`s after an action, and whether to `prelaunch` a planned browser task's browser (a planned task also warms diff --git a/crates/tinycomputer/src/tinybus_module/config.rs b/crates/tinycomputer/src/tinybus_module/config.rs index b1ae35aee..e0a2c32b2 100644 --- a/crates/tinycomputer/src/tinybus_module/config.rs +++ b/crates/tinycomputer/src/tinybus_module/config.rs @@ -134,6 +134,21 @@ impl BrowserDefaults { } } +/// Whether the host explicitly selected the trace/report callback. +pub(crate) fn trace_sink_requested(config: &serde_json::Value) -> Result { + match config + .as_object() + .and_then(|object| object.get("trace_sink")) + { + None => Ok(false), + Some(serde_json::Value::Bool(enabled)) => Ok(*enabled), + Some(_) => Err(crate::Error::ConfigFieldType { + field: "trace_sink", + expected: "a boolean", + }), + } +} + /// The `cursor` configuration: the agent's one on-screen cursor, shared by /// the desktop and every task's browser. Either a pace name, or an object /// with an optional `pace` and an optional `overlay` path to the diff --git a/crates/tinycomputer/src/tinybus_module/dispatch/mod.rs b/crates/tinycomputer/src/tinybus_module/dispatch/mod.rs index 54ef05e97..fced7eb95 100644 --- a/crates/tinycomputer/src/tinybus_module/dispatch/mod.rs +++ b/crates/tinycomputer/src/tinybus_module/dispatch/mod.rs @@ -50,6 +50,7 @@ use tinycomputer_bus::agent::{ use super::consequence_gate::ConsequenceLink; use super::runner::jev_not_configured; use super::site_memory::SiteLink; +use super::trace_sink::TraceLink; use crate::Desktop; use tinycomputer_browser::{ Action, Browser, DownloadWaitRequest, EvaluateRequest, NavigateRequest, OutputRequest, @@ -81,6 +82,8 @@ pub(crate) struct DesktopService { site_link: Option>, /// The host's consequence review, when the module was set up on a bus. consequence_link: Option>, + /// The host's trace and report persistence callback, when enabled. + trace_link: Option>, } #[tinybus::interface(name = "ai.tinyhumans.tinycomputer.Desktop")] @@ -200,7 +203,18 @@ impl DesktopService { &self, request: TaskReportRequest, ) -> TinyBusResult> { - self.on_tasks(move |tasks| tasks.report_for(&request)).await + let reply = self + .on_tasks(move |tasks| tasks.report_for(&request)) + .await?; + if let (Some(link), Some(report)) = (&self.trace_link, &reply.data) { + link.write_report(tinycomputer_bus::trace_sink::TaskReportRecord { + task_id: report.view.id.to_string(), + report: report.clone(), + }) + .await + .map_err(|_| tinybus::Error::failed("task report sink failed"))?; + } + Ok(reply) } /// The tasks this module holds, newest first. diff --git a/crates/tinycomputer/src/tinybus_module/dispatch/service.rs b/crates/tinycomputer/src/tinybus_module/dispatch/service.rs index f4d1847ba..bf786476e 100644 --- a/crates/tinycomputer/src/tinybus_module/dispatch/service.rs +++ b/crates/tinycomputer/src/tinybus_module/dispatch/service.rs @@ -17,6 +17,7 @@ use crate::tinybus_module::config::{BrowserDefaults, cursor_config}; use crate::tinybus_module::consequence_gate::{ConsequenceLink, ConsequencePort}; use crate::tinybus_module::runner::WorkspaceRunner; use crate::tinybus_module::site_memory::{SiteLink, SiteMemoryPort, refused_flow}; +use crate::tinybus_module::trace_sink::TraceLink; use crate::{Desktop, Result}; impl DesktopService { @@ -29,6 +30,26 @@ impl DesktopService { Self::with_browser(config, Arc::new(Browser::new(Arc::new(AgentBrowser)))) } + /// Builds the service with the connection used for optional host callbacks. + pub(crate) async fn from_config_with_connection( + config: &serde_json::Value, + connection: tinybus::Connection, + ) -> TinyBusResult { + let trace_link = if super::config::trace_sink_requested(config) + .map_err(|error| TinyBusError::failed(error.to_string()))? + { + Some(TraceLink::new(connection.clone())?) + } else { + None + }; + Self::with_browser_and_trace_sink( + config, + Arc::new(Browser::new(Arc::new(AgentBrowser))), + trace_link, + ) + .map_err(|error| TinyBusError::failed(error.to_string())) + } + /// Builds the service from the module configuration blob, opening browser /// sessions on `browser`. /// @@ -36,8 +57,19 @@ impl DesktopService { /// /// Propagates whatever [`Desktop::from_config`] rejects. pub(crate) fn with_browser(config: &serde_json::Value, browser: Arc) -> Result { + Self::with_browser_and_trace_sink(config, browser, None) + } + + fn with_browser_and_trace_sink( + config: &serde_json::Value, + browser: Arc, + trace_link: Option>, + ) -> Result { let cursor = Arc::new(cursor_config(config)?); - let desktop = Desktop::from_config(config)?.with_cursor(cursor.clone()); + let mut desktop = Desktop::from_config(config)?.with_cursor(cursor.clone()); + if let Some(link) = &trace_link { + desktop = desktop.with_trace_sink(link.clone()); + } let jev = config .as_object() .and_then(|object| object.get("jev")) @@ -94,6 +126,7 @@ impl DesktopService { accessibility: Arc::new(super::accessibility::Access::default()), site_link: None, consequence_link: None, + trace_link, }) } diff --git a/crates/tinycomputer/src/tinybus_module/mod.rs b/crates/tinycomputer/src/tinybus_module/mod.rs index 7fd82e399..2882669e8 100644 --- a/crates/tinycomputer/src/tinybus_module/mod.rs +++ b/crates/tinycomputer/src/tinybus_module/mod.rs @@ -24,6 +24,7 @@ mod consequence_gate; mod dispatch; mod runner; mod site_memory; +mod trace_sink; use serde_json::Value; use tinybus::{Connection, Result as TinyBusResult}; @@ -38,8 +39,7 @@ pub(crate) use dispatch::DesktopService; /// silently ignoring the session it was told to join would allocate refs /// nothing else can spend. async fn setup(connection: Connection, config: Value) -> TinyBusResult<()> { - let service = DesktopService::from_config(&config) - .map_err(|error| tinybus::Error::failed(error.to_string()))?; + let service = DesktopService::from_config_with_connection(&config, connection.clone()).await?; // The host's per-site memory; a host that does not serve it only costs // tasks what earlier ones learned. let service = service.with_site_memory(Box::new(site_memory::BusPort::new(connection.clone()))); @@ -94,6 +94,7 @@ tinybus_module::module_export_optional_static! { optional = [ "ai.tinyhumans.tinycomputer.SiteMemoryHost", "ai.tinyhumans.tinycomputer.ConsequenceHost", + "ai.tinyhumans.tinycomputer.TraceSinkHost", ], lazy = false, } diff --git a/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/config_tests.rs b/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/config_tests.rs index 38f6d41d5..27a37f3dc 100644 --- a/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/config_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/config_tests.rs @@ -267,3 +267,13 @@ fn the_cursor_is_configured_or_refused() { } assert!(DesktopService::from_config(&json!({"cursor": "off"})).is_ok()); } + +#[test] +fn trace_sink_is_an_explicit_boolean_opt_in() { + use crate::tinybus_module::config::trace_sink_requested; + + assert!(!trace_sink_requested(&json!({})).unwrap()); + assert!(trace_sink_requested(&json!({"trace_sink": true})).unwrap()); + assert!(!trace_sink_requested(&json!({"trace_sink": false})).unwrap()); + assert!(trace_sink_requested(&json!({"trace_sink": "yes"})).is_err()); +} diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs new file mode 100644 index 000000000..b9dc76940 --- /dev/null +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs @@ -0,0 +1,241 @@ +//! The optional host-owned persistence path for desktop traces and reports. +//! +//! The desktop engine emits trace events synchronously, sometimes while a +//! task is on a Tokio executor thread. This port moves every trace callback to +//! one dedicated worker before making a bounded synchronous wait, so the bus +//! acknowledgement never runs on the caller's executor thread. One worker +//! preserves event order for this module instance. + +use std::sync::Arc; +use std::sync::mpsc::{self, Receiver, RecvTimeoutError, SyncSender, TrySendError}; +use std::time::Duration; + +use serde::Serialize; +use serde::de::DeserializeOwned; +use tinybus::{Connection, Error as TinyBusError, Proxy, Result as TinyBusResult}; +use tinycomputer_bus::trace_sink::{ + self, SinkAck, TaskReportRecord, TraceArtifact, TraceArtifactKind, TraceArtifactRef, TraceEvent, +}; +use tinycomputer_desktop::{ + TraceSink as EngineTraceSink, TraceSinkArtifact, TraceSinkArtifactKind as EngineArtifactKind, + TraceSinkArtifactLimits, TraceSinkDeadline, TraceSinkError, +}; + +const CALL_TIMEOUT: Duration = Duration::from_secs(10); + +enum Command { + Append(TraceEvent, SyncSender>), + StoreArtifact(TraceArtifact, SyncSender>), +} + +/// The synchronous sink adapter, backed by a worker that owns the bus calls. +#[derive(Clone)] +pub(crate) struct TraceLink { + connection: Connection, + worker: SyncSender, +} + +impl std::fmt::Debug for TraceLink { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.debug_struct("TraceLink").finish_non_exhaustive() + } +} + +impl TraceLink { + pub(crate) fn new(connection: Connection) -> TinyBusResult> { + let worker_connection = connection.clone(); + let runtime = tokio::runtime::Handle::current(); + if runtime.runtime_flavor() != tokio::runtime::RuntimeFlavor::MultiThread { + return Err(TinyBusError::failed( + "trace sink requires a multi-thread Tokio runtime", + )); + } + let (sender, receiver) = mpsc::sync_channel(1); + std::thread::Builder::new() + .name("tinycomputer-trace-sink".into()) + .spawn(move || worker(runtime, worker_connection, receiver)) + .map_err(|error| TinyBusError::failed(format!("trace sink worker failed: {error}")))?; + Ok(Arc::new(Self { + connection, + worker: sender, + })) + } + + pub(crate) async fn write_report(&self, record: TaskReportRecord) -> TinyBusResult<()> { + call::( + &self.proxy(CALL_TIMEOUT)?, + trace_sink::methods::WRITE_REPORT, + (record,), + ) + .await + .map(|_| ()) + } + + fn proxy(&self, timeout: Duration) -> TinyBusResult { + self.connection + .proxy( + trace_sink::INTERFACE, + trace_sink::OBJECT_PATH, + trace_sink::INTERFACE, + ) + .map(|proxy| proxy.with_timeout(timeout)) + } +} + +fn worker(runtime: tokio::runtime::Handle, connection: Connection, receiver: Receiver) { + while let Ok(command) = receiver.recv() { + match command { + Command::Append(record, reply) => { + let timeout = timeout(record.deadline_ms); + let result = runtime.block_on(async { + let proxy = connection + .proxy( + trace_sink::INTERFACE, + trace_sink::OBJECT_PATH, + trace_sink::INTERFACE, + )? + .with_timeout(timeout); + call::(&proxy, trace_sink::methods::APPEND, (record,)) + .await + .map(|_| ()) + }); + let _ = reply.send(result.map_err(|_| ())); + } + Command::StoreArtifact(artifact, reply) => { + let timeout = timeout(artifact.deadline_ms); + let result = runtime.block_on(async { + let proxy = connection + .proxy( + trace_sink::INTERFACE, + trace_sink::OBJECT_PATH, + trace_sink::INTERFACE, + )? + .with_timeout(timeout); + call::( + &proxy, + trace_sink::methods::STORE_ARTIFACT, + (artifact,), + ) + .await + .map(|reply| reply.reference) + }); + let _ = reply.send(result.map_err(|_| ())); + } + } + } +} + +#[cfg(test)] +async fn call(proxy: &Proxy, member: &str, args: A) -> TinyBusResult +where + T: DeserializeOwned, + A: Serialize, +{ + proxy.call(member, args).await +} + +#[cfg(not(test))] +async fn call(proxy: &Proxy, member: &str, args: A) -> TinyBusResult +where + T: DeserializeOwned, + A: Serialize, +{ + proxy.call_confidential(member, args).await +} + +fn timeout(deadline_ms: u64) -> Duration { + Duration::from_millis(deadline_ms.max(1)).min(CALL_TIMEOUT) +} + +fn remaining_ms(deadline: TraceSinkDeadline) -> u64 { + u64::try_from(deadline.remaining().as_millis()).unwrap_or(u64::MAX) +} + +fn receive(receiver: &mpsc::Receiver, timeout: Duration) -> Result { + match tokio::runtime::Handle::try_current() { + Ok(handle) if handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread => { + tokio::task::block_in_place(|| receiver.recv_timeout(timeout)) + } + // A current-thread executor cannot make progress while this sync + // callback waits, so fail instead of deadlocking its dispatch loop. + Ok(_) => Err(RecvTimeoutError::Timeout), + Err(_) => receiver.recv_timeout(timeout), + } +} + +impl EngineTraceSink for TraceLink { + fn append( + &self, + record: &serde_json::Value, + deadline: TraceSinkDeadline, + byte_budget: u64, + ) -> std::result::Result<(), TraceSinkError> { + let deadline_ms = remaining_ms(deadline); + let (reply, result) = mpsc::sync_channel(1); + self.worker + .try_send(Command::Append( + TraceEvent { + record: record.clone(), + deadline_ms, + byte_budget, + }, + reply, + )) + .map_err(|error| match error { + TrySendError::Full(_) => { + TraceSinkError::Internal("trace sink worker is busy".into()) + } + TrySendError::Disconnected(_) => { + TraceSinkError::Internal("trace sink worker stopped".into()) + } + })?; + receive(&result, timeout(deadline_ms)) + .map_err(|_| TraceSinkError::Internal("trace sink acknowledgment timed out".into()))? + .map_err(|_| TraceSinkError::Internal("trace sink rejected event".into())) + } + + fn store_artifact( + &self, + artifact: TraceSinkArtifact<'_>, + limits: TraceSinkArtifactLimits, + ) -> std::result::Result { + let deadline_ms = remaining_ms(artifact.deadline); + let (reply, result) = mpsc::sync_channel(1); + let kind = match artifact.kind { + EngineArtifactKind::Screenshot => TraceArtifactKind::Screenshot, + EngineArtifactKind::RefMap => TraceArtifactKind::RefMap, + }; + self.worker + .try_send(Command::StoreArtifact( + TraceArtifact { + kind, + name: artifact.name.to_owned(), + bytes: artifact.bytes.to_vec(), + deadline_ms, + limits: tinycomputer_bus::trace_sink::TraceArtifactLimits { + screenshot_bytes: limits.screenshot_bytes, + screenshot_count: limits.screenshot_count, + refmap_bytes: limits.refmap_bytes, + }, + }, + reply, + )) + .map_err(|error| match error { + TrySendError::Full(_) => { + TraceSinkError::Internal("trace sink worker is busy".into()) + } + TrySendError::Disconnected(_) => { + TraceSinkError::Internal("trace sink worker stopped".into()) + } + })?; + receive(&result, timeout(deadline_ms)) + .map_err(|_| { + TraceSinkError::Internal("trace artifact acknowledgment timed out".into()) + })? + .map_err(|_| TraceSinkError::Internal("trace sink rejected artifact".into())) + } +} + +#[cfg(test)] +#[path = "trace_sink_tests.rs"] +mod tests; diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs new file mode 100644 index 000000000..456d9941c --- /dev/null +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs @@ -0,0 +1,194 @@ +use super::*; +use std::sync::Mutex; +use tinycomputer_bus::trace_sink::TraceEvent; + +#[derive(Clone, Default)] +struct RecordingHost { + events: Arc>>, + artifacts: Arc>>, + reports: Arc>>, + fail: bool, +} + +#[tinybus::interface(name = "ai.tinyhumans.tinycomputer.TraceSinkHost")] +impl RecordingHost { + async fn append(&self, request: TraceEvent) -> TinyBusResult { + if self.fail { + return Err(TinyBusError::failed("sink refused event")); + } + self.events.lock().unwrap().push(request.record); + Ok(SinkAck {}) + } + + async fn store_artifact(&self, request: TraceArtifact) -> TinyBusResult { + if self.fail { + return Err(TinyBusError::failed("sink refused artifact")); + } + self.artifacts.lock().unwrap().push(request.clone()); + Ok(TraceArtifactRef { + reference: format!("opaque:{}", request.name), + }) + } + + async fn write_report(&self, request: TaskReportRecord) -> TinyBusResult { + if self.fail { + return Err(TinyBusError::failed("sink refused report")); + } + self.reports.lock().unwrap().push(request); + Ok(SinkAck {}) + } +} + +async fn setup_host( + bus: &tinybus::transport::memory::MemoryBus, + host: RecordingHost, +) -> TinyBusResult { + let connection = Connection::connect(bus.connect().await?).await?; + connection + .serve_at(trace_sink::OBJECT_PATH.try_into()?, host) + .await?; + connection.request_name(trace_sink::INTERFACE).await?; + Ok(connection) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn trace_calls_are_ordered_and_artifacts_and_reports_reach_the_host() -> TinyBusResult<()> { + use tinycomputer_bus::agent::TaskReport; + + let bus = tinybus::transport::memory::MemoryBus::new(); + tinybus::broker::Broker::new().spawn(bus.clone()); + let host = RecordingHost::default(); + let _host_connection = setup_host(&bus, host.clone()).await?; + let module = Connection::connect(bus.connect().await?).await?; + let link = TraceLink::new(module)?; + + let first = serde_json::json!({"event": "first", "seq": 1}); + let second = serde_json::json!({"event": "second", "seq": 2}); + link.append(&first, TraceSinkDeadline::standard().unwrap(), 4096) + .expect("async executor callback is acknowledged"); + let trace_link = link.clone(); + tokio::task::spawn_blocking(move || { + trace_link + .append(&second, TraceSinkDeadline::standard().unwrap(), 4096) + .unwrap(); + trace_link + .store_artifact( + TraceSinkArtifact { + kind: EngineArtifactKind::Screenshot, + name: "screen.png", + bytes: b"image", + deadline: TraceSinkDeadline::standard().unwrap(), + }, + TraceSinkArtifactLimits { + screenshot_bytes: 100, + screenshot_count: 2, + refmap_bytes: 100, + }, + ) + .unwrap() + }) + .await + .expect("trace worker task completes"); + + let report = TaskReportRecord { + task_id: "task-1".into(), + report: serde_json::from_value::(serde_json::json!({ + "view": {"id": "task-1"}, + "steps": [], "records": {}, "artifacts": [], "learned": [], "trace": [] + })) + .unwrap(), + }; + link.write_report(report).await?; + + assert_eq!( + *host.events.lock().unwrap(), + [ + serde_json::json!({"event": "first", "seq": 1}), + serde_json::json!({"event": "second", "seq": 2}) + ] + ); + assert_eq!(host.artifacts.lock().unwrap()[0].name, "screen.png"); + assert_eq!(host.reports.lock().unwrap()[0].task_id, "task-1"); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn sink_failures_are_returned_without_fallback() -> TinyBusResult<()> { + let bus = tinybus::transport::memory::MemoryBus::new(); + tinybus::broker::Broker::new().spawn(bus.clone()); + let _host_connection = setup_host( + &bus, + RecordingHost { + fail: true, + ..Default::default() + }, + ) + .await?; + let module = Connection::connect(bus.connect().await?).await?; + let link = TraceLink::new(module)?; + + let trace_link = link.clone(); + let error = tokio::task::spawn_blocking(move || { + trace_link.append( + &serde_json::json!({"event": "rejected"}), + TraceSinkDeadline::standard().unwrap(), + 4096, + ) + }) + .await + .expect("trace worker task completes") + .expect_err("host failure must be returned to strict desktop trace"); + assert!(error.to_string().contains("rejected")); + assert!( + link.write_report(TaskReportRecord { + task_id: "task-1".into(), + report: serde_json::from_value(serde_json::json!({ + "view": {"id": "task-1"}, + "steps": [], "records": {}, "artifacts": [], "learned": [], "trace": [] + })) + .unwrap(), + }) + .await + .is_err() + ); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn task_report_member_persists_its_report_before_returning() -> TinyBusResult<()> { + use tinybus::Interface; + use tinycomputer_bus::agent::{AgentResponse, TaskView}; + use tinycomputer_bus::names; + + let bus = tinybus::transport::memory::MemoryBus::new(); + tinybus::broker::Broker::new().spawn(bus.clone()); + let host = RecordingHost::default(); + let _host_connection = setup_host(&bus, host.clone()).await?; + let module = Connection::connect(bus.connect().await?).await?; + let service = crate::tinybus_module::dispatch::DesktopService::from_config_with_connection( + &serde_json::json!({"trace_sink": true}), + module, + ) + .await? + .with_native_fixture(); + + let started = service + .call( + &names::methods::START_TASK.try_into()?, + serde_json::json!([{"flow": {"app": "Mail", "steps": ["start a note"]}}]), + ) + .await?; + let started: AgentResponse = serde_json::from_value(started)?; + let id = started.data.expect("task starts").id; + let report = service + .call( + &names::methods::TASK_REPORT.try_into()?, + serde_json::json!([{"id": id, "trace": false}]), + ) + .await?; + + assert!(report["ok"].as_bool().unwrap_or(false)); + assert_eq!(host.reports.lock().unwrap().len(), 1); + assert_eq!(host.reports.lock().unwrap()[0].task_id, id.to_string()); + Ok(()) +} diff --git a/docs/technical/specs/desktop-module-contract.md b/docs/technical/specs/desktop-module-contract.md index df9365af0..616e2dda1 100644 --- a/docs/technical/specs/desktop-module-contract.md +++ b/docs/technical/specs/desktop-module-contract.md @@ -88,6 +88,19 @@ classification (`irreversible` or `payment`). The module calls it from serves the interface and fails to answer, turns the approval into a decline, so the task never takes the action. A host that serves nothing leaves the pause as the only gate. A payment checkpoint is never continuable and needs no review. + +Trace and report persistence (2.20): when module configuration sets +`trace_sink: true`, the module calls the optional confidential +`ai.tinyhumans.tinycomputer.TraceSinkHost` interface. `Append` receives each +complete sanitized agent-desktop trace event in order. `StoreArtifact` receives +desktop trace screenshots and reference maps and returns their committed opaque +references. `WriteReport` receives a task id and the full `TaskReport` whenever +the caller requests `TaskReport`. The host acknowledges each write; trace +failures follow `trace_strict`, while a report write failure is returned to the +report caller. Sink mode has no local file/session fallback, even when its host +callback fails. Without the explicit config flag, existing desktop trace path +and session behavior remain in effect. Hosts should upsert reports by task id +because callers may request the same report more than once. - `TaskReport` takes a `TaskReportRequest` (2.7), `{"id", "trace"}` with `trace` always serialized, rather than a `TaskRef`. A TinyBus client refuses a confidential body holding an object whose only field is a string @@ -172,7 +185,7 @@ the only gate. A payment checkpoint is never continuable and needs no review. ### Configuration and concurrency - The module's configuration is a JSON object with optional `session_id` and - `trace_path` strings, `trace_strict` and `headed` booleans, and a `jev` + `trace_path` strings, `trace_strict`, `trace_sink`, and `headed` booleans, and a `jev` object containing provider configuration and its API key. `null` and `{}` yield desktop defaults with Jev disabled; invalid recognized fields fail before the served object is replaced. From 8ab256e73cf2a19d7d6f27a100b468186202ac04 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Mon, 19 Oct 2026 08:33:12 +0300 Subject: [PATCH 02/48] fix: bind trace sink to trusted host callback --- crates/tinycomputer-bus/README.md | 9 +- .../src/bin/verify_module.rs | 122 +++++++++- .../tinycomputer/src/tinybus_module/README.md | 12 +- .../tinycomputer/src/tinybus_module/config.rs | 41 +++- .../src/tinybus_module/dispatch/service.rs | 4 +- .../tinybus_module_tests/config_tests.rs | 33 ++- .../src/tinybus_module/trace_sink/mod.rs | 227 +++++++++++++----- .../trace_sink/trace_sink_tests.rs | 215 ++++------------- 8 files changed, 423 insertions(+), 240 deletions(-) diff --git a/crates/tinycomputer-bus/README.md b/crates/tinycomputer-bus/README.md index 1ef0e16c4..45f6bd022 100644 --- a/crates/tinycomputer-bus/README.md +++ b/crates/tinycomputer-bus/README.md @@ -167,8 +167,9 @@ See the [Globe contract](src/accessibility/README.md). Reliable Globe callers require a released 2.12-compatible artifact with a verified digest. -Contract 2.20 adds the optional confidential `TraceSinkHost` callback. When a -host sets `trace_sink: true`, TinyComputer sends sanitized desktop trace events, +Contract 2.20 adds the optional confidential `TraceSinkHost` callback. A host +prepares one exact callback binding per loaded module and supplies its unique +destination as `trace_sink.destination`. TinyComputer sends sanitized desktop trace events, trace artifacts, and requested task reports to `Append`, `StoreArtifact`, and `WriteReport`. Event delivery is ordered and acknowledged; strict trace mode propagates sink failures, best-effort mode keeps the existing warning behavior, @@ -178,7 +179,9 @@ engine limits and return an opaque host reference; the host enforces byte and count limits atomically and must reject storage it cannot provide. The confidential module caller is the sole scope authority: hosts derive the user and storage scope from that trusted identity and ignore payload fields when -choosing a scope. Sink callbacks must not call back into TinyComputer. Event +choosing a scope. Sink callbacks must not call back into TinyComputer. The +module refuses overlapping sink callbacks as bounded backpressure; it cannot +distinguish causal re-entry from unrelated concurrent work. Event and artifact acknowledgements are bounded by the engine's operation deadline; report calls have a ten-second transport timeout. A host that does not opt in keeps the existing desktop file/session trace behavior. diff --git a/crates/tinycomputer-examples/src/bin/verify_module.rs b/crates/tinycomputer-examples/src/bin/verify_module.rs index d682e94a6..dd944117a 100644 --- a/crates/tinycomputer-examples/src/bin/verify_module.rs +++ b/crates/tinycomputer-examples/src/bin/verify_module.rs @@ -7,13 +7,50 @@ use std::io; use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; use std::time::Duration; use tinybus::Connection; use tinybus::broker::Broker; -use tinybus::module::ModuleHost; +use tinybus::module::{HostCallbackEndpoint, ModuleHost}; use tinybus::transport::memory::MemoryBus; -use tinycomputer_bus::{DesktopResponse, METHODS, names}; +use tinycomputer_bus::{DesktopResponse, METHODS, names, trace_sink}; + +#[derive(Clone, Default)] +struct TraceSinkCapture { + events: Arc>>, + reports: Arc>>, + fail_reports: Arc, +} + +#[tinybus::interface(name = "ai.tinyhumans.tinycomputer.TraceSinkHost")] +impl TraceSinkCapture { + async fn append(&self, event: trace_sink::TraceEvent) -> tinybus::Result { + self.events.lock().unwrap().push(event.record); + Ok(trace_sink::SinkAck {}) + } + + async fn store_artifact( + &self, + _artifact: trace_sink::TraceArtifact, + ) -> tinybus::Result { + Err(tinybus::Error::failed( + "verification fixture does not persist trace artifacts", + )) + } + + async fn write_report( + &self, + report: trace_sink::TaskReportRecord, + ) -> tinybus::Result { + if self.fail_reports.load(Ordering::SeqCst) { + return Err(tinybus::Error::failed("verification report sink failure")); + } + self.reports.lock().unwrap().push(report); + Ok(trace_sink::SinkAck {}) + } +} #[tokio::main] async fn main() -> Result<(), Box> { @@ -22,7 +59,26 @@ async fn main() -> Result<(), Box> { let broker = Broker::new(); let broker_task = broker.spawn(bus.clone()); let module_host = ModuleHost::new(broker); - let info = module_host.load_file(&module)?; + let callback = module_host + .prepare_host_callbacks(vec![HostCallbackEndpoint { + path: trace_sink::OBJECT_PATH.parse()?, + interface: trace_sink::INTERFACE.parse()?, + members: trace_sink::METHODS + .iter() + .map(|member| (*member).parse()) + .collect::>()?, + }]) + .await?; + let capture = TraceSinkCapture::default(); + callback + .serve_at(trace_sink::OBJECT_PATH.parse()?, capture.clone()) + .await?; + let config = serde_json::json!({ + "trace_sink": {"destination": callback.unique_name()}, + }); + let info = module_host + .load_file_with_host_callbacks(&module, config, &callback) + .await?; if info.name != "tinycomputer" { return Err(io::Error::other(format!( @@ -59,6 +115,8 @@ async fn main() -> Result<(), Box> { .into()); } + verify_report_sink(&proxy, &capture).await?; + let declared: Vec<&str> = info .manifest .provides @@ -98,6 +156,64 @@ async fn main() -> Result<(), Box> { Ok(()) } +/// Exercises report delivery through the exact confidential callback binding. +async fn verify_report_sink( + proxy: &tinybus::Proxy, + capture: &TraceSinkCapture, +) -> Result<(), Box> { + use tinycomputer_bus::agent::{AgentResponse, StartTaskRequest, TaskReportRequest, TaskView}; + + let started: AgentResponse = proxy + .call_confidential( + names::methods::START_TASK, + (StartTaskRequest { + flow: Some(serde_json::from_value(serde_json::json!({ + "app": "verification", + "steps": [] + }))?), + ..StartTaskRequest::default() + },), + ) + .await?; + let task_id = started + .data + .ok_or_else(|| io::Error::other("module did not start the no-op verification task"))? + .id; + let report: AgentResponse = proxy + .call_confidential( + names::methods::TASK_REPORT, + (TaskReportRequest { + id: task_id.clone(), + trace: false, + },), + ) + .await?; + if report.data.is_none() { + return Err(io::Error::other("module did not return the verification task report").into()); + } + let captured = capture.reports.lock().unwrap(); + if captured.len() != 1 || captured[0].task_id != task_id.to_string() { + return Err( + io::Error::other("confidential host callback did not receive the task report").into(), + ); + } + drop(captured); + capture.fail_reports.store(true, Ordering::SeqCst); + let failed = proxy + .call_confidential::( + names::methods::TASK_REPORT, + (TaskReportRequest { + id: task_id, + trace: false, + },), + ) + .await; + if failed.is_ok() { + return Err(io::Error::other("task report sink failure was not returned").into()); + } + Ok(()) +} + /// Checks native lease admission and terminal shutdown without device access. async fn verify_globe_lifecycle(proxy: &tinybus::Proxy) -> Result<(), Box> { // Invalid handles exercise the new artifact paths without touching devices. diff --git a/crates/tinycomputer/src/tinybus_module/README.md b/crates/tinycomputer/src/tinybus_module/README.md index 5972de77a..f50098b02 100644 --- a/crates/tinycomputer/src/tinybus_module/README.md +++ b/crates/tinycomputer/src/tinybus_module/README.md @@ -54,11 +54,13 @@ against a scripted engine, so no browser is launched. The module takes its configuration from the loader as a JSON object, parsed into `Desktop` by `Desktop::from_config`: `session_id` and `trace_path` as strings, -`trace_strict`, `trace_sink`, and `headed` as booleans. Setting `trace_sink` to -`true` opts into the host's confidential `TraceSinkHost` interface for ordered -desktop trace events, trace artifacts, and requested task reports; selected -sink mode never writes local trace files. Leaving it absent or `false` retains -the existing `trace_path` and session behavior. `browser` sets how every browser +`trace_strict` and `headed` as booleans. Setting `trace_sink` to an object with +the unique `destination` supplied by `ModuleHost::prepare_host_callbacks` opts +into the host's confidential `TraceSinkHost` interface for ordered desktop +trace events, trace artifacts, and requested task reports; selected sink mode +never writes local trace files. Leaving it absent or `false` retains the +existing `trace_path` and session behavior. `true` without a callback +destination is rejected. `browser` sets how every browser launches — `executable`, `user_agent`, `args`, a task's page `perception`, how a page `settle`s after an action, and whether to `prelaunch` a planned browser task's browser (a planned task also warms diff --git a/crates/tinycomputer/src/tinybus_module/config.rs b/crates/tinycomputer/src/tinybus_module/config.rs index e0a2c32b2..9e95370c5 100644 --- a/crates/tinycomputer/src/tinybus_module/config.rs +++ b/crates/tinycomputer/src/tinybus_module/config.rs @@ -135,16 +135,49 @@ impl BrowserDefaults { } /// Whether the host explicitly selected the trace/report callback. -pub(crate) fn trace_sink_requested(config: &serde_json::Value) -> Result { +pub(crate) fn trace_sink_destination( + config: &serde_json::Value, +) -> Result> { match config .as_object() .and_then(|object| object.get("trace_sink")) { - None => Ok(false), - Some(serde_json::Value::Bool(enabled)) => Ok(*enabled), + None | Some(serde_json::Value::Bool(false)) => Ok(None), + Some(serde_json::Value::Bool(true)) => Err(crate::Error::ConfigFieldType { + field: "trace_sink", + expected: "an object with the trusted host callback `destination`", + }), + Some(serde_json::Value::Object(options)) => { + if options.len() != 1 { + return Err(crate::Error::ConfigFieldType { + field: "trace_sink", + expected: "an object containing only the trusted host callback `destination`", + }); + } + let destination = options + .get("destination") + .and_then(serde_json::Value::as_str) + .ok_or(crate::Error::ConfigFieldType { + field: "trace_sink.destination", + expected: "the unique name of the host callback prepared for this module", + })?; + tinybus::BusName::new(destination.to_owned()) + .map_err(|_| crate::Error::ConfigFieldType { + field: "trace_sink.destination", + expected: "the unique name of the host callback prepared for this module", + }) + .and_then(|name| { + name.is_unique() + .then_some(Some(name)) + .ok_or(crate::Error::ConfigFieldType { + field: "trace_sink.destination", + expected: "the unique name of the host callback prepared for this module", + }) + }) + } Some(_) => Err(crate::Error::ConfigFieldType { field: "trace_sink", - expected: "a boolean", + expected: "false or an object with the trusted host callback `destination`", }), } } diff --git a/crates/tinycomputer/src/tinybus_module/dispatch/service.rs b/crates/tinycomputer/src/tinybus_module/dispatch/service.rs index bf786476e..013742ba2 100644 --- a/crates/tinycomputer/src/tinybus_module/dispatch/service.rs +++ b/crates/tinycomputer/src/tinybus_module/dispatch/service.rs @@ -35,10 +35,10 @@ impl DesktopService { config: &serde_json::Value, connection: tinybus::Connection, ) -> TinyBusResult { - let trace_link = if super::config::trace_sink_requested(config) + let trace_link = if let Some(destination) = super::config::trace_sink_destination(config) .map_err(|error| TinyBusError::failed(error.to_string()))? { - Some(TraceLink::new(connection.clone())?) + Some(TraceLink::new(connection.clone(), destination)?) } else { None }; diff --git a/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/config_tests.rs b/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/config_tests.rs index 27a37f3dc..68afea45f 100644 --- a/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/config_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/config_tests.rs @@ -269,11 +269,32 @@ fn the_cursor_is_configured_or_refused() { } #[test] -fn trace_sink_is_an_explicit_boolean_opt_in() { - use crate::tinybus_module::config::trace_sink_requested; +fn trace_sink_requires_the_host_prepared_unique_destination() { + use crate::tinybus_module::config::trace_sink_destination; - assert!(!trace_sink_requested(&json!({})).unwrap()); - assert!(trace_sink_requested(&json!({"trace_sink": true})).unwrap()); - assert!(!trace_sink_requested(&json!({"trace_sink": false})).unwrap()); - assert!(trace_sink_requested(&json!({"trace_sink": "yes"})).is_err()); + assert!(trace_sink_destination(&json!({})).unwrap().is_none()); + assert!( + trace_sink_destination(&json!({"trace_sink": false})) + .unwrap() + .is_none() + ); + assert!(trace_sink_destination(&json!({"trace_sink": true})).is_err()); + assert!(trace_sink_destination(&json!({"trace_sink": {}})).is_err()); + assert!( + trace_sink_destination(&json!({ + "trace_sink": {"destination": ":1.42", "scope": "caller-selected"} + })) + .is_err() + ); + assert!( + trace_sink_destination(&json!({"trace_sink": {"destination": "org.example.Host"}})) + .is_err() + ); + assert_eq!( + trace_sink_destination(&json!({"trace_sink": {"destination": ":1.42"}})) + .unwrap() + .unwrap() + .as_str(), + ":1.42" + ); } diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs index b9dc76940..d445cf5c3 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs @@ -4,11 +4,14 @@ //! task is on a Tokio executor thread. This port moves every trace callback to //! one dedicated worker before making a bounded synchronous wait, so the bus //! acknowledgement never runs on the caller's executor thread. One worker -//! preserves event order for this module instance. +//! preserves accepted event order for this module instance. A shared in-flight +//! guard refuses overlapping callbacks as bounded backpressure; it does not +//! identify whether a call is causally re-entrant. use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{self, Receiver, RecvTimeoutError, SyncSender, TrySendError}; -use std::time::Duration; +use std::time::{Duration, Instant}; use serde::Serialize; use serde::de::DeserializeOwned; @@ -24,15 +27,29 @@ use tinycomputer_desktop::{ const CALL_TIMEOUT: Duration = Duration::from_secs(10); enum Command { - Append(TraceEvent, SyncSender>), - StoreArtifact(TraceArtifact, SyncSender>), + Append { + record: serde_json::Value, + deadline: Instant, + byte_budget: u64, + reply: SyncSender>, + }, + StoreArtifact { + kind: TraceArtifactKind, + name: String, + bytes: Vec, + deadline: Instant, + limits: tinycomputer_bus::trace_sink::TraceArtifactLimits, + reply: SyncSender>, + }, } /// The synchronous sink adapter, backed by a worker that owns the bus calls. #[derive(Clone)] pub(crate) struct TraceLink { connection: Connection, + destination: tinybus::BusName, worker: SyncSender, + callback_active: Arc, } impl std::fmt::Debug for TraceLink { @@ -42,8 +59,14 @@ impl std::fmt::Debug for TraceLink { } impl TraceLink { - pub(crate) fn new(connection: Connection) -> TinyBusResult> { + pub(crate) fn new( + connection: Connection, + destination: tinybus::BusName, + ) -> TinyBusResult> { let worker_connection = connection.clone(); + let worker_destination = destination.clone(); + let callback_active = Arc::new(AtomicBool::new(false)); + let worker_callback_active = callback_active.clone(); let runtime = tokio::runtime::Handle::current(); if runtime.runtime_flavor() != tokio::runtime::RuntimeFlavor::MultiThread { return Err(TinyBusError::failed( @@ -53,15 +76,27 @@ impl TraceLink { let (sender, receiver) = mpsc::sync_channel(1); std::thread::Builder::new() .name("tinycomputer-trace-sink".into()) - .spawn(move || worker(runtime, worker_connection, receiver)) + .spawn(move || { + worker( + runtime, + worker_connection, + worker_destination, + worker_callback_active, + receiver, + ) + }) .map_err(|error| TinyBusError::failed(format!("trace sink worker failed: {error}")))?; Ok(Arc::new(Self { connection, + destination, worker: sender, + callback_active, })) } pub(crate) async fn write_report(&self, record: TaskReportRecord) -> TinyBusResult<()> { + let _guard = CallbackGuard::try_acquire(&self.callback_active) + .ok_or_else(|| TinyBusError::failed("trace sink callback is busy"))?; call::( &self.proxy(CALL_TIMEOUT)?, trace_sink::methods::WRITE_REPORT, @@ -74,7 +109,7 @@ impl TraceLink { fn proxy(&self, timeout: Duration) -> TinyBusResult { self.connection .proxy( - trace_sink::INTERFACE, + self.destination.as_str(), trace_sink::OBJECT_PATH, trace_sink::INTERFACE, ) @@ -82,31 +117,79 @@ impl TraceLink { } } -fn worker(runtime: tokio::runtime::Handle, connection: Connection, receiver: Receiver) { +fn worker( + runtime: tokio::runtime::Handle, + connection: Connection, + destination: tinybus::BusName, + callback_active: Arc, + receiver: Receiver, +) { while let Ok(command) = receiver.recv() { match command { - Command::Append(record, reply) => { - let timeout = timeout(record.deadline_ms); + Command::Append { + record, + deadline, + byte_budget, + reply, + } => { + let Some(_guard) = CallbackGuard::try_acquire(&callback_active) else { + let _ = reply.send(Err(())); + continue; + }; + let Some(timeout) = remaining_timeout(deadline) else { + let _ = reply.send(Err(())); + continue; + }; + let Some(deadline_ms) = remaining_millis(deadline) else { + let _ = reply.send(Err(())); + continue; + }; let result = runtime.block_on(async { let proxy = connection .proxy( - trace_sink::INTERFACE, + destination.as_str(), trace_sink::OBJECT_PATH, trace_sink::INTERFACE, )? .with_timeout(timeout); - call::(&proxy, trace_sink::methods::APPEND, (record,)) - .await - .map(|_| ()) + call::( + &proxy, + trace_sink::methods::APPEND, + (TraceEvent { + record, + deadline_ms, + byte_budget, + },), + ) + .await + .map(|_| ()) }); let _ = reply.send(result.map_err(|_| ())); } - Command::StoreArtifact(artifact, reply) => { - let timeout = timeout(artifact.deadline_ms); + Command::StoreArtifact { + kind, + name, + bytes, + deadline, + limits, + reply, + } => { + let Some(_guard) = CallbackGuard::try_acquire(&callback_active) else { + let _ = reply.send(Err(())); + continue; + }; + let Some(timeout) = remaining_timeout(deadline) else { + let _ = reply.send(Err(())); + continue; + }; + let Some(deadline_ms) = remaining_millis(deadline) else { + let _ = reply.send(Err(())); + continue; + }; let result = runtime.block_on(async { let proxy = connection .proxy( - trace_sink::INTERFACE, + destination.as_str(), trace_sink::OBJECT_PATH, trace_sink::INTERFACE, )? @@ -114,7 +197,13 @@ fn worker(runtime: tokio::runtime::Handle, connection: Connection, receiver: Rec call::( &proxy, trace_sink::methods::STORE_ARTIFACT, - (artifact,), + (TraceArtifact { + kind, + name, + bytes, + deadline_ms, + limits, + },), ) .await .map(|reply| reply.reference) @@ -125,30 +214,48 @@ fn worker(runtime: tokio::runtime::Handle, connection: Connection, receiver: Rec } } -#[cfg(test)] async fn call(proxy: &Proxy, member: &str, args: A) -> TinyBusResult where T: DeserializeOwned, A: Serialize, { - proxy.call(member, args).await + proxy.call_confidential(member, args).await } -#[cfg(not(test))] -async fn call(proxy: &Proxy, member: &str, args: A) -> TinyBusResult -where - T: DeserializeOwned, - A: Serialize, -{ - proxy.call_confidential(member, args).await +fn remaining_timeout(deadline: Instant) -> Option { + let remaining = deadline.checked_duration_since(Instant::now())?; + let timeout = remaining.min(CALL_TIMEOUT); + (timeout.as_millis() > 0).then_some(timeout) +} + +fn remaining_millis(deadline: Instant) -> Option { + let remaining = deadline.checked_duration_since(Instant::now())?; + let millis = u64::try_from(remaining.as_millis()).unwrap_or(u64::MAX); + (millis > 0).then_some(millis) } -fn timeout(deadline_ms: u64) -> Duration { - Duration::from_millis(deadline_ms.max(1)).min(CALL_TIMEOUT) +struct CallbackGuard<'a>(&'a AtomicBool); + +impl<'a> CallbackGuard<'a> { + fn try_acquire(active: &'a AtomicBool) -> Option { + active + .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) + .ok() + .map(|_| Self(active)) + } } -fn remaining_ms(deadline: TraceSinkDeadline) -> u64 { - u64::try_from(deadline.remaining().as_millis()).unwrap_or(u64::MAX) +impl Drop for CallbackGuard<'_> { + fn drop(&mut self) { + self.0.store(false, Ordering::Release); + } +} + +fn operation_deadline(deadline: TraceSinkDeadline) -> Option { + let remaining = deadline.remaining(); + (!remaining.is_zero()) + .then(|| Instant::now().checked_add(remaining)) + .flatten() } fn receive(receiver: &mpsc::Receiver, timeout: Duration) -> Result { @@ -170,17 +277,23 @@ impl EngineTraceSink for TraceLink { deadline: TraceSinkDeadline, byte_budget: u64, ) -> std::result::Result<(), TraceSinkError> { - let deadline_ms = remaining_ms(deadline); + if self.callback_active.load(Ordering::Acquire) { + return Err(TraceSinkError::Internal( + "trace sink callback is busy".into(), + )); + } + let deadline = operation_deadline(deadline) + .ok_or_else(|| TraceSinkError::Internal("trace sink deadline expired".into()))?; + let timeout = remaining_timeout(deadline) + .ok_or_else(|| TraceSinkError::Internal("trace sink deadline expired".into()))?; let (reply, result) = mpsc::sync_channel(1); self.worker - .try_send(Command::Append( - TraceEvent { - record: record.clone(), - deadline_ms, - byte_budget, - }, + .try_send(Command::Append { + record: record.clone(), + deadline, + byte_budget, reply, - )) + }) .map_err(|error| match error { TrySendError::Full(_) => { TraceSinkError::Internal("trace sink worker is busy".into()) @@ -189,7 +302,7 @@ impl EngineTraceSink for TraceLink { TraceSinkError::Internal("trace sink worker stopped".into()) } })?; - receive(&result, timeout(deadline_ms)) + receive(&result, timeout) .map_err(|_| TraceSinkError::Internal("trace sink acknowledgment timed out".into()))? .map_err(|_| TraceSinkError::Internal("trace sink rejected event".into())) } @@ -199,27 +312,33 @@ impl EngineTraceSink for TraceLink { artifact: TraceSinkArtifact<'_>, limits: TraceSinkArtifactLimits, ) -> std::result::Result { - let deadline_ms = remaining_ms(artifact.deadline); + if self.callback_active.load(Ordering::Acquire) { + return Err(TraceSinkError::Internal( + "trace sink callback is busy".into(), + )); + } + let deadline = operation_deadline(artifact.deadline) + .ok_or_else(|| TraceSinkError::Internal("trace artifact deadline expired".into()))?; + let timeout = remaining_timeout(deadline) + .ok_or_else(|| TraceSinkError::Internal("trace artifact deadline expired".into()))?; let (reply, result) = mpsc::sync_channel(1); let kind = match artifact.kind { EngineArtifactKind::Screenshot => TraceArtifactKind::Screenshot, EngineArtifactKind::RefMap => TraceArtifactKind::RefMap, }; self.worker - .try_send(Command::StoreArtifact( - TraceArtifact { - kind, - name: artifact.name.to_owned(), - bytes: artifact.bytes.to_vec(), - deadline_ms, - limits: tinycomputer_bus::trace_sink::TraceArtifactLimits { - screenshot_bytes: limits.screenshot_bytes, - screenshot_count: limits.screenshot_count, - refmap_bytes: limits.refmap_bytes, - }, + .try_send(Command::StoreArtifact { + kind, + name: artifact.name.to_owned(), + bytes: artifact.bytes.to_vec(), + deadline, + limits: tinycomputer_bus::trace_sink::TraceArtifactLimits { + screenshot_bytes: limits.screenshot_bytes, + screenshot_count: limits.screenshot_count, + refmap_bytes: limits.refmap_bytes, }, reply, - )) + }) .map_err(|error| match error { TrySendError::Full(_) => { TraceSinkError::Internal("trace sink worker is busy".into()) @@ -228,7 +347,7 @@ impl EngineTraceSink for TraceLink { TraceSinkError::Internal("trace sink worker stopped".into()) } })?; - receive(&result, timeout(deadline_ms)) + receive(&result, timeout) .map_err(|_| { TraceSinkError::Internal("trace artifact acknowledgment timed out".into()) })? diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs index 456d9941c..f8f5e9ceb 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs @@ -3,192 +3,81 @@ use std::sync::Mutex; use tinycomputer_bus::trace_sink::TraceEvent; #[derive(Clone, Default)] -struct RecordingHost { - events: Arc>>, - artifacts: Arc>>, - reports: Arc>>, - fail: bool, -} +struct RecordingHost(Arc>>); #[tinybus::interface(name = "ai.tinyhumans.tinycomputer.TraceSinkHost")] impl RecordingHost { - async fn append(&self, request: TraceEvent) -> TinyBusResult { - if self.fail { - return Err(TinyBusError::failed("sink refused event")); - } - self.events.lock().unwrap().push(request.record); + async fn append(&self, event: TraceEvent) -> TinyBusResult { + self.0.lock().unwrap().push(event.record); Ok(SinkAck {}) } - async fn store_artifact(&self, request: TraceArtifact) -> TinyBusResult { - if self.fail { - return Err(TinyBusError::failed("sink refused artifact")); - } - self.artifacts.lock().unwrap().push(request.clone()); - Ok(TraceArtifactRef { - reference: format!("opaque:{}", request.name), - }) + async fn store_artifact(&self, _: TraceArtifact) -> TinyBusResult { + Err(TinyBusError::failed("unused by deadline test")) } - async fn write_report(&self, request: TaskReportRecord) -> TinyBusResult { - if self.fail { - return Err(TinyBusError::failed("sink refused report")); - } - self.reports.lock().unwrap().push(request); - Ok(SinkAck {}) + async fn write_report(&self, _: TaskReportRecord) -> TinyBusResult { + Err(TinyBusError::failed("unused by deadline test")) } } -async fn setup_host( - bus: &tinybus::transport::memory::MemoryBus, - host: RecordingHost, -) -> TinyBusResult { - let connection = Connection::connect(bus.connect().await?).await?; - connection - .serve_at(trace_sink::OBJECT_PATH.try_into()?, host) - .await?; - connection.request_name(trace_sink::INTERFACE).await?; - Ok(connection) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn trace_calls_are_ordered_and_artifacts_and_reports_reach_the_host() -> TinyBusResult<()> { - use tinycomputer_bus::agent::TaskReport; +#[test] +fn an_expired_deadline_is_never_renewed() { + let deadline = Instant::now() - Duration::from_millis(1); - let bus = tinybus::transport::memory::MemoryBus::new(); - tinybus::broker::Broker::new().spawn(bus.clone()); - let host = RecordingHost::default(); - let _host_connection = setup_host(&bus, host.clone()).await?; - let module = Connection::connect(bus.connect().await?).await?; - let link = TraceLink::new(module)?; - - let first = serde_json::json!({"event": "first", "seq": 1}); - let second = serde_json::json!({"event": "second", "seq": 2}); - link.append(&first, TraceSinkDeadline::standard().unwrap(), 4096) - .expect("async executor callback is acknowledged"); - let trace_link = link.clone(); - tokio::task::spawn_blocking(move || { - trace_link - .append(&second, TraceSinkDeadline::standard().unwrap(), 4096) - .unwrap(); - trace_link - .store_artifact( - TraceSinkArtifact { - kind: EngineArtifactKind::Screenshot, - name: "screen.png", - bytes: b"image", - deadline: TraceSinkDeadline::standard().unwrap(), - }, - TraceSinkArtifactLimits { - screenshot_bytes: 100, - screenshot_count: 2, - refmap_bytes: 100, - }, - ) - .unwrap() - }) - .await - .expect("trace worker task completes"); + assert!(remaining_timeout(deadline).is_none()); + assert!(remaining_millis(deadline).is_none()); +} - let report = TaskReportRecord { - task_id: "task-1".into(), - report: serde_json::from_value::(serde_json::json!({ - "view": {"id": "task-1"}, - "steps": [], "records": {}, "artifacts": [], "learned": [], "trace": [] - })) - .unwrap(), - }; - link.write_report(report).await?; +#[test] +fn callback_timeout_is_capped_without_extending_the_operation_deadline() { + let deadline = Instant::now() + CALL_TIMEOUT * 2; + let timeout = remaining_timeout(deadline).expect("future deadline"); - assert_eq!( - *host.events.lock().unwrap(), - [ - serde_json::json!({"event": "first", "seq": 1}), - serde_json::json!({"event": "second", "seq": 2}) - ] - ); - assert_eq!(host.artifacts.lock().unwrap()[0].name, "screen.png"); - assert_eq!(host.reports.lock().unwrap()[0].task_id, "task-1"); - Ok(()) + assert!(timeout <= CALL_TIMEOUT); + assert!(deadline > Instant::now()); } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn sink_failures_are_returned_without_fallback() -> TinyBusResult<()> { - let bus = tinybus::transport::memory::MemoryBus::new(); - tinybus::broker::Broker::new().spawn(bus.clone()); - let _host_connection = setup_host( - &bus, - RecordingHost { - fail: true, - ..Default::default() - }, - ) - .await?; - let module = Connection::connect(bus.connect().await?).await?; - let link = TraceLink::new(module)?; +#[test] +fn overlapping_callbacks_are_refused_until_the_outer_delivery_finishes() { + let active = AtomicBool::new(false); - let trace_link = link.clone(); - let error = tokio::task::spawn_blocking(move || { - trace_link.append( - &serde_json::json!({"event": "rejected"}), - TraceSinkDeadline::standard().unwrap(), - 4096, - ) - }) - .await - .expect("trace worker task completes") - .expect_err("host failure must be returned to strict desktop trace"); - assert!(error.to_string().contains("rejected")); - assert!( - link.write_report(TaskReportRecord { - task_id: "task-1".into(), - report: serde_json::from_value(serde_json::json!({ - "view": {"id": "task-1"}, - "steps": [], "records": {}, "artifacts": [], "learned": [], "trace": [] - })) - .unwrap(), - }) - .await - .is_err() - ); - Ok(()) + { + let _outer = CallbackGuard::try_acquire(&active).expect("first callback acquires guard"); + assert!(CallbackGuard::try_acquire(&active).is_none()); + } + + assert!(CallbackGuard::try_acquire(&active).is_some()); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn task_report_member_persists_its_report_before_returning() -> TinyBusResult<()> { - use tinybus::Interface; - use tinycomputer_bus::agent::{AgentResponse, TaskView}; - use tinycomputer_bus::names; - +async fn expired_queued_event_is_rejected_without_a_late_host_write() -> TinyBusResult<()> { let bus = tinybus::transport::memory::MemoryBus::new(); tinybus::broker::Broker::new().spawn(bus.clone()); + let host_connection = Connection::connect(bus.connect().await?).await?; let host = RecordingHost::default(); - let _host_connection = setup_host(&bus, host.clone()).await?; - let module = Connection::connect(bus.connect().await?).await?; - let service = crate::tinybus_module::dispatch::DesktopService::from_config_with_connection( - &serde_json::json!({"trace_sink": true}), - module, - ) - .await? - .with_native_fixture(); - - let started = service - .call( - &names::methods::START_TASK.try_into()?, - serde_json::json!([{"flow": {"app": "Mail", "steps": ["start a note"]}}]), - ) - .await?; - let started: AgentResponse = serde_json::from_value(started)?; - let id = started.data.expect("task starts").id; - let report = service - .call( - &names::methods::TASK_REPORT.try_into()?, - serde_json::json!([{"id": id, "trace": false}]), - ) + host_connection + .serve_at(trace_sink::OBJECT_PATH.try_into()?, host.clone()) .await?; - - assert!(report["ok"].as_bool().unwrap_or(false)); - assert_eq!(host.reports.lock().unwrap().len(), 1); - assert_eq!(host.reports.lock().unwrap()[0].task_id, id.to_string()); + host_connection.request_name(trace_sink::INTERFACE).await?; + let module = Connection::connect(bus.connect().await?).await?; + let link = TraceLink::new(module, tinybus::BusName::new(trace_sink::INTERFACE)?)?; + let (reply, result) = mpsc::sync_channel(1); + link.worker + .try_send(Command::Append { + record: serde_json::json!({"event": "expired"}), + deadline: Instant::now() - Duration::from_millis(1), + byte_budget: 4096, + reply, + }) + .expect("worker accepts the expired command for rejection"); + let acknowledgment = + tokio::task::spawn_blocking(move || result.recv_timeout(Duration::from_secs(1))) + .await + .expect("acknowledgment waiter completes") + .expect("worker sends a result"); + + assert!(acknowledgment.is_err()); + assert!(host.0.lock().unwrap().is_empty()); Ok(()) } From 54f65273b956d7bcbd9c42f350a76705ab8976de Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Mon, 19 Oct 2026 20:24:42 +0300 Subject: [PATCH 03/48] test: reject expired queued trace events --- .../trace_sink/trace_sink_tests.rs | 107 +++++++++++++++++- 1 file changed, 106 insertions(+), 1 deletion(-) diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs index f8f5e9ceb..488f045ef 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs @@ -51,7 +51,7 @@ fn overlapping_callbacks_are_refused_until_the_outer_delivery_finishes() { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn expired_queued_event_is_rejected_without_a_late_host_write() -> TinyBusResult<()> { +async fn an_already_expired_queued_event_is_rejected_without_a_host_write() -> TinyBusResult<()> { let bus = tinybus::transport::memory::MemoryBus::new(); tinybus::broker::Broker::new().spawn(bus.clone()); let host_connection = Connection::connect(bus.connect().await?).await?; @@ -81,3 +81,108 @@ async fn expired_queued_event_is_rejected_without_a_late_host_write() -> TinyBus assert!(host.0.lock().unwrap().is_empty()); Ok(()) } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn expired_queued_event_is_rejected_without_a_late_host_write() -> TinyBusResult<()> { + let bus = tinybus::transport::memory::MemoryBus::new(); + tinybus::broker::Broker::new().spawn(bus.clone()); + let host_connection = Connection::connect(bus.connect().await?).await?; + let (started_tx, started_rx) = tokio::sync::oneshot::channel(); + let (release_tx, release_rx) = tokio::sync::oneshot::channel(); + let host = BlockingRecordingHost { + events: Arc::default(), + started: Arc::new(std::sync::Mutex::new(Some(started_tx))), + release: Arc::new(std::sync::Mutex::new(Some(release_rx))), + }; + host_connection + .serve_at(trace_sink::OBJECT_PATH.try_into()?, host.clone()) + .await?; + host_connection.request_name(trace_sink::INTERFACE).await?; + let module = Connection::connect(bus.connect().await?).await?; + let link = TraceLink::new(module, tinybus::BusName::new(trace_sink::INTERFACE)?)?; + let (first_reply, first_result) = mpsc::sync_channel(1); + link.worker + .try_send(Command::Append { + record: serde_json::json!({"event": "blocker"}), + deadline: Instant::now() + Duration::from_secs(10), + byte_budget: 4096, + reply: first_reply, + }) + .expect("worker accepts the command that blocks its callback"); + tokio::time::timeout(Duration::from_secs(5), started_rx) + .await + .expect("first callback starts") + .expect("host signals that it is blocking the worker"); + + let (queued_reply, queued_result) = mpsc::sync_channel(1); + let queued_deadline = Instant::now() + Duration::from_millis(50); + link.worker + .try_send(Command::Append { + record: serde_json::json!({"event": "expired"}), + deadline: queued_deadline, + byte_budget: 4096, + reply: queued_reply, + }) + .expect("worker queue accepts the second command while processing the first"); + tokio::time::sleep_until( + tokio::time::Instant::from_std(queued_deadline) + Duration::from_millis(1), + ) + .await; + release_tx + .send(()) + .expect("test releases the first host callback"); + + let first_ack = + tokio::task::spawn_blocking(move || first_result.recv_timeout(Duration::from_secs(5))) + .await + .expect("first acknowledgment waiter completes") + .expect("worker acknowledges the first command"); + let queued_ack = + tokio::task::spawn_blocking(move || queued_result.recv_timeout(Duration::from_secs(5))) + .await + .expect("queued acknowledgment waiter completes") + .expect("worker rejects the expired queued command"); + + assert!(first_ack.is_ok()); + assert!(queued_ack.is_err()); + assert_eq!( + host.events.lock().unwrap().as_slice(), + &[serde_json::json!({"event": "blocker"})], + "the expired queued event must not be written late" + ); + Ok(()) +} + +#[derive(Clone)] +struct BlockingRecordingHost { + events: Arc>>, + started: Arc>>>, + release: Arc>>>, +} + +#[tinybus::interface(name = "ai.tinyhumans.tinycomputer.TraceSinkHost")] +impl BlockingRecordingHost { + async fn append(&self, event: TraceEvent) -> TinyBusResult { + if event.record["event"] == "blocker" { + if let Some(started) = self.started.lock().unwrap().take() { + let _ = started.send(()); + } + let release = self.release.lock().unwrap().take(); + if let Some(release) = release { + release + .await + .map_err(|_| TinyBusError::failed("test callback was not released"))?; + } + } + self.events.lock().unwrap().push(event.record); + Ok(SinkAck {}) + } + + async fn store_artifact(&self, _: TraceArtifact) -> TinyBusResult { + Err(TinyBusError::failed("unused by queued deadline test")) + } + + async fn write_report(&self, _: TaskReportRecord) -> TinyBusResult { + Err(TinyBusError::failed("unused by queued deadline test")) + } +} From 3864b0355cf453e05b0a723419d121b485566e8b Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Mon, 19 Oct 2026 20:24:46 +0300 Subject: [PATCH 04/48] chore: use merged agent-desktop trace sink --- vendor/agent-desktop | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vendor/agent-desktop b/vendor/agent-desktop index 9d7ba42a9..72f8af2f2 160000 --- a/vendor/agent-desktop +++ b/vendor/agent-desktop @@ -1 +1 @@ -Subproject commit 9d7ba42a94bc4ec018e624f3033602188f64af63 +Subproject commit 72f8af2f2bfb08a691fd374b6f2163061b83ea3c From b62b0a638548a9441c14bf88a340297c156c3f03 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Mon, 19 Oct 2026 20:27:01 +0300 Subject: [PATCH 05/48] test: verify compiled trace sink callback --- .../src/bin/verify_module.rs | 44 +++++++++++++++++++ .../tinycomputer/src/tinybus_module/README.md | 5 ++- 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/crates/tinycomputer-examples/src/bin/verify_module.rs b/crates/tinycomputer-examples/src/bin/verify_module.rs index dd944117a..79814fcdd 100644 --- a/crates/tinycomputer-examples/src/bin/verify_module.rs +++ b/crates/tinycomputer-examples/src/bin/verify_module.rs @@ -70,11 +70,21 @@ async fn main() -> Result<(), Box> { }]) .await?; let capture = TraceSinkCapture::default(); + let trace_path = std::env::temp_dir().join(format!( + "tinycomputer-module-trace-{}-{}.jsonl", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH)? + .as_nanos() + )); + let _trace_path = RemoveTraceFileOnDrop(trace_path.clone()); callback .serve_at(trace_sink::OBJECT_PATH.parse()?, capture.clone()) .await?; let config = serde_json::json!({ "trace_sink": {"destination": callback.unique_name()}, + "trace_path": trace_path.to_string_lossy(), + "trace_strict": true, }); let info = module_host .load_file_with_host_callbacks(&module, config, &callback) @@ -114,6 +124,7 @@ async fn main() -> Result<(), Box> { )) .into()); } + verify_trace_sink(&capture, &trace_path)?; verify_report_sink(&proxy, &capture).await?; @@ -156,6 +167,39 @@ async fn main() -> Result<(), Box> { Ok(()) } +/// Removes a trace path if a regression sends sink-mode events to disk. +struct RemoveTraceFileOnDrop(PathBuf); + +impl Drop for RemoveTraceFileOnDrop { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } +} + +/// Proves the loaded module emits a native desktop trace through its callback. +fn verify_trace_sink( + capture: &TraceSinkCapture, + legacy_path: &std::path::Path, +) -> Result<(), Box> { + if legacy_path.exists() { + return Err(io::Error::other("trace sink mode wrote the legacy trace file").into()); + } + let events = capture.events.lock().unwrap(); + let names = events + .iter() + .filter_map(|event| event.get("event").and_then(serde_json::Value::as_str)) + .collect::>(); + for required in ["trace.meta", "command.start", "command.end"] { + if !names.contains(&required) { + return Err(io::Error::other(format!( + "loaded module trace callback did not receive `{required}`" + )) + .into()); + } + } + Ok(()) +} + /// Exercises report delivery through the exact confidential callback binding. async fn verify_report_sink( proxy: &tinybus::Proxy, diff --git a/crates/tinycomputer/src/tinybus_module/README.md b/crates/tinycomputer/src/tinybus_module/README.md index f50098b02..14fe71654 100644 --- a/crates/tinycomputer/src/tinybus_module/README.md +++ b/crates/tinycomputer/src/tinybus_module/README.md @@ -85,7 +85,10 @@ of this module's own source, because reading them back out of the exported Integration tests use TinyBus's in-memory transport, and `crates/tinycomputer-examples/src/bin/verify_module.rs` loads a compiled `cdylib` through -the real dynamic loader before a release archive is accepted. +the real dynamic loader before a release archive is accepted. Its trace-sink +fixture invokes the no-permission `Version` member, checks captured native trace +records and confirms sink mode leaves the configured legacy trace path absent; +it also verifies successful and failed confidential task-report writes. ## Native accessibility lifecycle From 485879b71b8dfa0521599feaba668e065bb9242f Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 16:40:00 +0000 Subject: [PATCH 06/48] Fix desktop adapter for current engine APIs Co-authored-by: Medulla --- .../src/trace_sink/trace_sink_tests.rs | 28 ++-- .../tinycomputer-desktop/src/desktop/apps.rs | 16 ++- .../src/desktop/convert.rs | 27 +++- .../desktop/desktop_tests/convert_tests.rs | 46 +++++-- .../tinycomputer-desktop/src/desktop/input.rs | 10 +- .../src/desktop/interaction.rs | 12 +- .../tinycomputer-desktop/src/desktop/mod.rs | 13 +- .../src/desktop/observation.rs | 19 +-- .../src/desktop/trace_sink_tests.rs | 13 +- .../src/desktop/waiting.rs | 5 +- .../src/bin/verify_module.rs | 29 ++++- .../src/tinybus_module/dispatch/service.rs | 10 +- crates/tinycomputer/src/tinybus_module/mod.rs | 2 +- .../src/tinybus_module/trace_sink/mod.rs | 71 +++++++--- .../trace_sink/trace_sink_tests.rs | 122 ++++++++++-------- 15 files changed, 279 insertions(+), 144 deletions(-) diff --git a/crates/tinycomputer-bus/src/trace_sink/trace_sink_tests.rs b/crates/tinycomputer-bus/src/trace_sink/trace_sink_tests.rs index 7341a1477..d2bb60c99 100644 --- a/crates/tinycomputer-bus/src/trace_sink/trace_sink_tests.rs +++ b/crates/tinycomputer-bus/src/trace_sink/trace_sink_tests.rs @@ -1,7 +1,7 @@ use super::*; #[test] -fn sink_records_keep_their_wire_shapes() { +fn sink_records_keep_their_wire_shapes() -> Result<(), serde_json::Error> { let event = TraceEvent { record: serde_json::json!({ "event": "command.end", "seq": 4, "session_id": "s1" @@ -9,7 +9,7 @@ fn sink_records_keep_their_wire_shapes() { deadline_ms: 900, byte_budget: 4096, }; - let wire = serde_json::to_value(event).unwrap(); + let wire = serde_json::to_value(event)?; assert_eq!(wire["record"]["event"], "command.end"); assert_eq!(wire["deadline_ms"], 900); assert_eq!(wire["byte_budget"], 4096); @@ -25,30 +25,38 @@ fn sink_records_keep_their_wire_shapes() { refmap_bytes: 20, }, }; - let wire = serde_json::to_value(artifact).unwrap(); + let wire = serde_json::to_value(artifact)?; assert_eq!(wire["kind"], "ref_map"); assert_eq!(wire["bytes"], serde_json::json!([1, 2])); assert_eq!(wire["limits"]["refmap_bytes"], 20); + Ok(()) } #[test] -fn report_record_reuses_the_agent_report_contract() { +fn report_record_reuses_the_agent_report_contract() -> Result<(), serde_json::Error> { let report = TaskReportRecord { task_id: "task-1".into(), report: serde_json::from_value(serde_json::json!({ - "view": {"id": "task-1"}, + "view": { + "id": "task-1", + "status": {"state": "running"}, + "summary": "running", + "progress": 0.0, + "next": [] + }, "steps": [], "records": {}, "artifacts": [], "learned": [], "trace": [] - })) - .unwrap(), + }))?, }; - let wire = serde_json::to_value(report).unwrap(); + let wire = serde_json::to_value(report)?; assert_eq!(wire["task_id"], "task-1"); assert_eq!(wire["report"]["trace"], serde_json::json!([])); + Ok(()) } #[test] -fn the_host_interface_is_separate_and_has_stable_member_names() { +fn the_host_interface_is_separate_and_has_stable_member_names() -> Result<(), serde_json::Error> { assert_ne!(INTERFACE, crate::names::INTERFACE); assert_eq!(METHODS, ["Append", "StoreArtifact", "WriteReport"]); - assert_eq!(SinkAck {}, serde_json::from_str("{}").unwrap()); + assert_eq!(SinkAck {}, serde_json::from_str("{}")?); + Ok(()) } diff --git a/crates/tinycomputer-desktop/src/desktop/apps.rs b/crates/tinycomputer-desktop/src/desktop/apps.rs index 955b721b3..2e1a6cda1 100644 --- a/crates/tinycomputer-desktop/src/desktop/apps.rs +++ b/crates/tinycomputer-desktop/src/desktop/apps.rs @@ -103,7 +103,13 @@ impl Desktop { #[must_use] pub fn list_apps(&self, request: ListAppsRequest) -> DesktopResponse { self.run("list-apps", Need::Nothing, |adapter, _context| { - list_apps::execute(list_apps::ListAppsArgs { app: request.app }, adapter) + list_apps::execute( + list_apps::ListAppsArgs { + app: request.app, + timeout_ms: None, + }, + adapter, + ) }) } @@ -119,7 +125,13 @@ impl Desktop { #[must_use] pub fn list_windows(&self, request: ListWindowsRequest) -> DesktopResponse { self.run("list-windows", Need::Nothing, |adapter, _context| { - list_windows::execute(list_windows::ListWindowsArgs { app: request.app }, adapter) + list_windows::execute( + list_windows::ListWindowsArgs { + app: request.app, + timeout_ms: None, + }, + adapter, + ) }) } diff --git a/crates/tinycomputer-desktop/src/desktop/convert.rs b/crates/tinycomputer-desktop/src/desktop/convert.rs index f3bd7ebc3..4a03e0a28 100644 --- a/crates/tinycomputer-desktop/src/desktop/convert.rs +++ b/crates/tinycomputer-desktop/src/desktop/convert.rs @@ -130,12 +130,26 @@ pub(super) fn path(value: Option) -> Option { /// Converts a contract ref action payload into the engine's shared arguments. pub(super) fn ref_args(request: bus::RefRequest) -> core::commands::helpers::RefArgs { core::commands::helpers::RefArgs { - ref_id: request.ref_id, - snapshot_id: request.snapshot_id, + ref_id: qualified_ref(request.ref_id, request.snapshot_id.as_deref()), timeout_ms: request.timeout_ms, } } +/// Adds a separate snapshot id to a bare local ref while preserving refs that +/// already carry their snapshot in the engine's canonical wire form. +pub(super) fn qualified_ref(ref_id: String, snapshot_id: Option<&str>) -> String { + let Some(snapshot_id) = snapshot_id else { + return ref_id; + }; + let Some(element_number) = ref_id.strip_prefix("@e") else { + return ref_id; + }; + if element_number.is_empty() || !element_number.chars().all(|digit| digit.is_ascii_digit()) { + return ref_id; + } + format!("@{snapshot_id}:e{element_number}") +} + /// Converts a contract window target into the engine's. pub(super) fn window_args(request: bus::WindowRequest) -> core::commands::helpers::AppArgs { core::commands::helpers::AppArgs { @@ -150,9 +164,14 @@ pub(super) fn window_args(request: bus::WindowRequest) -> core::commands::helper /// A half-specified point — an `x` with no `y` — becomes no point at all, and /// the engine reports the missing input by name. Guessing a zero for the other /// half would drag to the corner of the screen. -pub(super) fn drag_endpoint(endpoint: bus::DragEndpoint) -> core::commands::drag::DragEndpoint { +pub(super) fn drag_endpoint( + endpoint: bus::DragEndpoint, + snapshot_id: Option<&str>, +) -> core::commands::drag::DragEndpoint { core::commands::drag::DragEndpoint { - ref_id: endpoint.ref_id, + ref_id: endpoint + .ref_id + .map(|ref_id| qualified_ref(ref_id, snapshot_id)), xy: point(endpoint.x, endpoint.y), } } diff --git a/crates/tinycomputer-desktop/src/desktop/desktop_tests/convert_tests.rs b/crates/tinycomputer-desktop/src/desktop/desktop_tests/convert_tests.rs index 1f8fbd588..d550f610d 100644 --- a/crates/tinycomputer-desktop/src/desktop/desktop_tests/convert_tests.rs +++ b/crates/tinycomputer-desktop/src/desktop/desktop_tests/convert_tests.rs @@ -21,16 +21,16 @@ fn every_contract_surface_maps_onto_an_engine_surface() { (bus::Surface::Alert, "alert"), (bus::Surface::Desktop, "desktop"), (bus::Surface::Taskbar, "taskbar"), - (bus::Surface::SystemTray, "system_tray"), - (bus::Surface::QuickSettings, "quick_settings"), - (bus::Surface::NotificationCenter, "notification_center"), + (bus::Surface::SystemTray, "system-tray"), + (bus::Surface::QuickSettings, "quick-settings"), + (bus::Surface::NotificationCenter, "notification-center"), (bus::Surface::Toolbar, "toolbar"), (bus::Surface::Dock, "dock"), (bus::Surface::Spotlight, "spotlight"), - (bus::Surface::MenuBarExtras, "menu_bar_extras"), - (bus::Surface::SystemTrayOverflow, "system_tray_overflow"), - (bus::Surface::StartMenu, "start_menu"), - (bus::Surface::ActionCenter, "action_center"), + (bus::Surface::MenuBarExtras, "menu-bar-extras"), + (bus::Surface::SystemTrayOverflow, "system-tray-overflow"), + (bus::Surface::StartMenu, "start-menu"), + (bus::Surface::ActionCenter, "action-center"), ] { assert_eq!(convert::surface(contract).as_str(), engine); } @@ -99,15 +99,18 @@ fn a_half_specified_point_becomes_no_point_at_all() { #[test] fn a_drag_endpoint_carries_a_ref_or_a_point_but_never_half_of_one() { - let by_ref = convert::drag_endpoint(bus::DragEndpoint::at_ref("@s1:e2")); + let by_ref = convert::drag_endpoint(bus::DragEndpoint::at_ref("@s1:e2"), None); assert_eq!(by_ref.ref_id.as_deref(), Some("@s1:e2")); assert_eq!(by_ref.xy, None); - let half = convert::drag_endpoint(bus::DragEndpoint { - ref_id: None, - x: Some(1.0), - y: None, - }); + let half = convert::drag_endpoint( + bus::DragEndpoint { + ref_id: None, + x: Some(1.0), + y: None, + }, + None, + ); assert_eq!(half.xy, None); } @@ -130,10 +133,25 @@ fn a_ref_request_converts_field_for_field() { }); assert_eq!(args.ref_id, "@s1:e2"); - assert_eq!(args.snapshot_id.as_deref(), Some("s1")); assert_eq!(args.timeout_ms, Some(1_000)); } +#[test] +fn a_bare_ref_is_qualified_by_its_snapshot() { + assert_eq!( + convert::qualified_ref("@e2".to_owned(), Some("s1")), + "@s1:e2" + ); + assert_eq!( + convert::qualified_ref("@s2:e2".to_owned(), Some("s1")), + "@s2:e2" + ); + assert_eq!( + convert::qualified_ref("@@e2".to_owned(), Some("s1")), + "@@e2" + ); +} + #[test] fn a_window_request_converts_field_for_field() { let args = convert::window_args(bus::WindowRequest { diff --git a/crates/tinycomputer-desktop/src/desktop/input.rs b/crates/tinycomputer-desktop/src/desktop/input.rs index d9f7f1060..f2623e868 100644 --- a/crates/tinycomputer-desktop/src/desktop/input.rs +++ b/crates/tinycomputer-desktop/src/desktop/input.rs @@ -101,8 +101,9 @@ impl Desktop { self.run("hover", Need::Accessibility, |adapter, context| { hover::execute( hover::HoverArgs { - ref_id: request.ref_id, - snapshot_id: request.snapshot_id, + ref_id: request.ref_id.map(|ref_id| { + convert::qualified_ref(ref_id, request.snapshot_id.as_deref()) + }), xy: convert::point(request.x, request.y), duration_ms: request.duration_ms, timeout_ms: request.timeout_ms, @@ -132,9 +133,8 @@ impl Desktop { self.run("drag", Need::Accessibility, |adapter, context| { drag::execute( drag::DragArgs { - from: convert::drag_endpoint(request.from), - to: convert::drag_endpoint(request.to), - snapshot_id: request.snapshot_id, + from: convert::drag_endpoint(request.from, request.snapshot_id.as_deref()), + to: convert::drag_endpoint(request.to, request.snapshot_id.as_deref()), duration_ms: request.duration_ms, drop_delay_ms: request.drop_delay_ms, timeout_ms: request.timeout_ms, diff --git a/crates/tinycomputer-desktop/src/desktop/interaction.rs b/crates/tinycomputer-desktop/src/desktop/interaction.rs index 74de9c1fe..b5dc42139 100644 --- a/crates/tinycomputer-desktop/src/desktop/interaction.rs +++ b/crates/tinycomputer-desktop/src/desktop/interaction.rs @@ -127,8 +127,7 @@ impl Desktop { self.run("type", Need::Accessibility, |adapter, context| { type_text::execute( type_text::TypeArgs { - ref_id: request.ref_id, - snapshot_id: request.snapshot_id, + ref_id: convert::qualified_ref(request.ref_id, request.snapshot_id.as_deref()), text: request.text, timeout_ms: request.timeout_ms, }, @@ -161,8 +160,7 @@ impl Desktop { self.run("set-value", Need::Accessibility, |adapter, context| { set_value::execute( set_value::SetValueArgs { - ref_id: request.ref_id, - snapshot_id: request.snapshot_id, + ref_id: convert::qualified_ref(request.ref_id, request.snapshot_id.as_deref()), value: request.value, timeout_ms: request.timeout_ms, }, @@ -191,8 +189,7 @@ impl Desktop { self.run("select", Need::Accessibility, |adapter, context| { select::execute( select::SelectArgs { - ref_id: request.ref_id, - snapshot_id: request.snapshot_id, + ref_id: convert::qualified_ref(request.ref_id, request.snapshot_id.as_deref()), value: request.value, timeout_ms: request.timeout_ms, }, @@ -216,8 +213,7 @@ impl Desktop { self.run("scroll", Need::Accessibility, |adapter, context| { scroll::execute( scroll::ScrollArgs { - ref_id: request.ref_id, - snapshot_id: request.snapshot_id, + ref_id: convert::qualified_ref(request.ref_id, request.snapshot_id.as_deref()), direction: convert::direction(request.direction), amount: request.amount, timeout_ms: request.timeout_ms, diff --git a/crates/tinycomputer-desktop/src/desktop/mod.rs b/crates/tinycomputer-desktop/src/desktop/mod.rs index d510226ee..00c73e3f3 100644 --- a/crates/tinycomputer-desktop/src/desktop/mod.rs +++ b/crates/tinycomputer-desktop/src/desktop/mod.rs @@ -350,7 +350,7 @@ impl Desktop { /// permission report is fetched and checked first: fetching one costs a /// round trip to the platform, so a command that needs no permission does /// not pay for it. - fn run(&self, command: &str, need: Need, run: F) -> DesktopResponse + fn run(&self, command: &'static str, need: Need, run: F) -> DesktopResponse where F: FnOnce(&dyn PlatformAdapter, &CommandContext) -> std::result::Result, { @@ -360,7 +360,7 @@ impl Desktop { } /// [`Desktop::run`] for the two members that also read the report itself. - fn run_with_report(&self, command: &str, need: Need, run: F) -> DesktopResponse + fn run_with_report(&self, command: &'static str, need: Need, run: F) -> DesktopResponse where F: FnOnce( &dyn PlatformAdapter, @@ -372,9 +372,12 @@ impl Desktop { let adapter: &dyn PlatformAdapter = &adapter; let result = self.context().and_then(|context| { - let report = permission::report(need, adapter)?; - permission::preflight(need, &report)?; - run(adapter, &context, &report) + let scope = context.command_scope(command)?; + let result = permission::report(need, adapter) + .and_then(|report| permission::preflight(need, &report).map(|()| report)) + .and_then(|report| run(adapter, &context, &report)); + scope.complete(&result)?; + result }); reply::envelope(command, result) diff --git a/crates/tinycomputer-desktop/src/desktop/observation.rs b/crates/tinycomputer-desktop/src/desktop/observation.rs index e64989348..17da59a7f 100644 --- a/crates/tinycomputer-desktop/src/desktop/observation.rs +++ b/crates/tinycomputer-desktop/src/desktop/observation.rs @@ -46,8 +46,11 @@ impl Desktop { compact: request.compact, surface: convert::surface(request.surface), skeleton: request.skeleton, - root_ref: request.root_ref, - snapshot_id: request.snapshot_id, + root_ref: request.root_ref.map(|ref_id| { + convert::qualified_ref(ref_id, request.snapshot_id.as_deref()) + }), + timeout_ms: None, + force_electron_a11y: false, }, adapter, context, @@ -77,8 +80,9 @@ impl Desktop { find::FindArgs { app: request.app, window_id: request.window_id, - root: request.root, - snapshot: request.snapshot, + root: request + .root + .map(|ref_id| convert::qualified_ref(ref_id, request.snapshot.as_deref())), surface: convert::surface(request.surface), filter: find::FindFilterArgs { role: request.role, @@ -101,6 +105,7 @@ impl Desktop { nth: request.nth, limit: request.limit, }, + timeout_ms: None, }, adapter, context, @@ -122,8 +127,7 @@ impl Desktop { self.run("get", Need::Accessibility, |adapter, context| { get::execute( get::GetArgs { - ref_id: request.ref_id, - snapshot_id: request.snapshot_id, + ref_id: convert::qualified_ref(request.ref_id, request.snapshot_id.as_deref()), property: convert::element_property(request.property), }, adapter, @@ -149,8 +153,7 @@ impl Desktop { self.run("is", Need::Accessibility, |adapter, context| { is_check::execute( is_check::IsArgs { - ref_id: request.ref_id, - snapshot_id: request.snapshot_id, + ref_id: convert::qualified_ref(request.ref_id, request.snapshot_id.as_deref()), property: convert::state_property(request.property), }, adapter, diff --git a/crates/tinycomputer-desktop/src/desktop/trace_sink_tests.rs b/crates/tinycomputer-desktop/src/desktop/trace_sink_tests.rs index a6eca8053..11fea0d2b 100644 --- a/crates/tinycomputer-desktop/src/desktop/trace_sink_tests.rs +++ b/crates/tinycomputer-desktop/src/desktop/trace_sink_tests.rs @@ -17,7 +17,10 @@ impl TraceSink for RecordingSink { _deadline: TraceSinkDeadline, _byte_budget: u64, ) -> std::result::Result<(), TraceSinkError> { - self.events.lock().unwrap().push(event.clone()); + self.events + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .push(event.clone()); Ok(()) } @@ -32,10 +35,8 @@ impl TraceSink for RecordingSink { #[test] fn opted_in_sink_receives_events_without_opening_the_configured_trace_path() { - let nonce = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .expect("system clock is after the Unix epoch") - .as_nanos(); + static NEXT_TEST_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let nonce = NEXT_TEST_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed); let path = std::env::temp_dir().join(format!( "tinycomputer-native-trace-{}-{nonce}.jsonl", std::process::id(), @@ -54,7 +55,7 @@ fn opted_in_sink_receives_events_without_opening_the_configured_trace_path() { assert!( sink.events .lock() - .unwrap() + .unwrap_or_else(std::sync::PoisonError::into_inner) .iter() .any(|event| event["event"] == "command.end") ); diff --git a/crates/tinycomputer-desktop/src/desktop/waiting.rs b/crates/tinycomputer-desktop/src/desktop/waiting.rs index 5960789cd..057190560 100644 --- a/crates/tinycomputer-desktop/src/desktop/waiting.rs +++ b/crates/tinycomputer-desktop/src/desktop/waiting.rs @@ -40,7 +40,9 @@ impl Desktop { wait::WaitArgs { mode: wait::WaitModeArgs { ms: request.ms, - element: request.element, + element: request.element.map(|ref_id| { + super::convert::qualified_ref(ref_id, request.snapshot_id.as_deref()) + }), window: request.window, text: request.text, surface: surface_wait(request.surface.as_deref())?, @@ -48,7 +50,6 @@ impl Desktop { window_id: request.window_id, }, predicate: wait::WaitPredicateArgs { - snapshot_id: request.snapshot_id, predicate: request.predicate, value: request.value, action: request.action, diff --git a/crates/tinycomputer-examples/src/bin/verify_module.rs b/crates/tinycomputer-examples/src/bin/verify_module.rs index 79814fcdd..7a2f8d397 100644 --- a/crates/tinycomputer-examples/src/bin/verify_module.rs +++ b/crates/tinycomputer-examples/src/bin/verify_module.rs @@ -27,7 +27,11 @@ struct TraceSinkCapture { #[tinybus::interface(name = "ai.tinyhumans.tinycomputer.TraceSinkHost")] impl TraceSinkCapture { async fn append(&self, event: trace_sink::TraceEvent) -> tinybus::Result { - self.events.lock().unwrap().push(event.record); + tokio::task::yield_now().await; + self.events + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .push(event.record); Ok(trace_sink::SinkAck {}) } @@ -35,6 +39,7 @@ impl TraceSinkCapture { &self, _artifact: trace_sink::TraceArtifact, ) -> tinybus::Result { + tokio::task::yield_now().await; Err(tinybus::Error::failed( "verification fixture does not persist trace artifacts", )) @@ -44,10 +49,14 @@ impl TraceSinkCapture { &self, report: trace_sink::TaskReportRecord, ) -> tinybus::Result { + tokio::task::yield_now().await; if self.fail_reports.load(Ordering::SeqCst) { return Err(tinybus::Error::failed("verification report sink failure")); } - self.reports.lock().unwrap().push(report); + self.reports + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .push(report); Ok(trace_sink::SinkAck {}) } } @@ -184,7 +193,10 @@ fn verify_trace_sink( if legacy_path.exists() { return Err(io::Error::other("trace sink mode wrote the legacy trace file").into()); } - let events = capture.events.lock().unwrap(); + let events = capture + .events + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); let names = events .iter() .filter_map(|event| event.get("event").and_then(serde_json::Value::as_str)) @@ -235,13 +247,18 @@ async fn verify_report_sink( if report.data.is_none() { return Err(io::Error::other("module did not return the verification task report").into()); } - let captured = capture.reports.lock().unwrap(); - if captured.len() != 1 || captured[0].task_id != task_id.to_string() { + let report_received = { + let captured = capture + .reports + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + captured.len() == 1 && captured[0].task_id == task_id.to_string() + }; + if !report_received { return Err( io::Error::other("confidential host callback did not receive the task report").into(), ); } - drop(captured); capture.fail_reports.store(true, Ordering::SeqCst); let failed = proxy .call_confidential::( diff --git a/crates/tinycomputer/src/tinybus_module/dispatch/service.rs b/crates/tinycomputer/src/tinybus_module/dispatch/service.rs index 013742ba2..8e4209715 100644 --- a/crates/tinycomputer/src/tinybus_module/dispatch/service.rs +++ b/crates/tinycomputer/src/tinybus_module/dispatch/service.rs @@ -13,7 +13,7 @@ use tinycomputer_bus::{DesktopResponse, JevConfig}; use tinycomputer_engine as agentic; use super::DesktopService; -use crate::tinybus_module::config::{BrowserDefaults, cursor_config}; +use crate::tinybus_module::config::{BrowserDefaults, cursor_config, trace_sink_destination}; use crate::tinybus_module::consequence_gate::{ConsequenceLink, ConsequencePort}; use crate::tinybus_module::runner::WorkspaceRunner; use crate::tinybus_module::site_memory::{SiteLink, SiteMemoryPort, refused_flow}; @@ -26,16 +26,17 @@ impl DesktopService { /// # Errors /// /// Propagates whatever [`Desktop::from_config`] rejects. + #[cfg(test)] pub(crate) fn from_config(config: &serde_json::Value) -> Result { Self::with_browser(config, Arc::new(Browser::new(Arc::new(AgentBrowser)))) } /// Builds the service with the connection used for optional host callbacks. - pub(crate) async fn from_config_with_connection( + pub(crate) fn from_config_with_connection( config: &serde_json::Value, - connection: tinybus::Connection, + connection: &tinybus::Connection, ) -> TinyBusResult { - let trace_link = if let Some(destination) = super::config::trace_sink_destination(config) + let trace_link = if let Some(destination) = trace_sink_destination(config) .map_err(|error| TinyBusError::failed(error.to_string()))? { Some(TraceLink::new(connection.clone(), destination)?) @@ -56,6 +57,7 @@ impl DesktopService { /// # Errors /// /// Propagates whatever [`Desktop::from_config`] rejects. + #[cfg(test)] pub(crate) fn with_browser(config: &serde_json::Value, browser: Arc) -> Result { Self::with_browser_and_trace_sink(config, browser, None) } diff --git a/crates/tinycomputer/src/tinybus_module/mod.rs b/crates/tinycomputer/src/tinybus_module/mod.rs index 2882669e8..fe35eab16 100644 --- a/crates/tinycomputer/src/tinybus_module/mod.rs +++ b/crates/tinycomputer/src/tinybus_module/mod.rs @@ -39,7 +39,7 @@ pub(crate) use dispatch::DesktopService; /// silently ignoring the session it was told to join would allocate refs /// nothing else can spend. async fn setup(connection: Connection, config: Value) -> TinyBusResult<()> { - let service = DesktopService::from_config_with_connection(&config, connection.clone()).await?; + let service = DesktopService::from_config_with_connection(&config, &connection)?; // The host's per-site memory; a host that does not serve it only costs // tasks what earlier ones learned. let service = service.with_site_memory(Box::new(site_memory::BusPort::new(connection.clone()))); diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs index d445cf5c3..ba4bcbabb 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs @@ -62,6 +62,22 @@ impl TraceLink { pub(crate) fn new( connection: Connection, destination: tinybus::BusName, + ) -> TinyBusResult> { + Self::new_with_confidentiality(connection, destination, true) + } + + #[cfg(test)] + fn new_for_bus_tests( + connection: Connection, + destination: tinybus::BusName, + ) -> TinyBusResult> { + Self::new_with_confidentiality(connection, destination, false) + } + + fn new_with_confidentiality( + connection: Connection, + destination: tinybus::BusName, + confidential: bool, ) -> TinyBusResult> { let worker_connection = connection.clone(); let worker_destination = destination.clone(); @@ -78,12 +94,13 @@ impl TraceLink { .name("tinycomputer-trace-sink".into()) .spawn(move || { worker( - runtime, - worker_connection, - worker_destination, - worker_callback_active, - receiver, - ) + &runtime, + &worker_connection, + &worker_destination, + &worker_callback_active, + &receiver, + confidential, + ); }) .map_err(|error| TinyBusError::failed(format!("trace sink worker failed: {error}")))?; Ok(Arc::new(Self { @@ -118,11 +135,12 @@ impl TraceLink { } fn worker( - runtime: tokio::runtime::Handle, - connection: Connection, - destination: tinybus::BusName, - callback_active: Arc, - receiver: Receiver, + runtime: &tokio::runtime::Handle, + connection: &Connection, + destination: &tinybus::BusName, + callback_active: &Arc, + receiver: &Receiver, + confidential: bool, ) { while let Ok(command) = receiver.recv() { match command { @@ -132,7 +150,7 @@ fn worker( byte_budget, reply, } => { - let Some(_guard) = CallbackGuard::try_acquire(&callback_active) else { + let Some(_guard) = CallbackGuard::try_acquire(callback_active) else { let _ = reply.send(Err(())); continue; }; @@ -152,7 +170,7 @@ fn worker( trace_sink::INTERFACE, )? .with_timeout(timeout); - call::( + call_to_host::( &proxy, trace_sink::methods::APPEND, (TraceEvent { @@ -160,6 +178,7 @@ fn worker( deadline_ms, byte_budget, },), + confidential, ) .await .map(|_| ()) @@ -174,7 +193,7 @@ fn worker( limits, reply, } => { - let Some(_guard) = CallbackGuard::try_acquire(&callback_active) else { + let Some(_guard) = CallbackGuard::try_acquire(callback_active) else { let _ = reply.send(Err(())); continue; }; @@ -194,7 +213,7 @@ fn worker( trace_sink::INTERFACE, )? .with_timeout(timeout); - call::( + call_to_host::( &proxy, trace_sink::methods::STORE_ARTIFACT, (TraceArtifact { @@ -204,6 +223,7 @@ fn worker( deadline_ms, limits, },), + confidential, ) .await .map(|reply| reply.reference) @@ -222,6 +242,23 @@ where proxy.call_confidential(member, args).await } +async fn call_to_host( + proxy: &Proxy, + member: &str, + args: A, + confidential: bool, +) -> TinyBusResult +where + T: DeserializeOwned, + A: Serialize, +{ + if confidential { + call(proxy, member, args).await + } else { + proxy.call(member, args).await + } +} + fn remaining_timeout(deadline: Instant) -> Option { let remaining = deadline.checked_duration_since(Instant::now())?; let timeout = remaining.min(CALL_TIMEOUT); @@ -304,7 +341,7 @@ impl EngineTraceSink for TraceLink { })?; receive(&result, timeout) .map_err(|_| TraceSinkError::Internal("trace sink acknowledgment timed out".into()))? - .map_err(|_| TraceSinkError::Internal("trace sink rejected event".into())) + .map_err(|()| TraceSinkError::Internal("trace sink rejected event".into())) } fn store_artifact( @@ -351,7 +388,7 @@ impl EngineTraceSink for TraceLink { .map_err(|_| { TraceSinkError::Internal("trace artifact acknowledgment timed out".into()) })? - .map_err(|_| TraceSinkError::Internal("trace sink rejected artifact".into())) + .map_err(|()| TraceSinkError::Internal("trace sink rejected artifact".into())) } } diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs index 488f045ef..d4513e155 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs @@ -8,22 +8,30 @@ struct RecordingHost(Arc>>); #[tinybus::interface(name = "ai.tinyhumans.tinycomputer.TraceSinkHost")] impl RecordingHost { async fn append(&self, event: TraceEvent) -> TinyBusResult { - self.0.lock().unwrap().push(event.record); + tokio::task::yield_now().await; + self.0 + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .push(event.record); Ok(SinkAck {}) } async fn store_artifact(&self, _: TraceArtifact) -> TinyBusResult { + tokio::task::yield_now().await; Err(TinyBusError::failed("unused by deadline test")) } async fn write_report(&self, _: TaskReportRecord) -> TinyBusResult { + tokio::task::yield_now().await; Err(TinyBusError::failed("unused by deadline test")) } } #[test] fn an_expired_deadline_is_never_renewed() { - let deadline = Instant::now() - Duration::from_millis(1); + let deadline = Instant::now() + .checked_sub(Duration::from_millis(1)) + .unwrap_or_else(Instant::now); assert!(remaining_timeout(deadline).is_none()); assert!(remaining_millis(deadline).is_none()); @@ -32,7 +40,8 @@ fn an_expired_deadline_is_never_renewed() { #[test] fn callback_timeout_is_capped_without_extending_the_operation_deadline() { let deadline = Instant::now() + CALL_TIMEOUT * 2; - let timeout = remaining_timeout(deadline).expect("future deadline"); + assert!(remaining_timeout(deadline).is_some()); + let timeout = remaining_timeout(deadline).unwrap_or_default(); assert!(timeout <= CALL_TIMEOUT); assert!(deadline > Instant::now()); @@ -43,7 +52,11 @@ fn overlapping_callbacks_are_refused_until_the_outer_delivery_finishes() { let active = AtomicBool::new(false); { - let _outer = CallbackGuard::try_acquire(&active).expect("first callback acquires guard"); + let outer = CallbackGuard::try_acquire(&active); + assert!(outer.is_some()); + let Some(_outer) = outer else { + return; + }; assert!(CallbackGuard::try_acquire(&active).is_none()); } @@ -51,7 +64,8 @@ fn overlapping_callbacks_are_refused_until_the_outer_delivery_finishes() { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn an_already_expired_queued_event_is_rejected_without_a_host_write() -> TinyBusResult<()> { +async fn an_already_expired_queued_event_is_rejected_without_a_host_write() +-> Result<(), Box> { let bus = tinybus::transport::memory::MemoryBus::new(); tinybus::broker::Broker::new().spawn(bus.clone()); let host_connection = Connection::connect(bus.connect().await?).await?; @@ -61,29 +75,27 @@ async fn an_already_expired_queued_event_is_rejected_without_a_host_write() -> T .await?; host_connection.request_name(trace_sink::INTERFACE).await?; let module = Connection::connect(bus.connect().await?).await?; - let link = TraceLink::new(module, tinybus::BusName::new(trace_sink::INTERFACE)?)?; + let link = TraceLink::new_for_bus_tests(module, tinybus::BusName::new(trace_sink::INTERFACE)?)?; let (reply, result) = mpsc::sync_channel(1); - link.worker - .try_send(Command::Append { - record: serde_json::json!({"event": "expired"}), - deadline: Instant::now() - Duration::from_millis(1), - byte_budget: 4096, - reply, - }) - .expect("worker accepts the expired command for rejection"); + link.worker.try_send(Command::Append { + record: serde_json::json!({"event": "expired"}), + deadline: Instant::now() + .checked_sub(Duration::from_millis(1)) + .unwrap_or_else(Instant::now), + byte_budget: 4096, + reply, + })?; let acknowledgment = - tokio::task::spawn_blocking(move || result.recv_timeout(Duration::from_secs(1))) - .await - .expect("acknowledgment waiter completes") - .expect("worker sends a result"); + tokio::task::spawn_blocking(move || result.recv_timeout(Duration::from_secs(1))).await??; assert!(acknowledgment.is_err()); - assert!(host.0.lock().unwrap().is_empty()); + assert!(host.0.lock().map_err(|error| error.to_string())?.is_empty()); Ok(()) } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn expired_queued_event_is_rejected_without_a_late_host_write() -> TinyBusResult<()> { +async fn expired_queued_event_is_rejected_without_a_late_host_write() +-> Result<(), Box> { let bus = tinybus::transport::memory::MemoryBus::new(); tinybus::broker::Broker::new().spawn(bus.clone()); let host_connection = Connection::connect(bus.connect().await?).await?; @@ -99,54 +111,46 @@ async fn expired_queued_event_is_rejected_without_a_late_host_write() -> TinyBus .await?; host_connection.request_name(trace_sink::INTERFACE).await?; let module = Connection::connect(bus.connect().await?).await?; - let link = TraceLink::new(module, tinybus::BusName::new(trace_sink::INTERFACE)?)?; + let link = TraceLink::new_for_bus_tests(module, tinybus::BusName::new(trace_sink::INTERFACE)?)?; let (first_reply, first_result) = mpsc::sync_channel(1); - link.worker - .try_send(Command::Append { - record: serde_json::json!({"event": "blocker"}), - deadline: Instant::now() + Duration::from_secs(10), - byte_budget: 4096, - reply: first_reply, - }) - .expect("worker accepts the command that blocks its callback"); - tokio::time::timeout(Duration::from_secs(5), started_rx) - .await - .expect("first callback starts") - .expect("host signals that it is blocking the worker"); + link.worker.try_send(Command::Append { + record: serde_json::json!({"event": "blocker"}), + deadline: Instant::now() + Duration::from_secs(10), + byte_budget: 4096, + reply: first_reply, + })?; + tokio::time::timeout(Duration::from_secs(5), started_rx).await??; let (queued_reply, queued_result) = mpsc::sync_channel(1); let queued_deadline = Instant::now() + Duration::from_millis(50); - link.worker - .try_send(Command::Append { - record: serde_json::json!({"event": "expired"}), - deadline: queued_deadline, - byte_budget: 4096, - reply: queued_reply, - }) - .expect("worker queue accepts the second command while processing the first"); + link.worker.try_send(Command::Append { + record: serde_json::json!({"event": "expired"}), + deadline: queued_deadline, + byte_budget: 4096, + reply: queued_reply, + })?; tokio::time::sleep_until( tokio::time::Instant::from_std(queued_deadline) + Duration::from_millis(1), ) .await; release_tx .send(()) - .expect("test releases the first host callback"); + .map_err(|()| TinyBusError::failed("test release receiver was dropped"))?; let first_ack = tokio::task::spawn_blocking(move || first_result.recv_timeout(Duration::from_secs(5))) - .await - .expect("first acknowledgment waiter completes") - .expect("worker acknowledges the first command"); + .await??; let queued_ack = tokio::task::spawn_blocking(move || queued_result.recv_timeout(Duration::from_secs(5))) - .await - .expect("queued acknowledgment waiter completes") - .expect("worker rejects the expired queued command"); + .await??; assert!(first_ack.is_ok()); assert!(queued_ack.is_err()); assert_eq!( - host.events.lock().unwrap().as_slice(), + host.events + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .as_slice(), &[serde_json::json!({"event": "blocker"})], "the expired queued event must not be written late" ); @@ -164,25 +168,39 @@ struct BlockingRecordingHost { impl BlockingRecordingHost { async fn append(&self, event: TraceEvent) -> TinyBusResult { if event.record["event"] == "blocker" { - if let Some(started) = self.started.lock().unwrap().take() { + if let Some(started) = self + .started + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take() + { let _ = started.send(()); } - let release = self.release.lock().unwrap().take(); + let release = self + .release + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take(); if let Some(release) = release { release .await .map_err(|_| TinyBusError::failed("test callback was not released"))?; } } - self.events.lock().unwrap().push(event.record); + self.events + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .push(event.record); Ok(SinkAck {}) } async fn store_artifact(&self, _: TraceArtifact) -> TinyBusResult { + tokio::task::yield_now().await; Err(TinyBusError::failed("unused by queued deadline test")) } async fn write_report(&self, _: TaskReportRecord) -> TinyBusResult { + tokio::task::yield_now().await; Err(TinyBusError::failed("unused by queued deadline test")) } } From 325ac515de22bfb2de520f518f25b76a9e1c2057 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 16:40:08 +0000 Subject: [PATCH 07/48] Update vulnerable transitive dependencies Co-authored-by: Medulla --- Cargo.lock | 142 +++++++++++++++++++++---------------------- vendor/agent-browser | 2 +- vendor/tinybus | 2 +- 3 files changed, 72 insertions(+), 74 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 96628891a..c0e600811 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -83,12 +83,12 @@ dependencies = [ "urlencoding", "uuid", "windows-sys 0.52.0", - "zip 8.6.0", + "zip", ] [[package]] name = "agent-desktop-core" -version = "0.9.4" +version = "0.10.1" dependencies = [ "base64 0.23.1", "libc", @@ -102,7 +102,7 @@ dependencies = [ [[package]] name = "agent-desktop-linux" -version = "0.9.4" +version = "0.10.1" dependencies = [ "agent-desktop-core", "thiserror 2.0.20", @@ -110,7 +110,7 @@ dependencies = [ [[package]] name = "agent-desktop-macos" -version = "0.9.4" +version = "0.10.1" dependencies = [ "accessibility-sys", "agent-desktop-core", @@ -129,10 +129,15 @@ dependencies = [ [[package]] name = "agent-desktop-windows" -version = "0.9.4" +version = "0.10.1" dependencies = [ "agent-desktop-core", + "serde_json", "thiserror 2.0.20", + "tracing", + "uiautomation", + "windows 0.62.2", + "windows-sys 0.61.2", ] [[package]] @@ -181,15 +186,6 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" -[[package]] -name = "arbitrary" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" -dependencies = [ - "derive_arbitrary", -] - [[package]] name = "arboard" version = "3.6.1" @@ -215,7 +211,7 @@ checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] @@ -395,7 +391,7 @@ version = "5.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a68fa787550392a9d58f44c21a3022cfb3ea3e2458b7f85d3b399d0ceeccf409" dependencies = [ - "nix", + "nix 0.27.1", "winapi", ] @@ -529,12 +525,6 @@ dependencies = [ "cfg-if", ] -[[package]] -name = "crossbeam-utils" -version = "0.8.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17" - [[package]] name = "crypto-common" version = "0.1.7" @@ -582,17 +572,6 @@ version = "0.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" -[[package]] -name = "derive_arbitrary" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "digest" version = "0.10.7" @@ -654,7 +633,7 @@ checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] @@ -758,7 +737,7 @@ checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] @@ -832,7 +811,7 @@ checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] @@ -1465,6 +1444,18 @@ dependencies = [ "libc", ] +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "ntapi" version = "0.4.3" @@ -2176,9 +2167,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.45" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "log", "once_cell", @@ -2270,7 +2261,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] @@ -2434,9 +2425,9 @@ dependencies = [ [[package]] name = "syn" -version = "3.0.3" +version = "3.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" dependencies = [ "proc-macro2", "quote", @@ -2460,7 +2451,7 @@ checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] @@ -2537,7 +2528,7 @@ checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] @@ -2572,7 +2563,7 @@ dependencies = [ [[package]] name = "tinybus" -version = "0.1.5" +version = "0.1.6" dependencies = [ "async-trait", "flate2", @@ -2588,12 +2579,12 @@ dependencies = [ "toml", "tracing", "ureq", - "zip 2.4.2", + "zip", ] [[package]] name = "tinybus-macros" -version = "0.1.5" +version = "0.1.6" dependencies = [ "proc-macro2", "quote", @@ -2602,7 +2593,7 @@ dependencies = [ [[package]] name = "tinybus-module" -version = "0.1.5" +version = "0.1.6" dependencies = [ "async-trait", "serde", @@ -2859,7 +2850,7 @@ checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] @@ -3066,6 +3057,29 @@ version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" +[[package]] +name = "uiautomation" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa2eacf9390a8491bc949b04230f40c12520c6423a2962a6087eea1ef14373af" +dependencies = [ + "chrono", + "uiautomation_derive", + "windows 0.62.2", + "windows-core 0.62.2", +] + +[[package]] +name = "uiautomation_derive" +version = "0.7.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c893ec96e05c3c81ba46f838f3190549ec185ef377d582ab3d44202b2dfacbd" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "unicase" version = "2.9.0" @@ -3243,7 +3257,7 @@ dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", "wasm-bindgen-shared", ] @@ -3329,7 +3343,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.48.0", ] [[package]] @@ -3791,7 +3805,7 @@ checksum = "33811428bee40dbceb6d545e95754741d17a6aef9a4849f0fd62e2ba4f412a78" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", "synstructure", ] @@ -3832,7 +3846,7 @@ checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", "synstructure", ] @@ -3872,36 +3886,20 @@ checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", -] - -[[package]] -name = "zip" -version = "2.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50" -dependencies = [ - "arbitrary", - "crc32fast", - "crossbeam-utils", - "displaydoc", - "flate2", - "indexmap", - "memchr", - "thiserror 2.0.20", - "zopfli", + "syn 3.0.9", ] [[package]] name = "zip" -version = "8.6.0" +version = "9.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b" +checksum = "6e04976da629d3b04204ba8105b396a193af8ad2583b2c79bfb3ab8af580a11e" dependencies = [ "crc32fast", "flate2", "indexmap", "memchr", + "nix 0.31.3", "typed-path", "zopfli", ] diff --git a/vendor/agent-browser b/vendor/agent-browser index f98d5fef6..2b10c825c 160000 --- a/vendor/agent-browser +++ b/vendor/agent-browser @@ -1 +1 @@ -Subproject commit f98d5fef6a57b6067e6c5710e6f0ea6fb0b3bd47 +Subproject commit 2b10c825c9649754edf81ccb0fdae0b971353fcf diff --git a/vendor/tinybus b/vendor/tinybus index eb5cf7270..aa36051e2 160000 --- a/vendor/tinybus +++ b/vendor/tinybus @@ -1 +1 @@ -Subproject commit eb5cf727071a6eb12f9efa3db8ec59e54039f336 +Subproject commit aa36051e2d384b09a1fb7871758fcf22c2a7e709 From 318c770984c08dc08021cc83d7ff6fd02b191146 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 16:46:41 +0000 Subject: [PATCH 08/48] Harden trace sink contract and configuration Co-authored-by: Medulla --- crates/tinycomputer-bus/Cargo.toml | 2 ++ crates/tinycomputer-bus/README.md | 14 +++++--- crates/tinycomputer-bus/src/trace_sink/mod.rs | 33 +++++++++++++++++-- .../src/trace_sink/trace_sink_tests.rs | 4 ++- crates/tinycomputer-bus/src/version/mod.rs | 4 +-- .../src/version/version_tests.rs | 7 ++-- .../tinycomputer/src/tinybus_module/README.md | 6 ++-- .../src/tinybus_module/dispatch/service.rs | 6 ++++ .../tinybus_module_tests/config_tests.rs | 10 ++++++ .../src/tinybus_module/trace_sink/mod.rs | 10 ++++++ .../trace_sink/trace_sink_tests.rs | 8 +++++ crates/tinycomputer/tests/public_api_tests.rs | 2 +- docs/crates/tinycomputer-bus/versioning.md | 14 ++++---- .../specs/desktop-module-contract.md | 9 ++--- 14 files changed, 102 insertions(+), 27 deletions(-) diff --git a/crates/tinycomputer-bus/Cargo.toml b/crates/tinycomputer-bus/Cargo.toml index 2c5777332..c1f9e68c5 100644 --- a/crates/tinycomputer-bus/Cargo.toml +++ b/crates/tinycomputer-bus/Cargo.toml @@ -22,6 +22,8 @@ publish = false thiserror = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } +# Base64 keeps binary trace artifacts compact enough for the TinyBus frame cap. +base64 = { workspace = true } [lints] workspace = true diff --git a/crates/tinycomputer-bus/README.md b/crates/tinycomputer-bus/README.md index 45f6bd022..6cc51f951 100644 --- a/crates/tinycomputer-bus/README.md +++ b/crates/tinycomputer-bus/README.md @@ -30,9 +30,11 @@ payload vocabulary has to be published as an ordinary library. This is it. | `agent` | the task members' requests, views, reports, and `Capabilities` | | `flow` | the flow grammar `RunFlow` and `StartTask` carry | | `browser` | the `Browser…` members' payloads, names, and error codes | +| `trace_sink` | the optional `TraceSinkHost` callback names and payloads | | `version` | `CONTRACT_VERSION` and the bind rule a host applies to it | -Three dependencies, all pure Rust: `thiserror`, `serde`, and `serde_json`. +Four dependencies, all pure Rust: `thiserror`, `serde`, `serde_json`, and +`base64` for compact binary artifact payloads. ## This crate sits underneath `tinycomputer` @@ -167,16 +169,18 @@ See the [Globe contract](src/accessibility/README.md). Reliable Globe callers require a released 2.12-compatible artifact with a verified digest. -Contract 2.20 adds the optional confidential `TraceSinkHost` callback. A host +Contract 2.21 adds the optional confidential `TraceSinkHost` callback. A host prepares one exact callback binding per loaded module and supplies its unique destination as `trace_sink.destination`. TinyComputer sends sanitized desktop trace events, trace artifacts, and requested task reports to `Append`, `StoreArtifact`, and `WriteReport`. Event delivery is ordered and acknowledged; strict trace mode propagates sink failures, best-effort mode keeps the existing warning behavior, and a selected sink never falls back to local trace files. Task report writes -are acknowledged before the report returns. Artifact writes carry the existing -engine limits and return an opaque host reference; the host enforces byte and -count limits atomically and must reject storage it cannot provide. The +are acknowledged before the report returns. Artifact bytes use standard padded +base64 and are capped at 8 MiB decoded to keep callbacks within the TinyBus +frame limit. Artifact writes carry the existing engine limits and return an +opaque host reference; the host enforces byte and count limits atomically and +must reject storage it cannot provide. The confidential module caller is the sole scope authority: hosts derive the user and storage scope from that trusted identity and ignore payload fields when choosing a scope. Sink callbacks must not call back into TinyComputer. The diff --git a/crates/tinycomputer-bus/src/trace_sink/mod.rs b/crates/tinycomputer-bus/src/trace_sink/mod.rs index 9002b95f9..7900c2ee2 100644 --- a/crates/tinycomputer-bus/src/trace_sink/mod.rs +++ b/crates/tinycomputer-bus/src/trace_sink/mod.rs @@ -15,6 +15,29 @@ use serde::{Deserialize, Serialize}; use serde_json::Value; +const MAX_ARTIFACT_BYTES: usize = 8 * 1024 * 1024; + +mod base64_bytes { + use base64::Engine as _; + use base64::engine::general_purpose::STANDARD; + use serde::{Deserialize, Deserializer, Serializer}; + + pub(super) fn serialize(bytes: &[u8], serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_str(&STANDARD.encode(bytes)) + } + + pub(super) fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> + where + D: Deserializer<'de>, + { + let encoded = String::deserialize(deserializer)?; + STANDARD.decode(encoded).map_err(serde::de::Error::custom) + } +} + use crate::agent::TaskReport; /// The interface the host serves for trace and report persistence. @@ -77,14 +100,17 @@ pub struct TraceArtifactLimits { } /// One trace artifact sent to the host. The bytes may contain screen content -/// and therefore this member is confidential. +/// and therefore this member is confidential. `bytes` is standard padded +/// base64 on the wire and contains at most [`MAX_TRACE_ARTIFACT_BYTES`] decoded +/// bytes, keeping the callback under `TinyBus`'s 16 MiB frame cap. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct TraceArtifact { /// Whether the bytes are a screenshot or a reference map. pub kind: TraceArtifactKind, /// Producer-generated name, scoped to the host's trace sink. pub name: String, - /// Artifact content. + /// Artifact content, encoded as standard padded base64 on the wire. + #[serde(with = "base64_bytes")] pub bytes: Vec, /// Remaining milliseconds in the engine's admission deadline. pub deadline_ms: u64, @@ -92,6 +118,9 @@ pub struct TraceArtifact { pub limits: TraceArtifactLimits, } +/// Maximum decoded artifact size accepted by the trace sink callback. +pub const MAX_TRACE_ARTIFACT_BYTES: usize = MAX_ARTIFACT_BYTES; + /// The host's committed opaque reference for an artifact. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct TraceArtifactRef { diff --git a/crates/tinycomputer-bus/src/trace_sink/trace_sink_tests.rs b/crates/tinycomputer-bus/src/trace_sink/trace_sink_tests.rs index d2bb60c99..973da94ec 100644 --- a/crates/tinycomputer-bus/src/trace_sink/trace_sink_tests.rs +++ b/crates/tinycomputer-bus/src/trace_sink/trace_sink_tests.rs @@ -27,8 +27,10 @@ fn sink_records_keep_their_wire_shapes() -> Result<(), serde_json::Error> { }; let wire = serde_json::to_value(artifact)?; assert_eq!(wire["kind"], "ref_map"); - assert_eq!(wire["bytes"], serde_json::json!([1, 2])); + assert_eq!(wire["bytes"], "AQI="); assert_eq!(wire["limits"]["refmap_bytes"], 20); + let decoded: TraceArtifact = serde_json::from_value(wire)?; + assert_eq!(decoded.bytes, [1, 2]); Ok(()) } diff --git a/crates/tinycomputer-bus/src/version/mod.rs b/crates/tinycomputer-bus/src/version/mod.rs index df0cfe38d..c26022e07 100644 --- a/crates/tinycomputer-bus/src/version/mod.rs +++ b/crates/tinycomputer-bus/src/version/mod.rs @@ -8,7 +8,7 @@ //! release workflow bumps, which tracks the shipped artifact. /// The wire contract version this crate defines. -pub const CONTRACT_VERSION: (u32, u32) = (2, 20); +pub const CONTRACT_VERSION: (u32, u32) = (2, 21); /// Returns whether a host holding [`CONTRACT_VERSION`] can bind to a module /// reporting `module`. @@ -22,7 +22,7 @@ pub const CONTRACT_VERSION: (u32, u32) = (2, 20); /// ``` /// # use tinycomputer_bus::{is_compatible, CONTRACT_VERSION}; /// assert!(is_compatible(CONTRACT_VERSION)); -/// assert!(is_compatible((2, 20))); +/// assert!(is_compatible((2, 21))); /// assert!(!is_compatible((2, 11))); /// assert!(!is_compatible((1, 8))); /// ``` diff --git a/crates/tinycomputer-bus/src/version/version_tests.rs b/crates/tinycomputer-bus/src/version/version_tests.rs index bfb9b521d..e45cc7366 100644 --- a/crates/tinycomputer-bus/src/version/version_tests.rs +++ b/crates/tinycomputer-bus/src/version/version_tests.rs @@ -6,7 +6,7 @@ use super::{CONTRACT_VERSION, binds, is_compatible}; #[test] fn the_shipped_contract_version_is_pinned() { - assert_eq!(CONTRACT_VERSION, (2, 20)); + assert_eq!(CONTRACT_VERSION, (2, 21)); } #[test] @@ -16,7 +16,7 @@ fn the_contract_binds_to_itself() { #[test] fn a_newer_minor_on_the_module_side_binds() { - assert!(is_compatible((2, 20))); + assert!(is_compatible((2, 21))); assert!(is_compatible((2, 97))); // 2.12 adds replayable GlobeRead and joined terminal GlobeShutdown. // A 2.11 module does not implement those members. @@ -35,7 +35,8 @@ fn a_newer_minor_on_the_module_side_binds() { // 2.19 adds the ConsequenceHost host-callback interface (Review): a 2.19 // host serves it, which a 2.18 module does not call, so its approvals // would never reach the host's policy. - // 2.20 adds TraceSinkHost so desktop events and task reports can be + // 2.20 adds SessionOptions identity fields for browser launches. + // 2.21 adds TraceSinkHost so desktop events and task reports can be // committed by the host without using a module-local trace file. assert!(!is_compatible((2, 18))); assert!(!is_compatible((2, 17))); diff --git a/crates/tinycomputer/src/tinybus_module/README.md b/crates/tinycomputer/src/tinybus_module/README.md index 14fe71654..502d09114 100644 --- a/crates/tinycomputer/src/tinybus_module/README.md +++ b/crates/tinycomputer/src/tinybus_module/README.md @@ -58,8 +58,10 @@ The module takes its configuration from the loader as a JSON object, parsed into the unique `destination` supplied by `ModuleHost::prepare_host_callbacks` opts into the host's confidential `TraceSinkHost` interface for ordered desktop trace events, trace artifacts, and requested task reports; selected sink mode -never writes local trace files. Leaving it absent or `false` retains the -existing `trace_path` and session behavior. `true` without a callback +never writes local trace files. Artifact bytes use base64 and are capped at +8 MiB decoded so the callback stays below TinyBus's frame limit. Leaving it +absent or `false` retains the existing `trace_path` and session behavior. +`true` without a callback destination is rejected. `browser` sets how every browser launches — `executable`, `user_agent`, `args`, a task's page `perception`, how a page `settle`s after an action, and whether to diff --git a/crates/tinycomputer/src/tinybus_module/dispatch/service.rs b/crates/tinycomputer/src/tinybus_module/dispatch/service.rs index 8e4209715..a0c947e57 100644 --- a/crates/tinycomputer/src/tinybus_module/dispatch/service.rs +++ b/crates/tinycomputer/src/tinybus_module/dispatch/service.rs @@ -59,6 +59,12 @@ impl DesktopService { /// Propagates whatever [`Desktop::from_config`] rejects. #[cfg(test)] pub(crate) fn with_browser(config: &serde_json::Value, browser: Arc) -> Result { + if trace_sink_destination(config)?.is_some() { + return Err(crate::Error::ConfigFieldType { + field: "trace_sink", + expected: "a module set up with its host callback connection", + }); + } Self::with_browser_and_trace_sink(config, browser, None) } diff --git a/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/config_tests.rs b/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/config_tests.rs index 68afea45f..80254b405 100644 --- a/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/config_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/config_tests.rs @@ -298,3 +298,13 @@ fn trace_sink_requires_the_host_prepared_unique_destination() { ":1.42" ); } + +#[test] +fn connectionless_service_construction_rejects_trace_sink_configuration() { + let error = DesktopService::from_config(&json!({ + "trace_sink": {"destination": ":1.42"} + })) + .expect_err("a host callback needs the module's bus connection"); + + assert!(error.to_string().contains("trace_sink")); +} diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs index ba4bcbabb..95e7e3bfe 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs @@ -26,6 +26,15 @@ use tinycomputer_desktop::{ const CALL_TIMEOUT: Duration = Duration::from_secs(10); +fn validate_artifact_size(size: usize) -> std::result::Result<(), TraceSinkError> { + if size > tinycomputer_bus::trace_sink::MAX_TRACE_ARTIFACT_BYTES { + return Err(TraceSinkError::Internal( + "trace artifact exceeds the 8 MiB bus limit".into(), + )); + } + Ok(()) +} + enum Command { Append { record: serde_json::Value, @@ -349,6 +358,7 @@ impl EngineTraceSink for TraceLink { artifact: TraceSinkArtifact<'_>, limits: TraceSinkArtifactLimits, ) -> std::result::Result { + validate_artifact_size(artifact.bytes.len())?; if self.callback_active.load(Ordering::Acquire) { return Err(TraceSinkError::Internal( "trace sink callback is busy".into(), diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs index d4513e155..93275c612 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs @@ -37,6 +37,14 @@ fn an_expired_deadline_is_never_renewed() { assert!(remaining_millis(deadline).is_none()); } +#[test] +fn artifacts_over_the_transport_safe_limit_are_refused_before_queueing() { + let limit = tinycomputer_bus::trace_sink::MAX_TRACE_ARTIFACT_BYTES; + + assert!(validate_artifact_size(limit).is_ok()); + assert!(validate_artifact_size(limit + 1).is_err()); +} + #[test] fn callback_timeout_is_capped_without_extending_the_operation_deadline() { let deadline = Instant::now() + CALL_TIMEOUT * 2; diff --git a/crates/tinycomputer/tests/public_api_tests.rs b/crates/tinycomputer/tests/public_api_tests.rs index e13461a87..04065f627 100644 --- a/crates/tinycomputer/tests/public_api_tests.rs +++ b/crates/tinycomputer/tests/public_api_tests.rs @@ -34,7 +34,7 @@ fn the_crate_re_exports_the_contract_rather_than_redefining_it() { #[test] fn the_shipped_contract_binds_to_itself() { assert!(is_compatible(CONTRACT_VERSION)); - assert_eq!(CONTRACT_VERSION, (2, 20)); + assert_eq!(CONTRACT_VERSION, (2, 21)); } #[test] diff --git a/docs/crates/tinycomputer-bus/versioning.md b/docs/crates/tinycomputer-bus/versioning.md index b8229e67b..c97ac3632 100644 --- a/docs/crates/tinycomputer-bus/versioning.md +++ b/docs/crates/tinycomputer-bus/versioning.md @@ -9,7 +9,7 @@ code, so this page exists mostly to keep them apart. ## `CONTRACT_VERSION`: does this host understand this module ```rust,ignore -pub const CONTRACT_VERSION: (u32, u32) = (2, 20); +pub const CONTRACT_VERSION: (u32, u32) = (2, 21); ``` This describes the *vocabulary*: the member set and the payload shapes, @@ -45,15 +45,15 @@ Two conditions, both necessary: relies on changed shape or disappeared, so a mismatched major is refused outright, in either direction. 2. **The module must be at least as new, minor-wise, as the host.** A host - built against `(2, 20)` expects at least the members and fields that - existed at `(2, 20)`. A module reporting `(2, 11)` might be missing one of + built against `(2, 21)` expects at least the members and fields that + existed at `(2, 21)`. A module reporting `(2, 11)` might be missing one of them, so it is rejected. A module reporting `(2, 20)` has everything the - host expects, plus something newer the host simply does not use yet, so - it is accepted. + host expected before `TraceSinkHost` was added, so it is rejected by a + 2.21 host. ```rust,ignore -assert!(is_compatible(CONTRACT_VERSION)); // (2, 20), the exact version this crate ships -assert!(is_compatible((2, 20))); // a newer, still-compatible module +assert!(is_compatible(CONTRACT_VERSION)); // (2, 21), the exact version this crate ships +assert!(is_compatible((2, 21))); // a newer, still-compatible module assert!(!is_compatible((2, 11))); // an older module, missing something assert!(!is_compatible((1, 10))); // a different major, all bets off ``` diff --git a/docs/technical/specs/desktop-module-contract.md b/docs/technical/specs/desktop-module-contract.md index 625d18aa1..fbacbbcb0 100644 --- a/docs/technical/specs/desktop-module-contract.md +++ b/docs/technical/specs/desktop-module-contract.md @@ -94,14 +94,15 @@ Session identity (2.20): `SessionOptions` takes the optional `timezone`, `stealth`. A client that sends none gets the defaults; a 2.19 module ignores them. They apply to a browser the module launches, not one it attaches to. -Trace and report persistence (2.20): when module configuration sets +Trace and report persistence (2.21): when module configuration sets `trace_sink` to an object containing the unique callback `destination`, the module calls the confidential `ai.tinyhumans.tinycomputer.TraceSinkHost` interface. `Append` receives each complete sanitized agent-desktop trace event in order. `StoreArtifact` receives desktop trace screenshots and reference maps -and returns their committed opaque references. `WriteReport` receives a task id -and the full `TaskReport` whenever the caller requests `TaskReport`. The host -acknowledges each write; trace failures follow `trace_strict`, while a report +as standard padded base64, capped at 8 MiB decoded, and returns their committed +opaque references. `WriteReport` receives a task id and the full `TaskReport` +whenever the caller requests `TaskReport`. The host acknowledges each write; +trace failures follow `trace_strict`, while a report write failure is returned to the report caller. Sink mode has no local file/session fallback, even when its host callback fails. Without the explicit configuration, existing desktop trace path and session behavior remain in From 2a74aa0d96f9f8d1317b02388a7c089d85d51e63 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 16:47:05 +0000 Subject: [PATCH 09/48] Lock trace sink base64 dependency Co-authored-by: Medulla --- Cargo.lock | 1 + 1 file changed, 1 insertion(+) diff --git a/Cargo.lock b/Cargo.lock index c0e600811..ecba5bea5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2659,6 +2659,7 @@ dependencies = [ name = "tinycomputer-bus" version = "0.15.0" dependencies = [ + "base64 0.22.1", "serde", "serde_json", "thiserror 2.0.20", From 055337f87784e991484c5fbfb835214e128cfe70 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:03:11 +0000 Subject: [PATCH 10/48] Cover trace callbacks and update advisory fixes Co-authored-by: Medulla --- Cargo.lock | 20 +- .../src/tinybus_module/trace_sink/mod.rs | 5 +- .../trace_sink/trace_sink_tests.rs | 180 +++++++++++++++++- 3 files changed, 193 insertions(+), 12 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ecba5bea5..d0842f1d4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1008,7 +1008,7 @@ dependencies = [ "tokio", "tokio-rustls", "tower-service", - "webpki-roots 1.0.9", + "webpki-roots 1.0.10", ] [[package]] @@ -2085,7 +2085,7 @@ dependencies = [ "wasm-bindgen-futures", "wasm-streams", "web-sys", - "webpki-roots 1.0.9", + "webpki-roots 1.0.10", ] [[package]] @@ -2192,9 +2192,9 @@ dependencies = [ [[package]] name = "rustls-webpki" -version = "0.103.15" +version = "0.103.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" dependencies = [ "ring", "rustls-pki-types", @@ -3123,7 +3123,7 @@ dependencies = [ "rustls-pki-types", "ureq-proto", "utf8-zero", - "webpki-roots 1.0.9", + "webpki-roots 1.0.10", ] [[package]] @@ -3310,14 +3310,14 @@ version = "0.26.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" dependencies = [ - "webpki-roots 1.0.9", + "webpki-roots 1.0.10", ] [[package]] name = "webpki-roots" -version = "1.0.9" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9" dependencies = [ "rustls-pki-types", ] @@ -3800,9 +3800,9 @@ dependencies = [ [[package]] name = "yoke-derive" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33811428bee40dbceb6d545e95754741d17a6aef9a4849f0fd62e2ba4f412a78" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" dependencies = [ "proc-macro2", "quote", diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs index 95e7e3bfe..12b859235 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs @@ -59,6 +59,7 @@ pub(crate) struct TraceLink { destination: tinybus::BusName, worker: SyncSender, callback_active: Arc, + confidential: bool, } impl std::fmt::Debug for TraceLink { @@ -117,16 +118,18 @@ impl TraceLink { destination, worker: sender, callback_active, + confidential, })) } pub(crate) async fn write_report(&self, record: TaskReportRecord) -> TinyBusResult<()> { let _guard = CallbackGuard::try_acquire(&self.callback_active) .ok_or_else(|| TinyBusError::failed("trace sink callback is busy"))?; - call::( + call_to_host::( &self.proxy(CALL_TIMEOUT)?, trace_sink::methods::WRITE_REPORT, (record,), + self.confidential, ) .await .map(|_| ()) diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs index 93275c612..5c047e285 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs @@ -1,10 +1,188 @@ use super::*; use std::sync::Mutex; -use tinycomputer_bus::trace_sink::TraceEvent; +use tinycomputer_bus::agent::TaskReport; +use tinycomputer_bus::trace_sink::{TaskReportRecord, TraceEvent}; #[derive(Clone, Default)] struct RecordingHost(Arc>>); +#[derive(Clone, Default)] +struct CompleteRecordingHost { + events: Arc>>, + artifacts: Arc>>, + reports: Arc>>, + reject: Arc, +} + +#[tinybus::interface(name = "ai.tinyhumans.tinycomputer.TraceSinkHost")] +impl CompleteRecordingHost { + async fn append(&self, event: TraceEvent) -> TinyBusResult { + tokio::task::yield_now().await; + if self.reject.load(Ordering::Acquire) { + return Err(TinyBusError::failed("host rejected event")); + } + self.events + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .push(event.record); + Ok(SinkAck {}) + } + + async fn store_artifact(&self, artifact: TraceArtifact) -> TinyBusResult { + tokio::task::yield_now().await; + if self.reject.load(Ordering::Acquire) { + return Err(TinyBusError::failed("host rejected artifact")); + } + self.artifacts + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .push(artifact); + Ok(TraceArtifactRef { + reference: "trace-artifact-1".into(), + }) + } + + async fn write_report(&self, report: TaskReportRecord) -> TinyBusResult { + tokio::task::yield_now().await; + if self.reject.load(Ordering::Acquire) { + return Err(TinyBusError::failed("host rejected report")); + } + self.reports + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .push(report); + Ok(SinkAck {}) + } +} + +async fn connected_link( + host: CompleteRecordingHost, +) -> Result<(Arc, CompleteRecordingHost, Connection), Box> { + let bus = tinybus::transport::memory::MemoryBus::new(); + tinybus::broker::Broker::new().spawn(bus.clone()); + let host_connection = Connection::connect(bus.connect().await?).await?; + host_connection + .serve_at(trace_sink::OBJECT_PATH.try_into()?, host.clone()) + .await?; + host_connection.request_name(trace_sink::INTERFACE).await?; + let module = Connection::connect(bus.connect().await?).await?; + let link = TraceLink::new_for_bus_tests(module, tinybus::BusName::new(trace_sink::INTERFACE)?)?; + Ok((link, host, host_connection)) +} + +fn empty_task_report() -> Result { + serde_json::from_value(serde_json::json!({ + "view": { + "id": "task-1", + "status": {"state": "running"}, + "summary": "working", + "progress": 0.0, + "next": [] + }, + "steps": [], + "records": {}, + "artifacts": [], + "learned": [], + "trace": [] + })) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn callbacks_commit_events_artifacts_and_reports_over_the_bus() +-> Result<(), Box> { + let (link, host, _host_connection) = connected_link(CompleteRecordingHost::default()).await?; + let deadline = TraceSinkDeadline::after(5_000)?; + link.append(&serde_json::json!({"event": "started"}), deadline, 4096) + .map_err(|error| error.to_string())?; + let artifact_deadline = TraceSinkDeadline::after(5_000)?; + let reference = link + .store_artifact( + TraceSinkArtifact { + kind: EngineArtifactKind::Screenshot, + name: "screen.png", + bytes: &[1, 2, 3], + deadline: artifact_deadline, + }, + TraceSinkArtifactLimits { + screenshot_bytes: 128, + screenshot_count: 2, + refmap_bytes: 64, + }, + ) + .map_err(|error| error.to_string())?; + link.write_report(TaskReportRecord { + task_id: "task-1".into(), + report: empty_task_report()?, + }) + .await?; + + assert_eq!(reference, "trace-artifact-1"); + assert_eq!( + host.events + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .as_slice(), + &[serde_json::json!({"event": "started"})] + ); + assert_eq!( + host.artifacts + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner)[0] + .bytes, + [1, 2, 3] + ); + assert_eq!( + host.reports + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner)[0] + .task_id, + "task-1" + ); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn rejected_host_callbacks_return_errors_to_the_caller() +-> Result<(), Box> { + let host = CompleteRecordingHost::default(); + host.reject.store(true, Ordering::Release); + let (link, _, _host_connection) = connected_link(host).await?; + + assert!( + link.append( + &serde_json::json!({"event": "rejected"}), + TraceSinkDeadline::after(5_000)?, + 4096, + ) + .is_err() + ); + assert!( + link.store_artifact( + TraceSinkArtifact { + kind: EngineArtifactKind::RefMap, + name: "refs.json", + bytes: &[4, 5], + deadline: TraceSinkDeadline::after(5_000)?, + }, + TraceSinkArtifactLimits { + screenshot_bytes: 128, + screenshot_count: 2, + refmap_bytes: 64, + }, + ) + .is_err() + ); + assert!( + link.write_report(TaskReportRecord { + task_id: "task-1".into(), + report: empty_task_report()?, + }) + .await + .is_err() + ); + Ok(()) +} + #[tinybus::interface(name = "ai.tinyhumans.tinycomputer.TraceSinkHost")] impl RecordingHost { async fn append(&self, event: TraceEvent) -> TinyBusResult { From 4a5ca91333ff337c7fa5ea9bea69ec96400c8761 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:10:00 +0000 Subject: [PATCH 11/48] Join trace worker and preserve report error envelope Co-authored-by: Medulla --- .../tinycomputer/src/tinybus_module/README.md | 5 +- .../tinybus_module/dispatch/dispatch_tests.rs | 19 +++ .../src/tinybus_module/dispatch/mod.rs | 48 +++++--- .../src/tinybus_module/trace_sink/mod.rs | 108 +++++++++++++----- .../trace_sink/trace_sink_tests.rs | 103 +++++++++++++---- .../specs/desktop-module-contract.md | 5 +- 6 files changed, 223 insertions(+), 65 deletions(-) create mode 100644 crates/tinycomputer/src/tinybus_module/dispatch/dispatch_tests.rs diff --git a/crates/tinycomputer/src/tinybus_module/README.md b/crates/tinycomputer/src/tinybus_module/README.md index 502d09114..a2af54e06 100644 --- a/crates/tinycomputer/src/tinybus_module/README.md +++ b/crates/tinycomputer/src/tinybus_module/README.md @@ -101,5 +101,6 @@ in the host. See the [contract](../../../tinycomputer-bus/src/accessibility/READ GlobeRead retains a bounded typed batch until acknowledgment. Native overflow or legacy destructive polling marks continuity loss, requiring activation reset. GlobeShutdown rejects new listener acquisition and awaits native child/pipe -cleanup before returning. Stop failures retain -ownership for retry; terminal shutdown must succeed before generic ABI unload. +cleanup before returning. Stop failures retain ownership for retry; terminal +shutdown joins native listeners and the trace sink worker before generic ABI +unload. diff --git a/crates/tinycomputer/src/tinybus_module/dispatch/dispatch_tests.rs b/crates/tinycomputer/src/tinybus_module/dispatch/dispatch_tests.rs new file mode 100644 index 000000000..c90fcfc80 --- /dev/null +++ b/crates/tinycomputer/src/tinybus_module/dispatch/dispatch_tests.rs @@ -0,0 +1,19 @@ +//! Tests for task-report failures returned through the agent response envelope. + +use super::report_sink_failure; + +#[test] +fn a_task_report_sink_failure_is_a_recoverable_agent_response() { + let response = report_sink_failure::(); + + assert!(!response.ok); + assert!(response.data.is_none()); + assert!(response.error.is_some()); + let Some(error) = response.error else { + return; + }; + assert_eq!(error.code, "TRACE_SINK_FAILED"); + assert!(error.message.contains("could not be persisted")); + assert!(error.hint.contains("retry TaskReport")); + assert!(error.recoverable); +} diff --git a/crates/tinycomputer/src/tinybus_module/dispatch/mod.rs b/crates/tinycomputer/src/tinybus_module/dispatch/mod.rs index fced7eb95..5efed9198 100644 --- a/crates/tinycomputer/src/tinybus_module/dispatch/mod.rs +++ b/crates/tinycomputer/src/tinybus_module/dispatch/mod.rs @@ -42,9 +42,9 @@ use tinycomputer_bus::{ use std::sync::Arc; use tinycomputer_bus::agent::{ - AgentResponse, AwaitTaskRequest, Capabilities, ContinueTaskRequest, PlanTaskRequest, - StartTaskRequest, SurfaceAvailability, SurfaceKind, TaskPlan, TaskRef, TaskReport, - TaskReportRequest, TaskView, + AgentError, AgentResponse, AwaitTaskRequest, Capabilities, ContinueTaskRequest, + PlanTaskRequest, StartTaskRequest, SurfaceAvailability, SurfaceKind, TaskPlan, TaskRef, + TaskReport, TaskReportRequest, TaskView, }; use super::consequence_gate::ConsequenceLink; @@ -206,13 +206,16 @@ impl DesktopService { let reply = self .on_tasks(move |tasks| tasks.report_for(&request)) .await?; - if let (Some(link), Some(report)) = (&self.trace_link, &reply.data) { - link.write_report(tinycomputer_bus::trace_sink::TaskReportRecord { - task_id: report.view.id.to_string(), - report: report.clone(), - }) - .await - .map_err(|_| tinybus::Error::failed("task report sink failed"))?; + if let (Some(link), Some(report)) = (&self.trace_link, &reply.data) + && link + .write_report(tinycomputer_bus::trace_sink::TaskReportRecord { + task_id: report.view.id.to_string(), + report: report.clone(), + }) + .await + .is_err() + { + return Ok(report_sink_failure()); } Ok(reply) } @@ -608,16 +611,22 @@ impl DesktopService { .await } - /// Terminal joined listener cleanup before unloading the module. + /// Joins native listeners and the trace sink worker before module unload. async fn globe_shutdown(&self) -> TinyBusResult { // Close admission before scheduling the blocking cleanup barrier. self.accessibility.close_admission(); - accessibility::run( + let accessibility_reply = accessibility::run( Arc::clone(&self.accessibility), "globe-shutdown", accessibility::Access::shutdown, ) - .await + .await; + if let Some(link) = self.trace_link.clone() { + tokio::task::spawn_blocking(move || link.shutdown()) + .await + .map_err(|_| tinybus::Error::failed("trace sink shutdown task failed"))??; + } + accessibility_reply } /// Native globe stop through module-owned resources. @@ -816,3 +825,16 @@ impl DesktopService { )) } } + +fn report_sink_failure() -> AgentResponse { + AgentResponse::err(AgentError::new( + "TRACE_SINK_FAILED", + "task report could not be persisted by the configured host", + "retry TaskReport to ask the host to persist it again", + true, + )) +} + +#[cfg(test)] +#[path = "dispatch_tests.rs"] +mod tests; diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs index 12b859235..9a2da906c 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs @@ -53,11 +53,11 @@ enum Command { } /// The synchronous sink adapter, backed by a worker that owns the bus calls. -#[derive(Clone)] pub(crate) struct TraceLink { connection: Connection, destination: tinybus::BusName, - worker: SyncSender, + worker: std::sync::Mutex>>, + worker_thread: std::sync::Mutex>>, callback_active: Arc, confidential: bool, } @@ -100,7 +100,7 @@ impl TraceLink { )); } let (sender, receiver) = mpsc::sync_channel(1); - std::thread::Builder::new() + let worker_thread = std::thread::Builder::new() .name("tinycomputer-trace-sink".into()) .spawn(move || { worker( @@ -116,15 +116,55 @@ impl TraceLink { Ok(Arc::new(Self { connection, destination, - worker: sender, + worker: std::sync::Mutex::new(Some(sender)), + worker_thread: std::sync::Mutex::new(Some(worker_thread)), callback_active, confidential, })) } + pub(crate) fn shutdown(&self) -> TinyBusResult<()> { + let sender = self + .worker + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take(); + drop(sender); + + let mut worker_thread = self + .worker_thread + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(worker_thread) = worker_thread.take() { + worker_thread + .join() + .map_err(|_| TinyBusError::failed("trace sink worker panicked during shutdown"))?; + } + + let deadline = Instant::now() + CALL_TIMEOUT + Duration::from_secs(1); + while self.callback_active.load(Ordering::Acquire) && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(1)); + } + if self.callback_active.load(Ordering::Acquire) { + return Err(TinyBusError::failed( + "trace sink callback did not finish during shutdown", + )); + } + Ok(()) + } + pub(crate) async fn write_report(&self, record: TaskReportRecord) -> TinyBusResult<()> { - let _guard = CallbackGuard::try_acquire(&self.callback_active) - .ok_or_else(|| TinyBusError::failed("trace sink callback is busy"))?; + let _guard = { + let worker = self + .worker + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if worker.is_none() { + return Err(TinyBusError::failed("trace sink worker stopped")); + } + CallbackGuard::try_acquire(&self.callback_active) + .ok_or_else(|| TinyBusError::failed("trace sink callback is busy"))? + }; call_to_host::( &self.proxy(CALL_TIMEOUT)?, trace_sink::methods::WRITE_REPORT, @@ -300,6 +340,12 @@ impl Drop for CallbackGuard<'_> { } } +impl Drop for TraceLink { + fn drop(&mut self) { + let _ = self.shutdown(); + } +} + fn operation_deadline(deadline: TraceSinkDeadline) -> Option { let remaining = deadline.remaining(); (!remaining.is_zero()) @@ -336,21 +382,15 @@ impl EngineTraceSink for TraceLink { let timeout = remaining_timeout(deadline) .ok_or_else(|| TraceSinkError::Internal("trace sink deadline expired".into()))?; let (reply, result) = mpsc::sync_channel(1); - self.worker - .try_send(Command::Append { + send( + &self.worker, + Command::Append { record: record.clone(), deadline, byte_budget, reply, - }) - .map_err(|error| match error { - TrySendError::Full(_) => { - TraceSinkError::Internal("trace sink worker is busy".into()) - } - TrySendError::Disconnected(_) => { - TraceSinkError::Internal("trace sink worker stopped".into()) - } - })?; + }, + )?; receive(&result, timeout) .map_err(|_| TraceSinkError::Internal("trace sink acknowledgment timed out".into()))? .map_err(|()| TraceSinkError::Internal("trace sink rejected event".into())) @@ -376,8 +416,9 @@ impl EngineTraceSink for TraceLink { EngineArtifactKind::Screenshot => TraceArtifactKind::Screenshot, EngineArtifactKind::RefMap => TraceArtifactKind::RefMap, }; - self.worker - .try_send(Command::StoreArtifact { + send( + &self.worker, + Command::StoreArtifact { kind, name: artifact.name.to_owned(), bytes: artifact.bytes.to_vec(), @@ -388,15 +429,8 @@ impl EngineTraceSink for TraceLink { refmap_bytes: limits.refmap_bytes, }, reply, - }) - .map_err(|error| match error { - TrySendError::Full(_) => { - TraceSinkError::Internal("trace sink worker is busy".into()) - } - TrySendError::Disconnected(_) => { - TraceSinkError::Internal("trace sink worker stopped".into()) - } - })?; + }, + )?; receive(&result, timeout) .map_err(|_| { TraceSinkError::Internal("trace artifact acknowledgment timed out".into()) @@ -405,6 +439,24 @@ impl EngineTraceSink for TraceLink { } } +fn send( + worker: &std::sync::Mutex>>, + command: Command, +) -> std::result::Result<(), TraceSinkError> { + let worker = worker + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let Some(worker) = worker.as_ref() else { + return Err(TraceSinkError::Internal("trace sink worker stopped".into())); + }; + worker.try_send(command).map_err(|error| match error { + TrySendError::Full(_) => TraceSinkError::Internal("trace sink worker is busy".into()), + TrySendError::Disconnected(_) => { + TraceSinkError::Internal("trace sink worker stopped".into()) + } + }) +} + #[cfg(test)] #[path = "trace_sink_tests.rs"] mod tests; diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs index 5c047e285..f7d6c83be 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs @@ -263,14 +263,17 @@ async fn an_already_expired_queued_event_is_rejected_without_a_host_write() let module = Connection::connect(bus.connect().await?).await?; let link = TraceLink::new_for_bus_tests(module, tinybus::BusName::new(trace_sink::INTERFACE)?)?; let (reply, result) = mpsc::sync_channel(1); - link.worker.try_send(Command::Append { - record: serde_json::json!({"event": "expired"}), - deadline: Instant::now() - .checked_sub(Duration::from_millis(1)) - .unwrap_or_else(Instant::now), - byte_budget: 4096, - reply, - })?; + send( + &link.worker, + Command::Append { + record: serde_json::json!({"event": "expired"}), + deadline: Instant::now() + .checked_sub(Duration::from_millis(1)) + .unwrap_or_else(Instant::now), + byte_budget: 4096, + reply, + }, + )?; let acknowledgment = tokio::task::spawn_blocking(move || result.recv_timeout(Duration::from_secs(1))).await??; @@ -299,22 +302,28 @@ async fn expired_queued_event_is_rejected_without_a_late_host_write() let module = Connection::connect(bus.connect().await?).await?; let link = TraceLink::new_for_bus_tests(module, tinybus::BusName::new(trace_sink::INTERFACE)?)?; let (first_reply, first_result) = mpsc::sync_channel(1); - link.worker.try_send(Command::Append { - record: serde_json::json!({"event": "blocker"}), - deadline: Instant::now() + Duration::from_secs(10), - byte_budget: 4096, - reply: first_reply, - })?; + send( + &link.worker, + Command::Append { + record: serde_json::json!({"event": "blocker"}), + deadline: Instant::now() + Duration::from_secs(10), + byte_budget: 4096, + reply: first_reply, + }, + )?; tokio::time::timeout(Duration::from_secs(5), started_rx).await??; let (queued_reply, queued_result) = mpsc::sync_channel(1); let queued_deadline = Instant::now() + Duration::from_millis(50); - link.worker.try_send(Command::Append { - record: serde_json::json!({"event": "expired"}), - deadline: queued_deadline, - byte_budget: 4096, - reply: queued_reply, - })?; + send( + &link.worker, + Command::Append { + record: serde_json::json!({"event": "expired"}), + deadline: queued_deadline, + byte_budget: 4096, + reply: queued_reply, + }, + )?; tokio::time::sleep_until( tokio::time::Instant::from_std(queued_deadline) + Duration::from_millis(1), ) @@ -343,6 +352,60 @@ async fn expired_queued_event_is_rejected_without_a_late_host_write() Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn shutdown_joins_an_active_host_callback_and_closes_admission() +-> Result<(), Box> { + let bus = tinybus::transport::memory::MemoryBus::new(); + tinybus::broker::Broker::new().spawn(bus.clone()); + let host_connection = Connection::connect(bus.connect().await?).await?; + let (started_tx, started_rx) = tokio::sync::oneshot::channel(); + let (release_tx, release_rx) = tokio::sync::oneshot::channel(); + let host = BlockingRecordingHost { + events: Arc::default(), + started: Arc::new(std::sync::Mutex::new(Some(started_tx))), + release: Arc::new(std::sync::Mutex::new(Some(release_rx))), + }; + host_connection + .serve_at(trace_sink::OBJECT_PATH.try_into()?, host) + .await?; + host_connection.request_name(trace_sink::INTERFACE).await?; + let module = Connection::connect(bus.connect().await?).await?; + let link = TraceLink::new_for_bus_tests(module, tinybus::BusName::new(trace_sink::INTERFACE)?)?; + let callback_link = link.clone(); + let callback_deadline = TraceSinkDeadline::after(5_000)?; + let callback = tokio::task::spawn_blocking(move || { + callback_link.append( + &serde_json::json!({"event": "blocker"}), + callback_deadline, + 4096, + ) + }); + tokio::time::timeout(Duration::from_secs(5), started_rx).await??; + + let shutdown_link = link.clone(); + let mut shutdown = tokio::task::spawn_blocking(move || shutdown_link.shutdown()); + assert!( + tokio::time::timeout(Duration::from_millis(50), &mut shutdown) + .await + .is_err() + ); + release_tx + .send(()) + .map_err(|()| TinyBusError::failed("test release receiver was dropped"))?; + + shutdown.await??; + assert!(callback.await?.is_ok()); + assert!( + link.append( + &serde_json::json!({"event": "after-shutdown"}), + TraceSinkDeadline::after(5_000)?, + 4096, + ) + .is_err() + ); + Ok(()) +} + #[derive(Clone)] struct BlockingRecordingHost { events: Arc>>, diff --git a/docs/technical/specs/desktop-module-contract.md b/docs/technical/specs/desktop-module-contract.md index fbacbbcb0..f4bfbf44e 100644 --- a/docs/technical/specs/desktop-module-contract.md +++ b/docs/technical/specs/desktop-module-contract.md @@ -102,8 +102,9 @@ in order. `StoreArtifact` receives desktop trace screenshots and reference maps as standard padded base64, capped at 8 MiB decoded, and returns their committed opaque references. `WriteReport` receives a task id and the full `TaskReport` whenever the caller requests `TaskReport`. The host acknowledges each write; -trace failures follow `trace_strict`, while a report -write failure is returned to the report caller. Sink mode has no local +trace failures follow `trace_strict`, while a report write failure returns a +recoverable `TRACE_SINK_FAILED` agent response. Terminal Globe shutdown joins +the trace worker before module unload. Sink mode has no local file/session fallback, even when its host callback fails. Without the explicit configuration, existing desktop trace path and session behavior remain in effect. Hosts should upsert reports by task id because callers may request the From 24c09944f367fd9924b628297a58771f8b54fe9e Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:15:28 +0000 Subject: [PATCH 12/48] Release trace guard before callback acknowledgment Co-authored-by: Medulla --- .../src/tinybus_module/trace_sink/mod.rs | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs index 9a2da906c..9b62020ac 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs @@ -202,15 +202,15 @@ fn worker( byte_budget, reply, } => { - let Some(_guard) = CallbackGuard::try_acquire(callback_active) else { + let Some(timeout) = remaining_timeout(deadline) else { let _ = reply.send(Err(())); continue; }; - let Some(timeout) = remaining_timeout(deadline) else { + let Some(deadline_ms) = remaining_millis(deadline) else { let _ = reply.send(Err(())); continue; }; - let Some(deadline_ms) = remaining_millis(deadline) else { + let Some(guard) = CallbackGuard::try_acquire(callback_active) else { let _ = reply.send(Err(())); continue; }; @@ -235,6 +235,7 @@ fn worker( .await .map(|_| ()) }); + drop(guard); let _ = reply.send(result.map_err(|_| ())); } Command::StoreArtifact { @@ -245,15 +246,15 @@ fn worker( limits, reply, } => { - let Some(_guard) = CallbackGuard::try_acquire(callback_active) else { + let Some(timeout) = remaining_timeout(deadline) else { let _ = reply.send(Err(())); continue; }; - let Some(timeout) = remaining_timeout(deadline) else { + let Some(deadline_ms) = remaining_millis(deadline) else { let _ = reply.send(Err(())); continue; }; - let Some(deadline_ms) = remaining_millis(deadline) else { + let Some(guard) = CallbackGuard::try_acquire(callback_active) else { let _ = reply.send(Err(())); continue; }; @@ -280,6 +281,7 @@ fn worker( .await .map(|reply| reply.reference) }); + drop(guard); let _ = reply.send(result.map_err(|_| ())); } } From 542fd92244908849034c874ba9a80415c38bd9ef Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:26:36 +0000 Subject: [PATCH 13/48] docs(trace-sink): document host-owned trace persistence Describe the new trace_sink configuration key, which routes desktop trace events, bounded artifacts, and task reports to the confidential TraceSinkHost interface at the destination prepared by ModuleHost::prepare_host_callbacks. Sink mode replaces local trace and session persistence without falling back to trace_path, and report write failures now surface as a recoverable TRACE_SINK_FAILED response, so the module verifier asserts that error shape Auto-committed-on: cuttlefish Co-authored-by: Medulla --- MODULE.md | 6 ++++++ .../src/bin/verify_module.rs | 16 +++++++++++--- docs/crates/tinycomputer/configuration.md | 21 +++++++++++++++++++ docs/technical/architecture.md | 1 + 4 files changed, 41 insertions(+), 3 deletions(-) diff --git a/MODULE.md b/MODULE.md index 3193acdc4..5cc663bb4 100644 --- a/MODULE.md +++ b/MODULE.md @@ -44,6 +44,12 @@ is optional: - `session_id` and `trace_path` (strings), `trace_strict` and `headed` (booleans) for the desktop engine; +- `trace_sink`: an object containing only the unique callback destination + prepared for this module by `ModuleHost::prepare_host_callbacks`. It opts + into confidential host persistence for desktop traces, bounded artifacts, + and requested task reports. Sink mode replaces local trace/session storage + and does not fall back to `trace_path`; event errors follow `trace_strict`, + and report write errors return a recoverable `TRACE_SINK_FAILED` response; - `jev`: the decision model and its API key, needed by the Jev-driven and task members. `provider` picks it: Jev through `type_safe` (the default), `open_router`, or `tiny_humans_open_router`; `open_jev` (OpenJEV's diff --git a/crates/tinycomputer-examples/src/bin/verify_module.rs b/crates/tinycomputer-examples/src/bin/verify_module.rs index 7a2f8d397..db070b01e 100644 --- a/crates/tinycomputer-examples/src/bin/verify_module.rs +++ b/crates/tinycomputer-examples/src/bin/verify_module.rs @@ -260,8 +260,8 @@ async fn verify_report_sink( ); } capture.fail_reports.store(true, Ordering::SeqCst); - let failed = proxy - .call_confidential::( + let failed: AgentResponse = proxy + .call_confidential( names::methods::TASK_REPORT, (TaskReportRequest { id: task_id, @@ -269,7 +269,17 @@ async fn verify_report_sink( },), ) .await; - if failed.is_ok() { + let expected_failure = match failed { + Ok(response) => { + !response.ok + && response.data.is_none() + && response + .error + .is_some_and(|error| error.code == "TRACE_SINK_FAILED" && error.recoverable) + } + Err(_) => false, + }; + if !expected_failure { return Err(io::Error::other("task report sink failure was not returned").into()); } Ok(()) diff --git a/docs/crates/tinycomputer/configuration.md b/docs/crates/tinycomputer/configuration.md index 328d2ac12..950d41161 100644 --- a/docs/crates/tinycomputer/configuration.md +++ b/docs/crates/tinycomputer/configuration.md @@ -45,6 +45,27 @@ about the on-screen overlay the agent draws to show where it is about to act, and it is a different setting from `constraints.headed` on a task, which controls the *browser's* visibility for that one task. +## `trace_sink` + +```json +{ + "trace_sink": { + "destination": ":1.42" + } +} +``` + +Set `trace_sink` to an object containing only the unique callback destination +prepared for this module by `ModuleHost::prepare_host_callbacks`. The module +then sends desktop trace events, bounded artifacts, and requested task reports +to the confidential `TraceSinkHost` interface. A selected sink replaces local +trace-file and session persistence; it never falls back to `trace_path` when +the host callback fails. Event failures follow `trace_strict`. A report write +failure returns a recoverable `TRACE_SINK_FAILED` agent response, so callers +can retry `TaskReport`. Without this key, or with `false`, the existing +`trace_path` behavior remains in effect. `true`, malformed objects, and +well-known bus names are rejected. + ## `jev` ```json diff --git a/docs/technical/architecture.md b/docs/technical/architecture.md index f055c29f9..1f0ef1317 100644 --- a/docs/technical/architecture.md +++ b/docs/technical/architecture.md @@ -221,6 +221,7 @@ configuration validates. | `session_id` | string | agent-desktop session to join | | `trace_path` | string | where agent-desktop writes its trace | | `trace_strict` | bool | fail a call when its trace cannot be written | +| `trace_sink` | object | optional host-owned persistence at the unique destination prepared by `ModuleHost::prepare_host_callbacks`; replaces local trace and session persistence | | `headed` | bool | use real input instead of accessibility actions | | `jev` | object | decision provider (`type_safe`, `open_router`, `tiny_humans_open_router`, `open_jev`, `sage`), API key, optional model, approved endpoint, timeout, retries, `sdk_name` for the TinyHumans proxy, and `fast` for Sage | | `planner` | object | `api_key`, `provider` (`open_router` or `tiny_humans`), approved `endpoint_url`, `sdk_name`, and optional `model` for the planner, optional `rescue_route` giving the rescuer its own route and key, optional `rescue_model` for rescuing failed steps (`docs/technical/specs/task-rescue.md`), and optional `output_model` for shaping a finished task's answer (`docs/technical/specs/task-output.md`); absent means no planner, no rescues, and no output shapes | From ac7ae3083781b560376ef813441cbbd700a702e3 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:27:36 +0000 Subject: [PATCH 14/48] fix(examples): annotate call_confidential return type The turbofish on call_confidential now supplies the response type explicitly, so the binding no longer needs a type annotation. This keeps the example compiling against the updated signature. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-examples/src/bin/verify_module.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/tinycomputer-examples/src/bin/verify_module.rs b/crates/tinycomputer-examples/src/bin/verify_module.rs index db070b01e..d2702fe35 100644 --- a/crates/tinycomputer-examples/src/bin/verify_module.rs +++ b/crates/tinycomputer-examples/src/bin/verify_module.rs @@ -260,8 +260,8 @@ async fn verify_report_sink( ); } capture.fail_reports.store(true, Ordering::SeqCst); - let failed: AgentResponse = proxy - .call_confidential( + let failed = proxy + .call_confidential::>( names::methods::TASK_REPORT, (TaskReportRequest { id: task_id, From ce7abf03149ab3e63149a5b3c4be24e21b3e3dec Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:39:25 +0000 Subject: [PATCH 15/48] refactor(trace_sink): extract engine adapter into its own module Moved the EngineTraceSink implementation and its send/receive helpers out of trace_sink/mod.rs into a dedicated engine_adapter module, exposing the shared helpers to the parent. The verification example now supplies a real task step and fails fast when the module rejects the flow, so the report sink check exercises an actual task instead of a no-op. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/bin/verify_module.rs | 5 +- .../src/tinybus_module/trace_sink/mod.rs | 104 ++---------------- 2 files changed, 11 insertions(+), 98 deletions(-) diff --git a/crates/tinycomputer-examples/src/bin/verify_module.rs b/crates/tinycomputer-examples/src/bin/verify_module.rs index d2702fe35..1e7970c29 100644 --- a/crates/tinycomputer-examples/src/bin/verify_module.rs +++ b/crates/tinycomputer-examples/src/bin/verify_module.rs @@ -225,12 +225,15 @@ async fn verify_report_sink( (StartTaskRequest { flow: Some(serde_json::from_value(serde_json::json!({ "app": "verification", - "steps": [] + "steps": ["verify report delivery"] }))?), ..StartTaskRequest::default() },), ) .await?; + if !started.ok { + return Err(io::Error::other("module rejected the verification task flow").into()); + } let task_id = started .data .ok_or_else(|| io::Error::other("module did not start the no-op verification task"))? diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs index 9b62020ac..aee2e5779 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs @@ -20,11 +20,13 @@ use tinycomputer_bus::trace_sink::{ self, SinkAck, TaskReportRecord, TraceArtifact, TraceArtifactKind, TraceArtifactRef, TraceEvent, }; use tinycomputer_desktop::{ - TraceSink as EngineTraceSink, TraceSinkArtifact, TraceSinkArtifactKind as EngineArtifactKind, - TraceSinkArtifactLimits, TraceSinkDeadline, TraceSinkError, + TraceSinkArtifactKind as EngineArtifactKind, TraceSinkError, }; -const CALL_TIMEOUT: Duration = Duration::from_secs(10); +mod engine_adapter; + +pub(super) use engine_adapter::{operation_deadline, receive, send}; +use engine_adapter::{CALL_TIMEOUT, remaining_timeout, validate_artifact_size}; fn validate_artifact_size(size: usize) -> std::result::Result<(), TraceSinkError> { if size > tinycomputer_bus::trace_sink::MAX_TRACE_ARTIFACT_BYTES { @@ -56,9 +58,9 @@ enum Command { pub(crate) struct TraceLink { connection: Connection, destination: tinybus::BusName, - worker: std::sync::Mutex>>, + pub(super) worker: std::sync::Mutex>>, worker_thread: std::sync::Mutex>>, - callback_active: Arc, + pub(super) callback_active: Arc, confidential: bool, } @@ -367,98 +369,6 @@ fn receive(receiver: &mpsc::Receiver, timeout: Duration) -> Result std::result::Result<(), TraceSinkError> { - if self.callback_active.load(Ordering::Acquire) { - return Err(TraceSinkError::Internal( - "trace sink callback is busy".into(), - )); - } - let deadline = operation_deadline(deadline) - .ok_or_else(|| TraceSinkError::Internal("trace sink deadline expired".into()))?; - let timeout = remaining_timeout(deadline) - .ok_or_else(|| TraceSinkError::Internal("trace sink deadline expired".into()))?; - let (reply, result) = mpsc::sync_channel(1); - send( - &self.worker, - Command::Append { - record: record.clone(), - deadline, - byte_budget, - reply, - }, - )?; - receive(&result, timeout) - .map_err(|_| TraceSinkError::Internal("trace sink acknowledgment timed out".into()))? - .map_err(|()| TraceSinkError::Internal("trace sink rejected event".into())) - } - - fn store_artifact( - &self, - artifact: TraceSinkArtifact<'_>, - limits: TraceSinkArtifactLimits, - ) -> std::result::Result { - validate_artifact_size(artifact.bytes.len())?; - if self.callback_active.load(Ordering::Acquire) { - return Err(TraceSinkError::Internal( - "trace sink callback is busy".into(), - )); - } - let deadline = operation_deadline(artifact.deadline) - .ok_or_else(|| TraceSinkError::Internal("trace artifact deadline expired".into()))?; - let timeout = remaining_timeout(deadline) - .ok_or_else(|| TraceSinkError::Internal("trace artifact deadline expired".into()))?; - let (reply, result) = mpsc::sync_channel(1); - let kind = match artifact.kind { - EngineArtifactKind::Screenshot => TraceArtifactKind::Screenshot, - EngineArtifactKind::RefMap => TraceArtifactKind::RefMap, - }; - send( - &self.worker, - Command::StoreArtifact { - kind, - name: artifact.name.to_owned(), - bytes: artifact.bytes.to_vec(), - deadline, - limits: tinycomputer_bus::trace_sink::TraceArtifactLimits { - screenshot_bytes: limits.screenshot_bytes, - screenshot_count: limits.screenshot_count, - refmap_bytes: limits.refmap_bytes, - }, - reply, - }, - )?; - receive(&result, timeout) - .map_err(|_| { - TraceSinkError::Internal("trace artifact acknowledgment timed out".into()) - })? - .map_err(|()| TraceSinkError::Internal("trace sink rejected artifact".into())) - } -} - -fn send( - worker: &std::sync::Mutex>>, - command: Command, -) -> std::result::Result<(), TraceSinkError> { - let worker = worker - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let Some(worker) = worker.as_ref() else { - return Err(TraceSinkError::Internal("trace sink worker stopped".into())); - }; - worker.try_send(command).map_err(|error| match error { - TrySendError::Full(_) => TraceSinkError::Internal("trace sink worker is busy".into()), - TrySendError::Disconnected(_) => { - TraceSinkError::Internal("trace sink worker stopped".into()) - } - }) -} - #[cfg(test)] #[path = "trace_sink_tests.rs"] mod tests; From ea82ed8a531fe9afe64400b7589dce7488a3d367 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:39:44 +0000 Subject: [PATCH 16/48] feat(trace_sink): add engine adapter for trace sink Introduce an adapter that bridges the trace sink to the engine, allowing trace events to be forwarded through the engine's interface. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../trace_sink/engine_adapter.rs | 142 ++++++++++++++++++ 1 file changed, 142 insertions(+) create mode 100644 crates/tinycomputer/src/tinybus_module/trace_sink/engine_adapter.rs diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/engine_adapter.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/engine_adapter.rs new file mode 100644 index 000000000..da3b214d6 --- /dev/null +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/engine_adapter.rs @@ -0,0 +1,142 @@ +//! Implements the desktop engine's synchronous trace callbacks over the worker queue. + +use std::sync::atomic::Ordering; +use std::sync::mpsc::{self, Receiver, RecvTimeoutError, SyncSender, TrySendError}; +use std::time::{Duration, Instant}; + +use tinycomputer_desktop::{ + TraceSink as EngineTraceSink, TraceSinkArtifact, TraceSinkArtifactKind as EngineArtifactKind, + TraceSinkArtifactLimits, TraceSinkDeadline, TraceSinkError, +}; + +use super::{CALL_TIMEOUT, CallbackGuard, Command, TraceLink, operation_deadline, receive}; + +impl EngineTraceSink for TraceLink { + fn append( + &self, + record: &serde_json::Value, + deadline: TraceSinkDeadline, + byte_budget: u64, + ) -> std::result::Result<(), TraceSinkError> { + if self.callback_active.load(Ordering::Acquire) { + return Err(TraceSinkError::Internal( + "trace sink callback is busy".into(), + )); + } + let deadline = operation_deadline(deadline) + .ok_or_else(|| TraceSinkError::Internal("trace sink deadline expired".into()))?; + let timeout = remaining_timeout(deadline) + .ok_or_else(|| TraceSinkError::Internal("trace sink deadline expired".into()))?; + let (reply, result) = mpsc::sync_channel(1); + send( + &self.worker, + Command::Append { + record: record.clone(), + deadline, + byte_budget, + reply, + }, + )?; + receive(&result, timeout) + .map_err(|_| TraceSinkError::Internal("trace sink acknowledgment timed out".into()))? + .map_err(|()| TraceSinkError::Internal("trace sink rejected event".into())) + } + + fn store_artifact( + &self, + artifact: TraceSinkArtifact<'_>, + limits: TraceSinkArtifactLimits, + ) -> std::result::Result { + validate_artifact_size(artifact.bytes.len())?; + if self.callback_active.load(Ordering::Acquire) { + return Err(TraceSinkError::Internal( + "trace sink callback is busy".into(), + )); + } + let deadline = operation_deadline(artifact.deadline) + .ok_or_else(|| TraceSinkError::Internal("trace artifact deadline expired".into()))?; + let timeout = remaining_timeout(deadline) + .ok_or_else(|| TraceSinkError::Internal("trace artifact deadline expired".into()))?; + let (reply, result) = mpsc::sync_channel(1); + let kind = match artifact.kind { + EngineArtifactKind::Screenshot => tinycomputer_bus::trace_sink::TraceArtifactKind::Screenshot, + EngineArtifactKind::RefMap => tinycomputer_bus::trace_sink::TraceArtifactKind::RefMap, + }; + send( + &self.worker, + Command::StoreArtifact { + kind, + name: artifact.name.to_owned(), + bytes: artifact.bytes.to_vec(), + deadline, + limits: tinycomputer_bus::trace_sink::TraceArtifactLimits { + screenshot_bytes: limits.screenshot_bytes, + screenshot_count: limits.screenshot_count, + refmap_bytes: limits.refmap_bytes, + }, + reply, + }, + )?; + receive(&result, timeout) + .map_err(|_| { + TraceSinkError::Internal("trace artifact acknowledgment timed out".into()) + })? + .map_err(|()| TraceSinkError::Internal("trace sink rejected artifact".into())) + } +} + +pub(super) fn validate_artifact_size(size: usize) -> std::result::Result<(), TraceSinkError> { + if size > tinycomputer_bus::trace_sink::MAX_TRACE_ARTIFACT_BYTES { + return Err(TraceSinkError::Internal( + "trace artifact exceeds the 8 MiB bus limit".into(), + )); + } + Ok(()) +} + +pub(super) fn remaining_timeout(deadline: Instant) -> Option { + let remaining = deadline.checked_duration_since(Instant::now())?; + let timeout = remaining.min(CALL_TIMEOUT); + (timeout.as_millis() > 0).then_some(timeout) +} + +pub(super) fn remaining_millis(deadline: Instant) -> Option { + let remaining = deadline.checked_duration_since(Instant::now())?; + let millis = u64::try_from(remaining.as_millis()).unwrap_or(u64::MAX); + (millis > 0).then_some(millis) +} + +pub(super) fn send( + worker: &std::sync::Mutex>>, + command: Command, +) -> std::result::Result<(), TraceSinkError> { + let worker = worker + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let Some(worker) = worker.as_ref() else { + return Err(TraceSinkError::Internal("trace sink worker stopped".into())); + }; + worker.try_send(command).map_err(|error| match error { + TrySendError::Full(_) => TraceSinkError::Internal("trace sink worker is busy".into()), + TrySendError::Disconnected(_) => { + TraceSinkError::Internal("trace sink worker stopped".into()) + } + }) +} + +pub(super) fn operation_deadline(deadline: TraceSinkDeadline) -> Option { + let remaining = deadline.remaining(); + (!remaining.is_zero()) + .then(|| Instant::now().checked_add(remaining)) + .flatten() +} + +pub(super) fn receive(receiver: &Receiver, timeout: Duration) -> Result { + match tokio::runtime::Handle::try_current() { + Ok(handle) if handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread => { + tokio::task::block_in_place(|| receiver.recv_timeout(timeout)) + } + Ok(_) => Err(RecvTimeoutError::Timeout), + Err(_) => receiver.recv_timeout(timeout), + } +} From 977b7be63a9d25518deb5fbce3d2ee9a205b8072 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:40:27 +0000 Subject: [PATCH 17/48] refactor(trace_sink): move shared helpers into engine adapter The trace sink module now re-exports its timeout, receive, and validation helpers from the engine adapter instead of defining duplicate copies, and the command and callback guard types are exposed to the adapter. This removes the redundant implementations and keeps a single source of truth for the bus call plumbing. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../trace_sink/engine_adapter.rs | 4 +- .../src/tinybus_module/trace_sink/mod.rs | 56 +++---------------- 2 files changed, 11 insertions(+), 49 deletions(-) diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/engine_adapter.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/engine_adapter.rs index da3b214d6..888b685c9 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/engine_adapter.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/engine_adapter.rs @@ -59,7 +59,9 @@ impl EngineTraceSink for TraceLink { .ok_or_else(|| TraceSinkError::Internal("trace artifact deadline expired".into()))?; let (reply, result) = mpsc::sync_channel(1); let kind = match artifact.kind { - EngineArtifactKind::Screenshot => tinycomputer_bus::trace_sink::TraceArtifactKind::Screenshot, + EngineArtifactKind::Screenshot => { + tinycomputer_bus::trace_sink::TraceArtifactKind::Screenshot + } EngineArtifactKind::RefMap => tinycomputer_bus::trace_sink::TraceArtifactKind::RefMap, }; send( diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs index aee2e5779..1e9b18337 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs @@ -10,7 +10,7 @@ use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::mpsc::{self, Receiver, RecvTimeoutError, SyncSender, TrySendError}; +use std::sync::mpsc::{self, Receiver, SyncSender}; use std::time::{Duration, Instant}; use serde::Serialize; @@ -19,25 +19,16 @@ use tinybus::{Connection, Error as TinyBusError, Proxy, Result as TinyBusResult} use tinycomputer_bus::trace_sink::{ self, SinkAck, TaskReportRecord, TraceArtifact, TraceArtifactKind, TraceArtifactRef, TraceEvent, }; -use tinycomputer_desktop::{ - TraceSinkArtifactKind as EngineArtifactKind, TraceSinkError, -}; +use tinycomputer_desktop::{TraceSinkArtifactKind as EngineArtifactKind, TraceSinkError}; mod engine_adapter; -pub(super) use engine_adapter::{operation_deadline, receive, send}; -use engine_adapter::{CALL_TIMEOUT, remaining_timeout, validate_artifact_size}; - -fn validate_artifact_size(size: usize) -> std::result::Result<(), TraceSinkError> { - if size > tinycomputer_bus::trace_sink::MAX_TRACE_ARTIFACT_BYTES { - return Err(TraceSinkError::Internal( - "trace artifact exceeds the 8 MiB bus limit".into(), - )); - } - Ok(()) -} +pub(super) use engine_adapter::{ + operation_deadline, receive, remaining_millis, remaining_timeout, send, validate_artifact_size, +}; +pub(super) const CALL_TIMEOUT: Duration = Duration::from_secs(10); -enum Command { +pub(super) enum Command { Append { record: serde_json::Value, deadline: Instant, @@ -315,19 +306,7 @@ where } } -fn remaining_timeout(deadline: Instant) -> Option { - let remaining = deadline.checked_duration_since(Instant::now())?; - let timeout = remaining.min(CALL_TIMEOUT); - (timeout.as_millis() > 0).then_some(timeout) -} - -fn remaining_millis(deadline: Instant) -> Option { - let remaining = deadline.checked_duration_since(Instant::now())?; - let millis = u64::try_from(remaining.as_millis()).unwrap_or(u64::MAX); - (millis > 0).then_some(millis) -} - -struct CallbackGuard<'a>(&'a AtomicBool); +pub(super) struct CallbackGuard<'a>(&'a AtomicBool); impl<'a> CallbackGuard<'a> { fn try_acquire(active: &'a AtomicBool) -> Option { @@ -350,25 +329,6 @@ impl Drop for TraceLink { } } -fn operation_deadline(deadline: TraceSinkDeadline) -> Option { - let remaining = deadline.remaining(); - (!remaining.is_zero()) - .then(|| Instant::now().checked_add(remaining)) - .flatten() -} - -fn receive(receiver: &mpsc::Receiver, timeout: Duration) -> Result { - match tokio::runtime::Handle::try_current() { - Ok(handle) if handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread => { - tokio::task::block_in_place(|| receiver.recv_timeout(timeout)) - } - // A current-thread executor cannot make progress while this sync - // callback waits, so fail instead of deadlocking its dispatch loop. - Ok(_) => Err(RecvTimeoutError::Timeout), - Err(_) => receiver.recv_timeout(timeout), - } -} - #[cfg(test)] #[path = "trace_sink_tests.rs"] mod tests; From e76964300a4389637a2f3b791aef0b54b709430d Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:41:08 +0000 Subject: [PATCH 18/48] refactor(trace_sink): narrow engine adapter re-exports The engine adapter helpers are now imported privately instead of being re-exported to the parent module, and the engine trace sink types are imported directly where they are used. This keeps the module's public surface limited to what callers actually need. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/tinybus_module/trace_sink/engine_adapter.rs | 2 +- crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs | 9 ++++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/engine_adapter.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/engine_adapter.rs index 888b685c9..1d565d8bb 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/engine_adapter.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/engine_adapter.rs @@ -9,7 +9,7 @@ use tinycomputer_desktop::{ TraceSinkArtifactLimits, TraceSinkDeadline, TraceSinkError, }; -use super::{CALL_TIMEOUT, CallbackGuard, Command, TraceLink, operation_deadline, receive}; +use super::{CALL_TIMEOUT, CallbackGuard, Command, TraceLink}; impl EngineTraceSink for TraceLink { fn append( diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs index 1e9b18337..edaecfa54 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs @@ -10,7 +10,7 @@ use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::mpsc::{self, Receiver, SyncSender}; +use std::sync::mpsc::{self, SyncSender}; use std::time::{Duration, Instant}; use serde::Serialize; @@ -19,11 +19,14 @@ use tinybus::{Connection, Error as TinyBusError, Proxy, Result as TinyBusResult} use tinycomputer_bus::trace_sink::{ self, SinkAck, TaskReportRecord, TraceArtifact, TraceArtifactKind, TraceArtifactRef, TraceEvent, }; -use tinycomputer_desktop::{TraceSinkArtifactKind as EngineArtifactKind, TraceSinkError}; +use tinycomputer_desktop::{ + TraceSink as EngineTraceSink, TraceSinkArtifact, TraceSinkArtifactKind as EngineArtifactKind, + TraceSinkArtifactLimits, TraceSinkDeadline, TraceSinkError, +}; mod engine_adapter; -pub(super) use engine_adapter::{ +use engine_adapter::{ operation_deadline, receive, remaining_millis, remaining_timeout, send, validate_artifact_size, }; pub(super) const CALL_TIMEOUT: Duration = Duration::from_secs(10); From 0cb8577b7845ec970f670efa55a3eb15a14a29b8 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:42:00 +0000 Subject: [PATCH 19/48] refactor(trace_sink): narrow engine adapter imports Split the engine adapter imports so the desktop trace sink types are only pulled in under test, and the runtime path imports just the helpers it uses. This keeps the non-test build from depending on the desktop crate and drops the now-unused CallbackGuard import. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../tinybus_module/trace_sink/engine_adapter.rs | 2 +- .../src/tinybus_module/trace_sink/mod.rs | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/engine_adapter.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/engine_adapter.rs index 1d565d8bb..e256e9b81 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/engine_adapter.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/engine_adapter.rs @@ -9,7 +9,7 @@ use tinycomputer_desktop::{ TraceSinkArtifactLimits, TraceSinkDeadline, TraceSinkError, }; -use super::{CALL_TIMEOUT, CallbackGuard, Command, TraceLink}; +use super::{CALL_TIMEOUT, Command, TraceLink}; impl EngineTraceSink for TraceLink { fn append( diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs index edaecfa54..5d5108bb4 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs @@ -10,7 +10,7 @@ use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::mpsc::{self, SyncSender}; +use std::sync::mpsc::{self, Receiver, SyncSender}; use std::time::{Duration, Instant}; use serde::Serialize; @@ -19,16 +19,16 @@ use tinybus::{Connection, Error as TinyBusError, Proxy, Result as TinyBusResult} use tinycomputer_bus::trace_sink::{ self, SinkAck, TaskReportRecord, TraceArtifact, TraceArtifactKind, TraceArtifactRef, TraceEvent, }; +mod engine_adapter; + +#[cfg(test)] +use engine_adapter::{operation_deadline, receive, send, validate_artifact_size}; +use engine_adapter::{remaining_millis, remaining_timeout}; +#[cfg(test)] use tinycomputer_desktop::{ TraceSink as EngineTraceSink, TraceSinkArtifact, TraceSinkArtifactKind as EngineArtifactKind, TraceSinkArtifactLimits, TraceSinkDeadline, TraceSinkError, }; - -mod engine_adapter; - -use engine_adapter::{ - operation_deadline, receive, remaining_millis, remaining_timeout, send, validate_artifact_size, -}; pub(super) const CALL_TIMEOUT: Duration = Duration::from_secs(10); pub(super) enum Command { From d7d4fde098ca87bed30198c3d51277c62fe6f9b0 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:42:39 +0000 Subject: [PATCH 20/48] refactor(tinycomputer): narrow test-only trace sink imports Move the engine adapter and desktop trace sink imports under cfg(test) so they are only pulled in for tests, and drop the unused TraceSinkError import. This keeps the non-test build free of unused import warnings. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs index 5d5108bb4..c86e94cdf 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs @@ -21,13 +21,13 @@ use tinycomputer_bus::trace_sink::{ }; mod engine_adapter; -#[cfg(test)] -use engine_adapter::{operation_deadline, receive, send, validate_artifact_size}; use engine_adapter::{remaining_millis, remaining_timeout}; #[cfg(test)] +use engine_adapter::{send, validate_artifact_size}; +#[cfg(test)] use tinycomputer_desktop::{ TraceSink as EngineTraceSink, TraceSinkArtifact, TraceSinkArtifactKind as EngineArtifactKind, - TraceSinkArtifactLimits, TraceSinkDeadline, TraceSinkError, + TraceSinkArtifactLimits, TraceSinkDeadline, }; pub(super) const CALL_TIMEOUT: Duration = Duration::from_secs(10); From 9259b3910f684588e5f4919ce245838309f83c4b Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 18:02:44 +0000 Subject: [PATCH 21/48] test(persistence): assert browser profile in exported snapshot The paused-task round-trip test now parses the exported payload as JSON and checks the browser profile under the task constraints field instead of matching the raw serialized string, so the assertion verifies the profile lands in the right place rather than merely appearing somewhere in the output. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/task/task_tests/persistence_tests.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/tinycomputer-engine/src/task/task_tests/persistence_tests.rs b/crates/tinycomputer-engine/src/task/task_tests/persistence_tests.rs index fc863c6c5..1c8e8a73b 100644 --- a/crates/tinycomputer-engine/src/task/task_tests/persistence_tests.rs +++ b/crates/tinycomputer-engine/src/task/task_tests/persistence_tests.rs @@ -44,7 +44,11 @@ async fn a_paused_task_round_trips_into_a_fresh_controller() { let encoded = tasks.export_paused_task(&view.id).unwrap(); let serialized = std::str::from_utf8(&encoded).unwrap(); assert!(!serialized.contains("swordfish-secret")); - assert!(serialized.contains(&profile)); + let snapshot: serde_json::Value = serde_json::from_slice(&encoded).unwrap(); + assert_eq!( + snapshot["task"]["constraints"]["browser_profile"].as_str(), + Some(profile.as_str()) + ); drop(tasks); let (restored, script) = controller(vec![finished_run( From 6770cf419d07293b3a51a8222535f0ec27d13105 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 18:28:17 +0000 Subject: [PATCH 22/48] refactor(desktop): move trace configuration into a trace module Trace configuration and context construction moved out of the Desktop builder into a dedicated trace module, leaving the public builder surface unchanged. The contract version was bumped to 2.25 to reflect the TraceSinkHost addition, and the version tests and spec now pin that number. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-bus/src/version/mod.rs | 4 +- .../src/version/version_tests.rs | 7 +- .../tinycomputer-desktop/src/desktop/mod.rs | 82 +---------------- .../tinycomputer-desktop/src/desktop/trace.rs | 91 +++++++++++++++++++ crates/tinycomputer/tests/public_api_tests.rs | 2 +- .../specs/desktop-module-contract.md | 2 +- 6 files changed, 100 insertions(+), 88 deletions(-) create mode 100644 crates/tinycomputer-desktop/src/desktop/trace.rs diff --git a/crates/tinycomputer-bus/src/version/mod.rs b/crates/tinycomputer-bus/src/version/mod.rs index c238b7aef..d2c7e2cfe 100644 --- a/crates/tinycomputer-bus/src/version/mod.rs +++ b/crates/tinycomputer-bus/src/version/mod.rs @@ -8,7 +8,7 @@ //! release workflow bumps, which tracks the shipped artifact. /// The wire contract version this crate defines. -pub const CONTRACT_VERSION: (u32, u32) = (2, 24); +pub const CONTRACT_VERSION: (u32, u32) = (2, 25); /// Returns whether a host holding [`CONTRACT_VERSION`] can bind to a module /// reporting `module`. @@ -22,7 +22,7 @@ pub const CONTRACT_VERSION: (u32, u32) = (2, 24); /// ``` /// # use tinycomputer_bus::{is_compatible, CONTRACT_VERSION}; /// assert!(is_compatible(CONTRACT_VERSION)); -/// assert!(is_compatible((2, 24))); +/// assert!(is_compatible((2, 25))); /// assert!(!is_compatible((2, 11))); /// assert!(!is_compatible((1, 8))); /// ``` diff --git a/crates/tinycomputer-bus/src/version/version_tests.rs b/crates/tinycomputer-bus/src/version/version_tests.rs index 05eb4c277..dbaccb0cb 100644 --- a/crates/tinycomputer-bus/src/version/version_tests.rs +++ b/crates/tinycomputer-bus/src/version/version_tests.rs @@ -6,7 +6,7 @@ use super::{CONTRACT_VERSION, binds, is_compatible}; #[test] fn the_shipped_contract_version_is_pinned() { - assert_eq!(CONTRACT_VERSION, (2, 24)); + assert_eq!(CONTRACT_VERSION, (2, 25)); } #[test] @@ -16,7 +16,7 @@ fn the_contract_binds_to_itself() { #[test] fn a_newer_minor_on_the_module_side_binds() { - assert!(is_compatible((2, 24))); + assert!(is_compatible((2, 25))); assert!(is_compatible((2, 97))); // 2.24 adds same-task flow-to-planner handoff to StartTask. // 2.22 adds optional host-held secret handles to StartTask and RunFlow. @@ -40,8 +40,9 @@ fn a_newer_minor_on_the_module_side_binds() { // host serves it, which a 2.18 module does not call, so its approvals // would never reach the host's policy. // 2.20 adds SessionOptions identity fields for browser launches. - // 2.21 adds TraceSinkHost so desktop events and task reports can be + // 2.25 adds TraceSinkHost so desktop events and task reports can be // committed by the host without using a module-local trace file. + assert!(!is_compatible((2, 24))); assert!(!is_compatible((2, 23))); assert!(!is_compatible((2, 22))); assert!(!is_compatible((2, 18))); diff --git a/crates/tinycomputer-desktop/src/desktop/mod.rs b/crates/tinycomputer-desktop/src/desktop/mod.rs index 00c73e3f3..fb958babf 100644 --- a/crates/tinycomputer-desktop/src/desktop/mod.rs +++ b/crates/tinycomputer-desktop/src/desktop/mod.rs @@ -49,6 +49,7 @@ mod observation; mod permission; mod reply; mod system; +mod trace; mod waiting; use std::path::PathBuf; @@ -141,41 +142,6 @@ impl Desktop { self } - /// Returns this `Desktop` writing a command trace to `path`. - /// - /// A trace records each command and its outcome, which is what makes a - /// failed run reconstructable afterwards. `strict` additionally fails a - /// command whose trace could not be written, rather than letting it succeed - /// with no record — the right setting when the trace is the audit log - /// rather than a debugging aid. - /// - /// # Examples - /// - /// ``` - /// # use tinycomputer_desktop::Desktop; - /// let desktop = Desktop::new().with_trace("/tmp/run.jsonl", false); - /// assert!(desktop.is_tracing()); - /// ``` - #[must_use] - pub fn with_trace(mut self, path: impl Into, strict: bool) -> Self { - self.trace_path = Some(path.into()); - self.trace_strict = strict; - self - } - - /// Returns this `Desktop` sending desktop trace events to `sink`. - /// - /// The selected sink takes precedence over `trace_path` and session trace - /// files. Its synchronous methods are called in event order; strict mode - /// returns sink failures to the command, and best-effort mode warns and - /// continues, matching the local trace writer. The sink's authority stays - /// outside event data. - #[must_use] - pub fn with_trace_sink(mut self, sink: Arc) -> Self { - self.trace_sink = Some(sink); - self - } - /// Returns this `Desktop` in headed or headless mode. /// /// Headed mode lets a ref action take focus and move the real cursor when @@ -284,34 +250,6 @@ impl Desktop { self.session_id.as_deref() } - /// Whether commands write a trace. - /// - /// # Examples - /// - /// ``` - /// # use tinycomputer_desktop::Desktop; - /// assert!(!Desktop::new().is_tracing()); - /// ``` - #[must_use] - pub fn is_tracing(&self) -> bool { - self.trace_path.is_some() || self.trace_sink.is_some() - } - - /// Where commands write their trace, if anywhere. - /// - /// # Examples - /// - /// ``` - /// # use std::path::Path; - /// # use tinycomputer_desktop::Desktop; - /// let desktop = Desktop::new().with_trace("/tmp/run.jsonl", true); - /// assert_eq!(desktop.trace_path(), Some(Path::new("/tmp/run.jsonl"))); - /// ``` - #[must_use] - pub fn trace_path(&self) -> Option<&std::path::Path> { - self.trace_path.as_deref() - } - /// Whether ref actions may take focus and move the real cursor. /// /// # Examples @@ -325,24 +263,6 @@ impl Desktop { self.headed } - /// Builds the engine context every command runs under. - fn context(&self) -> std::result::Result { - let context = match &self.trace_sink { - Some(sink) => CommandContext::new_with_trace_sink( - self.session_id.clone(), - sink.clone(), - self.trace_strict, - true, - ), - None => CommandContext::new( - self.session_id.clone(), - self.trace_path.clone(), - self.trace_strict, - ), - }; - context.map(|context| context.with_headed(self.headed)) - } - /// Runs `command` under a fresh adapter and context, and wraps whatever it /// produces in the envelope. /// diff --git a/crates/tinycomputer-desktop/src/desktop/trace.rs b/crates/tinycomputer-desktop/src/desktop/trace.rs new file mode 100644 index 000000000..64c6e245c --- /dev/null +++ b/crates/tinycomputer-desktop/src/desktop/trace.rs @@ -0,0 +1,91 @@ +//! Trace configuration and engine-context setup for [`super::Desktop`]. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use agent_desktop_core::{AppError, context::CommandContext}; + +use super::Desktop; + +impl Desktop { + /// Returns this `Desktop` writing a command trace to `path`. + /// + /// A trace records each command and its outcome, which is what makes a + /// failed run reconstructable afterwards. `strict` additionally fails a + /// command whose trace could not be written, rather than letting it succeed + /// with no record — the right setting when the trace is the audit log + /// rather than a debugging aid. + /// + /// # Examples + /// + /// ``` + /// # use tinycomputer_desktop::Desktop; + /// let desktop = Desktop::new().with_trace("/tmp/run.jsonl", false); + /// assert!(desktop.is_tracing()); + /// ``` + #[must_use] + pub fn with_trace(mut self, path: impl Into, strict: bool) -> Self { + self.trace_path = Some(path.into()); + self.trace_strict = strict; + self + } + + /// Returns this `Desktop` sending desktop trace events to `sink`. + /// + /// The selected sink takes precedence over `trace_path` and session trace + /// files. Its synchronous methods are called in event order; strict mode + /// returns sink failures to the command, and best-effort mode warns and + /// continues, matching the local trace writer. The sink's authority stays + /// outside event data. + #[must_use] + pub fn with_trace_sink(mut self, sink: Arc) -> Self { + self.trace_sink = Some(sink); + self + } + + /// Whether commands write a trace. + /// + /// # Examples + /// + /// ``` + /// # use tinycomputer_desktop::Desktop; + /// assert!(!Desktop::new().is_tracing()); + /// ``` + #[must_use] + pub fn is_tracing(&self) -> bool { + self.trace_path.is_some() || self.trace_sink.is_some() + } + + /// Where commands write their trace, if anywhere. + /// + /// # Examples + /// + /// ``` + /// # use std::path::Path; + /// # use tinycomputer_desktop::Desktop; + /// let desktop = Desktop::new().with_trace("/tmp/run.jsonl", true); + /// assert_eq!(desktop.trace_path(), Some(Path::new("/tmp/run.jsonl"))); + /// ``` + #[must_use] + pub fn trace_path(&self) -> Option<&Path> { + self.trace_path.as_deref() + } + + /// Builds the engine context every command runs under. + pub(super) fn context(&self) -> Result { + let context = match &self.trace_sink { + Some(sink) => CommandContext::new_with_trace_sink( + self.session_id.clone(), + sink.clone(), + self.trace_strict, + true, + ), + None => CommandContext::new( + self.session_id.clone(), + self.trace_path.clone(), + self.trace_strict, + ), + }; + context.map(|context| context.with_headed(self.headed)) + } +} diff --git a/crates/tinycomputer/tests/public_api_tests.rs b/crates/tinycomputer/tests/public_api_tests.rs index c32b4d8b3..2a5ad2ad4 100644 --- a/crates/tinycomputer/tests/public_api_tests.rs +++ b/crates/tinycomputer/tests/public_api_tests.rs @@ -34,7 +34,7 @@ fn the_crate_re_exports_the_contract_rather_than_redefining_it() { #[test] fn the_shipped_contract_binds_to_itself() { assert!(is_compatible(CONTRACT_VERSION)); - assert_eq!(CONTRACT_VERSION, (2, 24)); + assert_eq!(CONTRACT_VERSION, (2, 25)); } #[test] diff --git a/docs/technical/specs/desktop-module-contract.md b/docs/technical/specs/desktop-module-contract.md index 9fcc0c6c2..f4fd406d4 100644 --- a/docs/technical/specs/desktop-module-contract.md +++ b/docs/technical/specs/desktop-module-contract.md @@ -94,7 +94,7 @@ Session identity (2.20): `SessionOptions` takes the optional `timezone`, `stealth`. A client that sends none gets the defaults; a 2.19 module ignores them. They apply to a browser the module launches, not one it attaches to. -Trace and report persistence (2.21): when module configuration sets +Trace and report persistence (2.25): when module configuration sets `trace_sink` to an object containing the unique callback `destination`, the module calls the confidential `ai.tinyhumans.tinycomputer.TraceSinkHost` interface. `Append` receives each complete sanitized agent-desktop trace event From 17b23e8c63dc23bc1238ddccf67d8bf05efa144b Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 18:28:50 +0000 Subject: [PATCH 23/48] test(trace_sink): split trace sink tests into focused modules The trace sink test file was broken up into callbacks, deadline, and lifecycle modules, leaving the original file to hold only the shared host fixtures. This keeps each test group small enough to navigate and lets the fixtures be reused without pulling in unrelated cases. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../trace_sink/trace_sink_tests.rs | 304 +----------------- .../trace_sink_tests/callbacks_tests.rs | 100 ++++++ .../trace_sink_tests/deadline_tests.rs | 81 +++++ .../trace_sink_tests/lifecycle_tests.rs | 128 ++++++++ 4 files changed, 315 insertions(+), 298 deletions(-) create mode 100644 crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/callbacks_tests.rs create mode 100644 crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/deadline_tests.rs create mode 100644 crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/lifecycle_tests.rs diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs index f7d6c83be..2db8162aa 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs @@ -1,3 +1,9 @@ +//! Shared host fixtures for trace-sink callback and lifecycle tests. + +mod callbacks_tests; +mod deadline_tests; +mod lifecycle_tests; + use super::*; use std::sync::Mutex; use tinycomputer_bus::agent::TaskReport; @@ -87,102 +93,6 @@ fn empty_task_report() -> Result { })) } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn callbacks_commit_events_artifacts_and_reports_over_the_bus() --> Result<(), Box> { - let (link, host, _host_connection) = connected_link(CompleteRecordingHost::default()).await?; - let deadline = TraceSinkDeadline::after(5_000)?; - link.append(&serde_json::json!({"event": "started"}), deadline, 4096) - .map_err(|error| error.to_string())?; - let artifact_deadline = TraceSinkDeadline::after(5_000)?; - let reference = link - .store_artifact( - TraceSinkArtifact { - kind: EngineArtifactKind::Screenshot, - name: "screen.png", - bytes: &[1, 2, 3], - deadline: artifact_deadline, - }, - TraceSinkArtifactLimits { - screenshot_bytes: 128, - screenshot_count: 2, - refmap_bytes: 64, - }, - ) - .map_err(|error| error.to_string())?; - link.write_report(TaskReportRecord { - task_id: "task-1".into(), - report: empty_task_report()?, - }) - .await?; - - assert_eq!(reference, "trace-artifact-1"); - assert_eq!( - host.events - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .as_slice(), - &[serde_json::json!({"event": "started"})] - ); - assert_eq!( - host.artifacts - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner)[0] - .bytes, - [1, 2, 3] - ); - assert_eq!( - host.reports - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner)[0] - .task_id, - "task-1" - ); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn rejected_host_callbacks_return_errors_to_the_caller() --> Result<(), Box> { - let host = CompleteRecordingHost::default(); - host.reject.store(true, Ordering::Release); - let (link, _, _host_connection) = connected_link(host).await?; - - assert!( - link.append( - &serde_json::json!({"event": "rejected"}), - TraceSinkDeadline::after(5_000)?, - 4096, - ) - .is_err() - ); - assert!( - link.store_artifact( - TraceSinkArtifact { - kind: EngineArtifactKind::RefMap, - name: "refs.json", - bytes: &[4, 5], - deadline: TraceSinkDeadline::after(5_000)?, - }, - TraceSinkArtifactLimits { - screenshot_bytes: 128, - screenshot_count: 2, - refmap_bytes: 64, - }, - ) - .is_err() - ); - assert!( - link.write_report(TaskReportRecord { - task_id: "task-1".into(), - report: empty_task_report()?, - }) - .await - .is_err() - ); - Ok(()) -} - #[tinybus::interface(name = "ai.tinyhumans.tinycomputer.TraceSinkHost")] impl RecordingHost { async fn append(&self, event: TraceEvent) -> TinyBusResult { @@ -205,208 +115,6 @@ impl RecordingHost { } } -#[test] -fn an_expired_deadline_is_never_renewed() { - let deadline = Instant::now() - .checked_sub(Duration::from_millis(1)) - .unwrap_or_else(Instant::now); - - assert!(remaining_timeout(deadline).is_none()); - assert!(remaining_millis(deadline).is_none()); -} - -#[test] -fn artifacts_over_the_transport_safe_limit_are_refused_before_queueing() { - let limit = tinycomputer_bus::trace_sink::MAX_TRACE_ARTIFACT_BYTES; - - assert!(validate_artifact_size(limit).is_ok()); - assert!(validate_artifact_size(limit + 1).is_err()); -} - -#[test] -fn callback_timeout_is_capped_without_extending_the_operation_deadline() { - let deadline = Instant::now() + CALL_TIMEOUT * 2; - assert!(remaining_timeout(deadline).is_some()); - let timeout = remaining_timeout(deadline).unwrap_or_default(); - - assert!(timeout <= CALL_TIMEOUT); - assert!(deadline > Instant::now()); -} - -#[test] -fn overlapping_callbacks_are_refused_until_the_outer_delivery_finishes() { - let active = AtomicBool::new(false); - - { - let outer = CallbackGuard::try_acquire(&active); - assert!(outer.is_some()); - let Some(_outer) = outer else { - return; - }; - assert!(CallbackGuard::try_acquire(&active).is_none()); - } - - assert!(CallbackGuard::try_acquire(&active).is_some()); -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn an_already_expired_queued_event_is_rejected_without_a_host_write() --> Result<(), Box> { - let bus = tinybus::transport::memory::MemoryBus::new(); - tinybus::broker::Broker::new().spawn(bus.clone()); - let host_connection = Connection::connect(bus.connect().await?).await?; - let host = RecordingHost::default(); - host_connection - .serve_at(trace_sink::OBJECT_PATH.try_into()?, host.clone()) - .await?; - host_connection.request_name(trace_sink::INTERFACE).await?; - let module = Connection::connect(bus.connect().await?).await?; - let link = TraceLink::new_for_bus_tests(module, tinybus::BusName::new(trace_sink::INTERFACE)?)?; - let (reply, result) = mpsc::sync_channel(1); - send( - &link.worker, - Command::Append { - record: serde_json::json!({"event": "expired"}), - deadline: Instant::now() - .checked_sub(Duration::from_millis(1)) - .unwrap_or_else(Instant::now), - byte_budget: 4096, - reply, - }, - )?; - let acknowledgment = - tokio::task::spawn_blocking(move || result.recv_timeout(Duration::from_secs(1))).await??; - - assert!(acknowledgment.is_err()); - assert!(host.0.lock().map_err(|error| error.to_string())?.is_empty()); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn expired_queued_event_is_rejected_without_a_late_host_write() --> Result<(), Box> { - let bus = tinybus::transport::memory::MemoryBus::new(); - tinybus::broker::Broker::new().spawn(bus.clone()); - let host_connection = Connection::connect(bus.connect().await?).await?; - let (started_tx, started_rx) = tokio::sync::oneshot::channel(); - let (release_tx, release_rx) = tokio::sync::oneshot::channel(); - let host = BlockingRecordingHost { - events: Arc::default(), - started: Arc::new(std::sync::Mutex::new(Some(started_tx))), - release: Arc::new(std::sync::Mutex::new(Some(release_rx))), - }; - host_connection - .serve_at(trace_sink::OBJECT_PATH.try_into()?, host.clone()) - .await?; - host_connection.request_name(trace_sink::INTERFACE).await?; - let module = Connection::connect(bus.connect().await?).await?; - let link = TraceLink::new_for_bus_tests(module, tinybus::BusName::new(trace_sink::INTERFACE)?)?; - let (first_reply, first_result) = mpsc::sync_channel(1); - send( - &link.worker, - Command::Append { - record: serde_json::json!({"event": "blocker"}), - deadline: Instant::now() + Duration::from_secs(10), - byte_budget: 4096, - reply: first_reply, - }, - )?; - tokio::time::timeout(Duration::from_secs(5), started_rx).await??; - - let (queued_reply, queued_result) = mpsc::sync_channel(1); - let queued_deadline = Instant::now() + Duration::from_millis(50); - send( - &link.worker, - Command::Append { - record: serde_json::json!({"event": "expired"}), - deadline: queued_deadline, - byte_budget: 4096, - reply: queued_reply, - }, - )?; - tokio::time::sleep_until( - tokio::time::Instant::from_std(queued_deadline) + Duration::from_millis(1), - ) - .await; - release_tx - .send(()) - .map_err(|()| TinyBusError::failed("test release receiver was dropped"))?; - - let first_ack = - tokio::task::spawn_blocking(move || first_result.recv_timeout(Duration::from_secs(5))) - .await??; - let queued_ack = - tokio::task::spawn_blocking(move || queued_result.recv_timeout(Duration::from_secs(5))) - .await??; - - assert!(first_ack.is_ok()); - assert!(queued_ack.is_err()); - assert_eq!( - host.events - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .as_slice(), - &[serde_json::json!({"event": "blocker"})], - "the expired queued event must not be written late" - ); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn shutdown_joins_an_active_host_callback_and_closes_admission() --> Result<(), Box> { - let bus = tinybus::transport::memory::MemoryBus::new(); - tinybus::broker::Broker::new().spawn(bus.clone()); - let host_connection = Connection::connect(bus.connect().await?).await?; - let (started_tx, started_rx) = tokio::sync::oneshot::channel(); - let (release_tx, release_rx) = tokio::sync::oneshot::channel(); - let host = BlockingRecordingHost { - events: Arc::default(), - started: Arc::new(std::sync::Mutex::new(Some(started_tx))), - release: Arc::new(std::sync::Mutex::new(Some(release_rx))), - }; - host_connection - .serve_at(trace_sink::OBJECT_PATH.try_into()?, host) - .await?; - host_connection.request_name(trace_sink::INTERFACE).await?; - let module = Connection::connect(bus.connect().await?).await?; - let link = TraceLink::new_for_bus_tests(module, tinybus::BusName::new(trace_sink::INTERFACE)?)?; - let callback_link = link.clone(); - let callback_deadline = TraceSinkDeadline::after(5_000)?; - let callback = tokio::task::spawn_blocking(move || { - callback_link.append( - &serde_json::json!({"event": "blocker"}), - callback_deadline, - 4096, - ) - }); - tokio::time::timeout(Duration::from_secs(5), started_rx).await??; - - let shutdown_link = link.clone(); - let mut shutdown = tokio::task::spawn_blocking(move || shutdown_link.shutdown()); - assert!( - tokio::time::timeout(Duration::from_millis(50), &mut shutdown) - .await - .is_err() - ); - release_tx - .send(()) - .map_err(|()| TinyBusError::failed("test release receiver was dropped"))?; - - shutdown.await??; - assert!(callback.await?.is_ok()); - assert!( - link.append( - &serde_json::json!({"event": "after-shutdown"}), - TraceSinkDeadline::after(5_000)?, - 4096, - ) - .is_err() - ); - Ok(()) -} - -#[derive(Clone)] struct BlockingRecordingHost { events: Arc>>, started: Arc>>>, diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/callbacks_tests.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/callbacks_tests.rs new file mode 100644 index 000000000..b1d7f13a1 --- /dev/null +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/callbacks_tests.rs @@ -0,0 +1,100 @@ +//! Tests for trace-sink host callback delivery and rejection. + +use super::*; + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn callbacks_commit_events_artifacts_and_reports_over_the_bus() +-> Result<(), Box> { + let (link, host, _host_connection) = connected_link(CompleteRecordingHost::default()).await?; + let deadline = TraceSinkDeadline::after(5_000)?; + link.append(&serde_json::json!({"event": "started"}), deadline, 4096) + .map_err(|error| error.to_string())?; + let artifact_deadline = TraceSinkDeadline::after(5_000)?; + let reference = link + .store_artifact( + TraceSinkArtifact { + kind: EngineArtifactKind::Screenshot, + name: "screen.png", + bytes: &[1, 2, 3], + deadline: artifact_deadline, + }, + TraceSinkArtifactLimits { + screenshot_bytes: 128, + screenshot_count: 2, + refmap_bytes: 64, + }, + ) + .map_err(|error| error.to_string())?; + link.write_report(TaskReportRecord { + task_id: "task-1".into(), + report: empty_task_report()?, + }) + .await?; + + assert_eq!(reference, "trace-artifact-1"); + assert_eq!( + host.events + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .as_slice(), + &[serde_json::json!({"event": "started"})] + ); + assert_eq!( + host.artifacts + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner)[0] + .bytes, + [1, 2, 3] + ); + assert_eq!( + host.reports + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner)[0] + .task_id, + "task-1" + ); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn rejected_host_callbacks_return_errors_to_the_caller() +-> Result<(), Box> { + let host = CompleteRecordingHost::default(); + host.reject.store(true, Ordering::Release); + let (link, _, _host_connection) = connected_link(host).await?; + + assert!( + link.append( + &serde_json::json!({"event": "rejected"}), + TraceSinkDeadline::after(5_000)?, + 4096, + ) + .is_err() + ); + assert!( + link.store_artifact( + TraceSinkArtifact { + kind: EngineArtifactKind::RefMap, + name: "refs.json", + bytes: &[4, 5], + deadline: TraceSinkDeadline::after(5_000)?, + }, + TraceSinkArtifactLimits { + screenshot_bytes: 128, + screenshot_count: 2, + refmap_bytes: 64, + }, + ) + .is_err() + ); + assert!( + link.write_report(TaskReportRecord { + task_id: "task-1".into(), + report: empty_task_report()?, + }) + .await + .is_err() + ); + Ok(()) +} + diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/deadline_tests.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/deadline_tests.rs new file mode 100644 index 000000000..a4cbd0da2 --- /dev/null +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/deadline_tests.rs @@ -0,0 +1,81 @@ +//! Tests for callback deadlines and expired queue entries. + +use super::*; + +#[test] +fn an_expired_deadline_is_never_renewed() { + let deadline = Instant::now() + .checked_sub(Duration::from_millis(1)) + .unwrap_or_else(Instant::now); + + assert!(remaining_timeout(deadline).is_none()); + assert!(remaining_millis(deadline).is_none()); +} + +#[test] +fn artifacts_over_the_transport_safe_limit_are_refused_before_queueing() { + let limit = tinycomputer_bus::trace_sink::MAX_TRACE_ARTIFACT_BYTES; + + assert!(validate_artifact_size(limit).is_ok()); + assert!(validate_artifact_size(limit + 1).is_err()); +} + +#[test] +fn callback_timeout_is_capped_without_extending_the_operation_deadline() { + let deadline = Instant::now() + CALL_TIMEOUT * 2; + assert!(remaining_timeout(deadline).is_some()); + let timeout = remaining_timeout(deadline).unwrap_or_default(); + + assert!(timeout <= CALL_TIMEOUT); + assert!(deadline > Instant::now()); +} + +#[test] +fn overlapping_callbacks_are_refused_until_the_outer_delivery_finishes() { + let active = AtomicBool::new(false); + + { + let outer = CallbackGuard::try_acquire(&active); + assert!(outer.is_some()); + let Some(_outer) = outer else { + return; + }; + assert!(CallbackGuard::try_acquire(&active).is_none()); + } + + assert!(CallbackGuard::try_acquire(&active).is_some()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn an_already_expired_queued_event_is_rejected_without_a_host_write() +-> Result<(), Box> { + let bus = tinybus::transport::memory::MemoryBus::new(); + tinybus::broker::Broker::new().spawn(bus.clone()); + let host_connection = Connection::connect(bus.connect().await?).await?; + let host = RecordingHost::default(); + host_connection + .serve_at(trace_sink::OBJECT_PATH.try_into()?, host.clone()) + .await?; + host_connection.request_name(trace_sink::INTERFACE).await?; + let module = Connection::connect(bus.connect().await?).await?; + let link = TraceLink::new_for_bus_tests(module, tinybus::BusName::new(trace_sink::INTERFACE)?)?; + let (reply, result) = mpsc::sync_channel(1); + send( + &link.worker, + Command::Append { + record: serde_json::json!({"event": "expired"}), + deadline: Instant::now() + .checked_sub(Duration::from_millis(1)) + .unwrap_or_else(Instant::now), + byte_budget: 4096, + reply, + }, + )?; + let acknowledgment = + tokio::task::spawn_blocking(move || result.recv_timeout(Duration::from_secs(1))).await??; + + assert!(acknowledgment.is_err()); + assert!(host.0.lock().map_err(|error| error.to_string())?.is_empty()); + Ok(()) +} + diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/lifecycle_tests.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/lifecycle_tests.rs new file mode 100644 index 000000000..fc3516a80 --- /dev/null +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/lifecycle_tests.rs @@ -0,0 +1,128 @@ +//! Tests for queued callback delivery and trace-sink shutdown. + +use super::*; + +async fn expired_queued_event_is_rejected_without_a_late_host_write() +-> Result<(), Box> { + let bus = tinybus::transport::memory::MemoryBus::new(); + tinybus::broker::Broker::new().spawn(bus.clone()); + let host_connection = Connection::connect(bus.connect().await?).await?; + let (started_tx, started_rx) = tokio::sync::oneshot::channel(); + let (release_tx, release_rx) = tokio::sync::oneshot::channel(); + let host = BlockingRecordingHost { + events: Arc::default(), + started: Arc::new(std::sync::Mutex::new(Some(started_tx))), + release: Arc::new(std::sync::Mutex::new(Some(release_rx))), + }; + host_connection + .serve_at(trace_sink::OBJECT_PATH.try_into()?, host.clone()) + .await?; + host_connection.request_name(trace_sink::INTERFACE).await?; + let module = Connection::connect(bus.connect().await?).await?; + let link = TraceLink::new_for_bus_tests(module, tinybus::BusName::new(trace_sink::INTERFACE)?)?; + let (first_reply, first_result) = mpsc::sync_channel(1); + send( + &link.worker, + Command::Append { + record: serde_json::json!({"event": "blocker"}), + deadline: Instant::now() + Duration::from_secs(10), + byte_budget: 4096, + reply: first_reply, + }, + )?; + tokio::time::timeout(Duration::from_secs(5), started_rx).await??; + + let (queued_reply, queued_result) = mpsc::sync_channel(1); + let queued_deadline = Instant::now() + Duration::from_millis(50); + send( + &link.worker, + Command::Append { + record: serde_json::json!({"event": "expired"}), + deadline: queued_deadline, + byte_budget: 4096, + reply: queued_reply, + }, + )?; + tokio::time::sleep_until( + tokio::time::Instant::from_std(queued_deadline) + Duration::from_millis(1), + ) + .await; + release_tx + .send(()) + .map_err(|()| TinyBusError::failed("test release receiver was dropped"))?; + + let first_ack = + tokio::task::spawn_blocking(move || first_result.recv_timeout(Duration::from_secs(5))) + .await??; + let queued_ack = + tokio::task::spawn_blocking(move || queued_result.recv_timeout(Duration::from_secs(5))) + .await??; + + assert!(first_ack.is_ok()); + assert!(queued_ack.is_err()); + assert_eq!( + host.events + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .as_slice(), + &[serde_json::json!({"event": "blocker"})], + "the expired queued event must not be written late" + ); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn shutdown_joins_an_active_host_callback_and_closes_admission() +-> Result<(), Box> { + let bus = tinybus::transport::memory::MemoryBus::new(); + tinybus::broker::Broker::new().spawn(bus.clone()); + let host_connection = Connection::connect(bus.connect().await?).await?; + let (started_tx, started_rx) = tokio::sync::oneshot::channel(); + let (release_tx, release_rx) = tokio::sync::oneshot::channel(); + let host = BlockingRecordingHost { + events: Arc::default(), + started: Arc::new(std::sync::Mutex::new(Some(started_tx))), + release: Arc::new(std::sync::Mutex::new(Some(release_rx))), + }; + host_connection + .serve_at(trace_sink::OBJECT_PATH.try_into()?, host) + .await?; + host_connection.request_name(trace_sink::INTERFACE).await?; + let module = Connection::connect(bus.connect().await?).await?; + let link = TraceLink::new_for_bus_tests(module, tinybus::BusName::new(trace_sink::INTERFACE)?)?; + let callback_link = link.clone(); + let callback_deadline = TraceSinkDeadline::after(5_000)?; + let callback = tokio::task::spawn_blocking(move || { + callback_link.append( + &serde_json::json!({"event": "blocker"}), + callback_deadline, + 4096, + ) + }); + tokio::time::timeout(Duration::from_secs(5), started_rx).await??; + + let shutdown_link = link.clone(); + let mut shutdown = tokio::task::spawn_blocking(move || shutdown_link.shutdown()); + assert!( + tokio::time::timeout(Duration::from_millis(50), &mut shutdown) + .await + .is_err() + ); + release_tx + .send(()) + .map_err(|()| TinyBusError::failed("test release receiver was dropped"))?; + + shutdown.await??; + assert!(callback.await?.is_ok()); + assert!( + link.append( + &serde_json::json!({"event": "after-shutdown"}), + TraceSinkDeadline::after(5_000)?, + 4096, + ) + .is_err() + ); + Ok(()) +} + +#[derive(Clone)] From 2baf0c840ae0da699d8eddaa55426b5bb945bbdd Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 18:29:19 +0000 Subject: [PATCH 24/48] test(trace_sink): add explicit paths for test submodules The trace-sink test module declarations now specify their file paths explicitly so the submodules resolve correctly regardless of the directory layout. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/tinybus_module/trace_sink/trace_sink_tests.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs index 2db8162aa..77b184926 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs @@ -1,7 +1,10 @@ //! Shared host fixtures for trace-sink callback and lifecycle tests. +#[path = "trace_sink_tests/callbacks_tests.rs"] mod callbacks_tests; +#[path = "trace_sink_tests/deadline_tests.rs"] mod deadline_tests; +#[path = "trace_sink_tests/lifecycle_tests.rs"] mod lifecycle_tests; use super::*; From 6e58d2dde03fb57f9470ccea5f20956a167a32fa Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 18:30:05 +0000 Subject: [PATCH 25/48] test(trace_sink): derive Clone on BlockingRecordingHost The blocking test host now derives Clone so it can be reused across scenarios, and stray trailing blank lines and a misplaced derive were removed from the split test modules. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/tinybus_module/trace_sink/trace_sink_tests.rs | 1 + .../trace_sink/trace_sink_tests/callbacks_tests.rs | 1 - .../trace_sink/trace_sink_tests/deadline_tests.rs | 1 - .../trace_sink/trace_sink_tests/lifecycle_tests.rs | 2 -- 4 files changed, 1 insertion(+), 4 deletions(-) diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs index 77b184926..64e3322fd 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs @@ -118,6 +118,7 @@ impl RecordingHost { } } +#[derive(Clone)] struct BlockingRecordingHost { events: Arc>>, started: Arc>>>, diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/callbacks_tests.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/callbacks_tests.rs index b1d7f13a1..d3de85478 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/callbacks_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/callbacks_tests.rs @@ -97,4 +97,3 @@ async fn rejected_host_callbacks_return_errors_to_the_caller() ); Ok(()) } - diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/deadline_tests.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/deadline_tests.rs index a4cbd0da2..ee05557a2 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/deadline_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/deadline_tests.rs @@ -78,4 +78,3 @@ async fn an_already_expired_queued_event_is_rejected_without_a_host_write() assert!(host.0.lock().map_err(|error| error.to_string())?.is_empty()); Ok(()) } - diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/lifecycle_tests.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/lifecycle_tests.rs index fc3516a80..1cfca9584 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/lifecycle_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/lifecycle_tests.rs @@ -124,5 +124,3 @@ async fn shutdown_joins_an_active_host_callback_and_closes_admission() ); Ok(()) } - -#[derive(Clone)] From 36a20ec6cf5ed4cfe41c894727c8199795254817 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 18:30:40 +0000 Subject: [PATCH 26/48] docs(tinycomputer-bus): correct TraceSinkHost contract version to 2.25 The README credited the optional confidential TraceSinkHost callback to contract 2.21, but it actually landed in 2.25, so the version reference is updated to match. The expired-event lifecycle test now runs on a multi-thread runtime with two workers to match the conditions it exercises. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-bus/README.md | 2 +- .../trace_sink/trace_sink_tests/lifecycle_tests.rs | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/tinycomputer-bus/README.md b/crates/tinycomputer-bus/README.md index 92b4d0262..7e386a5eb 100644 --- a/crates/tinycomputer-bus/README.md +++ b/crates/tinycomputer-bus/README.md @@ -169,7 +169,7 @@ See the [Globe contract](src/accessibility/README.md). Reliable Globe callers require a released 2.12-compatible artifact with a verified digest. -Contract 2.21 adds the optional confidential `TraceSinkHost` callback. A host +Contract 2.25 adds the optional confidential `TraceSinkHost` callback. A host prepares one exact callback binding per loaded module and supplies its unique destination as `trace_sink.destination`. TinyComputer sends sanitized desktop trace events, trace artifacts, and requested task reports to `Append`, `StoreArtifact`, and diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/lifecycle_tests.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/lifecycle_tests.rs index 1cfca9584..107295c1e 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/lifecycle_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/lifecycle_tests.rs @@ -2,6 +2,7 @@ use super::*; +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn expired_queued_event_is_rejected_without_a_late_host_write() -> Result<(), Box> { let bus = tinybus::transport::memory::MemoryBus::new(); From d7df7dbab89097fdab718add52b2f9904c88336a Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 18:49:42 +0000 Subject: [PATCH 27/48] test(desktop): cover surface name wire spelling in replies Add tests asserting that surface names in both success data and error details are converted to the contract's snake_case wire spelling, so hyphenated names cannot leak through the reply envelope unnoticed. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/desktop/desktop_tests/reply_tests.rs | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/crates/tinycomputer-desktop/src/desktop/desktop_tests/reply_tests.rs b/crates/tinycomputer-desktop/src/desktop/desktop_tests/reply_tests.rs index a1dad25a2..339967b18 100644 --- a/crates/tinycomputer-desktop/src/desktop/desktop_tests/reply_tests.rs +++ b/crates/tinycomputer-desktop/src/desktop/desktop_tests/reply_tests.rs @@ -29,6 +29,52 @@ fn a_successful_result_becomes_a_successful_envelope() { assert!(envelope.error.is_none()); } +#[test] +fn surface_names_in_success_data_use_the_contract_wire_spelling() { + let envelope = reply::envelope( + "list-surfaces", + Ok(json!({ + "surfaces": [{ + "type": "system-tray", + "unclassified": ["notification-center"] + }] + })), + ); + + assert_eq!( + envelope.data, + Some(json!({ + "surfaces": [{ + "type": "system_tray", + "unclassified": ["notification_center"] + }] + })) + ); +} + +#[test] +fn supported_surface_names_in_error_details_use_the_contract_wire_spelling() { + let error = AppError::Adapter( + AdapterError::new(ErrorCode::PlatformNotSupported, "surface not supported") + .with_details(json!({ + "requested_surface": "quick-settings", + "supported_surfaces": ["system-tray", "notification-center"] + })), + ); + + let payload = reply::envelope("snapshot", Err(error)) + .error + .expect("a failed envelope carries an error"); + + assert_eq!( + payload.details, + Some(json!({ + "requested_surface": "quick_settings", + "supported_surfaces": ["system_tray", "notification_center"] + })) + ); +} + #[test] fn an_adapter_error_keeps_its_structured_detail_through_the_envelope() { let error = AppError::Adapter( From b46a87dff785aea24df5e33043d779c2ed2b064e Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 18:50:06 +0000 Subject: [PATCH 28/48] fix(desktop): normalize surface names to contract spelling in replies Surface identifiers produced by the engine were emitted with hyphenated aliases, which did not match the snake_case names the contract expects. Reply envelopes and error details now rewrite those fields recursively so clients see the wire spelling consistently. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/desktop/desktop_tests/reply_tests.rs | 7 ++- .../tinycomputer-desktop/src/desktop/reply.rs | 60 ++++++++++++++++++- 2 files changed, 62 insertions(+), 5 deletions(-) diff --git a/crates/tinycomputer-desktop/src/desktop/desktop_tests/reply_tests.rs b/crates/tinycomputer-desktop/src/desktop/desktop_tests/reply_tests.rs index 339967b18..50dd6496f 100644 --- a/crates/tinycomputer-desktop/src/desktop/desktop_tests/reply_tests.rs +++ b/crates/tinycomputer-desktop/src/desktop/desktop_tests/reply_tests.rs @@ -55,11 +55,12 @@ fn surface_names_in_success_data_use_the_contract_wire_spelling() { #[test] fn supported_surface_names_in_error_details_use_the_contract_wire_spelling() { let error = AppError::Adapter( - AdapterError::new(ErrorCode::PlatformNotSupported, "surface not supported") - .with_details(json!({ + AdapterError::new(ErrorCode::PlatformNotSupported, "surface not supported").with_details( + json!({ "requested_surface": "quick-settings", "supported_surfaces": ["system-tray", "notification-center"] - })), + }), + ), ); let payload = reply::envelope("snapshot", Err(error)) diff --git a/crates/tinycomputer-desktop/src/desktop/reply.rs b/crates/tinycomputer-desktop/src/desktop/reply.rs index 88f7d90cb..cdbd9c783 100644 --- a/crates/tinycomputer-desktop/src/desktop/reply.rs +++ b/crates/tinycomputer-desktop/src/desktop/reply.rs @@ -17,7 +17,10 @@ use tinycomputer_bus::{ /// Wraps `result` in the envelope, naming it `command`. pub(super) fn envelope(command: &str, result: Result) -> DesktopResponse { match result { - Ok(data) => DesktopResponse::ok(command, data), + Ok(mut data) => { + normalize_surface_fields(&mut data); + DesktopResponse::ok(command, data) + } Err(error) => DesktopResponse::err(command, desktop_error(&error)), } } @@ -28,7 +31,10 @@ pub(super) fn envelope(command: &str, result: Result) -> Deskto /// choosing the recovery strategy for a retry-safe code — so this reuses it /// rather than reimplementing the mapping and drifting from it. fn desktop_error(error: &AppError) -> DesktopError { - let payload = ErrorPayload::from_app_error(error); + let mut payload = ErrorPayload::from_app_error(error); + if let Some(details) = &mut payload.details { + normalize_surface_fields(details); + } DesktopError { code: payload.code, @@ -46,6 +52,56 @@ fn desktop_error(error: &AppError) -> DesktopError { } } +/// Restores the contract's snake_case spellings where the engine uses +/// `SnapshotSurface::as_str()` values in structured output. +fn normalize_surface_fields(value: &mut Value) { + match value { + Value::Array(values) => { + for value in values { + normalize_surface_fields(value); + } + } + Value::Object(fields) => { + for (field, value) in fields { + match field.as_str() { + "surface" | "requested_surface" | "type" => { + if let Some(surface) = value.as_str().and_then(contract_surface_name) { + *value = Value::String(surface.to_owned()); + } + } + "supported_surfaces" | "unclassified" => { + if let Value::Array(surfaces) = value { + for value in surfaces { + if let Some(surface) = + value.as_str().and_then(contract_surface_name) + { + *value = Value::String(surface.to_owned()); + } + } + } + } + _ => normalize_surface_fields(value), + } + } + } + _ => {} + } +} + +/// Returns the contract spelling for an engine surface alias. +fn contract_surface_name(surface: &str) -> Option<&'static str> { + match surface { + "system-tray" => Some("system_tray"), + "quick-settings" => Some("quick_settings"), + "notification-center" => Some("notification_center"), + "menu-bar-extras" => Some("menu_bar_extras"), + "system-tray-overflow" => Some("system_tray_overflow"), + "start-menu" => Some("start_menu"), + "action-center" => Some("action_center"), + _ => None, + } +} + /// Converts the engine's delivery semantics into the contract's pair. fn delivery(semantics: DeliverySemantics) -> Delivery { let disposition = match semantics { From 51f3b148fab1079c7ab3f87eeec8b1f2d155b879 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 18:50:55 +0000 Subject: [PATCH 29/48] docs(desktop): format snake_case in reply doc comment Wrap the snake_case mention in the normalize_surface_fields doc comment in backticks so it renders as code, matching the surrounding style. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-desktop/src/desktop/reply.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/tinycomputer-desktop/src/desktop/reply.rs b/crates/tinycomputer-desktop/src/desktop/reply.rs index cdbd9c783..d8864acfe 100644 --- a/crates/tinycomputer-desktop/src/desktop/reply.rs +++ b/crates/tinycomputer-desktop/src/desktop/reply.rs @@ -52,7 +52,7 @@ fn desktop_error(error: &AppError) -> DesktopError { } } -/// Restores the contract's snake_case spellings where the engine uses +/// Restores the contract's `snake_case` spellings where the engine uses /// `SnapshotSurface::as_str()` values in structured output. fn normalize_surface_fields(value: &mut Value) { match value { From 35f2238bf3658a0f491160271c61fbec85ba55ba Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 19:28:54 +0000 Subject: [PATCH 30/48] docs(tinycomputer-bus): document trace sink callbacks and contract version Update the crate docs to describe the TraceSinkHost callbacks and the base64 dependency they add, and note that trace read/export members remain absent. Bump the documented CONTRACT_VERSION to 2.25 and adjust the compatibility examples accordingly. Add module doc comments to the trace sink test files. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-bus/src/lib.rs | 22 +++++++++---------- .../src/desktop/trace_sink_tests.rs | 2 ++ .../trace_sink/trace_sink_tests.rs | 2 ++ docs/crates/tinycomputer-bus/versioning.md | 11 +++++----- 4 files changed, 21 insertions(+), 16 deletions(-) diff --git a/crates/tinycomputer-bus/src/lib.rs b/crates/tinycomputer-bus/src/lib.rs index c5086810e..b08ecfb5b 100644 --- a/crates/tinycomputer-bus/src/lib.rs +++ b/crates/tinycomputer-bus/src/lib.rs @@ -83,17 +83,17 @@ //! That is also a structural necessity, not only a preference: `tinybus` is //! vendored as a submodule whose manifest inherits fields from its own nested //! `[workspace.package]`. A crate that every workspace member can depend on has -//! to stay transport-free, and staying transport-free is what keeps this crate -//! down to three pure-Rust dependencies: `thiserror`, `serde`, and -//! `serde_json`. -//! -//! **No session, trace, or skills members.** The engine also offers session -//! lifecycle, trace read and export, and a bundled documentation loader. They -//! are process-lifecycle concerns of a CLI rather than of a loaded module: a -//! module is configured once, at load, and its session identity comes from that -//! configuration instead of from a member a caller has to remember to invoke. -//! They are candidates for a later minor version of this contract, which is -//! why the bind rule in [`version`] treats an added member as compatible. +//! to stay transport-free. Its four pure-Rust dependencies are `thiserror`, +//! `serde`, `serde_json`, and `base64`; the last encodes binary trace artifacts +//! in the `TraceSinkHost` callback payloads. +//! +//! **No session, trace read/export, or skills members.** The contract includes +//! `TraceSinkHost` callbacks so a module can send trace events, artifacts, and +//! requested reports to host-owned storage. It does not expose members to read +//! or export traces from the engine. Session lifecycle and the bundled +//! documentation loader are also absent: they are process-lifecycle concerns +//! of a CLI rather than of a loaded module, whose session identity comes from +//! its load configuration. //! //! # This crate sits underneath the implementation, not beside it //! diff --git a/crates/tinycomputer-desktop/src/desktop/trace_sink_tests.rs b/crates/tinycomputer-desktop/src/desktop/trace_sink_tests.rs index 11fea0d2b..f89203a06 100644 --- a/crates/tinycomputer-desktop/src/desktop/trace_sink_tests.rs +++ b/crates/tinycomputer-desktop/src/desktop/trace_sink_tests.rs @@ -1,3 +1,5 @@ +//! Tests for desktop trace-sink configuration and callback behavior. + use super::*; use crate::{ TraceSink, TraceSinkArtifact, TraceSinkArtifactLimits, TraceSinkDeadline, TraceSinkError, diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs index 64e3322fd..67d8b2e77 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs @@ -7,6 +7,8 @@ mod deadline_tests; #[path = "trace_sink_tests/lifecycle_tests.rs"] mod lifecycle_tests; +//! Tests for the TinyBus trace-sink callback transport and payloads. + use super::*; use std::sync::Mutex; use tinycomputer_bus::agent::TaskReport; diff --git a/docs/crates/tinycomputer-bus/versioning.md b/docs/crates/tinycomputer-bus/versioning.md index c97ac3632..632fea2a4 100644 --- a/docs/crates/tinycomputer-bus/versioning.md +++ b/docs/crates/tinycomputer-bus/versioning.md @@ -9,7 +9,7 @@ code, so this page exists mostly to keep them apart. ## `CONTRACT_VERSION`: does this host understand this module ```rust,ignore -pub const CONTRACT_VERSION: (u32, u32) = (2, 21); +pub const CONTRACT_VERSION: (u32, u32) = (2, 25); ``` This describes the *vocabulary*: the member set and the payload shapes, @@ -48,13 +48,14 @@ Two conditions, both necessary: built against `(2, 21)` expects at least the members and fields that existed at `(2, 21)`. A module reporting `(2, 11)` might be missing one of them, so it is rejected. A module reporting `(2, 20)` has everything the - host expected before `TraceSinkHost` was added, so it is rejected by a - 2.21 host. + host expected before the `TraceSinkHost` callbacks were added, so it is + rejected by a 2.25 host. ```rust,ignore -assert!(is_compatible(CONTRACT_VERSION)); // (2, 21), the exact version this crate ships -assert!(is_compatible((2, 21))); // a newer, still-compatible module +assert!(is_compatible(CONTRACT_VERSION)); // (2, 25), the exact version this crate ships +assert!(is_compatible((2, 25))); // a newer, still-compatible module assert!(!is_compatible((2, 11))); // an older module, missing something +assert!(!is_compatible((2, 24))); // predates the required TraceSinkHost callbacks assert!(!is_compatible((1, 10))); // a different major, all bets off ``` From 3257f9138ef79e3c0cfaa1ca198d7e0f98d64563 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 19:29:08 +0000 Subject: [PATCH 31/48] docs(tinybus_module): add trace sink README Document the trace sink module so its purpose and usage are discoverable alongside the code. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/tinybus_module/trace_sink/README.md | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 crates/tinycomputer/src/tinybus_module/trace_sink/README.md diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/README.md b/crates/tinycomputer/src/tinybus_module/trace_sink/README.md new file mode 100644 index 000000000..999277740 --- /dev/null +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/README.md @@ -0,0 +1,41 @@ +# Trace sink adapter + +This module connects the desktop engine's synchronous trace-sink interface to +the host's asynchronous TinyBus `TraceSinkHost` callbacks. `TraceLink` owns a +single named worker thread and exposes the engine adapter in +`engine_adapter.rs`; the parent module constructs it only when configuration +contains the unique callback destination prepared by the host. + +## Callback flow + +`append` and `store_artifact` copy the callback data into a bounded, one-slot +queue. The worker serializes accepted calls and performs the TinyBus request +using the runtime handle captured when `TraceLink` was created. A synchronous +engine callback waits only until its supplied deadline, capped by +`CALL_TIMEOUT`. Events carry their remaining deadline and byte budget; artifact +requests also carry their size limits. Artifacts larger than the bus contract's +8 MiB decoded limit are rejected before queueing. Production callbacks use +confidential TinyBus calls so trace contents and artifacts are not exposed as +ordinary module traffic. + +Task reports use `write_report` on the async dispatch path and are sent through +the same host interface. The callback-active guard rejects overlapping calls +across both paths, providing bounded backpressure and preventing recursive +host callbacks from waiting on one another. It detects overlap, not causal +re-entrancy: the host must not call back into this module and wait for another +trace callback to finish. + +## Lifecycle and constraints + +Construction requires a Tokio multi-thread runtime because the worker drives +async bus calls while the engine may synchronously wait for their result. The +worker queue has capacity one; a full queue fails the engine callback promptly +instead of growing memory or blocking the caller. The bus proxy timeout uses +the remaining callback deadline, so an expired operation is not sent. + +`shutdown` closes the queue, joins the worker, and waits briefly for an +in-flight report callback before the service is torn down. `Drop` invokes the +same shutdown path as a best effort. A shutdown error is surfaced during +explicit service teardown; the destructor cannot report it. Tests under +`trace_sink_tests/` cover wire payloads, callback ordering and errors, deadlines, +and worker shutdown over the in-memory bus. From c6958b8a8a3509adb01cfb65bb9fe1091febc7ae Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 19:29:27 +0000 Subject: [PATCH 32/48] test(trace_sink): move module doc comment to top of test file The inner doc comment describing the trace-sink test coverage was placed after the module declarations, where it no longer documents the module, so it has been moved to the top of the file and expanded to mention deadlines and shutdown. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/tinybus_module/trace_sink/trace_sink_tests.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs index 67d8b2e77..1276b3236 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs @@ -1,4 +1,5 @@ //! Shared host fixtures for trace-sink callback and lifecycle tests. +//! The cases cover the TinyBus transport, payloads, deadlines, and shutdown. #[path = "trace_sink_tests/callbacks_tests.rs"] mod callbacks_tests; @@ -7,8 +8,6 @@ mod deadline_tests; #[path = "trace_sink_tests/lifecycle_tests.rs"] mod lifecycle_tests; -//! Tests for the TinyBus trace-sink callback transport and payloads. - use super::*; use std::sync::Mutex; use tinycomputer_bus::agent::TaskReport; From 046857739648af6e7916195160b6edd898cdd926 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 19:32:11 +0000 Subject: [PATCH 33/48] docs(tinycomputer-bus): correct version numbers in compatibility example The prose example used `(2, 21)` as the host version while the surrounding text and code sample refer to `(2, 25)`, so the numbers were updated to match. The newer-module assertion was also bumped from `(2, 25)` to `(2, 26)` so it no longer duplicates the exact shipped version. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- docs/crates/tinycomputer-bus/versioning.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/crates/tinycomputer-bus/versioning.md b/docs/crates/tinycomputer-bus/versioning.md index 632fea2a4..58b9ce0ba 100644 --- a/docs/crates/tinycomputer-bus/versioning.md +++ b/docs/crates/tinycomputer-bus/versioning.md @@ -45,15 +45,15 @@ Two conditions, both necessary: relies on changed shape or disappeared, so a mismatched major is refused outright, in either direction. 2. **The module must be at least as new, minor-wise, as the host.** A host - built against `(2, 21)` expects at least the members and fields that - existed at `(2, 21)`. A module reporting `(2, 11)` might be missing one of - them, so it is rejected. A module reporting `(2, 20)` has everything the + built against `(2, 25)` expects at least the members and fields that + existed at `(2, 25)`. A module reporting `(2, 11)` might be missing one of + them, so it is rejected. A module reporting `(2, 24)` has everything the host expected before the `TraceSinkHost` callbacks were added, so it is rejected by a 2.25 host. ```rust,ignore assert!(is_compatible(CONTRACT_VERSION)); // (2, 25), the exact version this crate ships -assert!(is_compatible((2, 25))); // a newer, still-compatible module +assert!(is_compatible((2, 26))); // a newer, still-compatible module assert!(!is_compatible((2, 11))); // an older module, missing something assert!(!is_compatible((2, 24))); // predates the required TraceSinkHost callbacks assert!(!is_compatible((1, 10))); // a different major, all bets off From c1bf82b19c098aa8bdee23a292ed04c8a18bb2fa Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 19:32:20 +0000 Subject: [PATCH 34/48] docs(trace_sink): format TinyBus as code in test module docs Wrap the TinyBus mention in the trace-sink test fixtures doc comment in backticks so it renders as code. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/tinybus_module/trace_sink/trace_sink_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs index 1276b3236..8297a2202 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs @@ -1,5 +1,5 @@ //! Shared host fixtures for trace-sink callback and lifecycle tests. -//! The cases cover the TinyBus transport, payloads, deadlines, and shutdown. +//! The cases cover the `TinyBus` transport, payloads, deadlines, and shutdown. #[path = "trace_sink_tests/callbacks_tests.rs"] mod callbacks_tests; From 52f6c6b42ca029b12056cd9de560b63316dbfb94 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 19:43:16 +0000 Subject: [PATCH 35/48] docs(tinycomputer-bus): clarify minor version compatibility example Reword the versioning example so the 2.24 module is described as predating the TraceSinkHost callbacks a 2.25 host expects, making it clearer why such a module is rejected. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- docs/crates/tinycomputer-bus/versioning.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/crates/tinycomputer-bus/versioning.md b/docs/crates/tinycomputer-bus/versioning.md index 58b9ce0ba..e3a556356 100644 --- a/docs/crates/tinycomputer-bus/versioning.md +++ b/docs/crates/tinycomputer-bus/versioning.md @@ -47,9 +47,9 @@ Two conditions, both necessary: 2. **The module must be at least as new, minor-wise, as the host.** A host built against `(2, 25)` expects at least the members and fields that existed at `(2, 25)`. A module reporting `(2, 11)` might be missing one of - them, so it is rejected. A module reporting `(2, 24)` has everything the - host expected before the `TraceSinkHost` callbacks were added, so it is - rejected by a 2.25 host. + them, so it is rejected. A module reporting `(2, 24)` predates the + `TraceSinkHost` callbacks that a 2.25 host expects, so a 2.25 host + rejects it too. ```rust,ignore assert!(is_compatible(CONTRACT_VERSION)); // (2, 25), the exact version this crate ships From fcd0f86bb49d21183e7d9c9662a6037c5f65ef0b Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 20:18:11 +0000 Subject: [PATCH 36/48] test(trace_sink): make lifecycle timing assertions deterministic Replace the wall-clock sleeps in the trace sink lifecycle tests with state-based waits so they no longer depend on scheduler timing. The expired event test now queues an already-past deadline instead of sleeping, and the shutdown test polls the worker slot until it is taken before asserting that shutdown is still pending. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../trace_sink_tests/lifecycle_tests.rs | 21 +++++++++++-------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/lifecycle_tests.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/lifecycle_tests.rs index 107295c1e..96a703351 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/lifecycle_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/lifecycle_tests.rs @@ -34,7 +34,7 @@ async fn expired_queued_event_is_rejected_without_a_late_host_write() tokio::time::timeout(Duration::from_secs(5), started_rx).await??; let (queued_reply, queued_result) = mpsc::sync_channel(1); - let queued_deadline = Instant::now() + Duration::from_millis(50); + let queued_deadline = Instant::now() - Duration::from_millis(1); send( &link.worker, Command::Append { @@ -44,10 +44,6 @@ async fn expired_queued_event_is_rejected_without_a_late_host_write() reply: queued_reply, }, )?; - tokio::time::sleep_until( - tokio::time::Instant::from_std(queued_deadline) + Duration::from_millis(1), - ) - .await; release_tx .send(()) .map_err(|()| TinyBusError::failed("test release receiver was dropped"))?; @@ -103,11 +99,18 @@ async fn shutdown_joins_an_active_host_callback_and_closes_admission() tokio::time::timeout(Duration::from_secs(5), started_rx).await??; let shutdown_link = link.clone(); - let mut shutdown = tokio::task::spawn_blocking(move || shutdown_link.shutdown()); + let shutdown = tokio::task::spawn_blocking(move || shutdown_link.shutdown()); + while link + .worker + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .is_some() + { + tokio::task::yield_now().await; + } assert!( - tokio::time::timeout(Duration::from_millis(50), &mut shutdown) - .await - .is_err() + !shutdown.is_finished(), + "shutdown must wait for the active host callback" ); release_tx .send(()) From 2aade7221f70e37432e0fd192a0e9ebc514d489e Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 20:19:03 +0000 Subject: [PATCH 37/48] test(trace_sink): use checked_sub for past deadline Replace the subtraction that could panic on an instant near the clock's lower bound with checked_sub and an explicit expectation, so the lifecycle test fails with a clear message instead of an arithmetic overflow. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../trace_sink/trace_sink_tests/lifecycle_tests.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/lifecycle_tests.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/lifecycle_tests.rs index 96a703351..8ba10ece2 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/lifecycle_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/lifecycle_tests.rs @@ -34,7 +34,9 @@ async fn expired_queued_event_is_rejected_without_a_late_host_write() tokio::time::timeout(Duration::from_secs(5), started_rx).await??; let (queued_reply, queued_result) = mpsc::sync_channel(1); - let queued_deadline = Instant::now() - Duration::from_millis(1); + let queued_deadline = Instant::now() + .checked_sub(Duration::from_millis(1)) + .expect("an instant can represent a deadline one millisecond in the past"); send( &link.worker, Command::Append { From e96bb907b414af9db65b51cd4c46e6516065c26f Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 20:19:19 +0000 Subject: [PATCH 38/48] test(trace_sink): avoid panic when subtracting from instant Replace the expect on the checked_sub result with unwrap_or_else(Instant::now) so the lifecycle test no longer panics if the clock cannot represent a deadline one millisecond in the past. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../trace_sink/trace_sink_tests/lifecycle_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/lifecycle_tests.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/lifecycle_tests.rs index 8ba10ece2..5b46be51b 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/lifecycle_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/lifecycle_tests.rs @@ -36,7 +36,7 @@ async fn expired_queued_event_is_rejected_without_a_late_host_write() let (queued_reply, queued_result) = mpsc::sync_channel(1); let queued_deadline = Instant::now() .checked_sub(Duration::from_millis(1)) - .expect("an instant can represent a deadline one millisecond in the past"); + .unwrap_or_else(Instant::now); send( &link.worker, Command::Append { From 6c51548f62c683e8418a3926efd588bdcd8fa167 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 20:57:48 +0000 Subject: [PATCH 39/48] test(trace-sink): cover confidential report routing and full wire shape The wire-shape assertion now compares the whole serialized artifact instead of three fields, so extra or missing keys are caught. A new callback test checks that a configured service refuses to deliver a task report to an unattested host and surfaces TRACE_SINK_FAILED to the caller. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/trace_sink/trace_sink_tests.rs | 17 ++++-- .../trace_sink_tests/callbacks_tests.rs | 54 +++++++++++++++++++ 2 files changed, 68 insertions(+), 3 deletions(-) diff --git a/crates/tinycomputer-bus/src/trace_sink/trace_sink_tests.rs b/crates/tinycomputer-bus/src/trace_sink/trace_sink_tests.rs index 973da94ec..7d8431f64 100644 --- a/crates/tinycomputer-bus/src/trace_sink/trace_sink_tests.rs +++ b/crates/tinycomputer-bus/src/trace_sink/trace_sink_tests.rs @@ -26,9 +26,20 @@ fn sink_records_keep_their_wire_shapes() -> Result<(), serde_json::Error> { }, }; let wire = serde_json::to_value(artifact)?; - assert_eq!(wire["kind"], "ref_map"); - assert_eq!(wire["bytes"], "AQI="); - assert_eq!(wire["limits"]["refmap_bytes"], 20); + assert_eq!( + wire, + serde_json::json!({ + "kind": "ref_map", + "name": "snapshot.json", + "bytes": "AQI=", + "deadline_ms": 700, + "limits": { + "screenshot_bytes": 10, + "screenshot_count": 2, + "refmap_bytes": 20 + } + }) + ); let decoded: TraceArtifact = serde_json::from_value(wire)?; assert_eq!(decoded.bytes, [1, 2]); Ok(()) diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/callbacks_tests.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/callbacks_tests.rs index d3de85478..e4bf6d43d 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/callbacks_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/callbacks_tests.rs @@ -56,6 +56,60 @@ async fn callbacks_commit_events_artifacts_and_reports_over_the_bus() Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn configured_service_routes_task_reports_to_the_confidential_host_callback() +-> Result<(), Box> { + use tinycomputer_bus::agent::{AgentResponse, StartTaskRequest, TaskReport, TaskReportRequest, TaskView}; + use tinycomputer_bus::names; + + let bus = tinybus::transport::memory::MemoryBus::new(); + tinybus::broker::Broker::new().spawn(bus.clone()); + let host_connection = Connection::connect(bus.connect().await?).await?; + let host = CompleteRecordingHost::default(); + host_connection + .serve_at(trace_sink::OBJECT_PATH.try_into()?, host.clone()) + .await?; + host_connection.request_name(trace_sink::INTERFACE).await?; + let module_connection = Connection::connect(bus.connect().await?).await?; + let config = serde_json::json!({ + "trace_sink": {"destination": host_connection.unique_name().as_str()} + }); + let service = crate::tinybus_module::DesktopService::from_config_with_connection( + &config, + &module_connection, + )?; + + let started: AgentResponse = serde_json::from_value( + service + .call( + &names::methods::START_TASK.try_into()?, + (StartTaskRequest::new(serde_json::from_value(serde_json::json!({ + "flow": {"app": "Mail", "steps": ["start a new message"]} + }))?),), + ) + .await?, + )?; + let task_id = started.data.ok_or("start task returned no view")?.id; + let report: AgentResponse = serde_json::from_value( + service + .call( + &names::methods::TASK_REPORT.try_into()?, + (TaskReportRequest::new(task_id),), + ) + .await?, + )?; + + assert_eq!(report.error.as_ref().map(|error| error.code.as_str()), Some("TRACE_SINK_FAILED")); + assert!( + host.reports + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .is_empty(), + "the unattested test module must not deliver a confidential report" + ); + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn rejected_host_callbacks_return_errors_to_the_caller() -> Result<(), Box> { From 22858bf00df1ae76dd84958fc3ed3c91f7805bdd Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 20:58:21 +0000 Subject: [PATCH 40/48] test(trace_sink): adapt callback test to updated bus and task id apis Update the confidential host callback test to use the tinybus Interface trait for unique_name and to construct TaskId explicitly when building the task report request, matching the current bus and agent APIs. Also reformat the start task request and error assertion for readability. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../trace_sink_tests/callbacks_tests.rs | 25 +++++++++++++------ 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/callbacks_tests.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/callbacks_tests.rs index e4bf6d43d..650436762 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/callbacks_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/callbacks_tests.rs @@ -59,7 +59,10 @@ async fn callbacks_commit_events_artifacts_and_reports_over_the_bus() #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn configured_service_routes_task_reports_to_the_confidential_host_callback() -> Result<(), Box> { - use tinycomputer_bus::agent::{AgentResponse, StartTaskRequest, TaskReport, TaskReportRequest, TaskView}; + use tinybus::Interface; + use tinycomputer_bus::agent::{ + AgentResponse, StartTaskRequest, TaskId, TaskReport, TaskReportRequest, TaskView, + }; use tinycomputer_bus::names; let bus = tinybus::transport::memory::MemoryBus::new(); @@ -71,8 +74,11 @@ async fn configured_service_routes_task_reports_to_the_confidential_host_callbac .await?; host_connection.request_name(trace_sink::INTERFACE).await?; let module_connection = Connection::connect(bus.connect().await?).await?; + let host_name = host_connection + .unique_name() + .ok_or("host connection has no unique name")?; let config = serde_json::json!({ - "trace_sink": {"destination": host_connection.unique_name().as_str()} + "trace_sink": {"destination": host_name.as_str()} }); let service = crate::tinybus_module::DesktopService::from_config_with_connection( &config, @@ -83,9 +89,11 @@ async fn configured_service_routes_task_reports_to_the_confidential_host_callbac service .call( &names::methods::START_TASK.try_into()?, - (StartTaskRequest::new(serde_json::from_value(serde_json::json!({ - "flow": {"app": "Mail", "steps": ["start a new message"]} - }))?),), + (serde_json::from_value::( + serde_json::json!({ + "flow": {"app": "Mail", "steps": ["start a new message"]} + }), + )?,), ) .await?, )?; @@ -94,12 +102,15 @@ async fn configured_service_routes_task_reports_to_the_confidential_host_callbac service .call( &names::methods::TASK_REPORT.try_into()?, - (TaskReportRequest::new(task_id),), + (TaskReportRequest::new(TaskId::new(task_id.to_string())),), ) .await?, )?; - assert_eq!(report.error.as_ref().map(|error| error.code.as_str()), Some("TRACE_SINK_FAILED")); + assert_eq!( + report.error.as_ref().map(|error| error.code.as_str()), + Some("TRACE_SINK_FAILED") + ); assert!( host.reports .lock() From ee8586728689495383f421ad72ad9887b6581aa8 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 20:58:40 +0000 Subject: [PATCH 41/48] test(trace_sink): wrap callback call args in json arrays The callback tests now pass their request payloads as single-element JSON arrays instead of Rust tuples, matching the array-shaped arguments the service call expects. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../trace_sink/trace_sink_tests/callbacks_tests.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/callbacks_tests.rs b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/callbacks_tests.rs index 650436762..79444439f 100644 --- a/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/callbacks_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/callbacks_tests.rs @@ -89,11 +89,11 @@ async fn configured_service_routes_task_reports_to_the_confidential_host_callbac service .call( &names::methods::START_TASK.try_into()?, - (serde_json::from_value::( + serde_json::json!([serde_json::from_value::( serde_json::json!({ "flow": {"app": "Mail", "steps": ["start a new message"]} }), - )?,), + )?]), ) .await?, )?; @@ -102,7 +102,7 @@ async fn configured_service_routes_task_reports_to_the_confidential_host_callbac service .call( &names::methods::TASK_REPORT.try_into()?, - (TaskReportRequest::new(TaskId::new(task_id.to_string())),), + serde_json::json!([TaskReportRequest::new(TaskId::new(task_id.to_string()))]), ) .await?, )?; From c4c66467581655f69b9fab1120943f6576c57360 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 22:05:55 +0000 Subject: [PATCH 42/48] docs(versioning): correct BrowserEgressHost introduction version The versioning docs and tests attributed BrowserEgressHost to 2.26 alongside TraceSinkHost, but it was introduced in 2.20. The comments, prose, and desktop module contract now state the correct version so the compatibility rationale matches the actual contract history. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-bus/src/version/version_tests.rs | 6 ++---- docs/crates/tinycomputer-bus/versioning.md | 9 +++++---- docs/technical/specs/desktop-module-contract.md | 4 ++-- 3 files changed, 9 insertions(+), 10 deletions(-) diff --git a/crates/tinycomputer-bus/src/version/version_tests.rs b/crates/tinycomputer-bus/src/version/version_tests.rs index 7409e4622..925d38fe3 100644 --- a/crates/tinycomputer-bus/src/version/version_tests.rs +++ b/crates/tinycomputer-bus/src/version/version_tests.rs @@ -39,15 +39,13 @@ fn a_newer_minor_on_the_module_side_binds() { // 2.19 adds the ConsequenceHost host-callback interface (Review): a 2.19 // host serves it, which a 2.18 module does not call, so its approvals // would never reach the host's policy. - // 2.20 adds SessionOptions identity fields for browser launches. - // 2.26 adds TraceSinkHost and BrowserEgressHost, so a 2.25 module - // lacks callbacks required by the host. + // 2.20 adds SessionOptions identity fields and BrowserEgressHost. + // 2.26 adds TraceSinkHost, so a 2.25 module lacks that callback. assert!(!is_compatible((2, 25))); assert!(!is_compatible((2, 24))); assert!(!is_compatible((2, 23))); assert!(!is_compatible((2, 22))); // BrowserEgressHost authorizes, consumes, and validates each browser dial. - // 2.20 adds SessionOptions' optional browser identity and fingerprint fields. assert!(!is_compatible((2, 24))); assert!(!is_compatible((2, 20))); assert!(!is_compatible((2, 19))); diff --git a/docs/crates/tinycomputer-bus/versioning.md b/docs/crates/tinycomputer-bus/versioning.md index 7636f1141..e3fa3f6ea 100644 --- a/docs/crates/tinycomputer-bus/versioning.md +++ b/docs/crates/tinycomputer-bus/versioning.md @@ -46,15 +46,16 @@ Two conditions, both necessary: outright, in either direction. 2. **The module must be at least as new, minor-wise, as the host.** A host built against `(2, 26)` expects at least the members and fields that - existed at `(2, 26)`. A module reporting `(2, 25)` predates the combined - `TraceSinkHost` and `BrowserEgressHost` callback contract, so a 2.26 host - rejects it. A newer module with the same major is accepted. + existed at `(2, 26)`. A module reporting `(2, 25)` predates the + `TraceSinkHost` callback added in 2.26, so a 2.26 host rejects it. It does + include `BrowserEgressHost`, which was added in 2.20. A newer module with + the same major is accepted. ```rust,ignore assert!(is_compatible(CONTRACT_VERSION)); // (2, 26), the exact version this crate ships assert!(is_compatible((2, 27))); // a newer, still-compatible module assert!(!is_compatible((2, 11))); // an older module, missing something -assert!(!is_compatible((2, 25))); // predates TraceSinkHost and BrowserEgressHost +assert!(!is_compatible((2, 25))); // predates TraceSinkHost; BrowserEgressHost arrived in 2.20 assert!(!is_compatible((1, 10))); // a different major, all bets off ``` diff --git a/docs/technical/specs/desktop-module-contract.md b/docs/technical/specs/desktop-module-contract.md index 5a94b1967..af309cbad 100644 --- a/docs/technical/specs/desktop-module-contract.md +++ b/docs/technical/specs/desktop-module-contract.md @@ -89,7 +89,7 @@ serves the interface and fails to answer, turns the approval into a decline, so the task never takes the action. A host that serves nothing leaves the pause as the only gate. A payment checkpoint is never continuable and needs no review. -Browser egress (2.26): a host may serve the optional +Browser egress (2.20): a host may serve the optional `ai.tinyhumans.tinycomputer.BrowserEgressHost` interface (`tinycomputer_bus::browser_egress`) with `Authorize`, `Consume`, and `Validate`. Before a browser proxy request is dialed, the module asks the host @@ -97,7 +97,7 @@ to authorize its actual destination and receives vetted socket addresses plus an opaque lease. It consumes a one-use grant for an exact address before dialing, and reauthorizes before trying another address if a connection fails. The lease is revalidated while uploads, tunnels, or responses remain active. A -2.25 module cannot enforce these host decisions. +2.19 module cannot enforce these host decisions. Session identity (2.20): `SessionOptions` takes the optional `timezone`, `locale`, `accept_language`, `user_agent_metadata`, `screen`, `init_scripts` and From e836ed60f57584e1430b191de3f7ede70ac39788 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 22:34:58 +0000 Subject: [PATCH 43/48] docs: correct BrowserEgressHost introduction to 2.25 The docs and version test comments attributed BrowserEgressHost to contract 2.20, but it was actually introduced in 2.25. Updated the README, versioning guide, desktop module contract spec, and the version test comment so the recorded contract history matches the shipped interface. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-bus/README.md | 3 ++- crates/tinycomputer-bus/src/version/version_tests.rs | 3 ++- docs/crates/tinycomputer-bus/versioning.md | 4 ++-- docs/technical/specs/desktop-module-contract.md | 2 +- 4 files changed, 7 insertions(+), 5 deletions(-) diff --git a/crates/tinycomputer-bus/README.md b/crates/tinycomputer-bus/README.md index a367cd328..88bf0d96f 100644 --- a/crates/tinycomputer-bus/README.md +++ b/crates/tinycomputer-bus/README.md @@ -169,7 +169,8 @@ See the [Globe contract](src/accessibility/README.md). Reliable Globe callers require a released 2.12-compatible artifact with a verified digest. -Contract 2.26 adds the optional confidential `TraceSinkHost` and `BrowserEgressHost` callbacks. A host +Contract 2.25 adds the optional `BrowserEgressHost` callbacks, and 2.26 adds the +confidential `TraceSinkHost` callback. A host prepares one exact callback binding per loaded module and supplies its unique destination as `trace_sink.destination`. TinyComputer sends sanitized desktop trace events, trace artifacts, and requested task reports to `Append`, `StoreArtifact`, and diff --git a/crates/tinycomputer-bus/src/version/version_tests.rs b/crates/tinycomputer-bus/src/version/version_tests.rs index 925d38fe3..e813ad574 100644 --- a/crates/tinycomputer-bus/src/version/version_tests.rs +++ b/crates/tinycomputer-bus/src/version/version_tests.rs @@ -39,7 +39,8 @@ fn a_newer_minor_on_the_module_side_binds() { // 2.19 adds the ConsequenceHost host-callback interface (Review): a 2.19 // host serves it, which a 2.18 module does not call, so its approvals // would never reach the host's policy. - // 2.20 adds SessionOptions identity fields and BrowserEgressHost. + // 2.20 adds SessionOptions identity fields. + // 2.25 adds BrowserEgressHost. // 2.26 adds TraceSinkHost, so a 2.25 module lacks that callback. assert!(!is_compatible((2, 25))); assert!(!is_compatible((2, 24))); diff --git a/docs/crates/tinycomputer-bus/versioning.md b/docs/crates/tinycomputer-bus/versioning.md index e3fa3f6ea..b4767f549 100644 --- a/docs/crates/tinycomputer-bus/versioning.md +++ b/docs/crates/tinycomputer-bus/versioning.md @@ -48,14 +48,14 @@ Two conditions, both necessary: built against `(2, 26)` expects at least the members and fields that existed at `(2, 26)`. A module reporting `(2, 25)` predates the `TraceSinkHost` callback added in 2.26, so a 2.26 host rejects it. It does - include `BrowserEgressHost`, which was added in 2.20. A newer module with + include `BrowserEgressHost`, which was added in 2.25. A newer module with the same major is accepted. ```rust,ignore assert!(is_compatible(CONTRACT_VERSION)); // (2, 26), the exact version this crate ships assert!(is_compatible((2, 27))); // a newer, still-compatible module assert!(!is_compatible((2, 11))); // an older module, missing something -assert!(!is_compatible((2, 25))); // predates TraceSinkHost; BrowserEgressHost arrived in 2.20 +assert!(!is_compatible((2, 25))); // predates TraceSinkHost; includes BrowserEgressHost from 2.25 assert!(!is_compatible((1, 10))); // a different major, all bets off ``` diff --git a/docs/technical/specs/desktop-module-contract.md b/docs/technical/specs/desktop-module-contract.md index af309cbad..460755c67 100644 --- a/docs/technical/specs/desktop-module-contract.md +++ b/docs/technical/specs/desktop-module-contract.md @@ -89,7 +89,7 @@ serves the interface and fails to answer, turns the approval into a decline, so the task never takes the action. A host that serves nothing leaves the pause as the only gate. A payment checkpoint is never continuable and needs no review. -Browser egress (2.20): a host may serve the optional +Browser egress (2.25): a host may serve the optional `ai.tinyhumans.tinycomputer.BrowserEgressHost` interface (`tinycomputer_bus::browser_egress`) with `Authorize`, `Consume`, and `Validate`. Before a browser proxy request is dialed, the module asks the host From 376957f8d0c82806794fef739bdd90ef4ed8179e Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 22:35:08 +0000 Subject: [PATCH 44/48] docs(desktop-module-contract): update minimum module version to 2.24 The spec stated that a 2.19 module cannot enforce host decisions, but the minimum supported module version is now 2.24, so the reference was corrected to match. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- docs/technical/specs/desktop-module-contract.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/technical/specs/desktop-module-contract.md b/docs/technical/specs/desktop-module-contract.md index 460755c67..79d556918 100644 --- a/docs/technical/specs/desktop-module-contract.md +++ b/docs/technical/specs/desktop-module-contract.md @@ -97,7 +97,7 @@ to authorize its actual destination and receives vetted socket addresses plus an opaque lease. It consumes a one-use grant for an exact address before dialing, and reauthorizes before trying another address if a connection fails. The lease is revalidated while uploads, tunnels, or responses remain active. A -2.19 module cannot enforce these host decisions. +2.24 module cannot enforce these host decisions. Session identity (2.20): `SessionOptions` takes the optional `timezone`, `locale`, `accept_language`, `user_agent_metadata`, `screen`, `init_scripts` and From e40cf2fa3aac4ad897eb0191537e276283393baa Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 22:38:30 +0000 Subject: [PATCH 45/48] test(trace_sink): add module doc comment to trace sink tests Document the purpose of the trace sink test module so readers know it pins the contract's wire representations. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-bus/src/trace_sink/trace_sink_tests.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/tinycomputer-bus/src/trace_sink/trace_sink_tests.rs b/crates/tinycomputer-bus/src/trace_sink/trace_sink_tests.rs index 7d8431f64..00a466f24 100644 --- a/crates/tinycomputer-bus/src/trace_sink/trace_sink_tests.rs +++ b/crates/tinycomputer-bus/src/trace_sink/trace_sink_tests.rs @@ -1,3 +1,5 @@ +//! Tests pinning the trace sink contract's wire representations. + use super::*; #[test] From 42a12652f4b3c3632fdbaa545af53f41701e52c5 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 23:03:55 +0000 Subject: [PATCH 46/48] docs(tinycomputer-bus): correct BrowserEgressHost version in versioning guide The versioning guide claimed BrowserEgressHost was added in 2.25, but it actually landed in 2.20. The prose and the inline comment in the compatibility example now cite the correct version so the example stays consistent with the surrounding explanation. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- docs/crates/tinycomputer-bus/versioning.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/crates/tinycomputer-bus/versioning.md b/docs/crates/tinycomputer-bus/versioning.md index b4767f549..807ef239f 100644 --- a/docs/crates/tinycomputer-bus/versioning.md +++ b/docs/crates/tinycomputer-bus/versioning.md @@ -48,14 +48,14 @@ Two conditions, both necessary: built against `(2, 26)` expects at least the members and fields that existed at `(2, 26)`. A module reporting `(2, 25)` predates the `TraceSinkHost` callback added in 2.26, so a 2.26 host rejects it. It does - include `BrowserEgressHost`, which was added in 2.25. A newer module with + include `BrowserEgressHost`, which was added in 2.20. A newer module with the same major is accepted. ```rust,ignore assert!(is_compatible(CONTRACT_VERSION)); // (2, 26), the exact version this crate ships assert!(is_compatible((2, 27))); // a newer, still-compatible module assert!(!is_compatible((2, 11))); // an older module, missing something -assert!(!is_compatible((2, 25))); // predates TraceSinkHost; includes BrowserEgressHost from 2.25 +assert!(!is_compatible((2, 25))); // predates TraceSinkHost; includes BrowserEgressHost from 2.20 assert!(!is_compatible((1, 10))); // a different major, all bets off ``` From 3018ebf49b0c3bc2c04e3c0eab5ac03a0efa6a40 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 23:10:28 +0000 Subject: [PATCH 47/48] test(scripts): serialize cargo tests on windows Set RUST_TEST_THREADS=1 when the feature test script runs on Windows, since the module tests and trace-sink coverage both create multi-threaded Tokio runtimes and concurrent teardown was triggering an access violation in the test process. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- scripts/test-features.sh | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/scripts/test-features.sh b/scripts/test-features.sh index cdcc90070..aac4a46d6 100755 --- a/scripts/test-features.sh +++ b/scripts/test-features.sh @@ -3,6 +3,14 @@ set -euo pipefail cd "$(dirname "${BASH_SOURCE[0]}")/.." python3 scripts/test-e2e-version.py python3 scripts/test-source-line-endings.py +case "${RUNNER_OS:-$(uname -s)}" in + Windows|MINGW*|MSYS*|CYGWIN*) + # The module tests each create multi-thread Tokio runtimes, and trace-sink + # coverage also owns worker threads. Serial test execution avoids a + # Windows test-process access violation during concurrent runtime teardown. + export RUST_TEST_THREADS=1 + ;; +esac cargo test --locked --workspace cargo test --locked --workspace --all-features cargo test --locked -p tinycomputer --features static-link From 2a4d78e1598eef0d5dde6c11220d51f7d486e75a Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 23:29:49 +0000 Subject: [PATCH 48/48] docs(tinycomputer-bus): correct BrowserEgressHost version in versioning guide The versioning guide stated that BrowserEgressHost was added in 2.20, but it actually landed in 2.25. The prose and the accompanying compatibility example now reference the correct version so the documented rationale for rejecting a (2, 25) module matches reality. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- docs/crates/tinycomputer-bus/versioning.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/crates/tinycomputer-bus/versioning.md b/docs/crates/tinycomputer-bus/versioning.md index 807ef239f..b4767f549 100644 --- a/docs/crates/tinycomputer-bus/versioning.md +++ b/docs/crates/tinycomputer-bus/versioning.md @@ -48,14 +48,14 @@ Two conditions, both necessary: built against `(2, 26)` expects at least the members and fields that existed at `(2, 26)`. A module reporting `(2, 25)` predates the `TraceSinkHost` callback added in 2.26, so a 2.26 host rejects it. It does - include `BrowserEgressHost`, which was added in 2.20. A newer module with + include `BrowserEgressHost`, which was added in 2.25. A newer module with the same major is accepted. ```rust,ignore assert!(is_compatible(CONTRACT_VERSION)); // (2, 26), the exact version this crate ships assert!(is_compatible((2, 27))); // a newer, still-compatible module assert!(!is_compatible((2, 11))); // an older module, missing something -assert!(!is_compatible((2, 25))); // predates TraceSinkHost; includes BrowserEgressHost from 2.20 +assert!(!is_compatible((2, 25))); // predates TraceSinkHost; includes BrowserEgressHost from 2.25 assert!(!is_compatible((1, 10))); // a different major, all bets off ```