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.

Separate local and signed-in account memory collections

David5e2e95f4ab35
diff --git a/e2e/memory-collections.spec.ts b/e2e/memory-collections.spec.ts
new file mode 100644
index 00000000..7f6dc73c
--- /dev/null
+++ b/e2e/memory-collections.spec.ts
@@ -0,0 +1,55 @@
+import { expect, test, type Page } from '@playwright/test'
+
+async function signIn(page: Page, id: string) {
+ await page.evaluate(async owner => {
+ const path = '/src/stores/cloudAuthStore.ts'
+ const { useCloudAuthStore } = await import(path) as typeof import('../src/stores/cloudAuthStore')
+ useCloudAuthStore.getState().setSignedIn({ id: owner }, { licenseActive: false, tier: null, access: true, quota: null })
+ }, id)
+}
+async function add(page: Page, title: string) {
+ await page.getByRole('button', { name: 'Add Memory', exact: true }).click()
+ await page.getByPlaceholder('What should I remember?').fill(title)
+ await page.getByPlaceholder('Details… (required)').fill(`Private ${title}`)
+ await page.getByRole('button', { name: 'Save', exact: true }).click()
+}
+test('actual collection controls isolate two owners and retain local data through reload', async ({ page }, testInfo) => {
+ await page.goto('/e2e/memory-sensitive-proof.html')
+ await add(page, 'Local original')
+ await signIn(page, 'owner-a')
+ await page.getByRole('button', { name: 'Use account memories', exact: true }).click()
+ await expect(page.getByText('Local original', { exact: true })).toHaveCount(0)
+ await add(page, 'Owner A original')
+ await signIn(page, 'owner-b')
+ await expect(page.getByText('Local original', { exact: true })).toBeVisible()
+ await page.getByRole('button', { name: 'Use account memories', exact: true }).click()
+ await expect(page.getByText('Owner A original', { exact: true })).toHaveCount(0)
+ await add(page, 'Owner B original')
+ await signIn(page, 'owner-a')
+ await page.getByRole('button', { name: 'Use account memories', exact: true }).click()
+ await expect(page.getByText('Owner A original', { exact: true })).toBeVisible()
+ await expect(page.getByText('Owner B original', { exact: true })).toHaveCount(0)
+ await page.getByRole('button', { name: 'Preview AI memory context' }).click()
+ await expect(page.locator('#result')).toContainText('Owner A original')
+ await expect(page.locator('#result')).not.toContainText('Owner B original')
+ await page.getByRole('button', { name: 'Use local memories', exact: true }).click()
+ await expect(page.getByText('Local original', { exact: true })).toBeVisible()
+ 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')
+ return raw?.includes('Owner A original') && raw.includes('Owner B original') && raw.includes('Local original')
+ })).toBe(true)
+ await page.reload()
+ await expect(page.getByText('Local original', { exact: true })).toBeVisible()
+ await expect(page.getByText('Owner A original', { exact: true })).toHaveCount(0)
+ await signIn(page, 'owner-a')
+ await page.getByRole('button', { name: 'Use account memories', exact: true }).click()
+ await expect(page.getByText('Owner A original', { exact: true })).toBeVisible()
+ await signIn(page, 'owner-b')
+ await page.getByRole('button', { name: 'Use account memories', exact: true }).click()
+ await expect(page.getByText('Owner B original', { exact: true })).toBeVisible()
+ await expect(page.getByText('Owner A original', { exact: true })).toHaveCount(0)
+ await page.setViewportSize({ width: 390, height: 844 })
+ await page.screenshot({ path: testInfo.outputPath('memory-collections.png'), fullPage: true })
+})
diff --git a/src/components/settings/MemorySettings.tsx b/src/components/settings/MemorySettings.tsx
index a30f7fca..4109539e 100644
--- a/src/components/settings/MemorySettings.tsx
+++ b/src/components/settings/MemorySettings.tsx
@@ -11,6 +11,7 @@ import { getModelMaxTokens } from '../../lib/context-compaction'
import { formatContextWindow } from '../../lib/formatters'
import { GlowButton } from '../ui/GlowButton'
import type { MemoryType, MemoryFile } from '../../types/agent-mode'
+import { useCloudAuthStore } from '../../stores/cloudAuthStore'
// ── Subtle type indicator (internal, not user-facing) ─────────
@@ -29,6 +30,14 @@ const TYPE_DOT_COLORS: Record<MemoryType, string> = {
// ── Component ─────────────────────────────────────────────────
export function MemorySettings() {
+ const revision = useMemoryStore(state => state.memoryCollectionRevision)
+ return <MemorySettingsPanel key={revision} />
+}
+
+function MemorySettingsPanel() {
+ const owner = useCloudAuthStore(state => state.status === 'signed-in' ? state.user?.id : undefined)
+ const activeOwner = useMemoryStore(state => state.activeMemoryOwner)
+ const [collectionError, setCollectionError] = useState(false)
const remoteMemoryNotice = useRemoteStore(s => s.memoryNotice)
const conversation = useChatStore(s => s.conversations.find(c => c.id === s.activeConversationId))
const [savedProject, setSavedProject] = useState<string | null>(null)
@@ -130,7 +139,9 @@ export function MemorySettings() {
e.target.value = '' // allow re-picking the same file
if (!file) return
const reader = new FileReader()
+ const collectionRevision = useMemoryStore.getState().memoryCollectionRevision
reader.onload = (ev) => {
+ if (useMemoryStore.getState().memoryCollectionRevision !== collectionRevision) return
const content = ev.target?.result as string
if (!content) { setImportMsg('Could not read that file.'); return }
const trimmed = content.trimStart()
@@ -213,6 +224,13 @@ export function MemorySettings() {
return (
<div className="space-y-3">
+ <section aria-label="Memory collection" className="space-y-2 rounded-lg border border-gray-200 p-3 text-xs text-gray-700 dark:border-white/10 dark:text-gray-300">
+ <p>Memory collection: {activeOwner === null ? 'Local' : 'Signed-in account'}</p>
+ <p>Local memories stay separate. Account collections are stored on this device. Cloud synchronization is not enabled yet.</p>
+ <button className="mr-3 underline" disabled={activeOwner === null} onClick={() => setCollectionError(!useMemoryStore.getState().selectMemoryCollection(null))}>Use local memories</button>
+ {owner && <button className="underline" disabled={activeOwner === owner} onClick={() => setCollectionError(!useMemoryStore.getState().selectMemoryCollection(owner))}>Use account memories</button>}
+ {collectionError && <p role="alert">Could not open this memory collection. Existing data has not been replaced.</p>}
+ </section>
{/* Header */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
diff --git a/src/hooks/useMemory.ts b/src/hooks/useMemory.ts
index 363c913c..db3a69b7 100644
--- a/src/hooks/useMemory.ts
+++ b/src/hooks/useMemory.ts
@@ -121,6 +121,7 @@ export async function extractMemoriesFromPair(
if (!call) return
const { provider, modelId, callModel } = call
let expectedEntries = memState.entries
+ const collectionRevision = memState.memoryCollectionRevision
let revoked = false
unsubscribe = useCloudAuthStore.subscribe((state, previous) => {
if (state.status !== previous.status || state.user?.id !== previous.user?.id) revoked = true
@@ -128,7 +129,7 @@ export async function extractMemoriesFromPair(
const guard: MemoryWriteGuard = {
current: () => {
const current = useMemoryStore.getState()
- if (current.entries !== expectedEntries || !current.settings.autoExtractEnabled) revoked = true
+ if (current.entries !== expectedEntries || current.memoryCollectionRevision !== collectionRevision || !current.settings.autoExtractEnabled) revoked = true
return !revoked
},
wrote: () => { expectedEntries = useMemoryStore.getState().entries },
diff --git a/src/stores/__tests__/memory-collections.test.ts b/src/stores/__tests__/memory-collections.test.ts
new file mode 100644
index 00000000..f4301b5a
--- /dev/null
+++ b/src/stores/__tests__/memory-collections.test.ts
@@ -0,0 +1,78 @@
+import { afterEach, beforeEach, expect, it } from 'vitest'
+import { useMemoryStore, __setMemoryEmbedFn } from '../memoryStore'
+import { useCloudAuthStore } from '../cloudAuthStore'
+
+const account = { licenseActive: false, tier: null, access: true, quota: null }
+const signIn = (id: string) => useCloudAuthStore.getState().setSignedIn({ id }, account)
+const add = (content: string) => useMemoryStore.getState().addMemory({ type: 'user', title: content, content, description: '', tags: [], source: 'manual' })
+beforeEach(() => {
+ useCloudAuthStore.getState().setSignedOut()
+ useMemoryStore.setState({ entries: [], localEntries: [], accountCollections: {}, activeMemoryOwner: null, memoryCollectionRevision: 0 })
+ __setMemoryEmbedFn(async () => [])
+})
+afterEach(() => { useCloudAuthStore.getState().setSignedOut(); __setMemoryEmbedFn() })
+
+it('requires the matching signed-in owner and preserves local data', () => {
+ add('Local fact')
+ expect(useMemoryStore.getState().selectMemoryCollection('A')).toBe(false)
+ signIn('A')
+ expect(useMemoryStore.getState().selectMemoryCollection('B')).toBe(false)
+ expect(useMemoryStore.getState().selectMemoryCollection('A')).toBe(true)
+ expect(useMemoryStore.getState().entries).toEqual([])
+ add('Account A fact')
+ useCloudAuthStore.getState().setSignedOut()
+ expect(useMemoryStore.getState().entries.map(e => e.content)).toEqual(['Local fact'])
+ expect(useMemoryStore.getState().activeMemoryOwner).toBeNull()
+})
+it('isolates edits, deletion and exports across two account collections', () => {
+ signIn('A')
+ useMemoryStore.getState().selectMemoryCollection('A')
+ add('Account A fact')
+ signIn('B')
+ useMemoryStore.getState().selectMemoryCollection('B')
+ add('Account B fact')
+ expect(useMemoryStore.getState().exportAsJSON()).not.toContain('Account A fact')
+ useMemoryStore.getState().clearAll()
+ signIn('A')
+ useMemoryStore.getState().selectMemoryCollection('A')
+ expect(useMemoryStore.getState().entries.map(e => e.content)).toEqual(['Account A fact'])
+})
+it('preserves unreadable account data and refuses selection', () => {
+ signIn('A')
+ const malformed = [{ invalid: 'preserve this' }]
+ useMemoryStore.setState({ accountCollections: { A: malformed } } as unknown as Partial<ReturnType<typeof useMemoryStore.getState>>)
+ expect(useMemoryStore.getState().selectMemoryCollection('A')).toBe(false)
+ expect(useMemoryStore.getState().accountCollections.A).toBe(malformed)
+})
+it('never treats the active account as local data when a hydration read is absent', () => {
+ add('Local original')
+ signIn('A')
+ useMemoryStore.getState().selectMemoryCollection('A')
+ add('Account original')
+ const merge = useMemoryStore.persist.getOptions().merge!
+ const restored = merge(undefined, useMemoryStore.getState())
+ expect(restored.activeMemoryOwner).toBeNull()
+ expect(restored.entries.map(entry => entry.content)).toEqual(['Local original'])
+ expect(restored.accountCollections.A.map(entry => entry.content)).toEqual(['Account original'])
+})
+it('keeps valid oversized local account records accessible without loosening cloud validation', () => {
+ signIn('A')
+ useMemoryStore.getState().selectMemoryCollection('A')
+ const content = 'x'.repeat(20000)
+ add(content)
+ useMemoryStore.getState().selectMemoryCollection(null)
+ expect(useMemoryStore.getState().selectMemoryCollection('A')).toBe(true)
+ expect(useMemoryStore.getState().entries[0].content).toBe(content)
+})
+it('does not substitute another collection after asynchronous retrieval, including A-local-A', async () => {
+ signIn('A')
+ useMemoryStore.getState().selectMemoryCollection('A')
+ add('Private account fact')
+ let release!: (value: number[][]) => void
+ __setMemoryEmbedFn(() => new Promise(resolve => { release = resolve }))
+ const pending = useMemoryStore.getState().getMemoryContextAsync('private', 8192)
+ useMemoryStore.getState().selectMemoryCollection(null)
+ useMemoryStore.getState().selectMemoryCollection('A')
+ release([])
+ expect(await pending).toEqual({ text: '', memoryIds: [] })
+})
diff --git a/src/stores/memoryStore.ts b/src/stores/memoryStore.ts
index 03b4281d..55f83935 100644
--- a/src/stores/memoryStore.ts
+++ b/src/stores/memoryStore.ts
@@ -10,6 +10,7 @@ import { scoreMemoriesBlended, isStale, type BlendCandidate } from '../lib/memor
import type { ResolutionDecision } from '../lib/memory-extraction'
import { isRecord, prop, asString, asNumber, asStringArray } from '../types/json-guards'
import { log } from '../lib/logger'
+import { useCloudAuthStore } from './cloudAuthStore'
// ── Embedding model + dim (mirrors rag.ts default) ────────────────
const MEMORY_EMBED_MODEL = 'nomic-embed-text'
@@ -76,12 +77,14 @@ function hashContent(s: string): string {
* Skips when the existing stored vector already matches the content hash.
*/
async function enqueueEmbedding(entry: Pick<MemoryFile, 'id' | 'title' | 'content'>): Promise<void> {
+ const collectionRevision = useMemoryStore.getState().memoryCollectionRevision
try {
const text = embedText(entry)
const contentHash = hashContent(text)
const isCurrent = () => {
const current = useMemoryStore.getState().entries.find((item) => item.id === entry.id)
- return !!current && !current.sensitive && !isStale(current) && embedText(current) === text
+ return useMemoryStore.getState().memoryCollectionRevision === collectionRevision &&
+ !!current && !current.sensitive && !isStale(current) && embedText(current) === text
}
const existing = await loadVectors([entry.id])
if (!isCurrent()) return
@@ -270,6 +273,11 @@ function renderRememberedContext(ordered: MemoryFile[], budgetTokens: number, on
interface MemoryState {
entries: MemoryFile[]
+ localEntries: MemoryFile[]
+ accountCollections: Record<string, MemoryFile[]>
+ activeMemoryOwner: string | null
+ memoryCollectionRevision: number
+ selectMemoryCollection: (owner: string | null) => boolean
settings: MemorySettings
lastSynced: number
@@ -428,6 +436,25 @@ function asMemoryFile(v: unknown): MemoryFile | null {
const MEMORY_TYPES: readonly MemoryType[] = ['user', 'feedback', 'project', 'reference']
+/** Local account collections retain valid local records, including records
+ * larger than the cloud protocol permits. Upload validation is separate. */
+function readAccountMemory(raw: unknown): MemoryFile {
+ const invalid = () => new Error('Could not open this memory collection')
+ if (!isRecord(raw) || !['id', 'title', 'description', 'content', 'source'].every(key => typeof raw[key] === 'string') ||
+ !raw.id || !(raw.content as string).trim() || !MEMORY_TYPES.some(type => type === raw.type) ||
+ !Array.isArray(raw.tags) || !raw.tags.every(tag => typeof tag === 'string') ||
+ !['createdAt', 'updatedAt'].every(key => typeof raw[key] === 'number' && Number.isFinite(raw[key]))) throw invalid()
+ for (const key of ['sensitive', 'stale']) if (raw[key] !== undefined && typeof raw[key] !== 'boolean') throw invalid()
+ for (const key of ['scope', 'supersededBy', 'supersedesId']) {
+ if (raw[key] !== undefined && (typeof raw[key] !== 'string' || !raw[key].trim())) throw invalid()
+ }
+ for (const key of ['confirmedAt', 'validFrom']) {
+ if (raw[key] !== undefined && (typeof raw[key] !== 'number' || !Number.isFinite(raw[key]))) throw invalid()
+ }
+ if (raw.sourceKind !== undefined && !['chat', 'voice', 'screen'].some(kind => kind === raw.sourceKind)) throw invalid()
+ return { ...raw, tags: [...raw.tags] } as unknown as MemoryFile
+}
+
/**
* The persist `migrate` hook. Exported so a test can drive it directly — the
* persist internals are not reachable from vitest (same reason
@@ -502,6 +529,32 @@ export const useMemoryStore = create<MemoryState>()(
persist(
(set, get) => ({
entries: [],
+ localEntries: [],
+ accountCollections: {},
+ activeMemoryOwner: null,
+ memoryCollectionRevision: 0,
+ selectMemoryCollection: (owner) => {
+ if (!useMemoryStore.persist.hasHydrated()) return false
+ const state = get()
+ const auth = useCloudAuthStore.getState()
+ if (owner !== null && (auth.status !== 'signed-in' || auth.user?.id !== owner)) return false
+ if (owner === state.activeMemoryOwner) return true
+ const collections = { ...state.accountCollections }
+ if (state.activeMemoryOwner !== null) collections[state.activeMemoryOwner] = state.entries
+ const local = state.activeMemoryOwner === null ? state.entries : state.localEntries
+ let entries = local
+ if (owner !== null) {
+ const stored: unknown = Object.hasOwn(collections, owner) ? collections[owner] : []
+ // Preserve unreadable collections unchanged rather than hydrating
+ // them as empty and later overwriting their data.
+ if (!Array.isArray(stored)) return false
+ try { entries = stored.map(readAccountMemory) } catch { return false }
+ if (new Set(entries.map(entry => entry.id)).size !== entries.length) return false
+ }
+ set({ entries, localEntries: local, accountCollections: collections,
+ activeMemoryOwner: owner, memoryCollectionRevision: state.memoryCollectionRevision + 1 })
+ return true
+ },
settings: {
autoExtractEnabled: true,
autoExtractInAllModes: true,
@@ -643,16 +696,19 @@ export const useMemoryStore = create<MemoryState>()(
// back to the keyword result. Offline correctness invariant: this never
// returns empty/incorrect when the sync path would have returned text.
getMemoryContextAsync: async (query, contextTokens, opts) => {
+ const collectionRevision = get().memoryCollectionRevision
let memoryIds: string[] = []
const text = await get().getMemoriesForPromptAsync(query, contextTokens, {
...opts, onInjected: ids => { memoryIds = [...ids] },
})
- return { text, memoryIds }
+ return get().memoryCollectionRevision === collectionRevision ? { text, memoryIds } : { text: '', memoryIds: [] }
},
getMemoriesForPromptAsync: async (query, contextTokens, opts) => {
const requestOpts = opts ? { ...opts } : undefined
- const fallback = () => get().getMemoriesForPrompt(query, contextTokens, requestOpts)
+ const collectionRevision = get().memoryCollectionRevision
+ const fallback = () => get().memoryCollectionRevision === collectionRevision
+ ? get().getMemoriesForPrompt(query, contextTokens, requestOpts) : ''
const snapshot = get().entries
try {
const budget = effectiveMemoryBudget(contextTokens, get().settings.maxMemoriesOverride)
@@ -1014,11 +1070,34 @@ export const useMemoryStore = create<MemoryState>()(
// (zustand v5 PersistStorage; raw StateStorage → "[object Object]", FIX-3).
storage: createJSONStorage(() => idbStorage),
migrate: migrateMemoryState,
+ merge: (persisted, current) => {
+ const saved = isRecord(persisted) ? persisted : {}
+ const local = current.activeMemoryOwner === null ? current.entries : current.localEntries
+ const collections = current.activeMemoryOwner === null ? current.accountCollections
+ : { ...current.accountCollections, [current.activeMemoryOwner]: current.entries }
+ return { ...current, ...saved,
+ // Never expose an account collection during session restoration.
+ // Selection is explicit and checked against the signed-in owner.
+ entries: Array.isArray(saved.entries) ? saved.entries : local,
+ localEntries: Array.isArray(saved.entries) ? saved.entries : local,
+ accountCollections: isRecord(saved.accountCollections) ? saved.accountCollections : collections,
+ activeMemoryOwner: null,
+ memoryCollectionRevision: current.memoryCollectionRevision + 1,
+ } as MemoryState
+ },
partialize: (state) => ({
- entries: state.entries,
+ entries: state.activeMemoryOwner === null ? state.entries : state.localEntries,
+ accountCollections: state.activeMemoryOwner === null ? state.accountCollections
+ : { ...state.accountCollections, [state.activeMemoryOwner]: state.entries },
settings: state.settings,
lastSynced: state.lastSynced,
}),
}
)
)
+
+useCloudAuthStore.subscribe((state, previous) => {
+ if (state.status !== previous.status || state.user?.id !== previous.user?.id) {
+ useMemoryStore.getState().selectMemoryCollection(null)
+ }
+})