Skip to content

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

fix(artifacts): address the latest review findings

Sanil4b39fc6a2422
diff --git a/app/src/features/conversations/aui/ArtifactPreviewPanel.autosave.test.tsx b/app/src/features/conversations/aui/ArtifactPreviewPanel.autosave.test.tsx
index 30a8498e88..ebe72bf4c9 100644
--- a/app/src/features/conversations/aui/ArtifactPreviewPanel.autosave.test.tsx
+++ b/app/src/features/conversations/aui/ArtifactPreviewPanel.autosave.test.tsx
@@ -59,6 +59,37 @@ describe('useArtifactAutosave', () => {
expect(rpc).toHaveBeenCalledTimes(1);
});
+ it('keeps an edit whose save failed and saves it on the retry', async () => {
+ rpc.mockRejectedValueOnce(new Error('core restarting'));
+ const { result } = renderHook(() => useArtifactAutosave('a-1', '# v1', 1, true));
+ act(() => result.current.schedule('# kept'));
+ await act(async () => vi.advanceTimersByTime(AUTOSAVE_DELAY_MS));
+ expect(rpc).toHaveBeenCalledTimes(1);
+ expect(result.current.status).toBe('error');
+
+ await act(async () => vi.advanceTimersByTime(AUTOSAVE_DELAY_MS));
+ expect(rpc).toHaveBeenCalledTimes(2);
+ expect(rpc).toHaveBeenLastCalledWith({
+ method: 'openhuman.ai_save_artifact_version',
+ params: { artifact_id: 'a-1', body: '# kept' },
+ });
+ expect(result.current.status).toBe('saved');
+ });
+
+ it('a newer edit replaces a failed one instead of both being saved', async () => {
+ rpc.mockRejectedValueOnce(new Error('core restarting'));
+ const { result } = renderHook(() => useArtifactAutosave('a-1', '# v1', 1, true));
+ act(() => result.current.schedule('# old'));
+ await act(async () => vi.advanceTimersByTime(AUTOSAVE_DELAY_MS));
+ act(() => result.current.schedule('# newer'));
+ await act(async () => vi.advanceTimersByTime(AUTOSAVE_DELAY_MS));
+ expect(rpc).toHaveBeenCalledTimes(2);
+ expect(rpc).toHaveBeenLastCalledWith({
+ method: 'openhuman.ai_save_artifact_version',
+ params: { artifact_id: 'a-1', body: '# newer' },
+ });
+ });
+
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 2f0186d8ce..95340accb8 100644
--- a/app/src/features/conversations/aui/ArtifactPreviewPanel.tsx
+++ b/app/src/features/conversations/aui/ArtifactPreviewPanel.tsx
@@ -382,6 +382,8 @@ export function useArtifactAutosave(
const [version, setVersion] = useState(initialVersion);
const pending = useRef<string | null>(null);
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ // The retry after a failed save calls the current `save`.
+ const saveRef = useRef<() => Promise<void>>(async () => {});
useEffect(() => {
setVersion(initialVersion);
@@ -405,8 +407,18 @@ export function useArtifactAutosave(
} catch (err) {
console.error('[ArtifactPreviewPanel] autosave failed:', err);
setStatus('error');
+ // Keep the edit and try again later, unless a newer edit replaced it
+ // meanwhile (that one is saved instead).
+ if (pending.current === null) {
+ pending.current = next;
+ if (timer.current) clearTimeout(timer.current);
+ timer.current = setTimeout(() => void saveRef.current(), AUTOSAVE_DELAY_MS);
+ }
}
}, [artifactId]);
+ useEffect(() => {
+ saveRef.current = save;
+ }, [save]);
const schedule = useCallback(
(next: string) => {
diff --git a/app/src/services/api/__tests__/artifactRows.test.ts b/app/src/services/api/__tests__/artifactRows.test.ts
index 1ce114ee03..2df6f44923 100644
--- a/app/src/services/api/__tests__/artifactRows.test.ts
+++ b/app/src/services/api/__tests__/artifactRows.test.ts
@@ -30,6 +30,22 @@ const row = (artifactId: string, requestId?: string): ThreadMessage => ({
const ids = (message: ThreadMessage) => message.extraMetadata[ARTIFACT_IDS_METADATA_KEY];
describe('attachArtifactRows', () => {
+ it('places a backfilled row without a turn on the first reply saved after its artifact', () => {
+ const at = (message: ThreadMessage, createdAt: string) => ({ ...message, createdAt });
+ // An older thread: replies carry no turn id, and the backfilled row was
+ // appended at the end of the log with its artifact's own (earlier) time.
+ const out = attachArtifactRows([
+ at(user('u1', 'x'), '2026-10-01T09:00:00Z'),
+ at(reply('r1'), '2026-10-01T09:01:00Z'),
+ at(user('u2', 'y'), '2026-10-01T10:00:00Z'),
+ at(reply('r2'), '2026-10-01T10:01:00Z'),
+ at(row('old'), '2026-10-01T09:00:40Z'),
+ ]);
+ expect(out.map(m => m.id)).toEqual(['u1', 'r1', 'u2', 'r2']);
+ expect(ids(out[1])).toEqual(['old']);
+ expect(ids(out[3])).toBeUndefined();
+ });
+
it('takes rows out of the list and lists each artifact on its turn reply', () => {
const out = attachArtifactRows([
user('u1', 'req-1'),
diff --git a/app/src/services/api/artifactRows.ts b/app/src/services/api/artifactRows.ts
index a5070abcbb..6a63aeddac 100644
--- a/app/src/services/api/artifactRows.ts
+++ b/app/src/services/api/artifactRows.ts
@@ -25,7 +25,10 @@ function stringField(metadata: Record<string, unknown> | undefined, key: string)
/**
* The reply an artifact row belongs to: the last agent message of the row's
- * turn, or, for a row without a turn, the first agent message after it.
+ * turn, or, for a row without a turn, the first agent message saved at or after
+ * the artifact. A backfilled row is appended at the end of the log but keeps
+ * its artifact's time, so a row without a turn is placed by time, and by
+ * position only when a time cannot be read.
*/
function replyIndexFor(messages: readonly ThreadMessage[], rowIndex: number, requestId?: string) {
// Rows are agent messages too; a row is never a reply.
@@ -39,6 +42,13 @@ function replyIndexFor(messages: readonly ThreadMessage[], rowIndex: number, req
}
return -1;
}
+ const madeAt = Date.parse(messages[rowIndex].createdAt);
+ if (!Number.isNaN(madeAt)) {
+ return messages.findIndex(message => {
+ const savedAt = Date.parse(message.createdAt);
+ return isReply(message) && !Number.isNaN(savedAt) && savedAt >= madeAt;
+ });
+ }
return messages.findIndex((message, i) => i > rowIndex && isReply(message));
}
diff --git a/crates/openhuman-app/src/artifact_commands.rs b/crates/openhuman-app/src/artifact_commands.rs
index 297cb9e7ea..dcc6b66a69 100644
--- a/crates/openhuman-app/src/artifact_commands.rs
+++ b/crates/openhuman-app/src/artifact_commands.rs
@@ -75,13 +75,18 @@ fn check_artifact_id(artifact_id: &str) -> Result<(), String> {
#[tauri::command]
pub async fn read_artifact_body(artifact_id: String) -> Result<ArtifactBodyResult, String> {
- let config = openhuman_rpc::embed::config::load_config_with_timeout().await?;
- read_body_in(&config.workspace_dir, &artifact_id).await
+ 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.
+/// [`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)?;
@@ -111,7 +116,9 @@ async fn read_body_in(
// 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.
- if kind == "file" && !body.is_empty() {
+ // 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
@@ -166,7 +173,7 @@ pub async fn save_artifact_as(
artifact_id: String,
filename: String,
) -> Result<Option<String>, String> {
- let config = openhuman_rpc::embed::config::load_config_with_timeout().await?;
+ let config = openhuman_rpc::embed::config::load_host_config().await?;
let roots = openhuman_rpc::embed::artifacts::FileRoots::from_config(&config);
let source = resolve_source(&config.workspace_dir, &roots, &artifact_id).await?;
let sanitized = sanitize_filename(&filename)?;
diff --git a/crates/openhuman-app/src/artifact_commands_tests.rs b/crates/openhuman-app/src/artifact_commands_tests.rs
index 81fccabd99..be8f2191fa 100644
--- a/crates/openhuman-app/src/artifact_commands_tests.rs
+++ b/crates/openhuman-app/src/artifact_commands_tests.rs
@@ -278,10 +278,14 @@ async fn read_body_never_leaves_the_versioned_store() {
});
std::fs::write(workspace.path().join("x.json"), outside.to_string()).unwrap();
- let err = read_body_in(workspace.path(), "../../x")
- .await
- .err()
- .unwrap();
+ let err = read_body_in(
+ workspace.path(),
+ &FileRoots::new(workspace.path()),
+ "../../x",
+ )
+ .await
+ .err()
+ .unwrap();
assert!(err.contains("invalid artifact id"), "{err}");
}
@@ -289,13 +293,17 @@ async fn read_body_never_leaves_the_versioned_store() {
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(), "md-1").await.unwrap();
+ 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(), "f-1").await.unwrap();
+ 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));
}
@@ -308,7 +316,9 @@ async fn a_file_over_the_preview_limit_is_not_read() {
let path = file.display().to_string();
versioned_record(workspace.path(), "big-1", "file", &path);
- let read = read_body_in(workspace.path(), "big-1").await.unwrap();
+ 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);
@@ -340,3 +350,19 @@ fn docx_text_keeps_words_split_across_runs() {
"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-core/src/agent/artifacts/files.rs b/crates/openhuman-core/src/agent/artifacts/files.rs
index 4d4038204a..71c9d37769 100644
--- a/crates/openhuman-core/src/agent/artifacts/files.rs
+++ b/crates/openhuman-core/src/agent/artifacts/files.rs
@@ -77,6 +77,19 @@ 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))
+ }
+
/// Whether `root` is one of the vouched-for folders, compared canonically
/// where the paths exist.
fn trusts(&self, root: &Path) -> bool {
diff --git a/crates/openhuman-core/src/threads/artifact_rows.rs b/crates/openhuman-core/src/threads/artifact_rows.rs
index 1284c4b1aa..7e5dc50ee4 100644
--- a/crates/openhuman-core/src/threads/artifact_rows.rs
+++ b/crates/openhuman-core/src/threads/artifact_rows.rs
@@ -43,7 +43,16 @@ const BACKFILL_PAGE: usize = 1_000;
/// The row id for an artifact. One row per artifact: a new version, a retry or
/// a re-delivered ready event finds the row already there.
pub fn artifact_row_id(artifact_id: &str) -> String {
- format!("artifact:{artifact_id}")
+ format!("{ARTIFACT_ROW_ID_PREFIX}{artifact_id}")
+}
+
+/// Prefix of every artifact row's id ([`artifact_row_id`]).
+const ARTIFACT_ROW_ID_PREFIX: &str = "artifact:";
+
+/// Whether `message_id` names an artifact row: for readers that see ids but not
+/// message types, such as search hits.
+pub fn is_artifact_row_id(message_id: &str) -> bool {
+ message_id.starts_with(ARTIFACT_ROW_ID_PREFIX)
}
/// Whether `message` is an artifact row.
diff --git a/crates/openhuman-core/src/threads/artifact_rows_tests.rs b/crates/openhuman-core/src/threads/artifact_rows_tests.rs
index 6fca3fedef..569192e1cf 100644
--- a/crates/openhuman-core/src/threads/artifact_rows_tests.rs
+++ b/crates/openhuman-core/src/threads/artifact_rows_tests.rs
@@ -184,3 +184,34 @@ async fn recording_an_artifact_twice_writes_one_row() {
assert_eq!(row_request_id(&rows[0]), Some("req-1"));
assert_eq!(rows[0].extra_metadata["artifactId"], "a");
}
+
+#[tokio::test]
+async fn search_never_returns_artifact_rows() {
+ let ws = temp_ws();
+ seed_thread(&ws, "t-1");
+ // The row's content is the artifact's title, which the query matches.
+ record_artifact_row(
+ &DispatchCtx::unbound(),
+ ws.clone(),
+ "t-1",
+ "a",
+ "Quarterly roadmap",
+ Some("req-1"),
+ )
+ .await
+ .unwrap();
+
+ let hits = conversations::blocking::search_cross_thread_messages(
+ DispatchCtx::unbound(),
+ ws,
+ "roadmap".to_string(),
+ 10,
+ None,
+ )
+ .await
+ .unwrap();
+ assert!(
+ hits.iter().all(|hit| !is_artifact_row_id(&hit.message_id)),
+ "{hits:?}"
+ );
+}
diff --git a/crates/openhuman-core/src/threads/store/blocking.rs b/crates/openhuman-core/src/threads/store/blocking.rs
index 2adcdaaa00..98fefac2f7 100644
--- a/crates/openhuman-core/src/threads/store/blocking.rs
+++ b/crates/openhuman-core/src/threads/store/blocking.rs
@@ -274,6 +274,10 @@ pub async fn purge_threads(
///
/// The heaviest operation in the family: a cold inverted index reads every
/// thread's transcript before the search runs.
+///
+/// Artifact rows never come back: they only place cards in the UI, and these
+/// hits feed search results and the agent's cross-chat context. The search asks
+/// for extra hits so dropping rows still fills `limit`.
pub async fn search_cross_thread_messages(
ctx: DispatchCtx,
workspace_dir: PathBuf,
@@ -281,14 +285,20 @@ pub async fn search_cross_thread_messages(
limit: usize,
exclude_thread_id: Option<String>,
) -> Result<Vec<CrossThreadHit>, String> {
- run(ctx.clone(), "search_cross_thread_messages", move || {
+ let wanted = limit.saturating_mul(2).max(limit.saturating_add(8));
+ let hits = run(ctx.clone(), "search_cross_thread_messages", move || {
ConversationStore::new(ctx, workspace_dir).search_cross_thread_messages(
&query,
- limit,
+ wanted,
exclude_thread_id.as_deref(),
)
})
- .await
+ .await?;
+ Ok(hits
+ .into_iter()
+ .filter(|hit| !crate::threads::artifact_rows::is_artifact_row_id(&hit.message_id))
+ .take(limit)
+ .collect())
}
#[cfg(test)]