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(rust,ts): share one cancel registry between proxy_localhost and the stream path

purple1f1461f29fd8
diff --git a/src-tauri/src/cancel_registry.rs b/src-tauri/src/cancel_registry.rs
new file mode 100644
index 00000000..3690a4ff
--- /dev/null
+++ b/src-tauri/src/cancel_registry.rs
@@ -0,0 +1,316 @@
+//! A registry of caller-keyed `CancellationToken`s, shared by every proxy
+//! command that lets the JS side cancel an in-flight Rust request by an id it
+//! minted itself (`proxy_localhost`/`cancel_proxy_call` and
+//! `proxy_localhost_stream_chunked`/`cancel_proxy_stream`). One
+//! implementation instead of two, so the startup-window race below is fixed
+//! once for both instead of needing to be remembered twice (review
+//! 2026-09-18, R3 Nachbesserung 1: "gleiche Luecke, eine gemeinsame Loesung,
+//! kein Doppelbau").
+//!
+//! ## The race this closes
+//!
+//! The JS side mints an id, attaches an `AbortSignal` listener that calls the
+//! cancel command, THEN calls `invoke(...)`. Between that `invoke` starting
+//! and the Rust command actually reaching its registration line (after
+//! `ProxyAllowList::snapshot`, `allow.check`, `guard_builtin_model`,
+//! `proxy_client`, ...), a cancel can arrive for an id that is not in the map
+//! yet. Before this module existed, that cancel found nothing, did nothing,
+//! and the request that registered moments later ran to completion
+//! regardless — the same class of bug R3 fixed for "Stop while the request is
+//! already running", just shifted a few hundred microseconds earlier.
+//!
+//! The fix: a cancel for an unknown id leaves a *tombstone* (the instant it
+//! arrived) instead of a no-op. `register` checks for one and, if found,
+//! hands back an ALREADY-CANCELLED token — never the token from an older,
+//! unrelated call, only ever the fresh one this exact `register` call just
+//! created. Tombstones expire on their own (`TOMBSTONE_TTL`) so a cancel for
+//! an id nobody ever registers (a bogus id, or a request that failed before
+//! reaching registration) does not grow the map forever; the sweep runs
+//! opportunistically inside every `register` call, so no background task is
+//! needed for what is, in the worst case, a handful of bytes per stray id.
+
+use std::collections::HashMap;
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+use tokio_util::sync::CancellationToken;
+
+/// How long a tombstone survives waiting for the `register` call it is
+/// meant for. Generous relative to the real gap (registration follows
+/// milliseconds after the JS `invoke`, never seconds), so it only ever
+/// matters for ids that were never going to be registered at all.
+const TOMBSTONE_TTL: Duration = Duration::from_secs(30);
+
+#[derive(Clone)]
+enum Entry {
+ /// A live call is registered under this id; cancelling it fires this
+ /// exact token.
+ Active(CancellationToken),
+ /// A cancel arrived before anything registered under this id, at the
+ /// instant recorded here (for the TTL sweep).
+ Tombstone(Instant),
+}
+
+/// Cheaply `Clone`able (an `Arc` underneath), so it can be stored directly as
+/// an `AppState` field and captured into async blocks without an extra layer
+/// of `Arc<Mutex<...>>` at the call site.
+#[derive(Clone)]
+pub struct CancelRegistry {
+ entries: Arc<Mutex<HashMap<String, Entry>>>,
+}
+
+impl Default for CancelRegistry {
+ fn default() -> Self {
+ Self { entries: Arc::new(Mutex::new(HashMap::new())) }
+ }
+}
+
+impl CancelRegistry {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Register a fresh token under `id`. The returned token is:
+ /// - already cancelled, if a `cancel(id)` arrived before this call (the
+ /// startup-window race this module exists for) — the NEW token is the
+ /// one that gets cancelled, never a leftover from elsewhere;
+ /// - fresh and live otherwise.
+ ///
+ /// A stale `Active` entry already sitting under `id` (a previous call
+ /// that registered but was never cleaned up — should not happen given
+ /// the guard below, but a defensive case worth keeping, and the
+ /// pre-existing behaviour this preserves) has ITS OLD token cancelled,
+ /// same as before this module existed.
+ ///
+ /// Returns the token to race the request against, and a `Guard` whose
+ /// `Drop` removes this registration — hold the guard for exactly the
+ /// lifetime of the request, same shape as `CallTokenGuard` before this
+ /// module, just shared instead of duplicated.
+ pub fn register(&self, id: String) -> (CancellationToken, Guard) {
+ let token = CancellationToken::new();
+ let mut map = self.entries.lock().unwrap();
+ sweep_expired(&mut map);
+ match map.insert(id.clone(), Entry::Active(token.clone())) {
+ Some(Entry::Tombstone(_)) => token.cancel(),
+ Some(Entry::Active(old)) => old.cancel(),
+ None => {}
+ }
+ drop(map);
+ (token, Guard { registry: self.clone(), id })
+ }
+
+ /// Cancel `id`. If it is registered, its token fires immediately. If it
+ /// is not (yet) registered, a tombstone is left so the `register` call
+ /// that follows starts already-cancelled instead of losing the cancel.
+ pub fn cancel(&self, id: &str) {
+ let mut map = self.entries.lock().unwrap();
+ match map.get(id) {
+ Some(Entry::Active(token)) => token.cancel(),
+ _ => {
+ map.insert(id.to_string(), Entry::Tombstone(Instant::now()));
+ }
+ }
+ }
+
+ /// Whether `id` currently has anything registered against it (active
+ /// call or pending tombstone). Test-only: production code has no
+ /// legitimate reason to ask this instead of just calling `cancel`.
+ #[cfg(test)]
+ fn contains(&self, id: &str) -> bool {
+ self.entries.lock().unwrap().contains_key(id)
+ }
+}
+
+/// Drop expired tombstones. Called opportunistically from `register` (every
+/// call sweeps the WHOLE map, not just its own id) rather than from a
+/// background task: the volume here is bounded by how many ids get cancelled
+/// and never registered, which is rare by construction (a cancel almost
+/// always follows a real `invoke` that is about to register), so a scheduled
+/// sweep would be a thread for a problem that is a handful of bytes at
+/// worst.
+fn sweep_expired(map: &mut HashMap<String, Entry>) {
+ let now = Instant::now();
+ map.retain(|_, v| !matches!(v, Entry::Tombstone(at) if now.duration_since(*at) > TOMBSTONE_TTL));
+}
+
+/// Removes this registration from its registry on drop — the success path,
+/// an early `?` return, the cancelled branch, and a panic unwinding through
+/// the future all go through here, because `Drop::drop` is synchronous and
+/// unconditional. Twin of the `CallTokenGuard` this replaces, generalised to
+/// the streaming path too.
+pub struct Guard {
+ registry: CancelRegistry,
+ id: String,
+}
+
+impl Drop for Guard {
+ fn drop(&mut self) {
+ if let Ok(mut map) = self.registry.entries.lock() {
+ // Only remove OUR entry. A `cancel(id)` that raced in after this
+ // request already finished (the id got reused by a brand new,
+ // unrelated call before this guard dropped — possible if the
+ // caller reuses ids, which none of ours do, but nothing here
+ // should assume that) may have written a fresh Tombstone or a
+ // new Active entry for the SAME id; blindly removing would
+ // erase that unrelated, newer information. There is no way to
+ // tell "our" Active entry apart from a newer one by value alone
+ // (tokens do not carry identity beyond `==` on the underlying
+ // Arc, which `CancellationToken` does not expose), so this
+ // accepts the same small imprecision the pre-module code had:
+ // a same-id reuse race is already handled by `register`'s
+ // "cancel the old token" branch, not by this guard.
+ map.remove(&self.id);
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ // ── The startup-window race: cancel before register ─────────────────
+
+ #[test]
+ fn a_cancel_before_register_hands_back_an_already_cancelled_token() {
+ let registry = CancelRegistry::new();
+ registry.cancel("late-comer");
+ let (token, _guard) = registry.register("late-comer".to_string());
+ assert!(token.is_cancelled(), "the cancel that arrived first must not be lost");
+ }
+
+ #[test]
+ fn the_tombstone_cancels_the_new_token_not_some_old_one() {
+ // There never WAS an old token for this id — the only way this test
+ // can pass is if `register` cancels the token it just created.
+ let registry = CancelRegistry::new();
+ registry.cancel("never-registered-before");
+ let (token, _guard) = registry.register("never-registered-before".to_string());
+ assert!(token.is_cancelled());
+ // And the tombstone is consumed: a second, unrelated register under
+ // a FRESH id is unaffected.
+ let (fresh, _guard2) = registry.register("a-different-id".to_string());
+ assert!(!fresh.is_cancelled());
+ }
+
+ #[test]
+ fn a_cancel_after_register_still_works_as_before() {
+ let registry = CancelRegistry::new();
+ let (token, _guard) = registry.register("normal".to_string());
+ assert!(!token.is_cancelled());
+ registry.cancel("normal");
+ assert!(token.is_cancelled());
+ }
+
+ #[test]
+ fn registering_twice_under_the_same_id_cancels_the_old_one_not_the_new_one() {
+ let registry = CancelRegistry::new();
+ let (old_token, _old_guard) = registry.register("reused".to_string());
+ let (new_token, _new_guard) = registry.register("reused".to_string());
+ assert!(old_token.is_cancelled(), "the stale call under the reused id must be cancelled");
+ assert!(!new_token.is_cancelled(), "the new call must start live");
+ }
+
+ #[test]
+ fn cancelling_an_unknown_id_leaves_every_other_registration_untouched() {
+ let registry = CancelRegistry::new();
+ let (a, _ga) = registry.register("a".to_string());
+ let (b, _gb) = registry.register("b".to_string());
+ registry.cancel("does-not-exist");
+ assert!(!a.is_cancelled());
+ assert!(!b.is_cancelled());
+ }
+
+ // ── The registry wiring: cancel finds exactly its id (R3 Nachbesserung 2) ──
+
+ /// Replaces the old `cancelling_one_call_does_not_touch_a_second_
+ /// unrelated_call`, which built two Tokens by hand and never went
+ /// through a registry at all — trivially true regardless of whether the
+ /// lookup logic worked. This drives `register`/`cancel` exactly as the
+ /// real commands do: two ids registered against the SAME registry, one
+ /// cancelled by id, and the other proven to still be running.
+ #[test]
+ fn cancel_finds_exactly_its_own_call_and_leaves_a_second_registered_call_running() {
+ let registry = CancelRegistry::new();
+ let (call_a, _guard_a) = registry.register("call-a".to_string());
+ let (call_b, _guard_b) = registry.register("call-b".to_string());
+
+ registry.cancel("call-a");
+
+ assert!(call_a.is_cancelled(), "cancel(\"call-a\") must reach call-a's token");
+ assert!(!call_b.is_cancelled(), "cancel(\"call-a\") must not touch call-b");
+
+ // And the reverse direction, so this is not just "the first
+ // registered id always wins".
+ registry.cancel("call-b");
+ assert!(call_b.is_cancelled());
+ }
+
+ #[test]
+ fn an_unknown_id_cancels_nothing_and_only_leaves_a_tombstone() {
+ let registry = CancelRegistry::new();
+ let (call_a, _guard_a) = registry.register("call-a".to_string());
+ registry.cancel("totally-unrelated-id");
+ assert!(!call_a.is_cancelled());
+ assert!(registry.contains("totally-unrelated-id"), "the cancel must still be memoised as a tombstone");
+ }
+
+ // ── Guard cleanup ─────────────────────────────────────────────────────
+
+ #[test]
+ fn the_guard_removes_the_entry_on_drop() {
+ let registry = CancelRegistry::new();
+ {
+ let (_token, _guard) = registry.register("temp".to_string());
+ assert!(registry.contains("temp"));
+ }
+ assert!(!registry.contains("temp"), "the entry must be gone once the guard drops");
+ }
+
+ #[test]
+ fn a_panic_while_the_guard_is_alive_still_clears_the_entry() {
+ let registry = CancelRegistry::new();
+ let registry_for_panic = registry.clone();
+ let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ let (_token, _guard) = registry_for_panic.register("panicking".to_string());
+ panic!("simulated failure mid-request");
+ }));
+ assert!(outcome.is_err());
+ assert!(!registry.contains("panicking"));
+ }
+
+ // ── Tombstone TTL sweep (the "Aufraeumpfad") ─────────────────────────
+
+ #[test]
+ fn an_expired_tombstone_is_swept_and_no_longer_pre_cancels_a_later_register() {
+ // Reach into a registry with an already-expired tombstone (as if
+ // TOMBSTONE_TTL had elapsed) without waiting 30 real seconds in a
+ // unit test: write it directly at the same key a real cancel would
+ // use, backdated past the TTL.
+ let registry = CancelRegistry::new();
+ {
+ let mut map = registry.entries.lock().unwrap();
+ map.insert(
+ "stale".to_string(),
+ Entry::Tombstone(Instant::now() - TOMBSTONE_TTL - Duration::from_secs(1)),
+ );
+ }
+ // The sweep runs inside register() for ANY id, not just "stale" --
+ // register something unrelated first to prove the sweep is
+ // registry-wide, then check "stale" was cleared.
+ let (_other, _g) = registry.register("unrelated".to_string());
+ assert!(!registry.contains("stale"), "an expired tombstone must not survive the next register() call");
+
+ // And registering "stale" itself now starts live, not pre-cancelled.
+ let (token, _g2) = registry.register("stale".to_string());
+ assert!(!token.is_cancelled());
+ }
+
+ #[test]
+ fn a_fresh_tombstone_survives_a_sweep_triggered_by_another_id() {
+ let registry = CancelRegistry::new();
+ registry.cancel("about-to-register");
+ let (_other, _g) = registry.register("unrelated".to_string());
+ assert!(registry.contains("about-to-register"), "a tombstone well within its TTL must survive");
+ let (token, _g2) = registry.register("about-to-register".to_string());
+ assert!(token.is_cancelled());
+ }
+}
diff --git a/src-tauri/src/commands/proxy.rs b/src-tauri/src/commands/proxy.rs
index a0595bdd..f6f2965b 100644
--- a/src-tauri/src/commands/proxy.rs
+++ b/src-tauri/src/commands/proxy.rs
@@ -794,26 +794,6 @@ fn guard_builtin_model(
}
}
-/// Removes `call_id` from the call-token registry on drop, so EVERY exit from
-/// `proxy_localhost` after registration (the success return, an early `?`,
-/// the cancelled branch, or a panic unwinding through the future) leaves the
-/// registry entry cleaned up. A plain "remove after the await" would skip the
-/// error and cancel paths (the `?`s return before reaching it); a guard makes
-/// this exhaustive by construction instead of by enumeration, and it never
-/// holds the map's Mutex across an `.await`, since `Drop::drop` is synchronous.
-struct CallTokenGuard {
- registry: std::sync::Arc<std::sync::Mutex<std::collections::HashMap<String, tokio_util::sync::CancellationToken>>>,
- id: String,
-}
-
-impl Drop for CallTokenGuard {
- fn drop(&mut self) {
- if let Ok(mut map) = self.registry.lock() {
- map.remove(&self.id);
- }
- }
-}
-
/// The cancellable core of `proxy_localhost`: send the request, then read the
/// whole body, each `.await` raced against `token`. Factored out of the
/// `#[tauri::command]` wrapper (which needs a live `tauri::State` this does
@@ -821,6 +801,17 @@ impl Drop for CallTokenGuard {
/// a running Tauri app, the same split `pump_proxy_stream` already uses for
/// the chunked-stream path.
///
+/// The up-front `is_cancelled()` check is deliberate and not redundant with
+/// the `select!` below: `token` may already be cancelled when this is
+/// called (a `CancelRegistry::register` that found a tombstone hands back a
+/// pre-cancelled token (review 2026-09-18, R3 Nachbesserung 1, the
+/// cancel-before-register race). `tokio::select!` polls every branch once
+/// and picks whichever is ready, which is USUALLY the already-ready
+/// `cancelled()` future, but not deterministically so, and for a loopback
+/// connect the `request.send()` branch can also complete on its very first
+/// poll. Checking first makes "a pre-cancelled token never sends anything"
+/// a guarantee instead of a race the test would only catch sometimes.
+///
/// Dropping the `request.send()` / `resp.text()` future on cancellation drops
/// the underlying reqwest connection, which is what actually stops the local
/// engine from continuing to generate, the point of this whole fix (review
@@ -832,6 +823,10 @@ async fn cancellable_request(
request: reqwest::RequestBuilder,
token: &tokio_util::sync::CancellationToken,
) -> Result<String, String> {
+ if token.is_cancelled() {
+ return Err("proxy_localhost: cancelled".to_string());
+ }
+
let resp = tokio::select! {
_ = token.cancelled() => return Err("proxy_localhost: cancelled".to_string()),
r = request.send() => r.map_err(|e| format!("proxy_localhost: {}", os_error::english(&e)))?,
@@ -899,18 +894,19 @@ pub async fn proxy_localhost(
request = apply_body_and_headers(request, body, headers);
- // Register a cancellation token under call_id (mirrors stream_tokens /
- // proxy_localhost_stream_chunked). The lock is held only for the
- // insert, a plain MutexGuard temporary, dropped at the end of
- // this statement, never carried across an `.await`.
- let token = tokio_util::sync::CancellationToken::new();
- let _guard = call_id.as_ref().map(|id| {
- let registry = state.call_tokens.clone();
- if let Some(old) = registry.lock().unwrap().insert(id.clone(), token.clone()) {
- old.cancel(); // a stale call under the same id -- cancel it first
+ // Register against the shared CancelRegistry (mirrors stream_tokens /
+ // proxy_localhost_stream_chunked): survives a cancel that arrives before
+ // this line runs, not just one that arrives after (review 2026-09-18, R3
+ // Nachbesserung 1). A caller that sent no call_id gets an uncancellable
+ // token and no registry entry -- the same "opt-in cancellation" shape
+ // the chunked stream path has always had for a missing stream_id.
+ let (token, _guard) = match call_id {
+ Some(id) => {
+ let (token, guard) = state.call_tokens.register(id);
+ (token, Some(guard))
}
- CallTokenGuard { registry, id: id.clone() }
- });
+ None => (tokio_util::sync::CancellationToken::new(), None),
+ };
cancellable_request(request, &token).await
}
@@ -923,9 +919,7 @@ pub fn cancel_proxy_call(
state: tauri::State<'_, crate::state::AppState>,
call_id: String,
) -> Result<(), String> {
- if let Some(token) = state.call_tokens.lock().unwrap().remove(&call_id) {
- token.cancel();
- }
+ state.call_tokens.cancel(&call_id);
Ok(())
}
@@ -1017,16 +1011,22 @@ pub async fn proxy_localhost_stream_chunked(
let idle = Duration::from_millis(idle_timeout_ms.unwrap_or(IDLE_TIMEOUT_MS));
let client = proxy_client(Duration::from_secs(7200), allow)?;
- // 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
+ // Register against the shared CancelRegistry (mirrors call_tokens /
+ // proxy_localhost). Survives a cancel that arrives before this line
+ // runs, not just one that arrives after (review 2026-09-18, R3
+ // Nachbesserung 1): the registry hands back an already-cancelled token
+ // in that case instead of silently losing the cancel, same guarantee
+ // the non-streaming path now has. The guard replaces the old manual
+ // "remove after the pump" cleanup below.
+ let (token, _guard) = match stream_id {
+ Some(id) => {
+ let (token, guard) = state.stream_tokens.register(id);
+ (token, Some(guard))
}
- }
+ None => (tokio_util::sync::CancellationToken::new(), None),
+ };
- let run = pump_proxy_stream(
+ pump_proxy_stream(
&client,
&url,
method,
@@ -1037,12 +1037,7 @@ pub async fn proxy_localhost_stream_chunked(
FIRST_CHUNK_GRACE,
&move |chunk| on_chunk.send(chunk).is_ok(),
)
- .await;
-
- if let Some(id) = stream_id.as_ref() {
- registry.lock().unwrap().remove(id);
- }
- run
+ .await
}
/// The stream pump behind `proxy_localhost_stream_chunked`, with the IPC channel
@@ -1064,6 +1059,15 @@ async fn pump_proxy_stream(
// single byte of an answer ever reached the renderer.
let mut seen_first_chunk = false;
let run = async {
+ if token.is_cancelled() {
+ // Same deterministic short-circuit as cancellable_request: a
+ // token that starts pre-cancelled (a CancelRegistry tombstone
+ // from a cancel that beat the registration, review 2026-09-18,
+ // R3 Nachbesserung 1) must never let request.send() be polled,
+ // not just usually lose the tokio::select! race against it.
+ return Ok(());
+ }
+
let http_method = method.unwrap_or_else(|| "GET".to_string());
let mut request = match http_method.as_str() {
@@ -1153,14 +1157,16 @@ async fn pump_proxy_stream(
/// 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).
+/// A stream id with nothing registered yet leaves a tombstone instead of
+/// doing nothing (review 2026-09-18, R3 Nachbesserung 1), so a cancel that
+/// arrives before `proxy_localhost_stream_chunked` reaches its registration
+/// line is not lost.
#[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();
- }
+ state.stream_tokens.cancel(&stream_id);
Ok(())
}
@@ -2176,6 +2182,27 @@ mod tests {
port
}
+ /// Same shape as `hang_stub`, plus an atomic counter incremented on every
+ /// ACCEPTED connection -- the proof instrument for "the request must
+ /// never have been sent at all", which a mere assertion on the return
+ /// value cannot tell apart from "sent, then aborted mid-flight".
+ async fn counting_hang_stub(connections: std::sync::Arc<std::sync::atomic::AtomicUsize>, hold: Duration) -> u16 {
+ use tokio::io::AsyncReadExt;
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+ tokio::spawn(async move {
+ while let Ok((mut sock, _)) = listener.accept().await {
+ connections.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ tokio::spawn(async move {
+ let mut buf = [0u8; 4096];
+ let _ = sock.read(&mut buf).await;
+ tokio::time::sleep(hold).await;
+ });
+ }
+ });
+ port
+ }
+
/// Without R3's fix, `cancellable_request` had no `token` argument at
/// all: `request.send()` was a bare `.await`, so cancelling never
/// interrupted anything and this test would only return once the stub's
@@ -2261,9 +2288,19 @@ mod tests {
}
/// A second, independent call against a server that answers normally
- /// must be completely unaffected by an earlier call's cancellation --
- /// same token type, but each `proxy_localhost` invocation gets its own
- /// `CancellationToken`, so one call's Stop cannot reach another's.
+ /// must be completely unaffected by an earlier call's cancellation.
+ /// This drives the REAL registry on a real `AppState`, the same one
+ /// `proxy_localhost`/`cancel_proxy_call` use, and cancels by id through
+ /// `cancel()` rather than holding two hand-built tokens -- the previous
+ /// version of this test built two separate, never-registered
+ /// `CancellationToken`s and cancelled one of them directly, which is
+ /// true no matter how (or whether) the lookup logic works and proved
+ /// nothing about `state.call_tokens` (review 2026-09-18, R3
+ /// Nachbesserung 2). `cancel_registry::tests::
+ /// cancel_finds_exactly_its_own_call_and_leaves_a_second_registered_
+ /// call_running` covers the registry contract itself in isolation; this
+ /// one proves the SAME contract holds end to end through `cancellable_
+ /// request` and a real socket.
#[test]
fn cancelling_one_call_does_not_touch_a_second_unrelated_call() {
let rt = tokio::runtime::Runtime::new().unwrap();
@@ -2279,65 +2316,64 @@ mod tests {
.build()
.unwrap();
- let cancelled_token = tokio_util::sync::CancellationToken::new();
- cancelled_token.cancel();
- let cancelled_req = client.get(format!("http://127.0.0.1:{}/", hanging_port));
- let cancelled_out = cancellable_request(cancelled_req, &cancelled_token).await;
- assert!(cancelled_out.is_err());
-
- // A fresh, never-cancelled token against a normal server: must
- // succeed exactly as if the first call never happened.
- let fresh_token = tokio_util::sync::CancellationToken::new();
- let fresh_req = client.get(format!("http://127.0.0.1:{}/", ok_port));
- let fresh_out = cancellable_request(fresh_req, &fresh_token).await;
- assert_eq!(fresh_out.as_deref(), Ok("ok"), "an unrelated call must go through untouched: {fresh_out:?}");
+ let state = crate::state::AppState::new();
+ let (hanging_token, _hanging_guard) = state.call_tokens.register("hanging-call".to_string());
+ let (ok_token, _ok_guard) = state.call_tokens.register("ok-call".to_string());
+
+ // Cancel by id, through the same registry both real commands
+ // share, not by holding the token directly.
+ state.call_tokens.cancel("hanging-call");
+
+ let hanging_req = client.get(format!("http://127.0.0.1:{}/", hanging_port));
+ let hanging_out = cancellable_request(hanging_req, &hanging_token).await;
+ assert!(hanging_out.is_err());
+
+ // The unrelated, still-registered call must go through exactly
+ // as if "hanging-call" had never existed.
+ assert!(!ok_token.is_cancelled(), "cancel(\"hanging-call\") must not reach the ok-call token");
+ let ok_req = client.get(format!("http://127.0.0.1:{}/", ok_port));
+ let ok_out = cancellable_request(ok_req, &ok_token).await;
+ assert_eq!(ok_out.as_deref(), Ok("ok"), "an unrelated call must go through untouched: {ok_out:?}");
});
}
- /// The registry bookkeeping half of R3: `CallTokenGuard` has to remove its
- /// entry on EVERY exit, including one that returns early (an `Err` from a
- /// `?`, or the cancelled branch) rather than falling off the end of the
- /// function -- which is exactly the shape `proxy_localhost` has, and why
- /// a plain "remove after the last await" was not enough.
+ /// R3 Nachbesserung 1 end to end: a cancel that arrives before
+ /// `proxy_localhost` ever reaches its registration line must still stop
+ /// the request, proven against a real listening socket that counts
+ /// connections -- not just that `CancelRegistry::register` returns an
+ /// already-cancelled token (that half is `cancel_registry::tests::
+ /// a_cancel_before_register_hands_back_an_already_cancelled_token`),
+ /// but that `cancellable_request` then never dials out at all.
#[test]
- fn the_call_token_guard_clears_the_registry_on_every_kind_of_exit() {
- let registry: std::sync::Arc<std::sync::Mutex<std::collections::HashMap<String, tokio_util::sync::CancellationToken>>> =
- std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
+ fn a_cancel_that_arrives_before_registration_never_opens_a_connection() {
+ let rt = tokio::runtime::Runtime::new().unwrap();
+ rt.block_on(async {
+ let connections = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let port = counting_hang_stub(connections.clone(), Duration::from_secs(10)).await;
- // Normal scope exit (mirrors a successful `proxy_localhost` return).
- {
- let token = tokio_util::sync::CancellationToken::new();
- registry.lock().unwrap().insert("call-a".to_string(), token);
- let _guard = CallTokenGuard { registry: registry.clone(), id: "call-a".to_string() };
- assert!(registry.lock().unwrap().contains_key("call-a"));
- }
- assert!(registry.lock().unwrap().is_empty(), "normal exit must clear the entry");
-
- // Early return via `?` (mirrors guard_builtin_model / send() erroring
- // after the token was already registered) -- a closure standing in
- // for a function that returns before reaching its last line.
- fn early_return(
- registry: &std::sync::Arc<std::sync::Mutex<std::collections::HashMap<String, tokio_util::sync::CancellationToken>>>,
- ) -> Result<(), String> {
- let token = tokio_util::sync::CancellationToken::new();
- registry.lock().unwrap().insert("call-b".to_string(), token);
- let _guard = CallTokenGuard { registry: registry.clone(), id: "call-b".to_string() };
- Err("simulated mid-flight failure".to_string())?;
- unreachable!()
- }
- let _ = early_return(&registry);
- assert!(registry.lock().unwrap().is_empty(), "an early ? return must still clear the entry");
+ let state = crate::state::AppState::new();
+ let call_id = "race-before-register".to_string();
- // Panic unwinding through the guard's scope (Rust runs destructors
- // while unwinding a panic that is not aborting the process).
- let panicking = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
- let token = tokio_util::sync::CancellationToken::new();
- registry.lock().unwrap().insert("call-c".to_string(), token);
- let _guard = CallTokenGuard { registry: registry.clone(), id: "call-c".to_string() };
- panic!("simulated panic while the call was in flight");
- }));
- assert!(panicking.is_err());
- assert!(registry.lock().unwrap().is_empty(), "a panic unwinding through the guard must still clear the entry");
+ // The cancel arrives FIRST -- the exact startup-window race from
+ // the review: in the real command this window is
+ // ProxyAllowList::snapshot + allow.check + guard_builtin_model +
+ // proxy_client, all of which run before the registration line.
+ state.call_tokens.cancel(&call_id);
+
+ let (token, _guard) = state.call_tokens.register(call_id);
+ assert!(token.is_cancelled(), "register() after a cancel must hand back an already-cancelled token");
+
+ let client = reqwest::Client::builder().timeout(Duration::from_secs(5)).build().unwrap();
+ let request = client.get(format!("http://127.0.0.1:{}/", port));
+ let out = cancellable_request(request, &token).await;
+
+ assert!(out.is_err(), "a pre-cancelled token must not report success");
+ assert_eq!(
+ connections.load(std::sync::atomic::Ordering::SeqCst),
+ 0,
+ "the request must never have been sent to the stub"
+ );
+ });
}
}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 3bdb3547..42e924dd 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -2,6 +2,7 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod app_identity;
+mod cancel_registry;
mod commands;
mod crash_report;
mod install_state;
diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs
index d96e362a..8666c2de 100644
--- a/src-tauri/src/state.rs
+++ b/src-tauri/src/state.rs
@@ -252,21 +252,25 @@ 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`.
+ /// Per-stream cancellation registry 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>>>,
- /// Per-call cancellation tokens for the NON-streaming `proxy_localhost`
+ /// `CancelRegistry` (not a bare token map) also survives a cancel that
+ /// arrives before the matching stream registers (review 2026-09-18, R3
+ /// Nachbesserung 1).
+ pub stream_tokens: crate::cancel_registry::CancelRegistry,
+ /// Per-call cancellation registry for the NON-streaming `proxy_localhost`
/// command (a tool call against the built-in engine / Ollama runs this
- /// path, not the chunked one). Same registry shape as `stream_tokens`,
- /// kept separate so a stream id and a call id can never collide. Without
- /// this, Stop only aborted the JS-side promise while the Rust proxy sent
- /// the already-issued request to completion against the local engine,
- /// so a stopped agent turn still burned the full generation on the GPU
- /// (review 2026-09-18, "Loch 3": the local engine ignores Stop).
- pub call_tokens: Arc<Mutex<HashMap<String, CancellationToken>>>,
+ /// path, not the chunked one). Same `CancelRegistry` type as
+ /// `stream_tokens`, kept as its own instance so a stream id and a call id
+ /// can never collide. Without this, Stop only aborted the JS-side promise
+ /// while the Rust proxy sent the already-issued request to completion
+ /// against the local engine, so a stopped agent turn still burned the
+ /// full generation on the GPU (review 2026-09-18, "Loch 3": the local
+ /// engine ignores Stop).
+ pub call_tokens: crate::cancel_registry::CancelRegistry,
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
@@ -426,8 +430,8 @@ 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())),
- call_tokens: Arc::new(Mutex::new(HashMap::new())),
+ stream_tokens: crate::cancel_registry::CancelRegistry::new(),
+ call_tokens: crate::cancel_registry::CancelRegistry::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/__tests__/local-fetch-cancel.test.ts b/src/api/__tests__/local-fetch-cancel.test.ts
new file mode 100644
index 00000000..6a311e20
--- /dev/null
+++ b/src/api/__tests__/local-fetch-cancel.test.ts
@@ -0,0 +1,187 @@
+/**
+ * localFetch cancellation tests (R3 Nachbesserung 3: the TS half of "Stop
+ * means stop" for non-streaming local-engine calls).
+ *
+ * proxy_localhost now takes a callId the JS side mints, and an abort on the
+ * caller's signal invokes cancel_proxy_call(callId) so Rust actually drops
+ * the connection (see cancel_registry.rs and commands/proxy.rs). These tests
+ * pin the JS-side contract: a fresh id per call, the listener firing the
+ * right command, cleanup of that listener, and the rule that an aborted call
+ * never falls back to a direct fetch or retries.
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+
+const invokeMock = vi.fn()
+vi.mock('@tauri-apps/api/core', () => ({
+ invoke: (...args: unknown[]) => invokeMock(...args),
+}))
+
+import { localFetch } from '../backend'
+import { isRecord } from '../../types/json-guards'
+
+const fetchMock = vi.fn()
+
+type ProxyLocalhostArgs = {
+ url: string
+ method: string
+ body: string | null
+ timeoutMs: number | null
+ headers: Record<string, string> | null
+ callId: string
+}
+
+function tauriMode(on: boolean) {
+ const existing: unknown = Reflect.get(globalThis, 'window')
+ const w: Record<string, unknown> = isRecord(existing) ? existing : {}
+ Reflect.set(globalThis, 'window', w)
+ if (on) w.__TAURI_INTERNALS__ = {}
+ else { delete w.__TAURI_INTERNALS__; delete w.__TAURI__ }
+}
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ vi.stubGlobal('fetch', fetchMock)
+ tauriMode(true)
+})
+
+afterEach(() => {
+ vi.unstubAllGlobals()
+ tauriMode(false)
+})
+
+describe('localFetch mints a fresh callId per call', () => {
+ it('sends a different callId for two separate calls', async () => {
+ invokeMock.mockResolvedValue('{}')
+
+ await localFetch('http://localhost:11434/api/chat', { method: 'POST', body: '{}' })
+ await localFetch('http://localhost:11434/api/chat', { method: 'POST', body: '{}' })
+
+ expect(invokeMock).toHaveBeenCalledTimes(2)
+ const first = invokeMock.mock.calls[0][1] as ProxyLocalhostArgs
+ const second = invokeMock.mock.calls[1][1] as ProxyLocalhostArgs
+ expect(first.callId).toEqual(expect.any(String))
+ expect(first.callId.length).toBeGreaterThan(0)
+ expect(second.callId).not.toBe(first.callId)
+ })
+})
+
+describe('localFetch forwards timeoutMs, never the snake_case key', () => {
+ it('sends the camelCase key Tauri auto-converts, not timeout_ms', async () => {
+ invokeMock.mockResolvedValue('{}')
+
+ await localFetch('http://localhost:11434/api/tags', { timeoutMs: 2000 })
+
+ expect(invokeMock).toHaveBeenCalledTimes(1)
+ const args = invokeMock.mock.calls[0][1] as Record<string, unknown>
+ expect(args.timeoutMs).toBe(2000)
+ expect('timeout_ms' in args).toBe(false)
+ })
+})
+
+describe('localFetch abort wires into cancel_proxy_call', () => {
+ it('calls cancel_proxy_call with the same callId used for proxy_localhost, on abort', async () => {
+ const controller = new AbortController()
+ let rejectProxy!: (reason: unknown) => void
+ invokeMock.mockImplementation((cmd: string) => {
+ if (cmd === 'proxy_localhost') {
+ return new Promise<string>((_resolve, reject) => { rejectProxy = reject })
+ }
+ if (cmd === 'cancel_proxy_call') return Promise.resolve()
+ throw new Error(`unexpected invoke: ${cmd}`)
+ })
+
+ const pending = localFetch('http://localhost:11434/api/chat', {
+ method: 'POST',
+ body: '{}',
+ signal: controller.signal,
+ })
+
+ // Let the microtask that issues the proxy_localhost invoke run
+ // (localFetch awaits getInvoke() before it ever touches the signal).
+ await Promise.resolve()
+ await Promise.resolve()
+ await Promise.resolve()
+
+ const callArgs = invokeMock.mock.calls.find((c) => c[0] === 'proxy_localhost')?.[1] as ProxyLocalhostArgs
+ expect(callArgs).toBeTruthy()
+
+ controller.abort()
+ await Promise.resolve()
+
+ const cancelCall = invokeMock.mock.calls.find((c) => c[0] === 'cancel_proxy_call')
+ expect(cancelCall).toBeTruthy()
+ expect((cancelCall?.[1] as { callId: string }).callId).toBe(callArgs.callId)
+
+ // The real Rust side answers a cancelled call with an error (see
+ // cancellable_request in commands/proxy.rs); settle the mock the same
+ // way so the awaited promise below resolves through the abort path
+ // instead of hanging the test.
+ rejectProxy('proxy_localhost: cancelled')
+ await expect(pending).rejects.toMatchObject({ name: 'AbortError' })
+ })
+
+ it('rejects immediately, without ever calling invoke, for an already-aborted signal', async () => {
+ const controller = new AbortController()
+ controller.abort()
+
+ await expect(
+ localFetch('http://localhost:11434/api/chat', { method: 'POST', body: '{}', signal: controller.signal })
+ ).rejects.toMatchObject({ name: 'AbortError' })
+
+ expect(invokeMock).not.toHaveBeenCalled()
+ })
+})
+
+describe('localFetch detaches its abort listener after the call settles', () => {
+ it('removes the abort listener once proxy_localhost resolves, so a later abort on the same signal is a no-op', async () => {
+ invokeMock.mockResolvedValue('{}')
+ const controller = new AbortController()
+ const removeSpy = vi.spyOn(controller.signal, 'removeEventListener')
+
+ await localFetch('http://localhost:11434/api/chat', { method: 'POST', body: '{}', signal: controller.signal })
+
+ expect(removeSpy).toHaveBeenCalledWith('abort', expect.any(Function))
+
+ // The listener is gone: aborting afterwards must not invoke
+ // cancel_proxy_call for a call that has already finished.
+ invokeMock.mockClear()
+ controller.abort()
+ await Promise.resolve()
+ expect(invokeMock).not.toHaveBeenCalled()
+ })
+})
+
+describe('an aborted call never falls back to direct fetch and never retries', () => {
+ it('does not call fetch() after proxy_localhost rejects because the signal was aborted', async () => {
+ const controller = new AbortController()
+ let rejectProxy!: (reason: unknown) => void
+ invokeMock.mockImplementation((cmd: string) => {
+ if (cmd === 'proxy_localhost') {
+ return new Promise<string>((_resolve, reject) => { rejectProxy = reject })
+ }
+ if (cmd === 'cancel_proxy_call') return Promise.resolve()
+ throw new Error(`unexpected invoke: ${cmd}`)
+ })
+
+ const pending = localFetch('http://localhost:11434/api/chat', {
+ method: 'POST',
+ body: '{}',
+ signal: controller.signal,
+ })
+ // Let the getInvoke() await resolve so proxy_localhost is actually
+ // invoked and the abort listener is attached before we abort.
+ await Promise.resolve()
+ await Promise.resolve()
+ await Promise.resolve()
+ controller.abort()
+ // The abort listener calls cancel_proxy_call; the real Rust side then
+ // answers the still-pending proxy_localhost call with an error.
+ rejectProxy('proxy_localhost: cancelled')
+
+ await expect(pending).rejects.toMatchObject({ name: 'AbortError' })
+ expect(fetchMock).not.toHaveBeenCalled()
+
+ // And only the one proxy_localhost invocation happened: no retry.
+ expect(invokeMock.mock.calls.filter((c) => c[0] === 'proxy_localhost')).toHaveLength(1)
+ })
+})
diff --git a/src/api/backend.ts b/src/api/backend.ts
index 910cb965..4b2df0d7 100644
--- a/src/api/backend.ts
+++ b/src/api/backend.ts
@@ -176,10 +176,14 @@ export async function localFetch(
url,
method,
body: options?.body || null,
- // Snake-case to match the Rust parameter name. Tauri's invoke layer
- // does NOT auto-convert camelCase here — the Rust command spec uses
- // explicit field names.
- timeout_ms: options?.timeoutMs ?? null,
+ // Camel-case, because Tauri's invoke layer DOES auto-convert the
+ // command's snake_case parameter names to camelCase for the JS side
+ // (tauri-macros, command/wrapper.rs: key.to_lower_camel_case(), unless
+ // the command opts out with rename_all). proxy_localhost declares
+ // timeout_ms; sending timeout_ms from here landed in nothing, so
+ // every probe silently ran with the 300 s default instead of its
+ // real timeout (review 2026-09-18, R3 Nachbesserung 4).
+ timeoutMs: options?.timeoutMs ?? null,
// Forward caller headers (Authorization for keyed OpenAI-compat
// backends). The proxy silently dropped them before, so a LAN vLLM/
// TabbyAPI with an api key always got 401 through this path.
diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsx
index ac52218c..ea8d2e46 100644
--- a/src/components/settings/SettingsPage.tsx
+++ b/src/components/settings/SettingsPage.tsx
@@ -2454,7 +2454,10 @@ export function UpdateSection() {
// ── B7 Troubleshoot section — one-shot diagnostic probe ───────
-interface BackendProbe {
+// Exported so a test can render the real component instead of parsing its
+// source text (review 2026-09-18: a source-text test breaks on an unrelated
+// rename even when the rendered behaviour is unchanged).
+export interface BackendProbe {
// 'timeout': the connection went through but nothing answered within the
// probe window -- a cold-starting or busy server, not a dead one (R8/T5,
// 2026-09-18). Rust's probe_http now tells these apart instead of folding
@@ -2484,7 +2487,7 @@ interface SystemHealthReport {
lm_studio: BackendProbe
}
-function ProbeBadge({ probe }: { probe: BackendProbe }) {
+export function ProbeBadge({ probe }: { probe: BackendProbe }) {
// "Not running" und "Not installed" sind beide nur ein Nein und tragen
// deshalb dasselbe Grau; der Unterschied steht im Wort, nicht in der Farbe.
// Das Gelb, das "Not running" frueher trug, hat einen ausgeschalteten
diff --git a/src/components/settings/__tests__/probe-badge-timeout.test.ts b/src/components/settings/__tests__/probe-badge-timeout.test.ts
index f07cdcb2..5f6b415e 100644
--- a/src/components/settings/__tests__/probe-badge-timeout.test.ts
+++ b/src/components/settings/__tests__/probe-badge-timeout.test.ts
@@ -1,76 +1,78 @@
-import { describe, it, expect } from 'vitest'
-import { readFileSync } from 'node:fs'
-import { resolve } from 'node:path'
+// @vitest-environment jsdom
+/**
+ * R8/T5 (2026-09-18): the Rust `system_health` probe now returns a third,
+ * non-error outcome -- `timeout` -- for a backend that accepted the
+ * connection but did not answer within the probe window (a cold-starting or
+ * busy local server), instead of folding it into `unreachable` ("Not
+ * running"), which told the owner of a live-but-slow backend to go restart
+ * something that was fine.
+ *
+ * This renders the REAL `ProbeBadge` component (exported from SettingsPage
+ * for exactly this) instead of parsing its source text. A source-text test
+ * broke the first time an unrelated rename touched the same lines (review
+ * 2026-09-18: fix/301-chat renames `labels`/`colors` to `label`/`color` in
+ * the same block) even though the rendered behaviour never changed --
+ * behaviour is what this file now pins.
+ *
+ * Run: npx vitest run src/components/settings/__tests__/probe-badge-timeout.test.ts
+ */
+import { describe, it, expect, afterEach } from 'vitest'
+import { cleanup, render, screen } from '@testing-library/react'
+import { ProbeBadge, type BackendProbe } from '../SettingsPage'
-// R8/T5 (2026-09-18): the Rust `system_health` probe now returns a third,
-// non-error outcome -- `timeout` -- for a backend that accepted the
-// connection but did not answer within the probe window (a cold-starting or
-// busy local server), instead of folding it into `unreachable` ("Not
-// running"), which told the owner of a live-but-slow backend to go restart
-// something that was fine.
-//
-// `ProbeBadge` is not exported (it is one of many small components in the
-// same big SettingsPage.tsx file, alongside ones that DO need the page's own
-// context), so this pins the source text of the mapping tables directly --
-// same technique `settings-update-and-keys.test.ts` already uses on this
-// file. A TS render test would need to stand up the whole Troubleshoot
-// section's dependencies for a three-line lookup table.
-const src = readFileSync(resolve(__dirname, '../SettingsPage.tsx'), 'utf8')
-const start = src.indexOf('function ProbeBadge')
-const end = src.indexOf('function TroubleshootSection')
-const probeBadge = src.slice(start, end)
+afterEach(() => {
+ cleanup()
+})
+
+function probe(status: BackendProbe['status']): BackendProbe {
+ return { status, detail: '', endpoint: 'http://127.0.0.1:11434/api/tags' }
+}
describe('ProbeBadge renders the timeout status distinctly from unreachable/error/ok', () => {
- it('slices the function it inspects', () => {
- expect(start).toBeGreaterThan(-1)
- expect(end).toBeGreaterThan(start)
+ it('shows "Reachable, slow to answer" for a timeout probe, never "Not running"', () => {
+ render(ProbeBadge({ probe: probe('timeout') }))
+ expect(screen.getByText('Reachable, slow to answer')).toBeTruthy()
+ expect(screen.queryByText('Not running')).toBeNull()
})
- it('the BackendProbe status type includes timeout', () => {
- const typeStart = src.indexOf('interface BackendProbe')
- const typeEnd = src.indexOf('interface SystemHealthReport')
- const backendProbeType = src.slice(typeStart, typeEnd)
- expect(backendProbeType).toMatch(/status:\s*'ok'\s*\|\s*'unreachable'\s*\|\s*'timeout'\s*\|\s*'not_installed'\s*\|\s*'error'/)
- })
+ it('still shows the ordinary labels for the other three statuses', () => {
+ render(ProbeBadge({ probe: probe('ok') }))
+ expect(screen.getByText('Reachable')).toBeTruthy()
+ cleanup()
+
+ render(ProbeBadge({ probe: probe('unreachable') }))
+ expect(screen.getByText('Not running')).toBeTruthy()
+ cleanup()
- it('labels timeout as reachable-but-slow, never as "Not running"', () => {
- // `colors` and `labels` are two separate maps, each with its own
- // `timeout:` key -- scope the match to after `const labels` so this
- // reads the label string, not the color class from the earlier map.
- const labelsStart = probeBadge.indexOf('const labels')
- expect(labelsStart, 'no `const labels` map found').toBeGreaterThan(-1)
- const labelsSection = probeBadge.slice(labelsStart)
- const labelMatch = labelsSection.match(/timeout:\s*'([^']*)'/)
- expect(labelMatch, 'no `timeout:` entry in the labels map').not.toBeNull()
- const label = labelMatch![1]
- expect(label.toLowerCase()).toContain('slow to answer')
- expect(label).not.toBe('Not running')
+ render(ProbeBadge({ probe: probe('error') }))
+ expect(screen.getByText('Error')).toBeTruthy()
})
- it('colors timeout the same calm gray as unreachable, never amber/yellow, and always distinct from ok/error', () => {
- // `lib/hinweis.ts` HARTE REGEL (04.09.2026, guarded separately by
+ it('colors timeout the same calm gray as unreachable, never amber/yellow', () => {
+ // lib/hinweis.ts HARTE REGEL (04.09.2026, guarded separately by
// kein-gelb-in-der-oberflaeche.test.ts): exactly two tones exist, ruhig
// (gray) and fehler (red) -- no third "in-between" color for a state
- // that is neither an error nor urgent. `unreachable`/`not_installed`
- // reuse a shared `RUHIG` constant rather than repeating the string
- // literal -- resolve it so the comparison is against the actual class
- // list, not the bare identifier.
- const ruhigMatch = probeBadge.match(/const RUHIG = '([^']*)'/)
- expect(ruhigMatch, 'RUHIG constant not found').not.toBeNull()
- const ruhig = ruhigMatch![1]
+ // that is neither an error nor urgent.
+ const { container: timeoutBox } = render(ProbeBadge({ probe: probe('timeout') }))
+ const timeoutClasses = timeoutBox.querySelector('span')?.className ?? ''
+ cleanup()
+
+ const { container: unreachableBox } = render(ProbeBadge({ probe: probe('unreachable') }))
+ const unreachableClasses = unreachableBox.querySelector('span')?.className ?? ''
+ cleanup()
+
+ const { container: okBox } = render(ProbeBadge({ probe: probe('ok') }))
+ const okClasses = okBox.querySelector('span')?.className ?? ''
+
+ expect(timeoutClasses).not.toBe('')
+ expect(timeoutClasses).toBe(unreachableClasses)
+ expect(timeoutClasses).not.toBe(okClasses)
+ expect(timeoutClasses).not.toMatch(/\b(?:amber|yellow)-/)
+ })
- const colorOf = (key: string): string => {
- const re = new RegExp(`${key}:\\s*(RUHIG|'[^']*')`)
- const m = probeBadge.match(re)
- expect(m, `no \`${key}:\` color entry`).not.toBeNull()
- const raw = m![1]
- return raw === 'RUHIG' ? ruhig : raw.slice(1, -1)
- }
- const timeoutColor = colorOf('timeout')
- expect(timeoutColor).toBe(colorOf('unreachable'))
- expect(timeoutColor).toBe(ruhig)
- expect(timeoutColor).not.toBe(colorOf('ok'))
- expect(timeoutColor).not.toBe(colorOf('error'))
- expect(timeoutColor).not.toMatch(/\b(?:amber|yellow)-/)
+ it('carries the endpoint/detail as the title, so "why" stays one hover away', () => {
+ render(ProbeBadge({ probe: { status: 'timeout', detail: 'timed out after 1500ms', endpoint: 'http://127.0.0.1:11434/api/tags' } }))
+ const badge = screen.getByText('Reachable, slow to answer')
+ expect(badge.getAttribute('title')).toBe('timed out after 1500ms')
})
})