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.

feat: web chat export/import backup (konata)

purple3e9ba18e138c
diff --git a/src/components/settings/ChatBackupSettings.tsx b/src/components/settings/ChatBackupSettings.tsx
new file mode 100644
index 00000000..0e3bce87
--- /dev/null
+++ b/src/components/settings/ChatBackupSettings.tsx
@@ -0,0 +1,83 @@
+import { useRef, useState } from 'react'
+import { Download, Upload } from 'lucide-react'
+import { useChatStore } from '../../stores/chatStore'
+import { exportAllConversations, parseImportedChats } from '../../lib/chat-export'
+
+/**
+ * Chat Backup (konata 2026-06-28) — export ALL conversations to one JSON file
+ * and re-import them. The web build has no store_backup.json, so a web user on
+ * an SSH tunnel loses chats when the origin (host/port) changes; this is their
+ * manual backup + restore path. Works on desktop too (native Save As dialog).
+ */
+export function ChatBackupSettings() {
+ const conversations = useChatStore((s) => s.conversations)
+ const importConversations = useChatStore((s) => s.importConversations)
+ const fileRef = useRef<HTMLInputElement>(null)
+ const [msg, setMsg] = useState<string>('')
+
+ const handleExport = async () => {
+ if (conversations.length === 0) {
+ setMsg('No chats to export yet.')
+ return
+ }
+ const res = await exportAllConversations(conversations)
+ if (res.status === 'cancelled') return
+ if (res.status === 'saved') {
+ setMsg(`Saved ${res.count} chat${res.count === 1 ? '' : 's'} to ${res.path}`)
+ } else {
+ setMsg(`Downloaded ${res.count} chat${res.count === 1 ? '' : 's'} as JSON.`)
+ }
+ }
+
+ const handleImport = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0]
+ e.target.value = '' // allow re-picking the same file
+ if (!file) return
+ const reader = new FileReader()
+ reader.onload = (ev) => {
+ const content = ev.target?.result as string
+ if (!content) {
+ 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.')
+ }
+ }
+ reader.onerror = () => setMsg('Could not read that file.')
+ reader.readAsText(file)
+ }
+
+ return (
+ <div className="space-y-2">
+ <div className="text-[0.6rem] text-gray-500 dark:text-gray-500 leading-relaxed">
+ Save all your chats to a single JSON file, or restore them from one. On the web version your chats live in the
+ browser, so this is your backup if you ever open LU from a different address (e.g. after a tunnel reconnect).
+ </div>
+ <div className="flex gap-2">
+ <button
+ onClick={handleExport}
+ 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"
+ >
+ <Download size={12} /> Export all chats
+ </button>
+ <button
+ onClick={() => fileRef.current?.click()}
+ 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
+ </button>
+ <input ref={fileRef} type="file" accept=".json,application/json" onChange={handleImport} className="hidden" />
+ </div>
+ {msg && <div className="text-[0.6rem] text-gray-500 dark:text-gray-400">{msg}</div>}
+ </div>
+ )
+}
diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsx
index e643a70b..789661ab 100644
--- a/src/components/settings/SettingsPage.tsx
+++ b/src/components/settings/SettingsPage.tsx
@@ -23,6 +23,7 @@ const PIPER_VOICES: { id: string; label: string }[] = [
import { useAgentModeStore } from '../../stores/agentModeStore'
import { FEATURE_FLAGS } from '../../lib/constants'
import { MemorySettings } from './MemorySettings'
+import { ChatBackupSettings } from './ChatBackupSettings'
import { RemoteAccessSettings } from './RemoteAccessSettings'
import { RemoteAccessDocs } from './RemoteAccessDocs'
import { HardwareSettings } from './HardwareSettings'
@@ -1022,6 +1023,10 @@ export function SettingsPage() {
<ChatbotImporter />
</Section>
+ <Section title="Chat Backup">
+ <ChatBackupSettings />
+ </Section>
+
<Section title="Image / Video Generation Timeouts">
<div className="text-[0.6rem] text-gray-500 dark:text-gray-500 leading-relaxed pb-1.5">
Maximum minutes a ComfyUI generation can run before LU aborts it. Bump these up if you run on iGPU or CPU only — a 1024px image on integrated graphics can take 30+ min.
diff --git a/src/lib/__tests__/chat-backup.test.ts b/src/lib/__tests__/chat-backup.test.ts
new file mode 100644
index 00000000..1cc44a17
--- /dev/null
+++ b/src/lib/__tests__/chat-backup.test.ts
@@ -0,0 +1,66 @@
+import { describe, it, expect } from 'vitest'
+import { serializeAllConversations, parseImportedChats } from '../chat-export'
+import type { Conversation } from '../../types/chat'
+
+function conv(id: string, over: Partial<Conversation> = {}): Conversation {
+ return {
+ id,
+ title: `chat ${id}`,
+ messages: [],
+ model: 'llama3',
+ systemPrompt: '',
+ mode: 'lu',
+ createdAt: 1,
+ updatedAt: 1,
+ personaEnabled: false,
+ ...over,
+ } as Conversation
+}
+
+// Chat backup export/import (konata 2026-06-28: web build has no store_backup.json).
+describe('chat backup parse', () => {
+ it('bundle roundtrips through serialize → parse', () => {
+ const convs = [conv('a'), conv('b')]
+ const parsed = parseImportedChats(serializeAllConversations(convs))
+ expect(parsed.map((c) => c.id)).toEqual(['a', 'b'])
+ })
+
+ it('accepts a bare array export', () => {
+ const parsed = parseImportedChats(JSON.stringify([conv('x')]))
+ expect(parsed).toHaveLength(1)
+ expect(parsed[0].id).toBe('x')
+ })
+
+ it('accepts a single per-chat export object', () => {
+ const parsed = parseImportedChats(JSON.stringify(conv('solo')))
+ expect(parsed).toHaveLength(1)
+ expect(parsed[0].id).toBe('solo')
+ })
+
+ it('drops malformed entries but keeps valid ones', () => {
+ const mixed = JSON.stringify({
+ conversations: [conv('good'), { id: 5 }, null, { title: 'no messages' }],
+ })
+ const parsed = parseImportedChats(mixed)
+ expect(parsed.map((c) => c.id)).toEqual(['good'])
+ })
+
+ it('throws on invalid JSON', () => {
+ expect(() => parseImportedChats('{not json')).toThrow(/not valid JSON/i)
+ })
+
+ it('throws when nothing valid is found', () => {
+ expect(() => parseImportedChats(JSON.stringify({ foo: 1 }))).toThrow(/no conversations/i)
+ expect(() => parseImportedChats(JSON.stringify({ conversations: [{ id: 1 }] }))).toThrow(
+ /no valid conversations/i,
+ )
+ })
+
+ it('serializeAllConversations stamps a versioned bundle', () => {
+ const bundle = JSON.parse(serializeAllConversations([conv('a')]))
+ expect(bundle.app).toBe('locally-uncensored')
+ expect(bundle.kind).toBe('chat-export')
+ expect(bundle.version).toBe(1)
+ expect(bundle.count).toBe(1)
+ })
+})
diff --git a/src/lib/chat-export.ts b/src/lib/chat-export.ts
index 378b9aa3..62e186f3 100644
--- a/src/lib/chat-export.ts
+++ b/src/lib/chat-export.ts
@@ -116,3 +116,99 @@ export async function exportConversation(
downloadFile(content, filename, mime)
return { status: 'downloaded' }
}
+
+// ── 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). ─────────────────
+
+export interface ChatExportBundle {
+ app: 'locally-uncensored'
+ kind: 'chat-export'
+ version: 1
+ exportedAt: number
+ count: number
+ conversations: Conversation[]
+}
+
+export function serializeAllConversations(conversations: Conversation[]): string {
+ const bundle: ChatExportBundle = {
+ app: 'locally-uncensored',
+ kind: 'chat-export',
+ version: 1,
+ exportedAt: Date.now(),
+ count: conversations.length,
+ conversations,
+ }
+ return JSON.stringify(bundle, null, 2)
+}
+
+/**
+ * Export every conversation to a single JSON backup. Tauri → native Save As;
+ * browser → blob download (the whole point for web users on a tunnel).
+ */
+export async function exportAllConversations(
+ conversations: Conversation[],
+): Promise<{ status: 'saved' | 'cancelled' | 'downloaded'; path?: string; count: number; error?: string }> {
+ 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) }
+ }
+ }
+
+ downloadFile(content, filename, 'application/json')
+ return { status: 'downloaded', count }
+}
+
+/**
+ * Parse an exported file back into conversations. Accepts three shapes:
+ * - a bundle `{ conversations: [...] }` (export-all),
+ * - a bare array `[...]`,
+ * - a single conversation `{ id, messages, ... }` (per-chat .json export).
+ * Returns only structurally-valid conversations (string id + title + messages
+ * array). Throws on unparseable JSON or when nothing valid is found, so the UI
+ * can show a precise message.
+ */
+export function parseImportedChats(json: string): Conversation[] {
+ let data: unknown
+ try {
+ data = JSON.parse(json)
+ } catch {
+ throw new Error('That file is not valid JSON.')
+ }
+ let raw: unknown[]
+ if (Array.isArray(data)) {
+ raw = data
+ } else if (data && typeof data === 'object' && Array.isArray((data as { conversations?: unknown[] }).conversations)) {
+ raw = (data as { conversations: unknown[] }).conversations
+ } else if (data && typeof data === 'object' && Array.isArray((data as { messages?: unknown[] }).messages)) {
+ raw = [data] // a single per-chat export
+ } else {
+ throw new Error('No conversations found in that file. Use a Locally Uncensored chat export (.json).')
+ }
+ const valid = raw.filter(
+ (c): c is Conversation =>
+ !!c &&
+ typeof c === 'object' &&
+ typeof (c as Conversation).id === 'string' &&
+ typeof (c as Conversation).title === 'string' &&
+ Array.isArray((c as Conversation).messages),
+ )
+ if (valid.length === 0) {
+ throw new Error('No valid conversations found in that file.')
+ }
+ return valid
+}
diff --git a/src/stores/__tests__/chatStore-import.test.ts b/src/stores/__tests__/chatStore-import.test.ts
new file mode 100644
index 00000000..6f1a40a3
--- /dev/null
+++ b/src/stores/__tests__/chatStore-import.test.ts
@@ -0,0 +1,68 @@
+import { describe, it, expect, beforeEach } from 'vitest'
+import { useChatStore } from '../chatStore'
+import type { Conversation } from '../../types/chat'
+
+function conv(id: string, updatedAt: number, title = `chat ${id}`): Conversation {
+ return {
+ id,
+ title,
+ messages: [],
+ model: 'm',
+ systemPrompt: '',
+ mode: 'lu',
+ createdAt: 1,
+ updatedAt,
+ personaEnabled: false,
+ } as Conversation
+}
+
+// chatStore.importConversations — konata backup restore (merge never drops chats).
+describe('chatStore.importConversations', () => {
+ beforeEach(() => {
+ useChatStore.setState({ conversations: [], activeConversationId: null })
+ })
+
+ it('merge adds unseen conversations', () => {
+ useChatStore.setState({ conversations: [conv('a', 10)] })
+ const res = useChatStore.getState().importConversations([conv('b', 5), conv('c', 20)])
+ expect(res).toEqual({ added: 2, skipped: 0 })
+ expect(
+ useChatStore
+ .getState()
+ .conversations.map((c) => c.id)
+ .sort(),
+ ).toEqual(['a', 'b', 'c'])
+ })
+
+ it('merge skips duplicates that are not newer (existing is kept)', () => {
+ useChatStore.setState({ conversations: [conv('a', 10, 'live')] })
+ const res = useChatStore.getState().importConversations([conv('a', 10, 'stale')])
+ expect(res).toEqual({ added: 0, skipped: 1 })
+ expect(useChatStore.getState().conversations[0].title).toBe('live')
+ })
+
+ it('merge refreshes a conversation when the import is newer', () => {
+ useChatStore.setState({ conversations: [conv('a', 10, 'old')] })
+ const res = useChatStore.getState().importConversations([conv('a', 20, 'new')])
+ expect(res).toEqual({ added: 1, skipped: 0 })
+ expect(useChatStore.getState().conversations[0].title).toBe('new')
+ })
+
+ it('replace swaps the whole list', () => {
+ useChatStore.setState({ conversations: [conv('a', 10)] })
+ const res = useChatStore.getState().importConversations([conv('x', 1), conv('y', 2)], 'replace')
+ expect(res.added).toBe(2)
+ expect(
+ useChatStore
+ .getState()
+ .conversations.map((c) => c.id)
+ .sort(),
+ ).toEqual(['x', 'y'])
+ })
+
+ it('sorts merged conversations by updatedAt desc', () => {
+ useChatStore.setState({ conversations: [conv('a', 10)] })
+ useChatStore.getState().importConversations([conv('b', 30), conv('c', 20)])
+ expect(useChatStore.getState().conversations.map((c) => c.id)).toEqual(['b', 'c', 'a'])
+ })
+})
diff --git a/src/stores/chatStore.ts b/src/stores/chatStore.ts
index 88d0c077..5d3faa76 100644
--- a/src/stores/chatStore.ts
+++ b/src/stores/chatStore.ts
@@ -50,6 +50,11 @@ interface ChatState {
deleteMessagesAfter: (conversationId: string, messageId: string) => void
getActiveConversation: () => Conversation | undefined
searchConversations: (query: string) => Conversation[]
+ /** Bulk-import conversations from an exported backup (konata 2026-06-28: the
+ * web build has no store_backup.json, so a tunnel/origin change loses chats).
+ * merge = add unseen ids + refresh ones with a newer updatedAt; existing
+ * chats are never dropped. replace = swap the whole list. Returns counts. */
+ importConversations: (incoming: Conversation[], mode?: 'merge' | 'replace') => { added: number; skipped: number }
}
export const useChatStore = create<ChatState>()(
@@ -253,6 +258,36 @@ export const useChatStore = create<ChatState>()(
c.messages.some((m) => m.content.toLowerCase().includes(lower))
)
},
+
+ importConversations: (incoming, mode = 'merge') => {
+ // Normalize legacy block shapes on the way in (the same migration the
+ // persist layer runs on load), so an older export hydrates cleanly.
+ const clean = ((migratePersistedChat({ conversations: incoming })?.conversations ?? incoming) as Conversation[])
+ let added = 0
+ let skipped = 0
+ set((state) => {
+ if (mode === 'replace') {
+ added = clean.length
+ return { conversations: [...clean].sort((a, b) => (b.updatedAt || 0) - (a.updatedAt || 0)) }
+ }
+ const byId = new Map(state.conversations.map((c) => [c.id, c]))
+ for (const conv of clean) {
+ const existing = byId.get(conv.id)
+ if (!existing) {
+ byId.set(conv.id, conv)
+ added++
+ } else if ((conv.updatedAt || 0) > (existing.updatedAt || 0)) {
+ byId.set(conv.id, conv) // imported copy is newer → refresh it
+ added++
+ } else {
+ skipped++ // already present and not newer
+ }
+ }
+ const merged = Array.from(byId.values()).sort((a, b) => (b.updatedAt || 0) - (a.updatedAt || 0))
+ return { conversations: merged }
+ })
+ return { added, skipped }
+ },
}),
{
name: 'chat-conversations',