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(chat): keep citations on the stored reply and make recovery deterministic
Shanud9337b44218e
diff --git a/app/src/lib/i18n/ar.ts b/app/src/lib/i18n/ar.tsindex f91a78f11a..41fb2dfa35 100644--- a/app/src/lib/i18n/ar.ts+++ b/app/src/lib/i18n/ar.ts@@ -6404,6 +6404,9 @@ const messages: TranslationMap = {'userErrors.localModelUnavailable.title': 'النموذج المحلي غير متاح','userErrors.localModelUnavailable.body':'لا يمكن الوصول إلى Ollama على النقطة الطرفية المُهيأة، أو أن النموذج المطلوب غير مثبّت عليها. شغّل Ollama ونزّل النموذج على تلك النقطة الطرفية، أو حوّل هذا العمل إلى مزوّد سحابي.',+ 'userErrors.replyDeliveryFailed.title': 'تعذّر عرض الرد',+ 'userErrors.replyDeliveryFailed.body':+ 'أنهى الوكيل هذه الجولة، لكن تعذّر حفظ ردّه أو قراءته مجددًا. اطلب منه تكرار الرد.','userErrors.memoryStoreCorrupt.title': 'تلف فهرس الذاكرة','userErrors.memoryStoreCorrupt.body':'كانت قاعدة بيانات شجرة الذاكرة تالفة. تم الاحتفاظ بالملف التالف بجوار بيانات الذاكرة وأعيد إنشاء فهرس فارغ. أعد مزامنة مصادر الذاكرة لإعادة تعبئته.',diff --git a/app/src/lib/i18n/bn.ts b/app/src/lib/i18n/bn.tsindex fa73f7cf1c..df8d7a4b70 100644--- a/app/src/lib/i18n/bn.ts+++ b/app/src/lib/i18n/bn.ts@@ -6554,6 +6554,9 @@ const messages: TranslationMap = {'userErrors.localModelUnavailable.title': 'লোকাল মডেল অনুপলব্ধ','userErrors.localModelUnavailable.body':'কনফিগার করা এন্ডপয়েন্টে Ollama-তে পৌঁছানো যাচ্ছে না, অথবা সেখানে প্রয়োজনীয় মডেলটি ইনস্টল করা নেই। Ollama চালু করে সেই এন্ডপয়েন্টে মডেলটি পুল করুন, অথবা এই কাজটি কোনো ক্লাউড প্রোভাইডারে সরিয়ে নিন।',+ 'userErrors.replyDeliveryFailed.title': 'উত্তরটি দেখানো যায়নি',+ 'userErrors.replyDeliveryFailed.body':+ 'এজেন্ট এই দফাটি শেষ করেছে, কিন্তু তার উত্তর সংরক্ষণ বা পুনরায় পড়া যায়নি। আবার জিজ্ঞাসা করলে সে উত্তরটি আবার দেবে।','userErrors.memoryStoreCorrupt.title': 'মেমোরি ইনডেক্স নষ্ট হয়ে গেছে','userErrors.memoryStoreCorrupt.body':'আপনার মেমোরি ট্রির ডেটাবেস নষ্ট হয়ে গিয়েছিল। নষ্ট ফাইলটি মেমোরি ডেটার পাশে সংরক্ষিত আছে এবং একটি খালি ইনডেক্স নতুন করে তৈরি হয়েছে। আবার পূরণ করতে মেমোরি উৎসগুলি পুনরায় সিঙ্ক করুন।',diff --git a/app/src/lib/i18n/de.ts b/app/src/lib/i18n/de.tsindex 9fddcfc4b7..c3a8b0267e 100644--- a/app/src/lib/i18n/de.ts+++ b/app/src/lib/i18n/de.ts@@ -6739,6 +6739,9 @@ const messages: TranslationMap = {'userErrors.localModelUnavailable.title': 'Lokales Modell nicht verfügbar','userErrors.localModelUnavailable.body':'Ollama ist unter dem konfigurierten Endpunkt nicht erreichbar, oder das benötigte Modell ist dort nicht installiert. Starte Ollama und lade das Modell auf diesem Endpunkt, oder verlagere diese Arbeit auf einen Cloud-Anbieter.',+ 'userErrors.replyDeliveryFailed.title': 'Antwort konnte nicht angezeigt werden',+ 'userErrors.replyDeliveryFailed.body':+ 'Der Agent hat diese Runde beendet, seine Antwort ließ sich aber weder speichern noch erneut lesen. Frag noch einmal, damit er sie wiederholt.','userErrors.memoryStoreCorrupt.title': 'Gedächtnisindex war beschädigt','userErrors.memoryStoreCorrupt.body':'Die Datenbank des Gedächtnisbaums war beschädigt. Die beschädigte Datei wurde neben deinen Gedächtnisdaten aufbewahrt und ein leerer Index neu aufgebaut. Synchronisiere deine Gedächtnisquellen erneut, um ihn wieder zu füllen.',diff --git a/app/src/lib/i18n/en.ts b/app/src/lib/i18n/en.tsindex bd411add04..1641176490 100644--- a/app/src/lib/i18n/en.ts+++ b/app/src/lib/i18n/en.ts@@ -7069,6 +7069,9 @@ const en: TranslationMap = {'userErrors.localModelUnavailable.title': 'Local model unavailable','userErrors.localModelUnavailable.body':'Ollama is not reachable at the configured endpoint, or the required model is not installed there. Start Ollama and pull the model at that endpoint, or switch this workload to a cloud provider.',+ 'userErrors.replyDeliveryFailed.title': 'Reply could not be shown',+ 'userErrors.replyDeliveryFailed.body':+ 'The agent finished this turn, but its reply could not be saved or read back. Ask again to have it repeated.','userErrors.memoryStoreCorrupt.title': 'Memory index was corrupted','userErrors.memoryStoreCorrupt.body':'The database behind your memory tree was damaged. The damaged file was preserved next to your memory data, and an empty index was rebuilt. Re-sync your memory sources to fill it again.',diff --git a/app/src/lib/i18n/es.ts b/app/src/lib/i18n/es.tsindex bf53103b48..0364a571fd 100644--- a/app/src/lib/i18n/es.ts+++ b/app/src/lib/i18n/es.ts@@ -6698,6 +6698,9 @@ const messages: TranslationMap = {'userErrors.localModelUnavailable.title': 'Modelo local no disponible','userErrors.localModelUnavailable.body':'No se puede acceder a Ollama en el punto de conexión configurado, o el modelo necesario no está instalado allí. Inicia Ollama y descarga el modelo en ese punto de conexión, o cambia este trabajo a un proveedor en la nube.',+ 'userErrors.replyDeliveryFailed.title': 'No se pudo mostrar la respuesta',+ 'userErrors.replyDeliveryFailed.body':+ 'El agente terminó este turno, pero su respuesta no se pudo guardar ni volver a leer. Vuelve a preguntar para que la repita.','userErrors.memoryStoreCorrupt.title': 'El índice de memoria se dañó','userErrors.memoryStoreCorrupt.body':'La base de datos del árbol de memoria estaba dañada. El archivo dañado se conservó junto a tus datos de memoria y se reconstruyó un índice vacío. Vuelve a sincronizar tus fuentes de memoria para rellenarlo.',diff --git a/app/src/lib/i18n/fr.ts b/app/src/lib/i18n/fr.tsindex b690c1ef8d..2ead912adb 100644--- a/app/src/lib/i18n/fr.ts+++ b/app/src/lib/i18n/fr.ts@@ -6726,6 +6726,9 @@ const messages: TranslationMap = {'userErrors.localModelUnavailable.body':"Ollama n'est pas joignable sur le point de terminaison configuré, ou le modèle requis n'y est pas installé. Lancez Ollama et téléchargez le modèle sur ce point de terminaison, ou basculez cette charge de travail vers un fournisseur cloud.",'userErrors.scope.chat': 'Chat',+ 'userErrors.replyDeliveryFailed.title': 'Impossible d’afficher la réponse',+ 'userErrors.replyDeliveryFailed.body':+ 'L’agent a terminé ce tour, mais sa réponse n’a pas pu être enregistrée ni relue. Redemande-lui de la répéter.','userErrors.memoryStoreCorrupt.title': 'L’index mémoire a été corrompu','userErrors.memoryStoreCorrupt.body':'La base de données de l’arbre mémoire était endommagée. Le fichier endommagé a été conservé à côté de vos données mémoire et un index vide a été reconstruit. Resynchronisez vos sources mémoire pour le remplir à nouveau.',diff --git a/app/src/lib/i18n/hi.ts b/app/src/lib/i18n/hi.tsindex 760e545108..ba7835b026 100644--- a/app/src/lib/i18n/hi.ts+++ b/app/src/lib/i18n/hi.ts@@ -6554,6 +6554,9 @@ const messages: TranslationMap = {'userErrors.localModelUnavailable.title': 'लोकल मॉडल उपलब्ध नहीं है','userErrors.localModelUnavailable.body':'कॉन्फ़िगर किए गए एंडपॉइंट पर Ollama तक पहुँच नहीं है, या ज़रूरी मॉडल वहाँ इंस्टॉल नहीं है। Ollama शुरू करके उसी एंडपॉइंट पर मॉडल पुल करें, या इस काम को किसी क्लाउड प्रोवाइडर पर ले जाएँ।',+ 'userErrors.replyDeliveryFailed.title': 'उत्तर दिखाया नहीं जा सका',+ 'userErrors.replyDeliveryFailed.body':+ 'एजेंट ने यह बारी पूरी कर ली, लेकिन उसका उत्तर न सहेजा जा सका और न दोबारा पढ़ा जा सका। दोबारा पूछें ताकि वह उत्तर फिर से दे।','userErrors.memoryStoreCorrupt.title': 'मेमोरी इंडेक्स खराब हो गया','userErrors.memoryStoreCorrupt.body':'आपकी मेमोरी ट्री का डेटाबेस खराब हो गया था। खराब फाइल आपके मेमोरी डेटा के पास सुरक्षित रखी गई है, और एक खाली इंडेक्स फिर से बनाया गया है। इसे दोबारा भरने के लिए अपने मेमोरी स्रोतों को फिर से सिंक करें।',diff --git a/app/src/lib/i18n/id.ts b/app/src/lib/i18n/id.tsindex ec5787c00a..9d4057a5a1 100644--- a/app/src/lib/i18n/id.ts+++ b/app/src/lib/i18n/id.ts@@ -6590,6 +6590,9 @@ const messages: TranslationMap = {'userErrors.localModelUnavailable.title': 'Model lokal tidak tersedia','userErrors.localModelUnavailable.body':'Ollama tidak dapat dijangkau di endpoint yang dikonfigurasi, atau model yang dibutuhkan belum terpasang di sana. Jalankan Ollama dan unduh modelnya di endpoint tersebut, atau alihkan pekerjaan ini ke penyedia cloud.',+ 'userErrors.replyDeliveryFailed.title': 'Balasan tidak dapat ditampilkan',+ 'userErrors.replyDeliveryFailed.body':+ 'Agen menyelesaikan giliran ini, tetapi balasannya tidak dapat disimpan atau dibaca ulang. Tanyakan lagi agar diulangi.','userErrors.memoryStoreCorrupt.title': 'Indeks memori rusak','userErrors.memoryStoreCorrupt.body':'Basis data pohon memori mengalami kerusakan. Berkas yang rusak disimpan di samping data memori Anda, dan indeks kosong telah dibangun ulang. Sinkronkan ulang sumber memori untuk mengisinya kembali.',diff --git a/app/src/lib/i18n/it.ts b/app/src/lib/i18n/it.tsindex 06a36c2a7d..3e032f8bf4 100644--- a/app/src/lib/i18n/it.ts+++ b/app/src/lib/i18n/it.ts@@ -6680,6 +6680,9 @@ const messages: TranslationMap = {'userErrors.localModelUnavailable.body':"Ollama non è raggiungibile sull'endpoint configurato, oppure il modello necessario non è installato lì. Avvia Ollama e scarica il modello su quell'endpoint, oppure sposta questo lavoro su un provider cloud.",'userErrors.scope.chat': 'Chat',+ 'userErrors.replyDeliveryFailed.title': 'Impossibile mostrare la risposta',+ 'userErrors.replyDeliveryFailed.body':+ 'L’agente ha completato questo turno, ma la sua risposta non è stata salvata né rilette. Chiedi di nuovo per fartela ripetere.','userErrors.memoryStoreCorrupt.title': 'L’indice della memoria era corrotto','userErrors.memoryStoreCorrupt.body':'Il database dell’albero della memoria era danneggiato. Il file danneggiato è stato conservato accanto ai tuoi dati di memoria ed è stato ricostruito un indice vuoto. Risincronizza le tue fonti di memoria per riempirlo di nuovo.',diff --git a/app/src/lib/i18n/ko.ts b/app/src/lib/i18n/ko.tsindex d571709b0b..b471dfc1a9 100644--- a/app/src/lib/i18n/ko.ts+++ b/app/src/lib/i18n/ko.ts@@ -6480,6 +6480,9 @@ const messages: TranslationMap = {'userErrors.localModelUnavailable.title': '로컬 모델을 사용할 수 없음','userErrors.localModelUnavailable.body':'구성된 엔드포인트에서 Ollama에 연결할 수 없거나 필요한 모델이 그곳에 설치되어 있지 않습니다. Ollama를 실행하고 해당 엔드포인트에 모델을 내려받거나, 이 작업을 클라우드 제공업체로 전환하세요.',+ 'userErrors.replyDeliveryFailed.title': '답변을 표시하지 못했습니다',+ 'userErrors.replyDeliveryFailed.body':+ '에이전트가 이 턴을 마쳤지만 답변을 저장하거나 다시 읽어올 수 없었습니다. 다시 물어보면 답변을 되풀이합니다.','userErrors.memoryStoreCorrupt.title': '메모리 인덱스가 손상되었습니다','userErrors.memoryStoreCorrupt.body':'메모리 트리의 데이터베이스가 손상되었습니다. 손상된 파일은 메모리 데이터 옆에 보존되었고 빈 인덱스가 다시 생성되었습니다. 메모리 소스를 다시 동기화하여 채워 주세요.',diff --git a/app/src/lib/i18n/pl.ts b/app/src/lib/i18n/pl.tsindex 9773ad6732..b4573a5a6d 100644--- a/app/src/lib/i18n/pl.ts+++ b/app/src/lib/i18n/pl.ts@@ -6656,6 +6656,9 @@ const messages: TranslationMap = {'userErrors.localModelUnavailable.title': 'Model lokalny niedostępny','userErrors.localModelUnavailable.body':'Ollama jest nieosiągalna pod skonfigurowanym punktem końcowym albo wymagany model nie jest tam zainstalowany. Uruchom Ollamę i pobierz model w tym punkcie końcowym lub przenieś tę pracę do dostawcy w chmurze.',+ 'userErrors.replyDeliveryFailed.title': 'Nie udało się pokazać odpowiedzi',+ 'userErrors.replyDeliveryFailed.body':+ 'Agent zakończył tę turę, ale jego odpowiedzi nie udało się zapisać ani odczytać ponownie. Zapytaj jeszcze raz, aby ją powtórzył.','userErrors.memoryStoreCorrupt.title': 'Indeks pamięci był uszkodzony','userErrors.memoryStoreCorrupt.body':'Baza danych drzewa pamięci była uszkodzona. Uszkodzony plik zachowano obok danych pamięci i odbudowano pusty indeks. Zsynchronizuj ponownie źródła pamięci, aby go wypełnić.',diff --git a/app/src/lib/i18n/pt.ts b/app/src/lib/i18n/pt.tsindex b52244a773..8eb69772af 100644--- a/app/src/lib/i18n/pt.ts+++ b/app/src/lib/i18n/pt.ts@@ -6667,6 +6667,9 @@ const messages: TranslationMap = {'userErrors.localModelUnavailable.title': 'Modelo local indisponível','userErrors.localModelUnavailable.body':'O Ollama não está acessível no endpoint configurado, ou o modelo necessário não está instalado nele. Inicie o Ollama e baixe o modelo nesse endpoint, ou mude este trabalho para um provedor na nuvem.',+ 'userErrors.replyDeliveryFailed.title': 'Não foi possível mostrar a resposta',+ 'userErrors.replyDeliveryFailed.body':+ 'O agente concluiu este turno, mas a resposta dele não pôde ser salva nem lida novamente. Pergunte de novo para que ele repita.','userErrors.memoryStoreCorrupt.title': 'O índice de memória foi corrompido','userErrors.memoryStoreCorrupt.body':'O banco de dados da árvore de memória estava danificado. O arquivo danificado foi preservado ao lado dos seus dados de memória e um índice vazio foi reconstruído. Sincronize novamente suas fontes de memória para preenchê-lo.',diff --git a/app/src/lib/i18n/ru.ts b/app/src/lib/i18n/ru.tsindex 2f5b85dc17..d834f52ecc 100644--- a/app/src/lib/i18n/ru.ts+++ b/app/src/lib/i18n/ru.ts@@ -6629,6 +6629,9 @@ const messages: TranslationMap = {'userErrors.localModelUnavailable.title': 'Локальная модель недоступна','userErrors.localModelUnavailable.body':'Ollama недоступен по настроенному адресу, либо нужная модель там не установлена. Запустите Ollama и загрузите модель по этому адресу или переведите эту работу на облачного провайдера.',+ 'userErrors.replyDeliveryFailed.title': 'Не удалось показать ответ',+ 'userErrors.replyDeliveryFailed.body':+ 'Агент завершил этот ход, но его ответ не удалось сохранить или прочитать заново. Спросите ещё раз, чтобы он повторил.','userErrors.memoryStoreCorrupt.title': 'Индекс памяти был повреждён','userErrors.memoryStoreCorrupt.body':'База данных дерева памяти была повреждена. Повреждённый файл сохранён рядом с данными памяти, а пустой индекс создан заново. Заново синхронизируйте источники памяти, чтобы заполнить его.',diff --git a/app/src/lib/i18n/zh-CN.ts b/app/src/lib/i18n/zh-CN.tsindex 75a2a9bcb3..d2c0e1ccbc 100644--- a/app/src/lib/i18n/zh-CN.ts+++ b/app/src/lib/i18n/zh-CN.ts@@ -6191,6 +6191,9 @@ const messages: TranslationMap = {'userErrors.localModelUnavailable.title': '本地模型不可用','userErrors.localModelUnavailable.body':'无法在配置的端点连接 Ollama,或所需模型未安装在该端点。请启动 Ollama 并在该端点拉取模型,或将此工作切换到云端提供商。',+ 'userErrors.replyDeliveryFailed.title': '无法显示回复',+ 'userErrors.replyDeliveryFailed.body':+ '智能体已完成这一轮,但它的回复既没能保存也没能重新读取。再问一次即可让它重复回复。','userErrors.memoryStoreCorrupt.title': '记忆索引已损坏','userErrors.memoryStoreCorrupt.body':'记忆树使用的数据库已损坏。受损文件已保留在记忆数据旁边,并已重建一个空索引。请重新同步记忆来源以重新填充。',diff --git a/app/src/lib/userErrors/classify.ts b/app/src/lib/userErrors/classify.tsindex b2dad07116..82f95a04a3 100644--- a/app/src/lib/userErrors/classify.ts+++ b/app/src/lib/userErrors/classify.ts@@ -127,6 +127,30 @@ export function classifyIntegrationError(};}+/**+ * #6034: a completed reply that reached neither writer, so there is nothing to+ * render and nothing to re-read.+ *+ * The caller already knows this happened — it just failed an append and a+ * refetch — so, like the two constructors above, this takes the fact rather+ * than sniffing prose. Scoped per thread so two different lost replies are two+ * entries, and one thread failing repeatedly is one entry with a count.+ */+export function classifyReplyDeliveryFailure(threadId: string): UserErrorDescriptor | null {+ const thread = threadId?.trim();+ if (!thread) return null;+ return {+ id: userErrorId('reply_delivery_failed', 'chat', thread),+ kind: 'reply_delivery_failed',+ severity: 'error',+ scope: 'chat',+ sourceDomain: 'chat',+ titleKey: 'userErrors.replyDeliveryFailed.title',+ bodyKey: 'userErrors.replyDeliveryFailed.body',+ action: 'dismiss',+ };+}+/** Build the stable dedupe identity for an error. */export function userErrorId(kind: UserErrorDescriptor['kind'],diff --git a/app/src/providers/ChatRuntimeProvider.tsx b/app/src/providers/ChatRuntimeProvider.tsxindex 8e838b0525..a1279bc9db 100644--- a/app/src/providers/ChatRuntimeProvider.tsx+++ b/app/src/providers/ChatRuntimeProvider.tsx@@ -7,6 +7,7 @@ import {createSkillToolChainLatencyTracker,SKILL_TOOL_CHAIN_TARGET_MS,} from '../lib/ai/skillToolChainLatency';+import { classifyReplyDeliveryFailure } from '../lib/userErrors/classify';import { ingestRuntimeErrorSignal } from '../lib/userErrors/report';import { maybeParseWorkflowProposalTool } from '../lib/workflows/workflowProposal';import {@@ -79,6 +80,7 @@ import {setActiveThread,setSelectedThread,} from '../store/threadSlice';+import { reportUserError } from '../store/userErrorsSlice';import { IS_PROD } from '../utils/config';import { AssistantUiRuntimeProvider } from './AssistantUiRuntimeProvider';import { isProactiveConversationSurface, proactiveThreadPins } from './proactiveThreadPins';@@ -501,6 +503,20 @@ const ChatRuntimeProvider = ({ children }: { children: React.ReactNode }) => {}};+ /**+ * Tell the user a finished reply could not be shown.+ *+ * The turn ran and was paid for, and by this point neither writer left a+ * row — so a console line is the wrong place for it. An in-thread message+ * is not an option either: writing one needs the very append that just+ * failed. The shell's notice panel is the surface that does not depend on+ * the thread store.+ */+ const reportLostReply = (threadId: string) => {+ const descriptor = classifyReplyDeliveryFailure(threadId);+ if (descriptor) dispatch(reportUserError({ descriptor, at: Date.now() }));+ };+/*** Put a delivered reply back on screen after our own append failed.*@@ -529,6 +545,7 @@ const ChatRuntimeProvider = ({ children }: { children: React.ReactNode }) => {refetchError instanceof Error ? refetchError.message : String(refetchError),});+ reportLostReply(event.thread_id);return;}const recovered = expectedId@@ -548,6 +565,7 @@ const ChatRuntimeProvider = ({ children }: { children: React.ReactNode }) => {requestId: event.request_id,appendError: cause instanceof Error ? cause.message : String(cause),});+ reportLostReply(event.thread_id);};const finishChatDoneTurn = async (event: ChatDoneEvent, path: string) => {@@ -1602,11 +1620,22 @@ const ChatRuntimeProvider = ({ children }: { children: React.ReactNode }) => {if (socketStatus !== 'connected') return;const interrupted = interruptedThreadsRef.current;if (interrupted.size === 0) return;- interruptedThreadsRef.current = new Set();rtLog('socket_reconnect_heal', { threads: interrupted.size });- for (const threadId of interrupted) {- socketService.subscribeThread(threadId);- void dispatch(loadThreadMessages(threadId));+ for (const threadId of [...interrupted]) {+ // Read only after the room join is acknowledged. Firing both at once+ // leaves a window where the read misses a reply that lands a moment+ // later and the turn's `chat_done` goes to a room we have not joined+ // yet — the reply would then stay invisible until a manual reload.+ // `subscribeThread` resolves `false` on its own timeout, or immediately+ // if the socket has already dropped again, so the read is never skipped.+ void socketService.subscribeThread(threadId).then(joined => {+ // Forget the thread only once it is provably back in its room. A+ // socket that dropped again between `connected` and this effect never+ // emitted, and dropping the id here would strand that thread until the+ // user reselected it; keeping it means the next connection retries.+ if (joined) interruptedThreadsRef.current.delete(threadId);+ return dispatch(loadThreadMessages(threadId));+ });}}, [socketStatus, dispatch]);diff --git a/app/src/providers/__tests__/ChatRuntimeProvider.test.tsx b/app/src/providers/__tests__/ChatRuntimeProvider.test.tsxindex 48e976e1ff..eb7ddff5b6 100644--- a/app/src/providers/__tests__/ChatRuntimeProvider.test.tsx+++ b/app/src/providers/__tests__/ChatRuntimeProvider.test.tsx@@ -45,7 +45,9 @@ vi.mock('../../services/api/threadApi', () => ({},}));-vi.mock('../../services/socketService', () => ({ socketService: { subscribeThread: vi.fn() } }));+vi.mock('../../services/socketService', () => ({+ socketService: { subscribeThread: vi.fn(() => Promise.resolve(true)) },+}));vi.mock('../../hooks/usageRefresh', () => ({ requestUsageRefresh: vi.fn() }));@@ -634,6 +636,34 @@ describe('ChatRuntimeProvider — dedupe, proactive resolution, mid-turn invariaexpect(persisted.sender).toBe('agent');});+ it('surfaces a user-visible error when neither writer stored the reply (#6034)', async () => {+ vi.mocked(threadApi.appendMessage).mockRejectedValueOnce(new Error('rpc timeout'));+ // The refetch succeeds but the row is genuinely not there — the case+ // where the core write failed too. A console line is not enough here:+ // the user is looking at a finished turn with no answer.+ vi.mocked(threadApi.getThreadMessages).mockResolvedValueOnce({+ messages: [],+ } as unknown as Awaited<ReturnType<typeof threadApi.getThreadMessages>>);++ const listeners = renderProvider();+ act(() => {+ listeners.onDone?.({+ thread_id: 't-gone',+ request_id: 'r-gone',+ full_response: 'an answer nobody stored',+ rounds_used: 1,+ });+ });++ await waitFor(() =>+ expect(+ Object.values(store.getState().userErrors.byId).some(+ e => e.kind === 'reply_delivery_failed'+ )+ ).toBe(true)+ );+ });+it('keeps a generated id for a segmented chat_done (the core left those rows to us)', async () => {const listeners = renderProvider();@@ -1179,6 +1209,40 @@ describe('ChatRuntimeProvider — dedupe, proactive resolution, mid-turn invariaawait waitFor(() => expect(threadApi.getThreadMessages).toHaveBeenCalledWith('t-away'));});+ it('retries a thread whose room join never emitted, on the next connection', async () => {+ vi.mocked(threadApi.getThreadMessages).mockResolvedValue({+ messages: [],+ } as unknown as Awaited<ReturnType<typeof threadApi.getThreadMessages>>);+ // The socket dropped again between `connected` and this effect, so the+ // emit never went out. Forgetting the thread here would strand it until+ // the user reselected it.+ vi.mocked(socketService.subscribeThread).mockResolvedValueOnce(false);++ renderProvider();+ act(() => {+ store.dispatch(setActiveThread('t-flaky'));+ });+ act(() => {+ store.dispatch(setStatusForUser({ userId: '__pending__', status: 'disconnected' }));+ });+ act(() => {+ store.dispatch(setStatusForUser({ userId: '__pending__', status: 'connected' }));+ });+ await waitFor(() => expect(socketService.subscribeThread).toHaveBeenCalledWith('t-flaky'));++ vi.mocked(socketService.subscribeThread).mockClear();+ vi.mocked(socketService.subscribeThread).mockResolvedValue(true);++ // Second reconnect: the thread is still pending, so it is retried.+ act(() => {+ store.dispatch(setStatusForUser({ userId: '__pending__', status: 'disconnected' }));+ });+ act(() => {+ store.dispatch(setStatusForUser({ userId: '__pending__', status: 'connected' }));+ });+ await waitFor(() => expect(socketService.subscribeThread).toHaveBeenCalledWith('t-flaky'));+ });+it('does nothing on a connect with no interrupted threads', async () => {renderProvider();vi.mocked(socketService.subscribeThread).mockClear();diff --git a/app/src/services/socketService.ts b/app/src/services/socketService.tsindex eb376450fa..7bceae779e 100644--- a/app/src/services/socketService.ts+++ b/app/src/services/socketService.ts@@ -488,10 +488,31 @@ class SocketService {* disconnected call quiet: re-subscription is what the `connect` handler* already does, so a warning here would only be noise.*/- subscribeThread(threadId: string): void {- if (!threadId || !this.socket?.connected) return;+ subscribeThread(threadId: string, timeoutMs = 3000): Promise<boolean> {+ if (!threadId || !this.socket?.connected) return Promise.resolve(false);socketLog('Subscribing to thread room', { threadId });- this.socket.emit('thread:subscribe', { thread_id: threadId });+ const socket = this.socket;+ return new Promise<boolean>(resolve => {+ let settled = false;+ const finish = (joined: boolean) => {+ if (settled) return;+ settled = true;+ resolve(joined);+ };+ // A caller that reads the thread after this resolves cannot race the+ // join: the server acknowledges only once the socket is in the room.+ // The timeout keeps a server that never acks (an older core) from+ // stalling recovery — the read still happens, just without the ordering+ // guarantee, which is exactly the pre-ack behaviour.+ const timer = setTimeout(() => {+ socketWarn('Thread room subscription not acknowledged', { threadId });+ finish(false);+ }, timeoutMs);+ socket.emit('thread:subscribe', { thread_id: threadId }, () => {+ clearTimeout(timer);+ finish(true);+ });+ });}/**diff --git a/app/src/types/userError.ts b/app/src/types/userError.tsindex 49b7293651..6b1e113d6d 100644--- a/app/src/types/userError.ts+++ b/app/src/types/userError.ts@@ -51,7 +51,16 @@ export type UserErrorKind =* rebuilt tree repopulates by re-syncing sources, which is why the action* deep-links to Brain's sync tab rather than any settings screen.*/- | 'memory_store_corrupt';+ | 'memory_store_corrupt'+ /**+ * A reply the agent finished could not be shown: neither the core's write+ * nor the client's append left a row, and re-reading the thread did not+ * find one (#6034). Distinct from every entry above because nothing is+ * misconfigured — the turn ran and was paid for, and the only useful next+ * step is to ask again, so the action is `dismiss` rather than a settings+ * deep link.+ */+ | 'reply_delivery_failed';/** Where the failure originated, for grouping/labelling (privacy-safe). */export type UserErrorScope =diff --git a/src/core/socketio.rs b/src/core/socketio.rsindex 7b453d9816..b5f6910ffb 100644--- a/src/core/socketio.rs+++ b/src/core/socketio.rs@@ -12,7 +12,7 @@ use serde_json::Value;#[cfg(feature = "http-server")]use serde_json::json;#[cfg(feature = "http-server")]-use socketioxide::extract::{Data, SocketRef, TryData};+use socketioxide::extract::{AckSender, Data, SocketRef, TryData};#[cfg(feature = "http-server")]use socketioxide::SocketIo;@@ -428,6 +428,13 @@ struct ThreadSubscribePayload {thread_id: String,}+/// Reply to `thread:subscribe`, so a client can order a read after the join.+#[cfg(feature = "http-server")]+#[derive(Debug, Serialize)]+struct ThreadSubscribeAck {+ joined: bool,+}+/// Attaches the Socket.IO layer to the Axum router and sets up event handlers.////// It configures:@@ -668,19 +675,32 @@ pub fn attach_socketio() -> (socketioxide::layer::SocketIoLayer, SocketIo) {// frontend emits this on connect/reconnect for the active thread, so// the new socket re-joins the thread room and keeps receiving the// stream. Membership is dropped automatically on disconnect.+ //+ // The join is acknowledged so a client can *order* work against it.+ // A reconnecting client re-reads the thread to pick up a reply that+ // landed while it was away (#6034); firing that read before the join+ // is processed leaves a window where the read misses the row and the+ // turn's `chat_done` is emitted to a room this socket has not joined+ // yet, so the reply stays invisible until a manual reload. The ack+ // closes it. Clients that ignore the ack are unaffected — an unused+ // acknowledgement is inert.socket.on("thread:subscribe",- |socket: SocketRef, Data(payload): Data<ThreadSubscribePayload>| async move {+ |socket: SocketRef, Data(payload): Data<ThreadSubscribePayload>, ack: AckSender| async move {if !socket_is_authed(&socket) {drop_unauthed(&socket, "thread:subscribe from unauthenticated socket");return;}let thread_id = payload.thread_id.trim();if thread_id.is_empty() {+ // Still acknowledge: a client awaiting this must not be+ // left hanging on its own malformed payload.+ ack.send(&ThreadSubscribeAck { joined: false }).ok();return;}let room = format!("thread:{thread_id}");join_room_logged(&socket, &room, &socket.id.to_string());+ ack.send(&ThreadSubscribeAck { joined: true }).ok();},);},diff --git a/src/openhuman/web_chat/presentation.rs b/src/openhuman/web_chat/presentation.rsindex e05c2a68fc..d95e117d38 100644--- a/src/openhuman/web_chat/presentation.rs+++ b/src/openhuman/web_chat/presentation.rs@@ -94,14 +94,17 @@ pub(crate) async fn deliver_response(// work that has no business holding a runtime worker while a turn// is settling. Hand it to the blocking pool and await the handle,// which keeps the ordering this whole change rests on.- let (dir, thread, request, reply) = (+ let (dir, thread, request, reply, cites) = (dir.to_path_buf(),thread_id.to_string(),request_id.to_string(),full_response.to_string(),+ citations.to_vec(),);let persisted = tokio::task::spawn_blocking(move || {- super::reply_persistence::persist_delivered_reply(&dir, &thread, &request, &reply)+ super::reply_persistence::persist_delivered_reply(+ &dir, &thread, &request, &reply, &cites,+ )}).await;match persisted {diff --git a/src/openhuman/web_chat/presentation_tests.rs b/src/openhuman/web_chat/presentation_tests.rsindex 7cc7761e59..031f197786 100644--- a/src/openhuman/web_chat/presentation_tests.rs+++ b/src/openhuman/web_chat/presentation_tests.rs@@ -331,13 +331,21 @@ async fn delivery_stores_the_reply_before_announcing_it() {).expect("thread created");+ let citation = crate::openhuman::memory::agent::memory_loader::MemoryCitation {+ id: "mem-deliver".to_string(),+ key: "summary-source".to_string(),+ namespace: None,+ score: Some(0.8),+ timestamp: "2026-09-04T00:00:00Z".to_string(),+ snippet: "source snippet".to_string(),+ };test_support::deliver_response_in_workspace_for_test("client-1","t-deliver","req-deliver","Here is the summary you asked for.","summarise this",- &[],+ &[citation],Some(ws.as_path()),).await;@@ -351,6 +359,12 @@ async fn delivery_stores_the_reply_before_announcing_it() {assert_eq!(messages[0].id, "agent:req-deliver");assert_eq!(messages[0].content, "Here is the summary you asked for.");assert_eq!(messages[0].sender, "agent");+ // The client's append is deduped onto this row, so the citations it would+ // have written must already be here or the chips render empty.+ assert_eq!(+ messages[0].extra_metadata["citations"][0]["id"],+ "mem-deliver"+ );}#[tokio::test]diff --git a/src/openhuman/web_chat/reply_persistence.rs b/src/openhuman/web_chat/reply_persistence.rsindex 59675abb45..b449c4cf7f 100644--- a/src/openhuman/web_chat/reply_persistence.rs+++ b/src/openhuman/web_chat/reply_persistence.rs@@ -22,6 +22,7 @@ use std::path::Path;use serde_json::json;+use crate::openhuman::memory::agent::memory_loader::MemoryCitation;use crate::openhuman::memory::conversations::{self, run_reply_message_id, ConversationMessage};/// Metadata scope stamped on a reply persisted by the web-channel delivery path.@@ -40,16 +41,34 @@ const REPLY_SCOPE: &str = "web_chat_reply";/// Callers must treat an `Err` as non-fatal and announce the reply anyway: the/// client's own append is still a working fallback, and losing the delivery on/// top of losing the row would turn a storage problem into a visibly dead turn.+///+/// **This row's metadata is what the reader ends up with, so it must carry+/// everything the client would have written.** Because the store is idempotent+/// for this id, the client's later append returns *this* row rather than its+/// own, and whatever is missing here is missing from the rendered message —+/// which is how citations vanished in review. `citations` therefore mirrors the+/// shape `chatDoneExtraMetadata` builds, and any field added to that helper+/// belongs here too.pub(crate) fn persist_delivered_reply(workspace_dir: &Path,thread_id: &str,request_id: &str,full_response: &str,+ citations: &[MemoryCitation],) -> Result<bool, String> {let content = full_response.trim();if content.is_empty() {return Ok(false);}+ let mut extra_metadata = json!({+ "scope": REPLY_SCOPE,+ "requestId": request_id,+ });+ if !citations.is_empty() {+ // Same key and payload the client stamps, so a row read back from disk+ // renders identical chips to one the client had appended itself.+ extra_metadata["citations"] = json!(citations);+ }conversations::append_message(workspace_dir.to_path_buf(),thread_id,@@ -57,10 +76,7 @@ pub(crate) fn persist_delivered_reply(id: run_reply_message_id(request_id),content: content.to_string(),message_type: "text".to_string(),- extra_metadata: json!({- "scope": REPLY_SCOPE,- "requestId": request_id,- }),+ extra_metadata,sender: "agent".to_string(),created_at: chrono::Utc::now().to_rfc3339(),},diff --git a/src/openhuman/web_chat/reply_persistence_tests.rs b/src/openhuman/web_chat/reply_persistence_tests.rsindex 28336a3ce5..b1c0ff5f0e 100644--- a/src/openhuman/web_chat/reply_persistence_tests.rs+++ b/src/openhuman/web_chat/reply_persistence_tests.rs@@ -1,6 +1,7 @@use std::path::PathBuf;use super::persist_delivered_reply;+use crate::openhuman::memory::agent::memory_loader::MemoryCitation;use crate::openhuman::memory::conversations::{self, CreateConversationThread};fn temp_ws() -> PathBuf {@@ -29,7 +30,7 @@ fn persists_the_reply_under_the_id_the_client_will_reuse() {let ws = temp_ws();seed_thread(&ws, "t-1");- let stored = persist_delivered_reply(&ws, "t-1", "req-1", "Done, the draft is updated.")+ let stored = persist_delivered_reply(&ws, "t-1", "req-1", "Done, the draft is updated.", &[]).expect("append succeeds");assert!(stored, "a non-empty reply must report that it was stored");@@ -49,12 +50,12 @@ fn a_second_write_of_the_same_turn_does_not_add_a_row() {let ws = temp_ws();seed_thread(&ws, "t-2");- persist_delivered_reply(&ws, "t-2", "req-2", "First").expect("first append");+ persist_delivered_reply(&ws, "t-2", "req-2", "First", &[]).expect("first append");// The client persists the same reply from the `chat_done` it received. The// store's idempotency for deterministic ids is what keeps the thread at one// row; assert the second write here so a change to the id shape (which// would silently opt out of that lookup) fails loudly.- persist_delivered_reply(&ws, "t-2", "req-2", "First").expect("second append");+ persist_delivered_reply(&ws, "t-2", "req-2", "First", &[]).expect("second append");let messages = conversations::get_messages(ws.clone(), "t-2").expect("messages");assert_eq!(messages.len(), 1, "one turn must never leave two rows");@@ -65,7 +66,7 @@ fn an_empty_reply_is_not_stored() {let ws = temp_ws();seed_thread(&ws, "t-3");- let stored = persist_delivered_reply(&ws, "t-3", "req-3", " \n ").expect("no error");+ let stored = persist_delivered_reply(&ws, "t-3", "req-3", " \n ", &[]).expect("no error");assert!(!stored, "an empty reply reports that nothing was stored");assert!(conversations::get_messages(ws.clone(), "t-3").expect("messages")@@ -77,7 +78,7 @@ fn content_is_trimmed_the_way_the_autonomous_path_trims_it() {let ws = temp_ws();seed_thread(&ws, "t-4");- persist_delivered_reply(&ws, "t-4", "req-4", " padded reply\n").expect("append");+ persist_delivered_reply(&ws, "t-4", "req-4", " padded reply\n", &[]).expect("append");let messages = conversations::get_messages(ws.clone(), "t-4").expect("messages");assert_eq!(messages[0].content, "padded reply");@@ -87,7 +88,48 @@ fn content_is_trimmed_the_way_the_autonomous_path_trims_it() {fn a_missing_thread_is_reported_rather_than_silently_dropped() {let ws = temp_ws();- let err = persist_delivered_reply(&ws, "nope", "req-5", "text")+ let err = persist_delivered_reply(&ws, "nope", "req-5", "text", &[]).expect_err("a missing thread must not look like a successful store");assert!(err.contains("nope"), "error names the thread: {err}");}++#[test]+fn citations_ride_on_the_authoritative_row() {+ let ws = temp_ws();+ seed_thread(&ws, "t-6");++ let citation = MemoryCitation {+ id: "mem-1".to_string(),+ key: "draft-location".to_string(),+ namespace: Some("notes".to_string()),+ score: Some(0.91),+ timestamp: "2026-09-04T00:00:00Z".to_string(),+ snippet: "The draft lives in Notion.".to_string(),+ };+ persist_delivered_reply(&ws, "t-6", "req-6", "Updated the draft.", &[citation])+ .expect("append");++ // The client's append is deduped onto this row, so whatever is missing here+ // is missing from the rendered message — citation chips included. Losing+ // them was a real regression caught in review of #6034.+ let messages = conversations::get_messages(ws.clone(), "t-6").expect("messages");+ let cites = messages[0].extra_metadata["citations"]+ .as_array()+ .expect("citations are stored as an array");+ assert_eq!(cites.len(), 1);+ assert_eq!(cites[0]["id"], "mem-1");+}++#[test]+fn a_reply_without_citations_stores_no_citations_key() {+ let ws = temp_ws();+ seed_thread(&ws, "t-7");++ persist_delivered_reply(&ws, "t-7", "req-7", "No sources for this one.", &[]).expect("append");++ let messages = conversations::get_messages(ws.clone(), "t-7").expect("messages");+ assert!(+ messages[0].extra_metadata.get("citations").is_none(),+ "an empty citation list must not add an empty array the client never wrote"+ );+}