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.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
Fence late automatic memory writes after local or account changes
David817018c96a15
diff --git a/e2e/memory-write-fence.spec.ts b/e2e/memory-write-fence.spec.tsnew file mode 100644index 00000000..e83f845f--- /dev/null+++ b/e2e/memory-write-fence.spec.ts@@ -0,0 +1,66 @@+import { expect, test } from '@playwright/test'+import { DEFAULT_MODEL_NAME } from './support/tauri-mock'++test('deleting through Memory Settings survives a late automatic extraction and reload', async ({ page }) => {+ await page.route('**/*', route => new URL(route.request().url()).port === '5273' ? route.continue() : route.abort())+ await page.goto('/e2e/memory-sensitive-proof.html')+ await page.evaluate(async (modelName) => {+ const memoryPath = '/src/stores/memoryStore.ts'+ const modelPath = '/src/stores/modelStore.ts'+ const settingsPath = '/src/stores/settingsStore.ts'+ const providersPath = '/src/api/providers/index.ts'+ const hookPath = '/src/hooks/useMemory.ts'+ const memory = await import(memoryPath) as typeof import('../src/stores/memoryStore')+ const model = await import(modelPath) as typeof import('../src/stores/modelStore')+ const settings = await import(settingsPath) as typeof import('../src/stores/settingsStore')+ const providers = await import(providersPath) as typeof import('../src/api/providers')+ const hook = await import(hookPath) as typeof import('../src/hooks/useMemory')+ await model.useModelStore.persist.rehydrate()+ await settings.useSettingsStore.persist.rehydrate()+ model.useModelStore.setState({ activeModel: modelName })+ settings.useSettingsStore.getState().updateSettings({ contextWindowOverride: 8192 })+ memory.useMemoryStore.getState().updateMemorySettings({ autoExtractEnabled: true, autoExtractInAllModes: true })+ memory.useMemoryStore.getState().addMemory({ title: 'Private original', content: 'Private original fact', description: '', type: 'user', tags: [], source: 'manual' })+ const { provider } = providers.getProviderForModel(modelName)+ const original = provider.chatStream+ const gate = new Promise<void>(resolve => { Reflect.set(window, 'releaseMemoryExtraction', resolve) })+ provider.chatStream = async function* () {+ document.body.dataset.extraction = 'waiting'+ await gate+ yield { content: JSON.stringify({ shouldSave: true, memories: [{ type: 'user', title: 'Private restored', content: 'Private original fact', description: '', tags: [] }] }), done: true }+ }+ const pending = (async () => {+ try {+ for (let i = 0; i < 3; i++) await hook.extractMemoriesFromPair('Remember this fact', 'Synthetic response. '.repeat(20), 'proof-conversation')+ } finally { provider.chatStream = original }+ })()+ Reflect.set(window, 'pendingMemoryExtraction', pending)+ }, DEFAULT_MODEL_NAME)+ await expect(page.locator('body')).toHaveAttribute('data-extraction', 'waiting')+ await page.getByRole('button', { name: 'Delete entry', exact: true }).click()+ await page.evaluate(async () => {+ const release: unknown = Reflect.get(window, 'releaseMemoryExtraction')+ if (typeof release !== 'function') throw new Error('Missing fixture release')+ release()+ await Reflect.get(window, 'pendingMemoryExtraction')+ })+ await expect(page.getByRole('button', { name: 'Delete entry', exact: true })).toHaveCount(0)+ // Ordinary Zustand persistence is asynchronous. Observe the committed+ // value before testing reload, rather than racing navigation against it.+ await expect.poll(() => page.evaluate(async () => {+ const path = '/src/lib/idbStorage.ts'+ const { idbStorage } = await import(path) as typeof import('../src/lib/idbStorage')+ const raw = await idbStorage.getItem('locally-uncensored-memory')+ if (!raw) return -1+ const parsed: unknown = JSON.parse(raw)+ if (typeof parsed !== 'object' || parsed === null) return -1+ const state: unknown = Reflect.get(parsed, 'state')+ if (typeof state !== 'object' || state === null) return -1+ const entries: unknown = Reflect.get(state, 'entries')+ return Array.isArray(entries) ? entries.length : -1+ })).toBe(0)+ await page.reload()+ await expect(page.getByRole('button', { name: 'Delete entry', exact: true })).toHaveCount(0)+ await page.getByRole('button', { name: 'Preview AI memory context' }).click()+ await expect(page.locator('#result')).toHaveText('No eligible memories')+})diff --git a/src/hooks/__tests__/memory-silent-call-gate.test.ts b/src/hooks/__tests__/memory-silent-call-gate.test.tsindex 2162043f..67a1f548 100644--- a/src/hooks/__tests__/memory-silent-call-gate.test.ts+++ b/src/hooks/__tests__/memory-silent-call-gate.test.ts@@ -18,6 +18,9 @@*/import { describe, it, expect, beforeEach, vi } from 'vitest'import type { MemoryFile } from '../../types/agent-mode'+import { useCloudAuthStore } from '../../stores/cloudAuthStore'+import { generateEmbeddings, cosineSimilarity } from '../../api/rag'+import { loadVectors } from '../../lib/memoryEmbedDB'// ── Mocked module graph ────────────────────────────────────────// Everything the extraction touches, kept dumb so the only interesting@@ -25,6 +28,7 @@ import type { MemoryFile } from '../../types/agent-mode'const chatStream = vi.fn()const addMemory = vi.fn(() => 'mem-1')+const applyWriteDecision = vi.fn()let activeModel = 'qwen3:8b'let models: Array<{ name: string; type: string }> = []@@ -43,7 +47,7 @@ vi.mock('../../stores/memoryStore', () => ({entries: memoryEntries,addMemory,removeMemory: vi.fn(),- applyWriteDecision: vi.fn(),+ applyWriteDecision,}),},}))@@ -112,6 +116,11 @@ beforeEach(() => {chatStream.mockReset()chatStream.mockImplementation(() => emptyStream())addMemory.mockClear()+ applyWriteDecision.mockClear()+ vi.mocked(generateEmbeddings).mockResolvedValue([[]])+ vi.mocked(cosineSimilarity).mockReturnValue(0)+ vi.mocked(loadVectors).mockResolvedValue(new Map())+ useCloudAuthStore.getState().setSignedOut()memoryEntries = []memorySettings = { autoExtractEnabled: true, autoExtractInAllModes: false }models = [@@ -121,6 +130,49 @@ beforeEach(() => {]})+describe('late extraction writes', () => {+ const extracted = JSON.stringify({ shouldSave: true, memories: [{ type: 'user', title: 'Fact', description: 'Fact', content: 'New fact', tags: [] }] })+ it('does not restore data after local memories change during extraction', async () => {+ activeModel = 'qwen3:8b'+ chatStream.mockImplementation(() => (async function* () {+ memoryEntries = []+ yield { content: extracted, done: true }+ })())+ await threeTurns()+ expect(chatStream).toHaveBeenCalledTimes(1)+ expect(addMemory).not.toHaveBeenCalled()+ })+ it('permanently revokes a pending write across sign-out and sign-in to the same account', async () => {+ activeModel = 'qwen3:8b'+ const account = { licenseActive: false, tier: null, access: true, quota: null }+ useCloudAuthStore.getState().setSignedIn({ id: 'owner-a' }, account)+ chatStream.mockImplementation(() => (async function* () {+ useCloudAuthStore.getState().setSignedOut()+ useCloudAuthStore.getState().setSignedIn({ id: 'owner-a' }, account)+ yield { content: extracted, done: true }+ })())+ await threeTurns()+ expect(addMemory).not.toHaveBeenCalled()+ })+ it('does not apply a late merge over a target edited while the resolver streamed', async () => {+ activeModel = 'qwen3:8b'+ memoryEntries = [{ id: 'target', type: 'user', title: 'Original', content: 'Original', description: '', tags: [], source: 'manual', createdAt: 1, updatedAt: 1 }]+ vi.mocked(generateEmbeddings).mockResolvedValue([[1]])+ vi.mocked(cosineSimilarity).mockReturnValue(0.75)+ vi.mocked(loadVectors).mockResolvedValue(new Map([['target', { dim: 1, vector: [1], model: 'fixture', contentHash: 'fixture' }]]))+ chatStream.mockImplementationOnce(() => (async function* () { yield { content: extracted, done: true } })())+ chatStream.mockImplementationOnce(() => (async function* () {+ memoryEntries = memoryEntries.map(entry => ({ ...entry, content: 'User correction' }))+ yield { content: JSON.stringify({ action: 'UPDATE', targetId: 'target', mergedContent: 'Late overwrite' }), done: true }+ })())+ await threeTurns()+ expect(chatStream).toHaveBeenCalledTimes(2)+ expect(addMemory).toHaveBeenCalledTimes(1)+ expect(applyWriteDecision).not.toHaveBeenCalled()+ expect(memoryEntries[0].content).toBe('User correction')+ })+})+describe('project extraction isolation', () => {it('preserves project and modality when the first write fails', async () => {activeModel = 'qwen3:8b'diff --git a/src/hooks/useMemory.ts b/src/hooks/useMemory.tsindex 71b443bb..363c913c 100644--- a/src/hooks/useMemory.ts+++ b/src/hooks/useMemory.ts@@ -24,6 +24,12 @@ import { generateEmbeddings, cosineSimilarity } from '../api/rag'import { loadVectors } from '../lib/memoryEmbedDB'import { silentCallAllowed, pickSilentCallModel } from '../lib/silent-model-calls'import type { MemoryFile } from '../types/agent-mode'+import { useCloudAuthStore } from '../stores/cloudAuthStore'++interface MemoryWriteGuard {+ current: () => boolean+ wrote: () => void+}// Rate limit: only extract every Nth turn to reduce costlet _extractCounter = 0@@ -87,6 +93,7 @@ export async function extractMemoriesFromPair(): Promise<void> {const scope = options?.scopeconst sourceKind = options?.sourceKind ?? 'chat'+ let unsubscribe: (() => void) | undefinedtry {const { activeModel } = useModelStore.getState()if (!activeModel) return@@ -113,6 +120,19 @@ export async function extractMemoriesFromPair(const call = resolveSilentCall(activeModel)if (!call) returnconst { provider, modelId, callModel } = call+ let expectedEntries = memState.entries+ let revoked = false+ unsubscribe = useCloudAuthStore.subscribe((state, previous) => {+ if (state.status !== previous.status || state.user?.id !== previous.user?.id) revoked = true+ })+ const guard: MemoryWriteGuard = {+ current: () => {+ const current = useMemoryStore.getState()+ if (current.entries !== expectedEntries || !current.settings.autoExtractEnabled) revoked = true+ return !revoked+ },+ wrote: () => { expectedEntries = useMemoryStore.getState().entries },+ }// Same num_ctx as the chat that just ran on this model. Ollama reloads the// model whenever num_ctx changes between requests, so an options-less@@ -126,6 +146,7 @@ export async function extractMemoriesFromPair(useSettingsStore.getState().settings.contextWindowOverride,callModel,)+ if (!guard.current()) return// Re-read immediately before the request; protected or other-project// titles must not leak through the extraction deduplication summary.@@ -142,6 +163,7 @@ export async function extractMemoriesFromPair(})for await (const chunk of stream) {+ if (!guard.current()) returnif (chunk.content) fullResponse += chunk.contentif (chunk.done) break}@@ -151,12 +173,14 @@ export async function extractMemoriesFromPair(const result = parseExtractionResponse(fullResponse)if (result.shouldSave) {for (const memory of result.memories) {+ if (!guard.current()) return// Serial per-memory so the second (resolution) LLM call is bounded and// we don't fire N concurrent inferences. Each is wrapped so one bad// memory never aborts the rest.try {- await resolveAndSaveMemory(memory, conversationId, scope, sourceKind)+ await resolveAndSaveMemory(memory, conversationId, scope, sourceKind, guard)} catch {+ if (!guard.current()) return// Per-memory failure → fall back to a plain add so the fact isn't lost.memState.addMemory({type: memory.type,@@ -168,11 +192,14 @@ export async function extractMemoriesFromPair(scope,sourceKind,})+ guard.wrote()}}}} catch {// Extraction failures are non-critical — silently swallowed+ } finally {+ unsubscribe?.()}}@@ -188,10 +215,11 @@ export async function extractMemoriesFromPair(* Fire-and-forget contract: any embedding/LLM failure falls back to a plain* addMemory so a fact is never silently dropped. Never blocks the chat turn.*/-async function resolveAndSaveMemory(memory: ExtractedMemory, conversationId: string, scope?: string, sourceKind?: MemoryFile['sourceKind']): Promise<void> {+async function resolveAndSaveMemory(memory: ExtractedMemory, conversationId: string, scope: string | undefined, sourceKind: MemoryFile['sourceKind'], guard: MemoryWriteGuard): Promise<void> {const memState = useMemoryStore.getState()- const addPlain = (): string =>- memState.addMemory({+ const addPlain = (): string => {+ if (!guard.current()) return ''+ const id = memState.addMemory({type: memory.type,title: memory.title,description: memory.description,@@ -201,6 +229,9 @@ async function resolveAndSaveMemory(memory: ExtractedMemory, conversationId: strsourceKind,scope,})+ guard.wrote()+ return id+ }// Same-type, non-stale existing memories are the only merge candidates —// a "user" fact never merges into a "reference", etc.@@ -220,6 +251,7 @@ async function resolveAndSaveMemory(memory: ExtractedMemory, conversationId: str} catch {// Ollama unreachable → can't compute similarity → just add (offline-safe).}+ if (!guard.current()) returnif (!newVec) {addPlain()return@@ -227,6 +259,7 @@ async function resolveAndSaveMemory(memory: ExtractedMemory, conversationId: str// Hydrate vectors for same-type candidates and find the most similar one.const vecMap = await loadVectors(sameType.map((e) => e.id))+ if (!guard.current()) returnlet bestSim = -1let bestEntry: MemoryFile | null = nullconst scored: Array<{ entry: MemoryFile; sim: number }> = []@@ -276,6 +309,7 @@ async function resolveAndSaveMemory(memory: ExtractedMemory, conversationId: strconst call = resolveSilentCall(activeModel)if (!call) returnconst { provider, modelId } = call+ if (!guard.current()) returnconst currentEntries = useMemoryStore.getState().entriesif (topK.some(candidate => !currentEntries.some(entry => entry.id === candidate.id && !entry.sensitive && entry.scope === scope && entry.content === candidate.content))) returnconst messages = buildResolutionPrompt(@@ -285,6 +319,7 @@ async function resolveAndSaveMemory(memory: ExtractedMemory, conversationId: strlet full = ''const stream = provider.chatStream(modelId, messages, { temperature: 0.1, maxTokens: 300 })for await (const chunk of stream) {+ if (!guard.current()) returnif (chunk.content) full += chunk.contentif (chunk.done) break}@@ -294,6 +329,8 @@ async function resolveAndSaveMemory(memory: ExtractedMemory, conversationId: strreturn}+ if (!guard.current()) return+if (decision.action === 'ADD') {// Already added as `newId` — nothing more to do.return@@ -301,10 +338,12 @@ async function resolveAndSaveMemory(memory: ExtractedMemory, conversationId: strif (decision.action === 'NOOP') {// Duplicate after all → undo the speculative add.if (newId) useMemoryStore.getState().removeMemory(newId)+ guard.wrote()return}// UPDATE: merge into the target, mark the speculative candidate superseded.useMemoryStore.getState().applyWriteDecision(decision, { newId: newId || undefined })+ guard.wrote()}/**