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.

Add foreground memory synchronization cancellation

David04ec37aad7f9
diff --git a/e2e/memory-sync.spec.ts b/e2e/memory-sync.spec.ts
index f8b7b3fa..43675ff5 100644
--- a/e2e/memory-sync.spec.ts
+++ b/e2e/memory-sync.spec.ts
@@ -17,6 +17,55 @@ async function accountFixture(page: Page) {
await page.getByRole('button', { name: 'Use account memories', exact: true }).click()
}
+test('foreground cancellation stops a held pull and leaving the collection cancels the next run', async ({ page }) => {
+ let finish: (() => Promise<void>) | undefined
+ let hold = true
+ let reads = 0
+ await page.route('**/*', route => new URL(route.request().url()).port === '5273' ? route.continue() : route.abort())
+ await page.route('**/api/memory/sync**', async route => {
+ expect(route.request().method()).toBe('GET')
+ reads++
+ const respond = () => route.fulfill({ json: { ownerId: 'owner-a', records: [], next: null } })
+ if (hold) {
+ await new Promise<void>(resolve => { finish = async () => { await respond().catch(() => {}); resolve() } })
+ } else await respond()
+ })
+ await page.goto('/e2e/memory-sensitive-proof.html')
+ await page.evaluate(() => {
+ const original = window.fetch.bind(window)
+ Reflect.set(window, 'memoryProofAborts', 0)
+ window.fetch = (input, init) => {
+ if (String(input).includes('/api/memory/sync')) init?.signal?.addEventListener('abort', () => {
+ Reflect.set(window, 'memoryProofAborts', Number(Reflect.get(window, 'memoryProofAborts')) + 1)
+ }, { once: true })
+ return original(input, init)
+ }
+ })
+ await accountFixture(page)
+ await page.getByLabel('Allow cloud storage for this account collection', { exact: true }).check()
+ const sync = page.getByRole('button', { name: 'Sync account memories', exact: true })
+ await sync.click()
+ await expect.poll(() => reads).toBe(1)
+ await page.getByRole('button', { name: 'Cancel synchronization', exact: true }).click()
+ await expect(page.getByRole('status')).toHaveText('Memory synchronization cancelled. Some changes may already be saved.')
+ await expect(sync).toBeEnabled()
+ expect(await page.evaluate(() => Reflect.get(window, 'memoryProofAborts'))).toBe(1)
+ await finish!()
+ finish = undefined
+ await sync.click()
+ await expect.poll(() => reads).toBe(2)
+ await page.getByRole('button', { name: 'Use local memories', exact: true }).click()
+ await page.getByRole('button', { name: 'Use account memories', exact: true }).click()
+ expect(await page.evaluate(() => Reflect.get(window, 'memoryProofAborts'))).toBe(2)
+ await finish!()
+ hold = false
+ await page.getByLabel('Allow cloud storage for this account collection', { exact: true }).check()
+ await sync.click()
+ await expect(page.getByRole('status')).toHaveText('Synced 0 uploads and 0 downloads. 0 conflicting memories left unchanged.')
+ expect(reads).toBe(3)
+ await expect(page.getByRole('button', { name: 'Cancel synchronization', exact: true })).toHaveCount(0)
+})
+
test('explicit UI sync uploads, downloads, preserves conflicts and persists shared deletion', async ({ page }, testInfo) => {
let records: SyncedMemoryRecord[] = []
let writes = 0
@@ -126,9 +175,11 @@ test('explicit UI sync uploads, downloads, preserves conflicts and persists shar
expect(baseline).toEqual([{ revision: 8, hash: null }])
})
-test('a lost first-upload response cannot revive a locally deleted memory after reload', async ({ page }) => {
+for (const responseMode of ['lost', 'cancelled'] as const) {
+test(`a ${responseMode} first-upload response cannot revive a locally deleted memory after reload`, async ({ page }) => {
let records: SyncedMemoryRecord[] = []
let lostResponse = false
+ let finish: (() => Promise<void>) | undefined
await page.route('**/*', route => new URL(route.request().url()).port === '5273' ? route.continue() : route.abort())
await page.route('**/api/memory/sync**', async route => {
if (route.request().method() === 'GET') return route.fulfill({ json: { ownerId: 'owner-a', records, next: null } })
@@ -139,7 +190,16 @@ test('a lost first-upload response cannot revive a locally deleted memory after
const record = { memory_id: body.memoryId, revision: body.expectedRevision + 1, payload: body.payload,
deleted: body.deleted === true, updated_at: '2026-09-09T00:00:00Z' }
records = [record]
- if (!lostResponse) { lostResponse = true; return route.abort('failed') }
+ if (!lostResponse) {
+ lostResponse = true
+ if (responseMode === 'lost') return route.abort('failed')
+ return new Promise<void>(resolve => {
+ finish = async () => {
+ await route.fulfill({ json: { ownerId: 'owner-a', record } }).catch(() => {})
+ resolve()
+ }
+ })
+ }
return route.fulfill({ json: { ownerId: 'owner-a', record } })
})
await page.goto('/e2e/memory-sensitive-proof.html')
@@ -150,6 +210,12 @@ test('a lost first-upload response cannot revive a locally deleted memory after
await page.getByRole('button', { name: 'Save', exact: true }).click()
await page.getByLabel('Allow cloud storage for this account collection', { exact: true }).check()
await page.getByRole('button', { name: 'Sync account memories', exact: true }).click()
+ if (responseMode === 'cancelled') {
+ await expect.poll(() => Boolean(finish)).toBe(true)
+ await page.getByRole('button', { name: 'Cancel synchronization', exact: true }).click()
+ await expect(page.getByRole('status')).toHaveText('Memory synchronization cancelled. Some changes may already be saved.')
+ await finish!()
+ }
await expect(page.getByRole('status')).toContainText('Some changes may already be saved')
expect(records[0].deleted).toBe(false)
await page.getByRole('button', { name: 'Delete entry', exact: true }).click()
@@ -171,3 +237,4 @@ test('a lost first-upload response cannot revive a locally deleted memory after
expect(records[0]).toMatchObject({ revision: 2, payload: null, deleted: true })
await expect(page.getByRole('button', { name: 'Delete entry', exact: true })).toHaveCount(0)
})
+}
diff --git a/src/api/cloud/__tests__/memory-sync.test.ts b/src/api/cloud/__tests__/memory-sync.test.ts
index 91c7ce37..bad93b66 100644
--- a/src/api/cloud/__tests__/memory-sync.test.ts
+++ b/src/api/cloud/__tests__/memory-sync.test.ts
@@ -102,7 +102,7 @@ it('sends the verified session through real HTTP and parses a payload-free delet
expect(received).toEqual({ memoryId: 'one', expectedRevision: 0, payload: null, deleted: true })
} finally { server.closeAllConnections(); await new Promise<void>(resolve => server.close(() => resolve())) }
})
-it('closes a real unfinished HTTP response on account revocation', async () => {
+it.each(['account', 'cancelled'] as const)('closes a real unfinished HTTP response on %s', async kind => {
let started!: () => void
let closed!: () => void
const seen = new Promise<void>(resolve => { started = resolve })
@@ -117,11 +117,37 @@ it('closes a real unfinished HTTP response on account revocation', async () => {
endpoint.base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`
vi.stubGlobal('fetch', networkFetch)
try {
- const pending = withMemorySyncSession('a', client => client.pull())
- const failure = expect(pending).rejects.toMatchObject({ kind: 'account' })
+ const controller = new AbortController()
+ const pending = withMemorySyncSession('a', client => client.pull(), controller.signal)
+ const failure = expect(pending).rejects.toMatchObject({ kind })
await seen
- useCloudAuthStore.getState().setSignedOut()
+ if (kind === 'account') useCloudAuthStore.getState().setSignedOut()
+ else controller.abort('PRIVATE_CALLER_REASON')
await failure
await disconnected
} finally { server.closeAllConnections(); await new Promise<void>(resolve => server.close(() => resolve())) }
})
+
+it('refuses pre-cancelled work without SDK or network calls', async () => {
+ const controller = new AbortController()
+ controller.abort('PRIVATE_CALLER_REASON')
+ await expect(withMemorySyncSession('a', client => client.pull(), controller.signal)).rejects.toMatchObject({
+ kind: 'cancelled', message: 'Memory synchronization cancelled. Some changes may already be saved.',
+ })
+ expect(auth.getSession).not.toHaveBeenCalled()
+ expect(fetcher).not.toHaveBeenCalled()
+})
+
+it('cancels stalled identity verification and removes the caller listener', async () => {
+ auth.getUser.mockImplementation(() => new Promise(() => {}))
+ const controller = new AbortController()
+ const remove = vi.spyOn(controller.signal, 'removeEventListener')
+ const pending = withMemorySyncSession('a', client => client.pull(), controller.signal)
+ const failure = expect(pending).rejects.toMatchObject({ kind: 'cancelled' })
+ await vi.waitFor(() => expect(auth.getUser).toHaveBeenCalled())
+ controller.abort()
+ await failure
+ expect(fetcher).not.toHaveBeenCalled()
+ expect(auth.unsubscribe).toHaveBeenCalledOnce()
+ expect(remove).toHaveBeenCalledWith('abort', expect.any(Function))
+})
diff --git a/src/api/cloud/memory-sync.ts b/src/api/cloud/memory-sync.ts
index 87d59704..c8fe6e4c 100644
--- a/src/api/cloud/memory-sync.ts
+++ b/src/api/cloud/memory-sync.ts
@@ -12,7 +12,7 @@ export interface SyncedMemoryRecord {
updated_at: string
}
export class MemorySyncError extends Error {
- readonly kind: 'account' | 'conflict' | 'network' | 'invalid'
+ readonly kind: 'account' | 'conflict' | 'network' | 'invalid' | 'cancelled'
constructor(kind: MemorySyncError['kind'], message: string) { super(message); this.kind = kind }
}
const invalid = () => new MemorySyncError('invalid', 'Invalid memory synchronization response')
@@ -31,8 +31,10 @@ export interface MemorySyncSession {
}
/** No background activity or opt-in: callers explicitly own one bounded run. */
-export async function withMemorySyncSession<T>(ownerId: string, work: (session: MemorySyncSession) => Promise<T>): Promise<T> {
+export async function withMemorySyncSession<T>(ownerId: string, work: (session: MemorySyncSession) => Promise<T>, signal?: AbortSignal): Promise<T> {
const controller = new AbortController()
+ const cancel = () => controller.abort(new MemorySyncError('cancelled', 'Memory synchronization cancelled. Some changes may already be saved.'))
+ if (signal?.aborted) cancel()
const accountError = () => new MemorySyncError('account', 'Memory synchronization stopped because the account changed')
const assertCurrent = () => {
const current = useCloudAuthStore.getState()
@@ -40,6 +42,7 @@ export async function withMemorySyncSession<T>(ownerId: string, work: (session:
if (current.status !== 'signed-in' || current.user?.id !== ownerId) throw accountError()
}
assertCurrent()
+ signal?.addEventListener('abort', cancel, { once: true })
const stopStore = useCloudAuthStore.subscribe(state => {
if (state.status !== 'signed-in' || state.user?.id !== ownerId) controller.abort(accountError())
})
@@ -137,5 +140,6 @@ export async function withMemorySyncSession<T>(ownerId: string, work: (session:
clearTimeout(timer)
stopStore()
stopAuth?.()
+ signal?.removeEventListener('abort', cancel)
}
}
diff --git a/src/components/settings/MemorySettings.tsx b/src/components/settings/MemorySettings.tsx
index 3c4f0080..8e2407fd 100644
--- a/src/components/settings/MemorySettings.tsx
+++ b/src/components/settings/MemorySettings.tsx
@@ -39,6 +39,12 @@ function MemorySettingsPanel() {
const [syncConsent, setSyncConsent] = useState(false)
const [sensitiveSyncConsent, setSensitiveSyncConsent] = useState(false)
const [syncBusy, setSyncBusy] = useState(false)
+ const syncController = useRef<AbortController | null>(null)
+ useEffect(() => () => {
+ const controller = syncController.current
+ syncController.current = null
+ controller?.abort()
+ }, [])
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)
@@ -72,20 +78,30 @@ function MemorySettingsPanel() {
if (state.entries !== previous.entries) setSyncConflicts([])
}), [])
const runSync = async (resolution?: MemorySyncResolution) => {
- if (activeOwner === null || !syncConsent || syncBusy) return
+ if (activeOwner === null || !syncConsent || syncController.current) return
+ const controller = new AbortController()
+ syncController.current = controller
setSyncBusy(true)
setSyncConflicts([])
setSyncMessage('Synchronizing memories...')
try {
- const result = await synchronizeMemoryCollection(activeOwner, sensitiveSyncConsent, resolution)
+ const result = await synchronizeMemoryCollection(activeOwner, sensitiveSyncConsent, resolution, controller.signal)
+ if (syncController.current !== controller) return
setSyncConflicts(result.conflicts)
setSyncMessage(`Synced ${result.uploaded} uploads and ${result.downloaded} downloads. ${result.conflicts.length} conflicting memories left unchanged.`)
} catch (error) {
+ if (syncController.current !== controller) return
const messages = ['Sensitive memories need explicit permission for cloud storage before this collection can synchronize',
- 'This conflict changed. Sync again before choosing a version.']
+ 'This conflict changed. Sync again before choosing a version.',
+ 'Memory synchronization cancelled. Some changes may already be saved.']
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) }
+ } finally {
+ if (syncController.current === controller) {
+ syncController.current = null
+ setSyncBusy(false)
+ }
+ }
}
// ── New memory form state ───────────────────────────────────
@@ -263,6 +279,7 @@ function MemorySettingsPanel() {
<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={() => void runSync()}>Sync account memories</button>
+ {syncBusy && <button className="ml-3 underline" onClick={() => syncController.current?.abort()}>Cancel synchronization</button>}
{syncMessage && <p role="status">{syncMessage}</p>}
{syncConflicts.map((conflict, index) => {
const local = entries.find(entry => entry.id === conflict.id)
diff --git a/src/lib/__tests__/memory-sync-coordinator.test.ts b/src/lib/__tests__/memory-sync-coordinator.test.ts
index 7f81c724..d99a3eca 100644
--- a/src/lib/__tests__/memory-sync-coordinator.test.ts
+++ b/src/lib/__tests__/memory-sync-coordinator.test.ts
@@ -38,6 +38,36 @@ it('persists an intent before uploading and acknowledges accepted content afterw
expect(useMemoryStore.getState().memorySyncBaselines.A.one.revision).toBe(1)
expect(fixture.flush).toHaveBeenCalledTimes(4)
})
+
+it('does not start a pull after cancellation during pending local confirmation', async () => {
+ let finish!: () => void
+ fixture.flush.mockImplementationOnce(() => new Promise<void>(resolve => { finish = resolve }))
+ const controller = new AbortController()
+ const pending = synchronizeMemoryCollection('A', false, undefined, controller.signal)
+ controller.abort()
+ finish()
+ await expect(pending).rejects.toMatchObject({ kind: 'cancelled' })
+ expect(fixture.pull).not.toHaveBeenCalled()
+ expect(fixture.write).not.toHaveBeenCalled()
+ expect((await synchronizeMemoryCollection('A')).uploaded).toBe(0)
+})
+
+it('retains accepted-write intent on cancel and recovers deletion on the next run', async () => {
+ useMemoryStore.setState({ entries: [memory] })
+ const controller = new AbortController()
+ const normalWrite = fixture.write.getMockImplementation()!
+ fixture.write.mockImplementationOnce(async (...args: unknown[]) => {
+ const saved = await normalWrite(...args)
+ controller.abort()
+ return saved
+ })
+ await expect(synchronizeMemoryCollection('A', false, undefined, controller.signal)).rejects.toMatchObject({ kind: 'cancelled' })
+ expect(useMemoryStore.getState().memorySyncPending.A.one.revision).toBe(0)
+ useMemoryStore.getState().removeMemory('one')
+ await synchronizeMemoryCollection('A')
+ expect(remote[0]).toMatchObject({ revision: 2, deleted: true, payload: null })
+ expect(useMemoryStore.getState().memorySyncPending.A).toEqual({})
+})
it('preserves valid prototype-named IDs as own metadata keys', async () => {
useMemoryStore.setState({ entries: [{ ...memory, id: '__proto__' }] })
await synchronizeMemoryCollection('A')
diff --git a/src/lib/memory-sync.ts b/src/lib/memory-sync.ts
index ed747227..dfb18cfc 100644
--- a/src/lib/memory-sync.ts
+++ b/src/lib/memory-sync.ts
@@ -37,7 +37,7 @@ 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, resolution?: MemorySyncResolution) {
+export async function synchronizeMemoryCollection(owner: string, allowSensitive = false, resolution?: MemorySyncResolution, signal?: AbortSignal) {
if (running) throw new Error('Memory synchronization is already running')
const initial = useMemoryStore.getState()
let expectedEntries = initial.entries
@@ -47,6 +47,7 @@ export async function synchronizeMemoryCollection(owner: string, allowSensitive
const choice = resolution ? { ...resolution } : undefined
if (choice && (choice.owner !== owner || choice.collectionRevision !== revision || !['local', 'cloud'].includes(choice.choice))) throw conflictChanged()
const check = () => {
+ if (signal?.aborted) throw new MemorySyncError('cancelled', 'Memory synchronization cancelled. Some changes may already be saved.')
const state = useMemoryStore.getState()
const auth = useCloudAuthStore.getState()
if (auth.status !== 'signed-in' || auth.user?.id !== owner || state.activeMemoryOwner !== owner ||
@@ -155,6 +156,6 @@ export async function synchronizeMemoryCollection(owner: string, allowSensitive
}))
guard()
return { downloaded: plan.pull.length, uploaded, removed: plan.remove.length, conflicts }
- })
+ }, signal)
} finally { running = false }
}