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
Revoke Remote context when shared memory changes
David84a7ee0f24fc
diff --git a/e2e/remote-memory-proof.html b/e2e/remote-memory-proof.htmlnew file mode 100644index 00000000..0334ecac--- /dev/null+++ b/e2e/remote-memory-proof.html@@ -0,0 +1,4 @@+<!doctype html>+<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Remote memory revocation proof</title></head>+<body><div id="root"></div><button id="start">Start proof remote session</button><pre id="remote-state"></pre>+<script type="module" src="/e2e/remote-memory-proof.ts"></script></body></html>diff --git a/e2e/remote-memory-proof.ts b/e2e/remote-memory-proof.tsnew file mode 100644index 00000000..ccde9845--- /dev/null+++ b/e2e/remote-memory-proof.ts@@ -0,0 +1,16 @@+import { createElement } from 'react'+import { createRoot } from 'react-dom/client'+import { MemorySettings } from '../src/components/settings/MemorySettings'+import { useMemoryStore, __setMemoryEmbedFn } from '../src/stores/memoryStore'+import { useRemoteStore } from '../src/stores/remoteStore'+import '../src/index.css'++await useMemoryStore.persist.rehydrate()+__setMemoryEmbedFn(async () => [])+createRoot(document.getElementById('root')!).render(createElement(MemorySettings))+useRemoteStore.subscribe(state => {+ document.getElementById('remote-state')!.textContent = JSON.stringify({ enabled: state.enabled, qrVisible: state.qrVisible })+})+document.getElementById('start')!.onclick = () => {+ void useRemoteStore.getState().startServer().catch(() => { /* Store renders the error. */ })+}diff --git a/e2e/remote-memory.spec.ts b/e2e/remote-memory.spec.tsnew file mode 100644index 00000000..a870fa6e--- /dev/null+++ b/e2e/remote-memory.spec.ts@@ -0,0 +1,33 @@+import { expect, test } from '@playwright/test'++for (const fail of [false, true]) {+ test(`actual sensitive control ${fail ? 'reports unconfirmed native failure' : 'requests Remote revocation'}`, async ({ page }, testInfo) => {+ await page.addInitScript(({ fail }) => {+ const calls: string[] = []+ Object.defineProperty(window, 'remoteProofCalls', { value: calls })+ Object.defineProperty(window, '__TAURI_INTERNALS__', { value: {+ invoke: async (command: string) => {+ calls.push(command)+ if (fail && ['revoke_remote_memory', 'stop_remote_server'].includes(command)) throw new Error('Synthetic native failure')+ if (command === 'start_remote_server') return { port: 11435, passcode: 'fixture', passcodeExpiresAt: 1, lanUrl: '', mobileUrl: '' }+ if (command === 'remote_qr_code') return { qr_png_base64: '', url: '', passcode: '' }+ if (command === 'revoke_remote_memory') return null+ throw new Error('Unsupported proof command')+ },+ } })+ }, { fail })+ await page.goto('/e2e/remote-memory-proof.html')+ await page.getByRole('button', { name: 'Add Memory', exact: true }).click()+ await page.getByPlaceholder('What should I remember?').fill('Remote proof preference')+ await page.getByPlaceholder('Details… (required)').fill('Synthetic remembered preference')+ await page.getByRole('button', { name: 'Save', exact: true }).click()+ await page.getByRole('button', { name: 'Start proof remote session' }).click()+ await expect(page.locator('#remote-state')).toContainText('"qrVisible":true')+ await page.getByLabel('Sensitive: exclude from AI requests').check()+ await expect(page.getByRole('status')).toContainText(fail ? 'could not be confirmed' : 'Restart Remote Access and reconnect')+ await expect(page.locator('#remote-state')).toHaveText('{"enabled":true,"qrVisible":false}')+ expect(await page.evaluate(() => (window as unknown as { remoteProofCalls: string[] }).remoteProofCalls)).toContain('revoke_remote_memory')+ await page.setViewportSize({ width: 390, height: 844 })+ await page.screenshot({ path: testInfo.outputPath('remote-memory-notice.png'), fullPage: true })+ })+}diff --git a/src/components/settings/MemorySettings.tsx b/src/components/settings/MemorySettings.tsxindex 69ee1f43..da16e713 100644--- a/src/components/settings/MemorySettings.tsx+++ b/src/components/settings/MemorySettings.tsx@@ -1,6 +1,7 @@import { useState, useRef, useEffect } from 'react'import { Brain, Download, Upload, Trash2, Search, Plus, X, Check, Pencil, Zap, FileJson, Archive, Sparkles } from 'lucide-react'import { useMemoryStore, effectiveMemoryBudget } from '../../stores/memoryStore'+import { useRemoteStore } from '../../stores/remoteStore'import { useModelStore } from '../../stores/modelStore'import { useChatStore, persistConversationMemoryScope } from '../../stores/chatStore'import { getModelMaxTokens } from '../../lib/context-compaction'@@ -28,6 +29,7 @@ const TYPE_DOT_COLORS: Record<MemoryType, string> = {// ── Component ─────────────────────────────────────────────────export function MemorySettings() {+ 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)const [projectSaveError, setProjectSaveError] = useState(false)@@ -304,6 +306,7 @@ export function MemorySettings() {)}<p className="text-xs text-gray-500">Mark sensitive memories to exclude them from AI requests and embeddings. This does not detect secrets automatically or erase earlier requests. Markdown export omits sensitive and project-scoped entries; JSON export preserves their flags and scope.</p><p className="text-xs text-gray-500" role="note">Remote sessions can retain previously shared memory in their prompts. This control cannot revoke those copies. End the remote session before handling sensitive data.</p>+ {remoteMemoryNotice && <p role="status" className="text-sm text-red-600 dark:text-red-300">{remoteMemoryNotice}</p>}<div className="relative"><Search size={12} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-gray-500" /><inputdiff --git a/src/stores/__tests__/remote-memory-revocation.test.ts b/src/stores/__tests__/remote-memory-revocation.test.tsnew file mode 100644index 00000000..b357e9c3--- /dev/null+++ b/src/stores/__tests__/remote-memory-revocation.test.ts@@ -0,0 +1,144 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import type { MemoryFile } from '../../types/agent-mode'+vi.mock('../../api/backend', () => ({ backendCall: vi.fn(), isTauri: () => true }))+import { backendCall } from '../../api/backend'+import { useMemoryStore, __setMemoryEmbedFn } from '../memoryStore'+import { useRemoteStore, remoteMemoryChanged, REMOTE_MEMORY_CHANGED } from '../remoteStore'++const call = vi.mocked(backendCall)+const entry: MemoryFile = {+ id: 'proof-memory', type: 'user', title: 'Preference', description: '',+ content: 'Synthetic remembered preference', tags: [], source: 'manual',+ createdAt: Date.now(), updatedAt: Date.now(),+}+const started = { port: 11435, passcode: 'fixture', lanUrl: '', mobileUrl: '', passcodeExpiresAt: 1 }+const retrieve = useMemoryStore.getState().getMemoriesForPromptAsync+function deferred<T>() {+ let resolve!: (value: T) => void+ const promise = new Promise<T>(done => { resolve = done })+ return { promise, resolve }+}+beforeEach(() => {+ call.mockReset().mockResolvedValue(started)+ useRemoteStore.setState({ enabled: false, loading: false, error: null, qrVisible: false })+ useMemoryStore.setState({ entries: [{ ...entry }], getMemoriesForPromptAsync: retrieve })+ __setMemoryEmbedFn(async () => [])+})+afterEach(async () => {+ call.mockResolvedValue(started)+ useRemoteStore.setState({ loading: false })+ await useRemoteStore.getState().stopServer()+ __setMemoryEmbedFn()+})++describe('automatic Remote memory revocation', () => {+ it.each(['delete', 'edit', 'sensitive', 'scope', 'clear'] as const)('revokes a running prompt on %s', async kind => {+ await useRemoteStore.getState().startServer()+ expect(call.mock.calls.find(([name]) => name === 'start_remote_server')?.[1]?.systemPrompt).toContain(entry.content)+ if (kind === 'delete') useMemoryStore.getState().removeMemory(entry.id)+ if (kind === 'clear') useMemoryStore.getState().clearAll()+ if (kind === 'edit') useMemoryStore.getState().updateMemory(entry.id, { content: 'Replacement' })+ if (kind === 'sensitive') useMemoryStore.getState().updateMemory(entry.id, { sensitive: true })+ if (kind === 'scope') useMemoryStore.getState().updateMemory(entry.id, { scope: 'private-project' })+ await vi.waitFor(() => expect(useRemoteStore.getState().error).toBe(REMOTE_MEMORY_CHANGED))+ expect(call).toHaveBeenCalledWith('revoke_remote_memory')+ expect(useRemoteStore.getState().qrVisible).toBe(false)+ })++ it('does not interrupt an existing prompt for additions or excluded entries', () => {+ expect(remoteMemoryChanged([entry], [entry, { ...entry, id: 'new' }])).toBe(false)+ expect(remoteMemoryChanged([{ ...entry, sensitive: true }], [])).toBe(false)+ expect(remoteMemoryChanged([{ ...entry, scope: 'project' }], [])).toBe(false)+ expect(remoteMemoryChanged([entry], [{ ...entry, stale: true }])).toBe(true)+ })++ it('rejects mutation during enrichment before submitting the stale prompt', async () => {+ const context = deferred<string>()+ const pendingRetrieval = vi.fn(() => context.promise)+ useMemoryStore.setState({ getMemoriesForPromptAsync: pendingRetrieval })+ const start = useRemoteStore.getState().startServer()+ const assertion = expect(start).rejects.toThrow(REMOTE_MEMORY_CHANGED)+ await vi.waitFor(() => expect(pendingRetrieval).toHaveBeenCalled())+ useMemoryStore.getState().removeMemory(entry.id)+ context.resolve(entry.content)+ await assertion+ expect(call.mock.calls.some(([name]) => name === 'start_remote_server')).toBe(false)+ })++ it.each(['startServer', 'restart'] as const)('revokes again after mutation during native %s, before showing QR', async method => {+ const native = deferred<typeof started>()+ const command = method === 'restart' ? 'restart_remote_server' : 'start_remote_server'+ call.mockImplementation(async name => name === command ? native.promise : started)+ const start = useRemoteStore.getState()[method]()+ const assertion = expect(start).rejects.toThrow(REMOTE_MEMORY_CHANGED)+ await vi.waitFor(() => expect(call.mock.calls.some(([name]) => name === command)).toBe(true))+ useMemoryStore.getState().removeMemory(entry.id)+ await vi.waitFor(() => expect(call).toHaveBeenCalledWith('revoke_remote_memory'))+ native.resolve(started)+ await assertion+ expect(call.mock.calls.filter(([name]) => name === 'revoke_remote_memory')).toHaveLength(2)+ expect(call.mock.calls.some(([name]) => name === 'remote_qr_code')).toBe(false)+ expect(useRemoteStore.getState().enabled).toBe(true)+ expect(useRemoteStore.getState().qrVisible).toBe(false)+ })++ it('stops the native server if the revocation command fails', async () => {+ await useRemoteStore.getState().startServer()+ call.mockImplementation(async name => {+ if (name === 'revoke_remote_memory') throw new Error('synthetic private diagnostic')+ return started+ })+ useMemoryStore.getState().removeMemory(entry.id)+ await vi.waitFor(() => expect(useRemoteStore.getState().enabled).toBe(false))+ expect(call).toHaveBeenCalledWith('stop_remote_server')+ expect(useRemoteStore.getState().error).toBe(REMOTE_MEMORY_CHANGED)+ })++ it('does not claim a failed revoke and failed stop made the server safe', async () => {+ await useRemoteStore.getState().startServer()+ call.mockRejectedValue(new Error('synthetic private diagnostic'))+ useMemoryStore.getState().removeMemory(entry.id)+ await vi.waitFor(() => expect(useRemoteStore.getState().error).toContain('could not be confirmed'))+ expect(useRemoteStore.getState().enabled).toBe(true)+ expect(useRemoteStore.getState().error).not.toContain('synthetic private diagnostic')+ await expect(useRemoteStore.getState().restart()).rejects.toThrow('could not be confirmed')+ })++ it('does not permit overlapping starts', async () => {+ const native = deferred<typeof started>()+ call.mockImplementation(async name => name === 'start_remote_server' ? native.promise : started)+ const start = useRemoteStore.getState().startServer()+ await expect(useRemoteStore.getState().restart()).rejects.toThrow('already starting')+ native.resolve(started)+ await start+ })++ it('waits for a delayed stop fallback before restarting with current memory', async () => {+ await useRemoteStore.getState().startServer()+ const stopped = deferred<typeof started>()+ const stoppedAgain = deferred<typeof started>()+ let stops = 0+ call.mockImplementation(async name => {+ if (name === 'revoke_remote_memory') throw new Error('Synthetic failure')+ if (name === 'stop_remote_server') return ++stops === 1 ? stopped.promise : stoppedAgain.promise+ return started+ })+ useMemoryStore.getState().removeMemory(entry.id)+ await vi.waitFor(() => expect(call).toHaveBeenCalledWith('stop_remote_server'))+ const restart = useRemoteStore.getState().restart()+ await Promise.resolve()+ expect(call.mock.calls.some(([name]) => name === 'restart_remote_server')).toBe(false)+ // Queue another revocation after restart has begun waiting on the first.+ useMemoryStore.setState({ entries: [{ ...entry, id: 'second' }] })+ useMemoryStore.getState().removeMemory('second')+ stopped.resolve(started)+ await vi.waitFor(() => expect(stops).toBe(2))+ expect(call.mock.calls.some(([name]) => name === 'restart_remote_server')).toBe(false)+ stoppedAgain.resolve(started)+ await restart+ const args = call.mock.calls.find(([name]) => name === 'restart_remote_server')?.[1]+ expect(args?.systemPrompt).toBeUndefined()+ expect(useRemoteStore.getState().enabled).toBe(true)+ expect(useRemoteStore.getState().memoryNotice).toBeNull()+ })+})diff --git a/src/stores/remoteStore.ts b/src/stores/remoteStore.tsindex 714c461c..7dec5e79 100644--- a/src/stores/remoteStore.ts+++ b/src/stores/remoteStore.ts@@ -3,6 +3,59 @@ import { backendCall, isTauri } from '../api/backend'import { useMemoryStore } from './memoryStore'import { useProviderStore } from './providerStore'import type { ProviderId } from '../api/providers/types'+import type { MemoryFile } from '../types/agent-mode'++export const REMOTE_MEMORY_CHANGED = 'Remote memory changed. Restart Remote Access and reconnect before continuing. Previously delivered data cannot be recalled.'+const REMOTE_MEMORY_UNCONFIRMED = 'Remote memory changed, but blocking Remote Access could not be confirmed. Disconnect remote devices and stop Remote Access before continuing.'+let memoryRevision = 0+let revocationPending: Promise<void> = Promise.resolve()++async function waitForMemoryRevocation(ignoreFailure = false): Promise<void> {+ let pending: Promise<void>+ do {+ pending = revocationPending+ if (ignoreFailure) await pending.catch(() => {})+ else await pending+ // Another mutation may have queued work while the preceding IPC awaited.+ } while (pending !== revocationPending)+}++/** Additions cannot invalidate an older prompt. Conservatively revoke edits to+ * any previously shareable global entry, even if the prompt budget omitted it.+ * Scoped and sensitive entries are never included in Remote's global prompt.+ */+export function remoteMemoryChanged(before: MemoryFile[], after: MemoryFile[]): boolean {+ if (before === after) return false+ const current = new Map(after.map(entry => [entry.id, entry]))+ return before.some(entry => !entry.sensitive && entry.scope === undefined &&+ JSON.stringify(entry) !== JSON.stringify(current.get(entry.id)))+}++function revokeRemoteMemory(): Promise<void> {+ const pendingNotice = 'Blocking Remote Access because memory changed...'+ useRemoteStore.setState({ error: pendingNotice, memoryNotice: pendingNotice, qrVisible: false })+ // Serialize failures and their stop fallback with the next start/restart.+ // A delayed fallback must never stop a newer, successfully started session.+ revocationPending = revocationPending.catch(() => {}).then(async () => {+ try {+ await backendCall('revoke_remote_memory')+ useRemoteStore.setState({ error: REMOTE_MEMORY_CHANGED, memoryNotice: REMOTE_MEMORY_CHANGED, qrVisible: false })+ } catch {+ try {+ await backendCall('stop_remote_server')+ useRemoteStore.setState({+ enabled: false, passcode: '', qrPngBase64: '', connectedDevices: [],+ tunnelActive: false, tunnelUrl: '', awaitingTunnel: false, qrVisible: false,+ error: REMOTE_MEMORY_CHANGED, memoryNotice: REMOTE_MEMORY_CHANGED,+ })+ } catch {+ useRemoteStore.setState({ error: REMOTE_MEMORY_UNCONFIRMED, memoryNotice: REMOTE_MEMORY_UNCONFIRMED, qrVisible: false })+ throw new Error(REMOTE_MEMORY_UNCONFIRMED)+ }+ }+ })+ return revocationPending+}/*** #87: derive the backend the mobile proxy should reach for a dispatched@@ -163,6 +216,7 @@ interface RemoteState {awaitingTunnel: booleanloading: booleanerror: string | null+ memoryNotice: string | null// DispatchdispatchedConversationId: string | null// UI — Bug #16: QR panel is visible right after dispatch; collapses on@@ -203,10 +257,12 @@ export const useRemoteStore = create<RemoteState>()((set, get) => ({awaitingTunnel: false,loading: false,error: null,+ memoryNotice: null,dispatchedConversationId: null,qrVisible: false,startServer: async (model?: string, systemPrompt?: string) => {+ if (get().loading) throw new Error('Remote Access is already starting. Wait for it to finish.')if (!isTauri()) {// Defense in depth: Sidebar.handleDispatch already short-circuits// before this point, but any other caller (tests, future components,@@ -216,7 +272,10 @@ export const useRemoteStore = create<RemoteState>()((set, get) => ({throw new Error(REMOTE_DEV_MODE_ERROR)}set({ loading: true, error: null })+ let serverStarted = falsetry {+ await waitForMemoryRevocation()+ const revision = memoryRevisionconst args: Record<string, unknown> = {}// #87: tell the Rust proxy which backend serves the dispatched model so// remote reaches the real backend (built-in engine / LM Studio / Lemonade@@ -231,6 +290,7 @@ export const useRemoteStore = create<RemoteState>()((set, get) => ({// prompt, we still want the remembered context injected so cross-chat// memory reaches the Remote session.const enriched = await enrichSystemPromptWithMemory(systemPrompt || '')+ if (revision !== memoryRevision) throw new Error(REMOTE_MEMORY_CHANGED)if (enriched) args.systemPrompt = enrichedconst result = await backendCall<{port: number@@ -240,11 +300,20 @@ export const useRemoteStore = create<RemoteState>()((set, get) => ({mobileUrl: stringpermissions?: RemotePermissions}>('start_remote_server', args)+ serverStarted = true+ // A mutation may have revoked the old native guard before start reset+ // it. Revoke again after the response, before exposing a new QR/passcode.+ if (revision !== memoryRevision) {+ set({ enabled: true })+ await revokeRemoteMemory()+ throw new Error(REMOTE_MEMORY_CHANGED)+ }// RA-1: read the server's effective permissions back in the SAME set()// that flips `enabled: true`. There must be no window in which the panel// renders one thing and the running server enforces another.const startPerms = normalizeRemotePermissions(result.permissions)set({+ memoryNotice: null,enabled: true,port: result.port,passcode: result.passcode,@@ -263,7 +332,8 @@ export const useRemoteStore = create<RemoteState>()((set, get) => ({// dispatchedConversationId on a server that never actually started —// user saw "Server stopped" with no explanation and Restart hit the// same silent failure.- set({ loading: false, enabled: false, error: String(err) })+ const memoryFailure = err instanceof Error && [REMOTE_MEMORY_CHANGED, REMOTE_MEMORY_UNCONFIRMED].includes(err.message)+ set({ loading: false, enabled: (serverStarted || memoryFailure) && get().enabled, error: String(err) })throw err}},@@ -271,6 +341,9 @@ export const useRemoteStore = create<RemoteState>()((set, get) => ({stopServer: async () => {try {await backendCall('stop_remote_server')+ // A confirmed explicit stop also permits recovery from failed IPC.+ await waitForMemoryRevocation(true)+ revocationPending = Promise.resolve()set({enabled: false,passcode: '',@@ -461,12 +534,16 @@ export const useRemoteStore = create<RemoteState>()((set, get) => ({},restart: async (model?: string, systemPrompt?: string) => {+ if (get().loading) throw new Error('Remote Access is already starting. Wait for it to finish.')if (!isTauri()) {set({ loading: false, enabled: false, error: REMOTE_DEV_MODE_ERROR })throw new Error(REMOTE_DEV_MODE_ERROR)}set({ loading: true, error: null })+ let serverStarted = falsetry {+ await waitForMemoryRevocation()+ const revision = memoryRevisionconst args: Record<string, unknown> = {}// #87: same backend derivation as startServer so a restart keeps routing// to the desktop's real backend, not just Ollama.@@ -479,6 +556,7 @@ export const useRemoteStore = create<RemoteState>()((set, get) => ({// Refresh memory context on restart so newly-extracted memories from// the ongoing session propagate into the next mobile connection.const enriched = await enrichSystemPromptWithMemory(systemPrompt || '')+ if (revision !== memoryRevision) throw new Error(REMOTE_MEMORY_CHANGED)if (enriched) args.systemPrompt = enrichedconst result = await backendCall<{port: number@@ -488,10 +566,17 @@ export const useRemoteStore = create<RemoteState>()((set, get) => ({mobileUrl: stringpermissions?: RemotePermissions}>('restart_remote_server', args)+ serverStarted = true+ if (revision !== memoryRevision) {+ set({ enabled: true })+ await revokeRemoteMemory()+ throw new Error(REMOTE_MEMORY_CHANGED)+ }// RA-1: same read-back as startServer — restart_remote_server delegates// to start_remote_server on the Rust side and reports them identically.const restartPerms = normalizeRemotePermissions(result.permissions)set({+ memoryNotice: null,enabled: true,port: result.port,passcode: result.passcode,@@ -510,7 +595,8 @@ export const useRemoteStore = create<RemoteState>()((set, get) => ({// #29: rethrow so the click-handler (ChatView.handleRemoteReactivate// or Sidebar restart chip) can surface the actual reason instead of// looking like the button did nothing.- set({ loading: false, enabled: false, error: String(err) })+ const memoryFailure = err instanceof Error && [REMOTE_MEMORY_CHANGED, REMOTE_MEMORY_UNCONFIRMED].includes(err.message)+ set({ loading: false, enabled: (serverStarted || memoryFailure) && get().enabled, error: String(err) })throw err}},@@ -519,3 +605,13 @@ export const useRemoteStore = create<RemoteState>()((set, get) => ({hideQr: () => set({ qrVisible: false }),clearError: () => set({ error: null }),}))++const unsubscribeRemoteMemory = useMemoryStore.subscribe((state, previous) => {+ if (!remoteMemoryChanged(previous.entries, state.entries) && state.settings === previous.settings) return+ memoryRevision += 1+ const remote = useRemoteStore.getState()+ if (isTauri() && (remote.enabled || remote.loading)) {+ void revokeRemoteMemory().catch(() => { /* Failure is explicitly visible in the store. */ })+ }+})+if (import.meta.hot) import.meta.hot.dispose(unsubscribeRemoteMemory)