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
fix(artifacts): address M3gA-Mind's review (#4, #6, #8, #9, #10)
Sanilfab531d46215
diff --git a/app/src/features/conversations/aui/ArtifactPreviewPanel.refresh.test.tsx b/app/src/features/conversations/aui/ArtifactPreviewPanel.refresh.test.tsxnew file mode 100644index 0000000000..ce2fe851ec--- /dev/null+++ b/app/src/features/conversations/aui/ArtifactPreviewPanel.refresh.test.tsx@@ -0,0 +1,82 @@+import { configureStore } from '@reduxjs/toolkit';+import { act, fireEvent, render, screen, waitFor } 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 rpc = vi.mocked(callCoreRpc);+const body = (text: string, version: number) => ({+ kind: 'markdown',+ title: 'Notes',+ version,+ body: text,+ is_text: true,+ converted: false,+});+const ready = () =>+ upsertArtifactReadyForThread({+ threadId: 't-1',+ artifactId: 'a-1',+ kind: 'document',+ title: 'Notes',+ path: '/tmp/n.md',+ sizeBytes: 4,+ });++function setup() {+ const store = configureStore({ reducer: { chatRuntime: chatRuntimeReducer } });+ store.dispatch(ready());+ store.dispatch(openArtifact('a-1'));+ render(+ <Provider store={store}>+ <ArtifactPreviewPanel />+ </Provider>+ );+ return store;+}++describe('ArtifactPreviewPanel — versions saved elsewhere', () => {+ beforeEach(() => rpc.mockReset());++ it('shows an agent revision of the open artifact', async () => {+ rpc.mockResolvedValueOnce(body('# first', 1));+ const store = setup();+ expect((await screen.findByRole('heading', { level: 1 })).textContent).toBe('first');++ rpc.mockResolvedValueOnce(body('# revised by the agent', 2));+ await act(async () => {+ await new Promise(resolve => setTimeout(resolve, 2));+ store.dispatch(ready());+ });+ await waitFor(() =>+ expect(screen.getByRole('heading', { level: 1 }).textContent).toBe('revised by the agent')+ );+ });++ it('keeps an unsaved edit when a revision arrives', async () => {+ rpc.mockResolvedValueOnce(body('# first', 1));+ const store = setup();+ await screen.findByRole('heading', { level: 1 });+ fireEvent.click(screen.getByRole('button', { name: /Code/ }));+ fireEvent.change(screen.getByRole('textbox'), { target: { value: '# my edit' } });++ rpc.mockResolvedValueOnce(body('# revised by the agent', 2));+ await act(async () => {+ await new Promise(resolve => setTimeout(resolve, 2));+ store.dispatch(ready());+ });+ await waitFor(() => expect(rpc).toHaveBeenCalledTimes(2));+ expect((screen.getByRole('textbox') as HTMLTextAreaElement).value).toBe('# my edit');+ });+});diff --git a/app/src/features/conversations/aui/ArtifactPreviewPanel.tsx b/app/src/features/conversations/aui/ArtifactPreviewPanel.tsxindex 90dd6db640..c68dfd27c6 100644--- a/app/src/features/conversations/aui/ArtifactPreviewPanel.tsx+++ b/app/src/features/conversations/aui/ArtifactPreviewPanel.tsx@@ -190,7 +190,7 @@ export function ArtifactPreviewPanel(_props: ArtifactPreviewPanelProps) {{/* Content */}<div className="flex-1 overflow-hidden">{activeArtifact ? (- <ArtifactContentPanel artifact={activeArtifact} />+ <ArtifactContentPanel key={activeArtifact.artifactId} artifact={activeArtifact} />) : (<div className="flex items-center justify-center h-full p-4 text-sm text-muted-foreground">{t('chat.artifact.notFound')}@@ -244,6 +244,27 @@ function ArtifactContentPanel({ artifact }: { artifact: ArtifactSnapshot }) {};}, [artifact.artifactId]);+ // A new version saved while the panel is open (the agent revised it, or an+ // autosave landed): read it again, without the loading state.+ const seenUpdate = useRef(artifact.updatedAt);+ useEffect(() => {+ if (seenUpdate.current === artifact.updatedAt) return;+ seenUpdate.current = artifact.updatedAt;+ if (!artifact.artifactId || artifact.status !== 'ready') return;+ let cancelled = false;+ void callCoreRpc<ArtifactBodyResponse>({+ method: 'openhuman.ai_read_artifact_body',+ params: { artifact_id: artifact.artifactId },+ })+ .then(result => {+ if (!cancelled) setBodyResult(result);+ })+ .catch(err => console.warn('[ArtifactPreviewPanel] refresh failed:', err));+ return () => {+ cancelled = true;+ };+ }, [artifact.artifactId, artifact.status, artifact.updatedAt]);+if (loading) {return (<div className="flex items-center justify-center h-full p-8">@@ -400,7 +421,9 @@ export function useArtifactAutosave(useEffect(() => {setVersion(initialVersion);- setStatus('saved');+ // A new body read in while an edit is pending does not make that edit+ // saved.+ if (pending.current === null) setStatus('saved');}, [artifactId, body, initialVersion]);const save = useCallback(async () => {@@ -659,9 +682,13 @@ function EditableTextViewer({const editable = EDITABLE_KINDS.has(kind) && !error;const autosave = useArtifactAutosave(artifact.artifactId, body, version, editable);- // Sync when body changes (switching artifact tabs)+ // Take a new body (another artifact, or a version saved elsewhere) unless+ // there is an unsaved edit here: that edit is saved as the next version.+ const hasLocalEdit = autosave.status === 'pending' || autosave.status === 'saving';+ const hasLocalEditRef = useRef(hasLocalEdit);+ hasLocalEditRef.current = hasLocalEdit;useEffect(() => {- setEditedBody(body);+ if (!hasLocalEditRef.current) setEditedBody(body);}, [body]);const onEdit = useCallback(diff --git a/crates/openhuman-core/src/agent/artifacts/preview.rs b/crates/openhuman-core/src/agent/artifacts/preview.rsindex a4adf2e4e0..f086e3a144 100644--- a/crates/openhuman-core/src/agent/artifacts/preview.rs+++ b/crates/openhuman-core/src/agent/artifacts/preview.rs@@ -48,13 +48,8 @@ pub struct ArtifactBody {/// read.pub async fn read_body(config: &Config, id: &str) -> Result<ArtifactBody, String> {let files = super::files::FileRoots::from_config(config);- // Where a file version may live: its own kept copy, the agent's working- // folder, or the files folders.- let mut roots: Vec<PathBuf> = vec![- super::tiny_store::version_files_dir(&config.workspace_dir),- config.action_dir.clone(),- ];- roots.extend(files.trusted().iter().cloned());+ let mut roots =+ super::tiny_store::file_roots(&config.workspace_dir, &files, Some(&config.action_dir));let versioned = super::tiny_store::artifacts_service(&config.workspace_dir,files.clone(),diff --git a/crates/openhuman-core/src/agent/artifacts/production.rs b/crates/openhuman-core/src/agent/artifacts/production.rsindex 515e5a3baf..704bf6f3de 100644--- a/crates/openhuman-core/src/agent/artifacts/production.rs+++ b/crates/openhuman-core/src/agent/artifacts/production.rs@@ -34,6 +34,9 @@ pub struct Production {chat: Option<ApprovalChatContext>,id: String,path: PathBuf,+ /// Whether this adds a version to an artifact that already has one: its+ /// failure must leave that artifact as it was, not fail it.+ revision: bool,}impl std::fmt::Debug for Production {@@ -85,13 +88,14 @@ impl Production {.await?;let artifacts = artifacts_service(workspace_dir, files.clone(), None, chat);- let production = Self {+ let mut production = Self {artifacts,workspace_dir: workspace_dir.to_path_buf(),files,chat: chat.cloned(),id: meta.id.clone(),path,+ revision: false,};// A revision keeps its record and history; a new artifact opens one.let existing = production@@ -100,7 +104,10 @@ impl Production {.await.map_err(|e| e.to_string());let opened = match existing {- Ok(Some(_)) => Ok(()),+ Ok(Some(record)) => {+ production.revision = !record.versions.is_empty();+ Ok(())+ }Ok(None) => production.artifacts.begin(kind, title, Some(meta.id.clone()))@@ -145,30 +152,81 @@ impl Production {None,).await;- let reason = match saved {- Ok(saved) => match (- saved.notice,- saved.record.latest().and_then(|v| v.file.clone()),- ) {- (None, Some(file)) => return Ok(file.size_bytes),- (Some(notice), _) => notice,- (None, None) => "the recorded version has no file".to_string(),- },- Err(err) => err.to_string(),- };- let reason = format!("failed to finalize artifact: {reason}");- self.fail_card(&reason).await;- Err(reason)+ match saved {+ Ok(saved) => {+ let reason = match (+ saved.notice,+ saved.record.latest().and_then(|v| v.file.clone()),+ ) {+ (None, Some(file)) => return Ok(file.size_bytes),+ (Some(notice), _) => notice,+ (None, None) => "the recorded version has no file".to_string(),+ };+ // The version is recorded; only the card could not follow.+ let reason = format!("failed to finalize artifact: {reason}");+ self.fail_card(&reason).await;+ Err(reason)+ }+ // Nothing was recorded: end it as any failed production ends.+ Err(err) => {+ let reason = format!("failed to finalize artifact: {err}");+ self.fail(&reason).await;+ Err(reason)+ }+ }}- /// Fail the artifact with `reason`.+ /// End the production with `reason`. A new artifact is failed, record and+ /// card. A revision leaves the artifact as it was: the record keeps its+ /// versions and the card shows the newest of them again.pub async fn fail(&self, reason: &str) {- if let Err(err) = self.artifacts.fail(&self.id, reason).await {+ if self.revision {+ self.restore_card(reason).await;+ return;+ }+ let shown = match self.artifacts.fail(&self.id, reason).await {+ Ok(saved) => saved.notice,+ Err(err) => Some(err.to_string()),+ };+ // The record took the failure but the card did not follow (or the+ // record could not take it): fail the card directly, so it never stays+ // "generating".+ if let Some(why) = shown {+ tracing::warn!(+ target: "tiny-artifacts",+ artifact_id = %self.id,+ err = %why,+ "[artifacts] the failure did not reach the card; failing it directly"+ );+ self.fail_card(reason).await;+ }+ }++ /// Show a revised artifact's newest recorded version again after its+ /// revision failed. Failing the card is the fallback when that is not+ /// possible.+ async fn restore_card(&self, reason: &str) {+ tracing::warn!(+ target: "tiny-artifacts",+ artifact_id = %self.id,+ reason,+ "[artifacts] revision failed; keeping the artifact's newest version"+ );+ let record = match self.artifacts.get(&self.id).await {+ Ok(Some(record)) if record.latest().is_some() => record,+ _ => return self.fail_card(reason).await,+ };+ let bridge = super::tiny_store::LegacyUiBridge::new(+ &self.workspace_dir,+ self.files.clone(),+ self.chat.as_ref(),+ );+ if let Err(err) = bridge.show_newest(&record).await {tracing::warn!(target: "tiny-artifacts",artifact_id = %self.id,err = %err,- "[artifacts] could not mark the versioned record failed"+ "[artifacts] could not show the newest version again");self.fail_card(reason).await;}diff --git a/crates/openhuman-core/src/agent/artifacts/production_tests.rs b/crates/openhuman-core/src/agent/artifacts/production_tests.rsindex 9adca7f2bd..e935ec7db3 100644--- a/crates/openhuman-core/src/agent/artifacts/production_tests.rs+++ b/crates/openhuman-core/src/agent/artifacts/production_tests.rs@@ -153,3 +153,67 @@ async fn a_failed_production_fails_card_and_record() {assert_eq!(record.status, RecordStatus::Failed);assert_eq!(record.error.as_deref(), Some("provider timed out"));}++#[tokio::test]+async fn a_failed_revision_keeps_the_artifact_and_shows_its_newest_version() {+ let (workspace, files) = temp_dirs();+ let id = produce(&workspace, &files, b"deck-v1", None, None).await;++ let revision = Production::start(+ &workspace,+ FileRoots::new(&files),+ ArtifactKind::File,+ "Quarterly Deck",+ "pptx",+ None,+ Some(&id),+ None,+ )+ .await+ .unwrap();+ // The producer got as far as clobbering the file before failing.+ tokio::fs::write(revision.path(), b"half-writ")+ .await+ .unwrap();+ revision.fail("engine crashed").await;++ let record = versioned_store(&workspace).get(&id).await.unwrap().unwrap();+ assert_eq!(record.status, RecordStatus::Ready);+ assert_eq!(record.versions.len(), 1);+ let card = get_artifact(&workspace, &id).await.unwrap();+ assert_eq!(card.status, CardStatus::Ready);+ assert_eq!(+ std::fs::read(files.join("quarterly-deck.pptx")).unwrap(),+ b"deck-v1"+ );+}++#[tokio::test]+async fn a_completion_that_records_nothing_fails_the_record_too() {+ let (workspace, files) = temp_dirs();+ let production = Production::start(+ &workspace,+ FileRoots::new(&files),+ ArtifactKind::File,+ "Quarterly Deck",+ "pptx",+ None,+ None,+ None,+ )+ .await+ .unwrap();+ // No file: the version cannot be recorded.+ let _ = std::fs::remove_file(production.path());+ assert!(production.complete().await.is_err());++ let record = versioned_store(&workspace)+ .get(production.id())+ .await+ .unwrap()+ .unwrap();+ // Not left pending, so its card never stays "generating".+ assert_eq!(record.status, RecordStatus::Failed);+ let card = get_artifact(&workspace, production.id()).await.unwrap();+ assert_eq!(card.status, CardStatus::Failed);+}diff --git a/crates/openhuman-core/src/agent/artifacts/store.rs b/crates/openhuman-core/src/agent/artifacts/store.rsindex acb03378ca..451f4a296a 100644--- a/crates/openhuman-core/src/agent/artifacts/store.rs+++ b/crates/openhuman-core/src/agent/artifacts/store.rs@@ -117,7 +117,12 @@ pub(crate) async fn list_artifacts(workspace_dir);let docs = documents(workspace_dir).await?;- let all = on_docs(docs, |docs| docs.list_meta()).await?;+ let owned = thread_id.map(str::to_string);+ let all = on_docs(docs, move |docs| match owned {+ Some(thread_id) => docs.list_meta_for_thread(&thread_id),+ None => docs.list_meta(),+ })+ .await?;Ok(page_of(all, offset, limit, thread_id))}diff --git a/crates/openhuman-core/src/agent/artifacts/store_documents.rs b/crates/openhuman-core/src/agent/artifacts/store_documents.rsindex 5bf8063a68..85d5b18f40 100644--- a/crates/openhuman-core/src/agent/artifacts/store_documents.rs+++ b/crates/openhuman-core/src/agent/artifacts/store_documents.rs@@ -34,7 +34,7 @@ use std::path::Path;use anyhow::{Context, Result};use serde_json::{json, Value};-use tinystoragedrivers::{CollectionSpec, Precondition, Query, Sort};+use tinystoragedrivers::{CollectionSpec, Filter, IndexSpec, Precondition, Query, Sort};use super::types::ArtifactMeta;use crate::storage::documents::Repo;@@ -45,7 +45,11 @@ const ARGS: &str = "artifact_args";const DOMAIN: &str = "artifacts::store";fn collections() -> Vec<CollectionSpec> {- vec![CollectionSpec::new(ARTIFACTS), CollectionSpec::new(ARGS)]+ vec![+ CollectionSpec::new(ARTIFACTS)+ .index(IndexSpec::new("by_thread", ["thread_id", "created_ms"])),+ CollectionSpec::new(ARGS),+ ]}/// The document store for this call: the installed backend, else the@@ -126,15 +130,20 @@ impl Docs {/// Every record, newest first. A document that no longer parses is skipped/// with a warning, as a corrupt `meta.json` is.pub(super) fn list_meta(&self) -> Result<Vec<ArtifactMeta>> {- let stored = self.0.run(|docs| async move {- docs.query_all(- ARTIFACTS,- &Query::all()- .sort(Sort::desc("created_ms"))- .sort(Sort::asc("_id")),- )- .await- })?;+ self.query_meta(Query::all())+ }++ /// The records of one thread, newest first, read through the `by_thread`+ /// index rather than by listing the workspace.+ pub(super) fn list_meta_for_thread(&self, thread_id: &str) -> Result<Vec<ArtifactMeta>> {+ self.query_meta(Query::filter(Filter::eq("thread_id", thread_id)))+ }++ fn query_meta(&self, query: Query) -> Result<Vec<ArtifactMeta>> {+ let query = query.sort(Sort::desc("created_ms")).sort(Sort::asc("_id"));+ let stored = self+ .0+ .run(|docs| async move { docs.query_all(ARTIFACTS, &query).await })?;Ok(stored.into_iter().filter_map(|item| match serde_json::from_value(item.doc) {diff --git a/crates/openhuman-core/src/agent/artifacts/tiny_store.rs b/crates/openhuman-core/src/agent/artifacts/tiny_store.rsindex c9baa6549d..03157bb620 100644--- a/crates/openhuman-core/src/agent/artifacts/tiny_store.rs+++ b/crates/openhuman-core/src/agent/artifacts/tiny_store.rs@@ -121,7 +121,7 @@ impl LegacyUiBridge {/// Put the newest version in the files folder under the artifact's id and/// mark it ready: the content for text kinds, a copy of the file for file/// kinds (unless the file already is the one the artifact owns).- async fn show_newest(&self, record: &ArtifactRecord) -> anyhow::Result<()> {+ pub(crate) async fn show_newest(&self, record: &ArtifactRecord) -> anyhow::Result<()> {let (Some(latest), Some((legacy_kind, ext))) = (record.latest(), legacy_shape(record))else {return Ok(());@@ -235,18 +235,37 @@ impl ArtifactObserver for LegacyUiBridge {}}+/// The folders a file version may point into: its own kept copy, the agent's+/// working folder, and every files folder the host trusts. A folder used+/// before the current one stays trusted, so an artifact made there can still+/// be revised in place.+pub fn file_roots(+ workspace_dir: &Path,+ files: &FileRoots,+ action_dir: Option<&Path>,+) -> Vec<PathBuf> {+ // A relative path resolves against the first root: the agent's working+ // folder when there is one, else the current files folder.+ let mut roots: Vec<PathBuf> = action_dir.map(Path::to_path_buf).into_iter().collect();+ for folder in files.trusted() {+ if !roots.contains(folder) {+ roots.push(folder.clone());+ }+ }+ roots.push(version_files_dir(workspace_dir));+ roots+}+/// The artifact service for one workspace: OpenHuman's store and UI bridge,-/// with file artifacts allowed from the agent's working folder and the files-/// folder. Cards are announced to `chat`, the turn making the change (`None`-/// outside a chat turn).+/// with file artifacts allowed from [`file_roots`]. Cards are announced to+/// `chat`, the turn making the change (`None` outside a chat turn).pub fn artifacts_service(workspace_dir: &Path,files: FileRoots,action_dir: Option<&Path>,chat: Option<&ApprovalChatContext>,) -> Artifacts {- let mut roots: Vec<PathBuf> = action_dir.map(Path::to_path_buf).into_iter().collect();- roots.push(files.current().to_path_buf());+ let roots = file_roots(workspace_dir, &files, action_dir);Artifacts::new(Arc::new(versioned_store(workspace_dir))).with_observer(Arc::new(LegacyUiBridge::new(workspace_dir, files, chat))).with_file_roots(tiny_artifacts::FileRoots::new(roots))diff --git a/crates/openhuman-core/src/agent/artifacts/tiny_store_tests.rs b/crates/openhuman-core/src/agent/artifacts/tiny_store_tests.rsindex 95a4f89c6f..7c64e95788 100644--- a/crates/openhuman-core/src/agent/artifacts/tiny_store_tests.rs+++ b/crates/openhuman-core/src/agent/artifacts/tiny_store_tests.rs@@ -203,3 +203,38 @@ fn share_artifact_is_offered_only_with_a_publisher() {let with = names(Some(std::sync::Arc::new(NoopPublisher)));assert!(with.contains(&"share_artifact".to_string()), "{with:?}");}++#[tokio::test]+async fn a_file_in_an_earlier_files_folder_can_still_be_revised() {+ let (workspace, files) = temp_dirs();+ let earlier = files.parent().unwrap().join("OldFiles");+ std::fs::create_dir_all(&earlier).unwrap();+ let old = earlier.join("deck.pptx");+ std::fs::write(&old, b"v1").unwrap();+ // The files folder moved; the earlier one stays trusted.+ let roots = FileRoots::new(&files).with_trusted([earlier.clone()]);+ let artifacts = artifacts_service(&workspace, roots, None, None);+ let id = artifacts+ .create(+ ArtifactKind::File,+ "Deck",+ Content::File(old.display().to_string()),+ &Author::agent("agent"),+ None,+ )+ .await+ .unwrap()+ .record+ .id;+ std::fs::write(&old, b"v2").unwrap();+ let saved = artifacts+ .revise(+ &id,+ Content::File(old.display().to_string()),+ &Author::agent("agent"),+ None,+ )+ .await+ .unwrap();+ assert_eq!(saved.version, 2);+}