Skip to content

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

fix(memory): name a refused credential and an unreachable engine

Shanu735b75a07efd
diff --git a/app/src/components/settings/panels/MemoryEngineErrorAlert.test.tsx b/app/src/components/settings/panels/MemoryEngineErrorAlert.test.tsx
index ef95a3037e..a77a31f528 100644
--- a/app/src/components/settings/panels/MemoryEngineErrorAlert.test.tsx
+++ b/app/src/components/settings/panels/MemoryEngineErrorAlert.test.tsx
@@ -25,6 +25,21 @@ describe('MemoryEngineErrorAlert', () => {
expect(screen.getByTestId('memory-engine-sign-in')).toBeInTheDocument();
});
+ test('a refused credential is its own state, never a sign-in prompt', () => {
+ renderWithProviders(
+ <MemoryEngineErrorAlert error="MEMORY_FORBIDDEN: the memory engine refused this credential" />
+ );
+ expect(screen.getByTestId('memory-engine-error-memory_forbidden')).toBeInTheDocument();
+ expect(screen.queryByTestId('memory-engine-sign-in')).toBeNull();
+ });
+
+ test('an unreachable engine shows the unavailable state', () => {
+ renderWithProviders(
+ <MemoryEngineErrorAlert error="MEMORY_UNREACHABLE: the memory engine is not available right now" />
+ );
+ expect(screen.getByTestId('memory-engine-error-backend_unavailable')).toBeInTheDocument();
+ });
+
test('any other error shows the caller fallback text and no action', () => {
renderWithProviders(<MemoryEngineErrorAlert error="boom" fallbackText="Graph failed" />);
expect(screen.getByTestId('memory-engine-error-other')).toHaveTextContent('Graph failed');
diff --git a/app/src/components/settings/panels/MemoryEngineErrorAlert.tsx b/app/src/components/settings/panels/MemoryEngineErrorAlert.tsx
index a78bc135a5..8fe0a406aa 100644
--- a/app/src/components/settings/panels/MemoryEngineErrorAlert.tsx
+++ b/app/src/components/settings/panels/MemoryEngineErrorAlert.tsx
@@ -12,9 +12,11 @@ export function useMemoryEngineErrorText(): (kind: MemoryEngineErrorKind) => str
? t('memoryEngine.error.insufficientCredits')
: kind === 'session_expired'
? t('memoryEngine.error.sessionExpired')
- : kind === 'backend_unavailable'
- ? t('memoryEngine.error.backendUnavailable')
- : t('memoryEngine.error.generic');
+ : kind === 'memory_forbidden'
+ ? t('memoryEngine.error.forbidden')
+ : kind === 'backend_unavailable'
+ ? t('memoryEngine.error.backendUnavailable')
+ : t('memoryEngine.error.generic');
}
interface MemoryEngineErrorAlertProps {
diff --git a/app/src/components/settings/panels/memoryEngineUtils.ts b/app/src/components/settings/panels/memoryEngineUtils.ts
index 0c3166180f..621417a6d6 100644
--- a/app/src/components/settings/panels/memoryEngineUtils.ts
+++ b/app/src/components/settings/panels/memoryEngineUtils.ts
@@ -3,6 +3,7 @@ import type { MemoryEngineDescriptor } from '../../../utils/tauriCommands/memory
export type MemoryEngineErrorKind =
| 'insufficient_credits'
| 'session_expired'
+ | 'memory_forbidden'
| 'backend_unavailable'
| 'other';
@@ -11,7 +12,12 @@ export function classifyMemoryEngineError(err: unknown): MemoryEngineErrorKind {
const message = err instanceof Error ? err.message : String(err ?? '');
if (message.includes('INSUFFICIENT_CREDITS:')) return 'insufficient_credits';
if (message.includes('SESSION_EXPIRED:')) return 'session_expired';
- if (message.includes('BACKEND_UNAVAILABLE:')) return 'backend_unavailable';
+ // A refused credential (an API key without the memory scope): not a lapsed
+ // session, so it must never read as one and sign the user out.
+ if (message.includes('MEMORY_FORBIDDEN:')) return 'memory_forbidden';
+ if (message.includes('BACKEND_UNAVAILABLE:') || message.includes('MEMORY_UNREACHABLE:')) {
+ return 'backend_unavailable';
+ }
return 'other';
}
diff --git a/app/src/lib/i18n/ar.ts b/app/src/lib/i18n/ar.ts
index 91c7ce2828..db6eb5ff19 100644
--- a/app/src/lib/i18n/ar.ts
+++ b/app/src/lib/i18n/ar.ts
@@ -7129,6 +7129,8 @@ const messages: TranslationMap = {
'نفد رصيد OpenHuman لديك. أضف رصيدًا لاستخدام هذا المحرك.',
'memoryEngine.error.sessionExpired': 'انتهت جلستك. سجّل الدخول مرة أخرى للمتابعة.',
'memoryEngine.error.backendUnavailable': 'خدمة الذاكرة غير متاحة حاليًا. حاول مرة أخرى بعد قليل.',
+ 'memoryEngine.error.forbidden':
+ 'رفضت خدمة الذاكرة بيانات اعتماد هذا الحساب. إذا كنت تستخدم مفتاح API، فامنحه نطاق memory.',
'memoryEngine.error.generic': 'تعذّر تغيير محرك الذاكرة. تحقق من الإعدادات وحاول مرة أخرى.',
'memoryEngine.error.openBilling': 'فتح الفوترة',
'memoryEngine.error.signIn': 'تسجيل الدخول',
diff --git a/app/src/lib/i18n/bn.ts b/app/src/lib/i18n/bn.ts
index 476560dafa..67aef52986 100644
--- a/app/src/lib/i18n/bn.ts
+++ b/app/src/lib/i18n/bn.ts
@@ -7282,6 +7282,8 @@ const messages: TranslationMap = {
'আপনার সেশনের মেয়াদ শেষ হয়েছে। চালিয়ে যেতে আবার সাইন ইন করুন।',
'memoryEngine.error.backendUnavailable':
'মেমোরি পরিষেবা এখন অনুপলব্ধ। একটু পরে আবার চেষ্টা করুন।',
+ 'memoryEngine.error.forbidden':
+ 'মেমরি পরিষেবা এই অ্যাকাউন্টের ক্রেডেনশিয়াল প্রত্যাখ্যান করেছে। আপনি API কী ব্যবহার করলে সেটিকে memory স্কোপ দিন।',
'memoryEngine.error.generic':
'মেমোরি ইঞ্জিন পরিবর্তন করা যায়নি। সেটিংস পরীক্ষা করে আবার চেষ্টা করুন।',
'memoryEngine.error.openBilling': 'বিলিং খুলুন',
diff --git a/app/src/lib/i18n/de.ts b/app/src/lib/i18n/de.ts
index 78bdbe2f8c..317a6beb17 100644
--- a/app/src/lib/i18n/de.ts
+++ b/app/src/lib/i18n/de.ts
@@ -7480,6 +7480,8 @@ const messages: TranslationMap = {
'Deine Sitzung ist abgelaufen. Melde dich erneut an, um fortzufahren.',
'memoryEngine.error.backendUnavailable':
'Der Speicherdienst ist derzeit nicht erreichbar. Versuche es gleich noch einmal.',
+ 'memoryEngine.error.forbidden':
+ 'Der Speicher hat die Anmeldedaten dieses Kontos abgelehnt. Wenn du einen API-Schlüssel verwendest, gib ihm den Bereich memory.',
'memoryEngine.error.generic':
'Die Speicher-Engine konnte nicht geändert werden. Prüfe die Einstellungen und versuche es erneut.',
'memoryEngine.error.openBilling': 'Abrechnung öffnen',
diff --git a/app/src/lib/i18n/en.ts b/app/src/lib/i18n/en.ts
index 990426720f..0389e667bf 100644
--- a/app/src/lib/i18n/en.ts
+++ b/app/src/lib/i18n/en.ts
@@ -7588,6 +7588,8 @@ const en: TranslationMap = {
'memoryEngine.error.sessionExpired': 'Your session expired. Sign in again to continue.',
'memoryEngine.error.backendUnavailable':
'The memory service is unavailable right now. Try again shortly.',
+ 'memoryEngine.error.forbidden':
+ 'Memory refused the credential for this account. If you use an API key, give it the memory scope.',
'memoryEngine.error.generic':
'Could not change the memory engine. Check the settings and try again.',
'memoryEngine.error.openBilling': 'Open billing',
diff --git a/app/src/lib/i18n/es.ts b/app/src/lib/i18n/es.ts
index 7adfbb48e0..9b5913833f 100644
--- a/app/src/lib/i18n/es.ts
+++ b/app/src/lib/i18n/es.ts
@@ -7433,6 +7433,8 @@ const messages: TranslationMap = {
'Tu sesión ha caducado. Inicia sesión de nuevo para continuar.',
'memoryEngine.error.backendUnavailable':
'El servicio de memoria no está disponible en este momento. Inténtalo de nuevo en breve.',
+ 'memoryEngine.error.forbidden':
+ 'La memoria rechazó la credencial de esta cuenta. Si usas una clave de API, dale el alcance memory.',
'memoryEngine.error.generic':
'No se pudo cambiar el motor de memoria. Revisa los ajustes e inténtalo de nuevo.',
'memoryEngine.error.openBilling': 'Abrir facturación',
diff --git a/app/src/lib/i18n/fr.ts b/app/src/lib/i18n/fr.ts
index c1b8954815..9d490f73f9 100644
--- a/app/src/lib/i18n/fr.ts
+++ b/app/src/lib/i18n/fr.ts
@@ -7462,6 +7462,8 @@ const messages: TranslationMap = {
'memoryEngine.error.sessionExpired': 'Votre session a expiré. Reconnectez-vous pour continuer.',
'memoryEngine.error.backendUnavailable':
'Le service de mémoire est indisponible pour le moment. Réessayez dans un instant.',
+ 'memoryEngine.error.forbidden':
+ 'La mémoire a refusé les identifiants de ce compte. Si vous utilisez une clé API, accordez-lui la portée memory.',
'memoryEngine.error.generic':
'Impossible de changer le moteur de mémoire. Vérifiez les paramètres et réessayez.',
'memoryEngine.error.openBilling': 'Ouvrir la facturation',
diff --git a/app/src/lib/i18n/hi.ts b/app/src/lib/i18n/hi.ts
index 2fc13bc06a..58581ab09e 100644
--- a/app/src/lib/i18n/hi.ts
+++ b/app/src/lib/i18n/hi.ts
@@ -7284,6 +7284,8 @@ const messages: TranslationMap = {
'आपका सत्र समाप्त हो गया है। जारी रखने के लिए फिर से साइन इन करें।',
'memoryEngine.error.backendUnavailable':
'मेमोरी सेवा अभी उपलब्ध नहीं है। थोड़ी देर बाद फिर कोशिश करें।',
+ 'memoryEngine.error.forbidden':
+ 'मेमोरी सेवा ने इस खाते का क्रेडेंशियल अस्वीकार कर दिया। यदि आप API कुंजी का उपयोग करते हैं, तो उसे memory स्कोप दें।',
'memoryEngine.error.generic': 'मेमोरी इंजन बदला नहीं जा सका। सेटिंग जाँचकर फिर कोशिश करें।',
'memoryEngine.error.openBilling': 'बिलिंग खोलें',
'memoryEngine.error.signIn': 'साइन इन करें',
diff --git a/app/src/lib/i18n/id.ts b/app/src/lib/i18n/id.ts
index bb0cfa4060..51a0f9dfd2 100644
--- a/app/src/lib/i18n/id.ts
+++ b/app/src/lib/i18n/id.ts
@@ -7329,6 +7329,8 @@ const messages: TranslationMap = {
'memoryEngine.error.sessionExpired': 'Sesi Anda berakhir. Masuk lagi untuk melanjutkan.',
'memoryEngine.error.backendUnavailable':
'Layanan memori sedang tidak tersedia. Coba lagi sebentar lagi.',
+ 'memoryEngine.error.forbidden':
+ 'Layanan memori menolak kredensial akun ini. Jika Anda memakai kunci API, berikan cakupan memory padanya.',
'memoryEngine.error.generic':
'Tidak dapat mengubah mesin memori. Periksa pengaturan lalu coba lagi.',
'memoryEngine.error.openBilling': 'Buka penagihan',
diff --git a/app/src/lib/i18n/it.ts b/app/src/lib/i18n/it.ts
index 90a43869e4..bfff829d71 100644
--- a/app/src/lib/i18n/it.ts
+++ b/app/src/lib/i18n/it.ts
@@ -7410,6 +7410,8 @@ const messages: TranslationMap = {
'memoryEngine.error.sessionExpired': 'La sessione è scaduta. Accedi di nuovo per continuare.',
'memoryEngine.error.backendUnavailable':
'Il servizio di memoria non è disponibile al momento. Riprova tra poco.',
+ 'memoryEngine.error.forbidden':
+ 'La memoria ha rifiutato le credenziali di questo account. Se usi una chiave API, concedile il permesso memory.',
'memoryEngine.error.generic':
'Impossibile cambiare il motore di memoria. Controlla le impostazioni e riprova.',
'memoryEngine.error.openBilling': 'Apri fatturazione',
diff --git a/app/src/lib/i18n/ko.ts b/app/src/lib/i18n/ko.ts
index 0610e3f42f..1a70f50b9a 100644
--- a/app/src/lib/i18n/ko.ts
+++ b/app/src/lib/i18n/ko.ts
@@ -7201,6 +7201,8 @@ const messages: TranslationMap = {
'memoryEngine.error.sessionExpired': '세션이 만료되었습니다. 계속하려면 다시 로그인하세요.',
'memoryEngine.error.backendUnavailable':
'메모리 서비스를 지금 사용할 수 없습니다. 잠시 후 다시 시도하세요.',
+ 'memoryEngine.error.forbidden':
+ '메모리 서비스가 이 계정의 자격 증명을 거부했습니다. API 키를 사용한다면 memory 범위를 부여하세요.',
'memoryEngine.error.generic':
'메모리 엔진을 변경할 수 없습니다. 설정을 확인하고 다시 시도하세요.',
'memoryEngine.error.openBilling': '결제 열기',
diff --git a/app/src/lib/i18n/pl.ts b/app/src/lib/i18n/pl.ts
index 1efafe20c5..282f63b12f 100644
--- a/app/src/lib/i18n/pl.ts
+++ b/app/src/lib/i18n/pl.ts
@@ -7389,6 +7389,8 @@ const messages: TranslationMap = {
'memoryEngine.error.sessionExpired': 'Sesja wygasła. Zaloguj się ponownie, aby kontynuować.',
'memoryEngine.error.backendUnavailable':
'Usługa pamięci jest teraz niedostępna. Spróbuj ponownie za chwilę.',
+ 'memoryEngine.error.forbidden':
+ 'Usługa pamięci odrzuciła dane uwierzytelniające tego konta. Jeśli używasz klucza API, nadaj mu zakres memory.',
'memoryEngine.error.generic':
'Nie udało się zmienić silnika pamięci. Sprawdź ustawienia i spróbuj ponownie.',
'memoryEngine.error.openBilling': 'Otwórz rozliczenia',
diff --git a/app/src/lib/i18n/pt.ts b/app/src/lib/i18n/pt.ts
index d37fc7b427..cd98ddb6dc 100644
--- a/app/src/lib/i18n/pt.ts
+++ b/app/src/lib/i18n/pt.ts
@@ -7401,6 +7401,8 @@ const messages: TranslationMap = {
'Sua sessão expirou. Inicie sessão novamente para continuar.',
'memoryEngine.error.backendUnavailable':
'O serviço de memória está indisponível no momento. Tente novamente em instantes.',
+ 'memoryEngine.error.forbidden':
+ 'A memória recusou a credencial desta conta. Se você usa uma chave de API, conceda a ela o escopo memory.',
'memoryEngine.error.generic':
'Não foi possível trocar o mecanismo de memória. Verifique as configurações e tente novamente.',
'memoryEngine.error.openBilling': 'Abrir faturamento',
diff --git a/app/src/lib/i18n/ru.ts b/app/src/lib/i18n/ru.ts
index 578e031074..e0901bd4bf 100644
--- a/app/src/lib/i18n/ru.ts
+++ b/app/src/lib/i18n/ru.ts
@@ -7355,6 +7355,8 @@ const messages: TranslationMap = {
'memoryEngine.error.sessionExpired': 'Сеанс истёк. Войдите снова, чтобы продолжить.',
'memoryEngine.error.backendUnavailable':
'Служба памяти сейчас недоступна. Повторите попытку чуть позже.',
+ 'memoryEngine.error.forbidden':
+ 'Служба памяти отклонила учётные данные этой учётной записи. Если вы используете ключ API, выдайте ему область memory.',
'memoryEngine.error.generic':
'Не удалось сменить движок памяти. Проверьте настройки и повторите попытку.',
'memoryEngine.error.openBilling': 'Открыть оплату',
diff --git a/app/src/lib/i18n/zh-CN.ts b/app/src/lib/i18n/zh-CN.ts
index f150a28135..dcada1aff3 100644
--- a/app/src/lib/i18n/zh-CN.ts
+++ b/app/src/lib/i18n/zh-CN.ts
@@ -6903,6 +6903,8 @@ const messages: TranslationMap = {
'memoryEngine.error.insufficientCredits': '你的 OpenHuman 额度已用完。请充值后再使用此引擎。',
'memoryEngine.error.sessionExpired': '会话已过期。请重新登录以继续。',
'memoryEngine.error.backendUnavailable': '记忆服务暂时不可用,请稍后重试。',
+ 'memoryEngine.error.forbidden':
+ '记忆服务拒绝了此账户的凭据。如果使用 API 密钥,请为其授予 memory 权限范围。',
'memoryEngine.error.generic': '无法更改记忆引擎。请检查设置后重试。',
'memoryEngine.error.openBilling': '打开账单',
'memoryEngine.error.signIn': '登录',
diff --git a/crates/openhuman-core/src/memory/ops/engine.rs b/crates/openhuman-core/src/memory/ops/engine.rs
index d0b2bd7ff4..b72d34c437 100644
--- a/crates/openhuman-core/src/memory/ops/engine.rs
+++ b/crates/openhuman-core/src/memory/ops/engine.rs
@@ -27,6 +27,14 @@ const LOG_PREFIX: &str = "[memory:engine]";
pub const INSUFFICIENT_CREDITS_PREFIX: &str = "INSUFFICIENT_CREDITS:";
/// Error prefix for "no valid TinyHumans session".
pub const SESSION_EXPIRED_PREFIX: &str = "SESSION_EXPIRED:";
+/// Error prefix for "the engine refused this credential" (HTTP 403 — for
+/// example an API key without the memory scope). Deliberately not
+/// [`SESSION_EXPIRED_PREFIX`]: the app reads that one as a lapsed sign-in and
+/// signs the user out, which a refused key is not.
+pub const MEMORY_FORBIDDEN_PREFIX: &str = "MEMORY_FORBIDDEN:";
+/// Error prefix for "the engine cannot be reached or cannot serve right now"
+/// (a timeout, a refused connection, a 429 or a 5xx that outlasted retries).
+pub const MEMORY_UNREACHABLE_PREFIX: &str = "MEMORY_UNREACHABLE:";
/// One selectable engine, as `memory.engines_list` reports it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
@@ -188,32 +196,50 @@ fn normalized_driver(config: &Config) -> String {
}
/// Map an engine-layer failure to the RPC error vocabulary the UI keys on:
-/// `INSUFFICIENT_CREDITS:`, `SESSION_EXPIRED:` or `BACKEND_UNAVAILABLE:`, else
-/// the message as is (already scrubbed of keys and endpoints by the engine
-/// layer).
+/// `INSUFFICIENT_CREDITS:`, `SESSION_EXPIRED:`, `MEMORY_FORBIDDEN:`,
+/// `MEMORY_UNREACHABLE:` or `BACKEND_UNAVAILABLE:`, else the message as is
+/// (already scrubbed of keys and endpoints by the engine layer).
#[must_use]
pub fn classify_engine_error(error: &anyhow::Error) -> String {
use crate::memory::api::error::MemoryError;
- if let Some(me) = error.downcast_ref::<MemoryError>() {
- match me {
- // The hosted backend's 402 carries a `[USER_INSUFFICIENT_CREDITS]`
- // message prefix (`tinymemory_remote::hosted`).
- MemoryError::BudgetExceeded(message)
- if message
- .trim_start()
- .starts_with("[USER_INSUFFICIENT_CREDITS]") =>
- {
- return format!(
- "{INSUFFICIENT_CREDITS_PREFIX} the memory engine is out of credits"
- );
- }
- MemoryError::Unauthorized(_) => {
- return format!("{SESSION_EXPIRED_PREFIX} the memory engine rejected the session");
- }
- _ => {}
+ match error.downcast_ref::<MemoryError>() {
+ Some(typed) => classify_memory_error(typed),
+ None => classify_engine_message(&format!("{error:#}")),
+ }
+}
+
+/// [`classify_engine_error`] for a typed memory error.
+#[must_use]
+pub fn classify_memory_error(error: &crate::memory::api::error::MemoryError) -> String {
+ use crate::memory::api::error::MemoryError;
+ match error {
+ // The hosted backend's 402 carries a `[USER_INSUFFICIENT_CREDITS]`
+ // message prefix (`tinymemory_remote::hosted`).
+ MemoryError::BudgetExceeded(message)
+ if message
+ .trim_start()
+ .starts_with("[USER_INSUFFICIENT_CREDITS]") =>
+ {
+ format!("{INSUFFICIENT_CREDITS_PREFIX} the memory engine is out of credits")
+ }
+ MemoryError::Unauthorized(message) if is_forbidden(message) => {
+ format!("{MEMORY_FORBIDDEN_PREFIX} the memory engine refused this credential")
}
+ MemoryError::Unauthorized(_) => {
+ format!("{SESSION_EXPIRED_PREFIX} the memory engine rejected the session")
+ }
+ MemoryError::Unavailable(_) | MemoryError::Unreachable(_) | MemoryError::Timeout(_) => {
+ format!("{MEMORY_UNREACHABLE_PREFIX} the memory engine is not available right now")
+ }
+ other => classify_engine_message(&other.to_string()),
}
- classify_engine_message(&format!("{error:#}"))
+}
+
+/// Whether an `Unauthorized` message is a 403: the credential was valid and
+/// refused, as opposed to missing or lapsed. The remote adapters render the
+/// status into the message (`(HTTP 403 Forbidden)`).
+fn is_forbidden(message: &str) -> bool {
+ message.contains("(HTTP 403")
}
/// [`classify_engine_error`] for a failure that is already a string.
@@ -222,18 +248,31 @@ pub fn classify_engine_message(message: &str) -> String {
if message.contains(crate::core::observability::BACKEND_UNAVAILABLE_PREFIX)
|| message.starts_with(SESSION_EXPIRED_PREFIX)
|| message.starts_with(INSUFFICIENT_CREDITS_PREFIX)
+ || message.starts_with(MEMORY_FORBIDDEN_PREFIX)
+ || message.starts_with(MEMORY_UNREACHABLE_PREFIX)
{
return message.to_string();
}
if message.contains("USER_INSUFFICIENT_CREDITS") {
return format!("{INSUFFICIENT_CREDITS_PREFIX} the memory engine is out of credits");
}
+ if is_forbidden(message) {
+ return format!("{MEMORY_FORBIDDEN_PREFIX} the memory engine refused this credential");
+ }
if message.contains(SESSION_EXPIRED_PREFIX)
|| message.contains("[UNAUTHORIZED]")
|| (message.starts_with("unauthorized:") && message.contains("re-authenticate"))
{
return format!("{SESSION_EXPIRED_PREFIX} no TinyHumans session");
}
+ // `MemoryError`'s own renderings of the not-now classes, at the start of
+ // the message or after a caller's `context: ` wrapper.
+ if ["unavailable: ", "unreachable: ", "timed out: "]
+ .iter()
+ .any(|class| message.starts_with(class) || message.contains(&format!(": {class}")))
+ {
+ return format!("{MEMORY_UNREACHABLE_PREFIX} the memory engine is not available right now");
+ }
message.to_string()
}
diff --git a/crates/openhuman-core/src/memory/ops/engine_tests.rs b/crates/openhuman-core/src/memory/ops/engine_tests.rs
index 9aa50f17c3..aeb302ea31 100644
--- a/crates/openhuman-core/src/memory/ops/engine_tests.rs
+++ b/crates/openhuman-core/src/memory/ops/engine_tests.rs
@@ -154,6 +154,44 @@ fn unauthorized_becomes_session_expired() {
assert!(classify_engine_error(&error).starts_with(SESSION_EXPIRED_PREFIX));
}
+#[test]
+fn a_403_is_a_refused_credential_not_an_expired_session() {
+ // An API key without the memory scope is a backend 403. `SESSION_EXPIRED:`
+ // would make the app sign the user out; the credential is valid, just not
+ // allowed here.
+ let refused = "[FORBIDDEN] memory API memory/recall on host (HTTP 403 Forbidden): API key \
+ is missing the required scope: memory — the session expired or the API \
+ key was rejected; re-authenticate";
+ let error = anyhow::Error::new(MemoryError::Unauthorized(refused.into()));
+ let typed = classify_engine_error(&error);
+ assert!(typed.starts_with(MEMORY_FORBIDDEN_PREFIX), "{typed}");
+ let text = classify_engine_message(&format!("unauthorized: {refused}"));
+ assert!(text.starts_with(MEMORY_FORBIDDEN_PREFIX), "{text}");
+ assert!(!text.contains(SESSION_EXPIRED_PREFIX), "{text}");
+}
+
+#[test]
+fn an_engine_that_cannot_serve_now_is_unreachable() {
+ for error in [
+ MemoryError::Unavailable("[RATE_LIMITED] memory API memory/recall (HTTP 429)".into()),
+ MemoryError::Unreachable("memory API request to host: could not connect".into()),
+ MemoryError::Timeout("memory API request to host: timed out".into()),
+ ] {
+ let rendered = error.to_string();
+ let typed = classify_engine_error(&anyhow::Error::new(error));
+ assert!(typed.starts_with(MEMORY_UNREACHABLE_PREFIX), "{typed}");
+ let text = classify_engine_message(&rendered);
+ assert!(
+ text.starts_with(MEMORY_UNREACHABLE_PREFIX),
+ "{rendered} -> {text}"
+ );
+ }
+ assert_eq!(
+ classify_engine_message("MEMORY_UNREACHABLE: already classified"),
+ "MEMORY_UNREACHABLE: already classified"
+ );
+}
+
#[test]
fn backend_unavailable_and_prefixed_messages_pass_through() {
let unavailable = format!(