Skip to content

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

fix(memory-sources): review follow-ups — one exit deadline, cleanup on error exits, honest zero-item chips

Shanu715c46c1ca1b
diff --git a/app/src-tauri/src/core_process.rs b/app/src-tauri/src/core_process.rs
index 1c1a0c8865..c6bd66e0d3 100644
--- a/app/src-tauri/src/core_process.rs
+++ b/app/src-tauri/src/core_process.rs
@@ -701,19 +701,27 @@ impl CoreProcessHandle {
/// Wait a bounded moment for the server task to finish on its own after
/// its token was cancelled, so the teardown inside it runs.
+ ///
+ /// The moment is sized from what that teardown is allowed to take, so the
+ /// abort below never lands in the middle of it: the memory exit budget
+ /// (`EXIT_BUDGET`, every driver and the hook registry on one deadline),
+ /// the ollama cleanup after it in `serve_http` (2 s), and half a second
+ /// for the drain itself. Typical quits finish in milliseconds; the budget
+ /// is only what a wedged store or daemon may cost.
async fn drain_task_briefly(&self) {
- const BUDGET: Duration = Duration::from_millis(2_500);
+ const AFTER_MEMORY: Duration = Duration::from_millis(2_500);
+ let budget = openhuman_core::openhuman::memory::exit::EXIT_BUDGET + AFTER_MEMORY;
let mut task_guard = self.task.lock().await;
let Some(task) = task_guard.as_mut() else {
return;
};
- match timeout(BUDGET, task).await {
+ match timeout(budget, task).await {
Ok(_) => {
task_guard.take();
log::info!("[core] embedded core server task drained on app shutdown");
}
Err(_) => log::warn!(
- "[core] embedded core server task did not drain within {BUDGET:?}; aborting"
+ "[core] embedded core server task did not drain within {budget:?}; aborting"
),
}
}
diff --git a/app/src/components/intelligence/MemorySourceRow.tsx b/app/src/components/intelligence/MemorySourceRow.tsx
index 933c9a863e..b06ba5d3da 100644
--- a/app/src/components/intelligence/MemorySourceRow.tsx
+++ b/app/src/components/intelligence/MemorySourceRow.tsx
@@ -67,15 +67,14 @@ interface SourceRowProps {
}
/**
- * The line shown beside a successful count when the run stopped short. A
- * spent budget with a zero count is already the main text (there is nothing
- * else to say), so it is not repeated here.
+ * The line shown beside a successful count when the run stopped short. With a
+ * zero count the chip itself says why the run stopped (there is no count to
+ * show instead), so the note is never repeated beside it.
*/
function syncNoteKey(result: SyncResult): string | null {
+ if (!(result.items && result.items > 0)) return null;
if (result.note === 'more_pending') return 'memorySources.sync.morePending';
- if (result.note === 'budget_spent' && result.items && result.items > 0) {
- return 'memorySources.sync.budgetSpent';
- }
+ if (result.note === 'budget_spent') return 'memorySources.sync.budgetSpent';
return null;
}
@@ -185,7 +184,9 @@ export function MemorySourceRow({
? `${result.items.toLocaleString()} ${t('memorySources.sync.itemsSynced')}`
: result.note === 'budget_spent'
? t('memorySources.sync.budgetSpent')
- : t('memorySources.sync.upToDate')}
+ : result.note === 'more_pending'
+ ? t('memorySources.sync.morePending')
+ : t('memorySources.sync.upToDate')}
</span>
{noteKey && (
<span
diff --git a/app/src/components/intelligence/MemorySourcesRegistry.tsx b/app/src/components/intelligence/MemorySourcesRegistry.tsx
index b6643c91a2..c07cd830a6 100644
--- a/app/src/components/intelligence/MemorySourcesRegistry.tsx
+++ b/app/src/components/intelligence/MemorySourcesRegistry.tsx
@@ -211,17 +211,21 @@ export function MemorySourcesRegistry({
next.set(rowId, { kind: 'success', items, reason: null, note });
return next;
});
- const counted =
- items && items > 0
- ? `${items} ${tt('memorySources.sync.itemsSynced')}`
- : note === 'budget_spent'
- ? tt('memorySources.sync.budgetSpent')
+ // A zero count is not "up to date" when the run stopped short: the
+ // reason it stopped is the whole message then, not a suffix.
+ const hasItems = Boolean(items && items > 0);
+ const counted = hasItems
+ ? `${items} ${tt('memorySources.sync.itemsSynced')}`
+ : note === 'budget_spent'
+ ? tt('memorySources.sync.budgetSpent')
+ : note === 'more_pending'
+ ? tt('memorySources.sync.morePending')
: tt('memorySources.sync.upToDate');
onToastRef.current?.({
type: note === 'budget_spent' ? 'warning' : 'success',
title: `${tt('memorySources.sync.completeTitle')} ${label}`,
message:
- note === 'more_pending'
+ hasItems && note === 'more_pending'
? `${counted} — ${tt('memorySources.sync.morePending')}`
: counted,
});
diff --git a/app/src/components/intelligence/__tests__/MemorySourcesRegistry.sync.test.tsx b/app/src/components/intelligence/__tests__/MemorySourcesRegistry.sync.test.tsx
index d58a8aa2f5..79dfbbc914 100644
--- a/app/src/components/intelligence/__tests__/MemorySourcesRegistry.sync.test.tsx
+++ b/app/src/components/intelligence/__tests__/MemorySourcesRegistry.sync.test.tsx
@@ -654,4 +654,32 @@ describe('MemorySourcesRegistry', () => {
expect(screen.queryByText('memorySources.repair.confirm')).not.toBeInTheDocument();
expect(backfill).toHaveBeenCalledTimes(1);
});
+ it('says "more to sync" — not "Up to date" — when zero items arrived because the run stopped at its cap', async () => {
+ // A capped run can write nothing (everything on the page was already
+ // ingested) and still have more to read. Zero + more-pending used to
+ // render as "Up to date" beside a "more to sync" note — contradictory.
+ const sources = [makeSource('src-zero-more')];
+ listMemorySources.mockResolvedValue(sources);
+ memorySourcesStatusList.mockResolvedValue([]);
+
+ renderWithProviders(<MemorySourcesRegistry pollIntervalMs={0} />);
+ await waitFor(() => expect(screen.getByText('Source src-zero-more')).toBeInTheDocument());
+
+ act(() => {
+ window.dispatchEvent(
+ makeSyncStageEvent({
+ stage: 'completed',
+ source_id: 'src-zero-more',
+ detail: 'ingested 0 item(s), more pending — Sync again to continue',
+ })
+ );
+ });
+
+ await waitFor(() => {
+ const chip = screen.getByTestId('memory-source-result-src-zero-more');
+ expect(chip).toHaveTextContent('memorySources.sync.morePending');
+ expect(chip).not.toHaveTextContent('memorySources.sync.upToDate');
+ });
+ expect(screen.queryByTestId('memory-source-note-src-zero-more')).not.toBeInTheDocument();
+ });
});
diff --git a/app/src/lib/i18n/ar.ts b/app/src/lib/i18n/ar.ts
index 956b3db123..fe1c7ff736 100644
--- a/app/src/lib/i18n/ar.ts
+++ b/app/src/lib/i18n/ar.ts
@@ -2576,8 +2576,8 @@ const messages: TranslationMap = {
'memorySources.sync.itemsSynced': 'عناصر تمت مزامنتها',
'memorySources.sync.upToDate': 'محدّث',
'memorySources.sync.failedLabel': 'فشل',
- 'memorySources.sync.morePending': 'يوجد المزيد للمزامنة — انقر على «مزامنة» مرة أخرى',
- 'memorySources.sync.budgetSpent': 'استُنفدت ميزانية الطلبات لليوم — حاول مرة أخرى غدًا',
+ 'memorySources.sync.morePending': 'يوجد المزيد للمزامنة. انقر على «مزامنة» مرة أخرى',
+ 'memorySources.sync.budgetSpent': 'استُنفدت ميزانية الطلبات لليوم. حاول مرة أخرى غدًا',
'time.justNow': 'للتو',
'time.secondsAgoSuffix': 'ثانية مضت',
'time.minutesAgoSuffix': 'دقيقة مضت',
@@ -2625,10 +2625,10 @@ const messages: TranslationMap = {
'حُفظ ما يصل إلى {scanned} مستندًا متزامنًا قبل إصلاح الأرشفة في شجرة الذاكرة، وهي غير مرئية في رسم الذاكرة البياني. تستهلك أرشفتها رصيد التضمين. تُتخطى المستندات الموجودة أصلًا في الشجرة.',
'memorySources.repair.confirm': 'إصلاح',
'memorySources.repair.cancel': 'ليس الآن',
- 'memorySources.repair.nothing': 'لا شيء لإصلاحه — لا توجد مستندات متزامنة بانتظار الأرشفة.',
+ 'memorySources.repair.nothing': 'لا شيء لإصلاحه. لا توجد مستندات متزامنة بانتظار الأرشفة.',
'memorySources.repair.success':
'تمت أرشفة {ingested} في شجرة الذاكرة ({already} موجودة مسبقًا، {skipped} تم تخطيها).',
- 'memorySources.repair.morePending': 'بقي المزيد — انقر على «إصلاح الذكريات الأقدم» مرة أخرى.',
+ 'memorySources.repair.morePending': 'بقي المزيد. انقر على «إصلاح الذكريات الأقدم» مرة أخرى.',
'memorySources.repair.failed': 'تعذّر إصلاح الذكريات الأقدم.',
'memorySources.settings.button': 'الإعدادات',
'memorySources.settings.title': 'إعدادات المزامنة',
diff --git a/app/src/lib/i18n/bn.ts b/app/src/lib/i18n/bn.ts
index 1a58768314..6ae2a65470 100644
--- a/app/src/lib/i18n/bn.ts
+++ b/app/src/lib/i18n/bn.ts
@@ -2638,8 +2638,8 @@ const messages: TranslationMap = {
'memorySources.sync.itemsSynced': 'আইটেম সিঙ্ক হয়েছে',
'memorySources.sync.upToDate': 'হালনাগাদ আছে',
'memorySources.sync.failedLabel': 'ব্যর্থ',
- 'memorySources.sync.morePending': 'আরও সিঙ্ক বাকি আছে — আবার Sync-এ ক্লিক করুন',
- 'memorySources.sync.budgetSpent': 'আজকের অনুরোধের বাজেট শেষ — আগামীকাল আবার চেষ্টা করুন',
+ 'memorySources.sync.morePending': 'আরও সিঙ্ক বাকি আছে। আবার Sync-এ ক্লিক করুন',
+ 'memorySources.sync.budgetSpent': 'আজকের অনুরোধের বাজেট শেষ। আগামীকাল আবার চেষ্টা করুন',
'time.justNow': 'এইমাত্র',
'time.secondsAgoSuffix': 'সেকেন্ড আগে',
'time.minutesAgoSuffix': 'মিনিট আগে',
@@ -2688,10 +2688,10 @@ const messages: TranslationMap = {
'memorySources.repair.confirm': 'মেরামত করুন',
'memorySources.repair.cancel': 'এখন নয়',
'memorySources.repair.nothing':
- 'মেরামতের কিছু নেই — কোনো সিঙ্ক করা নথি ফাইল হওয়ার অপেক্ষায় নেই।',
+ 'মেরামতের কিছু নেই। কোনো সিঙ্ক করা নথি ফাইল হওয়ার অপেক্ষায় নেই।',
'memorySources.repair.success':
'{ingested}টি মেমোরি ট্রিতে ফাইল করা হয়েছে ({already}টি আগে থেকেই ছিল, {skipped}টি বাদ দেওয়া হয়েছে)।',
- 'memorySources.repair.morePending': 'আরও বাকি আছে — আবার পুরোনো স্মৃতি মেরামত করুন-এ ক্লিক করুন।',
+ 'memorySources.repair.morePending': 'আরও বাকি আছে। আবার পুরোনো স্মৃতি মেরামত করুন-এ ক্লিক করুন।',
'memorySources.repair.failed': 'পুরোনো স্মৃতি মেরামত করা যায়নি।',
'memorySources.settings.button': 'সেটিংস',
'memorySources.settings.title': 'সিঙ্ক সেটিংস',
diff --git a/app/src/lib/i18n/de.ts b/app/src/lib/i18n/de.ts
index 8ea0c6438b..8f5fafdc15 100644
--- a/app/src/lib/i18n/de.ts
+++ b/app/src/lib/i18n/de.ts
@@ -2713,9 +2713,9 @@ const messages: TranslationMap = {
'memorySources.sync.itemsSynced': 'Elemente synchronisiert',
'memorySources.sync.upToDate': 'Aktuell',
'memorySources.sync.failedLabel': 'Fehlgeschlagen',
- 'memorySources.sync.morePending': 'Mehr zu synchronisieren — erneut auf Synchronisieren klicken',
+ 'memorySources.sync.morePending': 'Mehr zu synchronisieren. Erneut auf Synchronisieren klicken',
'memorySources.sync.budgetSpent':
- 'Das heutige Anfragebudget ist aufgebraucht — morgen erneut versuchen',
+ 'Das heutige Anfragebudget ist aufgebraucht. Morgen erneut versuchen',
'time.justNow': 'gerade eben',
'time.secondsAgoSuffix': 'vor {count} Sek.',
'time.minutesAgoSuffix': 'vor {count} Min.',
@@ -2766,11 +2766,11 @@ const messages: TranslationMap = {
'memorySources.repair.confirm': 'Reparieren',
'memorySources.repair.cancel': 'Nicht jetzt',
'memorySources.repair.nothing':
- 'Nichts zu reparieren — keine synchronisierten Dokumente warten auf die Ablage.',
+ 'Nichts zu reparieren. Keine synchronisierten Dokumente warten auf die Ablage.',
'memorySources.repair.success':
'{ingested} im Gedächtnisbaum abgelegt ({already} bereits vorhanden, {skipped} übersprungen).',
'memorySources.repair.morePending':
- 'Es sind noch weitere übrig — erneut auf „Ältere Erinnerungen reparieren“ klicken.',
+ 'Es sind noch weitere übrig. Erneut auf „Ältere Erinnerungen reparieren“ klicken.',
'memorySources.repair.failed': 'Ältere Erinnerungen konnten nicht repariert werden.',
'memorySources.settings.button': 'Einstellungen',
'memorySources.settings.title': 'Synchronisierungseinstellungen',
diff --git a/app/src/lib/i18n/en.ts b/app/src/lib/i18n/en.ts
index 454dec5c17..8e816cab95 100644
--- a/app/src/lib/i18n/en.ts
+++ b/app/src/lib/i18n/en.ts
@@ -3005,8 +3005,8 @@ const en: TranslationMap = {
'memorySources.sync.itemsSynced': 'items synced',
'memorySources.sync.upToDate': 'Up to date',
'memorySources.sync.failedLabel': 'Failed',
- 'memorySources.sync.morePending': 'More to sync — click Sync again',
- 'memorySources.sync.budgetSpent': "Today's request budget is spent — try again tomorrow",
+ 'memorySources.sync.morePending': 'More to sync. Click Sync again',
+ 'memorySources.sync.budgetSpent': "Today's request budget is spent. Try again tomorrow",
'time.justNow': 'just now',
'time.secondsAgoSuffix': 's ago',
'time.minutesAgoSuffix': 'm ago',
@@ -3054,11 +3054,10 @@ const en: TranslationMap = {
'Up to {scanned} synced documents were stored before memory-tree filing was fixed and are invisible to the memory graph. Filing them uses embedding credits. Documents already in the tree are skipped.',
'memorySources.repair.confirm': 'Repair',
'memorySources.repair.cancel': 'Not now',
- 'memorySources.repair.nothing':
- 'Nothing to repair — no synced documents are waiting to be filed.',
+ 'memorySources.repair.nothing': 'Nothing to repair. No synced documents are waiting to be filed.',
'memorySources.repair.success':
'Filed {ingested} into the memory tree ({already} already there, {skipped} skipped).',
- 'memorySources.repair.morePending': 'More remain — click Repair older memories again.',
+ 'memorySources.repair.morePending': 'More remain. Click Repair older memories again.',
'memorySources.repair.failed': 'Could not repair older memories.',
'memorySources.settings.button': 'Settings',
'memorySources.settings.title': 'Sync settings',
diff --git a/app/src/lib/i18n/es.ts b/app/src/lib/i18n/es.ts
index 3c48785ee6..13a9bb57c8 100644
--- a/app/src/lib/i18n/es.ts
+++ b/app/src/lib/i18n/es.ts
@@ -2690,9 +2690,9 @@ const messages: TranslationMap = {
'memorySources.sync.itemsSynced': 'elementos sincronizados',
'memorySources.sync.upToDate': 'Actualizado',
'memorySources.sync.failedLabel': 'Fallido',
- 'memorySources.sync.morePending': 'Queda más por sincronizar — pulsa Sincronizar de nuevo',
+ 'memorySources.sync.morePending': 'Queda más por sincronizar. Pulsa Sincronizar de nuevo',
'memorySources.sync.budgetSpent':
- 'El presupuesto de solicitudes de hoy se ha agotado — inténtalo mañana',
+ 'El presupuesto de solicitudes de hoy se ha agotado. Inténtalo mañana',
'time.justNow': 'ahora mismo',
'time.secondsAgoSuffix': 's',
'time.minutesAgoSuffix': 'min',
@@ -2744,10 +2744,10 @@ const messages: TranslationMap = {
'memorySources.repair.confirm': 'Reparar',
'memorySources.repair.cancel': 'Ahora no',
'memorySources.repair.nothing':
- 'Nada que reparar — ningún documento sincronizado está pendiente de archivar.',
+ 'Nada que reparar. Ningún documento sincronizado está pendiente de archivar.',
'memorySources.repair.success':
'{ingested} archivados en el árbol de memoria ({already} ya estaban, {skipped} omitidos).',
- 'memorySources.repair.morePending': 'Quedan más — pulsa Reparar recuerdos antiguos de nuevo.',
+ 'memorySources.repair.morePending': 'Quedan más. Pulsa Reparar recuerdos antiguos de nuevo.',
'memorySources.repair.failed': 'No se pudieron reparar los recuerdos antiguos.',
'memorySources.settings.button': 'Configuración',
'memorySources.settings.title': 'Configuración de sincronización',
diff --git a/app/src/lib/i18n/fr.ts b/app/src/lib/i18n/fr.ts
index e8127c0bf2..557ff3bdbe 100644
--- a/app/src/lib/i18n/fr.ts
+++ b/app/src/lib/i18n/fr.ts
@@ -2713,8 +2713,8 @@ const messages: TranslationMap = {
'memorySources.sync.upToDate': 'À jour',
'memorySources.sync.failedLabel': 'Échec',
'memorySources.sync.morePending':
- 'Il reste des éléments à synchroniser — cliquez à nouveau sur Synchroniser',
- 'memorySources.sync.budgetSpent': 'Le budget de requêtes du jour est épuisé — réessayez demain',
+ 'Il reste des éléments à synchroniser. Cliquez à nouveau sur Synchroniser',
+ 'memorySources.sync.budgetSpent': 'Le budget de requêtes du jour est épuisé. Réessayez demain',
'time.justNow': "à l'instant",
'time.secondsAgoSuffix': 's',
'time.minutesAgoSuffix': 'min',
@@ -2766,11 +2766,11 @@ const messages: TranslationMap = {
'memorySources.repair.confirm': 'Réparer',
'memorySources.repair.cancel': 'Pas maintenant',
'memorySources.repair.nothing':
- "Rien à réparer — aucun document synchronisé n'attend d'être classé.",
+ "Rien à réparer. Aucun document synchronisé n'attend d'être classé.",
'memorySources.repair.success':
"{ingested} classés dans l'arbre de mémoire ({already} déjà présents, {skipped} ignorés).",
'memorySources.repair.morePending':
- 'Il en reste — cliquez à nouveau sur Réparer les souvenirs anciens.',
+ 'Il en reste. Cliquez à nouveau sur Réparer les souvenirs anciens.',
'memorySources.repair.failed': 'Impossible de réparer les souvenirs anciens.',
'memorySources.settings.title': 'Paramètres de synchronisation',
'memorySources.settings.maxPrs': 'Nombre maximal de pull requests',
diff --git a/app/src/lib/i18n/hi.ts b/app/src/lib/i18n/hi.ts
index 8d6195f124..f2cb6c40f2 100644
--- a/app/src/lib/i18n/hi.ts
+++ b/app/src/lib/i18n/hi.ts
@@ -2638,8 +2638,8 @@ const messages: TranslationMap = {
'memorySources.sync.itemsSynced': 'आइटम सिंक हुए',
'memorySources.sync.upToDate': 'अद्यतित',
'memorySources.sync.failedLabel': 'विफल',
- 'memorySources.sync.morePending': 'और सिंक बाकी है — फिर से Sync पर क्लिक करें',
- 'memorySources.sync.budgetSpent': 'आज का अनुरोध बजट खत्म हो गया है — कल फिर कोशिश करें',
+ 'memorySources.sync.morePending': 'और सिंक बाकी है। फिर से Sync पर क्लिक करें',
+ 'memorySources.sync.budgetSpent': 'आज का अनुरोध बजट खत्म हो गया है। कल फिर कोशिश करें',
'time.justNow': 'अभी',
'time.secondsAgoSuffix': 'सेकंड पहले',
'time.minutesAgoSuffix': 'मिनट पहले',
@@ -2689,10 +2689,10 @@ const messages: TranslationMap = {
'memorySources.repair.confirm': 'सुधारें',
'memorySources.repair.cancel': 'अभी नहीं',
'memorySources.repair.nothing':
- 'सुधारने के लिए कुछ नहीं — कोई सिंक किया गया दस्तावेज़ फाइल होने की प्रतीक्षा में नहीं है।',
+ 'सुधारने के लिए कुछ नहीं। कोई सिंक किया गया दस्तावेज़ फाइल होने की प्रतीक्षा में नहीं है।',
'memorySources.repair.success':
'{ingested} मेमोरी ट्री में फाइल किए गए ({already} पहले से थे, {skipped} छोड़े गए)।',
- 'memorySources.repair.morePending': 'और बाकी हैं — पुरानी यादें सुधारें पर फिर से क्लिक करें।',
+ 'memorySources.repair.morePending': 'और बाकी हैं। पुरानी यादें सुधारें पर फिर से क्लिक करें।',
'memorySources.repair.failed': 'पुरानी यादें सुधारी नहीं जा सकीं।',
'memorySources.settings.button': 'सेटिंग',
'memorySources.settings.title': 'सिंक सेटिंग',
diff --git a/app/src/lib/i18n/id.ts b/app/src/lib/i18n/id.ts
index 1ec0638d3f..6a29e24434 100644
--- a/app/src/lib/i18n/id.ts
+++ b/app/src/lib/i18n/id.ts
@@ -2650,8 +2650,8 @@ const messages: TranslationMap = {
'memorySources.sync.itemsSynced': 'item tersinkron',
'memorySources.sync.upToDate': 'Sudah terbaru',
'memorySources.sync.failedLabel': 'Gagal',
- 'memorySources.sync.morePending': 'Masih ada yang perlu disinkronkan — klik Sinkronkan lagi',
- 'memorySources.sync.budgetSpent': 'Anggaran permintaan hari ini sudah habis — coba lagi besok',
+ 'memorySources.sync.morePending': 'Masih ada yang perlu disinkronkan. Klik Sinkronkan lagi',
+ 'memorySources.sync.budgetSpent': 'Anggaran permintaan hari ini sudah habis. Coba lagi besok',
'time.justNow': 'baru saja',
'time.secondsAgoSuffix': 'd lalu',
'time.minutesAgoSuffix': 'm lalu',
@@ -2701,10 +2701,10 @@ const messages: TranslationMap = {
'memorySources.repair.confirm': 'Perbaiki',
'memorySources.repair.cancel': 'Nanti saja',
'memorySources.repair.nothing':
- 'Tidak ada yang perlu diperbaiki — tidak ada dokumen tersinkron yang menunggu diarsipkan.',
+ 'Tidak ada yang perlu diperbaiki. Tidak ada dokumen tersinkron yang menunggu diarsipkan.',
'memorySources.repair.success':
'{ingested} diarsipkan ke pohon memori ({already} sudah ada, {skipped} dilewati).',
- 'memorySources.repair.morePending': 'Masih ada sisa — klik Perbaiki memori lama lagi.',
+ 'memorySources.repair.morePending': 'Masih ada sisa. Klik Perbaiki memori lama lagi.',
'memorySources.repair.failed': 'Tidak dapat memperbaiki memori lama.',
'memorySources.settings.button': 'Pengaturan',
'memorySources.settings.title': 'Pengaturan sinkronisasi',
diff --git a/app/src/lib/i18n/it.ts b/app/src/lib/i18n/it.ts
index e73e069478..3f9a9e9487 100644
--- a/app/src/lib/i18n/it.ts
+++ b/app/src/lib/i18n/it.ts
@@ -2688,8 +2688,8 @@ const messages: TranslationMap = {
'memorySources.sync.itemsSynced': 'elementi sincronizzati',
'memorySources.sync.upToDate': 'Aggiornato',
'memorySources.sync.failedLabel': 'Non riuscito',
- 'memorySources.sync.morePending': 'Altro da sincronizzare — fai di nuovo clic su Sincronizza',
- 'memorySources.sync.budgetSpent': 'Il budget di richieste di oggi è esaurito — riprova domani',
+ 'memorySources.sync.morePending': 'Altro da sincronizzare. Fai di nuovo clic su Sincronizza',
+ 'memorySources.sync.budgetSpent': 'Il budget di richieste di oggi è esaurito. Riprova domani',
'time.justNow': 'proprio ora',
'time.secondsAgoSuffix': 's fa',
'time.minutesAgoSuffix': 'min fa',
@@ -2740,11 +2740,11 @@ const messages: TranslationMap = {
'memorySources.repair.confirm': 'Ripara',
'memorySources.repair.cancel': 'Non ora',
'memorySources.repair.nothing':
- 'Niente da riparare — nessun documento sincronizzato è in attesa di archiviazione.',
+ 'Niente da riparare. Nessun documento sincronizzato è in attesa di archiviazione.',
'memorySources.repair.success':
"{ingested} archiviati nell'albero della memoria ({already} già presenti, {skipped} saltati).",
'memorySources.repair.morePending':
- 'Ne restano altri — fai di nuovo clic su Ripara i ricordi meno recenti.',
+ 'Ne restano altri. Fai di nuovo clic su Ripara i ricordi meno recenti.',
'memorySources.repair.failed': 'Impossibile riparare i ricordi meno recenti.',
'memorySources.settings.button': 'Impostazioni',
'memorySources.settings.title': 'Impostazioni di sincronizzazione',
diff --git a/app/src/lib/i18n/ko.ts b/app/src/lib/i18n/ko.ts
index 8948a93ac3..2a8e01ce65 100644
--- a/app/src/lib/i18n/ko.ts
+++ b/app/src/lib/i18n/ko.ts
@@ -2605,8 +2605,8 @@ const messages: TranslationMap = {
'memorySources.sync.itemsSynced': '항목 동기화됨',
'memorySources.sync.upToDate': '최신 상태',
'memorySources.sync.failedLabel': '실패',
- 'memorySources.sync.morePending': '동기화할 항목이 더 있습니다 — 동기화를 다시 클릭하세요',
- 'memorySources.sync.budgetSpent': '오늘의 요청 한도를 모두 사용했습니다 — 내일 다시 시도하세요',
+ 'memorySources.sync.morePending': '동기화할 항목이 더 있습니다. 동기화를 다시 클릭하세요',
+ 'memorySources.sync.budgetSpent': '오늘의 요청 한도를 모두 사용했습니다. 내일 다시 시도하세요',
'time.justNow': '방금 전',
'time.secondsAgoSuffix': '초 전',
'time.minutesAgoSuffix': '분 전',
@@ -2656,10 +2656,10 @@ const messages: TranslationMap = {
'memorySources.repair.confirm': '복구',
'memorySources.repair.cancel': '나중에',
'memorySources.repair.nothing':
- '복구할 항목이 없습니다 — 정리를 기다리는 동기화된 문서가 없습니다.',
+ '복구할 항목이 없습니다. 정리를 기다리는 동기화된 문서가 없습니다.',
'memorySources.repair.success':
'{ingested}개를 메모리 트리에 정리했습니다 ({already}개 이미 있음, {skipped}개 건너뜀).',
- 'memorySources.repair.morePending': '남은 항목이 있습니다 — 이전 기억 복구를 다시 클릭하세요.',
+ 'memorySources.repair.morePending': '남은 항목이 있습니다. 이전 기억 복구를 다시 클릭하세요.',
'memorySources.repair.failed': '이전 기억을 복구하지 못했습니다.',
'memorySources.settings.button': '설정',
'memorySources.settings.title': '동기화 설정',
diff --git a/app/src/lib/i18n/pl.ts b/app/src/lib/i18n/pl.ts
index 2f0431d143..9dfb955250 100644
--- a/app/src/lib/i18n/pl.ts
+++ b/app/src/lib/i18n/pl.ts
@@ -2669,8 +2669,8 @@ const messages: TranslationMap = {
'memorySources.sync.itemsSynced': 'zsynchronizowanych elementów',
'memorySources.sync.upToDate': 'Aktualne',
'memorySources.sync.failedLabel': 'Niepowodzenie',
- 'memorySources.sync.morePending': 'Jest więcej do synchronizacji — kliknij Synchronizuj ponownie',
- 'memorySources.sync.budgetSpent': 'Dzisiejszy limit zapytań został wyczerpany — spróbuj jutro',
+ 'memorySources.sync.morePending': 'Jest więcej do synchronizacji. Kliknij Synchronizuj ponownie',
+ 'memorySources.sync.budgetSpent': 'Dzisiejszy limit zapytań został wyczerpany. Spróbuj jutro',
'time.justNow': 'przed chwilą',
'time.secondsAgoSuffix': 's temu',
'time.minutesAgoSuffix': 'min temu',
@@ -2722,11 +2722,11 @@ const messages: TranslationMap = {
'memorySources.repair.confirm': 'Napraw',
'memorySources.repair.cancel': 'Nie teraz',
'memorySources.repair.nothing':
- 'Nie ma nic do naprawy — żadne zsynchronizowane dokumenty nie czekają na skatalogowanie.',
+ 'Nie ma nic do naprawy. Żadne zsynchronizowane dokumenty nie czekają na skatalogowanie.',
'memorySources.repair.success':
'Skatalogowano {ingested} w drzewie pamięci ({already} już było, {skipped} pominięto).',
'memorySources.repair.morePending':
- 'Zostało więcej — kliknij ponownie Napraw starsze wspomnienia.',
+ 'Zostało więcej. Kliknij ponownie Napraw starsze wspomnienia.',
'memorySources.repair.failed': 'Nie udało się naprawić starszych wspomnień.',
'memorySources.settings.button': 'Ustawienia',
'memorySources.settings.title': 'Ustawienia synchronizacji',
diff --git a/app/src/lib/i18n/pt.ts b/app/src/lib/i18n/pt.ts
index 04b122ddb5..968177ecbc 100644
--- a/app/src/lib/i18n/pt.ts
+++ b/app/src/lib/i18n/pt.ts
@@ -2686,9 +2686,9 @@ const messages: TranslationMap = {
'memorySources.sync.itemsSynced': 'itens sincronizados',
'memorySources.sync.upToDate': 'Atualizado',
'memorySources.sync.failedLabel': 'Falhou',
- 'memorySources.sync.morePending': 'Há mais para sincronizar — clique em Sincronizar novamente',
+ 'memorySources.sync.morePending': 'Há mais para sincronizar. Clique em Sincronizar novamente',
'memorySources.sync.budgetSpent':
- 'O orçamento de solicitações de hoje acabou — tente novamente amanhã',
+ 'O orçamento de solicitações de hoje acabou. Tente novamente amanhã',
'time.justNow': 'agora mesmo',
'time.secondsAgoSuffix': 's atrás',
'time.minutesAgoSuffix': 'min atrás',
@@ -2739,11 +2739,11 @@ const messages: TranslationMap = {
'memorySources.repair.confirm': 'Reparar',
'memorySources.repair.cancel': 'Agora não',
'memorySources.repair.nothing':
- 'Nada a reparar — nenhum documento sincronizado aguarda arquivamento.',
+ 'Nada a reparar. Nenhum documento sincronizado aguarda arquivamento.',
'memorySources.repair.success':
'{ingested} arquivados na árvore de memória ({already} já existentes, {skipped} ignorados).',
'memorySources.repair.morePending':
- 'Ainda restam mais — clique em Reparar memórias antigas novamente.',
+ 'Ainda restam mais. Clique em Reparar memórias antigas novamente.',
'memorySources.repair.failed': 'Não foi possível reparar as memórias antigas.',
'memorySources.settings.button': 'Configurações',
'memorySources.settings.title': 'Configurações de sincronização',
diff --git a/app/src/lib/i18n/ru.ts b/app/src/lib/i18n/ru.ts
index a8099a9a47..a93515fe9b 100644
--- a/app/src/lib/i18n/ru.ts
+++ b/app/src/lib/i18n/ru.ts
@@ -2657,9 +2657,8 @@ const messages: TranslationMap = {
'memorySources.sync.itemsSynced': 'элементов синхронизировано',
'memorySources.sync.upToDate': 'Актуально',
'memorySources.sync.failedLabel': 'Не удалось',
- 'memorySources.sync.morePending':
- 'Есть что синхронизировать — нажмите «Синхронизировать» ещё раз',
- 'memorySources.sync.budgetSpent': 'Дневной лимит запросов исчерпан — попробуйте завтра',
+ 'memorySources.sync.morePending': 'Есть что синхронизировать. Нажмите «Синхронизировать» ещё раз',
+ 'memorySources.sync.budgetSpent': 'Дневной лимит запросов исчерпан. Попробуйте завтра',
'time.justNow': 'только что',
'time.secondsAgoSuffix': 'с назад',
'time.minutesAgoSuffix': 'мин назад',
@@ -2712,11 +2711,11 @@ const messages: TranslationMap = {
'memorySources.repair.confirm': 'Восстановить',
'memorySources.repair.cancel': 'Не сейчас',
'memorySources.repair.nothing':
- 'Нечего восстанавливать — нет синхронизированных документов, ожидающих размещения.',
+ 'Нечего восстанавливать. Нет синхронизированных документов, ожидающих размещения.',
'memorySources.repair.success':
'Размещено в дереве памяти: {ingested} ({already} уже было, {skipped} пропущено).',
'memorySources.repair.morePending':
- 'Остались ещё — нажмите «Восстановить старые воспоминания» снова.',
+ 'Остались ещё. Нажмите «Восстановить старые воспоминания» снова.',
'memorySources.repair.failed': 'Не удалось восстановить старые воспоминания.',
'memorySources.settings.button': 'Настройки',
'memorySources.settings.title': 'Настройки синхронизации',
diff --git a/app/src/lib/i18n/zh-CN.ts b/app/src/lib/i18n/zh-CN.ts
index ae1cf60872..ed2129d007 100644
--- a/app/src/lib/i18n/zh-CN.ts
+++ b/app/src/lib/i18n/zh-CN.ts
@@ -2488,8 +2488,8 @@ const messages: TranslationMap = {
'memorySources.sync.itemsSynced': '项已同步',
'memorySources.sync.upToDate': '已是最新',
'memorySources.sync.failedLabel': '失败',
- 'memorySources.sync.morePending': '还有更多待同步 — 请再次点击“同步”',
- 'memorySources.sync.budgetSpent': '今日请求额度已用完 — 请明天再试',
+ 'memorySources.sync.morePending': '还有更多待同步。请再次点击“同步”',
+ 'memorySources.sync.budgetSpent': '今日请求额度已用完。请明天再试',
'time.justNow': '刚刚',
'time.secondsAgoSuffix': '秒前',
'time.minutesAgoSuffix': '分钟前',
@@ -2534,13 +2534,13 @@ const messages: TranslationMap = {
'memorySources.repair.button': '修复较早的记忆',
'memorySources.repair.title': '要修复较早的记忆吗?',
'memorySources.repair.message':
- '最多 {scanned} 个已同步的文档在记忆树归档修复之前保存,因此不会显示在记忆图谱中。归档它们会消耗嵌入额度。已在记忆树中的文档会被跳过。',
+ '最多 {scanned} 个已同步的文档在记忆树摄取修复之前保存,因此不会显示在记忆图谱中。摄取它们会消耗嵌入额度。已在记忆树中的文档会被跳过。',
'memorySources.repair.confirm': '修复',
'memorySources.repair.cancel': '暂不',
- 'memorySources.repair.nothing': '无需修复 — 没有等待归档的已同步文档。',
+ 'memorySources.repair.nothing': '无需修复。没有等待摄取的已同步文档。',
'memorySources.repair.success':
- '已归档 {ingested} 个到记忆树({already} 个已存在,{skipped} 个已跳过)。',
- 'memorySources.repair.morePending': '还有剩余 — 请再次点击“修复较早的记忆”。',
+ '已摄取 {ingested} 个到记忆树({already} 个已存在,{skipped} 个已跳过)。',
+ 'memorySources.repair.morePending': '还有剩余。请再次点击“修复较早的记忆”。',
'memorySources.repair.failed': '无法修复较早的记忆。',
'memorySources.settings.button': '设置',
'memorySources.settings.title': '同步设置',
diff --git a/src/core/runtime/builder.rs b/src/core/runtime/builder.rs
index 450458ae10..1dd87ad8c4 100644
--- a/src/core/runtime/builder.rs
+++ b/src/core/runtime/builder.rs
@@ -841,7 +841,11 @@ impl CoreRuntime {
});
}
- if let Some(shutdown_token) = shutdown_token {
+ // The serve result is held, not propagated, until the exit work below
+ // has run. A `?` here on a server error would skip the memory teardown
+ // on exactly the exits where a wedged store is likeliest, and the
+ // callers only forward the error — nobody else runs the cleanup.
+ let served = if let Some(shutdown_token) = shutdown_token {
log::info!(
"[core] embedded server waiting on cancellation token for graceful shutdown"
);
@@ -849,18 +853,24 @@ impl CoreRuntime {
.with_graceful_shutdown(async move {
shutdown_token.cancelled().await;
})
- .await?;
+ .await
} else {
axum::serve(listener, app)
.with_graceful_shutdown(crate::core::shutdown::signal())
- .await?;
+ .await
+ };
+ if let Err(error) = &served {
+ log::warn!(
+ "[core] embedded server ended with an error; running exit cleanup before \
+ reporting it: {error}"
+ );
}
// Memory first. The engine's queue worker holds leases on in-flight
// jobs, and releasing them is a write to the store, so it has to happen
// while the store is still open and before anything else on the way
- // out (tinymemory#133). Bounded inside, per driver: a wedged store
- // costs at most its budget, never the exit.
+ // out (tinymemory#133). Bounded inside, on one shared deadline: a
+ // wedged store costs at most that budget, never the exit.
crate::openhuman::memory::exit::shutdown_for_exit().await;
// Server has stopped accepting and in-flight requests drained. Kill any
@@ -883,6 +893,7 @@ impl CoreRuntime {
}
}
+ served?;
Ok(())
}
diff --git a/src/openhuman/integrations/composio/ops/providers_ops.rs b/src/openhuman/integrations/composio/ops/providers_ops.rs
index d161cdadde..05872b10af 100644
--- a/src/openhuman/integrations/composio/ops/providers_ops.rs
+++ b/src/openhuman/integrations/composio/ops/providers_ops.rs
@@ -341,8 +341,9 @@ pub async fn composio_sync_budgeted(
let mut passes = 0usize;
let mut more_pending = false;
// The module's own account of a pass that stopped short (the day's
- // request budget, typically). The last one wins: it describes the
- // state the run ended in.
+ // request budget, typically). The last pass's word wins, present or
+ // absent: it describes the state the run ended in, and a pass that
+ // completes cleanly must not inherit the note of an earlier one.
let mut stop_note: Option<String> = None;
let outcome = loop {
passes += 1;
@@ -365,14 +366,12 @@ pub async fn composio_sync_budgeted(
Ok(pass) => {
total_written = total_written.saturating_add(u64::from(pass.written));
more_pending = pass.more_pending;
- if let Some(message) = pass
+ stop_note = pass
.message
.as_deref()
.map(str::trim)
.filter(|message| !message.is_empty())
- {
- stop_note = Some(message.to_string());
- }
+ .map(str::to_string);
tracing::info!(
toolkit = %toolkit_for_log,
connection_id = %connection_for_log,
diff --git a/src/openhuman/memory/exit.rs b/src/openhuman/memory/exit.rs
index 302af271f7..65306c5160 100644
--- a/src/openhuman/memory/exit.rs
+++ b/src/openhuman/memory/exit.rs
@@ -13,35 +13,86 @@
//! is bounded, because a quit that hangs on a wedged store is worse than a
//! lease that expires on its own.
+use std::collections::HashSet;
+use std::sync::Arc;
use std::time::Duration;
-/// What one driver's shutdown may take.
+use futures::future::join_all;
+use tokio::time::Instant;
+
+use crate::openhuman::memory::binding::MemoryBinding;
+
+/// The whole of memory's exit work — every bound driver's `shutdown`, then
+/// the host's hook registry — must fit in this, together.
///
-/// Releasing a lease is one write per in-flight job. Anything slower is a
-/// store that is not going to answer, and its leases expire by themselves.
-pub const DRIVER_EXIT_BUDGET: Duration = Duration::from_secs(2);
+/// One deadline rather than one per driver. The Tauri shell gives the server
+/// a bounded moment to drain before it aborts the task, and a per-driver
+/// budget multiplied by the number of bindings could outrun that moment with
+/// a hook still pending. Releasing a lease is one write per in-flight job;
+/// anything slower is a store that is not going to answer, and its leases
+/// expire by themselves. The shell sizes its drain budget from this constant
+/// plus the ollama cleanup that follows it in `serve_http`.
+pub const EXIT_BUDGET: Duration = Duration::from_secs(2);
+
+/// The least the hook registry gets even when the drivers spent the budget.
+/// In-process engines (dev runs, tests) release their leases through a hook,
+/// not a driver, so the hooks are never skipped outright.
+const HOOKS_FLOOR: Duration = Duration::from_millis(250);
+
+/// Rounds of "snapshot the cache, shut down what is new". Two is the honest
+/// number: the first round covers everything built before exit began, the
+/// second anything a background task built while the first round ran.
+const SNAPSHOT_ROUNDS: usize = 2;
/// Ask every bound memory driver to shut down, then run the hooks the
/// in-process engine registered with the host.
///
-/// Providers first: a module drains its own banked hook inside `Shutdown`, and
-/// the host's registry is where the in-process engine (dev runs and tests)
-/// registers instead. Both are idempotent — a provider's second `shutdown` is a
-/// no-op, and the registry drains — so a signal landing mid-teardown, or the
-/// app-update restart path calling this twice, repeats nothing.
+/// Providers first, concurrently and on the shared deadline: a module drains
+/// its own banked hook inside `Shutdown`, and the host's registry is where the
+/// in-process engine registers instead. The binding cache is snapshotted, not
+/// locked: a build that overlaps exit inserts after the snapshot, so a second
+/// round picks up whatever appeared. Both halves are idempotent — a provider's
+/// second `shutdown` is a no-op and the registry drains — so a signal landing
+/// mid-teardown, or the app-update restart path calling this twice, repeats
+/// nothing.
pub async fn shutdown_for_exit() {
- for binding in crate::openhuman::memory::binding::cached_bindings() {
- let driver = binding.driver_id().to_string();
- match tokio::time::timeout(DRIVER_EXIT_BUDGET, binding.provider().shutdown()).await {
- Ok(Ok(())) => log::debug!("[memory:exit] driver '{driver}' shut down"),
- Ok(Err(error)) => {
- log::warn!("[memory:exit] driver '{driver}' shutdown failed: {error}");
+ let deadline = Instant::now() + EXIT_BUDGET;
+ // Addresses, not pointers: a raw pointer in the set would make this future
+ // `!Send`, and the embedded server task that awaits it is spawned. The
+ // `Arc` snapshot keeps every binding alive across the loop, so an address
+ // cannot be reused for a different binding while it is in the set.
+ let mut seen: HashSet<usize> = HashSet::new();
+ for round in 1..=SNAPSHOT_ROUNDS {
+ let pending: Vec<Arc<MemoryBinding>> = crate::openhuman::memory::binding::cached_bindings()
+ .into_iter()
+ .filter(|binding| seen.insert(Arc::as_ptr(binding) as usize))
+ .collect();
+ if pending.is_empty() {
+ break;
+ }
+ let shutdowns = join_all(pending.iter().map(|binding| async move {
+ let driver = binding.driver_id().to_string();
+ match binding.provider().shutdown().await {
+ Ok(()) => log::debug!("[memory:exit] driver '{driver}' shut down"),
+ Err(error) => {
+ log::warn!("[memory:exit] driver '{driver}' shutdown failed: {error}");
+ }
}
- Err(_) => log::warn!(
- "[memory:exit] driver '{driver}' shutdown exceeded {DRIVER_EXIT_BUDGET:?}; \
- proceeding with exit"
- ),
+ }));
+ if tokio::time::timeout_at(deadline, shutdowns).await.is_err() {
+ log::warn!(
+ "[memory:exit] driver shutdown exceeded the {EXIT_BUDGET:?} exit budget in \
+ round {round}; proceeding with exit"
+ );
+ break;
}
}
- crate::core::shutdown::run_hooks_now().await;
+
+ let hooks_deadline = deadline.max(Instant::now() + HOOKS_FLOOR);
+ if tokio::time::timeout_at(hooks_deadline, crate::core::shutdown::run_hooks_now())
+ .await
+ .is_err()
+ {
+ log::warn!("[memory:exit] shutdown hooks exceeded the exit budget; proceeding with exit");
+ }
}
diff --git a/src/openhuman/memory/exit_tests.rs b/src/openhuman/memory/exit_tests.rs
index ab4173bf75..c552587601 100644
--- a/src/openhuman/memory/exit_tests.rs
+++ b/src/openhuman/memory/exit_tests.rs
@@ -2,14 +2,20 @@
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
+use std::time::Duration;
-use super::exit::shutdown_for_exit;
+use super::exit::{shutdown_for_exit, EXIT_BUDGET};
+
+/// The hook registry is process-global, so the two tests below must not see
+/// each other's hooks: each registers and drains under this lock.
+static REGISTRY: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
/// With no binding ever built, the exit path is the hook registry alone — and
/// the registry drains, so the hooks run once however many times exit is asked
/// for (the app-update restart path asks twice).
#[tokio::test]
async fn exit_runs_registered_hooks_once() {
+ let _serial = REGISTRY.lock().await;
let runs = Arc::new(AtomicUsize::new(0));
let counter = Arc::clone(&runs);
crate::core::shutdown::register(move || {
@@ -28,3 +34,22 @@ async fn exit_runs_registered_hooks_once() {
"the registry drains on the first exit; the second finds nothing"
);
}
+
+/// A hook that never answers must not hold the quit: exit returns within its
+/// budget (plus the hooks' floor) and the process goes on without it.
+#[tokio::test]
+async fn exit_is_bounded_even_when_a_hook_hangs() {
+ let _serial = REGISTRY.lock().await;
+ crate::core::shutdown::register(|| async {
+ tokio::time::sleep(Duration::from_secs(30)).await;
+ });
+
+ let started = std::time::Instant::now();
+ shutdown_for_exit().await;
+
+ assert!(
+ started.elapsed() < EXIT_BUDGET + Duration::from_secs(2),
+ "exit took {:?}; the hanging hook held it past the budget",
+ started.elapsed()
+ );
+}