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(chat): Stop/delete now cancels the backend stream, not just the JS loop

purple7326aa17cf4d
diff --git a/src-tauri/src/commands/proxy.rs b/src-tauri/src/commands/proxy.rs
index 0bcfc69c..9e4b7ea4 100644
--- a/src-tauri/src/commands/proxy.rs
+++ b/src-tauri/src/commands/proxy.rs
@@ -409,59 +409,104 @@ pub async fn proxy_localhost_stream_chunked(
method: Option<String>,
body: Option<String>,
on_chunk: tauri::ipc::Channel<Vec<u8>>,
+ // Optional id so the JS side can deterministically cancel THIS stream via
+ // `cancel_proxy_stream(stream_id)`. Without it, aborting only broke the JS
+ // read-loop while Ollama kept generating to completion on the proxy path
+ // (David 2026-06-15: deleting/Stopping a chat must stop the backend too).
+ stream_id: Option<String>,
state: tauri::State<'_, crate::state::AppState>,
) -> Result<(), String> {
validate_proxy_url(&url, &state)?;
- let client = reqwest::Client::builder()
- .user_agent("LocallyUncensored/2.0")
- .timeout(std::time::Duration::from_secs(7200))
- .build()
- .map_err(|e| e.to_string())?;
+ // Register a cancellation token under stream_id (mirrors pull_tokens).
+ let token = tokio_util::sync::CancellationToken::new();
+ let registry = state.stream_tokens.clone();
+ if let Some(id) = stream_id.as_ref() {
+ if let Some(old) = registry.lock().unwrap().insert(id.clone(), token.clone()) {
+ old.cancel(); // a stale stream under the same id — cancel it first
+ }
+ }
- let http_method = method.unwrap_or_else(|| "GET".to_string());
+ // Run the actual proxying in an inner future so we can always clean the
+ // token out of the registry afterwards, regardless of how we exit.
+ let run = async move {
+ let client = reqwest::Client::builder()
+ .user_agent("LocallyUncensored/2.0")
+ .timeout(std::time::Duration::from_secs(7200))
+ .build()
+ .map_err(|e| e.to_string())?;
- let mut request = match http_method.as_str() {
- "POST" => client.post(&url),
- "DELETE" => client.delete(&url),
- "PUT" => client.put(&url),
- _ => client.get(&url),
- };
+ let http_method = method.unwrap_or_else(|| "GET".to_string());
- if let Some(body_str) = body {
- request = request.header("Content-Type", "application/json").body(body_str);
- }
+ let mut request = match http_method.as_str() {
+ "POST" => client.post(&url),
+ "DELETE" => client.delete(&url),
+ "PUT" => client.put(&url),
+ _ => client.get(&url),
+ };
- let resp = request
- .send()
- .await
- .map_err(|e| format!("proxy_localhost_stream_chunked: {}", e))?;
+ if let Some(body_str) = body {
+ request = request.header("Content-Type", "application/json").body(body_str);
+ }
- if !resp.status().is_success() {
- let status = resp.status().as_u16();
- let text = resp.text().await.unwrap_or_default();
- return Err(format!("HTTP {}: {}", status, text));
- }
+ // Race the request against cancellation even during connect/headers.
+ let resp = tokio::select! {
+ _ = token.cancelled() => return Ok(()),
+ r = request.send() => r.map_err(|e| format!("proxy_localhost_stream_chunked: {}", e))?,
+ };
- use futures_util::StreamExt;
- let mut stream = resp.bytes_stream();
- while let Some(item) = stream.next().await {
- let bytes = item.map_err(|e| e.to_string())?;
- if bytes.is_empty() {
- continue;
+ if !resp.status().is_success() {
+ let status = resp.status().as_u16();
+ let text = resp.text().await.unwrap_or_default();
+ return Err(format!("HTTP {}: {}", status, text));
}
- // If the JS side is gone (reader cancelled / window closed), stop.
- if on_chunk.send(bytes.to_vec()).is_err() {
- break;
+
+ use futures_util::StreamExt;
+ let mut stream = resp.bytes_stream();
+ loop {
+ tokio::select! {
+ // Stop fires → drop `stream`/`resp` → the HTTP connection closes
+ // → Ollama stops generating (frees the GPU). This is the fix.
+ _ = token.cancelled() => break,
+ item = stream.next() => match item {
+ Some(it) => {
+ let bytes = it.map_err(|e| e.to_string())?;
+ if bytes.is_empty() { continue; }
+ // JS side gone (reader cancelled / window closed) → stop.
+ if on_chunk.send(bytes.to_vec()).is_err() { break; }
+ }
+ None => break,
+ }
+ }
}
+ // Explicit EOF marker (empty chunk — data chunks are never empty, the
+ // loop above skips them). The JS side closes its ReadableStream on THIS,
+ // not on the command's return: WebView2 149 delivers queued channel
+ // messages AFTER the invoke result resolves (live find 2026-06-11), so
+ // closing on the result raced ahead of the data and silently dropped
+ // every chunk — chats showed the user message but never a reply.
+ let _ = on_chunk.send(Vec::new());
+ Ok(())
+ }
+ .await;
+
+ if let Some(id) = stream_id.as_ref() {
+ registry.lock().unwrap().remove(id);
+ }
+ run
+}
+
+/// Cancel an in-flight `proxy_localhost_stream_chunked` by its stream id. Fired
+/// from the JS side when the user hits Stop or deletes/closes a chat, so the
+/// upstream Ollama request is actually aborted (not just the JS read-loop).
+#[tauri::command]
+pub fn cancel_proxy_stream(
+ state: tauri::State<'_, crate::state::AppState>,
+ stream_id: String,
+) -> Result<(), String> {
+ if let Some(token) = state.stream_tokens.lock().unwrap().remove(&stream_id) {
+ token.cancel();
}
- // Explicit EOF marker (empty chunk — data chunks are never empty, the
- // loop above skips them). The JS side closes its ReadableStream on THIS,
- // not on the command's return: WebView2 149 delivers queued channel
- // messages AFTER the invoke result resolves (live find 2026-06-11), so
- // closing on the result raced ahead of the data and silently dropped
- // every chunk — chats showed the user message but never a reply.
- let _ = on_chunk.send(Vec::new());
Ok(())
}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 65778b56..9471679f 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -206,6 +206,7 @@ fn main() {
commands::proxy::proxy_localhost,
commands::proxy::proxy_localhost_stream,
commands::proxy::proxy_localhost_stream_chunked,
+ commands::proxy::cancel_proxy_stream,
commands::proxy::register_openai_host,
commands::proxy::pull_model_stream,
commands::proxy::cancel_model_pull,
diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs
index 2b542e64..0e8c8efa 100644
--- a/src-tauri/src/state.rs
+++ b/src-tauri/src/state.rs
@@ -152,6 +152,12 @@ pub struct AppState {
pub downloads: Arc<Mutex<HashMap<String, DownloadProgress>>>,
pub download_tokens: Arc<Mutex<HashMap<String, CancellationToken>>>,
pub pull_tokens: Arc<Mutex<HashMap<String, CancellationToken>>>,
+ /// Per-stream cancellation tokens for `proxy_localhost_stream_chunked`.
+ /// When the user hits Stop or deletes/closes a chat, the JS side calls
+ /// `cancel_proxy_stream(stream_id)` → the token fires → the upstream reqwest
+ /// stream is dropped → Ollama actually stops generating (David 2026-06-15:
+ /// "Aktivität komplett stoppen"; aborting only stopped the JS loop before).
+ pub stream_tokens: Arc<Mutex<HashMap<String, CancellationToken>>>,
pub install_status: Arc<Mutex<InstallState>>,
/// Cancel flag for the ComfyUI installer (Bug #1, techx69 v2.4.3).
/// `install_comfyui` polls this between steps; setting it from
@@ -243,6 +249,7 @@ impl AppState {
downloads: Arc::new(Mutex::new(HashMap::new())),
download_tokens: Arc::new(Mutex::new(HashMap::new())),
pull_tokens: Arc::new(Mutex::new(HashMap::new())),
+ stream_tokens: Arc::new(Mutex::new(HashMap::new())),
install_status: Arc::new(Mutex::new(InstallState::default())),
comfyui_install_cancel: Arc::new(AtomicBool::new(false)),
ollama_install: Arc::new(Mutex::new(InstallState::default())),
diff --git a/src/api/backend.ts b/src/api/backend.ts
index a42a505a..28963c9e 100644
--- a/src/api/backend.ts
+++ b/src/api/backend.ts
@@ -210,7 +210,7 @@ export async function localFetchStream(
}
}
- const proxied = await proxyStreamChunked(url, method, body);
+ const proxied = await proxyStreamChunked(url, method, body, options?.signal);
if (proxied) return proxied;
// Proxy layer itself unavailable (invoke/Channel import died) — give the
@@ -242,7 +242,7 @@ export async function localFetchStream(
* Returns null when the invoke/Channel layer itself is unavailable so the
* caller can decide on a last-resort transport.
*/
-async function proxyStreamChunked(url: string, method: string, body?: string): Promise<Response | null> {
+async function proxyStreamChunked(url: string, method: string, body?: string, signal?: AbortSignal): Promise<Response | null> {
let invoke: Awaited<ReturnType<typeof getInvoke>>;
let ChannelCtor: typeof import("@tauri-apps/api/core").Channel;
try {
@@ -253,6 +253,25 @@ async function proxyStreamChunked(url: string, method: string, body?: string): P
return null;
}
+ // Deterministic backend cancellation: tag this stream with an id and, when the
+ // caller aborts (Stop button / chat delete/close), tell Rust to cancel the
+ // upstream request so Ollama actually stops generating — not just the JS loop
+ // (David 2026-06-15: "Aktivität komplett stoppen"). Without this, the proxy
+ // kept pulling from Ollama to completion after an abort, burning GPU.
+ const streamId =
+ (globalThis.crypto as Crypto | undefined)?.randomUUID?.() ??
+ `s_${Date.now()}_${Math.random().toString(36).slice(2)}`;
+ const cancelUpstream = () => { void invoke("cancel_proxy_stream", { streamId }).catch(() => { /* best-effort */ }); };
+ let onAbort: (() => void) | null = null;
+ if (signal) {
+ if (signal.aborted) cancelUpstream();
+ else {
+ onAbort = () => cancelUpstream();
+ signal.addEventListener("abort", onAbort, { once: true });
+ }
+ }
+ const detachAbort = () => { if (signal && onAbort) { signal.removeEventListener("abort", onAbort); onAbort = null; } };
+
try {
const channel = new ChannelCtor<number[]>();
let ctrl: ReadableStreamDefaultController<Uint8Array> | null = null;
@@ -263,6 +282,7 @@ async function proxyStreamChunked(url: string, method: string, body?: string): P
const closeStream = () => {
if (closed) return;
closed = true;
+ detachAbort();
try { ctrl?.close(); } catch { /* already closed */ }
};
@@ -293,7 +313,7 @@ async function proxyStreamChunked(url: string, method: string, body?: string): P
settleStreaming();
};
- void invoke("proxy_localhost_stream_chunked", { url, method, body: body || null, onChunk: channel })
+ void invoke("proxy_localhost_stream_chunked", { url, method, body: body || null, onChunk: channel, streamId })
.then(() => {
// Do NOT close here — the EOF marker does that (it may arrive after
// this resolves; see above). Grace fallback so a lost EOF can't leak
@@ -312,6 +332,7 @@ async function proxyStreamChunked(url: string, method: string, body?: string): P
? new Response(httpErr.body, { status: httpErr.status })
: new Response(JSON.stringify({ error: msg }), { status: 503 }));
closed = true;
+ detachAbort();
// If a reader is already consuming (mid-stream death), surface there too.
try { ctrl?.error(err instanceof Error ? err : new Error(msg)); } catch { /* no reader */ }
});
@@ -319,6 +340,7 @@ async function proxyStreamChunked(url: string, method: string, body?: string): P
return await settled;
} catch (chanErr) {
// Channel unavailable → legacy buffered proxy (still works, just not streamed).
+ detachAbort();
log.warn('[localFetchStream] Channel stream unavailable, buffering via proxy', { err: String(chanErr) });
try {
const bytes = await invoke("proxy_localhost_stream", {