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 CodeRabbit review
Sanil02e4a339e4af
diff --git a/app/src/features/conversations/Conversations.tsx b/app/src/features/conversations/Conversations.tsxindex ce1188d194..4d90be680a 100644--- a/app/src/features/conversations/Conversations.tsx+++ b/app/src/features/conversations/Conversations.tsx@@ -2175,9 +2175,11 @@ const Conversations = ({a =>// Ready artifacts render inside their turn's reply, placed by the// core's artifact rows (`MessageArtifactCards`); so does an- // in-progress one whose event names its turn. Only an in-progress- // artifact with no turn (an older core) waits at the end.- !a.ownerRequestId && !a.toolCallId && a.status === 'in_progress'+ // in-progress one whose event names its turn. Here wait an+ // in-progress artifact with no turn (an older core) and every failed+ // one, which needs its Retry button.+ !a.toolCallId &&+ (a.status === 'failed' || (!a.ownerRequestId && a.status === 'in_progress'))): [];const liveArtifactDeck =diff --git a/app/src/features/conversations/aui/ArtifactCardAdapter.tsx b/app/src/features/conversations/aui/ArtifactCardAdapter.tsxindex 963f6eecc6..d4eeb988b6 100644--- a/app/src/features/conversations/aui/ArtifactCardAdapter.tsx+++ b/app/src/features/conversations/aui/ArtifactCardAdapter.tsx@@ -55,27 +55,9 @@ export function ArtifactCardAdapter({? t('chat.artifact.failed'): '';- const handleClick = () => {- if (isReady && onOpenPreview) {- onOpenPreview(artifact.artifactId);- }- };-- const handleKeyDown = (e: React.KeyboardEvent) => {- if (e.key === 'Enter' || e.key === ' ') {- e.preventDefault();- handleClick();- }- };-+ // The card's own button is the one control that opens the preview.return (- <div- role={isReady && onOpenPreview ? 'button' : undefined}- tabIndex={isReady && onOpenPreview ? 0 : undefined}- onClick={handleClick}- onKeyDown={isReady && onOpenPreview ? handleKeyDown : undefined}- className={'flex flex-col items-start gap-1.5' + (isReady ? ' cursor-pointer' : '')}- data-testid="artifact-card-adapter">+ <div className="flex flex-col items-start gap-1.5" data-testid="artifact-card-adapter"><ArtifactCardtitle={artifact.title}meta={meta}diff --git a/app/src/features/conversations/aui/ArtifactPreviewPanel.markdown.test.tsx b/app/src/features/conversations/aui/ArtifactPreviewPanel.markdown.test.tsxindex 4d9aada8cc..b19be40a48 100644--- a/app/src/features/conversations/aui/ArtifactPreviewPanel.markdown.test.tsx+++ b/app/src/features/conversations/aui/ArtifactPreviewPanel.markdown.test.tsx@@ -1,6 +1,6 @@import { configureStore } from '@reduxjs/toolkit';import { invoke } from '@tauri-apps/api/core';-import { render, screen } from '@testing-library/react';+import { fireEvent, render, screen } from '@testing-library/react';import { Provider } from 'react-redux';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -16,9 +16,11 @@ vi.mock('../../../lib/i18n/I18nContext', () => ({const MD = '# Hello\n\nThis is **bold** text.\n';-function renderPanel(kind: string, body: string) {+function renderPanel(kind: string, body: string, failWith?: string) {// Stub the body fetch BEFORE mounting so the panel's effect resolves it.- vi.mocked(invoke).mockResolvedValue({ kind, title: 'Notes', version: 1, body, is_text: true });+ if (failWith) vi.mocked(invoke).mockRejectedValue(failWith);+ else+ vi.mocked(invoke).mockResolvedValue({ kind, title: 'Notes', version: 1, body, is_text: true });const store = configureStore({ reducer: { chatRuntime: chatRuntimeReducer } });store.dispatch(upsertArtifactReadyForThread({@@ -69,10 +71,19 @@ describe('ArtifactPreviewPanel — preview rendering by kind (#1535)', () => {const frame = await screen.findByTitle('HTML preview');expect(frame.tagName).toBe('IFRAME');- expect(frame.getAttribute('sandbox')).toBe('allow-scripts allow-same-origin');+ expect(frame.getAttribute('sandbox')).toBe('allow-scripts');expect(frame.getAttribute('srcdoc')).toContain('<h1>Hi</h1>');});+ it('keeps the editor read-only when the body failed to load', async () => {+ renderPanel('markdown', '', 'artifact unreadable');++ expect(await screen.findByText('artifact unreadable')).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: /Code/ }));+ // Typing here would save the empty text over the artifact.+ expect((screen.getByRole('textbox') as HTMLTextAreaElement).readOnly).toBe(true);+ });+it('still renders plain text kind as raw preformatted source', async () => {renderPanel('text', 'plain **not** markdown\n');diff --git a/app/src/features/conversations/aui/ArtifactPreviewPanel.tsx b/app/src/features/conversations/aui/ArtifactPreviewPanel.tsxindex ffeeb24f28..2f0186d8ce 100644--- a/app/src/features/conversations/aui/ArtifactPreviewPanel.tsx+++ b/app/src/features/conversations/aui/ArtifactPreviewPanel.tsx@@ -620,7 +620,9 @@ function EditableTextViewer({const [copied, setCopied] = useState(false);// Only kinds whose record holds the content itself can take a new version;// a `file` record holds a path, and its text here is read off that file.- const editable = EDITABLE_KINDS.has(kind);+ // A body that failed to load is not the artifact's content: editing it+ // would save the empty text over it.+ const editable = EDITABLE_KINDS.has(kind) && !error;const autosave = useArtifactAutosave(artifact.artifactId, body, version, editable);// Sync when body changes (switching artifact tabs)@@ -725,7 +727,9 @@ function EditableTextViewer({<iframesrcDoc={editedBody}className="w-full flex-1 border-0"- sandbox="allow-scripts allow-same-origin"+ // Scripts run, but in an opaque origin: the agent's HTML cannot+ // reach the app window, its storage or the Tauri bridge.+ sandbox="allow-scripts"title="HTML preview"/>) : isMarkdown ? (diff --git a/app/src/lib/i18n/ru.ts b/app/src/lib/i18n/ru.tsindex 335711bbcb..ee2e948136 100644--- a/app/src/lib/i18n/ru.ts+++ b/app/src/lib/i18n/ru.ts@@ -5080,8 +5080,8 @@ const messages: TranslationMap = {'conversations.tools.createArtifact.done': 'Артефакт создан','conversations.tools.updateArtifact.active': 'Обновление артефакта','conversations.tools.updateArtifact.done': 'Артефакт обновлён',- 'conversations.tools.shareArtifact.active': 'Отправка артефакта',- 'conversations.tools.shareArtifact.done': 'Артефакт отправлен',+ 'conversations.tools.shareArtifact.active': 'Создание ссылки на артефакт',+ 'conversations.tools.shareArtifact.done': 'Ссылка на артефакт создана','flows.suggest.trigger.schedule': 'По расписанию','flows.suggest.trigger.app_event': 'По событию','flows.suggest.trigger.manual': 'По запросу',diff --git a/app/src/store/__tests__/chatRuntimeSlice.artifactTabs.test.ts b/app/src/store/__tests__/chatRuntimeSlice.artifactTabs.test.tsindex 65f288573c..4b846d0335 100644--- a/app/src/store/__tests__/chatRuntimeSlice.artifactTabs.test.ts+++ b/app/src/store/__tests__/chatRuntimeSlice.artifactTabs.test.ts@@ -1,6 +1,11 @@import { describe, expect, it } from 'vitest';-import reducer, { activateArtifactTab, closeArtifactTab, openArtifact } from '../chatRuntimeSlice';+import reducer, {+ activateArtifactTab,+ clearAllChatRuntime,+ closeArtifactTab,+ openArtifact,+} from '../chatRuntimeSlice';function seeded() {let s = reducer(undefined, openArtifact('a-1'));@@ -19,6 +24,12 @@ describe('chatRuntimeSlice — artifact tab model (#1535)', () => {expect(s2.activeArtifactId).toBe('a-1');});+ it('a full runtime reset closes every preview tab', () => {+ const s = reducer(seeded(), clearAllChatRuntime());+ expect(s.openArtifactIds).toEqual([]);+ expect(s.activeArtifactId).toBeNull();+ });+it('activateArtifactTab switches the active tab', () => {const s = reducer(seeded(), activateArtifactTab('a-1'));expect(s.activeArtifactId).toBe('a-1');diff --git a/app/src/store/chatRuntimeSlice.ts b/app/src/store/chatRuntimeSlice.tsindex dcf5646c58..dcf385a32b 100644--- a/app/src/store/chatRuntimeSlice.ts+++ b/app/src/store/chatRuntimeSlice.ts@@ -2996,6 +2996,9 @@ const chatRuntimeSlice = createSlice({state.pendingPlanReviewByThread = {};state.pendingWorkflowProposalsByThread = {};state.artifactsByThread = {};+ // The preview tabs name artifacts that are gone now.+ state.openArtifactIds = [];+ state.activeArtifactId = null;state.queueStatusByThread = {};state.pendingSendThreadIds = {};},diff --git a/crates/openhuman-app/src/artifact_commands.rs b/crates/openhuman-app/src/artifact_commands.rsindex f58f6fe875..da86cee3e9 100644--- a/crates/openhuman-app/src/artifact_commands.rs+++ b/crates/openhuman-app/src/artifact_commands.rs@@ -59,14 +59,36 @@ pub struct ArtifactBodyResult {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_config_with_timeout().await?;- let path = config- .workspace_dir+ read_body_in(&config.workspace_dir, &artifact_id).await+}++/// [`read_artifact_body`] for a given workspace.+async fn read_body_in(+ workspace_dir: &Path,+ 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(&artifact_id)- .with_extension("json");+ .join(format!("{artifact_id}.json"));let json = tokio::fs::read_to_string(&path).await.map_err(|e| format!("artifact {artifact_id} not found: {e}"))?;@@ -91,8 +113,15 @@ pub async fn read_artifact_body(artifact_id: String) -> Result<ArtifactBodyResul// Truly binary files stay as paths — the panel shows metadata + download.if kind == "file" && !body.is_empty() {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 tokio::fs::read(&file_path).await {+ 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() {@@ -105,7 +134,10 @@ pub async fn read_artifact_body(artifact_id: String) -> Result<ArtifactBodyResulErr(_) => {}}// If still no text and it's a .docx, try to extract text via Python- if !is_text && file_path.extension().and_then(|e| e.to_str()) == Some("docx") {+ 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;diff --git a/crates/openhuman-app/src/artifact_commands_tests.rs b/crates/openhuman-app/src/artifact_commands_tests.rsindex b5f7ac4604..81fccabd99 100644--- a/crates/openhuman-app/src/artifact_commands_tests.rs+++ b/crates/openhuman-app/src/artifact_commands_tests.rs@@ -29,11 +29,14 @@ async fn ready_artifact(workspace: &Path, files_dir: &Path) -> String {ArtifactKind::Presentation,"Deck","pptx",+ None,).await.unwrap();std::fs::write(&path, b"deck").unwrap();- finalize_artifact(workspace, &meta.id, 4).await.unwrap();+ finalize_artifact(workspace, &meta.id, 4, None)+ .await+ .unwrap();meta.id}@@ -240,3 +243,100 @@ 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(), "../../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(), "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();+ 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(), "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"+ );+}diff --git a/crates/openhuman-app/src/docx.rs b/crates/openhuman-app/src/docx.rsindex e706998fc2..f0d51da19d 100644--- a/crates/openhuman-app/src/docx.rs+++ b/crates/openhuman-app/src/docx.rs@@ -12,14 +12,20 @@ use std::path::Path;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+import sys, zipfile, re, htmltry:with zipfile.ZipFile(sys.argv[1]) as z:xml = z.read('word/document.xml').decode('utf-8')- text = re.sub(r'<[^>]+>', ' ', xml)- text = re.sub(r'\s+', ' ', text).strip()- sys.stdout.write(text)+ 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)"#;diff --git a/crates/openhuman-core/src/integrations/file_storage/artifact_publisher.rs b/crates/openhuman-core/src/integrations/file_storage/artifact_publisher.rsindex aea9040e57..e7eec34275 100644--- a/crates/openhuman-core/src/integrations/file_storage/artifact_publisher.rs+++ b/crates/openhuman-core/src/integrations/file_storage/artifact_publisher.rs@@ -143,12 +143,23 @@ pub(crate) fn link_seconds(}}+/// Whether `err` is the backend refusing the request's values (a 400 or 422),+/// as opposed to a transport, authentication or server failure. The+/// integration client reports a status as "Backend returned <code> <reason>".+fn is_validation_rejection(err: &anyhow::Error) -> bool {+ let message = err.to_string();+ ["Backend returned 400 ", "Backend returned 422 "]+ .iter()+ .any(|prefix| message.contains(prefix))+}+impl StorageArtifactPublisher {/// A presigned link for `file_id` lasting `seconds`. If the backend- /// rejects that lifetime, one retry asks for its default lifetime instead.+ /// rejects that lifetime (a 400/422), one retry asks for its default+ /// lifetime instead; any other failure is returned as it is.async fn private_link(&self, file_id: &str, seconds: u64) -> anyhow::Result<LinkResponse> {let route = file_path(file_id, "/link");- match self+ let first = match self.client.post::<LinkResponse>(&self.approval,@@ -157,20 +168,20 @@ impl StorageArtifactPublisher {).await{- Ok(link) => Ok(link),- Err(first) => {- tracing::warn!(- file_id,- seconds,- err = %first,- "[file_storage] link with a set lifetime refused; retrying with the default"- );- self.client- .post::<LinkResponse>(&self.approval, &route, &json!({}))- .await- .map_err(|e| anyhow::anyhow!("link generation failed: {e}"))- }- }+ Ok(link) => return Ok(link),+ Err(err) if is_validation_rejection(&err) => err,+ Err(err) => return Err(anyhow::anyhow!("link generation failed: {err}")),+ };+ tracing::warn!(+ file_id,+ seconds,+ err = %first,+ "[file_storage] link with a set lifetime refused; retrying with the default"+ );+ self.client+ .post::<LinkResponse>(&self.approval, &route, &json!({}))+ .await+ .map_err(|e| anyhow::anyhow!("link generation failed: {e}"))}/// Delete an upload nothing points at. Best-effort.diff --git a/crates/openhuman-core/src/integrations/file_storage/artifact_publisher_tests.rs b/crates/openhuman-core/src/integrations/file_storage/artifact_publisher_tests.rsindex 814d1aa627..3e8e7fbeb4 100644--- a/crates/openhuman-core/src/integrations/file_storage/artifact_publisher_tests.rs+++ b/crates/openhuman-core/src/integrations/file_storage/artifact_publisher_tests.rs@@ -300,3 +300,41 @@ async fn an_upload_that_cannot_be_linked_is_deleted() {.unwrap_err();assert!(err.to_string().contains("link generation failed"), "{err}");}++#[tokio::test]+async fn a_server_failure_on_the_link_is_not_retried() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/agent-integrations/file-storage/files"))+ .respond_with(uploaded(None))+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path("/agent-integrations/file-storage/files/file-1/link"))+ .respond_with(+ ResponseTemplate::new(503)+ .set_body_json(json!({ "success": false, "error": "unavailable" })),+ )+ .expect(1)+ .mount(&server)+ .await;+ Mock::given(method("DELETE"))+ .and(path("/agent-integrations/file-storage/files/file-1"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "success": true, "data": { "deleted": true }+ })))+ .expect(1)+ .mount(&server)+ .await;++ let record = ArtifactRecord::new("a-1", "T", ArtifactKind::Text, "x", "agent", 1);+ let err = publisher(server.uri(), AutonomyLevel::Full)+ .publish(+ &record,+ record.latest().unwrap(),+ &PublishOptions::default(),+ )+ .await+ .unwrap_err();+ assert!(err.to_string().contains("link generation failed"), "{err}");+}diff --git a/crates/openhuman-core/src/threads/artifact_rows.rs b/crates/openhuman-core/src/threads/artifact_rows.rsindex 48b87196a7..1284c4b1aa 100644--- a/crates/openhuman-core/src/threads/artifact_rows.rs+++ b/crates/openhuman-core/src/threads/artifact_rows.rs@@ -37,8 +37,8 @@ pub const ARTIFACT_MESSAGE_TYPE: &str = "artifact";const LOG_PREFIX: &str = "[threads:artifact-rows]";-/// Most artifacts a thread is backfilled for in one pass.-const BACKFILL_LIMIT: usize = 1_000;+/// Artifacts read per page when a thread is backfilled.+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.@@ -173,13 +173,21 @@ pub async fn backfill_artifact_rows(thread_id: &str,messages: &[ConversationMessage],) -> Result<Vec<ConversationMessage>, String> {- let (artifacts, _) = crate::agent::artifacts::store::list_artifacts(- workspace_dir,- 0,- BACKFILL_LIMIT,- Some(thread_id),- )- .await?;+ let mut artifacts = Vec::new();+ loop {+ let (page, total) = crate::agent::artifacts::store::list_artifacts(+ workspace_dir,+ artifacts.len(),+ BACKFILL_PAGE,+ Some(thread_id),+ )+ .await?;+ let empty = page.is_empty();+ artifacts.extend(page);+ if empty || artifacts.len() >= total {+ break;+ }+ }let mut written = Vec::new();for row in missing_rows(messages, &artifacts) {let stored = conversations::blocking::append_message(