Skip to content

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

fix(artifacts): preview legacy artifacts; cap autosave retries

Sanil29a059088501
diff --git a/app/src/features/conversations/aui/ArtifactPreviewPanel.autosave.test.tsx b/app/src/features/conversations/aui/ArtifactPreviewPanel.autosave.test.tsx
index ebe72bf4c9..c24d5d3881 100644
--- a/app/src/features/conversations/aui/ArtifactPreviewPanel.autosave.test.tsx
+++ b/app/src/features/conversations/aui/ArtifactPreviewPanel.autosave.test.tsx
@@ -2,7 +2,11 @@ import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { callCoreRpc } from '../../../services/coreRpcClient';
-import { AUTOSAVE_DELAY_MS, useArtifactAutosave } from './ArtifactPreviewPanel';
+import {
+ AUTOSAVE_DELAY_MS,
+ AUTOSAVE_MAX_RETRIES,
+ useArtifactAutosave,
+} from './ArtifactPreviewPanel';
vi.mock('../../../services/coreRpcClient', () => ({
callCoreRpc: vi.fn().mockResolvedValue({ artifact_id: 'a-1', version: 2, saved: true }),
@@ -90,6 +94,23 @@ describe('useArtifactAutosave', () => {
});
});
+ it('stops retrying a save that keeps failing, even after the panel closed', async () => {
+ rpc.mockRejectedValue(new Error('core down'));
+ const { result, unmount } = renderHook(() => useArtifactAutosave('a-1', '# v1', 1, true));
+ act(() => result.current.schedule('# edited'));
+ await act(async () => vi.advanceTimersByTime(AUTOSAVE_DELAY_MS));
+ await act(async () => unmount());
+ for (let i = 0; i < AUTOSAVE_MAX_RETRIES + 3; i++) {
+ await act(async () => vi.advanceTimersByTime(AUTOSAVE_DELAY_MS));
+ }
+ // The first save, the save on close, then the capped retries — no more.
+ const calls = rpc.mock.calls.length;
+ expect(calls).toBeLessThanOrEqual(2 + AUTOSAVE_MAX_RETRIES);
+ await act(async () => vi.advanceTimersByTime(AUTOSAVE_DELAY_MS * 10));
+ expect(rpc.mock.calls.length).toBe(calls);
+ rpc.mockResolvedValue({ artifact_id: 'a-1', version: 2, saved: true });
+ });
+
it('never saves a read-only artifact', async () => {
const { result } = renderHook(() => useArtifactAutosave('a-1', 'text', 1, false));
act(() => result.current.schedule('changed'));
diff --git a/app/src/features/conversations/aui/ArtifactPreviewPanel.tsx b/app/src/features/conversations/aui/ArtifactPreviewPanel.tsx
index 4cc685868f..90dd6db640 100644
--- a/app/src/features/conversations/aui/ArtifactPreviewPanel.tsx
+++ b/app/src/features/conversations/aui/ArtifactPreviewPanel.tsx
@@ -350,6 +350,9 @@ function FileViewer({
/** Versioned kinds whose record holds the content, so an edit is a version. */
const EDITABLE_KINDS = new Set(['text', 'markdown', 'html']);
+/** Times a failed autosave is retried on its own before waiting for the user. */
+export const AUTOSAVE_MAX_RETRIES = 3;
+
/** Wait after the last keystroke before saving the edit as a new version. */
export const AUTOSAVE_DELAY_MS = 5_000;
@@ -391,6 +394,9 @@ export function useArtifactAutosave(
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
// The retry after a failed save calls the current `save`.
const saveRef = useRef<() => Promise<void>>(async () => {});
+ // Retries since the last successful save or edit, so a save that keeps
+ // failing (also after the panel closed) stops instead of retrying forever.
+ const retries = useRef(0);
useEffect(() => {
setVersion(initialVersion);
@@ -409,6 +415,7 @@ export function useArtifactAutosave(
method: 'openhuman.ai_save_artifact_version',
params: { artifact_id: artifactId, body: next },
});
+ retries.current = 0;
if (typeof result?.version === 'number') setVersion(result.version);
setStatus(pending.current === null ? 'saved' : 'pending');
} catch (err) {
@@ -418,6 +425,10 @@ export function useArtifactAutosave(
// meanwhile (that one is saved instead).
if (pending.current === null) {
pending.current = next;
+ // The edit stays pending; past the cap only a new edit or a flush
+ // (download, closing the panel) tries again.
+ if (retries.current >= AUTOSAVE_MAX_RETRIES) return;
+ retries.current += 1;
if (timer.current) clearTimeout(timer.current);
timer.current = setTimeout(() => void saveRef.current(), AUTOSAVE_DELAY_MS);
}
@@ -430,6 +441,7 @@ export function useArtifactAutosave(
const schedule = useCallback(
(next: string) => {
if (!enabled) return;
+ retries.current = 0;
pending.current = next;
setStatus('pending');
if (timer.current) clearTimeout(timer.current);
diff --git a/crates/openhuman-core/src/agent/artifacts/preview.rs b/crates/openhuman-core/src/agent/artifacts/preview.rs
index 28e1f986c7..a4adf2e4e0 100644
--- a/crates/openhuman-core/src/agent/artifacts/preview.rs
+++ b/crates/openhuman-core/src/agent/artifacts/preview.rs
@@ -55,20 +55,66 @@ pub async fn read_body(config: &Config, id: &str) -> Result<ArtifactBody, String
config.action_dir.clone(),
];
roots.extend(files.trusted().iter().cloned());
- let record = super::tiny_store::artifacts_service(
+ let versioned = super::tiny_store::artifacts_service(
&config.workspace_dir,
- files,
+ files.clone(),
Some(&config.action_dir),
None,
)
.get(id)
.await
- .map_err(|e| e.to_string())?
- .ok_or_else(|| format!("artifact {id} not found"))?;
+ .map_err(|e| e.to_string())?;
+ let record = match versioned {
+ Some(record) => record,
+ // An artifact made before versioning has only its legacy record: show
+ // the file that record vouches for.
+ None => {
+ let record = legacy_record(&config.workspace_dir, &files, id).await?;
+ if let Some(folder) = record
+ .latest()
+ .and_then(|v| v.file.as_ref())
+ .and_then(|f| Path::new(&f.path).parent())
+ {
+ roots.push(folder.to_path_buf());
+ }
+ record
+ }
+ };
let converter = DocumentConverter::for_config(config);
Ok(body_of(&record, &tiny_artifacts::FileRoots::new(roots), &converter).await)
}
+/// A one-version file record for an artifact that has only its legacy
+/// [`ArtifactMeta`](super::types::ArtifactMeta), pointing at the file the
+/// legacy store vouches for (ready, inside its folders, still on disk).
+async fn legacy_record(
+ workspace_dir: &Path,
+ files: &super::files::FileRoots,
+ id: &str,
+) -> Result<ArtifactRecord, String> {
+ let meta = super::store::get_artifact(workspace_dir, id)
+ .await
+ .map_err(|_| format!("artifact {id} not found"))?;
+ let path = super::files::resolve_ready_file(workspace_dir, files, id).await?;
+ let path = path.display().to_string();
+ let at = u64::try_from(meta.created_at.timestamp_millis()).unwrap_or(0);
+ let mut version = tiny_artifacts::ArtifactVersion::new(
+ 1,
+ path.clone(),
+ tiny_artifacts::ArtifactAuthor::Agent,
+ super::tiny_store::AGENT_AUTHOR_ID,
+ at,
+ );
+ version.file = Some(tiny_artifacts::FileRef {
+ size_bytes: meta.size_bytes,
+ media_type: None,
+ path,
+ });
+ let mut record = ArtifactRecord::pending(id, meta.title, ArtifactKind::File, at);
+ record.versions.push(version);
+ Ok(record)
+}
+
/// 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> {
diff --git a/crates/openhuman-core/src/agent/artifacts/preview_tests.rs b/crates/openhuman-core/src/agent/artifacts/preview_tests.rs
index 2cb8960462..15cee0f3b3 100644
--- a/crates/openhuman-core/src/agent/artifacts/preview_tests.rs
+++ b/crates/openhuman-core/src/agent/artifacts/preview_tests.rs
@@ -115,6 +115,7 @@ fn config_in(workspace: &Path) -> crate::config::Config {
crate::config::Config {
workspace_dir: workspace.to_path_buf(),
action_dir: workspace.join("action"),
+ files_dir_override: Some(workspace.join("Files")),
..crate::config::Config::default()
}
}
@@ -136,3 +137,35 @@ async fn an_unknown_artifact_is_not_found() {
.unwrap_err();
assert!(err.contains("not found"), "{err}");
}
+
+#[tokio::test]
+async fn an_artifact_made_before_versioning_opens_from_its_legacy_record() {
+ use crate::agent::artifacts::store::{create_artifact, finalize_artifact};
+ use crate::agent::artifacts::types::ArtifactKind as LegacyKind;
+
+ let workspace = tempfile::tempdir().unwrap();
+ let config = config_in(workspace.path());
+ let files = config.files_dir();
+ std::fs::create_dir_all(&files).unwrap();
+ // Only the legacy record: no versioned one.
+ let (meta, path) = create_artifact(
+ workspace.path(),
+ files.clone(),
+ LegacyKind::Document,
+ "Old notes",
+ "md",
+ None,
+ )
+ .await
+ .unwrap();
+ std::fs::write(&path, "# from before").unwrap();
+ finalize_artifact(workspace.path(), &meta.id, 13, None)
+ .await
+ .unwrap();
+
+ let body = read_body(&config, &meta.id).await.unwrap();
+ assert_eq!(body.title, "Old notes");
+ assert_eq!(body.kind, "file");
+ assert_eq!(body.body, "# from before");
+ assert!(body.is_text);
+}