diff --git a/Cargo.lock b/Cargo.lock index 5bd1a6716..fdfcf4461 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -89,7 +89,7 @@ dependencies = [ [[package]] name = "agent-desktop-core" -version = "0.9.4" +version = "0.10.1" dependencies = [ "base64 0.23.1", "libc", @@ -103,7 +103,7 @@ dependencies = [ [[package]] name = "agent-desktop-linux" -version = "0.9.4" +version = "0.10.1" dependencies = [ "agent-desktop-core", "thiserror 2.0.20", @@ -111,7 +111,7 @@ dependencies = [ [[package]] name = "agent-desktop-macos" -version = "0.9.4" +version = "0.10.1" dependencies = [ "accessibility-sys", "agent-desktop-core", @@ -130,10 +130,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]] @@ -207,7 +212,7 @@ checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] @@ -682,7 +687,7 @@ checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] @@ -786,7 +791,7 @@ checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] @@ -870,7 +875,7 @@ checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] @@ -2416,7 +2421,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] @@ -2580,9 +2585,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", @@ -2606,7 +2611,7 @@ checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] @@ -2640,7 +2645,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.3.4", + "getrandom 0.4.3", "once_cell", "rustix 1.1.4", "windows-sys 0.61.2", @@ -2683,7 +2688,7 @@ checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] @@ -2816,6 +2821,7 @@ dependencies = [ name = "tinycomputer-bus" version = "0.15.0" dependencies = [ + "base64 0.22.1", "serde", "serde_json", "thiserror 2.0.20", @@ -3065,7 +3071,7 @@ checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] @@ -3271,6 +3277,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 = "ulid" version = "1.2.1" @@ -3467,7 +3496,7 @@ dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", "wasm-bindgen-shared", ] @@ -3544,7 +3573,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.48.0", + "windows-sys 0.61.2", ] [[package]] @@ -4028,7 +4057,7 @@ checksum = "33811428bee40dbceb6d545e95754741d17a6aef9a4849f0fd62e2ba4f412a78" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", "synstructure", ] @@ -4069,7 +4098,7 @@ checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", "synstructure", ] @@ -4109,7 +4138,7 @@ checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] 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-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 c4fa10bf5..88bf0d96f 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 (including opaque host-held secret handles), 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` @@ -166,3 +168,25 @@ 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.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 +`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 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 +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-bus/src/lib.rs b/crates/tinycomputer-bus/src/lib.rs index b1fac0100..e799910b1 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 //! @@ -132,6 +132,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..7900c2ee2 --- /dev/null +++ b/crates/tinycomputer-bus/src/trace_sink/mod.rs @@ -0,0 +1,142 @@ +//! 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; + +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. +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. `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, 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, + /// Limits the host must enforce atomically for this trace scope. + 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 { + /// 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..00a466f24 --- /dev/null +++ b/crates/tinycomputer-bus/src/trace_sink/trace_sink_tests.rs @@ -0,0 +1,77 @@ +//! Tests pinning the trace sink contract's wire representations. + +use super::*; + +#[test] +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" + }), + deadline_ms: 900, + byte_budget: 4096, + }; + 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); + + 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)?; + 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(()) +} + +#[test] +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", + "status": {"state": "running"}, + "summary": "running", + "progress": 0.0, + "next": [] + }, + "steps": [], "records": {}, "artifacts": [], "learned": [], "trace": [] + }))?, + }; + 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() -> Result<(), serde_json::Error> { + assert_ne!(INTERFACE, crate::names::INTERFACE); + assert_eq!(METHODS, ["Append", "StoreArtifact", "WriteReport"]); + assert_eq!(SinkAck {}, serde_json::from_str("{}")?); + Ok(()) +} diff --git a/crates/tinycomputer-bus/src/version/mod.rs b/crates/tinycomputer-bus/src/version/mod.rs index d2c7e2cfe..841c92b62 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, 25); +pub const CONTRACT_VERSION: (u32, u32) = (2, 26); /// 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, 25); /// ``` /// # use tinycomputer_bus::{is_compatible, CONTRACT_VERSION}; /// assert!(is_compatible(CONTRACT_VERSION)); -/// assert!(is_compatible((2, 25))); +/// assert!(is_compatible((2, 26))); /// 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 37d58e5bb..e813ad574 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, 25)); + assert_eq!(CONTRACT_VERSION, (2, 26)); } #[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, 25))); + assert!(is_compatible((2, 26))); 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. @@ -39,11 +39,14 @@ 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. + // 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))); assert!(!is_compatible((2, 23))); assert!(!is_compatible((2, 22))); - // 2.25 adds BrowserEgressHost (Authorize/Consume/Validate): a 2.25 host - // serves it, while a 2.24 module cannot enforce per-destination browser dials. - // 2.20 adds SessionOptions' optional browser identity and fingerprint fields. + // BrowserEgressHost authorizes, consumes, and validates each browser dial. assert!(!is_compatible((2, 24))); assert!(!is_compatible((2, 20))); assert!(!is_compatible((2, 19))); 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/desktop_tests/reply_tests.rs b/crates/tinycomputer-desktop/src/desktop/desktop_tests/reply_tests.rs index a1dad25a2..50dd6496f 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,53 @@ 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( 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 d4ca162cf..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; @@ -80,13 +81,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 { @@ -123,28 +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` in headed or headless mode. /// /// Headed mode lets a ref action take focus and move the real cursor when @@ -236,6 +233,7 @@ impl Desktop { trace_strict: flag(object.get("trace_strict"), "trace_strict")?, headed: flag(object.get("headed"), "headed")?, cursor: None, + trace_sink: None, }) } @@ -252,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() - } - - /// 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 @@ -293,16 +263,6 @@ impl Desktop { self.headed } - /// 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)) - } - /// Runs `command` under a fresh adapter and context, and wraps whatever it /// produces in the envelope. /// @@ -310,7 +270,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, { @@ -320,7 +280,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, @@ -332,9 +292,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) @@ -396,3 +359,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/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/reply.rs b/crates/tinycomputer-desktop/src/desktop/reply.rs index 88f7d90cb..d8864acfe 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 { 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-desktop/src/desktop/trace_sink_tests.rs b/crates/tinycomputer-desktop/src/desktop/trace_sink_tests.rs new file mode 100644 index 000000000..f89203a06 --- /dev/null +++ b/crates/tinycomputer-desktop/src/desktop/trace_sink_tests.rs @@ -0,0 +1,64 @@ +//! Tests for desktop trace-sink configuration and callback behavior. + +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_or_else(std::sync::PoisonError::into_inner) + .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() { + 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(), + )); + 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_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-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-engine/src/task/task_tests/persistence_tests.rs b/crates/tinycomputer-engine/src/task/task_tests/persistence_tests.rs index 1874c1632..b0683b4a4 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,7 @@ 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")); - let snapshot: serde_json::Value = serde_json::from_str(serialized).unwrap(); + let snapshot: serde_json::Value = serde_json::from_slice(&encoded).unwrap(); assert_eq!( snapshot .pointer("/task/constraints/browser_profile") diff --git a/crates/tinycomputer-examples/src/bin/verify_module.rs b/crates/tinycomputer-examples/src/bin/verify_module.rs index d682e94a6..1e7970c29 100644 --- a/crates/tinycomputer-examples/src/bin/verify_module.rs +++ b/crates/tinycomputer-examples/src/bin/verify_module.rs @@ -7,13 +7,59 @@ 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 { + tokio::task::yield_now().await; + self.events + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .push(event.record); + Ok(trace_sink::SinkAck {}) + } + + async fn store_artifact( + &self, + _artifact: trace_sink::TraceArtifact, + ) -> tinybus::Result { + tokio::task::yield_now().await; + Err(tinybus::Error::failed( + "verification fixture does not persist trace artifacts", + )) + } + + async fn write_report( + &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_or_else(std::sync::PoisonError::into_inner) + .push(report); + Ok(trace_sink::SinkAck {}) + } +} #[tokio::main] async fn main() -> Result<(), Box> { @@ -22,7 +68,36 @@ 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(); + 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) + .await?; if info.name != "tinycomputer" { return Err(io::Error::other(format!( @@ -58,6 +133,9 @@ async fn main() -> Result<(), Box> { )) .into()); } + verify_trace_sink(&capture, &trace_path)?; + + verify_report_sink(&proxy, &capture).await?; let declared: Vec<&str> = info .manifest @@ -98,6 +176,118 @@ 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_or_else(std::sync::PoisonError::into_inner); + 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, + 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": ["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"))? + .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 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(), + ); + } + capture.fail_reports.store(true, Ordering::SeqCst); + let failed = proxy + .call_confidential::>( + names::methods::TASK_REPORT, + (TaskReportRequest { + id: task_id, + trace: false, + },), + ) + .await; + 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(()) +} + /// 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 65ec251e3..a2af54e06 100644 --- a/crates/tinycomputer/src/tinybus_module/README.md +++ b/crates/tinycomputer/src/tinybus_module/README.md @@ -54,7 +54,15 @@ 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` 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. 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 `prelaunch` a planned browser task's browser (a planned task also warms @@ -79,7 +87,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 @@ -90,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/config.rs b/crates/tinycomputer/src/tinybus_module/config.rs index c8d3e4060..5521ae9f5 100644 --- a/crates/tinycomputer/src/tinybus_module/config.rs +++ b/crates/tinycomputer/src/tinybus_module/config.rs @@ -177,6 +177,54 @@ impl BrowserDefaults { } } +/// Whether the host explicitly selected the trace/report callback. +pub(crate) fn trace_sink_destination( + config: &serde_json::Value, +) -> Result> { + match config + .as_object() + .and_then(|object| object.get("trace_sink")) + { + 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: "false or an object with the trusted host callback `destination`", + }), + } +} + /// 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/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 54ef05e97..5efed9198 100644 --- a/crates/tinycomputer/src/tinybus_module/dispatch/mod.rs +++ b/crates/tinycomputer/src/tinybus_module/dispatch/mod.rs @@ -42,14 +42,15 @@ 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; 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,21 @@ 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 + .is_err() + { + return Ok(report_sink_failure()); + } + Ok(reply) } /// The tasks this module holds, newest first. @@ -594,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. @@ -802,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/dispatch/service.rs b/crates/tinycomputer/src/tinybus_module/dispatch/service.rs index 0fc700dcf..4385e3081 100644 --- a/crates/tinycomputer/src/tinybus_module/dispatch/service.rs +++ b/crates/tinycomputer/src/tinybus_module/dispatch/service.rs @@ -14,10 +14,11 @@ use tinycomputer_engine as agentic; use super::DesktopService; use crate::tinybus_module::browser_egress::BusAuthorizer; -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}; +use crate::tinybus_module::trace_sink::TraceLink; use crate::{Desktop, Result}; impl DesktopService { @@ -31,22 +32,31 @@ impl DesktopService { Self::with_browser(config, Arc::new(Browser::new(Arc::new(AgentBrowser)))) } - /// Builds the service with the authenticated host callback available on - /// the module connection. A configured egress scope always selects the - /// enforced browser launcher. + /// Builds the service with authenticated host callbacks available on the + /// module connection. A configured egress scope selects the enforced + /// browser launcher, and a configured trace sink receives desktop traces. pub(crate) fn from_config_with_connection( config: &serde_json::Value, connection: tinybus::Connection, - ) -> Result { - let defaults = BrowserDefaults::from_config(config)?; + ) -> TinyBusResult { + let defaults = BrowserDefaults::from_config(config) + .map_err(|error| TinyBusError::failed(error.to_string()))?; let browser = if let Some(egress) = defaults.egress { Arc::new(Browser::new(Arc::new(EnforcedAgentBrowser::new(Arc::new( - BusAuthorizer::new(connection, egress.policy_id, egress.generation), + BusAuthorizer::new(connection.clone(), egress.policy_id, egress.generation), ))))) } else { Arc::new(Browser::new(Arc::new(AgentBrowser))) }; - Self::with_browser(config, browser) + let trace_link = if let Some(destination) = trace_sink_destination(config) + .map_err(|error| TinyBusError::failed(error.to_string()))? + { + Some(TraceLink::new(connection, destination)?) + } else { + None + }; + Self::with_browser_and_trace_sink(config, browser, trace_link) + .map_err(|error| TinyBusError::failed(error.to_string())) } /// Builds the service from the module configuration blob, opening browser @@ -55,9 +65,27 @@ impl DesktopService { /// # Errors /// /// 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) + } + + 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")) @@ -114,6 +142,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 72f6ad0a8..62dfdc093 100644 --- a/crates/tinycomputer/src/tinybus_module/mod.rs +++ b/crates/tinycomputer/src/tinybus_module/mod.rs @@ -25,6 +25,7 @@ mod consequence_gate; mod dispatch; mod runner; mod site_memory; +mod trace_sink; use serde_json::Value; use tinybus::{Connection, Result as TinyBusResult}; @@ -95,6 +96,7 @@ tinybus_module::module_export_optional_static! { optional = [ "ai.tinyhumans.tinycomputer.SiteMemoryHost", "ai.tinyhumans.tinycomputer.ConsequenceHost", + "ai.tinyhumans.tinycomputer.TraceSinkHost", "ai.tinyhumans.tinycomputer.BrowserEgressHost", ], 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 9f273023a..c81d44495 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 @@ -276,3 +276,44 @@ fn the_cursor_is_configured_or_refused() { } assert!(DesktopService::from_config(&json!({"cursor": "off"})).is_ok()); } + +#[test] +fn trace_sink_requires_the_host_prepared_unique_destination() { + use crate::tinybus_module::config::trace_sink_destination; + + 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" + ); +} + +#[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/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. 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..e256e9b81 --- /dev/null +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/engine_adapter.rs @@ -0,0 +1,144 @@ +//! 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, Command, TraceLink}; + +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), + } +} 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..c86e94cdf --- /dev/null +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/mod.rs @@ -0,0 +1,337 @@ +//! 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 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, SyncSender}; +use std::time::{Duration, Instant}; + +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, +}; +mod engine_adapter; + +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, +}; +pub(super) const CALL_TIMEOUT: Duration = Duration::from_secs(10); + +pub(super) enum Command { + 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. +pub(crate) struct TraceLink { + connection: Connection, + destination: tinybus::BusName, + pub(super) worker: std::sync::Mutex>>, + worker_thread: std::sync::Mutex>>, + pub(super) callback_active: Arc, + confidential: bool, +} + +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, + 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(); + 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( + "trace sink requires a multi-thread Tokio runtime", + )); + } + let (sender, receiver) = mpsc::sync_channel(1); + let worker_thread = std::thread::Builder::new() + .name("tinycomputer-trace-sink".into()) + .spawn(move || { + worker( + &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 { + connection, + destination, + 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 = { + 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, + (record,), + self.confidential, + ) + .await + .map(|_| ()) + } + + fn proxy(&self, timeout: Duration) -> TinyBusResult { + self.connection + .proxy( + self.destination.as_str(), + trace_sink::OBJECT_PATH, + trace_sink::INTERFACE, + ) + .map(|proxy| proxy.with_timeout(timeout)) + } +} + +fn worker( + runtime: &tokio::runtime::Handle, + connection: &Connection, + destination: &tinybus::BusName, + callback_active: &Arc, + receiver: &Receiver, + confidential: bool, +) { + while let Ok(command) = receiver.recv() { + match command { + Command::Append { + record, + deadline, + byte_budget, + reply, + } => { + 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 Some(guard) = CallbackGuard::try_acquire(callback_active) else { + let _ = reply.send(Err(())); + continue; + }; + let result = runtime.block_on(async { + let proxy = connection + .proxy( + destination.as_str(), + trace_sink::OBJECT_PATH, + trace_sink::INTERFACE, + )? + .with_timeout(timeout); + call_to_host::( + &proxy, + trace_sink::methods::APPEND, + (TraceEvent { + record, + deadline_ms, + byte_budget, + },), + confidential, + ) + .await + .map(|_| ()) + }); + drop(guard); + let _ = reply.send(result.map_err(|_| ())); + } + Command::StoreArtifact { + kind, + name, + bytes, + deadline, + limits, + reply, + } => { + 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 Some(guard) = CallbackGuard::try_acquire(callback_active) else { + let _ = reply.send(Err(())); + continue; + }; + let result = runtime.block_on(async { + let proxy = connection + .proxy( + destination.as_str(), + trace_sink::OBJECT_PATH, + trace_sink::INTERFACE, + )? + .with_timeout(timeout); + call_to_host::( + &proxy, + trace_sink::methods::STORE_ARTIFACT, + (TraceArtifact { + kind, + name, + bytes, + deadline_ms, + limits, + },), + confidential, + ) + .await + .map(|reply| reply.reference) + }); + drop(guard); + let _ = reply.send(result.map_err(|_| ())); + } + } + } +} + +async fn call(proxy: &Proxy, member: &str, args: A) -> TinyBusResult +where + T: DeserializeOwned, + A: Serialize, +{ + 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 + } +} + +pub(super) 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)) + } +} + +impl Drop for CallbackGuard<'_> { + fn drop(&mut self) { + self.0.store(false, Ordering::Release); + } +} + +impl Drop for TraceLink { + fn drop(&mut self) { + let _ = self.shutdown(); + } +} + +#[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..8297a2202 --- /dev/null +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests.rs @@ -0,0 +1,168 @@ +//! 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; +#[path = "trace_sink_tests/deadline_tests.rs"] +mod deadline_tests; +#[path = "trace_sink_tests/lifecycle_tests.rs"] +mod lifecycle_tests; + +use super::*; +use std::sync::Mutex; +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": [] + })) +} + +#[tinybus::interface(name = "ai.tinyhumans.tinycomputer.TraceSinkHost")] +impl RecordingHost { + async fn append(&self, event: TraceEvent) -> TinyBusResult { + 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")) + } +} + +#[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_or_else(std::sync::PoisonError::into_inner) + .take() + { + let _ = started.send(()); + } + 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_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")) + } +} 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..965b2615d --- /dev/null +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/callbacks_tests.rs @@ -0,0 +1,164 @@ +//! 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 configured_service_routes_task_reports_to_the_confidential_host_callback() +-> Result<(), Box> { + use tinybus::Interface; + use tinycomputer_bus::agent::{ + AgentResponse, StartTaskRequest, TaskId, 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 host_name = host_connection + .unique_name() + .ok_or("host connection has no unique name")?; + let config = serde_json::json!({ + "trace_sink": {"destination": host_name.as_str()} + }); + let service = crate::tinybus_module::DesktopService::from_config_with_connection( + &config, + module_connection.clone(), + )?; + + let started: AgentResponse = serde_json::from_value( + service + .call( + &names::methods::START_TASK.try_into()?, + serde_json::json!([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()?, + serde_json::json!([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!( + 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> { + 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..ee05557a2 --- /dev/null +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/deadline_tests.rs @@ -0,0 +1,80 @@ +//! 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..5b46be51b --- /dev/null +++ b/crates/tinycomputer/src/tinybus_module/trace_sink/trace_sink_tests/lifecycle_tests.rs @@ -0,0 +1,132 @@ +//! Tests for queued callback delivery and trace-sink shutdown. + +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(); + 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() + .checked_sub(Duration::from_millis(1)) + .unwrap_or_else(Instant::now); + send( + &link.worker, + Command::Append { + record: serde_json::json!({"event": "expired"}), + deadline: queued_deadline, + byte_budget: 4096, + reply: queued_reply, + }, + )?; + 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 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!( + !shutdown.is_finished(), + "shutdown must wait for the active host callback" + ); + 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(()) +} diff --git a/crates/tinycomputer/tests/public_api_tests.rs b/crates/tinycomputer/tests/public_api_tests.rs index 2a5ad2ad4..9497a15c0 100644 --- a/crates/tinycomputer/tests/public_api_tests.rs +++ b/crates/tinycomputer/tests/public_api_tests.rs @@ -34,7 +34,8 @@ 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, 25)); + assert_eq!(CONTRACT_VERSION, (2, 26)); + assert!(!is_compatible((2, 25))); } #[test] diff --git a/docs/crates/tinycomputer-bus/versioning.md b/docs/crates/tinycomputer-bus/versioning.md index abeaff0dd..b4767f549 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, 25); +pub const CONTRACT_VERSION: (u32, u32) = (2, 26); ``` This describes the *vocabulary*: the member set and the payload shapes, @@ -45,17 +45,17 @@ 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, 24)` expects at least the members and fields that - existed at `(2, 24)`. A module reporting `(2, 23)` might be missing one of - them, so it is rejected. A module reporting `(2, 24)` is an exact match - and is accepted. A module reporting `(2, 25)` has everything the host - expects, plus something newer the host simply does not use yet, so it is - accepted. + 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 + the same major is accepted. ```rust,ignore -assert!(is_compatible(CONTRACT_VERSION)); // (2, 25), the exact version this crate ships -assert!(is_compatible((2, 26))); // a newer, still-compatible module +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((1, 10))); // a different major, all bets off ``` diff --git a/docs/crates/tinycomputer/configuration.md b/docs/crates/tinycomputer/configuration.md index e4c1a1539..51717dbf1 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 | diff --git a/docs/technical/specs/desktop-module-contract.md b/docs/technical/specs/desktop-module-contract.md index d2503c36d..79d556918 100644 --- a/docs/technical/specs/desktop-module-contract.md +++ b/docs/technical/specs/desktop-module-contract.md @@ -96,14 +96,30 @@ Browser egress (2.25): a host may serve the optional 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.24 -module cannot enforce these host decisions. +The lease is revalidated while uploads, tunnels, or responses remain active. A +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 `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.26): 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 +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 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 +same report more than once. + Host-held secret facts (2.22): `StartTask` and `RunFlow` accept optional `fact_handles`, keyed by fact name. Each entry carries only the host's opaque handle, a safe mask, and a kind. These fields are confidential request data. @@ -208,7 +224,8 @@ or false keeps the existing start behavior. ### 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` and `headed` booleans, an optional + `trace_sink` object containing the host-prepared unique callback destination, 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. 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 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