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.

Serialize Remote stop with pending startup

Davidc0cb21c73922
diff --git a/e2e/remote-memory-proof.html b/e2e/remote-memory-proof.html
index 0334ecac..2db12908 100644
--- a/e2e/remote-memory-proof.html
+++ b/e2e/remote-memory-proof.html
@@ -1,4 +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>
+<body><div id="root"></div><button id="start">Start proof remote session</button><button id="stop">Stop proof remote session</button><pre id="stop-result"></pre><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.ts
index 6bc2dc85..73e08966 100644
--- a/e2e/remote-memory-proof.ts
+++ b/e2e/remote-memory-proof.ts
@@ -19,3 +19,7 @@ useRemoteStore.subscribe(state => {
document.getElementById('start')!.onclick = () => {
void useRemoteStore.getState().startServer().catch(() => { /* Store renders the error. */ })
}
+document.getElementById('stop')!.onclick = async () => {
+ await useRemoteStore.getState().stopServer()
+ document.getElementById('stop-result')!.textContent = 'Stop completed'
+}
diff --git a/e2e/remote-memory.spec.ts b/e2e/remote-memory.spec.ts
index 379bb1f0..1c8610d5 100644
--- a/e2e/remote-memory.spec.ts
+++ b/e2e/remote-memory.spec.ts
@@ -1,5 +1,35 @@
import { expect, test } from '@playwright/test'
+test('stop waits for a pending native start and never publishes its QR', async ({ page }) => {
+ const calls: string[] = []
+ let running = false
+ let release!: () => void
+ const started = new Promise<void>(resolve => { release = resolve })
+ await page.exposeFunction('remoteNativeProof', async (command: string) => {
+ calls.push(command)
+ if (command === 'start_remote_server') { await started; running = true }
+ else if (command === 'stop_remote_server') running = false
+ else if (command !== 'remote_server_status') throw new Error('Unsupported proof command')
+ return { running, port: 11435, passcode: 'fixture', passcodeExpiresAt: 1, lanUrl: '', mobileUrl: '' }
+ })
+ await page.addInitScript(() => {
+ Object.defineProperty(window, '__TAURI_INTERNALS__', { value: {
+ invoke: (command: string) => (window as unknown as { remoteNativeProof: (name: string) => Promise<unknown> }).remoteNativeProof(command),
+ } })
+ })
+ await page.goto('/e2e/remote-memory-proof.html')
+ await page.getByRole('button', { name: 'Start proof remote session' }).click()
+ await expect.poll(() => calls.includes('start_remote_server')).toBe(true)
+ await page.getByRole('button', { name: 'Stop proof remote session' }).click()
+ expect(calls).not.toContain('stop_remote_server')
+ release()
+ await expect(page.locator('#stop-result')).toHaveText('Stop completed')
+ await expect(page.locator('#remote-state')).toHaveText('{"enabled":false,"qrVisible":false}')
+ expect(calls.filter(command => command === 'stop_remote_server')).toHaveLength(1)
+ expect(calls).not.toContain('remote_qr_code')
+ expect(running).toBe(false)
+})
+
test('reload revokes a native session that outlived the frontend', async ({ page }) => {
// This mock lives outside the page, so a real reload discards Zustand but
// intentionally retains the native-side session state and invocation log.
diff --git a/src/stores/__tests__/remote-memory-revocation.test.ts b/src/stores/__tests__/remote-memory-revocation.test.ts
index 4b6b9cbb..c7280422 100644
--- a/src/stores/__tests__/remote-memory-revocation.test.ts
+++ b/src/stores/__tests__/remote-memory-revocation.test.ts
@@ -32,6 +32,60 @@ afterEach(async () => {
})
describe('automatic Remote memory revocation', () => {
+ it.each(['startServer', 'restart'] as const)('stops after pending native %s completes without exposing its 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 cancelled = expect(start).rejects.toThrow('cancelled by a stop request')
+ await vi.waitFor(() => expect(call.mock.calls.some(([name]) => name === command)).toBe(true))
+ const stop = useRemoteStore.getState().stopServer()
+ expect(call).not.toHaveBeenCalledWith('stop_remote_server')
+ await expect(useRemoteStore.getState().startServer()).rejects.toThrow('starting or stopping')
+ native.resolve(started)
+ await cancelled
+ await stop
+ expect(call).toHaveBeenCalledWith('stop_remote_server')
+ expect(call).not.toHaveBeenCalledWith('remote_qr_code')
+ expect(useRemoteStore.getState().enabled).toBe(false)
+ expect(useRemoteStore.getState().loading).toBe(false)
+ expect(useRemoteStore.getState().qrVisible).toBe(false)
+ })
+
+ it('cancels during enrichment without sending a native start', async () => {
+ const context = deferred<string>()
+ const pending = vi.fn(() => context.promise)
+ useMemoryStore.setState({ getMemoriesForPromptAsync: pending })
+ const start = useRemoteStore.getState().startServer()
+ const cancelled = expect(start).rejects.toThrow('cancelled by a stop request')
+ await vi.waitFor(() => expect(pending).toHaveBeenCalled())
+ const stop = useRemoteStore.getState().stopServer()
+ context.resolve('Synthetic context')
+ await cancelled
+ await stop
+ expect(call.mock.calls.some(([name]) => name === 'start_remote_server')).toBe(false)
+ expect(useRemoteStore.getState().enabled).toBe(false)
+ })
+
+ it('retains the running state if stop after startup fails', async () => {
+ const native = deferred<typeof started>()
+ call.mockImplementation(async name => {
+ if (name === 'start_remote_server') return native.promise
+ if (name === 'stop_remote_server') throw new Error('Synthetic stop failure')
+ return started
+ })
+ const start = useRemoteStore.getState().startServer()
+ const cancelled = expect(start).rejects.toThrow('cancelled by a stop request')
+ await vi.waitFor(() => expect(call.mock.calls.some(([name]) => name === 'start_remote_server')).toBe(true))
+ const stop = useRemoteStore.getState().stopServer()
+ native.resolve(started)
+ await cancelled
+ await stop
+ expect(useRemoteStore.getState().enabled).toBe(true)
+ expect(useRemoteStore.getState().error).toContain('Synthetic stop failure')
+ expect(useRemoteStore.getState().qrVisible).toBe(false)
+ })
+
it('revokes a running native snapshot discovered after frontend state was lost', async () => {
call.mockResolvedValue({ ...started, running: true })
await useRemoteStore.getState().refreshStatus()
diff --git a/src/stores/remoteStore.ts b/src/stores/remoteStore.ts
index 3c12e27d..411e0455 100644
--- a/src/stores/remoteStore.ts
+++ b/src/stores/remoteStore.ts
@@ -9,6 +9,14 @@ export const REMOTE_MEMORY_CHANGED = 'Remote memory changed. Restart Remote Acce
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 lifecycleRevision = 0
+const REMOTE_START_CANCELLED = 'Remote startup was cancelled by a stop request.'
+let pendingStartup: Promise<void> | null = null
+let stopsInProgress = 0
+function trackStartup(): () => void {
+ let finish!: () => void
+ pendingStartup = new Promise<void>(resolve => { finish = resolve })
+ return () => { pendingStartup = null; finish() }
+}
let revocationPending: Promise<void> = Promise.resolve()
async function waitForMemoryRevocation(ignoreFailure = false): Promise<void> {
@@ -263,7 +271,7 @@ export const useRemoteStore = create<RemoteState>()((set, get) => ({
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 (get().loading || pendingStartup || stopsInProgress > 0) throw new Error('Remote Access is already starting or stopping. 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,
@@ -272,11 +280,13 @@ export const useRemoteStore = create<RemoteState>()((set, get) => ({
set({ loading: false, enabled: false, error: REMOTE_DEV_MODE_ERROR })
throw new Error(REMOTE_DEV_MODE_ERROR)
}
- lifecycleRevision += 1
+ const startupRevision = ++lifecycleRevision
+ const finishStartup = trackStartup()
set({ loading: true, error: null })
let serverStarted = false
try {
await waitForMemoryRevocation()
+ if (startupRevision !== lifecycleRevision) throw new Error(REMOTE_START_CANCELLED)
const revision = memoryRevision
const args: Record<string, unknown> = {}
// #87: tell the Rust proxy which backend serves the dispatched model so
@@ -292,6 +302,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 (startupRevision !== lifecycleRevision) throw new Error(REMOTE_START_CANCELLED)
if (revision !== memoryRevision) throw new Error(REMOTE_MEMORY_CHANGED)
if (enriched) args.systemPrompt = enriched
const result = await backendCall<{
@@ -303,6 +314,10 @@ export const useRemoteStore = create<RemoteState>()((set, get) => ({
permissions?: RemotePermissions
}>('start_remote_server', args)
serverStarted = true
+ if (startupRevision !== lifecycleRevision) {
+ set({ enabled: true, qrVisible: false })
+ throw new Error(REMOTE_START_CANCELLED)
+ }
// 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) {
@@ -334,15 +349,22 @@ 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.
- 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) })
+ const memoryFailure = err instanceof Error && [REMOTE_MEMORY_CHANGED, REMOTE_MEMORY_UNCONFIRMED, REMOTE_START_CANCELLED].includes(err.message)
+ set({ loading: stopsInProgress > 0, enabled: (serverStarted || memoryFailure) && get().enabled, error: String(err) })
throw err
+ } finally {
+ finishStartup()
}
},
stopServer: async () => {
lifecycleRevision += 1
+ stopsInProgress += 1
+ set({ loading: true, qrVisible: false })
try {
+ // Stopping before native startup returns can miss the server handle.
+ // Fence its result first, then stop after that attempt has settled.
+ if (pendingStartup) await pendingStartup
await backendCall('stop_remote_server')
// A confirmed explicit stop also permits recovery from failed IPC.
await waitForMemoryRevocation(true)
@@ -363,6 +385,9 @@ export const useRemoteStore = create<RemoteState>()((set, get) => ({
})
} catch (err) {
set({ error: String(err) })
+ } finally {
+ stopsInProgress -= 1
+ set({ loading: stopsInProgress > 0 })
}
},
@@ -546,16 +571,18 @@ 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 (get().loading || pendingStartup || stopsInProgress > 0) throw new Error('Remote Access is already starting or stopping. Wait for it to finish.')
if (!isTauri()) {
set({ loading: false, enabled: false, error: REMOTE_DEV_MODE_ERROR })
throw new Error(REMOTE_DEV_MODE_ERROR)
}
- lifecycleRevision += 1
+ const startupRevision = ++lifecycleRevision
+ const finishStartup = trackStartup()
set({ loading: true, error: null })
let serverStarted = false
try {
await waitForMemoryRevocation()
+ if (startupRevision !== lifecycleRevision) throw new Error(REMOTE_START_CANCELLED)
const revision = memoryRevision
const args: Record<string, unknown> = {}
// #87: same backend derivation as startServer so a restart keeps routing
@@ -569,6 +596,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 (startupRevision !== lifecycleRevision) throw new Error(REMOTE_START_CANCELLED)
if (revision !== memoryRevision) throw new Error(REMOTE_MEMORY_CHANGED)
if (enriched) args.systemPrompt = enriched
const result = await backendCall<{
@@ -580,6 +608,10 @@ export const useRemoteStore = create<RemoteState>()((set, get) => ({
permissions?: RemotePermissions
}>('restart_remote_server', args)
serverStarted = true
+ if (startupRevision !== lifecycleRevision) {
+ set({ enabled: true, qrVisible: false })
+ throw new Error(REMOTE_START_CANCELLED)
+ }
if (revision !== memoryRevision) {
set({ enabled: true })
await revokeRemoteMemory()
@@ -608,9 +640,11 @@ 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.
- 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) })
+ const memoryFailure = err instanceof Error && [REMOTE_MEMORY_CHANGED, REMOTE_MEMORY_UNCONFIRMED, REMOTE_START_CANCELLED].includes(err.message)
+ set({ loading: stopsInProgress > 0, enabled: (serverStarted || memoryFailure) && get().enabled, error: String(err) })
throw err
+ } finally {
+ finishStartup()
}
},