Skip to content

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

fix(memory): stop a v1 import on credits or outage instead of skipping every item

Ghost Scripterb2aba0fe5b2d
diff --git a/app/src/components/memory/MemoryImportBanner.test.tsx b/app/src/components/memory/MemoryImportBanner.test.tsx
index ac5f1983a3..bae12beea2 100644
--- a/app/src/components/memory/MemoryImportBanner.test.tsx
+++ b/app/src/components/memory/MemoryImportBanner.test.tsx
@@ -84,6 +84,32 @@ describe('MemoryImportBanner', () => {
);
});
+ it('resumes a failed import through the consent dialog', async () => {
+ hoisted.status.mockResolvedValue({
+ state: { phase: 'error', imported: 2, total: 9, error: 'not enough credits to import' },
+ });
+ hoisted.start.mockResolvedValue({ state: { phase: 'running', imported: 2, total: 9 } });
+ renderWithProviders(<MemoryImportBanner engineLabel="TinyHumans" />);
+
+ fireEvent.click(await screen.findByTestId('memory-import-resume'));
+ expect(screen.getByTestId('memory-import-consent')).toBeInTheDocument();
+ expect(hoisted.start).not.toHaveBeenCalled();
+
+ fireEvent.click(screen.getByTestId('memory-import-confirm'));
+ expect(await screen.findByTestId('memory-import-running')).toHaveTextContent(
+ '2 of 9 items imported'
+ );
+ expect(hoisted.start).toHaveBeenCalledTimes(1);
+ expect(screen.queryByTestId('memory-import-resume')).not.toBeInTheDocument();
+ });
+
+ it('offers no resume while an import is running', async () => {
+ hoisted.status.mockResolvedValue({ state: { phase: 'running', imported: 1, total: 9 } });
+ renderWithProviders(<MemoryImportBanner engineLabel="TinyHumans" />);
+ expect(await screen.findByTestId('memory-import-running')).toBeInTheDocument();
+ expect(screen.queryByTestId('memory-import-resume')).not.toBeInTheDocument();
+ });
+
it('shows a start failure', async () => {
hoisted.start.mockRejectedValue(new Error('UNAUTHORIZED: sign in again'));
renderWithProviders(<MemoryImportBanner engineLabel="TinyHumans" />);
diff --git a/app/src/components/memory/MemoryImportBanner.tsx b/app/src/components/memory/MemoryImportBanner.tsx
index 038e0335ae..14bbc05728 100644
--- a/app/src/components/memory/MemoryImportBanner.tsx
+++ b/app/src/components/memory/MemoryImportBanner.tsx
@@ -153,6 +153,18 @@ export default function MemoryImportBanner({ engineLabel }: MemoryImportBannerPr
total: state.total,
})}
</AlertDescription>
+ {state.phase === 'error' && (
+ // The core keeps the checkpoint, so starting again resumes where
+ // the import stopped; it still goes through the consent dialog.
+ <Button
+ type="button"
+ size="sm"
+ variant="primary"
+ data-testid="memory-import-resume"
+ onClick={() => setConsentOpen(true)}>
+ {t('memoryPage.import.resume')}
+ </Button>
+ )}
</div>
</Alert>
)}
diff --git a/app/src/lib/i18n/ar.ts b/app/src/lib/i18n/ar.ts
index 3a1c314f89..9e1a91f8d3 100644
--- a/app/src/lib/i18n/ar.ts
+++ b/app/src/lib/i18n/ar.ts
@@ -5044,6 +5044,7 @@ const messages: TranslationMap = {
'memoryPage.import.running': 'جارٍ استيراد الذاكرة السابقة…',
'memoryPage.import.done': 'تم استيراد الذاكرة السابقة',
'memoryPage.import.failed': 'فشل الاستيراد',
+ 'memoryPage.import.resume': 'استئناف الاستيراد',
'memoryPage.import.progress': 'تم استيراد {imported} من {total} عنصر',
};
diff --git a/app/src/lib/i18n/bn.ts b/app/src/lib/i18n/bn.ts
index 2e8f494f6d..05fb704ae6 100644
--- a/app/src/lib/i18n/bn.ts
+++ b/app/src/lib/i18n/bn.ts
@@ -5142,6 +5142,7 @@ const messages: TranslationMap = {
'memoryPage.import.running': 'আগের মেমোরি ইমপোর্ট হচ্ছে…',
'memoryPage.import.done': 'আগের মেমোরি ইমপোর্ট হয়েছে',
'memoryPage.import.failed': 'ইমপোর্ট ব্যর্থ হয়েছে',
+ 'memoryPage.import.resume': 'ইমপোর্ট আবার চালু করুন',
'memoryPage.import.progress': '{total}টির মধ্যে {imported}টি আইটেম ইমপোর্ট হয়েছে',
};
diff --git a/app/src/lib/i18n/de.ts b/app/src/lib/i18n/de.ts
index 2949e7eb73..3bf73bf09d 100644
--- a/app/src/lib/i18n/de.ts
+++ b/app/src/lib/i18n/de.ts
@@ -5284,6 +5284,7 @@ const messages: TranslationMap = {
'memoryPage.import.running': 'Früheres Gedächtnis wird importiert…',
'memoryPage.import.done': 'Früheres Gedächtnis importiert',
'memoryPage.import.failed': 'Import fehlgeschlagen',
+ 'memoryPage.import.resume': 'Import fortsetzen',
'memoryPage.import.progress': '{imported} von {total} Elementen importiert',
};
diff --git a/app/src/lib/i18n/en.ts b/app/src/lib/i18n/en.ts
index d349643a07..370bcaa167 100644
--- a/app/src/lib/i18n/en.ts
+++ b/app/src/lib/i18n/en.ts
@@ -5419,6 +5419,7 @@ const en: TranslationMap = {
'memoryPage.import.running': 'Importing previous memory…',
'memoryPage.import.done': 'Previous memory imported',
'memoryPage.import.failed': 'Import failed',
+ 'memoryPage.import.resume': 'Resume import',
'memoryPage.import.progress': '{imported} of {total} items imported',
};
diff --git a/app/src/lib/i18n/es.ts b/app/src/lib/i18n/es.ts
index 5f426c5aba..2dd2a67c49 100644
--- a/app/src/lib/i18n/es.ts
+++ b/app/src/lib/i18n/es.ts
@@ -5238,6 +5238,7 @@ const messages: TranslationMap = {
'memoryPage.import.running': 'Importando memoria anterior…',
'memoryPage.import.done': 'Memoria anterior importada',
'memoryPage.import.failed': 'Error al importar',
+ 'memoryPage.import.resume': 'Reanudar importación',
'memoryPage.import.progress': '{imported} de {total} elementos importados',
};
diff --git a/app/src/lib/i18n/fr.ts b/app/src/lib/i18n/fr.ts
index ef29af3097..26d98c6271 100644
--- a/app/src/lib/i18n/fr.ts
+++ b/app/src/lib/i18n/fr.ts
@@ -5264,6 +5264,7 @@ const messages: TranslationMap = {
'memoryPage.import.running': "Importation de l'ancienne mémoire…",
'memoryPage.import.done': 'Ancienne mémoire importée',
'memoryPage.import.failed': "Échec de l'importation",
+ 'memoryPage.import.resume': "Reprendre l'importation",
'memoryPage.import.progress': '{imported} éléments sur {total} importés',
};
diff --git a/app/src/lib/i18n/hi.ts b/app/src/lib/i18n/hi.ts
index 9634dd1e42..4066365e54 100644
--- a/app/src/lib/i18n/hi.ts
+++ b/app/src/lib/i18n/hi.ts
@@ -5143,6 +5143,7 @@ const messages: TranslationMap = {
'memoryPage.import.running': 'पिछली मेमोरी इंपोर्ट हो रही है…',
'memoryPage.import.done': 'पिछली मेमोरी इंपोर्ट हो गई',
'memoryPage.import.failed': 'इंपोर्ट विफल रहा',
+ 'memoryPage.import.resume': 'इंपोर्ट फिर से शुरू करें',
'memoryPage.import.progress': '{total} में से {imported} आइटम इंपोर्ट हुए',
};
diff --git a/app/src/lib/i18n/id.ts b/app/src/lib/i18n/id.ts
index ad736b7ed9..e43d33c90e 100644
--- a/app/src/lib/i18n/id.ts
+++ b/app/src/lib/i18n/id.ts
@@ -5184,6 +5184,7 @@ const messages: TranslationMap = {
'memoryPage.import.running': 'Mengimpor memori sebelumnya…',
'memoryPage.import.done': 'Memori sebelumnya telah diimpor',
'memoryPage.import.failed': 'Impor gagal',
+ 'memoryPage.import.resume': 'Lanjutkan impor',
'memoryPage.import.progress': '{imported} dari {total} item diimpor',
};
diff --git a/app/src/lib/i18n/it.ts b/app/src/lib/i18n/it.ts
index 67f7673a83..d361b2cc0f 100644
--- a/app/src/lib/i18n/it.ts
+++ b/app/src/lib/i18n/it.ts
@@ -5223,6 +5223,7 @@ const messages: TranslationMap = {
'memoryPage.import.running': 'Importazione della memoria precedente…',
'memoryPage.import.done': 'Memoria precedente importata',
'memoryPage.import.failed': 'Importazione non riuscita',
+ 'memoryPage.import.resume': "Riprendi l'importazione",
'memoryPage.import.progress': '{imported} di {total} elementi importati',
};
diff --git a/app/src/lib/i18n/ko.ts b/app/src/lib/i18n/ko.ts
index 57503e4740..680a45ed76 100644
--- a/app/src/lib/i18n/ko.ts
+++ b/app/src/lib/i18n/ko.ts
@@ -5094,6 +5094,7 @@ const messages: TranslationMap = {
'memoryPage.import.running': '이전 메모리를 가져오는 중…',
'memoryPage.import.done': '이전 메모리를 가져왔습니다',
'memoryPage.import.failed': '가져오기에 실패했습니다',
+ 'memoryPage.import.resume': '가져오기 재개',
'memoryPage.import.progress': '{total}개 중 {imported}개 항목을 가져왔습니다',
};
diff --git a/app/src/lib/i18n/pl.ts b/app/src/lib/i18n/pl.ts
index 755aed7004..8f8826df13 100644
--- a/app/src/lib/i18n/pl.ts
+++ b/app/src/lib/i18n/pl.ts
@@ -5211,6 +5211,7 @@ const messages: TranslationMap = {
'memoryPage.import.running': 'Importowanie poprzedniej pamięci…',
'memoryPage.import.done': 'Zaimportowano poprzednią pamięć',
'memoryPage.import.failed': 'Import nie powiódł się',
+ 'memoryPage.import.resume': 'Wznów import',
'memoryPage.import.progress': 'Zaimportowano {imported} z {total} elementów',
};
diff --git a/app/src/lib/i18n/pt.ts b/app/src/lib/i18n/pt.ts
index 8946b81949..deeb481f15 100644
--- a/app/src/lib/i18n/pt.ts
+++ b/app/src/lib/i18n/pt.ts
@@ -5212,6 +5212,7 @@ const messages: TranslationMap = {
'memoryPage.import.running': 'Importando memória anterior…',
'memoryPage.import.done': 'Memória anterior importada',
'memoryPage.import.failed': 'Falha na importação',
+ 'memoryPage.import.resume': 'Retomar importação',
'memoryPage.import.progress': '{imported} de {total} itens importados',
};
diff --git a/app/src/lib/i18n/ru.ts b/app/src/lib/i18n/ru.ts
index 011cf76b59..6c0cedd6d6 100644
--- a/app/src/lib/i18n/ru.ts
+++ b/app/src/lib/i18n/ru.ts
@@ -5192,6 +5192,7 @@ const messages: TranslationMap = {
'memoryPage.import.running': 'Импорт прежней памяти…',
'memoryPage.import.done': 'Прежняя память импортирована',
'memoryPage.import.failed': 'Не удалось выполнить импорт',
+ 'memoryPage.import.resume': 'Возобновить импорт',
'memoryPage.import.progress': 'Импортировано {imported} из {total}',
};
diff --git a/app/src/lib/i18n/zh-CN.ts b/app/src/lib/i18n/zh-CN.ts
index 5d7b03d8d5..53b9dd20b7 100644
--- a/app/src/lib/i18n/zh-CN.ts
+++ b/app/src/lib/i18n/zh-CN.ts
@@ -4858,6 +4858,7 @@ const messages: TranslationMap = {
'memoryPage.import.running': '正在导入旧版记忆…',
'memoryPage.import.done': '旧版记忆已导入',
'memoryPage.import.failed': '导入失败',
+ 'memoryPage.import.resume': '继续导入',
'memoryPage.import.progress': '已导入 {imported} / {total} 项',
};
diff --git a/crates/openhuman-core/src/memory/bus.rs b/crates/openhuman-core/src/memory/bus.rs
index 5a7a8b6111..4048f496ce 100644
--- a/crates/openhuman-core/src/memory/bus.rs
+++ b/crates/openhuman-core/src/memory/bus.rs
@@ -5,7 +5,8 @@
//!
//! - `memory_sources_sync` starts the due source syncs;
//! - `memory_background` runs the queued belief builds and deferred ingests
-//! (`lifecycle::jobs`).
+//! (`lifecycle::jobs`), after resuming a v1 import the app quit in the
+//! middle of (`import::resume_interrupted`).
//!
//! Turns are not ingested from the bus: the session host calls the lifecycle
//! hooks itself, under the session's own config (`lifecycle::hooks`).
@@ -68,7 +69,10 @@ pub async fn run_system_job(config: &crate::config::Config, job: &str) {
"[memory:bus] due source syncs started"
);
}
- BACKGROUND_JOB => super::lifecycle::jobs::run_due(config).await,
+ BACKGROUND_JOB => {
+ super::import::resume_interrupted(config).await;
+ super::lifecycle::jobs::run_due(config).await;
+ }
_ => {}
}
}
diff --git a/crates/openhuman-core/src/memory/import.rs b/crates/openhuman-core/src/memory/import.rs
index a6f7b1f5cb..28dc66f649 100644
--- a/crates/openhuman-core/src/memory/import.rs
+++ b/crates/openhuman-core/src/memory/import.rs
@@ -8,7 +8,10 @@
//! the resumable [`Checkpoint`]. Progress and the checkpoint persist in
//! `<workspace>/memory/import_state.json`, so a restarted import resumes where
//! the last one stopped (an item stored but not yet checkpointed is re-sent,
-//! and the engine treats it as a replay).
+//! and the engine treats it as a replay). An import the app quit in the middle
+//! of resumes on its own ([`resume_interrupted`]); one stopped by a failure
+//! that is not about a single item (credits exhausted, signed out, engine
+//! unreachable) waits for the user to start it again.
use std::collections::HashSet;
use std::path::{Path, PathBuf};
@@ -16,13 +19,13 @@ use std::sync::{LazyLock, Mutex};
use serde::{Deserialize, Serialize};
use tinymemory_api::ItemKind;
+use tinymemory_integrations::cortex::is_insufficient_credits;
use tinymemory_integrations::import::{Checkpoint, ImportedItem, LegacyWorkspace};
use crate::config::Config;
use super::engine::{self, BoundEngine};
use super::error::{MemoryError, MemoryResult};
-use super::ops::{store_many_on, store_on};
use super::types::{ImportCounts, ImportPhase, ImportScanView, ImportState};
/// Items stored between two checkpoint writes.
@@ -38,54 +41,88 @@ struct BatchOutcome {
stored: u64,
/// The checkpoint after the last item handled, stored or skipped.
checkpoint: Option<Checkpoint>,
- /// Why the import must stop (memory off, credential rejected).
+ /// Why the import must stop (credential rejected, credits exhausted,
+ /// engine unreachable).
fatal: Option<String>,
}
-fn is_fatal(error: &MemoryError) -> bool {
- matches!(error, MemoryError::Unauthorized(_) | MemoryError::Off(_))
+/// Whether a store failure is about the item (skip it and go on) rather than
+/// the engine or the account (stop, so a resume retries from here).
+///
+/// Only a refusal of the item itself is skippable: malformed or too large
+/// (`InvalidRequest`), not storable here (`Unsupported`, `NotFound`), or a
+/// replay key already bound to a different body (`Conflict`). Everything else
+/// would fail the next item the same way: a rejected credential, an exhausted
+/// credit balance (an `Engine` error), an unreachable or overloaded engine
+/// (`Unavailable`). Skipping those would advance the checkpoint past items
+/// that were never stored and finish `Done` with nothing imported.
+fn skips_item(error: &tinymemory_api::Error) -> bool {
+ use tinymemory_api::Error as E;
+ matches!(
+ error,
+ E::InvalidRequest(_) | E::Unsupported(_) | E::NotFound(_) | E::Conflict(_)
+ )
}
-/// Stores `batch` in one bulk call. If the engine refuses the batch for a
-/// reason that is not fatal (one unstorable item), the items are stored one
-/// at a time instead so only the bad ones are skipped.
+/// The message an import stopped by `error` reports.
+fn fatal_message(error: tinymemory_api::Error) -> String {
+ if is_insufficient_credits(&error) {
+ return "not enough credits to import your memory; top up, then resume the import to \
+ continue where it stopped"
+ .to_string();
+ }
+ MemoryError::from(error).to_string()
+}
+
+/// Stores `batch` in one bulk call. If the engine refuses the batch because
+/// of an item (see [`skips_item`]), the items are stored one at a time instead
+/// so only the bad ones are skipped. Any other failure stops the import
+/// without advancing the checkpoint past what was stored.
async fn store_batch(bound: &BoundEngine, batch: Vec<ImportedItem>) -> BatchOutcome {
let Some(last) = batch.last() else {
return BatchOutcome::default();
};
let last_checkpoint = last.checkpoint.clone();
let items: Vec<_> = batch.iter().map(|imported| imported.item.clone()).collect();
- match store_many_on(bound, items).await {
+ match bound.engine.store_many(items).await {
Ok(receipts) => {
+ tracing::debug!(
+ engine = %bound.id,
+ count = receipts.len(),
+ "[memory:import] batch stored"
+ );
return BatchOutcome {
stored: receipts.len() as u64,
checkpoint: Some(last_checkpoint),
fatal: None,
};
}
- Err(error) if is_fatal(&error) => {
+ Err(error) if !skips_item(&error) => {
return BatchOutcome {
- fatal: Some(error.to_string()),
+ fatal: Some(fatal_message(error)),
..BatchOutcome::default()
};
}
Err(error) => {
tracing::debug!(
- code = error.code(),
+ code = MemoryError::from(error).code(),
"[memory:import] batch refused; storing one by one"
);
}
}
let mut outcome = BatchOutcome::default();
for imported in batch {
- match store_on(bound, imported.item).await {
+ match bound.engine.store(imported.item).await {
Ok(_) => outcome.stored += 1,
- Err(error) if is_fatal(&error) => {
- outcome.fatal = Some(error.to_string());
+ Err(error) if !skips_item(&error) => {
+ outcome.fatal = Some(fatal_message(error));
return outcome;
}
Err(error) => {
- tracing::debug!(code = error.code(), "[memory:import] item skipped");
+ tracing::debug!(
+ code = MemoryError::from(error).code(),
+ "[memory:import] item skipped"
+ );
}
}
outcome.checkpoint = Some(imported.checkpoint);
@@ -178,11 +215,52 @@ pub fn status(config: &Config) -> ImportState {
.contains(&config.workspace_dir);
if state.phase == ImportPhase::Running && !running {
state.phase = ImportPhase::Error;
- state.error = Some("the import was interrupted; start it again to resume".to_string());
+ state.error = Some(
+ "the import was interrupted; it resumes on its own within a few minutes, or resume \
+ it now"
+ .to_string(),
+ );
}
state
}
+/// Resumes an import the app quit in the middle of, if there is one.
+///
+/// Only a `Running` state with no live run counts: the user consented when
+/// it started, and quitting the app is not a decision to stop. An import that
+/// stopped on an error (credits exhausted, signed out) stays stopped until the
+/// user starts it again, so a failure that would recur does not loop. Returns
+/// whether a run was started. Called from memory's background job.
+pub async fn resume_interrupted(config: &Config) -> bool {
+ if read_file(&config.workspace_dir).state.phase != ImportPhase::Running {
+ return false;
+ }
+ let live = RUNNING
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .contains(&config.workspace_dir);
+ if live {
+ return false;
+ }
+ match start(config, true).await {
+ Ok(state) => {
+ tracing::info!(
+ imported = state.imported,
+ total = state.total,
+ "[memory:import] resuming an interrupted import"
+ );
+ true
+ }
+ Err(error) => {
+ tracing::debug!(
+ code = error.code(),
+ "[memory:import] interrupted import not resumed"
+ );
+ false
+ }
+ }
+}
+
/// `memory_import_start`: requires `consent`, memory on, and a legacy store.
pub async fn start(config: &Config, consent: bool) -> MemoryResult<ImportState> {
if !consent {
diff --git a/crates/openhuman-core/src/memory/import_tests.rs b/crates/openhuman-core/src/memory/import_tests.rs
index e35f2b09fb..c5d4022bf4 100644
--- a/crates/openhuman-core/src/memory/import_tests.rs
+++ b/crates/openhuman-core/src/memory/import_tests.rs
@@ -1,6 +1,8 @@
use super::*;
use crate::memory::error::{INVALID_REQUEST, MEMORY_OFF};
use crate::memory::test_fixtures::{bind_reference, config_in, stored};
+use std::sync::Arc;
+
use rusqlite::{params, Connection};
use tinymemory_api::MetaFilter;
@@ -209,7 +211,11 @@ fn a_running_state_with_no_live_import_reads_as_interrupted() {
let state = status(&config);
assert_eq!(state.phase, ImportPhase::Error);
assert_eq!(state.imported, 3);
- assert!(state.error.as_deref().unwrap().contains("start it again"));
+ assert!(state
+ .error
+ .as_deref()
+ .unwrap()
+ .contains("resumes on its own"));
}
#[tokio::test]
@@ -245,3 +251,203 @@ fn a_corrupt_import_file_reads_as_idle() {
std::fs::write(file_path(tmp.path()), "garbage").unwrap();
assert_eq!(read_file(tmp.path()).state, ImportState::default());
}
+
+/// A reference engine that refuses a write with whatever `refuse` returns for
+/// its item, and stores it otherwise.
+struct FailingEngine {
+ inner: Arc<tinymemory_api::conformance::ReferenceEngine>,
+ refuse: fn(&tinymemory_api::StoreItem) -> Option<tinymemory_api::Error>,
+}
+
+#[async_trait::async_trait]
+impl tinymemory_api::MemoryEngine for FailingEngine {
+ fn descriptor(&self) -> &tinymemory_api::EngineDescriptor {
+ self.inner.descriptor()
+ }
+ async fn health(&self) -> tinymemory_api::EngineHealth {
+ self.inner.health().await
+ }
+ async fn recall(
+ &self,
+ req: tinymemory_api::RecallRequest,
+ ) -> tinymemory_api::Result<tinymemory_api::RecallAnswer> {
+ self.inner.recall(req).await
+ }
+ async fn fetch(
+ &self,
+ req: tinymemory_api::FetchRequest,
+ ) -> tinymemory_api::Result<tinymemory_api::FetchPage> {
+ self.inner.fetch(req).await
+ }
+ async fn store(
+ &self,
+ item: tinymemory_api::StoreItem,
+ ) -> tinymemory_api::Result<tinymemory_api::StoreReceipt> {
+ if let Some(error) = (self.refuse)(&item) {
+ return Err(error);
+ }
+ self.inner.store(item).await
+ }
+ async fn forget(
+ &self,
+ target: tinymemory_api::ForgetTarget,
+ ) -> tinymemory_api::Result<tinymemory_api::ForgetReport> {
+ self.inner.forget(target).await
+ }
+ async fn list(
+ &self,
+ req: tinymemory_api::ListRequest,
+ ) -> tinymemory_api::Result<tinymemory_api::ListPage> {
+ self.inner.list(req).await
+ }
+}
+
+/// Binds a [`FailingEngine`] and returns the engine behind it.
+fn bind_failing(
+ config: &Config,
+ refuse: fn(&tinymemory_api::StoreItem) -> Option<tinymemory_api::Error>,
+) -> Arc<tinymemory_api::conformance::ReferenceEngine> {
+ let inner = Arc::new(tinymemory_api::conformance::ReferenceEngine::new());
+ crate::memory::engine::install_test_engine(
+ &config.workspace_dir,
+ Arc::new(FailingEngine {
+ inner: inner.clone(),
+ refuse,
+ }),
+ );
+ inner
+}
+
+fn out_of_credits(_: &tinymemory_api::StoreItem) -> Option<tinymemory_api::Error> {
+ Some(tinymemory_api::Error::Engine(
+ "[USER_INSUFFICIENT_CREDITS] insufficient credits (HTTP 402)".into(),
+ ))
+}
+
+#[tokio::test]
+async fn exhausted_credits_stop_the_import_instead_of_skipping_everything() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ legacy_workspace(&config.workspace_dir);
+ let engine = bind_failing(&config, out_of_credits);
+
+ start(&config, true).await.unwrap();
+ let state = wait_until_settled(&config).await;
+ assert_eq!(state.phase, ImportPhase::Error, "{state:?}");
+ assert_eq!(state.imported, 0);
+ assert!(
+ state
+ .error
+ .as_deref()
+ .unwrap()
+ .contains("not enough credits"),
+ "{state:?}"
+ );
+ assert!(stored(&engine, MetaFilter::default()).await.is_empty());
+ assert_eq!(
+ read_file(&config.workspace_dir).checkpoint,
+ Checkpoint::default(),
+ "the checkpoint does not move past items that were never stored"
+ );
+}
+
+#[tokio::test]
+async fn an_unreachable_engine_stops_the_import_and_a_retry_resumes_it() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ legacy_workspace(&config.workspace_dir);
+ bind_failing(&config, |_| {
+ Some(tinymemory_api::Error::Unavailable(
+ "connection refused".into(),
+ ))
+ });
+
+ start(&config, true).await.unwrap();
+ let state = wait_until_settled(&config).await;
+ assert_eq!(state.phase, ImportPhase::Error, "{state:?}");
+ assert_eq!(state.imported, 0);
+
+ // The engine is back: starting again imports everything, nothing skipped.
+ let engine = bind_reference(&config);
+ start(&config, true).await.unwrap();
+ let done = wait_until_settled(&config).await;
+ assert_eq!(done.phase, ImportPhase::Done, "{done:?}");
+ assert_eq!(stored(&engine, MetaFilter::default()).await.len(), 5);
+}
+
+#[tokio::test]
+async fn an_item_the_engine_refuses_is_skipped_and_the_rest_imported() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ legacy_workspace(&config.workspace_dir);
+ // Refuses the "Ideas" document (d2) as malformed, stores the rest.
+ let engine = bind_failing(&config, |item| {
+ format!("{item:?}")
+ .contains("oolong")
+ .then(|| tinymemory_api::Error::InvalidRequest("item too large".into()))
+ });
+
+ start(&config, true).await.unwrap();
+ let done = wait_until_settled(&config).await;
+ assert_eq!(done.phase, ImportPhase::Done, "{done:?}");
+ assert_eq!(done.imported, 4);
+ let items = stored(&engine, MetaFilter::default()).await;
+ assert_eq!(items.len(), 4);
+ assert!(!items.iter().any(|item| item.text.contains("oolong")));
+}
+
+#[tokio::test]
+async fn an_import_the_app_quit_during_resumes_on_its_own() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ legacy_workspace(&config.workspace_dir);
+ let engine = bind_reference(&config);
+ // The app quit while the import was running, after d1 was stored.
+ write_file(
+ &config.workspace_dir,
+ &ImportFile {
+ state: ImportState {
+ phase: ImportPhase::Running,
+ imported: 1,
+ total: 5,
+ error: None,
+ },
+ checkpoint: Checkpoint {
+ documents: Some("d1".into()),
+ ..Checkpoint::default()
+ },
+ },
+ );
+
+ assert!(resume_interrupted(&config).await);
+ let done = wait_until_settled(&config).await;
+ assert_eq!(done.phase, ImportPhase::Done, "{done:?}");
+ assert_eq!(done.imported, 5);
+ assert_eq!(stored(&engine, MetaFilter::default()).await.len(), 4);
+}
+
+#[tokio::test]
+async fn a_stopped_or_finished_import_is_not_resumed_on_its_own() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ legacy_workspace(&config.workspace_dir);
+ let engine = bind_reference(&config);
+ assert!(!resume_interrupted(&config).await, "never started");
+
+ for phase in [ImportPhase::Error, ImportPhase::Done] {
+ write_file(
+ &config.workspace_dir,
+ &ImportFile {
+ state: ImportState {
+ phase,
+ imported: 0,
+ total: 5,
+ error: None,
+ },
+ checkpoint: Checkpoint::default(),
+ },
+ );
+ assert!(!resume_interrupted(&config).await, "{phase:?}");
+ }
+ assert!(stored(&engine, MetaFilter::default()).await.is_empty());
+}
diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.md
index ad4b32c44b..051299c143 100644
--- a/docs/TEST-COVERAGE-MATRIX.md
+++ b/docs/TEST-COVERAGE-MATRIX.md
@@ -365,7 +365,7 @@ Spec: `docs/specs/memory-v2.md` (host) and `vendor/tinymemory/docs/specs/memory-
| 8.2.5 | Document sources: add, sync, list, remove | RU+RI+WD | `crates/openhuman-core/src/memory/sources/sync_tests.rs`, `crates/openhuman-core/src/memory/sources/composio_tests.rs`, `crates/openhuman-core/src/memory/sources/mod_tests.rs`, `tests/memory_v2_e2e.rs` (`sources_add_sync_list_and_remove`), `app/test/playwright/specs/memory-v2.spec.ts` | ✅ | folder, file, link, github, rss, composio |
| 8.2.6 | Folder-source path picker | RU+VU | `crates/openhuman-app/src/directory_picker.rs`, `app/src/utils/tauriCommands/directoryPicker.test.ts` | ✅ | |
| 8.2.7 | Pack preview (Ask tab) and brain views | RU+RI+WD | `crates/openhuman-core/src/memory/lifecycle/views_tests.rs`, `crates/openhuman-core/src/memory/brain_tests.rs`, `tests/memory_v2_e2e.rs`, `app/test/playwright/specs/memory-v2.spec.ts` | ✅ | No `context.md`; pack never persisted in the transcript |
-| 8.2.8 | One-time import of previous (v1) memory | RU+RI+WD | `crates/openhuman-core/src/memory/import_tests.rs`, `tests/memory_v2_e2e.rs`, `app/test/playwright/specs/memory-v2.spec.ts` (`importing previous memory needs explicit consent`) | ✅ | Refused without consent |
+| 8.2.8 | One-time import of previous (v1) memory | RU+RI+WD | `crates/openhuman-core/src/memory/import_tests.rs`, `tests/memory_v2_e2e.rs`, `app/test/playwright/specs/memory-v2.spec.ts` (`importing previous memory needs explicit consent`), `app/src/components/memory/MemoryImportBanner.test.tsx` | ✅ | Refused without consent; stops (not skips) on exhausted credits or an unreachable engine; resumes on its own after the app quits; Resume button after an error |
| 8.2.9 | MCP memory tools | RU | `crates/openhuman-core/src/mcp/server/tools/` | ✅ | `memory.recall`, `memory.fetch`, `memory.list`, `memory.learn`, `memory.forget` |
| 8.2.10 | Memory UI chips and legacy redirects | VU+WD | `app/src/components/memory/*.test.tsx`, `app/test/playwright/specs/memory-v2.spec.ts` | ✅ | Engine, Ask, Explorer, Learnings, Conversations, Brain, Background, Settings; `/brain` and `/settings/memory-engine` redirect |