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
Resolve reviewed memory conflicts with revision-bound choices
David16447e8caea8
diff --git a/e2e/memory-sync.spec.ts b/e2e/memory-sync.spec.tsindex 75d51091..f8b7b3fa 100644--- a/e2e/memory-sync.spec.ts+++ b/e2e/memory-sync.spec.ts@@ -47,6 +47,11 @@ test('explicit UI sync uploads, downloads, preserves conflicts and persists sharawait page.getByRole('button', { name: 'Save', exact: true }).click()expect(writes).toBe(0)await page.getByLabel('Allow cloud storage for this account collection', { exact: true }).check()+ await page.getByLabel('Sensitive: exclude from AI requests', { exact: true }).check()+ await sync.click()+ await expect(page.getByRole('status')).toHaveText('Sensitive memories need explicit permission for cloud storage before this collection can synchronize')+ expect(writes).toBe(0)+ await page.getByLabel('Sensitive: exclude from AI requests', { exact: true }).uncheck()await sync.click()await expect(page.getByRole('status')).toHaveText('Synced 1 uploads and 0 downloads. 0 conflicting memories left unchanged.')expect(writes).toBe(1)@@ -65,10 +70,51 @@ test('explicit UI sync uploads, downloads, preserves conflicts and persists sharawait sync.click()await expect(page.getByRole('status')).toHaveText('Synced 0 uploads and 0 downloads. 1 conflicting memories left unchanged.')expect(writes).toBe(1)+ const conflict = page.getByRole('group', { name: 'Memory conflict 1', exact: true })+ await conflict.getByText('Compare full memory records', { exact: true }).click()+ await expect(conflict.locator('pre').first()).toContainText('Local correction')+ await expect(conflict.locator('pre').last()).toContainText('Concurrent cloud correction')+ const persistedReview = await page.evaluate(async () => {+ const path = '/src/lib/memory-persistence.ts'+ return (await import(path) as typeof import('../src/lib/memory-persistence')).flushMemoryPersist()+ })+ expect(persistedReview).not.toContain('Concurrent cloud correction')+ await conflict.screenshot({ path: testInfo.outputPath('memory-conflict.png') })+ // Another device changes the cloud record after review. The old choice+ // must not overwrite that new revision.+ records = records.map(record => ({ ...record, revision: 4, payload: { ...record.payload, content: 'Newer cloud correction', updatedAt: 4 } }))+ await page.getByRole('button', { name: 'Keep local version', exact: true }).click()+ await expect(page.getByRole('status')).toHaveText('This conflict changed. Sync again before choosing a version.')+ expect(writes).toBe(1)+ await sync.click()+ await expect(conflict).toBeVisible()+ await page.getByRole('button', { name: 'Use cloud version', exact: true }).click()+ await expect(page.getByRole('status')).toHaveText('Synced 0 uploads and 1 downloads. 0 conflicting memories left unchanged.')+ await expect(page.getByText('Newer cloud correction', { exact: true })).toBeVisible()+ await page.evaluate(async () => {+ const path = '/src/stores/memoryStore.ts'+ const { useMemoryStore } = await import(path) as typeof import('../src/stores/memoryStore')+ useMemoryStore.getState().updateMemory(useMemoryStore.getState().entries[0].id, { content: 'Final local correction' })+ })+ records = records.map(record => ({ ...record, revision: 5, payload: { ...record.payload, content: 'Another cloud correction', updatedAt: 5 } }))+ await sync.click()+ await expect(conflict).toBeVisible()+ await page.getByRole('button', { name: 'Keep local version', exact: true }).click()+ await expect(page.getByRole('status')).toHaveText('Synced 1 uploads and 0 downloads. 0 conflicting memories left unchanged.')+ expect(records[0]).toMatchObject({ revision: 6, payload: { content: 'Final local correction' } })+ await page.evaluate(async () => {+ const path = '/src/stores/memoryStore.ts'+ const { useMemoryStore } = await import(path) as typeof import('../src/stores/memoryStore')+ useMemoryStore.getState().updateMemory(useMemoryStore.getState().entries[0].id, { content: 'Delete this local fact' })+ })+ records = records.map(record => ({ ...record, revision: 7, payload: { ...record.payload, content: 'Delete this cloud fact', updatedAt: 7 } }))+ await sync.click()+ await expect(conflict).toBeVisible()await page.getByRole('button', { name: 'Delete entry', exact: true }).click()+ await expect(page.getByRole('group', { name: 'Memory conflict 1', exact: true })).toHaveCount(0)await sync.click()await expect(page.getByRole('status')).toHaveText('Synced 1 uploads and 0 downloads. 0 conflicting memories left unchanged.')- expect(records[0]).toMatchObject({ deleted: true, payload: null, revision: 4 })+ expect(records[0]).toMatchObject({ deleted: true, payload: null, revision: 8 })await page.reload()await accountFixture(page)await expect(page.getByRole('button', { name: 'Delete entry', exact: true })).toHaveCount(0)@@ -77,7 +123,7 @@ test('explicit UI sync uploads, downloads, preserves conflicts and persists sharconst { useMemoryStore } = await import(path) as typeof import('../src/stores/memoryStore')return Object.values(useMemoryStore.getState().memorySyncBaselines['owner-a'])})- expect(baseline).toEqual([{ revision: 4, hash: null }])+ expect(baseline).toEqual([{ revision: 8, hash: null }])})test('a lost first-upload response cannot revive a locally deleted memory after reload', async ({ page }) => {diff --git a/src/components/settings/MemorySettings.tsx b/src/components/settings/MemorySettings.tsxindex 4ef91cb2..3c4f0080 100644--- a/src/components/settings/MemorySettings.tsx+++ b/src/components/settings/MemorySettings.tsx@@ -12,7 +12,7 @@ import { formatContextWindow } from '../../lib/formatters'import { GlowButton } from '../ui/GlowButton'import type { MemoryType, MemoryFile } from '../../types/agent-mode'import { useCloudAuthStore } from '../../stores/cloudAuthStore'-import { synchronizeMemoryCollection } from '../../lib/memory-sync'+import { synchronizeMemoryCollection, type MemorySyncResolution } from '../../lib/memory-sync'// ── Subtle type indicator (internal, not user-facing) ─────────@@ -40,6 +40,7 @@ function MemorySettingsPanel() {const [sensitiveSyncConsent, setSensitiveSyncConsent] = useState(false)const [syncBusy, setSyncBusy] = useState(false)const [syncMessage, setSyncMessage] = useState('')+ const [syncConflicts, setSyncConflicts] = useState<Awaited<ReturnType<typeof synchronizeMemoryCollection>>['conflicts']>([])const owner = useCloudAuthStore(state => state.status === 'signed-in' ? state.user?.id : undefined)const activeOwner = useMemoryStore(state => state.activeMemoryOwner)const [collectionError, setCollectionError] = useState(false)@@ -65,6 +66,27 @@ function MemorySettingsPanel() {// imported — or why none were. The import used to fail silently.const [importMsg, setImportMsg] = useState<string | null>(null)const fileInputRef = useRef<HTMLInputElement>(null)+ useEffect(() => useMemoryStore.subscribe((state, previous) => {+ // Do not retain cloud previews after local editing or forgetting. A new+ // sync can fetch a fresh review; the durable metadata contains hashes only.+ if (state.entries !== previous.entries) setSyncConflicts([])+ }), [])+ const runSync = async (resolution?: MemorySyncResolution) => {+ if (activeOwner === null || !syncConsent || syncBusy) return+ setSyncBusy(true)+ setSyncConflicts([])+ setSyncMessage('Synchronizing memories...')+ try {+ const result = await synchronizeMemoryCollection(activeOwner, sensitiveSyncConsent, resolution)+ setSyncConflicts(result.conflicts)+ setSyncMessage(`Synced ${result.uploaded} uploads and ${result.downloaded} downloads. ${result.conflicts.length} conflicting memories left unchanged.`)+ } catch (error) {+ const messages = ['Sensitive memories need explicit permission for cloud storage before this collection can synchronize',+ 'This conflict changed. Sync again before choosing a version.']+ setSyncMessage(error instanceof Error && messages.includes(error.message) ? error.message+ : 'Could not complete memory synchronization. Check this account and try again. Some changes may already be saved.')+ } finally { setSyncBusy(false) }+ }// ── New memory form state ───────────────────────────────────const [newTitle, setNewTitle] = useState('')@@ -240,19 +262,24 @@ function MemorySettingsPanel() {<p>Marking a memory sensitive does not erase existing cloud copies. Delete the memory and sync to request its removal from cloud sync.</p><label className="block"><input type="checkbox" checked={syncConsent} disabled={syncBusy} onChange={event => setSyncConsent(event.target.checked)} /> Allow cloud storage for this account collection</label><label className="block"><input type="checkbox" checked={sensitiveSyncConsent} disabled={syncBusy} onChange={event => setSensitiveSyncConsent(event.target.checked)} /> Also allow cloud storage of sensitive memories</label>- <button className="underline disabled:opacity-50" disabled={!syncConsent || syncBusy} onClick={async () => {- setSyncBusy(true)- setSyncMessage('Synchronizing memories...')- try {- const result = await synchronizeMemoryCollection(activeOwner, sensitiveSyncConsent)- setSyncMessage(`Synced ${result.uploaded} uploads and ${result.downloaded} downloads. ${result.conflicts.length} conflicting memories left unchanged.`)- } catch (error) {- const sensitiveMessage = 'Sensitive memories need explicit permission for cloud storage before this collection can synchronize'- setSyncMessage(error instanceof Error && error.message === sensitiveMessage ? sensitiveMessage- : 'Could not complete memory synchronization. Check this account and try again. Some changes may already be saved.')- } finally { setSyncBusy(false) }- }}>Sync account memories</button>+ <button className="underline disabled:opacity-50" disabled={!syncConsent || syncBusy} onClick={() => void runSync()}>Sync account memories</button>{syncMessage && <p role="status">{syncMessage}</p>}+ {syncConflicts.map((conflict, index) => {+ const local = entries.find(entry => entry.id === conflict.id)+ const review = conflict.review+ return <div key={conflict.id} role="group" aria-label={`Memory conflict ${index + 1}`} className="space-y-2 border-t border-gray-200 pt-2 dark:border-white/10">+ <p>Conflicting memory: {local?.title ?? conflict.id}</p>+ {review ? <>+ <details><summary className="cursor-pointer">Compare full memory records</summary>+ <p>Local version</p><pre className="max-h-48 overflow-auto whitespace-pre-wrap break-words">{JSON.stringify(local, null, 2)}</pre>+ <p>Cloud version, revision {review.token.remoteRevision}</p><pre className="max-h-48 overflow-auto whitespace-pre-wrap break-words">{JSON.stringify(review.cloud, null, 2)}</pre>+ </details>+ <p>Choosing a version replaces the other version, including scope and privacy settings. Newer changes require another review.</p>+ <button className="mr-3 underline disabled:opacity-50" disabled={!syncConsent || syncBusy} onClick={() => void runSync({ ...review.token, choice: 'local' })}>Keep local version</button>+ <button className="underline disabled:opacity-50" disabled={!syncConsent || syncBusy} onClick={() => void runSync({ ...review.token, choice: 'cloud' })}>Use cloud version</button>+ </> : <p>The cloud record is missing or has an inconsistent deletion history. No version was overwritten. Sync again after checking the account.</p>}+ </div>+ })}</div>}</section>{/* Header */}diff --git a/src/lib/__tests__/memory-sync-coordinator.test.ts b/src/lib/__tests__/memory-sync-coordinator.test.tsindex c1724493..7f81c724 100644--- a/src/lib/__tests__/memory-sync-coordinator.test.ts+++ b/src/lib/__tests__/memory-sync-coordinator.test.ts@@ -5,7 +5,8 @@ import type { SyncedMemoryRecord } from '../../api/cloud/memory-sync'import type { MemoryFile } from '../../types/agent-mode'const fixture = vi.hoisted(() => ({ pull: vi.fn(), write: vi.fn(), flush: vi.fn() }))-vi.mock('../../api/cloud/memory-sync', () => ({ withMemorySyncSession: async (_owner: string, work: (session: unknown) => Promise<unknown>) =>+vi.mock('../../api/cloud/memory-sync', async importOriginal => ({ ...await importOriginal<typeof import('../../api/cloud/memory-sync')>(),+ withMemorySyncSession: async (_owner: string, work: (session: unknown) => Promise<unknown>) =>work({ assertCurrent: () => {}, pull: fixture.pull, write: fixture.write }) }))vi.mock('../memory-persistence', async importOriginal => ({...await importOriginal<typeof import('../memory-persistence')>(), flushMemoryPersist: (guard: () => boolean) => fixture.flush(guard),@@ -93,3 +94,46 @@ it('rejects applying a downloaded record after a collection change', async () =>expect(useMemoryStore.getState().entries).toEqual([])expect(fixture.write).not.toHaveBeenCalled()})++async function reviewConflict() {+ useMemoryStore.setState({ entries: [memory] })+ await synchronizeMemoryCollection('A')+ useMemoryStore.getState().updateMemory('one', { content: 'Local revised' })+ remote = [{ ...remote[0], revision: 2, payload: { ...memory, content: 'Cloud revised', updatedAt: 2 } }]+ const result = await synchronizeMemoryCollection('A')+ expect(result.conflicts).toHaveLength(1)+ expect(JSON.stringify(useMemoryStore.getState())).not.toContain('Cloud revised')+ return result.conflicts[0].review!.token+}++it('applies the reviewed cloud version locally without overwriting the server', async () => {+ const token = await reviewConflict()+ const result = await synchronizeMemoryCollection('A', false, { ...token, choice: 'cloud' })+ expect(result.conflicts).toEqual([])+ expect(useMemoryStore.getState().entries[0].content).toBe('Cloud revised')+ expect(fixture.write).toHaveBeenCalledTimes(1)+ expect(useMemoryStore.getState().memorySyncBaselines.A.one.revision).toBe(2)+})+it('keeps the reviewed local version with a revision-checked server mutation', async () => {+ const token = await reviewConflict()+ await synchronizeMemoryCollection('A', false, { ...token, choice: 'local' })+ expect(remote[0]).toMatchObject({ revision: 3, payload: { content: 'Local revised' } })+ expect(useMemoryStore.getState().memorySyncPending.A).toEqual({})+})+it('refuses a reviewed choice after the remote or local version changed', async () => {+ const token = await reviewConflict()+ remote = [{ ...remote[0], revision: 3, payload: { ...memory, content: 'New cloud edit' } }]+ await expect(synchronizeMemoryCollection('A', false, { ...token, choice: 'local' })).rejects.toThrow('This conflict changed')+ const fresh = (await synchronizeMemoryCollection('A')).conflicts[0].review!.token+ useMemoryStore.getState().updateMemory('one', { content: 'New local edit' })+ await expect(synchronizeMemoryCollection('A', false, { ...fresh, choice: 'cloud' })).rejects.toThrow('This conflict changed')+ expect(fixture.write).toHaveBeenCalledTimes(1)+ expect(useMemoryStore.getState().entries[0].content).toBe('New local edit')+})+it('invalidates the review after leaving and reopening the same collection', async () => {+ const token = await reviewConflict()+ useMemoryStore.getState().selectMemoryCollection(null)+ useMemoryStore.getState().selectMemoryCollection('A')+ await expect(synchronizeMemoryCollection('A', false, { ...token, choice: 'cloud' })).rejects.toThrow('This conflict changed')+ expect(fixture.write).toHaveBeenCalledTimes(1)+})diff --git a/src/lib/memory-sync.ts b/src/lib/memory-sync.tsindex f2ba5597..ed747227 100644--- a/src/lib/memory-sync.ts+++ b/src/lib/memory-sync.ts@@ -1,12 +1,22 @@import { useMemoryStore } from '../stores/memoryStore'import { useCloudAuthStore } from '../stores/cloudAuthStore'-import { withMemorySyncSession } from '../api/cloud/memory-sync'+import { withMemorySyncSession, MemorySyncError } from '../api/cloud/memory-sync'import { flushMemoryPersist } from './memory-persistence'import { planMemorySync, syncMemoryHash, decodeSyncMemory, type MemorySyncBaseline } from './memory-sync-plan'import { isRecord } from '../types/json-guards'let running = false-const changed = () => new Error('Memory synchronization stopped because the collection changed')+const changed = () => new MemorySyncError('account', 'Memory synchronization stopped because the collection changed')+const conflictChanged = () => new MemorySyncError('conflict', 'This conflict changed. Sync again before choosing a version.')+export interface MemorySyncResolution {+ owner: string+ collectionRevision: number+ id: string+ remoteRevision: number+ remoteHash: string+ localHash: string+ choice: 'local' | 'cloud'+}function ownerMetadata(all: unknown, owner: string, minimumRevision: number): Record<string, MemorySyncBaseline> {const invalid = () => new Error('Invalid stored memory synchronization data')@@ -27,13 +37,15 @@ function ownerMetadata(all: unknown, owner: string, minimumRevision: number): Re* Write intents contain hashes, not private payload copies. They are durable* before upload, so a crash or local deletion cannot turn an uncertain first* upload into an untracked remote record that gets downloaded again. */-export async function synchronizeMemoryCollection(owner: string, allowSensitive = false) {+export async function synchronizeMemoryCollection(owner: string, allowSensitive = false, resolution?: MemorySyncResolution) {if (running) throw new Error('Memory synchronization is already running')const initial = useMemoryStore.getState()let expectedEntries = initial.entrieslet expectedBaselines = initial.memorySyncBaselineslet expectedPending = initial.memorySyncPendingconst revision = initial.memoryCollectionRevision+ const choice = resolution ? { ...resolution } : undefined+ if (choice && (choice.owner !== owner || choice.collectionRevision !== revision || !['local', 'cloud'].includes(choice.choice))) throw conflictChanged()const check = () => {const state = useMemoryStore.getState()const auth = useCloudAuthStore.getState()@@ -85,9 +97,23 @@ export async function synchronizeMemoryCollection(owner: string, allowSensitivefor (const id of forcedDeletes.keys()) delete planningBase[id]const plan = await planMemorySync(expectedEntries.filter(entry => !forcedDeletes.has(entry.id)), planningBase, remote.filter(row => !forcedDeletes.has(row.memory_id)))guard()+ if (choice) {+ const conflict = plan.conflicts.find(item => item.id === choice.id && item.reason === 'both-edited')+ const local = expectedEntries.find(entry => entry.id === choice.id)+ const row = remoteById.get(choice.id)+ if (!conflict || !local || !row || row.deleted || row.revision !== choice.remoteRevision) throw conflictChanged()+ const cloud = decodeSyncMemory(row.payload)+ const cloudHash = await syncMemoryHash(cloud)+ const localHash = await syncMemoryHash(local)+ guard()+ if (cloudHash !== choice.remoteHash || localHash !== choice.localHash) throw conflictChanged()+ if (choice.choice === 'local') plan.push.push({ id: local.id, expectedRevision: row.revision, payload: decodeSyncMemory(local) })+ else plan.pull.push({ memory: cloud, baseline: { revision: row.revision, hash: cloudHash } })+ plan.conflicts = plan.conflicts.filter(item => item.id !== choice.id)+ }for (const [id, expectedRevision] of forcedDeletes) plan.push.push({ id, expectedRevision, payload: null })if (!allowSensitive && plan.push.some(write => write.payload?.sensitive)) {- throw new Error('Sensitive memories need explicit permission for cloud storage before this collection can synchronize')+ throw new MemorySyncError('invalid', 'Sensitive memories need explicit permission for cloud storage before this collection can synchronize')}const incoming = new Map(plan.pull.map(item => [item.memory.id, item.memory]))const removed = new Set([...plan.remove.map(item => item.id), ...forcedDeletes.keys()])@@ -113,7 +139,22 @@ export async function synchronizeMemoryCollection(owner: string, allowSensitiveawait commit(expectedEntries, { ...baselines }, { ...pending })uploaded++}- return { downloaded: plan.pull.length, uploaded, removed: plan.remove.length, conflicts: plan.conflicts }+ const conflicts = await Promise.all(plan.conflicts.map(async item => {+ const local = expectedEntries.find(entry => entry.id === item.id)+ const row = remoteById.get(item.id)+ if (item.reason !== 'both-edited' || !local || !row || row.deleted) return { ...item, review: null }+ const cloud = decodeSyncMemory(row.payload)+ const localHash = await syncMemoryHash(local)+ const remoteHash = await syncMemoryHash(cloud)+ return { ...item, review: {+ token: { owner, collectionRevision: revision, id: item.id, remoteRevision: row.revision, remoteHash, localHash },+ // Ephemeral UI preview only. Never persist cloud content in baseline+ // or pending-intent metadata; collection switches discard the panel.+ cloud,+ } }+ }))+ guard()+ return { downloaded: plan.pull.length, uploaded, removed: plan.remove.length, conflicts }})} finally { running = false }}