The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(memory): review round: gate the import retry; one retried read for the move
M3gA-Mind916598cf42ea
diff --git a/app/src/components/memory/MemoryImportBanner.test.tsx b/app/src/components/memory/MemoryImportBanner.test.tsxindex 528164bc66..e5537ef6f9 100644--- a/app/src/components/memory/MemoryImportBanner.test.tsx+++ b/app/src/components/memory/MemoryImportBanner.test.tsx@@ -217,6 +217,27 @@ describe('MemoryImportBanner', () => {expect(hoisted.mStart).not.toHaveBeenCalled();});+ it('organizes once the running import finishes', async () => {+ hoisted.status.mockResolvedValue({ state: { phase: 'running', imported: 2, total: 9 } });+ // Nothing to move until the import lands its items.+ hoisted.mScan.mockResolvedValue({ needed: false, shared: false });+ vi.useFakeTimers({ shouldAdvanceTime: true });+ renderWithProviders(<MemoryImportBanner engineLabel="TinyHumans" />);+ expect(await screen.findByTestId('memory-import-running')).toBeInTheDocument();+ expect(screen.queryByTestId('memory-migration-banner')).not.toBeInTheDocument();++ // The import finishes and the core starts the move.+ hoisted.status.mockResolvedValue({ state: { phase: 'done', imported: 9, total: 9 } });+ hoisted.mScan.mockResolvedValue({ needed: true, shared: false });+ hoisted.mStatus.mockResolvedValue(moving(3));+ await act(async () => {+ await vi.advanceTimersByTimeAsync(IMPORT_POLL_MS + 10);+ });+ expect(await screen.findByTestId('memory-migration-running')).toHaveTextContent('3');+ expect(screen.queryByTestId('memory-import-done')).not.toBeInTheDocument();+ expect(hoisted.mStart).not.toHaveBeenCalled();+ });+it('keeps the retry for refused items beside the move', async () => {hoisted.status.mockResolvedValue({state: { phase: 'done', imported: 7, total: 9, failed: 2 },@@ -362,6 +383,33 @@ describe('MemoryImportBanner', () => {expect(await screen.findByTestId('memory-import-error')).toBeInTheDocument();});+ it('offers nothing until the move’s status is known', async () => {+ hoisted.mScan.mockResolvedValue({ needed: true, shared: false });+ hoisted.mStatus.mockRejectedValueOnce(new Error('not ready')).mockResolvedValue(MOVE_IDLE);+ vi.useFakeTimers({ shouldAdvanceTime: true });+ renderWithProviders(<MemoryImportBanner engineLabel="TinyHumans" />);+ await waitFor(() => expect(hoisted.mStatus).toHaveBeenCalledTimes(1));+ expect(screen.queryByTestId('memory-migration-offer')).not.toBeInTheDocument();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(MIGRATION_IDLE_POLL_MS + 10);+ });+ expect(await screen.findByTestId('memory-migration-offer')).toBeInTheDocument();+ });++ it('keeps both retries when import and move each left items behind', async () => {+ hoisted.status.mockResolvedValue({+ state: { phase: 'done', imported: 7, total: 9, failed: 2 },+ });+ hoisted.mStatus.mockResolvedValue({+ state: { phase: 'cleaned', copied: 7, failures: [{ id: 'a', reason: 'x' }] },+ running: false,+ interrupted: false,+ });+ renderWithProviders(<MemoryImportBanner engineLabel="TinyHumans" />);+ expect(await screen.findByTestId('memory-migration-left')).toHaveTextContent('1');+ expect(screen.getByTestId('memory-import-retry-failed')).toBeInTheDocument();+ });+it('scans again after a failed scan', async () => {hoisted.mScan.mockRejectedValueOnce(new Error('not ready'))diff --git a/app/src/components/memory/MemoryImportBanner.tsx b/app/src/components/memory/MemoryImportBanner.tsxindex 717590d563..ce43bb59c6 100644--- a/app/src/components/memory/MemoryImportBanner.tsx+++ b/app/src/components/memory/MemoryImportBanner.tsx@@ -138,12 +138,18 @@ export default function MemoryImportBanner({ engineLabel }: MemoryImportBannerPrconst [takeoverOpen, setTakeoverOpen] = useState(false);const [mBusy, setMBusy] = useState(false);- // Bumped to scan again after a failed scan.+ // Every read of what is left to move goes through this one effect: at+ // mount, after a failed read (retried), when a run ends, and when the+ // import finishes. Bumping it re-runs the read and discards the answer of+ // the one it replaces.const [mScanAttempt, setMScanAttempt] = useState(0);+ const rescanMove = useCallback(() => setMScanAttempt(n => n + 1), []);useEffect(() => {let cancelled = false;let retry: ReturnType<typeof setTimeout> | undefined;- Promise.all([memoryMigrationScan(), memoryMigrationStatus().catch(() => null)])+ // Both answers or neither: an offer without a known status could start+ // a move that is already running.+ Promise.all([memoryMigrationScan(), memoryMigrationStatus()]).then(([found, current]) => {if (cancelled) return;mlog('scan: needed=%s shared=%s', found?.needed, found?.shared);@@ -154,14 +160,14 @@ export default function MemoryImportBanner({ engineLabel }: MemoryImportBannerPr// A transient failure must not hide the move for good: try again.mlog('scan failed: %o', err);if (!cancelled) {- retry = setTimeout(() => setMScanAttempt(n => n + 1), MIGRATION_IDLE_POLL_MS);+ retry = setTimeout(rescanMove, MIGRATION_IDLE_POLL_MS);}});return () => {cancelled = true;if (retry) clearTimeout(retry);};- }, [mScanAttempt]);+ }, [mScanAttempt, rescanMove]);const wasMoving = useRef(false);// One status request at a time: a slow answer must not land after, and@@ -174,7 +180,7 @@ export default function MemoryImportBanner({ engineLabel }: MemoryImportBannerPrconst next = await memoryMigrationStatus();setMStatus(next);// A run just ended: whether anything is still left to move changed.- if (wasMoving.current && !next.running) setMScan(await memoryMigrationScan());+ if (wasMoving.current && !next.running) rescanMove();wasMoving.current = next.running;} catch (err) {mlog('status failed: %o', err);@@ -182,7 +188,7 @@ export default function MemoryImportBanner({ engineLabel }: MemoryImportBannerPr} finally {mPolling.current = false;}- }, [t]);+ }, [t, rescanMove]);const moving = mStatus?.running ?? false;const moveOffered = mScan?.needed ?? false;@@ -233,22 +239,10 @@ export default function MemoryImportBanner({ engineLabel }: MemoryImportBannerPrconst importDone = state?.phase === 'done';// The core starts the move when the import finishes: look again, since the- // scan at mount may have found nothing to move before the import landed.+ // read at mount may have found nothing to move before the import landed.useEffect(() => {- if (!importDone) return;- let cancelled = false;- Promise.all([memoryMigrationScan(), memoryMigrationStatus()])- .then(([found, current]) => {- if (cancelled) return;- mlog('after import: needed=%s running=%s', found?.needed, current?.running);- setMScan(found ?? null);- setMStatus(current ?? null);- })- .catch(err => mlog('scan after import failed: %o', err));- return () => {- cancelled = true;- };- }, [importDone]);+ if (importDone) rescanMove();+ }, [importDone, rescanMove]);const mState = mStatus?.state;const left = (mState?.failures?.length ?? 0) + (mState?.incomplete?.length ?? 0);diff --git a/crates/openhuman-core/src/memory/import.rs b/crates/openhuman-core/src/memory/import.rsindex 5ea45290fa..8700c3fedd 100644--- a/crates/openhuman-core/src/memory/import.rs+++ b/crates/openhuman-core/src/memory/import.rs@@ -696,3 +696,7 @@ mod tests;#[cfg(test)]#[path = "import_recovery_tests.rs"]mod recovery_tests;++#[cfg(test)]+#[path = "import_organize_tests.rs"]+mod organize_tests;diff --git a/crates/openhuman-core/src/memory/import_organize_tests.rs b/crates/openhuman-core/src/memory/import_organize_tests.rsnew file mode 100644index 0000000000..e9c314eee6--- /dev/null+++ b/crates/openhuman-core/src/memory/import_organize_tests.rs@@ -0,0 +1,63 @@+//! Tests of the hand-off from the import to organizing memory: an import+//! counts as unfinished from its reservation, and a finished import starts+//! the move into the per-user tree.++use std::sync::Arc;++use tinymemory_api::MetaFilter;++use super::tests::{legacy_workspace, wait_until_settled};+use super::*;+use crate::memory::test_fixtures::{bind_reference, config_in, stored};++#[test]+fn an_import_counts_as_in_progress_from_its_reservation() {+ let tmp = tempfile::tempdir().unwrap();+ let config = config_in(&tmp);+ assert!(!in_progress(&config));+ // Reserved, still scanning the old store: no state written yet.+ RUNNING.lock().unwrap().insert(config.workspace_dir.clone());+ assert!(in_progress(&config));+ RUNNING.lock().unwrap().remove(&config.workspace_dir);+ assert!(!in_progress(&config));+}++#[tokio::test]+async fn a_finished_import_starts_organizing_into_the_per_user_tree() {+ let tmp = tempfile::tempdir().unwrap();+ let mut config = config_in(&tmp);+ let account = "0123456789abcdef01234567";+ // Signed in: the move needs the account's own root, and the switch+ // writes the account's config file.+ config.config_path = tmp.path().join("users").join(account).join("config.toml");+ std::fs::create_dir_all(config.config_path.parent().unwrap()).unwrap();+ config.save().await.unwrap();+ legacy_workspace(&config.workspace_dir);+ let legacy = bind_reference(&config);+ let tree = Arc::new(tinymemory_api::conformance::ReferenceEngine::new());+ crate::memory::engine::install_test_engine_for_root(+ &config.workspace_dir,+ Some(&format!("user:{account}")),+ tree.clone(),+ );++ start(&config, true).await.unwrap();+ assert_eq!(wait_until_settled(&config).await.phase, ImportPhase::Done);++ // The import's own task starts the move once it is done.+ let mut moved = None;+ for _ in 0..400 {+ let migration = crate::memory::layout_migration::status(&config).unwrap();+ if !migration.running+ && migration.state.phase == crate::memory::layout_migration::Phase::Cleaned+ {+ moved = Some(migration.state);+ break;+ }+ tokio::time::sleep(std::time::Duration::from_millis(25)).await;+ }+ let moved = moved.expect("the move never finished after the import");+ assert_eq!(moved.copied, 5);+ assert_eq!(stored(&tree, MetaFilter::default()).await.len(), 5);+ assert!(stored(&legacy, MetaFilter::default()).await.is_empty());+}diff --git a/crates/openhuman-core/src/memory/import_retry.rs b/crates/openhuman-core/src/memory/import_retry.rsindex 1cc9fba076..0b367ffd59 100644--- a/crates/openhuman-core/src/memory/import_retry.rs+++ b/crates/openhuman-core/src/memory/import_retry.rs@@ -11,7 +11,7 @@ use tinymemory_integrations::import::LegacyWorkspace;use super::{legacy_id, read_file, skips_item, status, with_retries, write_file, FailedItem, ImportFile,- PauseCheck, RUNNING,+ PauseCheck, RUNNING, START_GATE,};use crate::config::Config;use crate::memory::engine::{self, BoundEngine};@@ -44,10 +44,22 @@ pub(super) fn begin_retry() -> MemoryResult<ImportState> {let bound = engine::resolve(config).engine()?;let workspace_dir = config.workspace_dir.clone();- let claimed = RUNNING- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner)- .insert(workspace_dir.clone());+ let claimed = {+ // The same start gate as an import: a retry bound to the legacy tree+ // while it is being moved would leave its items behind there.+ let _gate = START_GATE+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ if crate::memory::layout_migration::service::is_running(config) {+ return Err(MemoryError::invalid(+ "memory is being organized; retry once that finishes",+ ));+ }+ RUNNING+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .insert(workspace_dir.clone())+ };if !claimed {return Ok(status(config));}diff --git a/crates/openhuman-core/src/memory/import_tests.rs b/crates/openhuman-core/src/memory/import_tests.rsindex 27241450e4..36d5d6181f 100644--- a/crates/openhuman-core/src/memory/import_tests.rs+++ b/crates/openhuman-core/src/memory/import_tests.rs@@ -252,58 +252,6 @@ async fn a_full_import_stores_every_item_and_finishes_done() {assert!(file_path(&config.workspace_dir).exists());}-#[test]-fn an_import_counts_as_in_progress_from_its_reservation() {- let tmp = tempfile::tempdir().unwrap();- let config = config_in(&tmp);- assert!(!in_progress(&config));- // Reserved, still scanning the old store: no state written yet.- RUNNING.lock().unwrap().insert(config.workspace_dir.clone());- assert!(in_progress(&config));- RUNNING.lock().unwrap().remove(&config.workspace_dir);- assert!(!in_progress(&config));-}--#[tokio::test]-async fn a_finished_import_starts_organizing_into_the_per_user_tree() {- let tmp = tempfile::tempdir().unwrap();- let mut config = config_in(&tmp);- let account = "0123456789abcdef01234567";- // Signed in: the move needs the account's own root, and the switch- // writes the account's config file.- config.config_path = tmp.path().join("users").join(account).join("config.toml");- std::fs::create_dir_all(config.config_path.parent().unwrap()).unwrap();- config.save().await.unwrap();- legacy_workspace(&config.workspace_dir);- let legacy = bind_reference(&config);- let tree = Arc::new(tinymemory_api::conformance::ReferenceEngine::new());- crate::memory::engine::install_test_engine_for_root(- &config.workspace_dir,- Some(&format!("user:{account}")),- tree.clone(),- );-- start(&config, true).await.unwrap();- assert_eq!(wait_until_settled(&config).await.phase, ImportPhase::Done);-- // The import's own task starts the move once it is done.- let mut moved = None;- for _ in 0..400 {- let migration = crate::memory::layout_migration::status(&config).unwrap();- if !migration.running- && migration.state.phase == crate::memory::layout_migration::Phase::Cleaned- {- moved = Some(migration.state);- break;- }- tokio::time::sleep(std::time::Duration::from_millis(25)).await;- }- let moved = moved.expect("the move never finished after the import");- assert_eq!(moved.copied, 5);- assert_eq!(stored(&tree, MetaFilter::default()).await.len(), 5);- assert!(stored(&legacy, MetaFilter::default()).await.is_empty());-}-#[tokio::test]async fn an_interrupted_import_resumes_from_its_checkpoint() {let tmp = tempfile::tempdir().unwrap();