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.

Preserve memory history across JSON imports

David01f5e9040c8a
diff --git a/e2e/memory-import-history.spec.ts b/e2e/memory-import-history.spec.ts
new file mode 100644
index 00000000..f8f52fb3
--- /dev/null
+++ b/e2e/memory-import-history.spec.ts
@@ -0,0 +1,33 @@
+import { expect, test } from '@playwright/test'
+test('JSON export and reimport keep superseded facts out of AI context after reload', async ({ page }, testInfo) => {
+ await page.goto('/e2e/memory-sensitive-proof.html')
+ const seed = Buffer.from(JSON.stringify([
+ { id: 'old', title: 'Old memory', content: 'private outdated fact', supersededBy: 'new' },
+ { id: 'new', title: 'Current memory', content: 'private current fact', supersedesId: 'old' },
+ ]))
+ const input = page.locator('input[type=file]')
+ await input.setInputFiles({ name: 'seed.json', mimeType: 'application/json', buffer: seed })
+ await expect(page.getByText('Imported 2 memories.', { exact: true })).toBeVisible()
+ await expect(page.getByText('Show outdated (1)', { exact: true })).toBeVisible()
+ 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.getByRole('button', { name: 'Clear', exact: true }).click()
+ await page.getByRole('button', { name: 'Sure?', exact: true }).click()
+ await expect(page.getByText('Current memory', { exact: true })).toHaveCount(0)
+ await input.setInputFiles({ name: 'roundtrip.json', mimeType: 'application/json', buffer: exported })
+ await expect(page.getByText('Current memory', { exact: true })).toBeVisible()
+ await page.reload()
+ await expect(page.getByText('Show outdated (1)', { exact: true })).toBeVisible()
+ await page.getByRole('button', { name: 'Preview AI memory context' }).click()
+ await expect(page.locator('#result')).toContainText('private current fact')
+ await expect(page.locator('#result')).not.toContainText('private outdated fact')
+ await expect(page.getByText('Old memory', { exact: true })).toHaveCount(0)
+ await page.getByRole('button', { name: 'Toggle outdated memories' }).click()
+ await expect(page.getByText('Old memory', { exact: true })).toBeVisible()
+ await page.screenshot({ path: testInfo.outputPath('memory-import-history.png') })
+})
diff --git a/src/stores/__tests__/memory-import-history.test.ts b/src/stores/__tests__/memory-import-history.test.ts
new file mode 100644
index 00000000..9806a909
--- /dev/null
+++ b/src/stores/__tests__/memory-import-history.test.ts
@@ -0,0 +1,39 @@
+import { afterEach, beforeEach, expect, it } from 'vitest'
+import { useMemoryStore, __setMemoryEmbedFn } from '../memoryStore'
+beforeEach(() => { useMemoryStore.setState({ entries: [] }); __setMemoryEmbedFn(async () => []) })
+afterEach(() => __setMemoryEmbedFn())
+it('keeps outdated records excluded and remaps internal history after JSON round trip', async () => {
+ const store = useMemoryStore.getState()
+ store.importFromJSON(JSON.stringify([
+ { id: 'old', content: 'private old fact', supersededBy: 'new' },
+ { id: 'new', content: 'private current fact', supersedesId: 'old', validFrom: 1000 },
+ { id: 'stale', content: 'private stale fact', stale: true },
+ ]))
+ const exported = store.exportAsJSON()
+ store.clearAll()
+ store.importFromJSON(exported)
+ const [old, current, stale] = useMemoryStore.getState().entries
+ expect(old.supersededBy).toBe(current.id)
+ expect(current.supersedesId).toBe(old.id)
+ expect(current.validFrom).toBe(1000)
+ expect(stale.stale).toBe(true)
+ const selected = await store.getMemoryContextAsync('private', 8192)
+ expect(selected.memoryIds).toEqual([current.id])
+ expect(selected.text).not.toContain('old fact')
+ expect(selected.text).not.toContain('stale fact')
+})
+it('does not bind missing or ambiguous imported history IDs to existing records', () => {
+ const store = useMemoryStore.getState()
+ store.importFromJSON(JSON.stringify([{ id: 'target', content: 'existing' }]))
+ const existingId = useMemoryStore.getState().entries[0].id
+ store.importFromJSON(JSON.stringify([
+ { content: 'missing replacement', supersededBy: existingId },
+ { content: 'ambiguous replacement', supersededBy: 'duplicate' },
+ { id: 'duplicate', content: 'first' }, { id: 'duplicate', content: 'second' },
+ ]))
+ const imported = useMemoryStore.getState().entries.slice(1, 3)
+ for (const entry of imported) {
+ expect(entry.stale).toBe(true)
+ expect(entry.supersededBy).toBeUndefined()
+ }
+})
diff --git a/src/stores/memoryStore.ts b/src/stores/memoryStore.ts
index 24d25522..03b4281d 100644
--- a/src/stores/memoryStore.ts
+++ b/src/stores/memoryStore.ts
@@ -923,6 +923,8 @@ export const useMemoryStore = create<MemoryState>()(
: []
const now = Date.now()
const newEntries: MemoryFile[] = []
+ const importedIds = new Map<string, string | null>()
+ const history: Array<{ supersededBy?: string; supersedesId?: string }> = []
for (const e of arr) {
const scope = prop(e, 'scope')
if (scope !== undefined && (typeof scope !== 'string' || !scope.trim())) continue
@@ -934,10 +936,15 @@ 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: uuid(),
+ id,
type,
title: (asString(prop(e, 'title')) ?? content).slice(0, 60).replace(/\n/g, ' '),
description: (asString(prop(e, 'description')) ?? content).slice(0, 120),
@@ -950,8 +957,18 @@ export const useMemoryStore = create<MemoryState>()(
confirmedAt: typeof confirmedAt === 'number' && Number.isFinite(confirmedAt) && confirmedAt > 0 && confirmedAt <= now ? confirmedAt : undefined,
sensitive: prop(e, 'sensitive') === true,
scope: asString(scope),
+ // A missing replacement must not reactivate an outdated fact.
+ stale: prop(e, 'stale') === true || supersededBy !== undefined,
+ validFrom: asNumber(prop(e, 'validFrom')),
})
}
+ // 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]
+ entry.supersededBy = links.supersededBy ? importedIds.get(links.supersededBy) ?? undefined : undefined
+ entry.supersedesId = links.supersedesId ? importedIds.get(links.supersedesId) ?? undefined : undefined
+ })
if (newEntries.length > 0) {
set((state) => ({
entries: [...state.entries, ...newEntries],