Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix(chat): Bilder im Chat sprengen den Speicher nicht mehr

purplea9bab55f8de2
diff --git a/dev-server/__tests__/mlx-media-endpoint-coverage.test.ts b/dev-server/__tests__/mlx-media-endpoint-coverage.test.ts
index 0df25eb8..686be8d9 100644
--- a/dev-server/__tests__/mlx-media-endpoint-coverage.test.ts
+++ b/dev-server/__tests__/mlx-media-endpoint-coverage.test.ts
@@ -139,6 +139,13 @@ describe('endpointMap covers every backendCall/invokeMedia site the frontend can
// shell_execute_cancel below, same reasoning, same Tauri-only shape
// (Rust kills the process tree by callId, no HTTP route makes sense).
'execute_code_cancel',
+ // Chat attachments (OOM fix, 2026-09-26): files beside store_backup.json
+ // and native Save As / Open dialogs. Every call site sits behind isTauri()
+ // (lib/chat-attachments.ts, ChatAttachment.tsx, chat-export.ts,
+ // ChatBackupSettings.tsx); the browser build keeps its images in IndexedDB
+ // and exports through a blob download, so there is no dev route to add.
+ 'export_chats_dialog', 'import_chats_dialog', 'read_chat_attachment',
+ 'save_binary_file_dialog', 'save_chat_attachment_dialog', 'write_chat_attachment',
'exit_app', 'file_read', 'find_orphan_downloads', 'fix_comfyui_cors', 'funnel_ping',
'get_comfy_gpu_status', 'get_current_time', 'import_local_model', 'install_character_trainer',
'install_lmstudio', 'install_lmstudio_status', 'install_method', 'install_python',
diff --git a/e2e/image-memory-proof.html b/e2e/image-memory-proof.html
new file mode 100644
index 00000000..f5b62173
--- /dev/null
+++ b/e2e/image-memory-proof.html
@@ -0,0 +1,79 @@
+<!doctype html><html lang="en"><meta charset="utf-8"><title>Chat image memory regression</title>
+<style>body{font:16px system-ui;background:#18181b;color:#eee;max-width:900px;margin:40px auto}button{padding:12px;margin-right:12px}pre{white-space:pre-wrap}</style>
+<h1>Chat image memory regression</h1><p>Synthetic images only. No model requests, no customer data.</p>
+<button id="run">Run upload and history test</button><button id="restore">Verify saved chat after reload</button><pre id="out">Ready</pre>
+<script type="module">
+import { prepareChatImage, prepareChatImages, MAX_IMAGE_BYTES, MAX_IMAGE_EDGE } from '/src/lib/chat-image-input.ts'
+import { useChatStore, flushChatPersist } from '/src/stores/chatStore.ts'
+import { idbStorage } from '/src/lib/idbStorage.ts'
+const out = document.querySelector('#out')
+const show = data => { out.textContent = JSON.stringify(data, null, 2) }
+const assert = (ok, reason) => { if (!ok) throw new Error(reason) }
+const toBlob = canvas => new Promise(resolve => canvas.toBlob(resolve, 'image/png'))
+const { originalAttachment, isAttachmentReference } = await import('/src/lib/chat-attachments.ts')
+const fromData = image => new Blob([Uint8Array.from(atob(image.data), c => c.charCodeAt(0))], {type:image.mimeType})
+const stored = () => new Promise((resolve,reject) => {
+ setTimeout(() => { if (!useChatStore.persist.hasHydrated()) reject(new Error('Store hydration timed out')) }, 5000)
+ if (useChatStore.persist.hasHydrated()) resolve()
+ else { const stop = useChatStore.persist.onFinishHydration(() => { stop(); resolve() }) }
+})
+document.querySelector('#run').onclick = async () => {
+ try {
+ show({status:'starting'})
+ await stored()
+ show({status:'creating synthetic image'})
+ const canvas = document.createElement('canvas'); canvas.width = 2600; canvas.height = 1800
+ const ctx = canvas.getContext('2d'); const pixels = ctx.createImageData(canvas.width, canvas.height)
+ let random = 42
+ for(let i=0;i<pixels.data.length;i+=4){random=(Math.imul(random,1664525)+1013904223)>>>0; pixels.data[i]=random&255; pixels.data[i+1]=(random>>>8)&255; pixels.data[i+2]=(random>>>16)&255; pixels.data[i+3]=255}
+ ctx.putImageData(pixels,0,0)
+ show({status:'encoding fixture'}); const blob = await toBlob(canvas); show({status:'fixture encoded',bytes:blob.size}); canvas.width=canvas.height=0
+ const file = new File([blob], 'synthetic-photo.png', {type:'image/png'})
+ const started = performance.now()
+ show({status:'preparing first batch',bytes:file.size}); const selection = await prepareChatImages(Array(100).fill(file), 5, undefined, async f => { show({status:'decoding file',bytes:f.size}); const result = await prepareChatImage(f); show({status:'file prepared',base64:result.data.length}); return result })
+ assert(selection.images.length===5 && !selection.errors.length, 'five selected images should succeed: '+selection.errors)
+ let largest = 0, firstDimensions
+ for(const image of selection.images){
+ const bytes = fromData(image); assert(bytes.size<=MAX_IMAGE_BYTES,'encoded budget exceeded'); largest=Math.max(largest, bytes.size)
+ const bitmap = await createImageBitmap(bytes); assert(Math.max(bitmap.width,bitmap.height)<=MAX_IMAGE_EDGE,'pixel budget exceeded'); firstDimensions=[bitmap.width,bitmap.height];bitmap.close()
+ }
+ const s=useChatStore.getState(); const id=s.createConversation('memory-regression', 'local'); localStorage.setItem('memory-proof-id',id)
+ let lastAnswer
+ for(let turn=0;turn<20;turn++){
+ const batch=turn===0?selection:await prepareChatImages(Array(5).fill(file),5)
+ assert(batch.images.length===5&&!batch.errors.length,'repeat upload failed')
+ useChatStore.getState().addMessage(id,{id:crypto.randomUUID(),timestamp:Date.now(),role:'user',content:'Synthetic image turn '+turn,images:batch.images})
+ lastAnswer=crypto.randomUUID();useChatStore.getState().addMessage(id,{id:lastAnswer,timestamp:Date.now(),role:'assistant',content:''})
+ for(let chunk=1;chunk<=30;chunk++){
+ useChatStore.getState().updateMessageContent(id,lastAnswer,'Synthetic answer '+turn+' '+'.'.repeat(chunk))
+ await new Promise(resolve=>setTimeout(resolve,2))
+ }
+ await flushChatPersist()
+ show({status:'running',completedTurns:turn+1,totalTurns:20,originalBytes:file.size,largestPreparedBytes:largest})
+ }
+ // The next turn has no images, as in the second customer report.
+ useChatStore.getState().addMessage(id,{id:crypto.randomUUID(),timestamp:Date.now(),role:'user',content:'Text only after image history'})
+ useChatStore.getState().addMessage(id,{id:crypto.randomUUID(),timestamp:Date.now(),role:'assistant',content:'TEXT_ONLY_OK'})
+ await flushChatPersist()
+ const saved=JSON.parse(await idbStorage.getItem('chat-conversations'))
+ const conv=saved.state.conversations.find(c=>c.id===id)
+ assert(conv.messages.length===42,'history missing messages')
+ assert(conv.messages.filter(m=>m.images?.length).length===20,'images missing')
+ assert(conv.messages.flatMap(m=>m.images??[]).every(img=>isAttachmentReference(img.data)), 'images must be references after persist')
+ assert(JSON.stringify(conv).length < 40000, 'chat metadata must remain small')
+ const result={status:'PASS',turns:20,images:100,messages:42,textOnlyTurn:true,originalBytes:file.size,largestPreparedBytes:largest,preparedDimensions:firstDimensions,reductionPercent:100*(1-largest/file.size),persistedBytes:new Blob([JSON.stringify(saved)]).size,elapsedSeconds:(performance.now()-started)/1000}
+ localStorage.setItem('memory-proof-result',JSON.stringify(result));show(result)
+ }catch(error){show({status:'FAIL',error:String(error),stack:error.stack})}
+}
+document.querySelector('#restore').onclick=async()=>{
+ try{
+ await stored();const id=localStorage.getItem('memory-proof-id');const conv=useChatStore.getState().conversations.find(c=>c.id===id)
+ assert(conv?.messages.length===42,'reloaded history incomplete');assert(conv.messages.at(-1).content==='TEXT_ONLY_OK','final text lost')
+ let count=0
+ for(const m of conv.messages) for(const img of m.images??[]){const bitmap=await createImageBitmap(fromData(await originalAttachment(img)));assert(bitmap.width>0,'broken image');bitmap.close();count++}
+ assert(count===100,'attachments lost on restart')
+ show({status:'PASS_AFTER_RELOAD',chatBytesAfter:JSON.stringify(conv).length,messages:conv.messages.length,decodedImages:count,previous:JSON.parse(localStorage.getItem('memory-proof-result'))})
+ }catch(error){show({status:'FAIL',error:String(error)})}
+}
+out.textContent='Ready (modules loaded)'
+</script></html>
diff --git a/e2e/legacy-profile-proof.html b/e2e/legacy-profile-proof.html
new file mode 100644
index 00000000..98706d3b
--- /dev/null
+++ b/e2e/legacy-profile-proof.html
@@ -0,0 +1,118 @@
+<!doctype html><html><head><meta charset="utf-8"><title>Legacy profile proof</title></head><body>
+<!--
+ A customer profile from before the attachment store, in a real Chromium:
+ N images of M MiB base64 each, inline in the saved chat history.
+
+ ?seed&images=100&mib=2 writes that profile straight into IndexedDB
+ (no app module loaded, like an old build left it)
+ ?launch loads the chat store the way the app does and
+ measures hydration, every write, the migration
+ ?verify second launch: small value, every image readable
+
+ Run through vite.memory-proof.config.ts (port 5297). Synthetic data only.
+-->
+<pre id="out">loading</pre>
+<script type="module">
+const out = document.querySelector('#out')
+const show = v => { out.textContent = JSON.stringify(v, null, 2); document.title = v.status }
+const params = new URLSearchParams(location.search)
+const heap = () => performance.memory ? Math.round(performance.memory.usedJSHeapSize / 1048576) : null
+const assert = (ok, msg) => { if (!ok) throw new Error(msg) }
+
+function rawIdb() {
+ return new Promise((resolve, reject) => {
+ const req = indexedDB.open('locally-uncensored-store', 1)
+ req.onupgradeneeded = () => req.result.createObjectStore('kv')
+ req.onsuccess = () => resolve(req.result)
+ req.onerror = () => reject(req.error)
+ })
+}
+async function rawGet(key) {
+ const db = await rawIdb()
+ return new Promise(r => { const q = db.transaction('kv').objectStore('kv').get(key); q.onsuccess = () => r(q.result) })
+}
+async function rawPut(key, value) {
+ const db = await rawIdb()
+ return new Promise((r, j) => { const tx = db.transaction('kv', 'readwrite'); tx.objectStore('kv').put(value, key); tx.oncomplete = r; tx.onerror = tx.onabort = () => j(tx.error ?? new Error('transaction aborted')) })
+}
+
+try {
+ if (params.has('seed')) {
+ const images = Number(params.get('images') ?? 100), mib = Number(params.get('mib') ?? 2)
+ await new Promise(r => { const q = indexedDB.deleteDatabase('lu-chat-attachments'); q.onsuccess = q.onerror = q.onblocked = r })
+ show({ status: 'SEEDING', images, mib })
+ const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
+ const block = Array.from({ length: 65536 }, (_, i) => alphabet[(i * 7919) % 64]).join('')
+ const conversations = []
+ for (let c = 0; c < images / 5; c++) {
+ const messages = []
+ for (let t = 0; t < 5; t++) {
+ const n = c * 5 + t
+ // Unique per image, so content addressing cannot fold them together.
+ const data = String(n).padStart(8, 'A').replace(/[^A-Za-z0-9]/g, 'A') + block.repeat(Math.ceil(mib * 16)).slice(8, mib * 1048576)
+ messages.push({ id: `u${n}`, role: 'user', content: `photo ${n}`, timestamp: n, images: [{ data, mimeType: 'image/jpeg', name: `p${n}.jpg` }] })
+ messages.push({ id: `a${n}`, role: 'assistant', content: `answer ${n}`, timestamp: n + 0.5 })
+ }
+ conversations.push({ id: `chat${c}`, title: `chat ${c}`, createdAt: c, updatedAt: c, messages })
+ }
+ const value = JSON.stringify({ state: { conversations, activeConversationId: 'chat0' }, version: 0 })
+ await rawPut('chat-conversations', value)
+ localStorage.setItem('proof-seed', JSON.stringify({ images, mib, bytes: value.length }))
+ show({ status: 'SEEDED', images, mib, historyMiB: Math.round(value.length / 1048576) })
+ } else if (params.has('launch')) {
+ const t0 = performance.now()
+ const writes = []
+ const { onIdbWrite } = await import('/src/lib/idbStorage.ts')
+ onIdbWrite((key, value) => {
+ if (key !== 'chat-conversations' || value == null) return
+ const conversations = JSON.parse(value).state.conversations
+ writes.push({ atMs: Math.round(performance.now() - t0), bytes: value.length, chats: conversations.length,
+ inline: conversations.reduce((n, c) => n + c.messages.filter(m => m.images?.some(i => !i.data.startsWith('lu-attachment:'))).length, 0) })
+ })
+ const { useChatStore } = await import('/src/stores/chatStore.ts')
+ const { isBackupHeld } = await import('/src/lib/backup-hold.ts')
+ // What the app does at launch before hydration is done.
+ useChatStore.getState().setActiveConversationModel('proof-model')
+ useChatStore.getState().createConversation('proof-model', '')
+ let peak = heap()
+ const sample = setInterval(() => { peak = Math.max(peak ?? 0, heap() ?? 0) }, 50)
+ await new Promise(r => useChatStore.persist.hasHydrated() ? r() : useChatStore.persist.onFinishHydration(r))
+ const hydratedMs = Math.round(performance.now() - t0)
+ const writesBeforeHydration = writes.filter(w => w.atMs <= hydratedMs).length
+ const heldDuringMigration = isBackupHeld()
+ while (writes.length === 0 || writes.at(-1).inline > 0) await new Promise(r => setTimeout(r, 100))
+ // Let the swap and its follow-up write land.
+ await new Promise(r => setTimeout(r, 1000))
+ clearInterval(sample)
+ const seed = JSON.parse(localStorage.getItem('proof-seed'))
+ const state = useChatStore.getState()
+ assert(writesBeforeHydration === 0, 'a write happened before hydration')
+ assert(writes.every(w => w.chats >= seed.images / 5), 'a write carried fewer chats than the profile has')
+ assert(state.conversations.flatMap(c => c.messages).every(m => !m.images || m.images.every(i => i.data.startsWith('lu-attachment:'))), 'live state still inline')
+ assert(!isBackupHeld(), 'backup still held after migration')
+ const stored = await rawGet('chat-conversations')
+ const result = { status: 'PASS_LAUNCH', seed, hydratedMs, migratedMs: writes.at(-1).atMs, writes, heldDuringMigration,
+ storedBytesAfter: stored.length, heapMiBPeak: peak, heapMiBNow: heap() }
+ localStorage.setItem('proof-launch', JSON.stringify(result))
+ show(result)
+ } else if (params.has('verify')) {
+ const t0 = performance.now()
+ const { useChatStore } = await import('/src/stores/chatStore.ts')
+ const { originalAttachment } = await import('/src/lib/chat-attachments.ts')
+ await new Promise(r => useChatStore.persist.hasHydrated() ? r() : useChatStore.persist.onFinishHydration(r))
+ const hydratedMs = Math.round(performance.now() - t0)
+ const seed = JSON.parse(localStorage.getItem('proof-seed'))
+ const images = useChatStore.getState().conversations.flatMap(c => c.messages.flatMap(m => m.images ?? []))
+ assert(images.length === seed.images, `expected ${seed.images} images, found ${images.length}`)
+ let checked = 0
+ for (const image of images) {
+ const original = await originalAttachment(image)
+ assert(original.data.length === seed.mib * 1048576, `original changed size: ${original.data.length}`)
+ checked++
+ }
+ const texts = useChatStore.getState().conversations.flatMap(c => c.messages.map(m => m.content))
+ assert(texts.filter(t => t.startsWith('answer ')).length === seed.images, 'assistant text lost')
+ show({ status: 'PASS_VERIFY', hydratedMs, imagesReadable: checked, storedBytes: (await rawGet('chat-conversations')).length, heapMiB: heap(), launch: JSON.parse(localStorage.getItem('proof-launch')) })
+ } else show({ status: 'IDLE' })
+} catch (error) { show({ status: 'FAIL', error: String(error), stack: error.stack }) }
+</script></body></html>
diff --git a/src-tauri/src/commands/chat_attachments.rs b/src-tauri/src/commands/chat_attachments.rs
new file mode 100644
index 00000000..55bd7358
--- /dev/null
+++ b/src-tauri/src/commands/chat_attachments.rs
@@ -0,0 +1,605 @@
+//! Chat image attachments, stored as files beside the native store backup.
+//!
+//! A chat image used to live inline in the chat history as base64, and the
+//! history is serialised as one string on every save, every backup and every
+//! restore. A few dozen phone photos made that string hundreds of megabytes
+//! and took the renderer down with "Out of Memory". The WebView now stores a
+//! reference (`lu-attachment:v1:<sha256>`) and the bytes live here.
+//!
+//! Everything that has to touch a whole history with its images happens on
+//! this side, in native memory and off the main thread:
+//! * restore: an old backup is migrated before the WebView sees it,
+//! * export: references are replaced by the image bytes while streaming to
+//! the chosen file, so the WebView never builds the full export string,
+//! * import: an export with inline images is moved into files before the
+//! WebView parses it.
+//!
+//! Files are content addressed and immutable. No caller-supplied paths: the id
+//! is 64 lowercase hex characters or the call is refused.
+
+use crate::os_error;
+use base64::Engine;
+use serde_json::Value;
+use sha2::{Digest, Sha256};
+use std::collections::HashSet;
+use std::io::{BufWriter, Read, Write};
+use std::path::{Path, PathBuf};
+use std::sync::Mutex;
+use std::time::{Duration, Instant};
+
+pub(crate) const PREFIX: &str = "lu-attachment:v1:";
+const CHAT_KEY: &str = "chat-conversations";
+
+pub(crate) fn attachment_dir() -> Result<PathBuf, String> {
+ Ok(crate::commands::system::persistent_dir()?.join("chat-attachments"))
+}
+
+fn is_id(id: &str) -> bool {
+ id.len() == 64 && id.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
+}
+
+fn attachment_path(dir: &Path, id: &str) -> Result<PathBuf, String> {
+ if !is_id(id) {
+ return Err("Invalid attachment id".into());
+ }
+ Ok(dir.join(id))
+}
+
+pub(crate) fn content_id(data: &str) -> String {
+ format!("{:x}", Sha256::digest(data.as_bytes()))
+}
+
+/// Write one attachment. Idempotent: an intact file with this id is left
+/// alone, a damaged one is replaced, and the rename is atomic either way.
+pub(crate) fn write_attachment(dir: &Path, id: &str, data: &str) -> Result<(), String> {
+ let path = attachment_path(dir, id)?;
+ if content_id(data) != id {
+ return Err("Attachment checksum mismatch".into());
+ }
+ if read_attachment(dir, id).is_ok() {
+ return Ok(());
+ }
+ std::fs::create_dir_all(dir).map_err(|e| os_error::english(&e))?;
+ let mut tmp = tempfile::NamedTempFile::new_in(dir).map_err(|e| os_error::english(&e))?;
+ tmp.write_all(data.as_bytes()).map_err(|e| os_error::english(&e))?;
+ tmp.as_file().sync_all().map_err(|e| os_error::english(&e))?;
+ tmp.persist(&path).map_err(|e| os_error::english(&e.error))?;
+ Ok(())
+}
+
+pub(crate) fn read_attachment(dir: &Path, id: &str) -> Result<String, String> {
+ let path = attachment_path(dir, id)?;
+ let data = std::fs::read_to_string(&path)
+ .map_err(|_| "Chat attachment is missing. Please attach the original image again.".to_string())?;
+ if content_id(&data) != id {
+ return Err("Chat attachment is damaged. Please attach the original image again.".into());
+ }
+ Ok(data)
+}
+
+#[tauri::command]
+pub async fn write_chat_attachment(id: String, data: String) -> Result<(), String> {
+ tauri::async_runtime::spawn_blocking(move || write_attachment(&attachment_dir()?, &id, &data))
+ .await
+ .map_err(|e| e.to_string())?
+}
+
+#[tauri::command]
+pub async fn read_chat_attachment(id: String) -> Result<String, String> {
+ tauri::async_runtime::spawn_blocking(move || read_attachment(&attachment_dir()?, &id))
+ .await
+ .map_err(|e| e.to_string())?
+}
+
+// ── Moving inline images into files ─────────────────────────────────────
+
+/// Replace every inline image in a list of conversations by a reference.
+/// An image whose file cannot be written keeps its inline data: slower, never
+/// lost. Returns how many images moved.
+fn externalize_conversations(conversations: &mut Value, dir: &Path) -> usize {
+ let mut moved = 0;
+ let Some(list) = conversations.as_array_mut() else { return 0 };
+ for conversation in list {
+ let Some(messages) = conversation.get_mut("messages").and_then(Value::as_array_mut) else { continue };
+ for message in messages {
+ let Some(images) = message.get_mut("images").and_then(Value::as_array_mut) else { continue };
+ for image in images {
+ let Some(data) = image.get("data").and_then(Value::as_str) else { continue };
+ if data.is_empty() || data.starts_with(PREFIX) {
+ continue;
+ }
+ let id = content_id(data);
+ match write_attachment(dir, &id, data) {
+ Ok(()) => {
+ image["data"] = Value::String(format!("{PREFIX}{id}"));
+ moved += 1;
+ }
+ Err(e) => tracing::warn!("chat image stays inline, its file could not be written: {e}"),
+ }
+ }
+ }
+ }
+ moved
+}
+
+/// The store backup with its chat images moved into files, or None when there
+/// was nothing to move (or nothing this function understands, in which case the
+/// caller hands the backup over unchanged, exactly as before).
+pub(crate) fn externalize_store_backup(raw: &str, dir: &Path) -> Option<String> {
+ // Cheap exit for every backup written since the attachment store: no
+ // inline image, no parse.
+ if !raw.contains("\\\"images\\\"") {
+ return None;
+ }
+ let Ok(Value::Object(mut outer)) = serde_json::from_str::<Value>(raw) else { return None };
+ let mut inner: Value = serde_json::from_str(outer.get(CHAT_KEY)?.as_str()?).ok()?;
+ let moved = externalize_conversations(inner.pointer_mut("/state/conversations")?, dir);
+ if moved == 0 {
+ return None;
+ }
+ tracing::info!("moved {moved} chat images out of the store backup");
+ outer.insert(CHAT_KEY.into(), Value::String(inner.to_string()));
+ Some(Value::Object(outer).to_string())
+}
+
+/// An import file with its inline images moved into files. Accepts the three
+/// shapes the WebView accepts (bundle, bare array, single conversation) and
+/// hands the file back in the same shape.
+pub(crate) fn externalize_import(raw: &str, dir: &Path) -> Result<String, String> {
+ let mut data: Value = serde_json::from_str(raw).map_err(|_| "That file is not valid JSON.".to_string())?;
+ if data.is_array() {
+ externalize_conversations(&mut data, dir);
+ } else if let Some(list) = data.get_mut("conversations").filter(|v| v.is_array()) {
+ externalize_conversations(list, dir);
+ } else if data.get("messages").map(Value::is_array).unwrap_or(false) {
+ let mut wrapped = Value::Array(vec![data]);
+ externalize_conversations(&mut wrapped, dir);
+ data = wrapped.as_array_mut().and_then(|a| a.pop()).unwrap_or(Value::Null);
+ }
+ Ok(data.to_string())
+}
+
+// ── Export ───────────────────────────────────────────────────────────────
+
+/// Write an export, replacing every `"data": "lu-attachment:v1:<id>"` by the
+/// image itself. The WebView sends the small form (references), this streams
+/// the large one to disk, so no full export string ever exists in memory.
+/// A reference whose file is missing stays as it is and is counted.
+pub(crate) fn write_export<W: Write>(content: &str, out: &mut W, dir: &Path) -> std::io::Result<usize> {
+ let mut missing = 0;
+ let mut at = 0;
+ while let Some(found) = content[at..].find(PREFIX) {
+ let start = at + found;
+ let id_end = start + PREFIX.len() + 64;
+ let id = content.get(start + PREFIX.len()..id_end).unwrap_or("");
+ let is_image_data = is_id(id)
+ && content[..start].ends_with('"')
+ && content[id_end..].starts_with('"')
+ && content[..start - 1].trim_end().strip_suffix(':').map(|k| k.trim_end().ends_with("\"data\"")).unwrap_or(false);
+ out.write_all(content[at..start].as_bytes())?;
+ if is_image_data {
+ match read_attachment(dir, id) {
+ Ok(data) => out.write_all(data.as_bytes())?,
+ Err(_) => {
+ missing += 1;
+ out.write_all(content[start..id_end].as_bytes())?;
+ }
+ }
+ at = id_end;
+ } else {
+ out.write_all(PREFIX.as_bytes())?;
+ at = start + PREFIX.len();
+ }
+ }
+ out.write_all(content[at..].as_bytes())?;
+ Ok(missing)
+}
+
+#[derive(serde::Serialize)]
+pub struct ExportOutcome {
+ path: String,
+ missing: usize,
+}
+
+/// Save As for a chat export (one chat or all), with the images put back in.
+#[tauri::command]
+#[allow(non_snake_case)]
+pub async fn export_chats_dialog(content: String, defaultName: String) -> Result<Option<ExportOutcome>, String> {
+ let Some(handle) = rfd::AsyncFileDialog::new()
+ .set_file_name(&defaultName)
+ .add_filter("JSON", &["json"])
+ .save_file()
+ .await
+ else {
+ return Ok(None);
+ };
+ let path = handle.path().to_path_buf();
+ tauri::async_runtime::spawn_blocking(move || {
+ let dir = attachment_dir()?;
+ let written = std::fs::File::create(&path).and_then(|file| {
+ let mut out = BufWriter::new(file);
+ let missing = write_export(&content, &mut out, &dir)?;
+ out.flush()?;
+ out.get_ref().sync_all()?;
+ Ok(missing)
+ });
+ match written {
+ Ok(missing) => Ok(Some(ExportOutcome { path: path.to_string_lossy().into_owned(), missing })),
+ Err(e) => {
+ // A half written export must not look like a finished one.
+ let _ = std::fs::remove_file(&path);
+ Err(format!("Write failed: {}", os_error::english(&e)))
+ }
+ }
+ })
+ .await
+ .map_err(|e| e.to_string())?
+}
+
+/// Open dialog for a chat import. Returns the file with its inline images
+/// already moved into attachments, or None when the user cancelled.
+#[tauri::command]
+pub async fn import_chats_dialog() -> Result<Option<String>, String> {
+ let Some(handle) = rfd::AsyncFileDialog::new().add_filter("JSON", &["json"]).pick_file().await else {
+ return Ok(None);
+ };
+ let path = handle.path().to_path_buf();
+ tauri::async_runtime::spawn_blocking(move || {
+ let raw = std::fs::read_to_string(&path).map_err(|_| "Could not read that file.".to_string())?;
+ externalize_import(&raw, &attachment_dir()?).map(Some)
+ })
+ .await
+ .map_err(|e| e.to_string())?
+}
+
+/// Save one chat image as a real image file. The WebView's own download path
+/// (an anchor on a blob URL) is unreliable in WebView2, see
+/// `save_binary_file_dialog`.
+#[tauri::command]
+#[allow(non_snake_case)]
+pub async fn save_chat_attachment_dialog(id: String, defaultName: String, mimeType: String) -> Result<Option<String>, String> {
+ let data = tauri::async_runtime::spawn_blocking(move || read_attachment(&attachment_dir()?, &id))
+ .await
+ .map_err(|e| e.to_string())??;
+ let bytes = base64::engine::general_purpose::STANDARD
+ .decode(data.as_bytes())
+ .map_err(|_| "Chat attachment is damaged. Please attach the original image again.".to_string())?;
+ let ext = match mimeType.as_str() {
+ "image/jpeg" | "image/jpg" => "jpg",
+ "image/webp" => "webp",
+ "image/gif" => "gif",
+ "image/bmp" => "bmp",
+ "image/avif" => "avif",
+ _ => "png",
+ };
+ let Some(handle) = rfd::AsyncFileDialog::new()
+ .set_file_name(&defaultName)
+ .add_filter("Image", &[ext])
+ .save_file()
+ .await
+ else {
+ return Ok(None);
+ };
+ let path = handle.path().to_path_buf();
+ std::fs::write(&path, &bytes).map_err(|e| format!("Write failed: {}", os_error::english(&e)))?;
+ Ok(Some(path.to_string_lossy().into_owned()))
+}
+
+// ── Deleting what nothing points at any more ────────────────────────────
+
+/// A file younger than this is never deleted: it may belong to a message the
+/// WebView has saved but no backup has caught yet.
+const GC_MIN_AGE: Duration = Duration::from_secs(60 * 60);
+const GC_INTERVAL: Duration = Duration::from_secs(10 * 60);
+static GC_LAST: Mutex<Option<Instant>> = Mutex::new(None);
+
+/// Every attachment id mentioned anywhere in these files. A file that exists
+/// but cannot be read is an error: then the set is incomplete and nothing may
+/// be deleted.
+fn referenced_ids(files: &[PathBuf]) -> Result<HashSet<String>, String> {
+ let mut ids = HashSet::new();
+ for path in files {
+ let meta = match std::fs::metadata(path) {
+ Ok(m) => m,
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
+ Err(e) => return Err(os_error::english(&e)),
+ };
+ // The set aside store_backup.prev.json never changes and may be a
+ // large pre-attachment file; scan each file version once.
+ let stamp = (meta.modified().map_err(|e| os_error::english(&e))?, meta.len());
+ let cached = SCAN_CACHE.lock().ok().and_then(|c| c.get(path).filter(|(s, _)| *s == stamp).map(|(_, ids)| ids.clone()));
+ let found = match cached {
+ Some(found) => found,
+ None => {
+ let found = scan_file(path)?;
+ if let Ok(mut cache) = SCAN_CACHE.lock() {
+ cache.insert(path.clone(), (stamp, found.clone()));
+ }
+ found
+ }
+ };
+ ids.extend(found);
+ }
+ Ok(ids)
+}
+
+type ScanStamp = (std::time::SystemTime, u64);
+static SCAN_CACHE: std::sync::LazyLock<Mutex<std::collections::HashMap<PathBuf, (ScanStamp, HashSet<String>)>>> =
+ std::sync::LazyLock::new(|| Mutex::new(std::collections::HashMap::new()));
+
+fn scan_file(path: &Path) -> Result<HashSet<String>, String> {
+ let mut ids = HashSet::new();
+ let keep = PREFIX.len() + 64;
+ {
+ let mut file = std::fs::File::open(path).map_err(|e| os_error::english(&e))?;
+ let mut window: Vec<u8> = Vec::new();
+ let mut chunk = vec![0u8; 1 << 20];
+ loop {
+ let n = file.read(&mut chunk).map_err(|e| os_error::english(&e))?;
+ if n == 0 {
+ break;
+ }
+ window.extend_from_slice(&chunk[..n]);
+ let mut i = 0;
+ while let Some(pos) = find(&window[i..], PREFIX.as_bytes()) {
+ let start = i + pos + PREFIX.len();
+ if start + 64 > window.len() {
+ break;
+ }
+ if let Ok(id) = std::str::from_utf8(&window[start..start + 64]) {
+ if is_id(id) {
+ ids.insert(id.to_string());
+ }
+ }
+ i = start;
+ }
+ // Keep a tail long enough to hold a reference cut by the chunk edge.
+ let tail = window.len().saturating_sub(keep);
+ window.drain(..tail);
+ }
+ }
+ Ok(ids)
+}
+
+fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
+ haystack.windows(needle.len()).position(|w| w == needle)
+}
+
+/// Delete attachment files that no store and no backup refers to.
+///
+/// Only runs against a live backup that carries the chat store, so the set of
+/// references is never judged from a snapshot that is missing the chats.
+pub(crate) fn collect_garbage(store_dir: &Path, dir: &Path, min_age: Duration) -> Result<usize, String> {
+ let live = store_dir.join("store_backup.json");
+ let head = std::fs::read(&live).map_err(|e| os_error::english(&e))?;
+ if find(&head, format!("\"{CHAT_KEY}\"").as_bytes()).is_none() {
+ return Ok(0);
+ }
+ drop(head);
+ let refs = referenced_ids(&crate::commands::system::backup_candidates(store_dir))?;
+ let entries = match std::fs::read_dir(dir) {
+ Ok(e) => e,
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(0),
+ Err(e) => return Err(os_error::english(&e)),
+ };
+ let mut removed = 0;
+ for entry in entries.flatten() {
+ let name = entry.file_name().to_string_lossy().into_owned();
+ let old_enough = entry
+ .metadata()
+ .and_then(|m| m.modified())
+ .ok()
+ .and_then(|t| t.elapsed().ok())
+ .map(|age| age >= min_age)
+ .unwrap_or(false);
+ if !old_enough {
+ continue;
+ }
+ // Content files nothing refers to, and temp files a crash left behind.
+ let orphan = (is_id(&name) && !refs.contains(&name)) || name.starts_with(".tmp");
+ if orphan && std::fs::remove_file(entry.path()).is_ok() {
+ removed += 1;
+ }
+ }
+ Ok(removed)
+}
+
+/// Schedule a collection after a complete backup landed, at most once per
+/// interval, on its own thread.
+pub(crate) fn collect_garbage_soon(store_dir: PathBuf) {
+ {
+ let Ok(mut last) = GC_LAST.lock() else { return };
+ if last.map(|t| t.elapsed() < GC_INTERVAL).unwrap_or(false) {
+ return;
+ }
+ *last = Some(Instant::now());
+ }
+ std::thread::spawn(move || {
+ let dir = store_dir.join("chat-attachments");
+ match collect_garbage(&store_dir, &dir, GC_MIN_AGE) {
+ Ok(0) => {}
+ Ok(n) => tracing::info!("removed {n} chat images that no chat refers to any more"),
+ Err(e) => tracing::warn!("chat image cleanup skipped: {e}"),
+ }
+ });
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn reference(data: &str) -> String {
+ format!("{PREFIX}{}", content_id(data))
+ }
+
+ fn age(path: &Path) {
+ let old = std::time::SystemTime::now() - Duration::from_secs(2 * 60 * 60);
+ std::fs::File::options().write(true).open(path).unwrap().set_modified(old).unwrap();
+ }
+
+ #[test]
+ fn original_survives_roundtrip_and_duplicate_write() {
+ let dir = tempfile::tempdir().unwrap();
+ let data = "YWJj";
+ let id = content_id(data);
+ write_attachment(dir.path(), &id, data).unwrap();
+ write_attachment(dir.path(), &id, data).unwrap();
+ assert_eq!(read_attachment(dir.path(), &id).unwrap(), data);
+ assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1);
+ }
+
+ #[test]
+ fn bad_checksum_and_traversal_never_create_an_attachment() {
+ let dir = tempfile::tempdir().unwrap();
+ assert!(write_attachment(dir.path(), &"a".repeat(64), "YWJj").is_err());
+ assert!(write_attachment(dir.path(), "../store_backup.json", "YWJj").is_err());
+ assert!(read_attachment(dir.path(), "../store_backup.json").is_err());
+ assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0);
+ }
+
+ #[test]
+ fn a_damaged_file_is_reported_and_repaired_by_the_next_write() {
+ let dir = tempfile::tempdir().unwrap();
+ let id = content_id("YWJj");
+ assert!(read_attachment(dir.path(), &id).is_err());
+ std::fs::write(dir.path().join(&id), "damaged").unwrap();
+ assert!(read_attachment(dir.path(), &id).is_err());
+ write_attachment(dir.path(), &id, "YWJj").unwrap();
+ assert_eq!(read_attachment(dir.path(), &id).unwrap(), "YWJj");
+ }
+
+ fn legacy_backup(images: &[&str]) -> String {
+ let imgs: Vec<Value> = images
+ .iter()
+ .map(|d| serde_json::json!({ "data": d, "mimeType": "image/png", "name": "a.png" }))
+ .collect();
+ let chat = serde_json::json!({
+ "state": { "conversations": [ { "id": "c1", "title": "t", "messages": [
+ { "id": "m1", "role": "user", "content": "look", "images": imgs },
+ { "id": "m2", "role": "assistant", "content": "ok" }
+ ] } ] },
+ "version": 0
+ });
+ serde_json::json!({ "__ts": "x", CHAT_KEY: chat.to_string(), "settings": "{\"a\":1}" }).to_string()
+ }
+
+ #[test]
+ fn restore_moves_inline_images_out_and_keeps_everything_else() {
+ let dir = tempfile::tempdir().unwrap();
+ let raw = legacy_backup(&["QUJD", "REVG"]);
+ let out = externalize_store_backup(&raw, dir.path()).expect("migrated");
+ assert!(!out.contains("QUJD") && !out.contains("REVG"));
+ assert!(out.contains(&reference("QUJD")) && out.contains(&reference("REVG")));
+ assert_eq!(read_attachment(dir.path(), &content_id("QUJD")).unwrap(), "QUJD");
+ let outer: Value = serde_json::from_str(&out).unwrap();
+ assert_eq!(outer["settings"], "{\"a\":1}");
+ assert_eq!(outer["__ts"], "x");
+ let inner: Value = serde_json::from_str(outer[CHAT_KEY].as_str().unwrap()).unwrap();
+ assert_eq!(inner["state"]["conversations"][0]["messages"][1]["content"], "ok");
+ assert_eq!(inner["version"], 0);
+ // Idempotent: a migrated backup has nothing left to move.
+ assert!(externalize_store_backup(&out, dir.path()).is_none());
+ }
+
+ #[test]
+ fn restore_keeps_an_image_inline_when_its_file_cannot_be_written() {
+ let dir = tempfile::tempdir().unwrap();
+ let blocked = dir.path().join("not-a-dir");
+ std::fs::write(&blocked, "file in the way").unwrap();
+ let raw = legacy_backup(&["QUJD"]);
+ assert!(externalize_store_backup(&raw, &blocked).is_none());
+ }
+
+ #[test]
+ fn restore_leaves_unknown_backups_alone() {
+ let dir = tempfile::tempdir().unwrap();
+ assert!(externalize_store_backup("not json \\\"images\\\"", dir.path()).is_none());
+ assert!(externalize_store_backup(r#"{"settings":"{}"}"#, dir.path()).is_none());
+ }
+
+ #[test]
+ fn import_accepts_all_three_shapes() {
+ let dir = tempfile::tempdir().unwrap();
+ let conv = serde_json::json!({ "id": "c", "title": "t", "messages": [ { "role": "user", "content": "x", "images": [ { "data": "QUJD", "mimeType": "image/png", "name": "a" } ] } ] });
+ for shape in [
+ serde_json::json!({ "app": "locally-uncensored", "conversations": [conv.clone()] }),
+ serde_json::json!([conv.clone()]),
+ conv.clone(),
+ ] {
+ let out = externalize_import(&shape.to_string(), dir.path()).unwrap();
+ assert!(!out.contains("\"QUJD\""), "{out}");
+ assert!(out.contains(&reference("QUJD")));
+ let back: Value = serde_json::from_str(&out).unwrap();
+ assert_eq!(back.is_array(), shape.is_array());
+ }
+ assert_eq!(externalize_import("nope", dir.path()).unwrap_err(), "That file is not valid JSON.");
+ }
+
+ #[test]
+ fn export_puts_the_images_back_and_counts_missing_ones() {
+ let dir = tempfile::tempdir().unwrap();
+ write_attachment(dir.path(), &content_id("QUJD"), "QUJD").unwrap();
+ let gone = reference("gone");
+ let content = serde_json::to_string_pretty(&serde_json::json!({ "conversations": [ { "messages": [ {
+ "content": format!("text mentioning {}", reference("QUJD")),
+ "images": [ { "data": reference("QUJD") }, { "data": gone } ]
+ } ] } ] }))
+ .unwrap();
+ let mut out = Vec::new();
+ let missing = write_export(&content, &mut out, dir.path()).unwrap();
+ let out = String::from_utf8(out).unwrap();
+ assert_eq!(missing, 1);
+ let back: Value = serde_json::from_str(&out).unwrap();
+ let message = &back["conversations"][0]["messages"][0];
+ assert_eq!(message["images"][0]["data"], "QUJD");
+ assert_eq!(message["images"][1]["data"], gone.as_str());
+ // A reference inside ordinary text is text, not an image.
+ assert!(message["content"].as_str().unwrap().contains(&reference("QUJD")));
+ }
+
+ #[test]
+ fn cleanup_removes_only_old_files_nothing_refers_to() {
+ let store = tempfile::tempdir().unwrap();
+ let dir = store.path().join("chat-attachments");
+ for d in ["QUJD", "REVG", "R0hJ", "SktM"] {
+ write_attachment(&dir, &content_id(d), d).unwrap();
+ }
+ for d in ["QUJD", "REVG", "R0hJ"] {
+ age(&dir.join(content_id(d)));
+ }
+ // QUJD in the live backup, REVG only in an older generation, R0hJ in
+ // nothing and old, SktM in nothing but young.
+ let live = serde_json::json!({ CHAT_KEY: format!("{{\"images\":[{{\"data\":\"{}\"}}]}}", reference("QUJD")) });
+ std::fs::write(store.path().join("store_backup.json"), live.to_string()).unwrap();
+ std::fs::write(store.path().join("store_backup.2.json"), reference("REVG")).unwrap();
+ assert_eq!(collect_garbage(store.path(), &dir, GC_MIN_AGE).unwrap(), 1);
+ assert!(read_attachment(&dir, &content_id("QUJD")).is_ok());
+ assert!(read_attachment(&dir, &content_id("REVG")).is_ok());
+ assert!(read_attachment(&dir, &content_id("R0hJ")).is_err());
+ assert!(read_attachment(&dir, &content_id("SktM")).is_ok());
+ }
+
+ #[test]
+ fn cleanup_never_runs_against_a_backup_without_the_chats() {
+ let store = tempfile::tempdir().unwrap();
+ let dir = store.path().join("chat-attachments");
+ write_attachment(&dir, &content_id("QUJD"), "QUJD").unwrap();
+ age(&dir.join(content_id("QUJD")));
+ assert!(collect_garbage(store.path(), &dir, GC_MIN_AGE).is_err(), "no live backup at all");
+ std::fs::write(store.path().join("store_backup.json"), r#"{"settings":"{}"}"#).unwrap();
+ assert_eq!(collect_garbage(store.path(), &dir, GC_MIN_AGE).unwrap(), 0);
+ assert!(read_attachment(&dir, &content_id("QUJD")).is_ok());
+ }
+
+ #[test]
+ fn references_cut_by_the_read_chunk_edge_are_still_found() {
+ let store = tempfile::tempdir().unwrap();
+ let r = reference("QUJD");
+ for pad in [(1 << 20) - 10, (1 << 20) - PREFIX.len() - 3, (1 << 20) + 1] {
+ let path = store.path().join(format!("f{pad}"));
+ std::fs::write(&path, format!("{}{r}\"", "x".repeat(pad))).unwrap();
+ let ids = referenced_ids(&[path]).unwrap();
+ assert!(ids.contains(&content_id("QUJD")), "pad {pad}");
+ }
+ }
+}
diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs
index dfc43a7a..fbcfab31 100644
--- a/src-tauri/src/commands/mod.rs
+++ b/src-tauri/src/commands/mod.rs
@@ -1,5 +1,6 @@
pub mod agent;
pub mod bg_tasks;
+pub mod chat_attachments;
pub mod repo_map;
pub mod comfy_folders;
pub mod comfy_ws;
diff --git a/src-tauri/src/commands/system.rs b/src-tauri/src/commands/system.rs
index fff8db52..da1f6b11 100644
--- a/src-tauri/src/commands/system.rs
+++ b/src-tauri/src/commands/system.rs
@@ -531,13 +531,19 @@ pub fn backup_stores(data: String) -> Result<(), String> {
file.sync_all().map_err(|e| os_error::english(&e))?;
}
std::fs::rename(&tmp, &target).map_err(|e| os_error::english(&e))?;
+ // A complete snapshot just landed, so the set of images anything can still
+ // point at is known: the live stores (this file) and the older backups.
+ // Not after a merged one: its chat value may be older than the live store.
+ if lost.is_empty() {
+ crate::commands::chat_attachments::collect_garbage_soon(dir);
+ }
Ok(())
}
-/// Restore stores from the %APPDATA% backup, falling back through the rotated
-/// generations when the newest file cannot be read as a backup at all.
-#[tauri::command]
-pub fn restore_stores() -> Result<Option<String>, String> {
+/// Read the store backup, falling back through the rotated generations when
+/// the newest file cannot be read as a backup at all. Plain read, for the
+/// native callers that only look inside (the onboarding decision).
+pub fn read_store_backup() -> Result<Option<String>, String> {
let dir = persistent_dir()?;
Ok(pick_backup(
backup_candidates(&dir)
@@ -546,6 +552,26 @@ pub fn restore_stores() -> Result<Option<String>, String> {
))
}
+/// Restore stores from the %APPDATA% backup, for the WebView.
+///
+/// A backup written before the attachment store carries every chat image
+/// inline, and handing that to the WebView as one string is the largest
+/// allocation the renderer ever sees: the IPC string, its parse, the
+/// IndexedDB write, and after the reload the hydration read of the same
+/// value. So the images are moved into `chat-attachments` HERE, in native
+/// memory and off the main thread, and the WebView receives the small form.
+/// An image whose file cannot be written stays inline, so nothing is lost.
+#[tauri::command]
+pub async fn restore_stores() -> Result<Option<String>, String> {
+ tauri::async_runtime::spawn_blocking(|| {
+ let Some(raw) = read_store_backup()? else { return Ok(None) };
+ let dir = crate::commands::chat_attachments::attachment_dir()?;
+ Ok(Some(crate::commands::chat_attachments::externalize_store_backup(&raw, &dir).unwrap_or(raw)))
+ })
+ .await
+ .map_err(|e| e.to_string())?
+}
+
/// Backup the IndexedDB RAG chunks (embedding vectors) to %APPDATA%.
///
/// The chat-persistence triad (`store_backup.json`) only covers localStorage
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 8243e0e2..33950a40 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -535,6 +535,11 @@ fn main() {
commands::system::set_onboarding_done,
commands::system::get_current_time,
commands::system::backup_stores,
+ commands::chat_attachments::write_chat_attachment,
+ commands::chat_attachments::read_chat_attachment,
+ commands::chat_attachments::save_chat_attachment_dialog,
+ commands::chat_attachments::export_chats_dialog,
+ commands::chat_attachments::import_chats_dialog,
commands::system::restore_stores,
commands::system::backup_rag_chunks,
commands::system::restore_rag_chunks,
diff --git a/src-tauri/src/onboarding_window.rs b/src-tauri/src/onboarding_window.rs
index ed3f6a6b..ae8e8a65 100644
--- a/src-tauri/src/onboarding_window.rs
+++ b/src-tauri/src/onboarding_window.rs
@@ -64,7 +64,7 @@ use std::time::Duration;
use tauri::{AppHandle, Emitter, Manager, WebviewUrl, WebviewWindow, WebviewWindowBuilder};
-use crate::commands::system::{is_onboarding_done, restore_stores, write_onboarding_marker};
+use crate::commands::system::{is_onboarding_done, read_store_backup, write_onboarding_marker};
use crate::state::AppState;
/// Das Label des Hauptfensters (`tauri.conf.json`).
@@ -153,7 +153,7 @@ pub fn onboarding_done_in_backup(backup_json: &str) -> bool {
pub fn decide_first_window() -> FirstWindow {
let marker = is_onboarding_done();
let backup_says_done = !marker
- && matches!(restore_stores(), Ok(Some(json)) if onboarding_done_in_backup(&json));
+ && matches!(read_store_backup(), Ok(Some(json)) if onboarding_done_in_backup(&json));
if backup_says_done {
if let Err(e) = write_onboarding_marker(true) {
tracing::warn!("onboarding marker could not be migrated from the backup: {e}");
diff --git a/src-tauri/src/os_paths.rs b/src-tauri/src/os_paths.rs
index bac2b419..0b7a155d 100644
--- a/src-tauri/src/os_paths.rs
+++ b/src-tauri/src/os_paths.rs
@@ -154,7 +154,7 @@ pub(crate) mod test_storage {
let fixture = r#"{"native-isolation-fixture":"owned"}"#.to_string();
crate::commands::system::backup_stores(fixture.clone()).unwrap();
assert_eq!(std::fs::read_to_string(persistent.join("store_backup.json")).unwrap(), fixture);
- assert_eq!(crate::commands::system::restore_stores().unwrap(), Some(fixture));
+ assert_eq!(crate::commands::system::read_store_backup().unwrap(), Some(fixture));
}
}
diff --git a/src/api/providers/anthropic-provider.ts b/src/api/providers/anthropic-provider.ts
index 13a15d37..4a05783e 100644
--- a/src/api/providers/anthropic-provider.ts
+++ b/src/api/providers/anthropic-provider.ts
@@ -1,3 +1,4 @@
+import { resolveMessageAttachments } from '../../lib/chat-attachments'
/**
* Anthropic Provider — Claude API
*
@@ -305,6 +306,7 @@ export class AnthropicProvider implements ProviderClient {
messages: ChatMessage[],
options?: ChatOptions,
): AsyncGenerator<ChatStreamChunk> {
+ messages = await resolveMessageAttachments(messages)
const { system, anthropicMessages } = this.convertMessages(messages)
const body: MessagesBody = {
@@ -514,6 +516,7 @@ export class AnthropicProvider implements ProviderClient {
tools: ToolDefinition[],
options?: ChatOptions,
): Promise<{ content: string; toolCalls: ToolCall[]; promptEvalCount?: number; evalCount?: number }> {
+ messages = await resolveMessageAttachments(messages)
const { system, anthropicMessages } = this.convertMessages(messages)
const body: MessagesBody = {
diff --git a/src/api/providers/ollama-provider.ts b/src/api/providers/ollama-provider.ts
index 9c10f93a..7985cc29 100644
--- a/src/api/providers/ollama-provider.ts
+++ b/src/api/providers/ollama-provider.ts
@@ -1,3 +1,4 @@
+import { resolveMessageAttachments } from '../../lib/chat-attachments'
/**
* Ollama Provider, wraps existing ollama.ts into the ProviderClient interface.
*
@@ -118,6 +119,7 @@ export class OllamaProvider implements ProviderClient {
// row either. Ollama renders the model's own template exactly the way
// llama.cpp does, and a strict one raises instead of improvising. See
// providers/normalize-system.ts for the whole contract.
+ messages = await resolveMessageAttachments(messages)
const ollamaMessages = applyTemplateContract(messages, {
toolRole: 'text',
alternate: true,
@@ -289,6 +291,7 @@ export class OllamaProvider implements ProviderClient {
// `tools` payload keeps the native tool channel. The strategy resolution
// only sends one after Ollama itself reported the `tools` capability for
// this model (/api/show, see lib/tool-support.ts).
+ messages = await resolveMessageAttachments(messages)
const ollamaMessages = applyTemplateContract(messages, {
toolRole: tools.length > 0 ? 'native' : 'text',
alternate: tools.length === 0,
diff --git a/src/api/providers/openai-provider.ts b/src/api/providers/openai-provider.ts
index 7b07d700..42440151 100644
--- a/src/api/providers/openai-provider.ts
+++ b/src/api/providers/openai-provider.ts
@@ -1,3 +1,4 @@
+import { resolveMessageAttachments } from '../../lib/chat-attachments'
import { captureFlashGeneration, parseFlashPolicy, recordFlashResponse } from '../../lib/flash-ui'
/**
@@ -782,6 +783,7 @@ export class OpenAIProvider implements ProviderClient {
messages: ChatMessage[],
options?: ChatOptions,
): AsyncGenerator<ChatStreamChunk> {
+ messages = await resolveMessageAttachments(messages)
const body: OpenAIChatRequest = {
model,
// Bug B3: one system message, first. The built-in engine and LM Studio
@@ -996,6 +998,7 @@ export class OpenAIProvider implements ProviderClient {
tools: ToolDefinition[],
options?: ChatOptions,
): Promise<{ content: string; toolCalls: ToolCall[]; promptEvalCount?: number; evalCount?: number; thinking?: string }> {
+ messages = await resolveMessageAttachments(messages)
const body: OpenAIChatRequest = {
model,
// Bug B3: same invariant as chatStream, see providers/normalize-system.ts.
diff --git a/src/components/chat/ChatAttachment.tsx b/src/components/chat/ChatAttachment.tsx
new file mode 100644
index 00000000..539bc464
--- /dev/null
+++ b/src/components/chat/ChatAttachment.tsx
@@ -0,0 +1,64 @@
+import { useEffect, useRef, useState } from 'react'
+import type { ImageAttachment } from '../../types/chat'
+import { attachmentBlob, originalAttachment, previewAttachment, referenceId } from '../../lib/chat-attachments'
+import { backendCall, isTauri } from '../../api/backend'
+
+/** Offscreen messages hold no data URLs, decoded images or object URLs. */
+export function ChatAttachment({ image }: { image: ImageAttachment }) {
+ const host = useRef<HTMLDivElement>(null)
+ const [visible, setVisible] = useState(false)
+ const [url, setUrl] = useState<string>()
+ const [error, setError] = useState<string>()
+ useEffect(() => {
+ const element = host.current
+ if (!element) return
+ const observer = new IntersectionObserver(entries => setVisible(entries[0]?.isIntersecting ?? false), { rootMargin: '120px' })
+ observer.observe(element)
+ return () => observer.disconnect()
+ }, [])
+ useEffect(() => {
+ if (!visible) return
+ let cancelled = false
+ let objectUrl: string | undefined
+ // Thumbnails have their own small queue, so scrolling never delays a send.
+ void previewAttachment(image, () => cancelled).then(prepared => {
+ if (cancelled) return
+ objectUrl = URL.createObjectURL(attachmentBlob(prepared.data, prepared.mimeType))
+ setUrl(objectUrl)
+ setError(undefined)
+ }).catch(() => { if (!cancelled) setError('Preview unavailable. Click to save the original.') })
+ return () => { cancelled = true; if (objectUrl) URL.revokeObjectURL(objectUrl); setUrl(undefined) }
+ }, [image, visible])
+ async function save() {
+ try {
+ const id = referenceId(image.data)
+ // Desktop: a native Save As. An anchor on a blob URL is unreliable in
+ // WebView2 (see save_binary_file_dialog), so it is the browser path only.
+ if (isTauri()) {
+ if (id) {
+ await backendCall('save_chat_attachment_dialog', { id, defaultName: image.name || 'image', mimeType: image.mimeType })
+ } else {
+ const bytes = new Uint8Array(await attachmentBlob(image.data, image.mimeType).arrayBuffer())
+ const extension = (image.mimeType.split('/')[1] || 'png').replace('jpeg', 'jpg').replace(/[^a-z0-9]/g, '')
+ await backendCall('save_binary_file_dialog', { bytes: Array.from(bytes), defaultName: image.name || 'image', extension, extLabel: 'Image' })
+ }
+ return
+ }
+ const original = await originalAttachment(image)
+ const objectUrl = URL.createObjectURL(attachmentBlob(original.data, image.mimeType))
+ const anchor = document.createElement('a')
+ anchor.href = objectUrl
+ anchor.download = image.name
+ anchor.click()
+ setTimeout(() => URL.revokeObjectURL(objectUrl), 1000)
+ } catch { setError('Attachment unavailable. Please attach the original image again.') }
+ }
+ return <div ref={host} className="w-[180px] min-h-[120px]">
+ <button type="button" onClick={() => void save()} title="Save original image" className="text-left">
+ {url ? <img src={url} width={180} height={120} decoding="async" alt={image.name}
+ className="max-w-[180px] max-h-[120px] object-contain rounded-md border border-white/10 hover:border-white/25 transition-colors" />
+ : <span className="text-xs text-zinc-400">{image.name}</span>}
+ </button>
+ {error && <p role="status" className="text-xs text-zinc-400">{error}</p>}
+ </div>
+}
diff --git a/src/components/chat/ChatInput.tsx b/src/components/chat/ChatInput.tsx
index 3fdc9ace..f131ec3b 100644
--- a/src/components/chat/ChatInput.tsx
+++ b/src/components/chat/ChatInput.tsx
@@ -12,6 +12,7 @@ import { isThinkingCompatible, isVisionCompatible, declaredVision } from '../../
import { clampEffort, effortChoices, effortLabel, nextEffort, DEFAULT_EFFORT } from '../../lib/effort'
import type { AgentToolCall } from '../../types/agent-mode'
import type { ImageAttachment } from '../../types/chat'
+import { MAX_CHAT_IMAGES, prepareChatImages } from '../../lib/chat-image-input'
import { COMPOSER_MAX_W } from './composer-width'
import { consumeComposerFocusPending } from '../../hooks/useKeyboardShortcuts'
import { useChatNoticeStore, CHAT_NOTICE_MS } from '../../stores/chatNoticeStore'
@@ -82,23 +83,12 @@ function passSendLock(lock: { current: number }): boolean {
return true
}
-function fileToImageAttachment(file: File): Promise<ImageAttachment> {
- return new Promise((resolve, reject) => {
- const reader = new FileReader()
- reader.onload = () => {
- const dataUrl = reader.result as string
- const base64 = dataUrl.split(',')[1]
- resolve({ data: base64, mimeType: file.type || 'image/png', name: file.name })
- }
- reader.onerror = reject
- reader.readAsDataURL(file)
- })
-}
-
export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, pendingApproval, onApprove, onReject, disabled, slashCommands, composerModel, composerActions, composerAbove }: Props) {
const [input, setInput] = useState('')
const [images, setImages] = useState<ImageAttachment[]>([])
const [isDragOver, setIsDragOver] = useState(false)
+ const [preparingImages, setPreparingImages] = useState(false)
+ const imageJob = useRef({ busy: false, epoch: 0 })
const [isVoiceRecording, setIsVoiceRecording] = useState(false)
// Slash-command autocomplete (v2.5.3). When the input is a lone "/token", show
// the matching agent commands; ↑/↓ to move, Enter/Tab to pick, Esc to dismiss.
@@ -149,6 +139,14 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
* nicht gelesen werden (Regel 1), und gelesen werden muessen hier beide.
*/
const conversationId = useChatStore((s) => s.activeConversationId)
+ useEffect(() => {
+ const job = imageJob.current
+ const unsubscribe = useChatStore.subscribe((state, previous) => {
+ if (state.activeConversationId !== previous.activeConversationId) job.epoch++
+ })
+ const stop = () => { job.epoch++; unsubscribe() }
+ return stop
+ }, [])
const [entwuerfe, setEntwuerfe] = useState<Record<string, { text: string; bilder: ImageAttachment[] }>>({})
const [letztesGespraech, setLetztesGespraech] = useState(conversationId)
if (letztesGespraech !== conversationId) {
@@ -266,9 +264,41 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
)
}
if (imageFiles.length === 0) return
- const newImages = await Promise.all(imageFiles.map(fileToImageAttachment))
- setImages(prev => [...prev, ...newImages].slice(0, 5)) // max 5 images
- }, [])
+ // Die Zeilen zum Bildanhang stehen oben im Verlauf (`ChatNotices`), nie
+ // im Eingabekasten: „NICHTS im Prompt-Fenster", David 21.09.2026.
+ const notices = useChatNoticeStore.getState()
+ const job = imageJob.current
+ if (job.busy) {
+ notices.show('image-attach', 'Still preparing the previous images. Add these again in a moment.', 'ruhig', CHAT_NOTICE_MS)
+ return
+ }
+ const slots = MAX_CHAT_IMAGES - images.length
+ if (slots <= 0) {
+ notices.show('image-attach', 'You can attach up to five images per message.', 'ruhig', CHAT_NOTICE_MS)
+ return
+ }
+ job.busy = true
+ const epoch = job.epoch
+ const cancelled = () => job.epoch !== epoch || useChatStore.getState().activeConversationId !== conversationId
+ setPreparingImages(true)
+ notices.show('image-attach', 'Preparing images…')
+ try {
+ const result = await prepareChatImages(imageFiles, slots, cancelled)
+ if (cancelled()) return
+ setImages(prev => [...prev, ...result.images].slice(0, MAX_CHAT_IMAGES))
+ const message = result.errors[0] ?? (imageFiles.length > slots
+ ? 'You can attach up to five images per message. Extra images were not added.'
+ : '')
+ if (message) notices.show('image-attach', message, 'ruhig', CHAT_NOTICE_MS)
+ else notices.dismiss('image-attach')
+ } finally {
+ job.busy = false
+ setPreparingImages(false)
+ if (useChatNoticeStore.getState().notices.some(n => n.id === 'image-attach' && n.text === 'Preparing images…')) {
+ useChatNoticeStore.getState().dismiss('image-attach')
+ }
+ }
+ }, [images.length, conversationId])
/**
* Ein Bild an einem Modell, das keine sieht.
@@ -319,7 +349,7 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
const sendLockRef = useRef(0)
const handleSend = () => {
const trimmed = input.trim()
- if ((!trimmed && images.length === 0) || isGenerating || waitingForLocalLane || disabled) return
+ if (imageJob.current.busy || (!trimmed && images.length === 0) || isGenerating || waitingForLocalLane || disabled) return
if (!passSendLock(sendLockRef)) return
onSend(trimmed || '(image)', images.length > 0 ? images : undefined)
setInput('')
@@ -586,7 +616,7 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
{/* Clip button */}
<button
onClick={() => fileInputRef.current?.click()}
- disabled={isGenerating}
+ disabled={isGenerating || preparingImages}
className="lu-control lu-control--icon"
title="Attach images. For PDFs and documents use the Documents panel"
>
@@ -595,7 +625,7 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
<input
ref={fileInputRef}
type="file"
- accept="image/*"
+ accept="image/png,image/jpeg,image/webp,image/gif"
multiple
className="hidden"
onChange={(e) => { if (e.target.files) addFiles(e.target.files); e.target.value = '' }}
@@ -725,7 +755,7 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
) : (
<button
onClick={handleSend}
- disabled={(!input.trim() && images.length === 0) || isTranscribing || !!waitingForLocalLane}
+ disabled={preparingImages || (!input.trim() && images.length === 0) || isTranscribing || !!waitingForLocalLane}
className="lu-control lu-control--icon lu-primary w-full h-full"
aria-label="Send message"
>
diff --git a/src/components/chat/ChatNotices.tsx b/src/components/chat/ChatNotices.tsx
index 5481be12..be113b99 100644
--- a/src/components/chat/ChatNotices.tsx
+++ b/src/components/chat/ChatNotices.tsx
@@ -11,7 +11,7 @@
* fuer Anmerkungen und Fehler vorschreibt: eine Zeile, kein Kasten, ruhiges
* Grau oder Rot, und ein x, das sie wegnimmt.
*/
-import { ImageOff, Paperclip } from 'lucide-react'
+import { ImageOff, Images, Paperclip } from 'lucide-react'
import { Hinweis } from '../ui/Hinweis'
import { useChatNoticeStore, type ChatNoticeId } from '../../stores/chatNoticeStore'
import { COMPOSER_MAX_W } from './composer-width'
@@ -20,6 +20,7 @@ import { COMPOSER_MAX_W } from './composer-width'
const ICON: Record<ChatNoticeId, typeof Paperclip> = {
'attachment-is-not-an-image': Paperclip,
'model-cannot-see-images': ImageOff,
+ 'image-attach': Images,
}
interface Props {
diff --git a/src/components/chat/ChatView.tsx b/src/components/chat/ChatView.tsx
index a96159bc..510341e2 100644
--- a/src/components/chat/ChatView.tsx
+++ b/src/components/chat/ChatView.tsx
@@ -38,7 +38,7 @@ import { ABCompare } from './ABCompare'
import { RecentChats } from './RecentChats'
import { useUIStore } from '../../stores/uiStore'
import { useCompareStore } from '../../stores/compareStore'
-import { exportConversation } from '../../lib/chat-export'
+import { exportConversation, missingImagesNote } from '../../lib/chat-export'
import { conversationMode } from '../../lib/conversation-mode'
import { PermissionOverrideBar } from './PermissionOverrideBar'
import { CodexView } from './CodexView'
@@ -657,8 +657,10 @@ export function ChatView() {
setExportOpen(false)
if (!conv) return
const result = await exportConversation(conv, fmt)
- if (result.status === 'saved' && result.path) {
- setExportToast(`Saved to ${result.path}`)
+ if (result.status === 'error') {
+ setExportToast(result.error ?? 'Could not export chat.')
+ } else if (result.status === 'saved' && result.path) {
+ setExportToast(`Saved to ${result.path}.${missingImagesNote(result.missing)}`)
} else if (result.status === 'downloaded') {
setExportToast(`Downloaded .${fmt === 'markdown' ? 'md' : 'json'}`)
}
diff --git a/src/components/chat/MessageBubble.tsx b/src/components/chat/MessageBubble.tsx
index ef689031..af319d51 100644
--- a/src/components/chat/MessageBubble.tsx
+++ b/src/components/chat/MessageBubble.tsx
@@ -1,3 +1,4 @@
+import { ChatAttachment } from './ChatAttachment'
import { motion } from 'framer-motion'
import { User, Copy, Check, Pencil, RefreshCw, X, Wrench, Trash2, Scissors, Unlink } from 'lucide-react'
import { useState, useRef, useEffect, useMemo, memo } from 'react'
@@ -405,18 +406,7 @@ function MessageBubbleImpl({ message, onRegenerate, onEdit, pendingApprovalId, o
{message.images && message.images.length > 0 && (
<div className="flex gap-1 flex-wrap">
{message.images.map((img, i) => (
- <a
- key={i}
- href={`data:${img.mimeType};base64,${img.data}`}
- target="_blank"
- rel="noopener noreferrer"
- >
- <img
- src={`data:${img.mimeType};base64,${img.data}`}
- alt={img.name}
- className="max-w-[180px] max-h-[120px] object-cover rounded-md border border-white/10 hover:border-white/25 transition-colors cursor-pointer"
- />
- </a>
+ <ChatAttachment key={i} image={img} />
))}
</div>
)}
diff --git a/src/components/chat/__tests__/chat-attachment-preview.test.tsx b/src/components/chat/__tests__/chat-attachment-preview.test.tsx
new file mode 100644
index 00000000..2496ca84
--- /dev/null
+++ b/src/components/chat/__tests__/chat-attachment-preview.test.tsx
@@ -0,0 +1,49 @@
+// @vitest-environment jsdom
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { act, cleanup, render, screen } from '@testing-library/react'
+import { ChatAttachment } from '../ChatAttachment'
+import { previewAttachment } from '../../../lib/chat-attachments'
+
+vi.mock('../../../lib/chat-attachments', () => ({
+ previewAttachment: vi.fn(), originalAttachment: vi.fn(), attachmentBlob: () => new Blob(['image']),
+ referenceId: (data: string) => data.startsWith('lu-attachment:v1:') ? data.slice(17) : null,
+}))
+let observe: (entries: { isIntersecting: boolean }[]) => void
+const image = { data:'lu-attachment:v1:test', mimeType:'image/png', name:'test.png' }
+beforeEach(() => {
+ vi.stubGlobal('IntersectionObserver', class {
+ constructor(callback: typeof observe) { observe = callback }
+ observe() {}
+ disconnect() {}
+ })
+ vi.stubGlobal('URL', { createObjectURL: vi.fn(() => 'blob:test'), revokeObjectURL: vi.fn() })
+ vi.mocked(previewAttachment).mockReset().mockResolvedValue({ ...image, data:'YWJj' })
+})
+afterEach(() => { cleanup(); vi.unstubAllGlobals() })
+it('loads only visible images and releases their URLs when scrolled away', async () => {
+ render(<ChatAttachment image={image} />)
+ expect(previewAttachment).not.toHaveBeenCalled()
+ await act(async () => observe([{isIntersecting:true}]))
+ expect(screen.getByAltText('test.png').getAttribute('src')).toBe('blob:test')
+ await act(async () => observe([{isIntersecting:false}]))
+ expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:test')
+ expect(screen.queryByAltText('test.png')).toBeNull()
+})
+it('cancels stale preview work and does not allocate a URL after unmount', async () => {
+ let finish!: (value: typeof image) => void
+ vi.mocked(previewAttachment).mockImplementation(() => new Promise(resolve => { finish = resolve }))
+ const view = render(<ChatAttachment image={image} />)
+ await act(async () => observe([{isIntersecting:true}]))
+ const cancelled = vi.mocked(previewAttachment).mock.calls[0][1]!
+ expect(cancelled()).toBe(false)
+ view.unmount()
+ expect(cancelled()).toBe(true)
+ await act(async () => finish(image))
+ expect(URL.createObjectURL).not.toHaveBeenCalled()
+})
+it('shows an actionable error for a missing image instead of crashing the chat', async () => {
+ vi.mocked(previewAttachment).mockRejectedValue(new Error('missing'))
+ render(<ChatAttachment image={image} />)
+ await act(async () => observe([{isIntersecting:true}]))
+ expect(screen.getByRole('status').textContent).toContain('save the original')
+})
diff --git a/src/components/chat/__tests__/image-upload-races.test.tsx b/src/components/chat/__tests__/image-upload-races.test.tsx
new file mode 100644
index 00000000..54daff2f
--- /dev/null
+++ b/src/components/chat/__tests__/image-upload-races.test.tsx
@@ -0,0 +1,87 @@
+// @vitest-environment jsdom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { ChatInput } from '../ChatInput'
+import { useChatStore } from '../../../stores/chatStore'
+import { prepareChatImages } from '../../../lib/chat-image-input'
+import { useChatNoticeStore } from '../../../stores/chatNoticeStore'
+
+vi.mock('../../../lib/chat-image-input', () => ({ MAX_CHAT_IMAGES: 5, prepareChatImages: vi.fn() }))
+const prepare = vi.mocked(prepareChatImages)
+const picture = { data: 'cGljdHVyZQ==', mimeType: 'image/png', name: 'test.png' }
+let finish: (value: { images: typeof picture[]; errors: string[] }) => void
+beforeEach(() => {
+ prepare.mockReset()
+ prepare.mockImplementation(() => new Promise(resolve => { finish = resolve }))
+ useChatStore.setState({ activeConversationId: 'a' })
+ useChatNoticeStore.getState().clear()
+})
+afterEach(cleanup)
+function setup() {
+ const send = vi.fn()
+ const { container } = render(<ChatInput onSend={send} onStop={() => {}} isGenerating={false} />)
+ const input = container.querySelector('input[type=file]')!
+ const attach = () => fireEvent.change(input, { target: { files: [new File(['data'], 'test.png', { type: 'image/png' })] } })
+ return { send, attach }
+}
+
+describe('attachment completion belongs to its composer', () => {
+ it('blocks Enter and duplicate uploads until images are ready, then sends exactly once', async () => {
+ const { send, attach } = setup()
+ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'describe this' } })
+ attach(); attach()
+ fireEvent.keyDown(screen.getByRole('textbox'), { key: 'Enter' })
+ expect(send).not.toHaveBeenCalled()
+ expect(prepare).toHaveBeenCalledTimes(1)
+ await act(async () => finish({ images: [picture], errors: [] }))
+ fireEvent.click(screen.getByRole('button', { name: 'Send message' }))
+ expect(send).toHaveBeenCalledWith('describe this', [picture])
+ expect(screen.queryByAltText('test.png')).toBeNull()
+ })
+ it('does not attach a late image to a different chat', async () => {
+ const { attach } = setup()
+ attach()
+ act(() => useChatStore.setState({ activeConversationId: 'b' }))
+ expect(prepare.mock.calls[0][2]!()).toBe(true)
+ await act(async () => finish({ images: [picture], errors: [] }))
+ expect(screen.queryByAltText('test.png')).toBeNull()
+ })
+ it('also cancels a late image when switching away and back during its decode', async () => {
+ const { attach } = setup()
+ attach()
+ act(() => useChatStore.setState({ activeConversationId: 'b' }))
+ act(() => useChatStore.setState({ activeConversationId: 'a' }))
+ expect(prepare.mock.calls[0][2]!()).toBe(true)
+ await act(async () => finish({ images: [picture], errors: [] }))
+ expect(screen.queryByAltText('test.png')).toBeNull()
+ })
+ it('keeps a readable error and accepts another selection after a rejected image', async () => {
+ const { attach } = setup()
+ attach()
+ await act(async () => finish({ images: [], errors: ['test.png: This image exceeds 20 MB.'] }))
+ // Said at the head of the transcript (ChatNotices), never in the composer.
+ const notices = () => useChatNoticeStore.getState().notices.map(n => n.text)
+ expect(notices()).toEqual(['test.png: This image exceeds 20 MB.'])
+ expect(screen.queryByText('test.png: This image exceeds 20 MB.')).toBeNull()
+ attach()
+ expect(prepare).toHaveBeenCalledTimes(2)
+ await act(async () => finish({ images: [picture], errors: [] }))
+ expect(screen.getByAltText('test.png')).toBeTruthy()
+ })
+ it('a second selection while images are preparing is refused out loud, not silently', async () => {
+ const { attach } = setup()
+ attach()
+ expect(useChatNoticeStore.getState().notices.map(n => n.text)).toEqual(['Preparing images…'])
+ attach()
+ expect(prepare).toHaveBeenCalledTimes(1)
+ expect(useChatNoticeStore.getState().notices.map(n => n.text)).toEqual(['Still preparing the previous images. Add these again in a moment.'])
+ await act(async () => finish({ images: [picture], errors: [] }))
+ expect(screen.getByAltText('test.png')).toBeTruthy()
+ })
+ it('the preparing line goes away when the images are ready', async () => {
+ const { attach } = setup()
+ attach()
+ await act(async () => finish({ images: [picture], errors: [] }))
+ expect(useChatNoticeStore.getState().notices).toEqual([])
+ })
+})
diff --git a/src/components/layout/AppShell.tsx b/src/components/layout/AppShell.tsx
index dd047487..5d87b686 100644
--- a/src/components/layout/AppShell.tsx
+++ b/src/components/layout/AppShell.tsx
@@ -31,7 +31,8 @@ import { extractMemoriesFromPair } from '../../hooks/useMemory'
import { detectLocalBackends, type DetectedBackend } from '../../lib/backend-detector'
import { whenRunsIdle } from '../../lib/run-idle'
import { backendCall, isTauri } from '../../api/backend'
-import { idbStorage } from '../../lib/idbStorage'
+import { idbStorage, hasStoredItem } from '../../lib/idbStorage'
+import { recoverChatsFromBackup } from '../../lib/chat-backup-recovery'
import { STORE_KEYS, IDB_STORE_KEYS, backupStoresIfChanged, flushSyncStoreBackup } from '../../lib/store-backup'
import { idbKeysToRestore, mayReloadForIdbRestore } from '../../lib/idb-restore'
import { log } from '../../lib/logger'
@@ -378,7 +379,14 @@ export function AppShell() {
try {
const live: Record<string, string | null> = {}
for (const key of IDB_STORE_KEYS) {
- live[key] = await Promise.resolve(idbStorage.getItem(key)).catch(() => null)
+ // Presence only. Only an absent store is restored, and reading
+ // the whole value here doubled the largest string at launch.
+ const present = await hasStoredItem(key)
+ live[key] = present === true
+ ? 'present'
+ : present === false
+ ? null
+ : await Promise.resolve(idbStorage.getItem(key)).catch(() => null)
}
if (Object.values(live).some((v) => !v)) {
const raw = await backendCall<string | null>('restore_stores')
@@ -405,6 +413,19 @@ export function AppShell() {
}
}
} catch { /* best-effort, the RAG restore below still runs */ }
+ // Chats a failed IndexedDB save never kept, see chat-backup-recovery.ts.
+ // Before resolveRestoreDecided below: the first backup must not
+ // replace store_backup.json before it has been looked at.
+ try {
+ await new Promise<void>((resolve) => {
+ if (useChatStore.persist.hasHydrated()) resolve()
+ else useChatStore.persist.onFinishHydration(() => resolve())
+ })
+ await recoverChatsFromBackup(
+ () => useChatStore.getState().conversations,
+ (chats) => { useChatStore.getState().importConversations(chats, 'merge') },
+ )
+ } catch (err) { log.warn('[AppShell] chat recovery from the backup failed, will retry next launch', { err: String(err) }) }
try {
const data = await backendCall<string | null>('restore_rag_chunks')
if (data) {
diff --git a/src/components/settings/ChatBackupSettings.tsx b/src/components/settings/ChatBackupSettings.tsx
index cdf3acff..3b3c052d 100644
--- a/src/components/settings/ChatBackupSettings.tsx
+++ b/src/components/settings/ChatBackupSettings.tsx
@@ -1,7 +1,8 @@
import { useRef, useState } from 'react'
import { Download, Upload } from 'lucide-react'
import { useChatStore } from '../../stores/chatStore'
-import { exportAllConversations, parseImportedChats } from '../../lib/chat-export'
+import { exportAllConversations, parseImportedChats, missingImagesNote } from '../../lib/chat-export'
+import { backendCall, isTauri } from '../../api/backend'
/**
* Chat Backup (konata 2026-06-28) — export ALL conversations to one JSON file
@@ -22,13 +23,41 @@ export function ChatBackupSettings() {
}
const res = await exportAllConversations(conversations)
if (res.status === 'cancelled') return
+ if (res.status === 'error') { setMsg(res.error ?? 'Could not export chats.'); return }
if (res.status === 'saved') {
- setMsg(`Saved ${res.count} chat${res.count === 1 ? '' : 's'} to ${res.path}`)
+ setMsg(`Saved ${res.count} chat${res.count === 1 ? '' : 's'} to ${res.path}.${missingImagesNote(res.missing)}`)
} else {
setMsg(`Downloaded ${res.count} chat${res.count === 1 ? '' : 's'} as JSON.`)
}
}
+ const importText = (content: string) => {
+ try {
+ const convs = parseImportedChats(content)
+ const { added, skipped } = importConversations(convs, 'merge')
+ setMsg(
+ added > 0
+ ? `Imported ${added} chat${added === 1 ? '' : 's'}${skipped ? `, skipped ${skipped} already present` : ''}.`
+ : `Nothing new, all ${skipped} chat${skipped === 1 ? '' : 's'} were already here.`,
+ )
+ } catch (err) {
+ setMsg(err instanceof Error ? err.message : 'Could not import that file.')
+ }
+ }
+
+ // Desktop: the file is read natively and its images are moved into the
+ // attachment store before the WebView parses it, so a large export with
+ // every image inline is never one string in the renderer.
+ const handleImportClick = async () => {
+ if (!isTauri()) { fileRef.current?.click(); return }
+ try {
+ const content = await backendCall<string | null>('import_chats_dialog')
+ if (content) importText(content)
+ } catch (err) {
+ setMsg(err instanceof Error ? err.message : String(err))
+ }
+ }
+
const handleImport = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]
e.target.value = '' // allow re-picking the same file
@@ -40,17 +69,7 @@ export function ChatBackupSettings() {
setMsg('Could not read that file.')
return
}
- try {
- const convs = parseImportedChats(content)
- const { added, skipped } = importConversations(convs, 'merge')
- setMsg(
- added > 0
- ? `Imported ${added} chat${added === 1 ? '' : 's'}${skipped ? `, skipped ${skipped} already present` : ''}.`
- : `Nothing new, all ${skipped} chat${skipped === 1 ? '' : 's'} were already here.`,
- )
- } catch (err) {
- setMsg(err instanceof Error ? err.message : 'Could not import that file.')
- }
+ importText(content)
}
reader.onerror = () => setMsg('Could not read that file.')
reader.readAsText(file)
@@ -70,7 +89,7 @@ export function ChatBackupSettings() {
<Download size={12} /> Export all chats
</button>
<button
- onClick={() => fileRef.current?.click()}
+ onClick={() => void handleImportClick()}
className="flex-1 text-[0.65rem] flex items-center justify-center gap-1.5 px-2 py-1.5 rounded border border-gray-200 dark:border-white/10 text-gray-600 dark:text-gray-300 hover:border-gray-400 dark:hover:border-white/20 transition-colors"
>
<Upload size={12} /> Import chats
diff --git a/src/lib/__tests__/chat-attachments.test.ts b/src/lib/__tests__/chat-attachments.test.ts
new file mode 100644
index 00000000..a314147a
--- /dev/null
+++ b/src/lib/__tests__/chat-attachments.test.ts
@@ -0,0 +1,202 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { webcrypto } from 'node:crypto'
+const disk = new Map<string, string>()
+const backend = vi.hoisted(() => vi.fn())
+const prepare = vi.hoisted(() => vi.fn())
+vi.mock('../../api/backend', () => ({ isTauri: () => true, backendCall: backend }))
+vi.mock('../chat-image-input', () => ({ prepareChatImage: prepare }))
+import {
+ __resetAttachmentBackoff, CONTEXT_IMAGE_BUDGET, externalizeConversations, hasInlineImages, OMITTED_IMAGE_NOTE,
+ originalAttachment, resolveMessageAttachments, storeAttachment,
+} from '../chat-attachments'
+import { coalescedJSONStorage } from '../coalescedStorage'
+import { portableConversation, parseImportedChats, exportAsJSON, exportConversation, exportAllConversations } from '../chat-export'
+import type { Conversation } from '../../types/chat'
+
+beforeEach(() => {
+ vi.stubGlobal('crypto', webcrypto)
+ disk.clear()
+ __resetAttachmentBackoff()
+ prepare.mockReset().mockImplementation(async () => ({ data: 'YWJj', mimeType: 'image/png', name: 'image' }))
+ backend.mockReset().mockImplementation(async (cmd, args) => {
+ if (cmd === 'write_chat_attachment') { disk.set(args.id, args.data); return }
+ if (cmd === 'export_chats_dialog') return { path: '/tmp/out.json', missing: 0 }
+ if (!disk.has(args.id)) throw new Error('missing')
+ return disk.get(args.id)
+ })
+})
+const image = () => ({ data: 'YWJj', name: 'original.png', mimeType: 'image/png' })
+const conversations = () => [{ messages: [{ images: [image()], content: 'hello' }] }]
+
+describe('separate durable chat attachments', () => {
+ it('removes inline data without altering originals, and round trips the original bytes', async () => {
+ const before = conversations()
+ const after = await externalizeConversations(before)
+ expect(before[0].messages[0].images[0].data).toBe('YWJj')
+ expect(after[0].messages[0].images[0].data).toMatch(/^lu-attachment:v1:[a-f0-9]{64}$/)
+ expect(await originalAttachment(after[0].messages[0].images[0])).toEqual(image())
+ expect(await externalizeConversations(after)).toBe(after)
+ expect(backend.mock.calls.filter(c => c[0] === 'write_chat_attachment')).toHaveLength(1)
+ })
+
+ it('does not hash and write the same image object twice', async () => {
+ const before = conversations()
+ await externalizeConversations(before)
+ await externalizeConversations(before)
+ expect(backend.mock.calls.filter(c => c[0] === 'write_chat_attachment')).toHaveLength(1)
+ })
+
+ it('a failed image write keeps that image inline and never throws', async () => {
+ backend.mockRejectedValue(new Error('disk full'))
+ const before = conversations()
+ const after = await externalizeConversations(before)
+ expect(after).toBe(before)
+ expect(before[0].messages[0].images[0]).toEqual(image())
+ expect(hasInlineImages(after)).toBe(true)
+ })
+
+ it('after a failure the next attempts wait instead of hammering a full disk', async () => {
+ backend.mockRejectedValueOnce(new Error('disk full'))
+ await externalizeConversations(conversations())
+ await externalizeConversations(conversations())
+ expect(backend).toHaveBeenCalledTimes(1)
+ __resetAttachmentBackoff()
+ const after = await externalizeConversations(conversations())
+ expect(hasInlineImages(after)).toBe(false)
+ })
+
+ it('resolves only images retained in a request and leaves stored references alone', async () => {
+ const stored = await storeAttachment(image())
+ const wire = await resolveMessageAttachments([{ role: 'user', content: 'x', images: [stored] }])
+ expect(wire[0].images![0].data).toBe('YWJj')
+ expect(stored.data).toMatch(/^lu-attachment:/)
+ })
+
+ it('a missing, invalid or undecodable image is left out with a note, the send goes on', async () => {
+ const stored = await storeAttachment(image())
+ disk.clear()
+ const wire = await resolveMessageAttachments([
+ { role: 'user', content: 'first', images: [{ ...stored, data: 'lu-attachment:v1:bad/path' }] },
+ { role: 'user', content: 'second', images: [stored] },
+ ])
+ expect(wire[0].images).toBeUndefined()
+ expect(wire[0].content).toBe(`first\n\n${OMITTED_IMAGE_NOTE}`)
+ expect(wire[1].images).toBeUndefined()
+ expect(wire[1].content).toContain(OMITTED_IMAGE_NOTE)
+ prepare.mockRejectedValueOnce(new Error('Use a valid PNG'))
+ disk.set(stored.data.slice('lu-attachment:v1:'.length), 'YWJj')
+ const again = await resolveMessageAttachments([{ role: 'user', content: '', images: [stored] }])
+ expect(again[0].content).toBe(OMITTED_IMAGE_NOTE)
+ })
+
+ it('over the per-request budget the OLDEST images are left out, never the newest, and it never throws', async () => {
+ const big = 'A'.repeat(CONTEXT_IMAGE_BUDGET / 4)
+ prepare.mockImplementation(async () => ({ data: big, mimeType: 'image/jpeg', name: 'x' }))
+ const stored = await storeAttachment(image())
+ const turns = Array.from({ length: 6 }, (_, i) => ({ role: 'user', content: `t${i}`, images: [stored] }))
+ const wire = await resolveMessageAttachments(turns)
+ expect(wire.slice(2).every(m => m.images?.length === 1)).toBe(true)
+ expect(wire.slice(0, 2).every(m => !m.images && m.content.endsWith(OMITTED_IMAGE_NOTE))).toBe(true)
+ })
+
+ it('an original that stayed inline after a failed write is still prepared before it is sent', async () => {
+ const original = { data: 'Q'.repeat(2_000_000), mimeType: 'image/jpeg', name: 'phone.jpg' }
+ const wire = await resolveMessageAttachments([{ role: 'user', content: 'x', images: [original] }])
+ expect(wire[0].images![0].data).toBe('YWJj')
+ expect(prepare).toHaveBeenCalledOnce()
+ })
+
+ it('JSON export on desktop hands references to the native writer, never the image bytes', async () => {
+ const stored = await storeAttachment(image())
+ const conv = { id: 'test', title: 'test', messages: [{ id: 'm', role: 'user', content: 'hello', timestamp: 1, images: [stored] }] } as Conversation
+ backend.mockImplementation(async (cmd) => cmd === 'export_chats_dialog' ? { path: '/x.json', missing: 1 } : undefined)
+ const one = await exportConversation(conv, 'json')
+ expect(one).toEqual({ status: 'saved', path: '/x.json', missing: 1 })
+ const all = await exportAllConversations([conv])
+ expect(all.status).toBe('saved')
+ const exports = backend.mock.calls.filter(call => call[0] === 'export_chats_dialog')
+ expect(exports).toHaveLength(2)
+ for (const call of exports) {
+ expect(call[1].content).toContain(stored.data)
+ expect(call[1].content).not.toContain('"YWJj"')
+ }
+ })
+
+ it('a failing native export is reported, not turned into a broken download', async () => {
+ const conv = { id: 'test', title: 'test', messages: [] } as unknown as Conversation
+ backend.mockRejectedValue(new Error('Write failed: disk full'))
+ const res = await exportAllConversations([conv])
+ expect(res.status).toBe('error')
+ expect(res.error).toContain('disk full')
+ })
+
+ it('exports portable originals that can be imported on another installation', async () => {
+ const stored = await storeAttachment(image())
+ const conv = { id: 'test', title: 'test', messages: [{ id: 'm', role: 'user', content: 'hello', timestamp: 1, images: [stored] }] } as Conversation
+ const portable = await portableConversation(conv)
+ const json = exportAsJSON(portable)
+ expect(json).not.toContain('lu-attachment:')
+ expect(parseImportedChats(json)[0].messages[0].images![0]).toEqual(image())
+ })
+})
+
+describe('the chat save around the images', () => {
+ const state = () => ({ conversations: conversations() })
+
+ it('hydration reads and parses, nothing else: no migration, no write', async () => {
+ const setItem = vi.fn()
+ const prepareWrite = vi.fn()
+ const storage = coalescedJSONStorage({ getItem: () => JSON.stringify({ state: state() }), setItem, removeItem: vi.fn() }, { prepare: prepareWrite })
+ expect(await storage.getItem('chats')).toEqual({ state: state() })
+ expect(prepareWrite).not.toHaveBeenCalled()
+ expect(setItem).not.toHaveBeenCalled()
+ })
+
+ it('a prepare that throws still writes the chat, every time', async () => {
+ const written: string[] = []
+ const storage = coalescedJSONStorage<{ text: string }>({ getItem: () => null, setItem: (_k, v) => { written.push(v) }, removeItem: vi.fn() }, {
+ waitMs: 0, prepare: async () => { throw new Error('disk full') },
+ })
+ storage.setItem('chats', { state: { text: 'one' }, version: 0 })
+ await storage.flush()
+ storage.setItem('chats', { state: { text: 'two' }, version: 0 })
+ await storage.flush()
+ expect(written.map(v => JSON.parse(v).state.text)).toEqual(['one', 'two'])
+ })
+
+ it('a write that fails does not stop the next one', async () => {
+ const written: string[] = []
+ let fail = true
+ const storage = coalescedJSONStorage<{ text: string }>({ getItem: () => null, setItem: (_k, v) => { if (fail) { fail = false; throw new Error('quota') } written.push(v) }, removeItem: vi.fn() }, { waitMs: 0 })
+ storage.setItem('chats', { state: { text: 'lost to quota' }, version: 0 })
+ await storage.flush()
+ storage.setItem('chats', { state: { text: 'kept' }, version: 0 })
+ await storage.flush()
+ expect(written.map(v => JSON.parse(v).state.text)).toEqual(['kept'])
+ })
+
+ it('writes offered before the store is ready are dropped, not written later', async () => {
+ const setItem = vi.fn()
+ let ready = false
+ const storage = coalescedJSONStorage<{ text: string }>({ getItem: () => null, setItem, removeItem: vi.fn() }, { waitMs: 0, ready: () => ready })
+ storage.setItem('chats', { state: { text: 'default, before hydration' }, version: 0 })
+ await storage.flush()
+ await new Promise(r => setTimeout(r, 5))
+ expect(setItem).not.toHaveBeenCalled()
+ ready = true
+ storage.setItem('chats', { state: { text: 'real' }, version: 0 })
+ await storage.flush()
+ expect(setItem).toHaveBeenCalledOnce()
+ expect(JSON.parse(setItem.mock.calls[0][1]).state.text).toBe('real')
+ })
+
+ it('prepared() hears only about writes that changed something', async () => {
+ const prepared = vi.fn()
+ const storage = coalescedJSONStorage<{ text: string }>({ getItem: () => null, setItem: vi.fn(), removeItem: vi.fn() }, {
+ waitMs: 0, prepare: async v => v, prepared,
+ })
+ storage.setItem('chats', { state: { text: 'x' }, version: 0 })
+ await storage.flush()
+ expect(prepared).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/lib/__tests__/chat-backup-recovery.test.ts b/src/lib/__tests__/chat-backup-recovery.test.ts
new file mode 100644
index 00000000..71e453b5
--- /dev/null
+++ b/src/lib/__tests__/chat-backup-recovery.test.ts
@@ -0,0 +1,44 @@
+import { beforeEach, expect, it, vi } from 'vitest'
+const backend = vi.hoisted(() => vi.fn())
+vi.mock('../../api/backend', () => ({ isTauri: () => true, backendCall: backend }))
+import { conversationsToRecover, recoverChatsFromBackup, RECOVERY_DONE_KEY } from '../chat-backup-recovery'
+import type { Conversation } from '../../types/chat'
+
+const chat = (id: string, updatedAt: number, messages = 1) =>
+ ({ id, title: id, createdAt: 0, updatedAt, messages: Array.from({ length: messages }, (_, i) => ({ id: `${id}${i}`, role: 'user', content: 'x', timestamp: i })) }) as unknown as Conversation
+const backupWith = (conversations: Conversation[]) =>
+ JSON.stringify({ 'chat-conversations': JSON.stringify({ state: { conversations }, version: 0 }), settings: '{}' })
+const memory = () => { const m = new Map<string, string>(); return { getItem: (k: string) => m.get(k) ?? null, setItem: (k: string, v: string) => void m.set(k, v) } }
+
+beforeEach(() => backend.mockReset())
+
+it('brings back chats newer than anything the store kept, and newer copies of kept chats', () => {
+ const live = [chat('a', 10), chat('b', 20, 1)]
+ const backup = [chat('a', 10), chat('b', 30, 4), chat('lost', 40), chat('deleted-long-ago', 5)]
+ expect(conversationsToRecover(live, backup).map(c => c.id)).toEqual(['b', 'lost'])
+})
+
+it('never replaces a chat the store has a newer copy of, and ignores malformed entries', () => {
+ const live = [chat('a', 50, 3)]
+ expect(conversationsToRecover(live, [chat('a', 40, 9), null as unknown as Conversation, { id: 'x' } as Conversation])).toEqual([])
+})
+
+it('runs once, hands the chats to the store, and retries after a failure', async () => {
+ const storage = memory()
+ const add = vi.fn()
+ backend.mockRejectedValueOnce(new Error('no backup yet'))
+ await expect(recoverChatsFromBackup(() => [chat('a', 10)], add, storage)).rejects.toThrow()
+ expect(storage.getItem(RECOVERY_DONE_KEY)).toBeNull()
+ backend.mockResolvedValue(backupWith([chat('a', 10), chat('lost', 99)]))
+ expect(await recoverChatsFromBackup(() => [chat('a', 10)], add, storage)).toBe(1)
+ expect(add.mock.calls[0][0].map((c: Conversation) => c.id)).toEqual(['lost'])
+ expect(await recoverChatsFromBackup(() => [chat('a', 10)], add, storage)).toBe(0)
+ expect(backend).toHaveBeenCalledTimes(2)
+})
+
+it('a backup without chats is fine', async () => {
+ backend.mockResolvedValue(JSON.stringify({ settings: '{}' }))
+ expect(await recoverChatsFromBackup(() => [], vi.fn(), memory())).toBe(0)
+ backend.mockResolvedValue(null)
+ expect(await recoverChatsFromBackup(() => [], vi.fn(), memory())).toBe(0)
+})
diff --git a/src/lib/__tests__/chat-image-input.test.ts b/src/lib/__tests__/chat-image-input.test.ts
new file mode 100644
index 00000000..829ece8a
--- /dev/null
+++ b/src/lib/__tests__/chat-image-input.test.ts
@@ -0,0 +1,113 @@
+import { describe, expect, it, vi } from 'vitest'
+import { imageDimensions, MAX_IMAGE_FILE_BYTES, MAX_IMAGE_PIXELS, prepareChatImage, prepareChatImages } from '../chat-image-input'
+
+function png(width: number, height: number) {
+ const data = new Uint8Array(24)
+ data.set([137,80,78,71,13,10,26,10], 0)
+ data.set([73,72,68,82], 12)
+ const view = new DataView(data.buffer)
+ view.setUint32(16, width); view.setUint32(20, height)
+ return new Blob([data], { type: 'image/png' })
+}
+
+describe('chat image admission', () => {
+ it('reads PNG dimensions without decoding pixels', async () => {
+ expect(await imageDimensions(png(4000, 3000))).toEqual({ width: 4000, height: 3000 })
+ })
+ it('rejects a compressed pixel bomb before invoking the decoder', async () => {
+ await expect(imageDimensions(png(50000, 50000))).rejects.toThrow('32 megapixels')
+ await expect(imageDimensions(png(1, MAX_IMAGE_PIXELS))).rejects.toThrow('32 megapixels')
+ })
+ it('rejects unrecognized and truncated files with an actionable error', async () => {
+ for (const blob of [new Blob([]), new Blob(['<svg/>']), new Blob([new Uint8Array([255,216,255,192,0,8])])]) {
+ await expect(imageDimensions(blob)).rejects.toThrow('valid PNG')
+ }
+ })
+ it('accepts baseline and progressive JPEG headers', async () => {
+ for (const marker of [0xc0, 0xc2]) {
+ const bytes = new Uint8Array([255,216,255,marker,0,8,8,4,0,8,0,1])
+ expect(await imageDimensions(new Blob([bytes]))).toEqual({ width: 2048, height: 1024 })
+ }
+ })
+ it('reads GIF and extended WebP dimensions', async () => {
+ const gif = new Uint8Array([71,73,70,56,57,97,0,4,0,2])
+ expect(await imageDimensions(new Blob([gif]))).toEqual({ width: 1024, height: 512 })
+ const webp = new Uint8Array(30)
+ webp.set(new TextEncoder().encode('RIFF'),0)
+ webp.set(new TextEncoder().encode('WEBPVP8X'),8)
+ webp.set([255,3,0,255,1,0],24)
+ expect(await imageDimensions(new Blob([webp]))).toEqual({ width: 1024, height: 512 })
+ })
+ it('rejects oversized files before reading even their header', async () => {
+ const read = vi.fn()
+ await expect(prepareChatImage({ size: MAX_IMAGE_FILE_BYTES + 1, slice: read } as unknown as File)).rejects.toThrow('20 MB')
+ expect(read).not.toHaveBeenCalled()
+ })
+ it('finds the frame header of a phone JPEG behind large EXIF, ICC and XMP segments', async () => {
+ // Five 64 KiB application segments before the SOF, 320 KiB in: past the
+ // old 256 KiB window, which refused such photos as "not a valid JPEG".
+ const segments = 5, segment = 65535
+ const bytes = new Uint8Array(2 + segments * (2 + segment) + 12)
+ bytes.set([255, 216], 0)
+ let at = 2
+ for (let i = 0; i < segments; i++) {
+ bytes.set([255, 0xe1 + i, segment >> 8, segment & 255], at)
+ at += 2 + segment
+ }
+ bytes.set([255, 0xc0, 0, 8, 8, 4, 0, 8, 0, 1], at)
+ expect(await imageDimensions(new Blob([bytes]))).toEqual({ width: 2048, height: 1024 })
+ })
+ it('a saved legacy image in a format the header scan does not know is decoded, not refused', async () => {
+ const close = vi.fn()
+ vi.stubGlobal('createImageBitmap', vi.fn(async () => ({ width: 100, height: 50, close })))
+ const canvas = { width: 0, height: 0, getContext: () => ({ drawImage: vi.fn(), fillRect: vi.fn() }),
+ toBlob: (cb: (b: Blob) => void, type: string) => cb(new Blob(['x'], { type })) }
+ vi.stubGlobal('document', { createElement: () => canvas })
+ vi.stubGlobal('FileReader', class { result = ''; onload?: () => void
+ readAsDataURL() { this.result = 'data:image/png;base64,eA=='; this.onload?.() } })
+ const bmp = new File([new Uint8Array([66, 77, 0, 0, 0, 0])], 'old.bmp', { type: 'image/bmp' })
+ await expect(prepareChatImage(bmp)).rejects.toThrow('valid PNG')
+ expect(await prepareChatImage(bmp, { legacy: true })).toEqual({ data: 'eA==', mimeType: 'image/png', name: 'old.bmp' })
+ expect(close).toHaveBeenCalled()
+ // A KNOWN header above the pixel cap stays refused, legacy or not.
+ await expect(prepareChatImage(new File([png(50000, 50000)], 'bomb.png', { type: 'image/png' }), { legacy: true })).rejects.toThrow('32 megapixels')
+ vi.unstubAllGlobals()
+ })
+})
+
+describe('serial image selection', () => {
+ const files = Array.from({ length: 100 }, (_, i) => ({ name: `${i}.png` }) as File)
+ it('reads only the available slots, one file at a time', async () => {
+ let active = 0, peak = 0
+ const prepare = vi.fn(async (file: File) => {
+ active++; peak = Math.max(peak, active)
+ await new Promise(resolve => setTimeout(resolve, 1))
+ active--
+ return { data: 'a', name: file.name, mimeType: 'image/png' }
+ })
+ const result = await prepareChatImages(files, 2, undefined, prepare)
+ expect(prepare).toHaveBeenCalledTimes(2)
+ expect(peak).toBe(1)
+ expect(result.images.map(i => i.name)).toEqual(['0.png', '1.png'])
+ await prepareChatImages(files, 0, undefined, prepare)
+ expect(prepare).toHaveBeenCalledTimes(2)
+ })
+ it('a broken file does not discard the valid attachments or reject the batch', async () => {
+ const result = await prepareChatImages(files, 2, undefined, async file => {
+ if (file.name === '0.png') throw new Error('bad header')
+ return { data: 'a', name: file.name, mimeType: 'image/png' }
+ })
+ expect(result.images).toHaveLength(1)
+ expect(result.errors).toEqual(['0.png: bad header'])
+ })
+ it('switching chats while decoding discards that result and stops the next decode', async () => {
+ let cancelled = false
+ const prepare = vi.fn(async (file: File) => {
+ cancelled = true
+ return { data: 'a', name: file.name, mimeType: 'image/png' }
+ })
+ const result = await prepareChatImages(files, 5, () => cancelled, prepare)
+ expect(prepare).toHaveBeenCalledTimes(1)
+ expect(result.images).toHaveLength(0)
+ })
+})
diff --git a/src/lib/__tests__/idbStorage-read-failure.test.ts b/src/lib/__tests__/idbStorage-read-failure.test.ts
index 6cdfbc37..9a4eb760 100644
--- a/src/lib/__tests__/idbStorage-read-failure.test.ts
+++ b/src/lib/__tests__/idbStorage-read-failure.test.ts
@@ -276,3 +276,26 @@ describe('backup_stores merges a lost key instead of replacing the file', () =>
expect(body).toMatch(/read_to_string\(&target\)[\s\S]*keys_lost\(/)
})
})
+
+describe('hasStoredItem answers presence without reading the value', () => {
+ beforeEach(() => {
+ vi.resetModules()
+ vi.stubGlobal('localStorage', fakeLocalStorage())
+ })
+ afterEach(() => { vi.unstubAllGlobals() })
+
+ it('present, absent, and "could not ask", and never a get()', async () => {
+ const data: Record<string, string> = { 'chat-conversations': HISTORY }
+ const idb = fakeIndexedDB(data)
+ idb.state.failReads = false
+ vi.stubGlobal('indexedDB', idb)
+ const { hasStoredItem } = await import('../idbStorage')
+ expect(await hasStoredItem('chat-conversations')).toBe(true)
+ expect(await hasStoredItem('staged-changes')).toBe(false)
+ idb.state.failReads = true
+ // Unknown is its own answer, so the caller can fall back to a real read
+ // instead of taking a failed probe for an empty store.
+ expect(await hasStoredItem('chat-conversations')).toBeNull()
+ })
+})
+
diff --git a/src/lib/__tests__/store-backup-pressure.test.ts b/src/lib/__tests__/store-backup-pressure.test.ts
new file mode 100644
index 00000000..a5c6000a
--- /dev/null
+++ b/src/lib/__tests__/store-backup-pressure.test.ts
@@ -0,0 +1,102 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const backendCall = vi.fn()
+vi.mock('../../api/backend', () => ({ backendCall: (...args: unknown[]) => backendCall(...args) }))
+
+describe('backups under a slow disk', () => {
+ beforeEach(() => {
+ vi.resetModules()
+ backendCall.mockReset()
+ const values = new Map<string, string>()
+ vi.stubGlobal('localStorage', {
+ getItem: (key: string) => values.get(key) ?? null,
+ setItem: (key: string, value: string) => { values.set(key, value) },
+ removeItem: (key: string) => { values.delete(key) },
+ })
+ })
+ afterEach(() => vi.unstubAllGlobals())
+
+ it('never sends a second full-history payload while a backup is unfinished', async () => {
+ const completions: (() => void)[] = []
+ backendCall.mockImplementation(() => new Promise<void>(resolve => completions.push(resolve)))
+ const backup = await import('../store-backup')
+ const { idbStorage } = await import('../idbStorage')
+ const history = 'A'.repeat(1024 * 1024)
+ const pending: Promise<unknown>[] = []
+ for (let i = 0; i < 12; i++) {
+ await idbStorage.setItem('chat-conversations', JSON.stringify({ history, turn: i }))
+ pending.push(backup.backupStoresIfChanged())
+ await new Promise(resolve => setTimeout(resolve, 0))
+ }
+ const whileBlocked = backendCall.mock.calls.length
+ // Release all work so even the pre-fix failure leaves no dangling promises.
+ for (let i = 0; i < 16; i++) {
+ completions.splice(0).forEach(resolve => resolve())
+ await new Promise(resolve => setTimeout(resolve, 0))
+ }
+ await Promise.all(pending)
+ expect(whileBlocked).toBe(1)
+ expect(backendCall.mock.calls.length).toBeLessThanOrEqual(2)
+ const latest = JSON.parse(backendCall.mock.calls.at(-1)![1].data)
+ expect(JSON.parse(latest['chat-conversations']).turn).toBe(11)
+ })
+
+ it('an update waits behind the active backup and writes the newest state last', async () => {
+ let finishFirst!: () => void
+ backendCall.mockImplementationOnce(() => new Promise<void>(resolve => { finishFirst = resolve }))
+ backendCall.mockResolvedValue(undefined)
+ const backup = await import('../store-backup')
+ localStorage.setItem('chat-settings', 'old')
+ const first = backup.backupStoresIfChanged()
+ await new Promise(resolve => setTimeout(resolve, 0))
+ localStorage.setItem('chat-settings', 'new')
+ const update = backup.backupStoresNow()
+ await new Promise(resolve => setTimeout(resolve, 0))
+ const whileBlocked = backendCall.mock.calls.length
+ finishFirst()
+ await first
+ expect(await update).toBe(true)
+ expect(whileBlocked).toBe(1)
+ expect(JSON.parse(backendCall.mock.calls.at(-1)![1].data)['chat-settings']).toBe('new')
+ })
+
+ it('still backs up when the small localStorage restore marker cannot be written', async () => {
+ backendCall.mockResolvedValue(undefined)
+ const backup = await import('../store-backup')
+ localStorage.setItem('chat-settings', 'keep this')
+ vi.spyOn(localStorage, 'setItem').mockImplementation(() => { throw new Error('QuotaExceededError') })
+ expect(await backup.backupStoresNow()).toBe(true)
+ expect(JSON.parse(backendCall.mock.calls.at(-1)![1].data)['chat-settings']).toBe('keep this')
+ })
+
+ it('coalesces the close-time flush with an active backup instead of copying the history again', async () => {
+ let finishFirst!: () => void
+ backendCall.mockImplementationOnce(() => new Promise<void>(resolve => { finishFirst = resolve }))
+ backendCall.mockResolvedValue(undefined)
+ const backup = await import('../store-backup')
+ localStorage.setItem('chat-settings', 'old')
+ await backup.backupStoresIfChanged()
+ localStorage.setItem('chat-settings', 'new')
+ backup.flushSyncStoreBackup()
+ expect(backendCall).toHaveBeenCalledTimes(1)
+ finishFirst()
+ await new Promise(resolve => setTimeout(resolve, 0))
+ expect(backendCall).toHaveBeenCalledTimes(2)
+ expect(JSON.parse(backendCall.mock.calls.at(-1)![1].data)['chat-settings']).toBe('new')
+ })
+
+ it('holds the backup while the chat store is about to shrink, and never reads the store meanwhile', async () => {
+ backendCall.mockResolvedValue(undefined)
+ const backup = await import('../store-backup')
+ const hold = await import('../backup-hold')
+ const { idbStorage } = await import('../idbStorage')
+ await idbStorage.setItem('chat-conversations', JSON.stringify({ inline: 'A'.repeat(1024) }))
+ hold.holdBackup('test')
+ expect(await backup.backupStoresIfChanged()).toBe('held-back')
+ expect(backup.flushSyncStoreBackup()).toBe('held-back')
+ expect(backendCall).not.toHaveBeenCalled()
+ hold.releaseBackup('test')
+ expect(await backup.backupStoresIfChanged()).toBe('written')
+ expect(backendCall).toHaveBeenCalledOnce()
+ })
+})
diff --git a/src/lib/backup-hold.ts b/src/lib/backup-hold.ts
new file mode 100644
index 00000000..bbe0c8e4
--- /dev/null
+++ b/src/lib/backup-hold.ts
@@ -0,0 +1,18 @@
+/**
+ * Holds the native store backup while a store is about to shrink.
+ *
+ * A history saved by a build before the attachment store carries every image
+ * inline. The first backup tick after launch used to read that value out of
+ * IndexedDB a second time, serialise it into the snapshot and hand it to IPC:
+ * three more copies of the largest thing in the renderer, on top of the one
+ * hydration just made. The chat store holds the backup until its first write
+ * has moved the images out, so the backup copies the small form instead.
+ *
+ * Nothing is lost while held: store_backup.json keeps the previous snapshot,
+ * which already contains everything the held store had at launch.
+ */
+const holds = new Set<string>()
+
+export function holdBackup(reason: string): void { holds.add(reason) }
+export function releaseBackup(reason: string): void { holds.delete(reason) }
+export function isBackupHeld(): boolean { return holds.size > 0 }
diff --git a/src/lib/chat-attachments.ts b/src/lib/chat-attachments.ts
new file mode 100644
index 00000000..38f55820
--- /dev/null
+++ b/src/lib/chat-attachments.ts
@@ -0,0 +1,234 @@
+/** Attachments live outside the frequently serialized chat state. `data` keeps
+ * its wire-compatible string shape; local references are resolved ONLY at the
+ * provider boundary, after context trimming. Originals are never downsampled
+ * in storage. Native files survive a WebView cache reset alongside store backup.
+ *
+ * Nothing in this module may cost the user a chat. Every path that can fail
+ * (disk full, a locked file, a missing attachment, an image the decoder
+ * refuses) degrades to "this image stays inline" or "this image is left out
+ * with a note", never to "the save is skipped" or "the send is refused".
+ */
+import { backendCall, isTauri } from '../api/backend'
+import { log } from './logger'
+import type { ImageAttachment } from '../types/chat'
+import { prepareChatImage } from './chat-image-input'
+
+const PREFIX = 'lu-attachment:v1:'
+export function isAttachmentReference(data: string): boolean { return data.startsWith(PREFIX) }
+function attachmentId(data: string): string {
+ const id = data.slice(PREFIX.length)
+ if (!/^[a-f0-9]{64}$/.test(id)) throw new Error('Invalid chat attachment reference.')
+ return id
+}
+/** The content id behind a reference, or null for inline data. */
+export function referenceId(data: string): string | null {
+ if (!isAttachmentReference(data)) return null
+ try { return attachmentId(data) } catch { return null }
+}
+let database: Promise<IDBDatabase> | undefined
+function db(): Promise<IDBDatabase> {
+ return database ??= new Promise((resolve, reject) => {
+ const req = indexedDB.open('lu-chat-attachments', 1)
+ req.onupgradeneeded = () => req.result.createObjectStore('images')
+ req.onsuccess = () => resolve(req.result)
+ req.onerror = () => { database = undefined; reject(req.error) }
+ })
+}
+async function browserWrite(id: string, data: string): Promise<void> {
+ const database = await db()
+ await new Promise<void>((resolve, reject) => {
+ const tx = database.transaction('images', 'readwrite')
+ tx.objectStore('images').put(data, id)
+ tx.oncomplete = () => resolve()
+ tx.onabort = tx.onerror = () => reject(tx.error ?? new Error('Could not save chat attachment.'))
+ })
+}
+async function read(data: string): Promise<string> {
+ if (!isAttachmentReference(data)) return data
+ const id = attachmentId(data)
+ if (isTauri()) return backendCall<string>('read_chat_attachment', { id })
+ const database = await db()
+ return new Promise((resolve, reject) => {
+ const req = database.transaction('images').objectStore('images').get(id)
+ req.onsuccess = () => typeof req.result === 'string' ? resolve(req.result) : reject(new Error('Chat attachment is missing. Please attach the original image again.'))
+ req.onerror = () => reject(req.error)
+ })
+}
+
+/** The reference an inline image object already got. Keyed by the object, so
+ * a state snapshot taken before the swap does not hash and write the same
+ * megabytes a second time. */
+const storedRefs = new WeakMap<object, string>()
+
+export async function storeAttachment<T extends { data: string }>(image: T): Promise<T> {
+ if (!image.data || isAttachmentReference(image.data)) return image
+ const known = storedRefs.get(image)
+ if (known) return { ...image, data: known }
+ const bytes = new TextEncoder().encode(image.data)
+ const hash = await crypto.subtle.digest('SHA-256', bytes)
+ const id = Array.from(new Uint8Array(hash), b => b.toString(16).padStart(2, '0')).join('')
+ if (isTauri()) await backendCall('write_chat_attachment', { id, data: image.data })
+ else await browserWrite(id, image.data)
+ // References are published only after the durable write succeeded.
+ storedRefs.set(image, PREFIX + id)
+ return { ...image, data: PREFIX + id }
+}
+
+export function attachmentBlob(data: string, mimeType: string): Blob {
+ // Chunk conversion avoids a second giant numeric JS array for old images.
+ const chunks: Uint8Array<ArrayBuffer>[] = []
+ for (let at = 0; at < data.length; at += 65536) {
+ const binary = atob(data.slice(at, at + 65536))
+ const bytes = new Uint8Array(binary.length)
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)
+ chunks.push(bytes)
+ }
+ return new Blob(chunks, { type: mimeType })
+}
+export async function originalAttachment<T extends { data: string }>(image: T): Promise<T> {
+ return { ...image, data: await read(image.data) }
+}
+
+/**
+ * Sequential, bounded decoding, one queue per purpose. Sending and previews
+ * used to share a single queue, so scrolling through an old chat delayed the
+ * next send behind every thumbnail on screen, and one decoder that never
+ * settled stalled both. Two queues bound the worst case at two decodes at a
+ * time, and a preview can never stand in front of a send.
+ */
+const queues = { send: Promise.resolve(), preview: Promise.resolve() }
+/** A decode that has not settled after this long releases its queue. The
+ * work itself cannot be cancelled, but the next image no longer waits. */
+const DECODE_TIMEOUT_MS = 30_000
+export const PREVIEW_EDGE = 512
+
+function enqueue<T>(queue: keyof typeof queues, job: () => Promise<T>): Promise<T> {
+ const result = queues[queue].then(() => new Promise<T>((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error('Image preparation timed out.')), DECODE_TIMEOUT_MS)
+ job().then(resolve, reject).finally(() => clearTimeout(timer))
+ }))
+ queues[queue] = result.then(() => {}, () => {})
+ return result
+}
+
+async function prepareStored<T extends { data: string; mimeType: string }>(image: T, maxEdge: number | undefined, cancelled: () => boolean): Promise<T> {
+ if (cancelled()) throw new Error('Image no longer visible.')
+ const original = await originalAttachment(image)
+ if (cancelled()) throw new Error('Image no longer visible.')
+ const file = new File([attachmentBlob(original.data, image.mimeType)], 'chat-image', { type: image.mimeType })
+ const prepared = await prepareChatImage(file, { maxEdge, legacy: true })
+ return { ...image, data: prepared.data, mimeType: prepared.mimeType }
+}
+
+/** The copy a model receives: at most 2048 px and 512 KiB, from the stored original. */
+export function boundedAttachment<T extends { data: string; mimeType: string }>(image: T, cancelled: () => boolean = () => false): Promise<T> {
+ return enqueue('send', () => prepareStored(image, undefined, cancelled))
+}
+
+/** The thumbnail in the transcript. Its own queue and a small edge. */
+export function previewAttachment<T extends { data: string; mimeType: string }>(image: T, cancelled: () => boolean = () => false): Promise<T> {
+ return enqueue('preview', () => prepareStored(image, PREVIEW_EDGE, cancelled))
+}
+
+/** The prepared images a single request may carry, base64 characters. About
+ * twenty-three optimized images; more than any vision model takes. */
+export const CONTEXT_IMAGE_BUDGET = 16 * 1024 * 1024
+
+/** Base64 length up to which an inline image is taken as the composer made
+ * it (512 KiB of bytes is about 700k characters). */
+const INLINE_READY_LIMIT = 1_000_000
+
+export const OMITTED_IMAGE_NOTE = '[An image attached here was left out of this request.]'
+
+/**
+ * Resolve references to model-ready images. Never refuses a send: an image
+ * that cannot be read, cannot be decoded, or no longer fits the per-request
+ * budget is left out and the message says so in one line. The newest images
+ * are resolved first, so the budget always goes to the turn the user is on.
+ */
+export async function resolveMessageAttachments<T extends { content?: string; images?: { data: string; mimeType: string }[] }>(messages: T[]): Promise<T[]> {
+ const result = messages.slice()
+ let bytes = 0
+ for (let index = messages.length - 1; index >= 0; index--) {
+ const message = messages[index]
+ if (!message.images?.length) continue
+ const images: { data: string; mimeType: string }[] = []
+ let omitted = 0
+ for (const image of message.images) {
+ if (bytes >= CONTEXT_IMAGE_BUDGET) { omitted++; continue }
+ try {
+ // The composer already hands over optimized images. Anything else
+ // (a reference, or an original that stayed inline because its
+ // write failed) goes through the same bounded preparation.
+ const resolved = isAttachmentReference(image.data) || image.data.length > INLINE_READY_LIMIT
+ ? await boundedAttachment(image)
+ : image
+ if (bytes + resolved.data.length > CONTEXT_IMAGE_BUDGET) { omitted++; continue }
+ bytes += resolved.data.length
+ images.push(resolved)
+ } catch (err) {
+ log.warn('[chat-attachments] image left out of the request', { err: String(err) })
+ omitted++
+ }
+ }
+ if (omitted === 0 && images.every((image, i) => image === message.images![i])) continue
+ const note = Array(omitted).fill(OMITTED_IMAGE_NOTE).join('\n')
+ const next = { ...message, images: images as T['images'] }
+ if (note && typeof message.content === 'string') next.content = message.content ? `${message.content}\n\n${note}` : note
+ if (images.length === 0) delete next.images
+ result[index] = next
+ }
+ return result
+}
+
+export function hasInlineImages(conversations: readonly { messages: readonly { images?: readonly ImageAttachment[] }[] }[]): boolean {
+ return conversations.some(c => c.messages.some(m => m.images?.some(i => i.data && !isAttachmentReference(i.data))))
+}
+
+/** After a failed attachment write the next attempt waits this long, so a
+ * full disk costs one failed IPC per window instead of one per keystroke. */
+const RETRY_AFTER_FAILURE_MS = 30_000
+let retryAt = 0
+
+/**
+ * Immutable migration, best effort per image. An image whose write fails
+ * stays inline, exactly as it was, and the rest still move out. Never throws:
+ * the caller writes whatever comes back, so a failing disk can delay the
+ * move of the images but never the save of the chat around them.
+ */
+export async function externalizeConversations<T extends { messages: { images?: ImageAttachment[] }[] }>(conversations: T[]): Promise<T[]> {
+ let changed = false
+ const result: T[] = []
+ let blocked = Date.now() < retryAt
+ for (const conversation of conversations) {
+ let convChanged = false
+ const messages = []
+ for (const message of conversation.messages) {
+ if (blocked || !message.images?.some(image => image.data && !isAttachmentReference(image.data))) { messages.push(message); continue }
+ const images = []
+ let messageChanged = false
+ for (const image of message.images) {
+ if (blocked) { images.push(image); continue }
+ try {
+ const stored = await storeAttachment(image)
+ if (stored !== image) messageChanged = true
+ images.push(stored)
+ } catch (err) {
+ blocked = true
+ retryAt = Date.now() + RETRY_AFTER_FAILURE_MS
+ log.error('[chat-attachments] attachment write failed, the image stays inline for now', { err: String(err) })
+ images.push(image)
+ }
+ }
+ if (messageChanged) {
+ messages.push({ ...message, images })
+ convChanged = changed = true
+ } else messages.push(message)
+ }
+ result.push(convChanged ? { ...conversation, messages } : conversation)
+ }
+ return changed ? result : conversations
+}
+
+/** Test seam: forget the failure backoff. */
+export function __resetAttachmentBackoff(): void { retryAt = 0 }
diff --git a/src/lib/chat-backup-recovery.ts b/src/lib/chat-backup-recovery.ts
new file mode 100644
index 00000000..22055063
--- /dev/null
+++ b/src/lib/chat-backup-recovery.ts
@@ -0,0 +1,63 @@
+/**
+ * One look into the native backup for chats the chat store never saved.
+ *
+ * Chromium refuses an IndexedDB value above 127 MiB, measured in this build's
+ * engine on 26.09.2026: "The serialized keys and/or value are too large
+ * (size=209736576 bytes, max=133169152 bytes)". WebView2 is Chromium. With
+ * every image inline, a handful of chats with phone photos crossed that line,
+ * and from then on every save of the chat store failed while the app kept
+ * running on what it had in memory. The native backup took the same value
+ * over IPC, so store_backup.json may hold chats that IndexedDB never got.
+ *
+ * Recovered, once, after the attachment store has made the history small:
+ * - a chat the store has, where the backup copy is newer (more messages)
+ * - a chat the store does not have, newer than the newest chat it does have
+ * The second rule is what keeps a chat the user deleted from coming back: a
+ * deleted chat is older than the ones the store kept writing after it.
+ */
+import { backendCall, isTauri } from '../api/backend'
+import { log } from './logger'
+import type { Conversation } from '../types/chat'
+
+export const RECOVERY_DONE_KEY = 'lu-chat-backup-recovery-v1'
+
+export function conversationsToRecover(live: readonly Conversation[], backup: readonly Conversation[]): Conversation[] {
+ const newestLive = live.reduce((max, c) => Math.max(max, c.updatedAt || 0), 0)
+ const byId = new Map(live.map(c => [c.id, c]))
+ return backup.filter(c => {
+ if (!c || typeof c.id !== 'string' || !Array.isArray(c.messages)) return false
+ const mine = byId.get(c.id)
+ return mine ? (c.updatedAt || 0) > (mine.updatedAt || 0) : (c.updatedAt || 0) > newestLive
+ })
+}
+
+function backupConversations(raw: string | null): Conversation[] {
+ if (!raw) return []
+ const outer: unknown = JSON.parse(raw)
+ const chat = outer && typeof outer === 'object' ? (outer as Record<string, unknown>)['chat-conversations'] : undefined
+ if (typeof chat !== 'string' || !chat) return []
+ const list = (JSON.parse(chat) as { state?: { conversations?: unknown } })?.state?.conversations
+ return Array.isArray(list) ? list as Conversation[] : []
+}
+
+/**
+ * Returns how many chats came back. Runs at most once per installation of
+ * this version; a failure leaves the flag unset, so the next launch tries
+ * again.
+ */
+export async function recoverChatsFromBackup(
+ live: () => readonly Conversation[],
+ add: (conversations: Conversation[]) => void,
+ storage: Pick<Storage, 'getItem' | 'setItem'> | null = typeof localStorage !== 'undefined' ? localStorage : null,
+): Promise<number> {
+ if (!isTauri() || !storage || storage.getItem(RECOVERY_DONE_KEY)) return 0
+ // restore_stores moves inline images into files natively and hands back
+ // the small form, so this never parses a large backup in the renderer.
+ const recovered = conversationsToRecover(live(), backupConversations(await backendCall<string | null>('restore_stores')))
+ if (recovered.length > 0) {
+ add(recovered)
+ log.warn('[chat-backup-recovery] chats the store never saved came back from the native backup', { count: recovered.length })
+ }
+ storage.setItem(RECOVERY_DONE_KEY, '1')
+ return recovered.length
+}
diff --git a/src/lib/chat-export.ts b/src/lib/chat-export.ts
index 40e7f5ac..53c4ba6b 100644
--- a/src/lib/chat-export.ts
+++ b/src/lib/chat-export.ts
@@ -8,6 +8,7 @@
import type { Conversation } from '../types/chat'
import { isTauri, backendCall } from '../api/backend'
+import { originalAttachment } from './chat-attachments'
import { conversationModelOf } from './conversation-model'
export function exportAsMarkdown(conversation: Conversation): string {
@@ -92,16 +93,20 @@ export function downloadFile(content: string, filename: string, type: string) {
export async function exportConversation(
conversation: Conversation,
format: 'markdown' | 'json',
-): Promise<{ status: 'saved' | 'cancelled' | 'downloaded'; path?: string; error?: string }> {
+): Promise<{ status: 'saved' | 'cancelled' | 'downloaded' | 'error'; path?: string; error?: string; missing?: number }> {
const safeTitle = conversation.title.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 50)
const ext = format === 'markdown' ? 'md' : 'json'
const extLabel = format === 'markdown' ? 'Markdown' : 'JSON'
const mime = format === 'markdown' ? 'text/markdown' : 'application/json'
const filename = `${safeTitle}.${ext}`
- const content = format === 'markdown' ? exportAsMarkdown(conversation) : exportAsJSON(conversation)
- // Inside Tauri → native Save As dialog + real disk write
+ // Inside Tauri → native Save As dialog + real disk write. A JSON export
+ // goes out with its image references, and the native side puts the image
+ // bytes back while it streams to the file (export_chats_dialog), so the
+ // WebView never holds the full export.
if (isTauri()) {
+ if (format === 'json') return saveNativeExport(exportAsJSON(conversation), filename)
+ const content = exportAsMarkdown(conversation)
try {
const chosenPath = await backendCall<string | null>('save_text_file_dialog', {
content,
@@ -119,10 +124,27 @@ export async function exportConversation(
}
// Plain browser fallback
+ const content = format === 'markdown' ? exportAsMarkdown(conversation) : exportAsJSON(await portableConversation(conversation))
downloadFile(content, filename, mime)
return { status: 'downloaded' }
}
+async function saveNativeExport(content: string, defaultName: string): Promise<{ status: 'saved' | 'cancelled' | 'error'; path?: string; error?: string; missing?: number }> {
+ try {
+ const outcome = await backendCall<{ path: string; missing: number } | null>('export_chats_dialog', { content, defaultName })
+ if (!outcome) return { status: 'cancelled' }
+ return { status: 'saved', path: outcome.path, missing: outcome.missing }
+ } catch (e) {
+ return { status: 'error', error: `Could not export chats: ${e instanceof Error ? e.message : String(e)}` }
+ }
+}
+
+/** The line a UI shows after a saved export. */
+export function missingImagesNote(missing: number | undefined): string {
+ if (!missing) return ''
+ return ` ${missing} image${missing === 1 ? ' was' : 's were'} no longer on this computer and could not be included.`
+}
+
// ── Bulk backup (konata 2026-06-28: the web build has no store_backup.json,
// so a tunnel/origin change loses chats). Export ALL conversations to one JSON
// file the user can re-import into any LU (web or desktop). ─────────────────
@@ -154,28 +176,15 @@ export function serializeAllConversations(conversations: Conversation[]): string
*/
export async function exportAllConversations(
conversations: Conversation[],
-): Promise<{ status: 'saved' | 'cancelled' | 'downloaded'; path?: string; count: number; error?: string }> {
+): Promise<{ status: 'saved' | 'cancelled' | 'downloaded' | 'error'; path?: string; count: number; error?: string; missing?: number }> {
const count = conversations.length
- const content = serializeAllConversations(conversations)
const filename = `locally-uncensored-chats-${count}.json`
- if (isTauri()) {
- try {
- const chosenPath = await backendCall<string | null>('save_text_file_dialog', {
- content,
- defaultName: filename,
- extension: 'json',
- extLabel: 'JSON',
- })
- if (!chosenPath) return { status: 'cancelled', count }
- return { status: 'saved', path: chosenPath, count }
- } catch (e) {
- downloadFile(content, filename, 'application/json')
- return { status: 'downloaded', count, error: String(e) }
- }
- }
+ if (isTauri()) return { ...(await saveNativeExport(serializeAllConversations(conversations), filename)), count }
- downloadFile(content, filename, 'application/json')
+ const portable: Conversation[] = []
+ for (const conversation of conversations) portable.push(await portableConversation(conversation))
+ downloadFile(serializeAllConversations(portable), filename, 'application/json')
return { status: 'downloaded', count }
}
@@ -218,3 +227,17 @@ export function parseImportedChats(json: string): Conversation[] {
}
return valid
}
+
+/** References are installation-local. The browser build exports the original
+ * bytes; an image that can no longer be read keeps its reference rather than
+ * costing the user the whole export. */
+export async function portableConversation(conversation: Conversation): Promise<Conversation> {
+ const messages = []
+ for (const message of conversation.messages) {
+ if (!message.images?.length) { messages.push(message); continue }
+ const images = []
+ for (const image of message.images) images.push(await originalAttachment(image).catch(() => image))
+ messages.push({ ...message, images })
+ }
+ return { ...conversation, messages }
+}
diff --git a/src/lib/chat-image-input.ts b/src/lib/chat-image-input.ts
new file mode 100644
index 00000000..2142770f
--- /dev/null
+++ b/src/lib/chat-image-input.ts
@@ -0,0 +1,162 @@
+import type { ImageAttachment } from '../types/chat'
+
+export const MAX_CHAT_IMAGES = 5
+export const MAX_IMAGE_FILE_BYTES = 20 * 1024 * 1024
+export const MAX_IMAGE_PIXELS = 32 * 1024 * 1024
+export const MAX_IMAGE_EDGE = 2048
+export const MAX_IMAGE_BYTES = 512 * 1024
+
+/** How far into the file the header scan reads. Phone JPEGs carry EXIF, XMP,
+ * ICC and MPF segments of up to 64 KiB each before the frame header, so a
+ * short window rejected valid photos. One MiB is still a cheap slice. */
+const HEADER_WINDOW = 1024 * 1024
+
+/** Read dimensions before decoding: a tiny compressed file may contain an
+ * enormous bitmap. Unsupported/ambiguous headers never reach the decoder. */
+export async function imageDimensions(file: Blob): Promise<{ width: number; height: number }> {
+ const bytes = new Uint8Array(await file.slice(0, HEADER_WINDOW).arrayBuffer())
+ const view = new DataView(bytes.buffer)
+ const ascii = (offset: number, text: string) => [...text].every((c, i) => bytes[offset + i] === c.charCodeAt(0))
+ let width = 0, height = 0
+ if (bytes.length >= 24 && bytes[0] === 137 && ascii(1, 'PNG\r\n\x1a\n') && ascii(12, 'IHDR')) {
+ width = view.getUint32(16); height = view.getUint32(20)
+ } else if (bytes.length >= 10 && (ascii(0, 'GIF87a') || ascii(0, 'GIF89a'))) {
+ width = view.getUint16(6, true); height = view.getUint16(8, true)
+ } else if (bytes.length >= 30 && ascii(0, 'RIFF') && ascii(8, 'WEBP')) {
+ if (ascii(12, 'VP8X')) {
+ width = 1 + bytes[24] + (bytes[25] << 8) + (bytes[26] << 16)
+ height = 1 + bytes[27] + (bytes[28] << 8) + (bytes[29] << 16)
+ } else if (ascii(12, 'VP8 ') && bytes[23] === 0x9d && bytes[24] === 1 && bytes[25] === 0x2a) {
+ width = view.getUint16(26, true) & 0x3fff; height = view.getUint16(28, true) & 0x3fff
+ } else if (ascii(12, 'VP8L') && bytes[20] === 0x2f) {
+ width = 1 + (bytes[21] | ((bytes[22] & 0x3f) << 8))
+ height = 1 + ((bytes[22] >> 6) | (bytes[23] << 2) | ((bytes[24] & 0xf) << 10))
+ }
+ } else if (bytes[0] === 0xff && bytes[1] === 0xd8) {
+ let p = 2
+ while (p + 3 < bytes.length) {
+ if (bytes[p++] !== 0xff) break
+ while (bytes[p] === 0xff) p++
+ const marker = bytes[p++]
+ if (marker === 0xda || marker === 0xd9) break
+ if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) continue
+ if (p + 2 > bytes.length) break
+ const size = view.getUint16(p)
+ if (size < 2 || p + size > bytes.length) break
+ if ([0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf].includes(marker) && size >= 8) {
+ height = view.getUint16(p + 3); width = view.getUint16(p + 5)
+ break
+ }
+ p += size
+ }
+ }
+ if (!width || !height) throw new Error('Use a valid PNG, JPEG, WebP or GIF image.')
+ if (width * height > MAX_IMAGE_PIXELS || width > 32768 || height > 32768) {
+ throw new Error('This image is too large. Resize it to 32 megapixels or less and try again.')
+ }
+ return { width, height }
+}
+
+function dataURL(blob: Blob): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader()
+ reader.onload = () => resolve(String(reader.result).split(',')[1])
+ reader.onerror = () => reject(new Error('This image could not be read. Try selecting it again.'))
+ reader.onabort = () => reject(new Error('Image loading was cancelled.'))
+ reader.readAsDataURL(blob)
+ })
+}
+
+function encode(canvas: HTMLCanvasElement, type: string, quality?: number): Promise<Blob> {
+ return new Promise((resolve, reject) => canvas.toBlob(blob => {
+ if (blob) resolve(blob)
+ else reject(new Error('This image could not be prepared. Try another image.'))
+ }, type, quality))
+}
+
+export interface PrepareOptions {
+ /** Longest edge of the result. Previews ask for less than the model does. */
+ maxEdge?: number
+ /**
+ * An image that is already in a saved chat. Builds before the attachment
+ * store accepted any `image/*` at any size, and the model and the viewer
+ * both took it. A header this scanner cannot read (BMP, AVIF, HEIC) is
+ * therefore no reason to refuse it any more; a KNOWN header above the pixel
+ * cap still is, because decoding it is the memory spike this module exists
+ * to prevent.
+ */
+ legacy?: boolean
+}
+
+export async function prepareChatImage(file: File, options: PrepareOptions = {}): Promise<ImageAttachment> {
+ const maxEdge = options.maxEdge ?? MAX_IMAGE_EDGE
+ if (file.size > MAX_IMAGE_FILE_BYTES) throw new Error('This image exceeds 20 MB. Choose a smaller file.')
+ try {
+ await imageDimensions(file)
+ } catch (error) {
+ const unknownFormat = error instanceof Error && error.message.startsWith('Use a valid')
+ if (!options.legacy || !unknownFormat) throw error
+ }
+ // A single frame also bounds animated GIF/WebP decoding in the transcript.
+ const bitmap = await createImageBitmap(file).catch(() => {
+ throw new Error('This image could not be opened. Try a PNG or JPEG copy.')
+ })
+ const canvas = document.createElement('canvas')
+ try {
+ // ImageBitmap applies EXIF orientation; use its dimensions, not the raw
+ // JPEG header, or portrait phone photos would be stretched after rotation.
+ if (bitmap.width * bitmap.height > MAX_IMAGE_PIXELS) throw new Error('This image is too large. Resize it to 32 megapixels or less and try again.')
+ const ratio = Math.min(1, maxEdge / Math.max(bitmap.width, bitmap.height))
+ canvas.width = Math.max(1, Math.round(bitmap.width * ratio))
+ canvas.height = Math.max(1, Math.round(bitmap.height * ratio))
+ const ctx = canvas.getContext('2d')
+ if (!ctx) throw new Error('Image preparation is unavailable. Restart the app and try again.')
+ ctx.drawImage(bitmap, 0, 0, canvas.width, canvas.height)
+ // Keep transparency and sharp screenshot text whenever PNG fits the budget.
+ let blob = await encode(canvas, 'image/png')
+ if (blob.size > MAX_IMAGE_BYTES) {
+ ctx.globalCompositeOperation = 'destination-over'
+ ctx.fillStyle = '#ffffff'
+ ctx.fillRect(0, 0, canvas.width, canvas.height)
+ ctx.globalCompositeOperation = 'source-over'
+ for (const quality of [0.85, 0.7, 0.5]) {
+ blob = await encode(canvas, 'image/jpeg', quality)
+ if (blob.size <= MAX_IMAGE_BYTES) break
+ }
+ }
+ while (blob.size > MAX_IMAGE_BYTES && Math.max(canvas.width, canvas.height) > 512) {
+ canvas.width = Math.max(1, Math.round(canvas.width * 0.75))
+ canvas.height = Math.max(1, Math.round(canvas.height * 0.75))
+ ctx.fillStyle = '#ffffff'
+ ctx.fillRect(0, 0, canvas.width, canvas.height)
+ ctx.drawImage(bitmap, 0, 0, canvas.width, canvas.height)
+ blob = await encode(canvas, 'image/jpeg', 0.8)
+ }
+ if (blob.size > MAX_IMAGE_BYTES) throw new Error('This image is too detailed. Crop it or choose a smaller image.')
+ return { data: await dataURL(blob), mimeType: blob.type, name: file.name }
+ } finally {
+ bitmap.close()
+ canvas.width = 0; canvas.height = 0
+ }
+}
+
+/** Serial decoding, limit BEFORE reading. Cancellation stops the next decode
+ * and prevents results from crossing into another conversation. */
+export async function prepareChatImages(
+ files: readonly File[], slots: number, cancelled: () => boolean = () => false,
+ prepare: (file: File) => Promise<ImageAttachment> = prepareChatImage,
+): Promise<{ images: ImageAttachment[]; errors: string[] }> {
+ const images: ImageAttachment[] = []
+ const errors: string[] = []
+ for (const file of files.slice(0, Math.max(0, Math.min(MAX_CHAT_IMAGES, slots)))) {
+ if (cancelled()) break
+ try {
+ const image = await prepare(file)
+ if (cancelled()) break
+ images.push(image)
+ } catch (error) {
+ errors.push(`${file.name}: ${error instanceof Error ? error.message : 'This image could not be opened.'}`)
+ }
+ }
+ return { images, errors }
+}
diff --git a/src/lib/coalescedStorage.ts b/src/lib/coalescedStorage.ts
index 7944d70f..95aa8a3c 100644
--- a/src/lib/coalescedStorage.ts
+++ b/src/lib/coalescedStorage.ts
@@ -56,7 +56,23 @@
import type { PersistStorage, StateStorage, StorageValue } from 'zustand/middleware'
import { log } from './logger'
-export interface CoalescedOptions {
+export interface CoalescedOptions<S> {
+ /**
+ * Runs right before a write and may return a lighter value to store (the
+ * chat store moves image bytes out of the history here). It must not cost
+ * the write: if it throws, the value is written as it came in.
+ */
+ prepare?: (value: StorageValue<S>) => Promise<StorageValue<S>>
+ /** Called after a prepared value landed, with what came in and what went out. */
+ prepared?: (before: StorageValue<S>, after: StorageValue<S>) => void
+ /**
+ * False until the store has hydrated. zustand writes on every set(), also
+ * the ones that happen while hydration is still reading, and what it would
+ * write then is the DEFAULT state: no chats. Such writes are dropped, not
+ * deferred. Hydration replaces that state wholesale anyway, and a store
+ * whose read failed never becomes ready, so it is never written over.
+ */
+ ready?: () => boolean
/** Quiet period after the last change before writing. */
waitMs?: number
/** Hard cap on how long a continuously-changing store stays unwritten. */
@@ -70,7 +86,7 @@ export interface CoalescedStorage<S> extends PersistStorage<S> {
export function coalescedJSONStorage<S>(
base: StateStorage,
- { waitMs = 250, maxWaitMs = 2000 }: CoalescedOptions = {}
+ { waitMs = 250, maxWaitMs = 2000, prepare, prepared, ready }: CoalescedOptions<S> = {}
): CoalescedStorage<S> {
let pending: { name: string; value: StorageValue<S> } | null = null
let timer: ReturnType<typeof setTimeout> | null = null
@@ -99,9 +115,20 @@ export function coalescedJSONStorage<S>(
const next = pending
pending = null
firstQueuedAt = 0
+ let value = next.value
+ if (prepare) {
+ try {
+ value = await prepare(next.value)
+ } catch (err) {
+ // Losing the lighter form is fine, losing the chat is not.
+ log.error('[coalescedStorage] prepare failed, writing the state as it is', { key: next.name, err: String(err) })
+ value = next.value
+ }
+ }
try {
// The single stringify this whole module exists to make rare.
- await base.setItem(next.name, JSON.stringify(next.value))
+ await base.setItem(next.name, JSON.stringify(value))
+ if (value !== next.value) prepared?.(next.value, value)
} catch (err) {
log.error('[coalescedStorage] persist write failed', { key: next.name, err: String(err) })
}
@@ -138,10 +165,14 @@ export function coalescedJSONStorage<S>(
// idbStorage answers synchronously when IndexedDB is absent (node tests,
// degraded webview). Staying synchronous there keeps hydration synchronous,
// which is what those tests rely on.
+ // Nothing is migrated here. Hydration waits on this read, and every
+ // second it takes is a second in which the store holds no chats; any
+ // lighter form is produced by the next ordinary write (see `prepare`).
return raw instanceof Promise ? raw.then(parse) : parse(raw)
},
setItem: (name, value) => {
+ if (ready && !ready()) return
pending = { name, value }
schedule()
},
diff --git a/src/lib/idbStorage.ts b/src/lib/idbStorage.ts
index 8ab6c0a1..4a151bcd 100644
--- a/src/lib/idbStorage.ts
+++ b/src/lib/idbStorage.ts
@@ -38,6 +38,9 @@ const DB_VERSION = 1
// hydrated or migrated — treat it as absent so the store starts clean.
const LEGACY_CORRUPT = '[object Object]'
+/** Above this a localStorage fallback cannot succeed (about 5 MB per origin). */
+const LS_FALLBACK_MAX_CHARS = 4 * 1024 * 1024
+
function lsGet(k: string): string | null {
try { return typeof localStorage !== 'undefined' ? localStorage.getItem(k) : null } catch { return null }
}
@@ -231,6 +234,22 @@ export async function compareAndSetIdbItem(
}
}
+/**
+ * Whether `key` holds a value, without reading it. For callers that only need
+ * to know if a store is there, such as the restore check at launch: reading a
+ * large chat history just to test it for null put a second full copy of it in
+ * memory while hydration was reading the first. Answers null when IndexedDB
+ * could not be asked, so the caller can fall back to its old path.
+ */
+export async function hasStoredItem(key: string): Promise<boolean | null> {
+ if (!hasIDB) return lsGet(key) != null
+ try {
+ return (await idbHas(key)) || lsGet(key) != null
+ } catch {
+ return null
+ }
+}
+
let _persistAsked = false
function askPersist(): void {
if (_persistAsked) return
@@ -291,8 +310,12 @@ export const idbStorage: StateStorage = {
key: name,
err: String(err),
})
- lsSet(name, value) // idb write failed → localStorage best-effort
- if (lsGet(name) !== value) {
+ // localStorage holds about 5 MB per origin. Offering it a larger value
+ // only copies the string once more on the way to the quota error,
+ // which is the worst moment for a copy: the value that failed here is
+ // typically one Chromium refused as too large (127 MiB cap).
+ if (value.length <= LS_FALLBACK_MAX_CHARS) lsSet(name, value) // idb write failed → localStorage best-effort
+ if (value.length > LS_FALLBACK_MAX_CHARS || lsGet(name) !== value) {
log.error('[idbStorage] BOTH backends failed — this state is NOT being persisted', {
key: name,
bytes: value.length,
diff --git a/src/lib/ollama-stream-tools.ts b/src/lib/ollama-stream-tools.ts
index 5f4b7e22..9d52c568 100644
--- a/src/lib/ollama-stream-tools.ts
+++ b/src/lib/ollama-stream-tools.ts
@@ -1,3 +1,4 @@
+import { resolveMessageAttachments } from './chat-attachments'
import type { ChatMessage, ToolCall, ToolDefinition } from '../api/providers/types'
import { ollamaUrl, localFetchStream } from '../api/backend'
import { isLocalTransportFailure, localBackendUnreachableMessage } from './local-backend-transport'
@@ -64,6 +65,7 @@ export async function streamOllamaChatWithTools(
// strategy resolution only routes here after Ollama reported the model's
// `tools` capability), so the tool channel stays native and only the
// system-first rule is enforced.
+ messages = await resolveMessageAttachments(messages)
const ollamaMessages = applyTemplateContract(messages, {
toolRole: 'native',
alternate: false,
diff --git a/src/lib/store-backup.ts b/src/lib/store-backup.ts
index 4ad0277b..0c89010a 100644
--- a/src/lib/store-backup.ts
+++ b/src/lib/store-backup.ts
@@ -17,6 +17,7 @@
import { backendCall } from '../api/backend'
import { idbStorage, hasFailedRead, onIdbWrite } from './idbStorage'
import { log } from './logger'
+import { isBackupHeld } from './backup-hold'
/** Every store that is worth carrying across an update or a wiped WebView2
* profile. Order is irrelevant, presence is not: a key missing from this list
@@ -110,6 +111,9 @@ async function idbValueForBackup(key: string): Promise<string | null> {
if (mirrored !== undefined) return mirrored
const read = await Promise.resolve(idbStorage.getItem(key)).catch(() => undefined)
if (read === undefined || hasFailedRead(key)) return null
+ // A write (including attachment migration) may finish during the initial read.
+ // Never replace its current metadata with the stale pre-migration blob.
+ if (idbMirror[key] !== undefined) return idbMirror[key]
idbMirror[key] = read
return read
}
@@ -145,8 +149,8 @@ function unreadableIdbKeys(): string[] {
* the identical string reference (everything the mirror serves) settle on the
* pointer comparison. */
function differsFromDisk(next: Record<string, string>): boolean {
- if (!lastWritten) return true
- const prev = lastWritten
+ const prev = pendingWrite?.body ?? activeWrite?.body ?? lastWritten
+ if (!prev) return true
const prevKeys = Object.keys(prev)
const nextKeys = Object.keys(next)
if (prevKeys.length !== nextKeys.length) return true
@@ -186,14 +190,48 @@ async function collectComparableSnapshot(): Promise<Record<string, string>> {
return body
}
-function writeSnapshot(body: Record<string, string>): void {
- try { localStorage.setItem('lu-restore-complete', '1') } catch { /* quota */ }
- // Marked clean optimistically so the next tick can skip, and un-marked if the
- // invoke fails — otherwise one failed write would make the triad believe the
- // change is on disk and it would never be retried.
- lastWritten = body
- backendCall('backup_stores', { data: JSON.stringify({ __ts: new Date().toISOString(), ...body }) })
- .catch(() => { if (lastWritten === body) lastWritten = null })
+interface SnapshotWrite {
+ body: Record<string, string>
+ done: Promise<boolean>
+ resolve: (ok: boolean) => void
+}
+
+// One native write and one latest snapshot. Never queue serialized histories:
+// the IPC payload itself stays live until the native command returns.
+let activeWrite: SnapshotWrite | null = null
+let pendingWrite: SnapshotWrite | null = null
+
+function dispatchWrite(job: SnapshotWrite): void {
+ activeWrite = job
+ const complete = (ok: boolean) => {
+ if (ok) lastWritten = job.body
+ activeWrite = null
+ job.resolve(ok)
+ const next = pendingWrite
+ pendingWrite = null
+ if (next) dispatchWrite(next)
+ }
+ try {
+ try { localStorage.setItem('lu-restore-complete', '1') } catch { /* quota must not block the file backup */ }
+ const data = JSON.stringify({ __ts: new Date().toISOString(), ...job.body })
+ void backendCall('backup_stores', { data }).then(() => complete(true), () => complete(false))
+ } catch {
+ complete(false)
+ }
+}
+
+function writeSnapshot(body: Record<string, string>): Promise<boolean> {
+ if (pendingWrite) {
+ // All callers waiting for a queued snapshot wait for its newest version.
+ pendingWrite.body = body
+ return pendingWrite.done
+ }
+ let resolve!: (ok: boolean) => void
+ const done = new Promise<boolean>(r => { resolve = r })
+ const job = { body, done, resolve }
+ if (activeWrite) pendingWrite = job
+ else dispatchWrite(job)
+ return done
}
/**
@@ -208,6 +246,9 @@ function writeSnapshot(body: Record<string, string>): void {
* a written one.
*/
export async function backupStoresIfChanged(): Promise<'written' | 'unchanged' | 'held-back'> {
+ // A store is about to shrink (lib/backup-hold.ts). The file on disk keeps
+ // the previous snapshot meanwhile, so waiting costs nothing.
+ if (isBackupHeld()) return 'held-back'
const body = await collectComparableSnapshot()
const blind = unreadableIdbKeys()
if (blind.length > 0) {
@@ -222,16 +263,20 @@ export async function backupStoresIfChanged(): Promise<'written' | 'unchanged' |
})
}
if (!differsFromDisk(body)) return 'unchanged'
- writeSnapshot(body)
+ void writeSnapshot(body)
return 'written'
}
/**
* beforeunload's flush. Synchronous on purpose: an await during page teardown
* means the trailing `backup_stores` invoke may never fire, so this reads the
- * localStorage stores directly and the IndexedDB ones from the mirror.
+ * localStorage stores directly and the IndexedDB ones from the mirror. If a
+ * native write is still running, its successor is queued without another IPC
+ * allocation. Delivery during teardown remains best effort; update-time backup
+ * explicitly awaits that queue before restart.
*/
export function flushSyncStoreBackup(): 'written' | 'unchanged' | 'held-back' {
+ if (isBackupHeld()) return 'held-back'
try {
// The mirror is the only IndexedDB value reachable without awaiting, and
// before the first async backup has filled it there is no way to tell
@@ -248,7 +293,7 @@ export function flushSyncStoreBackup(): 'written' | 'unchanged' | 'held-back' {
if (val) body[key] = val
}
if (!differsFromDisk(body)) return 'unchanged'
- writeSnapshot(body)
+ void writeSnapshot(body)
return 'written'
} catch {
return 'held-back' // best-effort: the window is going away either way
@@ -258,10 +303,9 @@ export function flushSyncStoreBackup(): 'written' | 'unchanged' | 'held-back' {
/**
* Build a snapshot and write it, and resolve only once the file is on disk.
*
- * The triad's own backup is fire and forget on purpose, it must never hold up
- * a render. This one is awaited, because its whole reason to exist is the
- * caller that is about to end the process. It ignores the dirty check for the
- * same reason: an update is the one moment worth paying for a redundant write.
+ * All callers share the same bounded write queue. This one awaits the native
+ * completion because its caller is about to end the process. It ignores the
+ * dirty check for the same reason: an update is the one moment worth paying for a redundant write.
*
* Returns whether the file was written. Never throws: a backup that fails is
* not a reason to refuse an update the user already agreed to.
@@ -280,14 +324,9 @@ export async function backupStoresNow(): Promise<boolean> {
keys: blind,
})
}
- localStorage.setItem('lu-restore-complete', '1')
- await backendCall('backup_stores', { data: JSON.stringify(snapshot) })
- // Same body the dirty check compares against, so the tick right after an
- // update-time backup does not rewrite the identical file.
const body: Record<string, string> = { ...snapshot }
delete body.__ts
- lastWritten = body
- return true
+ return await writeSnapshot(body)
} catch {
return false
}
diff --git a/src/stores/__tests__/chatStore-attachment-race.test.ts b/src/stores/__tests__/chatStore-attachment-race.test.ts
new file mode 100644
index 00000000..a6f63df2
--- /dev/null
+++ b/src/stores/__tests__/chatStore-attachment-race.test.ts
@@ -0,0 +1,38 @@
+import { afterEach, expect, it, vi } from 'vitest'
+import type { Conversation } from '../../types/chat'
+const prepared = vi.hoisted(() => vi.fn())
+const storage = vi.hoisted(() => ({ getItem: vi.fn(() => null), setItem: vi.fn(async (_key: string, _value: string) => {}), removeItem: vi.fn() }))
+vi.mock('../../lib/idbStorage', () => ({ idbStorage: storage, onIdbWrite: vi.fn() }))
+vi.mock('../../lib/chat-attachments', async (original) => ({ ...(await original<typeof import('../../lib/chat-attachments')>()), externalizeConversations: prepared }))
+afterEach(() => { vi.unstubAllGlobals(); vi.useRealTimers() })
+it('migration completion cannot overwrite streamed text, new messages or deleted chats', async () => {
+ vi.stubGlobal('indexedDB', {})
+ let finish!: () => void
+ prepared.mockImplementationOnce((conversations: Conversation[]) => new Promise(resolve => {
+ finish = () => resolve(conversations.map(c => ({...c, messages:c.messages.map(m => m.images ? {...m,images:m.images.map(i => ({...i,data:'lu-attachment:v1:stored'}))} : m)})))
+ })).mockImplementation(async value => value)
+ const { useChatStore, flushChatPersist } = await import('../chatStore')
+ await new Promise<void>(resolve => {
+ if (useChatStore.persist.hasHydrated()) resolve()
+ else { const off = useChatStore.persist.onFinishHydration(() => {off();resolve()}) }
+ })
+ const store = useChatStore.getState()
+ const id = store.createConversation('test', '')
+ const gone = store.createConversation('test', '')
+ store.addMessage(id, {id:'image',role:'user',content:'photo',timestamp:1,images:[{data:'YWJj',mimeType:'image/png',name:'image'}]})
+ store.addMessage(id, {id:'answer',role:'assistant',content:'initial',timestamp:2})
+ const saving = flushChatPersist()
+ await Promise.resolve()
+ store.updateMessageContent(id, 'answer', 'newest streamed text')
+ store.addMessage(id, {id:'new',role:'user',content:'new question',timestamp:3})
+ store.deleteConversation(gone)
+ finish()
+ await saving
+ const current = useChatStore.getState().conversations.find(c => c.id === id)!
+ expect(current.messages.find(m => m.id === 'answer')?.content).toBe('newest streamed text')
+ expect(current.messages.at(-1)?.id).toBe('new')
+ expect(current.messages[0].images?.[0].data).toBe('lu-attachment:v1:stored')
+ expect(useChatStore.getState().conversations.some(c => c.id === gone)).toBe(false)
+ const last = JSON.parse(storage.setItem.mock.calls.at(-1)![1])
+ expect(last.state.conversations.find((c: Conversation) => c.id === id).messages.at(-1).id).toBe('new')
+})
diff --git a/src/stores/__tests__/chatStore-hydration-gate.test.ts b/src/stores/__tests__/chatStore-hydration-gate.test.ts
new file mode 100644
index 00000000..158b2c39
--- /dev/null
+++ b/src/stores/__tests__/chatStore-hydration-gate.test.ts
@@ -0,0 +1,110 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import type { Conversation } from '../../types/chat'
+
+// A history saved before the attachment store: every image inline. The chat
+// store must not write ANYTHING until that history is in memory, must never
+// write a state without it, and must move the images out on its own once it
+// has loaded, through the ordinary write path.
+const read = vi.hoisted(() => ({ resolve: (_: string | null) => {} }))
+const storage = vi.hoisted(() => ({
+ getItem: vi.fn(() => new Promise<string | null>(resolve => { read.resolve = resolve })),
+ setItem: vi.fn(async (_key: string, _value: string) => {}),
+ removeItem: vi.fn(),
+}))
+const externalize = vi.hoisted(() => vi.fn())
+vi.mock('../../lib/idbStorage', () => ({ idbStorage: storage, onIdbWrite: vi.fn() }))
+vi.mock('../../lib/chat-attachments', async (original) => ({
+ ...(await original<typeof import('../../lib/chat-attachments')>()),
+ externalizeConversations: externalize,
+}))
+
+const legacy = (images: boolean) => JSON.stringify({
+ state: {
+ conversations: [{
+ id: 'old', title: 'old chat', createdAt: 1, updatedAt: 1, messages: [
+ { id: 'p', role: 'user', content: 'photo', timestamp: 1, ...(images ? { images: [{ data: 'YWJj', mimeType: 'image/png', name: 'p.png' }] } : {}) },
+ { id: 'a', role: 'assistant', content: 'nice', timestamp: 2 },
+ ],
+ }],
+ activeConversationId: 'old',
+ },
+ version: 0,
+})
+
+beforeEach(() => {
+ vi.resetModules()
+ vi.stubGlobal('indexedDB', {})
+ storage.setItem.mockClear()
+ // Same contract as the real one: the identical array back when nothing moved.
+ externalize.mockReset().mockImplementation(async (conversations: Conversation[]) => {
+ const inline = (m: Conversation['messages'][number]) => m.images?.some(i => !i.data.startsWith('lu-attachment:'))
+ if (!conversations.some(c => c.messages.some(inline))) return conversations
+ return conversations.map(c => ({
+ ...c, messages: c.messages.map(m => inline(m) ? { ...m, images: m.images!.map(i => ({ ...i, data: 'lu-attachment:v1:' + 'a'.repeat(64) })) } : m),
+ }))
+ })
+})
+afterEach(() => { vi.unstubAllGlobals() })
+
+const settle = () => new Promise(r => setTimeout(r, 400))
+const written = () => storage.setItem.mock.calls.map(c => JSON.parse(c[1]).state.conversations as Conversation[])
+
+it('writes nothing while hydration is still reading, whatever the app does meanwhile', async () => {
+ const { useChatStore, flushChatPersist } = await import('../chatStore')
+ const { isBackupHeld } = await import('../../lib/backup-hold')
+ // What the app really does at launch: the model store writes the active
+ // chat's model (modelStore.ts), a new chat may be created.
+ useChatStore.getState().setActiveConversationModel?.('some-model')
+ useChatStore.getState().createConversation('m', '')
+ await flushChatPersist()
+ await settle()
+ expect(storage.setItem).not.toHaveBeenCalled()
+ expect(isBackupHeld()).toBe(true)
+ read.resolve(legacy(true))
+ await settle()
+ expect(useChatStore.persist.hasHydrated()).toBe(true)
+ // Every write that ever happened carries the old chat.
+ expect(written().length).toBeGreaterThan(0)
+ for (const conversations of written()) expect(conversations.some(c => c.id === 'old')).toBe(true)
+})
+
+it('after hydration the images move out by themselves, the text is untouched, the backup is released', async () => {
+ const { useChatStore } = await import('../chatStore')
+ const { isBackupHeld } = await import('../../lib/backup-hold')
+ read.resolve(legacy(true))
+ await settle()
+ expect(externalize).toHaveBeenCalled()
+ const last = written().at(-1)!
+ const old = last.find(c => c.id === 'old')!
+ expect(old.messages[0].images![0].data).toMatch(/^lu-attachment:v1:/)
+ expect(old.messages.map(m => m.content)).toEqual(['photo', 'nice'])
+ expect(JSON.stringify(last)).not.toContain('YWJj')
+ // The live state swapped to the references too, so no later write carries
+ // the inline bytes again.
+ expect(useChatStore.getState().conversations[0].messages[0].images![0].data).toMatch(/^lu-attachment:v1:/)
+ expect(isBackupHeld()).toBe(false)
+})
+
+it('a history without inline images is not rewritten at launch and releases the backup at once', async () => {
+ await import('../chatStore')
+ const { isBackupHeld } = await import('../../lib/backup-hold')
+ read.resolve(legacy(false))
+ await settle()
+ expect(storage.setItem).not.toHaveBeenCalled()
+ expect(externalize).not.toHaveBeenCalled()
+ expect(isBackupHeld()).toBe(false)
+})
+
+it('when every attachment write fails, the chat is still saved (inline) and the backup is released', async () => {
+ externalize.mockReset().mockImplementation(async (conversations: Conversation[]) => conversations)
+ const { useChatStore } = await import('../chatStore')
+ const { isBackupHeld } = await import('../../lib/backup-hold')
+ read.resolve(legacy(true))
+ await settle()
+ useChatStore.getState().addMessage('old', { id: 'n', role: 'user', content: 'typed after the failure', timestamp: 3 })
+ await settle()
+ const last = written().at(-1)!
+ expect(last[0].messages.at(-1)!.content).toBe('typed after the failure')
+ expect(last[0].messages[0].images![0].data).toBe('YWJj')
+ expect(isBackupHeld()).toBe(false)
+})
diff --git a/src/stores/chatNoticeStore.ts b/src/stores/chatNoticeStore.ts
index f7bb836b..c36fe4f2 100644
--- a/src/stores/chatNoticeStore.ts
+++ b/src/stores/chatNoticeStore.ts
@@ -33,7 +33,7 @@ import type { HinweisTon } from '../lib/hinweis'
/** Die Zeilen, die es gibt. Kein freier Schluessel: eine Aufzaehlung laesst
* sich nachzaehlen, ein String-Schluessel waechst unbemerkt. */
-export type ChatNoticeId = 'attachment-is-not-an-image' | 'model-cannot-see-images'
+export type ChatNoticeId = 'attachment-is-not-an-image' | 'model-cannot-see-images' | 'image-attach'
export interface ChatNotice {
id: ChatNoticeId
diff --git a/src/stores/chatStore.ts b/src/stores/chatStore.ts
index 813a448a..6f7b856f 100644
--- a/src/stores/chatStore.ts
+++ b/src/stores/chatStore.ts
@@ -5,6 +5,8 @@ import type { Conversation, Message, ChatArtifact, CompactionRecord } from '../t
import type { AgentBlock } from '../types/agent-mode'
import { clampSampling, type SamplingOverrides } from '../lib/sampling'
import { idbStorage } from '../lib/idbStorage'
+import { externalizeConversations, hasInlineImages } from '../lib/chat-attachments'
+import { holdBackup, releaseBackup } from '../lib/backup-hold'
import { coalescedJSONStorage } from '../lib/coalescedStorage'
import { migrateBlockInPlace } from '../api/agents/block-helpers'
import { markStaleWorkflowProgressStoppedOnBlock, extractWorkflowNameFromProgressMessage } from '../lib/workflow-progress-view'
@@ -188,7 +190,43 @@ interface ChatState {
* history that was gigabytes of live strings per answer and an Out of Memory in
* the renderer. Now the newest state is written at most once per window.
*/
-const chatStorage = coalescedJSONStorage<ChatState>(idbStorage)
+const MIGRATION_HOLD = 'chat-attachment-migration'
+const durableAttachments = typeof indexedDB !== 'undefined'
+// Released by the first write after hydration, or right at hydration when
+// there is nothing to move. See lib/backup-hold.ts.
+if (durableAttachments) holdBackup(MIGRATION_HOLD)
+
+const chatStorage = coalescedJSONStorage<ChatState>(idbStorage, {
+ // Hydration first, then writes: see `ready` in coalescedStorage.ts. Without
+ // it a set() during hydration (picking a model does one) wrote an empty
+ // history over the real one, and a crash before the next write kept it.
+ // try: a write offered while create() itself runs sees the store before its
+ // binding exists, and that write is one of the ones to drop.
+ ready: (): boolean => { try { return useChatStore.persist.hasHydrated() } catch { return false } },
+ // Keep synchronous fallback hydration in environments without durable blobs.
+ ...(durableAttachments ? {
+ prepare: async (value) => {
+ if (!Array.isArray(value.state?.conversations)) return value
+ const conversations = await externalizeConversations(value.state.conversations)
+ // Whatever could move has moved. If a disk error kept some images
+ // inline, the backup goes on as it always did rather than stay held.
+ if (conversations === value.state.conversations) releaseBackup(MIGRATION_HOLD)
+ return conversations === value.state.conversations ? value : { ...value, state: { ...value.state, conversations } }
+ },
+ prepared: (before, after) => {
+ releaseBackup(MIGRATION_HOLD)
+ if (before === after) return
+ // Replace only the exact image arrays we migrated. Streaming content,
+ // deleted chats and new messages that arrived while saving win.
+ const replacements = new Map(before.state.conversations.flatMap((c, ci) =>
+ c.messages.flatMap((m, mi) => m.images && m.images !== after.state.conversations[ci].messages[mi].images
+ ? [[m.images, after.state.conversations[ci].messages[mi].images] as const] : [])))
+ useChatStore.setState(state => ({ conversations: state.conversations.map(c => ({ ...c,
+ messages: c.messages.map(m => m.images && replacements.has(m.images) ? { ...m, images: replacements.get(m.images) } : m),
+ })) }))
+ },
+ } : {}),
+})
/**
* Write the chat history out NOW instead of waiting for the coalescing window.
@@ -645,3 +683,24 @@ export const useChatStore = create<ChatState>()(
}
)
)
+
+/**
+ * After hydration, move a legacy history's images out through the ordinary
+ * write path. Nothing here blocks the app: the chats are on screen already,
+ * the old value stays on disk untouched until the lighter one has landed, and
+ * an interruption at any point leaves one of the two complete.
+ */
+function afterHydration(): void {
+ if (!durableAttachments) return
+ const state = useChatStore.getState()
+ if (!hasInlineImages(state.conversations)) {
+ releaseBackup(MIGRATION_HOLD)
+ return
+ }
+ const { name, version, partialize } = useChatStore.persist.getOptions()
+ if (!name) return
+ const persisted = (partialize ? partialize({ ...state }) : { ...state }) as ChatState
+ void chatStorage.setItem(name, { state: persisted, version })
+}
+if (useChatStore.persist.hasHydrated()) afterHydration()
+else useChatStore.persist.onFinishHydration(afterHydration)
diff --git a/src/types/chat.ts b/src/types/chat.ts
index f2857913..412fa640 100644
--- a/src/types/chat.ts
+++ b/src/types/chat.ts
@@ -4,7 +4,7 @@ import type { SamplingOverrides } from '../lib/sampling'
export type Role = 'user' | 'assistant' | 'system' | 'tool'
export interface ImageAttachment {
- data: string // base64 encoded
+ data: string // base64 while composing; lu-attachment:v1:<sha256> in saved chats
mimeType: string // e.g. 'image/png', 'image/jpeg'
name: string // filename
}
diff --git a/vite.memory-proof.config.ts b/vite.memory-proof.config.ts
new file mode 100644
index 00000000..defa036a
--- /dev/null
+++ b/vite.memory-proof.config.ts
@@ -0,0 +1,4 @@
+import { defineConfig } from 'vite'
+import react from '@vitejs/plugin-react'
+import tailwindcss from '@tailwindcss/vite'
+export default defineConfig({ plugins: [react(), tailwindcss()], server: { host: '127.0.0.1', port: 5297, strictPort: true } })