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
Pin desktop memory sync runs to verified accounts
Davidd6e07174fa76
diff --git a/src/api/cloud/__tests__/memory-sync.test.ts b/src/api/cloud/__tests__/memory-sync.test.tsnew file mode 100644index 00000000..91c7ce37--- /dev/null+++ b/src/api/cloud/__tests__/memory-sync.test.ts@@ -0,0 +1,127 @@+import { beforeEach, afterEach, expect, it, vi } from 'vitest'+import { createServer } from 'node:http'+import type { AddressInfo } from 'node:net'+const endpoint = vi.hoisted(() => ({ base: 'https://fixture.invalid' }))+vi.mock('../config', () => ({ get CLOUD_BASE() { return endpoint.base } }))+const networkFetch = globalThis.fetch.bind(globalThis)+const auth = vi.hoisted(() => ({ getSession: vi.fn(), getUser: vi.fn(), unsubscribe: vi.fn(), changed: undefined as undefined | ((event: string, session: { user: { id: string } } | null) => void) }))+vi.mock('../supabase', () => ({ supabaseCloud: () => ({ auth: {+ getSession: auth.getSession, getUser: auth.getUser,+ onAuthStateChange: (changed: typeof auth.changed) => { auth.changed = changed; return { data: { subscription: { unsubscribe: auth.unsubscribe } } } },+} }) }))+import { withMemorySyncSession } from '../memory-sync'+import { useCloudAuthStore } from '../../../stores/cloudAuthStore'+const fetcher = vi.fn()+const signIn = (id: string) => useCloudAuthStore.getState().setSignedIn({ id }, { licenseActive: true, tier: null, access: true, quota: null })+const row = (id: string) => ({ memory_id: id, revision: 1, deleted: false, payload: { id, content: 'Synthetic memory' }, updated_at: '2026-09-09T00:00:00Z' })+const response = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status })+beforeEach(() => {+ signIn('a'); vi.stubGlobal('fetch', fetcher); fetcher.mockReset(); auth.unsubscribe.mockReset()+ auth.getSession.mockReset().mockResolvedValue({ data: { session: { access_token: 'synthetic-token-a', user: { id: 'a' } } } })+ auth.getUser.mockReset().mockResolvedValue({ data: { user: { id: 'a' } }, error: null })+})+afterEach(() => { vi.unstubAllGlobals(); vi.useRealTimers() })+it('pins the verified token across pages, retains tombstones and releases listeners', async () => {+ fetcher.mockResolvedValueOnce(response({ ownerId: 'a', records: [row('one')], next: 'one' }))+ .mockResolvedValueOnce(response({ ownerId: 'a', records: [{ ...row('two'), deleted: true, payload: null }], next: null }))+ const rows = await withMemorySyncSession('a', client => client.pull())+ expect(rows).toHaveLength(2)+ expect(rows[1].payload).toBeNull()+ expect(auth.getUser).toHaveBeenCalledWith('synthetic-token-a')+ expect(fetcher.mock.calls[1][0]).toContain('?after=one')+ for (const [, init] of fetcher.mock.calls) {+ expect(init.headers.authorization).toBe('Bearer synthetic-token-a')+ expect(init.credentials).toBe('omit')+ expect(init.redirect).toBe('error')+ }+ expect(auth.unsubscribe).toHaveBeenCalledOnce()+})+it('never sends data if the restored or verified account differs', async () => {+ auth.getUser.mockResolvedValue({ data: { user: { id: 'b' } }, error: null })+ await expect(withMemorySyncSession('a', client => client.write('one', 0, { id: 'one' }))).rejects.toMatchObject({ kind: 'account' })+ expect(fetcher).not.toHaveBeenCalled()+})+it('rejects a delayed page after sign-out and return to the same account', async () => {+ let finish!: (value: Response) => void+ fetcher.mockImplementation(() => new Promise<Response>(resolve => { finish = resolve }))+ const pending = withMemorySyncSession('a', client => client.pull())+ const failure = expect(pending).rejects.toMatchObject({ kind: 'account' })+ await vi.waitFor(() => expect(fetcher).toHaveBeenCalled())+ useCloudAuthStore.getState().setSignedOut(); signIn('a')+ finish(response({ ownerId: 'a', records: [row('one')], next: 'one' }))+ await failure+ expect(fetcher).toHaveBeenCalledOnce()+ expect(fetcher.mock.calls[0][1].signal.aborted).toBe(true)+})+it('SDK account changes abort even before the UI auth store updates', async () => {+ fetcher.mockImplementation(() => new Promise(() => {}))+ const pending = withMemorySyncSession('a', client => client.pull())+ const failure = expect(pending).rejects.toMatchObject({ kind: 'account' })+ await vi.waitFor(() => expect(fetcher).toHaveBeenCalled())+ auth.changed?.('SIGNED_OUT', null)+ await failure+ expect(auth.unsubscribe).toHaveBeenCalledOnce()+})+it('bounds a stalled response body, not only response headers', async () => {+ vi.useFakeTimers()+ fetcher.mockResolvedValue(new Response(new ReadableStream({ start() {} })))+ const pending = withMemorySyncSession('a', client => client.pull())+ const failure = expect(pending).rejects.toMatchObject({ kind: 'network', message: 'Memory synchronization timed out' })+ await vi.advanceTimersByTimeAsync(60001)+ await failure+})+it('rejects another response owner and cyclic pagination instead of partially applying it', async () => {+ fetcher.mockResolvedValue(response({ ownerId: 'b', records: [], next: null }))+ await expect(withMemorySyncSession('a', client => client.pull())).rejects.toMatchObject({ kind: 'account' })+ fetcher.mockImplementation(async () => response({ ownerId: 'a', records: [row('one')], next: 'one' }))+ await expect(withMemorySyncSession('a', client => client.pull())).rejects.toMatchObject({ kind: 'invalid' })+})+it('surfaces conflicts without retries or private upstream diagnostics', async () => {+ fetcher.mockResolvedValue(response({ error: 'PRIVATE_RESPONSE_CONTENT' }, 409))+ await expect(withMemorySyncSession('a', client => client.write('one', 0, { id: 'one' }))).rejects.toMatchObject({ kind: 'conflict' })+ expect(fetcher).toHaveBeenCalledOnce()+})+it('sends the verified session through real HTTP and parses a payload-free deletion', async () => {+ let received: unknown+ let bearer: string | undefined+ const server = createServer(async (request, reply) => {+ bearer = request.headers.authorization+ let body = ''+ for await (const chunk of request) body += chunk+ received = JSON.parse(body)+ reply.setHeader('content-type', 'application/json')+ reply.end(JSON.stringify({ ownerId: 'a', record: { ...row('one'), deleted: true, payload: null } }))+ })+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))+ endpoint.base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`+ vi.stubGlobal('fetch', networkFetch)+ try {+ const deleted = await withMemorySyncSession('a', client => client.write('one', 0, null))+ expect(deleted.deleted).toBe(true)+ expect(bearer).toBe('Bearer synthetic-token-a')+ 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 () => {+ let started!: () => void+ let closed!: () => void+ const seen = new Promise<void>(resolve => { started = resolve })+ const disconnected = new Promise<void>(resolve => { closed = resolve })+ const server = createServer((_request, reply) => {+ reply.on('close', closed)+ reply.writeHead(200, { 'content-type': 'application/json' })+ reply.write('{')+ started()+ })+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))+ 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' })+ await seen+ useCloudAuthStore.getState().setSignedOut()+ await failure+ await disconnected+ } finally { server.closeAllConnections(); await new Promise<void>(resolve => server.close(() => resolve())) }+})diff --git a/src/api/cloud/memory-sync.ts b/src/api/cloud/memory-sync.tsnew file mode 100644index 00000000..87d59704--- /dev/null+++ b/src/api/cloud/memory-sync.ts@@ -0,0 +1,141 @@+import { CLOUD_BASE } from './config'+import { supabaseCloud } from './supabase'+import { useCloudAuthStore } from '../../stores/cloudAuthStore'+import { isRecord } from '../../types/json-guards'++export interface SyncedMemoryRecord {+ memory_id: string+ revision: number+ deleted: boolean+ /** Still untrusted record data; the store must validate its memory schema. */+ payload: Record<string, unknown> | null+ updated_at: string+}+export class MemorySyncError extends Error {+ readonly kind: 'account' | 'conflict' | 'network' | 'invalid'+ constructor(kind: MemorySyncError['kind'], message: string) { super(message); this.kind = kind }+}+const invalid = () => new MemorySyncError('invalid', 'Invalid memory synchronization response')+const validId = (value: unknown): value is string => typeof value === 'string' && value.length > 0 && value.length <= 128 && value.trim() === value+function record(raw: unknown): SyncedMemoryRecord {+ if (!isRecord(raw) || !validId(raw.memory_id) || !Number.isSafeInteger(raw.revision) || Number(raw.revision) < 1 ||+ typeof raw.deleted !== 'boolean' || typeof raw.updated_at !== 'string' ||+ (raw.deleted ? raw.payload !== null : !isRecord(raw.payload) || raw.payload.id !== raw.memory_id)) throw invalid()+ return { memory_id: raw.memory_id, revision: Number(raw.revision), deleted: raw.deleted,+ payload: raw.payload as Record<string, unknown> | null, updated_at: raw.updated_at }+}+export interface MemorySyncSession {+ assertCurrent(): void+ pull(): Promise<SyncedMemoryRecord[]>+ write(id: string, revision: number, payload: Record<string, unknown> | null): Promise<SyncedMemoryRecord>+}++/** 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> {+ const controller = new AbortController()+ const accountError = () => new MemorySyncError('account', 'Memory synchronization stopped because the account changed')+ const assertCurrent = () => {+ const current = useCloudAuthStore.getState()+ if (controller.signal.aborted) throw controller.signal.reason+ if (current.status !== 'signed-in' || current.user?.id !== ownerId) throw accountError()+ }+ assertCurrent()+ const stopStore = useCloudAuthStore.subscribe(state => {+ if (state.status !== 'signed-in' || state.user?.id !== ownerId) controller.abort(accountError())+ })+ const timer = setTimeout(() => controller.abort(new MemorySyncError('network', 'Memory synchronization timed out')), 60000)+ const bounded = <V>(promise: PromiseLike<V>): Promise<V> => new Promise((resolve, reject) => {+ const stop = () => reject(controller.signal.reason)+ Promise.resolve(promise).then(resolve, reject).finally(() => controller.signal.removeEventListener('abort', stop))+ if (controller.signal.aborted) stop()+ else controller.signal.addEventListener('abort', stop, { once: true })+ })+ let stopAuth: (() => void) | undefined+ try {+ const auth = supabaseCloud().auth+ const listener = auth.onAuthStateChange((_event, session) => {+ if (session?.user.id !== ownerId) controller.abort(accountError())+ })+ stopAuth = () => listener.data.subscription.unsubscribe()+ const { data } = await bounded(auth.getSession())+ const token = data.session?.access_token+ if (!token || data.session?.user.id !== ownerId) throw accountError()+ const verified = await bounded(auth.getUser(token))+ if (verified.error || verified.data.user?.id !== ownerId) throw accountError()+ assertCurrent()+ let receivedBytes = 0+ const request = async (suffix: string, body?: unknown): Promise<Record<string, unknown>> => {+ assertCurrent()+ const response = await bounded(fetch(`${CLOUD_BASE}/api/memory/sync${suffix}`, {+ method: body === undefined ? 'GET' : 'POST', credentials: 'omit', redirect: 'error',+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },+ body: body === undefined ? undefined : JSON.stringify(body), signal: controller.signal,+ }))+ if (!response.ok) {+ void response.body?.cancel().catch(() => {})+ if (response.status === 409) throw new MemorySyncError('conflict', 'Memory changed or was deleted. Pull before resolving the conflict.')+ throw new MemorySyncError('network', 'Could not synchronize memories')+ }+ const reader = response.body?.getReader()+ if (!reader) throw invalid()+ let bytes = 0+ const chunks: Uint8Array[] = []+ try {+ for (;;) {+ const part = await bounded(reader.read())+ if (part.done) break+ bytes += part.value.byteLength+ receivedBytes += part.value.byteLength+ if (bytes > 2_000_000 || receivedBytes > 16_000_000) throw invalid()+ chunks.push(part.value)+ }+ } finally { void reader.cancel().catch(() => {}); reader.releaseLock() }+ const joined = new Uint8Array(bytes)+ let offset = 0+ for (const chunk of chunks) { joined.set(chunk, offset); offset += chunk.byteLength }+ const raw: unknown = JSON.parse(new TextDecoder().decode(joined))+ assertCurrent()+ if (!isRecord(raw) || raw.ownerId !== ownerId) {+ controller.abort(accountError())+ throw accountError()+ }+ return raw+ }+ const result = await bounded(work({+ assertCurrent,+ async pull() {+ const records: SyncedMemoryRecord[] = []+ const ids = new Set<string>()+ let next: string | null = null+ for (let page = 0; page < 1000; page++) {+ const raw = await request(next ? `?after=${encodeURIComponent(next)}` : '')+ if (!Array.isArray(raw.records) || raw.records.length > 50) throw invalid()+ const batch = raw.records.map(record)+ for (const item of batch) { if (ids.has(item.memory_id)) throw invalid(); ids.add(item.memory_id); records.push(item) }+ if (raw.next === null) return records+ if (!validId(raw.next) || raw.next !== batch.at(-1)?.memory_id || raw.next === next) throw invalid()+ next = raw.next+ }+ throw invalid()+ },+ async write(id, revision, payload) {+ if (!validId(id) || !Number.isSafeInteger(revision) || revision < 0 || (payload !== null && payload.id !== id)) throw invalid()+ if (payload !== null && new TextEncoder().encode(JSON.stringify(payload)).length > 32768) throw invalid()+ const raw = await request('', { memoryId: id, expectedRevision: revision, deleted: payload === null, payload })+ const saved = record(raw.record)+ if (saved.memory_id !== id || saved.revision !== revision + 1 || saved.deleted !== (payload === null)) throw invalid()+ return saved+ },+ }))+ assertCurrent()+ return result+ } catch (error) {+ if (error instanceof MemorySyncError) throw error+ throw new MemorySyncError('network', 'Could not synchronize memories')+ } finally {+ controller.abort(accountError())+ clearTimeout(timer)+ stopStore()+ stopAuth?.()+ }+}