Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

Merge upstream/main into feat/tiny-artifacts-service

Sanilbcb248dde611
diff --cc app/src/components/assistant-ui/thread.tsx
index 0f5fb3365a,5e1d272cb9..ac1db5c31b
--- a/app/src/components/assistant-ui/thread.tsx
+++ b/app/src/components/assistant-ui/thread.tsx
@@@ -1182,9 -1146,10 +1175,11 @@@ const AssistantMessage: FC = () =>
ActivityGroup = DefaultActivityGroup,
SourceGroup,
MessageTasks,
+ MessageArtifacts,
} = useContext(MessageComponentsContext);
const stopped = useAuiState(isStoppedRun);
+ const parts = useAuiState(s => s.message.parts);
+ const widgets = useMemo(() => collectMessageWidgets(parts), [parts]);
const ACTION_BAR_PT = 'pt-1.5';
// `min-h` reserves the bar's height (`pt-1.5` + a `size-6` button = 7.5) so a
diff --cc crates/openhuman-app/src/lib.rs
index c40eeca264,0a48f172b8..5441003044
--- a/crates/openhuman-app/src/lib.rs
+++ b/crates/openhuman-app/src/lib.rs
@@@ -77,6 -76,6 +76,7 @@@ mod core_rpc
mod deep_link_ipc;
#[cfg(target_os = "windows")]
mod deep_link_ipc_windows;
++mod docx;
mod remote_ws_relay;
// Cross-platform module: the registry-reading function is windows-only, but
// the parsing helpers compile (and test) everywhere so `cargo test` on the
diff --cc crates/openhuman-core/src/agent/artifacts/README.md
index 5914eb1683,234f21a3d3..763363fdab
--- a/crates/openhuman-core/src/agent/artifacts/README.md
+++ b/crates/openhuman-core/src/agent/artifacts/README.md
@@@ -20,11 -20,10 +20,11 @@@ renders artifact content itself
| [`types.rs`](./types.rs) | `ArtifactKind` (presentation/document/image/other), `ArtifactStatus` (pending/ready/failed), `ArtifactMeta`. Enums serialize lowercase; `parse` is case-insensitive and never errors (unknown kind → `Other`, unknown status → `Pending`). `ArtifactMeta.error` and `.thread_id` are optional, `skip_serializing_if` none. |
| [`files.rs`](./files.rs) | Where the bytes live: `reserve_file` (claims `<stem>.<ext>`, then `<stem> (2).<ext>`, with `create_new` in the shared files folder), `resolve_file` + the escape guard, `resolve_ready_file` (`pub`: the one id → existing-file lookup for readers and the desktop Download command), `remove_empty_placeholder`, the "file missing" error. |
| [`migrate.rs`](./migrate.rs) | `migrate_legacy_artifacts`: the idempotent, crash-safe boot move of pre-#5505 files into the files folder (copy to `.<id>.partial` → claim a name and rename → atomic meta write → delete legacy bytes). Run per account from `config::ensure_agent_dirs`. |
- | [`store.rs`](./store.rs) | All filesystem I/O over `tokio::fs`: `artifacts_root`, `create_artifact`, `finalize_artifact`, `fail_artifact`, `read_artifact_bytes` (`pub`); `save_artifact_meta`, `save_artifact_args`, `read_artifact_args`, `list_artifacts`, `get_artifact`, `delete_artifact` (`pub(crate)`); `validate_artifact_id` / `assert_within_root` sandboxing; the `REGENERATE_TARGET_ID` task-local; `sanitize_filename_stem`. |
+ | [`store.rs`](./store.rs) | All filesystem I/O over `tokio::fs`: `artifacts_root`, `create_artifact`, `finalize_artifact`, `fail_artifact`, `read_artifact_bytes` (`pub`); `save_artifact_meta`, `save_artifact_args`, `read_artifact_args`, `list_artifacts`, `get_artifact`, `delete_artifact` (`pub(crate)`); `validate_artifact_id` / `assert_within_root` sandboxing; `create_artifact_regenerating` (explicit regenerate target); `sanitize_filename_stem`. |
| [`ops.rs`](./ops.rs) | RPC business logic returning `Outcome<Value>`: `ai_list_artifacts`, `ai_get_artifact`, `ai_delete_artifact`, `ai_regenerate`. `DEFAULT_LIMIT = 50`, `MAX_LIMIT = 200`. The regenerate path that re-runs `PresentationTool` is `#[cfg(feature = "documents")]`; without the feature `ai_regenerate` returns an error. |
| [`schemas.rs`](./schemas.rs) | `ControllerSchema`s and `handle_*` fns for the four `ai.*` controllers; param helpers `read_required`, `read_optional_u64`, `read_optional_string` (whitespace-only → absent), `type_name`. |
-| [`tools.rs`](./tools.rs) | `ArtifactListTool`, `ArtifactGetTool`, `ArtifactDeleteTool`: shims over `ops` that unwrap the `Outcome` and return `outcome.value` as the `ToolResult` string. |
+| [`tiny_store.rs`](./tiny_store.rs) | OpenHuman's side of the versioned artifacts (`tiny-artifacts`): `versioned_store` (the crate's `FsArtifactStore` over `<workspace>/artifacts/versioned/`, one `<id>.json` per artifact), `LegacyUiBridge` (the crate's `ArtifactObserver`: shows each artifact's newest version through the legacy row + events and the files folder), `artifacts_service`, the agent tools, and `save_operator_version` (the preview panel's autosave). |
+| [`production.rs`](./production.rs) | `Production`: how producer tools (deck, document, generated media) file their output — reserve the file and the card, open the versioned record under the same id, then complete or fail it. |
| `*_tests.rs` | Sibling test files for each of the above (`#[path]`). |
## Public surface
diff --cc crates/openhuman-core/src/agent/artifacts/ops.rs
index 2b9dac7988,1df3fffd63..91f9a45b6e
--- a/crates/openhuman-core/src/agent/artifacts/ops.rs
+++ b/crates/openhuman-core/src/agent/artifacts/ops.rs
@@@ -276,73 -276,3 +276,74 @@@ async fn regenerate_presentation
#[cfg(test)]
#[path = "ops_tests.rs"]
mod tests;
+
+/// Save the user's edit of a versioned artifact as a new operator version
+/// (the preview panel's autosave). See
+/// [`super::tiny_store::save_operator_version`].
+pub async fn ai_save_artifact_version(
+ config: &Config,
+ artifact_id: &str,
+ body: &str,
+) -> Result<Outcome<Value>, String> {
+ let saved = super::tiny_store::save_operator_version(
+ &config.workspace_dir,
+ super::files::FileRoots::from_config(config),
+ artifact_id,
+ body,
+ )
+ .await?;
+ log::debug!(
+ "[artifacts] ai_save_artifact_version id={artifact_id} version={} saved={}",
+ saved.version,
+ saved.saved
+ );
+ Ok(Outcome::new(
+ json!({ "artifact_id": artifact_id, "version": saved.version, "saved": saved.saved }),
+ vec![],
+ ))
+}
+
+/// Share a version of an artifact through cloud file storage (the preview
+/// panel's Share button): uploads it and returns its link, which is also
+/// recorded on the version. A version that already has a live link of the same
+/// kind returns it without uploading again.
+pub async fn ai_share_artifact(
+ config: &Config,
+ artifact_id: &str,
+ version: Option<u32>,
+ public: bool,
+) -> Result<Outcome<Value>, String> {
+ let publisher = crate::integrations::file_storage::artifact_publisher(config)
+ .ok_or_else(|| "sign in to share artifacts".to_string())?;
+ let artifacts = super::tiny_store::artifacts_service(
+ &config.workspace_dir,
+ super::files::FileRoots::from_config(config),
+ None,
++ None,
+ )
+ .with_publisher(publisher);
+ let options = tiny_artifacts::PublishOptions {
+ public,
+ ..tiny_artifacts::PublishOptions::default()
+ };
+ let shared = artifacts
+ .publish(artifact_id, version, &options)
+ .await
+ .map_err(|e| e.to_string())?;
+ log::debug!(
+ "[artifacts] ai_share_artifact id={artifact_id} version={} public={public} reused={}",
+ shared.version,
+ shared.reused
+ );
+ Ok(Outcome::new(
+ json!({
+ "artifact_id": artifact_id,
+ "version": shared.version,
+ "url": shared.link.url,
+ "public": shared.link.public,
+ "expires_at_millis": shared.link.expires_at_millis,
+ "reused": shared.reused,
+ }),
+ vec![],
+ ))
+}
diff --cc crates/openhuman-core/src/agent/artifacts/production.rs
index d274e994c8,0000000000..515e5a3baf
mode 100644,000000..100644
--- a/crates/openhuman-core/src/agent/artifacts/production.rs
+++ b/crates/openhuman-core/src/agent/artifacts/production.rs
@@@ -1,194 -1,0 +1,192 @@@
+//! [`Production`]: how a producer tool (a deck, a document, a generated image
+//! or video) files what it makes as a versioned artifact.
+//!
+//! Every artifact goes through the `tiny-artifacts` service; a producer only
+//! adds the part that is OpenHuman's — reserving a file name in the visible
+//! files folder, so it can write its bytes there while the user already sees
+//! a "generating…" card. The flow:
+//!
+//! 1. [`Production::start`] reserves the file and the card, and opens the
- //! versioned record under the same id. A revision (`revise`, or a
- //! regenerate running inside [`super::store::REGENERATE_TARGET_ID`]) reuses
- //! the existing id and file, and keeps the record's history.
++//! versioned record under the same id. A revision (`revise`: an
++//! `artifact_id` argument or a regenerate target) reuses the existing id
++//! and file, and keeps the record's history.
+//! 2. The producer writes its bytes to [`Production::path`].
+//! 3. [`Production::complete`] appends the file as a new agent version; the UI
+//! bridge marks the card ready. [`Production::fail`] fails both instead.
+//!
+//! The record is written before the card is marked ready, so a ready card
+//! always has its versioned record.
+
+use std::path::{Path, PathBuf};
+
+use tiny_artifacts::{ArtifactKind, Artifacts, Author, Content};
+
+use super::files::FileRoots;
+use super::tiny_store::{artifacts_service, legacy_kind_for_extension};
+use super::types::ArtifactKind as LegacyArtifactKind;
++use crate::security::approval::ApprovalChatContext;
+
+/// A file being produced as an artifact.
+pub struct Production {
+ artifacts: Artifacts,
+ workspace_dir: PathBuf,
+ files: FileRoots,
++ chat: Option<ApprovalChatContext>,
+ id: String,
+ path: PathBuf,
+}
+
+impl std::fmt::Debug for Production {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("Production")
+ .field("id", &self.id)
+ .field("path", &self.path)
+ .finish_non_exhaustive()
+ }
+}
+
+impl Production {
+ /// Reserve the file (`<title>.<extension>` in the files folder) and open
+ /// the artifact. `revise` names an existing artifact to add a version to;
- /// otherwise a regenerate in scope is revised, or a new artifact is made.
- /// `tool_call_id` ties the card to the producing call's bubble.
++ /// otherwise a new artifact is made. `tool_call_id` ties the card to the
++ /// producing call's bubble; `chat` is the turn the card is announced to
++ /// (`None` outside a chat turn).
+ ///
+ /// # Errors
+ ///
+ /// Returns an error when the file cannot be reserved or the record cannot
+ /// be opened; the card is failed in the second case.
+ pub async fn start(
+ workspace_dir: &Path,
+ files: FileRoots,
+ kind: ArtifactKind,
+ title: &str,
+ extension: &str,
+ tool_call_id: Option<&str>,
+ revise: Option<&str>,
++ chat: Option<&ApprovalChatContext>,
+ ) -> Result<Self, String> {
+ let legacy_kind = if kind == ArtifactKind::Image {
+ LegacyArtifactKind::Image
+ } else {
+ legacy_kind_for_extension(&extension.to_ascii_lowercase())
+ };
- let target = revise
- .map(str::to_string)
- .or_else(|| {
- super::store::REGENERATE_TARGET_ID
- .try_with(Clone::clone)
- .ok()
- })
- .filter(|id| !id.trim().is_empty());
- let reserve = super::store::create_artifact_for_call(
++ let target = revise.filter(|id| !id.trim().is_empty());
++ let (meta, path) = super::store::create_artifact_regenerating(
+ workspace_dir,
+ files.clone(),
+ legacy_kind,
+ title,
+ extension,
+ tool_call_id,
- );
- let (meta, path) = match &target {
- Some(id) => {
- super::store::REGENERATE_TARGET_ID
- .scope(id.clone(), reserve)
- .await?
- }
- None => reserve.await?,
- };
++ target,
++ chat,
++ )
++ .await?;
+
- let artifacts = artifacts_service(workspace_dir, files.clone(), None);
++ let artifacts = artifacts_service(workspace_dir, files.clone(), None, chat);
+ let production = Self {
+ artifacts,
+ workspace_dir: workspace_dir.to_path_buf(),
+ files,
++ chat: chat.cloned(),
+ id: meta.id.clone(),
+ path,
+ };
+ // A revision keeps its record and history; a new artifact opens one.
+ let existing = production
+ .artifacts
+ .get(&meta.id)
+ .await
+ .map_err(|e| e.to_string());
+ let opened = match existing {
+ Ok(Some(_)) => Ok(()),
+ Ok(None) => production
+ .artifacts
+ .begin(kind, title, Some(meta.id.clone()))
+ .await
+ .map(|_| ())
+ .map_err(|e| e.to_string()),
+ Err(err) => Err(err),
+ };
+ if let Err(err) = opened {
+ let reason = format!("could not open the artifact record: {err}");
+ production.fail_card(&reason).await;
+ return Err(reason);
+ }
+ Ok(production)
+ }
+
+ /// The artifact's id.
+ pub fn id(&self) -> &str {
+ &self.id
+ }
+
+ /// Where the producer writes its bytes.
+ pub fn path(&self) -> &Path {
+ &self.path
+ }
+
+ /// File the written bytes as a new version and mark the card ready.
+ /// Returns the file's size.
+ ///
+ /// # Errors
+ ///
+ /// Returns an error when the version cannot be recorded or the card cannot
+ /// be marked ready; the card is failed then.
+ pub async fn complete(&self) -> Result<u64, String> {
+ let path = self.path.display().to_string();
+ let saved = self
+ .artifacts
+ .revise(
+ &self.id,
+ Content::File(path),
+ &Author::agent(super::tiny_store::AGENT_AUTHOR_ID),
+ None,
+ )
+ .await;
+ let reason = match saved {
+ Ok(saved) => match (
+ saved.notice,
+ saved.record.latest().and_then(|v| v.file.clone()),
+ ) {
+ (None, Some(file)) => return Ok(file.size_bytes),
+ (Some(notice), _) => notice,
+ (None, None) => "the recorded version has no file".to_string(),
+ },
+ Err(err) => err.to_string(),
+ };
+ let reason = format!("failed to finalize artifact: {reason}");
+ self.fail_card(&reason).await;
+ Err(reason)
+ }
+
+ /// Fail the artifact with `reason`.
+ pub async fn fail(&self, reason: &str) {
+ if let Err(err) = self.artifacts.fail(&self.id, reason).await {
+ tracing::warn!(
+ target: "tiny-artifacts",
+ artifact_id = %self.id,
+ err = %err,
+ "[artifacts] could not mark the versioned record failed"
+ );
+ self.fail_card(reason).await;
+ }
+ }
+
+ /// Fail the card directly (when the record could not take the change).
+ async fn fail_card(&self, reason: &str) {
- let _ =
- super::store::fail_artifact(&self.workspace_dir, self.files.clone(), &self.id, reason)
- .await;
++ let _ = super::store::fail_artifact(
++ &self.workspace_dir,
++ self.files.clone(),
++ &self.id,
++ reason,
++ self.chat.as_ref(),
++ )
++ .await;
+ }
+}
+
+#[cfg(test)]
+#[path = "production_tests.rs"]
+mod tests;
diff --cc crates/openhuman-core/src/agent/artifacts/production_tests.rs
index b0f63af70e,0000000000..b0d1934bc0
mode 100644,000000..100644
--- a/crates/openhuman-core/src/agent/artifacts/production_tests.rs
+++ b/crates/openhuman-core/src/agent/artifacts/production_tests.rs
@@@ -1,159 -1,0 +1,147 @@@
+use std::path::PathBuf;
+
+use tiny_artifacts::{ArtifactKind, ArtifactStatus as RecordStatus, ArtifactStore};
+
+use super::*;
- use crate::agent::artifacts::store::{get_artifact, REGENERATE_TARGET_ID};
++use crate::agent::artifacts::store::get_artifact;
+use crate::agent::artifacts::tiny_store::versioned_store;
+use crate::agent::artifacts::types::{ArtifactKind as CardKind, ArtifactStatus as CardStatus};
+
+fn temp_dirs() -> (PathBuf, PathBuf) {
+ let root = std::env::temp_dir().join(format!("production-{}", uuid::Uuid::new_v4()));
+ let (workspace, files) = (root.join("workspace"), root.join("Files"));
+ std::fs::create_dir_all(&workspace).unwrap();
+ std::fs::create_dir_all(&files).unwrap();
+ (workspace, files)
+}
+
+fn files_in(dir: &PathBuf) -> Vec<String> {
+ let mut names: Vec<String> = std::fs::read_dir(dir)
+ .unwrap()
+ .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
+ .collect();
+ names.sort();
+ names
+}
+
+async fn produce(
+ workspace: &PathBuf,
+ files: &PathBuf,
+ bytes: &[u8],
+ tool_call_id: Option<&str>,
+ revise: Option<&str>,
+) -> String {
+ let production = Production::start(
+ workspace,
+ FileRoots::new(files),
+ ArtifactKind::File,
+ "Quarterly Deck",
+ "pptx",
+ tool_call_id,
+ revise,
++ None,
+ )
+ .await
+ .unwrap();
+ tokio::fs::write(production.path(), bytes).await.unwrap();
+ assert_eq!(production.complete().await.unwrap(), bytes.len() as u64);
+ production.id().to_string()
+}
+
+#[tokio::test]
+async fn a_new_artifact_shares_one_id_and_one_file_between_card_and_record() {
+ let (workspace, files) = temp_dirs();
+ let production = Production::start(
+ &workspace,
+ FileRoots::new(&files),
+ ArtifactKind::File,
+ "Quarterly Deck",
+ "pptx",
+ None,
+ None,
++ None,
+ )
+ .await
+ .unwrap();
+ let id = production.id().to_string();
+
+ // While generating: a pending card, and a pending record with no version.
+ let card = get_artifact(&workspace, &id).await.unwrap();
+ assert_eq!(card.status, CardStatus::Pending);
+ assert_eq!(card.kind, CardKind::Presentation);
+ let record = versioned_store(&workspace).get(&id).await.unwrap().unwrap();
+ assert_eq!(record.status, RecordStatus::Pending);
+ assert!(record.versions.is_empty());
+
+ tokio::fs::write(production.path(), b"deck-v1")
+ .await
+ .unwrap();
+ production.complete().await.unwrap();
+
+ let card = get_artifact(&workspace, &id).await.unwrap();
+ assert_eq!(card.status, CardStatus::Ready);
+ assert_eq!(card.size_bytes, 7);
+ let record = versioned_store(&workspace).get(&id).await.unwrap().unwrap();
+ assert_eq!(record.status, RecordStatus::Ready);
+ assert_eq!(
+ record.latest().unwrap().author_id,
+ crate::agent::artifacts::tiny_store::AGENT_AUTHOR_ID
+ );
+ let file = record.latest().unwrap().file.clone().unwrap();
+ assert!(file.path.ends_with("quarterly-deck.pptx"), "{}", file.path);
+ assert_eq!(
+ files_in(&files),
+ vec!["quarterly-deck.pptx"],
+ "no second copy"
+ );
+}
+
+#[tokio::test]
+async fn a_revision_reuses_the_id_and_file_and_keeps_the_history() {
+ let (workspace, files) = temp_dirs();
+ let id = produce(&workspace, &files, b"deck-v1", Some("call-1"), None).await;
+ let again = produce(&workspace, &files, b"deck-v2!", None, Some(&id)).await;
+ assert_eq!(again, id);
+
+ let record = versioned_store(&workspace).get(&id).await.unwrap().unwrap();
+ assert_eq!(record.versions.len(), 2);
+ let card = get_artifact(&workspace, &id).await.unwrap();
+ assert_eq!(card.status, CardStatus::Ready);
+ assert_eq!(card.size_bytes, 8);
+ // The revision keeps the card tied to the call that made the artifact.
+ assert_eq!(card.tool_call_id.as_deref(), Some("call-1"));
+ assert_eq!(files_in(&files), vec!["quarterly-deck.pptx"]);
+ assert_eq!(
+ std::fs::read(files.join("quarterly-deck.pptx")).unwrap(),
+ b"deck-v2!"
+ );
+}
+
- #[tokio::test]
- async fn a_regenerate_in_scope_revises_the_target() {
- let (workspace, files) = temp_dirs();
- let id = produce(&workspace, &files, b"deck-v1", None, None).await;
- let again = REGENERATE_TARGET_ID
- .scope(
- id.clone(),
- produce(&workspace, &files, b"deck-v2", None, None),
- )
- .await;
- assert_eq!(again, id);
- let record = versioned_store(&workspace).get(&id).await.unwrap().unwrap();
- assert_eq!(record.versions.len(), 2);
- }
-
+#[tokio::test]
+async fn a_failed_production_fails_card_and_record() {
+ let (workspace, files) = temp_dirs();
+ let production = Production::start(
+ &workspace,
+ FileRoots::new(&files),
+ ArtifactKind::Image,
+ "Logo",
+ "png",
+ None,
+ None,
++ None,
+ )
+ .await
+ .unwrap();
+ production.fail("provider timed out").await;
+
+ let card = get_artifact(&workspace, production.id()).await.unwrap();
+ assert_eq!(card.status, CardStatus::Failed);
+ assert_eq!(card.error.as_deref(), Some("provider timed out"));
+ let record = versioned_store(&workspace)
+ .get(production.id())
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(record.status, RecordStatus::Failed);
+ assert_eq!(record.error.as_deref(), Some("provider timed out"));
+}
diff --cc crates/openhuman-core/src/agent/artifacts/schemas.rs
index 93a5209e1c,f050ff5b2f..b94cefefae
--- a/crates/openhuman-core/src/agent/artifacts/schemas.rs
+++ b/crates/openhuman-core/src/agent/artifacts/schemas.rs
@@@ -394,54 -285,9 +395,54 @@@ fn handle_get_artifact(ctx: DispatchCtx
})
}
- fn handle_save_artifact_version(params: Map<String, Value>) -> ControllerFuture {
++fn handle_save_artifact_version(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
++ let config = ctx.load_config().await?;
+ let artifact_id = read_required::<String>(&params, "artifact_id")?;
+ let body = read_required::<String>(&params, "body")?;
+ to_json(
+ crate::agent::artifacts::ops::ai_save_artifact_version(
+ &config,
+ artifact_id.trim(),
+ &body,
+ )
+ .await?,
+ )
+ })
+}
+
- fn handle_share_artifact(params: Map<String, Value>) -> ControllerFuture {
++fn handle_share_artifact(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
++ let config = ctx.load_config().await?;
+ let artifact_id = read_required::<String>(&params, "artifact_id")?;
+ let version = read_optional_u64(&params, "version")?
+ .map(|v| u32::try_from(v).map_err(|_| "invalid 'version': too large".to_string()))
+ .transpose()?;
+ let public = match params.get("public") {
+ None | Some(Value::Null) => false,
+ Some(Value::Bool(b)) => *b,
+ Some(other) => {
+ return Err(format!(
+ "invalid 'public': expected bool, got {}",
+ type_name(other)
+ ))
+ }
+ };
+ to_json(
+ crate::agent::artifacts::ops::ai_share_artifact(
+ &config,
+ artifact_id.trim(),
+ version,
+ public,
+ )
+ .await?,
+ )
+ })
+}
+
- fn handle_delete_artifact(params: Map<String, Value>) -> ControllerFuture {
+ fn handle_delete_artifact(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = ctx.load_config().await?;
let artifact_id = read_required::<String>(&params, "artifact_id")?;
to_json(
crate::agent::artifacts::ops::ai_delete_artifact(&config, artifact_id.trim()).await?,
diff --cc crates/openhuman-core/src/agent/artifacts/tiny_store.rs
index a6a3d2b20a,0000000000..10122a3d4a
mode 100644,000000..100644
--- a/crates/openhuman-core/src/agent/artifacts/tiny_store.rs
+++ b/crates/openhuman-core/src/agent/artifacts/tiny_store.rs
@@@ -1,296 -1,0 +1,349 @@@
+//! OpenHuman's side of the versioned artifacts (`tiny-artifacts`).
+//!
+//! The crate owns what an artifact is and how it changes; every creation and
+//! revision goes through its [`Artifacts`] service. OpenHuman supplies the
+//! service's ports:
+//!
+//! * [`versioned_store`] — the crate's [`FsArtifactStore`] over
+//! `<workspace>/artifacts/versioned/` (one `<id>.json` per artifact);
+//! * [`LegacyUiBridge`] — the observer that shows each artifact in the
+//! desktop UI;
+//! * the folders file artifacts may point into: the agent's working folder
+//! and the visible files folder.
+//!
+//! # UI bridge
+//!
+//! The desktop UI knows only the legacy artifact pipeline (an `ArtifactMeta`
+//! row plus the `ArtifactPending` / `ArtifactReady` domain events), and only
+//! the newest version of each artifact. [`LegacyUiBridge`] turns every
+//! service write into that pipeline: the newest version's content (or, for an
+//! image or file artifact, a copy of its file) is written into the files folder
+//! under the same artifact id, through the "regenerate in place" flow
- //! ([`super::store::REGENERATE_TARGET_ID`]), so a revision overwrites the file
- //! the artifact already owns and its card updates in place.
++//! ([`super::store::create_artifact_regenerating`]), so a revision overwrites
++//! the file the artifact already owns and its card updates in place. The bridge
++//! carries the chat routing of the turn that made the change, so the card
++//! reaches that chat live.
+
+use std::path::{Path, PathBuf};
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use tiny_artifacts::{
+ ArtifactEvent, ArtifactEventKind, ArtifactKind, ArtifactObserver, ArtifactRecord, Artifacts,
+ Author, Content,
+};
+
+use super::files::FileRoots;
+use super::types::ArtifactKind as LegacyArtifactKind;
++use crate::security::approval::ApprovalChatContext;
++use crate::tools::per_call::PerCallTool;
+
+/// Subdirectory under the artifacts root holding versioned records.
+const VERSIONED_SUBDIR: &str = "versioned";
+
+/// The legacy kind and file extension the UI gets for an artifact's newest
+/// version: text kinds by kind, file kinds by the file's extension.
+fn legacy_shape(record: &ArtifactRecord) -> Option<(LegacyArtifactKind, String)> {
+ let latest = record.latest()?;
+ let shape = match record.kind {
+ ArtifactKind::Text => (LegacyArtifactKind::Document, "txt".to_string()),
+ ArtifactKind::Markdown => (LegacyArtifactKind::Document, "md".to_string()),
+ ArtifactKind::Html => (LegacyArtifactKind::Document, "html".to_string()),
+ ArtifactKind::Image | ArtifactKind::File => {
+ let ext = latest
+ .file
+ .as_ref()
+ .and_then(tiny_artifacts::FileRef::extension)
+ .or_else(|| {
+ Path::new(&latest.body)
+ .extension()
+ .and_then(|e| e.to_str())
+ .map(str::to_ascii_lowercase)
+ })
+ .unwrap_or_else(|| "bin".to_string());
+ let kind = if record.kind == ArtifactKind::Image {
+ LegacyArtifactKind::Image
+ } else {
+ legacy_kind_for_extension(&ext)
+ };
+ (kind, ext)
+ }
+ };
+ Some(shape)
+}
+
+pub(crate) fn legacy_kind_for_extension(ext: &str) -> LegacyArtifactKind {
+ match ext {
+ "pptx" | "ppt" | "key" | "odp" => LegacyArtifactKind::Presentation,
+ "docx" | "doc" | "pdf" | "md" | "txt" | "rtf" | "odt" | "html" | "htm" => {
+ LegacyArtifactKind::Document
+ }
+ "png" | "jpg" | "jpeg" | "gif" | "webp" | "svg" => LegacyArtifactKind::Image,
+ "mp4" | "webm" | "mov" => LegacyArtifactKind::Video,
+ _ => LegacyArtifactKind::Other,
+ }
+}
+
+pub use tiny_artifacts::FsArtifactStore;
+
+/// The versioned records of a workspace: `tiny-artifacts`' file-system store
+/// over `<workspace>/artifacts/versioned/` (one `<id>.json` per artifact).
+pub fn versioned_store(workspace_dir: &Path) -> FsArtifactStore {
+ FsArtifactStore::new(workspace_dir.join("artifacts").join(VERSIONED_SUBDIR))
+}
+
+/// Shows versioned artifacts in the desktop UI through the legacy pipeline.
+pub struct LegacyUiBridge {
+ workspace_dir: PathBuf,
+ files: FileRoots,
++ chat: Option<ApprovalChatContext>,
+}
+
+impl LegacyUiBridge {
- /// A bridge writing into `files` (the visible files folder).
- pub fn new(workspace_dir: impl Into<PathBuf>, files: FileRoots) -> Self {
++ /// A bridge writing into `files` (the visible files folder), announcing
++ /// cards to `chat` (`None` outside a chat turn).
++ pub fn new(
++ workspace_dir: impl Into<PathBuf>,
++ files: FileRoots,
++ chat: Option<&ApprovalChatContext>,
++ ) -> Self {
+ Self {
+ workspace_dir: workspace_dir.into(),
+ files,
++ chat: chat.cloned(),
+ }
+ }
+
+ /// Put the newest version in the files folder under the artifact's id and
+ /// mark it ready: the content for text kinds, a copy of the file for file
+ /// kinds (unless the file already is the one the artifact owns).
+ async fn show_newest(&self, record: &ArtifactRecord) -> anyhow::Result<()> {
+ let (Some(latest), Some((legacy_kind, ext))) = (record.latest(), legacy_shape(record))
+ else {
+ return Ok(());
+ };
+ // A producer writes its file straight into the row it reserved: the
+ // row only needs marking ready (re-reserving would flash its card
+ // back to "generating").
+ if let Some(file) = latest.file.as_ref() {
+ if let Ok(meta) = super::store::get_artifact(&self.workspace_dir, &record.id).await {
+ let owned = meta.file.as_deref().map(Path::new);
+ if owned.is_some_and(|owned| same_file(owned, Path::new(&file.path))) {
+ let size = tokio::fs::metadata(&file.path).await?.len();
- super::store::finalize_artifact(&self.workspace_dir, &record.id, size)
- .await
- .map_err(anyhow::Error::msg)?;
++ super::store::finalize_artifact(
++ &self.workspace_dir,
++ &record.id,
++ size,
++ self.chat.as_ref(),
++ )
++ .await
++ .map_err(anyhow::Error::msg)?;
+ return Ok(());
+ }
+ }
+ }
- super::store::REGENERATE_TARGET_ID
- .scope(record.id.clone(), async {
- let (meta, dest) = super::store::create_artifact(
- &self.workspace_dir,
- self.files.clone(),
- legacy_kind,
- &record.title,
- &ext,
- )
- .await
- .map_err(anyhow::Error::msg)?;
- let size = if record.holds_file() {
- let source = latest
- .file
- .as_ref()
- .map_or_else(|| PathBuf::from(&latest.body), |f| PathBuf::from(&f.path));
- if same_file(&source, &dest) {
- tokio::fs::metadata(&dest).await?.len()
- } else {
- tokio::fs::copy(&source, &dest).await?
- }
- } else {
- tokio::fs::write(&dest, latest.body.as_bytes()).await?;
- latest.body.len() as u64
- };
- super::store::finalize_artifact(&self.workspace_dir, &meta.id, size)
- .await
- .map_err(anyhow::Error::msg)?;
- Ok::<(), anyhow::Error>(())
- })
++ let (meta, dest) = super::store::create_artifact_regenerating(
++ &self.workspace_dir,
++ self.files.clone(),
++ legacy_kind,
++ &record.title,
++ &ext,
++ None,
++ Some(&record.id),
++ self.chat.as_ref(),
++ )
++ .await
++ .map_err(anyhow::Error::msg)?;
++ let size = if record.holds_file() {
++ let source = latest
++ .file
++ .as_ref()
++ .map_or_else(|| PathBuf::from(&latest.body), |f| PathBuf::from(&f.path));
++ if same_file(&source, &dest) {
++ tokio::fs::metadata(&dest).await?.len()
++ } else {
++ tokio::fs::copy(&source, &dest).await?
++ }
++ } else {
++ tokio::fs::write(&dest, latest.body.as_bytes()).await?;
++ latest.body.len() as u64
++ };
++ super::store::finalize_artifact(&self.workspace_dir, &meta.id, size, self.chat.as_ref())
+ .await
++ .map_err(anyhow::Error::msg)?;
++ Ok(())
+ }
+}
+
+fn same_file(a: &Path, b: &Path) -> bool {
+ match (std::fs::canonicalize(a), std::fs::canonicalize(b)) {
+ (Ok(a), Ok(b)) => a == b,
+ _ => false,
+ }
+}
+
+#[async_trait]
+impl ArtifactObserver for LegacyUiBridge {
+ async fn on_event(&self, event: &ArtifactEvent) -> anyhow::Result<()> {
+ let id = &event.record.id;
+ match event.kind {
+ ArtifactEventKind::Ready => self.show_newest(&event.record).await,
+ ArtifactEventKind::Failed => {
+ let reason = event.record.error.as_deref().unwrap_or("failed");
+ // Only an artifact the UI already shows has a row to fail.
+ if super::store::get_artifact(&self.workspace_dir, id)
+ .await
+ .is_ok()
+ {
+ super::store::fail_artifact(
+ &self.workspace_dir,
+ self.files.clone(),
+ id,
+ reason,
++ self.chat.as_ref(),
+ )
+ .await
+ .map_err(anyhow::Error::msg)?;
+ }
+ Ok(())
+ }
+ ArtifactEventKind::Deleted => {
+ let _ = super::store::delete_artifact(&self.workspace_dir, self.files.clone(), id)
+ .await;
+ Ok(())
+ }
+ // The legacy pipeline's pending row needs the file's extension,
+ // which a pending artifact does not have yet; its card appears
+ // when the first version lands.
+ ArtifactEventKind::Pending => Ok(()),
+ }
+ }
+}
+
+/// The artifact service for one workspace: OpenHuman's store and UI bridge,
+/// with file artifacts allowed from the agent's working folder and the files
- /// folder.
++/// folder. Cards are announced to `chat`, the turn making the change (`None`
++/// outside a chat turn).
+pub fn artifacts_service(
+ workspace_dir: &Path,
+ files: FileRoots,
+ action_dir: Option<&Path>,
++ chat: Option<&ApprovalChatContext>,
+) -> Artifacts {
+ let mut roots: Vec<PathBuf> = action_dir.map(Path::to_path_buf).into_iter().collect();
+ roots.push(files.current().to_path_buf());
+ Artifacts::new(Arc::new(versioned_store(workspace_dir)))
- .with_observer(Arc::new(LegacyUiBridge::new(workspace_dir, files)))
++ .with_observer(Arc::new(LegacyUiBridge::new(workspace_dir, files, chat)))
+ .with_file_roots(tiny_artifacts::FileRoots::new(roots))
+}
+
+/// 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<Arc<dyn tiny_artifacts::ArtifactPublisher>>,
+) -> Vec<Box<dyn tinytools::Tool>> {
- let mut service = artifacts_service(workspace_dir, files, Some(action_dir));
- if let Some(publisher) = publisher {
- service = service.with_publisher(publisher);
++ 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>| {
++ let mut service =
++ artifacts_service(&workspace_dir, files.clone(), Some(&action_dir), chat);
++ if let Some(publisher) = &publisher {
++ service = service.with_publisher(publisher.clone());
++ }
++ Arc::new(service)
++ })
++ };
++ let author = Author::agent(AGENT_AUTHOR_ID);
++ let mut tools: Vec<Box<dyn tinytools::Tool>> = Vec::new();
++ {
++ let (service, author) = (service.clone(), author.clone());
++ tools.push(Box::new(PerCallTool::new(move |chat, _| {
++ tiny_artifacts::CreateArtifactTool::new(service(chat), author.clone())
++ })));
++ }
++ tools.push(Box::new(tiny_artifacts::ReadArtifactTool::new(service(
++ None,
++ ))));
++ {
++ let (service, author) = (service.clone(), author.clone());
++ tools.push(Box::new(PerCallTool::new(move |chat, _| {
++ tiny_artifacts::UpdateArtifactTool::new(service(chat), author.clone())
++ })));
++ }
++ tools.push(Box::new(tiny_artifacts::ListArtifactsTool::new(service(
++ None,
++ ))));
++ {
++ let service = service.clone();
++ tools.push(Box::new(PerCallTool::new(move |chat, _| {
++ tiny_artifacts::DeleteArtifactTool::new(service(chat))
++ })));
+ }
- let artifacts = Arc::new(service);
- let mut tools =
- tiny_artifacts::registered_tools(artifacts.clone(), Author::agent(AGENT_AUTHOR_ID));
- tools.push(Box::new(tiny_artifacts::DeleteArtifactTool::new(
- artifacts.clone(),
- )));
- if artifacts.can_publish() {
- tools.push(Box::new(tiny_artifacts::ShareArtifactTool::new(artifacts)));
++ if can_publish {
++ tools.push(Box::new(PerCallTool::new(move |chat, _| {
++ tiny_artifacts::ShareArtifactTool::new(service(chat))
++ })));
+ }
+ 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,
+) -> Result<SavedVersion, String> {
- let saved = artifacts_service(workspace_dir, files, None)
++ let saved = artifacts_service(workspace_dir, files, None, None)
+ .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,
+}
+
+#[cfg(test)]
+#[path = "tiny_store_tests.rs"]
+mod tests;
diff --cc crates/openhuman-core/src/agent/artifacts/tiny_store_tests.rs
index 18871fc0bf,0000000000..d7dd2d0b57
mode 100644,000000..100644
--- a/crates/openhuman-core/src/agent/artifacts/tiny_store_tests.rs
+++ b/crates/openhuman-core/src/agent/artifacts/tiny_store_tests.rs
@@@ -1,202 -1,0 +1,202 @@@
+use std::path::PathBuf;
+
+use tiny_artifacts::{
+ ArtifactAuthor, ArtifactKind, ArtifactRecord, ArtifactStore, Author, Content,
+};
+
+use super::*;
+
+fn temp_dirs() -> (PathBuf, PathBuf) {
+ let root = std::env::temp_dir().join(format!("tiny-store-{}", uuid::Uuid::new_v4()));
+ let (workspace, files) = (root.join("workspace"), root.join("Files"));
+ std::fs::create_dir_all(&workspace).unwrap();
+ std::fs::create_dir_all(&files).unwrap();
+ (workspace, files)
+}
+
+async fn seeded(workspace: &PathBuf, _files: &PathBuf) -> FsArtifactStore {
+ let store = versioned_store(&workspace);
+ let record = ArtifactRecord::new(
+ "a-1",
+ "Notes",
+ ArtifactKind::Markdown,
+ "# v1",
+ "agent",
+ 1_000,
+ );
+ store.upsert(&record).await.unwrap();
+ store
+}
+
+#[tokio::test]
+async fn an_edit_is_appended_as_an_operator_version_and_written_to_the_file() {
+ let (workspace, files) = temp_dirs();
+ let store = seeded(&workspace, &files).await;
+
+ let saved = save_operator_version(&workspace, FileRoots::new(&files), "a-1", "# v2")
+ .await
+ .unwrap();
+ assert_eq!(
+ saved,
+ SavedVersion {
+ version: 2,
+ saved: true
+ }
+ );
+
+ let record = store.get("a-1").await.unwrap().unwrap();
+ let latest = record.latest().unwrap();
+ assert_eq!(latest.body, "# v2");
+ assert_eq!(latest.author, ArtifactAuthor::Operator);
+ assert_eq!(latest.author_id, OPERATOR_AUTHOR_ID);
+ assert!(record.human_edit_diff().is_some(), "the edit is diff-able");
+
+ // The visible file now holds the edit.
+ let written = std::fs::read_to_string(files.join("notes.md")).unwrap();
+ assert_eq!(written, "# v2");
+}
+
+#[tokio::test]
+async fn an_unchanged_body_appends_nothing() {
+ let (workspace, files) = temp_dirs();
+ let store = seeded(&workspace, &files).await;
+
+ let saved = save_operator_version(&workspace, FileRoots::new(&files), "a-1", "# v1")
+ .await
+ .unwrap();
+ assert_eq!(
+ saved,
+ SavedVersion {
+ version: 1,
+ saved: false
+ }
+ );
+ assert_eq!(store.get("a-1").await.unwrap().unwrap().versions.len(), 1);
+}
+
+#[tokio::test]
+async fn a_missing_artifact_is_an_error() {
+ let (workspace, files) = temp_dirs();
+ let err = save_operator_version(&workspace, FileRoots::new(&files), "nope", "x")
+ .await
+ .unwrap_err();
+ assert!(err.contains("not found"), "{err}");
+}
+
+#[tokio::test]
+async fn an_image_filed_through_the_service_gets_a_card_and_a_copy_in_files() {
+ let (workspace, files) = temp_dirs();
+ let action = workspace.parent().unwrap().join("projects");
+ std::fs::create_dir_all(&action).unwrap();
+ std::fs::write(action.join("chart.png"), b"png-bytes").unwrap();
- let artifacts = artifacts_service(&workspace, FileRoots::new(&files), Some(&action));
++ let artifacts = artifacts_service(&workspace, FileRoots::new(&files), Some(&action), None);
+
+ let saved = artifacts
+ .create(
+ ArtifactKind::Image,
+ "Chart",
+ Content::File("chart.png".into()),
+ &Author::agent("agent"),
+ None,
+ )
+ .await
+ .unwrap();
+ assert!(saved.notice.is_none(), "{:?}", saved.notice);
+
+ // The UI's row: ready, an image, with the file copied into Files.
+ let meta = super::super::store::get_artifact(&workspace, &saved.record.id)
+ .await
+ .unwrap();
+ assert_eq!(meta.status, super::super::types::ArtifactStatus::Ready);
+ assert_eq!(meta.kind, super::super::types::ArtifactKind::Image);
+ assert_eq!(
+ std::fs::read(files.join("chart.png")).unwrap(),
+ b"png-bytes"
+ );
+ assert_eq!(meta.size_bytes, 9);
+}
+
+#[tokio::test]
+async fn a_file_outside_the_allowed_folders_is_refused() {
+ let (workspace, files) = temp_dirs();
+ let elsewhere = workspace.parent().unwrap().join("elsewhere");
+ std::fs::create_dir_all(&elsewhere).unwrap();
+ std::fs::write(elsewhere.join("x.pdf"), b"x").unwrap();
- let artifacts = artifacts_service(&workspace, FileRoots::new(&files), None);
++ let artifacts = artifacts_service(&workspace, FileRoots::new(&files), None, None);
+ let err = artifacts
+ .create(
+ ArtifactKind::File,
+ "X",
+ Content::File(elsewhere.join("x.pdf").display().to_string()),
+ &Author::agent("agent"),
+ None,
+ )
+ .await
+ .unwrap_err();
+ assert!(err.to_string().contains("outside"), "{err}");
+}
+
+#[tokio::test]
+async fn deleting_an_artifact_removes_its_card() {
+ let (workspace, files) = temp_dirs();
- let artifacts = artifacts_service(&workspace, FileRoots::new(&files), None);
++ let artifacts = artifacts_service(&workspace, FileRoots::new(&files), None, None);
+ let saved = artifacts
+ .create(
+ ArtifactKind::Markdown,
+ "Notes",
+ Content::Text("# hi".into()),
+ &Author::agent("agent"),
+ None,
+ )
+ .await
+ .unwrap();
+ let id = saved.record.id;
+ assert!(super::super::store::get_artifact(&workspace, &id)
+ .await
+ .is_ok());
+
+ let (removed, notice) = artifacts.delete(&id).await.unwrap();
+ assert!(removed);
+ assert!(notice.is_none(), "{notice:?}");
+ assert!(super::super::store::get_artifact(&workspace, &id)
+ .await
+ .is_err());
+}
+
+struct NoopPublisher;
+
+#[async_trait::async_trait]
+impl tiny_artifacts::ArtifactPublisher for NoopPublisher {
+ async fn publish(
+ &self,
+ _record: &ArtifactRecord,
+ _version: &tiny_artifacts::ArtifactVersion,
+ options: &tiny_artifacts::PublishOptions,
+ ) -> anyhow::Result<tiny_artifacts::PublishedLink> {
+ Ok(tiny_artifacts::PublishedLink {
+ url: "https://example/x".into(),
+ expires_at_millis: None,
+ published_at_millis: 0,
+ public: options.public,
+ })
+ }
+}
+
+#[test]
+fn share_artifact_is_offered_only_with_a_publisher() {
+ let (workspace, files) = temp_dirs();
+ let names = |publisher: Option<std::sync::Arc<dyn tiny_artifacts::ArtifactPublisher>>| {
+ registered_tools(&workspace, FileRoots::new(&files), &workspace, publisher)
+ .iter()
+ .map(|t| t.name().to_string())
+ .collect::<Vec<_>>()
+ };
+ let without = names(None);
+ assert!(
+ !without.contains(&"share_artifact".to_string()),
+ "{without:?}"
+ );
+ assert!(without.contains(&"delete_artifact".to_string()));
+ let with = names(Some(std::sync::Arc::new(NoopPublisher)));
+ assert!(with.contains(&"share_artifact".to_string()), "{with:?}");
+}
diff --cc crates/openhuman-core/src/integrations/file_storage/artifact_publisher.rs
index 926d00a6b2,0000000000..aea9040e57
mode 100644,000000..100644
--- a/crates/openhuman-core/src/integrations/file_storage/artifact_publisher.rs
+++ b/crates/openhuman-core/src/integrations/file_storage/artifact_publisher.rs
@@@ -1,251 -1,0 +1,263 @@@
+//! Sharing artifacts through managed cloud file storage.
+//!
+//! [`StorageArtifactPublisher`] is OpenHuman's implementation of the
+//! `tiny-artifacts` [`ArtifactPublisher`] port: it uploads one version of an
+//! artifact through the same backend routes the `storage_*` tools use and
+//! returns its link — a private presigned link by default, the stored file's
+//! public URL when asked. The crate records the link on that version.
+//!
+//! What is uploaded is exactly the version asked for: a text version's own
+//! content (so any version can be shared), or a file version's file. The
+//! same guards as the storage tools apply: nothing is shared under read-only
+//! autonomy, and the publisher only exists when the integration client does
+//! (a backend is configured and the user is signed in).
+
+use std::path::Path;
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use serde_json::json;
+use tiny_artifacts::{
+ ArtifactKind, ArtifactPublisher, ArtifactRecord, ArtifactVersion, PublishOptions, PublishedLink,
+};
+
+use super::tools::helpers::{file_path, mime_for_path, FILES_PATH};
+use super::types::{LinkResponse, UploadResponse};
+use crate::integrations::IntegrationClient;
++use crate::security::approval::ApprovalTurnContext;
+use crate::security::SecurityPolicy;
+
+/// Lifetime of a private link when the caller does not choose: the backend's
+/// maximum, 7 days.
+const DEFAULT_LINK_SECONDS: u64 = 604_800;
+
+/// Shares artifact versions through the backend's file storage.
+pub struct StorageArtifactPublisher {
+ client: Arc<IntegrationClient>,
+ security: Arc<SecurityPolicy>,
++ /// The turn the backend requests are reported to. A publisher is built
++ /// once per tool set, not per call, so it reports outside any chat.
++ approval: ApprovalTurnContext,
+}
+
+impl StorageArtifactPublisher {
+ /// A publisher over `client`, refusing to share when `security` is
+ /// read-only.
+ pub fn new(client: Arc<IntegrationClient>, security: Arc<SecurityPolicy>) -> Self {
- Self { client, security }
++ Self {
++ client,
++ security,
++ approval: ApprovalTurnContext::default(),
++ }
+ }
+}
+
+/// The publisher for `config`, or `None` when there is no integration client
+/// (no backend URL configured, or not signed in) — the same condition under
+/// which the `storage_*` tools are absent.
+pub fn artifact_publisher(config: &crate::config::Config) -> Option<Arc<dyn ArtifactPublisher>> {
+ let client = crate::integrations::build_client(config)?;
+ let security = Arc::new(SecurityPolicy::from_config(
+ &config.autonomy,
+ &config.workspace_dir,
+ &config.action_dir,
+ ));
+ Some(Arc::new(StorageArtifactPublisher::new(client, security)))
+}
+
+/// The bytes, file name and media type a version uploads as.
+async fn upload_body(
+ record: &ArtifactRecord,
+ version: &ArtifactVersion,
+) -> anyhow::Result<(Vec<u8>, String, &'static str)> {
+ if record.holds_file() {
+ let path = version
+ .file
+ .as_ref()
+ .map_or(version.body.as_str(), |f| f.path.as_str());
+ let path = Path::new(path);
+ let bytes = tokio::fs::read(path)
+ .await
+ .map_err(|e| anyhow::anyhow!("cannot read the artifact's file: {e}"))?;
+ let name = path
+ .file_name()
+ .and_then(|n| n.to_str())
+ .unwrap_or("artifact")
+ .to_string();
+ let mime = mime_for_path(path);
+ return Ok((bytes, name, mime));
+ }
+ let ext = match record.kind {
+ ArtifactKind::Markdown => "md",
+ ArtifactKind::Html => "html",
+ _ => "txt",
+ };
+ let name = format!("{}.{ext}", file_stem(&record.title));
+ let mime = match record.kind {
+ ArtifactKind::Markdown => "text/markdown",
+ ArtifactKind::Html => "text/html",
+ _ => "text/plain",
+ };
+ Ok((version.body.clone().into_bytes(), name, mime))
+}
+
+/// A file-name stem from a title: path separators and control characters
+/// dropped, never empty.
+fn file_stem(title: &str) -> String {
+ let stem: String = title
+ .chars()
+ .filter(|c| !matches!(c, '/' | '\\' | '\0') && !c.is_control())
+ .collect::<String>()
+ .trim()
+ .trim_matches('.')
+ .to_string();
+ if stem.is_empty() {
+ "artifact".to_string()
+ } else {
+ stem
+ }
+}
+
+fn millis(rfc3339: Option<&str>) -> Option<u64> {
+ let at = chrono::DateTime::parse_from_rfc3339(rfc3339?).ok()?;
+ u64::try_from(at.timestamp_millis()).ok()
+}
+
+/// Seconds a private link should last: what was asked (7 days by default,
+/// within the backend's 60 s – 7 day range), never past the uploaded file's
+/// own expiry — a link may not outlive its file — less a minute of margin.
+pub(crate) fn link_seconds(
+ requested: Option<u64>,
+ file_expires_at_millis: Option<u64>,
+ now_millis: u64,
+) -> u64 {
+ let wanted = requested
+ .unwrap_or(DEFAULT_LINK_SECONDS)
+ .clamp(60, DEFAULT_LINK_SECONDS);
+ match file_expires_at_millis {
+ Some(expires) => {
+ let left = expires.saturating_sub(now_millis) / 1000;
+ wanted.min(left.saturating_sub(60)).max(60)
+ }
+ None => wanted,
+ }
+}
+
+impl StorageArtifactPublisher {
+ /// A presigned link for `file_id` lasting `seconds`. If the backend
+ /// rejects that lifetime, one retry asks for its default lifetime instead.
+ async fn private_link(&self, file_id: &str, seconds: u64) -> anyhow::Result<LinkResponse> {
+ let route = file_path(file_id, "/link");
+ match self
+ .client
- .post::<LinkResponse>(&route, &json!({ "expiresInSeconds": seconds }))
++ .post::<LinkResponse>(
++ &self.approval,
++ &route,
++ &json!({ "expiresInSeconds": seconds }),
++ )
+ .await
+ {
+ Ok(link) => Ok(link),
+ Err(first) => {
+ tracing::warn!(
+ file_id,
+ seconds,
+ err = %first,
+ "[file_storage] link with a set lifetime refused; retrying with the default"
+ );
+ self.client
- .post::<LinkResponse>(&route, &json!({}))
++ .post::<LinkResponse>(&self.approval, &route, &json!({}))
+ .await
+ .map_err(|e| anyhow::anyhow!("link generation failed: {e}"))
+ }
+ }
+ }
+
+ /// Delete an upload nothing points at. Best-effort.
+ async fn discard(&self, file_id: &str) {
+ if let Err(err) = self
+ .client
- .delete::<super::types::DeleteResponse>(&file_path(file_id, ""))
++ .delete::<super::types::DeleteResponse>(&self.approval, &file_path(file_id, ""))
+ .await
+ {
+ tracing::warn!(file_id, err = %err, "[file_storage] could not delete an unshared upload");
+ }
+ }
+}
+
+#[async_trait]
+impl ArtifactPublisher for StorageArtifactPublisher {
+ async fn publish(
+ &self,
+ record: &ArtifactRecord,
+ version: &ArtifactVersion,
+ options: &PublishOptions,
+ ) -> anyhow::Result<PublishedLink> {
+ if !self.security.can_act() {
+ anyhow::bail!("[policy-blocked] Action blocked: autonomy is read-only");
+ }
+ let (bytes, filename, mime) = upload_body(record, version).await?;
+ tracing::debug!(
+ artifact_id = %record.id,
+ version = version.version,
+ bytes = bytes.len(),
+ public = options.public,
+ "[file_storage] sharing artifact version"
+ );
+ let part = reqwest::multipart::Part::bytes(bytes)
+ .file_name(filename)
+ .mime_str(mime)?;
+ let visibility = if options.public { "public" } else { "private" };
+ let form = reqwest::multipart::Form::new()
+ .part("file", part)
+ .text("visibility", visibility);
+ let uploaded = self
+ .client
- .upload_multipart::<UploadResponse>(FILES_PATH, form)
++ .upload_multipart::<UploadResponse>(&self.approval, FILES_PATH, form)
+ .await
+ .map_err(|e| anyhow::anyhow!("upload failed: {e}"))?;
+
+ let link = if options.public {
+ uploaded
+ .public_url
+ .clone()
+ .map(|url| (url, uploaded.expires_at.clone()))
+ .ok_or_else(|| anyhow::anyhow!("the stored file has no public URL"))
+ } else {
+ let seconds = link_seconds(
+ options.expires_in_seconds,
+ millis(uploaded.expires_at.as_deref()),
+ tiny_artifacts::now_millis(),
+ );
+ self.private_link(&uploaded.file_id, seconds)
+ .await
+ .map(|link| (link.url, link.expires_at))
+ };
+ let (url, expires_at) = match link {
+ Ok(link) => link,
+ Err(err) => {
+ // Nothing will point at the upload: free it rather than leave
+ // a billed orphan.
+ self.discard(&uploaded.file_id).await;
+ return Err(err);
+ }
+ };
+ tracing::info!(
+ artifact_id = %record.id,
+ version = version.version,
+ file_id = %uploaded.file_id,
+ public = options.public,
+ "[file_storage] shared artifact version"
+ );
+ Ok(PublishedLink {
+ url,
+ expires_at_millis: millis(expires_at.as_deref()),
+ published_at_millis: tiny_artifacts::now_millis(),
+ public: options.public,
+ })
+ }
+}
+
+#[cfg(test)]
+#[path = "artifact_publisher_tests.rs"]
+mod tests;
diff --cc crates/openhuman-core/src/media/generation/artifact_tool.rs
index 21d41b60c8,a85e2ccc06..a3798d08c0
--- a/crates/openhuman-core/src/media/generation/artifact_tool.rs
+++ b/crates/openhuman-core/src/media/generation/artifact_tool.rs
@@@ -34,9 -36,14 +34,13 @@@ use tinytools::
ToolRunContext, ToolScope, ToolTimeout,
};
-use crate::agent::artifacts::{
- create_artifact_for_call, fail_artifact, finalize_artifact, ArtifactKind,
-};
+use crate::agent::artifacts::production::Production;
+use crate::agent::artifacts::ArtifactKind;
+ use crate::security::approval::ApprovalChatContext;
use crate::tools::host_extensions::tool_call_id;
+ use tinyagents_harness::tinyinference_video::ProgressFn;
+
+ use super::progress::{video_status_observer, JobStateSlot};
/// Maximum characters of the prompt kept in a generated artifact's title.
const TITLE_PROMPT_CHARS: usize = 60;
@@@ -49,8 -56,17 +53,16 @@@ pub struct MediaArtifactTool<T: Tool>
workspace_dir: PathBuf,
/// Visible folder each generated file is moved into (#5505).
files_dir: crate::agent::artifacts::FileRoots,
+ /// Builds the inner tool for one call around that call's poll observer.
+ /// Set for the video tool, whose `WaitPolicy::progress` hook is fixed at
+ /// construction: a tool per call lets the observer record into the call's
+ /// own [`JobStateSlot`]. `inner` still answers the static `Tool` metadata.
+ per_call: Option<PerCallInner<T>>,
}
-type PerCallInner<T> = std::sync::Arc<
- dyn Fn(ProgressFn, Option<&ApprovalChatContext>) -> T + Send + Sync,
->;
++type PerCallInner<T> =
++ std::sync::Arc<dyn Fn(ProgressFn, Option<&ApprovalChatContext>) -> T + Send + Sync>;
+
impl<T: Tool> MediaArtifactTool<T> {
/// `kind` is the artifact category to file every generated output
/// under (`ArtifactKind::Image` / `ArtifactKind::Video`); `workspace_dir`
@@@ -116,8 -146,8 +142,16 @@@
else {
continue;
};
- self.file_one(entry, &src_path, args, index, total, call_id.as_deref())
- self.file_one(entry, &src_path, args, index, total, call_id.as_deref(), chat)
-- .await;
++ self.file_one(
++ entry,
++ &src_path,
++ args,
++ index,
++ total,
++ call_id.as_deref(),
++ chat,
++ )
++ .await;
}
result
}
@@@ -151,7 -175,7 +186,8 @@@
&title,
&ext,
call_id,
+ None,
+ chat,
)
.await
{
diff --cc crates/openhuman-core/src/threads/artifact_rows.rs
index 884274d356,0000000000..48b87196a7
mode 100644,000000..100644
--- a/crates/openhuman-core/src/threads/artifact_rows.rs
+++ b/crates/openhuman-core/src/threads/artifact_rows.rs
@@@ -1,255 -1,0 +1,266 @@@
+//! Artifact rows in a thread's message log.
+//!
+//! When an artifact becomes ready in a chat, a row is appended to the thread's
+//! message log recording which turn made it: `type: "artifact"` with
+//! `extraMetadata: { artifactId, requestId }`. The UI reads the row to render
+//! the artifact's card inside that turn's reply, so a card stays with its
+//! message across refreshes, cleared client storage and other devices. The row
+//! is the only record of that placement; the UI's own artifact state is a
+//! cache.
+//!
+//! The rows are for the UI only. Every core reader of the message log goes
+//! through [`crate::threads::store::get_messages`] or its blocking twin, which
+//! drop them, so they never reach a model (title generation, memory backfill,
+//! voice context, channel adapters, edit/regenerate). Only the UI's
+//! `threads.messages_list` reads the log with them.
+//!
+//! Artifacts made before these rows existed get one on demand
+//! ([`backfill_artifact_rows`]): the turn is the first agent reply saved at or
+//! after the artifact, since a turn makes its artifacts before its reply is
+//! saved.
+
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, OnceLock};
+
+use async_trait::async_trait;
+use chrono::{DateTime, Utc};
+use serde_json::json;
+use tinybus::{EventHandler, SubscriptionHandle};
+
+use crate::agent::artifacts::types::{ArtifactMeta, ArtifactStatus};
+use crate::core::events::DomainEvent;
++use crate::core::runtime::DispatchCtx;
+use crate::threads::store::{self as conversations, ConversationMessage};
+
+/// `type` of an artifact row.
+pub const ARTIFACT_MESSAGE_TYPE: &str = "artifact";
+
+const LOG_PREFIX: &str = "[threads:artifact-rows]";
+
+/// Most artifacts a thread is backfilled for in one pass.
+const BACKFILL_LIMIT: usize = 1_000;
+
+/// The row id for an artifact. One row per artifact: a new version, a retry or
+/// a re-delivered ready event finds the row already there.
+pub fn artifact_row_id(artifact_id: &str) -> String {
+ format!("artifact:{artifact_id}")
+}
+
+/// Whether `message` is an artifact row.
+pub fn is_artifact_row(message: &ConversationMessage) -> bool {
+ message.message_type == ARTIFACT_MESSAGE_TYPE
+}
+
+/// `messages` without artifact rows: what every non-UI reader sees.
+pub fn without_artifact_rows(messages: Vec<ConversationMessage>) -> Vec<ConversationMessage> {
+ messages
+ .into_iter()
+ .filter(|message| !is_artifact_row(message))
+ .collect()
+}
+
+fn artifact_row(
+ artifact_id: &str,
+ title: &str,
+ request_id: Option<&str>,
+ created_at: String,
+) -> ConversationMessage {
+ let mut extra_metadata = json!({ "artifactId": artifact_id });
+ if let Some(request_id) = request_id {
+ extra_metadata["requestId"] = json!(request_id);
+ }
+ ConversationMessage {
+ id: artifact_row_id(artifact_id),
+ content: title.to_string(),
+ message_type: ARTIFACT_MESSAGE_TYPE.to_string(),
+ extra_metadata,
+ sender: "agent".to_string(),
+ created_at,
+ }
+}
+
+/// Append the row for `artifact_id` unless the thread already has it. Returns
+/// whether a row was written.
+pub async fn record_artifact_row(
++ ctx: &DispatchCtx,
+ workspace_dir: PathBuf,
+ thread_id: &str,
+ artifact_id: &str,
+ title: &str,
+ request_id: Option<&str>,
+) -> Result<bool, String> {
- let messages =
- conversations::blocking::get_messages_with_artifact_rows(workspace_dir.clone(), thread_id)
- .await?;
++ let messages = conversations::blocking::get_messages_with_artifact_rows(
++ ctx.clone(),
++ workspace_dir.clone(),
++ thread_id,
++ )
++ .await?;
+ let row_id = artifact_row_id(artifact_id);
+ if messages.iter().any(|message| message.id == row_id) {
+ return Ok(false);
+ }
+ let row = artifact_row(artifact_id, title, request_id, Utc::now().to_rfc3339());
- conversations::blocking::append_message(workspace_dir, thread_id.to_string(), row).await?;
++ conversations::blocking::append_message(ctx.clone(), workspace_dir, thread_id.to_string(), row)
++ .await?;
+ log::debug!(
+ "{LOG_PREFIX} recorded artifact_id={artifact_id} thread_id={thread_id} request_id={request_id:?}"
+ );
+ Ok(true)
+}
+
+fn parse_time(raw: &str) -> Option<DateTime<Utc>> {
+ DateTime::parse_from_rfc3339(raw)
+ .ok()
+ .map(|time| time.with_timezone(&Utc))
+}
+
+/// The turn that made an artifact created at `created_at`: the first agent
+/// reply saved at or after it. `None` when the artifact is newer than every
+/// reply (its turn has not saved one).
+fn owning_request_id(
+ messages: &[ConversationMessage],
+ created_at: DateTime<Utc>,
+) -> Option<String> {
+ messages
+ .iter()
+ .filter(|message| message.sender == "agent" && !is_artifact_row(message))
+ .filter_map(|message| {
+ let request_id = message.extra_metadata.get("requestId")?.as_str()?;
+ Some((parse_time(&message.created_at)?, request_id))
+ })
+ .filter(|(saved_at, _)| *saved_at >= created_at)
+ .min_by_key(|(saved_at, _)| *saved_at)
+ .map(|(_, request_id)| request_id.to_string())
+}
+
+/// Rows for `artifacts` the thread has none for, in creation order. Only ready
+/// artifacts without a tool call get one: a tool call's artifact renders with
+/// its tool call.
+pub(crate) fn missing_rows(
+ messages: &[ConversationMessage],
+ artifacts: &[ArtifactMeta],
+) -> Vec<ConversationMessage> {
+ let mut missing: Vec<&ArtifactMeta> = artifacts
+ .iter()
+ .filter(|artifact| artifact.status == ArtifactStatus::Ready)
+ .filter(|artifact| artifact.tool_call_id.is_none())
+ .filter(|artifact| {
+ let row_id = artifact_row_id(&artifact.id);
+ !messages.iter().any(|message| message.id == row_id)
+ })
+ .collect();
+ missing.sort_by_key(|artifact| artifact.created_at);
+ missing
+ .into_iter()
+ .map(|artifact| {
+ let request_id = owning_request_id(messages, artifact.created_at);
+ artifact_row(
+ &artifact.id,
+ &artifact.title,
+ request_id.as_deref(),
+ artifact.created_at.to_rfc3339(),
+ )
+ })
+ .collect()
+}
+
+/// Write rows for the thread's artifacts that have none (made before these
+/// rows existed, or whose row write failed), given the thread's full message
+/// log. Returns the rows written.
+pub async fn backfill_artifact_rows(
++ ctx: &DispatchCtx,
+ workspace_dir: &Path,
+ thread_id: &str,
+ messages: &[ConversationMessage],
+) -> Result<Vec<ConversationMessage>, String> {
+ let (artifacts, _) = crate::agent::artifacts::store::list_artifacts(
+ workspace_dir,
+ 0,
+ BACKFILL_LIMIT,
+ Some(thread_id),
+ )
+ .await?;
+ let mut written = Vec::new();
+ for row in missing_rows(messages, &artifacts) {
+ let stored = conversations::blocking::append_message(
++ ctx.clone(),
+ workspace_dir.to_path_buf(),
+ thread_id.to_string(),
+ row,
+ )
+ .await?;
+ written.push(stored);
+ }
+ if !written.is_empty() {
+ log::info!(
+ "{LOG_PREFIX} backfilled {} artifact row(s) thread_id={thread_id}",
+ written.len()
+ );
+ }
+ Ok(written)
+}
+
+/// Writes an artifact's row when it becomes ready in a chat.
+struct ArtifactRowSubscriber;
+
+#[async_trait]
+impl EventHandler<DomainEvent> for ArtifactRowSubscriber {
+ fn name(&self) -> &str {
+ "threads::artifact_rows"
+ }
+
+ fn domains(&self) -> Option<&[&str]> {
+ Some(&["artifact"])
+ }
+
+ async fn handle(&self, event: &DomainEvent) {
+ let DomainEvent::ArtifactReady {
+ artifact_id,
+ title,
+ workspace_dir,
+ thread_id: Some(thread_id),
+ tool_call_id: None,
+ request_id,
+ ..
+ } = event
+ else {
+ return;
+ };
++ // A bus event carries no context of its own (see
++ // `DispatchCtx::host_default`).
+ if let Err(error) = record_artifact_row(
++ &DispatchCtx::host_default(),
+ PathBuf::from(workspace_dir),
+ thread_id,
+ artifact_id,
+ title,
+ request_id.as_deref(),
+ )
+ .await
+ {
+ log::warn!(
+ "{LOG_PREFIX} row write failed artifact_id={artifact_id} thread_id={thread_id}: {error}"
+ );
+ }
+ }
+}
+
+static ARTIFACT_ROW_HANDLE: OnceLock<SubscriptionHandle> = OnceLock::new();
+
+/// Register the subscriber that writes artifact rows. Idempotent.
+pub fn register_artifact_row_subscriber() {
+ if ARTIFACT_ROW_HANDLE.get().is_some() {
+ return;
+ }
+ match crate::core::bus::BUS.subscribe(Arc::new(ArtifactRowSubscriber)) {
+ Some(handle) => {
+ let _ = ARTIFACT_ROW_HANDLE.set(handle);
+ log::info!("{LOG_PREFIX} subscriber registered (domain=artifact)");
+ }
+ None => log::warn!("{LOG_PREFIX} failed to register subscriber — bus not initialized"),
+ }
+}
+
+#[cfg(test)]
+#[path = "artifact_rows_tests.rs"]
+mod tests;
diff --cc crates/openhuman-core/src/threads/artifact_rows_tests.rs
index 383845070e,0000000000..6fca3fedef
mode 100644,000000..100644
--- a/crates/openhuman-core/src/threads/artifact_rows_tests.rs
+++ b/crates/openhuman-core/src/threads/artifact_rows_tests.rs
@@@ -1,162 -1,0 +1,186 @@@
+use std::path::{Path, PathBuf};
+
+use chrono::{DateTime, TimeZone, Utc};
+use serde_json::json;
+
+use super::*;
+use crate::agent::artifacts::types::{ArtifactKind, ArtifactMeta, ArtifactStatus};
++use crate::core::runtime::DispatchCtx;
+use crate::threads::store::{self as conversations, CreateConversationThread};
+
+fn temp_ws() -> PathBuf {
+ let dir = std::env::temp_dir().join(format!("artifact-rows-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ dir
+}
+
+fn seed_thread(ws: &Path, thread_id: &str) {
+ conversations::ensure_thread(
++ &DispatchCtx::unbound(),
+ ws.to_path_buf(),
+ CreateConversationThread {
+ id: thread_id.to_string(),
+ title: "Chat".to_string(),
+ created_at: Utc::now().to_rfc3339(),
+ parent_thread_id: None,
+ labels: None,
+ personality_id: None,
+ working_dir: None,
+ },
+ )
+ .expect("thread created");
+}
+
+fn at(secs: i64) -> DateTime<Utc> {
+ Utc.timestamp_opt(1_800_000_000 + secs, 0).unwrap()
+}
+
+fn reply(request_id: &str, secs: i64) -> ConversationMessage {
+ ConversationMessage {
+ id: format!("agent:{request_id}"),
+ content: "Done.".to_string(),
+ message_type: "text".to_string(),
+ extra_metadata: json!({ "scope": "web_chat_reply", "requestId": request_id }),
+ sender: "agent".to_string(),
+ created_at: at(secs).to_rfc3339(),
+ }
+}
+
+fn artifact(id: &str, secs: i64) -> ArtifactMeta {
+ ArtifactMeta {
+ id: id.to_string(),
+ kind: ArtifactKind::Document,
+ title: format!("Title {id}"),
+ path: format!("{id}.md"),
+ file: None,
+ file_root: None,
+ size_bytes: 12,
+ status: ArtifactStatus::Ready,
+ created_at: at(secs),
+ error: None,
+ thread_id: Some("t-1".to_string()),
+ tool_call_id: None,
+ }
+}
+
+fn row_request_id(row: &ConversationMessage) -> Option<&str> {
+ row.extra_metadata.get("requestId").and_then(|v| v.as_str())
+}
+
+#[test]
+fn backfilled_rows_take_the_turn_of_the_first_reply_after_the_artifact() {
+ let messages = vec![reply("req-1", 10), reply("req-2", 20)];
+ let rows = missing_rows(&messages, &[artifact("b", 15), artifact("a", 5)]);
+
+ // Creation order, each with its own turn.
+ let ids: Vec<&str> = rows.iter().map(|row| row.id.as_str()).collect();
+ assert_eq!(ids, ["artifact:a", "artifact:b"]);
+ assert_eq!(row_request_id(&rows[0]), Some("req-1"));
+ assert_eq!(row_request_id(&rows[1]), Some("req-2"));
+ assert!(rows.iter().all(is_artifact_row));
+}
+
+#[test]
+fn an_artifact_newer_than_every_reply_gets_a_row_without_a_turn() {
+ let rows = missing_rows(&[reply("req-1", 10)], &[artifact("a", 30)]);
+ assert_eq!(rows.len(), 1);
+ assert_eq!(row_request_id(&rows[0]), None);
+}
+
+#[test]
+fn no_row_for_existing_rows_tool_calls_or_unfinished_artifacts() {
+ let existing = artifact_row("a", "A", Some("req-1"), at(5).to_rfc3339());
+ let mut tool = artifact("tool", 5);
+ tool.tool_call_id = Some("call-1".to_string());
+ let mut pending = artifact("pending", 5);
+ pending.status = ArtifactStatus::Pending;
+
+ let rows = missing_rows(
+ &[reply("req-1", 10), existing],
+ &[artifact("a", 5), tool, pending],
+ );
+ assert!(rows.is_empty(), "unexpected rows: {rows:?}");
+}
+
+#[test]
+fn readers_never_see_artifact_rows_but_the_ui_list_does() {
+ let ws = temp_ws();
+ seed_thread(&ws, "t-1");
- conversations::append_message(ws.clone(), "t-1", reply("req-1", 10)).unwrap();
+ conversations::append_message(
++ &DispatchCtx::unbound(),
++ ws.clone(),
++ "t-1",
++ reply("req-1", 10),
++ )
++ .unwrap();
++ conversations::append_message(
++ &DispatchCtx::unbound(),
+ ws.clone(),
+ "t-1",
+ artifact_row("a", "A", Some("req-1"), at(5).to_rfc3339()),
+ )
+ .unwrap();
+
- let model_facing = conversations::get_messages(ws.clone(), "t-1").unwrap();
++ let model_facing =
++ conversations::get_messages(&DispatchCtx::unbound(), ws.clone(), "t-1").unwrap();
+ assert_eq!(model_facing.len(), 1);
+ assert!(!model_facing.iter().any(is_artifact_row));
+
+ let runtime = tokio::runtime::Runtime::new().unwrap();
+ let blocking = runtime
+ .block_on(conversations::blocking::get_messages(
++ DispatchCtx::unbound(),
+ ws.clone(),
+ "t-1".to_string(),
+ ))
+ .unwrap();
+ assert!(!blocking.iter().any(is_artifact_row));
+ let ui = runtime
+ .block_on(conversations::blocking::get_messages_with_artifact_rows(
- ws, "t-1",
++ DispatchCtx::unbound(),
++ ws,
++ "t-1",
+ ))
+ .unwrap();
+ assert_eq!(ui.iter().filter(|m| is_artifact_row(m)).count(), 1);
+}
+
+#[tokio::test]
+async fn recording_an_artifact_twice_writes_one_row() {
+ let ws = temp_ws();
+ seed_thread(&ws, "t-1");
+
- assert!(
- record_artifact_row(ws.clone(), "t-1", "a", "A", Some("req-1"))
- .await
- .unwrap()
- );
++ assert!(record_artifact_row(
++ &DispatchCtx::unbound(),
++ ws.clone(),
++ "t-1",
++ "a",
++ "A",
++ Some("req-1")
++ )
++ .await
++ .unwrap());
+ // A new version, a retry or a re-delivered ready event.
- assert!(
- !record_artifact_row(ws.clone(), "t-1", "a", "A v2", Some("req-2"))
++ assert!(!record_artifact_row(
++ &DispatchCtx::unbound(),
++ ws.clone(),
++ "t-1",
++ "a",
++ "A v2",
++ Some("req-2")
++ )
++ .await
++ .unwrap());
++
++ let rows: Vec<_> =
++ conversations::blocking::get_messages_with_artifact_rows(DispatchCtx::unbound(), ws, "t-1")
+ .await
+ .unwrap()
- );
-
- let rows: Vec<_> = conversations::blocking::get_messages_with_artifact_rows(ws, "t-1")
- .await
- .unwrap()
- .into_iter()
- .filter(is_artifact_row)
- .collect();
++ .into_iter()
++ .filter(is_artifact_row)
++ .collect();
+ assert_eq!(rows.len(), 1);
+ assert_eq!(rows[0].id, "artifact:a");
+ assert_eq!(row_request_id(&rows[0]), Some("req-1"));
+ assert_eq!(rows[0].extra_metadata["artifactId"], "a");
+}
diff --cc crates/openhuman-core/src/threads/mod.rs
index bbaacaab77,78fb738641..1adea2380c
--- a/crates/openhuman-core/src/threads/mod.rs
+++ b/crates/openhuman-core/src/threads/mod.rs
@@@ -1,10 -1,9 +1,10 @@@
//! Conversation thread and message management.
//!
//! Thread lifecycle (create, list, delete, purge) and per-thread message
- //! CRUD. Storage is [`store`] (JSONL files over `tinyagents_session::threads`);
+ //! CRUD. Storage is [`store`] (the storage backend, through `tinyagents_session::threads`);
//! this module owns the RPC surface and controller registry.
+pub mod artifact_rows;
pub mod error;
pub mod ops;
pub mod rpc_models;
diff --cc crates/openhuman-core/src/threads/ops/crud.rs
index d1a9e099af,55e613dbc7..3745f2f5ea
--- a/crates/openhuman-core/src/threads/ops/crud.rs
+++ b/crates/openhuman-core/src/threads/ops/crud.rs
@@@ -102,31 -108,18 +108,40 @@@ pub async fn thread_create_new
))
}
-/// Lists messages for a conversation thread.
+/// Lists messages for a conversation thread, artifact rows included: the UI
+/// renders each artifact's card from its row (see
+/// [`crate::threads::artifact_rows`]). Artifacts that have no row yet get one
+/// first, so a thread's older artifacts are placed too.
pub async fn messages_list(
+ ctx: &DispatchCtx,
request: ConversationMessagesRequest,
) -> Result<Outcome<ApiEnvelope<ConversationMessagesResponse>>, String> {
let dir = workspace_dir().await?;
- let mut messages =
- conversations::blocking::get_messages_with_artifact_rows(dir.clone(), &request.thread_id)
- .await?;
- match crate::threads::artifact_rows::backfill_artifact_rows(&dir, &request.thread_id, &messages)
- .await
- let messages =
- conversations::blocking::get_messages(ctx.clone(), dir, request.thread_id.clone())
- .await?
- .into_iter()
- .map(message_to_record)
- .collect::<Vec<_>>();
++ let mut messages = conversations::blocking::get_messages_with_artifact_rows(
++ ctx.clone(),
++ dir.clone(),
++ &request.thread_id,
++ )
++ .await?;
++ match crate::threads::artifact_rows::backfill_artifact_rows(
++ ctx,
++ &dir,
++ &request.thread_id,
++ &messages,
++ )
++ .await
+ {
+ Ok(written) => messages.extend(written),
+ // The list still serves; the rows are retried on the next read.
+ Err(error) => log::warn!(
+ "[threads] artifact row backfill failed thread_id={}: {error}",
+ request.thread_id
+ ),
+ }
+ let messages = messages
+ .into_iter()
+ .map(message_to_record)
+ .collect::<Vec<_>>();
let count = messages.len();
Ok(envelope(
ConversationMessagesResponse { messages, count },
diff --cc crates/openhuman-core/src/threads/store/blocking.rs
index 27ee528413,b9ddf290b7..2210e68db7
--- a/crates/openhuman-core/src/threads/store/blocking.rs
+++ b/crates/openhuman-core/src/threads/store/blocking.rs
@@@ -96,32 -98,24 +98,41 @@@ pub async fn ensure_thread
}
/// [`store::list_threads`] on the blocking pool.
- pub async fn list_threads(workspace_dir: PathBuf) -> Result<Vec<ConversationThread>, String> {
- run("list_threads", move || store::list_threads(workspace_dir)).await
+ pub async fn list_threads(
+ ctx: DispatchCtx,
+ workspace_dir: PathBuf,
+ ) -> Result<Vec<ConversationThread>, String> {
+ run("list_threads", move || {
+ store::list_threads(&ctx, workspace_dir)
+ })
+ .await
}
-/// [`store::get_messages`] on the blocking pool.
+/// [`super::get_messages`] on the blocking pool: the thread's messages without
+/// artifact rows (see [`crate::threads::artifact_rows`]).
pub async fn get_messages(
+ ctx: DispatchCtx,
workspace_dir: PathBuf,
thread_id: String,
) -> Result<Vec<ConversationMessage>, String> {
run("get_messages", move || {
- super::get_messages(workspace_dir, &thread_id)
- store::get_messages(&ctx, workspace_dir, &thread_id)
++ super::get_messages(&ctx, workspace_dir, &thread_id)
+ })
+ .await
+}
+
- /// [`store::get_messages`] on the blocking pool, artifact rows included. Only
++/// [`super::backend::get_messages`] on the blocking pool, artifact rows included. Only
+/// for the UI's message list and the artifact-row writers.
+pub async fn get_messages_with_artifact_rows(
++ ctx: DispatchCtx,
+ workspace_dir: PathBuf,
+ thread_id: &str,
+) -> Result<Vec<ConversationMessage>, String> {
+ let thread_id = thread_id.to_string();
- // The vendored store directly: `store::get_messages` is the filtered one.
++ // The backend's read keeps every row; `super::get_messages` (and
++ // `store::get_messages`) drop the artifact rows.
+ run("get_messages_with_artifact_rows", move || {
- tinyagents_session::threads::get_messages(workspace_dir, &thread_id)
++ super::backend::get_messages(&ctx, workspace_dir, &thread_id)
})
.await
}
diff --cc crates/openhuman-core/src/threads/store/mod.rs
index 18e50607e0,d63aec580d..f59c52671b
--- a/crates/openhuman-core/src/threads/store/mod.rs
+++ b/crates/openhuman-core/src/threads/store/mod.rs
@@@ -29,29 -32,48 +32,61 @@@ pub mod backend
pub mod blocking;
mod bus;
- use tinyagents_session::threads as store;
+ mod legacy_import;
-mod transcript_key;
+ #[cfg(test)]
+ #[path = "legacy_import_tests.rs"]
+ mod legacy_import_tests;
++mod transcript_key;
+
+ use backend as store;
+ use tinyagents_session::threads as types;
+
+ /// Counts returned when the host purges stored conversations.
+ ///
+ /// This keeps the host-facing store contract independent of the underlying
+ /// session-store crate's concrete return type.
+ #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+ pub struct ConversationPurgeStats {
+ /// Number of conversations removed.
+ pub thread_count: usize,
+ /// Number of messages removed across those conversations.
+ pub message_count: usize,
+ }
+
+ impl From<types::ConversationPurgeStats> for ConversationPurgeStats {
+ fn from(stats: types::ConversationPurgeStats) -> Self {
+ Self {
+ thread_count: stats.thread_count,
+ message_count: stats.message_count,
+ }
+ }
+ }
// Only the hosted-channel relay (`channels`) claims turns.
#[cfg(feature = "channels")]
pub(crate) use bus::claim_channel_turn;
pub use bus::register_conversation_persistence_subscriber;
-pub(crate) use transcript_key::bind_transcript_key;
pub use store::{
- append_message, delete_messages_from, delete_thread, ensure_thread,
- is_deterministic_message_id, list_threads, purge_threads, reply_run_id, run_reply_message_id,
- update_message, update_thread_labels, update_thread_title, update_thread_working_dir,
- ConversationPurgeStats, ConversationStore, ConversationThread, CreateConversationThread,
- CrossThreadHit, ThreadMessage as ConversationMessage,
- append_message, delete_messages_from, delete_thread, ensure_thread, get_messages, list_threads,
++ append_message, delete_messages_from, delete_thread, ensure_thread, list_threads,
+ purge_threads, update_message, update_thread_labels, update_thread_title,
+ update_thread_working_dir, ConversationStore,
+ };
++pub(crate) use transcript_key::bind_transcript_key;
+ pub use types::{
+ is_deterministic_message_id, reply_run_id, run_reply_message_id, ConversationThread,
+ CreateConversationThread, CrossThreadHit, ThreadMessage as ConversationMessage,
ThreadMessagePatch as ConversationMessagePatch,
};
+
+/// A thread's messages without artifact rows. Artifact rows place artifact
+/// cards in the UI and must never reach a model, so this is what every core
+/// reader uses; only the UI's message list reads them
+/// ([`blocking::get_messages_with_artifact_rows`]).
+pub fn get_messages(
++ ctx: &crate::core::runtime::DispatchCtx,
+ workspace_dir: std::path::PathBuf,
+ thread_id: &str,
+) -> Result<Vec<ConversationMessage>, String> {
- store::get_messages(workspace_dir, thread_id)
++ store::get_messages(ctx, workspace_dir, thread_id)
+ .map(crate::threads::artifact_rows::without_artifact_rows)
+}
diff --cc crates/openhuman-core/src/tools/impl/document/mod.rs
index d2a674dcfc,ed3b09ceb3..6ef7b66061
--- a/crates/openhuman-core/src/tools/impl/document/mod.rs
+++ b/crates/openhuman-core/src/tools/impl/document/mod.rs
@@@ -198,21 -194,29 +198,43 @@@ impl Tool for DocumentTool
}
async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
+ self.run(args, None).await
+ }
+
+ async fn execute_with_context(
+ &self,
+ args: Value,
+ _options: tinytools::ToolCallOptions,
+ context: Option<&dyn tinytools::ToolRunContext>,
+ ) -> anyhow::Result<ToolResult> {
+ let approval = crate::agent::tinyagents::host::run_context::approval_for_tool(context);
+ self.run(args, approval.chat.as_ref()).await
+ }
+ }
+
+ impl DocumentTool {
+ /// Produces the artifact for a turn whose chat routing is `chat` (`None`
+ /// outside a chat turn).
+ pub(crate) async fn run(
+ &self,
+ args: Value,
+ chat: Option<&crate::security::approval::ApprovalChatContext>,
+ ) -> anyhow::Result<ToolResult> {
- let input: GenerateDocumentInput = match serde_json::from_value(args.clone()) {
+ // The document wire contract is `deny_unknown_fields`, so the optional
+ // `artifact_id` is read here (and stripped from the args before
+ // deserialisation) rather than deserialised into
+ // `GenerateDocumentInput` (Phase 2d).
+ let artifact_id = args
+ .get("artifact_id")
+ .and_then(serde_json::Value::as_str)
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .map(str::to_string);
+ let mut spec_args = args.clone();
+ if let Some(obj) = spec_args.as_object_mut() {
+ obj.remove("artifact_id");
+ }
+ let input: GenerateDocumentInput = match serde_json::from_value(spec_args) {
Ok(v) => v,
Err(err) => {
let msg = format!("invalid generate_document arguments: {err}");
@@@ -234,16 -238,13 +256,17 @@@
"[document] generation request accepted"
);
- let (meta, output_path) = create_artifact(
+ // Reserve the file and open the artifact: a new one, or a new version
+ // of `artifact_id` (same id, same file, history kept).
+ let production = Production::start(
&self.workspace_dir,
- &self.files_dir,
- ArtifactKind::Document,
+ self.files_dir.clone(),
+ tiny_artifacts::ArtifactKind::File,
&input.title,
"docx",
+ None,
+ artifact_id.as_deref(),
+ chat,
)
.await
.map_err(anyhow::Error::msg)?;
diff --cc crates/openhuman-core/src/tools/impl/presentation/mod.rs
index 002ac7b2cf,1579019a01..e5db47f616
--- a/crates/openhuman-core/src/tools/impl/presentation/mod.rs
+++ b/crates/openhuman-core/src/tools/impl/presentation/mod.rs
@@@ -322,7 -363,8 +367,11 @@@ impl PresentationTool
&input.title,
"pptx",
None,
- input.artifact_id.as_deref(),
- self.regenerate_target.as_deref(),
++ input
++ .artifact_id
++ .as_deref()
++ .or(self.regenerate_target.as_deref()),
+ chat,
)
.await
.map_err(anyhow::Error::msg)?;
diff --cc scripts/ci/process-statics.json
index bdea1d2a6f,982386fe6d..1765d5b551
--- a/scripts/ci/process-statics.json
+++ b/scripts/ci/process-statics.json
@@@ -26,7 -36,97 +36,107 @@@
"type": "std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<String,std::sync::Arc<tokio::sync::Mutex<()>>>>, >",
"count": 1,
"category": "B",
- "reason": "Holds only unit mutexes. The key is the workspace directory plus the acting memory identity, so different scopes never share or wait on a lock and no tenant data is stored.",
+ "reason": "Holds only unit mutexes. The key is the workspace directory, so different workspaces never share or wait on a lock and no tenant data is stored.",
"verification": "tinymemes/service_tests.rs: foreground_remixes_share_a_lock_per_workspace_and_never_across_workspaces"
+ },
+ {
+ "file": "crates/openhuman-core/src/modules/runtime.rs",
+ "scope": "",
+ "name": "RUNTIME",
+ "type": "OnceLock<Result<ModuleRuntime,String>>",
+ "count": 1,
+ "category": "A",
+ "reason": "The single tinybus module bus (broker, loader, connection) for the process; tinybus never unloads a module, so there is exactly one. Carries no tenant data: tenant scope is resolved per call by the host callbacks it serves.",
+ "verification": "modules/runtime_tests.rs: the_module_bus_is_a_singleton_and_serves_proxies"
+ },
+ {
+ "file": "crates/openhuman-core/src/modules/runtime.rs",
+ "scope": "",
+ "name": "CALLBACKS",
+ "type": "tokio::sync::OnceCell<Result<(),String>>",
+ "count": 1,
+ "category": "A",
+ "reason": "Records that the host callback objects were served on the module bus once, before any module loads; infrastructure only.",
+ "verification": "modules/runtime_tests.rs: wallet_host_callback_is_served_before_the_module_is_loaded"
+ },
+ {
+ "file": "crates/openhuman-core/src/modules/report.rs",
+ "scope": "",
+ "name": "REPORTER",
+ "type": "OnceLock<Arc<FailureReporter>>",
+ "count": 1,
+ "category": "A",
+ "reason": "Deduplicates terminal module outcomes per (module id, reason) so a broken install is one Sentry event per process; keys are registry ids only and no tenant data is held.",
+ "verification": "modules/report_tests.rs: terminal_reports_are_sanitized_and_deduplicated"
+ },
+ {
+ "file": "crates/openhuman-core/src/modules/registry.rs",
+ "scope": "",
+ "name": "TABLE",
+ "type": "std::sync::OnceLock<Vec<tinybus::module::ReleaseRecord>>",
+ "count": 1,
+ "category": "A",
+ "reason": "The compiled module registry in the shape the tinybus resolver consumes; constants only.",
+ "verification": "modules/ops_tests.rs: list_reports_every_registry_entry"
+ },
+ {
+ "file": "crates/openhuman-core/src/modules/ops.rs",
+ "scope": "",
+ "name": "LOGGED",
+ "type": "OnceLock<Mutex<std::collections::HashSet<&'static str>>>",
+ "count": 1,
+ "category": "A",
+ "reason": "Registry ids whose serving source was already logged, so each is logged once; holds static ids only.",
+ "verification": "modules/ops_tests.rs: status_reports_the_source_that_serves_a_module"
+ },
+ {
+ "file": "crates/openhuman-core/src/web_chat/ops/test_hooks.rs",
+ "scope": "",
+ "name": "TEST_PARK_AFTER_RUN",
+ "type": "std::sync::atomic::AtomicBool",
+ "count": 1,
+ "category": "A",
+ "reason": "A debug/test-only hook flag (`cfg(any(test, debug_assertions))`) that parks `run_chat_task` after its run so the idle guard can be exercised end to end; it holds no tenant data and is off unless a test sets it.",
+ "verification": "tests/agent_harness_e2e.rs: idle_guard_local::stalled_turn_is_stopped_by_the_idle_guard_and_closed_with_a_summary"
+ },
+ {
+ "file": "crates/openhuman-core/src/modules/connectors.rs",
+ "scope": "",
+ "name": "ROUTE_TURN",
+ "type": "tokio::sync::Mutex<()>",
+ "count": 1,
+ "category": "A",
+ "reason": "Test-only (cfg(test)): serializes each TinyConnectors call with the route it sets, because libtest runs a crate's tests in one process and the module's route is process-global; it guards no data and carries no tenant state.",
+ "verification": "flows/tinyflows/caps/tools/composio_tests.rs: backend_dispatch_forwards_the_workflow_connection_id"
+ },
+ {
+ "file": "crates/openhuman-core/src/agent/session_store/mod.rs",
+ "scope": "",
+ "name": "OPEN_WORKSPACE_STORES",
+ "type": "LazyLock<Mutex<HashMap<(std::path::PathBuf,String),tinyagents_session::port::WorkspaceStores>>, >",
+ "count": 1,
+ "category": "D",
+ "reason": "Holds open the workspace transcript stores used when no host session store is installed. Each entry is a handle to the SQLite store under one workspace, keyed by that workspace and the session store key (agent_key_for: <profile>~<agent> for a SaaS profile), so two profiles or agents never share an entry; the store under the workspace is the authoritative data. release_workspace_defaults drops them all for a data reset, release_workspace those of one workspace.",
+ "verification": "threads/ops/edit_tests.rs: a_profile_prefixed_key_round_trips_through_edit_and_regenerate; agent/session_store/mod_tests.rs: without_a_store_transcripts_come_from_the_workspace_store_not_files"
+ },
+ {
+ "file": "crates/openhuman-core/src/agent/session_store/rebound.rs",
+ "scope": "",
+ "name": "PROCESS",
+ "type": "LazyLock<StoreRegistry>",
+ "count": 1,
+ "category": "A",
+ "reason": "The process's registry of weak handles to the rebindable session-store providers a host installed, so a workspace switch (storage::rebind) can point each at the new backend. It holds no records and no tenant state, only Weak references; the stores' data lives in the storage backend. A test builds its own StoreRegistry, so rebinding one never moves another's stores.",
+ "verification": "agent/session_store/rebound_tests.rs: a_registry_rebind_leaves_other_registries_alone"
++ },
++ {
++ "file": "crates/openhuman-core/src/threads/artifact_rows.rs",
++ "scope": "",
++ "name": "ARTIFACT_ROW_HANDLE",
++ "type": "OnceLock<SubscriptionHandle>",
++ "count": 1,
++ "category": "A",
++ "reason": "Keeps the one process-wide event-bus subscription that writes artifact rows alive and makes registration idempotent; it holds no data, and each event names the workspace and thread its row is written to.",
++ "verification": "threads/artifact_rows_tests.rs: recording_an_artifact_twice_writes_one_row"
}
]