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): adopt the tiny-artifacts service for every artifact
Sanilc6627bd41f46
diff --git a/Cargo.lock b/Cargo.lockindex 7a10a1cdbd..0586b3c45b 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -7407,6 +7407,8 @@ dependencies = ["serde_json","thiserror 2.0.20","tinytools",+ "tokio",+ "tracing","uuid",]diff --git a/app/src/features/conversations/tools/__fixtures__/coreToolNames.json b/app/src/features/conversations/tools/__fixtures__/coreToolNames.jsonindex c1640bebe8..4206d241a6 100644--- a/app/src/features/conversations/tools/__fixtures__/coreToolNames.json+++ b/app/src/features/conversations/tools/__fixtures__/coreToolNames.json@@ -1,8 +1,5 @@["apply_patch",- "artifact_delete",- "artifact_get",- "artifact_list","ask_user_clarification","await_workflow","browser",@@ -20,6 +17,7 @@"cost_get_daily_history","cost_get_dashboard","cost_get_summary",+ "create_artifact","create_skill","create_workflow","credential_list",@@ -37,6 +35,7 @@"daemon_host_prefs_set","dashboard_model_health","delegate_graph",+ "delete_artifact","describe_workflow","desktop_continue_goal","desktop_find",@@ -85,6 +84,7 @@"juice_summarize","list","list_agent_definitions",+ "list_artifacts","list_connectable_toolkits","list_flow_connections","list_flow_runs",@@ -112,6 +112,7 @@"propose_workflow","proxy_config","pushover",+ "read_artifact","read_diff","read_workflow_resource","read_workflow_run_log",@@ -163,6 +164,7 @@"tool_search","uninstall_workflow","update_apply",+ "update_artifact","update_check","use_skill","validate_workflow",diff --git a/app/src/features/conversations/tools/toolPhrases.ts b/app/src/features/conversations/tools/toolPhrases.tsindex d9f6406464..b51c556a1f 100644--- a/app/src/features/conversations/tools/toolPhrases.ts+++ b/app/src/features/conversations/tools/toolPhrases.ts@@ -213,6 +213,9 @@ export const TOOL_PHRASES = {setUpWorkspace: { active: 'Setting up workspace', done: 'Set up workspace' },checkArtifacts: { active: 'Checking artifacts', done: 'Checked artifacts' },deleteArtifact: { active: 'Deleting artifact', done: 'Deleted artifact' },+ createArtifact: { active: 'Creating artifact', done: 'Created artifact' },+ updateArtifact: { active: 'Updating artifact', done: 'Updated artifact' },+ shareArtifact: { active: 'Sharing artifact', done: 'Shared artifact' },} as const satisfies Record<string, { active: string; done: string }>;export type ToolPhraseId = keyof typeof TOOL_PHRASES;diff --git a/app/src/features/conversations/tools/toolSpecs.ts b/app/src/features/conversations/tools/toolSpecs.tsindex 98d123e0e5..877cfe78bd 100644--- a/app/src/features/conversations/tools/toolSpecs.ts+++ b/app/src/features/conversations/tools/toolSpecs.ts@@ -443,7 +443,12 @@ export const EXACT_TOOL_SPECS: Record<string, ToolSpec> = {workspace_update_persona: spec('updatePersona', UserRoundIcon, 'system'),workspace_reset_persona: spec('updatePersona', UserRoundIcon, 'system'),workspace_init: spec('setUpWorkspace', FolderOpenIcon, 'system'),- artifact_delete: spec('deleteArtifact', PackageIcon, 'system'),+ create_artifact: spec('createArtifact', PackageIcon, 'system'),+ update_artifact: spec('updateArtifact', PackageIcon, 'system'),+ read_artifact: spec('checkArtifacts', PackageIcon, 'system'),+ list_artifacts: spec('checkArtifacts', PackageIcon, 'system'),+ delete_artifact: spec('deleteArtifact', PackageIcon, 'system'),+ share_artifact: spec('shareArtifact', PackageIcon, 'system'),};/**diff --git a/app/src/lib/i18n/ar.ts b/app/src/lib/i18n/ar.tsindex c27cb01880..083942b908 100644--- a/app/src/lib/i18n/ar.ts+++ b/app/src/lib/i18n/ar.ts@@ -4900,6 +4900,12 @@ const messages: TranslationMap = {'conversations.tools.checkArtifacts.done': 'تم فحص الملفات المُنشأة','conversations.tools.deleteArtifact.active': 'جارٍ حذف الملف المُنشأ','conversations.tools.deleteArtifact.done': 'تم حذف الملف المُنشأ',+ 'conversations.tools.createArtifact.active': 'جارٍ إنشاء ملف مُنشأ',+ 'conversations.tools.createArtifact.done': 'تم إنشاء الملف المُنشأ',+ 'conversations.tools.updateArtifact.active': 'جارٍ تحديث الملف المُنشأ',+ 'conversations.tools.updateArtifact.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/lib/i18n/bn.ts b/app/src/lib/i18n/bn.tsindex 42de9b1b47..b176014bfa 100644--- a/app/src/lib/i18n/bn.ts+++ b/app/src/lib/i18n/bn.ts@@ -4998,6 +4998,12 @@ const messages: TranslationMap = {'conversations.tools.checkArtifacts.done': 'আর্টিফ্যাক্ট যাচাই করা হয়েছে','conversations.tools.deleteArtifact.active': 'আর্টিফ্যাক্ট মোছা হচ্ছে','conversations.tools.deleteArtifact.done': 'আর্টিফ্যাক্ট মোছা হয়েছে',+ 'conversations.tools.createArtifact.active': 'আর্টিফ্যাক্ট তৈরি হচ্ছে',+ 'conversations.tools.createArtifact.done': 'আর্টিফ্যাক্ট তৈরি হয়েছে',+ 'conversations.tools.updateArtifact.active': 'আর্টিফ্যাক্ট আপডেট হচ্ছে',+ 'conversations.tools.updateArtifact.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/lib/i18n/de.ts b/app/src/lib/i18n/de.tsindex 5f7eb1439e..f6bc85d82f 100644--- a/app/src/lib/i18n/de.ts+++ b/app/src/lib/i18n/de.ts@@ -5179,6 +5179,12 @@ const messages: TranslationMap = {'conversations.tools.checkArtifacts.done': 'Artefakte geprüft','conversations.tools.deleteArtifact.active': 'Artefakt wird gelöscht','conversations.tools.deleteArtifact.done': 'Artefakt gelöscht',+ 'conversations.tools.createArtifact.active': 'Artefakt wird erstellt',+ 'conversations.tools.createArtifact.done': 'Artefakt erstellt',+ 'conversations.tools.updateArtifact.active': 'Artefakt wird aktualisiert',+ 'conversations.tools.updateArtifact.done': 'Artefakt aktualisiert',+ 'conversations.tools.shareArtifact.active': 'Artefakt wird geteilt',+ 'conversations.tools.shareArtifact.done': 'Artefakt geteilt','flows.suggest.trigger.schedule': 'Geplant','flows.suggest.trigger.app_event': 'Bei Ereignis','flows.suggest.trigger.manual': 'Auf Abruf',diff --git a/app/src/lib/i18n/en.ts b/app/src/lib/i18n/en.tsindex b6267a6a05..5e91c7ceeb 100644--- a/app/src/lib/i18n/en.ts+++ b/app/src/lib/i18n/en.ts@@ -5323,6 +5323,12 @@ const en: TranslationMap = {'conversations.tools.checkArtifacts.done': 'Checked artifacts','conversations.tools.deleteArtifact.active': 'Deleting artifact','conversations.tools.deleteArtifact.done': 'Deleted artifact',+ 'conversations.tools.createArtifact.active': 'Creating artifact',+ 'conversations.tools.createArtifact.done': 'Created artifact',+ 'conversations.tools.updateArtifact.active': 'Updating artifact',+ 'conversations.tools.updateArtifact.done': 'Updated artifact',+ 'conversations.tools.shareArtifact.active': 'Sharing artifact',+ 'conversations.tools.shareArtifact.done': 'Shared artifact','flows.suggest.trigger.schedule': 'Scheduled','flows.suggest.trigger.app_event': 'On event','flows.suggest.trigger.manual': 'On demand',diff --git a/app/src/lib/i18n/es.ts b/app/src/lib/i18n/es.tsindex 353e8103d4..8225461f78 100644--- a/app/src/lib/i18n/es.ts+++ b/app/src/lib/i18n/es.ts@@ -5105,6 +5105,12 @@ const messages: TranslationMap = {'conversations.tools.checkArtifacts.done': 'Artefactos comprobados','conversations.tools.deleteArtifact.active': 'Eliminando artefacto','conversations.tools.deleteArtifact.done': 'Artefacto eliminado',+ 'conversations.tools.createArtifact.active': 'Creando artefacto',+ 'conversations.tools.createArtifact.done': 'Artefacto creado',+ 'conversations.tools.updateArtifact.active': 'Actualizando artefacto',+ 'conversations.tools.updateArtifact.done': 'Artefacto actualizado',+ 'conversations.tools.shareArtifact.active': 'Compartiendo artefacto',+ 'conversations.tools.shareArtifact.done': 'Artefacto compartido','flows.suggest.trigger.schedule': 'Programado','flows.suggest.trigger.app_event': 'En evento','flows.suggest.trigger.manual': 'Bajo demanda',diff --git a/app/src/lib/i18n/fr.ts b/app/src/lib/i18n/fr.tsindex 5d28e0765a..9fb82ad744 100644--- a/app/src/lib/i18n/fr.ts+++ b/app/src/lib/i18n/fr.ts@@ -5125,6 +5125,12 @@ const messages: TranslationMap = {'conversations.tools.checkArtifacts.done': 'Artefacts vérifiés','conversations.tools.deleteArtifact.active': "Suppression de l'artefact",'conversations.tools.deleteArtifact.done': 'Artefact supprimé',+ 'conversations.tools.createArtifact.active': "Création de l'artefact",+ 'conversations.tools.createArtifact.done': 'Artefact créé',+ 'conversations.tools.updateArtifact.active': "Mise à jour de l'artefact",+ 'conversations.tools.updateArtifact.done': 'Artefact mis à jour',+ 'conversations.tools.shareArtifact.active': "Partage de l'artefact",+ 'conversations.tools.shareArtifact.done': 'Artefact partagé','flows.suggest.trigger.schedule': 'Planifié','flows.suggest.trigger.app_event': 'Sur événement','flows.suggest.trigger.manual': 'À la demande',diff --git a/app/src/lib/i18n/hi.ts b/app/src/lib/i18n/hi.tsindex 391c1f03b9..9b28c1bcda 100644--- a/app/src/lib/i18n/hi.ts+++ b/app/src/lib/i18n/hi.ts@@ -5036,6 +5036,12 @@ const messages: TranslationMap = {'conversations.tools.checkArtifacts.done': 'आर्टिफैक्ट जाँचे','conversations.tools.deleteArtifact.active': 'आर्टिफैक्ट हटा रहा है','conversations.tools.deleteArtifact.done': 'आर्टिफैक्ट हटाया',+ 'conversations.tools.createArtifact.active': 'आर्टिफैक्ट बना रहा है',+ 'conversations.tools.createArtifact.done': 'आर्टिफैक्ट बनाया',+ 'conversations.tools.updateArtifact.active': 'आर्टिफैक्ट अपडेट कर रहा है',+ 'conversations.tools.updateArtifact.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/lib/i18n/id.ts b/app/src/lib/i18n/id.tsindex 08fee49e9b..95a522bde1 100644--- a/app/src/lib/i18n/id.ts+++ b/app/src/lib/i18n/id.ts@@ -5044,6 +5044,12 @@ const messages: TranslationMap = {'conversations.tools.checkArtifacts.done': 'Artefak diperiksa','conversations.tools.deleteArtifact.active': 'Menghapus artefak','conversations.tools.deleteArtifact.done': 'Artefak dihapus',+ 'conversations.tools.createArtifact.active': 'Membuat artefak',+ 'conversations.tools.createArtifact.done': 'Artefak dibuat',+ 'conversations.tools.updateArtifact.active': 'Memperbarui artefak',+ 'conversations.tools.updateArtifact.done': 'Artefak diperbarui',+ 'conversations.tools.shareArtifact.active': 'Membagikan artefak',+ 'conversations.tools.shareArtifact.done': 'Artefak dibagikan','flows.suggest.trigger.schedule': 'Terjadwal','flows.suggest.trigger.app_event': 'Saat peristiwa','flows.suggest.trigger.manual': 'Sesuai permintaan',diff --git a/app/src/lib/i18n/it.ts b/app/src/lib/i18n/it.tsindex 54373ad8a3..ae21aad0d1 100644--- a/app/src/lib/i18n/it.ts+++ b/app/src/lib/i18n/it.ts@@ -5115,6 +5115,12 @@ const messages: TranslationMap = {'conversations.tools.checkArtifacts.done': 'Artefatti verificati','conversations.tools.deleteArtifact.active': "Eliminazione dell'artefatto",'conversations.tools.deleteArtifact.done': 'Artefatto eliminato',+ 'conversations.tools.createArtifact.active': "Creazione dell'artefatto",+ 'conversations.tools.createArtifact.done': 'Artefatto creato',+ 'conversations.tools.updateArtifact.active': "Aggiornamento dell'artefatto",+ 'conversations.tools.updateArtifact.done': 'Artefatto aggiornato',+ 'conversations.tools.shareArtifact.active': "Condivisione dell'artefatto",+ 'conversations.tools.shareArtifact.done': 'Artefatto condiviso','flows.suggest.trigger.schedule': 'Pianificato','flows.suggest.trigger.app_event': 'Su evento','flows.suggest.trigger.manual': 'Su richiesta',diff --git a/app/src/lib/i18n/ja.ts b/app/src/lib/i18n/ja.tsindex 4646890e9d..171a8a441c 100644--- a/app/src/lib/i18n/ja.ts+++ b/app/src/lib/i18n/ja.ts@@ -5398,6 +5398,12 @@ const messages: TranslationMap = {'conversations.tools.checkArtifacts.done': 'アーティファクトを確認しました','conversations.tools.deleteArtifact.active': 'アーティファクトを削除中','conversations.tools.deleteArtifact.done': 'アーティファクトを削除しました',+ 'conversations.tools.createArtifact.active': 'アーティファクトを作成中',+ 'conversations.tools.createArtifact.done': 'アーティファクトを作成しました',+ 'conversations.tools.updateArtifact.active': 'アーティファクトを更新中',+ 'conversations.tools.updateArtifact.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/lib/i18n/ko.ts b/app/src/lib/i18n/ko.tsindex 56e9d0dca6..1133d84f4c 100644--- a/app/src/lib/i18n/ko.ts+++ b/app/src/lib/i18n/ko.ts@@ -4950,6 +4950,12 @@ const messages: TranslationMap = {'conversations.tools.checkArtifacts.done': '아티팩트 확인함','conversations.tools.deleteArtifact.active': '아티팩트 삭제 중','conversations.tools.deleteArtifact.done': '아티팩트 삭제함',+ 'conversations.tools.createArtifact.active': '아티팩트 만드는 중',+ 'conversations.tools.createArtifact.done': '아티팩트 만듦',+ 'conversations.tools.updateArtifact.active': '아티팩트 업데이트 중',+ 'conversations.tools.updateArtifact.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/lib/i18n/pl.ts b/app/src/lib/i18n/pl.tsindex 2e6c054512..aab54e8b3d 100644--- a/app/src/lib/i18n/pl.ts+++ b/app/src/lib/i18n/pl.ts@@ -5068,6 +5068,12 @@ const messages: TranslationMap = {'conversations.tools.checkArtifacts.done': 'Sprawdzono artefakty','conversations.tools.deleteArtifact.active': 'Usuwanie artefaktu','conversations.tools.deleteArtifact.done': 'Usunięto artefakt',+ 'conversations.tools.createArtifact.active': 'Tworzenie artefaktu',+ 'conversations.tools.createArtifact.done': 'Utworzono artefakt',+ 'conversations.tools.updateArtifact.active': 'Aktualizowanie artefaktu',+ 'conversations.tools.updateArtifact.done': 'Zaktualizowano artefakt',+ 'conversations.tools.shareArtifact.active': 'Udostępnianie artefaktu',+ 'conversations.tools.shareArtifact.done': 'Udostępniono artefakt','flows.suggest.trigger.schedule': 'Zaplanowane','flows.suggest.trigger.app_event': 'Przy zdarzeniu','flows.suggest.trigger.manual': 'Na żądanie',diff --git a/app/src/lib/i18n/pt.ts b/app/src/lib/i18n/pt.tsindex 27e7e93ad2..3ec12c915e 100644--- a/app/src/lib/i18n/pt.ts+++ b/app/src/lib/i18n/pt.ts@@ -5074,6 +5074,12 @@ const messages: TranslationMap = {'conversations.tools.checkArtifacts.done': 'Artefatos verificados','conversations.tools.deleteArtifact.active': 'Excluindo artefato','conversations.tools.deleteArtifact.done': 'Artefato excluído',+ 'conversations.tools.createArtifact.active': 'Criando artefato',+ 'conversations.tools.createArtifact.done': 'Artefato criado',+ 'conversations.tools.updateArtifact.active': 'Atualizando artefato',+ 'conversations.tools.updateArtifact.done': 'Artefato atualizado',+ 'conversations.tools.shareArtifact.active': 'Compartilhando artefato',+ 'conversations.tools.shareArtifact.done': 'Artefato compartilhado','flows.suggest.trigger.schedule': 'Agendado','flows.suggest.trigger.app_event': 'Em evento','flows.suggest.trigger.manual': 'Sob demanda',diff --git a/app/src/lib/i18n/ru.ts b/app/src/lib/i18n/ru.tsindex efd53ac951..2ddef795e4 100644--- a/app/src/lib/i18n/ru.ts+++ b/app/src/lib/i18n/ru.ts@@ -5055,6 +5055,12 @@ const messages: TranslationMap = {'conversations.tools.checkArtifacts.done': 'Артефакты проверены','conversations.tools.deleteArtifact.active': 'Удаление артефакта','conversations.tools.deleteArtifact.done': 'Артефакт удалён',+ 'conversations.tools.createArtifact.active': 'Создание артефакта',+ 'conversations.tools.createArtifact.done': 'Артефакт создан',+ 'conversations.tools.updateArtifact.active': 'Обновление артефакта',+ 'conversations.tools.updateArtifact.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/lib/i18n/tr.ts b/app/src/lib/i18n/tr.tsindex a1268f0972..4d8ddf36c3 100644--- a/app/src/lib/i18n/tr.ts+++ b/app/src/lib/i18n/tr.ts@@ -5048,6 +5048,12 @@ const messages: TranslationMap = {'conversations.tools.checkArtifacts.done': 'Çıktılar kontrol edildi','conversations.tools.deleteArtifact.active': 'Çıktı siliniyor','conversations.tools.deleteArtifact.done': 'Çıktı silindi',+ 'conversations.tools.createArtifact.active': 'Çıktı oluşturuluyor',+ 'conversations.tools.createArtifact.done': 'Çıktı oluşturuldu',+ 'conversations.tools.updateArtifact.active': 'Çıktı güncelleniyor',+ 'conversations.tools.updateArtifact.done': 'Çıktı güncellendi',+ 'conversations.tools.shareArtifact.active': 'Çıktı paylaşılıyor',+ 'conversations.tools.shareArtifact.done': 'Çıktı paylaşıldı','flows.suggest.trigger.schedule': 'Zamanlanmış','flows.suggest.trigger.app_event': 'Olay olduğunda','flows.suggest.trigger.manual': 'İsteğe bağlı',diff --git a/app/src/lib/i18n/zh-CN.ts b/app/src/lib/i18n/zh-CN.tsindex 0d38b56d90..2478b1890a 100644--- a/app/src/lib/i18n/zh-CN.ts+++ b/app/src/lib/i18n/zh-CN.ts@@ -4727,6 +4727,12 @@ const messages: TranslationMap = {'conversations.tools.checkArtifacts.done': '已检查工件','conversations.tools.deleteArtifact.active': '正在删除工件','conversations.tools.deleteArtifact.done': '已删除工件',+ 'conversations.tools.createArtifact.active': '正在创建工件',+ 'conversations.tools.createArtifact.done': '已创建工件',+ 'conversations.tools.updateArtifact.active': '正在更新工件',+ 'conversations.tools.updateArtifact.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/crates/openhuman-app/Cargo.lock b/crates/openhuman-app/Cargo.lockindex f85509f516..ca1a7f0a3a 100644--- a/crates/openhuman-app/Cargo.lock+++ b/crates/openhuman-app/Cargo.lock@@ -6561,6 +6561,8 @@ dependencies = ["serde_json","thiserror 2.0.20","tinytools",+ "tokio",+ "tracing","uuid",]diff --git a/crates/openhuman-app/permissions/README.md b/crates/openhuman-app/permissions/README.mdindex d336cc6e3b..a109224dd2 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`. |+| [`allow-artifact-download.toml`](allow-artifact-download.toml) | `allow-artifact-download` | `download_artifact_to_downloads`, `read_artifact_body`, `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 b09e94956c..9b6711467c 100644--- a/crates/openhuman-app/permissions/allow-artifact-download.toml+++ b/crates/openhuman-app/permissions/allow-artifact-download.toml@@ -7,7 +7,7 @@ description = "Allow copying agent-generated artifacts from the workspace artifaallow = ["download_artifact_to_downloads","read_artifact_body",- "save_artifact_body",+ "save_artifact_as",]deny = []diff --git a/crates/openhuman-app/src/artifact_commands.rs b/crates/openhuman-app/src/artifact_commands.rsindex 3021488949..f58f6fe875 100644--- a/crates/openhuman-app/src/artifact_commands.rs+++ b/crates/openhuman-app/src/artifact_commands.rs@@ -25,8 +25,8 @@//! 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};-use serde::{Deserialize, Serialize};/// Resolve an artifact id to the file the core's artifact store vouches for,/// in the given workspace. Isolated from config loading for unit testing.@@ -62,7 +62,8 @@ pub struct ArtifactBodyResult {#[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+ let path = config+ .workspace_dir.join("artifacts/versioned").join(&artifact_id).with_extension("json");@@ -113,58 +114,46 @@ pub async fn read_artifact_body(artifact_id: String) -> Result<ArtifactBodyResul}}}- Ok(ArtifactBodyResult { kind, title, version: versions, body, is_text })-}--#[derive(Deserialize)]-pub struct SaveArtifactBodyArgs {- pub artifact_id: String,- pub body: String,- pub note: Option<String>,+ 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.+///+/// Returns `Ok(Some(path))` once copied, `Ok(None)` when the user cancels.+/// The file copied is the one the core's artifact store vouches for; for a+/// versioned artifact that is its latest version.#[tauri::command]-pub async fn save_artifact_body(args: SaveArtifactBodyArgs) -> Result<(), String> {+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 path = config.workspace_dir- .join("artifacts/versioned")- .join(&args.artifact_id)- .with_extension("json");-- // Read existing record- let json = tokio::fs::read_to_string(&path)- .await- .map_err(|e| format!("artifact {} not found: {e}", args.artifact_id))?;- let mut record: serde_json::Value = serde_json::from_str(&json)- .map_err(|e| format!("artifact {} parse error: {e}", args.artifact_id))?;-- // Add new version- let now = chrono::Utc::now().to_rfc3339();- let new_version = serde_json::json!({- "version": record["versions"].as_array().map(|v| v.len() as u64 + 1).unwrap_or(1),- "body": args.body,- "created_at": now,- "note": args.note.unwrap_or_default(),- });-- record["versions"]- .as_array_mut()- .ok_or_else(|| "versions is not an array".to_string())?- .push(new_version);- record["updated_at"] = serde_json::Value::String(now);+ 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)?;- let updated = serde_json::to_string_pretty(&record)- .map_err(|e| format!("serialization error: {e}"))?;- tokio::fs::write(&path, &updated)+ // macOS: NSSavePanel. Windows: IFileSaveDialog. Linux: the GTK chooser.+ let Some(handle) = rfd::AsyncFileDialog::new()+ .set_file_name(&sanitized)+ .save_file().await- .map_err(|e| format!("write error: {e}"))?;-- log::info!(- "[artifact_commands] save_artifact_body id={} version={}",- args.artifact_id,- record["versions"].as_array().map(|v| v.len()).unwrap_or(0)- );- Ok(())+ else {+ log::debug!("[artifact_commands] save_artifact_as cancelled by user");+ return Ok(None);+ };+ let dest = handle.path().to_path_buf();+ let bytes = copy_to_path(&source, &dest).await?;+ // The chosen path carries the user's login and folder names; it is not+ // logged (see `directory_picker`).+ log::info!("[artifact_commands] save_artifact_as bytes={bytes}");+ Ok(Some(dest.display().to_string()))}/// Maximum number of `(N)` suffixes we'll append when picking adiff --git a/crates/openhuman-app/src/lib.rs b/crates/openhuman-app/src/lib.rsindex 583a1c454a..c40eeca264 100644--- a/crates/openhuman-app/src/lib.rs+++ b/crates/openhuman-app/src/lib.rs@@ -3305,7 +3305,7 @@ pub fn run() {// 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_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-side// substitute: a `webkitdirectory` input cannot report where thediff --git a/crates/openhuman-core/src/agent/artifacts/README.md b/crates/openhuman-core/src/agent/artifacts/README.mdindex 229c6d3a51..5914eb1683 100644--- a/crates/openhuman-core/src/agent/artifacts/README.md+++ b/crates/openhuman-core/src/agent/artifacts/README.md@@ -23,7 +23,8 @@ renders artifact content itself.| [`store.rs`](./store.rs) | All filesystem I/O over `tokio::fs`: `artifacts_root`, `create_artifact`, `finalize_artifact`, `fail_artifact`, `read_artifact_bytes` (`pub`); `save_artifact_meta`, `save_artifact_args`, `read_artifact_args`, `list_artifacts`, `get_artifact`, `delete_artifact` (`pub(crate)`); `validate_artifact_id` / `assert_within_root` sandboxing; the `REGENERATE_TARGET_ID` task-local; `sanitize_filename_stem`. || [`ops.rs`](./ops.rs) | RPC business logic returning `Outcome<Value>`: `ai_list_artifacts`, `ai_get_artifact`, `ai_delete_artifact`, `ai_regenerate`. `DEFAULT_LIMIT = 50`, `MAX_LIMIT = 200`. The regenerate path that re-runs `PresentationTool` is `#[cfg(feature = "documents")]`; without the feature `ai_regenerate` returns an error. || [`schemas.rs`](./schemas.rs) | `ControllerSchema`s and `handle_*` fns for the four `ai.*` controllers; param helpers `read_required`, `read_optional_u64`, `read_optional_string` (whitespace-only → absent), `type_name`. |-| [`tools.rs`](./tools.rs) | `ArtifactListTool`, `ArtifactGetTool`, `ArtifactDeleteTool`: shims over `ops` that unwrap the `Outcome` and return `outcome.value` as the `ToolResult` string. |+| [`tiny_store.rs`](./tiny_store.rs) | OpenHuman's side of the versioned artifacts (`tiny-artifacts`): `versioned_store` (the crate's `FsArtifactStore` over `<workspace>/artifacts/versioned/`, one `<id>.json` per artifact), `LegacyUiBridge` (the crate's `ArtifactObserver`: shows each artifact's newest version through the legacy row + events and the files folder), `artifacts_service`, the agent tools, and `save_operator_version` (the preview panel's autosave). |+| [`production.rs`](./production.rs) | `Production`: how producer tools (deck, document, generated media) file their output — reserve the file and the card, open the versioned record under the same id, then complete or fail it. || `*_tests.rs` | Sibling test files for each of the above (`#[path]`). |## Public surface@@ -62,16 +63,23 @@ When `thread_id` is given to `list_artifacts`, legacy records with no## Agent tools-Constructed in [`tools/ops.rs`](../../tools/ops.rs) (unconditionally) and re-exported through-[`tools/mod.rs`](../../tools/mod.rs) (`pub use crate::agent::artifacts::tools::*`).+The agent's artifact tools are the `tiny-artifacts` crate's, bound to this+workspace by [`tiny_store::registered_tools`](./tiny_store.rs) and constructed in+[`tools/ops.rs`](../../tools/ops.rs). Every write goes through the crate's+`Artifacts` service, so a tool-made artifact is a versioned record shown+through `LegacyUiBridge` exactly like a producer-made one.| Tool | Permission | Behavior || --- | --- | --- |-| `artifact_list` | default | `ops::ai_list_artifacts(.., thread_id = None)`: always the whole workspace; the per-thread filter is RPC-only. `offset` / `limit` args. Concurrency-safe. |-| `artifact_get` | default | `ops::ai_get_artifact`; `artifact_id` required. Concurrency-safe. |-| `artifact_delete` | `Dangerous` | `ops::ai_delete_artifact`. Default-OFF: listed as its own `ToolFamily` (`id: "artifact_delete"`, `default_enabled: false`) in `TOOL_FAMILIES` in [`tools/user_filter.rs`](../../tools/user_filter.rs); `artifact_list` / `artifact_get` are deliberately not in that map so they cannot be toggled off. |+| `create_artifact` | `Write` | New artifact with its first version: `body` for `text` / `markdown` / `html`, `path` (a file in the agent's working folder or the files folder) for `image` / `file`. |+| `update_artifact` | `Write` | Appends a version; an identical text body appends nothing. |+| `read_artifact` | default | One record with its full history. |+| `list_artifacts` | default | Every versioned record, newest first. |+| `delete_artifact` | `Dangerous` | Deletes the record, its card and file. Default-OFF: its `ToolFamily` in [`tools/user_filter.rs`](../../tools/user_filter.rs) keeps the old toggle id `artifact_delete` so saved choices still apply. |-There is no regenerate tool; regeneration is RPC-only.+All five classify as `DomainGroup::Agent` (`tools/ops_tool_groups.rs`), so a+harness-scoped agent keeps them. There is no regenerate tool; regeneration is+RPC-only.## Events@@ -145,7 +153,7 @@ event.- `create_artifact` rejects empty titles/extensions and extensionscontaining `/`, `\`, or `.`. Filename stems are lowercased ASCII`[a-z0-9_-]`, capped at 80 chars, fallback `artifact`.-- Log prefix is `[artifacts]` (`[tool][artifacts]` in `tools.rs`).+- Log prefix is `[artifacts]` (`[tiny-artifacts]` in `tiny_store.rs`).## Further readingdiff --git a/crates/openhuman-core/src/agent/artifacts/mod.rs b/crates/openhuman-core/src/agent/artifacts/mod.rsindex 305fa9eb89..f1e5d4274c 100644--- a/crates/openhuman-core/src/agent/artifacts/mod.rs+++ b/crates/openhuman-core/src/agent/artifacts/mod.rs@@ -1,11 +1,11 @@pub mod files;pub mod migrate;pub mod ops;+pub mod production;pub mod schemas;pub mod store;mod store_documents;pub mod tiny_store;-pub mod tools;pub mod types;pub use files::{resolve_ready_file, FileRoots};diff --git a/crates/openhuman-core/src/agent/artifacts/ops.rs b/crates/openhuman-core/src/agent/artifacts/ops.rsindex eb0cca8b57..2b9dac7988 100644--- a/crates/openhuman-core/src/agent/artifacts/ops.rs+++ b/crates/openhuman-core/src/agent/artifacts/ops.rs@@ -276,3 +276,73 @@ async fn regenerate_presentation(#[cfg(test)]#[path = "ops_tests.rs"]mod tests;++/// Save the user's edit of a versioned artifact as a new operator version+/// (the preview panel's autosave). See+/// [`super::tiny_store::save_operator_version`].+pub async fn ai_save_artifact_version(+ config: &Config,+ artifact_id: &str,+ body: &str,+) -> Result<Outcome<Value>, String> {+ let saved = super::tiny_store::save_operator_version(+ &config.workspace_dir,+ super::files::FileRoots::from_config(config),+ artifact_id,+ body,+ )+ .await?;+ log::debug!(+ "[artifacts] ai_save_artifact_version id={artifact_id} version={} saved={}",+ saved.version,+ saved.saved+ );+ Ok(Outcome::new(+ json!({ "artifact_id": artifact_id, "version": saved.version, "saved": saved.saved }),+ vec![],+ ))+}++/// Share a version of an artifact through cloud file storage (the preview+/// panel's Share button): uploads it and returns its link, which is also+/// recorded on the version. A version that already has a live link of the same+/// kind returns it without uploading again.+pub async fn ai_share_artifact(+ config: &Config,+ artifact_id: &str,+ version: Option<u32>,+ public: bool,+) -> Result<Outcome<Value>, String> {+ let publisher = crate::integrations::file_storage::artifact_publisher(config)+ .ok_or_else(|| "sign in to share artifacts".to_string())?;+ let artifacts = super::tiny_store::artifacts_service(+ &config.workspace_dir,+ super::files::FileRoots::from_config(config),+ None,+ )+ .with_publisher(publisher);+ let options = tiny_artifacts::PublishOptions {+ public,+ ..tiny_artifacts::PublishOptions::default()+ };+ let shared = artifacts+ .publish(artifact_id, version, &options)+ .await+ .map_err(|e| e.to_string())?;+ log::debug!(+ "[artifacts] ai_share_artifact id={artifact_id} version={} public={public} reused={}",+ shared.version,+ shared.reused+ );+ Ok(Outcome::new(+ json!({+ "artifact_id": artifact_id,+ "version": shared.version,+ "url": shared.link.url,+ "public": shared.link.public,+ "expires_at_millis": shared.link.expires_at_millis,+ "reused": shared.reused,+ }),+ vec![],+ ))+}diff --git a/crates/openhuman-core/src/agent/artifacts/ops_tests.rs b/crates/openhuman-core/src/agent/artifacts/ops_tests.rsindex 40a534a128..393aad3e35 100644--- a/crates/openhuman-core/src/agent/artifacts/ops_tests.rs+++ b/crates/openhuman-core/src/agent/artifacts/ops_tests.rs@@ -448,3 +448,13 @@ async fn get_and_delete_refuse_a_record_rooted_outside_the_files_folder() {"the file outside the files folder is left alone");}++#[tokio::test]+async fn sharing_without_cloud_storage_is_refused_with_a_reason() {+ let tmp = TempDir::new().unwrap();+ let config = test_config(&tmp);+ let err = ai_share_artifact(&config, "a-1", None, false)+ .await+ .unwrap_err();+ assert!(err.contains("sign in"), "{err}");+}diff --git a/crates/openhuman-core/src/agent/artifacts/production.rs b/crates/openhuman-core/src/agent/artifacts/production.rsnew file mode 100644index 0000000000..d274e994c8--- /dev/null+++ b/crates/openhuman-core/src/agent/artifacts/production.rs@@ -0,0 +1,194 @@+//! [`Production`]: how a producer tool (a deck, a document, a generated image+//! or video) files what it makes as a versioned artifact.+//!+//! Every artifact goes through the `tiny-artifacts` service; a producer only+//! adds the part that is OpenHuman's — reserving a file name in the visible+//! files folder, so it can write its bytes there while the user already sees+//! a "generating…" card. The flow:+//!+//! 1. [`Production::start`] reserves the file and the card, and opens the+//! versioned record under the same id. A revision (`revise`, or a+//! regenerate running inside [`super::store::REGENERATE_TARGET_ID`]) reuses+//! the existing id and file, and keeps the record's history.+//! 2. The producer writes its bytes to [`Production::path`].+//! 3. [`Production::complete`] appends the file as a new agent version; the UI+//! bridge marks the card ready. [`Production::fail`] fails both instead.+//!+//! The record is written before the card is marked ready, so a ready card+//! always has its versioned record.++use std::path::{Path, PathBuf};++use tiny_artifacts::{ArtifactKind, Artifacts, Author, Content};++use super::files::FileRoots;+use super::tiny_store::{artifacts_service, legacy_kind_for_extension};+use super::types::ArtifactKind as LegacyArtifactKind;++/// A file being produced as an artifact.+pub struct Production {+ artifacts: Artifacts,+ workspace_dir: PathBuf,+ files: FileRoots,+ id: String,+ path: PathBuf,+}++impl std::fmt::Debug for Production {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("Production")+ .field("id", &self.id)+ .field("path", &self.path)+ .finish_non_exhaustive()+ }+}++impl Production {+ /// Reserve the file (`<title>.<extension>` in the files folder) and open+ /// the artifact. `revise` names an existing artifact to add a version to;+ /// otherwise a regenerate in scope is revised, or a new artifact is made.+ /// `tool_call_id` ties the card to the producing call's bubble.+ ///+ /// # Errors+ ///+ /// Returns an error when the file cannot be reserved or the record cannot+ /// be opened; the card is failed in the second case.+ pub async fn start(+ workspace_dir: &Path,+ files: FileRoots,+ kind: ArtifactKind,+ title: &str,+ extension: &str,+ tool_call_id: Option<&str>,+ revise: Option<&str>,+ ) -> Result<Self, String> {+ let legacy_kind = if kind == ArtifactKind::Image {+ LegacyArtifactKind::Image+ } else {+ legacy_kind_for_extension(&extension.to_ascii_lowercase())+ };+ let target = revise+ .map(str::to_string)+ .or_else(|| {+ super::store::REGENERATE_TARGET_ID+ .try_with(Clone::clone)+ .ok()+ })+ .filter(|id| !id.trim().is_empty());+ let reserve = super::store::create_artifact_for_call(+ workspace_dir,+ files.clone(),+ legacy_kind,+ title,+ extension,+ tool_call_id,+ );+ let (meta, path) = match &target {+ Some(id) => {+ super::store::REGENERATE_TARGET_ID+ .scope(id.clone(), reserve)+ .await?+ }+ None => reserve.await?,+ };++ let artifacts = artifacts_service(workspace_dir, files.clone(), None);+ let production = Self {+ artifacts,+ workspace_dir: workspace_dir.to_path_buf(),+ files,+ id: meta.id.clone(),+ path,+ };+ // A revision keeps its record and history; a new artifact opens one.+ let existing = production+ .artifacts+ .get(&meta.id)+ .await+ .map_err(|e| e.to_string());+ let opened = match existing {+ Ok(Some(_)) => Ok(()),+ Ok(None) => production+ .artifacts+ .begin(kind, title, Some(meta.id.clone()))+ .await+ .map(|_| ())+ .map_err(|e| e.to_string()),+ Err(err) => Err(err),+ };+ if let Err(err) = opened {+ let reason = format!("could not open the artifact record: {err}");+ production.fail_card(&reason).await;+ return Err(reason);+ }+ Ok(production)+ }++ /// The artifact's id.+ pub fn id(&self) -> &str {+ &self.id+ }++ /// Where the producer writes its bytes.+ pub fn path(&self) -> &Path {+ &self.path+ }++ /// File the written bytes as a new version and mark the card ready.+ /// Returns the file's size.+ ///+ /// # Errors+ ///+ /// Returns an error when the version cannot be recorded or the card cannot+ /// be marked ready; the card is failed then.+ pub async fn complete(&self) -> Result<u64, String> {+ let path = self.path.display().to_string();+ let saved = self+ .artifacts+ .revise(+ &self.id,+ Content::File(path),+ &Author::agent(super::tiny_store::AGENT_AUTHOR_ID),+ 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)+ }++ /// Fail the artifact with `reason`.+ pub async fn fail(&self, reason: &str) {+ if let Err(err) = self.artifacts.fail(&self.id, reason).await {+ tracing::warn!(+ target: "tiny-artifacts",+ artifact_id = %self.id,+ err = %err,+ "[artifacts] could not mark the versioned record failed"+ );+ self.fail_card(reason).await;+ }+ }++ /// Fail the card directly (when the record could not take the change).+ async fn fail_card(&self, reason: &str) {+ let _ =+ super::store::fail_artifact(&self.workspace_dir, self.files.clone(), &self.id, reason)+ .await;+ }+}++#[cfg(test)]+#[path = "production_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/agent/artifacts/production_tests.rs b/crates/openhuman-core/src/agent/artifacts/production_tests.rsnew file mode 100644index 0000000000..b0f63af70e--- /dev/null+++ b/crates/openhuman-core/src/agent/artifacts/production_tests.rs@@ -0,0 +1,159 @@+use std::path::PathBuf;++use tiny_artifacts::{ArtifactKind, ArtifactStatus as RecordStatus, ArtifactStore};++use super::*;+use crate::agent::artifacts::store::{get_artifact, REGENERATE_TARGET_ID};+use crate::agent::artifacts::tiny_store::versioned_store;+use crate::agent::artifacts::types::{ArtifactKind as CardKind, ArtifactStatus as CardStatus};++fn temp_dirs() -> (PathBuf, PathBuf) {+ let root = std::env::temp_dir().join(format!("production-{}", uuid::Uuid::new_v4()));+ let (workspace, files) = (root.join("workspace"), root.join("Files"));+ std::fs::create_dir_all(&workspace).unwrap();+ std::fs::create_dir_all(&files).unwrap();+ (workspace, files)+}++fn files_in(dir: &PathBuf) -> Vec<String> {+ let mut names: Vec<String> = std::fs::read_dir(dir)+ .unwrap()+ .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())+ .collect();+ names.sort();+ names+}++async fn produce(+ workspace: &PathBuf,+ files: &PathBuf,+ bytes: &[u8],+ tool_call_id: Option<&str>,+ revise: Option<&str>,+) -> String {+ let production = Production::start(+ workspace,+ FileRoots::new(files),+ ArtifactKind::File,+ "Quarterly Deck",+ "pptx",+ tool_call_id,+ revise,+ )+ .await+ .unwrap();+ tokio::fs::write(production.path(), bytes).await.unwrap();+ assert_eq!(production.complete().await.unwrap(), bytes.len() as u64);+ production.id().to_string()+}++#[tokio::test]+async fn a_new_artifact_shares_one_id_and_one_file_between_card_and_record() {+ let (workspace, files) = temp_dirs();+ let production = Production::start(+ &workspace,+ FileRoots::new(&files),+ ArtifactKind::File,+ "Quarterly Deck",+ "pptx",+ None,+ None,+ )+ .await+ .unwrap();+ let id = production.id().to_string();++ // While generating: a pending card, and a pending record with no version.+ let card = get_artifact(&workspace, &id).await.unwrap();+ assert_eq!(card.status, CardStatus::Pending);+ assert_eq!(card.kind, CardKind::Presentation);+ let record = versioned_store(&workspace).get(&id).await.unwrap().unwrap();+ assert_eq!(record.status, RecordStatus::Pending);+ assert!(record.versions.is_empty());++ tokio::fs::write(production.path(), b"deck-v1")+ .await+ .unwrap();+ production.complete().await.unwrap();++ let card = get_artifact(&workspace, &id).await.unwrap();+ assert_eq!(card.status, CardStatus::Ready);+ assert_eq!(card.size_bytes, 7);+ let record = versioned_store(&workspace).get(&id).await.unwrap().unwrap();+ assert_eq!(record.status, RecordStatus::Ready);+ assert_eq!(+ record.latest().unwrap().author_id,+ crate::agent::artifacts::tiny_store::AGENT_AUTHOR_ID+ );+ let file = record.latest().unwrap().file.clone().unwrap();+ assert!(file.path.ends_with("quarterly-deck.pptx"), "{}", file.path);+ assert_eq!(+ files_in(&files),+ vec!["quarterly-deck.pptx"],+ "no second copy"+ );+}++#[tokio::test]+async fn a_revision_reuses_the_id_and_file_and_keeps_the_history() {+ let (workspace, files) = temp_dirs();+ let id = produce(&workspace, &files, b"deck-v1", Some("call-1"), None).await;+ let again = produce(&workspace, &files, b"deck-v2!", None, Some(&id)).await;+ assert_eq!(again, id);++ let record = versioned_store(&workspace).get(&id).await.unwrap().unwrap();+ assert_eq!(record.versions.len(), 2);+ let card = get_artifact(&workspace, &id).await.unwrap();+ assert_eq!(card.status, CardStatus::Ready);+ assert_eq!(card.size_bytes, 8);+ // The revision keeps the card tied to the call that made the artifact.+ assert_eq!(card.tool_call_id.as_deref(), Some("call-1"));+ assert_eq!(files_in(&files), vec!["quarterly-deck.pptx"]);+ assert_eq!(+ std::fs::read(files.join("quarterly-deck.pptx")).unwrap(),+ b"deck-v2!"+ );+}++#[tokio::test]+async fn a_regenerate_in_scope_revises_the_target() {+ let (workspace, files) = temp_dirs();+ let id = produce(&workspace, &files, b"deck-v1", None, None).await;+ let again = REGENERATE_TARGET_ID+ .scope(+ id.clone(),+ produce(&workspace, &files, b"deck-v2", None, None),+ )+ .await;+ assert_eq!(again, id);+ let record = versioned_store(&workspace).get(&id).await.unwrap().unwrap();+ assert_eq!(record.versions.len(), 2);+}++#[tokio::test]+async fn a_failed_production_fails_card_and_record() {+ let (workspace, files) = temp_dirs();+ let production = Production::start(+ &workspace,+ FileRoots::new(&files),+ ArtifactKind::Image,+ "Logo",+ "png",+ None,+ None,+ )+ .await+ .unwrap();+ production.fail("provider timed out").await;++ let card = get_artifact(&workspace, production.id()).await.unwrap();+ assert_eq!(card.status, CardStatus::Failed);+ assert_eq!(card.error.as_deref(), Some("provider timed out"));+ let record = versioned_store(&workspace)+ .get(production.id())+ .await+ .unwrap()+ .unwrap();+ assert_eq!(record.status, RecordStatus::Failed);+ assert_eq!(record.error.as_deref(), Some("provider timed out"));+}diff --git a/crates/openhuman-core/src/agent/artifacts/schemas.rs b/crates/openhuman-core/src/agent/artifacts/schemas.rsindex c190e1232e..93a5209e1c 100644--- a/crates/openhuman-core/src/agent/artifacts/schemas.rs+++ b/crates/openhuman-core/src/agent/artifacts/schemas.rs@@ -12,6 +12,8 @@ pub fn all_controller_schemas() -> Vec<ControllerSchema> {schemas("get_artifact"),schemas("delete_artifact"),schemas("regenerate"),+ schemas("save_artifact_version"),+ schemas("share_artifact"),]}@@ -33,6 +35,14 @@ pub fn all_registered_controllers() -> Vec<RegisteredController> {schema: schemas("regenerate"),handler: handle_regenerate,},+ RegisteredController {+ schema: schemas("save_artifact_version"),+ handler: handle_save_artifact_version,+ },+ RegisteredController {+ schema: schemas("share_artifact"),+ handler: handle_share_artifact,+ },]}@@ -149,6 +159,106 @@ pub fn schemas(function: &str) -> ControllerSchema {},],},+ "save_artifact_version" => ControllerSchema {+ namespace: "ai",+ function: "save_artifact_version",+ description: "Save the user's edit of a versioned artifact as a new operator-authored version; updates its file and card.",+ inputs: vec![+ artifact_id_input("Identifier of the versioned artifact."),+ FieldSchema {+ name: "body",+ ty: TypeSchema::String,+ comment: "Full content of the new version.",+ required: true,+ },+ ],+ outputs: vec![FieldSchema {+ name: "result",+ ty: TypeSchema::Object {+ fields: vec![+ FieldSchema {+ name: "artifact_id",+ ty: TypeSchema::String,+ comment: "Identifier of the artifact.",+ required: true,+ },+ FieldSchema {+ name: "version",+ ty: TypeSchema::U64,+ comment: "The newest version number after the call.",+ required: true,+ },+ FieldSchema {+ name: "saved",+ ty: TypeSchema::Bool,+ comment: "False when the body matched the newest version and nothing was appended.",+ required: true,+ },+ ],+ },+ comment: "Save result payload.",+ required: true,+ }],+ },+ "share_artifact" => ControllerSchema {+ namespace: "ai",+ function: "share_artifact",+ description: "Share a version of an artifact through cloud file storage and return its link (reused while it still works).",+ inputs: vec![+ artifact_id_input("Identifier of the versioned artifact."),+ FieldSchema {+ name: "version",+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),+ comment: "Version to share; the newest when absent.",+ required: false,+ },+ FieldSchema {+ name: "public",+ ty: TypeSchema::Option(Box::new(TypeSchema::Bool)),+ comment: "A stable public link instead of a private, expiring one.",+ required: false,+ },+ ],+ outputs: vec![FieldSchema {+ name: "result",+ ty: TypeSchema::Object {+ fields: vec![+ FieldSchema {+ name: "url",+ ty: TypeSchema::String,+ comment: "The shareable link.",+ required: true,+ },+ FieldSchema {+ name: "version",+ ty: TypeSchema::U64,+ comment: "The version shared.",+ required: true,+ },+ FieldSchema {+ name: "public",+ ty: TypeSchema::Bool,+ comment: "Whether the link is public.",+ required: true,+ },+ FieldSchema {+ name: "expires_at_millis",+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),+ comment: "When the link stops working, if it expires.",+ required: false,+ },+ FieldSchema {+ name: "reused",+ ty: TypeSchema::Bool,+ comment: "True when an existing live link was returned without uploading.",+ required: true,+ },+ ],+ },+ comment: "Share result payload.",+ required: true,+ }],+ },"delete_artifact" => ControllerSchema {namespace: "ai",function: "delete_artifact",@@ -284,6 +394,51 @@ fn handle_get_artifact(params: Map<String, Value>) -> ControllerFuture {})}+fn handle_save_artifact_version(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let config = config_rpc::load_config_with_timeout().await?;+ let artifact_id = read_required::<String>(¶ms, "artifact_id")?;+ let body = read_required::<String>(¶ms, "body")?;+ to_json(+ crate::agent::artifacts::ops::ai_save_artifact_version(+ &config,+ artifact_id.trim(),+ &body,+ )+ .await?,+ )+ })+}++fn handle_share_artifact(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let config = config_rpc::load_config_with_timeout().await?;+ let artifact_id = read_required::<String>(¶ms, "artifact_id")?;+ let version = read_optional_u64(¶ms, "version")?+ .map(|v| u32::try_from(v).map_err(|_| "invalid 'version': too large".to_string()))+ .transpose()?;+ let public = match params.get("public") {+ None | Some(Value::Null) => false,+ Some(Value::Bool(b)) => *b,+ Some(other) => {+ return Err(format!(+ "invalid 'public': expected bool, got {}",+ type_name(other)+ ))+ }+ };+ to_json(+ crate::agent::artifacts::ops::ai_share_artifact(+ &config,+ artifact_id.trim(),+ version,+ public,+ )+ .await?,+ )+ })+}+fn handle_delete_artifact(params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let config = config_rpc::load_config_with_timeout().await?;diff --git a/crates/openhuman-core/src/agent/artifacts/schemas_tests.rs b/crates/openhuman-core/src/agent/artifacts/schemas_tests.rsindex f8646fb2b1..646e4c2c29 100644--- a/crates/openhuman-core/src/agent/artifacts/schemas_tests.rs+++ b/crates/openhuman-core/src/agent/artifacts/schemas_tests.rs@@ -78,7 +78,9 @@ fn all_controller_schemas_covers_every_supported_function() {"list_artifacts","get_artifact","delete_artifact",- "regenerate"+ "regenerate",+ "save_artifact_version",+ "share_artifact"]);}@@ -86,7 +88,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(), 4);+ assert_eq!(controllers.len(), 6);let names: Vec<_> = controllers.iter().map(|c| c.schema.function).collect();assert_eq!(names,@@ -94,7 +96,9 @@ fn all_registered_controllers_has_handler_per_schema() {"list_artifacts","get_artifact","delete_artifact",- "regenerate"+ "regenerate",+ "save_artifact_version",+ "share_artifact"]);}diff --git a/crates/openhuman-core/src/agent/artifacts/store.rs b/crates/openhuman-core/src/agent/artifacts/store.rsindex 8527d84144..01d44f1e46 100644--- a/crates/openhuman-core/src/agent/artifacts/store.rs+++ b/crates/openhuman-core/src/agent/artifacts/store.rs@@ -596,7 +596,11 @@ pub async fn create_artifact_for_call(created_at,error: None,thread_id,- tool_call_id: tool_call_id.map(str::to_string),+ // A regenerate keeps the tool call that made the artifact: dropping it+ // would detach the card from that call's bubble.+ tool_call_id: tool_call_id+ .map(str::to_string)+ .or_else(|| previous.as_ref().and_then(|prev| prev.tool_call_id.clone())),};save_artifact_meta(workspace_dir, &meta).await?;diff --git a/crates/openhuman-core/src/agent/artifacts/tiny_store.rs b/crates/openhuman-core/src/agent/artifacts/tiny_store.rsindex db1ac498a0..a6a3d2b20a 100644--- a/crates/openhuman-core/src/agent/artifacts/tiny_store.rs+++ b/crates/openhuman-core/src/agent/artifacts/tiny_store.rs@@ -1,32 +1,35 @@-//! `ArtifactStore` implementation for OpenHuman: versioned artifacts live-//! under `<workspace>/artifacts/versioned/`.+//! OpenHuman's side of the versioned artifacts (`tiny-artifacts`).//!-//! The crate `tiny-artifacts` defines the versioned model (`ArtifactRecord`,-//! `ArtifactVersion`, `ArtifactAuthor`) and the [`ArtifactStore`] trait; this-//! module provides OpenHuman's storage backend for it. Records are persisted-//! one file per artifact as `<root>/versioned/<id>.json`, outside the-//! legacy `meta.json` layout the one-shot producers use, so the two systems-//! coexist.+//! The crate owns what an artifact is and how it changes; every creation and+//! revision goes through its [`Artifacts`] service. OpenHuman supplies the+//! service's ports:+//!+//! * [`versioned_store`] — the crate's [`FsArtifactStore`] over+//! `<workspace>/artifacts/versioned/` (one `<id>.json` per artifact);+//! * [`LegacyUiBridge`] — the observer that shows each artifact in the+//! desktop UI;+//! * the folders file artifacts may point into: the agent's working folder+//! and the visible files folder.//!//! # UI bridge//!//! The desktop UI knows only the legacy artifact pipeline (an `ArtifactMeta`-//! row plus the `ArtifactPending` / `ArtifactReady` domain events), and it-//! only needs the *latest* revision of a deliverable — there is no version-//! stack in the UI. So every [`FsArtifactStore::upsert`] of a text-bearing-//! versioned artifact also mirrors the latest version into that legacy-//! pipeline, using the existing "regenerate in place" flow-//! ([`super::store::REGENERATE_TARGET_ID`]) so the same artifact id is-//! reused, the file it already owns is overwritten, and the UI card swaps in-//! place without flicker. Image/File kinds carry a *reference* (path), not-//! content, so they are not mirrored — their producers already file them-//! through the legacy path directly.--use std::path::Path;+//! row plus the `ArtifactPending` / `ArtifactReady` domain events), and only+//! the newest version of each artifact. [`LegacyUiBridge`] turns every+//! service write into that pipeline: the newest version's content (or, for an+//! image or file artifact, a copy of its file) is written into the files folder+//! under the same artifact id, through the "regenerate in place" flow+//! ([`super::store::REGENERATE_TARGET_ID`]), so a revision overwrites the file+//! the artifact already owns and its card updates in place.++use std::path::{Path, PathBuf};use std::sync::Arc;use async_trait::async_trait;-use tiny_artifacts::{ArtifactKind, ArtifactRecord, ArtifactStore};+use tiny_artifacts::{+ ArtifactEvent, ArtifactEventKind, ArtifactKind, ArtifactObserver, ArtifactRecord, Artifacts,+ Author, Content,+};use super::files::FileRoots;use super::types::ArtifactKind as LegacyArtifactKind;@@ -34,180 +37,260 @@ use super::types::ArtifactKind as LegacyArtifactKind;/// Subdirectory under the artifacts root holding versioned records.const VERSIONED_SUBDIR: &str = "versioned";-/// The artifacts root, mirroring [`super::store::artifacts_root`]:-/// `<workspace_dir>/artifacts/`.-async fn root(workspace_dir: &Path) -> Result<std::path::PathBuf, String> {- let root = workspace_dir.join("artifacts");- tokio::fs::create_dir_all(&root)- .await- .map_err(|e| format!("[tiny-artifacts] failed to create artifacts root {:?}: {e}", root))?;- Ok(root)+/// The legacy kind and file extension the UI gets for an artifact's newest+/// version: text kinds by kind, file kinds by the file's extension.+fn legacy_shape(record: &ArtifactRecord) -> Option<(LegacyArtifactKind, String)> {+ let latest = record.latest()?;+ let shape = match record.kind {+ ArtifactKind::Text => (LegacyArtifactKind::Document, "txt".to_string()),+ ArtifactKind::Markdown => (LegacyArtifactKind::Document, "md".to_string()),+ ArtifactKind::Html => (LegacyArtifactKind::Document, "html".to_string()),+ ArtifactKind::Image | ArtifactKind::File => {+ let ext = latest+ .file+ .as_ref()+ .and_then(tiny_artifacts::FileRef::extension)+ .or_else(|| {+ Path::new(&latest.body)+ .extension()+ .and_then(|e| e.to_str())+ .map(str::to_ascii_lowercase)+ })+ .unwrap_or_else(|| "bin".to_string());+ let kind = if record.kind == ArtifactKind::Image {+ LegacyArtifactKind::Image+ } else {+ legacy_kind_for_extension(&ext)+ };+ (kind, ext)+ }+ };+ Some(shape)}-/// Reject ids that could escape the root as a path component.-fn validate_id(id: &str) -> Result<(), String> {- if id.is_empty() {- return Err("[tiny-artifacts] artifact id must not be empty".into());- }- if id == "." || id == ".." {- return Err(format!("[tiny-artifacts] invalid artifact id: {id:?}"));- }- if id.contains('/') || id.contains('\\') {- return Err(format!("[tiny-artifacts] artifact id must not contain path separators: {id:?}"));- }- if id.starts_with('/') || id.starts_with('\\') {- return Err(format!("[tiny-artifacts] artifact id must not be absolute: {id:?}"));+pub(crate) fn legacy_kind_for_extension(ext: &str) -> LegacyArtifactKind {+ match ext {+ "pptx" | "ppt" | "key" | "odp" => LegacyArtifactKind::Presentation,+ "docx" | "doc" | "pdf" | "md" | "txt" | "rtf" | "odt" | "html" | "htm" => {+ LegacyArtifactKind::Document+ }+ "png" | "jpg" | "jpeg" | "gif" | "webp" | "svg" => LegacyArtifactKind::Image,+ "mp4" | "webm" | "mov" => LegacyArtifactKind::Video,+ _ => LegacyArtifactKind::Other,}- Ok(())}-/// Mapping from the shared model's kinds to the legacy kinds the UI renders,-/// plus the file extension for the mirrored deliverable. `None` for kinds-/// whose body is a reference rather than content (image, file) — mirroring-/// those would write the reference string as the file's bytes.-fn legacy_mirror(kind: ArtifactKind) -> Option<(LegacyArtifactKind, &'static str)> {- match kind {- ArtifactKind::Text => Some((LegacyArtifactKind::Document, "txt")),- ArtifactKind::Markdown => Some((LegacyArtifactKind::Document, "md")),- ArtifactKind::Html => Some((LegacyArtifactKind::Document, "html")),- ArtifactKind::Image | ArtifactKind::File => None,- }+pub use tiny_artifacts::FsArtifactStore;++/// The versioned records of a workspace: `tiny-artifacts`' file-system store+/// over `<workspace>/artifacts/versioned/` (one `<id>.json` per artifact).+pub fn versioned_store(workspace_dir: &Path) -> FsArtifactStore {+ FsArtifactStore::new(workspace_dir.join("artifacts").join(VERSIONED_SUBDIR))}-/// OpenHuman's storage backend for the shared versioned artifact model.-///-/// Each record is stored whole (JSON) at `<workspace>/artifacts/versioned/<id>.json`.-pub struct FsArtifactStore {- workspace_dir: std::path::PathBuf,+/// Shows versioned artifacts in the desktop UI through the legacy pipeline.+pub struct LegacyUiBridge {+ workspace_dir: PathBuf,files: FileRoots,}-impl FsArtifactStore {- /// Creates a store rooted at `workspace_dir`; `files` is the visible- /// files folder mirrored deliverables land in (same as the legacy- /// producers use, see [`FileRoots`]).- pub fn new(workspace_dir: impl Into<std::path::PathBuf>, files: FileRoots) -> Self {- Self { workspace_dir: workspace_dir.into(), files }- }-- async fn record_path(&self, id: &str) -> Result<std::path::PathBuf, String> {- validate_id(id)?;- let root = root(&self.workspace_dir).await?;- let dir = root.join(VERSIONED_SUBDIR);- tokio::fs::create_dir_all(&dir)- .await- .map_err(|e| format!("[tiny-artifacts] failed to create versioned dir {:?}: {e}", dir))?;- Ok(dir.join(format!("{id}.json")))+impl LegacyUiBridge {+ /// A bridge writing into `files` (the visible files folder).+ pub fn new(workspace_dir: impl Into<PathBuf>, files: FileRoots) -> Self {+ Self {+ workspace_dir: workspace_dir.into(),+ files,+ }}- /// Mirror the latest revision into the legacy UI pipeline: mint (or- /// regenerate) the legacy meta row under the same artifact id, write the- /// latest body to the visible files folder, and publish the ready event.- /// Best-effort — a mirror failure must not fail the versioned write.- async fn mirror_to_legacy(&self, record: &ArtifactRecord) -> anyhow::Result<()> {- let Some((legacy_kind, ext)) = legacy_mirror(record.kind) else {- return Ok(());- };- let Some(latest) = record.latest() else {+ /// 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<()> {+ let (Some(latest), Some((legacy_kind, ext))) = (record.latest(), legacy_shape(record))+ else {return Ok(());};- // Reuse the existing in-place regenerate flow so the artifact id is- // stable and the file an older revision already owns is overwritten- // rather than claiming a second name (#5505).+ // A producer writes its file straight into the row it reserved: the+ // row only needs marking ready (re-reserving would flash its card+ // back to "generating").+ if let Some(file) = latest.file.as_ref() {+ if let Ok(meta) = super::store::get_artifact(&self.workspace_dir, &record.id).await {+ let owned = meta.file.as_deref().map(Path::new);+ if owned.is_some_and(|owned| same_file(owned, Path::new(&file.path))) {+ let size = tokio::fs::metadata(&file.path).await?.len();+ super::store::finalize_artifact(&self.workspace_dir, &record.id, size)+ .await+ .map_err(anyhow::Error::msg)?;+ return Ok(());+ }+ }+ }super::store::REGENERATE_TARGET_ID.scope(record.id.clone(), async {- let (meta, path) = super::store::create_artifact(+ let (meta, dest) = super::store::create_artifact(&self.workspace_dir,self.files.clone(),legacy_kind,&record.title,- ext,+ &ext,).await.map_err(anyhow::Error::msg)?;- tokio::fs::write(&path, latest.body.as_bytes()).await?;- super::store::finalize_artifact(&self.workspace_dir, &meta.id, latest.body.len() as u64)+ let size = if record.holds_file() {+ let source = latest+ .file+ .as_ref()+ .map_or_else(|| PathBuf::from(&latest.body), |f| PathBuf::from(&f.path));+ if same_file(&source, &dest) {+ tokio::fs::metadata(&dest).await?.len()+ } else {+ tokio::fs::copy(&source, &dest).await?+ }+ } else {+ tokio::fs::write(&dest, latest.body.as_bytes()).await?;+ latest.body.len() as u64+ };+ super::store::finalize_artifact(&self.workspace_dir, &meta.id, size).await.map_err(anyhow::Error::msg)?;Ok::<(), anyhow::Error>(())})- .await?;- Ok(())+ .await+ }+}++fn same_file(a: &Path, b: &Path) -> bool {+ match (std::fs::canonicalize(a), std::fs::canonicalize(b)) {+ (Ok(a), Ok(b)) => a == b,+ _ => false,}}#[async_trait]-impl ArtifactStore for FsArtifactStore {- async fn list(&self) -> anyhow::Result<Vec<ArtifactRecord>> {- let root = root(&self.workspace_dir).await.map_err(anyhow::Error::msg)?;- let dir = root.join(VERSIONED_SUBDIR);- let mut records = Vec::new();- let mut entries = match tokio::fs::read_dir(&dir).await {- Ok(e) => e,- Err(_) => return Ok(records), // no versioned dir yet → nothing stored- };- while let Some(entry) = entries.next_entry().await? {- let path = entry.path();- if path.extension().and_then(|e| e.to_str()) != Some("json") {- continue;+impl ArtifactObserver for LegacyUiBridge {+ async fn on_event(&self, event: &ArtifactEvent) -> anyhow::Result<()> {+ let id = &event.record.id;+ match event.kind {+ ArtifactEventKind::Ready => self.show_newest(&event.record).await,+ ArtifactEventKind::Failed => {+ let reason = event.record.error.as_deref().unwrap_or("failed");+ // Only an artifact the UI already shows has a row to fail.+ if super::store::get_artifact(&self.workspace_dir, id)+ .await+ .is_ok()+ {+ super::store::fail_artifact(+ &self.workspace_dir,+ self.files.clone(),+ id,+ reason,+ )+ .await+ .map_err(anyhow::Error::msg)?;+ }+ Ok(())}- let bytes = tokio::fs::read(&path).await?;- if let Ok(record) = serde_json::from_slice::<ArtifactRecord>(&bytes) {- records.push(record);+ ArtifactEventKind::Deleted => {+ let _ = super::store::delete_artifact(&self.workspace_dir, self.files.clone(), id)+ .await;+ Ok(())}+ // The legacy pipeline's pending row needs the file's extension,+ // which a pending artifact does not have yet; its card appears+ // when the first version lands.+ ArtifactEventKind::Pending => Ok(()),}- // Most-recently-updated first, mirroring the crate's documented order.- records.sort_by(|a, b| b.updated_at_millis.cmp(&a.updated_at_millis));- Ok(records)}+}- async fn get(&self, id: &str) -> anyhow::Result<Option<ArtifactRecord>> {- let path = self.record_path(id).await.map_err(anyhow::Error::msg)?;- let bytes = match tokio::fs::read(&path).await {- Ok(b) => b,- Err(_) => return Ok(None),- };- let record = serde_json::from_slice(&bytes)?;- Ok(Some(record))- }+/// 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.+pub fn artifacts_service(+ workspace_dir: &Path,+ files: FileRoots,+ action_dir: Option<&Path>,+) -> Artifacts {+ let mut roots: Vec<PathBuf> = action_dir.map(Path::to_path_buf).into_iter().collect();+ roots.push(files.current().to_path_buf());+ Artifacts::new(Arc::new(versioned_store(workspace_dir)))+ .with_observer(Arc::new(LegacyUiBridge::new(workspace_dir, files)))+ .with_file_roots(tiny_artifacts::FileRoots::new(roots))+}- async fn upsert(&self, artifact: &ArtifactRecord) -> anyhow::Result<()> {- let path = self.record_path(&artifact.id).await.map_err(anyhow::Error::msg)?;- let bytes = serde_json::to_vec(artifact)?;- tokio::fs::write(&path, bytes).await?;- // UI bridge: surface the latest revision through the legacy pipeline.- if let Err(err) = self.mirror_to_legacy(artifact).await {- tracing::warn!(- target: "tiny-artifacts",- err = %err,- artifact_id = %artifact.id,- "[tiny-artifacts] failed to mirror artifact into legacy UI pipeline"- );- }- Ok(())+/// Build the artifact tools bound to this workspace's service: the crate's+/// default set (`create_artifact`, `read_artifact`, `update_artifact`,+/// `list_artifacts`), `delete_artifact` (default-off through its+/// `tools::user_filter` family), and — only when a `publisher` exists, i.e. the+/// user can use cloud file storage — `share_artifact`.+pub fn registered_tools(+ workspace_dir: &Path,+ files: FileRoots,+ action_dir: &Path,+ publisher: Option<Arc<dyn tiny_artifacts::ArtifactPublisher>>,+) -> Vec<Box<dyn tinytools::Tool>> {+ let mut service = artifacts_service(workspace_dir, files, Some(action_dir));+ if let Some(publisher) = publisher {+ service = service.with_publisher(publisher);+ }+ let artifacts = Arc::new(service);+ let mut tools =+ tiny_artifacts::registered_tools(artifacts.clone(), Author::agent(AGENT_AUTHOR_ID));+ tools.push(Box::new(tiny_artifacts::DeleteArtifactTool::new(+ artifacts.clone(),+ )));+ if artifacts.can_publish() {+ tools.push(Box::new(tiny_artifacts::ShareArtifactTool::new(artifacts)));}+ tools+}- async fn delete(&self, id: &str) -> anyhow::Result<bool> {- let path = self.record_path(id).await.map_err(anyhow::Error::msg)?;- let removed = match tokio::fs::remove_file(&path).await {- Ok(()) => true,- Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,- Err(e) => return Err(e.into()),- };- if removed {- // Drop the mirrored legacy row too so the Files panel does not- // keep listing a deleted artifact.- let _ = super::store::delete_artifact(&self.workspace_dir, self.files.clone(), id)- .await;- }- Ok(removed)+/// Author id stamped on versions the user writes in the desktop editor.+pub const OPERATOR_AUTHOR_ID: &str = "operator";++/// Author id stamped on versions OpenHuman's agent writes — through the+/// artifact tools and through producer tools alike. A tool run carries no+/// agent identity, so every agent-written version is attributed to this one.+pub const AGENT_AUTHOR_ID: &str = "openhuman";++/// Append the user's edit of artifact `id` as a new operator-authored version+/// (the preview panel's autosave). The UI bridge writes it to the files folder+/// and updates the card. A body identical to the newest version appends+/// nothing.+pub async fn save_operator_version(+ workspace_dir: &Path,+ files: FileRoots,+ id: &str,+ body: &str,+) -> Result<SavedVersion, String> {+ let saved = artifacts_service(workspace_dir, files, None)+ .revise(+ id,+ Content::Text(body.to_string()),+ &Author::operator(OPERATOR_AUTHOR_ID),+ None,+ )+ .await+ .map_err(|e| e.to_string())?;+ if let Some(notice) = &saved.notice {+ tracing::warn!(target: "tiny-artifacts", artifact_id = %id, "[tiny-artifacts] {notice}");}+ Ok(SavedVersion {+ version: saved.version,+ saved: saved.appended,+ })}-/// Build the versioned artifact tools bound to this store — the four tools in-/// the crate's catalogue order: `create_artifact`, `read_artifact`,-/// `update_artifact`, `list_artifacts`.-pub fn registered_tools(workspace_dir: &Path, files: FileRoots) -> Vec<Box<dyn tinytools::Tool>> {- let store: Arc<dyn ArtifactStore> = Arc::new(FsArtifactStore::new(workspace_dir, files));- tiny_artifacts::registered_tools(store)+/// Result of [`save_operator_version`].+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]+pub struct SavedVersion {+ /// The newest version number after the call.+ pub version: u32,+ /// Whether a version was appended.+ pub saved: bool,}++#[cfg(test)]+#[path = "tiny_store_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/agent/artifacts/tiny_store_tests.rs b/crates/openhuman-core/src/agent/artifacts/tiny_store_tests.rsnew file mode 100644index 0000000000..18871fc0bf--- /dev/null+++ b/crates/openhuman-core/src/agent/artifacts/tiny_store_tests.rs@@ -0,0 +1,202 @@+use std::path::PathBuf;++use tiny_artifacts::{+ ArtifactAuthor, ArtifactKind, ArtifactRecord, ArtifactStore, Author, Content,+};++use super::*;++fn temp_dirs() -> (PathBuf, PathBuf) {+ let root = std::env::temp_dir().join(format!("tiny-store-{}", uuid::Uuid::new_v4()));+ let (workspace, files) = (root.join("workspace"), root.join("Files"));+ std::fs::create_dir_all(&workspace).unwrap();+ std::fs::create_dir_all(&files).unwrap();+ (workspace, files)+}++async fn seeded(workspace: &PathBuf, _files: &PathBuf) -> FsArtifactStore {+ let store = versioned_store(&workspace);+ let record = ArtifactRecord::new(+ "a-1",+ "Notes",+ ArtifactKind::Markdown,+ "# v1",+ "agent",+ 1_000,+ );+ store.upsert(&record).await.unwrap();+ store+}++#[tokio::test]+async fn an_edit_is_appended_as_an_operator_version_and_written_to_the_file() {+ let (workspace, files) = temp_dirs();+ let store = seeded(&workspace, &files).await;++ let saved = save_operator_version(&workspace, FileRoots::new(&files), "a-1", "# v2")+ .await+ .unwrap();+ assert_eq!(+ saved,+ SavedVersion {+ version: 2,+ saved: true+ }+ );++ let record = store.get("a-1").await.unwrap().unwrap();+ let latest = record.latest().unwrap();+ assert_eq!(latest.body, "# v2");+ assert_eq!(latest.author, ArtifactAuthor::Operator);+ assert_eq!(latest.author_id, OPERATOR_AUTHOR_ID);+ assert!(record.human_edit_diff().is_some(), "the edit is diff-able");++ // The visible file now holds the edit.+ let written = std::fs::read_to_string(files.join("notes.md")).unwrap();+ assert_eq!(written, "# v2");+}++#[tokio::test]+async fn an_unchanged_body_appends_nothing() {+ let (workspace, files) = temp_dirs();+ let store = seeded(&workspace, &files).await;++ let saved = save_operator_version(&workspace, FileRoots::new(&files), "a-1", "# v1")+ .await+ .unwrap();+ assert_eq!(+ saved,+ SavedVersion {+ version: 1,+ saved: false+ }+ );+ assert_eq!(store.get("a-1").await.unwrap().unwrap().versions.len(), 1);+}++#[tokio::test]+async fn a_missing_artifact_is_an_error() {+ let (workspace, files) = temp_dirs();+ let err = save_operator_version(&workspace, FileRoots::new(&files), "nope", "x")+ .await+ .unwrap_err();+ assert!(err.contains("not found"), "{err}");+}++#[tokio::test]+async fn an_image_filed_through_the_service_gets_a_card_and_a_copy_in_files() {+ let (workspace, files) = temp_dirs();+ let action = workspace.parent().unwrap().join("projects");+ std::fs::create_dir_all(&action).unwrap();+ std::fs::write(action.join("chart.png"), b"png-bytes").unwrap();+ let artifacts = artifacts_service(&workspace, FileRoots::new(&files), Some(&action));++ let saved = artifacts+ .create(+ ArtifactKind::Image,+ "Chart",+ Content::File("chart.png".into()),+ &Author::agent("agent"),+ None,+ )+ .await+ .unwrap();+ assert!(saved.notice.is_none(), "{:?}", saved.notice);++ // The UI's row: ready, an image, with the file copied into Files.+ let meta = super::super::store::get_artifact(&workspace, &saved.record.id)+ .await+ .unwrap();+ assert_eq!(meta.status, super::super::types::ArtifactStatus::Ready);+ assert_eq!(meta.kind, super::super::types::ArtifactKind::Image);+ assert_eq!(+ std::fs::read(files.join("chart.png")).unwrap(),+ b"png-bytes"+ );+ assert_eq!(meta.size_bytes, 9);+}++#[tokio::test]+async fn a_file_outside_the_allowed_folders_is_refused() {+ let (workspace, files) = temp_dirs();+ let elsewhere = workspace.parent().unwrap().join("elsewhere");+ std::fs::create_dir_all(&elsewhere).unwrap();+ std::fs::write(elsewhere.join("x.pdf"), b"x").unwrap();+ let artifacts = artifacts_service(&workspace, FileRoots::new(&files), None);+ let err = artifacts+ .create(+ ArtifactKind::File,+ "X",+ Content::File(elsewhere.join("x.pdf").display().to_string()),+ &Author::agent("agent"),+ None,+ )+ .await+ .unwrap_err();+ assert!(err.to_string().contains("outside"), "{err}");+}++#[tokio::test]+async fn deleting_an_artifact_removes_its_card() {+ let (workspace, files) = temp_dirs();+ let artifacts = artifacts_service(&workspace, FileRoots::new(&files), None);+ let saved = artifacts+ .create(+ ArtifactKind::Markdown,+ "Notes",+ Content::Text("# hi".into()),+ &Author::agent("agent"),+ None,+ )+ .await+ .unwrap();+ let id = saved.record.id;+ assert!(super::super::store::get_artifact(&workspace, &id)+ .await+ .is_ok());++ let (removed, notice) = artifacts.delete(&id).await.unwrap();+ assert!(removed);+ assert!(notice.is_none(), "{notice:?}");+ assert!(super::super::store::get_artifact(&workspace, &id)+ .await+ .is_err());+}++struct NoopPublisher;++#[async_trait::async_trait]+impl tiny_artifacts::ArtifactPublisher for NoopPublisher {+ async fn publish(+ &self,+ _record: &ArtifactRecord,+ _version: &tiny_artifacts::ArtifactVersion,+ options: &tiny_artifacts::PublishOptions,+ ) -> anyhow::Result<tiny_artifacts::PublishedLink> {+ Ok(tiny_artifacts::PublishedLink {+ url: "https://example/x".into(),+ expires_at_millis: None,+ published_at_millis: 0,+ public: options.public,+ })+ }+}++#[test]+fn share_artifact_is_offered_only_with_a_publisher() {+ let (workspace, files) = temp_dirs();+ let names = |publisher: Option<std::sync::Arc<dyn tiny_artifacts::ArtifactPublisher>>| {+ registered_tools(&workspace, FileRoots::new(&files), &workspace, publisher)+ .iter()+ .map(|t| t.name().to_string())+ .collect::<Vec<_>>()+ };+ let without = names(None);+ assert!(+ !without.contains(&"share_artifact".to_string()),+ "{without:?}"+ );+ assert!(without.contains(&"delete_artifact".to_string()));+ let with = names(Some(std::sync::Arc::new(NoopPublisher)));+ assert!(with.contains(&"share_artifact".to_string()), "{with:?}");+}diff --git a/crates/openhuman-core/src/agent/artifacts/tools.rs b/crates/openhuman-core/src/agent/artifacts/tools.rsdeleted file mode 100644index 0f7e01b51c..0000000000--- a/crates/openhuman-core/src/agent/artifacts/tools.rs+++ /dev/null@@ -1,212 +0,0 @@-//! LLM-callable wrappers over the artifacts metadata domain.-//!-//! Each tool is a thin shim over a read/delete handler in-//! [`crate::agent::artifacts::ops`], unwrapping the `Outcome`-//! envelope and emitting the inner JSON value. The artifacts domain owns-//! agent-generated files (presentations/documents/images): metadata under-//! `<workspace>/artifacts/`, the files themselves in the visible files folder-//! (`~/OpenHuman/projects/Files`, #5505); these tools let the agent enumerate-//! and inspect what it has produced.-//!-//! `artifact_list` / `artifact_get` are read-only and default-enabled.-//! `artifact_delete` is `Dangerous` (irreversibly removes the file and its record) and-//! ships default-OFF — it must be opted in via the tool toggle-//! (the `artifact_delete` `ToolFamily` in `TOOL_FAMILIES`,-//! `tools/user_filter.rs`).--use std::sync::Arc;--use async_trait::async_trait;-use serde_json::json;--use crate::agent::artifacts::ops;-use crate::config::Config;-use tinytools::{PermissionLevel, Tool, ToolResult};--/// Read `offset` / `limit` as optional `usize` from tool args.-fn read_opt_usize(args: &serde_json::Value, key: &str) -> Option<usize> {- args.get(key)- .and_then(serde_json::Value::as_u64)- .map(|v| v as usize)-}--/// Read a required, non-empty string arg.-fn read_required_str(args: &serde_json::Value, key: &str) -> anyhow::Result<String> {- let raw = args- .get(key)- .and_then(serde_json::Value::as_str)- .map(str::trim)- .filter(|s| !s.is_empty());- match raw {- Some(s) => Ok(s.to_string()),- None => Err(anyhow::anyhow!("missing required string argument `{key}`")),- }-}--/// List artifacts the agent has produced, newest first.-pub struct ArtifactListTool {- config: Arc<Config>,-}--impl ArtifactListTool {- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }-}--#[async_trait]-impl Tool for ArtifactListTool {- fn name(&self) -> &str {- "artifact_list"- }-- fn description(&self) -> &str {- "List agent-generated artifacts (presentations, documents, images, \- and other files this assistant has produced), sorted by creation \- time descending. Each entry carries `id`, `kind`, `title`, `path`, \- `size_bytes`, `status`, and `created_at`. Use this to recall what \- you have already generated for the user before regenerating, or to \- find an artifact `id` to pass to `artifact_get`. Supports `offset` \- and `limit` pagination."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "offset": { "type": "integer", "minimum": 0, "description": "Pagination offset (default 0)." },- "limit": { "type": "integer", "minimum": 1, "description": "Max artifacts to return (default 50, cap 200)." }- }- })- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- log::debug!("[tool][artifacts] list invoked");- let offset = read_opt_usize(&args, "offset");- let limit = read_opt_usize(&args, "limit");- // The agent-facing tool surface lists everything in the workspace;- // the per-chat filter is an RPC-only knob used by the React panel- // (#3226). Keep the tool path unchanged so existing agent flows- // (orchestrator artifact reasoning) still see the full set.- let outcome = ops::ai_list_artifacts(&self.config, offset, limit, None)- .await- .map_err(|e| anyhow::anyhow!("artifact_list: {e}"))?;- Ok(ToolResult::success(serde_json::to_string(&outcome.value)?))- }-- fn is_concurrency_safe(&self, _args: &serde_json::Value) -> bool {- true- }-}--/// Retrieve a single artifact's metadata plus its absolute on-disk path.-pub struct ArtifactGetTool {- config: Arc<Config>,-}--impl ArtifactGetTool {- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }-}--#[async_trait]-impl Tool for ArtifactGetTool {- fn name(&self) -> &str {- "artifact_get"- }-- fn description(&self) -> &str {- "Get one agent-generated artifact by `id`, returning its metadata \- (`kind`, `title`, `path`, `size_bytes`, `status`, `created_at`) plus \- a computed `absolute_path` you can read from. Call `artifact_list` \- first to discover ids."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "artifact_id": { "type": "string", "description": "The artifact id (UUID) to fetch." }- },- "required": ["artifact_id"]- })- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- log::debug!("[tool][artifacts] get invoked");- let id = read_required_str(&args, "artifact_id")?;- let outcome = ops::ai_get_artifact(&self.config, &id)- .await- .map_err(|e| anyhow::anyhow!("artifact_get: {e}"))?;- Ok(ToolResult::success(serde_json::to_string(&outcome.value)?))- }-- fn is_concurrency_safe(&self, _args: &serde_json::Value) -> bool {- true- }-}--/// Delete an artifact directory and all its contents. **Irreversible** —-/// ships default-OFF (`Dangerous`).-pub struct ArtifactDeleteTool {- config: Arc<Config>,-}--impl ArtifactDeleteTool {- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }-}--#[async_trait]-impl Tool for ArtifactDeleteTool {- fn name(&self) -> &str {- "artifact_delete"- }-- fn description(&self) -> &str {- "Permanently delete an agent-generated artifact and all of its files \- by `id`. This is IRREVERSIBLE — the artifact directory is removed \- from disk. Only use when the user has clearly asked to discard a \- specific artifact."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "artifact_id": { "type": "string", "description": "The artifact id (UUID) to delete." }- },- "required": ["artifact_id"]- })- }-- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Dangerous- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- log::debug!("[tool][artifacts] delete invoked");- let id = read_required_str(&args, "artifact_id")?;- let outcome = ops::ai_delete_artifact(&self.config, &id)- .await- .map_err(|e| anyhow::anyhow!("artifact_delete: {e}"))?;- Ok(ToolResult::success(serde_json::to_string(&outcome.value)?))- }-}--/// Build this domain's tools in their persisted catalogue order.-pub(crate) fn registered_tools(- config: std::sync::Arc<crate::config::Config>,-) -> Vec<Box<dyn tinytools::Tool>> {- vec![- Box::new(ArtifactListTool::new(config.clone())),- Box::new(ArtifactGetTool::new(config.clone())),- Box::new(ArtifactDeleteTool::new(config.clone())),- ]-}--#[cfg(test)]-#[path = "tools_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/agent/artifacts/tools_tests.rs b/crates/openhuman-core/src/agent/artifacts/tools_tests.rsdeleted file mode 100644index 90d0129b59..0000000000--- a/crates/openhuman-core/src/agent/artifacts/tools_tests.rs+++ /dev/null@@ -1,68 +0,0 @@-use super::*;-use tinytools::ToolScope;--fn test_config() -> Arc<Config> {- Arc::new(Config::default())-}--#[test]-fn metadata_is_stable() {- let cfg = test_config();- assert_eq!(ArtifactListTool::new(cfg.clone()).name(), "artifact_list");- assert_eq!(ArtifactGetTool::new(cfg.clone()).name(), "artifact_get");- assert_eq!(- ArtifactDeleteTool::new(cfg.clone()).name(),- "artifact_delete"- );- assert_eq!(- ArtifactListTool::new(cfg.clone()).permission_level(),- PermissionLevel::ReadOnly- );- assert_eq!(- ArtifactDeleteTool::new(cfg.clone()).permission_level(),- PermissionLevel::Dangerous- );- assert_eq!(ArtifactListTool::new(cfg).scope(), ToolScope::All);-}--#[test]-fn read_tools_are_concurrency_safe() {- let cfg = test_config();- assert!(ArtifactListTool::new(cfg.clone()).is_concurrency_safe(&serde_json::Value::Null));- assert!(ArtifactGetTool::new(cfg).is_concurrency_safe(&serde_json::Value::Null));-}--#[tokio::test]-async fn get_requires_artifact_id() {- let tool = ArtifactGetTool::new(test_config());- let err = tool- .execute(json!({}))- .await- .expect_err("expected missing-arg error");- assert!(err.to_string().contains("artifact_id"));-}--#[tokio::test]-async fn delete_requires_artifact_id() {- let tool = ArtifactDeleteTool::new(test_config());- let err = tool- .execute(json!({ "artifact_id": " " }))- .await- .expect_err("expected missing-arg error");- assert!(err.to_string().contains("artifact_id"));-}--#[tokio::test]-async fn list_returns_artifacts_envelope() {- // Config::default() points at a workspace dir; listing an empty/missing- // artifacts root yields an empty list, not an error.- let tool = ArtifactListTool::new(test_config());- let result = tool.execute(json!({ "limit": 5 })).await;- // Either a clean empty listing or a benign error if the workspace is- // unwritable in the sandbox — assert it does not panic and, when Ok,- // carries the expected shape.- if let Ok(res) = result {- let body = res.output_for_llm(false);- assert!(body.contains("artifacts"), "body was: {body}");- }-}diff --git a/crates/openhuman-core/src/agent/registry/agents/task_manager_agent/agent.toml b/crates/openhuman-core/src/agent/registry/agents/task_manager_agent/agent.tomlindex 5fb9d69b92..934c276334 100644--- a/crates/openhuman-core/src/agent/registry/agents/task_manager_agent/agent.toml+++ b/crates/openhuman-core/src/agent/registry/agents/task_manager_agent/agent.toml@@ -25,9 +25,9 @@ named = ["task_source_add","task_source_update","task_source_remove",- "artifact_list",- "artifact_get",- "artifact_delete",+ "list_artifacts",+ "read_artifact",+ "delete_artifact","current_time",# Resolve due-date / reminder windows to exact timestamps instead of# hand-computing epoch seconds.diff --git a/crates/openhuman-core/src/agent/registry/agents/task_manager_agent/prompt.md b/crates/openhuman-core/src/agent/registry/agents/task_manager_agent/prompt.mdindex 7c3a4ff384..dbf98dc41e 100644--- a/crates/openhuman-core/src/agent/registry/agents/task_manager_agent/prompt.md+++ b/crates/openhuman-core/src/agent/registry/agents/task_manager_agent/prompt.md@@ -6,7 +6,7 @@ Operate as a stateful specialist:- Always read before you write. Inspect the current source or artifact with the narrowest read tool before changing it.- Prefer partial updates (`task_source_update`) over remove-and-recreate.-- Use destructive tools (`artifact_delete`, `task_source_remove`) only when the user explicitly names what should be removed or confirms your proposed removal.+- Use destructive tools (`delete_artifact`, `task_source_remove`) only when the user explicitly names what should be removed or confirms your proposed removal.- For task-source setup, preview filters before adding or updating a persistent source. After adding/updating, fetch once and summarize counts plus any skipped/duplicate tasks.Return a concise summary with changed ids and final state.diff --git a/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs b/crates/openhuman-core/src/channels/runtime/startup/start_channels.rsindex a9ef945be4..35b1e43350 100644--- a/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs+++ b/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs@@ -44,6 +44,7 @@ async fn start_channels_inner(mut config: Config, session: CancellationToken) ->// ArtifactFailed) as `artifact_ready` / `artifact_failed` web-channel// events so the frontend ArtifactCard can render in chat (#2779).crate::web_chat::register_artifact_surface_subscriber();+ crate::threads::artifact_rows::register_artifact_row_subscriber();// Surface external-egress disclosure events (ExternalTransferPending) as// `external_transfer_pending` web-channel events so the frontend can show a// per-action "what leaves, to where, why" card (privacy epic S2, #4436).diff --git a/crates/openhuman-core/src/core/runtime/bootstrap.rs b/crates/openhuman-core/src/core/runtime/bootstrap.rsindex bd0de7e726..1fd8c80e36 100644--- a/crates/openhuman-core/src/core/runtime/bootstrap.rs+++ b/crates/openhuman-core/src/core/runtime/bootstrap.rs@@ -342,6 +342,7 @@ pub(crate) async fn bootstrap_core_runtime(// (The approval/plan-review surface bridge is registered unconditionally// above — it must run even when this gate-install branch is skipped.)crate::web_chat::register_artifact_surface_subscriber();+ crate::threads::artifact_rows::register_artifact_row_subscriber();} else {log::info!("[runtime] approval gate DISABLED (OPENHUMAN_APPROVAL_GATE=0 honored on host={}) — \@@ -360,6 +361,7 @@ pub(crate) async fn bootstrap_core_runtime(// sets OPENHUMAN_APPROVAL_GATE=0 (CR #3328947323 on PR #3026). Idempotent// (OnceLock-guarded inside register_artifact_surface_subscriber).crate::web_chat::register_artifact_surface_subscriber();+ crate::threads::artifact_rows::register_artifact_row_subscriber();// Memory-activity surface bridges DomainEvent::MemoryStored/Recalled onto// the web channel's `memory_activity` event (C5) — same unconditional// placement rationale as the bridges above. Idempotent (OnceLock-guarded).diff --git a/crates/openhuman-core/src/integrations/file_storage/artifact_publisher.rs b/crates/openhuman-core/src/integrations/file_storage/artifact_publisher.rsnew file mode 100644index 0000000000..926d00a6b2--- /dev/null+++ b/crates/openhuman-core/src/integrations/file_storage/artifact_publisher.rs@@ -0,0 +1,251 @@+//! Sharing artifacts through managed cloud file storage.+//!+//! [`StorageArtifactPublisher`] is OpenHuman's implementation of the+//! `tiny-artifacts` [`ArtifactPublisher`] port: it uploads one version of an+//! artifact through the same backend routes the `storage_*` tools use and+//! returns its link — a private presigned link by default, the stored file's+//! public URL when asked. The crate records the link on that version.+//!+//! What is uploaded is exactly the version asked for: a text version's own+//! content (so any version can be shared), or a file version's file. The+//! same guards as the storage tools apply: nothing is shared under read-only+//! autonomy, and the publisher only exists when the integration client does+//! (a backend is configured and the user is signed in).++use std::path::Path;+use std::sync::Arc;++use async_trait::async_trait;+use serde_json::json;+use tiny_artifacts::{+ ArtifactKind, ArtifactPublisher, ArtifactRecord, ArtifactVersion, PublishOptions, PublishedLink,+};++use super::tools::helpers::{file_path, mime_for_path, FILES_PATH};+use super::types::{LinkResponse, UploadResponse};+use crate::integrations::IntegrationClient;+use crate::security::SecurityPolicy;++/// Lifetime of a private link when the caller does not choose: the backend's+/// maximum, 7 days.+const DEFAULT_LINK_SECONDS: u64 = 604_800;++/// Shares artifact versions through the backend's file storage.+pub struct StorageArtifactPublisher {+ client: Arc<IntegrationClient>,+ security: Arc<SecurityPolicy>,+}++impl StorageArtifactPublisher {+ /// A publisher over `client`, refusing to share when `security` is+ /// read-only.+ pub fn new(client: Arc<IntegrationClient>, security: Arc<SecurityPolicy>) -> Self {+ Self { client, security }+ }+}++/// The publisher for `config`, or `None` when there is no integration client+/// (no backend URL configured, or not signed in) — the same condition under+/// which the `storage_*` tools are absent.+pub fn artifact_publisher(config: &crate::config::Config) -> Option<Arc<dyn ArtifactPublisher>> {+ let client = crate::integrations::build_client(config)?;+ let security = Arc::new(SecurityPolicy::from_config(+ &config.autonomy,+ &config.workspace_dir,+ &config.action_dir,+ ));+ Some(Arc::new(StorageArtifactPublisher::new(client, security)))+}++/// The bytes, file name and media type a version uploads as.+async fn upload_body(+ record: &ArtifactRecord,+ version: &ArtifactVersion,+) -> anyhow::Result<(Vec<u8>, String, &'static str)> {+ if record.holds_file() {+ let path = version+ .file+ .as_ref()+ .map_or(version.body.as_str(), |f| f.path.as_str());+ let path = Path::new(path);+ let bytes = tokio::fs::read(path)+ .await+ .map_err(|e| anyhow::anyhow!("cannot read the artifact's file: {e}"))?;+ let name = path+ .file_name()+ .and_then(|n| n.to_str())+ .unwrap_or("artifact")+ .to_string();+ let mime = mime_for_path(path);+ return Ok((bytes, name, mime));+ }+ let ext = match record.kind {+ ArtifactKind::Markdown => "md",+ ArtifactKind::Html => "html",+ _ => "txt",+ };+ let name = format!("{}.{ext}", file_stem(&record.title));+ let mime = match record.kind {+ ArtifactKind::Markdown => "text/markdown",+ ArtifactKind::Html => "text/html",+ _ => "text/plain",+ };+ Ok((version.body.clone().into_bytes(), name, mime))+}++/// A file-name stem from a title: path separators and control characters+/// dropped, never empty.+fn file_stem(title: &str) -> String {+ let stem: String = title+ .chars()+ .filter(|c| !matches!(c, '/' | '\\' | '\0') && !c.is_control())+ .collect::<String>()+ .trim()+ .trim_matches('.')+ .to_string();+ if stem.is_empty() {+ "artifact".to_string()+ } else {+ stem+ }+}++fn millis(rfc3339: Option<&str>) -> Option<u64> {+ let at = chrono::DateTime::parse_from_rfc3339(rfc3339?).ok()?;+ u64::try_from(at.timestamp_millis()).ok()+}++/// Seconds a private link should last: what was asked (7 days by default,+/// within the backend's 60 s – 7 day range), never past the uploaded file's+/// own expiry — a link may not outlive its file — less a minute of margin.+pub(crate) fn link_seconds(+ requested: Option<u64>,+ file_expires_at_millis: Option<u64>,+ now_millis: u64,+) -> u64 {+ let wanted = requested+ .unwrap_or(DEFAULT_LINK_SECONDS)+ .clamp(60, DEFAULT_LINK_SECONDS);+ match file_expires_at_millis {+ Some(expires) => {+ let left = expires.saturating_sub(now_millis) / 1000;+ wanted.min(left.saturating_sub(60)).max(60)+ }+ None => wanted,+ }+}++impl StorageArtifactPublisher {+ /// A presigned link for `file_id` lasting `seconds`. If the backend+ /// rejects that lifetime, one retry asks for its default lifetime instead.+ async fn private_link(&self, file_id: &str, seconds: u64) -> anyhow::Result<LinkResponse> {+ let route = file_path(file_id, "/link");+ match self+ .client+ .post::<LinkResponse>(&route, &json!({ "expiresInSeconds": seconds }))+ .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>(&route, &json!({}))+ .await+ .map_err(|e| anyhow::anyhow!("link generation failed: {e}"))+ }+ }+ }++ /// Delete an upload nothing points at. Best-effort.+ async fn discard(&self, file_id: &str) {+ if let Err(err) = self+ .client+ .delete::<super::types::DeleteResponse>(&file_path(file_id, ""))+ .await+ {+ tracing::warn!(file_id, err = %err, "[file_storage] could not delete an unshared upload");+ }+ }+}++#[async_trait]+impl ArtifactPublisher for StorageArtifactPublisher {+ async fn publish(+ &self,+ record: &ArtifactRecord,+ version: &ArtifactVersion,+ options: &PublishOptions,+ ) -> anyhow::Result<PublishedLink> {+ if !self.security.can_act() {+ anyhow::bail!("[policy-blocked] Action blocked: autonomy is read-only");+ }+ let (bytes, filename, mime) = upload_body(record, version).await?;+ tracing::debug!(+ artifact_id = %record.id,+ version = version.version,+ bytes = bytes.len(),+ public = options.public,+ "[file_storage] sharing artifact version"+ );+ let part = reqwest::multipart::Part::bytes(bytes)+ .file_name(filename)+ .mime_str(mime)?;+ let visibility = if options.public { "public" } else { "private" };+ let form = reqwest::multipart::Form::new()+ .part("file", part)+ .text("visibility", visibility);+ let uploaded = self+ .client+ .upload_multipart::<UploadResponse>(FILES_PATH, form)+ .await+ .map_err(|e| anyhow::anyhow!("upload failed: {e}"))?;++ let link = if options.public {+ uploaded+ .public_url+ .clone()+ .map(|url| (url, uploaded.expires_at.clone()))+ .ok_or_else(|| anyhow::anyhow!("the stored file has no public URL"))+ } else {+ let seconds = link_seconds(+ options.expires_in_seconds,+ millis(uploaded.expires_at.as_deref()),+ tiny_artifacts::now_millis(),+ );+ self.private_link(&uploaded.file_id, seconds)+ .await+ .map(|link| (link.url, link.expires_at))+ };+ let (url, expires_at) = match link {+ Ok(link) => link,+ Err(err) => {+ // Nothing will point at the upload: free it rather than leave+ // a billed orphan.+ self.discard(&uploaded.file_id).await;+ return Err(err);+ }+ };+ tracing::info!(+ artifact_id = %record.id,+ version = version.version,+ file_id = %uploaded.file_id,+ public = options.public,+ "[file_storage] shared artifact version"+ );+ Ok(PublishedLink {+ url,+ expires_at_millis: millis(expires_at.as_deref()),+ published_at_millis: tiny_artifacts::now_millis(),+ public: options.public,+ })+ }+}++#[cfg(test)]+#[path = "artifact_publisher_tests.rs"]+mod tests;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.rsnew file mode 100644index 0000000000..814d1aa627--- /dev/null+++ b/crates/openhuman-core/src/integrations/file_storage/artifact_publisher_tests.rs@@ -0,0 +1,302 @@+use std::sync::Arc;++use serde_json::json;+use tiny_artifacts::{+ ArtifactKind, ArtifactPublisher, ArtifactRecord, ArtifactVersion, Artifacts, Author, Content,+ FileRef, PublishOptions,+};+use wiremock::matchers::{body_string_contains, method, path};+use wiremock::{Mock, MockServer, ResponseTemplate};++use super::*;+use crate::agent::artifacts::tiny_store::versioned_store;+use crate::security::AutonomyLevel;++fn publisher(server_uri: String, autonomy: AutonomyLevel) -> StorageArtifactPublisher {+ StorageArtifactPublisher::new(+ Arc::new(IntegrationClient::new(server_uri, "tok".to_string())),+ Arc::new(SecurityPolicy {+ autonomy,+ ..SecurityPolicy::default()+ }),+ )+}++fn uploaded(public_url: Option<&str>) -> ResponseTemplate {+ ResponseTemplate::new(200).set_body_json(json!({+ "success": true,+ "data": {+ "fileId": "file-1",+ "filename": "x",+ "size": 4,+ "contentType": "text/markdown",+ "visibility": if public_url.is_some() { "public" } else { "private" },+ "expiresAt": "2030-01-01T00:00:00.000Z",+ "publicUrl": public_url,+ "costUsd": 0.0001+ }+ }))+}++async fn mount_link(server: &MockServer, expect: u64) {+ Mock::given(method("POST"))+ .and(path("/agent-integrations/file-storage/files/file-1/link"))+ .and(body_string_contains("604800"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "success": true,+ "data": {+ "url": "https://s3.example/presigned?sig=abc",+ "expiresAt": "2030-01-08T00:00:00.000Z",+ "costUsd": 0.0001+ }+ })))+ .expect(expect)+ .mount(server)+ .await;+}++#[tokio::test]+async fn a_text_version_uploads_its_own_content_behind_a_private_link() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/agent-integrations/file-storage/files"))+ .and(body_string_contains("# version one"))+ .and(body_string_contains("filename=\"Release Notes.md\""))+ .and(body_string_contains("private"))+ .respond_with(uploaded(None))+ .expect(1)+ .mount(&server)+ .await;+ mount_link(&server, 1).await;++ let mut record = ArtifactRecord::new(+ "a-1",+ "Release Notes",+ ArtifactKind::Markdown,+ "# version one",+ "agent",+ 1,+ );+ record.push_version(ArtifactVersion::new(+ 0,+ "# version two",+ tiny_artifacts::ArtifactAuthor::Agent,+ "agent",+ 2,+ ));+ // Version 1, not the newest: its own text is what goes out.+ let link = publisher(server.uri(), AutonomyLevel::Full)+ .publish(+ &record,+ record.version(1).unwrap(),+ &PublishOptions::default(),+ )+ .await+ .unwrap();+ assert_eq!(link.url, "https://s3.example/presigned?sig=abc");+ assert!(!link.public);+ assert_eq!(link.expires_at_millis, Some(1_894_060_800_000));+}++#[tokio::test]+async fn a_public_file_share_uses_the_public_url_and_makes_no_link() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/agent-integrations/file-storage/files"))+ .and(body_string_contains("PNG-BYTES"))+ .and(body_string_contains("filename=\"chart.png\""))+ .and(body_string_contains("public"))+ .respond_with(uploaded(Some("https://api.example/public/file-1")))+ .expect(1)+ .mount(&server)+ .await;+ mount_link(&server, 0).await;++ let dir = tempfile::tempdir().unwrap();+ let file = dir.path().join("chart.png");+ std::fs::write(&file, b"PNG-BYTES").unwrap();+ let mut version = ArtifactVersion::new(+ 1,+ file.display().to_string(),+ tiny_artifacts::ArtifactAuthor::Agent,+ "agent",+ 1,+ );+ version.file = Some(FileRef {+ path: file.display().to_string(),+ size_bytes: 9,+ media_type: Some("image/png".into()),+ });+ let mut record = ArtifactRecord::pending("img-1", "Chart", ArtifactKind::Image, 1);+ record.versions.push(version.clone());++ let options = PublishOptions {+ public: true,+ ..PublishOptions::default()+ };+ let link = publisher(server.uri(), AutonomyLevel::Full)+ .publish(&record, &version, &options)+ .await+ .unwrap();+ assert_eq!(link.url, "https://api.example/public/file-1");+ assert!(link.public);+}++#[tokio::test]+async fn read_only_autonomy_blocks_sharing_before_any_network_call() {+ let record = ArtifactRecord::new("a-1", "T", ArtifactKind::Text, "x", "agent", 1);+ // An unreachable backend: a network attempt would fail differently.+ let err = publisher("http://127.0.0.1:9".into(), AutonomyLevel::ReadOnly)+ .publish(+ &record,+ record.latest().unwrap(),+ &PublishOptions::default(),+ )+ .await+ .unwrap_err();+ assert!(err.to_string().contains("[policy-blocked]"), "{err}");+}++#[tokio::test]+async fn sharing_through_the_service_records_and_reuses_the_link() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/agent-integrations/file-storage/files"))+ .respond_with(uploaded(None))+ .expect(1)+ .mount(&server)+ .await;+ mount_link(&server, 1).await;++ let workspace = tempfile::tempdir().unwrap();+ let artifacts = Artifacts::new(Arc::new(versioned_store(workspace.path())))+ .with_publisher(Arc::new(publisher(server.uri(), AutonomyLevel::Full)));+ let id = artifacts+ .create(+ ArtifactKind::Markdown,+ "Notes",+ Content::Text("# hi".into()),+ &Author::agent("agent"),+ None,+ )+ .await+ .unwrap()+ .record+ .id;++ let first = artifacts+ .publish(&id, None, &PublishOptions::default())+ .await+ .unwrap();+ assert!(!first.reused);+ let stored = artifacts.get(&id).await.unwrap().unwrap();+ assert_eq!(+ stored.latest().unwrap().published.as_ref(),+ Some(&first.link)+ );++ // The link is live (expires 2030): no second upload.+ let again = artifacts+ .publish(&id, None, &PublishOptions::default())+ .await+ .unwrap();+ assert!(again.reused);+ assert_eq!(again.link.url, first.link.url);+}++#[test]+fn a_link_never_outlives_its_file() {+ let now = 1_000_000_000_000;+ let day = 86_400;+ // The free plan's file lives exactly 7 days from upload: a 7-day link+ // would end a moment after it, so it is cut to the file's life less a+ // minute.+ let file_expires = Some(now + 7 * day * 1000);+ assert_eq!(link_seconds(None, file_expires, now), 7 * day - 60);+ // A shorter request stands.+ assert_eq!(link_seconds(Some(3600), file_expires, now), 3600);+ // Requests are held to the backend's 60 s – 7 day range.+ assert_eq!(link_seconds(Some(10), None, now), 60);+ assert_eq!(link_seconds(Some(30 * day), None, now), 7 * day);+ // A file about to expire still gets the shortest valid link.+ assert_eq!(link_seconds(None, Some(now + 30_000), now), 60);+}++#[tokio::test]+async fn a_refused_lifetime_falls_back_to_the_backend_default() {+ 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"))+ .and(body_string_contains("expiresInSeconds"))+ .respond_with(+ ResponseTemplate::new(400)+ .set_body_json(json!({ "success": false, "error": "Validation failed" })),+ )+ .expect(1)+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path("/agent-integrations/file-storage/files/file-1/link"))+ .and(wiremock::matchers::body_json(json!({})))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "success": true,+ "data": { "url": "https://s3.example/default", "expiresAt": "2030-01-01T01:00:00.000Z", "costUsd": 0.0 }+ })))+ .expect(1)+ .mount(&server)+ .await;++ let record = ArtifactRecord::new("a-1", "T", ArtifactKind::Text, "x", "agent", 1);+ let link = publisher(server.uri(), AutonomyLevel::Full)+ .publish(+ &record,+ record.latest().unwrap(),+ &PublishOptions::default(),+ )+ .await+ .unwrap();+ assert_eq!(link.url, "https://s3.example/default");+}++#[tokio::test]+async fn an_upload_that_cannot_be_linked_is_deleted() {+ 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(400)+ .set_body_json(json!({ "success": false, "error": "Validation failed" })),+ )+ .expect(2)+ .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/integrations/file_storage/mod.rs b/crates/openhuman-core/src/integrations/file_storage/mod.rsindex 0b5f2f2f00..a145f9bf87 100644--- a/crates/openhuman-core/src/integrations/file_storage/mod.rs+++ b/crates/openhuman-core/src/integrations/file_storage/mod.rs@@ -8,9 +8,12 @@//! download into the agent's action dir and expose list / link / visibility ///! delete operations.+pub mod artifact_publisher;pub mod tools;pub mod types;+pub use artifact_publisher::{artifact_publisher, StorageArtifactPublisher};+pub use tools::{build_file_storage_tools, StorageDeleteFileTool, StorageDownloadFileTool, StorageGetLinkTool,StorageListFilesTool, StorageSetVisibilityTool, StorageUploadFileTool,diff --git a/crates/openhuman-core/src/integrations/file_storage/tools/helpers.rs b/crates/openhuman-core/src/integrations/file_storage/tools/helpers.rsindex 82556bf092..01c5ccead7 100644--- a/crates/openhuman-core/src/integrations/file_storage/tools/helpers.rs+++ b/crates/openhuman-core/src/integrations/file_storage/tools/helpers.rs@@ -8,7 +8,7 @@ use tinytools::ToolRunContext;use crate::security::SecurityPolicy;use tinytools::ToolResult;-pub(super) const FILES_PATH: &str = "/agent-integrations/file-storage/files";+pub(crate) const FILES_PATH: &str = "/agent-integrations/file-storage/files";/// Subdirectory (under `action_dir`) where downloaded files are stored./// Mirrors `media_generation`'s `generated-media/` root — the action dir is@@ -145,7 +145,7 @@ pub(super) fn extension_for_content_type(content_type: Option<&str>) -> &'static/// Guess a mime type from a filename extension for the multipart upload/// part. Best-effort — the backend stores whatever we send and S3 doesn't/// care; unknown extensions fall back to `application/octet-stream`.-pub(super) fn mime_for_path(path: &Path) -> &'static str {+pub(crate) fn mime_for_path(path: &Path) -> &'static str {match path.extension().and_then(|e| e.to_str())@@ -187,7 +187,7 @@ pub(super) fn action_dir_for_context(default_action_dir.to_path_buf()}-pub(super) fn file_path(file_id: &str, suffix: &str) -> String {+pub(crate) fn file_path(file_id: &str, suffix: &str) -> String {format!("{FILES_PATH}/{file_id}{suffix}")}diff --git a/crates/openhuman-core/src/integrations/file_storage/tools/mod.rs b/crates/openhuman-core/src/integrations/file_storage/tools/mod.rsindex 2dc77d2642..20364d11cc 100644--- a/crates/openhuman-core/src/integrations/file_storage/tools/mod.rs+++ b/crates/openhuman-core/src/integrations/file_storage/tools/mod.rs@@ -20,7 +20,7 @@ mod tools_tests;mod delete;mod download;-mod helpers;+pub(crate) mod helpers;mod link;mod list;mod registry;diff --git a/crates/openhuman-core/src/media/generation/artifact_tool.rs b/crates/openhuman-core/src/media/generation/artifact_tool.rsindex 6a1dc8b285..21d41b60c8 100644--- a/crates/openhuman-core/src/media/generation/artifact_tool.rs+++ b/crates/openhuman-core/src/media/generation/artifact_tool.rs@@ -1,9 +1,8 @@//! [`MediaArtifactTool`] — wraps a media-generation [`Tool`] (TinyAgents'//! `GenerateImageTool` / `GenerateVideoTool`, boxed in `super::tools`) so-//! every file the inner tool saves is also tracked as an OpenHuman artifact,-//! following the pattern `tools/impl/document/mod.rs` and-//! `tools/impl/presentation/mod.rs` use for their own producers-//! (`create_artifact` → write bytes → `finalize_artifact`/`fail_artifact`).+//! every file the inner tool saves is also filed as a versioned OpenHuman+//! artifact, through the same [`Production`] flow the document and+//! presentation producers use.//!//! The inner tool already writes bytes under//! `<action_dir>/generated-media/...` (see [`super::tools::media_tools_from`])@@ -11,10 +10,9 @@//! (`{"type": "image"|"video", "path", "media_type"|"format", "bytes"}`, see//! `tinyagents_harness::media::{GenerateImageTool, GenerateVideoTool}`). This//! wrapper runs the inner tool unchanged, then for every reported file:-//! reserves an artifact via `create_artifact_for_call` (recording the-//! provider-assigned tool-call id so `ArtifactPending`/`Ready`/`Failed`-//! correlate with the tool-call bubble, #C5), moves the file into the-//! artifact's reserved path, and finalizes it — or fails just that one+//! starts a [`Production`] (recording the provider-assigned tool-call id so the+//! card correlates with the tool-call bubble, #C5), moves the file into the+//! artifact's reserved path, and completes it — or fails just that one//! artifact and annotates its entry with `artifact_error`, without//! disturbing the others (`n > 1` generations are common for images). On//! success each entry gains an `artifact_id` field so the model (and the@@ -22,7 +20,7 @@//! tool's JSON/markdown result shape is preserved byte-for-byte.//!//! A run with no context (`execute`/`execute_with_options`, e.g. CLI/tests)-//! still creates artifacts — `create_artifact_for_call` simply records no+//! still creates artifacts — the production simply records no//! `tool_call_id` and the chat-context bridge in `agent/artifacts/store.rs`//! degrades to `thread_id = None` as it already does for every other//! producer.@@ -36,11 +34,8 @@ use tinytools::{ToolRunContext, ToolScope, ToolTimeout,};-use crate::agent::artifacts::{- create_artifact_for_call, fail_artifact, finalize_artifact, ArtifactKind,-};-use crate::agent::artifacts::tiny_store::FsArtifactStore;-use tiny_artifacts::{ArtifactRecord, ArtifactStore};+use crate::agent::artifacts::production::Production;+use crate::agent::artifacts::ArtifactKind;use crate::tools::host_extensions::tool_call_id;/// Maximum characters of the prompt kept in a generated artifact's title.@@ -142,78 +137,55 @@ impl<T: Tool> MediaArtifactTool<T> {.unwrap_or("bin").to_string();let title = Self::artifact_title(args, index, total);- let (meta, dest) = match create_artifact_for_call(+ let kind = match self.kind {+ ArtifactKind::Image => tiny_artifacts::ArtifactKind::Image,+ _ => tiny_artifacts::ArtifactKind::File,+ };+ // Reserve the file in the files folder (the card shows+ // "generating…", tied to this tool call's bubble) and open the+ // versioned artifact under the same id.+ let production = match Production::start(&self.workspace_dir,- &self.files_dir,- self.kind.clone(),+ self.files_dir.clone(),+ kind,&title,&ext,call_id,+ None,).await{- Ok(pair) => pair,+ Ok(production) => production,Err(err) => {tracing::warn!(target: "media_generation",err = %err,- "[media_generation] create_artifact failed; generated file left unfiled"+ "[media_generation] could not open the artifact; generated file left unfiled");set_artifact_error(entry, &err);return;}};- match move_or_copy(src, &dest).await {- Ok(size_bytes) => {- match finalize_artifact(&self.workspace_dir, &meta.id, size_bytes).await {- Ok(updated) => {- if let Some(obj) = entry.as_object_mut() {- obj.insert("artifact_id".into(), json!(updated.id));- }- // Phase 2d: mirror into the versioned artifact store- // (tiny-artifacts crate). Each generated file becomes- // a fresh versioned record – the shared model stores- // a workspace-path reference, not bytes. Best-effort:- // a failure here must not fail the filed artifact.- let versioned = FsArtifactStore::new(&self.workspace_dir, self.files_dir.clone());- let kind = match self.kind {- ArtifactKind::Image => tiny_artifacts::ArtifactKind::Image,- _ => tiny_artifacts::ArtifactKind::File,- };- let record = ArtifactRecord::new(- &updated.id,- &title,- kind,- dest.display().to_string(),- "agent",- tiny_artifacts::now_millis(),- );- if let Err(err) = versioned.upsert(&record).await {- tracing::warn!(- target: "media_generation",- err = %err,- artifact_id = %updated.id,- "[media_generation] failed to mirror artifact into versioned store"- );- }- }- Err(err) => {- let _ = fail_artifact(&self.workspace_dir, &self.files_dir, &meta.id, &err)- .await;- set_artifact_error(entry, &err);- }+ if let Err(err) = move_or_copy(src, production.path()).await {+ production.fail(&err).await;+ tracing::warn!(+ target: "media_generation",+ err = %err,+ artifact_id = %production.id(),+ "[media_generation] failed to file generated media as an artifact"+ );+ set_artifact_error(entry, &err);+ return;+ }+ // The moved file becomes the artifact's first version; the card turns+ // ready from that record.+ match production.complete().await {+ Ok(_) => {+ if let Some(obj) = entry.as_object_mut() {+ obj.insert("artifact_id".into(), json!(production.id()));}}- Err(err) => {- let _ = fail_artifact(&self.workspace_dir, &self.files_dir, &meta.id, &err).await;- tracing::warn!(- target: "media_generation",- err = %err,- artifact_id = %meta.id,- "[media_generation] failed to file generated media as an artifact"- );- set_artifact_error(entry, &err);- }+ Err(err) => set_artifact_error(entry, &err),}}}diff --git a/crates/openhuman-core/src/threads/artifact_rows.rs b/crates/openhuman-core/src/threads/artifact_rows.rsnew file mode 100644index 0000000000..884274d356--- /dev/null+++ b/crates/openhuman-core/src/threads/artifact_rows.rs@@ -0,0 +1,255 @@+//! Artifact rows in a thread's message log.+//!+//! When an artifact becomes ready in a chat, a row is appended to the thread's+//! message log recording which turn made it: `type: "artifact"` with+//! `extraMetadata: { artifactId, requestId }`. The UI reads the row to render+//! the artifact's card inside that turn's reply, so a card stays with its+//! message across refreshes, cleared client storage and other devices. The row+//! is the only record of that placement; the UI's own artifact state is a+//! cache.+//!+//! The rows are for the UI only. Every core reader of the message log goes+//! through [`crate::threads::store::get_messages`] or its blocking twin, which+//! drop them, so they never reach a model (title generation, memory backfill,+//! voice context, channel adapters, edit/regenerate). Only the UI's+//! `threads.messages_list` reads the log with them.+//!+//! Artifacts made before these rows existed get one on demand+//! ([`backfill_artifact_rows`]): the turn is the first agent reply saved at or+//! after the artifact, since a turn makes its artifacts before its reply is+//! saved.++use std::path::{Path, PathBuf};+use std::sync::{Arc, OnceLock};++use async_trait::async_trait;+use chrono::{DateTime, Utc};+use serde_json::json;+use tinybus::{EventHandler, SubscriptionHandle};++use crate::agent::artifacts::types::{ArtifactMeta, ArtifactStatus};+use crate::core::events::DomainEvent;+use crate::threads::store::{self as conversations, ConversationMessage};++/// `type` of an artifact row.+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;++/// 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}")+}++/// Whether `message` is an artifact row.+pub fn is_artifact_row(message: &ConversationMessage) -> bool {+ message.message_type == ARTIFACT_MESSAGE_TYPE+}++/// `messages` without artifact rows: what every non-UI reader sees.+pub fn without_artifact_rows(messages: Vec<ConversationMessage>) -> Vec<ConversationMessage> {+ messages+ .into_iter()+ .filter(|message| !is_artifact_row(message))+ .collect()+}++fn artifact_row(+ artifact_id: &str,+ title: &str,+ request_id: Option<&str>,+ created_at: String,+) -> ConversationMessage {+ let mut extra_metadata = json!({ "artifactId": artifact_id });+ if let Some(request_id) = request_id {+ extra_metadata["requestId"] = json!(request_id);+ }+ ConversationMessage {+ id: artifact_row_id(artifact_id),+ content: title.to_string(),+ message_type: ARTIFACT_MESSAGE_TYPE.to_string(),+ extra_metadata,+ sender: "agent".to_string(),+ created_at,+ }+}++/// Append the row for `artifact_id` unless the thread already has it. Returns+/// whether a row was written.+pub async fn record_artifact_row(+ workspace_dir: PathBuf,+ thread_id: &str,+ artifact_id: &str,+ title: &str,+ request_id: Option<&str>,+) -> Result<bool, String> {+ let messages =+ conversations::blocking::get_messages_with_artifact_rows(workspace_dir.clone(), thread_id)+ .await?;+ let row_id = artifact_row_id(artifact_id);+ if messages.iter().any(|message| message.id == row_id) {+ return Ok(false);+ }+ let row = artifact_row(artifact_id, title, request_id, Utc::now().to_rfc3339());+ conversations::blocking::append_message(workspace_dir, thread_id.to_string(), row).await?;+ log::debug!(+ "{LOG_PREFIX} recorded artifact_id={artifact_id} thread_id={thread_id} request_id={request_id:?}"+ );+ Ok(true)+}++fn parse_time(raw: &str) -> Option<DateTime<Utc>> {+ DateTime::parse_from_rfc3339(raw)+ .ok()+ .map(|time| time.with_timezone(&Utc))+}++/// The turn that made an artifact created at `created_at`: the first agent+/// reply saved at or after it. `None` when the artifact is newer than every+/// reply (its turn has not saved one).+fn owning_request_id(+ messages: &[ConversationMessage],+ created_at: DateTime<Utc>,+) -> Option<String> {+ messages+ .iter()+ .filter(|message| message.sender == "agent" && !is_artifact_row(message))+ .filter_map(|message| {+ let request_id = message.extra_metadata.get("requestId")?.as_str()?;+ Some((parse_time(&message.created_at)?, request_id))+ })+ .filter(|(saved_at, _)| *saved_at >= created_at)+ .min_by_key(|(saved_at, _)| *saved_at)+ .map(|(_, request_id)| request_id.to_string())+}++/// Rows for `artifacts` the thread has none for, in creation order. Only ready+/// artifacts without a tool call get one: a tool call's artifact renders with+/// its tool call.+pub(crate) fn missing_rows(+ messages: &[ConversationMessage],+ artifacts: &[ArtifactMeta],+) -> Vec<ConversationMessage> {+ let mut missing: Vec<&ArtifactMeta> = artifacts+ .iter()+ .filter(|artifact| artifact.status == ArtifactStatus::Ready)+ .filter(|artifact| artifact.tool_call_id.is_none())+ .filter(|artifact| {+ let row_id = artifact_row_id(&artifact.id);+ !messages.iter().any(|message| message.id == row_id)+ })+ .collect();+ missing.sort_by_key(|artifact| artifact.created_at);+ missing+ .into_iter()+ .map(|artifact| {+ let request_id = owning_request_id(messages, artifact.created_at);+ artifact_row(+ &artifact.id,+ &artifact.title,+ request_id.as_deref(),+ artifact.created_at.to_rfc3339(),+ )+ })+ .collect()+}++/// Write rows for the thread's artifacts that have none (made before these+/// rows existed, or whose row write failed), given the thread's full message+/// log. Returns the rows written.+pub async fn backfill_artifact_rows(+ workspace_dir: &Path,+ 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 written = Vec::new();+ for row in missing_rows(messages, &artifacts) {+ let stored = conversations::blocking::append_message(+ workspace_dir.to_path_buf(),+ thread_id.to_string(),+ row,+ )+ .await?;+ written.push(stored);+ }+ if !written.is_empty() {+ log::info!(+ "{LOG_PREFIX} backfilled {} artifact row(s) thread_id={thread_id}",+ written.len()+ );+ }+ Ok(written)+}++/// Writes an artifact's row when it becomes ready in a chat.+struct ArtifactRowSubscriber;++#[async_trait]+impl EventHandler<DomainEvent> for ArtifactRowSubscriber {+ fn name(&self) -> &str {+ "threads::artifact_rows"+ }++ fn domains(&self) -> Option<&[&str]> {+ Some(&["artifact"])+ }++ async fn handle(&self, event: &DomainEvent) {+ let DomainEvent::ArtifactReady {+ artifact_id,+ title,+ workspace_dir,+ thread_id: Some(thread_id),+ tool_call_id: None,+ request_id,+ ..+ } = event+ else {+ return;+ };+ if let Err(error) = record_artifact_row(+ PathBuf::from(workspace_dir),+ thread_id,+ artifact_id,+ title,+ request_id.as_deref(),+ )+ .await+ {+ log::warn!(+ "{LOG_PREFIX} row write failed artifact_id={artifact_id} thread_id={thread_id}: {error}"+ );+ }+ }+}++static ARTIFACT_ROW_HANDLE: OnceLock<SubscriptionHandle> = OnceLock::new();++/// Register the subscriber that writes artifact rows. Idempotent.+pub fn register_artifact_row_subscriber() {+ if ARTIFACT_ROW_HANDLE.get().is_some() {+ return;+ }+ match crate::core::bus::BUS.subscribe(Arc::new(ArtifactRowSubscriber)) {+ Some(handle) => {+ let _ = ARTIFACT_ROW_HANDLE.set(handle);+ log::info!("{LOG_PREFIX} subscriber registered (domain=artifact)");+ }+ None => log::warn!("{LOG_PREFIX} failed to register subscriber — bus not initialized"),+ }+}++#[cfg(test)]+#[path = "artifact_rows_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/threads/artifact_rows_tests.rs b/crates/openhuman-core/src/threads/artifact_rows_tests.rsnew file mode 100644index 0000000000..383845070e--- /dev/null+++ b/crates/openhuman-core/src/threads/artifact_rows_tests.rs@@ -0,0 +1,162 @@+use std::path::{Path, PathBuf};++use chrono::{DateTime, TimeZone, Utc};+use serde_json::json;++use super::*;+use crate::agent::artifacts::types::{ArtifactKind, ArtifactMeta, ArtifactStatus};+use crate::threads::store::{self as conversations, CreateConversationThread};++fn temp_ws() -> PathBuf {+ let dir = std::env::temp_dir().join(format!("artifact-rows-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&dir).unwrap();+ dir+}++fn seed_thread(ws: &Path, thread_id: &str) {+ conversations::ensure_thread(+ ws.to_path_buf(),+ CreateConversationThread {+ id: thread_id.to_string(),+ title: "Chat".to_string(),+ created_at: Utc::now().to_rfc3339(),+ parent_thread_id: None,+ labels: None,+ personality_id: None,+ working_dir: None,+ },+ )+ .expect("thread created");+}++fn at(secs: i64) -> DateTime<Utc> {+ Utc.timestamp_opt(1_800_000_000 + secs, 0).unwrap()+}++fn reply(request_id: &str, secs: i64) -> ConversationMessage {+ ConversationMessage {+ id: format!("agent:{request_id}"),+ content: "Done.".to_string(),+ message_type: "text".to_string(),+ extra_metadata: json!({ "scope": "web_chat_reply", "requestId": request_id }),+ sender: "agent".to_string(),+ created_at: at(secs).to_rfc3339(),+ }+}++fn artifact(id: &str, secs: i64) -> ArtifactMeta {+ ArtifactMeta {+ id: id.to_string(),+ kind: ArtifactKind::Document,+ title: format!("Title {id}"),+ path: format!("{id}.md"),+ file: None,+ file_root: None,+ size_bytes: 12,+ status: ArtifactStatus::Ready,+ created_at: at(secs),+ error: None,+ thread_id: Some("t-1".to_string()),+ tool_call_id: None,+ }+}++fn row_request_id(row: &ConversationMessage) -> Option<&str> {+ row.extra_metadata.get("requestId").and_then(|v| v.as_str())+}++#[test]+fn backfilled_rows_take_the_turn_of_the_first_reply_after_the_artifact() {+ let messages = vec![reply("req-1", 10), reply("req-2", 20)];+ let rows = missing_rows(&messages, &[artifact("b", 15), artifact("a", 5)]);++ // Creation order, each with its own turn.+ let ids: Vec<&str> = rows.iter().map(|row| row.id.as_str()).collect();+ assert_eq!(ids, ["artifact:a", "artifact:b"]);+ assert_eq!(row_request_id(&rows[0]), Some("req-1"));+ assert_eq!(row_request_id(&rows[1]), Some("req-2"));+ assert!(rows.iter().all(is_artifact_row));+}++#[test]+fn an_artifact_newer_than_every_reply_gets_a_row_without_a_turn() {+ let rows = missing_rows(&[reply("req-1", 10)], &[artifact("a", 30)]);+ assert_eq!(rows.len(), 1);+ assert_eq!(row_request_id(&rows[0]), None);+}++#[test]+fn no_row_for_existing_rows_tool_calls_or_unfinished_artifacts() {+ let existing = artifact_row("a", "A", Some("req-1"), at(5).to_rfc3339());+ let mut tool = artifact("tool", 5);+ tool.tool_call_id = Some("call-1".to_string());+ let mut pending = artifact("pending", 5);+ pending.status = ArtifactStatus::Pending;++ let rows = missing_rows(+ &[reply("req-1", 10), existing],+ &[artifact("a", 5), tool, pending],+ );+ assert!(rows.is_empty(), "unexpected rows: {rows:?}");+}++#[test]+fn readers_never_see_artifact_rows_but_the_ui_list_does() {+ let ws = temp_ws();+ seed_thread(&ws, "t-1");+ conversations::append_message(ws.clone(), "t-1", reply("req-1", 10)).unwrap();+ conversations::append_message(+ ws.clone(),+ "t-1",+ artifact_row("a", "A", Some("req-1"), at(5).to_rfc3339()),+ )+ .unwrap();++ let model_facing = conversations::get_messages(ws.clone(), "t-1").unwrap();+ assert_eq!(model_facing.len(), 1);+ assert!(!model_facing.iter().any(is_artifact_row));++ let runtime = tokio::runtime::Runtime::new().unwrap();+ let blocking = runtime+ .block_on(conversations::blocking::get_messages(+ ws.clone(),+ "t-1".to_string(),+ ))+ .unwrap();+ assert!(!blocking.iter().any(is_artifact_row));+ let ui = runtime+ .block_on(conversations::blocking::get_messages_with_artifact_rows(+ ws, "t-1",+ ))+ .unwrap();+ assert_eq!(ui.iter().filter(|m| is_artifact_row(m)).count(), 1);+}++#[tokio::test]+async fn recording_an_artifact_twice_writes_one_row() {+ let ws = temp_ws();+ seed_thread(&ws, "t-1");++ assert!(+ record_artifact_row(ws.clone(), "t-1", "a", "A", Some("req-1"))+ .await+ .unwrap()+ );+ // A new version, a retry or a re-delivered ready event.+ assert!(+ !record_artifact_row(ws.clone(), "t-1", "a", "A v2", Some("req-2"))+ .await+ .unwrap()+ );++ let rows: Vec<_> = conversations::blocking::get_messages_with_artifact_rows(ws, "t-1")+ .await+ .unwrap()+ .into_iter()+ .filter(is_artifact_row)+ .collect();+ assert_eq!(rows.len(), 1);+ assert_eq!(rows[0].id, "artifact:a");+ assert_eq!(row_request_id(&rows[0]), Some("req-1"));+ assert_eq!(rows[0].extra_metadata["artifactId"], "a");+}diff --git a/crates/openhuman-core/src/threads/mod.rs b/crates/openhuman-core/src/threads/mod.rsindex 34b62dd929..bbaacaab77 100644--- a/crates/openhuman-core/src/threads/mod.rs+++ b/crates/openhuman-core/src/threads/mod.rs@@ -4,6 +4,7 @@//! CRUD. Storage is [`store`] (JSONL files over `tinyagents_session::threads`);//! this module owns the RPC surface and controller registry.+pub mod artifact_rows;pub mod error;pub mod ops;pub mod rpc_models;diff --git a/crates/openhuman-core/src/threads/ops/crud.rs b/crates/openhuman-core/src/threads/ops/crud.rsindex dcff852b28..d1a9e099af 100644--- a/crates/openhuman-core/src/threads/ops/crud.rs+++ b/crates/openhuman-core/src/threads/ops/crud.rs@@ -102,13 +102,28 @@ pub async fn thread_create_new())}-/// Lists messages for a conversation thread.+/// Lists messages for a conversation thread, artifact rows included: the UI+/// renders each artifact's card from its row (see+/// [`crate::threads::artifact_rows`]). Artifacts that have no row yet get one+/// first, so a thread's older artifacts are placed too.pub async fn messages_list(request: ConversationMessagesRequest,) -> Result<Outcome<ApiEnvelope<ConversationMessagesResponse>>, String> {let dir = workspace_dir().await?;- let messages = conversations::blocking::get_messages(dir, request.thread_id.clone())- .await?+ let mut messages =+ conversations::blocking::get_messages_with_artifact_rows(dir.clone(), &request.thread_id)+ .await?;+ match crate::threads::artifact_rows::backfill_artifact_rows(&dir, &request.thread_id, &messages)+ .await+ {+ Ok(written) => messages.extend(written),+ // The list still serves; the rows are retried on the next read.+ Err(error) => log::warn!(+ "[threads] artifact row backfill failed thread_id={}: {error}",+ request.thread_id+ ),+ }+ let messages = messages.into_iter().map(message_to_record).collect::<Vec<_>>();diff --git a/crates/openhuman-core/src/threads/store/blocking.rs b/crates/openhuman-core/src/threads/store/blocking.rsindex f1a798694c..27ee528413 100644--- a/crates/openhuman-core/src/threads/store/blocking.rs+++ b/crates/openhuman-core/src/threads/store/blocking.rs@@ -100,13 +100,28 @@ pub async fn list_threads(workspace_dir: PathBuf) -> Result<Vec<ConversationThrerun("list_threads", move || store::list_threads(workspace_dir)).await}-/// [`store::get_messages`] on the blocking pool.+/// [`super::get_messages`] on the blocking pool: the thread's messages without+/// artifact rows (see [`crate::threads::artifact_rows`]).pub async fn get_messages(workspace_dir: PathBuf,thread_id: String,) -> Result<Vec<ConversationMessage>, String> {run("get_messages", move || {- store::get_messages(workspace_dir, &thread_id)+ super::get_messages(workspace_dir, &thread_id)+ })+ .await+}++/// [`store::get_messages`] on the blocking pool, artifact rows included. Only+/// for the UI's message list and the artifact-row writers.+pub async fn get_messages_with_artifact_rows(+ workspace_dir: PathBuf,+ thread_id: &str,+) -> Result<Vec<ConversationMessage>, String> {+ let thread_id = thread_id.to_string();+ // The vendored store directly: `store::get_messages` is the filtered one.+ run("get_messages_with_artifact_rows", move || {+ tinyagents_session::threads::get_messages(workspace_dir, &thread_id)}).await}diff --git a/crates/openhuman-core/src/threads/store/mod.rs b/crates/openhuman-core/src/threads/store/mod.rsindex 1f11bf9cc0..18e50607e0 100644--- a/crates/openhuman-core/src/threads/store/mod.rs+++ b/crates/openhuman-core/src/threads/store/mod.rs@@ -36,10 +36,22 @@ use tinyagents_session::threads as store;pub(crate) use bus::claim_channel_turn;pub use bus::register_conversation_persistence_subscriber;pub use store::{- append_message, delete_messages_from, delete_thread, ensure_thread, get_messages,+ append_message, delete_messages_from, delete_thread, ensure_thread,is_deterministic_message_id, list_threads, purge_threads, reply_run_id, run_reply_message_id,update_message, update_thread_labels, update_thread_title, update_thread_working_dir,ConversationPurgeStats, ConversationStore, ConversationThread, CreateConversationThread,CrossThreadHit, ThreadMessage as ConversationMessage,ThreadMessagePatch as ConversationMessagePatch,};++/// A thread's messages without artifact rows. Artifact rows place artifact+/// cards in the UI and must never reach a model, so this is what every core+/// reader uses; only the UI's message list reads them+/// ([`blocking::get_messages_with_artifact_rows`]).+pub fn get_messages(+ workspace_dir: std::path::PathBuf,+ thread_id: &str,+) -> Result<Vec<ConversationMessage>, String> {+ store::get_messages(workspace_dir, thread_id)+ .map(crate::threads::artifact_rows::without_artifact_rows)+}diff --git a/crates/openhuman-core/src/tools/impl/document/mod.rs b/crates/openhuman-core/src/tools/impl/document/mod.rsindex 595d528aef..d2a674dcfc 100644--- a/crates/openhuman-core/src/tools/impl/document/mod.rs+++ b/crates/openhuman-core/src/tools/impl/document/mod.rs@@ -5,22 +5,22 @@//! producers stay parallel)://! 1. Validate the JSON-Schema input early (`types::validate_input`) so//! the agent gets a structured `InvalidInput` it can self-correct on.-//! 2. Allocate an artifact dir via `artifacts::create_artifact` (kind =-//! [`ArtifactKind::Document`], extension `"docx"`). The returned-//! `meta` starts at `ArtifactStatus::Pending` so an interrupted run-//! never surfaces as Ready.+//! 2. Start a [`Production`]: it reserves `<title>.docx` in the files folder+//! (the card shows "generating…") and opens the versioned artifact — or,+//! with an `artifact_id` arg, a new version of that artifact under the same+//! id and file.//! 3. Persist the verbatim args via `save_artifact_args` for regeneration//! parity (the failed-card Retry path, #3162).//! 4. Generate the `.docx` bytes via [`engine::generate`] — pure Rust,//! `docx-rs`-backed, no subprocess. Wrapped in `spawn_blocking` +//! `tokio::time::timeout`.-//! 5. Write the bytes, stat for size, flip the artifact to `Ready` via-//! `finalize_artifact`, return the artifact id + path.-//! 6. On any failure: flip the artifact to `Failed` via `fail_artifact`-//! so the UI surfaces the reason instead of an indefinite spinner.+//! 5. Write the bytes and [`Production::complete`]: the file becomes the+//! artifact's newest version and the card turns ready.+//! 6. On any failure: [`Production::fail`] so the UI surfaces the reason+//! instead of an indefinite spinner.//!-//! Added in GH #4847 (Problem 3: `.docx` export). The-//! [`ArtifactKind::Document`] enum variant already existed but had no+//! Added in GH #4847 (Problem 3: `.docx` export). The legacy+//! `ArtifactKind::Document` enum variant already existed but had no//! producer; the byte-agnostic artifact pipeline (Save-As dialog +//! Downloads copy) and the frontend `document → docx` extension map need//! no format-specific changes.@@ -32,11 +32,9 @@ use std::time::Duration;use async_trait::async_trait;use serde_json::{json, Value};-use crate::agent::artifacts::{create_artifact, fail_artifact, finalize_artifact, ArtifactKind};-use crate::agent::artifacts::tiny_store::FsArtifactStore;+use crate::agent::artifacts::production::Production;use crate::security::SecurityPolicy;use tinytools::{PermissionLevel, Tool, ToolResult};-use tiny_artifacts::{ArtifactAuthor, ArtifactRecord, ArtifactStore, ArtifactVersion};mod engine;/// The document wire contract, shared with the `tinydocs` module.@@ -236,28 +234,36 @@ impl Tool for DocumentTool {"[document] generation request accepted");- let (meta, output_path) = create_artifact(+ // Reserve the file and open the artifact: a new one, or a new version+ // of `artifact_id` (same id, same file, history kept).+ let production = Production::start(&self.workspace_dir,- &self.files_dir,- ArtifactKind::Document,+ self.files_dir.clone(),+ tiny_artifacts::ArtifactKind::File,&input.title,"docx",+ None,+ artifact_id.as_deref(),).await.map_err(anyhow::Error::msg)?;+ let output_path = production.path().to_path_buf();// Persist the verbatim args next to meta.json so a failed card's// Retry can re-dispatch this exact spec (#3162). Best-effort: a// write failure only forfeits regeneration, never aborts an// otherwise-successful generation.- if let Err(err) =- crate::agent::artifacts::store::save_artifact_args(&self.workspace_dir, &meta.id, &args)- .await+ if let Err(err) = crate::agent::artifacts::store::save_artifact_args(+ &self.workspace_dir,+ production.id(),+ &args,+ )+ .await{tracing::warn!(target: "document",err = %err,- artifact_id = %meta.id,+ artifact_id = %production.id(),"[document] failed to persist args.json; artifact will not be regenerable");}@@ -265,13 +271,7 @@ impl Tool for DocumentTool {let bytes = match engine::generate(&input, GENERATION_TIMEOUT).await {Ok(bytes) => bytes,Err(err) => {- let _ = fail_artifact(- &self.workspace_dir,- &self.files_dir,- &meta.id,- &err.to_string(),- )- .await;+ production.fail(&err.to_string()).await;tracing::warn!(target: "document",err = %err,@@ -287,34 +287,26 @@ impl Tool for DocumentTool {.map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();let reason = format!("failed to write generated document ({filename}): {err}");- let _ = fail_artifact(&self.workspace_dir, &self.files_dir, &meta.id, &reason).await;+ production.fail(&reason).await;tracing::warn!(target: "document",err = %err,- artifact_id = %meta.id,+ artifact_id = %production.id(),filename = %filename,"[document] artifact file write failed");return Ok(ToolResult::error(reason));}- let size_bytes = bytes.len() as u64;- let updated = match finalize_artifact(&self.workspace_dir, &meta.id, size_bytes).await {- Ok(updated) => updated,- Err(err) => {- let reason = format!("failed to finalize artifact: {err}");- // File is already on disk but the ledger transition failed.- // Flip to Failed so the UI surfaces the error instead of a- // stuck `Pending` spinner. Fail-artifact errors are- // swallowed — they can only recur if the same ledger backend- // is unavailable.- let _ =- fail_artifact(&self.workspace_dir, &self.files_dir, &meta.id, &reason).await;+ // Record the file as the artifact's newest version; the card turns+ // ready from that record.+ let size_bytes = match production.complete().await {+ Ok(size) => size,+ Err(reason) => {tracing::warn!(target: "document",- err = %err,- artifact_id = %meta.id,- "[document] finalize_artifact failed; flipped to Failed"+ artifact_id = %production.id(),+ "[document] {reason}");return Ok(ToolResult::error(reason));}@@ -322,91 +314,14 @@ impl Tool for DocumentTool {tracing::info!(target: "document",- artifact_id = %updated.id,+ artifact_id = %production.id(),size_bytes,section_count = input.sections.len(),"[document] generation complete");- // Phase 2d: mirror the finished document into the versioned artifact- // store (tiny-artifacts crate). With an `artifact_id` arg the document- // is saved as a new version of that existing artifact, otherwise a- // fresh record is created. The body is the workspace path — the- // document is a binary file, and the shared model stores a reference,- // not bytes.- let versioned_store = FsArtifactStore::new(&self.workspace_dir, self.files_dir.clone());- let versioned_result = (|| async {- let body = output_path.display().to_string();- let now = tiny_artifacts::now_millis();- match &artifact_id {- Some(existing_id) => {- match versioned_store.get(existing_id).await? {- Some(mut record) => {- let v = ArtifactVersion::new(- 0,- body,- ArtifactAuthor::Agent,- "agent",- now,- );- record.push_version(v);- versioned_store.upsert(&record).await?;- tracing::info!(- target: "document",- artifact_id = existing_id,- "[document] versioned artifact updated"- );- }- None => {- let record = ArtifactRecord::new(- existing_id,- &input.title,- tiny_artifacts::ArtifactKind::File,- body,- "agent",- now,- );- versioned_store.upsert(&record).await?;- tracing::info!(- target: "document",- artifact_id = existing_id,- "[document] versioned artifact created from update target"- );- }- }- }- None => {- let record = ArtifactRecord::new(- &meta.id,- &input.title,- tiny_artifacts::ArtifactKind::File,- body,- "agent",- now,- );- versioned_store.upsert(&record).await?;- tracing::info!(- target: "document",- artifact_id = %meta.id,- "[document] versioned artifact created"- );- }- }- Ok::<(), anyhow::Error>(())- })()- .await;- if let Err(err) = versioned_result {- // The legacy meta.json flow already succeeded; a versioned-store- // write failure must not abort the reply.- tracing::warn!(- target: "document",- err = %err,- "[document] failed to mirror artifact into versioned store"- );- }-let out = GenerateDocumentOutput {- artifact_id: updated.id.clone(),+ artifact_id: production.id().to_string(),artifact_path: output_path.display().to_string(),section_count: input.sections.len(),size_bytes,diff --git a/crates/openhuman-core/src/tools/impl/presentation/mod.rs b/crates/openhuman-core/src/tools/impl/presentation/mod.rsindex 26dbe112ec..002ac7b2cf 100644--- a/crates/openhuman-core/src/tools/impl/presentation/mod.rs+++ b/crates/openhuman-core/src/tools/impl/presentation/mod.rs@@ -5,19 +5,18 @@//! 1. Validate the JSON-Schema input early (`types::validate_input`)//! so the agent gets a structured `InvalidInput` it can self-correct//! on instead of a low-level error.-//! 2. Allocate an artifact dir via `artifacts::create_artifact`. The-//! returned `meta` starts at `ArtifactStatus::Pending` so an-//! interrupted run never surfaces as Ready.+//! 2. Start a [`Production`]: it reserves `<title>.pptx` in the files folder+//! (the card shows "generating…") and opens the versioned artifact — or,+//! with an `artifact_id` arg or a regenerate in scope, a new version of+//! that artifact under the same id and file.//! 3. Generate the deck bytes via [`engine::generate`] — pure Rust,//! `ppt-rs`-backed, no Python runtime, no subprocess. Wrapped in//! `spawn_blocking` + `tokio::time::timeout` so the synchronous//! library work neither blocks the async executor nor can wedge//! the agent loop.-//! 4. Write the bytes to the artifact's output path, stat for size,-//! flip artifact to `Ready` via `artifacts::finalize_artifact`,-//! return the artifact id + path.-//! 5. On failure: flip artifact to `Failed` via-//! `artifacts::fail_artifact` so the UI can surface the reason.+//! 4. Write the bytes and [`Production::complete`]: the file becomes the+//! artifact's newest version and the card turns ready.+//! 5. On failure: [`Production::fail`] so the UI can surface the reason.//!//! Originally shipped in #2778 against a managed python-pptx venv;//! refactored to a native-Rust engine in #2780-follow-up to drop the@@ -34,11 +33,8 @@ use std::time::Duration;use async_trait::async_trait;use serde_json::{json, Value};-use crate::agent::artifacts::{- create_artifact, fail_artifact, finalize_artifact, read_artifact_bytes, ArtifactKind,-};-use crate::agent::artifacts::tiny_store::FsArtifactStore;-use tiny_artifacts::{ArtifactAuthor, ArtifactRecord, ArtifactStore, ArtifactVersion};+use crate::agent::artifacts::production::Production;+use crate::agent::artifacts::read_artifact_bytes;use crate::security::SecurityPolicy;use tinytools::{PermissionLevel, Tool, ToolResult};@@ -316,28 +312,37 @@ impl Tool for PresentationTool {);}- let (meta, output_path) = create_artifact(+ // Reserve the file and open the artifact: a new one, or a new version+ // of `artifact_id` / the regenerate target (same id, same file,+ // history kept).+ let production = Production::start(&self.workspace_dir,- &self.files_dir,- ArtifactKind::Presentation,+ self.files_dir.clone(),+ tiny_artifacts::ArtifactKind::File,&input.title,"pptx",+ None,+ input.artifact_id.as_deref(),).await.map_err(anyhow::Error::msg)?;+ let output_path = production.path().to_path_buf();// Persist the verbatim args next to meta.json so a failed card's// Retry can re-dispatch this exact spec deterministically (#3162).// Best-effort: a write failure only forfeits future regeneration,// it must not abort an otherwise-successful generation.- if let Err(err) =- crate::agent::artifacts::store::save_artifact_args(&self.workspace_dir, &meta.id, &args)- .await+ if let Err(err) = crate::agent::artifacts::store::save_artifact_args(+ &self.workspace_dir,+ production.id(),+ &args,+ )+ .await{tracing::warn!(target: "presentation",err = %err,- artifact_id = %meta.id,+ artifact_id = %production.id(),"[presentation] failed to persist args.json; artifact will not be regenerable");}@@ -352,13 +357,7 @@ impl Tool for PresentationTool {{Ok(bytes) => bytes,Err(err) => {- let _ = fail_artifact(- &self.workspace_dir,- &self.files_dir,- &meta.id,- &err.to_string(),- )- .await;+ production.fail(&err.to_string()).await;tracing::warn!(target: "presentation",err = %err,@@ -374,35 +373,26 @@ impl Tool for PresentationTool {.map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();let reason = format!("failed to write generated deck ({filename}): {err}");- let _ = fail_artifact(&self.workspace_dir, &self.files_dir, &meta.id, &reason).await;+ production.fail(&reason).await;tracing::warn!(target: "presentation",err = %err,- artifact_id = %meta.id,+ artifact_id = %production.id(),filename = %filename,"[presentation] artifact file write failed");return Ok(ToolResult::error(reason));}- let size_bytes = bytes.len() as u64;- let updated = match finalize_artifact(&self.workspace_dir, &meta.id, size_bytes).await {- Ok(updated) => updated,- Err(err) => {- let reason = format!("failed to finalize artifact: {err}");- // File is already on disk but the ledger transition failed.- // Flip the artifact to Failed so the UI surfaces the error- // instead of leaving it stuck in `Pending`. Fail-artifact- // errors are swallowed — they can only happen if the same- // ledger backend is unavailable, in which case nothing we- // do here will help.- let _ =- fail_artifact(&self.workspace_dir, &self.files_dir, &meta.id, &reason).await;+ // Record the file as the artifact's newest version; the card turns+ // ready from that record.+ let size_bytes = match production.complete().await {+ Ok(size) => size,+ Err(reason) => {tracing::warn!(target: "presentation",- err = %err,- artifact_id = %meta.id,- "[presentation] finalize_artifact failed; flipped to Failed"+ artifact_id = %production.id(),+ "[presentation] {reason}");return Ok(ToolResult::error(reason));}@@ -410,91 +400,14 @@ impl Tool for PresentationTool {tracing::info!(target: "presentation",- artifact_id = %updated.id,+ artifact_id = %production.id(),size_bytes,slide_count = input.slides.len(),"[presentation] generation complete");- // Phase 2d: mirror the finished deck into the versioned artifact- // store (tiny-artifacts crate). When the caller passed an- // `artifact_id`, the deck is saved as a new version of that existing- // artifact; otherwise a fresh record is created. The body is the- // workspace path — the deck is a binary file, and the shared model- // stores a reference, not bytes.- let versioned_store = FsArtifactStore::new(&self.workspace_dir, self.files_dir.clone());- let versioned_result = (|| async {- let body = output_path.display().to_string();- let now = tiny_artifacts::now_millis();- match &input.artifact_id {- Some(existing_id) => {- match versioned_store.get(existing_id).await? {- Some(mut record) => {- let v = ArtifactVersion::new(- 0,- body,- ArtifactAuthor::Agent,- "agent",- now,- );- record.push_version(v);- versioned_store.upsert(&record).await?;- tracing::info!(- target: "presentation",- artifact_id = existing_id,- "[presentation] versioned artifact updated"- );- }- None => {- let record = ArtifactRecord::new(- existing_id,- &input.title,- tiny_artifacts::ArtifactKind::File,- body,- "agent",- now,- );- versioned_store.upsert(&record).await?;- tracing::info!(- target: "presentation",- artifact_id = existing_id,- "[presentation] versioned artifact created from update target"- );- }- }- }- None => {- let record = ArtifactRecord::new(- &meta.id,- &input.title,- tiny_artifacts::ArtifactKind::File,- body,- "agent",- now,- );- versioned_store.upsert(&record).await?;- tracing::info!(- target: "presentation",- artifact_id = %meta.id,- "[presentation] versioned artifact created"- );- }- }- Ok::<(), anyhow::Error>(())- })()- .await;- if let Err(err) = versioned_result {- // The legacy meta.json flow already succeeded; a versioned-store- // write failure must not abort the reply.- tracing::warn!(- target: "presentation",- err = %err,- "[presentation] failed to mirror artifact into versioned store"- );- }-let out = GeneratePresentationOutput {- artifact_id: updated.id.clone(),+ artifact_id: production.id().to_string(),artifact_path: output_path.display().to_string(),slide_count: input.slides.len(),size_bytes,diff --git a/crates/openhuman-core/src/tools/ops.rs b/crates/openhuman-core/src/tools/ops.rsindex a132bc343e..069c0fadce 100644--- a/crates/openhuman-core/src/tools/ops.rs+++ b/crates/openhuman-core/src/tools/ops.rs@@ -163,17 +163,16 @@ pub fn all_tools_with_runtime(tools.append(&mut vec![// Task & productivity tools (issue: agent-tool expansion).// Read/observe + bounded-write tools are registered here; the- // destructive/overextending siblings (artifact_delete,+ // destructive/overextending siblings (delete_artifact,// task_source_add/update/remove) are registered too but ship// default-OFF via `tools::user_filter` (their toggle IDs default off// in onboarding). The per-call permission ladder still gates them.]);- tools.extend(crate::agent::artifacts::tools::registered_tools(- config.clone(),- ));tools.extend(crate::agent::artifacts::tiny_store::registered_tools(&config.workspace_dir,crate::agent::artifacts::FileRoots::from_config(&config),+ action_dir,+ crate::integrations::file_storage::artifact_publisher(&config),));tools.extend(crate::integrations::task_sources::tools::registered_tools(config.clone(),diff --git a/crates/openhuman-core/src/tools/ops_tests.rs b/crates/openhuman-core/src/tools/ops_tests.rsindex 99b0e4cbc1..9dcc6b3aab 100644--- a/crates/openhuman-core/src/tools/ops_tests.rs+++ b/crates/openhuman-core/src/tools/ops_tests.rs@@ -125,9 +125,11 @@ const PRODUCTIVITY_TOOLS: &[&str] = &[// `agent_workflows` domain was dissolved into `workflows`; workflow// discovery/run tools now live under the Knowledge theme// (`list_workflows`, `run_workflow`, …).- "artifact_list",- "artifact_get",- "artifact_delete",+ "create_artifact",+ "read_artifact",+ "update_artifact",+ "list_artifacts",+ "delete_artifact","task_source_list","task_source_get","task_source_fetch",@@ -140,15 +142,17 @@ const PRODUCTIVITY_TOOLS: &[&str] = &[];const PRODUCTIVITY_DEFAULT_OFF: &[&str] = &[- "artifact_delete",+ "delete_artifact","task_source_add","task_source_update","task_source_remove",];const PRODUCTIVITY_ALWAYS_ON: &[&str] = &[- "artifact_list",- "artifact_get",+ "create_artifact",+ "read_artifact",+ "update_artifact",+ "list_artifacts","task_source_fetch","task_source_status",];diff --git a/crates/openhuman-core/src/tools/ops_tests_capability_gating_tests.rs b/crates/openhuman-core/src/tools/ops_tests_capability_gating_tests.rsindex 7659fa1291..9e2fd1e37f 100644--- a/crates/openhuman-core/src/tools/ops_tests_capability_gating_tests.rs+++ b/crates/openhuman-core/src/tools/ops_tests_capability_gating_tests.rs@@ -56,10 +56,25 @@ fn tool_group_classifies_gate_and_harness_families() {);}assert_eq!(tool_group("media_generate_image"), DomainGroup::Media);+ // Sharing uploads through cloud file storage, so it gates with `storage_*`.+ assert_eq!(tool_group("share_artifact"), DomainGroup::Integrations);+ assert_eq!(tool_group("storage_upload_file"), DomainGroup::Integrations);// Harness-mapped families → kept under harness().assert_eq!(tool_group("memory"), DomainGroup::Memory);assert_eq!(tool_group("goal_get"), DomainGroup::Threads);- assert_eq!(tool_group("artifact_list"), DomainGroup::Agent);+ for name in [+ "create_artifact",+ "read_artifact",+ "update_artifact",+ "list_artifacts",+ "delete_artifact",+ ] {+ assert_eq!(+ tool_group(name),+ DomainGroup::Agent,+ "{name} is harness-kept"+ );+ }assert_eq!(tool_group("learning_list_facets"), DomainGroup::Agent);assert_eq!(tool_group("spawn_subagent"), DomainGroup::Agent);for name in [@@ -112,7 +127,7 @@ fn tool_group_gate_families_dropped_under_harness_not_full() {}// Harness keeps memory/threads, drops gate families AND platform.assert!(harness.allows(tool_group("memory")));- assert!(harness.allows(tool_group("artifact_list")));+ assert!(harness.allows(tool_group("list_artifacts")));assert!(harness.allows(tool_group("config_snapshot")));assert!(harness.allows(tool_group("security_policy_info")));assert!(!harness.allows(tool_group("wallet_status")));diff --git a/crates/openhuman-core/src/tools/ops_tests_domain_family_tests.rs b/crates/openhuman-core/src/tools/ops_tests_domain_family_tests.rsindex 49d2a7add9..0f6cf3e332 100644--- a/crates/openhuman-core/src/tools/ops_tests_domain_family_tests.rs+++ b/crates/openhuman-core/src/tools/ops_tests_domain_family_tests.rs@@ -185,16 +185,24 @@ fn productivity_default_off_tools_retained_when_opted_in() {}#[tokio::test]-async fn artifact_list_through_registry_returns_envelope() {+async fn artifacts_created_through_the_registry_are_listed() {let tmp = TempDir::new().unwrap();let tools = expansion_tools_for(&tmp);- let out = find_tool(&tools, "artifact_list")- .execute(serde_json::json!({ "limit": 10 }))+ let created = find_tool(&tools, "create_artifact")+ .execute(serde_json::json!({ "kind": "markdown", "title": "Notes", "body": "# hi" })).await- .expect("artifact_list execute");+ .expect("create_artifact execute");+ assert!(!created.is_error, "{}", created.output_for_llm(false));++ let out = find_tool(&tools, "list_artifacts")+ .execute(serde_json::json!({}))+ .await+ .expect("list_artifacts execute");let body = out.output_for_llm(false);- assert!(body.contains("artifacts"), "envelope missing: {body}");- assert!(body.contains("total"), "envelope missing total: {body}");+ assert!(+ body.contains("\"title\":\"Notes\""),+ "listing missing the artifact: {body}"+ );}#[test]diff --git a/crates/openhuman-core/src/tools/ops_tool_groups.rs b/crates/openhuman-core/src/tools/ops_tool_groups.rsindex 75837d99f9..528b103a2c 100644--- a/crates/openhuman-core/src/tools/ops_tool_groups.rs+++ b/crates/openhuman-core/src/tools/ops_tool_groups.rs@@ -1,5 +1,15 @@//! Domain-family classification used to filter the callable tool catalog.+/// The versioned artifact tools (`tiny-artifacts`). Harness-kept, like the+/// rest of the agent's own working surface.+const ARTIFACT_TOOLS: &[&str] = &[+ "create_artifact",+ "read_artifact",+ "update_artifact",+ "list_artifacts",+ "delete_artifact",+];+/// Classify an agent tool into its [`DomainGroup`](crate::core::all::DomainGroup)/// by its `name()`, so [`all_tools_with_runtime`](super::all_tools_with_runtime) can drop tools whose family is/// disabled under the ambient [`DomainSet`](crate::core::runtime::DomainSet).@@ -124,6 +134,7 @@ pub(crate) fn tool_group(name: &str) -> crate::core::all::DomainGroup {}// Harness families realigned out of Platform.if name.starts_with("artifact_")+ || ARTIFACT_TOOLS.contains(&name)|| name.starts_with("learning_")|| name.contains("subagent")|| matches!(@@ -181,6 +192,8 @@ pub(crate) fn tool_group(name: &str) -> crate::core::all::DomainGroup {|| name.starts_with("google_places_")|| name.starts_with("stock_")|| name.starts_with("storage_")+ // Shares an artifact by uploading it to the same cloud storage.+ || name == "share_artifact"|| name.starts_with("task_source_")// Hosting: `hosting_` is a domain-exclusive prefix, so a NEW hosting// tool auto-gates rather than falling through to Platform and stayingdiff --git a/crates/openhuman-core/src/tools/user_filter.rs b/crates/openhuman-core/src/tools/user_filter.rsindex dfaf53f882..71a482b77b 100644--- a/crates/openhuman-core/src/tools/user_filter.rs+++ b/crates/openhuman-core/src/tools/user_filter.rs@@ -165,7 +165,7 @@ const TOOL_FAMILIES: &[ToolFamily] = &[// Task & workflow productivity — overextending tools (agent-tool// expansion). Only the destructive/persistent-config mutators are listed// here so the onboarding toggle surface can default them OFF and let users- // opt in; the read-only + bounded-write siblings (e.g. `artifact_list`,+ // opt in; the read-only + bounded-write siblings (e.g. `list_artifacts`,// `task_source_fetch`) are intentionally NOT listed, so they// are always-retained infrastructure. Grouped one toggle per risk family.ToolFamily {@@ -173,9 +173,11 @@ const TOOL_FAMILIES: &[ToolFamily] = &[rust_names: &["agent_workflow_uninstall"],default_enabled: false,},+ // The toggle id predates the tool's rename to `delete_artifact`; it stays+ // so a user's saved choice keeps applying.ToolFamily {id: "artifact_delete",- rust_names: &["artifact_delete"],+ rust_names: &["delete_artifact"],default_enabled: false,},ToolFamily {diff --git a/scripts/ci/check-storage-bypass.mjs b/scripts/ci/check-storage-bypass.mjsindex 0dfc1eb765..13678a1e62 100755--- a/scripts/ci/check-storage-bypass.mjs+++ b/scripts/ci/check-storage-bypass.mjs@@ -163,6 +163,12 @@ export const ALLOW = new Map("match tokio::fs::OpenOptions::new()","reserves the artifact's content file in the user-visible files folder; the bytes stay a file on every backend (the port has no blob store), only the records moved",],+ [+ "agent/artifacts/tiny_store.rs",+ "json-write",+ "tokio::fs::write(&dest, latest.body.as_bytes()).await?;",+ "writes a text artifact's newest version into its file in the user-visible files folder; the deliverable is a user file on every backend, the versioned record itself goes through the artifact store",+ ],].reduce((map, [path, rule, site, reason]) => {const key = `${SRC}${path}`;map.set(key, [...(map.get(key) ?? []), { rule, site, reason }]);diff --git a/vendor/tiny-artifacts b/vendor/tiny-artifactsindex 65730e8de0..d84cecbff8 160000--- a/vendor/tiny-artifacts+++ b/vendor/tiny-artifacts@@ -1 +1 @@-Subproject commit 65730e8de006877b167858d5c94cbf412612087e+Subproject commit d84cecbff85a350658edc4fcfe47e061b59c1b47