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.

Recover Remote state during pending native operations

Davidb92a5f29beaf
diff --git a/e2e/remote-memory.spec.ts b/e2e/remote-memory.spec.ts
index 1c8610d5..0f0a7bff 100644
--- a/e2e/remote-memory.spec.ts
+++ b/e2e/remote-memory.spec.ts
@@ -1,5 +1,27 @@
import { expect, test } from '@playwright/test'
+test('app recovery stops a native operation whose startup outlived the frontend', async ({ page }) => {
+ let release!: () => void
+ let stopCalls = 0
+ const nativeFinished = new Promise<void>(resolve => { release = resolve })
+ await page.exposeFunction('remoteNativeProof', async (command: string) => {
+ if (command === 'remote_server_status') return { running: false, lifecycleBusy: true }
+ if (command === 'stop_remote_server') { stopCalls += 1; await nativeFinished; return null }
+ throw new Error('Unsupported proof command')
+ })
+ 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 expect(page.getByRole('status')).toContainText('Recovering an unfinished Remote operation')
+ await expect.poll(() => stopCalls).toBe(1)
+ release()
+ await expect(page.getByRole('status')).toContainText('was stopped during recovery')
+ await expect(page.locator('#remote-state')).toHaveText('{"enabled":false,"qrVisible":false}')
+})
+
test('stop waits for a pending native start and never publishes its QR', async ({ page }) => {
const calls: string[] = []
let running = false
diff --git a/src-tauri/src/commands/remote.rs b/src-tauri/src/commands/remote.rs
index dd6f175e..630fd7a0 100644
--- a/src-tauri/src/commands/remote.rs
+++ b/src-tauri/src/commands/remote.rs
@@ -2583,6 +2583,8 @@ struct RemoteLifecycle(Arc<TokioMutex<()>>);
impl RemoteLifecycle {
fn new() -> Self { Self(Arc::new(TokioMutex::new(()))) }
+ fn is_busy(&self) -> bool { self.0.try_lock().is_err() }
+
async fn acquire(&self) -> Result<tokio::sync::OwnedMutexGuard<()>, String> {
self.acquire_with_timeout(std::time::Duration::from_secs(15)).await
}
@@ -2907,10 +2909,11 @@ async fn stop_remote_server_inner(
pub async fn remote_server_status(
state: tauri::State<'_, crate::state::AppState>,
) -> Result<serde_json::Value, String> {
- let (running, port, passcode_arc, tunnel_url_arc, tunnel_pid, permissions_arc) = {
+ let (running, lifecycle_busy, port, passcode_arc, tunnel_url_arc, tunnel_pid, permissions_arc) = {
let remote = state.remote.lock().map_err(|e| e.to_string())?;
(
remote.handle.is_some(),
+ remote.lifecycle.is_busy(),
remote.port,
remote.passcode.clone(),
remote.tunnel_url.clone(),
@@ -2944,6 +2947,7 @@ pub async fn remote_server_status(
Ok(serde_json::json!({
"running": running,
+ "lifecycleBusy": lifecycle_busy,
"port": port,
"passcode": if running { passcode } else { String::new() },
"passcodeExpiresAt": if running { expires_at } else { 0 },
@@ -3457,11 +3461,14 @@ mod memory_revocation_tests {
#[tokio::test]
async fn lifecycle_wait_is_bounded_and_timeout_does_not_poison_queue() {
let lifecycle = RemoteLifecycle::new();
+ assert!(!lifecycle.is_busy());
let held = lifecycle.acquire().await.unwrap();
+ assert!(lifecycle.is_busy());
let result = lifecycle.acquire_with_timeout(std::time::Duration::from_millis(10)).await;
assert!(result.is_err());
assert!(result.unwrap_err().contains("Remote lifecycle is busy"));
drop(held);
+ assert!(!lifecycle.is_busy());
let recovered = lifecycle.acquire().await.unwrap();
drop(recovered);
}
diff --git a/src/stores/__tests__/remote-memory-revocation.test.ts b/src/stores/__tests__/remote-memory-revocation.test.ts
index c7280422..2a131688 100644
--- a/src/stores/__tests__/remote-memory-revocation.test.ts
+++ b/src/stores/__tests__/remote-memory-revocation.test.ts
@@ -32,6 +32,26 @@ afterEach(async () => {
})
describe('automatic Remote memory revocation', () => {
+ it('stops an unknown busy native operation before accepting recovered state', async () => {
+ call.mockResolvedValue({ ...started, running: false, lifecycleBusy: true })
+ await useRemoteStore.getState().refreshStatus()
+ expect(call).toHaveBeenCalledWith('stop_remote_server')
+ expect(useRemoteStore.getState().enabled).toBe(false)
+ expect(useRemoteStore.getState().memoryNotice).toContain('was stopped during recovery')
+ })
+
+ it('retains an uncertain running state when busy recovery cannot stop native work', async () => {
+ call.mockImplementation(async name => {
+ if (name === 'stop_remote_server') throw new Error('Synthetic busy failure')
+ return { ...started, running: false, lifecycleBusy: true }
+ })
+ await useRemoteStore.getState().refreshStatus()
+ expect(useRemoteStore.getState().enabled).toBe(true)
+ expect(useRemoteStore.getState().memoryNotice).toContain('could not be stopped')
+ expect(useRemoteStore.getState().memoryNotice).not.toContain('Synthetic busy failure')
+ expect(useRemoteStore.getState().qrVisible).toBe(false)
+ })
+
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'
diff --git a/src/stores/remoteStore.ts b/src/stores/remoteStore.ts
index 411e0455..cf59db39 100644
--- a/src/stores/remoteStore.ts
+++ b/src/stores/remoteStore.ts
@@ -234,7 +234,7 @@ interface RemoteState {
qrVisible: boolean
startServer: (model?: string, systemPrompt?: string) => Promise<void>
- stopServer: () => Promise<void>
+ stopServer: () => Promise<boolean>
refreshStatus: () => Promise<void>
refreshDevices: () => Promise<void>
regenerateToken: () => Promise<void>
@@ -371,6 +371,8 @@ export const useRemoteStore = create<RemoteState>()((set, get) => ({
revocationPending = Promise.resolve()
set({
enabled: false,
+ error: null,
+ memoryNotice: null,
passcode: '',
passcodeExpiresAt: 0,
lanUrl: '',
@@ -383,8 +385,10 @@ export const useRemoteStore = create<RemoteState>()((set, get) => ({
dispatchedConversationId: null,
qrVisible: false,
})
+ return true
} catch (err) {
set({ error: String(err) })
+ return false
} finally {
stopsInProgress -= 1
set({ loading: stopsInProgress > 0 })
@@ -397,6 +401,7 @@ export const useRemoteStore = create<RemoteState>()((set, get) => ({
try {
const status = await backendCall<{
running: boolean
+ lifecycleBusy?: boolean
port: number
passcode: string
passcodeExpiresAt: number
@@ -409,6 +414,18 @@ export const useRemoteStore = create<RemoteState>()((set, get) => ({
// A response requested before a start/stop must not resurrect stale UI
// state or revoke the freshly started replacement session.
if (revision !== lifecycleRevision || get().loading) return
+ if (status.lifecycleBusy === true) {
+ // No local startup is active, so this operation belongs to an older
+ // frontend or another caller. Stop it before accepting its snapshot.
+ set({ enabled: true, qrVisible: false, passcode: '', qrPngBase64: '',
+ memoryNotice: 'Recovering an unfinished Remote operation. Stopping it before reconnecting...' })
+ const stopped = await get().stopServer()
+ const notice = stopped
+ ? 'An unfinished Remote operation was stopped during recovery. Start Remote Access again to continue.'
+ : 'An unfinished Remote operation could not be stopped. Stop Remote Access on the desktop before reconnecting.'
+ set({ memoryNotice: notice, error: stopped ? null : notice })
+ return
+ }
const unknownRunningSnapshot = status.running && !get().enabled
const next: Partial<RemoteState> = {
enabled: status.running,