The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(artifacts): serve the preview body from the core
Sanil9b2dc1f333f5
diff --git a/app/src/features/conversations/aui/ArtifactPreviewPanel.markdown.test.tsx b/app/src/features/conversations/aui/ArtifactPreviewPanel.markdown.test.tsxindex b19be40a48..fde1934622 100644--- a/app/src/features/conversations/aui/ArtifactPreviewPanel.markdown.test.tsx+++ b/app/src/features/conversations/aui/ArtifactPreviewPanel.markdown.test.tsx@@ -1,26 +1,35 @@import { configureStore } from '@reduxjs/toolkit';-import { invoke } from '@tauri-apps/api/core';import { fireEvent, render, screen } from '@testing-library/react';import { Provider } from 'react-redux';import { beforeEach, describe, expect, it, vi } from 'vitest';+import { callCoreRpc } from '../../../services/coreRpcClient';import chatRuntimeReducer, {openArtifact,upsertArtifactReadyForThread,} from '../../../store/chatRuntimeSlice';import { ArtifactPreviewPanel } from './ArtifactPreviewPanel';+vi.mock('../../../services/coreRpcClient', () => ({ callCoreRpc: vi.fn() }));+vi.mock('../../../lib/i18n/I18nContext', () => ({useT: () => ({ t: (k: string) => k, locale: 'en' }),}));const MD = '# Hello\n\nThis is **bold** text.\n';-function renderPanel(kind: string, body: string, failWith?: string) {+function renderPanel(kind: string, body: string, failWith?: string, converted = false) {// Stub the body fetch BEFORE mounting so the panel's effect resolves it.- if (failWith) vi.mocked(invoke).mockRejectedValue(failWith);+ if (failWith) vi.mocked(callCoreRpc).mockRejectedValue(failWith);else- vi.mocked(invoke).mockResolvedValue({ kind, title: 'Notes', version: 1, body, is_text: true });+ vi.mocked(callCoreRpc).mockResolvedValue({+ kind,+ title: 'Notes',+ version: 1,+ body,+ is_text: true,+ converted,+ });const store = configureStore({ reducer: { chatRuntime: chatRuntimeReducer } });store.dispatch(upsertArtifactReadyForThread({@@ -42,7 +51,7 @@ function renderPanel(kind: string, body: string, failWith?: string) {describe('ArtifactPreviewPanel — preview rendering by kind (#1535)', () => {beforeEach(() => {- vi.mocked(invoke).mockReset();+ vi.mocked(callCoreRpc).mockReset();});it('renders markdown as formatted content, not raw source', async () => {@@ -58,6 +67,25 @@ describe('ArtifactPreviewPanel — preview rendering by kind (#1535)', () => {expect(screen.queryByText(/# Hello/)).toBeNull();});+ it('reads the body from the core', async () => {+ renderPanel('markdown', MD);+ await screen.findByRole('heading', { level: 1 });+ expect(callCoreRpc).toHaveBeenCalledWith({+ method: 'openhuman.ai_read_artifact_body',+ params: { artifact_id: 'a-1' },+ });+ });++ it('renders a converted document as Markdown, read-only', async () => {+ renderPanel('file', '# Quarterly report\n\nRevenue **up**.\n', undefined, true);++ const h1 = await screen.findByRole('heading', { level: 1 });+ expect(h1.textContent).toBe('Quarterly report');+ fireEvent.click(screen.getByRole('button', { name: /Code/ }));+ // The artifact is the file, not this text: it cannot be edited here.+ expect((screen.getByRole('textbox') as HTMLTextAreaElement).readOnly).toBe(true);+ });+it('renders GFM constructs (tables) via remark-gfm', async () => {renderPanel('markdown', '| a | b |\n| --- | --- |\n| one | two |\n');diff --git a/app/src/features/conversations/aui/ArtifactPreviewPanel.tsx b/app/src/features/conversations/aui/ArtifactPreviewPanel.tsxindex 95340accb8..4cc685868f 100644--- a/app/src/features/conversations/aui/ArtifactPreviewPanel.tsx+++ b/app/src/features/conversations/aui/ArtifactPreviewPanel.tsx@@ -32,6 +32,8 @@ interface ArtifactBodyResponse {version: number;body: string;is_text: boolean;+ /** `body` is Markdown converted from a document file (DOCX, PDF, ...). */+ converted?: boolean;}// ─── Constants ──────────────────────────────────────────────────@@ -223,8 +225,11 @@ function ArtifactContentPanel({ artifact }: { artifact: ArtifactSnapshot }) {const fetchBody = async () => {try {- const result = await invoke<ArtifactBodyResponse>('read_artifact_body', {- artifactId: artifact.artifactId,+ // Read from the core the app talks to (local or remote): it opens the+ // file and converts documents where the artifact lives.+ const result = await callCoreRpc<ArtifactBodyResponse>({+ method: 'openhuman.ai_read_artifact_body',+ params: { artifact_id: artifact.artifactId },});if (!cancelled) setBodyResult(result);} catch (err) {@@ -251,6 +256,7 @@ function ArtifactContentPanel({ artifact }: { artifact: ArtifactSnapshot }) {const body = bodyResult?.body || '';const version = bodyResult?.version || 1;const isText = bodyResult?.is_text ?? false;+ const converted = bodyResult?.converted ?? false;// File kind whose body is actual readable text → editable viewer.// Truly binary files (body stays a path) → FileViewer (metadata + download).@@ -263,6 +269,7 @@ function ArtifactContentPanel({ artifact }: { artifact: ArtifactSnapshot }) {version={version}kind={kind}error={error}+ converted={converted}/>);}@@ -620,12 +627,15 @@ function EditableTextViewer({version,kind,error,+ converted = false,}: {artifact: ArtifactSnapshot;body: string;version: number;kind: string;error: string | null;+ /** The body is Markdown converted from a document file: render it as such. */+ converted?: boolean;}) {const [tab, setTab] = useState<'preview' | 'code'>('preview');const [editedBody, setEditedBody] = useState(body);@@ -667,7 +677,7 @@ function EditableTextViewer({// const sharing = useArtifactShare(artifact.artifactId, autosave.flush);const isHtml = kind === 'html';- const isMarkdown = kind === 'markdown';+ const isMarkdown = kind === 'markdown' || converted;return (<div className="flex flex-col h-full">diff --git a/crates/openhuman-app/permissions/README.md b/crates/openhuman-app/permissions/README.mdindex a109224dd2..ddfc6d5ac5 100644--- a/crates/openhuman-app/permissions/README.md+++ b/crates/openhuman-app/permissions/README.md@@ -34,7 +34,7 @@ RuntimeAuthority::resolve_access| [`allow-core-process.toml`](allow-core-process.toml) | `allow-core-process` | Core endpoint and lifecycle (`core_rpc_*`, `relay_http_rpc`, `relay_remote_socket`, `start_core_process`, `restart_core_process`, `reset_local_data`), app control (`restart_app`, `app_quit`), session (`get_active_user_id`, `auth_*`), dictation and push-to-talk hotkeys, `show_ptt_overlay`, `activate_main_window`, notch window, native notifications, and log folder commands. || [`allow-app-update.toml`](allow-app-update.toml) | `allow-app-update` | `check_app_update`, `apply_app_update`, `download_app_update`, `install_app_update`. || [`allow-workspace-files.toml`](allow-workspace-files.toml) | `allow-workspace-files` | `open_workspace_path`, `reveal_workspace_path`, `preview_workspace_text`. |-| [`allow-artifact-download.toml`](allow-artifact-download.toml) | `allow-artifact-download` | `download_artifact_to_downloads`, `read_artifact_body`, `save_artifact_as`. |+| [`allow-artifact-download.toml`](allow-artifact-download.toml) | `allow-artifact-download` | `download_artifact_to_downloads`, `save_artifact_as`. || `allow-artifact-save.toml` | `allow-artifact-save` | `save_artifact_via_dialog`. || [`allow-directory-picker.toml`](allow-directory-picker.toml) | `allow-directory-picker` | `pick_directory_via_dialog`. || [`allow-loopback-oauth.toml`](allow-loopback-oauth.toml) | `allow-loopback-oauth` | `start_loopback_oauth_listener`, `stop_loopback_oauth_listener`. Kept separate so a consumer of `allow-core-process` does not also get OAuth listener control. |diff --git a/crates/openhuman-app/permissions/allow-artifact-download.toml b/crates/openhuman-app/permissions/allow-artifact-download.tomlindex 9b6711467c..69ad7dddad 100644--- a/crates/openhuman-app/permissions/allow-artifact-download.toml+++ b/crates/openhuman-app/permissions/allow-artifact-download.toml@@ -6,7 +6,6 @@ description = "Allow copying agent-generated artifacts from the workspace artifaallow = ["download_artifact_to_downloads",- "read_artifact_body","save_artifact_as",]diff --git a/crates/openhuman-app/src/artifact_commands.rs b/crates/openhuman-app/src/artifact_commands.rsindex dcc6b66a69..f25f467b3b 100644--- a/crates/openhuman-app/src/artifact_commands.rs+++ b/crates/openhuman-app/src/artifact_commands.rs@@ -25,7 +25,6 @@//! already vouches for. The filename hint is still sanitized so nothing is//! written outside the Downloads directory.-use serde::Serialize;use std::path::{Path, PathBuf};/// Resolve an artifact id to the file the core's artifact store vouches for,@@ -50,118 +49,6 @@ async fn copy_to_path(source: &Path, dest: &Path) -> Result<u64, String> {.map_err(|e| format!("failed to copy artifact to {:?}: {e}", dest))}-#[derive(Serialize)]-pub struct ArtifactBodyResult {- pub kind: String,- pub title: String,- pub version: u32,- pub body: String,- pub is_text: bool,-}--/// Largest file the preview reads as text. A bigger file shows as a file-/// (metadata and download) without being loaded into memory.-const PREVIEW_MAX_BYTES: u64 = 10 * 1024 * 1024;--/// An artifact id is one file name in the versioned store: anything that could-/// name another file (a separator, `..`, a drive prefix) is refused.-fn check_artifact_id(artifact_id: &str) -> Result<(), String> {- let id = artifact_id.trim();- if id.is_empty() || id.starts_with('.') || id.contains(['/', '\\', ':', '\0']) {- return Err(format!("invalid artifact id {artifact_id:?}"));- }- Ok(())-}--#[tauri::command]-pub async fn read_artifact_body(artifact_id: String) -> Result<ArtifactBodyResult, String> {- let config = openhuman_rpc::embed::config::load_host_config().await?;- // A file version may point into the agent's working folder or the files- // folders, the same places the artifact service accepts.- let roots = openhuman_rpc::embed::artifacts::FileRoots::from_config(&config)- .with_trusted([config.action_dir.clone()]);- read_body_in(&config.workspace_dir, &roots, &artifact_id).await-}--/// [`read_artifact_body`] for a given workspace and its trusted folders.-async fn read_body_in(- workspace_dir: &Path,- roots: &openhuman_rpc::embed::artifacts::FileRoots,- artifact_id: &str,-) -> Result<ArtifactBodyResult, String> {- check_artifact_id(artifact_id)?;- let artifact_id = artifact_id.trim();- let path = workspace_dir- .join("artifacts/versioned")- .join(format!("{artifact_id}.json"));- let json = tokio::fs::read_to_string(&path)- .await- .map_err(|e| format!("artifact {artifact_id} not found: {e}"))?;- let record: serde_json::Value = serde_json::from_str(&json)- .map_err(|e| format!("artifact {artifact_id} parse error: {e}"))?;- let kind = record["kind"].as_str().unwrap_or("text").to_string();- let title = record["title"].as_str().unwrap_or("artifact").to_string();- let versions = record["versions"]- .as_array()- .map(|v| v.len() as u32)- .unwrap_or(0);- let mut body = record["versions"]- .as_array()- .and_then(|v| v.last())- .and_then(|v| v["body"].as_str())- .unwrap_or("")- .to_string();- let mut is_text = kind != "file" && kind != "image";-- // For file-kind artifacts the body is a path to a real file. Try to read- // its text content so the panel can render it (md/txt/html/etc).- // Truly binary files stay as paths — the panel shows metadata + download.- // A file outside the trusted folders (a hand-edited record) is never- // opened: it shows as a file, its path only.- if kind == "file" && !body.is_empty() && roots.holds(Path::new(&body)) {- let file_path = PathBuf::from(&body);- let small_enough = tokio::fs::metadata(&file_path)- .await- .is_ok_and(|meta| meta.len() <= PREVIEW_MAX_BYTES);- // First pass: try the native UTF-8 read (text files like .md, .txt)- match if small_enough {- tokio::fs::read(&file_path).await- } else {- Err(std::io::Error::other("too large to preview"))- } {- Ok(bytes) => {- let probe = &bytes[..bytes.len().min(8192)];- if !probe.contains(&0) && std::str::from_utf8(probe).is_ok() {- if let Ok(text) = String::from_utf8(bytes) {- body = text;- is_text = true;- }- }- }- Err(_) => {}- }- // If still no text and it's a .docx, try to extract text via Python- if !is_text- && small_enough- && file_path.extension().and_then(|e| e.to_str()) == Some("docx")- {- if let Ok(text) = crate::docx::extract_text(&file_path) {- if !text.is_empty() {- body = text;- is_text = true;- }- }- }- }- Ok(ArtifactBodyResult {- kind,- title,- version: versions,- body,- is_text,- })-}-/// Ask the user where to save an artifact (the OS save dialog, prefilled with/// `filename`) and copy the artifact's file there.///diff --git a/crates/openhuman-app/src/artifact_commands_tests.rs b/crates/openhuman-app/src/artifact_commands_tests.rsindex be8f2191fa..91ef35954b 100644--- a/crates/openhuman-app/src/artifact_commands_tests.rs+++ b/crates/openhuman-app/src/artifact_commands_tests.rs@@ -243,126 +243,3 @@ async fn download_rejects_invalid_inputs() {.is_err());}--fn versioned_record(workspace: &Path, id: &str, kind: &str, body: &str) {- let dir = workspace.join("artifacts/versioned");- std::fs::create_dir_all(&dir).unwrap();- let record = serde_json::json!({- "id": id,- "title": "T",- "kind": kind,- "versions": [{ "version": 1, "body": body }],- });- std::fs::write(dir.join(format!("{id}.json")), record.to_string()).unwrap();-}--#[test]-fn artifact_ids_that_name_another_file_are_refused() {- for id in [- "", " ", ".", "..", "../x", "a/b", "a\\b", "C:x", ".hidden", "a\0b",- ] {- assert!(check_artifact_id(id).is_err(), "{id:?} must be refused");- }- assert!(check_artifact_id("2bf47908-fdef-40b2-953c-d72c47314290").is_ok());-}--#[tokio::test]-async fn read_body_never_leaves_the_versioned_store() {- let workspace = tempfile::tempdir().unwrap();- // A record outside `artifacts/versioned` that names a readable file.- let secret = workspace.path().join("secret.txt");- std::fs::write(&secret, "do not read").unwrap();- let outside = serde_json::json!({- "kind": "file",- "versions": [{ "body": secret.display().to_string() }],- });- std::fs::write(workspace.path().join("x.json"), outside.to_string()).unwrap();-- let err = read_body_in(- workspace.path(),- &FileRoots::new(workspace.path()),- "../../x",- )- .await- .err()- .unwrap();- assert!(err.contains("invalid artifact id"), "{err}");-}--#[tokio::test]-async fn read_body_returns_a_text_version_and_a_small_text_file() {- let workspace = tempfile::tempdir().unwrap();- versioned_record(workspace.path(), "md-1", "markdown", "# hi");- let text = read_body_in(workspace.path(), &FileRoots::new(workspace.path()), "md-1")- .await- .unwrap();- assert_eq!((text.body.as_str(), text.is_text), ("# hi", true));-- let file = workspace.path().join("notes.txt");- std::fs::write(&file, "plain notes").unwrap();- versioned_record(workspace.path(), "f-1", "file", &file.display().to_string());- let read = read_body_in(workspace.path(), &FileRoots::new(workspace.path()), "f-1")- .await- .unwrap();- assert_eq!((read.body.as_str(), read.is_text), ("plain notes", true));-}--#[tokio::test]-async fn a_file_over_the_preview_limit_is_not_read() {- let workspace = tempfile::tempdir().unwrap();- let file = workspace.path().join("big.txt");- let handle = std::fs::File::create(&file).unwrap();- handle.set_len(PREVIEW_MAX_BYTES + 1).unwrap();- let path = file.display().to_string();- versioned_record(workspace.path(), "big-1", "file", &path);-- let read = read_body_in(workspace.path(), &FileRoots::new(workspace.path()), "big-1")- .await- .unwrap();- // Shown as a file: the body stays its path.- assert!(!read.is_text);- assert_eq!(read.body, path);-}--#[test]-fn docx_text_keeps_words_split_across_runs() {- let dir = tempfile::tempdir().unwrap();- let docx = dir.path().join("split.docx");- let xml = concat!(- r#"<w:document><w:body>"#,- r#"<w:p><w:r><w:t>Hel</w:t></w:r><w:r><w:rPr><w:b/></w:rPr><w:t>lo</w:t></w:r>"#,- r#"<w:r><w:t xml:space="preserve"> world & more</w:t></w:r></w:p>"#,- r#"<w:p><w:r><w:t>Second</w:t></w:r></w:p>"#,- r#"</w:body></w:document>"#- );- let made = std::process::Command::new("python3")- .arg("-c")- .arg("import sys, zipfile\nwith zipfile.ZipFile(sys.argv[1], 'w') as z: z.writestr('word/document.xml', sys.argv[2])")- .arg(&docx)- .arg(xml)- .status();- if !made.is_ok_and(|status| status.success()) {- eprintln!("python3 unavailable; skipping");- return;- }- assert_eq!(- crate::docx::extract_text(&docx).unwrap(),- "Hello world & more\nSecond"- );-}--#[tokio::test]-async fn a_file_outside_the_trusted_folders_is_not_read() {- let workspace = tempfile::tempdir().unwrap();- let elsewhere = tempfile::tempdir().unwrap();- let secret = elsewhere.path().join("secret.txt");- std::fs::write(&secret, "do not read").unwrap();- let path = secret.display().to_string();- versioned_record(workspace.path(), "out-1", "file", &path);-- let read = read_body_in(workspace.path(), &FileRoots::new(workspace.path()), "out-1")- .await- .unwrap();- assert!(!read.is_text);- assert_eq!(read.body, path);-}diff --git a/crates/openhuman-app/src/docx.rs b/crates/openhuman-app/src/docx.rsdeleted file mode 100644index f0d51da19d..0000000000--- a/crates/openhuman-app/src/docx.rs+++ /dev/null@@ -1,47 +0,0 @@-//! Minimal `.docx` text extraction for artifact previewing.-//!-//! A `.docx` is a ZIP container whose `word/document.xml` holds the text.-//! Rather than pulling the whole `zip` crate into the shell binary, we-//! delegate to the platform `python3` (present on macOS and most Linux-//! systems). If python3 is missing (or the file is not a real docx),-//! extraction fails cleanly and the panel falls back to the file viewer.--use std::path::Path;--/// Extract plain text from a `.docx` file. Returns empty string on failure.-pub fn extract_text(path: &Path) -> Result<String, String> {- use std::process::Command;-- // Text runs (`<w:t>`) are joined as they are: formatting can split one- // word across several runs. Paragraphs, line breaks and tabs become- // whitespace; every other tag is dropped.- let script = r#"-import sys, zipfile, re, html-try:- with zipfile.ZipFile(sys.argv[1]) as z:- xml = z.read('word/document.xml').decode('utf-8')- xml = re.sub(r'</w:p>', '\n', xml)- xml = re.sub(r'<w:(br|cr)\b[^>]*/>', '\n', xml)- xml = re.sub(r'<w:tab\b[^>]*/>', '\t', xml)- text = html.unescape(re.sub(r'<[^>]+>', '', xml))- lines = [re.sub(r'[ \t]+', ' ', line).strip() for line in text.split('\n')]- sys.stdout.write('\n'.join(line for line in lines if line))-except Exception:- sys.exit(1)-"#;-- let output = Command::new("python3")- .arg("-c")- .arg(script)- .arg(path.as_os_str())- .output()- .map_err(|e| format!("python3 unavailable: {e}"))?;-- if !output.status.success() {- return Err(format!(- "docx extraction failed: {}",- String::from_utf8_lossy(&output.stderr).trim()- ));- }- Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())-}diff --git a/crates/openhuman-app/src/lib.rs b/crates/openhuman-app/src/lib.rsindex 5441003044..620c716b81 100644--- a/crates/openhuman-app/src/lib.rs+++ b/crates/openhuman-app/src/lib.rs@@ -76,7 +76,6 @@ mod core_rpc;mod deep_link_ipc;#[cfg(target_os = "windows")]mod deep_link_ipc_windows;-mod docx;mod remote_ws_relay;// Cross-platform module: the registry-reading function is windows-only, but// the parsing helpers compile (and test) everywhere so `cargo test` on the@@ -3306,7 +3305,6 @@ pub fn run() {// too (CodeRabbit on #4127). The Save-As dialog that used to sit in// front of this went with the shell's `rfd` dependency.artifact_commands::download_artifact_to_downloads,- artifact_commands::read_artifact_body,artifact_commands::save_artifact_as,// Native directory chooser for the folder memory-source (#5831).// Unlike the Save-As dialog above it, this one has no renderer-sidediff --git a/crates/openhuman-core/src/agent/artifacts/files.rs b/crates/openhuman-core/src/agent/artifacts/files.rsindex 71c9d37769..a832da42af 100644--- a/crates/openhuman-core/src/agent/artifacts/files.rs+++ b/crates/openhuman-core/src/agent/artifacts/files.rs@@ -77,17 +77,9 @@ impl FileRoots {&self.current}- /// Whether `path` names an existing file inside one of the vouched-for- /// folders. Both sides are canonicalized, so `..` and symlinks cannot reach- /// outside; a path that does not exist is held by none.- pub fn holds(&self, path: &Path) -> bool {- let Ok(path) = path.canonicalize() else {- return false;- };- self.trusted- .iter()- .filter_map(|folder| folder.canonicalize().ok())- .any(|folder| path.starts_with(folder))+ /// Every vouched-for folder: [`Self::current`] and the trusted ones.+ pub fn trusted(&self) -> &[PathBuf] {+ &self.trusted}/// Whether `root` is one of the vouched-for folders, compared canonicallydiff --git a/crates/openhuman-core/src/agent/artifacts/files_tests.rs b/crates/openhuman-core/src/agent/artifacts/files_tests.rsindex 8c8f94f3bc..210ad49076 100644--- a/crates/openhuman-core/src/agent/artifacts/files_tests.rs+++ b/crates/openhuman-core/src/agent/artifacts/files_tests.rs@@ -15,9 +15,16 @@ async fn create_ready(title: &str,bytes: &[u8],) -> ArtifactMeta {- let (meta, path) = create_artifact(workspace, files_dir, ArtifactKind::Document, title, "txt", None)- .await- .expect("create_artifact");+ let (meta, path) = create_artifact(+ workspace,+ files_dir,+ ArtifactKind::Document,+ title,+ "txt",+ None,+ )+ .await+ .expect("create_artifact");tokio::fs::write(&path, bytes).await.unwrap();finalize_artifact(workspace, &meta.id, bytes.len() as u64, None).awaitdiff --git a/crates/openhuman-core/src/agent/artifacts/mod.rs b/crates/openhuman-core/src/agent/artifacts/mod.rsindex 200714266c..42f2890595 100644--- a/crates/openhuman-core/src/agent/artifacts/mod.rs+++ b/crates/openhuman-core/src/agent/artifacts/mod.rs@@ -1,6 +1,7 @@pub mod files;pub mod migrate;pub mod ops;+pub mod preview;pub mod production;pub mod schemas;pub mod store;diff --git a/crates/openhuman-core/src/agent/artifacts/preview.rs b/crates/openhuman-core/src/agent/artifacts/preview.rsnew file mode 100644index 0000000000..528cd4342e--- /dev/null+++ b/crates/openhuman-core/src/agent/artifacts/preview.rs@@ -0,0 +1,188 @@+//! What the preview panel shows for an artifact: the newest version's content.+//!+//! Served by the core (`ai.read_artifact_body`), so the panel reads from+//! whichever core the app talks to, local or remote, and document conversion+//! runs where the artifact lives.+//!+//! * Text kinds (`text`, `markdown`, `html`) return their stored content.+//! * A file or image version is opened only when its path is inside the+//! folders file artifacts may point into (the agent's working folder and the+//! files folders), and only up to [`PREVIEW_MAX_BYTES`]. A UTF-8 file comes+//! back as text; a DOCX, PPTX, XLSX or PDF is converted to Markdown through+//! the TinyDocs module. Anything else comes back as its path, for the panel+//! to show as a file.++use std::path::{Path, PathBuf};++use serde::Serialize;+use tiny_artifacts::{ArtifactKind, ArtifactRecord};++use crate::config::Config;++/// Largest file the preview opens. A bigger one shows as a file.+pub const PREVIEW_MAX_BYTES: u64 = 10 * 1024 * 1024;++/// The newest version of an artifact, as the preview panel shows it.+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+pub struct ArtifactBody {+ /// The record's kind: `text`, `markdown`, `html`, `image` or `file`.+ pub kind: String,+ pub title: String,+ /// The newest version number (0 for an artifact still being produced).+ pub version: u32,+ /// The content to show: the text, the converted Markdown, or the file's+ /// path when it is not shown as text.+ pub body: String,+ /// Whether `body` is content rather than a path.+ pub is_text: bool,+ /// Whether `body` is Markdown converted from a document, to render as+ /// Markdown. The artifact itself is still a file: it is not edited.+ pub converted: bool,+}++/// The preview of artifact `id` in `config`'s workspace.+///+/// # Errors+///+/// Returns an error when the artifact does not exist or its record cannot be+/// read.+pub async fn read_body(config: &Config, id: &str) -> Result<ArtifactBody, String> {+ let files = super::files::FileRoots::from_config(config);+ let mut roots: Vec<PathBuf> = vec![config.action_dir.clone()];+ roots.extend(files.trusted().iter().cloned());+ let record = super::tiny_store::artifacts_service(+ &config.workspace_dir,+ files,+ Some(&config.action_dir),+ None,+ )+ .get(id)+ .await+ .map_err(|e| e.to_string())?+ .ok_or_else(|| format!("artifact {id} not found"))?;+ let converter = DocumentConverter::for_config(config);+ Ok(body_of(&record, &tiny_artifacts::FileRoots::new(roots), &converter).await)+}++/// Converts a document's bytes to Markdown. `None` when conversion is not+/// available (the documents component is off, or not in this build).+pub(crate) struct DocumentConverter<'a> {+ #[cfg_attr(not(feature = "documents"), allow(dead_code))]+ config: Option<&'a Config>,+}++impl<'a> DocumentConverter<'a> {+ fn for_config(config: &'a Config) -> Self {+ Self {+ config: config.components.documents.then_some(config),+ }+ }++ /// A converter that converts nothing.+ #[cfg(test)]+ pub(crate) fn none() -> Self {+ Self { config: None }+ }++ #[cfg(feature = "documents")]+ async fn convert(&self, extension: &str, bytes: &[u8]) -> Option<String> {+ use tinydocs_bus::DocumentFormat;+ let config = self.config?;+ let format = match extension {+ "docx" => DocumentFormat::Docx,+ "pptx" => DocumentFormat::Pptx,+ "xlsx" => DocumentFormat::Xlsx,+ "pdf" => DocumentFormat::Pdf,+ _ => return None,+ };+ match crate::modules::documents::convert_markdown(config, format, bytes).await {+ Ok(markdown) => Some(markdown),+ Err(err) => {+ tracing::debug!(+ target: "artifacts",+ extension,+ err = ?err,+ "[artifacts] preview conversion failed; showing the file"+ );+ None+ }+ }+ }++ #[cfg(not(feature = "documents"))]+ async fn convert(&self, _extension: &str, _bytes: &[u8]) -> Option<String> {+ None+ }+}++/// The preview of `record`'s newest version, opening files only inside+/// `roots`.+pub(crate) async fn body_of(+ record: &ArtifactRecord,+ roots: &tiny_artifacts::FileRoots,+ converter: &DocumentConverter<'_>,+) -> ArtifactBody {+ let latest = record.latest();+ let stored = latest.map(|v| v.body.clone()).unwrap_or_default();+ let mut preview = ArtifactBody {+ kind: kind_name(record.kind).to_string(),+ title: record.title.clone(),+ version: latest.map_or(0, |v| v.version),+ body: stored.clone(),+ is_text: !record.holds_file(),+ converted: false,+ };+ if !record.holds_file() {+ return preview;+ }+ let path = latest+ .and_then(|v| v.file.as_ref())+ .map_or(stored, |f| f.path.clone());+ preview.body = path.clone();+ // Inside the trusted folders, an existing regular file: anything else is+ // shown by its path only.+ let Ok(file) = roots.resolve(&path).await else {+ return preview;+ };+ if file.size_bytes > PREVIEW_MAX_BYTES {+ return preview;+ }+ let Ok(bytes) = tokio::fs::read(Path::new(&file.path)).await else {+ return preview;+ };+ let probe = &bytes[..bytes.len().min(8192)];+ if !probe.contains(&0) && std::str::from_utf8(probe).is_ok() {+ if let Ok(text) = String::from_utf8(bytes) {+ preview.body = text;+ preview.is_text = true;+ }+ return preview;+ }+ let Some(extension) = file.extension() else {+ return preview;+ };+ if let Some(markdown) = converter+ .convert(&extension, &bytes)+ .await+ .filter(|markdown| !markdown.trim().is_empty())+ {+ preview.body = markdown;+ preview.is_text = true;+ preview.converted = true;+ }+ preview+}++fn kind_name(kind: ArtifactKind) -> &'static str {+ match kind {+ ArtifactKind::Text => "text",+ ArtifactKind::Markdown => "markdown",+ ArtifactKind::Html => "html",+ ArtifactKind::Image => "image",+ ArtifactKind::File => "file",+ }+}++#[cfg(test)]+#[path = "preview_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/agent/artifacts/preview_tests.rs b/crates/openhuman-core/src/agent/artifacts/preview_tests.rsnew file mode 100644index 0000000000..2cb8960462--- /dev/null+++ b/crates/openhuman-core/src/agent/artifacts/preview_tests.rs@@ -0,0 +1,138 @@+use std::path::Path;++use tiny_artifacts::{ArtifactAuthor, ArtifactKind, ArtifactRecord, ArtifactVersion, FileRef};++use super::*;++fn file_record(path: &Path) -> ArtifactRecord {+ let mut version = ArtifactVersion::new(+ 1,+ path.display().to_string(),+ ArtifactAuthor::Agent,+ "agent",+ 1,+ );+ version.file = Some(FileRef {+ path: path.display().to_string(),+ size_bytes: std::fs::metadata(path).map(|m| m.len()).unwrap_or(0),+ media_type: None,+ });+ let mut record = ArtifactRecord::pending("f-1", "Report", ArtifactKind::File, 1);+ record.versions.push(version);+ record+}++fn roots(dir: &Path) -> tiny_artifacts::FileRoots {+ tiny_artifacts::FileRoots::new([dir.to_path_buf()])+}++#[tokio::test]+async fn a_text_kind_shows_its_newest_version() {+ let mut record =+ ArtifactRecord::new("m-1", "Notes", ArtifactKind::Markdown, "# v1", "agent", 1);+ record.push_version(ArtifactVersion::new(+ 0,+ "# v2",+ ArtifactAuthor::Operator,+ "operator",+ 2,+ ));+ let dir = tempfile::tempdir().unwrap();+ let body = body_of(&record, &roots(dir.path()), &DocumentConverter::none()).await;+ assert_eq!(body.kind, "markdown");+ assert_eq!(body.version, 2);+ assert_eq!(body.body, "# v2");+ assert!(body.is_text && !body.converted);+}++#[tokio::test]+async fn a_text_file_inside_the_roots_is_read() {+ let dir = tempfile::tempdir().unwrap();+ let file = dir.path().join("notes.txt");+ std::fs::write(&file, "plain notes").unwrap();+ let body = body_of(+ &file_record(&file),+ &roots(dir.path()),+ &DocumentConverter::none(),+ )+ .await;+ assert_eq!(body.kind, "file");+ assert_eq!(body.body, "plain notes");+ assert!(body.is_text);+}++#[tokio::test]+async fn a_file_outside_the_roots_is_not_opened() {+ let dir = tempfile::tempdir().unwrap();+ let elsewhere = tempfile::tempdir().unwrap();+ let secret = elsewhere.path().join("secret.txt");+ std::fs::write(&secret, "do not read").unwrap();+ let body = body_of(+ &file_record(&secret),+ &roots(dir.path()),+ &DocumentConverter::none(),+ )+ .await;+ // Shown as a file: its path, never its content.+ assert!(!body.is_text);+ assert_eq!(body.body, secret.display().to_string());+}++#[tokio::test]+async fn a_file_over_the_preview_limit_is_not_read() {+ let dir = tempfile::tempdir().unwrap();+ let file = dir.path().join("big.txt");+ std::fs::File::create(&file)+ .unwrap()+ .set_len(PREVIEW_MAX_BYTES + 1)+ .unwrap();+ let body = body_of(+ &file_record(&file),+ &roots(dir.path()),+ &DocumentConverter::none(),+ )+ .await;+ assert!(!body.is_text);+ assert_eq!(body.body, file.display().to_string());+}++#[tokio::test]+async fn a_binary_file_with_no_converter_shows_as_a_file() {+ let dir = tempfile::tempdir().unwrap();+ let file = dir.path().join("report.docx");+ std::fs::write(&file, b"PK\x03\x04\x00\x00binary").unwrap();+ let body = body_of(+ &file_record(&file),+ &roots(dir.path()),+ &DocumentConverter::none(),+ )+ .await;+ assert!(!body.is_text && !body.converted);+ assert_eq!(body.body, file.display().to_string());+}++fn config_in(workspace: &Path) -> crate::config::Config {+ crate::config::Config {+ workspace_dir: workspace.to_path_buf(),+ action_dir: workspace.join("action"),+ ..crate::config::Config::default()+ }+}++#[tokio::test]+async fn ids_that_name_another_file_are_refused() {+ let workspace = tempfile::tempdir().unwrap();+ let config = config_in(workspace.path());+ for id in ["../x", "a/b", "..", ".hidden"] {+ assert!(read_body(&config, id).await.is_err(), "{id:?}");+ }+}++#[tokio::test]+async fn an_unknown_artifact_is_not_found() {+ let workspace = tempfile::tempdir().unwrap();+ let err = read_body(&config_in(workspace.path()), "missing")+ .await+ .unwrap_err();+ assert!(err.contains("not found"), "{err}");+}diff --git a/crates/openhuman-core/src/agent/artifacts/schemas.rs b/crates/openhuman-core/src/agent/artifacts/schemas.rsindex b94cefefae..ec95e37844 100644--- a/crates/openhuman-core/src/agent/artifacts/schemas.rs+++ b/crates/openhuman-core/src/agent/artifacts/schemas.rs@@ -15,6 +15,7 @@ pub fn all_controller_schemas() -> Vec<ControllerSchema> {schemas("regenerate"),schemas("save_artifact_version"),schemas("share_artifact"),+ schemas("read_artifact_body"),]}@@ -44,6 +45,10 @@ pub fn all_registered_controllers() -> Vec<RegisteredController> {schema: schemas("share_artifact"),handler: handle_share_artifact,},+ RegisteredController {+ schema: schemas("read_artifact_body"),+ handler: handle_read_artifact_body,+ },]}@@ -201,6 +206,57 @@ pub fn schemas(function: &str) -> ControllerSchema {required: true,}],},+ "read_artifact_body" => ControllerSchema {+ namespace: "ai",+ function: "read_artifact_body",+ description: "The newest version of an artifact for the preview panel: its text, a document converted to Markdown, or the file's path.",+ inputs: vec![artifact_id_input("Identifier of the versioned artifact.")],+ outputs: vec![FieldSchema {+ name: "result",+ ty: TypeSchema::Object {+ fields: vec![+ FieldSchema {+ name: "kind",+ ty: TypeSchema::String,+ comment: "text, markdown, html, image or file.",+ required: true,+ },+ FieldSchema {+ name: "title",+ ty: TypeSchema::String,+ comment: "The artifact's title.",+ required: true,+ },+ FieldSchema {+ name: "version",+ ty: TypeSchema::U64,+ comment: "The newest version number.",+ required: true,+ },+ FieldSchema {+ name: "body",+ ty: TypeSchema::String,+ comment: "The content, or the file's path when is_text is false.",+ required: true,+ },+ FieldSchema {+ name: "is_text",+ ty: TypeSchema::Bool,+ comment: "Whether body is content rather than a path.",+ required: true,+ },+ FieldSchema {+ name: "converted",+ ty: TypeSchema::Bool,+ comment: "Whether body is Markdown converted from a document file.",+ required: true,+ },+ ],+ },+ comment: "Preview payload.",+ required: true,+ }],+ },"share_artifact" => ControllerSchema {namespace: "ai",function: "share_artifact",@@ -411,6 +467,15 @@ fn handle_save_artifact_version(ctx: DispatchCtx, params: Map<String, Value>) ->})}+fn handle_read_artifact_body(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let config = ctx.load_config().await?;+ let artifact_id = read_required::<String>(¶ms, "artifact_id")?;+ let body = crate::agent::artifacts::preview::read_body(&config, artifact_id.trim()).await?;+ to_json(Outcome::new(body, vec![]))+ })+}+fn handle_share_artifact(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let config = ctx.load_config().await?;diff --git a/crates/openhuman-core/src/agent/artifacts/schemas_tests.rs b/crates/openhuman-core/src/agent/artifacts/schemas_tests.rsindex 646e4c2c29..e6188fc07c 100644--- a/crates/openhuman-core/src/agent/artifacts/schemas_tests.rs+++ b/crates/openhuman-core/src/agent/artifacts/schemas_tests.rs@@ -80,7 +80,8 @@ fn all_controller_schemas_covers_every_supported_function() {"delete_artifact","regenerate","save_artifact_version",- "share_artifact"+ "share_artifact",+ "read_artifact_body"]);}@@ -88,7 +89,7 @@ fn all_controller_schemas_covers_every_supported_function() {#[test]fn all_registered_controllers_has_handler_per_schema() {let controllers = all_registered_controllers();- assert_eq!(controllers.len(), 6);+ assert_eq!(controllers.len(), 7);let names: Vec<_> = controllers.iter().map(|c| c.schema.function).collect();assert_eq!(names,@@ -98,7 +99,8 @@ fn all_registered_controllers_has_handler_per_schema() {"delete_artifact","regenerate","save_artifact_version",- "share_artifact"+ "share_artifact",+ "read_artifact_body"]);}