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(memory): der eigene Export laesst sich wieder einlesen, ohne die Sammlung zu verdoppeln

Davidee246ca927fe
diff --git a/e2e/memory-import-dedupe.spec.ts b/e2e/memory-import-dedupe.spec.ts
new file mode 100644
index 00000000..428a2130
--- /dev/null
+++ b/e2e/memory-import-dedupe.spec.ts
@@ -0,0 +1,51 @@
+import { expect, test } from '@playwright/test'
+
+/**
+ * Box-Test T5 vom 11.09.2026, Punkt 4: Export, Oberflaeche neu laden, dieselbe
+ * Datei importieren. Der Zaehler sprang von `4 memories` auf `8 memories` und
+ * `T5-bread` stand zweimal da. Dieser Lauf fuehrt genau diesen Weg durch die
+ * echte Oberflaeche, mit der echten Exportdatei aus dem Download.
+ */
+test('the app reads its own memory export back without doubling the collection', async ({ page }, testInfo) => {
+ await page.goto('/e2e/memory-sensitive-proof.html')
+ const seed = Buffer.from(JSON.stringify({
+ entries: [
+ { id: 't5-1', type: 'user', title: 'T5-bread', content: "The tester's favourite bread is rye.", sensitive: false },
+ { id: 't5-2', type: 'user', title: 'T5-box', content: 'The box runs Windows 10.', sensitive: false },
+ { id: 't5-3', type: 'feedback', title: 'T5-issues', content: 'Check the repository before filing one.', sensitive: false },
+ { id: 't5-4', type: 'project', title: 'T5-port', content: 'The engine listens on port 8127.', sensitive: false },
+ ],
+ }))
+ const input = page.locator('input[type=file]')
+ await input.setInputFiles({ name: 'seed.json', mimeType: 'application/json', buffer: seed })
+ await expect(page.getByText('Imported 4 memories.', { exact: true })).toBeVisible()
+ await expect(page.getByText('4 memories', { exact: true })).toBeVisible()
+
+ // Die echte Exportdatei, so wie sie der Knopf `.json` auf die Platte legt.
+ const pendingDownload = page.waitForEvent('download')
+ await page.getByRole('button', { name: '.json', exact: true }).click()
+ const stream = await (await pendingDownload).createReadStream()
+ if (!stream) throw new Error('No exported JSON stream')
+ const chunks: Buffer[] = []
+ for await (const chunk of stream) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk))
+ const exported = Buffer.concat(chunks)
+
+ await page.reload()
+ await expect(page.getByText('4 memories', { exact: true })).toBeVisible()
+
+ await page.locator('input[type=file]').setInputFiles({ name: 'memory.json', mimeType: 'application/json', buffer: exported })
+ await expect(page.getByText('Imported 0 new memories, 4 already present.', { exact: true })).toBeVisible()
+ await expect(page.getByText('4 memories', { exact: true })).toBeVisible()
+ await expect(page.getByText('T5-bread', { exact: true })).toHaveCount(1)
+ await page.screenshot({ path: testInfo.outputPath('memory-import-dedupe.png') })
+
+ // Gegenpfad: dieselbe Datei mit einem Eintrag mehr. Der eine kommt an, die
+ // vier bekannten nicht noch einmal.
+ const gewachsen = JSON.parse(exported.toString('utf8'))
+ gewachsen.entries.push({ id: 't5-5', type: 'user', title: 'T5-tea', content: "The tester's favourite tea is rooibos.", sensitive: false })
+ await page.locator('input[type=file]').setInputFiles({
+ name: 'memory-plus-one.json', mimeType: 'application/json', buffer: Buffer.from(JSON.stringify(gewachsen)),
+ })
+ await expect(page.getByText('Imported 1 new memory, 4 already present.', { exact: true })).toBeVisible()
+ await expect(page.getByText('5 memories', { exact: true })).toBeVisible()
+})
diff --git a/src/components/settings/LocalApiSettings.tsx b/src/components/settings/LocalApiSettings.tsx
index 0ab574c2..22e07bfd 100644
--- a/src/components/settings/LocalApiSettings.tsx
+++ b/src/components/settings/LocalApiSettings.tsx
@@ -48,7 +48,7 @@ export function LocalApiSettings() {
return (
<div className="space-y-3">
<p className="t-micro text-gray-600">
- One OpenAI-compatible address for every model on this machine — LU Engine, Ollama
+ One OpenAI-compatible address for every model on this machine: LU Engine, Ollama
and LM Studio under a single URL. Anything that can talk to OpenAI can talk to your
local models through it.
</p>
@@ -110,7 +110,7 @@ export function LocalApiSettings() {
<div className="flex items-center gap-2">
<Globe className="w-3 h-3 text-gray-500" />
<span className="t-micro text-gray-500">
- Browser access — leave empty if no web page should use the API.
+ Browser access. Leave empty if no web page should use the API.
</span>
</div>
<input
@@ -127,7 +127,7 @@ export function LocalApiSettings() {
<div className="space-y-1">
<div className="flex items-center gap-2">
<KeyRound className="w-3 h-3 text-gray-500" />
- <span className="t-micro text-gray-500">Token — every request needs it, including from this machine.</span>
+ <span className="t-micro text-gray-500">Token. Every request needs it, including from this machine.</span>
</div>
<div className="flex items-center gap-2">
<input
diff --git a/src/components/settings/MemorySettings.tsx b/src/components/settings/MemorySettings.tsx
index 8e2407fd..228bfec0 100644
--- a/src/components/settings/MemorySettings.tsx
+++ b/src/components/settings/MemorySettings.tsx
@@ -1,6 +1,6 @@
import { useState, useRef, useEffect } from 'react'
import { Brain, Download, Upload, Trash2, Search, Plus, X, Check, Pencil, Zap, FileJson, Archive, Sparkles } from 'lucide-react'
-import { useMemoryStore, effectiveMemoryBudget } from '../../stores/memoryStore'
+import { useMemoryStore, effectiveMemoryBudget, describeMemoryImport } from '../../stores/memoryStore'
import { useRemoteStore } from '../../stores/remoteStore'
import { useModelStore } from '../../stores/modelStore'
import { useChatStore, persistConversationMemoryScope } from '../../stores/chatStore'
@@ -189,10 +189,10 @@ function MemorySettingsPanel() {
if (!content) { setImportMsg('Could not read that file.'); return }
const trimmed = content.trimStart()
const isJson = /\.json$/i.test(file.name) || trimmed.startsWith('{') || trimmed.startsWith('[')
- const count = isJson ? importFromJSON(content) : importFromMarkdown(content)
+ const result = isJson ? importFromJSON(content) : importFromMarkdown(content)
setImportMsg(
- count > 0
- ? `Imported ${count} ${count === 1 ? 'memory' : 'memories'}.`
+ result.added + result.updated + result.alreadyPresent > 0
+ ? describeMemoryImport(result)
: 'No memories found in that file. Use an LU .md or .json export (JSON needs an "entries" or "memories" array).',
)
}
diff --git a/src/components/settings/RemoteAccessDocs.tsx b/src/components/settings/RemoteAccessDocs.tsx
index b9130b2c..010ee3bd 100644
--- a/src/components/settings/RemoteAccessDocs.tsx
+++ b/src/components/settings/RemoteAccessDocs.tsx
@@ -67,7 +67,7 @@ export function RemoteAccessDocs() {
<Step n={3} icon={<Globe size={12} className="text-gray-500" />} title="Dispatch over the internet">
Choose <span className="text-gray-400 font-medium">Dispatch → Internet</span> instead to
reach LU from anywhere. LU starts a Cloudflare tunnel and gives you a public
- <span className="text-gray-400"> https://…trycloudflare.com</span> URL — no router or
+ <span className="text-gray-400"> https://…trycloudflare.com</span> URL, with no router or
port-forwarding setup. The tunnel only exists while the session is dispatched.
</Step>
diff --git a/src/components/settings/__tests__/keine-gedankenstriche-in-remote-und-local-api.test.ts b/src/components/settings/__tests__/keine-gedankenstriche-in-remote-und-local-api.test.ts
new file mode 100644
index 00000000..0c298722
--- /dev/null
+++ b/src/components/settings/__tests__/keine-gedankenstriche-in-remote-und-local-api.test.ts
@@ -0,0 +1,64 @@
+/**
+ * Hausregel: kein Gedankenstrich im Text, den ein Kunde liest. Der Satz wird
+ * umgebaut, mit Punkt, Komma oder Doppelpunkt.
+ *
+ * Box-Test T5 vom 11.09.2026, Nebenfund 1: fuenf Zeichen U+2014 im
+ * Oberflaechentext, ueber `charCodeAt` gezaehlt. Einer im Hilfetext von Remote
+ * Access, vier im Panel Local API. Alle sind umgeschrieben, dazu ein sechster
+ * im LAN-Satz der Local API, den der Tester nicht zu sehen bekam.
+ *
+ * Der Wachposten haelt genau diese drei Quelldateien. Ein Durchgang ueber das
+ * ganze Repo ist ausdruecklich nicht gewollt (David hat ihn am 08.09. gestoppt,
+ * GitHub #163), und ein Waechter, der mehr behauptet als er traegt, ist
+ * schlimmer als keiner. Kommentare bleiben draussen: sie erreichen keinen
+ * Leser. Dasselbe Muster haelt im Web-Repo die drei Marketing-Seiten
+ * (`public-copy-dashes.test.ts`, Bauer W5).
+ *
+ * Die Striche stehen hier als Code-Punkte, damit diese Datei nicht ihr eigener
+ * erster Fund wird.
+ *
+ * Run: npx vitest run src/components/settings/__tests__/keine-gedankenstriche-in-remote-und-local-api.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+
+const SRC = join(__dirname, '..', '..', '..')
+
+/** Die Oberflaechen des Fundes, je Quelldatei ihres Textes. */
+const QUELLEN: Array<[flaeche: string, datei: string]> = [
+ ['Settings > Voice & Remote > Local API', join('components', 'settings', 'LocalApiSettings.tsx')],
+ ['die Saetze der Local API', join('lib', 'local-api.ts')],
+ ['Settings > Voice & Remote > Remote Access, How it works', join('components', 'settings', 'RemoteAccessDocs.tsx')],
+]
+
+/** Quelltext ohne Kommentare: nur was den Leser erreicht, zaehlt. */
+function ausgeliefert(datei: string): string {
+ return readFileSync(join(SRC, datei), 'utf8')
+ .replace(/\/\*[\s\S]*?\*\//g, '')
+ .replace(/(^|[^:])\/\/[^\n]*/g, '$1')
+}
+
+const STRICHE = ['\u2014', '\u2013']
+
+describe('die Texte aus T5 tragen keinen Gedankenstrich', () => {
+ for (const [flaeche, datei] of QUELLEN) {
+ it(`${flaeche} kommt ohne aus`, () => {
+ const gefunden = [...ausgeliefert(datei)].filter((c) => STRICHE.includes(c))
+ expect(gefunden, `${gefunden.length} Strich(e) in ${datei}`).toEqual([])
+ })
+ }
+
+ it('POSITIVKONTROLLE: die Suche findet beide Striche, wenn sie dastehen', () => {
+ // Ohne sie koennte der Waechter an einem kaputten Muster blind sein und
+ // trotzdem gruen melden.
+ const probe = 'a \u2014 b \u2013 c'
+ expect([...probe].filter((c) => STRICHE.includes(c))).toHaveLength(2)
+ })
+
+ it('POSITIVKONTROLLE: ein Strich im Kommentar zaehlt nicht, einer im Text schon', () => {
+ const mitKommentar = ausgeliefert(join('lib', 'local-api.ts'))
+ expect(mitKommentar).not.toContain('Die lokale Modell-API')
+ expect(mitKommentar).toContain('No web page may read this API')
+ })
+})
diff --git a/src/lib/local-api.ts b/src/lib/local-api.ts
index dd0d8076..1088f0d2 100644
--- a/src/lib/local-api.ts
+++ b/src/lib/local-api.ts
@@ -104,7 +104,7 @@ export function clientFelder(base: string, token: string): Array<{ feld: string;
*/
export function reichweiteText(lan: boolean): string {
return lan
- ? 'Any device on your network can reach the API — guests on the same Wi-Fi included. The token is then the only boundary.'
+ ? 'Any device on your network can reach the API, guests on the same Wi-Fi included. The token is then the only boundary.'
: 'Only programs on this machine reach the API. Other devices on the network do not.'
}
@@ -161,7 +161,7 @@ export function parseCorsOrigins(text: string): string[] {
*/
export function corsText(origins: string[]): string {
if (origins.length === 0) {
- return 'Closed. No web page may read this API — command-line tools and apps are unaffected.'
+ return 'Closed. No web page may read this API. Command-line tools and apps are unaffected.'
}
return origins.length === 1
? `Open to ${origins[0]} only.`
diff --git a/src/stores/__tests__/der-eigene-export-liest-sich-wieder-ein.test.ts b/src/stores/__tests__/der-eigene-export-liest-sich-wieder-ein.test.ts
index 7803a9ac..9f837b5b 100644
--- a/src/stores/__tests__/der-eigene-export-liest-sich-wieder-ein.test.ts
+++ b/src/stores/__tests__/der-eigene-export-liest-sich-wieder-ein.test.ts
@@ -40,7 +40,7 @@ function rundlauf(eintraege: MemoryFile[]): MemoryFile[] {
leerenUndSetzen(eintraege)
const md = useMemoryStore.getState().exportAsMarkdown()
leerenUndSetzen([])
- const zahl = useMemoryStore.getState().importFromMarkdown(md)
+ const zahl = useMemoryStore.getState().importFromMarkdown(md).added
expect(zahl).toBe(eintraege.length)
return useMemoryStore.getState().entries
}
@@ -110,7 +110,7 @@ describe('der eigene Markdown-Export laesst sich wieder einlesen', () => {
].join('\n')
leerenUndSetzen([])
- expect(useMemoryStore.getState().importFromMarkdown(alt)).toBe(1)
+ expect(useMemoryStore.getState().importFromMarkdown(alt).added).toBe(1)
const [zurueck] = useMemoryStore.getState().entries
expect(zurueck.title).toBe('Arbeitet auf Deutsch')
expect(zurueck.content).toBe(EINTRAG.content)
@@ -120,7 +120,7 @@ describe('der eigene Markdown-Export laesst sich wieder einlesen', () => {
it('POSITIVKONTROLLE: der schlichte Strichpunkt ohne Auszeichnung geht auch ein', () => {
leerenUndSetzen([])
- expect(useMemoryStore.getState().importFromMarkdown('## User\n\n- Ein blanker Satz ohne alles\n')).toBe(1)
+ expect(useMemoryStore.getState().importFromMarkdown('## User\n\n- Ein blanker Satz ohne alles\n').added).toBe(1)
expect(useMemoryStore.getState().entries[0].content).toBe('Ein blanker Satz ohne alles')
})
})
diff --git a/src/stores/__tests__/der-import-derselben-datei-verdoppelt-nichts.test.ts b/src/stores/__tests__/der-import-derselben-datei-verdoppelt-nichts.test.ts
new file mode 100644
index 00000000..d9dfd726
--- /dev/null
+++ b/src/stores/__tests__/der-import-derselben-datei-verdoppelt-nichts.test.ts
@@ -0,0 +1,200 @@
+/**
+ * Die eigene Exportdatei darf beim Zurueckladen keine zweite Sammlung anlegen.
+ *
+ * Box-Test T5 vom 11.09.2026, Punkt 4, DURCHGEFALLEN: vier Erinnerungen,
+ * Export als `.json` (2630 Bytes, vier Eintraege mit `sensitive` und `scope`),
+ * Oberflaeche neu geladen, dieselbe Datei wieder eingelesen. Die App meldete
+ * `Imported 4 memories.`, der Zaehler stand auf `8 memories` und `T5-bread`
+ * stand zweimal da, obwohl jeder Eintrag seine Kennung mitbrachte.
+ *
+ * Der Import haengte bis dahin jeden gelesenen Eintrag mit frisch gewuerfelter
+ * Kennung hinten an. Jetzt trifft er die Sammlung, die schon da ist: gleiche
+ * Kennung oder gleicher Inhalt zaehlt als derselbe Eintrag.
+ *
+ * Run: npx vitest run src/stores/__tests__/der-import-derselben-datei-verdoppelt-nichts.test.ts
+ */
+import { describe, it, expect, beforeEach, afterEach } from 'vitest'
+import { useMemoryStore, describeMemoryImport, __setMemoryEmbedFn } from '../memoryStore'
+import type { MemoryFile } from '../../types/agent-mode'
+
+const STAND = Date.UTC(2026, 8, 11, 20, 30)
+
+/** Die vier Eintraege der Box, Feld fuer Feld wie in der Exportdatei. */
+const VIER: MemoryFile[] = [
+ {
+ id: '036d5d61-0000-4000-8000-000000000001', type: 'user', title: 'T5-bread',
+ description: "The tester's favourite bread is rye.", content: "The tester's favourite bread is rye.",
+ tags: [], source: 'manual', sensitive: false, scope: 't5-other',
+ createdAt: STAND - 90_000, updatedAt: STAND - 60_000,
+ },
+ {
+ id: '036d5d61-0000-4000-8000-000000000002', type: 'feedback', title: 'Assistant is prone to file issues',
+ description: 'Check the repository before opening one.', content: 'Check the repository before opening one.',
+ tags: ['github'], source: 'auto:extraction', sensitive: false,
+ createdAt: STAND - 80_000, updatedAt: STAND - 80_000,
+ },
+ {
+ id: '036d5d61-0000-4000-8000-000000000003', type: 'project', title: 'Box runs Windows 10',
+ description: 'The test machine is a Windows 10 box with 12 GB VRAM.',
+ content: 'The test machine is a Windows 10 box with 12 GB VRAM.',
+ tags: [], source: 'manual', sensitive: false,
+ createdAt: STAND - 70_000, updatedAt: STAND - 70_000,
+ },
+ {
+ id: '036d5d61-0000-4000-8000-000000000004', type: 'user', title: 'T5-secret',
+ description: 'Private note that never leaves the machine.',
+ content: 'Private note that never leaves the machine.',
+ tags: [], source: 'manual', sensitive: true,
+ createdAt: STAND - 60_000, updatedAt: STAND - 60_000,
+ },
+]
+
+function sammlung(eintraege: MemoryFile[] = VIER) {
+ useMemoryStore.setState({ entries: eintraege.map((e) => ({ ...e })) })
+}
+
+/** Was der Knopf `.json` auf die Platte schreibt. */
+function exportdatei(): string {
+ return useMemoryStore.getState().exportAsJSON()
+}
+
+function titel(): string[] {
+ return useMemoryStore.getState().entries.map((e) => e.title)
+}
+
+beforeEach(() => {
+ __setMemoryEmbedFn(async () => [])
+ sammlung([])
+})
+afterEach(() => __setMemoryEmbedFn())
+
+describe('Export, neu laden, dieselbe Datei importieren', () => {
+ it('HAUPTFALL: der Bestand bleibt bei vier, T5-bread steht einmal da', () => {
+ sammlung()
+ const datei = exportdatei()
+
+ const ergebnis = useMemoryStore.getState().importFromJSON(datei)
+
+ expect(ergebnis).toEqual({ added: 0, updated: 0, alreadyPresent: 4 })
+ expect(useMemoryStore.getState().entries).toHaveLength(4)
+ expect(titel().filter((t) => t === 'T5-bread')).toHaveLength(1)
+ })
+
+ it('HAUPTFALL: die Meldung nennt die Zahlen, die wirklich gelaufen sind', () => {
+ sammlung()
+ const ergebnis = useMemoryStore.getState().importFromJSON(exportdatei())
+
+ expect(describeMemoryImport(ergebnis)).toBe('Imported 0 new memories, 4 already present.')
+ })
+
+ it('die erkannten Eintraege werden nicht angefasst: Kennung, Geburtstag und Stand bleiben', () => {
+ sammlung()
+ const vorher = useMemoryStore.getState().entries
+
+ useMemoryStore.getState().importFromJSON(exportdatei())
+
+ expect(useMemoryStore.getState().entries).toEqual(vorher)
+ })
+
+ it('GEGENPFAD: eine Datei mit einem zusaetzlichen Eintrag legt genau diesen an', () => {
+ sammlung()
+ const datei = JSON.parse(exportdatei())
+ datei.entries.push({
+ id: '036d5d61-0000-4000-8000-000000000009', type: 'user', title: 'T5-tea',
+ description: "The tester's favourite tea is rooibos.", content: "The tester's favourite tea is rooibos.",
+ tags: [], source: 'manual', sensitive: false, createdAt: STAND, updatedAt: STAND,
+ })
+
+ const ergebnis = useMemoryStore.getState().importFromJSON(JSON.stringify(datei))
+
+ expect(ergebnis).toEqual({ added: 1, updated: 0, alreadyPresent: 4 })
+ expect(useMemoryStore.getState().entries).toHaveLength(5)
+ expect(titel()).toContain('T5-tea')
+ expect(describeMemoryImport(ergebnis)).toBe('Imported 1 new memory, 4 already present.')
+ })
+
+ it('ein geaenderter Eintrag ersetzt seinen alten Stand, statt daneben zu stehen', () => {
+ sammlung()
+ const datei = JSON.parse(exportdatei())
+ datei.entries[0].content = "The tester's favourite bread is sourdough."
+ datei.entries[0].description = "The tester's favourite bread is sourdough."
+
+ const ergebnis = useMemoryStore.getState().importFromJSON(JSON.stringify(datei))
+
+ expect(ergebnis).toEqual({ added: 0, updated: 1, alreadyPresent: 3 })
+ expect(useMemoryStore.getState().entries).toHaveLength(4)
+ const brot = useMemoryStore.getState().entries.filter((e) => e.title === 'T5-bread')
+ expect(brot).toHaveLength(1)
+ expect(brot[0].id).toBe(VIER[0].id)
+ expect(brot[0].content).toBe("The tester's favourite bread is sourdough.")
+ expect(brot[0].createdAt).toBe(VIER[0].createdAt)
+ expect(describeMemoryImport(ergebnis)).toBe('Imported 0 new memories, 1 updated, 3 already present.')
+ })
+
+ it('eine Datei ohne Kennungen wird am Inhalt erkannt', () => {
+ // Eine fremde Ausfuhr oder ein von Hand geschriebener Satz traegt keine
+ // stabile Kennung. Dann entscheiden Inhalt, Sorte und Projekt.
+ sammlung()
+ const ohne = JSON.parse(exportdatei())
+ for (const e of ohne.entries) delete e.id
+
+ expect(useMemoryStore.getState().importFromJSON(JSON.stringify(ohne)))
+ .toEqual({ added: 0, updated: 0, alreadyPresent: 4 })
+ expect(useMemoryStore.getState().entries).toHaveLength(4)
+ })
+
+ it('dieselbe Erinnerung zweimal in EINER Datei landet einmal', () => {
+ sammlung([])
+ const doppelt = JSON.stringify([
+ { id: 'a', type: 'user', title: 'Doppelt', content: 'Steht zweimal in der Datei.' },
+ { id: 'b', type: 'user', title: 'Doppelt', content: 'Steht zweimal in der Datei.' },
+ ])
+
+ expect(useMemoryStore.getState().importFromJSON(doppelt)).toEqual({ added: 1, updated: 0, alreadyPresent: 1 })
+ expect(useMemoryStore.getState().entries).toHaveLength(1)
+ })
+
+ it('derselbe Satz in einem anderen Projekt ist eine andere Erinnerung', () => {
+ // Gegenprobe zur Entdopplung: sie darf nicht ueber Projektgrenzen greifen.
+ sammlung()
+ const fremd = JSON.stringify([{ ...VIER[0], id: 'neu', scope: 'anderes-projekt' }])
+
+ expect(useMemoryStore.getState().importFromJSON(fremd)).toEqual({ added: 1, updated: 0, alreadyPresent: 0 })
+ expect(useMemoryStore.getState().entries).toHaveLength(5)
+ })
+
+ it('POSITIVKONTROLLE: in eine leere Sammlung kommen alle vier an, mit der alten Meldung', () => {
+ sammlung()
+ const datei = exportdatei()
+ sammlung([])
+
+ const ergebnis = useMemoryStore.getState().importFromJSON(datei)
+
+ expect(ergebnis).toEqual({ added: 4, updated: 0, alreadyPresent: 0 })
+ expect(useMemoryStore.getState().entries).toHaveLength(4)
+ expect(describeMemoryImport(ergebnis)).toBe('Imported 4 memories.')
+ })
+
+ it('auch der Markdown-Export laesst sich zweimal lesen', () => {
+ // Ein Knopf liest beide Formate. Markdown traegt keine Kennung, also
+ // greift dort dieselbe Regel ueber den Inhalt.
+ sammlung()
+ const md = useMemoryStore.getState().exportAsMarkdown()
+ sammlung([])
+ // Markdown traegt weder den sensiblen noch den Projekt-Eintrag, es bleiben zwei.
+ expect(useMemoryStore.getState().importFromMarkdown(md).added).toBe(2)
+
+ expect(useMemoryStore.getState().importFromMarkdown(md))
+ .toEqual({ added: 0, updated: 0, alreadyPresent: 2 })
+ expect(useMemoryStore.getState().entries).toHaveLength(2)
+ })
+})
+
+describe('die Meldung nach dem Import', () => {
+ it('nennt nur die Zahlen, die es gibt', () => {
+ expect(describeMemoryImport({ added: 1, updated: 0, alreadyPresent: 0 })).toBe('Imported 1 memory.')
+ expect(describeMemoryImport({ added: 0, updated: 0, alreadyPresent: 1 })).toBe('Imported 0 new memories, 1 already present.')
+ expect(describeMemoryImport({ added: 2, updated: 1, alreadyPresent: 0 })).toBe('Imported 2 new memories, 1 updated.')
+ expect(describeMemoryImport({ added: 0, updated: 4, alreadyPresent: 2 })).toBe('Imported 0 new memories, 4 updated, 2 already present.')
+ })
+})
diff --git a/src/stores/__tests__/memory-provenance.test.ts b/src/stores/__tests__/memory-provenance.test.ts
index 1ef66c41..0bcc7fb3 100644
--- a/src/stores/__tests__/memory-provenance.test.ts
+++ b/src/stores/__tests__/memory-provenance.test.ts
@@ -35,7 +35,7 @@ it('round trips source identity, modality and review through JSON without invent
const original = useMemoryStore.getState().entries[0]
const json = useMemoryStore.getState().exportAsJSON()
useMemoryStore.getState().clearAll()
- expect(useMemoryStore.getState().importFromJSON(json)).toBe(1)
+ expect(useMemoryStore.getState().importFromJSON(json).added).toBe(1)
expect(useMemoryStore.getState().entries[0]).toMatchObject({ source: original.source, sourceKind: 'voice', confirmedAt: original.confirmedAt })
useMemoryStore.getState().importFromJSON(JSON.stringify([{ content: 'Legacy fact' }, { content: 'Invalid metadata', sourceKind: 'forged', confirmedAt: 1e99 }]))
for (const entry of useMemoryStore.getState().entries.slice(1)) {
diff --git a/src/stores/__tests__/memory-scope.test.ts b/src/stores/__tests__/memory-scope.test.ts
index f31389bb..29f544b6 100644
--- a/src/stores/__tests__/memory-scope.test.ts
+++ b/src/stores/__tests__/memory-scope.test.ts
@@ -29,10 +29,10 @@ it('preserves JSON scope and never promotes malformed scope to global', () => {
add('A')
const json = useMemoryStore.getState().exportAsJSON()
useMemoryStore.getState().clearAll()
- expect(useMemoryStore.getState().importFromJSON(json)).toBe(1)
+ expect(useMemoryStore.getState().importFromJSON(json).added).toBe(1)
expect(useMemoryStore.getState().entries[0].scope).toBe('A')
for (const scope of [null, 12, '', ' ']) {
- expect(useMemoryStore.getState().importFromJSON(JSON.stringify([{ content: 'bad scope', scope }]))).toBe(0)
+ expect(useMemoryStore.getState().importFromJSON(JSON.stringify([{ content: 'bad scope', scope }])).added).toBe(0)
}
expect(useMemoryStore.getState().exportAsMarkdown()).not.toContain('Project fixture')
})
diff --git a/src/stores/__tests__/memory-sensitive.test.ts b/src/stores/__tests__/memory-sensitive.test.ts
index 5e062c78..bc5b8609 100644
--- a/src/stores/__tests__/memory-sensitive.test.ts
+++ b/src/stores/__tests__/memory-sensitive.test.ts
@@ -25,7 +25,7 @@ it('preserves sensitivity through JSON export/import and omits it from Markdown'
const json = useMemoryStore.getState().exportAsJSON()
expect(useMemoryStore.getState().exportAsMarkdown()).not.toContain('Synthetic private')
useMemoryStore.getState().clearAll()
- expect(useMemoryStore.getState().importFromJSON(json)).toBe(1)
+ expect(useMemoryStore.getState().importFromJSON(json).added).toBe(1)
expect(useMemoryStore.getState().entries[0].sensitive).toBe(true)
expect(useMemoryStore.getState().getMemoriesForPrompt('private', 8192)).toBe('')
})
diff --git a/src/stores/__tests__/stores.test.ts b/src/stores/__tests__/stores.test.ts
index 158caee5..d0df4072 100644
--- a/src/stores/__tests__/stores.test.ts
+++ b/src/stores/__tests__/stores.test.ts
@@ -409,30 +409,31 @@ describe('memoryStore', () => {
{ type: 'user', title: 'A', content: 'alpha' },
{ type: 'project', title: 'B', content: 'beta' },
] }))
- expect(n).toBe(2)
+ expect(n.added).toBe(2)
expect(useMemoryStore.getState().entries).toHaveLength(2)
})
it('tolerates a bare array', () => {
- expect(useMemoryStore.getState().importFromJSON(JSON.stringify([{ content: 'x' }, { content: 'y' }]))).toBe(2)
+ expect(useMemoryStore.getState().importFromJSON(JSON.stringify([{ content: 'x' }, { content: 'y' }])).added).toBe(2)
})
it('tolerates a {memories:[...]} shape', () => {
- expect(useMemoryStore.getState().importFromJSON(JSON.stringify({ memories: [{ content: 'z' }] }))).toBe(1)
+ expect(useMemoryStore.getState().importFromJSON(JSON.stringify({ memories: [{ content: 'z' }] })).added).toBe(1)
})
it('returns 0 for invalid JSON and for entries without content', () => {
- expect(useMemoryStore.getState().importFromJSON('not json')).toBe(0)
- expect(useMemoryStore.getState().importFromJSON(JSON.stringify({ entries: [{ title: 'no content' }] }))).toBe(0)
+ expect(useMemoryStore.getState().importFromJSON('not json').added).toBe(0)
+ expect(useMemoryStore.getState().importFromJSON(JSON.stringify({ entries: [{ title: 'no content' }] })).added).toBe(0)
expect(useMemoryStore.getState().entries).toHaveLength(0)
})
- it('regenerates ids so a re-imported export never collides', () => {
+ it('reads the same file twice without a second copy and without an id collision', () => {
const json = JSON.stringify({ entries: [{ id: 'fixed-id', type: 'user', title: 'T', content: 'c' }] })
- useMemoryStore.getState().importFromJSON(json)
- useMemoryStore.getState().importFromJSON(json)
+ expect(useMemoryStore.getState().importFromJSON(json).added).toBe(1)
+ expect(useMemoryStore.getState().importFromJSON(json)).toEqual({ added: 0, updated: 0, alreadyPresent: 1 })
const ids = useMemoryStore.getState().entries.map(e => e.id)
- expect(new Set(ids).size).toBe(2)
+ expect(ids).toHaveLength(1)
+ expect(new Set(ids).size).toBe(1)
})
it('importFromMarkdown returns the number of parsed entries', () => {
const md = '# Memory\n\n## User\n\n- **Likes** — coffee [drinks] *(import)*\n'
- expect(useMemoryStore.getState().importFromMarkdown(md)).toBe(1)
+ expect(useMemoryStore.getState().importFromMarkdown(md).added).toBe(1)
expect(useMemoryStore.getState().entries[0].content).toBe('coffee')
})
})
diff --git a/src/stores/memoryStore.ts b/src/stores/memoryStore.ts
index a74f163b..40c7957b 100644
--- a/src/stores/memoryStore.ts
+++ b/src/stores/memoryStore.ts
@@ -66,6 +66,52 @@ export function memoryMatchesScope(memory: Pick<MemoryFile, 'scope'>, scope?: st
return memory.scope === undefined ||
(typeof memory.scope === 'string' && memory.scope.trim().length > 0 && memory.scope === scope)
}
+
+/**
+ * Same memory inside one collection: same content, same type, same scope.
+ * addMemory has always refused a second record on this rule; the importers
+ * reuse it, so reading the app's own export back in cannot double a collection
+ * (box test T5 punkt 4, 11.09.2026: import of a 4-entry export gave 8 entries).
+ */
+export function isSameMemory(
+ a: Pick<MemoryFile, 'content' | 'type' | 'scope'>,
+ b: Pick<MemoryFile, 'content' | 'type' | 'scope'>,
+): boolean {
+ return a.content === b.content && a.type === b.type && a.scope === b.scope
+}
+
+/**
+ * Everything an import did. Every usable entry of the file lands in exactly one
+ * counter, so the UI can name the numbers instead of claiming a flat import.
+ */
+export interface MemoryImportResult {
+ /** Written as new records. */
+ added: number
+ /** Known records (same id) refreshed from the file because fields changed. */
+ updated: number
+ /** Already in this collection, left untouched. */
+ alreadyPresent: number
+}
+
+/** Everything that decides whether a known record still matches the file. */
+function importDigest(m: MemoryFile): string {
+ return JSON.stringify([m.type, m.title, m.description, m.content, [...m.tags].sort(), m.source,
+ m.sourceKind ?? null, m.confirmedAt ?? null, m.sensitive === true, m.scope ?? null,
+ m.stale === true, m.validFrom ?? null, m.supersededBy ?? null, m.supersedesId ?? null])
+}
+
+/** The sentence the settings page shows after an import. Desktop and web share the wording. */
+export function describeMemoryImport(result: MemoryImportResult): string {
+ const noun = (n: number) => (n === 1 ? 'memory' : 'memories')
+ if (result.updated === 0 && result.alreadyPresent === 0) {
+ return `Imported ${result.added} ${noun(result.added)}.`
+ }
+ const parts = [`Imported ${result.added} new ${noun(result.added)}`]
+ if (result.updated > 0) parts.push(`${result.updated} updated`)
+ if (result.alreadyPresent > 0) parts.push(`${result.alreadyPresent} already present`)
+ return `${parts.join(', ')}.`
+}
+
function hashContent(s: string): string {
let h = 5381
for (let i = 0; i < s.length; i++) h = (h * 33) ^ s.charCodeAt(i)
@@ -307,12 +353,13 @@ interface MemoryState {
// Settings
updateMemorySettings: (updates: Partial<MemorySettings>) => void
- // Export / Import — importers return the number of entries actually added
- // so the UI can give feedback (konata-session 2026-06-07: silent 0-import).
+ // Export / Import — importers report what they did with every usable entry
+ // of the file so the UI can give feedback (konata-session 2026-06-07: silent
+ // 0-import; box test T5 2026-09-11: re-import doubled the collection).
exportAsMarkdown: () => string
- importFromMarkdown: (markdown: string) => number
+ importFromMarkdown: (markdown: string) => MemoryImportResult
exportAsJSON: () => string
- importFromJSON: (json: string) => number
+ importFromJSON: (json: string) => MemoryImportResult
// Legacy compat (used by old code paths during transition)
addEntry: (category: MemoryCategory, content: string, source?: string) => void
@@ -577,9 +624,9 @@ export const useMemoryStore = create<MemoryState>()(
const trimmedContent = memory.content.trim()
if (!trimmedContent) return ''
- // Deduplicate: don't add if exact same content + type exists
- const existing = get().entries
- if (existing.some(e => e.content === trimmedContent && e.type === memory.type && e.scope === memory.scope)) return ''
+ // Deduplicate: don't add if the same memory is already in the collection
+ const candidate = { content: trimmedContent, type: memory.type, scope: memory.scope }
+ if (get().entries.some(e => isSameMemory(e, candidate))) return ''
const id = uuid()
set((state) => ({
@@ -914,7 +961,9 @@ export const useMemoryStore = create<MemoryState>()(
importFromMarkdown: (markdown) => {
const lines = markdown.split('\n')
+ const pool: MemoryFile[] = [...get().entries]
const newEntries: MemoryFile[] = []
+ let alreadyPresent = 0
let currentType: MemoryType = 'user'
const typeMap: Record<string, MemoryType> = {
@@ -940,7 +989,7 @@ export const useMemoryStore = create<MemoryState>()(
const stand = isoBack(itemMatch[5]) ?? Date.now()
if (content) {
- newEntries.push({
+ const entry: MemoryFile = {
id: uuid(),
type: currentType,
title: title.substring(0, 60),
@@ -950,7 +999,12 @@ export const useMemoryStore = create<MemoryState>()(
createdAt: stand,
updatedAt: stand,
source,
- })
+ }
+ // A markdown export carries no id, so the collection itself
+ // decides what is already known.
+ if (pool.some((known) => isSameMemory(known, entry))) { alreadyPresent++; continue }
+ pool.push(entry)
+ newEntries.push(entry)
}
}
}
@@ -961,7 +1015,7 @@ export const useMemoryStore = create<MemoryState>()(
lastSynced: Date.now(),
}))
}
- return newEntries.length
+ return { added: newEntries.length, updated: 0, alreadyPresent }
},
exportAsJSON: () => {
@@ -975,7 +1029,7 @@ export const useMemoryStore = create<MemoryState>()(
raw = JSON.parse(json)
} catch {
log.error('Failed to parse memory JSON import')
- return 0
+ return { added: 0, updated: 0, alreadyPresent: 0 }
}
// Tolerant shape handling: accept LU's own {entries:[...]} export, a
// bare [...] array, or {memories:[...]} (konata-session 2026-06-07 —
@@ -987,9 +1041,15 @@ export const useMemoryStore = create<MemoryState>()(
: Array.isArray(memoriesField) ? memoriesField
: []
const now = Date.now()
- const newEntries: MemoryFile[] = []
+ // The collection as it stands, grown while the file is read, so a file
+ // that carries the same memory twice cannot land twice either.
+ const pool: MemoryFile[] = [...get().entries]
const importedIds = new Map<string, string | null>()
- const history: Array<{ supersededBy?: string; supersedesId?: string }> = []
+ const landed: Array<{
+ entry: MemoryFile
+ links: { supersededBy?: string; supersedesId?: string }
+ known?: MemoryFile
+ }> = []
for (const e of arr) {
const scope = prop(e, 'scope')
if (scope !== undefined && (typeof scope !== 'string' || !scope.trim())) continue
@@ -1001,21 +1061,14 @@ export const useMemoryStore = create<MemoryState>()(
const type = MEMORY_TYPES.find((t) => t === prop(e, 'type')) ?? 'user'
const sourceKind = prop(e, 'sourceKind')
const confirmedAt = prop(e, 'confirmedAt')
- const id = uuid()
const originalId = asString(prop(e, 'id'))
- if (originalId) importedIds.set(originalId, importedIds.has(originalId) ? null : id)
const supersededBy = asString(prop(e, 'supersededBy'))
- history.push({ supersededBy, supersedesId: asString(prop(e, 'supersedesId')) })
- newEntries.push({
- // Always mint a fresh id so a re-imported export can never collide
- // with an existing entry's id (which broke edit/remove-by-id).
- id,
+ const draft: Omit<MemoryFile, 'id' | 'createdAt'> = {
type,
title: (asString(prop(e, 'title')) ?? content).slice(0, 60).replace(/\n/g, ' '),
description: (asString(prop(e, 'description')) ?? content).slice(0, 120),
content,
tags: asStringArray(prop(e, 'tags')),
- createdAt: asNumber(prop(e, 'createdAt')) ?? now,
updatedAt: now,
source: asString(prop(e, 'source')) ?? 'import',
sourceKind: sourceKind === 'chat' || sourceKind === 'voice' || sourceKind === 'screen' ? sourceKind : undefined,
@@ -1025,22 +1078,55 @@ export const useMemoryStore = create<MemoryState>()(
// A missing replacement must not reactivate an outdated fact.
stale: prop(e, 'stale') === true || supersededBy !== undefined,
validFrom: asNumber(prop(e, 'validFrom')),
- })
+ }
+ // The app's own export carries the record id, so the same file read
+ // twice meets its own entries again. A file without ids still meets
+ // them through content, type and scope.
+ const known = (originalId ? pool.find((p) => p.id === originalId) : undefined)
+ ?? pool.find((p) => isSameMemory(p, draft))
+ // A known record keeps its id and its birthday; only a genuinely new
+ // one gets a fresh id, which is why no import can collide with an
+ // existing entry's id (that once broke edit/remove-by-id).
+ const entry: MemoryFile = {
+ ...draft,
+ id: known?.id ?? uuid(),
+ createdAt: known?.createdAt ?? asNumber(prop(e, 'createdAt')) ?? now,
+ }
+ if (originalId) importedIds.set(originalId, importedIds.has(originalId) ? null : entry.id)
+ landed.push({ entry, links: { supersededBy, supersedesId: asString(prop(e, 'supersedesId')) }, known })
+ const at = known ? pool.indexOf(known) : -1
+ if (at >= 0) pool[at] = entry
+ else pool.push(entry)
}
- // References may only bind to unique IDs in this imported batch,
- // never to existing local entries or an ambiguous duplicate ID.
- newEntries.forEach((entry, index) => {
- const links = history[index]
+ // References may only bind to unique IDs of this file, never to an
+ // unrelated local entry or an ambiguous duplicate ID. An ID the file
+ // shares with a record already here names that record, because it is
+ // the same memory.
+ for (const { entry, links } of landed) {
entry.supersededBy = links.supersededBy ? importedIds.get(links.supersededBy) ?? undefined : undefined
entry.supersedesId = links.supersedesId ? importedIds.get(links.supersedesId) ?? undefined : undefined
- })
- if (newEntries.length > 0) {
+ }
+ const newEntries: MemoryFile[] = []
+ const updates = new Map<string, MemoryFile>()
+ let alreadyPresent = 0
+ for (const { entry, known } of landed) {
+ if (!known) newEntries.push(entry)
+ else if (importDigest(known) === importDigest(entry)) alreadyPresent++
+ else updates.set(entry.id, entry)
+ }
+ if (newEntries.length > 0 || updates.size > 0) {
set((state) => ({
- entries: [...state.entries, ...newEntries],
+ entries: [...state.entries.map((e) => updates.get(e.id) ?? e), ...newEntries],
lastSynced: now,
}))
}
- return newEntries.length
+ // A refreshed record keeps its id, so its stored vector still carries
+ // the old text until it is re-embedded.
+ for (const entry of updates.values()) {
+ if (entry.sensitive) void deleteVector(entry.id)
+ else void enqueueEmbedding(entry)
+ }
+ return { added: newEntries.length, updated: updates.size, alreadyPresent }
},
// ── Legacy Compat ───────────────────────────────────────