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.

fix(remote): stop-everything on chat close, gate QR on tunnel, 1-click LAN allow

purple323e0f8a6f5d
diff --git a/src-tauri/src/commands/remote.rs b/src-tauri/src/commands/remote.rs
index 827dce4c..6982590d 100644
--- a/src-tauri/src/commands/remote.rs
+++ b/src-tauri/src/commands/remote.rs
@@ -3767,6 +3767,92 @@ fn ensure_lan_firewall_rule(port: u16) {
#[cfg(not(target_os = "windows"))]
fn ensure_lan_firewall_rule(_port: u16) {}
+/// User-triggered, ELEVATED counterpart to `ensure_lan_firewall_rule`. The
+/// best-effort version can't elevate, so a per-user install's inbound rule
+/// never gets created and a phone on the same Wi-Fi can't reach the (correct)
+/// LAN URL — David 2026-06-15: "manual URL works on the PC but not the phone".
+/// This relaunches `netsh` via a UAC prompt to add the rule once, then verifies
+/// it landed in a locale-independent way (exit code + port match, since David's
+/// Windows is German and netsh's text is localized).
+#[tauri::command]
+pub async fn allow_lan_access(port: Option<u16>) -> Result<String, String> {
+ let port = port.unwrap_or(11435);
+ #[cfg(target_os = "windows")]
+ {
+ use std::os::windows::process::CommandExt;
+ use std::process::Command;
+ const CREATE_NO_WINDOW: u32 = 0x08000000;
+ let name = format!("Locally Uncensored Remote {}", port);
+
+ // A tiny .cmd lets cmd.exe parse the spaced, quoted rule name natively
+ // — avoids the PowerShell→netsh nested-quoting trap entirely.
+ let script = format!(
+ "@echo off\r\n\
+ netsh advfirewall firewall delete rule name=\"{name}\" >nul 2>&1\r\n\
+ netsh advfirewall firewall add rule name=\"{name}\" dir=in action=allow protocol=TCP localport={port} profile=private,domain\r\n",
+ name = name, port = port
+ );
+ let cmd_path = std::env::temp_dir().join("lu_allow_lan.cmd");
+ std::fs::write(&cmd_path, script)
+ .map_err(|e| format!("Could not write helper script: {}", e))?;
+
+ // Relaunch the .cmd elevated (UAC). -Wait so we know when it finished;
+ // a cancelled UAC makes Start-Process throw → powershell exits non-zero.
+ let ps = format!(
+ "Start-Process -FilePath '{}' -Verb RunAs -WindowStyle Hidden -Wait",
+ cmd_path.display()
+ );
+ let out = Command::new("powershell")
+ .args(["-NoProfile", "-WindowStyle", "Hidden", "-Command", &ps])
+ .creation_flags(CREATE_NO_WINDOW)
+ .output()
+ .map_err(|e| format!("Could not launch elevated helper: {}", e))?;
+ let ps_ok = out.status.success();
+ let ps_err = String::from_utf8_lossy(&out.stderr).trim().to_string();
+
+ // Verify the rule exists now. Reading rules needs no admin. netsh
+ // returns a non-zero exit when no rule matches, and the port number is
+ // locale-independent — check both so a German Windows can't fool us.
+ let check = Command::new("netsh")
+ .args(["advfirewall", "firewall", "show", "rule", &format!("name={}", name)])
+ .creation_flags(CREATE_NO_WINDOW)
+ .output();
+ let exists = match check {
+ Ok(o) => o.status.success()
+ || String::from_utf8_lossy(&o.stdout).contains(&port.to_string()),
+ Err(_) => false,
+ };
+
+ let _ = std::fs::remove_file(&cmd_path); // best-effort cleanup
+
+ if exists {
+ Ok(format!(
+ "LAN access enabled (inbound TCP {port} allowed). Re-scan the QR on your phone — same Wi-Fi."
+ ))
+ } else if !ps_ok {
+ Err(format!(
+ "Permission was declined, so LAN access wasn't changed{}. Click again and accept the Windows prompt, or run this once in an Admin PowerShell:\n\
+ netsh advfirewall firewall add rule name=\"{name}\" dir=in action=allow protocol=TCP localport={port}",
+ if ps_err.is_empty() { String::new() } else { format!(" ({})", ps_err) },
+ name = name, port = port
+ ))
+ } else {
+ Err(format!(
+ "Tried to allow LAN access but couldn't confirm the firewall rule. Run this once in an Admin PowerShell:\n\
+ netsh advfirewall firewall add rule name=\"{name}\" dir=in action=allow protocol=TCP localport={port}",
+ name = name, port = port
+ ))
+ }
+ }
+ #[cfg(not(target_os = "windows"))]
+ {
+ Ok(format!(
+ "Automatic firewall setup is Windows-only. On Linux/macOS, allow inbound TCP {} in your system firewall (e.g. `sudo ufw allow {}/tcp`).",
+ port, port
+ ))
+ }
+}
+
#[tauri::command]
pub async fn start_remote_server(
app: AppHandle,
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 65778b56..9e919866 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -199,6 +199,7 @@ fn main() {
commands::remote::start_tunnel,
commands::remote::stop_tunnel,
commands::remote::tunnel_status,
+ commands::remote::allow_lan_access,
// Proxy
commands::proxy::ollama_search,
commands::proxy::fetch_external,
diff --git a/src/components/layout/Sidebar.tsx b/src/components/layout/Sidebar.tsx
index 87b90176..3ce01b9e 100644
--- a/src/components/layout/Sidebar.tsx
+++ b/src/components/layout/Sidebar.tsx
@@ -21,7 +21,7 @@ export function Sidebar() {
const {
enabled: remoteEnabled, passcode, passcodeExpiresAt, lanUrl, mobileUrl,
qrPngBase64, loading: remoteLoading, error: remoteError,
- tunnelActive, tunnelUrl, tunnelLoading,
+ tunnelActive, tunnelUrl, tunnelLoading, awaitingTunnel,
qrVisible, hideQr, refreshDevices,
dispatchedConversationId, dispatch, undispatch, regenerateToken, restart,
} = useRemoteStore()
@@ -31,6 +31,8 @@ export function Sidebar() {
const [countdown, setCountdown] = useState('')
const [dispatchPicker, setDispatchPicker] = useState(false)
const [qrModalOpen, setQrModalOpen] = useState(false)
+ const [lanFixMsg, setLanFixMsg] = useState<string | null>(null)
+ const [lanFixing, setLanFixing] = useState(false)
const isCodingMode = chatMode === 'codex'
const isRemoteMode = chatMode === 'remote'
@@ -125,6 +127,11 @@ export function Sidebar() {
const persona = personasEnabled ? getActivePersona() : null
const convId = createConversation(activeModel, persona?.systemPrompt || '', 'remote')
setView('chat')
+ // For internet mode, suppress the QR until the Cloudflare tunnel is
+ // verified up (David 2026-06-15). Set this BEFORE dispatch() so the LAN
+ // QR fetched during startServer never flashes. LAN mode shows the QR
+ // immediately (no tunnel to wait for).
+ useRemoteStore.setState({ awaitingTunnel: mode === 'internet' })
try {
await dispatch(convId, activeModel, '')
} catch {
@@ -134,10 +141,12 @@ export function Sidebar() {
// server that never came up. The error banner still surfaces in
// ChatView so the user can act on it (e.g. close another LU
// instance, then click Dispatch again).
+ useRemoteStore.setState({ awaitingTunnel: false })
deleteConversation(convId)
return
}
- // Auto-start tunnel for internet mode
+ // Auto-start tunnel for internet mode. startTunnel() clears awaitingTunnel
+ // once Cloudflare is verified serving (or it fails), which reveals the QR.
if (mode === 'internet') {
useRemoteStore.getState().startTunnel()
}
@@ -154,6 +163,23 @@ export function Sidebar() {
navigator.clipboard.writeText(text)
}
+ // One-click LAN firewall fix: relaunch netsh elevated (UAC) to add the
+ // inbound allow rule for the remote port, so a phone on the same Wi-Fi can
+ // actually reach the server (David 2026-06-15: the QR/IP were correct but
+ // Windows silently dropped the phone's connection — no inbound rule).
+ const handleAllowLan = async () => {
+ setLanFixing(true)
+ setLanFixMsg('Requesting permission (accept the Windows prompt)…')
+ try {
+ const msg = await useRemoteStore.getState().allowLanAccess()
+ setLanFixMsg(msg || 'LAN access allowed — re-scan the QR on your phone.')
+ } catch (e) {
+ setLanFixMsg(String(e))
+ } finally {
+ setLanFixing(false)
+ }
+ }
+
// Auto-hide the QR panel (a) as soon as the dispatched conversation
// receives its first message, OR (b) as soon as a mobile has authenticated.
// refreshDevices() itself sets qrVisible=false when devices.length > 0,
@@ -300,8 +326,17 @@ export function Sidebar() {
</div>
</div>
- {/* QR Code — small, clickable to open enlarged modal */}
- {qrPngBase64 && (
+ {/* QR Code — hidden until Cloudflare is verified up (internet
+ mode); shown immediately for LAN. David 2026-06-15: never
+ flash a QR that points at the LAN IP while the tunnel is
+ still coming up. */}
+ {awaitingTunnel ? (
+ <div className="w-full flex flex-col items-center justify-center gap-1 py-4 text-center">
+ <RefreshCw size={16} className="animate-spin text-emerald-400/70" />
+ <span className="text-[0.55rem] text-emerald-400/80">Connecting to Cloudflare…</span>
+ <span className="text-[0.45rem] text-gray-500 leading-snug px-2">The QR appears once the tunnel is live</span>
+ </div>
+ ) : qrPngBase64 ? (
<button
onClick={() => setQrModalOpen(true)}
title="Show large QR code"
@@ -311,7 +346,7 @@ export function Sidebar() {
<img src={`data:image/png;base64,${qrPngBase64}`} alt="QR" className="w-[72px] h-[72px]" />
</div>
</button>
- )}
+ ) : null}
{/* Passcode */}
<div className="flex items-center justify-between">
@@ -358,6 +393,26 @@ export function Sidebar() {
</p>
)}
+ {/* LAN reachability helper — only relevant for LAN dispatch.
+ Adds the Windows Firewall inbound rule (elevated UAC) so a
+ phone on the same Wi-Fi can actually reach the server. */}
+ {!tunnelActive && !awaitingTunnel && (mobileUrl || lanUrl) && (
+ <div className="pt-0.5">
+ <button
+ onClick={handleAllowLan}
+ disabled={lanFixing}
+ title="If your phone can't open the URL on the same Wi-Fi, click to allow LAN access through Windows Firewall (requires admin)"
+ className="w-full flex items-center justify-center gap-1 px-1.5 py-0.5 rounded text-[0.5rem] text-amber-400/90 hover:bg-amber-500/15 border border-amber-500/20 transition-all disabled:opacity-50"
+ >
+ <Wifi size={8} className={lanFixing ? 'animate-pulse' : ''} />
+ {lanFixing ? 'Allowing…' : "Phone can't connect? Allow LAN access"}
+ </button>
+ {lanFixMsg && (
+ <p className="text-[0.45rem] text-gray-400 leading-snug mt-0.5 break-words">{lanFixMsg}</p>
+ )}
+ </div>
+ )}
+
{remoteError && (
<p className="text-[0.5rem] text-red-400 truncate">{remoteError}</p>
)}
@@ -570,7 +625,13 @@ export function Sidebar() {
</button>
</div>
- {qrPngBase64 && (
+ {awaitingTunnel ? (
+ <div className="flex flex-col items-center justify-center gap-2 py-10 text-center">
+ <RefreshCw size={28} className="animate-spin text-emerald-400/70" />
+ <span className="text-[0.8rem] text-emerald-400/90">Connecting to Cloudflare…</span>
+ <span className="text-[0.6rem] text-gray-500">The QR appears once the tunnel is live</span>
+ </div>
+ ) : qrPngBase64 ? (
<div className="bg-white rounded-lg p-3">
<img
src={`data:image/png;base64,${qrPngBase64}`}
@@ -579,7 +640,7 @@ export function Sidebar() {
style={{ imageRendering: 'pixelated' }}
/>
</div>
- )}
+ ) : null}
<div className="flex items-center justify-center gap-3 w-full">
<code className="text-2xl font-mono font-bold text-amber-400 tracking-[8px]">{passcode}</code>
diff --git a/src/stores/chatStore.ts b/src/stores/chatStore.ts
index 58646010..88d0c077 100644
--- a/src/stores/chatStore.ts
+++ b/src/stores/chatStore.ts
@@ -6,6 +6,7 @@ import type { AgentBlock } from '../types/agent-mode'
import { idbStorage } from '../lib/idbStorage'
import { migrateBlockInPlace } from '../api/agents/block-helpers'
import { useGenerationStore } from './generationStore'
+import { useRemoteStore } from './remoteStore'
/**
* Rehydration migration for Phase 1 (v2.4.0) — wraps legacy
@@ -99,6 +100,18 @@ export const useChatStore = create<ChatState>()(
// completely — no orphaned stream burning tokens / GPU after the chat
// is gone (David 2026-06-15).
try { useGenerationStore.getState().abortConversation(id) } catch { /* best-effort */ }
+ // If this is the dispatched Remote chat, deleting/closing it must also
+ // tear down the whole Remote session — stop the axum server AND kill
+ // the Cloudflare tunnel/cloudflared process (David 2026-06-15: closing
+ // the remote chat has to stop *everything*, not leave the server +
+ // tunnel running in the background). undispatch() → stopServer() →
+ // stop_remote_server (taskkill /T /F on the tunnel PID + abort serve).
+ try {
+ const remote = useRemoteStore.getState()
+ if (remote.dispatchedConversationId === id) {
+ void remote.undispatch()
+ }
+ } catch { /* best-effort */ }
set((state) => ({
conversations: state.conversations.filter((c) => c.id !== id),
activeConversationId:
diff --git a/src/stores/remoteStore.ts b/src/stores/remoteStore.ts
index 371ccdf0..ce4af771 100644
--- a/src/stores/remoteStore.ts
+++ b/src/stores/remoteStore.ts
@@ -71,6 +71,12 @@ interface RemoteState {
tunnelActive: boolean
tunnelUrl: string
tunnelLoading: boolean
+ // True from the moment an *internet* dispatch begins until the Cloudflare
+ // tunnel either comes up or fails. While set, the UI must NOT show a QR
+ // code — David 2026-06-15: the QR may only appear once Cloudflare is
+ // actually connected (otherwise it briefly points at the LAN IP, which is
+ // useless over the internet and confused users into thinking it was broken).
+ awaitingTunnel: boolean
loading: boolean
error: string | null
// Dispatch
@@ -89,6 +95,7 @@ interface RemoteState {
setPermissions: (perms: RemotePermissions) => Promise<void>
startTunnel: () => Promise<void>
stopTunnel: () => Promise<void>
+ allowLanAccess: () => Promise<string>
dispatch: (conversationId: string, model: string, systemPrompt: string) => Promise<void>
undispatch: () => Promise<void>
restart: (model?: string, systemPrompt?: string) => Promise<void>
@@ -110,6 +117,7 @@ export const useRemoteStore = create<RemoteState>()((set, get) => ({
tunnelActive: false,
tunnelUrl: '',
tunnelLoading: false,
+ awaitingTunnel: false,
loading: false,
error: null,
dispatchedConversationId: null,
@@ -176,6 +184,7 @@ export const useRemoteStore = create<RemoteState>()((set, get) => ({
connectedDevices: [],
tunnelActive: false,
tunnelUrl: '',
+ awaitingTunnel: false,
dispatchedConversationId: null,
qrVisible: false,
})
@@ -273,11 +282,16 @@ export const useRemoteStore = create<RemoteState>()((set, get) => ({
set({ tunnelLoading: true, error: null })
try {
const url = await backendCall<string>('start_tunnel')
- set({ tunnelActive: true, tunnelUrl: url, tunnelLoading: false })
+ // Tunnel is up AND verified serving (start_tunnel polls /mobile before
+ // returning) → now it's safe to reveal the QR. Clear awaitingTunnel so
+ // the gated QR finally renders, then refresh it to the tunnel URL.
+ set({ tunnelActive: true, tunnelUrl: url, tunnelLoading: false, awaitingTunnel: false })
// Refresh QR to show tunnel URL instead of LAN IP
get().fetchQrCode()
} catch (err) {
- set({ tunnelLoading: false, error: String(err) })
+ // Tunnel failed: stop waiting so the UI falls back to the LAN QR + the
+ // error chip explains why, instead of spinning "Connecting…" forever.
+ set({ tunnelLoading: false, awaitingTunnel: false, error: String(err) })
}
},
@@ -292,6 +306,18 @@ export const useRemoteStore = create<RemoteState>()((set, get) => ({
}
},
+ // Open the LAN port in Windows Firewall so phones on the same Wi-Fi can
+ // reach the remote server. This needs admin, so the Rust side relaunches
+ // `netsh` elevated via a UAC prompt. Root cause of David's 2026-06-15
+ // "manual URL works on PC but not the phone": no inbound firewall rule
+ // existed (the QR/IP were correct all along). Returns a human-readable
+ // result for the UI to show.
+ allowLanAccess: async (): Promise<string> => {
+ if (!isTauri()) return REMOTE_DEV_MODE_ERROR
+ const port = get().port || 11435
+ return await backendCall<string>('allow_lan_access', { port })
+ },
+
dispatch: async (conversationId: string, model: string, systemPrompt: string) => {
const { enabled, stopServer, startServer } = get()
// Stop existing server if running