Skip to content

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

feat(artifacts): write agent deliverables to a visible Files folder

M3gA-Minde37caa11a219
diff --git a/app/src/services/__tests__/artifactDownloadService.test.ts b/app/src/services/__tests__/artifactDownloadService.test.ts
index 7412388885..cbf9f62a75 100644
--- a/app/src/services/__tests__/artifactDownloadService.test.ts
+++ b/app/src/services/__tests__/artifactDownloadService.test.ts
@@ -234,7 +234,7 @@ describe('downloadArtifact', () => {
const outcome = await downloadArtifact('art-1', 'fallback-title', 'pptx');
expect(outcome).toEqual({ ok: true, path: '/Users/me/Downloads/climate-deck.pptx' });
expect(hoisted.invoke).toHaveBeenCalledWith('download_artifact_to_downloads', {
- sourcePath: '/workspace/artifacts/art-1/deck.pptx',
+ artifactId: 'art-1',
filename: 'climate-deck.pptx',
});
});
@@ -247,7 +247,7 @@ describe('downloadArtifact', () => {
hoisted.invoke.mockResolvedValueOnce('/dest/file.pdf');
await downloadArtifact('art-1', 'caller-fallback', 'pdf');
expect(hoisted.invoke).toHaveBeenCalledWith('download_artifact_to_downloads', {
- sourcePath: '/p/file',
+ artifactId: 'art-1',
filename: 'caller-fallback.pdf',
});
});
@@ -257,7 +257,7 @@ describe('downloadArtifact', () => {
hoisted.invoke.mockResolvedValueOnce('/dest/x');
await downloadArtifact('art-1', ' ', 'bin');
expect(hoisted.invoke).toHaveBeenCalledWith('download_artifact_to_downloads', {
- sourcePath: '/p/file',
+ artifactId: 'art-1',
filename: 'artifact.bin',
});
});
@@ -270,7 +270,7 @@ describe('downloadArtifact', () => {
hoisted.invoke.mockResolvedValueOnce('/dest/deck.pptx');
await downloadArtifact('art-1', 'deck', '...pptx');
expect(hoisted.invoke).toHaveBeenCalledWith('download_artifact_to_downloads', {
- sourcePath: '/p/file',
+ artifactId: 'art-1',
filename: 'deck.pptx',
});
});
@@ -283,7 +283,7 @@ describe('downloadArtifact', () => {
hoisted.invoke.mockResolvedValueOnce('/dest/deck.pptx');
await downloadArtifact('art-1', 'deck.pptx', 'pptx');
expect(hoisted.invoke).toHaveBeenCalledWith('download_artifact_to_downloads', {
- sourcePath: '/p/file',
+ artifactId: 'art-1',
filename: 'deck.pptx',
});
});
@@ -296,7 +296,7 @@ describe('downloadArtifact', () => {
hoisted.invoke.mockResolvedValueOnce('/dest/x');
await downloadArtifact('art-1', 'DECK.PPTX', 'pptx');
expect(hoisted.invoke).toHaveBeenCalledWith('download_artifact_to_downloads', {
- sourcePath: '/p/file',
+ artifactId: 'art-1',
filename: 'DECK.PPTX',
});
});
@@ -311,7 +311,7 @@ describe('downloadArtifact', () => {
hoisted.invoke.mockResolvedValueOnce('/dest/x');
await downloadArtifact('art-1', 'deck.pdf', 'pptx');
expect(hoisted.invoke).toHaveBeenCalledWith('download_artifact_to_downloads', {
- sourcePath: '/p/file',
+ artifactId: 'art-1',
filename: 'deck.pdf',
});
});
@@ -324,7 +324,7 @@ describe('downloadArtifact', () => {
hoisted.invoke.mockResolvedValueOnce('/dest/climate-overview.pptx');
await downloadArtifact('art-1', 'climate-overview', 'pptx');
expect(hoisted.invoke).toHaveBeenCalledWith('download_artifact_to_downloads', {
- sourcePath: '/p/file',
+ artifactId: 'art-1',
filename: 'climate-overview.pptx',
});
});
@@ -337,7 +337,7 @@ describe('downloadArtifact', () => {
hoisted.invoke.mockResolvedValueOnce('/dest/just-a-title');
await downloadArtifact('art-1', 'just-a-title', '');
expect(hoisted.invoke).toHaveBeenCalledWith('download_artifact_to_downloads', {
- sourcePath: '/p/file',
+ artifactId: 'art-1',
filename: 'just-a-title',
});
});
@@ -468,7 +468,7 @@ describe('saveArtifactViaDialog (dialog removed with rfd)', () => {
const outcome = await saveArtifactViaDialog('a-1', 'Deck', 'pptx');
expect(outcome).toEqual({ ok: true, path: '/Users/me/Downloads/Deck.pptx' });
expect(hoisted.invoke).toHaveBeenCalledWith('download_artifact_to_downloads', {
- sourcePath: '/ws/artifacts/a-1/deck.pptx',
+ artifactId: 'a-1',
filename: 'Deck.pptx',
});
// The removed `rfd` command must never be invoked again.
diff --git a/app/src/services/artifactDownloadService.ts b/app/src/services/artifactDownloadService.ts
index 6344d39273..b4e486516e 100644
--- a/app/src/services/artifactDownloadService.ts
+++ b/app/src/services/artifactDownloadService.ts
@@ -1,11 +1,14 @@
/**
* Artifact export service (#2779).
*
- * All paths first resolve the artifact's absolute on-disk path + meta
- * via the `openhuman.ai_get_artifact` core RPC, then hand a source path
- * + filename hint to the `download_artifact_to_downloads` Tauri command,
- * which copies into the user's Downloads directory with a non-colliding
- * name and returns the dest path so the UI can offer "Reveal in Finder".
+ * All paths first resolve the artifact's meta via the
+ * `openhuman.ai_get_artifact` core RPC (which also reports a file moved or
+ * deleted outside OpenHuman), then hand the artifact id + filename hint to
+ * the `download_artifact_to_downloads` Tauri command. The shell resolves the
+ * id through the core's artifact store itself — it never trusts a
+ * renderer-supplied path (#5505) — copies into the user's Downloads directory
+ * with a non-colliding name, and returns the dest path so the UI can offer
+ * "Reveal in Finder".
*
* {@link saveArtifactViaDialog} is kept as the name its callers use, but
* the native Save-As dialog behind it was removed with the shell's `rfd`
@@ -247,7 +250,7 @@ export async function downloadArtifact(
try {
const dest = await invoke<string>('download_artifact_to_downloads', {
- sourcePath: resolved.sourcePath,
+ artifactId,
filename: resolved.filename,
});
return { ok: true, path: dest };
diff --git a/app/src/services/chatService.ts b/app/src/services/chatService.ts
index cee7e0afc9..94e41f0003 100644
--- a/app/src/services/chatService.ts
+++ b/app/src/services/chatService.ts
@@ -482,7 +482,7 @@ export interface ArtifactReadyEvent {
* wrong `<workspace>/artifacts/` tree after a workspace switch.
*/
workspace_dir: string;
- /** Relative path under `<workspace>/artifacts/`, e.g. `<uuid>/deck.pptx`. */
+ /** File name relative to its root: `deck.pptx` in the visible files folder, or `<uuid>/deck.pptx` for a legacy record. */
path: string;
/** Final on-disk size in bytes. */
size_bytes: number;
@@ -530,7 +530,7 @@ export interface ArtifactPendingEvent {
title: string;
/** Absolute workspace root — see {@link ArtifactReadyEvent.workspace_dir}. */
workspace_dir: string;
- /** Relative path under `<workspace>/artifacts/`, e.g. `<uuid>/deck.pptx`. */
+ /** File name relative to its root: `deck.pptx` in the visible files folder, or `<uuid>/deck.pptx` for a legacy record. */
path: string;
/** See {@link ArtifactReadyEvent.tool_call_id}. */
tool_call_id?: string;
diff --git a/app/src/store/chatRuntimeSlice.ts b/app/src/store/chatRuntimeSlice.ts
index 429f390e14..7d37f72897 100644
--- a/app/src/store/chatRuntimeSlice.ts
+++ b/app/src/store/chatRuntimeSlice.ts
@@ -775,7 +775,7 @@ export interface ArtifactSnapshot {
status: ArtifactStatus;
/** Final on-disk size. Only set when `status === 'ready'`. */
sizeBytes?: number;
- /** Relative path under `<workspace>/artifacts/`. Only set when `status === 'ready'`. */
+ /** File name relative to its root folder. Only set when `status === 'ready'`. */
path?: string;
/** Producer-supplied reason. Only set when `status === 'failed'`. */
error?: string;
diff --git a/crates/openhuman-app/src/artifact_commands.rs b/crates/openhuman-app/src/artifact_commands.rs
index 157c86efc8..b66a9a3680 100644
--- a/crates/openhuman-app/src/artifact_commands.rs
+++ b/crates/openhuman-app/src/artifact_commands.rs
@@ -1,10 +1,10 @@
//! Tauri commands for exporting agent-generated artifacts (#2779).
//!
-//! One export path, fed by the frontend resolving an artifact's absolute
-//! source path via the `openhuman.ai_get_artifact` core RPC:
-//! [`download_artifact_to_downloads`] copies the artifact into the user's
-//! Downloads directory with a non-colliding name and returns the dest path
-//! so the UI can offer "Reveal in Finder". Cross-platform.
+//! One export path, fed by an artifact id:
+//! [`download_artifact_to_downloads`] resolves the id through the core's
+//! artifact store, copies the file into the user's Downloads directory with a
+//! non-colliding name, and returns the dest path so the UI can offer "Reveal in
+//! Finder". Cross-platform.
//!
//! **The native Save-As dialog (#3162) was removed.** It was one call into
//! `rfd`, and `rfd` carried 13 packages — the xdg-desktop-portal client
@@ -16,61 +16,25 @@
//! fewer. If a real Save-As is wanted again, prefer the destination-picking
//! surface Tauri itself already links over re-adding a second dialog stack.
//!
-//! It validates that the source is an existing file inside the OpenHuman
-//! data dir's `artifacts/` tree, and sanitizes the filename hint, so the
-//! renderer can never copy an arbitrary local file out nor write outside
-//! the Downloads directory.
+//! The renderer names an artifact, never a path (#5505). Artifact files now
+//! live in a visible, user-configurable folder rather than under the data
+//! dir, so the shell cannot check a renderer-supplied path against a fixed
+//! root; instead it asks the core, whose `resolve_ready_file` applies the
+//! artifact escape guard and refuses records that are not `Ready`. A
+//! compromised renderer can therefore only copy out files the artifact store
+//! already vouches for. The filename hint is still sanitized so nothing is
+//! written outside the Downloads directory.
use std::path::{Path, PathBuf};
-/// Validate a renderer-supplied source path: must be a non-empty,
-/// absolute path that exists on disk AND resolve inside the OpenHuman
-/// data directory's `artifacts/` tree. The path always originates from
-/// the core `ai_get_artifact` RPC's `absolute_path`, but the command is
-/// reachable by the renderer directly, so we re-validate the trust
-/// boundary here — without the artifacts-root check a compromised
-/// renderer could copy any readable local file out through the Save-As
-/// dialog under an artifact-looking name (Codex P2).
-fn validate_source(source_path: &str) -> Result<PathBuf, String> {
- if source_path.trim().is_empty() {
- return Err("source_path must not be empty".to_string());
+/// Resolve an artifact id to the file the core's artifact store vouches for,
+/// in the given workspace. Isolated from config loading for unit testing.
+async fn resolve_source(workspace_dir: &Path, artifact_id: &str) -> Result<PathBuf, String> {
+ let artifact_id = artifact_id.trim();
+ if artifact_id.is_empty() {
+ return Err("artifact_id must not be empty".to_string());
}
- let source = PathBuf::from(source_path);
- if !source.is_absolute() {
- return Err(format!(
- "source_path must be absolute (came from ai_get_artifact): {source_path:?}"
- ));
- }
- if !source.is_file() {
- return Err(format!(
- "artifact source not present on disk: {source_path}"
- ));
- }
- let root = crate::file_logging::resolve_data_dir();
- assert_artifact_source(&source, &root)?;
- Ok(source)
-}
-
-/// Confirm `source` resolves inside `root` (the OpenHuman data dir) and
-/// carries an `artifacts` path component — i.e. it is a workspace
-/// artifact, not an arbitrary local file. Canonicalizes both sides so
-/// symlink trickery can't escape the root. Isolated for unit testing
-/// without touching the real home directory.
-fn assert_artifact_source(source: &Path, root: &Path) -> Result<(), String> {
- let canon_source = source
- .canonicalize()
- .map_err(|e| format!("cannot resolve source path: {e}"))?;
- let canon_root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
- if !canon_source.starts_with(&canon_root) {
- return Err("source must be inside the OpenHuman data directory".to_string());
- }
- if !canon_source
- .components()
- .any(|c| c.as_os_str() == "artifacts")
- {
- return Err("source must be a workspace artifact file".to_string());
- }
- Ok(())
+ openhuman_core::agent::artifacts::resolve_ready_file(workspace_dir, artifact_id).await
}
/// Copy `source` to `dest`, returning the byte count. Isolated so it is
@@ -88,10 +52,14 @@ const MAX_COLLISION_SUFFIX: u32 = 1000;
#[tauri::command]
pub async fn download_artifact_to_downloads(
- source_path: String,
+ artifact_id: String,
filename: String,
) -> Result<String, String> {
- let source = validate_source(&source_path)?;
+ if artifact_id.trim().is_empty() {
+ return Err("artifact_id must not be empty".to_string());
+ }
+ let config = openhuman_core::config::rpc::load_config_with_timeout().await?;
+ let source = resolve_source(&config.workspace_dir, &artifact_id).await?;
if filename.trim().is_empty() {
return Err("filename must not be empty".to_string());
}
diff --git a/crates/openhuman-app/src/artifact_commands_tests.rs b/crates/openhuman-app/src/artifact_commands_tests.rs
index f32279986d..42b0c33b44 100644
--- a/crates/openhuman-app/src/artifact_commands_tests.rs
+++ b/crates/openhuman-app/src/artifact_commands_tests.rs
@@ -20,45 +20,68 @@ fn sanitize_accepts_plain_names() {
assert_eq!(sanitize_filename(" trim me ").unwrap(), "trim me");
}
-#[test]
-fn validate_source_rejects_relative_and_empty() {
- assert!(validate_source("").is_err());
- assert!(validate_source("relative/path.pptx").is_err());
- assert!(validate_source("/definitely/not/here.pptx").is_err());
+async fn ready_artifact(workspace: &Path, files_dir: &Path) -> String {
+ use openhuman_core::agent::artifacts::{create_artifact, finalize_artifact, ArtifactKind};
+ let (meta, path) = create_artifact(
+ workspace,
+ files_dir,
+ ArtifactKind::Presentation,
+ "Deck",
+ "pptx",
+ )
+ .await
+ .unwrap();
+ std::fs::write(&path, b"deck").unwrap();
+ finalize_artifact(workspace, &meta.id, 4).await.unwrap();
+ meta.id
}
-#[test]
-fn assert_artifact_source_accepts_file_under_artifacts_root() {
+#[tokio::test]
+async fn resolve_source_returns_the_file_in_the_files_folder() {
let temp = tempfile::tempdir().unwrap();
- let root = temp.path();
- let art = root.join("users/u1/workspace/artifacts/a-1");
- std::fs::create_dir_all(&art).unwrap();
- let file = art.join("deck.pptx");
- std::fs::write(&file, b"x").unwrap();
- assert!(assert_artifact_source(&file, root).is_ok());
+ let files_dir = temp.path().join("Files");
+ let id = ready_artifact(temp.path(), &files_dir).await;
+ assert_eq!(
+ resolve_source(temp.path(), &id).await.unwrap(),
+ files_dir.join("deck.pptx")
+ );
}
-#[test]
-fn assert_artifact_source_rejects_file_without_artifacts_component() {
+#[tokio::test]
+async fn resolve_source_rejects_unknown_ids_and_paths() {
let temp = tempfile::tempdir().unwrap();
- let root = temp.path();
- let other = root.join("users/u1/secrets");
- std::fs::create_dir_all(&other).unwrap();
- let file = other.join("token.txt");
- std::fs::write(&file, b"x").unwrap();
- assert!(assert_artifact_source(&file, root).is_err());
+ assert!(resolve_source(temp.path(), "").await.is_err());
+ assert!(resolve_source(temp.path(), "no-such-artifact")
+ .await
+ .is_err());
+ // A path is not an id: the store's id validation refuses separators.
+ assert!(resolve_source(temp.path(), "/etc/passwd").await.is_err());
}
-#[test]
-fn assert_artifact_source_rejects_file_outside_root() {
- let root_dir = tempfile::tempdir().unwrap();
- let outside_dir = tempfile::tempdir().unwrap();
- // Even with an `artifacts` segment, a path outside the root is denied.
- let art = outside_dir.path().join("artifacts");
- std::fs::create_dir_all(&art).unwrap();
- let file = art.join("evil.pptx");
- std::fs::write(&file, b"x").unwrap();
- assert!(assert_artifact_source(&file, root_dir.path()).is_err());
+#[tokio::test]
+async fn resolve_source_refuses_a_file_the_store_does_not_vouch_for() {
+ use openhuman_core::agent::artifacts::{ArtifactKind, ArtifactMeta, ArtifactStatus};
+ let temp = tempfile::tempdir().unwrap();
+ let secret = temp.path().join("secret.txt");
+ std::fs::write(&secret, b"private").unwrap();
+ let meta = ArtifactMeta {
+ id: "tampered".to_string(),
+ kind: ArtifactKind::Other,
+ title: "x".to_string(),
+ path: "secret.txt".to_string(),
+ file: Some(secret.to_string_lossy().into_owned()),
+ file_root: Some(temp.path().join("Files").to_string_lossy().into_owned()),
+ size_bytes: 7,
+ status: ArtifactStatus::Ready,
+ created_at: chrono::Utc::now(),
+ error: None,
+ thread_id: None,
+ tool_call_id: None,
+ };
+ let dir = temp.path().join("artifacts").join("tampered");
+ std::fs::create_dir_all(&dir).unwrap();
+ std::fs::write(dir.join("meta.json"), serde_json::to_vec(&meta).unwrap()).unwrap();
+ assert!(resolve_source(temp.path(), "tampered").await.is_err());
}
#[tokio::test]
@@ -82,7 +105,7 @@ async fn download_rejects_bad_source() {
.is_err()
);
assert!(
- download_artifact_to_downloads("relative".to_string(), "x.pptx".to_string())
+ download_artifact_to_downloads(" ".to_string(), "x.pptx".to_string())
.await
.is_err()
);
diff --git a/crates/openhuman-core/src/agent/artifacts/README.md b/crates/openhuman-core/src/agent/artifacts/README.md
index a95079e892..00d100b64f 100644
--- a/crates/openhuman-core/src/agent/artifacts/README.md
+++ b/crates/openhuman-core/src/agent/artifacts/README.md
@@ -1,9 +1,12 @@
# artifacts
Metadata store and lifecycle for agent-generated files (presentations,
-documents, images) under `<workspace_dir>/artifacts/`. Producer tools
-(`tools/impl/presentation`, `tools/impl/document`) call this module to
-reserve an artifact directory, write their bytes, and flip the record to
+documents, images, video). Metadata lives in the hidden, per-account
+`<workspace_dir>/artifacts/`; the files themselves are written to a visible
+files folder, `~/OpenHuman/projects/Files` by default
+(`config::default_files_dir`, #5505). Producer tools
+(`tools/impl/presentation`, `tools/impl/document`, `media::generation`) call
+this module to reserve an artifact and its file, write their bytes, and flip the record to
`Ready` or `Failed`; the module publishes the matching bus events, persists
`meta.json` / `args.json`, and exposes `ai.*` RPC controllers plus three
agent tools for listing, fetching, deleting, and regenerating. It never
@@ -15,6 +18,8 @@ renders artifact content itself.
| --- | --- |
| `mod.rs` | `mod` decls and re-exports: `ArtifactKind` / `ArtifactMeta` / `ArtifactStatus`, the producer API (`create_artifact`, `finalize_artifact`, `fail_artifact`, `read_artifact_bytes`), and `all_artifacts_controller_schemas` / `all_artifacts_registered_controllers`. |
| `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` | 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_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` | 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`. |
| `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` | `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`. |
@@ -85,25 +90,43 @@ event.
## Persistence
-- Root `<workspace_dir>/artifacts/`, created on demand by `artifacts_root`.
-- `<root>/<id>/meta.json`: pretty-printed `ArtifactMeta`.
+- Metadata root `<workspace_dir>/artifacts/`, created on demand by
+ `artifacts_root`. Per account; listed in `WORKSPACE_INTERNAL_DIRS`
+ because `meta.json` names the file Download and `read_artifact_bytes`
+ follow.
+- `<root>/<id>/meta.json`: pretty-printed `ArtifactMeta`, written
+ atomically (temp + rename).
- `<root>/<id>/args.json`: verbatim producer-tool args, written by the
producer via `save_artifact_args`, read by `ai_regenerate`. Absent for
artifacts created before it existed, which makes them non-regenerable.
-- `<root>/<id>/<stem>.<ext>`: the artifact bytes; `meta.path` is the
- `<id>/<filename>` relative path.
+- `<files_dir>/<stem>.<ext>`: the artifact bytes. `meta.file` is the
+ absolute path, `meta.file_root` the files folder it was placed in, and
+ `meta.path` the file name. The files folder is shared by every account on
+ the OS user; `create_new` keeps names from colliding, and each account
+ lists only its own metadata. Changing the folder affects new artifacts
+ only; existing ones keep resolving through their recorded `file`.
+- Legacy records (`file` absent) keep `meta.path` = `<id>/<filename>` under
+ the metadata root until `migrate_legacy_artifacts` moves them.
+- A failed generation removes its zero-byte placeholder; deleting an
+ artifact removes its file and its metadata directory; a `Ready` record
+ whose file was moved or deleted outside OpenHuman reads as "file missing".
- `list_artifacts` scans root subdirectories, sorts by `created_at`
descending, applies the `thread_id` filter before pagination, and skips
entries whose `meta.json` is missing or corrupt (`warn!`, not an error).
-- Regeneration reuses the existing directory and preserves the original
- `created_at` so the artifact keeps its position in the sorted list.
+- Regeneration reuses the existing directory and the file it owns, and
+ preserves the original `created_at` so the artifact keeps its position in
+ the sorted list.
## Used by
- `tools/impl/presentation/mod.rs` and `tools/impl/document/mod.rs`
(`documents` feature; in `scripts/ci/product-features.txt`, not in Cargo
- defaults): the only producers. Presentation also uses
- `read_artifact_bytes` for its image pipeline.
+ defaults), and `media/generation/artifact_tool.rs`: the producers.
+ Presentation also uses `read_artifact_bytes` for its image pipeline.
+- `config/ops/agent.rs` (`ensure_agent_dirs`): creates the files folder and
+ runs the migration at boot.
+- `crates/openhuman-app/src/artifact_commands.rs`: the desktop Download
+ command resolves an artifact id through `resolve_ready_file`.
- `web_chat/event_bus.rs`: bridges the three events to web-channel
`artifact_*` events.
- `core/all.rs`: controller registry.
@@ -113,8 +136,11 @@ event.
- Path-traversal hardening is layered: `validate_artifact_id` rejects
empty, `.`, `..`, anything containing `/` or `\`, absolute paths, and
`X:` drive-letter prefixes; `assert_within_root` re-checks every resolved
- path; `ai_get_artifact` and `read_artifact_bytes` additionally re-check
- that a stored `meta.path` does not escape the root.
+ path; every reader resolves through `files::resolve_file`, which refuses
+ a legacy `meta.path` with `..` components (a lexical `starts_with` alone
+ let `<root>/../x` through) and holds a recorded `file` to the escape guard:
+ absolute, no `..`, strictly inside its `file_root` (symlinks resolved), and
+ never `SecurityPolicy::is_always_forbidden`.
- `create_artifact` rejects empty titles/extensions and extensions
containing `/`, `\`, or `.`. Filename stems are lowercased ASCII
`[a-z0-9_-]`, capped at 80 chars, fallback `artifact`.
diff --git a/crates/openhuman-core/src/agent/artifacts/files.rs b/crates/openhuman-core/src/agent/artifacts/files.rs
new file mode 100644
index 0000000000..f495dc6afb
--- /dev/null
+++ b/crates/openhuman-core/src/agent/artifacts/files.rs
@@ -0,0 +1,200 @@
+//! Where an artifact's bytes live (#5505).
+//!
+//! An artifact's metadata stays in the hidden, per-account
+//! `<workspace_dir>/artifacts/<id>/`, but the file itself is written to a
+//! visible folder the user can open (`~/OpenHuman/projects/Files` by default,
+//! [`crate::config::default_files_dir`]). Files there are named for people —
+//! `<sanitized-title>.<ext>`, then `<sanitized-title> (2).<ext>` on collision —
+//! and each record carries the absolute `file` it owns plus the `file_root` it
+//! was placed in.
+//!
+//! The folder is shared by every account on the OS user, so a name is claimed
+//! with `create_new` (an atomic "fail if it exists"): two accounts, or two
+//! concurrent generations, can never be handed the same path.
+//!
+//! # The escape guard
+//!
+//! `meta.json` is data, so a record's `file` is checked before anything reads
+//! or copies it: it must be absolute, free of `..`, strictly inside the
+//! record's `file_root` (after resolving symlinks when it exists), and never a
+//! path [`SecurityPolicy::is_always_forbidden`] rejects. That last check is the
+//! same floor the agent's own file tools keep when the autonomy policy is off,
+//! so a hand-edited record cannot reach further than the agent already could.
+//! With the policy on, `artifacts/` is a workspace-internal dir and the agent
+//! cannot edit the record at all.
+
+use std::path::{Component, Path, PathBuf};
+
+use super::store::{artifacts_root, get_artifact};
+use super::types::{ArtifactMeta, ArtifactStatus};
+use crate::security::SecurityPolicy;
+
+/// Collision suffixes tried before falling back to an id-tagged name.
+const MAX_COLLISION_SUFFIX: u32 = 1000;
+
+/// Claim a fresh, human-named file in `files_dir` for `<stem>.<ext>`.
+///
+/// Creates `files_dir` when missing, then creates an empty placeholder with
+/// `create_new` so the name belongs to this caller before any bytes are
+/// generated. Returns the placeholder's absolute path.
+pub(crate) async fn reserve_file(
+ files_dir: &Path,
+ stem: &str,
+ ext: &str,
+ id: &str,
+) -> Result<PathBuf, String> {
+ tokio::fs::create_dir_all(files_dir)
+ .await
+ .map_err(|e| format!("[artifacts] failed to create files folder {files_dir:?}: {e}"))?;
+ let candidates = (1..=MAX_COLLISION_SUFFIX)
+ .map(|n| {
+ if n == 1 {
+ format!("{stem}.{ext}")
+ } else {
+ format!("{stem} ({n}).{ext}")
+ }
+ })
+ .chain(std::iter::once(format!("{stem}-{id}.{ext}")));
+ for name in candidates {
+ let candidate = files_dir.join(&name);
+ match tokio::fs::OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .open(&candidate)
+ .await
+ {
+ Ok(_) => {
+ log::debug!("[artifacts] reserve_file: id={id} claimed {name:?}");
+ return Ok(candidate);
+ }
+ Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
+ Err(e) => {
+ return Err(format!(
+ "[artifacts] failed to reserve {candidate:?} for id={id}: {e}"
+ ))
+ }
+ }
+ }
+ Err(format!(
+ "[artifacts] no free file name for id={id} in {files_dir:?}"
+ ))
+}
+
+/// Resolve the absolute path of a record's bytes, applying the escape guard.
+///
+/// A record with `file` set resolves to it; a legacy record resolves to
+/// `<workspace>/artifacts/<meta.path>`. Does not require the file to exist.
+pub(crate) async fn resolve_file(
+ workspace_dir: &Path,
+ meta: &ArtifactMeta,
+) -> Result<PathBuf, String> {
+ let Some(file) = meta.file.as_deref() else {
+ let root = artifacts_root(workspace_dir).await?;
+ let resolved = root.join(&meta.path);
+ if has_parent_component(Path::new(&meta.path)) || !resolved.starts_with(&root) {
+ return Err(format!(
+ "[artifacts] meta.path {:?} escapes artifacts root for id={}",
+ meta.path, meta.id
+ ));
+ }
+ return Ok(resolved);
+ };
+ let file = PathBuf::from(file);
+ let root = meta
+ .file_root
+ .as_deref()
+ .map(PathBuf::from)
+ .ok_or_else(|| format!("[artifacts] id={} has a file but no file_root", meta.id))?;
+ check_within(&root, &file).map_err(|reason| {
+ format!(
+ "[artifacts] file for id={} rejected by the escape guard: {reason}",
+ meta.id
+ )
+ })?;
+ Ok(file)
+}
+
+fn has_parent_component(path: &Path) -> bool {
+ path.components().any(|c| matches!(c, Component::ParentDir))
+}
+
+/// The escape guard for a recorded `file` against its `file_root`.
+fn check_within(root: &Path, file: &Path) -> Result<(), &'static str> {
+ if !root.is_absolute() || !file.is_absolute() {
+ return Err("path is not absolute");
+ }
+ if has_parent_component(root) || has_parent_component(file) {
+ return Err("path contains '..'");
+ }
+ if file == root || !file.starts_with(root) {
+ return Err("file is outside its files folder");
+ }
+ if SecurityPolicy::is_always_forbidden(file) {
+ return Err("file is in a protected location");
+ }
+ // A symlink inside the folder must not lead out of it.
+ if let (Ok(canon_file), Ok(canon_root)) = (file.canonicalize(), root.canonicalize()) {
+ if !canon_file.starts_with(&canon_root) || SecurityPolicy::is_always_forbidden(&canon_file)
+ {
+ return Err("file resolves outside its files folder");
+ }
+ }
+ Ok(())
+}
+
+/// Resolve a `Ready` artifact's bytes to an existing file.
+///
+/// The one sanctioned id → path lookup for anything that reads or exports the
+/// file (`read_artifact_bytes`, `ai.get_artifact`, the desktop Download
+/// command). Errors when the record is not `Ready`, fails the escape guard, or
+/// its file was moved or deleted outside OpenHuman.
+pub async fn resolve_ready_file(
+ workspace_dir: &Path,
+ artifact_id: &str,
+) -> Result<PathBuf, String> {
+ let meta = get_artifact(workspace_dir, artifact_id).await?;
+ if !matches!(meta.status, ArtifactStatus::Ready) {
+ return Err(format!(
+ "[artifacts] artifact id={artifact_id} is not ready (status={:?})",
+ meta.status
+ ));
+ }
+ let path = resolve_file(workspace_dir, &meta).await?;
+ if !tokio::fs::try_exists(&path).await.unwrap_or(false) {
+ return Err(missing_file_error(artifact_id, &path));
+ }
+ Ok(path)
+}
+
+/// The error for a `Ready` record whose file is gone.
+pub(crate) fn missing_file_error(artifact_id: &str, path: &Path) -> String {
+ format!(
+ "[artifacts] file missing for id={artifact_id}: {} was moved or deleted outside OpenHuman",
+ path.display()
+ )
+}
+
+/// A failed generation must not leave an empty file in the user's files
+/// folder: drop the zero-byte placeholder `create_artifact` reserved. A file
+/// with bytes (e.g. the previous output of a failed regenerate) is kept.
+pub(crate) async fn remove_empty_placeholder(workspace_dir: &Path, meta: &ArtifactMeta) {
+ if meta.file.is_none() {
+ return;
+ }
+ let Ok(path) = resolve_file(workspace_dir, meta).await else {
+ return;
+ };
+ if matches!(tokio::fs::metadata(&path).await, Ok(m) if m.is_file() && m.len() == 0) {
+ match tokio::fs::remove_file(&path).await {
+ Ok(()) => log::debug!("[artifacts] removed empty placeholder for id={}", meta.id),
+ Err(e) => log::warn!(
+ "[artifacts] could not remove empty placeholder for id={}: {e}",
+ meta.id
+ ),
+ }
+ }
+}
+
+#[cfg(test)]
+#[path = "files_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/agent/artifacts/files_tests.rs b/crates/openhuman-core/src/agent/artifacts/files_tests.rs
new file mode 100644
index 0000000000..208e582388
--- /dev/null
+++ b/crates/openhuman-core/src/agent/artifacts/files_tests.rs
@@ -0,0 +1,306 @@
+use std::path::{Path, PathBuf};
+
+use tempfile::TempDir;
+
+use super::*;
+use crate::agent::artifacts::store::{
+ create_artifact, delete_artifact, fail_artifact, finalize_artifact, list_artifacts,
+ read_artifact_bytes, save_artifact_meta, REGENERATE_TARGET_ID,
+};
+use crate::agent::artifacts::types::ArtifactKind;
+
+async fn create_ready(
+ workspace: &Path,
+ files_dir: &Path,
+ title: &str,
+ bytes: &[u8],
+) -> ArtifactMeta {
+ let (meta, path) = create_artifact(workspace, files_dir, ArtifactKind::Document, title, "txt")
+ .await
+ .expect("create_artifact");
+ tokio::fs::write(&path, bytes).await.unwrap();
+ finalize_artifact(workspace, &meta.id, bytes.len() as u64)
+ .await
+ .expect("finalize_artifact")
+}
+
+fn legacy_meta(id: &str, path: &str) -> ArtifactMeta {
+ ArtifactMeta {
+ id: id.to_string(),
+ kind: ArtifactKind::Document,
+ title: "Legacy".to_string(),
+ path: path.to_string(),
+ file: None,
+ file_root: None,
+ size_bytes: 3,
+ status: ArtifactStatus::Ready,
+ created_at: chrono::Utc::now(),
+ error: None,
+ thread_id: None,
+ tool_call_id: None,
+ }
+}
+
+fn names_in(dir: &Path) -> 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
+}
+
+#[tokio::test]
+async fn new_artifact_is_written_to_the_files_folder_not_the_workspace() {
+ let tmp = TempDir::new().unwrap();
+ let workspace = tmp.path().join("ws");
+ let files_dir = tmp.path().join("Files");
+
+ let (meta, path) = create_artifact(
+ &workspace,
+ &files_dir,
+ ArtifactKind::Presentation,
+ "Q3 Deck",
+ "pptx",
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(path, files_dir.join("q3-deck.pptx"));
+ assert!(path.is_file(), "the name is claimed with a placeholder");
+ assert_eq!(meta.path, "q3-deck.pptx");
+ assert_eq!(meta.file.as_deref(), Some(path.to_string_lossy().as_ref()));
+ assert_eq!(
+ meta.file_root.as_deref(),
+ Some(files_dir.to_string_lossy().as_ref())
+ );
+ // Metadata stays hidden in the workspace; no bytes land beside it.
+ assert_eq!(
+ names_in(&workspace.join("artifacts").join(&meta.id)),
+ vec!["meta.json"]
+ );
+}
+
+#[tokio::test]
+async fn files_folder_is_created_on_first_use() {
+ let tmp = TempDir::new().unwrap();
+ let files_dir = tmp.path().join("not").join("yet").join("Files");
+ create_artifact(
+ tmp.path(),
+ &files_dir,
+ ArtifactKind::Document,
+ "Notes",
+ "docx",
+ )
+ .await
+ .unwrap();
+ assert!(files_dir.is_dir());
+}
+
+#[tokio::test]
+async fn a_repeated_title_gets_a_numbered_name_instead_of_overwriting() {
+ let tmp = TempDir::new().unwrap();
+ let files_dir = tmp.path().join("Files");
+ let first = create_ready(tmp.path(), &files_dir, "Report", b"one").await;
+ let second = create_ready(tmp.path(), &files_dir, "Report", b"two").await;
+
+ assert_eq!(first.path, "report.txt");
+ assert_eq!(second.path, "report (2).txt");
+ assert_eq!(
+ read_artifact_bytes(tmp.path(), &first.id).await.unwrap(),
+ b"one"
+ );
+ assert_eq!(
+ read_artifact_bytes(tmp.path(), &second.id).await.unwrap(),
+ b"two"
+ );
+}
+
+/// The files folder is shared by every account on the OS user; metadata is
+/// not. Two accounts saving the same title must get distinct files, and each
+/// account's listing must show only its own records.
+#[tokio::test]
+async fn two_accounts_share_the_files_folder_without_clobbering_or_leaking() {
+ let tmp = TempDir::new().unwrap();
+ let files_dir = tmp.path().join("Files");
+ let ws_a = tmp.path().join("users").join("a").join("workspace");
+ let ws_b = tmp.path().join("users").join("b").join("workspace");
+
+ let a = create_ready(&ws_a, &files_dir, "Budget", b"account a").await;
+ let b = create_ready(&ws_b, &files_dir, "Budget", b"account b").await;
+
+ assert_ne!(a.file, b.file);
+ assert_eq!(
+ read_artifact_bytes(&ws_a, &a.id).await.unwrap(),
+ b"account a"
+ );
+ assert_eq!(
+ read_artifact_bytes(&ws_b, &b.id).await.unwrap(),
+ b"account b"
+ );
+
+ let (listed_b, total_b) = list_artifacts(&ws_b, 0, 50, None).await.unwrap();
+ assert_eq!(total_b, 1);
+ assert_eq!(listed_b[0].id, b.id);
+ assert!(
+ get_artifact(&ws_b, &a.id).await.is_err(),
+ "B cannot open A's record"
+ );
+}
+
+#[tokio::test]
+async fn regenerate_overwrites_the_file_it_owns() {
+ let tmp = TempDir::new().unwrap();
+ let files_dir = tmp.path().join("Files");
+ let original = create_ready(tmp.path(), &files_dir, "Deck", b"v1").await;
+
+ let (again, path) = REGENERATE_TARGET_ID
+ .scope(original.id.clone(), async {
+ create_artifact(
+ tmp.path(),
+ &files_dir,
+ ArtifactKind::Document,
+ "Deck",
+ "txt",
+ )
+ .await
+ })
+ .await
+ .unwrap();
+
+ assert_eq!(again.id, original.id);
+ assert_eq!(again.file, original.file);
+ assert_eq!(path, PathBuf::from(original.file.clone().unwrap()));
+ assert_eq!(names_in(&files_dir), vec!["deck.txt"]);
+}
+
+#[tokio::test]
+async fn a_failed_generation_leaves_no_empty_file_behind() {
+ let tmp = TempDir::new().unwrap();
+ let files_dir = tmp.path().join("Files");
+ let (meta, path) = create_artifact(
+ tmp.path(),
+ &files_dir,
+ ArtifactKind::Document,
+ "Doomed",
+ "docx",
+ )
+ .await
+ .unwrap();
+ assert!(path.is_file());
+
+ fail_artifact(tmp.path(), &meta.id, "engine exploded")
+ .await
+ .unwrap();
+
+ assert!(!path.exists(), "the zero-byte placeholder is removed");
+}
+
+#[tokio::test]
+async fn delete_removes_the_file_and_the_record() {
+ let tmp = TempDir::new().unwrap();
+ let files_dir = tmp.path().join("Files");
+ let meta = create_ready(tmp.path(), &files_dir, "Gone", b"bye").await;
+ let file = PathBuf::from(meta.file.clone().unwrap());
+
+ delete_artifact(tmp.path(), &meta.id).await.unwrap();
+
+ assert!(!file.exists());
+ assert!(!tmp.path().join("artifacts").join(&meta.id).exists());
+}
+
+#[tokio::test]
+async fn a_file_removed_outside_openhuman_is_reported_missing() {
+ let tmp = TempDir::new().unwrap();
+ let files_dir = tmp.path().join("Files");
+ let meta = create_ready(tmp.path(), &files_dir, "Moved", b"abc").await;
+ std::fs::remove_file(meta.file.as_deref().unwrap()).unwrap();
+
+ let err = read_artifact_bytes(tmp.path(), &meta.id).await.unwrap_err();
+ assert!(err.contains("file missing"), "{err}");
+ let err = resolve_ready_file(tmp.path(), &meta.id).await.unwrap_err();
+ assert!(err.contains("file missing"), "{err}");
+}
+
+async fn tampered(workspace: &Path, file: &Path, file_root: &Path) -> String {
+ let mut meta = legacy_meta("tampered", "x.txt");
+ meta.file = Some(file.to_string_lossy().into_owned());
+ meta.file_root = Some(file_root.to_string_lossy().into_owned());
+ save_artifact_meta(workspace, &meta).await.unwrap();
+ read_artifact_bytes(workspace, "tampered")
+ .await
+ .unwrap_err()
+}
+
+#[tokio::test]
+async fn the_escape_guard_rejects_a_file_outside_its_folder() {
+ let tmp = TempDir::new().unwrap();
+ let files_dir = tmp.path().join("Files");
+ std::fs::create_dir_all(&files_dir).unwrap();
+ let secret = tmp.path().join("secret.txt");
+ std::fs::write(&secret, b"private").unwrap();
+
+ let err = tampered(tmp.path(), &secret, &files_dir).await;
+ assert!(err.contains("escape guard"), "{err}");
+
+ let dotdot = files_dir.join("..").join("secret.txt");
+ let err = tampered(tmp.path(), &dotdot, &files_dir).await;
+ assert!(err.contains("escape guard"), "{err}");
+}
+
+#[tokio::test]
+async fn the_escape_guard_keeps_the_credential_store_floor() {
+ let tmp = TempDir::new().unwrap();
+ let ssh = tmp.path().join(".ssh");
+ std::fs::create_dir_all(&ssh).unwrap();
+ let key = ssh.join("id_ed25519");
+ std::fs::write(&key, b"-----BEGIN").unwrap();
+
+ // Even a record whose root claims the key's parent is refused.
+ let err = tampered(tmp.path(), &key, tmp.path()).await;
+ assert!(err.contains("escape guard"), "{err}");
+}
+
+#[cfg(unix)]
+#[tokio::test]
+async fn the_escape_guard_rejects_a_symlink_out_of_the_folder() {
+ let tmp = TempDir::new().unwrap();
+ let files_dir = tmp.path().join("Files");
+ std::fs::create_dir_all(&files_dir).unwrap();
+ let secret = tmp.path().join("secret.txt");
+ std::fs::write(&secret, b"private").unwrap();
+ let link = files_dir.join("innocent.txt");
+ std::os::unix::fs::symlink(&secret, &link).unwrap();
+
+ let err = tampered(tmp.path(), &link, &files_dir).await;
+ assert!(err.contains("escape guard"), "{err}");
+}
+
+#[tokio::test]
+async fn a_legacy_record_still_resolves_under_the_workspace() {
+ let tmp = TempDir::new().unwrap();
+ let meta = legacy_meta("legacy-1", "legacy-1/old.txt");
+ save_artifact_meta(tmp.path(), &meta).await.unwrap();
+ std::fs::write(tmp.path().join("artifacts/legacy-1/old.txt"), b"old").unwrap();
+
+ assert_eq!(
+ read_artifact_bytes(tmp.path(), "legacy-1").await.unwrap(),
+ b"old"
+ );
+}
+
+/// `root.join("../x").starts_with(root)` is true lexically, so the legacy
+/// guard must reject `..` components rather than rely on `starts_with`.
+#[tokio::test]
+async fn a_legacy_path_with_parent_components_is_rejected() {
+ let tmp = TempDir::new().unwrap();
+ let workspace = tmp.path().join("ws");
+ std::fs::write(tmp.path().join("secret.txt"), b"private").unwrap();
+ let meta = legacy_meta("legacy-2", "../../secret.txt");
+ save_artifact_meta(&workspace, &meta).await.unwrap();
+
+ let err = read_artifact_bytes(&workspace, "legacy-2")
+ .await
+ .unwrap_err();
+ assert!(err.contains("escapes artifacts root"), "{err}");
+}
diff --git a/crates/openhuman-core/src/agent/artifacts/migrate.rs b/crates/openhuman-core/src/agent/artifacts/migrate.rs
new file mode 100644
index 0000000000..8aeb605126
--- /dev/null
+++ b/crates/openhuman-core/src/agent/artifacts/migrate.rs
@@ -0,0 +1,252 @@
+//! Move legacy artifact files into the visible files folder (#5505).
+//!
+//! Artifacts created before the files folder existed keep their bytes under
+//! the hidden `<workspace>/artifacts/<id>/`. At boot each account's legacy
+//! `Ready` records are moved to the files folder so the user can find them.
+//! Metadata (`meta.json`, `args.json`) never moves.
+//!
+//! Each file goes through four steps, ordered so that at every point the
+//! record still resolves to a complete file and nothing is lost:
+//!
+//! 1. copy the bytes to a hidden `.<id>.partial` in the files folder and
+//! flush them to disk (a copy, not a rename: the two folders can sit on
+//! different volumes);
+//! 2. claim a human-readable name (`create_new`, suffixed on collision) and
+//! rename the partial onto it;
+//! 3. rewrite `meta.json` atomically to point at the new file;
+//! 4. only then delete the legacy bytes.
+//!
+//! A crash before step 3 leaves the record on its legacy path, and the next
+//! boot migrates again; the worst leftover is one duplicate visible copy
+//! (after step 2) or a `.partial` (after step 1), which the next run removes.
+//! A crash after step 3 leaves a legacy copy the next run deletes. Running it
+//! again on a migrated workspace changes nothing.
+
+use std::path::{Path, PathBuf};
+
+use super::files;
+use super::store::{artifacts_root, save_artifact_meta};
+use super::types::{ArtifactMeta, ArtifactStatus};
+
+/// What one migration pass did, for the boot log and tests.
+#[derive(Debug, Default, Clone, PartialEq, Eq)]
+pub struct MigrationReport {
+ /// Records whose file was moved into the files folder.
+ pub moved: usize,
+ /// Legacy copies removed for records already pointing at the files folder.
+ pub cleaned: usize,
+ /// Records left on their legacy path because a step failed.
+ pub failed: usize,
+}
+
+/// A step to stop after, simulating a crash. Test-only in effect: the public
+/// entry point always passes `None`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum CrashAfter {
+ Copy,
+ Rename,
+ MetaWrite,
+}
+
+const PARTIAL_SUFFIX: &str = ".partial";
+/// Files in `<workspace>/artifacts/<id>/` that are metadata, never bytes.
+const METADATA_FILES: &[&str] = &["meta.json", "args.json", "meta.json.tmp"];
+
+/// Migrate every legacy `Ready` artifact in `workspace_dir` into `files_dir`.
+/// Idempotent and safe to run on every boot.
+pub async fn migrate_legacy_artifacts(workspace_dir: &Path, files_dir: &Path) -> MigrationReport {
+ migrate_with(workspace_dir, files_dir, None).await
+}
+
+pub(crate) async fn migrate_with(
+ workspace_dir: &Path,
+ files_dir: &Path,
+ crash_after: Option<CrashAfter>,
+) -> MigrationReport {
+ let mut report = MigrationReport::default();
+ let Ok(root) = artifacts_root(workspace_dir).await else {
+ return report;
+ };
+ let Ok(mut entries) = tokio::fs::read_dir(&root).await else {
+ return report;
+ };
+ let mut records = Vec::new();
+ while let Ok(Some(entry)) = entries.next_entry().await {
+ let meta_path = entry.path().join("meta.json");
+ let Ok(raw) = tokio::fs::read_to_string(&meta_path).await else {
+ continue;
+ };
+ let Ok(meta) = serde_json::from_str::<ArtifactMeta>(&raw) else {
+ continue;
+ };
+ records.push((entry.path(), meta));
+ }
+ if records.is_empty() {
+ return report;
+ }
+ remove_stale_partials(files_dir).await;
+
+ for (artifact_dir, meta) in records {
+ if meta.file.is_some() {
+ // Already migrated; a crash after step 3 may have left the legacy
+ // copy behind.
+ report.cleaned += remove_legacy_leftovers(&artifact_dir).await;
+ continue;
+ }
+ if !matches!(meta.status, ArtifactStatus::Ready) {
+ continue;
+ }
+ let Some(src) = legacy_bytes(&root, &artifact_dir, &meta) else {
+ continue;
+ };
+ match migrate_one(workspace_dir, files_dir, &meta, &src, crash_after).await {
+ Ok(true) => report.moved += 1,
+ Ok(false) => {}
+ Err(e) => {
+ report.failed += 1;
+ log::warn!(
+ "[artifacts][migrate] id={} left on legacy path: {e}",
+ meta.id
+ );
+ }
+ }
+ if crash_after.is_some() {
+ break;
+ }
+ }
+ log::info!(
+ "[artifacts][migrate] moved={} cleaned={} failed={}",
+ report.moved,
+ report.cleaned,
+ report.failed
+ );
+ report
+}
+
+/// The legacy on-disk bytes of an unmigrated record, when present and inside
+/// its own artifact directory.
+fn legacy_bytes(root: &Path, artifact_dir: &Path, meta: &ArtifactMeta) -> Option<PathBuf> {
+ let rel = Path::new(&meta.path);
+ if rel.is_absolute()
+ || rel
+ .components()
+ .any(|c| matches!(c, std::path::Component::ParentDir))
+ {
+ return None;
+ }
+ let candidate = root.join(rel);
+ (candidate.starts_with(artifact_dir) && candidate.is_file()).then_some(candidate)
+}
+
+/// For a migrated record, every regular file in its artifact directory other
+/// than the metadata sidecars is a legacy copy left by a crash between steps 3
+/// and 4. Returns how many were removed.
+async fn remove_legacy_leftovers(artifact_dir: &Path) -> usize {
+ let Ok(mut entries) = tokio::fs::read_dir(artifact_dir).await else {
+ return 0;
+ };
+ let mut removed = 0;
+ while let Ok(Some(entry)) = entries.next_entry().await {
+ let name = entry.file_name().to_string_lossy().into_owned();
+ if METADATA_FILES.contains(&name.as_str()) {
+ continue;
+ }
+ if matches!(entry.file_type().await, Ok(ft) if ft.is_file())
+ && tokio::fs::remove_file(entry.path()).await.is_ok()
+ {
+ removed += 1;
+ }
+ }
+ removed
+}
+
+/// Returns `Ok(true)` when the file was moved, `Ok(false)` on a simulated crash.
+async fn migrate_one(
+ workspace_dir: &Path,
+ files_dir: &Path,
+ meta: &ArtifactMeta,
+ src: &Path,
+ crash_after: Option<CrashAfter>,
+) -> Result<bool, String> {
+ tokio::fs::create_dir_all(files_dir)
+ .await
+ .map_err(|e| format!("create files folder: {e}"))?;
+
+ // Step 1: copy to a hidden partial and flush it.
+ let partial = files_dir.join(format!(".{}{PARTIAL_SUFFIX}", meta.id));
+ let _ = tokio::fs::remove_file(&partial).await;
+ tokio::fs::copy(src, &partial)
+ .await
+ .map_err(|e| format!("copy: {e}"))?;
+ tokio::fs::File::open(&partial)
+ .await
+ .map_err(|e| format!("reopen partial: {e}"))?
+ .sync_all()
+ .await
+ .map_err(|e| format!("flush partial: {e}"))?;
+ if crash_after == Some(CrashAfter::Copy) {
+ return Ok(false);
+ }
+
+ // Step 2: claim a readable name and move the partial onto it.
+ let file_name = src
+ .file_name()
+ .map(|n| n.to_string_lossy().into_owned())
+ .unwrap_or_default();
+ let (stem, ext) = match file_name.rsplit_once('.') {
+ Some((stem, ext)) if !stem.is_empty() => (stem.to_string(), ext.to_string()),
+ _ => (file_name.clone(), "bin".to_string()),
+ };
+ let target = files::reserve_file(files_dir, &stem, &ext, &meta.id).await?;
+ if let Err(e) = tokio::fs::rename(&partial, &target).await {
+ let _ = tokio::fs::remove_file(&target).await;
+ let _ = tokio::fs::remove_file(&partial).await;
+ return Err(format!("rename partial: {e}"));
+ }
+ if crash_after == Some(CrashAfter::Rename) {
+ return Ok(false);
+ }
+
+ // Step 3: point the record at the moved file.
+ let mut moved = meta.clone();
+ moved.path = target
+ .file_name()
+ .map(|n| n.to_string_lossy().into_owned())
+ .unwrap_or_default();
+ moved.file = Some(target.to_string_lossy().into_owned());
+ moved.file_root = Some(files_dir.to_string_lossy().into_owned());
+ if let Err(e) = save_artifact_meta(workspace_dir, &moved).await {
+ let _ = tokio::fs::remove_file(&target).await;
+ return Err(format!("write meta: {e}"));
+ }
+ if crash_after == Some(CrashAfter::MetaWrite) {
+ return Ok(false);
+ }
+
+ // Step 4: the record no longer points at the legacy bytes.
+ if let Err(e) = tokio::fs::remove_file(src).await {
+ log::warn!(
+ "[artifacts][migrate] id={} moved; legacy copy not removed: {e}",
+ meta.id
+ );
+ }
+ log::debug!("[artifacts][migrate] id={} moved to files folder", meta.id);
+ Ok(true)
+}
+
+/// Remove `.<id>.partial` leftovers from an interrupted earlier run.
+async fn remove_stale_partials(files_dir: &Path) {
+ let Ok(mut entries) = tokio::fs::read_dir(files_dir).await else {
+ return;
+ };
+ while let Ok(Some(entry)) = entries.next_entry().await {
+ let name = entry.file_name().to_string_lossy().into_owned();
+ if name.starts_with('.') && name.ends_with(PARTIAL_SUFFIX) {
+ let _ = tokio::fs::remove_file(entry.path()).await;
+ }
+ }
+}
+
+#[cfg(test)]
+#[path = "migrate_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/agent/artifacts/migrate_tests.rs b/crates/openhuman-core/src/agent/artifacts/migrate_tests.rs
new file mode 100644
index 0000000000..2cae766169
--- /dev/null
+++ b/crates/openhuman-core/src/agent/artifacts/migrate_tests.rs
@@ -0,0 +1,286 @@
+use std::path::{Path, PathBuf};
+
+use tempfile::TempDir;
+
+use super::*;
+use crate::agent::artifacts::store::{
+ get_artifact, list_artifacts, read_artifact_bytes, save_artifact_args, save_artifact_meta,
+};
+use crate::agent::artifacts::types::ArtifactKind;
+
+/// A pre-#5505 record: bytes under `<workspace>/artifacts/<id>/<name>`.
+async fn legacy(workspace: &Path, id: &str, name: &str, bytes: &[u8], status: ArtifactStatus) {
+ let meta = ArtifactMeta {
+ id: id.to_string(),
+ kind: ArtifactKind::Document,
+ title: name.to_string(),
+ path: format!("{id}/{name}"),
+ file: None,
+ file_root: None,
+ size_bytes: bytes.len() as u64,
+ status,
+ created_at: chrono::Utc::now(),
+ error: None,
+ thread_id: None,
+ tool_call_id: None,
+ };
+ save_artifact_meta(workspace, &meta).await.unwrap();
+ save_artifact_args(workspace, id, &serde_json::json!({ "title": name }))
+ .await
+ .unwrap();
+ std::fs::write(workspace.join("artifacts").join(id).join(name), bytes).unwrap();
+}
+
+fn legacy_path(workspace: &Path, id: &str, name: &str) -> PathBuf {
+ workspace.join("artifacts").join(id).join(name)
+}
+
+/// Visible files in the folder (hidden `.partial`s excluded).
+fn visible(files_dir: &Path) -> Vec<String> {
+ let Ok(entries) = std::fs::read_dir(files_dir) else {
+ return Vec::new();
+ };
+ let mut names: Vec<String> = entries
+ .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
+ .filter(|n| !n.starts_with('.'))
+ .collect();
+ names.sort();
+ names
+}
+
+fn partials(files_dir: &Path) -> usize {
+ std::fs::read_dir(files_dir)
+ .map(|entries| {
+ entries
+ .filter(|e| {
+ e.as_ref()
+ .unwrap()
+ .file_name()
+ .to_string_lossy()
+ .ends_with(".partial")
+ })
+ .count()
+ })
+ .unwrap_or(0)
+}
+
+#[tokio::test]
+async fn moves_a_legacy_file_into_the_files_folder() {
+ let tmp = TempDir::new().unwrap();
+ let ws = tmp.path().join("ws");
+ let files_dir = tmp.path().join("Files");
+ legacy(
+ &ws,
+ "a1",
+ "q3-deck.pptx",
+ b"deck bytes",
+ ArtifactStatus::Ready,
+ )
+ .await;
+
+ let report = migrate_legacy_artifacts(&ws, &files_dir).await;
+
+ assert_eq!(
+ report,
+ MigrationReport {
+ moved: 1,
+ cleaned: 0,
+ failed: 0
+ }
+ );
+ let meta = get_artifact(&ws, "a1").await.unwrap();
+ assert_eq!(
+ meta.file.as_deref(),
+ Some(files_dir.join("q3-deck.pptx").to_string_lossy().as_ref())
+ );
+ assert_eq!(
+ meta.file_root.as_deref(),
+ Some(files_dir.to_string_lossy().as_ref())
+ );
+ assert_eq!(meta.path, "q3-deck.pptx");
+ assert_eq!(read_artifact_bytes(&ws, "a1").await.unwrap(), b"deck bytes");
+ assert!(
+ !legacy_path(&ws, "a1", "q3-deck.pptx").exists(),
+ "legacy bytes removed"
+ );
+ assert!(
+ ws.join("artifacts/a1/args.json").is_file(),
+ "metadata never moves"
+ );
+}
+
+#[tokio::test]
+async fn running_twice_changes_nothing() {
+ let tmp = TempDir::new().unwrap();
+ let ws = tmp.path().join("ws");
+ let files_dir = tmp.path().join("Files");
+ legacy(&ws, "a1", "notes.docx", b"notes", ArtifactStatus::Ready).await;
+
+ migrate_legacy_artifacts(&ws, &files_dir).await;
+ let second = migrate_legacy_artifacts(&ws, &files_dir).await;
+
+ assert_eq!(second, MigrationReport::default());
+ assert_eq!(visible(&files_dir), vec!["notes.docx"]);
+ assert_eq!(read_artifact_bytes(&ws, "a1").await.unwrap(), b"notes");
+}
+
+#[tokio::test]
+async fn leaves_pending_and_failed_records_alone() {
+ let tmp = TempDir::new().unwrap();
+ let ws = tmp.path().join("ws");
+ let files_dir = tmp.path().join("Files");
+ legacy(&ws, "p1", "half.pptx", b"", ArtifactStatus::Pending).await;
+ legacy(&ws, "f1", "broken.pptx", b"", ArtifactStatus::Failed).await;
+
+ let report = migrate_legacy_artifacts(&ws, &files_dir).await;
+
+ assert_eq!(report, MigrationReport::default());
+ assert!(get_artifact(&ws, "p1").await.unwrap().file.is_none());
+ assert!(get_artifact(&ws, "f1").await.unwrap().file.is_none());
+ assert!(visible(&files_dir).is_empty());
+}
+
+#[tokio::test]
+async fn a_name_already_in_the_folder_is_never_overwritten() {
+ let tmp = TempDir::new().unwrap();
+ let ws = tmp.path().join("ws");
+ let files_dir = tmp.path().join("Files");
+ std::fs::create_dir_all(&files_dir).unwrap();
+ std::fs::write(files_dir.join("report.txt"), b"the user's own file").unwrap();
+ legacy(
+ &ws,
+ "a1",
+ "report.txt",
+ b"agent report",
+ ArtifactStatus::Ready,
+ )
+ .await;
+
+ migrate_legacy_artifacts(&ws, &files_dir).await;
+
+ assert_eq!(
+ std::fs::read(files_dir.join("report.txt")).unwrap(),
+ b"the user's own file"
+ );
+ assert_eq!(
+ get_artifact(&ws, "a1").await.unwrap().path,
+ "report (2).txt"
+ );
+ assert_eq!(
+ read_artifact_bytes(&ws, "a1").await.unwrap(),
+ b"agent report"
+ );
+}
+
+/// Two accounts migrate a same-named file into the one shared folder: both
+/// survive under distinct names, and each account still lists only its own.
+#[tokio::test]
+async fn two_accounts_migrate_into_the_shared_folder_without_clobbering() {
+ let tmp = TempDir::new().unwrap();
+ let files_dir = tmp.path().join("Files");
+ let ws_a = tmp.path().join("users/a/workspace");
+ let ws_b = tmp.path().join("users/b/workspace");
+ legacy(
+ &ws_a,
+ "a1",
+ "budget.xlsx",
+ b"a's budget",
+ ArtifactStatus::Ready,
+ )
+ .await;
+ legacy(
+ &ws_b,
+ "b1",
+ "budget.xlsx",
+ b"b's budget",
+ ArtifactStatus::Ready,
+ )
+ .await;
+
+ migrate_legacy_artifacts(&ws_a, &files_dir).await;
+ migrate_legacy_artifacts(&ws_b, &files_dir).await;
+
+ assert_eq!(visible(&files_dir), vec!["budget (2).xlsx", "budget.xlsx"]);
+ assert_eq!(
+ read_artifact_bytes(&ws_a, "a1").await.unwrap(),
+ b"a's budget"
+ );
+ assert_eq!(
+ read_artifact_bytes(&ws_b, "b1").await.unwrap(),
+ b"b's budget"
+ );
+ let (listed, total) = list_artifacts(&ws_b, 0, 50, None).await.unwrap();
+ assert_eq!((total, listed[0].id.as_str()), (1, "b1"));
+}
+
+// ── Crash safety: stop after each step, check nothing is lost, rerun ──────
+
+#[tokio::test]
+async fn a_crash_after_the_copy_leaves_the_record_intact_and_is_redone() {
+ let tmp = TempDir::new().unwrap();
+ let ws = tmp.path().join("ws");
+ let files_dir = tmp.path().join("Files");
+ legacy(&ws, "a1", "deck.pptx", b"deck", ArtifactStatus::Ready).await;
+
+ migrate_with(&ws, &files_dir, Some(CrashAfter::Copy)).await;
+ assert!(get_artifact(&ws, "a1").await.unwrap().file.is_none());
+ assert_eq!(read_artifact_bytes(&ws, "a1").await.unwrap(), b"deck");
+ assert_eq!(partials(&files_dir), 1);
+
+ let report = migrate_legacy_artifacts(&ws, &files_dir).await;
+ assert_eq!(report.moved, 1);
+ assert_eq!(partials(&files_dir), 0, "the stale partial is removed");
+ assert_eq!(visible(&files_dir), vec!["deck.pptx"]);
+ assert_eq!(read_artifact_bytes(&ws, "a1").await.unwrap(), b"deck");
+}
+
+#[tokio::test]
+async fn a_crash_after_the_rename_loses_nothing_and_leaves_at_most_one_duplicate() {
+ let tmp = TempDir::new().unwrap();
+ let ws = tmp.path().join("ws");
+ let files_dir = tmp.path().join("Files");
+ legacy(&ws, "a1", "deck.pptx", b"deck", ArtifactStatus::Ready).await;
+
+ migrate_with(&ws, &files_dir, Some(CrashAfter::Rename)).await;
+ assert!(get_artifact(&ws, "a1").await.unwrap().file.is_none());
+ assert_eq!(read_artifact_bytes(&ws, "a1").await.unwrap(), b"deck");
+
+ migrate_legacy_artifacts(&ws, &files_dir).await;
+ let meta = get_artifact(&ws, "a1").await.unwrap();
+ assert!(meta.file.is_some());
+ assert_eq!(read_artifact_bytes(&ws, "a1").await.unwrap(), b"deck");
+ assert!(visible(&files_dir).len() <= 2);
+ assert!(!legacy_path(&ws, "a1", "deck.pptx").exists());
+}
+
+#[tokio::test]
+async fn a_crash_after_the_meta_write_is_finished_by_the_next_run() {
+ let tmp = TempDir::new().unwrap();
+ let ws = tmp.path().join("ws");
+ let files_dir = tmp.path().join("Files");
+ legacy(&ws, "a1", "deck.pptx", b"deck", ArtifactStatus::Ready).await;
+
+ migrate_with(&ws, &files_dir, Some(CrashAfter::MetaWrite)).await;
+ assert!(get_artifact(&ws, "a1").await.unwrap().file.is_some());
+ assert!(
+ legacy_path(&ws, "a1", "deck.pptx").exists(),
+ "legacy copy not yet removed"
+ );
+ assert_eq!(read_artifact_bytes(&ws, "a1").await.unwrap(), b"deck");
+
+ let report = migrate_legacy_artifacts(&ws, &files_dir).await;
+ assert_eq!(
+ report,
+ MigrationReport {
+ moved: 0,
+ cleaned: 1,
+ failed: 0
+ }
+ );
+ assert!(!legacy_path(&ws, "a1", "deck.pptx").exists());
+ assert_eq!(visible(&files_dir), vec!["deck.pptx"]);
+ assert!(
+ ws.join("artifacts/a1/args.json").is_file(),
+ "sidecars are never cleaned"
+ );
+}
diff --git a/crates/openhuman-core/src/agent/artifacts/mod.rs b/crates/openhuman-core/src/agent/artifacts/mod.rs
index c0679861e2..3635cc8cd6 100644
--- a/crates/openhuman-core/src/agent/artifacts/mod.rs
+++ b/crates/openhuman-core/src/agent/artifacts/mod.rs
@@ -1,9 +1,13 @@
+pub mod files;
+pub mod migrate;
pub mod ops;
pub mod schemas;
pub mod store;
pub mod tools;
pub mod types;
+pub use files::resolve_ready_file;
+pub use migrate::{migrate_legacy_artifacts, MigrationReport};
pub use schemas::{
all_controller_schemas as all_artifacts_controller_schemas,
all_registered_controllers as all_artifacts_registered_controllers,
diff --git a/crates/openhuman-core/src/agent/artifacts/ops.rs b/crates/openhuman-core/src/agent/artifacts/ops.rs
index ccf4aa046b..a329a0c9ad 100644
--- a/crates/openhuman-core/src/agent/artifacts/ops.rs
+++ b/crates/openhuman-core/src/agent/artifacts/ops.rs
@@ -79,15 +79,15 @@ pub async fn ai_get_artifact(config: &Config, artifact_id: &str) -> Result<Outco
let meta = store::get_artifact(&config.workspace_dir, artifact_id).await?;
- // Compute absolute path for the caller's convenience.
- // Guard against a corrupt or adversarial meta.path that escapes the artifacts root.
- let artifacts_root = config.workspace_dir.join("artifacts");
- let resolved = artifacts_root.join(&meta.path);
- if !resolved.starts_with(&artifacts_root) {
- return Err(format!(
- "[artifacts] meta.path {:?} escapes artifacts root for id={artifact_id}",
- meta.path
- ));
+ // Resolve through the escape guard (#5505): a record's `file` must sit
+ // inside its recorded files folder, a legacy `meta.path` inside the
+ // artifacts root. A Ready record whose file was moved or deleted outside
+ // OpenHuman is an error rather than a path that points at nothing.
+ let resolved = super::files::resolve_file(&config.workspace_dir, &meta).await?;
+ if matches!(meta.status, super::types::ArtifactStatus::Ready)
+ && !tokio::fs::try_exists(&resolved).await.unwrap_or(false)
+ {
+ return Err(super::files::missing_file_error(artifact_id, &resolved));
}
let absolute_path = resolved.to_string_lossy().into_owned();
@@ -204,8 +204,12 @@ async fn regenerate_presentation(
&config.workspace_dir,
&config.action_dir,
));
- let tool =
- PresentationTool::with_config(config.workspace_dir.clone(), security, config.clone());
+ let tool = PresentationTool::with_config(
+ config.workspace_dir.clone(),
+ crate::config::default_files_dir(),
+ security,
+ config.clone(),
+ );
let chat_ctx = ApprovalChatContext {
thread_id: thread_id.to_string(),
diff --git a/crates/openhuman-core/src/agent/artifacts/ops_tests.rs b/crates/openhuman-core/src/agent/artifacts/ops_tests.rs
index e7f7cc0c0f..54c6150cfb 100644
--- a/crates/openhuman-core/src/agent/artifacts/ops_tests.rs
+++ b/crates/openhuman-core/src/agent/artifacts/ops_tests.rs
@@ -46,6 +46,8 @@ async fn list_without_thread_filter_returns_all_threads() {
kind: ArtifactKind::Document,
title: id.to_string(),
path: format!("{id}/x.txt"),
+ file: None,
+ file_root: None,
size_bytes: 0,
status: ArtifactStatus::Ready,
created_at: chrono::Utc::now(),
@@ -86,6 +88,8 @@ async fn list_with_thread_filter_returns_only_matching_thread() {
kind: ArtifactKind::Document,
title: id.to_string(),
path: format!("{id}/x.txt"),
+ file: None,
+ file_root: None,
size_bytes: 0,
status: ArtifactStatus::Ready,
created_at: chrono::Utc::now(),
@@ -137,6 +141,8 @@ async fn list_with_thread_filter_unknown_thread_returns_zero() {
kind: ArtifactKind::Document,
title: "only".to_string(),
path: "only/x.txt".to_string(),
+ file: None,
+ file_root: None,
size_bytes: 0,
status: ArtifactStatus::Ready,
created_at: chrono::Utc::now(),
@@ -206,6 +212,8 @@ async fn regenerate_rejects_non_presentation_kind() {
kind: ArtifactKind::Document,
title: "notes".to_string(),
path: "doc-1/notes.txt".to_string(),
+ file: None,
+ file_root: None,
size_bytes: 0,
status: ArtifactStatus::Failed,
created_at: chrono::Utc::now(),
@@ -241,9 +249,15 @@ async fn regenerate_errors_when_args_missing() {
// A presentation artifact with no persisted args.json (e.g. created
// before #3162) cannot be regenerated.
- let (meta, _) = create_artifact(tmp.path(), ArtifactKind::Presentation, "Old Deck", "pptx")
- .await
- .unwrap();
+ let (meta, _) = create_artifact(
+ tmp.path(),
+ &tmp.path().join("Files"),
+ ArtifactKind::Presentation,
+ "Old Deck",
+ "pptx",
+ )
+ .await
+ .unwrap();
let err = ai_regenerate(&config, &meta.id, "t", "c")
.await
.unwrap_err();
@@ -260,9 +274,15 @@ async fn regenerate_reruns_producer_and_reuses_id() {
let config = test_config(&tmp);
// Seed a presentation artifact + its persisted creation args.
- let (meta, _) = create_artifact(tmp.path(), ArtifactKind::Presentation, "Q3 Deck", "pptx")
- .await
- .unwrap();
+ let (meta, _) = create_artifact(
+ tmp.path(),
+ &tmp.path().join("Files"),
+ ArtifactKind::Presentation,
+ "Q3 Deck",
+ "pptx",
+ )
+ .await
+ .unwrap();
let args = serde_json::json!({
"title": "Q3 Deck",
"slides": [{ "title": "Intro", "bullets": ["alpha", "beta"] }],
@@ -287,3 +307,59 @@ async fn regenerate_reruns_producer_and_reuses_id() {
assert_eq!(got.id, meta.id);
assert_eq!(got.status, ArtifactStatus::Ready);
}
+
+// ── #5505: files folder ─────────────────────────────────────────────────────
+
+#[tokio::test]
+async fn get_returns_the_files_folder_path() {
+ use crate::agent::artifacts::store::{create_artifact, finalize_artifact};
+ use crate::agent::artifacts::types::ArtifactKind;
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let files_dir = tmp.path().join("Files");
+ let (meta, path) = create_artifact(
+ tmp.path(),
+ &files_dir,
+ ArtifactKind::Document,
+ "Plan",
+ "docx",
+ )
+ .await
+ .unwrap();
+ std::fs::write(&path, b"plan").unwrap();
+ finalize_artifact(tmp.path(), &meta.id, 4).await.unwrap();
+
+ let value = ai_get_artifact(&config, &meta.id)
+ .await
+ .unwrap()
+ .into_cli_compatible_json()
+ .unwrap();
+
+ assert_eq!(
+ value["absolute_path"],
+ files_dir.join("plan.docx").to_string_lossy().as_ref()
+ );
+}
+
+#[tokio::test]
+async fn get_reports_a_ready_file_removed_outside_openhuman() {
+ use crate::agent::artifacts::store::{create_artifact, finalize_artifact};
+ use crate::agent::artifacts::types::ArtifactKind;
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let (meta, path) = create_artifact(
+ tmp.path(),
+ &tmp.path().join("Files"),
+ ArtifactKind::Document,
+ "Plan",
+ "docx",
+ )
+ .await
+ .unwrap();
+ std::fs::write(&path, b"plan").unwrap();
+ finalize_artifact(tmp.path(), &meta.id, 4).await.unwrap();
+ std::fs::remove_file(&path).unwrap();
+
+ let err = ai_get_artifact(&config, &meta.id).await.unwrap_err();
+ assert!(err.contains("file missing"), "{err}");
+}
diff --git a/crates/openhuman-core/src/agent/artifacts/schemas.rs b/crates/openhuman-core/src/agent/artifacts/schemas.rs
index c3b2f57da2..c190e1232e 100644
--- a/crates/openhuman-core/src/agent/artifacts/schemas.rs
+++ b/crates/openhuman-core/src/agent/artifacts/schemas.rs
@@ -120,7 +120,7 @@ pub fn schemas(function: &str) -> ControllerSchema {
FieldSchema {
name: "path",
ty: TypeSchema::String,
- comment: "Relative path from the artifacts root.",
+ comment: "File name relative to its root: the files folder, or the artifacts root for a legacy record.",
required: true,
},
FieldSchema {
diff --git a/crates/openhuman-core/src/agent/artifacts/store.rs b/crates/openhuman-core/src/agent/artifacts/store.rs
index e72cba68a1..b06f1bce47 100644
--- a/crates/openhuman-core/src/agent/artifacts/store.rs
+++ b/crates/openhuman-core/src/agent/artifacts/store.rs
@@ -1,9 +1,11 @@
use std::path::{Path, PathBuf};
+use super::files;
use super::types::{ArtifactMeta, ArtifactStatus};
const ARTIFACTS_SUBDIR: &str = "artifacts";
const META_FILENAME: &str = "meta.json";
+const META_TMP_FILENAME: &str = "meta.json.tmp";
/// Sidecar file holding the verbatim producer-tool arguments that
/// generated the artifact, persisted next to `meta.json` so a failed
/// card's Retry button can re-dispatch the exact same generation
@@ -113,12 +115,24 @@ pub(crate) async fn save_artifact_meta(
meta.id
)
})?;
- tokio::fs::write(&meta_path, json).await.map_err(|e| {
+ // Write-then-rename so a crash mid-write never leaves a truncated
+ // meta.json: the migration relies on the record flipping atomically
+ // from the legacy path to the moved file.
+ let tmp_path = artifact_dir.join(META_TMP_FILENAME);
+ tokio::fs::write(&tmp_path, json).await.map_err(|e| {
format!(
"[artifacts] failed to write meta.json for id={}: {e}",
meta.id
)
})?;
+ tokio::fs::rename(&tmp_path, &meta_path)
+ .await
+ .map_err(|e| {
+ format!(
+ "[artifacts] failed to commit meta.json for id={}: {e}",
+ meta.id
+ )
+ })?;
log::debug!("[artifacts] saved meta.json for id={}", meta.id);
Ok(())
}
@@ -311,27 +325,17 @@ pub(crate) async fn read_artifact_args(
/// Read the raw bytes of a finalized artifact's output file.
///
/// Single source of truth for resolving an artifact id → on-disk bytes:
-/// callers (e.g. the presentation image pipeline) must not reconstruct
-/// the `<root>/<id>/<filename>` path scheme themselves. Validates the id,
-/// confirms the resolved path stays under the artifacts root, and refuses
-/// artifacts that are not yet [`ArtifactStatus::Ready`] (a `Pending` /
-/// `Failed` record may have no bytes — or partial bytes — on disk).
+/// callers (e.g. the presentation image pipeline) must not reconstruct the
+/// path themselves. Goes through [`files::resolve_ready_file`], which refuses
+/// records that are not yet [`ArtifactStatus::Ready`] (a `Pending` / `Failed`
+/// record may have no bytes — or partial bytes — on disk), applies the escape
+/// guard, and reports a file removed outside OpenHuman as missing.
pub async fn read_artifact_bytes(
workspace_dir: &Path,
artifact_id: &str,
) -> Result<Vec<u8>, String> {
log::debug!("[artifacts] read_artifact_bytes: id={artifact_id}");
- let meta = get_artifact(workspace_dir, artifact_id).await?;
- if !matches!(meta.status, ArtifactStatus::Ready) {
- return Err(format!(
- "[artifacts] artifact id={artifact_id} is not ready (status={:?})",
- meta.status
- ));
- }
- let root = artifacts_root(workspace_dir).await?;
- // `meta.path` is the store-internal `<id>/<filename>` relative path.
- let file_path = root.join(&meta.path);
- assert_within_root(&root, &file_path)?;
+ let file_path = files::resolve_ready_file(workspace_dir, artifact_id).await?;
let bytes = tokio::fs::read(&file_path)
.await
.map_err(|e| format!("[artifacts] failed to read artifact bytes id={artifact_id}: {e}"))?;
@@ -342,13 +346,33 @@ pub async fn read_artifact_bytes(
Ok(bytes)
}
-/// Delete an artifact directory and all its contents.
+/// Delete an artifact: its file in the files folder, then its metadata
+/// directory. A file already gone, or one the escape guard rejects, is left
+/// alone (logged) and the record is still removed.
pub(crate) async fn delete_artifact(workspace_dir: &Path, artifact_id: &str) -> Result<(), String> {
log::debug!("[artifacts] delete_artifact: id={artifact_id}");
validate_artifact_id(artifact_id)?;
let root = artifacts_root(workspace_dir).await?;
let artifact_dir = root.join(artifact_id);
assert_within_root(&root, &artifact_dir)?;
+ if let Ok(meta) = get_artifact(workspace_dir, artifact_id).await {
+ if meta.file.is_some() {
+ match files::resolve_file(workspace_dir, &meta).await {
+ Ok(file) => match tokio::fs::remove_file(&file).await {
+ Ok(()) => log::debug!(
+ "[artifacts] delete_artifact: removed file for id={artifact_id}"
+ ),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
+ Err(e) => {
+ return Err(format!(
+ "[artifacts] failed to delete file for id={artifact_id}: {e}"
+ ))
+ }
+ },
+ Err(e) => log::warn!("[artifacts] delete_artifact: leaving file in place: {e}"),
+ }
+ }
+ }
tokio::fs::remove_dir_all(&artifact_dir)
.await
.map_err(|e| format!("[artifacts] failed to delete artifact id={artifact_id}: {e}"))?;
@@ -428,11 +452,12 @@ fn sanitize_filename_stem(title: &str) -> String {
/// bridge silently drops the event for lack of a routing target.
pub async fn create_artifact(
workspace_dir: &Path,
+ files_dir: &Path,
kind: super::types::ArtifactKind,
title: &str,
extension: &str,
) -> Result<(ArtifactMeta, PathBuf), String> {
- create_artifact_for_call(workspace_dir, kind, title, extension, None).await
+ create_artifact_for_call(workspace_dir, files_dir, kind, title, extension, None).await
}
/// As [`create_artifact`], but also records the provider-assigned
@@ -443,6 +468,7 @@ pub async fn create_artifact(
/// exactly like [`create_artifact`].
pub async fn create_artifact_for_call(
workspace_dir: &Path,
+ files_dir: &Path,
kind: super::types::ArtifactKind,
title: &str,
extension: &str,
@@ -474,8 +500,7 @@ pub async fn create_artifact_for_call(
.filter(|target| !target.trim().is_empty());
let is_regenerate = reused_id.is_some();
let id = reused_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
- let filename = format!("{}.{trimmed_ext}", sanitize_filename_stem(trimmed_title));
- let relative_path = format!("{id}/{filename}");
+ let stem = sanitize_filename_stem(trimmed_title);
let root = artifacts_root(workspace_dir).await?;
let artifact_dir = root.join(&id);
@@ -488,7 +513,6 @@ pub async fn create_artifact_for_call(
artifact_dir
)
})?;
- let absolute_path = artifact_dir.join(&filename);
// Capture the originating chat thread (if any) at create-time so the
// panel can repopulate from disk after a redux-persist purge — see
@@ -501,20 +525,46 @@ pub async fn create_artifact_for_call(
// `created_at` — bumping it to now would reorder the artifact to the
// top of the `created_at`-sorted list/panel even though it is the same
// logical artifact (#3162, CodeRabbit). New artifacts always stamp now.
- let created_at = if is_regenerate {
- match get_artifact(workspace_dir, &id).await {
- Ok(prev) => prev.created_at,
- Err(_) => chrono::Utc::now(),
- }
+ // A regenerate also overwrites the file it already owns (#5505) rather
+ // than claiming a second name in the files folder.
+ let previous = if is_regenerate {
+ get_artifact(workspace_dir, &id).await.ok()
} else {
- chrono::Utc::now()
+ None
+ };
+ let created_at = previous
+ .as_ref()
+ .map(|prev| prev.created_at)
+ .unwrap_or_else(chrono::Utc::now);
+ let owned_file = match previous.as_ref().filter(|prev| prev.file.is_some()) {
+ Some(prev) => match files::resolve_file(workspace_dir, prev).await {
+ Ok(path) if tokio::fs::try_exists(&path).await.unwrap_or(false) => prev
+ .file_root
+ .clone()
+ .map(|root| (path, PathBuf::from(root))),
+ _ => None,
+ },
+ None => None,
+ };
+ let (absolute_path, file_root) = match owned_file {
+ Some(pair) => pair,
+ None => (
+ files::reserve_file(files_dir, &stem, trimmed_ext, &id).await?,
+ files_dir.to_path_buf(),
+ ),
};
+ let filename = absolute_path
+ .file_name()
+ .map(|n| n.to_string_lossy().into_owned())
+ .unwrap_or_else(|| format!("{stem}.{trimmed_ext}"));
let meta = ArtifactMeta {
id: id.clone(),
kind,
title: trimmed_title.to_string(),
- path: relative_path,
+ path: filename,
+ file: Some(absolute_path.to_string_lossy().into_owned()),
+ file_root: Some(file_root.to_string_lossy().into_owned()),
size_bytes: 0,
status: ArtifactStatus::Pending,
created_at,
@@ -614,6 +664,7 @@ pub async fn fail_artifact(
meta.status = ArtifactStatus::Failed;
meta.error = Some(reason.to_string());
save_artifact_meta(workspace_dir, &meta).await?;
+ files::remove_empty_placeholder(workspace_dir, &meta).await;
// Log only the size of the reason — it can carry provider stderr
// / user-derived content, which we don't want flushed verbatim
// into structured logs. The full payload is still persisted on
diff --git a/crates/openhuman-core/src/agent/artifacts/store_tests.rs b/crates/openhuman-core/src/agent/artifacts/store_tests.rs
index a96a1e95cb..635eab5c2d 100644
--- a/crates/openhuman-core/src/agent/artifacts/store_tests.rs
+++ b/crates/openhuman-core/src/agent/artifacts/store_tests.rs
@@ -10,6 +10,8 @@ fn make_meta(id: &str, title: &str, created_at: chrono::DateTime<Utc>) -> Artifa
kind: ArtifactKind::Document,
title: title.to_string(),
path: format!("{id}/file.txt"),
+ file: None,
+ file_root: None,
size_bytes: 100,
status: ArtifactStatus::Ready,
created_at,
@@ -261,9 +263,15 @@ async fn create_artifact_publishes_artifact_pending_event() {
let _handle = collector.subscribe();
let tmp = TempDir::new().unwrap();
- let (meta, _path) = create_artifact(tmp.path(), ArtifactKind::Presentation, "Q3 Deck", "pptx")
- .await
- .expect("create_artifact succeeds");
+ let (meta, _path) = create_artifact(
+ tmp.path(),
+ &tmp.path().join("Files"),
+ ArtifactKind::Presentation,
+ "Q3 Deck",
+ "pptx",
+ )
+ .await
+ .expect("create_artifact succeeds");
let expected_workspace = tmp.path().to_string_lossy().into_owned();
// The bus is broadcast-based and processed off-task — wait until the
@@ -352,10 +360,15 @@ async fn artifact_events_fill_request_id_from_chat_context() {
let (meta, _path) = APPROVAL_CHAT_CONTEXT
.scope(ctx, async {
- let (meta, _path) =
- create_artifact(tmp.path(), ArtifactKind::Document, "Report", "pdf")
- .await
- .expect("create_artifact succeeds");
+ let (meta, _path) = create_artifact(
+ tmp.path(),
+ &tmp.path().join("Files"),
+ ArtifactKind::Document,
+ "Report",
+ "pdf",
+ )
+ .await
+ .expect("create_artifact succeeds");
finalize_artifact(tmp.path(), &meta.id, 42)
.await
.expect("finalize_artifact succeeds");
@@ -427,10 +440,15 @@ async fn fail_artifact_fills_request_id_from_chat_context() {
let meta = APPROVAL_CHAT_CONTEXT
.scope(ctx, async {
- let (meta, _path) =
- create_artifact(tmp.path(), ArtifactKind::Document, "Report", "pdf")
- .await
- .expect("create_artifact succeeds");
+ let (meta, _path) = create_artifact(
+ tmp.path(),
+ &tmp.path().join("Files"),
+ ArtifactKind::Document,
+ "Report",
+ "pdf",
+ )
+ .await
+ .expect("create_artifact succeeds");
fail_artifact(tmp.path(), &meta.id, "boom")
.await
.expect("fail_artifact succeeds");
@@ -497,9 +515,15 @@ async fn read_args_errors_when_absent() {
#[tokio::test]
async fn create_artifact_mints_fresh_id_without_scope() {
let tmp = TempDir::new().unwrap();
- let (meta, _path) = create_artifact(tmp.path(), ArtifactKind::Presentation, "Q3 Deck", "pptx")
- .await
- .unwrap();
+ let (meta, _path) = create_artifact(
+ tmp.path(),
+ &tmp.path().join("Files"),
+ ArtifactKind::Presentation,
+ "Q3 Deck",
+ "pptx",
+ )
+ .await
+ .unwrap();
// A normal (non-regenerate) create mints a UUID, never an empty id.
assert!(!meta.id.is_empty());
assert_eq!(meta.status, ArtifactStatus::Pending);
@@ -511,7 +535,14 @@ async fn create_artifact_reuses_id_inside_regenerate_scope() {
let workspace = tmp.path().to_path_buf();
let (meta, _path) = REGENERATE_TARGET_ID
.scope("reused-id".to_string(), async move {
- create_artifact(&workspace, ArtifactKind::Presentation, "Q3 Deck", "pptx").await
+ create_artifact(
+ &workspace,
+ &workspace.join("Files"),
+ ArtifactKind::Presentation,
+ "Q3 Deck",
+ "pptx",
+ )
+ .await
})
.await
.unwrap();
@@ -528,9 +559,15 @@ async fn regenerate_preserves_original_created_at() {
let workspace = tmp.path().to_path_buf();
// First create stamps `created_at = now`.
- let (first, _) = create_artifact(tmp.path(), ArtifactKind::Presentation, "Deck", "pptx")
- .await
- .unwrap();
+ let (first, _) = create_artifact(
+ tmp.path(),
+ &tmp.path().join("Files"),
+ ArtifactKind::Presentation,
+ "Deck",
+ "pptx",
+ )
+ .await
+ .unwrap();
let original_created = first.created_at;
// Regenerate reuses the id; created_at must NOT be bumped, otherwise the
@@ -539,7 +576,14 @@ async fn regenerate_preserves_original_created_at() {
let ws = workspace.clone();
let (second, _) = REGENERATE_TARGET_ID
.scope(id.clone(), async move {
- create_artifact(&ws, ArtifactKind::Presentation, "Deck", "pptx").await
+ create_artifact(
+ &ws,
+ &ws.join("Files"),
+ ArtifactKind::Presentation,
+ "Deck",
+ "pptx",
+ )
+ .await
})
.await
.unwrap();
diff --git a/crates/openhuman-core/src/agent/artifacts/tools.rs b/crates/openhuman-core/src/agent/artifacts/tools.rs
index 34a8bbc51e..bbf27725cf 100644
--- a/crates/openhuman-core/src/agent/artifacts/tools.rs
+++ b/crates/openhuman-core/src/agent/artifacts/tools.rs
@@ -3,12 +3,13 @@
//! Each tool is a thin shim over a read/delete handler in
//! [`crate::agent::artifacts::ops`], unwrapping the `Outcome`
//! envelope and emitting the inner JSON value. The artifacts domain owns
-//! agent-generated files (presentations/documents/images) under
-//! `<workspace>/artifacts/`; these tools let the agent enumerate and
-//! inspect what it has produced.
+//! agent-generated files (presentations/documents/images): metadata under
+//! `<workspace>/artifacts/`, the files themselves in the visible files folder
+//! (`~/OpenHuman/projects/Files`, #5505); these tools let the agent enumerate
+//! and inspect what it has produced.
//!
//! `artifact_list` / `artifact_get` are read-only and default-enabled.
-//! `artifact_delete` is `Dangerous` (irreversible directory removal) and
+//! `artifact_delete` is `Dangerous` (irreversibly removes the file and its record) and
//! ships default-OFF — it must be opted in via the tool toggle
//! (the `artifact_delete` `ToolFamily` in `TOOL_FAMILIES`,
//! `tools/user_filter.rs`).
diff --git a/crates/openhuman-core/src/agent/artifacts/types.rs b/crates/openhuman-core/src/agent/artifacts/types.rs
index 0dfa3dc4c8..b3fc107246 100644
--- a/crates/openhuman-core/src/agent/artifacts/types.rs
+++ b/crates/openhuman-core/src/agent/artifacts/types.rs
@@ -80,8 +80,21 @@ pub struct ArtifactMeta {
pub kind: ArtifactKind,
/// Human-readable title.
pub title: String,
- /// Relative path from the artifacts root, e.g. `"<uuid>/deck.pptx"`.
+ /// The file's name relative to its root. For a record with [`Self::file`]
+ /// set it is relative to [`Self::file_root`] (e.g. `"deck.pptx"`); for a
+ /// legacy record it is relative to `<workspace>/artifacts/`
+ /// (e.g. `"<uuid>/deck.pptx"`).
pub path: String,
+ /// Absolute path of the deliverable in the visible files folder (#5505).
+ /// `None` for records written before that folder existed; those resolve
+ /// under `<workspace>/artifacts/` until the boot migration moves them.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub file: Option<String>,
+ /// The files folder [`Self::file`] was placed in. Recorded per artifact so
+ /// changing the folder later does not strand existing files, and so the
+ /// escape guard has a root to check `file` against.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub file_root: Option<String>,
/// Artifact file size in bytes.
pub size_bytes: u64,
/// Current lifecycle status.
diff --git a/crates/openhuman-core/src/agent/artifacts/types_tests.rs b/crates/openhuman-core/src/agent/artifacts/types_tests.rs
index 9e23f17182..3036eedaa9 100644
--- a/crates/openhuman-core/src/agent/artifacts/types_tests.rs
+++ b/crates/openhuman-core/src/agent/artifacts/types_tests.rs
@@ -105,6 +105,8 @@ fn artifact_meta_serde_roundtrip() {
kind: ArtifactKind::Presentation,
title: "Q3 Deck".to_string(),
path: "abc-123/deck.pptx".to_string(),
+ file: None,
+ file_root: None,
size_bytes: 204800,
status: ArtifactStatus::Ready,
created_at: Utc.with_ymd_and_hms(2025, 6, 1, 12, 0, 0).unwrap(),
@@ -130,6 +132,8 @@ fn artifact_meta_json_shape() {
kind: ArtifactKind::Other,
title: "test".to_string(),
path: "x/file.txt".to_string(),
+ file: None,
+ file_root: None,
size_bytes: 0,
status: ArtifactStatus::Pending,
created_at: Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap(),
@@ -187,6 +191,8 @@ fn artifact_meta_thread_id_none_is_skipped_in_serialised_form() {
kind: ArtifactKind::Other,
title: "t".to_string(),
path: "x/t.txt".to_string(),
+ file: None,
+ file_root: None,
size_bytes: 0,
status: ArtifactStatus::Pending,
created_at: Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap(),
@@ -210,6 +216,8 @@ fn artifact_meta_thread_id_some_round_trips() {
kind: ArtifactKind::Other,
title: "t".to_string(),
path: "x/t.txt".to_string(),
+ file: None,
+ file_root: None,
size_bytes: 0,
status: ArtifactStatus::Pending,
created_at: Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap(),
diff --git a/crates/openhuman-core/src/config/mod.rs b/crates/openhuman-core/src/config/mod.rs
index 094c19da9d..39e29a1820 100644
--- a/crates/openhuman-core/src/config/mod.rs
+++ b/crates/openhuman-core/src/config/mod.rs
@@ -29,9 +29,9 @@ pub use ops::*;
pub use schema::{
action_dir_env_override, active_user_marker_path, active_workspace_dir,
active_workspace_dir_cached, active_workspace_snapshot, clear_active_user, default_action_dir,
- default_projects_dir, default_root_openhuman_dir, is_legacy_tier_model, legacy_tier_role,
- pre_login_user_dir, read_active_user_id, resolve_action_dir, user_openhuman_dir,
- write_active_user_id, PRE_LOGIN_USER_ID, WORKLOAD_ROLES,
+ default_files_dir, default_projects_dir, default_root_openhuman_dir, is_legacy_tier_model,
+ legacy_tier_role, pre_login_user_dir, read_active_user_id, resolve_action_dir,
+ user_openhuman_dir, write_active_user_id, PRE_LOGIN_USER_ID, WORKLOAD_ROLES,
};
pub use workspace_handle::workspace_handle;
// Crate-internal: workspace→config-dir resolver reused by the cloud embedder.
diff --git a/crates/openhuman-core/src/config/ops/agent.rs b/crates/openhuman-core/src/config/ops/agent.rs
index abcee09ecc..777a812b1b 100644
--- a/crates/openhuman-core/src/config/ops/agent.rs
+++ b/crates/openhuman-core/src/config/ops/agent.rs
@@ -401,6 +401,28 @@ pub async fn ensure_agent_dirs(config: &mut Config) {
action = %redact_home(&action_dir),
"[startup] workspace (internal state) and action sandbox (tool cwd) directories configured"
);
+
+ // Agent deliverables are written to the visible files folder (#5505).
+ // Create it up front, and move this account's pre-#5505 artifact files out
+ // of the hidden workspace (idempotent; a no-op once migrated).
+ let files_dir = crate::config::default_files_dir();
+ if let Err(e) = tokio::fs::create_dir_all(&files_dir).await {
+ tracing::warn!(
+ dir = %redact_home(&files_dir),
+ error = %e,
+ "[startup] could not create files folder"
+ );
+ }
+ let report =
+ crate::agent::artifacts::migrate_legacy_artifacts(&config.workspace_dir, &files_dir).await;
+ if report != crate::agent::artifacts::MigrationReport::default() {
+ tracing::info!(
+ moved = report.moved,
+ cleaned = report.cleaned,
+ failed = report.failed,
+ "[startup] moved legacy artifact files into the files folder"
+ );
+ }
}
/// Ensure `dir` is usable as a process working directory: it must exist (we
diff --git a/crates/openhuman-core/src/config/schema/load/dirs.rs b/crates/openhuman-core/src/config/schema/load/dirs.rs
index 9c694d4dd4..7249a2e0a9 100644
--- a/crates/openhuman-core/src/config/schema/load/dirs.rs
+++ b/crates/openhuman-core/src/config/schema/load/dirs.rs
@@ -91,6 +91,17 @@ pub fn default_projects_dir() -> PathBuf {
.join("projects")
}
+/// Name of the visible folder, under the projects home, that holds the files
+/// the agent delivers (decks, documents, generated media) — see #5505.
+pub const FILES_DIRNAME: &str = "Files";
+
+/// Where agent deliverables are written by default: `~/OpenHuman/projects/Files`.
+/// Only the bytes live here; each artifact's metadata stays in the hidden,
+/// per-account `<workspace_dir>/artifacts/<id>/`.
+pub fn default_files_dir() -> PathBuf {
+ default_projects_dir().join(FILES_DIRNAME)
+}
+
/// The `OPENHUMAN_ACTION_DIR` env override, when set to a non-empty value.
///
/// Returns `None` when the variable is unset or blank (a common shape from
diff --git a/crates/openhuman-core/src/config/schema/load/mod.rs b/crates/openhuman-core/src/config/schema/load/mod.rs
index 2a116d3227..a2fe7fd6a4 100644
--- a/crates/openhuman-core/src/config/schema/load/mod.rs
+++ b/crates/openhuman-core/src/config/schema/load/mod.rs
@@ -12,9 +12,9 @@ pub use active_workspace::active_workspace_dir_cached;
pub(crate) use active_workspace::invalidate_active_workspace;
pub use dirs::{
action_dir_env_override, active_user_marker_path, active_workspace_dir,
- active_workspace_snapshot, clear_active_user, default_action_dir, default_projects_dir,
- default_root_openhuman_dir, pre_login_user_dir, read_active_user_id, resolve_action_dir,
- user_openhuman_dir, write_active_user_id, PRE_LOGIN_USER_ID,
+ active_workspace_snapshot, clear_active_user, default_action_dir, default_files_dir,
+ default_projects_dir, default_root_openhuman_dir, pre_login_user_dir, read_active_user_id,
+ resolve_action_dir, user_openhuman_dir, write_active_user_id, PRE_LOGIN_USER_ID,
};
// redact_url_for_log is pub(super) for the schema module; tests inside load
diff --git a/crates/openhuman-core/src/config/schema/mod.rs b/crates/openhuman-core/src/config/schema/mod.rs
index 216937f3f9..48b6a84aa3 100644
--- a/crates/openhuman-core/src/config/schema/mod.rs
+++ b/crates/openhuman-core/src/config/schema/mod.rs
@@ -35,8 +35,9 @@ mod load;
pub use load::{
action_dir_env_override, active_user_marker_path, active_workspace_dir,
active_workspace_dir_cached, active_workspace_snapshot, clear_active_user, default_action_dir,
- default_projects_dir, default_root_openhuman_dir, pre_login_user_dir, read_active_user_id,
- resolve_action_dir, user_openhuman_dir, write_active_user_id, PRE_LOGIN_USER_ID,
+ default_files_dir, default_projects_dir, default_root_openhuman_dir, pre_login_user_dir,
+ read_active_user_id, resolve_action_dir, user_openhuman_dir, write_active_user_id,
+ PRE_LOGIN_USER_ID,
};
// Crate-internal: the invalidation half of the cached active workspace. The
// marker writers in `load_user_state` call it from outside `load`; the
diff --git a/crates/openhuman-core/src/core/events.rs b/crates/openhuman-core/src/core/events.rs
index 865513477b..5b50185c7f 100644
--- a/crates/openhuman-core/src/core/events.rs
+++ b/crates/openhuman-core/src/core/events.rs
@@ -822,8 +822,9 @@ pub enum DomainEvent {
/// relative and would otherwise resolve into the wrong
/// `<workspace>/artifacts/` tree.
workspace_dir: String,
- /// Relative path under `<workspace>/artifacts/`, e.g.
- /// `"<uuid>/deck.pptx"`. The absolute path is reachable via
+ /// The file's name relative to its root: `"deck.pptx"` in the
+ /// visible files folder (#5505), or `"<uuid>/deck.pptx"` under
+ /// `<workspace>/artifacts/` for a legacy record. The absolute path is reachable via
/// `ai_get_artifact` so the renderer never needs the
/// workspace root.
path: String,
@@ -888,8 +889,8 @@ pub enum DomainEvent {
/// Absolute workspace root the artifact belongs to — see
/// [`Self::ArtifactReady::workspace_dir`] for rationale.
workspace_dir: String,
- /// Relative path under `<workspace>/artifacts/` where the file
- /// *will* land. The frontend uses it to render a stable card key
+ /// The name, relative to the visible files folder (#5505), the file
+ /// *will* land under. The frontend uses it to render a stable card key
/// so subsequent `ArtifactReady` can swap the same surface in
/// place without flicker.
path: String,
diff --git a/crates/openhuman-core/src/media/generation/README.md b/crates/openhuman-core/src/media/generation/README.md
index 98a30c7e41..1d20cdcaa8 100644
--- a/crates/openhuman-core/src/media/generation/README.md
+++ b/crates/openhuman-core/src/media/generation/README.md
@@ -40,7 +40,7 @@ agent's tool list; it returns an empty list rather than erroring when no
backend transport is installed, so a library host with no TinyHumans
connection simply has no media tools rather than a broken one. Generated
files land under `<action_dir>/generated-media/`, and `MediaArtifactTool`
-moves each one into the workspace's `artifacts/<id>/` layout so it shows up
+moves each one into the visible files folder (`~/OpenHuman/projects/Files`, metadata in the workspace's `artifacts/<id>/`) so it shows up
as a card in the chat UI. Billing and margin stay backend-side: this module
never charges directly, it only refuses to submit when
`crate::integrations::client::budget_gate` reports the account's managed
diff --git a/crates/openhuman-core/src/media/generation/artifact_tool.rs b/crates/openhuman-core/src/media/generation/artifact_tool.rs
index 2071fb5d2d..5446f90167 100644
--- a/crates/openhuman-core/src/media/generation/artifact_tool.rs
+++ b/crates/openhuman-core/src/media/generation/artifact_tool.rs
@@ -50,18 +50,26 @@ pub struct MediaArtifactTool<T: Tool> {
inner: T,
kind: ArtifactKind,
workspace_dir: PathBuf,
+ /// Visible folder each generated file is moved into (#5505).
+ files_dir: PathBuf,
}
impl<T: Tool> MediaArtifactTool<T> {
/// `kind` is the artifact category to file every generated output
/// under (`ArtifactKind::Image` / `ArtifactKind::Video`); `workspace_dir`
- /// is the same workspace root the rest of the artifacts module writes
- /// `<workspace_dir>/artifacts/<id>/...` under.
- pub fn new(inner: T, kind: ArtifactKind, workspace_dir: impl Into<PathBuf>) -> Self {
+ /// holds the artifact metadata; `files_dir` is the visible folder the
+ /// generated file is moved into (#5505).
+ pub fn new(
+ inner: T,
+ kind: ArtifactKind,
+ workspace_dir: impl Into<PathBuf>,
+ files_dir: impl Into<PathBuf>,
+ ) -> Self {
Self {
inner,
kind,
workspace_dir: workspace_dir.into(),
+ files_dir: files_dir.into(),
}
}
@@ -134,6 +142,7 @@ impl<T: Tool> MediaArtifactTool<T> {
let title = Self::artifact_title(args, index, total);
let (meta, dest) = match create_artifact_for_call(
&self.workspace_dir,
+ &self.files_dir,
self.kind.clone(),
&title,
&ext,
@@ -187,7 +196,7 @@ fn set_artifact_error(entry: &mut Value, message: &str) {
}
/// Moves `src` to `dest`, falling back to copy + remove across filesystem
-/// boundaries (`rename` fails with `EXDEV` when the artifacts root and the
+/// boundaries (`rename` fails with `EXDEV` when the files folder and the
/// media output dir are on different mounts). Returns the final file size.
async fn move_or_copy(src: &Path, dest: &Path) -> Result<u64, String> {
if tokio::fs::rename(src, dest).await.is_err() {
diff --git a/crates/openhuman-core/src/media/generation/artifact_tool_tests.rs b/crates/openhuman-core/src/media/generation/artifact_tool_tests.rs
index eab9fcb706..fc15401a30 100644
--- a/crates/openhuman-core/src/media/generation/artifact_tool_tests.rs
+++ b/crates/openhuman-core/src/media/generation/artifact_tool_tests.rs
@@ -79,6 +79,7 @@ async fn files_a_single_generated_artifact() {
},
ArtifactKind::Image,
workspace.clone(),
+ root.path().join("Files"),
);
let result = wrapped
@@ -115,6 +116,7 @@ async fn files_every_artifact_when_n_greater_than_one() {
},
ArtifactKind::Image,
workspace.clone(),
+ root.path().join("Files"),
);
let result = wrapped
@@ -148,6 +150,7 @@ async fn leaves_an_errored_tool_result_untouched() {
},
ArtifactKind::Image,
workspace.clone(),
+ root.path().join("Files"),
);
let result = wrapped.execute(json!({ "prompt": "x" })).await.unwrap();
@@ -166,7 +169,8 @@ async fn host_metadata_forwards_to_the_inner_tool() {
fail: false,
},
ArtifactKind::Video,
- workspace,
+ workspace.clone(),
+ workspace.join("Files"),
);
assert_eq!(wrapped.name(), "stub_generate");
assert_eq!(wrapped.permission_level(), PermissionLevel::ReadOnly);
diff --git a/crates/openhuman-core/src/media/generation/tools.rs b/crates/openhuman-core/src/media/generation/tools.rs
index 022cf3a5d7..a9e0a6a968 100644
--- a/crates/openhuman-core/src/media/generation/tools.rs
+++ b/crates/openhuman-core/src/media/generation/tools.rs
@@ -54,6 +54,7 @@ pub fn build_media_tools(root_config: &Config, action_dir: &Path) -> Vec<Box<dyn
generators,
action_dir,
&root_config.workspace_dir,
+ &crate::config::default_files_dir(),
WaitPolicy::new(VIDEO_POLL_INTERVAL, VIDEO_WAIT_BUDGET),
)
}
@@ -65,6 +66,7 @@ pub fn media_tools_from(
generators: MediaGenerators,
action_dir: &Path,
workspace_dir: &Path,
+ files_dir: &Path,
video_wait: WaitPolicy,
) -> Vec<Box<dyn Tool>> {
let MediaGenerators { image, video } = generators;
@@ -79,6 +81,7 @@ pub fn media_tools_from(
.with_category(ToolCategory::Workflow),
ArtifactKind::Image,
workspace_dir.to_path_buf(),
+ files_dir.to_path_buf(),
)),
Box::new(MediaArtifactTool::new(
GenerateVideoTool::new(Arc::clone(&video), output)
@@ -89,6 +92,7 @@ pub fn media_tools_from(
.with_wait_policy(video_wait),
ArtifactKind::Video,
workspace_dir.to_path_buf(),
+ files_dir.to_path_buf(),
)),
Box::new(MediaListModelsTool { image, video }),
];
diff --git a/crates/openhuman-core/src/media/generation/tools_tests.rs b/crates/openhuman-core/src/media/generation/tools_tests.rs
index cf08ebbd28..5107de67a5 100644
--- a/crates/openhuman-core/src/media/generation/tools_tests.rs
+++ b/crates/openhuman-core/src/media/generation/tools_tests.rs
@@ -19,6 +19,7 @@ fn tools(action_dir: &Path) -> Vec<Box<dyn Tool>> {
},
action_dir,
&action_dir.join("workspace"),
+ &action_dir.join("Files"),
tinyagents_harness::tinyinference_video::WaitPolicy::new(
std::time::Duration::from_millis(1),
std::time::Duration::from_secs(5),
@@ -150,20 +151,21 @@ async fn image_tool_files_each_generated_file_as_an_artifact() {
.count();
assert_eq!(staged, 0, "generated file should have been moved");
- // ...and the file now lives under the artifact store, alongside the
- // `meta.json` record `create_artifact_for_call` writes.
+ // ...the file now lives in the visible files folder (#5505), and only the
+ // `meta.json` record stays in the hidden artifact store.
let workspace = dir.path().join("workspace");
let artifact_dir = workspace.join("artifacts").join(artifact_id);
let entries: Vec<String> = std::fs::read_dir(&artifact_dir)
.unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
.collect();
- assert!(entries.contains(&"meta.json".to_string()), "{entries:?}");
- assert_eq!(
- entries.len(),
- 2,
- "expected meta.json + the moved media file under {artifact_dir:?}, got {entries:?}"
- );
+ assert_eq!(entries, vec!["meta.json".to_string()], "{artifact_dir:?}");
+ let filed: Vec<_> = std::fs::read_dir(dir.path().join("Files"))
+ .unwrap()
+ .map(|e| e.unwrap().path())
+ .collect();
+ assert_eq!(filed.len(), 1, "{filed:?}");
+ assert!(std::fs::metadata(&filed[0]).unwrap().len() > 0);
}
#[tokio::test]
diff --git a/crates/openhuman-core/src/security/policy/policy_workspace_internal_tests.rs b/crates/openhuman-core/src/security/policy/policy_workspace_internal_tests.rs
index 8082d0ad4c..599a844970 100644
--- a/crates/openhuman-core/src/security/policy/policy_workspace_internal_tests.rs
+++ b/crates/openhuman-core/src/security/policy/policy_workspace_internal_tests.rs
@@ -42,6 +42,22 @@ fn is_workspace_internal_path_blocks_state_dirs() {
assert!(policy.is_workspace_internal_path(&ws.join("codegraph")));
}
+/// #5505: `meta.json` names the file an artifact owns, and Download /
+/// `read_artifact_bytes` follow it, so the artifact metadata store is internal
+/// state. The deliverables themselves live in the visible files folder.
+#[test]
+fn is_workspace_internal_path_blocks_artifact_metadata() {
+ let tmp = tempfile::tempdir().expect("tempdir");
+ let ws = tmp.path().to_path_buf();
+ let policy = SecurityPolicy {
+ workspace_dir: ws.clone(),
+ action_dir: ws.join("action"),
+ ..SecurityPolicy::default()
+ };
+ assert!(policy.is_workspace_internal_path(&ws.join("artifacts").join("abc").join("meta.json")));
+ assert!(!policy.is_workspace_internal_path(&ws.join("action").join("Files").join("deck.pptx")));
+}
+
#[test]
fn is_workspace_internal_path_blocks_state_files() {
let tmp = tempfile::tempdir().expect("tempdir");
diff --git a/crates/openhuman-core/src/security/policy/types.rs b/crates/openhuman-core/src/security/policy/types.rs
index ed99a16dd9..e392b447f8 100644
--- a/crates/openhuman-core/src/security/policy/types.rs
+++ b/crates/openhuman-core/src/security/policy/types.rs
@@ -209,6 +209,11 @@ pub(super) const WORKSPACE_INTERNAL_DIRS: &[&str] = &[
// A removed relay domain may leave encrypted identity/session state in an
// upgraded workspace. Keep that legacy directory private.
"tinyplace",
+ // Artifact metadata (`meta.json` names the file an artifact owns, and
+ // Download / read_artifact_bytes follow it). The deliverables themselves
+ // live in the visible files folder (#5505), so nothing here is an agent
+ // work product.
+ "artifacts",
];
/// Files directly under `workspace_dir` that hold secrets or persona config
diff --git a/crates/openhuman-core/src/tools/impl/document/document_tests.rs b/crates/openhuman-core/src/tools/impl/document/document_tests.rs
index 44a0149874..db52a327b3 100644
--- a/crates/openhuman-core/src/tools/impl/document/document_tests.rs
+++ b/crates/openhuman-core/src/tools/impl/document/document_tests.rs
@@ -36,7 +36,11 @@ fn test_security(workspace: &Path) -> Arc<SecurityPolicy> {
}
fn make_tool(workspace: &Path) -> DocumentTool {
- DocumentTool::new(workspace.to_path_buf(), test_security(workspace))
+ DocumentTool::new(
+ workspace.to_path_buf(),
+ workspace.join("Files"),
+ test_security(workspace),
+ )
}
fn minimal_input_json() -> serde_json::Value {
diff --git a/crates/openhuman-core/src/tools/impl/document/mod.rs b/crates/openhuman-core/src/tools/impl/document/mod.rs
index 753024f37d..ebaffffb88 100644
--- a/crates/openhuman-core/src/tools/impl/document/mod.rs
+++ b/crates/openhuman-core/src/tools/impl/document/mod.rs
@@ -71,6 +71,8 @@ pub const TOOL_NAME: &str = "generate_document";
/// One-shot `.docx` generator. See module docs for the request flow.
pub struct DocumentTool {
workspace_dir: PathBuf,
+ /// Visible folder the generated document is written into (#5505).
+ files_dir: PathBuf,
/// Retained for constructor parity with [`PresentationTool`] (both are
/// registered identically in `tools::ops`) and for future features
/// (e.g. embedding a `File`-source image) that will need the same
@@ -84,9 +86,10 @@ impl DocumentTool {
/// directory the artifact pipeline writes into, plus the active
/// [`SecurityPolicy`] (same signature as [`PresentationTool::new`] so
/// both tools register with an identical call).
- pub fn new(workspace_dir: PathBuf, security: Arc<SecurityPolicy>) -> Self {
+ pub fn new(workspace_dir: PathBuf, files_dir: PathBuf, security: Arc<SecurityPolicy>) -> Self {
Self {
workspace_dir,
+ files_dir,
security,
}
}
@@ -201,6 +204,7 @@ impl Tool for DocumentTool {
let (meta, output_path) = create_artifact(
&self.workspace_dir,
+ &self.files_dir,
ArtifactKind::Document,
&input.title,
"docx",
diff --git a/crates/openhuman-core/src/tools/impl/presentation/mod.rs b/crates/openhuman-core/src/tools/impl/presentation/mod.rs
index dd3f62f13f..0c646d581f 100644
--- a/crates/openhuman-core/src/tools/impl/presentation/mod.rs
+++ b/crates/openhuman-core/src/tools/impl/presentation/mod.rs
@@ -67,6 +67,8 @@ pub const TOOL_NAME: &str = "generate_presentation";
/// One-shot `.pptx` generator. See module docs for the request flow.
pub struct PresentationTool {
workspace_dir: PathBuf,
+ /// Visible folder the generated deck is written into (#5505).
+ files_dir: PathBuf,
/// Existing host config when the caller already owns the authoritative
/// runtime snapshot. Keeping this optional preserves the ordinary agent
/// constructor while avoiding a process-global config reload during
@@ -84,9 +86,10 @@ impl PresentationTool {
/// resolution, venv setup, or cache directory needed. Pass the
/// workspace directory the artifact pipeline writes into, plus the
/// active [`SecurityPolicy`] for validating `File`-source image paths.
- pub fn new(workspace_dir: PathBuf, security: Arc<SecurityPolicy>) -> Self {
+ pub fn new(workspace_dir: PathBuf, files_dir: PathBuf, security: Arc<SecurityPolicy>) -> Self {
Self {
workspace_dir,
+ files_dir,
config: None,
security,
}
@@ -95,11 +98,13 @@ impl PresentationTool {
/// Construct the tool with an authoritative host config snapshot.
pub(crate) fn with_config(
workspace_dir: PathBuf,
+ files_dir: PathBuf,
security: Arc<SecurityPolicy>,
config: crate::config::Config,
) -> Self {
Self {
workspace_dir,
+ files_dir,
config: Some(config),
security,
}
@@ -256,6 +261,7 @@ impl Tool for PresentationTool {
let (meta, output_path) = create_artifact(
&self.workspace_dir,
+ &self.files_dir,
ArtifactKind::Presentation,
&input.title,
"pptx",
diff --git a/crates/openhuman-core/src/tools/impl/presentation/presentation_tests.rs b/crates/openhuman-core/src/tools/impl/presentation/presentation_tests.rs
index cfad6291d0..2722ba2fce 100644
--- a/crates/openhuman-core/src/tools/impl/presentation/presentation_tests.rs
+++ b/crates/openhuman-core/src/tools/impl/presentation/presentation_tests.rs
@@ -39,7 +39,11 @@ fn test_security(workspace: &Path) -> Arc<SecurityPolicy> {
/// Build a tool whose security policy is rooted at `workspace`.
fn make_tool(workspace: &Path) -> PresentationTool {
- PresentationTool::new(workspace.to_path_buf(), test_security(workspace))
+ PresentationTool::new(
+ workspace.to_path_buf(),
+ workspace.join("Files"),
+ test_security(workspace),
+ )
}
fn minimal_input_json() -> serde_json::Value {
diff --git a/crates/openhuman-core/src/tools/ops.rs b/crates/openhuman-core/src/tools/ops.rs
index 7d6b2604d2..45e9a86230 100644
--- a/crates/openhuman-core/src/tools/ops.rs
+++ b/crates/openhuman-core/src/tools/ops.rs
@@ -462,15 +462,9 @@ pub fn all_tools_with_runtime(
// diff, lint and test the working tree in the action sandbox. They
// were defined but never registered, so the belts naming them held
// nothing. `Deferred`, so they cost no schema until found.
- Box::new(ReadDiffTool::new(
- action_dir.to_path_buf(),
- )),
- Box::new(RunLinterTool::new(
- action_dir.to_path_buf(),
- )),
- Box::new(RunTestsTool::new(
- action_dir.to_path_buf(),
- )),
+ Box::new(ReadDiffTool::new(action_dir.to_path_buf())),
+ Box::new(RunLinterTool::new(action_dir.to_path_buf())),
+ Box::new(RunTestsTool::new(action_dir.to_path_buf())),
Box::new(PushoverTool::new(
security.clone(),
action_dir.to_path_buf(),
@@ -665,6 +659,7 @@ pub fn all_tools_with_runtime(
#[cfg(feature = "documents")]
tools.push(Box::new(PresentationTool::new(
root_config.workspace_dir.clone(),
+ crate::config::default_files_dir(),
security.clone(),
)));
@@ -675,6 +670,7 @@ pub fn all_tools_with_runtime(
#[cfg(feature = "documents")]
tools.push(Box::new(DocumentTool::new(
root_config.workspace_dir.clone(),
+ crate::config::default_files_dir(),
security.clone(),
)));
diff --git a/gitbooks/guides/move-to-new-pc.md b/gitbooks/guides/move-to-new-pc.md
index 84ef80c21f..3576968a95 100644
--- a/gitbooks/guides/move-to-new-pc.md
+++ b/gitbooks/guides/move-to-new-pc.md
@@ -62,7 +62,7 @@ Copy the **entire** data folder from the old machine to the same location on the
Copy the whole folder rather than cherry-picking. It keeps memory, persona, config, and history consistent with each other.
-The data folder holds config and memory but **not** the files the agent created or edited in its action sandbox. Also copy your **projects/action folder**, by default `~/OpenHuman/projects` (or wherever you pointed the action directory). Otherwise those project files stay behind on the old PC.
+The data folder holds config and memory but **not** the files the agent created or edited in its action sandbox. Also copy your **projects/action folder**, by default `~/OpenHuman/projects` (or wherever you pointed the action directory). Otherwise those project files stay behind on the old PC. That folder also holds `Files` (`~/OpenHuman/projects/Files`), where the decks, documents and generated images and videos the agent delivers are saved.
{% hint style="warning" %}
Copy it somewhere secure. This folder contains your personal memory in readable form. Treat the transfer like moving personal documents.