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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 24 additions & 8 deletions crates/openhuman-core/src/artifacts/box_source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use std::sync::Arc;

use async_trait::async_trait;
use serde_json::Value;
use tiny_artifacts::{ArtifactKind, Artifacts};
use tiny_artifacts::{ArtifactKind, Artifacts, FileStore};
use tinytools::{PermissionLevel, Tool, ToolResult};

use super::tiny_store::version_files_dir;
Expand Down Expand Up @@ -253,7 +253,7 @@ impl Tool for BoxSourced {
Ok(bytes) => bytes,
Err(error) => return Ok(ToolResult::error(error.to_string())),
};
let staged = match stage(&self.staging, &path, &bytes) {
let staged = match stage(&self.staging, &path, bytes).await {
Ok(staged) => staged,
Err(error) => {
tracing::warn!(%error, "[artifacts] could not stage a sandbox file");
Expand Down Expand Up @@ -294,9 +294,23 @@ impl Drop for Staged {
/// generated, so a box name the host's filesystem rejects (`?` on Windows)
/// still stages.
///
/// The folder is owned by the returned [`Staged`] from before it exists, and
/// nothing here awaits, so a call cancelled at any point leaves no copy behind.
fn stage(staging: &Path, box_path: &str, bytes: &[u8]) -> std::io::Result<Staged> {
/// The bytes go in through the artifact crate's [`FileStore`] port, like every
/// other artifact file, not a raw filesystem write.
///
/// The write runs in a task of its own that finishes whether or not the caller
/// is still waiting. The [`Staged`] guard lives in that task, so a call
/// cancelled mid-write still has its folder removed, and only after the write
/// has settled (a removal racing the storage layer's directory creation could
/// otherwise leave the folder behind).
async fn stage(staging: &Path, box_path: &str, bytes: Vec<u8>) -> std::io::Result<Staged> {
let staging = staging.to_path_buf();
let box_path = box_path.to_owned();
tokio::spawn(async move { stage_now(&staging, &box_path, &bytes).await })
.await
.map_err(std::io::Error::other)?
}

async fn stage_now(staging: &Path, box_path: &str, bytes: &[u8]) -> std::io::Result<Staged> {
let name = match Path::new(box_path)
.extension()
.and_then(|extension| extension.to_str())
Expand All @@ -308,11 +322,13 @@ fn stage(staging: &Path, box_path: &str, bytes: &[u8]) -> std::io::Result<Staged
};
let dir = staging.join(uuid::Uuid::new_v4().simple().to_string());
let staged = Staged {
file: dir.join(name),
file: dir.join(&name),
dir,
};
std::fs::create_dir_all(&staged.dir)?;
std::fs::write(&staged.file, bytes)?;
tiny_artifacts::FsFileStore::new(&staged.dir)
.put(&name, bytes, None)
.await
.map_err(std::io::Error::other)?;
Comment thread
senamakel marked this conversation as resolved.
Resolved
Ok(staged)
}

Expand Down
74 changes: 49 additions & 25 deletions crates/openhuman-core/src/artifacts/box_source_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -185,11 +185,23 @@ async fn created_id(tool: &BoxSourced, args: Value) -> String {
body["artifact_id"].as_str().unwrap().to_owned()
}

/// Keeps the security module's path floor scripted for the test's lifetime
/// when that module is built; a build without it has no floor to script.
#[cfg(feature = "security-module")]
fn path_floor() -> Box<dyn std::any::Any> {
Box::new(crate::modules::security::gap::install_path_floor_port(
crate::modules::security::gap::ScriptedPathFloorPort::new([], vec![]),
))
}

#[cfg(not(feature = "security-module"))]
fn path_floor() -> Box<dyn std::any::Any> {
Box::new(())
}

#[tokio::test]
async fn a_path_is_read_from_the_callers_box_when_the_backend_keeps_boxes() {
let _floor = crate::modules::security::gap::install_path_floor_port(
crate::modules::security::gap::ScriptedPathFloorPort::new([], vec![]),
);
let _floor = path_floor();
let fixture = Fixture::new();
let bytes: Vec<u8> = (0..=255u8).cycle().take(5000).collect();
fixture.the_box_holds(&bytes);
Expand All @@ -208,9 +220,7 @@ async fn a_path_is_read_from_the_callers_box_when_the_backend_keeps_boxes() {

#[tokio::test]
async fn a_path_inside_the_boxs_work_folder_is_read_by_its_relative_name() {
let _floor = crate::modules::security::gap::install_path_floor_port(
crate::modules::security::gap::ScriptedPathFloorPort::new([], vec![]),
);
let _floor = path_floor();
let fixture = Fixture::new();
fixture.the_box_holds(b"pdf");
let tool = fixture.tool(true, user("u1"));
Expand Down Expand Up @@ -240,9 +250,7 @@ async fn a_path_elsewhere_in_the_box_is_refused() {

#[tokio::test]
async fn a_path_is_read_from_the_host_when_the_backend_keeps_no_boxes() {
let _floor = crate::modules::security::gap::install_path_floor_port(
crate::modules::security::gap::ScriptedPathFloorPort::new([], vec![]),
);
let _floor = path_floor();
let fixture = Fixture::new();
std::fs::write(fixture.action.join("report.pdf"), b"host bytes").unwrap();
let tool = fixture.tool(false, user("u1"));
Expand All @@ -258,9 +266,7 @@ async fn a_path_is_read_from_the_host_when_the_backend_keeps_no_boxes() {

#[tokio::test]
async fn an_unreadable_configuration_is_a_tool_error_and_never_reads_the_host() {
let _floor = crate::modules::security::gap::install_path_floor_port(
crate::modules::security::gap::ScriptedPathFloorPort::new([], vec![]),
);
let _floor = path_floor();
let fixture = Fixture::new();
// A host file of the same name: it must not be imported in the box's place.
std::fs::write(fixture.action.join("report.pdf"), b"host bytes").unwrap();
Expand Down Expand Up @@ -316,9 +322,7 @@ async fn a_call_with_no_tenant_is_refused_without_touching_a_box_or_the_host() {

#[tokio::test]
async fn a_text_artifact_never_touches_a_box() {
let _floor = crate::modules::security::gap::install_path_floor_port(
crate::modules::security::gap::ScriptedPathFloorPort::new([], vec![]),
);
let _floor = path_floor();
let fixture = Fixture::new();
let tool = fixture.tool(true, user("u1"));

Expand Down Expand Up @@ -369,9 +373,7 @@ fn a_box_path_is_the_name_relative_to_the_work_folder() {

#[tokio::test]
async fn an_update_reads_its_new_file_from_the_callers_box() {
let _floor = crate::modules::security::gap::install_path_floor_port(
crate::modules::security::gap::ScriptedPathFloorPort::new([], vec![]),
);
let _floor = path_floor();
let fixture = Fixture::new();
fixture.the_box_holds(b"first");
let id = created_id(&fixture.tool(true, user("u1")), file_args("a.pdf")).await;
Expand Down Expand Up @@ -419,7 +421,9 @@ async fn an_update_of_a_text_artifact_never_touches_a_box() {
#[tokio::test]
async fn a_staged_copy_is_removed_when_its_call_is_dropped_before_it_finishes() {
let staging = tempfile::tempdir().unwrap();
let staged = stage(staging.path(), "out/a.pdf", b"bytes").unwrap();
let staged = stage(staging.path(), "out/a.pdf", b"bytes".to_vec())
.await
.unwrap();
let dir = staged.dir.clone();
assert!(dir.join("file.pdf").is_file());

Expand All @@ -432,9 +436,15 @@ async fn a_staged_copy_is_removed_when_its_call_is_dropped_before_it_finishes()
async fn a_box_name_the_host_cannot_hold_still_stages_with_its_extension() {
let staging = tempfile::tempdir().unwrap();

let odd = stage(staging.path(), "out/re?port*.pdf", b"x").unwrap();
let no_extension = stage(staging.path(), "out/Makefile", b"x").unwrap();
let hostile = stage(staging.path(), "out/a.p?f", b"x").unwrap();
let odd = stage(staging.path(), "out/re?port*.pdf", b"x".to_vec())
.await
.unwrap();
let no_extension = stage(staging.path(), "out/Makefile", b"x".to_vec())
.await
.unwrap();
let hostile = stage(staging.path(), "out/a.p?f", b"x".to_vec())
.await
.unwrap();

assert!(odd.file.ends_with("file.pdf"));
assert!(no_extension.file.ends_with("file"));
Expand All @@ -453,9 +463,7 @@ impl RecordKinds for BrokenRecords {

#[tokio::test]
async fn an_update_whose_record_cannot_be_read_fails_instead_of_reading_the_host() {
let _floor = crate::modules::security::gap::install_path_floor_port(
crate::modules::security::gap::ScriptedPathFloorPort::new([], vec![]),
);
let _floor = path_floor();
let fixture = Fixture::new();
std::fs::write(fixture.action.join("a.pdf"), b"host bytes").unwrap();
let tool = fixture.update_tool(true, user("u1"));
Expand All @@ -477,3 +485,19 @@ async fn an_update_whose_record_cannot_be_read_fails_instead_of_reading_the_host
);
assert!(fixture.driver.calls().is_empty(), "no box was touched");
}

#[tokio::test]
async fn a_call_cancelled_while_staging_leaves_no_copy_behind() {
let staging = tempfile::tempdir().unwrap();

// Poll the staging future once, so its write is started, then drop it.
tokio::select! {
biased;
_ = stage(staging.path(), "out/a.pdf", b"bytes".to_vec()) => unreachable!("staging cannot finish on its first poll"),
_ = std::future::ready(()) => {}
}
// The write finishes in its own task and its guard then removes the folder.
tokio::time::sleep(std::time::Duration::from_millis(500)).await;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Synchronize the cancellation test with staging completion

On a busy CI filesystem, the detached staging task can still be writing when this 500 ms sleep finishes, so the directory assertion can report a leak even though the guard will correctly remove it once the write settles. Wait for an explicit completion signal from the staging task before asserting cleanup rather than assuming an upper bound on filesystem latency. This also follows AGENTS.md's guidance against time-based unit-test flakes.

AGENTS.md reference: AGENTS.md:L191-L191

Useful? React with 👍 / 👎.


assert_eq!(std::fs::read_dir(staging.path()).unwrap().count(), 0);
}
145 changes: 4 additions & 141 deletions crates/openhuman-core/src/artifacts/tiny_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,12 @@ use std::sync::Arc;
use async_trait::async_trait;
use tiny_artifacts::{
ArtifactEvent, ArtifactEventKind, ArtifactKind, ArtifactObserver, ArtifactRecord,
ArtifactStore, Artifacts, Author, Content, FileRef, FileStore,
ArtifactStore, Artifacts, FileRef, FileStore,
};

use super::files::FileRoots;
use super::types::ArtifactKind as LegacyArtifactKind;
use crate::security::approval::ApprovalChatContext;
use crate::tools::per_call::{context as per_call_context, PerCallTool};

/// Subdirectory under the artifacts root holding versioned records.
const VERSIONED_SUBDIR: &str = "versioned";
Expand Down Expand Up @@ -607,145 +606,9 @@ pub fn stored_file_path(workspace_dir: &Path, file: &tiny_artifacts::FileRef) ->
version_files_dir(workspace_dir).join(&file.key)
}

/// Build the artifact tools bound to this workspace's service: the crate's
/// default set (`create_artifact`, `read_artifact`, `update_artifact`,
/// `list_artifacts`), `delete_artifact` (default-off through its
/// `tools::user_filter` family), and — only when a `publisher` exists, i.e. the
/// user can use cloud file storage — `share_artifact`.
///
/// The crate's tools run without a run context, so each call builds its tool
/// around a service whose UI bridge carries that call's chat routing
/// ([`PerCallTool`]); the card then reaches the chat the agent is answering.
pub fn registered_tools(
workspace_dir: &Path,
files: FileRoots,
action_dir: &Path,
publisher: Option<super::ArtifactPublisherBinder>,
) -> Vec<Box<dyn tinytools::Tool>> {
let can_publish = publisher.is_some();
let service = {
let workspace_dir = workspace_dir.to_path_buf();
let action_dir = action_dir.to_path_buf();
Arc::new(move |chat: Option<&ApprovalChatContext>| {
Arc::new(artifacts_service_with_publisher(
&workspace_dir,
files.clone(),
Some(&action_dir),
chat,
publisher.as_ref(),
))
})
};
let author = Author::agent(AGENT_AUTHOR_ID);
let mut tools: Vec<Box<dyn tinytools::Tool>> = Vec::new();
{
let (service, author) = (service.clone(), author.clone());
let staging = super::box_source::staging_dir(workspace_dir);
tools.push(Box::new(PerCallTool::new(
per_call_context,
move |context| {
let create = tiny_artifacts::CreateArtifactTool::new(
service(context.chat.as_ref()),
author.clone(),
);
let tenant = context.dispatch.tenant();
super::box_source::BoxSourced::new(
create,
super::box_source::KindSource::Args,
Arc::new(super::box_source::SandboxBoxFiles::new(context.dispatch)),
tenant,
staging.clone(),
)
},
)));
}
tools.push(Box::new(tiny_artifacts::ReadArtifactTool::new(service(
None,
))));
{
let (service, author) = (service.clone(), author.clone());
let staging = super::box_source::staging_dir(workspace_dir);
tools.push(Box::new(PerCallTool::new(
per_call_context,
move |context| {
let artifacts = service(context.chat.as_ref());
let update =
tiny_artifacts::UpdateArtifactTool::new(Arc::clone(&artifacts), author.clone());
let tenant = context.dispatch.tenant();
super::box_source::BoxSourced::new(
update,
super::box_source::KindSource::Record(artifacts),
Arc::new(super::box_source::SandboxBoxFiles::new(context.dispatch)),
tenant,
staging.clone(),
)
},
)));
}
tools.push(Box::new(tiny_artifacts::ListArtifactsTool::new(service(
None,
))));
{
let service = service.clone();
tools.push(Box::new(PerCallTool::new(
per_call_context,
move |context| tiny_artifacts::DeleteArtifactTool::new(service(context.chat.as_ref())),
)));
}
if can_publish {
tools.push(Box::new(PerCallTool::new(
per_call_context,
move |context| tiny_artifacts::ShareArtifactTool::new(service(context.chat.as_ref())),
)));
}
tools
}

/// Author id stamped on versions the user writes in the desktop editor.
pub const OPERATOR_AUTHOR_ID: &str = "operator";

/// Author id stamped on versions OpenHuman's agent writes — through the
/// artifact tools and through producer tools alike. A tool run carries no
/// agent identity, so every agent-written version is attributed to this one.
pub const AGENT_AUTHOR_ID: &str = "openhuman";

/// Append the user's edit of artifact `id` as a new operator-authored version
/// (the preview panel's autosave). The UI bridge writes it to the files folder
/// and updates the card. A body identical to the newest version appends
/// nothing.
pub async fn save_operator_version(
workspace_dir: &Path,
files: FileRoots,
id: &str,
body: &str,
ctx: &crate::core::runtime::DispatchCtx,
) -> Result<SavedVersion, String> {
let saved = artifacts_service(workspace_dir, files, None, None, ctx)
.revise(
id,
Content::Text(body.to_string()),
&Author::operator(OPERATOR_AUTHOR_ID),
None,
)
.await
.map_err(|e| e.to_string())?;
if let Some(notice) = &saved.notice {
tracing::warn!(target: "tiny-artifacts", artifact_id = %id, "[tiny-artifacts] {notice}");
}
Ok(SavedVersion {
version: saved.version,
saved: saved.appended,
})
}

/// Result of [`save_operator_version`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
pub struct SavedVersion {
/// The newest version number after the call.
pub version: u32,
/// Whether a version was appended.
pub saved: bool,
}
#[path = "tiny_store_tools.rs"]
mod tools;
pub use tools::*;

#[cfg(test)]
#[path = "tiny_store_tests.rs"]
Expand Down
Loading
Loading