Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(llamacpp): in-app ggml op diagnostics (#9663)

Akarshan Biswas01667116e6cb
diff --git a/docs/llamacpp-diagnostics/README.md b/docs/llamacpp-diagnostics/README.md
new file mode 100644
index 000000000..c826ae7cc
--- /dev/null
+++ b/docs/llamacpp-diagnostics/README.md
@@ -0,0 +1,70 @@
+# llama.cpp hardware check
+
+Runs every ggml operation on the user's devices and checks the results are
+correct, so "the model gives bad output" can be told apart from "this machine's
+q4_K matmul kernel is broken". It is upstream's `tests/test-backend-ops`,
+compiled into `jan-llama-worker` and driven from the app.
+
+Nothing is sent anywhere. The check runs locally and the report is handed to
+the clipboard for the user to paste.
+
+| Document | What is in it |
+|---|---|
+| [architecture.md](architecture.md) | The root/leaf process model, the upstream wrapper, how it is built |
+| [event-schema.md](event-schema.md) | The versioned JSON contract between the worker and the app |
+| [presets.md](presets.md) | Quick, Full and Model presets, shape filters, the vacuous-pass guards |
+| [measurements.md](measurements.md) | Binary size, build time, case counts, runtimes |
+
+## Running it
+
+**In the app:** the llama.cpp provider settings page, under the engine panel.
+Each GPU on the hardware page also links to it, carrying that device over.
+A failed model load offers "Check why this model failed", which runs only the
+ops that model's graph contains.
+
+**From a terminal:**
+
+```
+jan-llama-worker --diagnose [--diagnose-preset quick|full] [--device NAME]...
+ [--workers N] [--family-timeout SECS] [--deadline SECS]
+```
+
+It prints one JSON event per line on stdout (see
+[event-schema.md](event-schema.md)) and stops when its stdin closes. **A root
+started with stdin on `/dev/null` cancels immediately** -- give it a pipe the
+caller holds open.
+
+The other modes exist for the root to call, but are useful by hand:
+
+```
+jan-llama-worker --diagnose-devices # [{name, description, type, reg, memory_*}]
+jan-llama-worker --diagnose-ops # [{op, cases}] for every op family
+jan-llama-worker --diagnose-run <device> [--mode test|support] [--op RE] [--params RE]
+```
+
+## Reading the result
+
+A device gets one of four verdicts. Only one of them is a fault.
+
+| Verdict | Means |
+|---|---|
+| Working correctly | Every operation returned the right answer. |
+| Working correctly, some ops on the CPU | The device has no kernel for some ops, so ggml runs them elsewhere. Slower, not wrong. |
+| Problems found | A kernel computed the wrong answer, or the process died. A model using it will produce bad output or fail to load. |
+| Inconclusive | Part of the check tested nothing. Not a pass -- see [presets.md](presets.md). |
+
+**"Falls back to CPU" is not a failure.** It is the single most important thing
+to get right when reading a report: a device that does not implement an op is
+normal, and painting it red sends people chasing a non-problem. It explains
+slowness, nothing else.
+
+A crashed or hung family is reported as such and the run continues with the
+next one. That is the whole reason a leaf is a separate process: a
+`GGML_ASSERT` or a lost device costs one family, not the run and not the app.
+
+## Scope
+
+The op cases do not exercise shader or pipeline compilation failures, model
+architecture support, or anything above the kernel level. A load that fails
+before any kernel runs is covered by the diagnostics attached to the load
+error itself, not by this.
diff --git a/docs/llamacpp-diagnostics/architecture.md b/docs/llamacpp-diagnostics/architecture.md
new file mode 100644
index 000000000..e035425eb
--- /dev/null
+++ b/docs/llamacpp-diagnostics/architecture.md
@@ -0,0 +1,155 @@
+# Architecture
+
+Three layers: upstream's test driver compiled into the worker, a root process
+that supervises leaves running it, and a Tauri command that republishes the
+leaf events to the UI.
+
+```
+app (React) tauri-plugin-llamacpp jan-llama-worker
+ LlamacppDiagnostics -> start_diagnostics ---- spawns --> --diagnose (root, no ggml)
+ useLlamacppDiagnostics <- llamacpp-diagnostics events | spawns one per unit
+ v
+ --diagnose-run (leaf, holds ggml)
+ |
+ jan_llama_diag.cpp
+ |
+ tests/test-backend-ops.cpp
+```
+
+## The upstream wrapper
+
+`shim/jan_llama_diag.cpp` `#include`s llama.cpp's `tests/test-backend-ops.cpp`
+unmodified, with its `main` renamed, and is compiled as one translation unit by
+`build.rs` behind the `engine` feature. `LLAMA_BUILD_TESTS` stays OFF; this is
+the only file out of that directory that is built. A llama.cpp bump either
+compiles or fails loudly, which is the point of wrapping rather than forking a
+13.9k-line file.
+
+It needs only the four ggml headers (`ggml.h`, `ggml-alloc.h`, `ggml-backend.h`,
+`ggml-cpp.h`) plus `nlohmann/json.hpp` from `vendor/`, and links only the
+shared `ggml`/`ggml-base` the worker already links. No libllama, no libcommon,
+no generated headers.
+
+Entry points: `jan_llama_diag_run`, `jan_llama_diag_ops_json`,
+`jan_llama_diag_backends_json`, wrapped by `Engine::diag_run` /
+`diag_ops_json` / `diag_backends_json` in `engine/sys.rs` (an `Unavailable`
+stub without the feature).
+
+**Upstream writes to the process streams, so stdout had to be reclaimed.** The
+console printer plus bare `printf`/`fprintf(stderr, ...)` in the case code
+(failed allocation, `ERR = ...`, NaN reports, `graph_compute failed`, the Metal
+FA slice runner) would corrupt a JSON stream. The TU redefines `printf` and
+`fprintf` around the `#include` to capture into a per-thread buffer, which is
+attached to the failing result as `detail`. That is the only edit, and it is in
+our file, not upstream's. The macros are defined after every standard header
+the upstream file includes, so a header that merely mentions the token is not
+rewritten.
+
+Remaining stderr noise is ggml's own log callback (`load_backend: ...`,
+`ggml_cuda_init`, `ggml_vulkan`), which is not upstream's file. A leaf
+therefore keeps stdout for events and the root reads its stderr separately.
+
+### Toolchain notes
+
+Compiles as an included TU under gcc 11 / C++17. The only diagnostic is one
+`-Wunused-function` (`output_format_str`, used by its own `main`), silenced for
+this TU alone. `build.rs` adds `/utf-8` and `/bigobj` under `is_like_msvc()`,
+matching what llama.cpp's own CMake does for every target: the file has
+non-ASCII literals and 13.9k lines of case templates. Clang and MSVC are
+untested here. Metal needs no extra headers -- the file reaches its Metal-only
+path through `ggml_backend_reg_get_proc_address`.
+
+The vendored tree is not pruned: `make engine-source` is a shallow clone of the
+pinned tag, and `build.rs` asserts `tests/test-backend-ops.cpp` exists with a
+message pointing at it. The prebuilt-bundle recipe (`engine-prebuilt.sh`) reads
+`ARCHIVES`; the wrapper is built by `cc` on every build like the rest of the
+shim and is deliberately not in `ARCHIVES`, so prebuilt bundles are unaffected.
+
+## Root and leaf
+
+**The root (`--diagnose`) returns before `load_backend_modules()` is ever
+called.** It holds no ggml and no GPU context, so no kernel can take it down.
+It probes devices and the op list, builds a plan, then runs one leaf per
+(device, op family), emitting events as it goes.
+
+**The leaf (`--diagnose-run <device>`)** loads the backend modules from its own
+directory -- the same working-directory pinning and `llamacpp_env` the serving
+engine uses, so it tests exactly the modules Jan runs -- executes one family on
+one device, and prints `DiagEvent` lines.
+
+One leaf per family is the unit because that is the blast radius worth buying.
+Backend init costs 0.3-0.4 s and there are ~150 families, so per-family
+spawning costs about a minute per device against an 11-15 minute full run, and
+in exchange a `GGML_ASSERT` or a device loss costs one family: the root records
+it as `crashed` and moves on.
+
+**The root never touches the serving engine.** It holds no registry, opens no
+preset and speaks to no worker port, so a leaf crash cannot unload a model the
+user has resident.
+
+Cancellation is stdin close, the same signal the serving worker uses. The root
+`std::process::exit(0)`s when finished rather than returning: the cancel
+watcher is a blocking stdin read, and tokio waits for its blocking pool when
+the runtime drops, so a parent still holding the pipe would keep a finished
+root alive forever.
+
+## Reading a gguf for the Model preset
+
+`engine::model_plan` turns one gguf into a family list. It is Tauri-free and
+outside the `engine` feature, so it is unit-tested with no C++ toolchain.
+
+`ModelShape::from_gguf` reads architecture, head sizes and expert count from
+the metadata, and the weight types off the **tensor block** via
+`gguf::helpers::read_gguf_tensor_types` -- a second visitor over the walk
+`find_gguf_tensors` already does, not a second parser.
+
+**Weight types come from the tensors, not `general.file_type`.** A file type
+names a *recipe*, not a type: Q4_K_M is q4_K for most attention and
+feed-forward weights, q6_K for output and some feed-forward-down, q5_K
+elsewhere, f32 for the norms -- and llama.cpp's mixture rules have changed
+repeatedly. Walking the tensor block costs one pass over a few hundred KB of
+names and cannot be wrong. On `qwen-3.8.27b-iq4_xs.gguf` the tensors report
+`f32, q8_0, q4_K, q5_K, q6_K, iq4_xs`: four more types than the file type alone
+implies, each with its own kernel.
+
+The caller builds the plan, not the root: reading a gguf needs a model path,
+and the root deliberately holds no model. It arrives as `--diagnose-plan <json>`.
+
+## The Tauri layer
+
+`engine/diagnose_commands.rs` exposes `start_diagnostics(preset, devices, envs,
+model)` and `cancel_diagnostics(job)`, republishing each root line as a
+`llamacpp-diagnostics` event tagged with a job id.
+
+One run at a time, enforced in the plugin: the check saturates every core, so a
+second concurrent run would make both unreliable and the timings meaningless.
+A job id is still carried because events from a superseded run can be in flight
+when a new one starts.
+
+**The slot is reserved before the root is spawned**, and the spawned process is
+attached to it afterwards. Spawning first and claiming second is what lets a
+refused run exist: its caller is told the slot is taken while the root it
+already started keeps streaming on the shared channel. A stop that arrives in
+that window is remembered (`RunningJob::stopped`) and closes the new stdin as
+soon as it exists, rather than being lost against the `None` that stood in for
+it.
+
+A terminal `done` is emitted on every path, so a listener never waits forever:
+a root that could not be started, a root that stopped answering, and the
+cancel backstop -- which aborts the pump task that would otherwise have emitted
+it, and so must emit one itself.
+
+The frontend hook is the other half of that contract. A run outlives the panel
+and cannot be reattached to, so unmounting cancels an unfinished one rather
+than leaving it holding the slot with nobody listening; and because the root
+starts streaming before the `start_diagnostics` reply reaches the webview, the
+events that arrive before the job id is known are held and replayed against it
+instead of being dropped.
+
+## Tests
+
+`tests/diagnose_root.rs` drives the root against generated stand-in leaves
+(shell scripts, so no second binary) that exit cleanly, exit nonzero, stop
+without saying `done`, hang, and print garbage. Real processes, because
+`crashed` and `hung` are things an OS does to a child. It needs no `engine`
+feature, which is itself the check that the root links no ggml.
diff --git a/docs/llamacpp-diagnostics/event-schema.md b/docs/llamacpp-diagnostics/event-schema.md
new file mode 100644
index 000000000..bec576c45
--- /dev/null
+++ b/docs/llamacpp-diagnostics/event-schema.md
@@ -0,0 +1,92 @@
+# Event schema
+
+One JSON object per line on the root's stdout, discriminated by `event`.
+`engine::diagnose::RootEvent` is the producer; `guest-js/types.ts`
+`DiagnosticsEvent` is the consumer. The two must be changed together.
+
+Current version: **`schema: 2`**.
+
+Bump it when an existing event changes shape. Adding a *new* event does not
+need a bump: readers are required to ignore an `event` they do not know
+(`DiagEvent::Unknown` is the precedent).
+
+| Event | Fields |
+|---|---|
+| `start` | `schema`, `preset`, `engine {version, tag, commit}`, `families[]`, `model?`, `support_probe`, `backend_modules[]`, `units`, `family_timeout_secs`, `deadline_secs` |
+| `device` | `name`, `description`, `type`, `reg`, `memory_total_mib?`, `memory_free_mib?` |
+| `family_start` | `device`, `family`, `mode` |
+| `case` | `device`, `family`, then the leaf's own result flattened in: `backend`, `op`, `params`, `mode`, `status`, `error?`, `detail?` |
+| `family_end` | `device`, `family`, `status`, `ok`, `failed`, `not_supported`, `millis`, `exit?`, `last_lines[]`, `unparsed[]` |
+| `summary` | `device`, `ok`, `failed`, `not_supported`, `families_crashed`, `families_hung`, `families_no_cases`, `families_cancelled` |
+| `done` | `ok`, `cancelled`, `inconclusive`, `error?` |
+
+Order: one `start`, a `device` per device, then `family_start` / `case`\* /
+`family_end` per unit (device-major), then a `summary` per device, then exactly
+one `done`. A run always ends with `done`, including when cancelled, when the
+root could not start at all (`diag_root_fail` writes one before exiting, so the
+reason reaches the stream rather than only the root's stderr), and when the
+supervisor has to kill a root that ignored its stop request.
+
+`summary.ok` and `summary.failed` count the **test** units alone. The support
+probe asks `ggml_backend_supports_op` over the whole op list and reports every
+supported case as `ok` without computing or comparing anything, so counting it
+as a pass would tell the user that cases passed which were never run.
+`summary.not_supported` is the mirror image: the probe is authoritative when it
+ran, because it covers the whole op list rather than the families this run
+happened to test, and adding both sources would bill every probed case twice.
+With no probe, the test units are the only source.
+
+`case` is flattened rather than nested so a reader handles one flat object
+instead of reaching through a wrapper. `DiagCase` is the same struct the leaf
+serializes, so the two cannot drift.
+
+## `done.ok` means "a clean bill of health", not "nothing failed"
+
+A run with any `no_cases` family reports `ok: false` **and**
+`inconclusive: true`. This matters because a narrowed shape filter can match no
+case at all, and a reader that checks the obvious field alone must never be
+told that a run which tested nothing went fine. Check `inconclusive` to tell
+that apart from a real failure; the two are never both set.
+
+This follows the convention test runners settled on long ago -- "no tests
+matched the filter" is not success.
+
+## Case status
+
+`ok`, `fail`, `not_supported`, `skipped`.
+
+`not_supported` is **not** a failure. It is the device saying ggml will run
+that op somewhere else, which explains slowness rather than a wrong answer.
+
+## Family status
+
+| Status | What the root saw |
+|---|---|
+| `ok` | leaf exited 0, emitted `done`, no failing case |
+| `fail` | leaf exited cleanly but a case failed, or `done` carried an error |
+| `no_cases` | leaf exited cleanly, emitted `done`, and reported no case at all |
+| `crashed` | leaf exited nonzero, **or** exited 0 without ever emitting `done`, **or** could not be started |
+| `hung` | leaf outlived `--family-timeout` and was killed |
+| `cancelled` | stdin closed, or `--deadline` passed, before the leaf finished |
+
+Only `fail` means a kernel computed the wrong answer. `crashed` / `hung` /
+`cancelled` are the leaf process itself going wrong, which is the whole reason
+it is a separate process. `no_cases` is neither: the leaf ran cleanly and
+tested nothing, because its filter matched nothing.
+
+`exit` is `describe_exit`'s rendering, so a Windows crash reads as
+`exit code 0xC0000005` rather than a meaningless negative decimal. A hung or
+cancelled family has no `exit`: it was killed, so it never had a status of its
+own.
+
+`unparsed` holds leaf stdout lines that were not events, capped at 20 lines of
+2000 characters. A leaf printing these is a bug on our side rather than
+anything about the machine, so they are reported rather than dropped. Noise
+alone never fails a family.
+
+## Version history
+
+| Schema | Change |
+|---|---|
+| 1 | Initial contract. |
+| 2 | Added `FamilyStatus::no_cases`, `summary.families_no_cases`, `summary.families_cancelled`, `done.inconclusive`, `start.model`. Every added field is `#[serde(default)]`, so an older root still parses. |
diff --git a/docs/llamacpp-diagnostics/measurements.md b/docs/llamacpp-diagnostics/measurements.md
new file mode 100644
index 000000000..af8209789
--- /dev/null
+++ b/docs/llamacpp-diagnostics/measurements.md
@@ -0,0 +1,116 @@
+# Measurements
+
+One machine, one run each, so read these as orders of magnitude rather than
+benchmarks. **Check the build profile before comparing two rows** -- a debug
+`test-backend-ops` is several times slower than a release one, which is the
+easiest way to misread this page.
+
+**Reference machine:** 8 threads, Intel CPU (ggml picked the `sapphirerapids`
+variant), NVIDIA RTX 3090 (24 GiB), Ubuntu 22.04, gcc 11.4, ccache warm for
+ggml. Engine llama.cpp b12110.
+
+Devices available here: **CPU**, **CUDA0** (RTX 3090), **Vulkan0** (same card).
+No Metal, ROCm, or Windows figures.
+
+Nothing failed on this machine, so the FAIL path was exercised by unit tests
+only.
+
+## Binary size
+
+`jan-llama-worker`, stripped. The wrapper compiles to a 3.2 MB archive (1.3 MB
+of text) with no link-time dependency beyond ggml; LTO drops what nothing
+calls, so the figure depends on whether the entry points are referenced.
+
+| Variant | Without wrapper | Linked, entry points unused | Linked and called | Delta |
+|---|---|---|---|---|
+| cpu | 14,390,432 B | 14,417,592 B (+27 KB) | 15,698,008 B | +1.31 MB (+9.1%) |
+| vulkan | not built | 14,420,440 B | not built | expected the same ~+1.3 MB; the TU uses only ggml-base symbols, so it does not depend on the backend |
+
+Backend modules (`libggml-*.so`) are separate files and are unchanged.
+
+## Build time
+
+| Step | Time |
+|---|---|
+| cpu, `cargo build --release --features engine --bin jan-llama-worker` (baseline, no wrapper, ggml/llama via ccache) | 3m23s |
+| Wrapper TU alone, `g++ -O2` | 40 s (0.86 GB RSS) |
+| Wrapper TU alone, `g++ -O0` | 18 s |
+| Touch `jan_llama_diag.cpp`, rebuild worker (cc at opt 3 + fat LTO relink) | 88 s |
+| Upstream's own `test-backend-ops`, unmodified, `g++ -O2`, for reference | 48 s |
+| vulkan, `cargo test --release --features engine-vulkan --no-run` (all test bins, first Vulkan build in this tree) | 6m22s |
+
+The wrapper is the single heaviest C++ translation unit in the shim (13.9k
+lines of templates) and is rebuilt only when it or the upstream file changes.
+
+## Case counts
+
+`diag_ops_json`, test mode, pinned b12110: 163 entries, 150 with tests, 13
+without. Total **26,751 cases**. Counting is graph construction only: 50 ms.
+
+Upstream's `--list-ops` reports 130 operations and `--show-coverage` 123
+testable, 110 covered, 13 untested (ADD1, ADD_REL_POS, CUSTOM, DIAG_MASK_ZERO,
+FLASH_ATTN_BACK, GET_REL_POS, IM2COL_BACK, MAP_CUSTOM1-3, POOL_2D_BACK,
+WIN_PART, WIN_UNPART). Our listing has more entries because it keys on
+`op_desc`, so fusion cases get their own families (`MUL_MAT_VEC_FUSION`,
+`TOPK_MOE`, `RMS_NORM_MUL_ROPE`, ...), which the coverage report drops.
+
+| Family | Cases | | Family | Cases |
+|---|---|---|---|---|
+| FLASH_ATTN_EXT | 5439 | | SET_ROWS | 767 |
+| CONV_2D | 3144 | | TOPK_MOE | 672 |
+| MUL_MAT | 3091 | | CPY | 642 |
+| IM2COL_3D | 2051 | | TOP_K | 533 |
+| MUL_MAT_VEC_FUSION | 1754 | | ROPE | 470 |
+| OUT_PROD | 1543 | | ROPE_BACK | 404 |
+| MUL_MAT_ID | 1182 | | everything else (137 tested families) | 5,059 |
+
+Typical small families: ADD 173, MUL 143, SUB 142, SOFT_MAX 214, GET_ROWS 248.
+
+## Whole-run time
+
+Debug build unless marked. Each family is a separate leaf process, `-j 8`.
+
+| Run | Device | Cases run | Not supported | Wall time |
+|---|---|---|---|---|
+| Support probe, all families | CPU | 19,828 | 3,239 | 0.3 s |
+| Support probe, all families | CUDA0 | 16,228 | 6,839 | 0.4 s |
+| Support probe, all families | Vulkan0 | 18,623 | 4,444 | 0.4 s |
+| **Full**, 150 families | CPU (vs CPU reference) | 23,512 | 3,239 | **14m46s** |
+| **Full**, 150 families | CUDA0 | 19,306 | 7,445 | **11m03s** |
+
+Slowest families at `-j 8`, CUDA0: MUL_MAT_ID 121 s, FLASH_ATTN_EXT 97 s,
+MUL_MAT_ID_FUSION 81 s, MUL_MAT 80 s, GET_ROWS 54 s. CPU: FLASH_ATTN_EXT 168 s,
+MUL_MAT_ID 133 s, MUL_MAT 100 s, MUL_MAT_ID_FUSION 85 s.
+
+## Filter effectiveness
+
+CPU device only, **release** `test-backend-ops`, `-j 8`. Cases are those
+actually run in test mode.
+
+| Family | Filter | Cases | Seconds |
+|---|---|---|---|
+| MUL_MAT | none | 2633 | 101.8 |
+| MUL_MAT | Quick (`type_a=(f16\|f32\|bf16\|q4_0\|q8_0\|q2_K\|q3_K\|q4_K\|q5_K\|q6_K\|iq4_xs\|mxfp4),`) | 1731 | 49.9 |
+| MUL_MAT | model, Q4_K_M (`type_a=(q4_K\|q6_K\|f16\|f32),`) | 842 | 18.6 |
+| MUL_MAT_ID | none | 1184 | 149.0 |
+| MUL_MAT_ID | Quick | 672 | 37.1 |
+| MUL_MAT_ID | model, Q4_K_M | 110 | 5.0 |
+| FLASH_ATTN_EXT | none | 5441 | 185.7 |
+| FLASH_ATTN_EXT | Quick (`hsk=(64\|128),hsv=(64\|128),`) | 789 | 22.3 |
+| FLASH_ATTN_EXT | model, head size 128 | 575 | 19.5 |
+
+Quick buys the three heavy families for about 110 s on this machine. The Model
+preset covers them for about 43 s, or 38 s for a dense model, which skips
+`MUL_MAT_ID` entirely.
+
+## Notes
+
+- `ADD` costs about 19 s on every device at `-j 1`. Likely (not profiled) the
+ CPU reference run (`ggml_backend_cpu_set_use_ref`) plus tensor initialisation
+ dominating, since the GPU and the CPU device take the same time. **A GPU does
+ not make a test run fast.**
+- A bad `-p` regex throws `std::regex_error` out of `test_backend`; the wrapper
+ catches it and reports `done {ok: false, error}`.
+- Upstream's `show_test_coverage` loop aborts
+ (`GGML_ASSERT(!use_weight_context())`) and segfaults on fusion cases if copied
+ naively; `jan_llama_diag_ops_json` builds graphs the way `eval` does instead.
diff --git a/docs/llamacpp-diagnostics/presets.md b/docs/llamacpp-diagnostics/presets.md
new file mode 100644
index 000000000..923aa6575
--- /dev/null
+++ b/docs/llamacpp-diagnostics/presets.md
@@ -0,0 +1,165 @@
+# Presets and filters
+
+Upstream has ~150 op families and 26,751 cases. Running all of them is 11-15
+minutes per device, so every preset below is a choice about what to leave out
+-- and the hazard of leaving things out is the subject of the second half of
+this document.
+
+A unit of work is one (device, op family) pair with an optional parameter
+filter: `engine::diag::FamilyFilter { family, params }`, which is upstream's
+`-o` plus its `-p`. All three presets travel the same path.
+
+## Quick (the default)
+
+The support probe over every family on each device, then test mode on
+`model_plan::quick_families()`:
+
+- **Small families, whole:** ADD, SUB, MUL, DIV, SCALE, NORM, RMS_NORM,
+ SOFT_MAX, GET_ROWS, SET_ROWS, ROPE, CPY, CONT, CONCAT, SILU, GELU, SWIGLU,
+ GEGLU. 61-767 cases each; cheap, and on every token's path.
+- **MUL_MAT, MUL_MAT_ID, FLASH_ATTN_EXT**, narrowed to the types and head
+ sizes real models use. Unfiltered these three are over half the total case
+ count; a Quick check that skipped them would miss where a model spends almost
+ all its time.
+
+There is no `UNARY` family. Upstream keys on `op_desc`, so each unary op is its
+own family -- the family-name guard below is what caught that.
+
+## Full
+
+The support probe plus every family `--diagnose-ops` reports at least one case
+for. Minutes of 100% CPU on all cores; the UI warns before starting one, and on
+Windows a long GPU kernel can trip the display driver's watchdog, which resets
+the driver for every process.
+
+## Model
+
+The families one gguf's graph contains, at its own shapes. Offered after a
+failed load as "Check why this model failed".
+
+The caller builds the family list and passes it as `--diagnose-plan <json>`,
+which implies this preset: reading a gguf needs a model path and the root
+deliberately holds no model. See
+[architecture.md](architecture.md#reading-a-gguf-for-the-model-preset).
+
+## The support probe
+
+Runs first on every preset, at `--workers 1` regardless -- it builds graphs and
+asks whether the device supports them, and upstream threads test mode only. It
+costs under half a second for the whole op list and is the only thing that
+answers "which ops fall back to the CPU", so it is always worth its cost.
+
+## The vacuous-pass guard
+
+**Upstream's parameter strings are not a stable contract.** A filter that
+silently matches nothing produces a run where every family reports `ok`, and
+the user is told their hardware is fine on the strength of zero evidence. That
+is the one wrong answer a diagnostic must never give, and narrowing by shape is
+exactly what makes it likely.
+
+Two guards, because the two dimensions fail at different times.
+
+**Family names, before the run.** `diagnose::tested_families` intersects the
+wanted list with `--diagnose-ops` on *every* preset, so a family upstream has
+renamed or dropped is left out rather than passing vacuously. If the
+intersection is empty the root exits with an error rather than running the
+support probe alone and reporting a clean result. That error is written as a
+`done` event on stdout as well as to stderr, so the panel names the reason
+instead of reporting a bare early exit. The probe leaves are the exception:
+their stdout is one JSON document the root parses, so they report on stderr
+alone and `diagnose::probe` folds their last stderr lines into the error the
+root then emits as its own `done`.
+
+**Shapes, after the run.** These cannot be checked ahead of time, so the guard
+is at the other end. `run_unit` classifies a leaf that exited cleanly, emitted
+`done`, had no failure and reported `ok + not_supported == 0` as
+`FamilyStatus::NoCases`. It then propagates on its own channel, never folded
+into failure:
+
+```
+FamilyStatus::NoCases
+ -> summary.families_no_cases
+ -> done.inconclusive (and done.ok becomes false)
+ -> DiagnosticsRunStatus 'inconclusive'
+ -> deviceVerdict 'inconclusive'
+```
+
+A family the run never reached travels the same way. A cancel or a passed
+deadline leaves the families after it `FamilyStatus::Cancelled`, counted on
+`summary.families_cancelled`, and `deviceVerdict` reads that -- along with a
+device whose `summary` has not arrived at all -- as `inconclusive` too. The
+families that did run say nothing about the ones that did not, so a partial
+device must not report "Working correctly".
+
+The verdict ordering is `failed` > `inconclusive` > `fallback` > `passed`: a
+real failure still outranks an untested family, and an untested family always
+outranks a pass.
+
+Pinned by `a_filter_that_matches_nothing_is_inconclusive_not_a_pass` (root,
+against a real stand-in process),
+`a_family_the_device_does_not_implement_is_not_inconclusive` (not-supported is
+a real answer, not a vacuous one), and two UI tests that assert a narrowed run
+testing nothing never renders as a pass.
+
+`model_plan` additionally fails **open** at every step. An unreadable head size
+runs flash attention unfiltered rather than at a guessed geometry, and
+`MUL_MAT` runs unfiltered whenever the tensor list does not describe the whole
+model (`ModelShape::incomplete_weight_types`), which is three cases:
+
+- **no readable types at all**, where a filter would match nothing;
+- **any single unrecognised type id**, which is the realistic one. `from_gguf`
+ drops ids this build does not know and every gguf carries f32 norm tensors,
+ so a model quantized to a type added upstream after this pin still yields a
+ perfectly ordinary-looking `[f32, ...]`;
+- **a sharded model** (`split.count > 1`), where only the first split is ever
+ opened, so the list is complete for that shard and silent about the rest.
+
+The last two are the dangerous ones precisely because the list looks normal.
+Narrowing on it would run the attention kernels, skip the model's own, and
+report a pass. Over-running costs minutes; under-running costs the answer.
+
+## Why `--test-file` is not used
+
+Upstream's `--test-file` reads a line-per-op file produced by a separate
+`test-export-graph-ops` binary. It is strictly more exact than a regex over
+parameter strings -- it serializes the real `ggml_cgraph` nodes (op, type,
+`ne`, `op_params`, every source tensor's type/`ne`/`nb`) for the prompt and
+generation graphs, and replays them. If it were cheap it would replace
+`model_plan` outright.
+
+It is not cheap, for three independent reasons, any one of which disqualifies
+it:
+
+1. **It loads the model.** `common_init_from_params` (or
+ `llama_model_init_from_user` on the HF-fetch path) plus
+ `llama_graph_reserve`. The pre-flight exists to explain a load that just
+ *failed*; repeating the load inside the diagnostic is the thing being
+ avoided, plus tens of seconds and the model's full size in RAM.
+2. **It needs libllama and a private header.** `common.h`, `arg.h`,
+ `llama-cpp.h`, `download.h` and `../src/llama-ext.h` -- the last internal to
+ the llama.cpp build tree, not an installed header. The diag shim
+ deliberately needs ggml headers only and links no libllama; this would put a
+ model loader inside the leaf that exists to be a thin crash boundary.
+3. **The cases it produces are untyped `test_generic_op`s.** No
+ `max_nmse_err` override and no op-specific tolerance, so a FLASH_ATTN_EXT or
+ a quantized MUL_MAT replayed this way is compared at the generic default.
+ The curated cases are what encode upstream's knowledge of what "correct"
+ means per op.
+
+If exactness is ever needed, the right shape is to export the graph once at
+*load* time from the worker that already has the model open and hand the file
+to a leaf -- not to build a second model loader. That is separate work, and is
+not needed to answer "is this machine's q4_K matmul kernel broken", which the
+type filter answers directly.
+
+## Known gaps
+
+- `--diagnose-ops` reports case counts for the *unfiltered* list, so the root
+ cannot know a unit will be empty before spawning it. Making it filter-aware
+ needs a shim change and an engine rebuild to save ~0.4 s per empty unit;
+ `NoCases` already gives the correct answer without it.
+- Suggestions are drawn from the run alone, not from the failed load's
+ `LoadDiagnostics`. Cross-referencing the two ("your preset asks for flash
+ attention and this device's attention kernels are wrong") is a better
+ sentence, but needs the structured error to reach the provider page, which it
+ currently does not.
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/build.rs b/src-tauri/plugins/tauri-plugin-llamacpp/build.rs
index d4b985a59..8df4135b4 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/build.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/build.rs
@@ -41,6 +41,9 @@ const COMMANDS: &[&str] = &[
"begin_engine_restart",
"end_engine_restart",
"erase_thread_slot_state",
+ // The ggml op diagnostic, orchestrated by the worker
+ "start_diagnostics",
+ "cancel_diagnostics",
// GGUF commands
"read_gguf_metadata",
"find_gguf_tensors",
@@ -270,6 +273,7 @@ mod engine {
pub fn build() {
println!("cargo:rerun-if-changed=shim/jan_llama_shim.cpp");
println!("cargo:rerun-if-changed=shim/jan_llama_shim.h");
+ println!("cargo:rerun-if-changed=shim/jan_llama_diag.cpp");
println!("cargo:rerun-if-env-changed=JAN_LLAMA_PREBUILT_DIR");
println!("cargo:rerun-if-env-changed=JAN_LLAMA_CPP_DIR");
println!("cargo:rerun-if-env-changed=JAN_ENGINE_CUDA_ARCHS");
@@ -331,6 +335,7 @@ mod engine {
};
search_dirs.push(compile_shim(&src, &generated_include));
+ compile_diag(&src);
emit_link_flags(&search_dirs);
// ggml resolves backend modules against the *executable's* directory
@@ -1087,6 +1092,52 @@ mod engine {
PathBuf::from(env::var("OUT_DIR").unwrap())
}
+ /// Compiles `shim/jan_llama_diag.cpp`, which `#include`s upstream's
+ /// `tests/test-backend-ops.cpp` whole (after renaming its `main`).
+ ///
+ /// One translation unit through `cc`, not `-DLLAMA_BUILD_TESTS=ON`: that
+ /// switch would build and register every test target in `tests/`, which
+ /// the engine does not want and which would slow every build. The upstream
+ /// file needs ggml's headers only, so none of llama.cpp's generated headers
+ /// are on the include path and none of libllama or libcommon is linked in
+ /// for it; the ggml symbols resolve against the shared ggml the link line
+ /// already names.
+ ///
+ /// Not in `ARCHIVES`: it takes part in no link cycle, `cc` emits its own
+ /// link directive, and like the shim it is rebuilt on every build rather
+ /// than shipped in a prebuilt bundle (engine-prebuilt.sh reads `ARCHIVES`
+ /// to decide what the bundle must hold).
+ fn compile_diag(src: &Path) {
+ let upstream = src.join("tests/test-backend-ops.cpp");
+ assert!(
+ upstream.is_file(),
+ "{} is missing: the diagnostic wrapper includes it unmodified. A llama.cpp \
+ checkout pruned of tests/ cannot build the engine; re-run `make engine-source`.",
+ upstream.display()
+ );
+ println!("cargo:rerun-if-changed={}", upstream.display());
+
+ let mut cc = cc::Build::new();
+ cc.cpp(true)
+ .std("c++17")
+ .file("shim/jan_llama_diag.cpp")
+ .include("shim")
+ // `#include "tests/test-backend-ops.cpp"` resolves from the root.
+ .include(src)
+ .include(src.join("ggml/include"))
+ .include(src.join("vendor"));
+ if cc.get_compiler().is_like_msvc() {
+ // llama.cpp's own CMakeLists adds both for every target: the file
+ // holds non-ASCII literals and its test table overflows the default
+ // COFF section count.
+ cc.flag("/utf-8").flag("/bigobj");
+ }
+ // Upstream defines helpers its own main() uses (the output format
+ // names) that this driver does not; the file is not ours to prune.
+ cc.flag_if_supported("-Wno-unused-function");
+ cc.compile("jan_llama_diag");
+ }
+
fn emit_link_flags(dirs: &[PathBuf]) {
for d in dirs {
println!("cargo:rustc-link-search=native={}", d.display());
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts
index 13b6ab3b3..6c4c61d26 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts
@@ -1,4 +1,5 @@
import { invoke } from '@tauri-apps/api/core'
+import { listen, type UnlistenFn } from '@tauri-apps/api/event'
import {
SessionInfo,
DeviceList,
@@ -7,6 +8,9 @@ import {
EngineInfo,
EngineVersion,
GgufMetadata,
+ DiagnosticsEvent,
+ DiagnosticsJob,
+ DiagnosticsPreset,
} from './types'
// Helpers
@@ -250,4 +254,54 @@ export async function cleanupLlamaProcesses(): Promise<void> {
return await invoke('plugin:llamacpp|cleanup_llama_processes')
}
+// The ggml op diagnostic
+
+/** Every event of every run arrives here, tagged with its job id. */
+const DIAGNOSTICS_EVENT = 'llamacpp-diagnostics'
+
+/**
+ * Starts a hardware check and returns its id. One run at a time: the check
+ * saturates every core, so a second would make both unreliable.
+ *
+ * Events arrive via `onDiagnosticsEvent` until one carries `event: 'done'`,
+ * which is emitted on every path including a run that could not start.
+ *
+ * `model` is a model id and is required by the `model` preset, which resolves
+ * it to its gguf and runs only the families that model's graph contains. The
+ * other presets ignore it.
+ */
+export async function startDiagnostics(
+ preset: DiagnosticsPreset,
+ devices: string[] = [],
+ envs: Record<string, string> = {},
+ model?: string
+): Promise<DiagnosticsJob> {
+ return await invoke('plugin:llamacpp|start_diagnostics', {
+ preset,
+ devices,
+ envs,
+ model,
+ })
+}
+
+/**
+ * Asks a run to stop. Resolves once the request is made, not once it lands --
+ * the terminal `done` event is what says the run is over.
+ */
+export async function cancelDiagnostics(job: string): Promise<void> {
+ return await invoke('plugin:llamacpp|cancel_diagnostics', { job })
+}
+
+/**
+ * Subscribes to the run stream. Filter on `job`: events from a superseded run
+ * can still be in flight when a new one starts.
+ */
+export async function onDiagnosticsEvent(
+ handler: (event: DiagnosticsEvent) => void
+): Promise<UnlistenFn> {
+ return await listen<DiagnosticsEvent>(DIAGNOSTICS_EVENT, (e) =>
+ handler(e.payload)
+ )
+}
+
export * from './types'
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts
index 2411891ca..67d31e719 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts
@@ -185,3 +185,148 @@ export interface DeviceList {
free: number
}
+
+// The ggml op diagnostic. These mirror `engine::diagnose::RootEvent` and
+// `engine::diag`; see docs/llamacpp-diagnostics/event-schema.md.
+
+/** Bump in lockstep with `engine::diagnose::SCHEMA_VERSION`. */
+export const DIAGNOSTICS_SCHEMA = 2
+
+/**
+ * `model` runs only the families one gguf's graph contains, at its own
+ * shapes, and needs the model id passed with it.
+ */
+export type DiagnosticsPreset = 'quick' | 'full' | 'model'
+
+/**
+ * A case outcome. `not_supported` is not a failure: the device is saying ggml
+ * will run that op somewhere else, which explains slowness rather than a wrong
+ * answer.
+ */
+export type DiagnosticsCaseStatus =
+ | 'ok'
+ | 'fail'
+ | 'not_supported'
+ | 'skipped'
+
+/**
+ * A family outcome. Only `fail` means a kernel computed the wrong answer; the
+ * other three are the leaf process itself going wrong.
+ */
+export type DiagnosticsFamilyStatus =
+ | 'ok'
+ | 'fail'
+ /**
+ * The family ran cleanly and tested nothing, because its shape filter
+ * matched no case. Inconclusive, never a pass.
+ */
+ | 'no_cases'
+ | 'crashed'
+ | 'hung'
+ | 'cancelled'
+
+export type DiagnosticsDeviceKind =
+ | 'cpu'
+ | 'gpu'
+ | 'igpu'
+ | 'accel'
+ | 'meta'
+ | 'unknown'
+
+export interface DiagnosticsDevice {
+ name: string
+ description: string
+ type: DiagnosticsDeviceKind
+ reg: string
+ memory_total_mib?: number
+ memory_free_mib?: number
+}
+
+export interface DiagnosticsEngineBuild {
+ version: string
+ tag: string
+ commit: string
+}
+
+interface DiagnosticsEventBase {
+ job: string
+}
+
+export type DiagnosticsEvent = DiagnosticsEventBase &
+ (
+ | {
+ event: 'start'
+ schema: number
+ preset: DiagnosticsPreset
+ engine: DiagnosticsEngineBuild
+ families: string[]
+ /** The model file this run was built for, on the `model` preset. */
+ model?: string
+ support_probe: boolean
+ backend_modules: string[]
+ units: number
+ family_timeout_secs: number
+ deadline_secs: number
+ }
+ | ({ event: 'device' } & DiagnosticsDevice)
+ | {
+ event: 'family_start'
+ device: string
+ family: string
+ mode: 'test' | 'support'
+ }
+ | {
+ event: 'case'
+ device: string
+ family: string
+ backend: string
+ op: string
+ params: string
+ mode: string
+ status: DiagnosticsCaseStatus
+ error?: string
+ detail?: string
+ }
+ | {
+ event: 'family_end'
+ device: string
+ family: string
+ status: DiagnosticsFamilyStatus
+ ok: number
+ failed: number
+ not_supported: number
+ millis: number
+ exit?: string
+ last_lines?: string[]
+ unparsed?: string[]
+ }
+ | {
+ event: 'summary'
+ device: string
+ ok: number
+ failed: number
+ not_supported: number
+ families_crashed: number
+ families_hung: number
+ /** Families whose filter matched no case, so they tested nothing. */
+ families_no_cases?: number
+ /** Families the run never reached, because it was cancelled or timed out. */
+ families_cancelled?: number
+ }
+ | {
+ event: 'done'
+ ok: boolean
+ cancelled: boolean
+ /**
+ * At least one family tested nothing, so the run did not cover what
+ * it was asked to. `ok` is false in this case too -- read this flag
+ * to tell it apart from a real failure.
+ */
+ inconclusive?: boolean
+ error?: string
+ }
+ )
+
+export interface DiagnosticsJob {
+ id: string
+}
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md
index f50e6daed..3e1688142 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md
@@ -22,6 +22,8 @@ Default permissions for the llamacpp plugin
- `allow-begin-engine-restart`
- `allow-end-engine-restart`
- `allow-erase-thread-slot-state`
+- `allow-start-diagnostics`
+- `allow-cancel-diagnostics`
- `allow-read-gguf-metadata`
- `allow-find-gguf-tensors`
- `allow-is-model-supported`
@@ -64,6 +66,32 @@ Denies the begin_engine_restart command without any pre-configured scope.
<tr>
<td>
+`llamacpp:allow-cancel-diagnostics`
+
+</td>
+<td>
+
+Enables the cancel_diagnostics command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`llamacpp:deny-cancel-diagnostics`
+
+</td>
+<td>
+
+Denies the cancel_diagnostics command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
`llamacpp:allow-cleanup-llama-processes`
</td>
@@ -506,6 +534,32 @@ Denies the reload_engine_models command without any pre-configured scope.
<tr>
<td>
+`llamacpp:allow-start-diagnostics`
+
+</td>
+<td>
+
+Enables the start_diagnostics command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`llamacpp:deny-start-diagnostics`
+
+</td>
+<td>
+
+Denies the start_diagnostics command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
`llamacpp:allow-start-engine`
</td>
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.toml
index 9fe80c998..8328075df 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.toml
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.toml
@@ -25,6 +25,10 @@ permissions = [
"allow-end-engine-restart",
"allow-erase-thread-slot-state",
+ # The ggml op diagnostic
+ "allow-start-diagnostics",
+ "allow-cancel-diagnostics",
+
# GGUF
"allow-read-gguf-metadata",
"allow-find-gguf-tensors",
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json
index 5b48f185a..0e1ffc586 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json
@@ -306,6 +306,18 @@
"const": "deny-begin-engine-restart",
"markdownDescription": "Denies the begin_engine_restart command without any pre-configured scope."
},
+ {
+ "description": "Enables the cancel_diagnostics command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-cancel-diagnostics",
+ "markdownDescription": "Enables the cancel_diagnostics command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the cancel_diagnostics command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-cancel-diagnostics",
+ "markdownDescription": "Denies the cancel_diagnostics command without any pre-configured scope."
+ },
{
"description": "Enables the cleanup_llama_processes command without any pre-configured scope.",
"type": "string",
@@ -510,6 +522,18 @@
"const": "deny-reload-engine-models",
"markdownDescription": "Denies the reload_engine_models command without any pre-configured scope."
},
+ {
+ "description": "Enables the start_diagnostics command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-start-diagnostics",
+ "markdownDescription": "Enables the start_diagnostics command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the start_diagnostics command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-start-diagnostics",
+ "markdownDescription": "Denies the start_diagnostics command without any pre-configured scope."
+ },
{
"description": "Enables the start_engine command without any pre-configured scope.",
"type": "string",
@@ -547,10 +571,10 @@
"markdownDescription": "Denies the unload_llama_model command without any pre-configured scope."
},
{
- "description": "Default permissions for the llamacpp plugin\n#### This default permission set includes:\n\n- `allow-cleanup-llama-processes`\n- `allow-load-llama-model`\n- `allow-unload-llama-model`\n- `allow-generate-api-key`\n- `allow-ensure-session-ready`\n- `allow-find-session-by-model`\n- `allow-get-loaded-models`\n- `allow-start-engine`\n- `allow-stop-engine`\n- `allow-get-engine-info`\n- `allow-get-engine-version`\n- `allow-reload-engine-models`\n- `allow-engine-devices`\n- `allow-force-stop-engine`\n- `allow-engine-slots-idle`\n- `allow-begin-engine-restart`\n- `allow-end-engine-restart`\n- `allow-erase-thread-slot-state`\n- `allow-read-gguf-metadata`\n- `allow-find-gguf-tensors`\n- `allow-is-model-supported`",
+ "description": "Default permissions for the llamacpp plugin\n#### This default permission set includes:\n\n- `allow-cleanup-llama-processes`\n- `allow-load-llama-model`\n- `allow-unload-llama-model`\n- `allow-generate-api-key`\n- `allow-ensure-session-ready`\n- `allow-find-session-by-model`\n- `allow-get-loaded-models`\n- `allow-start-engine`\n- `allow-stop-engine`\n- `allow-get-engine-info`\n- `allow-get-engine-version`\n- `allow-reload-engine-models`\n- `allow-engine-devices`\n- `allow-force-stop-engine`\n- `allow-engine-slots-idle`\n- `allow-begin-engine-restart`\n- `allow-end-engine-restart`\n- `allow-erase-thread-slot-state`\n- `allow-start-diagnostics`\n- `allow-cancel-diagnostics`\n- `allow-read-gguf-metadata`\n- `allow-find-gguf-tensors`\n- `allow-is-model-supported`",
"type": "string",
"const": "default",
- "markdownDescription": "Default permissions for the llamacpp plugin\n#### This default permission set includes:\n\n- `allow-cleanup-llama-processes`\n- `allow-load-llama-model`\n- `allow-unload-llama-model`\n- `allow-generate-api-key`\n- `allow-ensure-session-ready`\n- `allow-find-session-by-model`\n- `allow-get-loaded-models`\n- `allow-start-engine`\n- `allow-stop-engine`\n- `allow-get-engine-info`\n- `allow-get-engine-version`\n- `allow-reload-engine-models`\n- `allow-engine-devices`\n- `allow-force-stop-engine`\n- `allow-engine-slots-idle`\n- `allow-begin-engine-restart`\n- `allow-end-engine-restart`\n- `allow-erase-thread-slot-state`\n- `allow-read-gguf-metadata`\n- `allow-find-gguf-tensors`\n- `allow-is-model-supported`"
+ "markdownDescription": "Default permissions for the llamacpp plugin\n#### This default permission set includes:\n\n- `allow-cleanup-llama-processes`\n- `allow-load-llama-model`\n- `allow-unload-llama-model`\n- `allow-generate-api-key`\n- `allow-ensure-session-ready`\n- `allow-find-session-by-model`\n- `allow-get-loaded-models`\n- `allow-start-engine`\n- `allow-stop-engine`\n- `allow-get-engine-info`\n- `allow-get-engine-version`\n- `allow-reload-engine-models`\n- `allow-engine-devices`\n- `allow-force-stop-engine`\n- `allow-engine-slots-idle`\n- `allow-begin-engine-restart`\n- `allow-end-engine-restart`\n- `allow-erase-thread-slot-state`\n- `allow-start-diagnostics`\n- `allow-cancel-diagnostics`\n- `allow-read-gguf-metadata`\n- `allow-find-gguf-tensors`\n- `allow-is-model-supported`"
}
]
}
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_diag.cpp b/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_diag.cpp
new file mode 100644
index 000000000..2c957108b
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_diag.cpp
@@ -0,0 +1,474 @@
+// Wraps llama.cpp's own tests/test-backend-ops.cpp, unmodified, so the app can
+// ask "does every ggml op run correctly on this device?" without a fork.
+//
+// The upstream file is one translation unit with a `static` driver and its own
+// main(), so it cannot be linked -- it is #included here after renaming main.
+// What this file adds is ours: a printer that emits JSON, and a driver that runs
+// one device through upstream's `test_backend` (the same function its main()
+// calls). A llama.cpp bump either still compiles against this or fails loudly.
+//
+// It needs ggml's headers only: no libllama and none of LLAMA_BUILD_COMMON.
+//
+// stdout and stderr stay clean. Upstream's per-case diagnostics ("[ADD] ERR =
+// ...", "failed to allocate tensors") are bare printf/fprintf calls, not part
+// of its printer interface; they are redirected into a per-thread buffer below
+// and attached to the JSON event they belong to.
+
+#include "jan_llama_shim.h"
+
+#include "ggml.h"
+#include "ggml-alloc.h"
+#include "ggml-backend.h"
+#include "ggml-cpp.h"
+
+#include "nlohmann/json.hpp"
+
+// Everything the upstream file includes, pulled in *before* printf is
+// redefined: a standard header that mentions the token (libstdc++'s <cstdio>
+// does, as `using ::printf`) would otherwise be mangled by the macro.
+#include <algorithm>
+#include <atomic>
+#include <array>
+#include <cfloat>
+#include <cinttypes>
+#include <cstdarg>
+#include <cstdint>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <ctime>
+#include <future>
+#include <fstream>
+#include <map>
+#include <memory>
+#include <mutex>
+#include <random>
+#include <regex>
+#include <set>
+#include <sstream>
+#include <string>
+#include <string_view>
+#include <thread>
+#include <vector>
+#include <unordered_map>
+
+namespace {
+
+// Text the upstream cases print while running. A case that fails prints its
+// reason and then reports through the printer; the two always happen on the
+// same thread, which is what makes a thread_local the right scope.
+thread_local std::string t_noise;
+
+// A failing run can print once per element of a large tensor on some paths.
+constexpr size_t NOISE_CAP = 8 * 1024;
+
+int noise_vprintf(const char * fmt, va_list ap) {
+ va_list copy;
+ va_copy(copy, ap);
+ const int n = std::vsnprintf(nullptr, 0, fmt, copy);
+ va_end(copy);
+ if (n <= 0) {
+ return n;
+ }
+ if (t_noise.size() < NOISE_CAP) {
+ std::string piece(static_cast<size_t>(n) + 1, '\0');
+ std::vsnprintf(&piece[0], piece.size(), fmt, ap);
+ piece.resize(static_cast<size_t>(n));
+ t_noise += piece;
+ }
+ return n;
+}
+
+int jan_diag_printf(const char * fmt, ...) {
+ va_list ap;
+ va_start(ap, fmt);
+ const int n = noise_vprintf(fmt, ap);
+ va_end(ap);
+ return n;
+}
+
+// Upstream also writes to an arbitrary FILE * (its SQL printer's `fout`); only
+// the two process streams are ours to capture.
+int jan_diag_fprintf(FILE * f, const char * fmt, ...) {
+ va_list ap;
+ va_start(ap, fmt);
+ int n;
+ if (f == stdout || f == stderr) {
+ n = noise_vprintf(fmt, ap);
+ } else {
+ n = std::vfprintf(f, fmt, ap);
+ }
+ va_end(ap);
+ return n;
+}
+
+std::string take_noise() {
+ std::string out = std::move(t_noise);
+ t_noise.clear();
+ while (!out.empty() && (out.back() == '\n' || out.back() == ' ')) {
+ out.pop_back();
+ }
+ return out;
+}
+
+} // namespace
+
+#define main jan_diag_upstream_main
+#define printf jan_diag_printf
+#define fprintf jan_diag_fprintf
+#include "tests/test-backend-ops.cpp"
+#undef fprintf
+#undef printf
+#undef main
+
+namespace {
+
+using json = nlohmann::json;
+
+struct json_printer : public printer {
+ json_printer(jan_llama_diag_cb cb, void * user_data) : cb(cb), user_data(user_data) {}
+
+ // The event sink. Cases run on several threads under -j; upstream
+ // serialises print_test_result, but the other hooks are not guaranteed to
+ // be, so the sink is.
+ void emit(const json & j) {
+ if (cb == nullptr) {
+ return;
+ }
+ // Device descriptions are vendor strings; invalid UTF-8 must not make
+ // dump() throw in the middle of a run.
+ const std::string line = j.dump(-1, ' ', false, json::error_handler_t::replace);
+ std::lock_guard<std::mutex> guard(emit_mutex);
+ cb(line.c_str(), user_data);
+ }
+
+ void print_test_result(const test_result & r) override {
+ const char * status = !r.supported ? "not_supported" : r.passed ? "ok" : "fail";
+ std::string noise = take_noise();
+ // Text left over from a case that printed a reason and then returned
+ // without a result (an allocation failure does) must not be pinned on
+ // the next case, so only a failing one takes it as its detail.
+ if (!noise.empty() && std::strcmp(status, "fail") != 0) {
+ emit({{"event", "log"}, {"text", noise}});
+ noise.clear();
+ }
+ json j = {
+ {"event", "result"},
+ {"backend", r.backend_name},
+ {"op", r.op_name},
+ {"params", r.op_params},
+ {"mode", r.test_mode},
+ {"status", status},
+ };
+ // In support mode upstream reuses error_message for "yes"/"no", which
+ // only restates the status and would read as a failure.
+ if (!r.error_message.empty() && r.test_mode != "support") {
+ j["error"] = r.error_message;
+ }
+ if (!noise.empty()) {
+ j["detail"] = noise;
+ }
+ emit(j);
+ }
+
+ void print_operation(const test_operation_info & info) override {
+ json j = {
+ {"event", "operation"},
+ {"op", info.op_name},
+ {"params", info.op_params},
+ {"backend", info.backend_name},
+ {"status", status_str(info.status)},
+ };
+ if (!info.failure_reason.empty()) {
+ j["reason"] = info.failure_reason;
+ }
+ if (info.has_error) {
+ j["component"] = info.error_component;
+ j["details"] = info.error_details;
+ }
+ emit(j);
+ }
+
+ void print_summary(const test_summary_info & info) override {
+ emit({{"event", "summary"}, {"passed", info.tests_passed}, {"total", info.tests_total}});
+ }
+
+ void print_testing_start(const testing_start_info & info) override {
+ emit({{"event", "testing_start"}, {"devices", info.device_count}});
+ }
+
+ void print_backend_init(const backend_init_info & info) override {
+ json j = {
+ {"event", "backend_init"},
+ {"index", info.device_index},
+ {"total", info.total_devices},
+ {"name", info.device_name},
+ {"skipped", info.skipped},
+ };
+ if (info.skipped) {
+ j["skip_reason"] = info.skip_reason;
+ }
+ if (!info.description.empty()) {
+ j["description"] = info.description;
+ }
+ if (info.has_memory_info) {
+ j["memory_total_mb"] = info.memory_total_mb;
+ j["memory_free_mb"] = info.memory_free_mb;
+ }
+ emit(j);
+ }
+
+ void print_backend_status(const backend_status_info & info) override {
+ emit({{"event", "backend_status"}, {"backend", info.backend_name}, {"status", status_str(info.status)}});
+ }
+
+ void print_overall_summary(const overall_summary_info & info) override {
+ emit({{"event", "overall_summary"},
+ {"passed", info.backends_passed},
+ {"total", info.backends_total},
+ {"all_passed", info.all_passed}});
+ }
+
+ void print_failed_tests(const std::vector<std::string> & failed_tests) override {
+ if (!failed_tests.empty()) {
+ emit({{"event", "failed_tests"}, {"tests", failed_tests}});
+ }
+ }
+
+ // Stream a trailing `log` for anything printed outside a case (upstream's
+ // Metal-only slice run prints a header and per-case failures).
+ void flush_noise() {
+ const std::string noise = take_noise();
+ if (!noise.empty()) {
+ emit({{"event", "log"}, {"text", noise}});
+ }
+ }
+
+ private:
+ static const char * status_str(test_status_t s) {
+ switch (s) {
+ case test_status_t::OK: return "ok";
+ case test_status_t::FAIL: return "fail";
+ case test_status_t::NOT_SUPPORTED: return "not_supported";
+ case test_status_t::SKIPPED: return "skipped";
+ }
+ return "fail";
+ }
+
+ jan_llama_diag_cb cb;
+ void * user_data;
+ std::mutex emit_mutex;
+};
+
+void set_err(char * err, size_t err_len, const std::string & msg) {
+ if (err == nullptr || err_len == 0) {
+ return;
+ }
+ std::snprintf(err, err_len, "%s", msg.c_str());
+}
+
+char * dup_string(const std::string & s) {
+ char * buf = static_cast<char *>(std::malloc(s.size() + 1));
+ if (buf == nullptr) {
+ return nullptr;
+ }
+ std::memcpy(buf, s.c_str(), s.size() + 1);
+ return buf;
+}
+
+const char * device_type_str(enum ggml_backend_dev_type t) {
+ switch (t) {
+ case GGML_BACKEND_DEVICE_TYPE_CPU: return "cpu";
+ case GGML_BACKEND_DEVICE_TYPE_GPU: return "gpu";
+ case GGML_BACKEND_DEVICE_TYPE_IGPU: return "igpu";
+ case GGML_BACKEND_DEVICE_TYPE_ACCEL: return "accel";
+ case GGML_BACKEND_DEVICE_TYPE_META: return "meta";
+ }
+ return "unknown";
+}
+
+// The body of upstream's main() for one named device, minus its argv parsing,
+// its CPU-skipping default and its stdout. Returns 1 when every case passed.
+int run_one_device(int mode_in, const char * backend, const char * op_filter, const char * params_filter,
+ int workers, json_printer & out, std::string & err) {
+ test_mode mode;
+ switch (mode_in) {
+ case JAN_LLAMA_DIAG_MODE_TEST: mode = MODE_TEST; break;
+ case JAN_LLAMA_DIAG_MODE_SUPPORT: mode = MODE_SUPPORT; break;
+ default:
+ err = "unknown diagnostic mode " + std::to_string(mode_in);
+ return -1;
+ }
+ if (backend == nullptr || *backend == '\0') {
+ err = "a backend name is required";
+ return -1;
+ }
+
+ const size_t n_dev = ggml_backend_dev_count();
+ ggml_backend_dev_t dev = nullptr;
+ size_t dev_index = 0;
+ for (size_t i = 0; i < n_dev; i++) {
+ if (std::strcmp(backend, ggml_backend_dev_name(ggml_backend_dev_get(i))) == 0) {
+ dev = ggml_backend_dev_get(i);
+ dev_index = i;
+ break;
+ }
+ }
+ if (dev == nullptr) {
+ err = std::string("no ggml device named ") + backend;
+ return -1;
+ }
+
+ ggml_backend_ptr be(ggml_backend_dev_init(dev, nullptr));
+ if (be == nullptr) {
+ err = std::string("could not initialise the ") + backend + " backend";
+ return -1;
+ }
+
+ ggml_backend_reg_t reg = ggml_backend_dev_backend_reg(dev);
+ auto set_n_threads = (ggml_backend_set_n_threads_t) ggml_backend_reg_get_proc_address(reg, "ggml_backend_set_n_threads");
+ if (set_n_threads) {
+ set_n_threads(be.get(), std::max<int>(1, N_THREADS / 2));
+ }
+
+ size_t free_mem = 0, total_mem = 0;
+ ggml_backend_dev_memory(dev, &free_mem, &total_mem);
+
+ out.print_testing_start(testing_start_info(1));
+ out.print_backend_init(backend_init_info(dev_index, n_dev, ggml_backend_dev_name(dev), false, "",
+ ggml_backend_dev_description(dev), total_mem / 1024 / 1024,
+ free_mem / 1024 / 1024, true));
+
+ const bool ok = test_backend(be.get(), dev, mode, op_filter, params_filter, &out, nullptr, std::max(1, workers));
+ out.flush_noise();
+ out.print_backend_status(backend_status_info(ggml_backend_name(be.get()), ok ? test_status_t::OK : test_status_t::FAIL));
+ // Counted over the devices that ran, not ggml's whole list as upstream's
+ // main() does: a leaf runs one, and "3/3 passed" for a skipped two reads
+ // as a result it is not.
+ out.print_overall_summary(overall_summary_info(ok ? 1 : 0, 1, ok));
+ ggml_quantize_free();
+ return ok ? 1 : 0;
+}
+
+} // namespace
+
+extern "C" {
+
+int jan_llama_diag_run(int mode,
+ const char * backend,
+ const char * op_filter,
+ const char * params_filter,
+ int workers,
+ jan_llama_diag_cb on_event,
+ void * user_data,
+ char * err,
+ size_t err_len) {
+ json_printer out(on_event, user_data);
+ std::string msg;
+ int rc = -1;
+ try {
+ const char * ops = (op_filter != nullptr && *op_filter != '\0') ? op_filter : nullptr;
+ const char * params = (params_filter != nullptr && *params_filter != '\0') ? params_filter : nullptr;
+ rc = run_one_device(mode, backend, ops, params, workers, out, msg);
+ } catch (const std::exception & e) {
+ // Chiefly std::regex_error from a bad -p filter, which upstream's
+ // test_backend lets escape.
+ msg = std::string("the diagnostic threw: ") + e.what();
+ rc = -1;
+ } catch (...) {
+ msg = "the diagnostic threw a non-standard exception";
+ rc = -1;
+ }
+ out.flush_noise();
+
+ json done = {{"event", "done"}, {"ok", rc == 1}};
+ if (rc < 0) {
+ done["error"] = msg;
+ set_err(err, err_len, msg);
+ }
+ out.emit(done);
+ return rc;
+}
+
+// Case counts per op, from the same list `test_backend` runs in test mode.
+// Built the way upstream's show_test_coverage does it (graph construction only,
+// nothing allocated), so it costs a few seconds of CPU and no device.
+char * jan_llama_diag_ops_json(void) {
+ std::map<std::string, size_t> counts;
+ try {
+ // The ops upstream's coverage report considers testable: every op bar
+ // the view-like ones, which have no kernel of their own. They start at
+ // zero so an untested op is listed rather than absent.
+ for (int i = 1; i < GGML_OP_COUNT; i++) {
+ auto op = (enum ggml_op) i;
+ if (op == GGML_OP_VIEW || op == GGML_OP_RESHAPE || op == GGML_OP_PERMUTE || op == GGML_OP_TRANSPOSE ||
+ op == GGML_OP_CONT || op == GGML_OP_GLU || op == GGML_OP_UNARY) {
+ continue;
+ }
+ counts[ggml_op_name(op)];
+ }
+ for (int i = 0; i < GGML_UNARY_OP_COUNT; i++) {
+ counts[ggml_unary_op_name((enum ggml_unary_op) i)];
+ }
+ for (int i = 0; i < GGML_GLU_OP_COUNT; i++) {
+ counts[ggml_glu_op_name((enum ggml_glu_op) i)];
+ }
+
+ ggml_init_params params = {
+ /* .mem_size = */ ggml_tensor_overhead() * 128 + ggml_graph_overhead(),
+ /* .mem_base = */ nullptr,
+ /* .no_alloc = */ true,
+ };
+ // Same size eval() uses, so a case builds the same graph here.
+ for (auto & tc : make_test_cases_eval()) {
+ ggml_context_ptr ctx(ggml_init(params));
+ // Built the way test_case::eval builds it. Upstream's own
+ // show_test_coverage calls the one-argument build_graph, which
+ // GGML_ASSERTs for a case that keeps its weights in a second
+ // context, so a copy of that loop aborts the process.
+ ggml_context_ptr ctx_weights(tc->use_weight_context() ? ggml_init(params) : nullptr);
+ if (!ctx || (tc->use_weight_context() && !ctx_weights)) {
+ continue;
+ }
+ tc->mode = MODE_TEST;
+ // Fusion cases (run_whole_graph) expand into the case's own graph
+ // while building, and upstream's coverage report simply drops them
+ // for that reason. They are real cases in test mode, so keep them.
+ tc->gf = ggml_new_graph(ctx.get());
+ ggml_tensor * out = tc->build_graph(ctx.get(), ctx_weights.get());
+ if (out && out->op != GGML_OP_NONE) {
+ // op_desc is what the -o filter matches against, so a count
+ // here is exactly what that filter would select.
+ counts[tc->op_desc(out)]++;
+ }
+ }
+ } catch (...) {
+ counts.clear();
+ }
+
+ json arr = json::array();
+ for (const auto & kv : counts) {
+ arr.push_back({{"op", kv.first}, {"cases", kv.second}});
+ }
+ return dup_string(arr.dump(-1, ' ', false, json::error_handler_t::replace));
+}
+
+char * jan_llama_diag_backends_json(void) {
+ json arr = json::array();
+ try {
+ for (size_t i = 0; i < ggml_backend_dev_count(); i++) {
+ ggml_backend_dev_t dev = ggml_backend_dev_get(i);
+ arr.push_back({
+ {"name", ggml_backend_dev_name(dev)},
+ {"description", ggml_backend_dev_description(dev)},
+ {"type", device_type_str(ggml_backend_dev_type(dev))},
+ {"reg", ggml_backend_reg_name(ggml_backend_dev_backend_reg(dev))},
+ });
+ }
+ } catch (...) {
+ arr = json::array();
+ }
+ return dup_string(arr.dump(-1, ' ', false, json::error_handler_t::replace));
+}
+
+} // extern "C"
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_shim.h b/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_shim.h
index 22406e020..2ff8590e8 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_shim.h
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_shim.h
@@ -101,6 +101,53 @@ char * jan_llama_device_identities_json(void);
void jan_llama_string_free(char * s);
+// ---- ggml op diagnostics (shim/jan_llama_diag.cpp) ----------------------
+//
+// llama.cpp's own tests/test-backend-ops.cpp, compiled unmodified, driven one
+// device at a time. Like the device listing these need no engine, only the
+// ggml backends to be registered (jan_llama_load_backends) beforehand.
+
+// One JSON object per call, with no trailing newline. Every object has an
+// "event" key: testing_start, backend_init, result, operation, summary,
+// failed_tests, backend_status, overall_summary, log, and last of all `done`.
+// Called on the thread that called jan_llama_diag_run, or on one of its
+// parallel workers; calls never overlap. `line` is valid for the call only.
+// Must not throw.
+typedef void (*jan_llama_diag_cb)(const char * line, void * user_data);
+
+#define JAN_LLAMA_DIAG_MODE_TEST 0 // compare against the CPU reference
+#define JAN_LLAMA_DIAG_MODE_SUPPORT 1 // only probe supports_op
+
+// Runs the cases of one device. `backend` is a ggml device name as listed by
+// jan_llama_diag_backends_json ("CPU", "CUDA0", "Vulkan0"). `op_filter` is
+// upstream's -o (comma separated op names, full case strings or regexes) and
+// `params_filter` its -p (a regex searched in each case's params); NULL or ""
+// means all. `workers` is upstream's -j (test mode only).
+//
+// Returns 1 when every case passed, 0 when one failed, -1 when nothing could
+// run (the reason is in `err`, and in the final `done` event). Never throws.
+// A crash inside a driver still kills the process: that is the caller's
+// isolation to provide.
+int jan_llama_diag_run(int mode,
+ const char * backend,
+ const char * op_filter,
+ const char * params_filter,
+ int workers,
+ jan_llama_diag_cb on_event,
+ void * user_data,
+ char * err,
+ size_t err_len);
+
+// [{"op":"ADD","cases":N}, ...]: every testable ggml op and how many cases
+// test mode would run for it (0 = upstream has no test). Builds the whole case
+// list, so it takes a few seconds. Never NULL; free with jan_llama_string_free.
+char * jan_llama_diag_ops_json(void);
+
+// [{"name","description","type","reg"}] for every registered ggml device,
+// CPU included, type being cpu/gpu/igpu/accel/meta. Never asks a device for
+// its memory. Never NULL; free with jan_llama_string_free.
+char * jan_llama_diag_backends_json(void);
+
// The llama.cpp the shim was compiled against, for the pin assertion in
// build.rs / engine::assert_pinned_version.
const char * jan_llama_version(void); // e.g. "0.9.0"
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/bin/jan-llama-worker.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/bin/jan-llama-worker.rs
index db8b287a0..de041f067 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/bin/jan-llama-worker.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/bin/jan-llama-worker.rs
@@ -9,6 +9,16 @@
//!
//! Usage:
//! jan-llama-worker --preset <router.preset.ini> [--port N] [--models-max N]
+//! jan-llama-worker --diagnose [--diagnose-preset quick|full|model]
+//! [--diagnose-plan JSON] [--device NAME]...
+//! jan-llama-worker --diagnose-run <device> [--mode test|support] [--op RE]
+//! [--params RE] [--workers N]
+//! jan-llama-worker --diagnose-devices | --diagnose-ops | --list-devices
+//!
+//! The diagnose modes are the ggml op check. `--diagnose` is the root: it loads
+//! no ggml and supervises one `--diagnose-run` leaf per device and op family,
+//! printing one JSON event per line (see `engine::diagnose::RootEvent`). Cancel
+//! it the same way the serving mode stops, by closing its stdin.
//!
//! The bearer token comes from `JAN_LLAMA_API_KEY`, never argv: argv is
//! readable by any other process on the machine (`ps`, `/proc/<pid>/cmdline`,
@@ -20,6 +30,9 @@
use std::sync::Arc;
+use tauri_plugin_llamacpp::engine::diag::{DiagMode, DiagRunRequest, FamilyFilter};
+use tauri_plugin_llamacpp::engine::model_plan::{self, ModelPlan};
+use tauri_plugin_llamacpp::engine::diagnose;
use tauri_plugin_llamacpp::engine::http::EngineServer;
use tauri_plugin_llamacpp::engine::preset;
use tauri_plugin_llamacpp::engine::registry::Registry;
@@ -27,6 +40,26 @@ use tauri_plugin_llamacpp::engine::slots::StateStore;
use tauri_plugin_llamacpp::engine::{assert_pinned_version, PINNED_TAG};
use tokio::sync::Mutex;
+/// What this invocation is for. All but [`Mode::Diagnose`] need ggml; the root
+/// deliberately does not, which is what makes it the crash boundary.
+#[derive(Debug, Clone, PartialEq, Eq)]
+enum Mode {
+ Serve,
+ /// Print the offloadable devices as JSON and exit. The desktop process
+ /// links the plugin *without* the engine feature, so it has no ggml to ask
+ /// -- it shells out here, exactly as it used to shell out to
+ /// `llama-server --list-devices`.
+ ListDevices,
+ /// Orchestrate an op diagnostic over leaf processes of this same binary.
+ Diagnose,
+ /// One device, one slice of the op list: the leaf a root spawns.
+ DiagnoseRun(String),
+ /// Every ggml device with its kind and memory, for a root building a plan.
+ DiagnoseDevices,
+ /// Every op family with its case count, for the Full preset.
+ DiagnoseOps,
+}
+
struct Args {
preset: Option<String>,
port: u16,
@@ -35,11 +68,56 @@ struct Args {
/// persistence off entirely: the directory is what the feature is, so
/// there is nothing to keep without a budget for it.
slot_cache_mib: u64,
- /// Print the offloadable devices as JSON and exit. The desktop process
- /// links the plugin *without* the engine feature, so it has no ggml to ask
- /// -- it shells out here, exactly as it used to shell out to
- /// `llama-server --list-devices`.
- list_devices: bool,
+ mode: Mode,
+ diag: DiagArgs,
+}
+
+#[derive(Debug, Clone)]
+struct DiagArgs {
+ preset: diagnose::DiagPreset,
+ mode: DiagMode,
+ op_filter: Option<String>,
+ params_filter: Option<String>,
+ /// Devices the root should check. Empty means every device the probe finds.
+ devices: Vec<String>,
+ /// The model-specific family list, from `--diagnose-plan`. Built by the
+ /// caller (which can read a gguf) rather than here, so the root still
+ /// holds no model and no ggml.
+ plan: Option<ModelPlan>,
+ /// 0 means "pick from the machine", which is only sensible in test mode.
+ workers: u32,
+ family_timeout: std::time::Duration,
+ deadline: std::time::Duration,
+}
+
+impl Default for DiagArgs {
+ fn default() -> Self {
+ Self {
+ preset: diagnose::DiagPreset::Quick,
+ mode: DiagMode::Test,
+ op_filter: None,
+ params_filter: None,
+ devices: Vec::new(),
+ plan: None,
+ workers: 0,
+ family_timeout: diagnose::DEFAULT_FAMILY_TIMEOUT,
+ deadline: diagnose::DEFAULT_DEADLINE,
+ }
+ }
+}
+
+impl DiagArgs {
+ /// Upstream threads test mode only, and a support probe builds graphs
+ /// rather than running them, so parallelism there buys nothing.
+ fn workers(&self) -> u32 {
+ if self.mode == DiagMode::Support {
+ return 1;
+ }
+ match self.workers {
+ 0 => std::thread::available_parallelism().map_or(1, |n| n.get() as u32),
+ n => n,
+ }
+ }
}
/// Read from the environment rather than argv so the token never appears in a
@@ -53,7 +131,8 @@ fn parse_args() -> Result<Args, String> {
port: 0,
models_max: 1,
slot_cache_mib: 0,
- list_devices: false,
+ mode: Mode::Serve,
+ diag: DiagArgs::default(),
};
let mut it = std::env::args().skip(1);
while let Some(flag) = it.next() {
@@ -76,7 +155,53 @@ fn parse_args() -> Result<Args, String> {
.parse()
.map_err(|e| format!("bad --slot-cache-mib: {e}"))?
}
- "--list-devices" => out.list_devices = true,
+ "--list-devices" => out.mode = Mode::ListDevices,
+ "--diagnose" => out.mode = Mode::Diagnose,
+ "--diagnose-run" => out.mode = Mode::DiagnoseRun(value()?),
+ "--diagnose-devices" => out.mode = Mode::DiagnoseDevices,
+ "--diagnose-ops" => out.mode = Mode::DiagnoseOps,
+ "--diagnose-preset" => {
+ out.diag.preset = match value()?.as_str() {
+ "quick" => diagnose::DiagPreset::Quick,
+ "full" => diagnose::DiagPreset::Full,
+ "model" => diagnose::DiagPreset::Model,
+ other => return Err(format!("bad --diagnose-preset: {other}")),
+ }
+ }
+ "--diagnose-plan" => {
+ out.diag.plan = Some(
+ serde_json::from_str(&value()?)
+ .map_err(|e| format!("bad --diagnose-plan: {e}"))?,
+ );
+ out.diag.preset = diagnose::DiagPreset::Model;
+ }
+ "--mode" => {
+ out.diag.mode = match value()?.as_str() {
+ "test" => DiagMode::Test,
+ "support" => DiagMode::Support,
+ other => return Err(format!("bad --mode: {other}")),
+ }
+ }
+ "--op" => out.diag.op_filter = Some(value()?),
+ "--params" => out.diag.params_filter = Some(value()?),
+ "--device" => out.diag.devices.push(value()?),
+ "--workers" => {
+ out.diag.workers = value()?
+ .parse()
+ .map_err(|e| format!("bad --workers: {e}"))?
+ }
+ "--family-timeout" => {
+ out.diag.family_timeout = std::time::Duration::from_secs(
+ value()?
+ .parse()
+ .map_err(|e| format!("bad --family-timeout: {e}"))?,
+ )
+ }
+ "--deadline" => {
+ out.diag.deadline = std::time::Duration::from_secs(
+ value()?.parse().map_err(|e| format!("bad --deadline: {e}"))?,
+ )
+ }
"--version" => {
println!("jan-llama-worker (llama.cpp {PINNED_TAG})");
std::process::exit(0);
@@ -100,9 +225,15 @@ fn device_identities() -> serde_json::Value {
#[tokio::main]
async fn main() {
+ // Before `parse_args`, since a failure to parse is one of the reasons the
+ // root never starts and the supervisor reads reasons off stdout alone.
+ let diagnosing = std::env::args().any(|a| a == "--diagnose");
let args = match parse_args() {
Ok(a) => a,
Err(e) => {
+ if diagnosing {
+ diag_root_fail(e);
+ }
eprintln!("jan-llama-worker: {e}");
std::process::exit(2);
}
@@ -112,22 +243,52 @@ async fn main() {
// common_params and llama_context_params cross the boundary by value and
// their layout has changed repeatedly upstream.
if let Err(e) = assert_pinned_version() {
+ if diagnosing {
+ diag_root_fail(e.to_string());
+ }
eprintln!("jan-llama-worker: {e}");
std::process::exit(3);
}
+ // The root is the one mode that must never hold ggml: it supervises the
+ // leaves that do, so a kernel that aborts cannot take the run with it.
+ if args.mode == Mode::Diagnose {
+ diagnose_root(&args.diag).await;
+ // Exit rather than return: the cancel watcher is a blocking read on
+ // stdin, and tokio waits for its blocking pool when the runtime drops,
+ // so a parent still holding the pipe would keep a finished root alive.
+ // Every event has already been written and flushed.
+ std::process::exit(0);
+ }
+
// Must precede any ggml call, including device enumeration.
tauri_plugin_llamacpp::engine::load_backend_modules();
- if args.list_devices {
- match tauri_plugin_llamacpp::engine::Engine::devices_json() {
- Ok(json) => println!("{json}"),
- Err(e) => {
- eprintln!("jan-llama-worker: could not list devices: {e}");
- std::process::exit(6);
+ match &args.mode {
+ Mode::ListDevices => {
+ match tauri_plugin_llamacpp::engine::Engine::devices_json() {
+ Ok(json) => println!("{json}"),
+ Err(e) => {
+ eprintln!("jan-llama-worker: could not list devices: {e}");
+ std::process::exit(6);
+ }
}
+ return;
+ }
+ Mode::DiagnoseDevices => {
+ arm_leaf_deadline(diagnose::PROBE_TIMEOUT);
+ return print_diagnose_devices();
+ }
+ Mode::DiagnoseOps => {
+ arm_leaf_deadline(diagnose::PROBE_TIMEOUT);
+ return print_diagnose_ops();
}
- return;
+ Mode::DiagnoseRun(device) => {
+ arm_leaf_deadline(args.diag.family_timeout);
+ return diagnose_leaf(device, &args.diag);
+ }
+ Mode::Diagnose => unreachable!("handled above, before ggml is loaded"),
+ Mode::Serve => {}
}
let mut registry = Registry::new(args.models_max);
@@ -245,6 +406,192 @@ async fn main() {
}
}
+/// Exit code for a diagnostic that could not start. A leaf that merely found a
+/// failing case exits 0: its verdict is in the event stream.
+const DIAG_EXIT: i32 = 8;
+
+/// For the probe leaves (`--diagnose-devices`, `--diagnose-ops`), whose stdout
+/// is a single JSON document the root parses -- an event line printed there
+/// would corrupt it. Their reason still reaches the user: a nonzero exit makes
+/// `diagnose::probe` fold the last stderr lines into its error, and the root
+/// then reports that through [`diag_root_fail`].
+fn diag_fail(msg: String) -> ! {
+ eprintln!("jan-llama-worker: {msg}");
+ std::process::exit(DIAG_EXIT);
+}
+
+/// The same, for the root, whose stdout *is* the event stream. Every run ends
+/// with a `done`, so a setup failure reports its reason there rather than only
+/// on a stderr the user never sees.
+fn diag_root_fail(msg: String) -> ! {
+ let done = diagnose::RootEvent::Done {
+ ok: false,
+ cancelled: false,
+ inconclusive: false,
+ error: Some(msg.clone()),
+ };
+ if let Ok(line) = serde_json::to_string(&done) {
+ print_event(&line);
+ }
+ diag_fail(msg)
+}
+
+/// Exit code for a leaf whose reader is gone. Distinct from [`DIAG_EXIT`]
+/// because nothing is left to read either one.
+const DIAG_EXIT_NO_READER: i32 = 9;
+
+/// Exit code for a leaf that outlived the deadline the root gave it.
+const DIAG_EXIT_DEADLINE: i32 = 10;
+
+/// How long after the root's own limit a leaf waits before ending itself. The
+/// root kills an overrunning leaf at the limit exactly, so this only ever
+/// fires when there is no root left to do it.
+const LEAF_DEADLINE_GRACE: std::time::Duration = std::time::Duration::from_secs(30);
+
+/// Ends this leaf if it is still alive well after the root would have killed
+/// it.
+///
+/// The backstop for an orphan: on Windows the plugin cannot kill a
+/// grandchild (see `engine::diagnose_commands::kill_process_group`), and a
+/// leaf wedged inside a driver call writes nothing, so the broken-stdout exit
+/// in [`print_event`] never gets a chance to fire. A plain OS thread is what
+/// makes this work -- it keeps running while the main thread is blocked
+/// inside ggml, which is the state being bounded.
+fn arm_leaf_deadline(limit: std::time::Duration) {
+ let deadline = limit + LEAF_DEADLINE_GRACE;
+ std::thread::spawn(move || {
+ std::thread::sleep(deadline);
+ eprintln!(
+ "jan-llama-worker: no root took this leaf down within {}s; exiting",
+ deadline.as_secs()
+ );
+ std::process::exit(DIAG_EXIT_DEADLINE);
+ });
+}
+
+/// stdout is a pipe to the root, so it is block-buffered; a run that streams
+/// has to flush each line or the UI sees nothing until the leaf exits.
+///
+/// A failed write means the root is gone, and this process is then an orphan
+/// holding a device with nobody to report to, so it stops. On Unix the broken
+/// pipe would raise SIGPIPE and end it anyway; Windows has no such signal,
+/// which is where this is load-bearing -- the plugin cannot kill a
+/// grandchild there (see `kill_process_group`). It does not bound a leaf hung
+/// inside a driver call, which by definition prints nothing.
+fn print_event(line: &str) {
+ use std::io::Write;
+ let mut out = std::io::stdout().lock();
+ if writeln!(out, "{line}").and_then(|()| out.flush()).is_err() {
+ std::process::exit(DIAG_EXIT_NO_READER);
+ }
+}
+
+fn print_diagnose_devices() {
+ use tauri_plugin_llamacpp::engine::diag::{merge_devices, DiagBackend, DiagDeviceMemory};
+ use tauri_plugin_llamacpp::engine::Engine;
+
+ let backends: Vec<DiagBackend> = Engine::diag_backends_json()
+ .map_err(|e| e.to_string())
+ .and_then(|json| serde_json::from_str(&json).map_err(|e| e.to_string()))
+ .unwrap_or_else(|e| diag_fail(format!("could not list ggml devices: {e}")));
+ // Memory is a nice-to-have: a backend that will not report it must not cost
+ // us the device list the plan is built from.
+ let memory: Vec<DiagDeviceMemory> = Engine::devices_json()
+ .ok()
+ .and_then(|json| serde_json::from_str(&json).ok())
+ .unwrap_or_default();
+ println!(
+ "{}",
+ serde_json::to_string(&merge_devices(backends, &memory)).unwrap_or_else(|_| "[]".into())
+ );
+}
+
+fn print_diagnose_ops() {
+ match tauri_plugin_llamacpp::engine::Engine::diag_ops_json() {
+ Ok(json) => println!("{json}"),
+ Err(e) => diag_fail(format!("could not list ops: {e}")),
+ }
+}
+
+/// One device, one slice of the op list. Everything this prints on stdout is an
+/// event; ggml's own logging goes to stderr, which the root reads separately.
+fn diagnose_leaf(device: &str, diag: &DiagArgs) {
+ let request = DiagRunRequest {
+ mode: diag.mode,
+ backend: device.to_string(),
+ op_filter: diag.op_filter.clone(),
+ params_filter: diag.params_filter.clone(),
+ workers: diag.workers(),
+ };
+ let outcome = tauri_plugin_llamacpp::engine::Engine::diag_run(&request, &|line| {
+ print_event(line)
+ });
+ // The wrapper emits `done` on every path it reaches, including a throw.
+ // This covers the one it cannot: a build with no engine to call at all.
+ if let Err(e) = outcome {
+ print_event(
+ &serde_json::json!({"event": "done", "ok": false, "error": e.to_string()}).to_string(),
+ );
+ }
+}
+
+/// Picks the work, then supervises one leaf per device and family.
+async fn diagnose_root(diag: &DiagArgs) {
+ let exe = std::env::current_exe()
+ .unwrap_or_else(|e| diag_root_fail(format!("could not find my own path: {e}")));
+ let spec = diagnose::LeafSpec::new(exe);
+
+ let (mut devices, backend_modules) = diagnose::probe_devices(&spec)
+ .await
+ .unwrap_or_else(|e| diag_root_fail(e));
+ if !diag.devices.is_empty() {
+ devices.retain(|d| diag.devices.iter().any(|name| name == &d.name));
+ if devices.is_empty() {
+ diag_root_fail(format!("no ggml device named {}", diag.devices.join(", ")));
+ }
+ }
+
+ // Asked for even on Quick: a family name upstream does not know runs no
+ // cases and reports a clean pass, which is the one wrong answer a
+ // diagnostic must not give.
+ let tested = diagnose::probe_families(&spec)
+ .await
+ .unwrap_or_else(|e| diag_root_fail(e));
+ let wanted: Vec<FamilyFilter> = match (&diag.plan, diag.preset) {
+ (Some(plan), _) => plan.families.clone(),
+ (None, diagnose::DiagPreset::Full) => tested
+ .iter()
+ .map(|t| FamilyFilter::new(t.clone(), None))
+ .collect(),
+ (None, diagnose::DiagPreset::Quick) => model_plan::quick_families(),
+ (None, diagnose::DiagPreset::Model) => {
+ diag_root_fail("--diagnose-preset model needs a --diagnose-plan".to_string())
+ }
+ };
+ let families = diagnose::tested_families(wanted, &tested).unwrap_or_else(|e| diag_root_fail(e));
+
+ let plan = diagnose::DiagnosePlan {
+ preset: diag.preset,
+ engine: tauri_plugin_llamacpp::diagnostics::EngineBuild::pinned(),
+ devices,
+ families,
+ model: diag.plan.as_ref().map(|p| p.model.clone()),
+ support_probe: true,
+ workers: diag.workers(),
+ backend_modules,
+ family_timeout: diag.family_timeout,
+ deadline: diag.deadline,
+ };
+
+ diagnose::run(&plan, &spec, shutdown_requested(), &mut |event| {
+ match serde_json::to_string(&event) {
+ Ok(line) => print_event(&line),
+ Err(e) => eprintln!("jan-llama-worker: could not encode an event: {e}"),
+ }
+ })
+ .await;
+}
+
/// How long in-flight requests get to finish once shutdown is requested.
const DRAIN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs
index 76cab90d9..368ee1657 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs
@@ -5,6 +5,7 @@ use std::sync::Arc;
use std::time::Duration;
use tauri::{Emitter, Manager, Runtime, State};
+use crate::diagnostics;
use crate::engine::preset;
use crate::engine::worker::FitMark;
use crate::error::{ErrorCode, LlamacppError, ServerError, ServerResult};
@@ -169,6 +170,78 @@ async fn explain_load_failure(
}
}
+/// A failed load with everything a bug report needs attached: the settings the
+/// preset asked for, the model's architecture and quantization, the machine's
+/// GPUs, the backends the worker loaded, the engine build and the worker's log
+/// since the load began. Best effort throughout: a piece that cannot be read is
+/// left out rather than hiding the failure it describes.
+async fn diagnose_load_failure(
+ state: &LlamacppState,
+ port: u16,
+ model_id: &str,
+ mark: Option<FitMark>,
+ err: LlamacppError,
+) -> LlamacppError {
+ let mut err = explain_load_failure(state, port, model_id, mark, err).await;
+ let (ini_path, log, log_cut, backends) = {
+ let guard = state.engine.lock().await;
+ match guard.as_ref().filter(|h| h.port == port) {
+ Some(h) => {
+ let (lines, cut) = mark.map(|m| h.log_since(m)).unwrap_or_default();
+ (Some(h.preset_path.clone()), lines, cut, h.backends())
+ }
+ None => (None, Vec::new(), false, Vec::new()),
+ }
+ };
+ let ini = match &ini_path {
+ Some(path) => tokio::fs::read_to_string(path).await.unwrap_or_default(),
+ None => String::new(),
+ };
+ let model_path = preset::value(&ini, model_id, "model");
+ let (architecture, quantization) = match &model_path {
+ Some(path) => match crate::gguf::utils::read_gguf_metadata_internal(path.clone()).await {
+ Ok(meta) => diagnostics::model_traits(&meta.metadata),
+ Err(_) => (None, None),
+ },
+ None => (None, None),
+ };
+ let gpus = tokio::task::spawn_blocking(machine_gpus)
+ .await
+ .unwrap_or_default();
+ let (log, log_truncated) = diagnostics::cap_log(&log, diagnostics::MAX_LOG_BYTES, log_cut);
+ err.diagnostics = Some(Box::new(diagnostics::LoadDiagnostics {
+ model_file: model_path.as_deref().map(diagnostics::file_name),
+ architecture,
+ quantization,
+ request: diagnostics::LoadRequest::from_preset(&ini, model_id),
+ gpus,
+ backends,
+ engine: diagnostics::EngineBuild::pinned(),
+ log,
+ log_truncated,
+ }));
+ err
+}
+
+/// The GPUs the machine reports, with their driver and memory. Blocking: the
+/// vendor libraries are queried for current usage.
+fn machine_gpus() -> Vec<diagnostics::GpuReport> {
+ tauri_plugin_hardware::get_system_info()
+ .gpus
+ .iter()
+ .map(|gpu| {
+ let usage = gpu.get_usage();
+ diagnostics::GpuReport {
+ name: gpu.name.clone(),
+ driver_version: gpu.driver_version.clone(),
+ total_mib: gpu.total_memory,
+ free_mib: (usage.total_memory > 0)
+ .then(|| usage.total_memory.saturating_sub(usage.used_memory)),
+ }
+ })
+ .collect()
+}
+
/// Checks the process, which is the one thing that tells the two causes of an
/// unreachable worker apart: a crash, or something between Jan and 127.0.0.1.
///
@@ -568,7 +641,7 @@ async fn post_load<R: Runtime>(
if !body.to_lowercase().contains("already") {
progress_task.abort();
let err = load_rejection_error(status.as_u16(), &body);
- let err = explain_load_failure(&state, port, model_id, mark, err).await;
+ let err = diagnose_load_failure(&state, port, model_id, mark, err).await;
return Err(ServerError::Llamacpp(err));
}
}
@@ -597,7 +670,7 @@ async fn post_load<R: Runtime>(
progress_task.abort();
match result {
Err(ServerError::Llamacpp(err)) => Err(ServerError::Llamacpp(
- explain_load_failure(&state, port, model_id, mark, err).await,
+ diagnose_load_failure(&state, port, model_id, mark, err).await,
)),
other => other,
}
@@ -1295,6 +1368,44 @@ mod unreachable_worker_tests {
state.engine.lock().await.take().unwrap().kill().await;
}
+ // The bug report for a failed load: what was asked, what the worker said
+ // while it ran, and no directory of the user's in the model name.
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn a_failed_load_carries_the_request_the_backends_and_the_worker_log() {
+ let dir = tempfile::tempdir().unwrap();
+ let (state, port) = fit_worker(
+ dir.path(),
+ "echo 'load_backend: loaded CPU backend from /home/bob/jan/libggml-cpu.so' >&2\n\
+ sleep 0.2\n\
+ echo 'llama_model_load: error loading model: bad tensor' >&2",
+ "[*]\nctx-size = 8192\n[m]\nmodel = /home/bob/models/qwen.gguf\nn-gpu-layers = 12\n",
+ )
+ .await;
+ // The backend line is printed at start, before the load's mark.
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ let mark = fit_mark(&state, port).await;
+ tokio::time::sleep(Duration::from_millis(400)).await;
+
+ let failed = LlamacppError::from_load_failure("failed to load model");
+ let err = diagnose_load_failure(&state, port, "m", mark, failed).await;
+ let d = err.diagnostics.expect("diagnostics are attached");
+ assert_eq!(d.model_file.as_deref(), Some("qwen.gguf"));
+ assert_eq!(d.request.ctx_size.as_deref(), Some("8192"));
+ assert_eq!(d.request.n_gpu_layers.as_deref(), Some("12"));
+ assert_eq!(d.backends, ["CPU (libggml-cpu.so)"]);
+ assert!(d.log.contains("bad tensor"), "{}", d.log);
+ assert!(!d.log.contains("load_backend"), "printed before the mark: {}", d.log);
+ assert_eq!(d.engine.tag, crate::engine::PINNED_TAG);
+ let wire = serde_json::to_string(&json(&LlamacppError {
+ diagnostics: Some(d),
+ ..LlamacppError::from_load_failure("x")
+ }))
+ .unwrap();
+ assert!(!wire.contains("/home/bob"), "{wire}");
+ stop(state).await;
+ }
+
// No GPU: fit gives up out loud, and the load that follows fails with
// whatever llama.cpp hit next. The fit line is the cause.
#[cfg(unix)]
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/diagnostics.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/diagnostics.rs
new file mode 100644
index 000000000..8d7dfbaf5
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/diagnostics.rs
@@ -0,0 +1,227 @@
+//! What a failed model load carries so a bug report can be acted on without a
+//! back-and-forth: the request, the machine, the engine and the engine's own
+//! log. Everything stays local; it rides on [`crate::error::LlamacppError`] to
+//! the UI, which formats it for the user to paste.
+
+use serde::{Deserialize, Serialize};
+
+use crate::engine::preset;
+
+/// Largest captured log kept on an error. The newest lines win: the load's
+/// verdict is printed last, and the worker's own backend announcements are
+/// reported separately.
+pub const MAX_LOG_BYTES: usize = 64 * 1024;
+
+/// The settings a load was asked for, as the preset spells them. `None` is a
+/// setting the preset leaves to llama.cpp's default.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct LoadRequest {
+ pub ctx_size: Option<String>,
+ pub n_gpu_layers: Option<String>,
+ pub load_mode: Option<String>,
+ pub flash_attn: Option<String>,
+ pub cache_type_k: Option<String>,
+ pub cache_type_v: Option<String>,
+ pub device: Option<String>,
+ pub fit: Option<String>,
+}
+
+impl LoadRequest {
+ pub fn from_preset(ini: &str, model_id: &str) -> Self {
+ let get = |key: &str| preset::value(ini, model_id, key);
+ Self {
+ ctx_size: get("ctx-size"),
+ n_gpu_layers: get("n-gpu-layers"),
+ load_mode: get("load-mode"),
+ flash_attn: get("flash-attn"),
+ cache_type_k: get("cache-type-k"),
+ cache_type_v: get("cache-type-v"),
+ device: get("device"),
+ fit: get("fit"),
+ }
+ }
+}
+
+/// A GPU as the machine reports it, with memory in MiB.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct GpuReport {
+ pub name: String,
+ pub driver_version: String,
+ pub total_mib: u64,
+ /// `None` when the vendor gives no usage figure.
+ pub free_mib: Option<u64>,
+}
+
+/// The pinned engine, whose tag is mutable upstream while the commit is not.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct EngineBuild {
+ pub version: String,
+ pub tag: String,
+ pub commit: String,
+}
+
+impl EngineBuild {
+ pub fn pinned() -> Self {
+ Self {
+ version: crate::engine::PINNED_VERSION.to_string(),
+ tag: crate::engine::PINNED_TAG.to_string(),
+ commit: crate::engine::PINNED_COMMIT.to_string(),
+ }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct LoadDiagnostics {
+ /// File name only: the directory is the user's and means nothing to us.
+ pub model_file: Option<String>,
+ pub architecture: Option<String>,
+ pub quantization: Option<String>,
+ pub request: LoadRequest,
+ pub gpus: Vec<GpuReport>,
+ /// Backend modules the worker loaded, e.g. `CUDA (libggml-cuda.so)`.
+ pub backends: Vec<String>,
+ pub engine: EngineBuild,
+ /// What the worker printed during the load, capped at [`MAX_LOG_BYTES`].
+ pub log: String,
+ /// True when older lines were dropped to fit the cap or the buffer.
+ pub log_truncated: bool,
+}
+
+/// The last name in a path of either separator style. A model path comes from
+/// the preset, which can hold a Windows path while this runs on Unix in tests.
+pub fn file_name(path: &str) -> String {
+ path.rsplit(['/', '\\']).next().unwrap_or(path).to_string()
+}
+
+/// Joins `lines`, dropping the oldest until the text fits `max_bytes`. The
+/// flag is true when anything was dropped, here or by the caller
+/// (`already_truncated`).
+pub fn cap_log(lines: &[String], max_bytes: usize, already_truncated: bool) -> (String, bool) {
+ let mut kept = 0usize;
+ let mut size = 0usize;
+ for line in lines.iter().rev() {
+ let next = size + line.len() + 1;
+ if next > max_bytes {
+ break;
+ }
+ size = next;
+ kept += 1;
+ }
+ let start = lines.len() - kept;
+ (
+ lines[start..].join("\n"),
+ already_truncated || start > 0,
+ )
+}
+
+/// llama.cpp's name for a `general.file_type` value (`enum llama_ftype`).
+pub fn quantization_name(file_type: u32) -> Option<&'static str> {
+ Some(match file_type {
+ 0 => "F32",
+ 1 => "F16",
+ 2 => "Q4_0",
+ 3 => "Q4_1",
+ 7 => "Q8_0",
+ 8 => "Q5_0",
+ 9 => "Q5_1",
+ 10 => "Q2_K",
+ 11 => "Q3_K_S",
+ 12 => "Q3_K_M",
+ 13 => "Q3_K_L",
+ 14 => "Q4_K_S",
+ 15 => "Q4_K_M",
+ 16 => "Q5_K_S",
+ 17 => "Q5_K_M",
+ 18 => "Q6_K",
+ 19 => "IQ2_XXS",
+ 20 => "IQ2_XS",
+ 21 => "Q2_K_S",
+ 22 => "IQ3_XS",
+ 23 => "IQ3_XXS",
+ 24 => "IQ1_S",
+ 25 => "IQ4_NL",
+ 26 => "IQ3_S",
+ 27 => "IQ3_M",
+ 28 => "IQ2_S",
+ 29 => "IQ2_M",
+ 30 => "IQ4_XS",
+ 31 => "IQ1_M",
+ 32 => "BF16",
+ 36 => "TQ1_0",
+ 37 => "TQ2_0",
+ 38 => "MXFP4_MOE",
+ _ => return None,
+ })
+}
+
+/// Architecture and quantization out of GGUF metadata.
+pub fn model_traits(
+ metadata: &std::collections::HashMap<String, String>,
+) -> (Option<String>, Option<String>) {
+ let architecture = metadata.get("general.architecture").cloned();
+ let quantization = metadata
+ .get("general.file_type")
+ .and_then(|v| v.parse::<u32>().ok())
+ .map(|t| quantization_name(t).map_or_else(|| format!("ftype {t}"), str::to_string));
+ (architecture, quantization)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_request_reads_the_model_line_over_the_shared_block() {
+ let ini = "[*]\nctx-size = 8192\nflash-attn = auto\n[m]\nctx-size = 4096\nn-gpu-layers = 20\ndevice = Vulkan0\n";
+ let r = LoadRequest::from_preset(ini, "m");
+ assert_eq!(r.ctx_size.as_deref(), Some("4096"));
+ assert_eq!(r.n_gpu_layers.as_deref(), Some("20"));
+ assert_eq!(r.flash_attn.as_deref(), Some("auto"));
+ assert_eq!(r.device.as_deref(), Some("Vulkan0"));
+ assert_eq!(r.load_mode, None);
+ }
+
+ #[test]
+ fn a_model_path_is_reduced_to_its_file_name() {
+ assert_eq!(file_name("/home/bob/models/qwen.gguf"), "qwen.gguf");
+ assert_eq!(file_name(r"C:\Users\bob\models\qwen.gguf"), "qwen.gguf");
+ assert_eq!(file_name("qwen.gguf"), "qwen.gguf");
+ }
+
+ #[test]
+ fn the_log_cap_keeps_the_newest_lines_and_says_so() {
+ let lines: Vec<String> = (0..10).map(|i| format!("line {i}")).collect();
+ let (all, cut) = cap_log(&lines, MAX_LOG_BYTES, false);
+ assert!(!cut);
+ assert_eq!(all.lines().count(), 10);
+
+ // "line N" is 6 bytes plus a newline: room for three.
+ let (tail, cut) = cap_log(&lines, 21, false);
+ assert!(cut);
+ assert_eq!(tail, "line 7\nline 8\nline 9");
+
+ let (_, cut) = cap_log(&lines, MAX_LOG_BYTES, true);
+ assert!(cut, "a truncation upstream of the cap still counts");
+ assert_eq!(cap_log(&[], 10, false), (String::new(), false));
+ }
+
+ #[test]
+ fn quantization_and_architecture_come_from_the_gguf_metadata() {
+ let meta = [
+ ("general.architecture", "qwen3"),
+ ("general.file_type", "15"),
+ ]
+ .into_iter()
+ .map(|(k, v)| (k.to_string(), v.to_string()))
+ .collect();
+ assert_eq!(
+ model_traits(&meta),
+ (Some("qwen3".into()), Some("Q4_K_M".into()))
+ );
+
+ let odd = [("general.file_type".to_string(), "999".to_string())]
+ .into_iter()
+ .collect();
+ assert_eq!(model_traits(&odd), (None, Some("ftype 999".into())));
+ }
+}
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/commands.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/commands.rs
index dd41e1f94..b923a8dc5 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/commands.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/commands.rs
@@ -61,7 +61,7 @@ fn generate_worker_key() -> String {
/// so its absence always means the install is damaged rather than that the user
/// has something to configure, and which directory came up empty is the only
/// thing that distinguishes the ways that happens.
-fn resolve_worker_exe<R: tauri::Runtime>(
+pub(crate) fn resolve_worker_exe<R: tauri::Runtime>(
app_handle: &tauri::AppHandle<R>,
) -> Result<PathBuf, String> {
if let Some(p) = std::env::var_os("JAN_LLAMA_WORKER_BIN") {
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/diag.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/diag.rs
new file mode 100644
index 000000000..aeac5b35f
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/diag.rs
@@ -0,0 +1,404 @@
+//! Types for the ggml op diagnostic: what to run, and the JSON events the
+//! upstream `test-backend-ops` wrapper (`shim/jan_llama_diag.cpp`) emits.
+//!
+//! Deliberately not behind the `engine` feature: the desktop process links
+//! this crate without ggml and still has to parse what a worker prints, and
+//! these are pure data so `make test-rust` covers them.
+
+use serde::{Deserialize, Serialize};
+
+/// What a run checks. Perf and grad are upstream modes too and are left out on
+/// purpose: neither answers "does this op work here".
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum DiagMode {
+ /// Run each case on the device and on the CPU reference and compare.
+ Test,
+ /// Only ask the device whether it supports each case's ops.
+ Support,
+}
+
+/// One device, one slice of the cases. This is the unit a leaf process runs.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct DiagRunRequest {
+ pub mode: DiagMode,
+ /// A ggml device name as `Engine::diag_backends_json` lists it ("CPU",
+ /// "CUDA0", "Vulkan0").
+ pub backend: String,
+ /// Upstream's `-o`: comma separated op names, full case strings or regexes.
+ pub op_filter: Option<String>,
+ /// Upstream's `-p`: a regex searched in each case's parameter string.
+ pub params_filter: Option<String>,
+ /// Upstream's `-j`. Test mode only; 1 is the sequential default.
+ pub workers: u32,
+}
+
+/// One slice of the op list: a family, optionally narrowed to the shapes a
+/// particular model uses.
+///
+/// `params` is upstream's `-p`, a regex searched in each case's parameter
+/// string. Those strings are not a stable contract, so a filter that matches
+/// nothing must never read as a pass; the root reports such a unit as
+/// [`crate::engine::diagnose::FamilyStatus::NoCases`] rather than `Ok`.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct FamilyFilter {
+ pub family: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub params: Option<String>,
+}
+
+impl FamilyFilter {
+ pub fn new(family: impl Into<String>, params: Option<&str>) -> Self {
+ Self {
+ family: family.into(),
+ params: params.map(str::to_string),
+ }
+ }
+}
+
+/// A case's outcome. `NotSupported` is not a failure: it is the device saying
+/// ggml will run that op somewhere else, which explains slowness.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum DiagStatus {
+ Ok,
+ Fail,
+ NotSupported,
+ Skipped,
+}
+
+/// One finished case. Its own struct because the root's `case` event
+/// ([`crate::engine::diagnose`]) forwards exactly this, tagged with the device
+/// and family it came from, rather than restating the fields.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct DiagCase {
+ pub backend: String,
+ pub op: String,
+ pub params: String,
+ pub mode: String,
+ pub status: DiagStatus,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub error: Option<String>,
+ /// The text upstream printed while the case ran (the offending tensor and
+ /// its error), present only on a failure.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub detail: Option<String>,
+}
+
+/// One ggml device, as a `--diagnose-devices` leaf reports it. ggml knows no
+/// driver version; the plugin joins that in by name.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct DiagDevice {
+ pub name: String,
+ pub description: String,
+ #[serde(rename = "type")]
+ pub kind: DiagDeviceKind,
+ pub reg: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub memory_total_mib: Option<u64>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub memory_free_mib: Option<u64>,
+}
+
+/// An entry of `Engine::devices_json`, which reports memory but omits the CPU.
+#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
+pub struct DiagDeviceMemory {
+ pub id: String,
+ #[serde(rename = "mem")]
+ pub total_mib: u64,
+ #[serde(rename = "free")]
+ pub free_mib: u64,
+}
+
+/// Joins the two listings ggml offers: `diag_backends_json` knows every device
+/// and its kind, `devices_json` knows how much memory the offloadable ones
+/// have. Kept apart upstream of here because asking a CUDA device for its
+/// memory creates a context the process then holds.
+pub fn merge_devices(backends: Vec<DiagBackend>, memory: &[DiagDeviceMemory]) -> Vec<DiagDevice> {
+ backends
+ .into_iter()
+ .map(|b| {
+ let mem = memory.iter().find(|m| m.id == b.name);
+ DiagDevice {
+ name: b.name,
+ description: b.description,
+ kind: b.kind,
+ reg: b.reg,
+ memory_total_mib: mem.map(|m| m.total_mib),
+ memory_free_mib: mem.map(|m| m.free_mib),
+ }
+ })
+ .collect()
+}
+
+/// One line of the wrapper's JSON stream, discriminated by its `event` key.
+///
+/// The field names are upstream's `printer` structs, snake_cased. An event the
+/// parser does not know deserializes to `Unknown`, so a llama.cpp bump that adds
+/// one cannot break a reader that only wants results.
+#[derive(Debug, Clone, PartialEq, Deserialize)]
+#[serde(tag = "event", rename_all = "snake_case")]
+pub enum DiagEvent {
+ TestingStart {
+ devices: usize,
+ },
+ BackendInit {
+ index: usize,
+ total: usize,
+ name: String,
+ skipped: bool,
+ #[serde(default)]
+ skip_reason: Option<String>,
+ #[serde(default)]
+ description: Option<String>,
+ #[serde(default)]
+ memory_total_mb: Option<u64>,
+ #[serde(default)]
+ memory_free_mb: Option<u64>,
+ },
+ Result(DiagCase),
+ /// Upstream's per-operation report, which only its grad mode and a few
+ /// error paths use; kept so nothing the printer interface says is dropped.
+ Operation {
+ op: String,
+ params: String,
+ backend: String,
+ status: DiagStatus,
+ #[serde(default)]
+ reason: Option<String>,
+ #[serde(default)]
+ component: Option<String>,
+ #[serde(default)]
+ details: Option<String>,
+ },
+ /// The per-device case tally. Not-supported and skipped cases are not in it.
+ Summary {
+ passed: usize,
+ total: usize,
+ },
+ /// `op(params)` of every failed case, as upstream spells them, so a case
+ /// can be re-run through `op_filter`.
+ FailedTests {
+ tests: Vec<String>,
+ },
+ BackendStatus {
+ backend: String,
+ status: DiagStatus,
+ },
+ OverallSummary {
+ passed: usize,
+ total: usize,
+ all_passed: bool,
+ },
+ /// Text upstream printed outside a case's result.
+ Log {
+ text: String,
+ },
+ /// Always the last event of a run. `error` is set when nothing could run.
+ Done {
+ ok: bool,
+ #[serde(default)]
+ error: Option<String>,
+ },
+ #[serde(other)]
+ Unknown,
+}
+
+impl DiagEvent {
+ pub fn parse(line: &str) -> Result<Self, serde_json::Error> {
+ serde_json::from_str(line)
+ }
+}
+
+/// Running totals over the `Result` events of one stream.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct DiagTally {
+ pub ok: usize,
+ pub failed: usize,
+ pub not_supported: usize,
+}
+
+impl DiagTally {
+ pub fn record(&mut self, event: &DiagEvent) {
+ if let DiagEvent::Result(case) = event {
+ match case.status {
+ DiagStatus::Ok => self.ok += 1,
+ DiagStatus::Fail => self.failed += 1,
+ DiagStatus::NotSupported => self.not_supported += 1,
+ DiagStatus::Skipped => {}
+ }
+ }
+ }
+}
+
+/// An entry of `Engine::diag_ops_json`: how many cases test mode runs for an
+/// op family. Zero means upstream has no test for it.
+#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
+pub struct DiagOp {
+ pub op: String,
+ pub cases: usize,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum DiagDeviceKind {
+ Cpu,
+ Gpu,
+ Igpu,
+ Accel,
+ Meta,
+ #[serde(other)]
+ Unknown,
+}
+
+/// An entry of `Engine::diag_backends_json`.
+#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
+pub struct DiagBackend {
+ pub name: String,
+ pub description: String,
+ #[serde(rename = "type")]
+ pub kind: DiagDeviceKind,
+ /// The backend registry the device belongs to ("CPU", "CUDA", "Vulkan").
+ pub reg: String,
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_passing_result_parses() {
+ let e = DiagEvent::parse(
+ r#"{"event":"result","backend":"CPU","op":"ADD","params":"type=f32","mode":"test","status":"ok"}"#,
+ )
+ .unwrap();
+ assert_eq!(
+ e,
+ DiagEvent::Result(DiagCase {
+ backend: "CPU".into(),
+ op: "ADD".into(),
+ params: "type=f32".into(),
+ mode: "test".into(),
+ status: DiagStatus::Ok,
+ error: None,
+ detail: None,
+ })
+ );
+ }
+
+ #[test]
+ fn a_failure_keeps_the_text_upstream_printed() {
+ let e = DiagEvent::parse(
+ r#"{"event":"result","backend":"Vulkan0","op":"MUL_MAT","params":"k=3","mode":"test","status":"fail","error":"compare failed","detail":"[MUL_MAT] ERR = 0.5 > 0.0001"}"#,
+ )
+ .unwrap();
+ let DiagEvent::Result(case) = e else {
+ panic!("not a result");
+ };
+ assert_eq!(case.status, DiagStatus::Fail);
+ assert_eq!(case.error.as_deref(), Some("compare failed"));
+ assert!(case.detail.unwrap().contains("ERR"));
+ }
+
+ #[test]
+ fn the_device_events_parse_with_and_without_memory() {
+ let skipped =
+ DiagEvent::parse(r#"{"event":"backend_init","index":0,"total":2,"name":"CPU","skipped":true,"skip_reason":"Skipping"}"#)
+ .unwrap();
+ assert!(matches!(skipped, DiagEvent::BackendInit { skipped: true, memory_free_mb: None, .. }));
+
+ let live = DiagEvent::parse(
+ r#"{"event":"backend_init","index":1,"total":2,"name":"CUDA0","skipped":false,"description":"RTX","memory_total_mb":24576,"memory_free_mb":20000}"#,
+ )
+ .unwrap();
+ assert!(matches!(live, DiagEvent::BackendInit { memory_total_mb: Some(24576), .. }));
+ }
+
+ #[test]
+ fn the_stream_terminators_parse() {
+ assert_eq!(
+ DiagEvent::parse(r#"{"event":"done","ok":false,"error":"no ggml device named X"}"#).unwrap(),
+ DiagEvent::Done { ok: false, error: Some("no ggml device named X".into()) }
+ );
+ assert_eq!(
+ DiagEvent::parse(r#"{"event":"overall_summary","passed":1,"total":1,"all_passed":true}"#).unwrap(),
+ DiagEvent::OverallSummary { passed: 1, total: 1, all_passed: true }
+ );
+ }
+
+ #[test]
+ fn an_event_from_a_newer_wrapper_is_unknown_not_an_error() {
+ assert_eq!(
+ DiagEvent::parse(r#"{"event":"something_new","x":1}"#).unwrap(),
+ DiagEvent::Unknown
+ );
+ }
+
+ #[test]
+ fn a_line_that_is_not_an_event_is_an_error() {
+ assert!(DiagEvent::parse("Testing 1 devices").is_err());
+ assert!(DiagEvent::parse(r#"{"no_event_key":1}"#).is_err());
+ }
+
+ #[test]
+ fn the_tally_counts_results_and_ignores_everything_else() {
+ let line = |status: &str| {
+ DiagEvent::parse(&format!(
+ r#"{{"event":"result","backend":"CPU","op":"ADD","params":"","mode":"test","status":"{status}"}}"#
+ ))
+ .unwrap()
+ };
+ let mut t = DiagTally::default();
+ for e in [
+ line("ok"),
+ line("ok"),
+ line("fail"),
+ line("not_supported"),
+ line("skipped"),
+ DiagEvent::Summary { passed: 2, total: 3 },
+ ] {
+ t.record(&e);
+ }
+ assert_eq!(t, DiagTally { ok: 2, failed: 1, not_supported: 1 });
+ }
+
+ #[test]
+ fn a_device_keeps_its_kind_and_gains_memory_only_if_ggml_reports_it() {
+ let backends = vec![
+ DiagBackend {
+ name: "CPU".into(),
+ description: "12th Gen Intel".into(),
+ kind: DiagDeviceKind::Cpu,
+ reg: "CPU".into(),
+ },
+ DiagBackend {
+ name: "CUDA0".into(),
+ description: "RTX 3090".into(),
+ kind: DiagDeviceKind::Gpu,
+ reg: "CUDA".into(),
+ },
+ ];
+ let memory = vec![DiagDeviceMemory {
+ id: "CUDA0".into(),
+ total_mib: 24576,
+ free_mib: 20000,
+ }];
+ let merged = merge_devices(backends, &memory);
+ assert_eq!(merged[0].memory_total_mib, None, "the CPU is not listed");
+ assert_eq!(merged[0].kind, DiagDeviceKind::Cpu);
+ assert_eq!(merged[1].memory_free_mib, Some(20000));
+ }
+
+ #[test]
+ fn the_op_and_backend_listings_parse() {
+ let ops: Vec<DiagOp> = serde_json::from_str(r#"[{"op":"ADD","cases":120},{"op":"FOO","cases":0}]"#).unwrap();
+ assert_eq!(ops[0], DiagOp { op: "ADD".into(), cases: 120 });
+
+ let b: Vec<DiagBackend> = serde_json::from_str(
+ r#"[{"name":"CUDA0","description":"RTX 3090","type":"gpu","reg":"CUDA"},{"name":"X","description":"","type":"npu","reg":"X"}]"#,
+ )
+ .unwrap();
+ assert_eq!(b[0].kind, DiagDeviceKind::Gpu);
+ assert_eq!(b[1].kind, DiagDeviceKind::Unknown);
+ }
+}
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/diagnose.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/diagnose.rs
new file mode 100644
index 000000000..9a46819ad
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/diagnose.rs
@@ -0,0 +1,960 @@
+//! The root of the ggml op diagnostic: it picks the work, runs each slice in a
+//! leaf process, and prints one JSON event per line.
+//!
+//! The root never loads ggml and never registers a backend, so no kernel can
+//! take it down; a `GGML_ASSERT` costs the leaf that ran it. That is also why
+//! this module is outside the `engine` feature gate: it is process supervision
+//! plus bookkeeping, so `cargo test` covers it with no C++ toolchain, exactly
+//! as [`super::diag`] and [`super::worker`] are.
+//!
+//! Nothing here touches the serving engine. The root holds no registry, opens
+//! no preset and speaks to no worker port, so a leaf crash cannot unload a
+//! model the user has resident.
+
+use std::collections::VecDeque;
+use std::path::PathBuf;
+use std::process::Stdio;
+use std::time::Duration;
+
+use serde::{Deserialize, Serialize};
+use tokio::io::{AsyncBufReadExt, BufReader};
+use tokio::process::Command;
+
+use crate::diagnostics::EngineBuild;
+
+use super::diag::{
+ DiagCase, DiagDevice, DiagEvent, DiagMode, DiagRunRequest, DiagTally, FamilyFilter,
+};
+use super::worker::describe_exit;
+
+/// Version of the event stream below. Bumped when an existing event changes
+/// shape; a *new* event does not need it, since readers treat an unknown
+/// `event` as `Unknown` (see [`super::diag::DiagEvent`]).
+///
+/// 2 added [`FamilyStatus::NoCases`], `summary.families_no_cases`,
+/// `done.inconclusive` and `start.model`.
+pub const SCHEMA_VERSION: u32 = 2;
+
+/// The family name standing for "every op", used by the support probe.
+pub const ALL_FAMILIES: &str = "*";
+
+/// Narrows `wanted` to the families upstream actually has cases for.
+///
+/// The guard that keeps a preset honest in its *family* dimension: a name
+/// upstream has dropped runs no cases and would report a clean pass, which is
+/// the one wrong answer a diagnostic must not give. The shape dimension cannot
+/// be checked ahead of time and is caught at the other end, by
+/// [`FamilyStatus::NoCases`].
+///
+/// Nothing left is an error whatever was asked for: the support probe alone
+/// would otherwise report a clean run having checked nothing.
+pub fn tested_families(
+ wanted: Vec<FamilyFilter>,
+ tested: &[String],
+) -> Result<Vec<FamilyFilter>, String> {
+ let asked = wanted.len();
+ let kept: Vec<FamilyFilter> = wanted
+ .into_iter()
+ .filter(|f| tested.contains(&f.family))
+ .collect();
+ if !kept.is_empty() {
+ return Ok(kept);
+ }
+ let tag = super::PINNED_TAG;
+ Err(if asked > 0 {
+ format!("none of the {asked} requested op families exist in llama.cpp {tag}")
+ } else if tested.is_empty() {
+ format!("llama.cpp {tag} reported no op families to test")
+ } else {
+ "the diagnostic plan names no op families to test".to_string()
+ })
+}
+
+/// Per-family ceiling. The slowest measured family is MUL_MAT_ID at 121 s on a
+/// warm GPU, so this is generous enough that a leaf hitting it is wedged rather
+/// than slow.
+pub const DEFAULT_FAMILY_TIMEOUT: Duration = Duration::from_secs(600);
+
+/// Ceiling on the whole run. A Full run measured 15 min on one device, so this
+/// covers a few devices and still bounds a machine that is thrashing.
+pub const DEFAULT_DEADLINE: Duration = Duration::from_secs(5400);
+
+/// How much of a leaf's stderr, and how many of its unreadable stdout lines,
+/// are kept for the family that produced them.
+const LEAF_TAIL_LINES: usize = 20;
+
+/// Longest leaf line kept, so a runaway print cannot grow the root's memory.
+const LEAF_LINE_CHARS: usize = 2000;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum DiagPreset {
+ /// The support probe plus the common-shape list
+ /// ([`super::model_plan::quick_families`]) in test mode.
+ Quick,
+ /// Every family upstream has a test for.
+ Full,
+ /// Only the families one gguf's graph contains, at its own shapes
+ /// ([`super::model_plan::model_families`]).
+ Model,
+}
+
+/// How a family ended. Only `Fail` means a kernel computed the wrong answer;
+/// the rest are the leaf itself going wrong.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum FamilyStatus {
+ Ok,
+ Fail,
+ /// The leaf ran cleanly and tested nothing, because the shape filter
+ /// matched no case. Inconclusive, never a pass: reporting it green is
+ /// exactly the wrong answer, and upstream's parameter strings are not a
+ /// stable contract, so this is a thing that will happen.
+ NoCases,
+ /// The leaf died, which is what a `GGML_ASSERT` or a device loss looks like.
+ Crashed,
+ /// The leaf outlived its timeout and was killed.
+ Hung,
+ /// Cancelled, or the run's deadline passed, before the leaf finished.
+ Cancelled,
+}
+
+/// One device and one slice of the op list: the unit a leaf process runs.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct DiagUnit {
+ pub device: String,
+ /// Display name of the slice; [`ALL_FAMILIES`] for the support probe.
+ pub family: String,
+ pub request: DiagRunRequest,
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub struct DiagnosePlan {
+ pub preset: DiagPreset,
+ pub engine: EngineBuild,
+ pub devices: Vec<DiagDevice>,
+ /// Families to run in test mode, in order, each optionally narrowed to
+ /// the shapes a model uses.
+ pub families: Vec<FamilyFilter>,
+ /// The model this plan was built for, for the `start` event. Only the
+ /// [`DiagPreset::Model`] preset has one.
+ pub model: Option<String>,
+ /// Run the whole-op-list support probe on each device first. It costs under
+ /// a second and is the only thing that answers "what falls back to CPU".
+ pub support_probe: bool,
+ pub workers: u32,
+ /// Backend modules the probe process loaded, e.g. `libggml-cuda.so`.
+ pub backend_modules: Vec<String>,
+ pub family_timeout: Duration,
+ pub deadline: Duration,
+}
+
+impl DiagnosePlan {
+ pub fn units(&self) -> Vec<DiagUnit> {
+ let mut out = Vec::new();
+ for device in &self.devices {
+ if self.support_probe {
+ out.push(DiagUnit {
+ device: device.name.clone(),
+ family: ALL_FAMILIES.to_string(),
+ request: DiagRunRequest {
+ mode: DiagMode::Support,
+ backend: device.name.clone(),
+ op_filter: None,
+ params_filter: None,
+ workers: 1,
+ },
+ });
+ }
+ for family in &self.families {
+ out.push(DiagUnit {
+ device: device.name.clone(),
+ family: family.family.clone(),
+ request: DiagRunRequest {
+ mode: DiagMode::Test,
+ backend: device.name.clone(),
+ op_filter: Some(family.family.clone()),
+ params_filter: family.params.clone(),
+ workers: self.workers,
+ },
+ });
+ }
+ }
+ out
+ }
+}
+
+/// One line of the root's stdout. Readers must tolerate an unknown `event`.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(tag = "event", rename_all = "snake_case")]
+pub enum RootEvent {
+ Start {
+ schema: u32,
+ preset: DiagPreset,
+ engine: EngineBuild,
+ /// Family names, in the order they run. The filters themselves stay
+ /// out: a user reading the result has no use for a ggml regex, and a
+ /// narrowed family that tests nothing reports itself as `no_cases`.
+ families: Vec<String>,
+ /// The model file this run was built for, on the model preset.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ model: Option<String>,
+ support_probe: bool,
+ backend_modules: Vec<String>,
+ /// How many leaf processes the run will spawn if nothing cancels it.
+ units: usize,
+ family_timeout_secs: u64,
+ deadline_secs: u64,
+ },
+ Device(DiagDevice),
+ FamilyStart {
+ device: String,
+ family: String,
+ mode: DiagMode,
+ },
+ /// One case, as the leaf reported it, tagged with where it came from.
+ Case {
+ device: String,
+ family: String,
+ #[serde(flatten)]
+ case: DiagCase,
+ },
+ FamilyEnd {
+ device: String,
+ family: String,
+ status: FamilyStatus,
+ ok: usize,
+ failed: usize,
+ not_supported: usize,
+ millis: u64,
+ /// How the leaf ended, from [`describe_exit`]. Absent when it was still
+ /// running (hung, cancelled).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ exit: Option<String>,
+ /// The leaf's last stderr lines, oldest first.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ last_lines: Vec<String>,
+ /// Stdout lines that were not events. A leaf writing these is a bug on
+ /// our side, not the machine's, so they are reported rather than hidden.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ unparsed: Vec<String>,
+ },
+ Summary {
+ device: String,
+ ok: usize,
+ failed: usize,
+ not_supported: usize,
+ families_crashed: usize,
+ families_hung: usize,
+ /// Families whose filter matched no case, so they tested nothing.
+ #[serde(default)]
+ families_no_cases: usize,
+ /// Families the run never reached, because it was cancelled or passed
+ /// its deadline. Reported so a device whose remaining families were
+ /// dropped is not read as a clean pass on the ones that did run.
+ #[serde(default)]
+ families_cancelled: usize,
+ },
+ /// Always last. `ok` is false if any case failed or any family did not
+ /// complete.
+ Done {
+ ok: bool,
+ cancelled: bool,
+ /// At least one family tested nothing, so `ok` is not the whole
+ /// answer. Separate from `ok` on purpose: nothing failed, but the run
+ /// did not cover what it was asked to.
+ #[serde(default)]
+ inconclusive: bool,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ error: Option<String>,
+ },
+}
+
+/// How to start a leaf. Tests point `program` at a stand-in that exits, hangs
+/// or prints garbage; in the app it is the worker binary itself.
+#[derive(Debug, Clone)]
+pub struct LeafSpec {
+ pub program: PathBuf,
+}
+
+impl LeafSpec {
+ pub fn new(program: PathBuf) -> Self {
+ Self { program }
+ }
+
+ /// The argv a leaf is started with, which is also what
+ /// `jan-llama-worker` parses.
+ pub fn args(&self, unit: &DiagUnit, family_timeout: Duration) -> Vec<String> {
+ let mut args = vec!["--diagnose-run".to_string()];
+ args.push(unit.device.clone());
+ args.push("--mode".into());
+ args.push(
+ match unit.request.mode {
+ DiagMode::Test => "test",
+ DiagMode::Support => "support",
+ }
+ .into(),
+ );
+ if let Some(ops) = &unit.request.op_filter {
+ args.push("--op".into());
+ args.push(ops.clone());
+ }
+ if let Some(params) = &unit.request.params_filter {
+ args.push("--params".into());
+ args.push(params.clone());
+ }
+ args.push("--workers".into());
+ args.push(unit.request.workers.max(1).to_string());
+ // Passed so the leaf can end itself if this root dies without
+ // killing it. Enforced here too, which is what normally stops it.
+ args.push("--family-timeout".into());
+ args.push(family_timeout.as_secs().to_string());
+ args
+ }
+
+ fn command(&self, unit: &DiagUnit, family_timeout: Duration) -> Command {
+ self.base_command(&self.args(unit, family_timeout))
+ }
+
+ fn base_command(&self, args: &[String]) -> Command {
+ let mut cmd = Command::new(&self.program);
+ cmd.args(args)
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+ #[cfg(windows)]
+ {
+ // CREATE_NO_WINDOW: a leaf must not flash a console on the
+ // desktop. `creation_flags` is tokio's own, so std's `CommandExt`
+ // is not imported for it.
+ cmd.creation_flags(0x0800_0000);
+ }
+ cmd.kill_on_drop(true);
+ cmd
+ }
+}
+
+/// Ceiling on a one-shot probe. Generous because enumerating CUDA devices
+/// creates a context, which is seconds on a cold driver.
+pub const PROBE_TIMEOUT: Duration = Duration::from_secs(120);
+
+/// The flag the leaf answering [`probe_devices`] is started with.
+pub const DEVICES_FLAG: &str = "--diagnose-devices";
+/// The flag the leaf answering [`probe_families`] is started with.
+pub const OPS_FLAG: &str = "--diagnose-ops";
+
+async fn probe(spec: &LeafSpec, flag: &str) -> Result<(String, Vec<String>), String> {
+ let args = [flag.to_string()];
+ let out = tokio::time::timeout(PROBE_TIMEOUT, spec.base_command(&args).output())
+ .await
+ .map_err(|_| format!("{flag} did not answer within {}s", PROBE_TIMEOUT.as_secs()))?
+ .map_err(|e| format!("could not start {}: {e}", spec.program.display()))?;
+ let stderr = String::from_utf8_lossy(&out.stderr);
+ if !out.status.success() {
+ let tail: Vec<&str> = stderr.lines().filter(|l| !l.trim().is_empty()).collect();
+ let tail = tail[tail.len().saturating_sub(3)..].join("; ");
+ return Err(format!("{flag} failed: {} {tail}", describe_exit(&out.status)));
+ }
+ let backends = stderr
+ .lines()
+ .filter_map(super::worker::parse_backend_line)
+ .collect();
+ Ok((String::from_utf8_lossy(&out.stdout).into_owned(), backends))
+}
+
+/// Asks a leaf what ggml devices exist, and which backend modules it loaded to
+/// find them. The root cannot answer this itself: it holds no ggml on purpose.
+pub async fn probe_devices(spec: &LeafSpec) -> Result<(Vec<DiagDevice>, Vec<String>), String> {
+ let (stdout, backends) = probe(spec, DEVICES_FLAG).await?;
+ let devices = serde_json::from_str(stdout.trim())
+ .map_err(|e| format!("{DEVICES_FLAG} printed something unreadable: {e}"))?;
+ Ok((devices, backends))
+}
+
+/// The op families upstream has at least one test case for, which is the Full
+/// preset. Families with no case are dropped: a leaf for one would spawn,
+/// init a backend and report nothing.
+pub async fn probe_families(spec: &LeafSpec) -> Result<Vec<String>, String> {
+ let (stdout, _) = probe(spec, OPS_FLAG).await?;
+ let ops: Vec<super::diag::DiagOp> = serde_json::from_str(stdout.trim())
+ .map_err(|e| format!("{OPS_FLAG} printed something unreadable: {e}"))?;
+ Ok(ops
+ .into_iter()
+ .filter(|o| o.cases > 0)
+ .map(|o| o.op)
+ .collect())
+}
+
+/// What one leaf produced.
+#[derive(Debug, Clone, PartialEq)]
+struct UnitOutcome {
+ status: FamilyStatus,
+ tally: DiagTally,
+ exit: Option<String>,
+ last_lines: Vec<String>,
+ unparsed: Vec<String>,
+}
+
+fn push_tail(tail: &mut VecDeque<String>, line: &str) {
+ let line = line.trim_end();
+ if line.is_empty() {
+ return;
+ }
+ let line: String = line.chars().take(LEAF_LINE_CHARS).collect();
+ if tail.len() == LEAF_TAIL_LINES {
+ tail.pop_front();
+ }
+ tail.push_back(line);
+}
+
+/// Per-device counts of families that did not produce a usable result.
+#[derive(Debug, Clone, Copy, Default)]
+struct DeviceFaults {
+ crashed: usize,
+ hung: usize,
+ no_cases: usize,
+ cancelled: usize,
+}
+
+/// One device's running totals.
+///
+/// The test units and the support probe are kept apart because they answer
+/// different questions and a single tally conflates them. The probe asks
+/// `ggml_backend_supports_op` over the whole op list and reports every
+/// supported case as `ok` without computing anything, so folding it into the
+/// pass count inflates "Passed X of Y" with cases that were never run, and
+/// adding both `not_supported` counts bills every probed case twice.
+#[derive(Default)]
+struct DeviceRollup {
+ test: DiagTally,
+ probe: DiagTally,
+ probed: bool,
+ faults: DeviceFaults,
+}
+
+impl DeviceRollup {
+ fn add(&mut self, mode: DiagMode, tally: &DiagTally) {
+ let into = if mode == DiagMode::Support {
+ self.probed = true;
+ &mut self.probe
+ } else {
+ &mut self.test
+ };
+ into.ok += tally.ok;
+ into.failed += tally.failed;
+ into.not_supported += tally.not_supported;
+ }
+
+ /// What the device does not implement. The probe is authoritative when it
+ /// ran -- it covers the whole op list rather than the families this run
+ /// happened to test -- and the test units are the only source when it did
+ /// not.
+ fn not_supported(&self) -> usize {
+ if self.probed {
+ self.probe.not_supported
+ } else {
+ self.test.not_supported
+ }
+ }
+}
+
+/// Why a run stopped early, if it did.
+enum Interrupt {
+ Cancelled,
+ Deadline,
+}
+
+/// Runs `plan`, emitting every event through `emit` as it happens. Resolves
+/// when the plan is done, `cancel` resolves, or the deadline passes; a leaf
+/// still running at that point is killed.
+pub async fn run<F>(
+ plan: &DiagnosePlan,
+ spec: &LeafSpec,
+ cancel: F,
+ emit: &mut impl FnMut(RootEvent),
+) where
+ F: std::future::Future<Output = ()>,
+{
+ let units = plan.units();
+ emit(RootEvent::Start {
+ schema: SCHEMA_VERSION,
+ preset: plan.preset,
+ engine: plan.engine.clone(),
+ families: plan.families.iter().map(|f| f.family.clone()).collect(),
+ model: plan.model.clone(),
+ support_probe: plan.support_probe,
+ backend_modules: plan.backend_modules.clone(),
+ units: units.len(),
+ family_timeout_secs: plan.family_timeout.as_secs(),
+ deadline_secs: plan.deadline.as_secs(),
+ });
+ for device in &plan.devices {
+ emit(RootEvent::Device(device.clone()));
+ }
+
+ let mut cancel = std::pin::pin!(cancel);
+ let deadline = tokio::time::Instant::now() + plan.deadline;
+ let mut interrupt = None;
+ let mut any_failure = false;
+ let mut any_inconclusive = false;
+ // One entry per device, in the order the units visit them, which
+ // `DiagnosePlan::units` keeps device-major.
+ let mut per_device: Vec<(String, DeviceRollup)> = Vec::new();
+
+ for unit in &units {
+ if per_device.last().map(|d| d.0.as_str()) != Some(unit.device.as_str()) {
+ per_device.push((unit.device.clone(), DeviceRollup::default()));
+ }
+ emit(RootEvent::FamilyStart {
+ device: unit.device.clone(),
+ family: unit.family.clone(),
+ mode: unit.request.mode,
+ });
+
+ let started = std::time::Instant::now();
+ let outcome = if interrupt.is_some() {
+ UnitOutcome {
+ status: FamilyStatus::Cancelled,
+ tally: DiagTally::default(),
+ exit: None,
+ last_lines: Vec::new(),
+ unparsed: Vec::new(),
+ }
+ } else {
+ tokio::select! {
+ biased;
+ _ = &mut cancel => {
+ interrupt = Some(Interrupt::Cancelled);
+ cancelled_outcome()
+ }
+ _ = tokio::time::sleep_until(deadline) => {
+ interrupt = Some(Interrupt::Deadline);
+ cancelled_outcome()
+ }
+ o = run_unit(spec, unit, plan.family_timeout, emit) => o,
+ }
+ };
+
+ let device = per_device.last_mut().expect("pushed above");
+ device.1.add(unit.request.mode, &outcome.tally);
+ match outcome.status {
+ FamilyStatus::Crashed => device.1.faults.crashed += 1,
+ FamilyStatus::Hung => device.1.faults.hung += 1,
+ FamilyStatus::NoCases => device.1.faults.no_cases += 1,
+ FamilyStatus::Cancelled => device.1.faults.cancelled += 1,
+ _ => {}
+ }
+ // A family that tested nothing has not failed, so it must not read as
+ // "problems found"; it is reported on its own channel instead.
+ if outcome.status == FamilyStatus::NoCases {
+ any_inconclusive = true;
+ } else if outcome.status != FamilyStatus::Ok {
+ any_failure = true;
+ }
+
+ emit(RootEvent::FamilyEnd {
+ device: unit.device.clone(),
+ family: unit.family.clone(),
+ status: outcome.status,
+ ok: outcome.tally.ok,
+ failed: outcome.tally.failed,
+ not_supported: outcome.tally.not_supported,
+ millis: started.elapsed().as_millis() as u64,
+ exit: outcome.exit,
+ last_lines: outcome.last_lines,
+ unparsed: outcome.unparsed,
+ });
+ }
+
+ for (device, rollup) in per_device {
+ emit(RootEvent::Summary {
+ device,
+ // The test units alone: these are the cases that were computed and
+ // compared, which is what a pass count has to mean.
+ ok: rollup.test.ok,
+ failed: rollup.test.failed,
+ not_supported: rollup.not_supported(),
+ families_crashed: rollup.faults.crashed,
+ families_hung: rollup.faults.hung,
+ families_no_cases: rollup.faults.no_cases,
+ families_cancelled: rollup.faults.cancelled,
+ });
+ }
+
+ emit(RootEvent::Done {
+ // `ok` is "this run is a clean bill of health", not "nothing failed":
+ // a reader that checks only this field must never be told a run that
+ // tested nothing went fine, which is the whole hazard a narrowed
+ // filter introduces. `inconclusive` says which of the two it was.
+ ok: !any_failure && !any_inconclusive && interrupt.is_none(),
+ cancelled: matches!(interrupt, Some(Interrupt::Cancelled)),
+ inconclusive: any_inconclusive,
+ error: match interrupt {
+ Some(Interrupt::Deadline) => Some(format!(
+ "the run passed its {}s deadline",
+ plan.deadline.as_secs()
+ )),
+ _ => None,
+ },
+ });
+}
+
+fn cancelled_outcome() -> UnitOutcome {
+ UnitOutcome {
+ status: FamilyStatus::Cancelled,
+ tally: DiagTally::default(),
+ exit: None,
+ last_lines: Vec::new(),
+ unparsed: Vec::new(),
+ }
+}
+
+/// Spawns one leaf and reads it to the end, or kills it at `timeout`.
+async fn run_unit(
+ spec: &LeafSpec,
+ unit: &DiagUnit,
+ timeout: Duration,
+ emit: &mut impl FnMut(RootEvent),
+) -> UnitOutcome {
+ let mut child = match spec.command(unit, timeout).spawn() {
+ Ok(c) => c,
+ Err(e) => {
+ return UnitOutcome {
+ status: FamilyStatus::Crashed,
+ tally: DiagTally::default(),
+ exit: Some(format!("could not start {}: {e}", spec.program.display())),
+ last_lines: Vec::new(),
+ unparsed: Vec::new(),
+ }
+ }
+ };
+
+ // Drained on its own task: a leaf that fills the stderr pipe while we read
+ // stdout would deadlock against us.
+ let stderr_tail = std::sync::Arc::new(std::sync::Mutex::new(VecDeque::new()));
+ let stderr_drain = child.stderr.take().map(|stderr| {
+ let tail = std::sync::Arc::clone(&stderr_tail);
+ tokio::spawn(async move {
+ let mut lines = BufReader::new(stderr).lines();
+ while let Ok(Some(line)) = lines.next_line().await {
+ // ggml's startup announcements carry the module's full local
+ // path and say nothing about a crash; the plan already reports
+ // the modules, stripped, under `backend_modules`.
+ if super::worker::is_tail_noise(&line) {
+ continue;
+ }
+ if let Ok(mut tail) = tail.lock() {
+ push_tail(&mut tail, &line);
+ }
+ }
+ })
+ });
+
+ let mut tally = DiagTally::default();
+ let mut unparsed = VecDeque::new();
+ let mut saw_done = false;
+ let mut leaf_error = None;
+
+ let stdout = child.stdout.take();
+ let read = async {
+ let Some(stdout) = stdout else {
+ return;
+ };
+ let mut lines = BufReader::new(stdout).lines();
+ while let Ok(Some(line)) = lines.next_line().await {
+ if line.trim().is_empty() {
+ continue;
+ }
+ let Ok(event) = DiagEvent::parse(&line) else {
+ push_tail(&mut unparsed, &line);
+ continue;
+ };
+ tally.record(&event);
+ match event {
+ DiagEvent::Result(case) => emit(RootEvent::Case {
+ device: unit.device.clone(),
+ family: unit.family.clone(),
+ case,
+ }),
+ DiagEvent::Done { ok, error } => {
+ saw_done = true;
+ if !ok {
+ leaf_error = error;
+ }
+ }
+ _ => {}
+ }
+ }
+ };
+
+ let status = match tokio::time::timeout(timeout, async {
+ read.await;
+ child.wait().await
+ })
+ .await
+ {
+ Ok(status) => Some(status),
+ Err(_) => {
+ let _ = child.kill().await;
+ None
+ }
+ };
+
+ if let Some(drain) = stderr_drain {
+ // The leaf is gone by now either way, so this is already resolved or
+ // about to be; bounded so a stuck pipe cannot park the whole run.
+ let _ = tokio::time::timeout(Duration::from_secs(2), drain).await;
+ }
+ let mut last_lines: Vec<String> = stderr_tail
+ .lock()
+ .map(|t| t.iter().cloned().collect())
+ .unwrap_or_default();
+
+ let (status, exit) = match status {
+ None => (FamilyStatus::Hung, None),
+ Some(Err(e)) => (FamilyStatus::Crashed, Some(e.to_string())),
+ Some(Ok(code)) => {
+ let described = describe_exit(&code);
+ if !code.success() || !saw_done {
+ (FamilyStatus::Crashed, Some(described))
+ } else if tally.failed > 0 || leaf_error.is_some() {
+ (FamilyStatus::Fail, Some(described))
+ } else if tally.ok + tally.not_supported == 0 {
+ // A clean exit having tested nothing: the shape filter matched
+ // no case. The run must say so rather than count it as a pass.
+ (FamilyStatus::NoCases, Some(described))
+ } else {
+ (FamilyStatus::Ok, Some(described))
+ }
+ }
+ };
+ // The leaf's own reason for giving up reads better than its exit code, so
+ // it is kept rather than dropped for want of a field. It goes last
+ // because `last_lines` is oldest-first and this is the final thing the
+ // leaf said.
+ if let Some(error) = leaf_error {
+ last_lines.push(error);
+ }
+
+ UnitOutcome {
+ status,
+ tally,
+ exit,
+ last_lines,
+ unparsed: unparsed.into_iter().collect(),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::engine::diag::{DiagDeviceKind, DiagStatus};
+
+ fn device(name: &str) -> DiagDevice {
+ DiagDevice {
+ name: name.into(),
+ description: "test device".into(),
+ kind: DiagDeviceKind::Gpu,
+ reg: "Test".into(),
+ memory_total_mib: Some(1024),
+ memory_free_mib: Some(512),
+ }
+ }
+
+ fn plan(devices: Vec<DiagDevice>, families: Vec<&str>, support: bool) -> DiagnosePlan {
+ DiagnosePlan {
+ preset: DiagPreset::Quick,
+ engine: EngineBuild {
+ version: "0".into(),
+ tag: "b1".into(),
+ commit: "abc".into(),
+ },
+ devices,
+ families: families.into_iter().map(|f| FamilyFilter::new(f, None)).collect(),
+ model: None,
+ support_probe: support,
+ workers: 4,
+ backend_modules: vec!["libggml-cpu.so".into()],
+ family_timeout: DEFAULT_FAMILY_TIMEOUT,
+ deadline: DEFAULT_DEADLINE,
+ }
+ }
+
+ #[test]
+ fn the_probe_leads_each_device_and_families_follow_in_order() {
+ let p = plan(vec![device("CPU"), device("CUDA0")], vec!["ADD", "MUL"], true);
+ let units = p.units();
+ assert_eq!(units.len(), 6);
+ assert_eq!(units[0].family, ALL_FAMILIES);
+ assert_eq!(units[0].request.mode, DiagMode::Support);
+ assert_eq!(units[0].request.op_filter, None);
+ assert_eq!(units[1].family, "ADD");
+ assert_eq!(units[1].request.op_filter.as_deref(), Some("ADD"));
+ assert_eq!(units[1].request.workers, 4);
+ assert_eq!(units[3].device, "CUDA0");
+ }
+
+ #[test]
+ fn the_probe_is_the_only_unit_when_no_family_is_asked_for() {
+ let units = plan(vec![device("CPU")], vec![], true).units();
+ assert_eq!(units.len(), 1);
+ assert!(plan(vec![device("CPU")], vec![], false).units().is_empty());
+ }
+
+ #[test]
+ fn the_support_probe_never_runs_cases_in_parallel() {
+ // Support mode builds graphs and asks; workers would buy nothing and
+ // upstream only threads test mode.
+ let units = plan(vec![device("CPU")], vec!["ADD"], true).units();
+ assert_eq!(units[0].request.workers, 1);
+ }
+
+ #[test]
+ fn the_leaf_argv_carries_the_whole_request() {
+ let spec = LeafSpec::new(PathBuf::from("worker"));
+ let unit = DiagUnit {
+ device: "Vulkan0".into(),
+ family: "MUL_MAT".into(),
+ request: DiagRunRequest {
+ mode: DiagMode::Test,
+ backend: "Vulkan0".into(),
+ op_filter: Some("MUL_MAT".into()),
+ params_filter: Some("m=4096".into()),
+ workers: 8,
+ },
+ };
+ assert_eq!(
+ spec.args(&unit, DEFAULT_FAMILY_TIMEOUT),
+ vec![
+ "--diagnose-run",
+ "Vulkan0",
+ "--mode",
+ "test",
+ "--op",
+ "MUL_MAT",
+ "--params",
+ "m=4096",
+ "--workers",
+ "8",
+ "--family-timeout",
+ "600",
+ ]
+ );
+ }
+
+ #[test]
+ fn a_probe_argv_omits_the_filters_it_has_none_of() {
+ let spec = LeafSpec::new(PathBuf::from("worker"));
+ let units = plan(vec![device("CPU")], vec![], true).units();
+ let args = spec.args(&units[0], DEFAULT_FAMILY_TIMEOUT);
+ assert!(!args.iter().any(|a| a == "--op" || a == "--params"));
+ assert_eq!(args[3], "support");
+ }
+
+ #[test]
+ fn the_tail_keeps_the_newest_lines_and_drops_blanks() {
+ let mut tail = VecDeque::new();
+ for i in 0..LEAF_TAIL_LINES + 5 {
+ push_tail(&mut tail, &format!("line {i}"));
+ push_tail(&mut tail, " ");
+ }
+ assert_eq!(tail.len(), LEAF_TAIL_LINES);
+ assert_eq!(tail.back().unwrap(), &format!("line {}", LEAF_TAIL_LINES + 4));
+
+ push_tail(&mut tail, &"x".repeat(LEAF_LINE_CHARS * 2));
+ assert_eq!(tail.back().unwrap().chars().count(), LEAF_LINE_CHARS);
+ }
+
+ #[test]
+ fn a_family_upstream_no_longer_has_is_dropped_rather_than_passing_vacuously() {
+ let wanted = vec![
+ FamilyFilter::new("ADD", None),
+ FamilyFilter::new("UNARY", None),
+ FamilyFilter::new("MUL_MAT", Some("type_a=q4_K,")),
+ ];
+ let kept = tested_families(wanted, &["ADD".to_string(), "MUL_MAT".to_string()]);
+ assert_eq!(
+ kept,
+ Ok(vec![
+ FamilyFilter::new("ADD", None),
+ FamilyFilter::new("MUL_MAT", Some("type_a=q4_K,")),
+ ]),
+ "the filter must survive the intersection, and UNARY must not"
+ );
+ }
+
+ #[test]
+ fn a_request_upstream_has_none_of_is_refused() {
+ let err = tested_families(vec![FamilyFilter::new("UNARY", None)], &["ADD".to_string()])
+ .unwrap_err();
+ assert!(err.contains("none of the 1 requested"), "{err}");
+ }
+
+ // Full asks for exactly what the op probe listed, so a probe that failed
+ // and listed nothing must not turn into a run that checks nothing.
+ #[test]
+ fn an_empty_op_list_is_refused_rather_than_passing_vacuously() {
+ let err = tested_families(vec![], &[]).unwrap_err();
+ assert!(err.contains("reported no op families"), "{err}");
+ }
+
+ #[test]
+ fn a_plan_naming_no_families_is_refused() {
+ let err = tested_families(vec![], &["ADD".to_string()]).unwrap_err();
+ assert!(err.contains("names no op families"), "{err}");
+ }
+
+ #[test]
+ fn a_narrowed_family_carries_its_filter_into_its_unit() {
+ let mut p = plan(vec![device("CPU")], vec![], false);
+ p.families = vec![FamilyFilter::new("MUL_MAT", Some("type_a=q4_K,"))];
+ let units = p.units();
+ assert_eq!(units.len(), 1);
+ assert_eq!(units[0].request.op_filter.as_deref(), Some("MUL_MAT"));
+ assert_eq!(units[0].request.params_filter.as_deref(), Some("type_a=q4_K,"));
+ }
+
+ #[test]
+ fn the_start_event_round_trips_through_json() {
+ let p = plan(vec![device("CPU")], vec!["ADD"], true);
+ let event = RootEvent::Start {
+ schema: SCHEMA_VERSION,
+ preset: p.preset,
+ engine: p.engine.clone(),
+ families: p.families.iter().map(|f| f.family.clone()).collect(),
+ model: Some("qwen3.gguf".into()),
+ support_probe: true,
+ backend_modules: p.backend_modules.clone(),
+ units: 2,
+ family_timeout_secs: 600,
+ deadline_secs: 5400,
+ };
+ let json = serde_json::to_string(&event).unwrap();
+ assert!(json.contains(r#""event":"start""#));
+ assert_eq!(serde_json::from_str::<RootEvent>(&json).unwrap(), event);
+ }
+
+ #[test]
+ fn a_case_event_is_flat_so_a_reader_sees_one_object() {
+ let json = serde_json::to_string(&RootEvent::Case {
+ device: "CPU".into(),
+ family: "ADD".into(),
+ case: DiagCase {
+ backend: "CPU".into(),
+ op: "ADD".into(),
+ params: "type=f32".into(),
+ mode: "test".into(),
+ status: DiagStatus::Ok,
+ error: None,
+ detail: None,
+ },
+ })
+ .unwrap();
+ assert!(json.contains(r#""family":"ADD""#), "{json}");
+ assert!(json.contains(r#""params":"type=f32""#), "{json}");
+ assert!(
+ !json.contains(r#""case":{"#),
+ "the case must not be nested: {json}"
+ );
+ }
+}
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/diagnose_commands.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/diagnose_commands.rs
new file mode 100644
index 000000000..1d0b72f2b
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/diagnose_commands.rs
@@ -0,0 +1,573 @@
+//! Tauri surface for the ggml op diagnostic.
+//!
+//! The root (`engine::diagnose`) is a process this spawns, read line by line
+//! and republished as Tauri events. Keeping the orchestration in the worker
+//! rather than here is the point: the desktop links this plugin *without* the
+//! `engine` feature, so it has no ggml of its own, and a leaf that aborts must
+//! not be able to take the app with it.
+
+use std::sync::{Arc, Mutex};
+
+use serde::{Deserialize, Serialize};
+use tauri::{Emitter, Manager, State};
+use tokio::io::{AsyncBufReadExt, BufReader};
+
+use super::diagnose::{DiagPreset, RootEvent};
+use super::model_plan::{model_families, ModelPlan, ModelShape};
+use super::{commands::resolve_worker_exe, preset, worker};
+
+/// Every event of every run arrives on this one channel, tagged with its job.
+pub const DIAGNOSTICS_EVENT: &str = "llamacpp-diagnostics";
+
+/// Ceiling on a whole run, over and above the root's own `--deadline`. This is
+/// the backstop for a root that stops answering rather than one that overruns.
+const HARD_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(7200);
+
+/// How long a cancelled root gets to notice its stdin closed before it is
+/// killed. It only has to finish the leaf it is reading and print `done`.
+const CANCEL_GRACE: std::time::Duration = std::time::Duration::from_secs(10);
+
+/// One line of a run, as the frontend receives it. `RootEvent` is flattened so
+/// a listener reads one flat object rather than reaching through a wrapper.
+#[derive(Debug, Clone, Serialize)]
+struct DiagnosticsEvent {
+ job: String,
+ #[serde(flatten)]
+ event: RootEvent,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct DiagnosticsJob {
+ pub id: String,
+}
+
+/// The run in flight, if any. One at a time on purpose: the check saturates
+/// every core, so a second concurrent run would only make both unreliable and
+/// the timings meaningless.
+#[derive(Default)]
+pub struct DiagnosticsState {
+ current: Mutex<Option<RunningJob>>,
+}
+
+struct RunningJob {
+ id: String,
+ /// Dropping this closes the root's stdin, which is how it is asked to stop.
+ /// `None` until the root is spawned, and again once it has been asked to
+ /// stop.
+ stdin: Option<tokio::process::ChildStdin>,
+ /// Kills the root if it does not stop on its own. `None` until the pump
+ /// task that owns the child exists.
+ kill: Option<tokio::task::AbortHandle>,
+ /// The root's pid, which is also its process group id. Killing the group
+ /// is what reaches the leaves; see [`kill_process_group`].
+ pid: Option<u32>,
+ /// Windows' equivalent: dropping this asks the OS to end everything still
+ /// in the job, the root and its leaves alike. `()` elsewhere, where the
+ /// process group does the work.
+ job: Option<ProcessJob>,
+ /// Set by [`DiagnosticsState::stop`] before the root was spawned, so the
+ /// stop is honoured rather than lost in that window.
+ stopped: bool,
+}
+
+impl DiagnosticsState {
+ /// Claims the single slot for `id` before anything is spawned, or reports
+ /// who holds it. The process is attached afterwards with [`Self::attach`]:
+ /// spawning first would leave a second run streaming its events after its
+ /// caller was told the slot was taken.
+ fn reserve(&self, id: &str) -> Result<(), String> {
+ let mut current = self.current.lock().map_err(|_| poisoned())?;
+ if current.is_some() {
+ return Err("a hardware check is already running".to_string());
+ }
+ *current = Some(RunningJob {
+ id: id.to_string(),
+ stdin: None,
+ kill: None,
+ pid: None,
+ job: None,
+ stopped: false,
+ });
+ Ok(())
+ }
+
+ /// Hands the spawned root to the slot `id` reserved. A stop that arrived
+ /// during the spawn closes the new stdin at once rather than being lost.
+ fn attach(
+ &self,
+ id: &str,
+ stdin: Option<tokio::process::ChildStdin>,
+ kill: tokio::task::AbortHandle,
+ pid: Option<u32>,
+ confined: Option<ProcessJob>,
+ ) {
+ if let Ok(mut current) = self.current.lock() {
+ if let Some(job) = current.as_mut().filter(|job| job.id == id) {
+ job.stdin = if job.stopped { None } else { stdin };
+ job.kill = Some(kill);
+ job.pid = pid;
+ job.job = confined;
+ }
+ }
+ }
+
+ /// Releases the slot if `id` still holds it. A run that finished after
+ /// being superseded must not clear a newer one.
+ fn release(&self, id: &str) {
+ if let Ok(mut current) = self.current.lock() {
+ if current.as_ref().is_some_and(|job| job.id == id) {
+ *current = None;
+ }
+ }
+ }
+
+ fn stop(&self, id: &str) -> Result<(), String> {
+ let mut current = self.current.lock().map_err(|_| poisoned())?;
+ match current.as_mut() {
+ Some(job) if job.id == id => {
+ // Closing stdin is the documented stop; the kill is the
+ // backstop for a root wedged somewhere it cannot read it.
+ job.stdin.take();
+ job.stopped = true;
+ Ok(())
+ }
+ _ => Err(format!("no hardware check with id {id} is running")),
+ }
+ }
+
+ fn kill_handle(&self, id: &str) -> Option<(tokio::task::AbortHandle, Option<u32>)> {
+ let current = self.current.lock().ok()?;
+ let job = current.as_ref()?;
+ (job.id == id).then(|| job.kill.clone().map(|kill| (kill, job.pid)))?
+ }
+}
+
+fn poisoned() -> String {
+ "the hardware check state is unusable".to_string()
+}
+
+/// Distinguishes this run's events from a previous run's that are still in
+/// flight. Not a secret and never persisted, so OS randomness is overkill but
+/// `rand` is already a dependency.
+fn new_job_id() -> String {
+ use rand::Rng;
+ let bytes: [u8; 8] = rand::thread_rng().gen();
+ bytes.iter().map(|b| format!("{b:02x}")).collect()
+}
+
+/// The gguf a model id is loaded from, out of the running engine's preset.
+///
+/// The preset is the only place that mapping exists outside the extension, and
+/// the model check is offered after a failed *load*, so the engine is up by
+/// definition on the path that matters. A stopped engine reports rather than
+/// guessing at a path.
+async fn model_gguf_path<R: tauri::Runtime>(
+ app_handle: &tauri::AppHandle<R>,
+ model_id: &str,
+) -> Result<String, String> {
+ let preset_path = {
+ let state = app_handle.state::<Arc<crate::state::LlamacppState>>();
+ let guard = state.engine.lock().await;
+ guard
+ .as_ref()
+ .map(|h| h.preset_path.clone())
+ .ok_or_else(|| "the llama.cpp engine is not running".to_string())?
+ };
+ let ini = tokio::fs::read_to_string(&preset_path)
+ .await
+ .map_err(|e| format!("could not read {}: {e}", preset_path.display()))?;
+ preset::value(&ini, model_id, "model")
+ .ok_or_else(|| format!("no model named {model_id} is configured"))
+}
+
+/// Reads a gguf and turns it into the family list its graph needs.
+async fn plan_for_model(path: &str) -> Result<ModelPlan, String> {
+ let metadata = crate::gguf::utils::read_gguf_metadata_internal(path.to_string()).await?;
+ let tensor_types =
+ crate::gguf::utils::read_gguf_tensor_types_internal(path.to_string()).await?;
+ let shape = ModelShape::from_gguf(&metadata.metadata, &tensor_types);
+ Ok(ModelPlan {
+ model: crate::diagnostics::file_name(path),
+ families: model_families(&shape),
+ })
+}
+
+/// Starts a run and returns its id. Events arrive on [`DIAGNOSTICS_EVENT`]
+/// until one carries `event: "done"`, which is emitted on every path including
+/// a root that could not start.
+///
+/// `model` is required by the `model` preset and ignored by the others: it is
+/// a model id, resolved to its gguf here so the worker still reads no model.
+#[tauri::command]
+pub async fn start_diagnostics<R: tauri::Runtime>(
+ app_handle: tauri::AppHandle<R>,
+ preset: String,
+ devices: Vec<String>,
+ envs: std::collections::HashMap<String, String>,
+ model: Option<String>,
+) -> Result<DiagnosticsJob, String> {
+ let preset = match preset.as_str() {
+ "quick" => DiagPreset::Quick,
+ "full" => DiagPreset::Full,
+ "model" => DiagPreset::Model,
+ other => return Err(format!("unknown preset: {other}")),
+ };
+ let model_plan = match preset {
+ DiagPreset::Model => {
+ let model_id = model
+ .as_deref()
+ .filter(|m| !m.is_empty())
+ .ok_or_else(|| "the model check needs a model".to_string())?;
+ let path = model_gguf_path(&app_handle, model_id).await?;
+ Some(plan_for_model(&path).await?)
+ }
+ _ => None,
+ };
+ let state = app_handle.state::<Arc<DiagnosticsState>>().inner().clone();
+ let exe = resolve_worker_exe(&app_handle)?;
+
+ let mut cmd = tokio::process::Command::new(&exe);
+ // Same pinned cwd as a serving worker: the leaves load their backend
+ // modules by scanning the directory they were started from.
+ if let Some(dir) = worker::worker_cwd(&exe) {
+ cmd.current_dir(dir);
+ }
+ cmd.arg("--diagnose")
+ .arg("--diagnose-preset")
+ .arg(match preset {
+ DiagPreset::Quick => "quick",
+ DiagPreset::Full => "full",
+ DiagPreset::Model => "model",
+ });
+ if let Some(plan) = &model_plan {
+ let json = serde_json::to_string(plan)
+ .map_err(|e| format!("could not encode the model plan: {e}"))?;
+ cmd.arg("--diagnose-plan").arg(json);
+ }
+ for device in &devices {
+ cmd.arg("--device").arg(device);
+ }
+ cmd.envs(envs)
+ // Held open for the whole run: closing it is the cancel signal, so it
+ // must not be inherited or dropped early.
+ .stdin(std::process::Stdio::piped())
+ .stdout(std::process::Stdio::piped())
+ .stderr(std::process::Stdio::piped());
+ jan_utils::system::setup_windows_process_flags(&mut cmd);
+ // Its own process group, so the leaves it spawns can be killed with it.
+ // `kill_on_drop` and `Child::kill` both signal the root alone, and a root
+ // that had to be killed is by definition one that did not get to stop its
+ // own leaf -- which would then keep a device at full load, with the slot
+ // already handed to the next run.
+ #[cfg(unix)]
+ cmd.process_group(0);
+ cmd.kill_on_drop(true);
+
+ // Reserved before the spawn: a run that starts and only then finds the
+ // slot taken would still be streaming its events on the shared channel
+ // while its caller was told it never started.
+ let id = new_job_id();
+ state.reserve(&id)?;
+
+ let mut child = match cmd.spawn() {
+ Ok(child) => child,
+ Err(e) => {
+ state.release(&id);
+ return Err(format!("could not start {}: {e}", exe.display()));
+ }
+ };
+
+ let pid = child.id();
+ let confined = confine_child(&child);
+ let stdin = child.stdin.take();
+ let stdout = child.stdout.take();
+ let stderr = child.stderr.take();
+
+ let pump = tokio::spawn(run_to_completion(
+ app_handle.clone(),
+ Arc::clone(&state),
+ id.clone(),
+ child,
+ stdout,
+ stderr,
+ ));
+
+ state.attach(&id, stdin, pump.abort_handle(), pid, confined);
+
+ Ok(DiagnosticsJob { id })
+}
+
+/// Asks a run to stop. Returns once the request is made, not once it lands:
+/// the terminal `done` event is what says the run is over.
+#[tauri::command]
+pub async fn cancel_diagnostics<R: tauri::Runtime>(
+ app_handle: tauri::AppHandle<R>,
+ state: State<'_, Arc<DiagnosticsState>>,
+ job: String,
+) -> Result<(), String> {
+ state.stop(&job)?;
+ let state = state.inner().clone();
+ tokio::spawn(async move {
+ tokio::time::sleep(CANCEL_GRACE).await;
+ if let Some((kill, pid)) = state.kill_handle(&job) {
+ log::warn!("hardware check {job} ignored its stop request; killing it");
+ // Aborting drops the pump mid-read, so the terminal `done` it
+ // would have emitted never happens; without this one the panel
+ // waits forever on a run that is already dead.
+ kill.abort();
+ // After the abort: dropping the child signals the root, and this
+ // reaches the leaf it left behind.
+ kill_process_group(pid);
+ emit_event(
+ &app_handle,
+ &job,
+ RootEvent::Done {
+ ok: false,
+ cancelled: true,
+ inconclusive: false,
+ error: Some(
+ "the hardware check did not stop when asked and was closed".to_string(),
+ ),
+ },
+ );
+ state.release(&job);
+ }
+ });
+ Ok(())
+}
+
+/// What holds a process tree together for the OS to collect.
+#[cfg(windows)]
+type ProcessJob = worker::reap::Job;
+#[cfg(not(windows))]
+type ProcessJob = ();
+
+/// Puts the root in a kill-on-close job object, so Windows ends its leaves
+/// when the job handle drops.
+///
+/// The same primitive the serving worker uses. Unix needs nothing here: the
+/// root leads its own process group and [`kill_process_group`] takes it.
+fn confine_child(child: &tokio::process::Child) -> Option<ProcessJob> {
+ #[cfg(windows)]
+ {
+ child.raw_handle().and_then(worker::reap::confine)
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = child;
+ None
+ }
+}
+
+/// Kills a root and every leaf it spawned.
+///
+/// The leaves are grandchildren of this process, which neither `kill_on_drop`
+/// nor `Child::kill` reaches. On Unix the root leads its own process group
+/// (`process_group(0)` above), so one `killpg` takes the group.
+///
+/// On Windows the job object does it instead, and not from here: the tree
+/// dies when the run's [`ProcessJob`] drops, which is why `RunningJob` holds
+/// one (`CREATE_NEW_PROCESS_GROUP` is set, but only console control events
+/// reach a group and a windowless sidecar receives none). Two backstops sit
+/// under that for a leaf the OS somehow leaves behind: it exits when a write
+/// to its stdout fails (`print_event`), and failing that it ends itself at
+/// the deadline the root passed down (`arm_leaf_deadline`), which is the one
+/// that covers a leaf wedged in a driver call with nothing to print.
+fn kill_process_group(pid: Option<u32>) {
+ #[cfg(unix)]
+ if let Some(pid) = pid {
+ use nix::sys::signal::{killpg, Signal};
+ use nix::unistd::Pid;
+ // ESRCH is the group already being gone, which is the goal.
+ if let Err(e) = killpg(Pid::from_raw(pid as i32), Signal::SIGKILL) {
+ if e != nix::errno::Errno::ESRCH {
+ log::warn!("could not kill the hardware check's process group: {e}");
+ }
+ }
+ }
+ #[cfg(not(unix))]
+ let _ = pid;
+}
+
+/// Publishes one event of one run on the shared channel.
+fn emit_event<R: tauri::Runtime>(app_handle: &tauri::AppHandle<R>, job: &str, event: RootEvent) {
+ let payload = DiagnosticsEvent {
+ job: job.to_string(),
+ event,
+ };
+ if let Err(e) = app_handle.emit(DIAGNOSTICS_EVENT, payload) {
+ log::warn!("emit {DIAGNOSTICS_EVENT} failed: {e}");
+ }
+}
+
+/// Reads the root to the end, republishing each line. Always emits a terminal
+/// `done`, so a listener never waits forever on a root that died silently.
+async fn run_to_completion<R: tauri::Runtime>(
+ app_handle: tauri::AppHandle<R>,
+ state: Arc<DiagnosticsState>,
+ id: String,
+ mut child: tokio::process::Child,
+ stdout: Option<tokio::process::ChildStdout>,
+ stderr: Option<tokio::process::ChildStderr>,
+) {
+ // The root's own stderr is for the log, not the UI: every user-facing
+ // failure reaches the stream as an event.
+ if let Some(stderr) = stderr {
+ tokio::spawn(async move {
+ let mut lines = BufReader::new(stderr).lines();
+ while let Ok(Some(line)) = lines.next_line().await {
+ log::debug!("llamacpp diagnose: {line}");
+ }
+ });
+ }
+
+ let emit = |event: RootEvent| emit_event(&app_handle, &id, event);
+
+ let mut saw_done = false;
+ let read = async {
+ let Some(stdout) = stdout else { return };
+ let mut lines = BufReader::new(stdout).lines();
+ while let Ok(Some(line)) = lines.next_line().await {
+ if line.trim().is_empty() {
+ continue;
+ }
+ match serde_json::from_str::<RootEvent>(&line) {
+ Ok(event) => {
+ saw_done |= matches!(event, RootEvent::Done { .. });
+ emit(event);
+ }
+ // A line the desktop cannot parse is a version skew between
+ // the app and the worker beside it, which is worth a log but
+ // is not something to show or to stop the run for.
+ Err(e) => log::warn!("unreadable diagnose event ({e}): {line}"),
+ }
+ }
+ };
+
+ let outcome = tokio::time::timeout(HARD_TIMEOUT, async {
+ read.await;
+ child.wait().await
+ })
+ .await;
+
+ let timed_out = outcome.is_err();
+ if !saw_done {
+ emit(RootEvent::Done {
+ ok: false,
+ cancelled: false,
+ inconclusive: false,
+ error: Some(match outcome {
+ Err(_) => format!(
+ "the hardware check stopped answering after {} minutes",
+ HARD_TIMEOUT.as_secs() / 60
+ ),
+ Ok(Ok(status)) => format!(
+ "the hardware check ended early: {}",
+ worker::describe_exit(&status)
+ ),
+ Ok(Err(e)) => format!("the hardware check could not be watched: {e}"),
+ }),
+ });
+ }
+ if timed_out {
+ // Same reasoning as the cancel backstop: the root is being killed, so
+ // nothing of its own will stop the leaf it was running.
+ let pid = child.id();
+ let _ = child.kill().await;
+ kill_process_group(pid);
+ }
+ state.release(&id);
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn abort_handle() -> tokio::task::AbortHandle {
+ tokio::spawn(std::future::pending::<()>()).abort_handle()
+ }
+
+ #[tokio::test]
+ async fn a_second_run_is_refused_while_one_is_in_flight() {
+ let state = DiagnosticsState::default();
+ state.reserve("a").unwrap();
+ let err = state.reserve("b").unwrap_err();
+ assert!(err.contains("already running"), "{err}");
+ }
+
+ #[tokio::test]
+ async fn the_slot_is_held_from_before_the_root_is_spawned() {
+ // The window the reservation closes: a second start arriving between
+ // the spawn and the attach must still be refused, or two roots stream
+ // on one channel.
+ let state = DiagnosticsState::default();
+ state.reserve("a").unwrap();
+ assert!(state.reserve("b").is_err(), "the slot is already reserved");
+ state.attach("a", None, abort_handle(), None, None);
+ assert!(state.reserve("b").is_err(), "and stays held once attached");
+ }
+
+ #[tokio::test]
+ async fn a_failed_spawn_hands_the_slot_back() {
+ let state = DiagnosticsState::default();
+ state.reserve("a").unwrap();
+ state.release("a");
+ state.reserve("b").expect("the slot should be free again");
+ }
+
+ #[tokio::test]
+ async fn the_slot_reopens_once_the_run_releases_it() {
+ let state = DiagnosticsState::default();
+ state.reserve("a").unwrap();
+ state.attach("a", None, abort_handle(), None, None);
+ state.release("a");
+ state.reserve("b").expect("the slot should be free again");
+ }
+
+ #[tokio::test]
+ async fn a_finished_run_cannot_release_the_one_that_replaced_it() {
+ let state = DiagnosticsState::default();
+ state.reserve("a").unwrap();
+ state.release("a");
+ state.reserve("b").unwrap();
+ // "a" finishing late must not clear "b".
+ state.release("a");
+ assert!(state.reserve("c").is_err(), "b still holds the slot");
+ }
+
+ #[tokio::test]
+ async fn only_the_running_job_can_be_stopped() {
+ let state = DiagnosticsState::default();
+ state.reserve("a").unwrap();
+ let err = state.stop("b").unwrap_err();
+ assert!(err.contains("no hardware check"), "{err}");
+ state.stop("a").expect("the running job stops");
+ }
+
+ #[tokio::test]
+ async fn a_stop_during_the_spawn_is_not_lost() {
+ let state = DiagnosticsState::default();
+ state.reserve("a").unwrap();
+ state.stop("a").unwrap();
+ state.attach("a", None, abort_handle(), None, None);
+ let current = state.current.lock().unwrap();
+ let job = current.as_ref().expect("still reserved");
+ assert!(job.stopped, "the stop is remembered across the attach");
+ assert!(job.stdin.is_none(), "and the new stdin is closed at once");
+ }
+
+ #[tokio::test]
+ async fn there_is_nothing_to_kill_before_the_root_is_attached() {
+ let state = DiagnosticsState::default();
+ state.reserve("a").unwrap();
+ assert!(state.kill_handle("a").is_none());
+ state.attach("a", None, abort_handle(), None, None);
+ assert!(state.kill_handle("a").is_some());
+ }
+
+ #[test]
+ fn a_job_id_is_unique_per_run() {
+ assert_ne!(new_job_id(), new_job_id());
+ assert_eq!(new_job_id().len(), 16);
+ }
+}
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/mod.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/mod.rs
index 857b4d6f3..8e460e140 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/mod.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/mod.rs
@@ -15,9 +15,13 @@
use std::fmt;
pub mod commands;
+pub mod diag;
+pub mod diagnose;
+pub mod diagnose_commands;
pub mod driver;
pub mod events;
pub mod http;
+pub mod model_plan;
pub mod preset;
pub mod registry;
pub mod slots;
@@ -41,6 +45,9 @@ pub enum EngineError {
VersionMismatch { expected: String, actual: String },
/// A route name the shim does not know.
UnknownRoute(String),
+ /// The op diagnostic could not run at all (unknown device, bad filter);
+ /// a case that merely fails is a result, not this.
+ Diagnostic(String),
}
impl fmt::Display for EngineError {
@@ -56,6 +63,7 @@ impl fmt::Display for EngineError {
"linked llama.cpp is {actual}, but this crate is pinned to {expected}"
),
Self::UnknownRoute(r) => write!(f, "unknown engine route: {r}"),
+ Self::Diagnostic(msg) => write!(f, "the ggml op diagnostic could not run: {msg}"),
}
}
}
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/model_plan.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/model_plan.rs
new file mode 100644
index 000000000..45471ee3f
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/model_plan.rs
@@ -0,0 +1,575 @@
+//! Which ggml kernels one particular model will actually use.
+//!
+//! The Full check runs every op upstream has a test for, which is 15 minutes a
+//! device; the Quick check runs a fixed list, which cannot say anything about
+//! the model in front of the user. This builds the third answer: read a GGUF's
+//! tensor types and attention geometry, and run only the families that model's
+//! graph contains, narrowed to its shapes through upstream's `-p` filter.
+//!
+//! Deliberately outside the `engine` feature and free of Tauri: it is a pure
+//! function of a gguf's metadata, so `cargo test` covers it with no C++
+//! toolchain and no ggml, exactly as [`super::diagnose`] is.
+//!
+//! The one thing this must never do is narrow a family to nothing and let the
+//! run report a pass. It cannot know whether a regex matches until the leaf
+//! runs, so it fails *open* -- a fact it could not read means no filter rather
+//! than a guessed one -- and the root reports a unit that ran no cases as
+//! [`super::diagnose::FamilyStatus::NoCases`].
+
+use std::collections::HashMap;
+
+use serde::{Deserialize, Serialize};
+
+use super::diag::FamilyFilter;
+
+/// What the root is asked to run for a model, as the worker receives it on
+/// `--diagnose-plan`.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct ModelPlan {
+ /// The model's file name, for the `start` event. Never the directory: that
+ /// is the user's and means nothing to a result.
+ pub model: String,
+ pub families: Vec<FamilyFilter>,
+}
+
+/// ggml's own name for a type id, which is the spelling upstream's parameter
+/// strings use (`ggml_type_name`, `ggml/src/ggml.c`).
+///
+/// `None` for an id this build has no name for: a filter must leave such a
+/// tensor out rather than invent a name that matches nothing.
+pub fn ggml_type_name(id: u32) -> Option<&'static str> {
+ Some(match id {
+ 0 => "f32",
+ 1 => "f16",
+ 2 => "q4_0",
+ 3 => "q4_1",
+ 6 => "q5_0",
+ 7 => "q5_1",
+ 8 => "q8_0",
+ 9 => "q8_1",
+ 10 => "q2_K",
+ 11 => "q3_K",
+ 12 => "q4_K",
+ 13 => "q5_K",
+ 14 => "q6_K",
+ 15 => "q8_K",
+ 16 => "iq2_xxs",
+ 17 => "iq2_xs",
+ 18 => "iq3_xxs",
+ 19 => "iq1_s",
+ 20 => "iq4_nl",
+ 21 => "iq3_s",
+ 22 => "iq2_s",
+ 23 => "iq4_xs",
+ 29 => "iq1_m",
+ 30 => "bf16",
+ 34 => "tq1_0",
+ 35 => "tq2_0",
+ 39 => "mxfp4",
+ 40 => "nvfp4",
+ 41 => "q1_0",
+ 42 => "q2_0",
+ 43 => "f8_e4m3",
+ // 24-28 are the integer and f64 types, which no weight uses, and the
+ // gaps are types upstream removed.
+ _ => return None,
+ })
+}
+
+/// What a gguf says about the kernels a load will exercise.
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct ModelShape {
+ pub architecture: Option<String>,
+ /// ggml type names of the tensors, deduplicated, in the order
+ /// [`ggml_type_name`] is defined. Read off the tensor block, so a mixture
+ /// (Q4_K_M is q4_K plus q5_K, q6_K and f32) is reported as it really is.
+ pub weight_types: Vec<String>,
+ /// Attention head size, which is what sizes a flash-attention kernel.
+ pub head_size_k: Option<u64>,
+ pub head_size_v: Option<u64>,
+ /// 0 for a dense model. Non-zero means the graph contains `MUL_MAT_ID`.
+ pub expert_count: u64,
+ /// `weight_types` does not describe the whole model, so narrowing
+ /// `MUL_MAT` to it would skip the very kernel the model runs on. Two
+ /// causes, both of which leave the list looking perfectly ordinary:
+ /// a tensor type id [`ggml_type_name`] does not know, and a sharded
+ /// model, whose later splits are never opened.
+ pub incomplete_weight_types: bool,
+}
+
+impl ModelShape {
+ pub fn from_gguf(metadata: &HashMap<String, String>, tensor_types: &[u32]) -> Self {
+ let architecture = metadata.get("general.architecture").cloned();
+ let number = |suffix: &str| -> Option<u64> {
+ let arch = architecture.as_deref()?;
+ metadata
+ .get(&format!("{arch}.{suffix}"))
+ .and_then(|v| v.parse::<u64>().ok())
+ .filter(|n| *n > 0)
+ };
+
+ // llama.cpp's own fallback: with no explicit key/value length, both are
+ // the embedding width divided by the head count.
+ let fallback = match (number("embedding_length"), number("attention.head_count")) {
+ (Some(embd), Some(heads)) if embd % heads == 0 => Some(embd / heads),
+ _ => None,
+ };
+
+ Self {
+ weight_types: tensor_types
+ .iter()
+ .filter_map(|id| ggml_type_name(*id))
+ .map(str::to_string)
+ .collect(),
+ incomplete_weight_types: tensor_types
+ .iter()
+ .any(|id| ggml_type_name(*id).is_none())
+ || is_split_model(metadata),
+ head_size_k: number("attention.key_length").or(fallback),
+ head_size_v: number("attention.value_length").or(fallback),
+ expert_count: number("expert_count").unwrap_or(0),
+ architecture,
+ }
+ }
+}
+
+/// Families every transformer graph contains, and which are small enough to
+/// run whole. Shared with the Quick preset, which is the same list plus the
+/// big families under a common-shape filter.
+pub const BASE_FAMILIES: &[&str] = &[
+ "ADD", "SUB", "MUL", "DIV", "SCALE", "NORM", "RMS_NORM", "SOFT_MAX", "GET_ROWS", "SET_ROWS",
+ "ROPE", "CPY", "CONT", "CONCAT", "SILU", "GELU", "SWIGLU", "GEGLU",
+];
+
+/// Architectures whose graph is recurrent rather than attention-only, and the
+/// families that carries. Matched on a substring because upstream names a
+/// family of them (`falcon_h1`, `granitemoehybrid`) rather than one.
+const RECURRENT_FAMILIES: &[(&str, &[&str])] = &[
+ ("mamba", &["SSM_CONV", "SSM_SCAN"]),
+ ("jamba", &["SSM_CONV", "SSM_SCAN"]),
+ ("falcon_h", &["SSM_CONV", "SSM_SCAN"]),
+ ("hybrid", &["SSM_CONV", "SSM_SCAN"]),
+ ("nemotron_h", &["SSM_CONV", "SSM_SCAN"]),
+ ("plamo2", &["SSM_CONV", "SSM_SCAN"]),
+ ("rwkv", &["RWKV_WKV6", "RWKV_WKV7"]),
+];
+
+/// Types every attention matmul uses whatever the weights are quantized to:
+/// the KV cache defaults to f16 and the activations are f32. Leaving them out
+/// would narrow `MUL_MAT` to the weight kernels alone and miss the attention
+/// ones, which is where a broken device usually shows.
+const ALWAYS_MATMUL_TYPES: &[&str] = &["f32", "f16"];
+
+/// The weight types real downloads use, for the Quick preset's `MUL_MAT`.
+/// Upstream also tests several research and accelerator-specific formats that
+/// no model on the hub ships.
+const COMMON_MATMUL_TYPES: &[&str] = &[
+ "f32", "f16", "bf16", "q4_0", "q8_0", "q2_K", "q3_K", "q4_K", "q5_K", "q6_K", "iq4_xs", "mxfp4",
+];
+
+/// Head sizes the overwhelming majority of chat models use. Quick is a fixed
+/// list, so this is a judgement about the population; the model check below
+/// uses the one head size the file in front of us actually has.
+const COMMON_HEAD_SIZES: &[u64] = &[64, 128];
+
+/// Upstream's `-p` for a matmul over `types`: an alternation anchored on the
+/// trailing comma of `type_a=<name>,` so `q4_0` cannot match `q4_0_whatever`
+/// and a short name cannot prefix a longer one.
+///
+/// `None` when `types` is empty: a file whose tensor types could not be read
+/// runs `MUL_MAT` unfiltered rather than narrowed to the attention types,
+/// which would test none of the quantized kernels it actually uses. See
+/// [`model_matmul_filter`] for the other half of that guard.
+fn matmul_filter(types: &[String]) -> Option<String> {
+ if types.is_empty() {
+ return None;
+ }
+ let mut names: Vec<&str> = types.iter().map(String::as_str).collect();
+ for always in ALWAYS_MATMUL_TYPES {
+ if !names.contains(always) {
+ names.push(always);
+ }
+ }
+ Some(format!("type_a=({}),", names.join("|")))
+}
+
+/// Whether this file is one shard of a sharded model.
+///
+/// `split.count` is what `llama-gguf-split` writes, and only the first shard
+/// is ever opened here, so for any other value the tensor list is the first
+/// shard's alone. A model whose quantization differs between shards would
+/// otherwise be narrowed to the types of the one shard that was read.
+fn is_split_model(metadata: &HashMap<String, String>) -> bool {
+ metadata
+ .get("split.count")
+ .and_then(|v| v.parse::<u64>().ok())
+ .is_some_and(|n| n > 1)
+}
+
+/// The `MUL_MAT` filter for one model, or `None` to run the family whole.
+///
+/// An empty `weight_types` is not the only way the list can fail to describe
+/// the file: `from_gguf` drops ids this build does not know, and every real
+/// gguf carries f32 norm tensors, so a model quantized to a type upstream
+/// added after this pin still yields a non-empty `[f32, ...]`. A sharded
+/// model is the same story from the other end -- the list is complete for
+/// the shard that was read and silent about the rest. Filtering on either
+/// would run some kernels, skip the model's own, and report a pass.
+fn model_matmul_filter(shape: &ModelShape) -> Option<String> {
+ if shape.incomplete_weight_types {
+ return None;
+ }
+ matmul_filter(&shape.weight_types)
+}
+
+/// Upstream's `-p` for flash attention at one head geometry. `hsk` and `hsv`
+/// lead the parameter string, so this is an exact match on the pair.
+fn flash_attention_filter(head_size_k: u64, head_size_v: u64) -> String {
+ format!("hsk={head_size_k},hsv={head_size_v},")
+}
+
+/// The Quick preset: the small families whole, plus the three expensive ones
+/// narrowed to what real models use.
+///
+/// `MUL_MAT` and `FLASH_ATTN_EXT` are most of what a model spends its time in
+/// and were absent from Quick entirely before this, because an unfiltered
+/// `FLASH_ATTN_EXT` is 5,439 cases. Narrowing them is what makes including
+/// them affordable.
+pub fn quick_families() -> Vec<FamilyFilter> {
+ let common: Vec<String> = COMMON_MATMUL_TYPES.iter().map(|s| s.to_string()).collect();
+ let matmul = matmul_filter(&common);
+ let heads = COMMON_HEAD_SIZES
+ .iter()
+ .map(|h| h.to_string())
+ .collect::<Vec<_>>()
+ .join("|");
+
+ let mut out: Vec<FamilyFilter> = BASE_FAMILIES
+ .iter()
+ .map(|f| FamilyFilter::new(*f, None))
+ .collect();
+ out.push(FamilyFilter {
+ family: "MUL_MAT".into(),
+ params: matmul.clone(),
+ });
+ out.push(FamilyFilter {
+ family: "MUL_MAT_ID".into(),
+ params: matmul,
+ });
+ out.push(FamilyFilter::new(
+ "FLASH_ATTN_EXT",
+ Some(&format!("hsk=({heads}),hsv=({heads}),")),
+ ));
+ out
+}
+
+/// The families one model's graph contains, narrowed to its own shapes.
+///
+/// Fails open at every step: an unreadable head size runs flash attention
+/// unfiltered rather than at a guessed geometry, and a file whose tensor types
+/// are unreadable *or* only partly recognised runs `MUL_MAT` unfiltered.
+/// Over-running costs minutes; under-running costs the answer.
+pub fn model_families(shape: &ModelShape) -> Vec<FamilyFilter> {
+ let mut out: Vec<FamilyFilter> = BASE_FAMILIES
+ .iter()
+ .map(|f| FamilyFilter::new(*f, None))
+ .collect();
+
+ let matmul = model_matmul_filter(shape);
+ out.push(FamilyFilter {
+ family: "MUL_MAT".into(),
+ params: matmul.clone(),
+ });
+ // A dense model has no expert routing, so its graph never reaches this op
+ // and running 1,182 cases for it would only lengthen the wait.
+ if shape.expert_count > 0 {
+ out.push(FamilyFilter {
+ family: "MUL_MAT_ID".into(),
+ params: matmul,
+ });
+ }
+
+ out.push(FamilyFilter::new(
+ "FLASH_ATTN_EXT",
+ match (shape.head_size_k, shape.head_size_v) {
+ (Some(k), Some(v)) => Some(flash_attention_filter(k, v)),
+ _ => None,
+ }
+ .as_deref(),
+ ));
+
+ let arch = shape.architecture.as_deref().unwrap_or("").to_lowercase();
+ for (marker, families) in RECURRENT_FAMILIES {
+ if arch.contains(marker) {
+ for family in *families {
+ if !out.iter().any(|f| f.family == *family) {
+ out.push(FamilyFilter::new(*family, None));
+ }
+ }
+ }
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn meta(pairs: &[(&str, &str)]) -> HashMap<String, String> {
+ pairs
+ .iter()
+ .map(|(k, v)| (k.to_string(), v.to_string()))
+ .collect()
+ }
+
+ fn filter_for<'a>(families: &'a [FamilyFilter], name: &str) -> Option<&'a FamilyFilter> {
+ families.iter().find(|f| f.family == name)
+ }
+
+ #[test]
+ fn a_q4_k_m_mixture_is_read_off_the_tensors_not_the_file_type() {
+ // general.file_type says Q4_K_M; the tensors say q4_K, q5_K, q6_K, f32.
+ let shape = ModelShape::from_gguf(
+ &meta(&[
+ ("general.architecture", "qwen3"),
+ ("general.file_type", "15"),
+ ]),
+ &[0, 12, 13, 14],
+ );
+ assert_eq!(shape.weight_types, ["f32", "q4_K", "q5_K", "q6_K"]);
+ }
+
+ #[test]
+ fn an_unknown_tensor_type_is_left_out_rather_than_guessed_at() {
+ let shape = ModelShape::from_gguf(&meta(&[]), &[0, 12, 99]);
+ assert_eq!(shape.weight_types, ["f32", "q4_K"]);
+ }
+
+ #[test]
+ fn the_head_size_falls_back_to_the_embedding_width_over_the_head_count() {
+ let shape = ModelShape::from_gguf(
+ &meta(&[
+ ("general.architecture", "llama"),
+ ("llama.embedding_length", "4096"),
+ ("llama.attention.head_count", "32"),
+ ]),
+ &[],
+ );
+ assert_eq!(shape.head_size_k, Some(128));
+ assert_eq!(shape.head_size_v, Some(128));
+ }
+
+ #[test]
+ fn an_explicit_key_length_wins_over_the_fallback() {
+ let shape = ModelShape::from_gguf(
+ &meta(&[
+ ("general.architecture", "deepseek2"),
+ ("deepseek2.embedding_length", "7168"),
+ ("deepseek2.attention.head_count", "128"),
+ ("deepseek2.attention.key_length", "576"),
+ ("deepseek2.attention.value_length", "512"),
+ ]),
+ &[],
+ );
+ assert_eq!(shape.head_size_k, Some(576));
+ assert_eq!(shape.head_size_v, Some(512));
+ }
+
+ #[test]
+ fn a_head_size_that_does_not_divide_evenly_is_not_reported() {
+ // Rather than a rounded one: a filter built on it would match nothing.
+ let shape = ModelShape::from_gguf(
+ &meta(&[
+ ("general.architecture", "x"),
+ ("x.embedding_length", "100"),
+ ("x.attention.head_count", "3"),
+ ]),
+ &[],
+ );
+ assert_eq!(shape.head_size_k, None);
+ }
+
+ #[test]
+ fn the_matmul_filter_always_carries_the_attention_types() {
+ let params = filter_for(
+ &model_families(&ModelShape {
+ weight_types: vec!["q4_K".into()],
+ ..Default::default()
+ }),
+ "MUL_MAT",
+ )
+ .and_then(|f| f.params.clone())
+ .expect("MUL_MAT is filtered");
+ assert!(params.contains("q4_K"), "{params}");
+ assert!(params.contains("f16"), "{params}");
+ assert!(params.contains("f32"), "{params}");
+ assert!(
+ params.ends_with("),"),
+ "the trailing comma anchors it: {params}"
+ );
+ }
+
+ #[test]
+ fn a_type_is_not_repeated_when_the_model_already_has_it() {
+ let params = matmul_filter(&["f32".into(), "f16".into()]).unwrap();
+ assert_eq!(params, "type_a=(f32|f16),");
+ }
+
+ #[test]
+ fn a_file_with_no_readable_types_runs_matrix_math_unfiltered() {
+ // Fails open: narrowing to the attention types alone would run none of
+ // the quantized kernels the file uses and still report a clean pass.
+ let families = model_families(&ModelShape::default());
+ let matmul = filter_for(&families, "MUL_MAT").expect("MUL_MAT is planned");
+ assert_eq!(matmul.params, None);
+ }
+
+ // The realistic shape of the hazard, and the one an empty-list guard alone
+ // misses: every gguf carries f32 norm tensors, so a model quantized to a
+ // type this build does not know still reports `[f32, ...]`. Filtering on
+ // that would run the attention kernels, skip the model's own, and call it
+ // a pass.
+ #[test]
+ fn a_weight_type_this_build_does_not_know_runs_matrix_math_unfiltered() {
+ let shape = ModelShape::from_gguf(
+ &meta(&[("general.architecture", "x")]),
+ // 0 is f32; 9999 is whatever upstream adds next.
+ &[0, 9999],
+ );
+ assert!(shape.incomplete_weight_types);
+ assert_eq!(shape.weight_types, ["f32"]);
+
+ let families = model_families(&shape);
+ let matmul = filter_for(&families, "MUL_MAT").expect("MUL_MAT is planned");
+ assert_eq!(matmul.params, None);
+ }
+
+ #[test]
+ fn a_file_whose_types_are_all_recognised_is_still_narrowed() {
+ let shape = ModelShape::from_gguf(&meta(&[("general.architecture", "x")]), &[0, 12]);
+ assert!(!shape.incomplete_weight_types);
+
+ let families = model_families(&shape);
+ let matmul = filter_for(&families, "MUL_MAT").expect("MUL_MAT is planned");
+ assert!(
+ matmul.params.as_deref().is_some_and(|p| p.contains("q4_K")),
+ "{:?}",
+ matmul.params
+ );
+ }
+
+ // Only the first shard is ever opened, so its type list says nothing
+ // about the rest of the model -- and unlike an unknown id, it looks
+ // entirely ordinary.
+ #[test]
+ fn a_sharded_model_runs_matrix_math_unfiltered() {
+ let shape = ModelShape::from_gguf(
+ &meta(&[("general.architecture", "x"), ("split.count", "4")]),
+ &[0, 12],
+ );
+ assert!(shape.incomplete_weight_types);
+
+ let families = model_families(&shape);
+ let matmul = filter_for(&families, "MUL_MAT").expect("MUL_MAT is planned");
+ assert_eq!(matmul.params, None);
+ }
+
+ #[test]
+ fn a_single_file_model_is_not_mistaken_for_a_shard() {
+ let shape = ModelShape::from_gguf(
+ &meta(&[("general.architecture", "x"), ("split.count", "1")]),
+ &[0, 12],
+ );
+ assert!(!shape.incomplete_weight_types);
+ }
+
+ #[test]
+ fn flash_attention_is_pinned_to_the_models_own_head_size() {
+ let families = model_families(&ModelShape {
+ head_size_k: Some(128),
+ head_size_v: Some(128),
+ ..Default::default()
+ });
+ assert_eq!(
+ filter_for(&families, "FLASH_ATTN_EXT").and_then(|f| f.params.as_deref()),
+ Some("hsk=128,hsv=128,")
+ );
+ }
+
+ #[test]
+ fn an_unreadable_head_size_runs_flash_attention_whole() {
+ let families = model_families(&ModelShape::default());
+ assert_eq!(
+ filter_for(&families, "FLASH_ATTN_EXT").map(|f| f.params.clone()),
+ Some(None)
+ );
+ }
+
+ #[test]
+ fn expert_routing_is_planned_only_for_a_mixture_of_experts() {
+ assert!(filter_for(&model_families(&ModelShape::default()), "MUL_MAT_ID").is_none());
+ assert!(filter_for(
+ &model_families(&ModelShape {
+ expert_count: 128,
+ ..Default::default()
+ }),
+ "MUL_MAT_ID"
+ )
+ .is_some());
+ }
+
+ #[test]
+ fn a_recurrent_architecture_adds_its_own_families() {
+ let families = model_families(&ModelShape {
+ architecture: Some("falcon_h1".into()),
+ ..Default::default()
+ });
+ assert!(filter_for(&families, "SSM_SCAN").is_some());
+ assert!(filter_for(&families, "RWKV_WKV7").is_none());
+
+ let rwkv = model_families(&ModelShape {
+ architecture: Some("RWKV6".into()),
+ ..Default::default()
+ });
+ assert!(filter_for(&rwkv, "RWKV_WKV6").is_some());
+ assert!(filter_for(&rwkv, "SSM_SCAN").is_none());
+ }
+
+ #[test]
+ fn the_quick_preset_covers_the_expensive_families_under_a_filter() {
+ let families = quick_families();
+ for name in ["MUL_MAT", "MUL_MAT_ID", "FLASH_ATTN_EXT"] {
+ let f = filter_for(&families, name).unwrap_or_else(|| panic!("{name} is planned"));
+ assert!(f.params.is_some(), "{name} must be narrowed");
+ }
+ // Every base family runs whole: they are small and on every token's path.
+ for name in BASE_FAMILIES {
+ assert_eq!(
+ filter_for(&families, name).map(|f| f.params.clone()),
+ Some(None),
+ "{name}"
+ );
+ }
+ }
+
+ #[test]
+ fn the_plan_round_trips_through_json() {
+ let plan = ModelPlan {
+ model: "qwen3-8b-q4_k_m.gguf".into(),
+ families: model_families(&ModelShape {
+ weight_types: vec!["q4_K".into()],
+ head_size_k: Some(128),
+ head_size_v: Some(128),
+ expert_count: 0,
+ architecture: Some("qwen3".into()),
+ incomplete_weight_types: false,
+ }),
+ };
+ let json = serde_json::to_string(&plan).unwrap();
+ assert_eq!(serde_json::from_str::<ModelPlan>(&json).unwrap(), plan);
+ assert!(
+ !json.contains(r#""params":null"#),
+ "an absent filter is omitted: {json}"
+ );
+ }
+}
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/preset.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/preset.rs
index 0dea3417f..a117db1df 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/preset.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/preset.rs
@@ -67,6 +67,18 @@ pub fn shared_value(ini: &str, key: &str) -> Option<String> {
None
}
+/// One setting of `section`: its own line wins over `[*]`, the order the C++
+/// loader applies them in.
+pub fn value(ini: &str, section: &str, key: &str) -> Option<String> {
+ let bodies = section_bodies(ini);
+ [section, "*"].iter().find_map(|name| {
+ bodies.get(*name)?.iter().find_map(|line| {
+ let (k, v) = line.split_once('=')?;
+ (k.trim() == key).then(|| v.trim().to_string())
+ })
+ })
+}
+
/// Whether auto-fit is free to size `section`'s context: fit is on (llama.cpp's
/// default when the preset says nothing), no `ctx-size` pins it, and the split
/// mode is not `tensor`.
@@ -81,15 +93,7 @@ pub fn shared_value(ini: &str, key: &str) -> Option<String> {
/// wins over `[*]`, the order the C++ loader applies them in. Only the spellings
/// Jan's preset generator writes are read.
pub fn fit_owns_context(ini: &str, section: &str) -> bool {
- let bodies = section_bodies(ini);
- let value = |key: &str| {
- [section, "*"].iter().find_map(|name| {
- bodies.get(*name)?.iter().find_map(|line| {
- let (k, v) = line.split_once('=')?;
- (k.trim() == key).then(|| v.trim().to_string())
- })
- })
- };
+ let value = |key: &str| value(ini, section, key);
// `common_arg_utils::is_falsey`; anything else leaves fit at its default.
let fit_on = !matches!(
value("fit").as_deref(),
@@ -214,6 +218,14 @@ embeddings = true
);
}
+ #[test]
+ fn a_model_line_wins_over_the_shared_block() {
+ let ini = "[*]\nctx-size = 8192\nflash-attn = on\n[m]\nctx-size = 4096\n";
+ assert_eq!(value(ini, "m", "ctx-size").as_deref(), Some("4096"));
+ assert_eq!(value(ini, "m", "flash-attn").as_deref(), Some("on"));
+ assert_eq!(value(ini, "m", "device"), None);
+ }
+
#[test]
fn fit_owns_the_context_only_when_on_and_no_ctx_size_pins_it() {
let auto = "[*]\nparallel = 1\n\n[m]\nmodel = /m.gguf\n";
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/sys.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/sys.rs
index a6838b22d..985c9db96 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/sys.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/sys.rs
@@ -10,18 +10,26 @@ use super::EngineError;
/// must be `Send + Sync`.
pub type StateCallback = std::sync::Arc<dyn Fn(&str, &str) + Send + Sync>;
+/// Sink for the op diagnostic's JSON events, one object per call. Runs on the
+/// calling thread or on one of the run's parallel workers, never concurrently
+/// with itself, hence `Sync` but not `Send`-bound state.
+pub type DiagSink<'a> = &'a (dyn Fn(&str) + Sync);
+
#[cfg(feature = "engine")]
mod imp {
use super::EngineError;
use std::ffi::{c_char, c_int, c_void, CStr, CString};
- use super::StateCallback;
+ use super::{DiagSink, StateCallback};
+ use crate::engine::diag::{DiagMode, DiagRunRequest};
type EngineHandle = *mut c_void;
type ResponseHandle = *mut c_void;
type StateTrampoline =
unsafe extern "C" fn(state: *const c_char, payload: *const c_char, user_data: *mut c_void);
+ type DiagTrampoline = unsafe extern "C" fn(line: *const c_char, user_data: *mut c_void);
+
// The shim's ABI. Hand-declared rather than bindgen-generated: it is our
// own 14-function surface, so there is no upstream struct layout to track
// and no libclang on the build path.
@@ -64,6 +72,19 @@ mod imp {
fn jan_llama_load_backends(dir: *const c_char);
fn jan_llama_devices_json() -> *mut c_char;
fn jan_llama_device_identities_json() -> *mut c_char;
+ fn jan_llama_diag_run(
+ mode: c_int,
+ backend: *const c_char,
+ op_filter: *const c_char,
+ params_filter: *const c_char,
+ workers: c_int,
+ on_event: Option<DiagTrampoline>,
+ user_data: *mut c_void,
+ err: *mut u8,
+ err_len: usize,
+ ) -> c_int;
+ fn jan_llama_diag_ops_json() -> *mut c_char;
+ fn jan_llama_diag_backends_json() -> *mut c_char;
fn jan_llama_string_free(s: *mut c_char);
fn jan_llama_version() -> *const c_char;
fn jan_llama_build_number() -> c_int;
@@ -108,6 +129,35 @@ mod imp {
});
}
+ /// The C ABI entry point for the op diagnostic's events. `user_data` is a
+ /// `*const DiagSink` living on `diag_run`'s stack for the whole call. A
+ /// panic is caught for the same reason as in `state_trampoline`.
+ unsafe extern "C" fn diag_trampoline(line: *const c_char, user_data: *mut c_void) {
+ if user_data.is_null() || line.is_null() {
+ return;
+ }
+ let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ // SAFETY: `diag_run` passes a pointer to a live `DiagSink` and the
+ // shim stops calling before it returns; `line` is a NUL-terminated
+ // string valid for this call.
+ let sink = unsafe { &*(user_data as *const DiagSink) };
+ let line = unsafe { CStr::from_ptr(line) }.to_string_lossy();
+ sink(&line);
+ }));
+ }
+
+ /// Reads and frees a string the shim returned, or `Unavailable` for null.
+ fn take_shim_string(raw: *mut c_char) -> Result<String, EngineError> {
+ if raw.is_null() {
+ return Err(EngineError::Unavailable);
+ }
+ // SAFETY: the shim malloc()s a NUL-terminated string and we hand the
+ // same pointer back to its free.
+ let json = unsafe { CStr::from_ptr(raw) }.to_string_lossy().into_owned();
+ unsafe { jan_llama_string_free(raw) };
+ Ok(json)
+ }
+
/// Leaks the callback for the duration of the call; `from_handle` either
/// hands ownership to the `Engine` or frees it.
fn leak_state_cb(cb: Option<StateCallback>) -> Option<*mut StateCallback> {
@@ -273,6 +323,76 @@ mod imp {
Ok(json)
}
+ /// Runs upstream's `test-backend-ops` cases on one device, streaming
+ /// one JSON object per call to `on_event` (see `engine::diag` for the
+ /// shape). `Ok(true)` when every case passed, `Ok(false)` when one
+ /// failed, `Err(Diagnostic)` when nothing could run. A crash inside a
+ /// backend kills the process, so callers run this in a leaf worker.
+ ///
+ /// Registers nothing: call `load_backend_modules` first.
+ pub fn diag_run(req: &DiagRunRequest, on_event: DiagSink) -> Result<bool, EngineError> {
+ let backend =
+ CString::new(req.backend.as_str()).map_err(|e| EngineError::Diagnostic(e.to_string()))?;
+ let ops = req
+ .op_filter
+ .as_deref()
+ .map(CString::new)
+ .transpose()
+ .map_err(|e| EngineError::Diagnostic(e.to_string()))?;
+ let params = req
+ .params_filter
+ .as_deref()
+ .map(CString::new)
+ .transpose()
+ .map_err(|e| EngineError::Diagnostic(e.to_string()))?;
+ let mode = match req.mode {
+ DiagMode::Test => 0,
+ DiagMode::Support => 1,
+ };
+ let workers = c_int::try_from(req.workers.max(1)).unwrap_or(1);
+ let mut err = vec![0u8; ERR_BUF_LEN];
+ let sink = on_event;
+ // SAFETY: every pointer outlives the call; `&sink` is a thin pointer
+ // to a fat one and the shim stops calling the trampoline before it
+ // returns. The shim copies nothing it keeps.
+ let rc = unsafe {
+ jan_llama_diag_run(
+ mode,
+ backend.as_ptr(),
+ ops.as_ref().map_or(std::ptr::null(), |c| c.as_ptr()),
+ params.as_ref().map_or(std::ptr::null(), |c| c.as_ptr()),
+ workers,
+ Some(diag_trampoline as DiagTrampoline),
+ &sink as *const DiagSink as *mut c_void,
+ err.as_mut_ptr(),
+ err.len(),
+ )
+ };
+ match rc {
+ 1 => Ok(true),
+ 0 => Ok(false),
+ _ => Err(EngineError::Diagnostic(
+ CStr::from_bytes_until_nul(&err)
+ .map(|c| c.to_string_lossy().into_owned())
+ .unwrap_or_else(|_| "unknown error".to_string()),
+ )),
+ }
+ }
+
+ /// `[{"op","cases"}]`: how many cases test mode runs per op family.
+ /// Builds the whole case list, so it takes a few seconds.
+ pub fn diag_ops_json() -> Result<String, EngineError> {
+ // SAFETY: a plain getter; the result is freed by take_shim_string.
+ take_shim_string(unsafe { jan_llama_diag_ops_json() })
+ }
+
+ /// `[{"name","description","type","reg"}]` for every registered ggml
+ /// device, CPU included, without querying any device's memory.
+ pub fn diag_backends_json() -> Result<String, EngineError> {
+ // SAFETY: as `diag_ops_json`.
+ take_shim_string(unsafe { jan_llama_diag_backends_json() })
+ }
+
pub fn linked_version() -> Result<String, EngineError> {
// SAFETY: returns a pointer to a static string in the shim.
Ok(unsafe { CStr::from_ptr(jan_llama_version()) }
@@ -407,7 +527,8 @@ mod imp {
#[cfg(not(feature = "engine"))]
mod imp {
- use super::EngineError;
+ use super::{DiagSink, EngineError};
+ use crate::engine::diag::DiagRunRequest;
/// Placeholder so the crate compiles without a C++ toolchain. Every entry
/// point reports `Unavailable` rather than panicking, so a build without
@@ -450,6 +571,15 @@ mod imp {
pub fn device_identities_json() -> Result<String, EngineError> {
Err(EngineError::Unavailable)
}
+ pub fn diag_run(_req: &DiagRunRequest, _on_event: DiagSink) -> Result<bool, EngineError> {
+ Err(EngineError::Unavailable)
+ }
+ pub fn diag_ops_json() -> Result<String, EngineError> {
+ Err(EngineError::Unavailable)
+ }
+ pub fn diag_backends_json() -> Result<String, EngineError> {
+ Err(EngineError::Unavailable)
+ }
pub fn linked_version() -> Result<String, EngineError> {
Err(EngineError::Unavailable)
}
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/worker.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/worker.rs
index 70af0df5a..4866d0d9b 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/worker.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/worker.rs
@@ -277,15 +277,66 @@ struct FitNotes {
type FitFailure = Arc<Mutex<FitNotes>>;
-/// How many fit-failure lines a worker had printed at some moment; see
-/// [`WorkerHandle::fit_failure_since`].
+/// Everything the worker printed to stderr, newest last, for a load-failure
+/// report. `total` counts every line ever seen, so a load can ask for the lines
+/// printed since it started even after older ones were evicted.
+#[derive(Default)]
+struct LogBuffer {
+ total: u64,
+ lines: VecDeque<String>,
+ /// Backend modules ggml announced (`load_backend: loaded CUDA backend from
+ /// ...`), as "CUDA (libggml-cuda.so)". Kept apart from `lines` because they
+ /// are printed once at start and would be evicted long before a load fails.
+ backends: Vec<String>,
+}
+
+type WorkerLog = Arc<Mutex<LogBuffer>>;
+
+/// Lines kept for a failure report. Enough for a verbose load (tensor and
+/// device tables run to a few hundred lines) without growing for the life of a
+/// long-running worker.
+const WORKER_LOG_LINES: usize = 600;
+
+/// Per line, so a runaway progress line cannot fill the buffer.
+const WORKER_LOG_LINE_CHARS: usize = 1000;
+
+fn record_log_line(log: &WorkerLog, line: &str) {
+ let Ok(mut log) = log.lock() else { return };
+ if let Some(backend) = parse_backend_line(line) {
+ if !log.backends.contains(&backend) {
+ log.backends.push(backend);
+ }
+ }
+ log.total += 1;
+ if log.lines.len() == WORKER_LOG_LINES {
+ log.lines.pop_front();
+ }
+ log.lines
+ .push_back(line.chars().take(WORKER_LOG_LINE_CHARS).collect());
+}
+
+/// `load_backend: loaded CUDA backend from /opt/jan/libggml-cuda.so` as
+/// `CUDA (libggml-cuda.so)`; the directory is dropped because it is a local path.
+pub fn parse_backend_line(line: &str) -> Option<String> {
+ let rest = line.trim().strip_prefix("load_backend: loaded ")?;
+ let (name, path) = rest.split_once(" backend from ")?;
+ let file = path.rsplit(['/', '\\']).next().unwrap_or(path).trim();
+ Some(format!("{} ({file})", name.trim()))
+}
+
+/// How far a worker's output had got at some moment: its fit-failure lines
+/// (see [`WorkerHandle::fit_failure_since`]) and its log (see
+/// [`WorkerHandle::log_since`]).
#[derive(Debug, Clone, Copy)]
-pub struct FitMark(u64);
+pub struct FitMark {
+ fit: u64,
+ log: u64,
+}
/// Lines that are kept out of the tail, though still logged. ggml prints one
/// `load_backend: loaded ... from <path>` per backend at start, which says
/// nothing about a crash and would fill the error with local paths.
-fn is_tail_noise(line: &str) -> bool {
+pub fn is_tail_noise(line: &str) -> bool {
line.starts_with("load_backend:")
}
@@ -483,7 +534,7 @@ impl std::fmt::Debug for WorkerHandle {
/// A job object whose last handle dies with this process is the one reaping the
/// OS will do on our behalf. Unix gets this from `process_group(0)`.
#[cfg(windows)]
-mod reap {
+pub(crate) mod reap {
use std::os::windows::io::RawHandle;
use windows_sys::Win32::Foundation::{CloseHandle, HANDLE};
use windows_sys::Win32::System::JobObjects::{
@@ -493,7 +544,7 @@ mod reap {
};
/// Closing this kills every process still in the job.
- pub struct Job(HANDLE);
+ pub(crate) struct Job(HANDLE);
// The handle is opaque to everything but `Drop`, which owns it exclusively.
unsafe impl Send for Job {}
@@ -507,7 +558,7 @@ mod reap {
/// Best effort: a Jan already confined to a job that forbids nesting should
/// lose the reaping guarantee, not the engine.
- pub fn confine(child: RawHandle) -> Option<Job> {
+ pub(crate) fn confine(child: RawHandle) -> Option<Job> {
let job = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
if job.is_null() {
log::warn!("could not create a job object for the worker");
@@ -555,6 +606,7 @@ pub struct WorkerHandle {
child: Child,
stderr_tail: StderrTail,
fit_failure: FitFailure,
+ log: WorkerLog,
/// The task filling `stderr_tail`; it ends when the worker's stderr closes.
stderr_drain: Option<tokio::task::JoinHandle<()>>,
/// Declared after `child` so it is dropped after it: the graceful stop must
@@ -634,7 +686,29 @@ impl WorkerHandle {
/// Taken before a load, so only a fit failure printed during that load is
/// blamed for it: a stale one would pin the next, unrelated failure on fit.
pub fn fit_mark(&self) -> FitMark {
- FitMark(self.fit_failure.lock().map(|f| f.count).unwrap_or(0))
+ FitMark {
+ fit: self.fit_failure.lock().map(|f| f.count).unwrap_or(0),
+ log: self.log.lock().map(|l| l.total).unwrap_or(0),
+ }
+ }
+
+ /// Whatever the worker printed after `mark`, oldest first, and whether the
+ /// start of it was already evicted.
+ pub fn log_since(&self, mark: FitMark) -> (Vec<String>, bool) {
+ let Ok(log) = self.log.lock() else {
+ return (Vec::new(), false);
+ };
+ let wanted = log.total.saturating_sub(mark.log) as usize;
+ let skip = log.lines.len().saturating_sub(wanted);
+ (
+ log.lines.iter().skip(skip).cloned().collect(),
+ wanted > log.lines.len(),
+ )
+ }
+
+ /// The backend modules the worker loaded, as ggml announced them.
+ pub fn backends(&self) -> Vec<String> {
+ self.log.lock().map(|l| l.backends.clone()).unwrap_or_default()
}
/// The latest fit-failure line, if one was printed after `mark`.
@@ -648,7 +722,7 @@ impl WorkerHandle {
/// frontend loads one chat model at a time.
pub fn fit_failure_since(&self, mark: FitMark) -> Option<String> {
let notes = self.fit_failure.lock().ok()?;
- if notes.count > mark.0 {
+ if notes.count > mark.fit {
notes.last.clone()
} else {
None
@@ -748,10 +822,12 @@ pub async fn spawn(
// worker mid-generation, which is a hang with no error message.
let stderr_tail = StderrTail::default();
let fit_failure = FitFailure::default();
+ let log = WorkerLog::default();
let mut stderr_drain = None;
if let Some(stderr) = child.stderr.take() {
let tail = stderr_tail.clone();
let fit_note = fit_failure.clone();
+ let worker_log = log.clone();
stderr_drain = Some(tokio::spawn(async move {
let mut lines = BufReader::new(stderr).lines();
let mut reader = FaultReader::default();
@@ -782,6 +858,7 @@ pub async fn spawn(
let Ok(Some(line)) = next else { break };
log::debug!("jan-llama-worker: {line}");
remember_stderr_line(&tail, &line);
+ record_log_line(&worker_log, &line);
if is_fit_failure_line(&line.to_lowercase()) {
if let Ok(mut notes) = fit_note.lock() {
notes.count += 1;
@@ -858,6 +935,7 @@ pub async fn spawn(
child,
stderr_tail,
fit_failure,
+ log,
stderr_drain,
#[cfg(windows)]
_job: job,
@@ -1298,6 +1376,41 @@ pub(crate) mod tests {
);
}
+ #[test]
+ fn the_log_since_a_mark_holds_only_what_came_after_it() {
+ let log = WorkerLog::default();
+ record_log_line(&log, "before");
+ let mark = FitMark { fit: 0, log: log.lock().unwrap().total };
+ record_log_line(&log, "during 1");
+ record_log_line(&log, "during 2");
+ let buf = log.lock().unwrap();
+ let wanted = buf.total.saturating_sub(mark.log) as usize;
+ let tail: Vec<_> = buf.lines.iter().skip(buf.lines.len() - wanted).collect();
+ assert_eq!(tail, ["during 1", "during 2"]);
+ }
+
+ #[test]
+ fn the_log_is_bounded_and_backends_survive_eviction() {
+ let log = WorkerLog::default();
+ record_log_line(&log, "load_backend: loaded CUDA backend from /home/u/jan/libggml-cuda.so");
+ for i in 0..(WORKER_LOG_LINES + 50) {
+ record_log_line(&log, &format!("line {i}"));
+ }
+ let buf = log.lock().unwrap();
+ assert_eq!(buf.lines.len(), WORKER_LOG_LINES);
+ assert_eq!(buf.backends, ["CUDA (libggml-cuda.so)"]);
+ }
+
+ #[test]
+ fn a_backend_line_drops_the_local_directory() {
+ assert_eq!(
+ parse_backend_line(r"load_backend: loaded Vulkan backend from C:\Users\bob\jan\ggml-vulkan.dll")
+ .as_deref(),
+ Some("Vulkan (ggml-vulkan.dll)")
+ );
+ assert_eq!(parse_backend_line("ggml_vulkan: Found 1 Vulkan devices"), None);
+ }
+
#[cfg(unix)]
#[test]
fn exit_statuses_read_the_way_users_search_for_them() {
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/error.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/error.rs
index 249058bb3..d43c64b42 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/error.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/error.rs
@@ -1,5 +1,7 @@
use serde::{Deserialize, Serialize};
+use crate::diagnostics::LoadDiagnostics;
+
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ErrorCode {
@@ -45,6 +47,9 @@ pub struct LlamacppError {
/// install advice instead of showing raw engine output.
#[serde(skip_serializing_if = "Option::is_none")]
pub missing_libraries: Option<Vec<String>>,
+ /// The request, machine, engine and log of a failed load, for a bug report.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub diagnostics: Option<Box<LoadDiagnostics>>,
}
impl LlamacppError {
@@ -54,6 +59,7 @@ impl LlamacppError {
message,
details,
missing_libraries: None,
+ diagnostics: None,
}
}
@@ -325,6 +331,31 @@ mod tests {
assert!(json.get("details").is_none(), "{json}");
assert!(json.get("missing_libraries").is_none(), "{json}");
+ assert!(json.get("diagnostics").is_none(), "{json}");
+ }
+
+ #[test]
+ fn diagnostics_cross_the_boundary_under_their_own_key() {
+ let mut err = LlamacppError::new(ErrorCode::ModelLoadFailed, "x".into(), None);
+ err.diagnostics = Some(Box::new(LoadDiagnostics {
+ model_file: Some("m.gguf".into()),
+ architecture: Some("qwen3".into()),
+ quantization: Some("Q4_K_M".into()),
+ request: Default::default(),
+ gpus: vec![],
+ backends: vec!["CPU (libggml-cpu.so)".into()],
+ engine: crate::diagnostics::EngineBuild {
+ version: "0.9.0".into(),
+ tag: "b1".into(),
+ commit: "abc".into(),
+ },
+ log: "boom".into(),
+ log_truncated: false,
+ }));
+ let json: serde_json::Value = serde_json::to_value(&err).unwrap();
+ assert_eq!(json["diagnostics"]["model_file"], "m.gguf");
+ assert_eq!(json["diagnostics"]["backends"][0], "CPU (libggml-cpu.so)");
+ assert_eq!(json["diagnostics"]["log"], "boom");
}
#[test]
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/helpers.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/helpers.rs
index b4c22d98a..b4982479a 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/helpers.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/helpers.rs
@@ -33,12 +33,46 @@ pub fn find_gguf_tensors<R: Read + Seek>(
reader: R,
wanted: &[String],
) -> io::Result<Vec<String>> {
- let mut file = BufReader::new(reader);
- let meta = read_header(&mut file)?;
-
if wanted.is_empty() {
return Ok(Vec::new());
}
+ let mut found: Vec<String> = Vec::new();
+ walk_tensor_info(reader, |name, _type_id| {
+ if wanted.contains(&name) && !found.contains(&name) {
+ found.push(name);
+ }
+ found.len() < wanted.len()
+ })?;
+ Ok(found)
+}
+
+/// The distinct ggml type ids the tensor block uses, in ascending order.
+///
+/// Ground truth for which quantized kernels a load will exercise, as against
+/// inferring them from `general.file_type`: a file type names a *recipe*
+/// (Q4_K_M mixes q4_K, q5_K, q6_K and f32), and llama.cpp's mixture rules
+/// change, while the tensors themselves cannot be wrong.
+pub fn read_gguf_tensor_types<R: Read + Seek>(reader: R) -> io::Result<Vec<u32>> {
+ let mut types: Vec<u32> = Vec::new();
+ walk_tensor_info(reader, |_name, type_id| {
+ if !types.contains(&type_id) {
+ types.push(type_id);
+ }
+ true
+ })?;
+ types.sort_unstable();
+ Ok(types)
+}
+
+/// Walks the tensor-info block, calling `visit` with each tensor's name and
+/// ggml type. Stops early when `visit` returns false.
+fn walk_tensor_info<R: Read + Seek>(
+ reader: R,
+ mut visit: impl FnMut(String, u32) -> bool,
+) -> io::Result<()> {
+ let mut file = BufReader::new(reader);
+ let meta = read_header(&mut file)?;
+
// v1 sized strings and dimensions with u32s. llama.cpp refuses that
// version outright, and reading it as v2 would invent names.
if meta.version < 2 {
@@ -54,7 +88,6 @@ pub fn find_gguf_tensors<R: Read + Seek>(
));
}
- let mut found: Vec<String> = Vec::new();
for i in 0..meta.tensor_count {
let name = read_gguf_string(&mut file).map_err(|e| {
io::Error::new(
@@ -74,17 +107,14 @@ pub fn find_gguf_tensors<R: Read + Seek>(
for _ in 0..n_dims {
file.read_u64::<LittleEndian>()?;
}
- file.read_u32::<LittleEndian>()?; // ggml type
+ let type_id = file.read_u32::<LittleEndian>()?;
file.read_u64::<LittleEndian>()?; // offset into the data section
- if wanted.contains(&name) && !found.contains(&name) {
- found.push(name);
- if found.len() == wanted.len() {
- break;
- }
+ if !visit(name, type_id) {
+ break;
}
}
- Ok(found)
+ Ok(())
}
/// Header plus the whole KV section, leaving the reader positioned at the
@@ -245,6 +275,16 @@ mod tests {
/// Hand-assembled because the point is to pin the byte layout the reader
/// walks; a fixture file would hide it.
fn gguf(version: u32, kv: &[(&str, &str)], tensors: &[(&str, &[u64])]) -> Vec<u8> {
+ let typed: Vec<(&str, &[u64], u32)> =
+ tensors.iter().map(|(n, d)| (*n, *d, 0u32)).collect();
+ gguf_typed(version, kv, &typed)
+ }
+
+ fn gguf_typed(
+ version: u32,
+ kv: &[(&str, &str)],
+ tensors: &[(&str, &[u64], u32)],
+ ) -> Vec<u8> {
let mut b = Vec::new();
b.extend_from_slice(b"GGUF");
b.write_u32::<LittleEndian>(version).unwrap();
@@ -260,13 +300,13 @@ mod tests {
b.write_u32::<LittleEndian>(GgufValueType::String as u32).unwrap();
string(&mut b, v);
}
- for (name, dims) in tensors {
+ for (name, dims, type_id) in tensors {
string(&mut b, name);
b.write_u32::<LittleEndian>(dims.len() as u32).unwrap();
for d in *dims {
b.write_u64::<LittleEndian>(*d).unwrap();
}
- b.write_u32::<LittleEndian>(0).unwrap(); // ggml type
+ b.write_u32::<LittleEndian>(*type_id).unwrap();
b.write_u64::<LittleEndian>(0).unwrap(); // offset
}
b
@@ -372,4 +412,33 @@ mod tests {
.expect("tensor scan")
.is_empty());
}
+
+ // A Q4_K_M file is a mixture, which is the whole reason the types are read
+ // off the tensors rather than inferred from `general.file_type`.
+ #[test]
+ fn the_distinct_tensor_types_are_reported_once_each_in_order() {
+ let bytes = gguf_typed(
+ 3,
+ &[],
+ &[
+ ("token_embd.weight", &[8], 14), // q6_K
+ ("blk.0.attn_norm.weight", &[8], 0), // f32
+ ("blk.0.attn_q.weight", &[8, 8], 12), // q4_K
+ ("blk.1.attn_q.weight", &[8, 8], 12),
+ ("blk.0.ffn_down.weight", &[8, 8], 13), // q5_K
+ ],
+ );
+ assert_eq!(
+ read_gguf_tensor_types(Cursor::new(bytes)).expect("tensor types"),
+ vec![0, 12, 13, 14]
+ );
+ }
+
+ #[test]
+ fn a_file_with_no_tensors_reports_no_types() {
+ let bytes = gguf(3, &[("general.architecture", "llama")], &[]);
+ assert!(read_gguf_tensor_types(Cursor::new(bytes))
+ .expect("tensor types")
+ .is_empty());
+ }
}
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/utils.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/utils.rs
index bc3c0e5d2..ca4dc4b5e 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/utils.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/utils.rs
@@ -89,6 +89,16 @@ pub async fn find_gguf_tensors_internal(
.await
}
+/// The distinct ggml type ids the gguf's tensors use. See
+/// [`helpers::read_gguf_tensor_types`] for why this is read rather than
+/// inferred from `general.file_type`.
+pub async fn read_gguf_tensor_types_internal(path: String) -> Result<Vec<u32>, String> {
+ parse_gguf(&path, "GGUF tensor types", |r: &mut (dyn ReadSeek + '_)| {
+ helpers::read_gguf_tensor_types(r)
+ })
+ .await
+}
+
/// Estimate KVCache size from a given metadata
pub async fn estimate_kv_cache_internal(
meta: HashMap<String, String>,
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs
index 4383514fa..e6d335b2c 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs
@@ -7,6 +7,7 @@ use tauri::{
pub mod cleanup;
mod commands;
+pub mod diagnostics;
pub mod engine;
mod error;
mod gguf;
@@ -33,6 +34,8 @@ pub fn init<R: Runtime>() -> TauriPlugin<R> {
engine::commands::begin_engine_restart,
engine::commands::end_engine_restart,
engine::commands::erase_thread_slot_state,
+ engine::diagnose_commands::start_diagnostics,
+ engine::diagnose_commands::cancel_diagnostics,
commands::generate_api_key,
commands::ensure_session_ready,
commands::find_session_by_model,
@@ -43,6 +46,7 @@ pub fn init<R: Runtime>() -> TauriPlugin<R> {
])
.setup(|app, _api| {
app.manage(Arc::new(state::LlamacppState::new()));
+ app.manage(Arc::new(engine::diagnose_commands::DiagnosticsState::default()));
Ok(())
})
.build()
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/tests/diag_backend_ops.rs b/src-tauri/plugins/tauri-plugin-llamacpp/tests/diag_backend_ops.rs
new file mode 100644
index 000000000..4af541305
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/tests/diag_backend_ops.rs
@@ -0,0 +1,91 @@
+//! The upstream `test-backend-ops` wrapper, driven through the safe API.
+//!
+//! Needs the `engine` feature and no model: it runs ggml's own CPU backend on
+//! a tiny op filter, so it is cheap enough to be a regular check.
+#![cfg(feature = "engine")]
+
+use std::sync::Mutex;
+
+use tauri_plugin_llamacpp::engine::diag::{
+ DiagBackend, DiagEvent, DiagMode, DiagOp, DiagRunRequest, DiagTally,
+};
+use tauri_plugin_llamacpp::engine::Engine;
+
+fn run(req: &DiagRunRequest) -> (Result<bool, tauri_plugin_llamacpp::engine::EngineError>, Vec<String>) {
+ tauri_plugin_llamacpp::engine::load_backend_modules();
+ let lines = Mutex::new(Vec::new());
+ let outcome = Engine::diag_run(req, &|line: &str| lines.lock().unwrap().push(line.to_string()));
+ (outcome, lines.into_inner().unwrap())
+}
+
+fn cpu_add() -> DiagRunRequest {
+ DiagRunRequest {
+ mode: DiagMode::Test,
+ backend: "CPU".to_string(),
+ op_filter: Some("ADD".to_string()),
+ // One shape family keeps this to a handful of cases.
+ params_filter: Some("type=f32,ne=\\[16,5,4,3\\],nr=\\[1,1,1,1\\]".to_string()),
+ workers: 1,
+ }
+}
+
+#[test]
+fn the_cpu_backend_passes_a_tiny_add_run_and_every_event_parses() {
+ let (outcome, lines) = run(&cpu_add());
+ assert_eq!(outcome, Ok(true), "events: {lines:#?}");
+
+ let events: Vec<DiagEvent> = lines
+ .iter()
+ .map(|l| DiagEvent::parse(l).unwrap_or_else(|e| panic!("unparsable event {l}: {e}")))
+ .collect();
+
+ let mut tally = DiagTally::default();
+ for e in &events {
+ tally.record(e);
+ }
+ assert!(tally.ok > 0, "no case ran: {lines:#?}");
+ assert_eq!(tally.failed, 0, "{lines:#?}");
+ assert!(
+ matches!(events.last(), Some(DiagEvent::Done { ok: true, error: None })),
+ "the stream must end with done: {lines:#?}"
+ );
+ assert!(events
+ .iter()
+ .any(|e| matches!(e, DiagEvent::OverallSummary { all_passed: true, .. })));
+}
+
+#[test]
+fn an_unknown_backend_is_reported_not_run() {
+ let mut req = cpu_add();
+ req.backend = "NoSuchDevice0".to_string();
+ let (outcome, lines) = run(&req);
+ assert!(outcome.is_err(), "{outcome:?}");
+ let last = DiagEvent::parse(lines.last().expect("a done event")).unwrap();
+ assert!(matches!(last, DiagEvent::Done { ok: false, error: Some(_) }), "{last:?}");
+}
+
+#[test]
+fn a_bad_params_regex_is_reported_not_thrown() {
+ let mut req = cpu_add();
+ req.params_filter = Some("(".to_string());
+ let (outcome, _) = run(&req);
+ assert!(outcome.is_err(), "{outcome:?}");
+}
+
+#[test]
+fn the_op_listing_counts_real_cases_per_family() {
+ tauri_plugin_llamacpp::engine::load_backend_modules();
+ let json = Engine::diag_ops_json().expect("ops listing");
+ let ops: Vec<DiagOp> = serde_json::from_str(&json).expect("ops json parses");
+ let add = ops.iter().find(|o| o.op == "ADD").expect("ADD is listed");
+ assert!(add.cases > 0, "ADD has no cases");
+ assert!(ops.iter().any(|o| o.cases == 0), "untested ops are listed with 0");
+}
+
+#[test]
+fn the_backend_listing_includes_the_cpu_device() {
+ tauri_plugin_llamacpp::engine::load_backend_modules();
+ let json = Engine::diag_backends_json().expect("backend listing");
+ let backends: Vec<DiagBackend> = serde_json::from_str(&json).expect("backends json parses");
+ assert!(backends.iter().any(|b| b.name == "CPU"), "{backends:?}");
+}
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/tests/diagnose_root.rs b/src-tauri/plugins/tauri-plugin-llamacpp/tests/diagnose_root.rs
new file mode 100644
index 000000000..b32bf1756
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/tests/diagnose_root.rs
@@ -0,0 +1,687 @@
+//! The root `--diagnose` orchestration against stand-in leaf processes.
+//!
+//! Real processes, not a mocked runner: CRASHED and HUNG are things an OS does
+//! to a child, and the point of the root is that it survives them. The leaves
+//! are generated scripts so the test needs no second binary.
+//!
+//! Needs no `engine` feature: the root loads no ggml, which is the property
+//! that makes it the crash boundary in the first place.
+
+use std::path::{Path, PathBuf};
+use std::time::Duration;
+
+use tauri_plugin_llamacpp::diagnostics::EngineBuild;
+use tauri_plugin_llamacpp::engine::diag::{
+ DiagDevice, DiagDeviceKind, DiagStatus, FamilyFilter,
+};
+use tauri_plugin_llamacpp::engine::diagnose::{
+ run, DiagPreset, DiagnosePlan, FamilyStatus, LeafSpec, RootEvent,
+};
+
+/// What a stand-in leaf does when it is run.
+#[derive(Default)]
+struct FakeLeaf {
+ stdout: Vec<String>,
+ stderr: Vec<String>,
+ /// Seconds to sleep after printing, before exiting.
+ sleep: u32,
+ exit: i32,
+}
+
+/// Argument that makes a stand-in leaf exit at once, printing nothing. Used to
+/// wait out `ETXTBSY` below; the real argv starts with `--diagnose-run`, so a
+/// leaf never sees it in anger.
+const PREFLIGHT: &str = "--jan-preflight";
+
+impl FakeLeaf {
+ fn write(&self, dir: &Path, name: &str) -> PathBuf {
+ let path = dir.join(format!("{name}{}", if cfg!(windows) { ".cmd" } else { ".sh" }));
+ let mut script = String::new();
+ if cfg!(windows) {
+ script.push_str("@echo off\r\n");
+ script.push_str(&format!("if \"%1\"==\"{PREFLIGHT}\" exit /b 0\r\n"));
+ for line in &self.stdout {
+ script.push_str(&format!("echo {line}\r\n"));
+ }
+ for line in &self.stderr {
+ script.push_str(&format!("echo {line} 1>&2\r\n"));
+ }
+ if self.sleep > 0 {
+ // Not `timeout /t`: it reads the console and exits at once
+ // with "Input redirection is not supported" when stdin is a
+ // pipe, which is exactly how the root starts a leaf. The leaf
+ // then never sleeps, and the tests that need one still running
+ // (hung, cancelled, deadline) see a crash instead. `ping`
+ // touches no console; -n counts pings, so it waits n-1 times.
+ script.push_str(&format!(
+ "ping -n {} 127.0.0.1 > nul\r\n",
+ self.sleep + 1
+ ));
+ }
+ script.push_str(&format!("exit /b {}\r\n", self.exit));
+ } else {
+ script.push_str("#!/bin/sh\n");
+ script.push_str(&format!("[ \"$1\" = \"{PREFLIGHT}\" ] && exit 0\n"));
+ for line in &self.stdout {
+ script.push_str(&format!("echo '{line}'\n"));
+ }
+ for line in &self.stderr {
+ script.push_str(&format!("echo '{line}' >&2\n"));
+ }
+ if self.sleep > 0 {
+ script.push_str(&format!("sleep {}\n", self.sleep));
+ }
+ script.push_str(&format!("exit {}\n", self.exit));
+ }
+ std::fs::write(&path, script).unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
+ }
+ wait_until_executable(&path);
+ path
+ }
+}
+
+/// Runs the script once, harmlessly, until the OS agrees it may be executed.
+///
+/// `cargo test` runs these tests on threads of one process, so another test's
+/// `fork` can inherit this file's still-open write descriptor and hold it
+/// across the window before that child `exec`s. Executing it then fails with
+/// `ETXTBSY` ("Text file busy"), which the root reports as a crashed family
+/// and the test reads as a real failure -- intermittently, on whichever test
+/// loses the race. Once a preflight succeeds the descriptor has drained, and
+/// nothing reopens the file for writing, so every later spawn is safe.
+fn wait_until_executable(path: &Path) {
+ for _ in 0..200 {
+ match std::process::Command::new(path).arg(PREFLIGHT).output() {
+ Ok(_) => return,
+ Err(e) if e.raw_os_error() == Some(26) => {
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ // Anything else is the test's own problem and will surface with a
+ // better message when the root tries to run it.
+ Err(_) => return,
+ }
+ }
+}
+
+fn result_line(op: &str, status: &str) -> String {
+ format!(
+ r#"{{"event":"result","backend":"CPU","op":"{op}","params":"type=f32","mode":"test","status":"{status}"}}"#
+ )
+}
+
+fn done_line(ok: bool) -> String {
+ format!(r#"{{"event":"done","ok":{ok}}}"#)
+}
+
+fn device(name: &str) -> DiagDevice {
+ DiagDevice {
+ name: name.into(),
+ description: "stand-in".into(),
+ kind: DiagDeviceKind::Cpu,
+ reg: "CPU".into(),
+ memory_total_mib: None,
+ memory_free_mib: None,
+ }
+}
+
+fn plan(families: &[&str]) -> DiagnosePlan {
+ DiagnosePlan {
+ preset: DiagPreset::Quick,
+ engine: EngineBuild {
+ version: "0.0.0".into(),
+ tag: "b12110".into(),
+ commit: "deadbeef".into(),
+ },
+ devices: vec![device("CPU")],
+ families: families
+ .iter()
+ .map(|f| FamilyFilter::new(*f, None))
+ .collect(),
+ model: None,
+ support_probe: false,
+ workers: 1,
+ backend_modules: vec!["libggml-cpu.so".into()],
+ family_timeout: Duration::from_millis(600),
+ deadline: Duration::from_secs(30),
+ }
+}
+
+async fn collect(plan: &DiagnosePlan, leaf: PathBuf) -> Vec<RootEvent> {
+ collect_with(plan, leaf, std::future::pending()).await
+}
+
+async fn collect_with(
+ plan: &DiagnosePlan,
+ leaf: PathBuf,
+ cancel: impl std::future::Future<Output = ()>,
+) -> Vec<RootEvent> {
+ let mut events = Vec::new();
+ run(plan, &LeafSpec::new(leaf), cancel, &mut |e| events.push(e)).await;
+ events
+}
+
+fn families(events: &[RootEvent]) -> Vec<(&str, FamilyStatus)> {
+ events
+ .iter()
+ .filter_map(|e| match e {
+ RootEvent::FamilyEnd { family, status, .. } => Some((family.as_str(), *status)),
+ _ => None,
+ })
+ .collect()
+}
+
+fn done(events: &[RootEvent]) -> (bool, bool) {
+ events
+ .iter()
+ .find_map(|e| match e {
+ RootEvent::Done { ok, cancelled, .. } => Some((*ok, *cancelled)),
+ _ => None,
+ })
+ .expect("a run always ends with done")
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn a_clean_leaf_reports_ok_and_forwards_every_case() {
+ let dir = tempfile::tempdir().unwrap();
+ let leaf = FakeLeaf {
+ stdout: vec![
+ result_line("ADD", "ok"),
+ result_line("ADD", "not_supported"),
+ done_line(true),
+ ],
+ ..Default::default()
+ }
+ .write(dir.path(), "clean");
+
+ let events = collect(&plan(&["ADD"]), leaf).await;
+
+ assert_eq!(families(&events), vec![("ADD", FamilyStatus::Ok)]);
+ assert_eq!(done(&events), (true, false));
+
+ let cases: Vec<_> = events
+ .iter()
+ .filter_map(|e| match e {
+ RootEvent::Case { case, family, .. } => Some((family.clone(), case.status)),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(
+ cases,
+ vec![
+ ("ADD".to_string(), DiagStatus::Ok),
+ ("ADD".to_string(), DiagStatus::NotSupported)
+ ],
+ "every case the leaf reported must reach the stream, tagged with its family"
+ );
+
+ let summary = events
+ .iter()
+ .find_map(|e| match e {
+ RootEvent::Summary {
+ ok, not_supported, ..
+ } => Some((*ok, *not_supported)),
+ _ => None,
+ })
+ .unwrap();
+ assert_eq!(summary, (1, 1), "a not-supported case is not a pass");
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn the_run_opens_with_the_schema_and_one_event_per_device() {
+ let dir = tempfile::tempdir().unwrap();
+ let leaf = FakeLeaf {
+ stdout: vec![done_line(true)],
+ ..Default::default()
+ }
+ .write(dir.path(), "empty");
+
+ let mut p = plan(&["ADD"]);
+ p.devices = vec![device("CPU"), device("Vulkan0")];
+ let events = collect(&p, leaf).await;
+
+ match &events[0] {
+ RootEvent::Start { schema, units, .. } => {
+ assert_eq!(*schema, 2);
+ assert_eq!(*units, 2, "one family on each of two devices");
+ }
+ other => panic!("a run must open with start, got {other:?}"),
+ }
+ assert_eq!(
+ events
+ .iter()
+ .filter(|e| matches!(e, RootEvent::Device(_)))
+ .count(),
+ 2
+ );
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn a_failing_case_is_a_failure_not_a_crash() {
+ let dir = tempfile::tempdir().unwrap();
+ let leaf = FakeLeaf {
+ stdout: vec![result_line("ADD", "fail"), done_line(false)],
+ ..Default::default()
+ }
+ .write(dir.path(), "failing");
+
+ let events = collect(&plan(&["ADD"]), leaf).await;
+
+ assert_eq!(families(&events), vec![("ADD", FamilyStatus::Fail)]);
+ assert_eq!(done(&events), (false, false));
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn a_leaf_that_dies_is_crashed_and_the_next_family_still_runs() {
+ let dir = tempfile::tempdir().unwrap();
+ let leaf = FakeLeaf {
+ stdout: vec![result_line("ADD", "ok")],
+ stderr: vec!["ggml_vulkan: device lost".into()],
+ exit: 1,
+ ..Default::default()
+ }
+ .write(dir.path(), "crasher");
+
+ let events = collect(&plan(&["ADD", "MUL"]), leaf).await;
+
+ assert_eq!(
+ families(&events),
+ vec![
+ ("ADD", FamilyStatus::Crashed),
+ ("MUL", FamilyStatus::Crashed)
+ ],
+ "a crash ends its own family only; the root keeps going"
+ );
+
+ let end = events
+ .iter()
+ .find_map(|e| match e {
+ RootEvent::FamilyEnd {
+ exit, last_lines, ok, ..
+ } => Some((exit.clone(), last_lines.clone(), *ok)),
+ _ => None,
+ })
+ .unwrap();
+ assert_eq!(end.0.as_deref(), Some("exit code 1"));
+ assert!(
+ end.1.iter().any(|l| l.contains("device lost")),
+ "the leaf's last words are what explain a crash: {:?}",
+ end.1
+ );
+ assert_eq!(end.2, 1, "cases reported before the crash are kept");
+ assert_eq!(done(&events), (false, false));
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn a_leaf_that_stops_without_saying_done_is_a_crash() {
+ let dir = tempfile::tempdir().unwrap();
+ // Exit 0, but the stream never terminated: the leaf went away mid-family.
+ let leaf = FakeLeaf {
+ stdout: vec![result_line("ADD", "ok")],
+ ..Default::default()
+ }
+ .write(dir.path(), "truncated");
+
+ let events = collect(&plan(&["ADD"]), leaf).await;
+ assert_eq!(families(&events), vec![("ADD", FamilyStatus::Crashed)]);
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn a_leaf_that_hangs_is_killed_and_marked_hung() {
+ let dir = tempfile::tempdir().unwrap();
+ let leaf = FakeLeaf {
+ stdout: vec![result_line("ADD", "ok")],
+ sleep: 60,
+ ..Default::default()
+ }
+ .write(dir.path(), "hung");
+
+ let started = std::time::Instant::now();
+ let events = collect(&plan(&["ADD"]), leaf).await;
+
+ assert_eq!(families(&events), vec![("ADD", FamilyStatus::Hung)]);
+ assert!(
+ started.elapsed() < Duration::from_secs(30),
+ "the family timeout, not the leaf, decides when a hang ends"
+ );
+ let exit = events.iter().find_map(|e| match e {
+ RootEvent::FamilyEnd { exit, .. } => exit.clone(),
+ _ => None,
+ });
+ assert_eq!(exit, None, "a killed leaf has no exit status of its own");
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn garbage_on_stdout_is_reported_rather_than_parsed() {
+ let dir = tempfile::tempdir().unwrap();
+ let leaf = FakeLeaf {
+ stdout: vec![
+ "Testing 2 devices".into(),
+ "not json at all".into(),
+ result_line("ADD", "ok"),
+ done_line(true),
+ ],
+ ..Default::default()
+ }
+ .write(dir.path(), "noisy");
+
+ let events = collect(&plan(&["ADD"]), leaf).await;
+
+ let (status, unparsed, ok) = events
+ .iter()
+ .find_map(|e| match e {
+ RootEvent::FamilyEnd {
+ status,
+ unparsed,
+ ok,
+ ..
+ } => Some((*status, unparsed.clone(), *ok)),
+ _ => None,
+ })
+ .unwrap();
+ assert_eq!(
+ status,
+ FamilyStatus::Ok,
+ "noise is not a reason to fail a family that otherwise passed"
+ );
+ assert_eq!(unparsed, vec!["Testing 2 devices", "not json at all"]);
+ assert_eq!(ok, 1, "the real events around the noise are still read");
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn cancel_ends_the_run_and_marks_what_never_ran() {
+ let dir = tempfile::tempdir().unwrap();
+ let leaf = FakeLeaf {
+ stdout: vec![result_line("ADD", "ok")],
+ sleep: 60,
+ ..Default::default()
+ }
+ .write(dir.path(), "slow");
+
+ let mut p = plan(&["ADD", "MUL", "SUB"]);
+ p.family_timeout = Duration::from_secs(60);
+
+ let started = std::time::Instant::now();
+ let events = collect_with(&p, leaf, tokio::time::sleep(Duration::from_millis(300))).await;
+
+ assert_eq!(
+ families(&events),
+ vec![
+ ("ADD", FamilyStatus::Cancelled),
+ ("MUL", FamilyStatus::Cancelled),
+ ("SUB", FamilyStatus::Cancelled)
+ ],
+ "the family in flight and every family after it are cancelled"
+ );
+ assert_eq!(done(&events), (false, true));
+ // Counted on the summary, or a device whose remaining families were
+ // dropped reads as a clean pass on the ones that did run.
+ let cancelled = events.iter().find_map(|e| match e {
+ RootEvent::Summary {
+ families_cancelled, ..
+ } => Some(*families_cancelled),
+ _ => None,
+ });
+ assert_eq!(cancelled, Some(3));
+ assert!(
+ started.elapsed() < Duration::from_secs(30),
+ "cancel must not wait out the family timeout"
+ );
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn the_support_probe_does_not_inflate_the_pass_count() {
+ // The probe asks `ggml_backend_supports_op` over the whole op list and
+ // reports every supported case as `ok` without computing anything, so a
+ // summary that adds it tells the user cases passed that never ran. The
+ // leaf is one script, so both units report the same three cases: the
+ // separation has to come from the unit's mode, not from the leaf.
+ let dir = tempfile::tempdir().unwrap();
+ let leaf = FakeLeaf {
+ stdout: vec![
+ result_line("ADD", "ok"),
+ result_line("ADD", "ok"),
+ result_line("ADD", "not_supported"),
+ done_line(true),
+ ],
+ ..Default::default()
+ }
+ .write(dir.path(), "probe-and-test");
+
+ let mut p = plan(&["ADD"]);
+ p.support_probe = true;
+
+ let events = collect(&p, leaf).await;
+
+ let summary = events.iter().find_map(|e| match e {
+ RootEvent::Summary {
+ ok,
+ failed,
+ not_supported,
+ ..
+ } => Some((*ok, *failed, *not_supported)),
+ _ => None,
+ });
+ assert_eq!(
+ summary,
+ Some((2, 0, 1)),
+ "the pass count is the test unit's alone, and the probe is the one \
+ source of not-supported rather than both being added"
+ );
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn a_device_with_no_probe_still_reports_what_it_could_not_run() {
+ // With no probe, the test units are the only source there is.
+ let dir = tempfile::tempdir().unwrap();
+ let leaf = FakeLeaf {
+ stdout: vec![result_line("ADD", "not_supported"), done_line(true)],
+ ..Default::default()
+ }
+ .write(dir.path(), "unsupported");
+
+ let events = collect(&plan(&["ADD"]), leaf).await;
+
+ let not_supported = events.iter().find_map(|e| match e {
+ RootEvent::Summary { not_supported, .. } => Some(*not_supported),
+ _ => None,
+ });
+ assert_eq!(not_supported, Some(1));
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn a_partly_cancelled_device_reports_what_never_ran() {
+ // The case the summary has to carry: one family passed and the rest were
+ // dropped, so the device is neither failed nor a clean pass.
+ let dir = tempfile::tempdir().unwrap();
+ let leaf = FakeLeaf {
+ stdout: vec![result_line("ADD", "ok"), done_line(true)],
+ sleep: 1,
+ ..Default::default()
+ }
+ .write(dir.path(), "quick-then-cancelled");
+
+ // Each family takes about a second, so the deadline lands with the early
+ // ones finished and the late ones never started.
+ let mut p = plan(&["ADD", "MUL", "SUB", "DIV", "SCALE"]);
+ p.family_timeout = Duration::from_secs(60);
+ p.deadline = Duration::from_millis(3000);
+
+ let events = collect(&p, leaf).await;
+
+ let summary = events.iter().find_map(|e| match e {
+ RootEvent::Summary {
+ ok,
+ failed,
+ families_cancelled,
+ ..
+ } => Some((*ok, *failed, *families_cancelled)),
+ _ => None,
+ });
+ let (ok, failed, cancelled) = summary.expect("the device is summarized");
+ assert!(ok > 0, "the families that ran passed");
+ assert_eq!(failed, 0);
+ assert!(cancelled > 0, "and the rest are reported as never run");
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn the_deadline_stops_the_run_and_says_why() {
+ let dir = tempfile::tempdir().unwrap();
+ let leaf = FakeLeaf {
+ stdout: vec![done_line(true)],
+ sleep: 60,
+ ..Default::default()
+ }
+ .write(dir.path(), "overrun");
+
+ let mut p = plan(&["ADD", "MUL"]);
+ p.family_timeout = Duration::from_secs(60);
+ p.deadline = Duration::from_millis(300);
+
+ let events = collect(&p, leaf).await;
+
+ let (ok, cancelled) = done(&events);
+ assert!(!ok);
+ assert!(!cancelled, "a deadline is not the user cancelling");
+ let error = events.iter().find_map(|e| match e {
+ RootEvent::Done { error, .. } => error.clone(),
+ _ => None,
+ });
+ assert!(
+ error.unwrap_or_default().contains("deadline"),
+ "the run has to say why it stopped short"
+ );
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn a_leaf_that_cannot_be_started_is_a_crash_not_a_panic() {
+ let events = collect(&plan(&["ADD"]), PathBuf::from("no-such-jan-llama-worker")).await;
+ assert_eq!(families(&events), vec![("ADD", FamilyStatus::Crashed)]);
+ let exit = events
+ .iter()
+ .find_map(|e| match e {
+ RootEvent::FamilyEnd { exit, .. } => exit.clone(),
+ _ => None,
+ })
+ .unwrap();
+ assert!(exit.contains("could not start"), "{exit}");
+}
+
+// The failure mode this whole phase has to avoid: a shape filter that matches
+// no case makes the leaf exit 0 having tested nothing. Reported as a pass, the
+// user is told their hardware is fine on the strength of zero evidence.
+#[tokio::test(flavor = "multi_thread")]
+async fn a_filter_that_matches_nothing_is_inconclusive_not_a_pass() {
+ let dir = tempfile::tempdir().unwrap();
+ let leaf = FakeLeaf {
+ stdout: vec![done_line(true)],
+ ..Default::default()
+ }
+ .write(dir.path(), "vacuous");
+
+ let mut p = plan(&["MUL_MAT"]);
+ p.families = vec![FamilyFilter::new("MUL_MAT", Some("type_a=nonesuch,"))];
+ let events = collect(&p, leaf).await;
+
+ assert_eq!(families(&events), vec![("MUL_MAT", FamilyStatus::NoCases)]);
+
+ let summary = events
+ .iter()
+ .find_map(|e| match e {
+ RootEvent::Summary {
+ ok,
+ failed,
+ families_no_cases,
+ ..
+ } => Some((*ok, *failed, *families_no_cases)),
+ _ => None,
+ })
+ .expect("a device summary");
+ assert_eq!(summary, (0, 0, 1), "nothing ran, so nothing passed");
+
+ let (ok, cancelled, inconclusive) = events
+ .iter()
+ .find_map(|e| match e {
+ RootEvent::Done {
+ ok,
+ cancelled,
+ inconclusive,
+ ..
+ } => Some((*ok, *cancelled, *inconclusive)),
+ _ => None,
+ })
+ .expect("a run always ends with done");
+ assert!(!cancelled);
+ assert!(
+ inconclusive,
+ "the run must say it did not cover what it was asked to"
+ );
+ assert!(
+ !ok,
+ "a reader that checks only `ok` must not be told a run that tested \
+ nothing was a clean bill of health; `inconclusive` is what separates \
+ this from a real failure"
+ );
+}
+
+// A filter narrow enough to keep one case is a real result, not a vacuous one.
+#[tokio::test(flavor = "multi_thread")]
+async fn a_filter_that_keeps_one_case_still_reports_a_pass() {
+ let dir = tempfile::tempdir().unwrap();
+ let leaf = FakeLeaf {
+ stdout: vec![result_line("MUL_MAT", "ok"), done_line(true)],
+ ..Default::default()
+ }
+ .write(dir.path(), "narrow");
+
+ let mut p = plan(&["MUL_MAT"]);
+ p.families = vec![FamilyFilter::new("MUL_MAT", Some("type_a=q4_K,"))];
+ let events = collect(&p, leaf).await;
+
+ assert_eq!(families(&events), vec![("MUL_MAT", FamilyStatus::Ok)]);
+}
+
+// Only-not-supported is a real answer: the device told us it runs the op
+// elsewhere, which is information, unlike a filter that selected no case.
+#[tokio::test(flavor = "multi_thread")]
+async fn a_family_the_device_does_not_implement_is_not_inconclusive() {
+ let dir = tempfile::tempdir().unwrap();
+ let leaf = FakeLeaf {
+ stdout: vec![result_line("SWIGLU", "not_supported"), done_line(true)],
+ ..Default::default()
+ }
+ .write(dir.path(), "unsupported");
+
+ let events = collect(&plan(&["SWIGLU"]), leaf).await;
+ assert_eq!(families(&events), vec![("SWIGLU", FamilyStatus::Ok)]);
+}
+
+// The filter rides the argv, or the leaf would run the whole family.
+#[tokio::test(flavor = "multi_thread")]
+async fn the_shape_filter_reaches_the_leaf_argv() {
+ let unit = DiagnosePlan {
+ families: vec![FamilyFilter::new("MUL_MAT", Some("type_a=(q4_K|f16),"))],
+ ..plan(&[])
+ }
+ .units()
+ .remove(0);
+ let args = LeafSpec::new(PathBuf::from("worker")).args(&unit, Duration::from_secs(600));
+ let at = args.iter().position(|a| a == "--params").expect("--params");
+ assert_eq!(args[at + 1], "type_a=(q4_K|f16),");
+}
+
+// The leaf arms its own deadline from this, which is the only thing that ends
+// an orphan on a platform where the plugin cannot kill a grandchild.
+#[tokio::test(flavor = "multi_thread")]
+async fn the_leaf_is_told_the_deadline_it_has_to_enforce() {
+ let unit = plan(&["ADD"]).units().remove(0);
+ let args = LeafSpec::new(PathBuf::from("worker")).args(&unit, Duration::from_secs(42));
+ let at = args
+ .iter()
+ .position(|a| a == "--family-timeout")
+ .expect("--family-timeout reaches the leaf");
+ assert_eq!(args[at + 1], "42");
+}
diff --git a/web-app/src/containers/LlamacppDiagnostics.tsx b/web-app/src/containers/LlamacppDiagnostics.tsx
new file mode 100644
index 000000000..130b1570a
--- /dev/null
+++ b/web-app/src/containers/LlamacppDiagnostics.tsx
@@ -0,0 +1,599 @@
+import { useEffect, useMemo, useState } from 'react'
+import {
+ IconChevronDown,
+ IconLoader2,
+ IconStethoscope,
+} from '@tabler/icons-react'
+import { toast } from 'sonner'
+
+import { Button } from '@/components/ui/button'
+import { Progress } from '@/components/ui/progress'
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu'
+import { useTranslation } from '@/i18n/react-i18next-compat'
+import { cn, formatMegaBytes } from '@/lib/utils'
+import {
+ deviceVerdict,
+ tallyOf,
+ groupForOp,
+ isQuantizedCase,
+ type DiagnosticsGroup,
+} from '@/lib/diagnosticsGroups'
+import { formatDiagnosticsReport } from '@/lib/diagnosticsReport'
+import { localHomeDir } from '@/lib/localHome'
+import {
+ diagnosticsSuggestions,
+ type DiagnosticsSuggestion,
+} from '@/lib/diagnosticsSuggestions'
+import {
+ isFinished,
+ useLlamacppDiagnostics,
+ unsupportedOps,
+ type DiagnosticsDeviceRun,
+ type DiagnosticsRun,
+} from '@/hooks/useLlamacppDiagnostics'
+import { groupLabelKeys, VERDICT_STYLES } from './llamacppDiagnosticsStatus'
+import { LlamacppDiagnosticsDialog } from './LlamacppDiagnosticsDialog'
+import { LlamacppDiagnosticsFullConfirm } from './LlamacppDiagnosticsFullConfirm'
+
+/** Group rollup for one device, worst group first. */
+interface GroupResult {
+ group: DiagnosticsGroup
+ failed: number
+ fallback: number
+ /** Cases behind `fallback`, so the row can say 12 of 185 rather than 12. */
+ fallbackTotal: number
+}
+
+function groupResults(
+ run: DiagnosticsRun,
+ device: DiagnosticsDeviceRun,
+ canOffload: boolean
+): { groups: GroupResult[]; quantizedFailures: number } {
+ const name = device.device.name
+ const byGroup = new Map<DiagnosticsGroup, GroupResult>()
+ const entryFor = (op: string) => {
+ const group = groupForOp(op)
+ const entry = byGroup.get(group) ?? {
+ group,
+ failed: 0,
+ fallback: 0,
+ fallbackTotal: 0,
+ }
+ byGroup.set(group, entry)
+ return entry
+ }
+ let quantizedFailures = 0
+ // Failures come from `cases`, which never drops one.
+ for (const c of run.cases) {
+ if (c.device !== name || c.status !== 'fail') continue
+ entryFor(c.op).failed += 1
+ if (isQuantizedCase(c.params)) quantizedFailures += 1
+ }
+ // Fallbacks come from `opSupport`, which is counted off every event --
+ // `cases` caps non-failing ones and would undercount a long run. Skipped
+ // entirely on the CPU, which has nowhere to offload to.
+ if (canOffload) {
+ for (const op of unsupportedOps(device)) {
+ const entry = entryFor(op.op)
+ entry.fallback += op.notSupported
+ entry.fallbackTotal += op.ok + op.notSupported
+ }
+ }
+ const groups = [...byGroup.values()].sort(
+ (a, b) => b.failed - a.failed || b.fallback - a.fallback
+ )
+ return { groups, quantizedFailures }
+}
+
+function DeviceRow({
+ device,
+ run,
+}: {
+ device: DiagnosticsDeviceRun
+ run: DiagnosticsRun
+}) {
+ const { t } = useTranslation()
+ const crashed = device.crashed > 0 || device.hung > 0
+ const tally = tallyOf(device)
+ const verdict = deviceVerdict(tally)
+ const style = VERDICT_STYLES[verdict]
+ const { groups, quantizedFailures } = groupResults(
+ run,
+ device,
+ tally.canOffload
+ )
+
+ const detail = crashed
+ ? t('providers:diagnostics.verdictCrashedDetail')
+ : verdict === 'failed'
+ ? t('providers:diagnostics.verdictFailedDetail', { count: device.failed })
+ : verdict === 'inconclusive'
+ ? device.noCases > 0
+ ? t('providers:diagnostics.verdictInconclusiveDetail', {
+ count: device.noCases,
+ })
+ : t('providers:diagnostics.verdictPartialDetail')
+ : verdict === 'fallback'
+ ? t('providers:diagnostics.verdictFallbackDetail', {
+ count: unsupportedOps(device).length,
+ })
+ : verdict === 'passed'
+ ? // A CPU with unsupported cases still passes, but the technical
+ // table will show those rows, so say up front why they are there.
+ !tally.canOffload && device.notSupported > 0
+ ? t('providers:diagnostics.verdictCpuUnsupportedDetail')
+ : t('providers:diagnostics.verdictPassedDetail')
+ : t('providers:diagnostics.verdictUnknownDetail')
+
+ const headline = crashed
+ ? t('providers:diagnostics.verdictCrashed')
+ : t(
+ `providers:diagnostics.verdict${verdict.charAt(0).toUpperCase()}${verdict.slice(1)}`
+ )
+
+ return (
+ <div
+ className={cn(
+ 'rounded-lg border border-border/60 border-l-2 p-3',
+ style.edge
+ )}
+ >
+ <div className="flex items-start justify-between gap-3">
+ <div className="min-w-0">
+ <h3 className="truncate font-medium text-foreground">
+ {device.device.name === device.device.description
+ ? device.device.name
+ : device.device.description}
+ </h3>
+ <p className={cn('mt-0.5 text-sm', style.text)}>{headline}</p>
+ </div>
+ {/* The backend chip from the hardware page, carrying the verdict in
+ its dot. An icon here read as a close button, and the device id
+ (CUDA0) is what tells two identical cards apart. */}
+ <span className="flex shrink-0 items-center gap-1.5 rounded-md border border-border px-2 py-0.5 font-mono text-xs tracking-wider text-foreground">
+ <span className={cn('size-1.5 rounded-full', style.dot)} />
+ {device.device.name}
+ </span>
+ </div>
+
+ <p className="mt-1.5 text-xs leading-normal text-muted-foreground">
+ {detail}
+ </p>
+
+ {device.complete && (
+ <dl className="mt-2.5 flex flex-wrap gap-x-5 gap-y-1">
+ <Fact
+ label={t('providers:diagnostics.passedLabel')}
+ value={`${device.ok.toLocaleString()} / ${(device.ok + device.failed).toLocaleString()}`}
+ />
+ {device.device.memory_free_mib !== undefined && (
+ <Fact
+ label={t('settings:hardware.vram')}
+ value={formatMegaBytes(device.device.memory_free_mib)}
+ />
+ )}
+ </dl>
+ )}
+
+ {/* Only once this device has a summary: a breakdown printed under
+ "Not checked" contradicts it, and the counts are partial until the
+ support probe for this device has finished. */}
+ {device.complete && groups.length > 0 && (
+ <ul className="mt-2.5 space-y-1.5">
+ {groups.map((g) => {
+ const keys = groupLabelKeys(g.group)
+ const bad = g.failed > 0
+ return (
+ <li key={g.group} className="flex items-baseline gap-2">
+ <span
+ className={cn(
+ 'mt-1.5 size-1.5 shrink-0 rounded-full',
+ bad ? VERDICT_STYLES.failed.dot : VERDICT_STYLES.fallback.dot
+ )}
+ />
+ <div className="min-w-0">
+ <span className="text-sm text-foreground">{t(keys.label)}</span>{' '}
+ <span className="font-mono text-xs tabular-nums text-muted-foreground">
+ {bad
+ ? t('providers:diagnostics.casesFailed', {
+ count: g.failed,
+ })
+ : t('providers:diagnostics.casesFallback', {
+ count: g.fallback,
+ total: g.fallbackTotal,
+ })}
+ </span>
+ <p className="text-xs leading-normal text-muted-foreground">
+ {t(keys.detail)}
+ </p>
+ </div>
+ </li>
+ )
+ })}
+ </ul>
+ )}
+
+ {quantizedFailures > 0 && (
+ // A callout, not a second verdict: loose red text at this width
+ // competed with the headline for the eye.
+ <p className="mt-2.5 rounded-md bg-red-500/10 px-2.5 py-1.5 text-xs leading-normal text-red-600 dark:text-red-400">
+ {t('providers:diagnostics.quantizedDetail')}
+ </p>
+ )}
+ </div>
+ )
+}
+
+function Fact({ label, value }: { label: string; value: string }) {
+ return (
+ <div className="flex items-baseline gap-1.5">
+ <dt className="text-xs text-muted-foreground">{label}</dt>
+ <dd className="font-mono text-xs tabular-nums text-foreground">
+ {value}
+ </dd>
+ </div>
+ )
+}
+
+/**
+ * What to do about the result, each with the observation it came from.
+ *
+ * Plain language throughout: the groups name what a kernel is for, and the
+ * ggml op names stay in the technical details table.
+ */
+function Suggestions({
+ suggestions,
+}: {
+ suggestions: DiagnosticsSuggestion[]
+}) {
+ const { t } = useTranslation()
+ if (suggestions.length === 0) return null
+ return (
+ <div className="mt-3 rounded-lg border border-border/60 p-3">
+ <h3 className="font-medium text-foreground">
+ {t('providers:diagnostics.suggestionsTitle')}
+ </h3>
+ <ol className="mt-2 space-y-2.5">
+ {suggestions.map((s) => {
+ const key = `${s.id}-${s.device}`
+ const label = s.id.charAt(0).toUpperCase() + s.id.slice(1)
+ const groups = s.groups
+ .map((g) => t(groupLabelKeys(g).label))
+ .join(', ')
+ return (
+ <li key={key}>
+ <p className="text-sm text-foreground">
+ {t(`providers:diagnostics.suggestion${label}`, s.values)}
+ </p>
+ <p className="mt-0.5 text-xs leading-normal text-muted-foreground">
+ {t(`providers:diagnostics.suggestion${label}Detail`, s.values)}
+ </p>
+ {groups && (
+ <p className="mt-0.5 text-xs leading-normal text-muted-foreground">
+ {t('providers:diagnostics.suggestionEvidence', { groups })}
+ </p>
+ )}
+ </li>
+ )
+ })}
+ </ol>
+ </div>
+ )
+}
+
+/**
+ * One preset in the run menu.
+ *
+ * The duration sits under the name rather than beside it: the two were a
+ * `justify-between` row, and at the menu's width "15 minutes or more per
+ * device" left the name too little room, so it broke mid-label ("Full /
+ * check") and the rows came out ragged. Stacked, every row is the same
+ * height whatever a translation does to the hint.
+ */
+function PresetItem({
+ label,
+ hint,
+ onSelect,
+}: {
+ label: string
+ hint: string
+ onSelect: () => void
+}) {
+ return (
+ <DropdownMenuItem onSelect={onSelect}>
+ <div className="flex w-full flex-col gap-0.5">
+ <span>{label}</span>
+ <span className="text-xs leading-snug text-muted-foreground">
+ {hint}
+ </span>
+ </div>
+ </DropdownMenuItem>
+ )
+}
+
+/**
+ * The hardware check, on the llama.cpp provider page beside the engine panel.
+ *
+ * Two readers at once. The default view answers "is my machine the problem?"
+ * in a sentence per device and never shows a ggml op name; the dialog behind
+ * `Show all cases` carries every case, its parameters and its error for
+ * someone filing a bug. Nothing is sent anywhere.
+ */
+export function LlamacppDiagnostics({
+ busy = false,
+ deviceHint,
+ modelHint,
+}: {
+ /** The engine is generating or loading. Supplied by the route, which already
+ * knows this page is llama.cpp's. */
+ busy?: boolean
+ /** Device to pre-select, from the hardware page's per-device entry point. */
+ deviceHint?: string
+ /** Model to check, from a failed load's "check why this model failed". Its
+ * presence is what offers the model preset at all: without a model there is
+ * no gguf to read a shape from. */
+ modelHint?: string
+} = {}) {
+ const { t } = useTranslation()
+ const { run, starting, running, start, cancel } = useLlamacppDiagnostics()
+ const [device, setDevice] = useState(deviceHint ?? 'all')
+ const [showCases, setShowCases] = useState(false)
+ const [confirmFull, setConfirmFull] = useState(false)
+ // A generation that began after the run did makes the timings, and a
+ // memory-starved failure, untrustworthy -- but the results so far are still
+ // real, so this reports rather than cancels.
+ const [disturbed, setDisturbed] = useState(false)
+ useEffect(() => {
+ if (busy && running) setDisturbed(true)
+ }, [busy, running])
+
+ // Accumulated, not taken from the last run alone: a run narrowed to one
+ // device reports only that device, which would shrink the list, hide the
+ // selector and pin every later run to it with no way back to 'all'.
+ const [devices, setDevices] = useState<string[]>([])
+ useEffect(() => {
+ const seen = run?.devices.map((d) => d.device.name) ?? []
+ if (seen.length === 0) return
+ setDevices((prev) => {
+ const merged = prev.concat(seen.filter((name) => !prev.includes(name)))
+ return merged.length === prev.length ? prev : merged
+ })
+ }, [run])
+ const finished = run ? isFinished(run.status) : false
+
+ const runPreset = (preset: 'quick' | 'full' | 'model') => {
+ setDisturbed(false)
+ return start(preset, device === 'all' ? [] : [device], modelHint)
+ }
+
+ const suggestions = useMemo(
+ () => (run && finished ? diagnosticsSuggestions(run) : []),
+ [run, finished]
+ )
+
+ const copy = async () => {
+ if (!run) return
+ try {
+ await navigator.clipboard.writeText(
+ formatDiagnosticsReport(run, { home: await localHomeDir() })
+ )
+ toast.success(t('providers:diagnostics.copied'))
+ } catch {
+ toast.error(t('providers:diagnostics.copyFailed'))
+ }
+ }
+
+ return (
+ <div className="rounded-lg border border-main-view-fg/10 bg-main-view-fg/5 p-4">
+ <div className="flex items-center gap-2">
+ <IconStethoscope
+ size={18}
+ className="shrink-0 text-muted-foreground"
+ />
+ <span className="font-medium text-foreground">
+ {t('providers:diagnostics.title')}
+ </span>
+ </div>
+ <p className="mt-1.5 text-xs leading-normal text-muted-foreground">
+ {t('providers:diagnostics.description')}
+ </p>
+
+ {running && run && (
+ <div className="mt-3">
+ <div className="flex items-baseline justify-between gap-4">
+ <span className="truncate text-sm text-foreground">
+ {run.current
+ ? t('providers:diagnostics.checking', {
+ family: run.current.family,
+ device: run.current.device,
+ })
+ : run.model
+ ? t('providers:diagnostics.modelOf', { model: run.model })
+ : t('providers:diagnostics.preparing')}
+ </span>
+ <span className="shrink-0 font-mono text-xs tabular-nums text-muted-foreground">
+ {t('providers:diagnostics.progress', {
+ done: run.finishedUnits,
+ total: run.totalUnits || '?',
+ })}
+ </span>
+ </div>
+ <Progress
+ value={
+ run.totalUnits > 0
+ ? (run.finishedUnits / run.totalUnits) * 100
+ : 0
+ }
+ className="mt-1.5 h-1.5 w-full border"
+ />
+ </div>
+ )}
+
+ {run && run.devices.length > 0 && (
+ <div className="mt-3 space-y-2">
+ {run.devices.map((d) => (
+ <DeviceRow key={d.device.name} device={d} run={run} />
+ ))}
+ </div>
+ )}
+
+ <Suggestions suggestions={suggestions} />
+
+ {run?.status === 'inconclusive' && (
+ <p className="mt-3 rounded-md bg-secondary px-2.5 py-1.5 text-xs leading-normal text-muted-foreground">
+ {t('providers:diagnostics.inconclusiveNotice')}
+ </p>
+ )}
+
+ {run?.status === 'error' && run.error && (
+ <p className="mt-3 text-xs leading-normal text-red-600 dark:text-red-400">
+ {t('providers:diagnostics.stoppedEarly', { reason: run.error })}
+ </p>
+ )}
+ {run?.status === 'cancelled' && (
+ <p className="mt-3 text-xs text-muted-foreground">
+ {t('providers:diagnostics.cancelled')}
+ </p>
+ )}
+
+ {busy && !running && (
+ <p className="mt-3 rounded-md bg-amber-500/10 px-2.5 py-1.5 text-xs leading-normal text-amber-700 dark:text-amber-400">
+ {t('providers:diagnostics.busyBlocked')}
+ </p>
+ )}
+ {disturbed && (
+ <p className="mt-3 rounded-md bg-amber-500/10 px-2.5 py-1.5 text-xs leading-normal text-amber-700 dark:text-amber-400">
+ {t('providers:diagnostics.busyDuringRun')}
+ </p>
+ )}
+
+ <div className="mt-4 flex flex-wrap items-center gap-2 border-t border-border/40 pt-3">
+ {running ? (
+ <Button variant="outline" size="sm" onClick={cancel}>
+ {t('providers:diagnostics.cancel')}
+ </Button>
+ ) : (
+ <div className="flex items-center">
+ <Button
+ size="sm"
+ disabled={starting || busy}
+ onClick={() => runPreset(modelHint ? 'model' : 'quick')}
+ className="rounded-r-none pr-3"
+ >
+ {starting && (
+ <IconLoader2 size={14} className="animate-spin" />
+ )}
+ {finished
+ ? t('providers:diagnostics.runAgain')
+ : modelHint
+ ? t('providers:diagnostics.model')
+ : t('providers:diagnostics.run')}
+ </Button>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ size="sm"
+ disabled={starting || busy}
+ aria-label={t('providers:diagnostics.runOptions')}
+ className="rounded-l-none border-l border-primary-foreground/20 px-2"
+ >
+ <IconChevronDown size={14} />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="w-64">
+ {modelHint && (
+ <PresetItem
+ label={t('providers:diagnostics.model')}
+ hint={t('providers:diagnostics.modelHint')}
+ onSelect={() => runPreset('model')}
+ />
+ )}
+ <PresetItem
+ label={t('providers:diagnostics.quick')}
+ hint={t('providers:diagnostics.quickHint')}
+ onSelect={() => runPreset('quick')}
+ />
+ <PresetItem
+ label={t('providers:diagnostics.full')}
+ hint={t('providers:diagnostics.fullHint')}
+ onSelect={() => setConfirmFull(true)}
+ />
+ {(devices.length > 1 || device !== 'all') && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuLabel className="text-xs font-normal text-muted-foreground">
+ {t('providers:diagnostics.device')}
+ </DropdownMenuLabel>
+ <DropdownMenuRadioGroup
+ value={device}
+ onValueChange={setDevice}
+ >
+ <DropdownMenuRadioItem value="all">
+ {t('providers:diagnostics.allDevices')}
+ </DropdownMenuRadioItem>
+ {devices.map((name) => (
+ <DropdownMenuRadioItem key={name} value={name}>
+ {name}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ )}
+
+ {/* Secondary actions sit opposite the primary one; without the gap
+ the two links read as a single phrase. */}
+ <div className="ml-auto flex items-center gap-4">
+ {run && run.cases.length > 0 && (
+ <Button
+ variant="link"
+ size="sm"
+ className="h-auto px-0 text-muted-foreground hover:text-foreground"
+ onClick={() => setShowCases(true)}
+ >
+ {t('providers:diagnostics.technicalDetails')}
+ </Button>
+ )}
+ {finished && run && (
+ <Button
+ variant="link"
+ size="sm"
+ className="h-auto px-0 text-muted-foreground hover:text-foreground"
+ onClick={copy}
+ >
+ {t('providers:diagnostics.copyResults')}
+ </Button>
+ )}
+ </div>
+ </div>
+
+ {run && (
+ <LlamacppDiagnosticsDialog
+ run={run}
+ open={showCases}
+ onOpenChange={setShowCases}
+ />
+ )}
+ <LlamacppDiagnosticsFullConfirm
+ open={confirmFull}
+ onOpenChange={setConfirmFull}
+ onConfirm={() => {
+ setConfirmFull(false)
+ runPreset('full')
+ }}
+ />
+ </div>
+ )
+}
diff --git a/web-app/src/containers/LlamacppDiagnosticsDialog.tsx b/web-app/src/containers/LlamacppDiagnosticsDialog.tsx
new file mode 100644
index 000000000..3192f4e37
--- /dev/null
+++ b/web-app/src/containers/LlamacppDiagnosticsDialog.tsx
@@ -0,0 +1,243 @@
+import { useMemo, useState } from 'react'
+import { toast } from 'sonner'
+
+import { Button } from '@/components/ui/button'
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog'
+import { Input } from '@/components/ui/input'
+import { useTranslation } from '@/i18n/react-i18next-compat'
+import { cn } from '@/lib/utils'
+import { groupForOp, hasCpuFallback } from '@/lib/diagnosticsGroups'
+import { formatDiagnosticsReport } from '@/lib/diagnosticsReport'
+import { localHomeDir } from '@/lib/localHome'
+import type { DiagnosticsRun } from '@/hooks/useLlamacppDiagnostics'
+import { groupLabelKeys, VERDICT_STYLES } from './llamacppDiagnosticsStatus'
+
+type StatusFilter = 'all' | 'fail' | 'not_supported' | 'ok'
+
+const STATUS_FILTERS: { value: StatusFilter; key: string }[] = [
+ { value: 'fail', key: 'providers:diagnostics.filterFailed' },
+ { value: 'not_supported', key: 'providers:diagnostics.filterFallback' },
+ { value: 'ok', key: 'providers:diagnostics.filterPassed' },
+ { value: 'all', key: 'providers:diagnostics.filterAll' },
+]
+
+const STATUS_LABEL: Record<string, string> = {
+ ok: 'providers:diagnostics.statusOk',
+ fail: 'providers:diagnostics.statusFail',
+ not_supported: 'providers:diagnostics.statusNotSupported',
+ skipped: 'providers:diagnostics.statusSkipped',
+}
+
+const STATUS_STYLE: Record<string, string> = {
+ ok: VERDICT_STYLES.passed.text,
+ fail: VERDICT_STYLES.failed.text,
+ not_supported: VERDICT_STYLES.fallback.text,
+ skipped: 'text-muted-foreground',
+}
+
+/**
+ * Every case of a run, for someone filing a bug.
+ *
+ * The operation column carries both readings: the plain name on top, the
+ * llama.cpp op underneath in mono. A reader who came from the summary
+ * recognises the first; a maintainer needs the second to re-run the case, and
+ * neither has to switch views to get it.
+ */
+export function LlamacppDiagnosticsDialog({
+ run,
+ open,
+ onOpenChange,
+}: {
+ run: DiagnosticsRun
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}) {
+ const { t } = useTranslation()
+ const [status, setStatus] = useState<StatusFilter>('fail')
+ const [device, setDevice] = useState('all')
+ const [query, setQuery] = useState('')
+
+ const cpuDevices = useMemo(
+ () =>
+ new Set(
+ run.devices
+ .filter((d) => !hasCpuFallback(d.device.type))
+ .map((d) => d.device.name)
+ ),
+ [run.devices]
+ )
+
+ const rows = useMemo(() => {
+ const needle = query.trim().toLowerCase()
+ return run.cases.filter((c) => {
+ if (status !== 'all' && c.status !== status) return false
+ if (device !== 'all' && c.device !== device) return false
+ if (!needle) return true
+ return (
+ c.op.toLowerCase().includes(needle) ||
+ c.params.toLowerCase().includes(needle)
+ )
+ })
+ }, [run.cases, status, device, query])
+
+ const copyAll = async () => {
+ try {
+ await navigator.clipboard.writeText(
+ formatDiagnosticsReport(
+ run,
+ { home: await localHomeDir() },
+ { allCases: true }
+ )
+ )
+ toast.success(t('providers:diagnostics.copied'))
+ } catch {
+ toast.error(t('providers:diagnostics.copyFailed'))
+ }
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="flex max-h-[85vh] flex-col gap-0 overflow-hidden p-0 lg:max-w-3xl xl:max-w-4xl">
+ <DialogHeader className="px-5 py-4">
+ <DialogTitle>{t('providers:diagnostics.allCasesTitle')}</DialogTitle>
+ </DialogHeader>
+
+ <div className="flex flex-wrap items-center gap-2 border-y border-border/60 px-5 py-3">
+ <div className="flex items-center gap-1">
+ {STATUS_FILTERS.map((f) => (
+ <button
+ key={f.value}
+ type="button"
+ onClick={() => setStatus(f.value)}
+ className={cn(
+ 'cursor-pointer rounded-md border px-2 py-0.5 text-xs transition-colors',
+ status === f.value
+ ? 'border-primary/60 text-foreground'
+ : 'border-border text-muted-foreground hover:border-foreground/40 hover:text-foreground'
+ )}
+ >
+ {t(f.key)}
+ </button>
+ ))}
+ </div>
+ {run.devices.length > 1 && (
+ <div className="flex items-center gap-1">
+ {['all', ...run.devices.map((d) => d.device.name)].map((name) => (
+ <button
+ key={name}
+ type="button"
+ onClick={() => setDevice(name)}
+ className={cn(
+ 'cursor-pointer rounded-md border px-2 py-0.5 font-mono text-xs transition-colors',
+ device === name
+ ? 'border-primary/60 text-foreground'
+ : 'border-border text-muted-foreground hover:border-foreground/40 hover:text-foreground'
+ )}
+ >
+ {name === 'all'
+ ? t('providers:diagnostics.filterAll')
+ : name}
+ </button>
+ ))}
+ </div>
+ )}
+ <Input
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder={t('providers:diagnostics.searchCases')}
+ className="h-7 w-full min-w-40 flex-1 text-xs sm:w-auto"
+ />
+ </div>
+
+ <div className="min-h-0 flex-1 overflow-y-auto">
+ {rows.length === 0 ? (
+ <p className="px-5 py-8 text-center text-sm text-muted-foreground">
+ {t('providers:diagnostics.noCases')}
+ </p>
+ ) : (
+ <table className="w-full border-collapse text-left">
+ <thead className="sticky top-0 bg-background">
+ <tr className="border-b border-border/60">
+ <th className="px-5 py-2 text-xs font-normal text-muted-foreground">
+ {t('providers:diagnostics.columnOp')}
+ </th>
+ <th className="px-3 py-2 text-xs font-normal text-muted-foreground">
+ {t('providers:diagnostics.columnParams')}
+ </th>
+ <th className="px-5 py-2 text-right text-xs font-normal text-muted-foreground">
+ {t('providers:diagnostics.columnStatus')}
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {rows.map((c, i) => (
+ <tr
+ key={`${c.device}-${c.op}-${c.params}-${i}`}
+ className="border-b border-border/40 last:border-none"
+ >
+ <td className="px-5 py-2.5 align-top">
+ <div className="text-sm text-foreground">
+ {t(groupLabelKeys(groupForOp(c.op)).label)}
+ </div>
+ <div
+ className="font-mono text-xs text-muted-foreground"
+ title={t('providers:diagnostics.opColumnHint')}
+ >
+ {c.op}
+ </div>
+ </td>
+ <td className="px-3 py-2.5 align-top">
+ <div className="font-mono text-xs break-all text-muted-foreground">
+ {c.params}
+ </div>
+ {(c.error || c.detail) && (
+ <div className="mt-1 font-mono text-xs break-all text-red-600 dark:text-red-400">
+ {c.error ?? c.detail}
+ </div>
+ )}
+ </td>
+ <td
+ className={cn(
+ 'px-5 py-2.5 text-right align-top text-xs whitespace-nowrap',
+ STATUS_STYLE[c.status]
+ )}
+ >
+ {/* "Runs on CPU" is circular on a CPU row: there is
+ nowhere below it to run. */}
+ {c.status === 'not_supported' && cpuDevices.has(c.device)
+ ? t('providers:diagnostics.statusNotImplemented')
+ : t(STATUS_LABEL[c.status] ?? c.status)}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ )}
+ </div>
+
+ <div className="flex flex-wrap items-center justify-between gap-2 border-t border-border/60 px-5 py-3">
+ <span className="font-mono text-xs tabular-nums text-muted-foreground">
+ {rows.length}
+ </span>
+ <div className="flex items-center gap-2">
+ {run.casesTruncated && (
+ <span className="text-xs text-muted-foreground">
+ {t('providers:diagnostics.casesTruncated', {
+ count: run.cases.length,
+ })}
+ </span>
+ )}
+ <Button variant="outline" size="sm" onClick={copyAll}>
+ {t('providers:diagnostics.copyResults')}
+ </Button>
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/web-app/src/containers/LlamacppDiagnosticsFullConfirm.tsx b/web-app/src/containers/LlamacppDiagnosticsFullConfirm.tsx
new file mode 100644
index 000000000..2bf6f0a6a
--- /dev/null
+++ b/web-app/src/containers/LlamacppDiagnosticsFullConfirm.tsx
@@ -0,0 +1,140 @@
+import { useEffect, useRef, useState } from 'react'
+import { IconAlertTriangle } from '@tabler/icons-react'
+import {
+ getLoadedModels,
+ unloadLlamaModel,
+} from '@janhq/tauri-plugin-llamacpp-api'
+
+import { Button } from '@/components/ui/button'
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog'
+import { Switch } from '@/components/ui/switch'
+import { useTranslation } from '@/i18n/react-i18next-compat'
+import { isPlatformTauri } from '@/lib/platform/utils'
+
+/**
+ * The gate in front of the full check.
+ *
+ * It exists for two costs the user cannot see from the menu: the run is 15
+ * minutes or more per device at full load, and on Windows a long GPU kernel
+ * can trip the display driver's watchdog, which resets the driver for every
+ * process -- including whatever model they have loaded. Process isolation does
+ * not prevent that, so the only honest mitigation is saying so first.
+ */
+export function LlamacppDiagnosticsFullConfirm({
+ open,
+ onOpenChange,
+ onConfirm,
+}: {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ onConfirm: () => void
+}) {
+ const { t } = useTranslation()
+ const [loaded, setLoaded] = useState<string[]>([])
+ const [unloadFirst, setUnloadFirst] = useState(true)
+ const [working, setWorking] = useState(false)
+
+ useEffect(() => {
+ if (!open || !isPlatformTauri()) return
+ let cancelled = false
+ getLoadedModels()
+ .then((models) => {
+ if (!cancelled) setLoaded(models ?? [])
+ })
+ .catch(() => {
+ // A model list we cannot read is not a reason to block the run; the
+ // duration and driver warnings stand on their own.
+ if (!cancelled) setLoaded([])
+ })
+ return () => {
+ cancelled = true
+ }
+ }, [open])
+
+ // Read inside `confirm`, which is awaiting when the close happens and would
+ // otherwise close over the `open` of the render it started in.
+ const openRef = useRef(open)
+ useEffect(() => {
+ openRef.current = open
+ }, [open])
+
+ const confirm = async () => {
+ if (unloadFirst && loaded.length > 0) {
+ setWorking(true)
+ // Best effort and sequential: a model that will not unload should not
+ // stop the check the user asked for.
+ for (const model of loaded) {
+ try {
+ await unloadLlamaModel(model)
+ } catch (e) {
+ console.warn('could not unload before the hardware check:', e)
+ }
+ }
+ setWorking(false)
+ // The dialog stays interactive while the unloads run, and closing it is
+ // the user withdrawing the request -- starting a multi-minute check
+ // anyway is the one thing Cancel must not do.
+ if (!openRef.current) return
+ }
+ onConfirm()
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2">
+ <IconAlertTriangle
+ size={18}
+ className="shrink-0 text-amber-500"
+ />
+ {t('providers:diagnostics.fullConfirmTitle')}
+ </DialogTitle>
+ <DialogDescription>
+ {t('providers:diagnostics.fullConfirmBody')}
+ </DialogDescription>
+ </DialogHeader>
+
+ <p className="text-sm leading-normal text-muted-foreground">
+ {t('providers:diagnostics.fullConfirmDriver')}
+ </p>
+
+ {loaded.length > 0 && (
+ <div className="flex items-center justify-between gap-4 rounded-lg border border-border/60 p-3">
+ <div className="min-w-0">
+ <p className="text-sm text-foreground">
+ {t('providers:diagnostics.fullConfirmLoaded', {
+ count: loaded.length,
+ })}
+ </p>
+ <p className="mt-0.5 text-xs text-muted-foreground">
+ {t('providers:diagnostics.unloadFirst')}
+ </p>
+ </div>
+ <Switch checked={unloadFirst} onCheckedChange={setUnloadFirst} />
+ </div>
+ )}
+
+ <DialogFooter>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => onOpenChange(false)}
+ >
+ {t('common:cancel')}
+ </Button>
+ <Button size="sm" disabled={working} onClick={confirm}>
+ {t('providers:diagnostics.fullConfirmRun')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/web-app/src/containers/MessageItem.tsx b/web-app/src/containers/MessageItem.tsx
index 4c3c19d49..7ffece93a 100644
--- a/web-app/src/containers/MessageItem.tsx
+++ b/web-app/src/containers/MessageItem.tsx
@@ -20,9 +20,12 @@ import {
} from './message/types'
import { CopyButton } from './CopyButton'
import { RememberButton } from './RememberButton'
+import { toast } from 'sonner'
import { useTranslation } from '@/i18n/react-i18next-compat'
import { formatDate, formatMessageTime } from '@/utils/formatDate'
import { useTouchDevice } from '@/hooks/useMediaQuery'
+import { Link } from '@tanstack/react-router'
+import { route } from '@/constants/routes'
import { useModelProvider } from '@/hooks/useModelProvider'
import { useInterfaceSettings } from '@/hooks/useInterfaceSettings'
import { useMessageErrors } from '@/stores/message-errors'
@@ -31,6 +34,7 @@ import {
IconPlayerPlay,
IconPaperclip,
IconAlertTriangle,
+ IconCopy,
IconChevronLeft,
IconChevronRight,
IconBellRinging,
@@ -133,6 +137,15 @@ export const MessageItem = memo(
// network (see lib/extensions/authorship).
const extensionAuthored = extensionAuthorOf(metadata) !== undefined
const messageError = useMessageErrors((s) => s.errors[message.id])
+ const loadReport = useMessageErrors((s) => s.reports[message.id])
+ // Recorded only when the failed turn ran on llama.cpp; the current
+ // selection would name a model that had nothing to do with the failure.
+ const diagnoseModel = loadReport?.model
+ const canRegenerate =
+ !!selectedModel &&
+ !!onRegenerate &&
+ status !== CHAT_STATUS.STREAMING &&
+ status !== CHAT_STATUS.SUBMITTED
const createdAt = (metadata?.createdAt as Date) ?? new Date()
// Machine-readable stamp for <time>; toISOString throws on an invalid date,
// which a malformed stored value must not turn into a crashed message.
@@ -705,21 +718,58 @@ export const MessageItem = memo(
<div className="text-muted-foreground break-words">
{messageError}
</div>
- </div>
- {selectedModel &&
- onRegenerate &&
- status !== CHAT_STATUS.STREAMING &&
- status !== CHAT_STATUS.SUBMITTED && (
- <Button
- variant="outline"
- size="sm"
- onClick={handleRegenerate}
- className="shrink-0"
- >
- <IconRefresh size={14} />
- <span>Regenerate</span>
- </Button>
+ {/* Below the text rather than beside it: three actions in one
+ row squeezed the error into a narrow column. */}
+ {(loadReport || canRegenerate) && (
+ <div className="mt-2 flex flex-wrap items-center gap-2">
+ {loadReport && (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => {
+ navigator.clipboard
+ .writeText(loadReport.text)
+ .then(() =>
+ toast.success(t('model-errors:diagnosticsCopied'))
+ )
+ .catch(() =>
+ toast.error(t('common:toast.errorCopyFailed.title'))
+ )
+ }}
+ >
+ <IconCopy size={14} />
+ <span>{t('model-errors:copyDiagnostics')}</span>
+ </Button>
+ )}
+ {canRegenerate && (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={handleRegenerate}
+ >
+ <IconRefresh size={14} />
+ <span>Regenerate</span>
+ </Button>
+ )}
+ {/* A load report is only built for a llama.cpp engine
+ failure, so its presence is what says the hardware check
+ has something to say about this message. The check itself
+ lives on the provider page; this carries the model over
+ rather than being a second place a minutes-long run can
+ start from. */}
+ {loadReport && diagnoseModel && (
+ <Link
+ to={route.settings.providers}
+ params={{ providerName: 'llamacpp' }}
+ search={{ diagnoseModel }}
+ className="whitespace-nowrap text-sm text-muted-foreground underline-offset-4 hover:text-foreground hover:underline"
+ >
+ {t('providers:diagnostics.checkThisModel')}
+ </Link>
+ )}
+ </div>
)}
+ </div>
</div>
)}
diff --git a/web-app/src/containers/__tests__/LlamacppDiagnostics.test.tsx b/web-app/src/containers/__tests__/LlamacppDiagnostics.test.tsx
new file mode 100644
index 000000000..0109a417f
--- /dev/null
+++ b/web-app/src/containers/__tests__/LlamacppDiagnostics.test.tsx
@@ -0,0 +1,589 @@
+import { StrictMode } from 'react'
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { act, render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+
+vi.mock('@/i18n/react-i18next-compat', () => ({
+ useTranslation: () => ({
+ t: (k: string, vars?: Record<string, unknown>) =>
+ vars ? `${k}:${JSON.stringify(vars)}` : k,
+ }),
+}))
+
+const { startDiagnostics, cancelDiagnostics, onDiagnosticsEvent, emit } =
+ vi.hoisted(() => {
+ const handlers: ((e: unknown) => void)[] = []
+ return {
+ startDiagnostics: vi.fn(),
+ cancelDiagnostics: vi.fn(),
+ getLoadedModels: vi.fn(),
+ // Returns a real unlisten, as the plugin does: a no-op one leaves two
+ // live listeners under StrictMode and every event applies twice.
+ onDiagnosticsEvent: vi.fn(async (h: (e: unknown) => void) => {
+ handlers.push(h)
+ return () => {
+ const i = handlers.indexOf(h)
+ if (i >= 0) handlers.splice(i, 1)
+ }
+ }),
+ emit: (event: unknown) => handlers.forEach((h) => h(event)),
+ }
+ })
+
+vi.mock('@janhq/tauri-plugin-llamacpp-api', () => ({
+ startDiagnostics,
+ cancelDiagnostics,
+ onDiagnosticsEvent,
+ getLoadedModels: vi.fn().mockResolvedValue([]),
+ unloadLlamaModel: vi.fn(),
+}))
+
+import { LlamacppDiagnostics } from '../LlamacppDiagnostics'
+
+/**
+ * Pushes events and lets the hook's batching interval land inside `act`. The
+ * hook deliberately flushes on a timer rather than per event, so a test that
+ * asserts straight after emitting would race it.
+ */
+async function push(...events: unknown[]) {
+ await act(async () => {
+ events.forEach(emit)
+ await new Promise((r) => setTimeout(r, 250))
+ })
+}
+
+const JOB = 'job-1'
+
+const START = {
+ job: JOB,
+ event: 'start',
+ schema: 1,
+ preset: 'quick',
+ engine: { version: '0.9.0', tag: 'b12110', commit: 'cd959bae99ff' },
+ families: ['MUL_MAT'],
+ support_probe: true,
+ backend_modules: ['CUDA (libggml-cuda.so)'],
+ units: 2,
+ family_timeout_secs: 600,
+ deadline_secs: 5400,
+}
+
+const DEVICE = {
+ job: JOB,
+ event: 'device',
+ name: 'CUDA0',
+ description: 'NVIDIA RTX 3090',
+ type: 'gpu',
+ reg: 'CUDA',
+ memory_total_mib: 24576,
+ memory_free_mib: 20480,
+}
+
+describe('LlamacppDiagnostics', () => {
+ beforeEach(() => {
+ startDiagnostics.mockReset()
+ cancelDiagnostics.mockReset()
+ cancelDiagnostics.mockResolvedValue(undefined)
+ startDiagnostics.mockResolvedValue({ id: JOB })
+ vi.useRealTimers()
+ })
+
+ it('offers the check before anything has run, and nothing else', () => {
+ render(<LlamacppDiagnostics />)
+
+ expect(screen.getByText('providers:diagnostics.title')).toBeInTheDocument()
+ expect(
+ screen.getByRole('button', { name: /diagnostics\.run$/ })
+ ).toBeInTheDocument()
+ // No results surface until there are results.
+ expect(
+ screen.queryByText('providers:diagnostics.technicalDetails')
+ ).not.toBeInTheDocument()
+ expect(
+ screen.queryByText('providers:diagnostics.copyResults')
+ ).not.toBeInTheDocument()
+ })
+
+ it('reports a clean device in plain words, with no ggml op name in sight', async () => {
+ const user = userEvent.setup()
+ render(<LlamacppDiagnostics />)
+ await user.click(screen.getByRole('button', { name: /diagnostics\.run$/ }))
+
+ await waitFor(() =>
+ expect(startDiagnostics).toHaveBeenCalledWith('quick', [], {}, undefined)
+ )
+
+ await push(START)
+ await push(DEVICE)
+ await push({
+ job: JOB,
+ event: 'summary',
+ device: 'CUDA0',
+ ok: 3000,
+ failed: 0,
+ not_supported: 0,
+ families_crashed: 0,
+ families_hung: 0,
+ })
+ await push({ job: JOB, event: 'done', ok: true, cancelled: false })
+
+ expect(await screen.findByText('NVIDIA RTX 3090')).toBeInTheDocument()
+ expect(
+ screen.getByText('providers:diagnostics.verdictPassed')
+ ).toBeInTheDocument()
+ expect(screen.queryByText(/MUL_MAT/)).not.toBeInTheDocument()
+ })
+
+ it('names the broken part in plain words when a kernel is wrong', async () => {
+ const user = userEvent.setup()
+ render(<LlamacppDiagnostics />)
+ await user.click(screen.getByRole('button', { name: /diagnostics\.run$/ }))
+ await waitFor(() => expect(startDiagnostics).toHaveBeenCalled())
+
+ await push(START)
+ await push(DEVICE)
+ await push({
+ job: JOB,
+ event: 'case',
+ device: 'CUDA0',
+ family: 'MUL_MAT',
+ backend: 'CUDA0',
+ op: 'MUL_MAT',
+ params: 'type_a=q4_K,m=4096',
+ mode: 'test',
+ status: 'fail',
+ error: 'NMSE 0.51 > 5e-4',
+ })
+ await push({
+ job: JOB,
+ event: 'summary',
+ device: 'CUDA0',
+ ok: 10,
+ failed: 1,
+ not_supported: 0,
+ families_crashed: 0,
+ families_hung: 0,
+ })
+ await push({ job: JOB, event: 'done', ok: false, cancelled: false })
+
+ // The group name, not the op: "Matrix multiplication", never MUL_MAT.
+ expect(
+ await screen.findByText('providers:diagnostics.groupMatrixMath')
+ ).toBeInTheDocument()
+ expect(
+ screen.getByText('providers:diagnostics.verdictFailed')
+ ).toBeInTheDocument()
+ expect(screen.queryByText(/MUL_MAT/)).not.toBeInTheDocument()
+ // A quantized failure is called out: every downloaded model is quantized.
+ expect(
+ screen.getByText('providers:diagnostics.quantizedDetail')
+ ).toBeInTheDocument()
+ })
+
+ it('treats an op that falls back to the CPU as working, not broken', async () => {
+ const user = userEvent.setup()
+ render(<LlamacppDiagnostics />)
+ await user.click(screen.getByRole('button', { name: /diagnostics\.run$/ }))
+ await waitFor(() => expect(startDiagnostics).toHaveBeenCalled())
+
+ await push(START)
+ await push(DEVICE)
+ await push({
+ job: JOB,
+ event: 'case',
+ device: 'CUDA0',
+ family: 'SILU',
+ backend: 'CUDA0',
+ op: 'SILU',
+ params: 'type=f16',
+ mode: 'test',
+ status: 'not_supported',
+ })
+ await push({
+ job: JOB,
+ event: 'summary',
+ device: 'CUDA0',
+ ok: 100,
+ failed: 0,
+ not_supported: 1,
+ families_crashed: 0,
+ families_hung: 0,
+ })
+ await push({ job: JOB, event: 'done', ok: true, cancelled: false })
+
+ expect(
+ await screen.findByText('providers:diagnostics.verdictFallback')
+ ).toBeInTheDocument()
+ expect(
+ screen.queryByText('providers:diagnostics.verdictFailed')
+ ).not.toBeInTheDocument()
+ })
+
+ it('says a device crashed rather than blaming a kernel', async () => {
+ const user = userEvent.setup()
+ render(<LlamacppDiagnostics />)
+ await user.click(screen.getByRole('button', { name: /diagnostics\.run$/ }))
+ await waitFor(() => expect(startDiagnostics).toHaveBeenCalled())
+
+ await push(START)
+ await push(DEVICE)
+ await push({
+ job: JOB,
+ event: 'summary',
+ device: 'CUDA0',
+ ok: 0,
+ failed: 0,
+ not_supported: 0,
+ families_crashed: 1,
+ families_hung: 0,
+ })
+ await push({ job: JOB, event: 'done', ok: false, cancelled: false })
+
+ expect(
+ await screen.findByText('providers:diagnostics.verdictCrashed')
+ ).toBeInTheDocument()
+ })
+
+ it('swaps Run for Stop while a check is in flight', async () => {
+ const user = userEvent.setup()
+ render(<LlamacppDiagnostics />)
+ await user.click(screen.getByRole('button', { name: /diagnostics\.run$/ }))
+ await waitFor(() => expect(startDiagnostics).toHaveBeenCalled())
+ await push(START)
+
+ const stop = await screen.findByRole('button', {
+ name: 'providers:diagnostics.cancel',
+ })
+ await user.click(stop)
+ expect(cancelDiagnostics).toHaveBeenCalledWith(JOB)
+ })
+
+ // The backend spawns the root, and starts pumping its events, before the
+ // reply to `start_diagnostics` crosses back into the webview, so the first
+ // events of a run arrive while its id is still unknown here.
+ it('keeps the events that arrive before the run reports its id', async () => {
+ const user = userEvent.setup()
+ let settle: (v: { id: string }) => void = () => {}
+ startDiagnostics.mockReturnValue(
+ new Promise<{ id: string }>((r) => {
+ settle = r
+ })
+ )
+ render(<LlamacppDiagnostics />)
+ await user.click(screen.getByRole('button', { name: /diagnostics\.run$/ }))
+ await waitFor(() => expect(startDiagnostics).toHaveBeenCalled())
+
+ // Emitted while the start call is still in flight.
+ await push(START, DEVICE)
+ await act(async () => {
+ settle({ id: JOB })
+ await new Promise((r) => setTimeout(r, 250))
+ })
+
+ expect(await screen.findByText('NVIDIA RTX 3090')).toBeInTheDocument()
+ })
+
+ it('stops a run the user walked away from', async () => {
+ const user = userEvent.setup()
+ const { unmount } = render(<LlamacppDiagnostics />)
+ await user.click(screen.getByRole('button', { name: /diagnostics\.run$/ }))
+ await waitFor(() => expect(startDiagnostics).toHaveBeenCalled())
+ await push(START)
+
+ // Nobody is left to read it, and it holds the single backend slot.
+ unmount()
+ expect(cancelDiagnostics).toHaveBeenCalledWith(JOB)
+ })
+
+ it('stops a run whose id arrives after the panel is gone', async () => {
+ // The start call is still in flight at unmount, so the cleanup has no id
+ // to cancel; the run exists all the same and holds the single slot.
+ const user = userEvent.setup()
+ let settle: (v: { id: string }) => void = () => {}
+ startDiagnostics.mockReturnValue(
+ new Promise<{ id: string }>((r) => {
+ settle = r
+ })
+ )
+ const { unmount } = render(<LlamacppDiagnostics />)
+ await user.click(screen.getByRole('button', { name: /diagnostics\.run$/ }))
+ await waitFor(() => expect(startDiagnostics).toHaveBeenCalled())
+
+ unmount()
+ await act(async () => {
+ settle({ id: JOB })
+ await new Promise((r) => setTimeout(r, 50))
+ })
+
+ expect(cancelDiagnostics).toHaveBeenCalledWith(JOB)
+ })
+
+ // StrictMode re-runs the effect on the *same* instance: mount, clean up,
+ // mount again, with the refs surviving. A flag the cleanup sets and nothing
+ // clears would therefore abandon every run for the life of the component --
+ // which is every run in a development build.
+ it('still runs under StrictMode, which mounts the effect twice', async () => {
+ const user = userEvent.setup()
+ render(
+ <StrictMode>
+ <LlamacppDiagnostics />
+ </StrictMode>
+ )
+
+ await user.click(screen.getByRole('button', { name: /diagnostics\.run$/ }))
+ await waitFor(() => expect(startDiagnostics).toHaveBeenCalled())
+ await push(START, DEVICE)
+
+ expect(cancelDiagnostics).not.toHaveBeenCalled()
+ expect(await screen.findByText('NVIDIA RTX 3090')).toBeInTheDocument()
+ })
+
+ it('does not cancel a run that already finished', async () => {
+ const user = userEvent.setup()
+ const { unmount } = render(<LlamacppDiagnostics />)
+ await user.click(screen.getByRole('button', { name: /diagnostics\.run$/ }))
+ await waitFor(() => expect(startDiagnostics).toHaveBeenCalled())
+ await push(START)
+ await push({ job: JOB, event: 'done', ok: true, cancelled: false })
+
+ unmount()
+ expect(cancelDiagnostics).not.toHaveBeenCalled()
+ })
+
+ it('ignores events from a run that has been superseded', async () => {
+ const user = userEvent.setup()
+ render(<LlamacppDiagnostics />)
+ await user.click(screen.getByRole('button', { name: /diagnostics\.run$/ }))
+ await waitFor(() => expect(startDiagnostics).toHaveBeenCalled())
+
+ await push(START)
+ await push({ ...DEVICE, job: 'an-older-job', name: 'STALE' })
+ await push({ job: JOB, event: 'done', ok: true, cancelled: false })
+
+ await waitFor(() =>
+ expect(
+ screen.queryByText('providers:diagnostics.preparing')
+ ).not.toBeInTheDocument()
+ )
+ expect(screen.queryByText('STALE')).not.toBeInTheDocument()
+ })
+
+ // A run narrowed to one device reports only that device. Sourcing the
+ // selector from the last run alone would then hide it and leave `device`
+ // pinned, with no way back to every device.
+ it('keeps a way back to all devices after a single-device run', async () => {
+ const user = userEvent.setup()
+ render(<LlamacppDiagnostics deviceHint="CUDA0" />)
+ await user.click(screen.getByRole('button', { name: /diagnostics\.run$/ }))
+ await waitFor(() =>
+ expect(startDiagnostics).toHaveBeenCalledWith(
+ 'quick',
+ ['CUDA0'],
+ {},
+ undefined
+ )
+ )
+ await push(START, DEVICE, {
+ job: JOB,
+ event: 'done',
+ ok: true,
+ cancelled: false,
+ })
+
+ await user.click(
+ screen.getByRole('button', { name: 'providers:diagnostics.runOptions' })
+ )
+ await user.click(
+ await screen.findByText('providers:diagnostics.allDevices')
+ )
+ // The button reads "run again" once a run has finished.
+ await user.click(
+ screen.getByRole('button', { name: 'providers:diagnostics.runAgain' })
+ )
+
+ await waitFor(() =>
+ expect(startDiagnostics).toHaveBeenLastCalledWith(
+ 'quick',
+ [],
+ {},
+ undefined
+ )
+ )
+ })
+
+ it('refuses to start while the engine is loading or replying', async () => {
+ render(<LlamacppDiagnostics busy />)
+
+ // Both halves of the split button, or the caret is a way around the gate.
+ expect(screen.getByRole('button', { name: /diagnostics\.run$/ })).toBeDisabled()
+ expect(
+ screen.getByRole('button', { name: 'providers:diagnostics.runOptions' })
+ ).toBeDisabled()
+ expect(
+ screen.getByText('providers:diagnostics.busyBlocked')
+ ).toBeInTheDocument()
+ expect(startDiagnostics).not.toHaveBeenCalled()
+ })
+
+ it('flags a generation that begins mid-run without throwing the results away', async () => {
+ const user = userEvent.setup()
+ const { rerender } = render(<LlamacppDiagnostics />)
+ await user.click(screen.getByRole('button', { name: /diagnostics\.run$/ }))
+ await waitFor(() => expect(startDiagnostics).toHaveBeenCalled())
+ await push(START)
+
+ rerender(<LlamacppDiagnostics busy />)
+
+ expect(
+ await screen.findByText('providers:diagnostics.busyDuringRun')
+ ).toBeInTheDocument()
+ // Busy mid-run is a warning, not a cancel.
+ expect(
+ screen.getByRole('button', { name: 'providers:diagnostics.cancel' })
+ ).toBeInTheDocument()
+ })
+
+ it('preselects the device the hardware page sent it', async () => {
+ const user = userEvent.setup()
+ render(<LlamacppDiagnostics deviceHint="Vulkan0" />)
+ await user.click(screen.getByRole('button', { name: /diagnostics\.run$/ }))
+
+ await waitFor(() =>
+ expect(startDiagnostics).toHaveBeenCalledWith(
+ 'quick',
+ ['Vulkan0'],
+ {},
+ undefined
+ )
+ )
+ })
+
+ it('runs the model check, not the quick one, when a model was named', async () => {
+ const user = userEvent.setup()
+ render(<LlamacppDiagnostics modelHint="qwen3:8b" />)
+ await user.click(
+ screen.getByRole('button', { name: /diagnostics\.model$/ })
+ )
+
+ await waitFor(() =>
+ expect(startDiagnostics).toHaveBeenCalledWith(
+ 'model',
+ [],
+ {},
+ 'qwen3:8b'
+ )
+ )
+ })
+
+ // The failure this phase has to avoid: a shape filter that matched nothing
+ // leaves every other family passing, and a user told "working correctly"
+ // acts on a result that was never measured.
+ it('never calls a narrowed run that tested nothing a pass', async () => {
+ const user = userEvent.setup()
+ render(<LlamacppDiagnostics modelHint="qwen3:8b" />)
+ await user.click(
+ screen.getByRole('button', { name: /diagnostics\.model$/ })
+ )
+
+ await push(START)
+ await push(DEVICE)
+ await push({
+ job: JOB,
+ event: 'summary',
+ device: 'CUDA0',
+ ok: 500,
+ failed: 0,
+ not_supported: 0,
+ families_crashed: 0,
+ families_hung: 0,
+ families_no_cases: 2,
+ })
+ // The wire shape the root actually emits: ok is false precisely so a
+ // reader of that field alone cannot mistake this for a pass.
+ await push({
+ job: JOB,
+ event: 'done',
+ ok: false,
+ cancelled: false,
+ inconclusive: true,
+ })
+
+ expect(
+ screen.queryByText('providers:diagnostics.verdictPassed')
+ ).not.toBeInTheDocument()
+ expect(
+ screen.getByText('providers:diagnostics.verdictInconclusive')
+ ).toBeInTheDocument()
+ expect(
+ screen.getByText('providers:diagnostics.inconclusiveNotice')
+ ).toBeInTheDocument()
+ // And it says what to do about it, with the count it was drawn from.
+ expect(
+ screen.getByText(
+ 'providers:diagnostics.suggestionRerunWholeCheck:{"device":"CUDA0","count":2}'
+ )
+ ).toBeInTheDocument()
+ })
+
+ it('surfaces a check that could not start at all', async () => {
+ const user = userEvent.setup()
+ startDiagnostics.mockRejectedValue(
+ new Error('a hardware check is already running')
+ )
+ render(<LlamacppDiagnostics />)
+ await user.click(screen.getByRole('button', { name: /diagnostics\.run$/ }))
+
+ expect(
+ await screen.findByText(/already running/)
+ ).toBeInTheDocument()
+ })
+
+ // The screenshot bug: a device with no summary yet showed "Not checked"
+ // above a full group breakdown with four-figure counts.
+ it('shows no group breakdown until the device has a verdict', async () => {
+ const user = userEvent.setup()
+ render(<LlamacppDiagnostics />)
+ await user.click(screen.getByRole('button', { name: /diagnostics\.run$/ }))
+ await waitFor(() => expect(startDiagnostics).toHaveBeenCalled())
+
+ await push(START, DEVICE, {
+ job: JOB,
+ event: 'case',
+ device: 'CUDA0',
+ family: '*',
+ backend: 'CUDA0',
+ op: 'MUL_MAT',
+ params: 'type_a=q4_0',
+ mode: 'support',
+ status: 'not_supported',
+ })
+
+ // Mid-run: the verdict is "not checked", so nothing may contradict it.
+ expect(
+ screen.getByText('providers:diagnostics.verdictUnknown')
+ ).toBeInTheDocument()
+ expect(
+ screen.queryByText('providers:diagnostics.groupMatrixMath')
+ ).not.toBeInTheDocument()
+
+ await push({
+ job: JOB,
+ event: 'summary',
+ device: 'CUDA0',
+ ok: 10,
+ failed: 0,
+ not_supported: 1,
+ families_crashed: 0,
+ families_hung: 0,
+ families_no_cases: 0,
+ })
+
+ // Once the summary lands the breakdown appears, with a denominator.
+ expect(
+ await screen.findByText('providers:diagnostics.groupMatrixMath')
+ ).toBeInTheDocument()
+ expect(
+ screen.getByText('providers:diagnostics.casesFallback:{"count":1,"total":1}')
+ ).toBeInTheDocument()
+ })
+})
diff --git a/web-app/src/containers/__tests__/MessageItem.test.tsx b/web-app/src/containers/__tests__/MessageItem.test.tsx
index d4a865bd8..c25fd6f78 100644
--- a/web-app/src/containers/__tests__/MessageItem.test.tsx
+++ b/web-app/src/containers/__tests__/MessageItem.test.tsx
@@ -12,9 +12,23 @@ vi.mock('@/i18n/react-i18next-compat', () => ({
}))
const selectedModelRef = vi.hoisted(() => ({ current: { id: 'm1' } as any }))
+const selectedProviderRef = vi.hoisted(() => ({ current: 'llamacpp' }))
+
+// The failed-load error row links to the provider page's hardware check, so
+// the component reaches the router. Only Link is used here.
+vi.mock('@tanstack/react-router', () => ({
+ Link: ({ children, search, ...rest }: any) => (
+ <a data-search={JSON.stringify(search)} {...rest}>
+ {children}
+ </a>
+ ),
+}))
vi.mock('@/hooks/useModelProvider', () => ({
useModelProvider: (selector: any) =>
- selector({ selectedModel: selectedModelRef.current }),
+ selector({
+ selectedModel: selectedModelRef.current,
+ selectedProvider: selectedProviderRef.current,
+ }),
}))
// Stub heavy children: RenderMarkdown
@@ -129,6 +143,7 @@ vi.mock('@/hooks/useToolApprovalRequests', () => ({
// Import after mocks
import { MessageItem } from '../MessageItem'
+import { useMessageErrors } from '@/stores/message-errors'
const makeMsg = (overrides: any = {}) => ({
id: 'msg-1',
@@ -142,6 +157,7 @@ describe('MessageItem', () => {
beforeEach(() => {
vi.clearAllMocks()
selectedModelRef.current = { id: 'm1' }
+ selectedProviderRef.current = 'llamacpp'
pendingApprovalsRef.current = {}
touchRef.current = false
})
@@ -905,4 +921,53 @@ describe('MessageItem', () => {
expect(regenerate.parentElement?.className).not.toContain('opacity-0')
})
})
+
+ // #9642: a failed llama.cpp load is the one place the user is holding the
+ // question the hardware check answers, so that is where it is offered.
+ describe('failed model load', () => {
+ const show = (model?: string) => {
+ useMessageErrors.getState().setError('msg-1', 'failed to load model')
+ useMessageErrors
+ .getState()
+ .setReport('msg-1', '## Model load failure', model)
+ render(
+ <MessageItem
+ message={makeMsg() as any}
+ isFirstMessage
+ isLastMessage
+ status={'ready' as any}
+ />
+ )
+ }
+
+ beforeEach(() => useMessageErrors.getState().clearAll())
+
+ it('offers the hardware check, carrying the model that failed', () => {
+ show('m1')
+ const link = screen.getByText('providers:diagnostics.checkThisModel')
+ expect(link.getAttribute('data-search')).toBe(
+ JSON.stringify({ diagnoseModel: 'm1' })
+ )
+ })
+
+ // No recorded model means the turn did not run on llama.cpp, so the
+ // llama.cpp model selected now has nothing to do with the failure.
+ it('offers no check when the failed turn recorded no model', () => {
+ show()
+ expect(
+ screen.queryByText('providers:diagnostics.checkThisModel')
+ ).not.toBeInTheDocument()
+ })
+
+ // The message is read long after the user moved on, so the link has to
+ // name the model that failed rather than whatever is selected now.
+ it('checks the model that failed, not the one selected since', () => {
+ show('qwen3-8b')
+ selectedModelRef.current = { id: 'something-else' }
+ const link = screen.getByText('providers:diagnostics.checkThisModel')
+ expect(link.getAttribute('data-search')).toBe(
+ JSON.stringify({ diagnoseModel: 'qwen3-8b' })
+ )
+ })
+ })
})
diff --git a/web-app/src/containers/dialogs/llamacppRouterError.test.ts b/web-app/src/containers/dialogs/llamacppRouterError.test.ts
index c5854942b..9af2041f3 100644
--- a/web-app/src/containers/dialogs/llamacppRouterError.test.ts
+++ b/web-app/src/containers/dialogs/llamacppRouterError.test.ts
@@ -1,5 +1,8 @@
import { describe, it, expect, beforeEach } from 'vitest'
-import { hasActiveLlamacppRequest } from './llamacppRouterError'
+import {
+ hasActiveLlamacppRequest,
+ isEngineWorkInFlight,
+} from './llamacppRouterError'
import { useAppState } from '@/hooks/useAppState'
import { useModelProvider } from '@/hooks/useModelProvider'
@@ -39,3 +42,23 @@ describe('hasActiveLlamacppRequest', () => {
expect(hasActiveLlamacppRequest()).toBe(true)
})
})
+
+// The hardware check reuses the predicate but not the provider gate: it runs
+// from the llama.cpp settings page, which already knows which engine it is.
+describe('isEngineWorkInFlight', () => {
+ it('reports work regardless of which provider is selected', () => {
+ useModelProvider.setState({ selectedProvider: 'openai' })
+ useAppState.setState({ currentStreamThreadId: 'thread-1' })
+ expect(isEngineWorkInFlight(useAppState.getState())).toBe(true)
+ expect(hasActiveLlamacppRequest()).toBe(false)
+ })
+
+ it('is false when nothing is loading or streaming', () => {
+ expect(isEngineWorkInFlight(useAppState.getState())).toBe(false)
+ })
+
+ it('counts a model that is still loading as work', () => {
+ useAppState.setState({ loadingModels: { 'qwen3': true } })
+ expect(isEngineWorkInFlight(useAppState.getState())).toBe(true)
+ })
+})
diff --git a/web-app/src/containers/dialogs/llamacppRouterError.ts b/web-app/src/containers/dialogs/llamacppRouterError.ts
index fd7d497e7..ffa54cab4 100644
--- a/web-app/src/containers/dialogs/llamacppRouterError.ts
+++ b/web-app/src/containers/dialogs/llamacppRouterError.ts
@@ -6,9 +6,22 @@ import { useModelProvider } from '@/hooks/useModelProvider'
// llamacpp generation. At launch/idle the router can emit startup noise with no
// active request — surfacing it would banner a provider the user never invoked
// (e.g. MLX selected on macOS).
-export function hasActiveLlamacppRequest(): boolean {
- if (useModelProvider.getState().selectedProvider !== 'llamacpp') return false
- const app = useAppState.getState()
+/**
+ * Whether the app has engine work in flight, independent of which provider is
+ * selected. Separate from [`hasActiveLlamacppRequest`] so a caller that
+ * already knows it is on llama.cpp -- the provider settings page -- can use it
+ * as a zustand selector and re-render when the answer changes.
+ */
+export function isEngineWorkInFlight(
+ app: Pick<
+ ReturnType<typeof useAppState.getState>,
+ | 'currentStreamThreadId'
+ | 'abortControllers'
+ | 'busyThreads'
+ | 'loadingModels'
+ | 'streamingContents'
+ >
+): boolean {
return (
// A token stream is the common case and sets none of the slots below;
// currentStreamThreadId is the reliable "request in flight" signal.
@@ -20,6 +33,11 @@ export function hasActiveLlamacppRequest(): boolean {
)
}
+export function hasActiveLlamacppRequest(): boolean {
+ if (useModelProvider.getState().selectedProvider !== 'llamacpp') return false
+ return isEngineWorkInFlight(useAppState.getState())
+}
+
export function stampErrorOnLastUserMessage(
field: 'oomError' | 'backendError',
value: string
diff --git a/web-app/src/containers/llamacppDiagnosticsStatus.ts b/web-app/src/containers/llamacppDiagnosticsStatus.ts
new file mode 100644
index 000000000..d8164acec
--- /dev/null
+++ b/web-app/src/containers/llamacppDiagnosticsStatus.ts
@@ -0,0 +1,90 @@
+import {
+ IconAlertTriangle,
+ IconCheck,
+ IconCircleDashed,
+ IconCpu,
+ IconHelpCircle,
+ IconX,
+ type Icon,
+} from '@tabler/icons-react'
+
+import type { DeviceVerdict, DiagnosticsGroup } from '@/lib/diagnosticsGroups'
+
+/**
+ * The visual vocabulary for a hardware check.
+ *
+ * Deliberately the same shape and the same four colours as
+ * `ModelInfoHoverCard`'s fit tiers -- a dot, a pill, an icon and a
+ * plain-language label -- so a green dot means the same thing wherever a user
+ * meets one in Jan. Amber is the interesting one here: an op the device does
+ * not implement is not a fault, it is slower, and painting it red would send
+ * people chasing a non-problem.
+ */
+export interface StatusStyle {
+ icon: Icon
+ dot: string
+ pill: string
+ /** Left edge of a device row; the hardware page uses the same device. */
+ edge: string
+ text: string
+}
+
+export const VERDICT_STYLES: Record<DeviceVerdict, StatusStyle> = {
+ passed: {
+ icon: IconCheck,
+ dot: 'bg-emerald-500',
+ pill: 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400',
+ edge: 'border-l-emerald-500',
+ text: 'text-emerald-600 dark:text-emerald-400',
+ },
+ fallback: {
+ icon: IconCpu,
+ dot: 'bg-amber-500',
+ pill: 'bg-amber-500/10 text-amber-700 dark:text-amber-400',
+ edge: 'border-l-amber-500',
+ text: 'text-amber-700 dark:text-amber-400',
+ },
+ // Nothing failed, but part of the check tested nothing. Neutral rather than
+ // red -- there is no fault here -- but it carries an edge and an icon of its
+ // own, because the one thing it must not look like is a pass.
+ inconclusive: {
+ icon: IconHelpCircle,
+ dot: 'bg-neutral-400',
+ pill: 'bg-secondary text-muted-foreground',
+ edge: 'border-l-neutral-400',
+ text: 'text-muted-foreground',
+ },
+ failed: {
+ icon: IconX,
+ dot: 'bg-red-500',
+ pill: 'bg-red-500/10 text-red-600 dark:text-red-400',
+ edge: 'border-l-red-500',
+ text: 'text-red-600 dark:text-red-400',
+ },
+ unknown: {
+ icon: IconCircleDashed,
+ dot: 'bg-neutral-400',
+ pill: 'bg-secondary text-muted-foreground',
+ // No edge colour: a device that has not run carries no verdict, and an
+ // absent border says that more honestly than a grey one.
+ edge: 'border-l-transparent',
+ text: 'text-muted-foreground',
+ },
+}
+
+export const CRASH_STYLE: StatusStyle = {
+ ...VERDICT_STYLES.failed,
+ icon: IconAlertTriangle,
+}
+
+/** Locale keys for the group name and its one-line explanation. */
+export function groupLabelKeys(group: DiagnosticsGroup): {
+ label: string
+ detail: string
+} {
+ const suffix = group.charAt(0).toUpperCase() + group.slice(1)
+ return {
+ label: `providers:diagnostics.group${suffix}`,
+ detail: `providers:diagnostics.group${suffix}Detail`,
+ }
+}
diff --git a/web-app/src/hooks/useLlamacppDiagnostics.ts b/web-app/src/hooks/useLlamacppDiagnostics.ts
new file mode 100644
index 000000000..5e6b5dd4f
--- /dev/null
+++ b/web-app/src/hooks/useLlamacppDiagnostics.ts
@@ -0,0 +1,444 @@
+import { useCallback, useEffect, useRef, useState } from 'react'
+import {
+ cancelDiagnostics,
+ onDiagnosticsEvent,
+ startDiagnostics,
+ type DiagnosticsCaseStatus,
+ type DiagnosticsDevice,
+ type DiagnosticsEngineBuild,
+ type DiagnosticsEvent,
+ type DiagnosticsFamilyStatus,
+ type DiagnosticsPreset,
+} from '@janhq/tauri-plugin-llamacpp-api'
+
+/**
+ * Non-failing cases kept for the detail table. Failures are always kept in
+ * full -- they are what the screen exists for and are rare -- but a Full run
+ * emits tens of thousands of passes per device, and holding them all would
+ * cost more memory than the answer is worth.
+ */
+const KEPT_CASE_LIMIT = 5000
+
+/**
+ * How often accumulated events reach React. The stream peaks in the thousands
+ * of events per second, so rendering per event would starve the UI thread;
+ * terminal events flush immediately regardless.
+ */
+const FLUSH_INTERVAL_MS = 150
+
+/**
+ * Events held while a run's id is still unknown. The window is one IPC
+ * round trip, but the stream peaks in the thousands of events per second, so
+ * it is bounded; the events past the cap are cases, which [`DiagnosticsRun`]
+ * caps anyway.
+ */
+const PENDING_EVENT_LIMIT = 5000
+
+export interface DiagnosticsCase {
+ device: string
+ family: string
+ op: string
+ params: string
+ status: DiagnosticsCaseStatus
+ error?: string
+ detail?: string
+}
+
+export interface DiagnosticsFamily {
+ family: string
+ status: DiagnosticsFamilyStatus
+ ok: number
+ failed: number
+ notSupported: number
+ millis: number
+ exit?: string
+ lastLines: string[]
+}
+
+export interface DiagnosticsDeviceRun {
+ device: DiagnosticsDevice
+ families: DiagnosticsFamily[]
+ ok: number
+ failed: number
+ notSupported: number
+ crashed: number
+ hung: number
+ /** Families whose shape filter matched no case, so they tested nothing. */
+ noCases: number
+ /** Families the run never reached, because it was cancelled or timed out. */
+ cancelled: number
+ /**
+ * Per-op support, keyed by op name. Counted from every case event rather
+ * than from `cases`, which is capped -- a long run would otherwise
+ * undercount.
+ */
+ opSupport: Record<string, OpSupport>
+ complete: boolean
+}
+
+/**
+ * How one op fared on one device.
+ *
+ * Counts, not a boolean: an op is very often *partially* supported. A device
+ * reporting some unsupported `MUL_MAT` cases still has a `MUL_MAT` kernel for
+ * almost all of them, and listing the bare op name says the opposite.
+ */
+export interface OpSupport {
+ op: string
+ /** Cases the device reported it supports, from the support probe. */
+ ok: number
+ notSupported: number
+ /** Parameter strings that had no kernel, for a report to quote. */
+ examples: string[]
+}
+
+/** Unsupported parameter strings kept per op; enough to show the shape. */
+export const EXAMPLES_PER_OP = 4
+
+/** Ops with at least one unsupported case, worst first. */
+export function unsupportedOps(device: DiagnosticsDeviceRun): OpSupport[] {
+ return Object.values(device.opSupport)
+ .filter((o) => o.notSupported > 0)
+ .sort((a, b) => b.notSupported - a.notSupported || a.op.localeCompare(b.op))
+}
+
+export type DiagnosticsRunStatus =
+ | 'idle'
+ | 'running'
+ | 'passed'
+ /**
+ * Nothing failed, but at least one family tested nothing. Its own status
+ * rather than a pass: a narrowed run that covered none of what it named
+ * must not read as "your hardware is fine".
+ */
+ | 'inconclusive'
+ | 'failed'
+ | 'cancelled'
+ | 'error'
+
+export interface DiagnosticsRun {
+ job: string
+ status: DiagnosticsRunStatus
+ preset: DiagnosticsPreset
+ engine?: DiagnosticsEngineBuild
+ /** The model this run was built for, on the `model` preset. */
+ model?: string
+ backendModules: string[]
+ devices: DiagnosticsDeviceRun[]
+ cases: DiagnosticsCase[]
+ /** True when non-failing cases were dropped at [`KEPT_CASE_LIMIT`]. */
+ casesTruncated: boolean
+ totalUnits: number
+ finishedUnits: number
+ current?: { device: string; family: string }
+ error?: string
+ startedAt: number
+ finishedAt?: number
+}
+
+function emptyRun(job: string, preset: DiagnosticsPreset): DiagnosticsRun {
+ return {
+ job,
+ status: 'running',
+ preset,
+ backendModules: [],
+ devices: [],
+ cases: [],
+ casesTruncated: false,
+ totalUnits: 0,
+ finishedUnits: 0,
+ startedAt: Date.now(),
+ }
+}
+
+function deviceEntry(
+ run: DiagnosticsRun,
+ name: string
+): DiagnosticsDeviceRun | undefined {
+ return run.devices.find((d) => d.device.name === name)
+}
+
+/**
+ * Folds one event into the run. Mutates on purpose: this runs on every case of
+ * a stream that peaks in the thousands per second, and the flush below is what
+ * hands React a fresh object.
+ */
+export function applyDiagnosticsEvent(
+ run: DiagnosticsRun,
+ event: DiagnosticsEvent
+): DiagnosticsRun {
+ switch (event.event) {
+ case 'start':
+ run.engine = event.engine
+ run.model = event.model
+ run.backendModules = event.backend_modules
+ run.totalUnits = event.units
+ break
+ case 'device':
+ run.devices.push({
+ device: {
+ name: event.name,
+ description: event.description,
+ type: event.type,
+ reg: event.reg,
+ memory_total_mib: event.memory_total_mib,
+ memory_free_mib: event.memory_free_mib,
+ },
+ families: [],
+ ok: 0,
+ failed: 0,
+ notSupported: 0,
+ crashed: 0,
+ hung: 0,
+ noCases: 0,
+ cancelled: 0,
+ opSupport: {},
+ complete: false,
+ })
+ break
+ case 'family_start':
+ run.current = { device: event.device, family: event.family }
+ break
+ case 'case': {
+ const failing = event.status === 'fail'
+ if (failing || run.cases.length < KEPT_CASE_LIMIT) {
+ run.cases.push({
+ device: event.device,
+ family: event.family,
+ op: event.op,
+ params: event.params,
+ status: event.status,
+ error: event.error,
+ detail: event.detail,
+ })
+ } else {
+ run.casesTruncated = true
+ }
+ // Support comes from the probe alone. It asks the whole op list once,
+ // so it is both authoritative and a correct denominator -- whereas the
+ // test run re-reports the same ops, and summing the two counted every
+ // quick-preset family twice.
+ //
+ // Counted outside the cap above: `ok` and `not_supported` cases are
+ // both non-failing, so a capped run would undercount them.
+ if (
+ event.mode === 'support' &&
+ (event.status === 'ok' || event.status === 'not_supported')
+ ) {
+ const device = deviceEntry(run, event.device)
+ if (device) {
+ const stat = (device.opSupport[event.op] ??= {
+ op: event.op,
+ ok: 0,
+ notSupported: 0,
+ examples: [],
+ })
+ if (event.status === 'ok') {
+ stat.ok += 1
+ } else {
+ stat.notSupported += 1
+ if (stat.examples.length < EXAMPLES_PER_OP) {
+ stat.examples.push(event.params)
+ }
+ }
+ }
+ }
+ break
+ }
+ case 'family_end': {
+ run.finishedUnits += 1
+ run.current = undefined
+ const device = deviceEntry(run, event.device)
+ if (device) {
+ device.families.push({
+ family: event.family,
+ status: event.status,
+ ok: event.ok,
+ failed: event.failed,
+ notSupported: event.not_supported,
+ millis: event.millis,
+ exit: event.exit,
+ lastLines: event.last_lines ?? [],
+ })
+ }
+ break
+ }
+ case 'summary': {
+ const device = deviceEntry(run, event.device)
+ if (device) {
+ device.ok = event.ok
+ device.failed = event.failed
+ device.notSupported = event.not_supported
+ device.crashed = event.families_crashed
+ device.hung = event.families_hung
+ device.noCases = event.families_no_cases ?? 0
+ device.cancelled = event.families_cancelled ?? 0
+ device.complete = true
+ }
+ break
+ }
+ case 'done':
+ run.current = undefined
+ run.finishedAt = Date.now()
+ run.error = event.error
+ // `inconclusive` is read before `ok`: an inconclusive run reports
+ // `ok: false` so a reader of that field alone cannot mistake it for a
+ // pass, and this is what tells it apart from a real failure.
+ run.status = event.cancelled
+ ? 'cancelled'
+ : event.error
+ ? 'error'
+ : event.inconclusive
+ ? 'inconclusive'
+ : event.ok
+ ? 'passed'
+ : 'failed'
+ break
+ }
+ return run
+}
+
+/** True once the run can no longer produce events. */
+export function isFinished(status: DiagnosticsRunStatus): boolean {
+ return status !== 'idle' && status !== 'running'
+}
+
+/**
+ * Drives one hardware check. One run at a time, enforced in the plugin too, so
+ * a second Run press reports rather than racing.
+ */
+export function useLlamacppDiagnostics() {
+ const [run, setRun] = useState<DiagnosticsRun | null>(null)
+ const [starting, setStarting] = useState(false)
+ // The run is accumulated here and copied into state on a timer; `job` gates
+ // events from a superseded run, which can still be in flight.
+ const buffer = useRef<DiagnosticsRun | null>(null)
+ const job = useRef<string | null>(null)
+ const dirty = useRef(false)
+ // The backend starts the root, and its event pump, before the reply to
+ // `startDiagnostics` reaches the webview, so the first events of a run can
+ // arrive while its id is still unknown. They are held here and replayed
+ // against the id once it lands; dropping them costs the run its device list
+ // or, on a fast failure, its terminal event.
+ const pending = useRef<DiagnosticsEvent[]>([])
+ const awaitingId = useRef(false)
+ // True while the panel is gone. A start in flight at that moment still gets
+ // its id back, and that run has to be cancelled too: it holds the single
+ // slot for as long as it runs, with nothing left to stop it.
+ const unmounted = useRef(false)
+
+ useEffect(() => {
+ // Cleared on every mount, not just the first. StrictMode mounts, cleans
+ // up and mounts again in development, so a flag only ever set would stay
+ // set for the life of the component and abandon every run started after
+ // it.
+ unmounted.current = false
+ let unlisten: (() => void) | undefined
+ let disposed = false
+ const flush = () => {
+ if (!dirty.current || !buffer.current) return
+ dirty.current = false
+ setRun({ ...buffer.current })
+ }
+ onDiagnosticsEvent((event) => {
+ if (!buffer.current || event.job !== job.current) {
+ if (awaitingId.current && pending.current.length < PENDING_EVENT_LIMIT) {
+ pending.current.push(event)
+ }
+ return
+ }
+ applyDiagnosticsEvent(buffer.current, event)
+ dirty.current = true
+ if (event.event === 'done') flush()
+ })
+ .then((fn) => {
+ if (disposed) fn()
+ else unlisten = fn
+ })
+ .catch((e) => console.warn('listen llamacpp-diagnostics failed:', e))
+
+ const timer = setInterval(flush, FLUSH_INTERVAL_MS)
+ return () => {
+ disposed = true
+ clearInterval(timer)
+ unlisten?.()
+ // A run outlives this panel and cannot be reattached to on a remount,
+ // so it would hold the single backend slot -- and every core -- with
+ // nothing listening. Leaving the page is a cancel.
+ unmounted.current = true
+ const id = job.current
+ if (id && buffer.current && !isFinished(buffer.current.status)) {
+ abandon(id)
+ }
+ }
+ }, [])
+
+ const start = useCallback(
+ async (
+ preset: DiagnosticsPreset,
+ devices: string[] = [],
+ model?: string
+ ) => {
+ setStarting(true)
+ pending.current = []
+ awaitingId.current = true
+ try {
+ const started = await startDiagnostics(preset, devices, {}, model)
+ // The panel can have gone while this was in flight, in which case the
+ // cleanup had no id to cancel and this is the first chance to.
+ if (unmounted.current) {
+ abandon(started.id)
+ return
+ }
+ job.current = started.id
+ buffer.current = emptyRun(started.id, preset)
+ // Replayed in arrival order, so the run reads exactly as it would
+ // have had the id been known from the first event.
+ for (const event of pending.current) {
+ if (event.job === started.id) {
+ applyDiagnosticsEvent(buffer.current, event)
+ }
+ }
+ setRun({ ...buffer.current })
+ } catch (e) {
+ job.current = null
+ buffer.current = null
+ setRun({
+ ...emptyRun('', preset),
+ status: 'error',
+ error: e instanceof Error ? e.message : String(e),
+ finishedAt: Date.now(),
+ })
+ } finally {
+ awaitingId.current = false
+ pending.current = []
+ setStarting(false)
+ }
+ },
+ []
+ )
+
+ const cancel = useCallback(async () => {
+ if (!job.current) return
+ try {
+ await cancelDiagnostics(job.current)
+ } catch (e) {
+ console.warn('cancel llamacpp diagnostics failed:', e)
+ }
+ }, [])
+
+ return {
+ run,
+ starting,
+ running: run?.status === 'running',
+ start,
+ cancel,
+ }
+}
+
+/** Stops a run nothing is listening to any more. */
+function abandon(id: string) {
+ void cancelDiagnostics(id).catch((e) =>
+ console.warn('cancel llamacpp diagnostics failed:', e)
+ )
+}
diff --git a/web-app/src/lib/__tests__/custom-chat-transport-failed-load.test.ts b/web-app/src/lib/__tests__/custom-chat-transport-failed-load.test.ts
new file mode 100644
index 000000000..d30e8f9bc
--- /dev/null
+++ b/web-app/src/lib/__tests__/custom-chat-transport-failed-load.test.ts
@@ -0,0 +1,148 @@
+import { describe, expect, it, vi, beforeEach } from 'vitest'
+import type { UIMessage } from '@ai-sdk/react'
+import type * as ProviderCaps from '@/lib/providerCaps'
+
+// A request that throws before its stream exists never reaches the stream's
+// onError/onFinish, so it must release the "request in flight" marker itself:
+// the hardware check is disabled for as long as that marker is set.
+
+const h = vi.hoisted(() => ({
+ serviceHub: null as unknown,
+ app: { currentStreamThreadId: undefined as string | undefined },
+ loads: [] as { reject: (e: unknown) => void }[],
+}))
+
+h.serviceHub = {
+ mcp: () => ({ getTools: vi.fn(async () => []) }),
+ rag: () => ({ getTools: async () => [] }),
+}
+
+const provider = { provider: 'llamacpp', api_key: '', models: [] }
+const selectedModel = { id: 'broken', capabilities: [] as string[] }
+
+vi.mock('@/hooks/useServiceHub', () => ({
+ useServiceStore: { getState: () => ({ serviceHub: h.serviceHub }) },
+}))
+vi.mock('@/hooks/useToolAvailable', () => ({
+ useToolAvailable: {
+ getState: () => ({
+ getDisabledTools: () => [],
+ getDefaultDisabledTools: () => [],
+ }),
+ },
+}))
+vi.mock('@/hooks/useModelProvider', () => ({
+ useModelProvider: {
+ getState: () => ({
+ selectedModel,
+ selectedProvider: 'llamacpp',
+ getProviderByName: () => provider,
+ }),
+ },
+}))
+vi.mock('@/hooks/useAssistant', () => ({
+ useAssistant: { getState: () => ({ currentAssistant: null }) },
+}))
+vi.mock('@/hooks/useThreads', () => ({
+ useThreads: { getState: () => ({ threads: {} }) },
+}))
+vi.mock('@/hooks/useAttachments', () => ({
+ useAttachments: { getState: () => ({ enabled: false }) },
+}))
+vi.mock('@/hooks/useMCPServers', () => ({
+ useMCPServers: { getState: () => ({ settings: {} }) },
+}))
+vi.mock('@/hooks/useAppState', () => ({
+ useAppState: {
+ getState: () =>
+ new Proxy(h.app, {
+ get: (target, key) => {
+ if (key === 'currentStreamThreadId') return target.currentStreamThreadId
+ if (key === 'setCurrentStreamThreadId')
+ return (id: string | undefined) => {
+ target.currentStreamThreadId = id
+ }
+ return () => undefined
+ },
+ }),
+ },
+}))
+vi.mock('@janhq/tauri-plugin-llamacpp-api', () => ({
+ getLoadedModels: async () => [],
+ unloadLlamaModel: async () => ({ success: true }),
+}))
+vi.mock('@/lib/mcp-orchestrator', () => ({
+ mcpOrchestrator: { getRelevantTools: vi.fn() },
+}))
+vi.mock('@/lib/mcp-router-model-filter', () => ({
+ isRouterModelSelectable: () => false,
+}))
+vi.mock('@/lib/reasoningProviderOptions', () => ({
+ buildReasoningProviderOptions: () => undefined,
+}))
+vi.mock('@/lib/providerCaps', async (importOriginal) => ({
+ ...(await importOriginal<typeof ProviderCaps>()),
+ isPredefinedRemoteProvider: () => false,
+ getProviderApiType: () => 'openai',
+}))
+vi.mock('../model-factory', () => ({
+ ModelFactory: {
+ createModel: () =>
+ new Promise((_, reject) => {
+ h.loads.push({ reject })
+ }),
+ },
+}))
+
+import { CustomChatTransport } from '../custom-chat-transport'
+
+const user = (id: string, text: string): UIMessage =>
+ ({ id, role: 'user', parts: [{ type: 'text', text }] }) as UIMessage
+
+const send = (transport: CustomChatTransport, chatId: string) =>
+ transport.sendMessages({
+ chatId,
+ messages: [user('m1', 'hi')],
+ abortSignal: undefined,
+ trigger: 'submit-message',
+ messageId: undefined,
+ })
+
+const loadStarted = async (count: number) => {
+ await vi.waitFor(() => expect(h.loads).toHaveLength(count))
+}
+
+describe('CustomChatTransport: a failed model load', () => {
+ beforeEach(() => {
+ h.app.currentStreamThreadId = undefined
+ h.loads.length = 0
+ })
+
+ it('clears the in-flight stream marker', async () => {
+ const transport = new CustomChatTransport()
+ const pending = send(transport, 'thread-1')
+ await loadStarted(1)
+ expect(h.app.currentStreamThreadId).toBe('thread-1')
+
+ h.loads[0].reject(new Error('failed to load model'))
+
+ await expect(pending).rejects.toThrow()
+ expect(h.app.currentStreamThreadId).toBeUndefined()
+ })
+
+ it('leaves the marker of a newer request alone', async () => {
+ const transport = new CustomChatTransport()
+ const first = send(transport, 'thread-1')
+ await loadStarted(1)
+ const second = send(transport, 'thread-2')
+ await loadStarted(2)
+
+ h.loads[0].reject(new Error('failed to load model'))
+ await expect(first).rejects.toThrow()
+ expect(h.app.currentStreamThreadId).toBe('thread-2')
+
+ h.loads[1].reject(new Error('failed to load model'))
+ await expect(second).rejects.toThrow()
+ expect(h.app.currentStreamThreadId).toBeUndefined()
+ })
+})
diff --git a/web-app/src/lib/__tests__/diagnosticsGroups.test.ts b/web-app/src/lib/__tests__/diagnosticsGroups.test.ts
new file mode 100644
index 000000000..4b56c9bdb
--- /dev/null
+++ b/web-app/src/lib/__tests__/diagnosticsGroups.test.ts
@@ -0,0 +1,183 @@
+import { describe, expect, it } from 'vitest'
+
+import {
+ deviceVerdict,
+ groupForOp,
+ isQuantizedCase,
+ type DeviceTally,
+ hasCpuFallback,
+} from '@/lib/diagnosticsGroups'
+
+const tally = (over: Partial<DeviceTally> = {}): DeviceTally => ({
+ ok: 100,
+ failed: 0,
+ notSupported: 0,
+ crashed: 0,
+ hung: 0,
+ noCases: 0,
+ cancelled: 0,
+ complete: true,
+ canOffload: true,
+ ...over,
+})
+
+describe('hasCpuFallback', () => {
+ it('is false only for the CPU itself', () => {
+ expect(hasCpuFallback('cpu')).toBe(false)
+ for (const kind of ['gpu', 'igpu', 'accel', 'meta', 'unknown'] as const) {
+ expect(hasCpuFallback(kind)).toBe(true)
+ }
+ })
+})
+
+describe('groupForOp', () => {
+ it('puts the matmul family together, including its fusions', () => {
+ for (const op of [
+ 'MUL_MAT',
+ 'MUL_MAT_ID',
+ 'MUL_MAT_VEC_FUSION',
+ 'MUL_MAT_ID_W4A8',
+ 'OUT_PROD',
+ ]) {
+ expect(groupForOp(op)).toBe('matrixMath')
+ }
+ })
+
+ it('does not let MUL_MAT fall into basic arithmetic', () => {
+ // The rule order is what prevents this: `MUL` is in the basic-math set.
+ expect(groupForOp('MUL')).toBe('basicMath')
+ expect(groupForOp('MUL_MAT')).toBe('matrixMath')
+ })
+
+ it('groups the token-mixing ops as attention, including the replacements', () => {
+ for (const op of [
+ 'FLASH_ATTN_EXT',
+ 'SOFT_MAX',
+ 'DIAG_MASK_INF',
+ 'TOPK_MOE',
+ 'TOP_K',
+ 'SSM_SCAN',
+ 'RWKV_WKV6',
+ 'GATED_LINEAR_ATTN',
+ 'GATED_DELTA_NET_CACHE_FUSION',
+ ]) {
+ expect(groupForOp(op)).toBe('attention')
+ }
+ })
+
+ it('reads a fused op by what it is for, not by every name in it', () => {
+ // Contains NORM, MUL and ROPE; it is a normalization kernel.
+ expect(groupForOp('RMS_NORM_MUL_ROPE')).toBe('normalization')
+ expect(groupForOp('GROUP_NORM_MUL_ADD')).toBe('normalization')
+ })
+
+ it('covers the remaining groups', () => {
+ expect(groupForOp('ROPE_BACK')).toBe('positional')
+ expect(groupForOp('CONV_2D')).toBe('convolution')
+ expect(groupForOp('IM2COL_3D')).toBe('convolution')
+ expect(groupForOp('SILU')).toBe('activation')
+ expect(groupForOp('SWIGLU')).toBe('activation')
+ expect(groupForOp('GET_ROWS')).toBe('memory')
+ expect(groupForOp('CPY')).toBe('memory')
+ expect(groupForOp('ADD')).toBe('basicMath')
+ })
+
+ it('is case insensitive and never throws on an op it does not know', () => {
+ expect(groupForOp('mul_mat')).toBe('matrixMath')
+ expect(groupForOp('SOMETHING_UPSTREAM_ADDED')).toBe('other')
+ expect(groupForOp('')).toBe('other')
+ })
+})
+
+describe('isQuantizedCase', () => {
+ it('reads quantization off the parameters, not the op name', () => {
+ expect(isQuantizedCase('type_a=q4_K,type_b=f32,m=4096')).toBe(true)
+ expect(isQuantizedCase('type=iq4_nl,ne=[128,2,2,2]')).toBe(true)
+ expect(isQuantizedCase('type=mxfp4,ne=[32]')).toBe(true)
+ expect(isQuantizedCase('type=f16,ne_a=[128,2,2,2],v=0')).toBe(false)
+ expect(isQuantizedCase('')).toBe(false)
+ })
+})
+
+describe('deviceVerdict', () => {
+ it('passes a device that ran cases and broke none', () => {
+ expect(deviceVerdict(tally())).toBe('passed')
+ })
+
+ it('treats a not-supported op as a fallback, never a failure', () => {
+ expect(deviceVerdict(tally({ notSupported: 300 }))).toBe('fallback')
+ })
+
+ // The CPU is ggml's fallback of last resort, so an op it lacks is not
+ // deferred anywhere. Reporting "runs on the processor" on the processor's
+ // own row is circular, and there is no slower path to warn about.
+ it('does not call the CPU a fallback, because it has nowhere to fall back to', () => {
+ expect(deviceVerdict(tally({ notSupported: 3239, canOffload: false }))).toBe(
+ 'passed'
+ )
+ })
+
+ it('still fails the CPU on a wrong answer', () => {
+ expect(
+ deviceVerdict(tally({ notSupported: 3239, failed: 1, canOffload: false }))
+ ).toBe('failed')
+ })
+
+ it('fails on a wrong answer, a crash or a hang alike', () => {
+ expect(deviceVerdict(tally({ failed: 1 }))).toBe('failed')
+ expect(deviceVerdict(tally({ crashed: 1 }))).toBe('failed')
+ expect(deviceVerdict(tally({ hung: 1 }))).toBe('failed')
+ })
+
+ it('a failure outranks a fallback', () => {
+ expect(deviceVerdict(tally({ failed: 1, notSupported: 300 }))).toBe('failed')
+ })
+
+ it('reports nothing rather than a pass when no case ran', () => {
+ expect(deviceVerdict(tally({ ok: 0 }))).toBe('unknown')
+ })
+
+ // The failure this phase exists to avoid: a shape filter that matched no
+ // case leaves the other families passing, and the device would otherwise
+ // read as a clean bill of health for parts that were never checked.
+ it('never calls a device passed while part of the check tested nothing', () => {
+ expect(deviceVerdict(tally({ noCases: 1 }))).toBe('inconclusive')
+ expect(deviceVerdict(tally({ noCases: 1, notSupported: 300 }))).toBe(
+ 'inconclusive'
+ )
+ })
+
+ // Same hazard as `noCases`, from the other direction: a run stopped by the
+ // user or by its deadline leaves the families it did reach passing, and the
+ // ones it never reached unaccounted for.
+ it('never calls a device passed while part of the check never ran', () => {
+ expect(deviceVerdict(tally({ cancelled: 1 }))).toBe('inconclusive')
+ expect(deviceVerdict(tally({ cancelled: 1, notSupported: 300 }))).toBe(
+ 'inconclusive'
+ )
+ })
+
+ it('a real failure still outranks a cancelled family', () => {
+ expect(deviceVerdict(tally({ cancelled: 1, failed: 2 }))).toBe('failed')
+ })
+
+ it('does not pass a device whose summary has not arrived', () => {
+ expect(deviceVerdict(tally({ complete: false }))).toBe('inconclusive')
+ })
+
+ // A narrowed run that matched no case has no passes behind it either, so
+ // the zero-pass check must not claim it first: "Not checked" would say the
+ // run never happened when it finished having covered nothing it named.
+ it('calls a run that tested nothing inconclusive, not unchecked', () => {
+ expect(deviceVerdict(tally({ ok: 0, noCases: 1 }))).toBe('inconclusive')
+ })
+
+ it('still reports nothing when nothing ran at all', () => {
+ expect(deviceVerdict(tally({ ok: 0, cancelled: 2 }))).toBe('unknown')
+ expect(deviceVerdict(tally({ ok: 0, complete: false }))).toBe('unknown')
+ })
+
+ it('a real failure still outranks an untested family', () => {
+ expect(deviceVerdict(tally({ noCases: 1, failed: 2 }))).toBe('failed')
+ })
+})
diff --git a/web-app/src/lib/__tests__/diagnosticsReport.test.ts b/web-app/src/lib/__tests__/diagnosticsReport.test.ts
new file mode 100644
index 000000000..f5a21563b
--- /dev/null
+++ b/web-app/src/lib/__tests__/diagnosticsReport.test.ts
@@ -0,0 +1,302 @@
+import { describe, expect, it } from 'vitest'
+import type { DiagnosticsEvent } from '@janhq/tauri-plugin-llamacpp-api'
+
+import { formatDiagnosticsReport } from '@/lib/diagnosticsReport'
+import {
+ applyDiagnosticsEvent,
+ unsupportedOps,
+ EXAMPLES_PER_OP,
+ type DiagnosticsRun,
+} from '@/hooks/useLlamacppDiagnostics'
+
+const JOB = 'test-job'
+
+function build(events: Omit<DiagnosticsEvent, 'job'>[]): DiagnosticsRun {
+ let run: DiagnosticsRun = {
+ job: JOB,
+ status: 'running',
+ preset: 'quick',
+ backendModules: [],
+ devices: [],
+ cases: [],
+ casesTruncated: false,
+ totalUnits: 0,
+ finishedUnits: 0,
+ startedAt: 0,
+ }
+ for (const event of events) {
+ run = applyDiagnosticsEvent(run, { ...event, job: JOB } as DiagnosticsEvent)
+ }
+ return run
+}
+
+const START = {
+ event: 'start',
+ schema: 1,
+ preset: 'quick',
+ engine: { version: '0.9.0', tag: 'b12110', commit: 'cd959bae99ff4bed' },
+ families: ['ADD'],
+ support_probe: true,
+ backend_modules: ['CUDA (libggml-cuda.so)'],
+ units: 2,
+ family_timeout_secs: 600,
+ deadline_secs: 5400,
+} as const
+
+const DEVICE = {
+ event: 'device',
+ name: 'CUDA0',
+ description: 'NVIDIA RTX 3090',
+ type: 'gpu',
+ reg: 'CUDA',
+ memory_total_mib: 24576,
+ memory_free_mib: 20480,
+} as const
+
+const caseEvent = (over: Record<string, unknown> = {}) =>
+ ({
+ event: 'case',
+ device: 'CUDA0',
+ family: 'MUL_MAT',
+ backend: 'CUDA0',
+ op: 'MUL_MAT',
+ params: 'type_a=q4_K,m=4096',
+ mode: 'test',
+ status: 'ok',
+ ...over,
+ }) as unknown as Omit<DiagnosticsEvent, 'job'>
+
+/** A case as the support probe reports it; only these feed `opSupport`. */
+const probeEvent = (over: Record<string, unknown> = {}) =>
+ caseEvent({ mode: 'support', family: '*', ...over })
+
+describe('applyDiagnosticsEvent', () => {
+ it('builds a device summary from the stream', () => {
+ const run = build([
+ START,
+ DEVICE,
+ { event: 'family_start', device: 'CUDA0', family: 'MUL_MAT', mode: 'test' },
+ caseEvent(),
+ caseEvent({ status: 'fail', error: 'compare failed' }),
+ probeEvent({ status: 'not_supported', op: 'SILU' }),
+ {
+ event: 'family_end',
+ device: 'CUDA0',
+ family: 'MUL_MAT',
+ status: 'fail',
+ ok: 1,
+ failed: 1,
+ not_supported: 1,
+ millis: 1200,
+ },
+ {
+ event: 'summary',
+ device: 'CUDA0',
+ ok: 1,
+ failed: 1,
+ not_supported: 1,
+ families_crashed: 0,
+ families_hung: 0,
+ },
+ { event: 'done', ok: false, cancelled: false },
+ ] as Omit<DiagnosticsEvent, 'job'>[])
+
+ expect(run.status).toBe('failed')
+ expect(run.devices).toHaveLength(1)
+ expect(run.devices[0].failed).toBe(1)
+ expect(run.devices[0].complete).toBe(true)
+ expect(run.finishedUnits).toBe(1)
+ expect(run.current).toBeUndefined()
+ })
+
+ // The defect this replaced: an op was recorded as "not implemented" when a
+ // single case of it was unsupported, so a device that ran 2630 of 3090
+ // MUL_MAT cases was reported as having no matrix multiply at all.
+ it('counts per-op support rather than flagging the whole op', () => {
+ const events: Omit<DiagnosticsEvent, 'job'>[] = [START, DEVICE]
+ for (let i = 0; i < 26; i++) events.push(probeEvent({ op: 'MUL_MAT', params: `ok${i}` }))
+ for (let i = 0; i < 4; i++)
+ events.push(
+ probeEvent({ status: 'not_supported', op: 'MUL_MAT', params: `type_a=q4_0,n=${i}` })
+ )
+ events.push(probeEvent({ status: 'not_supported', op: 'SILU', params: 'type=f16' }))
+ const run = build(events)
+
+ const ops = unsupportedOps(run.devices[0])
+ expect(ops.map((o) => [o.op, o.notSupported, o.ok])).toEqual([
+ ['MUL_MAT', 4, 26],
+ ['SILU', 1, 0],
+ ])
+ })
+
+ it('keeps the parameters of unsupported cases, capped', () => {
+ const events: Omit<DiagnosticsEvent, 'job'>[] = [START, DEVICE]
+ for (let i = 0; i < EXAMPLES_PER_OP + 3; i++)
+ events.push(probeEvent({ status: 'not_supported', op: 'MUL_MAT', params: `k=${i}` }))
+ const run = build(events)
+
+ const [mulmat] = unsupportedOps(run.devices[0])
+ expect(mulmat.notSupported).toBe(EXAMPLES_PER_OP + 3)
+ expect(mulmat.examples).toHaveLength(EXAMPLES_PER_OP)
+ expect(mulmat.examples[0]).toBe('k=0')
+ })
+
+ it('counts support past the cap on passing cases', () => {
+ const events: Omit<DiagnosticsEvent, 'job'>[] = [START, DEVICE]
+ for (let i = 0; i < 5200; i++) events.push(probeEvent({ op: 'MUL_MAT', params: `n=${i}` }))
+ events.push(probeEvent({ status: 'not_supported', op: 'MUL_MAT', params: 'odd' }))
+ const run = build(events)
+
+ // `cases` is capped at 5000; the ratio must not be.
+ expect(run.casesTruncated).toBe(true)
+ expect(unsupportedOps(run.devices[0])[0].ok).toBe(5200)
+ })
+
+ it('tells a cancelled run from a failed one', () => {
+ const cancelled = build([
+ START,
+ { event: 'done', ok: false, cancelled: true },
+ ] as Omit<DiagnosticsEvent, 'job'>[])
+ expect(cancelled.status).toBe('cancelled')
+
+ const errored = build([
+ START,
+ { event: 'done', ok: false, cancelled: false, error: 'deadline' },
+ ] as Omit<DiagnosticsEvent, 'job'>[])
+ expect(errored.status).toBe('error')
+ expect(errored.error).toBe('deadline')
+ })
+
+ it('keeps every failure even once passing cases are capped', () => {
+ const events: Omit<DiagnosticsEvent, 'job'>[] = [START, DEVICE]
+ for (let i = 0; i < 5200; i++) events.push(caseEvent({ params: `n=${i}` }))
+ events.push(caseEvent({ status: 'fail', error: 'late failure' }))
+ const run = build(events)
+
+ expect(run.casesTruncated).toBe(true)
+ const failures = run.cases.filter((c) => c.status === 'fail')
+ expect(failures).toHaveLength(1)
+ expect(failures[0].error).toBe('late failure')
+ })
+})
+
+describe('formatDiagnosticsReport', () => {
+ const run = () =>
+ build([
+ START,
+ DEVICE,
+ caseEvent({ status: 'fail', error: 'NMSE 0.51 > 5e-4' }),
+ probeEvent({ status: 'not_supported', op: 'SILU' }),
+ {
+ event: 'family_end',
+ device: 'CUDA0',
+ family: 'MUL_MAT',
+ status: 'crashed',
+ ok: 0,
+ failed: 1,
+ not_supported: 1,
+ millis: 900,
+ exit: 'exit code 0xC0000005',
+ last_lines: ['ggml_cuda: device lost at /home/bob/jan/libggml-cuda.so'],
+ },
+ {
+ event: 'summary',
+ device: 'CUDA0',
+ ok: 0,
+ failed: 1,
+ not_supported: 1,
+ families_crashed: 1,
+ families_hung: 0,
+ },
+ { event: 'done', ok: false, cancelled: false },
+ ] as Omit<DiagnosticsEvent, 'job'>[])
+
+ it('leads with what a maintainer needs to reproduce', () => {
+ const md = formatDiagnosticsReport(run(), {
+ appVersion: '0.7.1',
+ os: 'Windows 11',
+ })
+ expect(md).toContain('## llama.cpp hardware check')
+ expect(md).toContain('- Jan: 0.7.1')
+ expect(md).toContain('- OS: Windows 11')
+ expect(md).toContain('llama.cpp 0.9.0 (b12110, cd959bae)')
+ expect(md).toContain('CUDA (libggml-cuda.so)')
+ })
+
+ it('names the failing device, its exit and the failing cases', () => {
+ const md = formatDiagnosticsReport(run())
+ expect(md).toContain('### CUDA0 - FAILED')
+ expect(md).toContain('exit code 0xC0000005')
+ expect(md).toContain('MUL_MAT: crashed')
+ expect(md).toContain('NMSE 0.51 > 5e-4')
+ expect(md).toContain('SILU: 1 of 1 cases, the whole op')
+ })
+
+ it('leaves no home directory or user name in the report', () => {
+ const md = formatDiagnosticsReport(run())
+ expect(md).not.toContain('/home/bob')
+ expect(md).toContain('~/jan/libggml-cuda.so')
+ })
+
+ // The stop reason is engine-sourced like the rest: a spawn failure quotes
+ // the worker's own path, which lives under the user's home.
+ it('strips the home directory out of the stop reason too', () => {
+ const md = formatDiagnosticsReport(
+ build([
+ START,
+ DEVICE,
+ {
+ event: 'done',
+ ok: false,
+ cancelled: false,
+ error:
+ 'could not start /home/bob/.local/share/jan/jan-llama-worker: No such file',
+ },
+ ] as Omit<DiagnosticsEvent, 'job'>[])
+ )
+ expect(md).not.toContain('/home/bob')
+ expect(md).toContain('~/.local/share/jan/jan-llama-worker')
+ })
+
+ it('calls out quantized failures, which every local model hits', () => {
+ expect(formatDiagnosticsReport(run())).toContain(
+ '1 of the failures is in a quantized kernel'
+ )
+ })
+
+ it('lists only failures until all cases are asked for', () => {
+ const brief = formatDiagnosticsReport(run())
+ expect(brief).toContain('### Failing cases (1)')
+ expect(brief).not.toContain('### All cases')
+
+ const full = formatDiagnosticsReport(run(), {}, { allCases: true })
+ expect(full).toContain('### All cases')
+ expect(full).toContain('not_supported')
+ })
+
+ it('escapes a pipe so one error cannot break the table', () => {
+ const r = build([
+ START,
+ DEVICE,
+ caseEvent({ status: 'fail', error: 'a | b' }),
+ ] as Omit<DiagnosticsEvent, 'job'>[])
+ expect(formatDiagnosticsReport(r)).toContain('a \\| b')
+ })
+ // The support probe asks the whole op list, then the test run re-reports the
+ // same ops. Summing both counted every quick-preset family twice, which is
+ // what made a partly-supported MUL_MAT read as thousands of missing cases.
+ it('counts support from the probe alone, not the probe plus the test run', () => {
+ const run = build([
+ START,
+ DEVICE,
+ probeEvent({ op: 'MUL_MAT', params: 'a' }),
+ probeEvent({ status: 'not_supported', op: 'MUL_MAT', params: 'b' }),
+ // The same op, run again in test mode: must not be added on top.
+ caseEvent({ op: 'MUL_MAT', params: 'a' }),
+ caseEvent({ status: 'not_supported', op: 'MUL_MAT', params: 'b' }),
+ ] as Omit<DiagnosticsEvent, 'job'>[])
+
+ const [mulmat] = unsupportedOps(run.devices[0])
+ expect([mulmat.ok, mulmat.notSupported]).toEqual([1, 1])
+ })
+})
diff --git a/web-app/src/lib/__tests__/diagnosticsSuggestions.test.ts b/web-app/src/lib/__tests__/diagnosticsSuggestions.test.ts
new file mode 100644
index 000000000..e8cab44f1
--- /dev/null
+++ b/web-app/src/lib/__tests__/diagnosticsSuggestions.test.ts
@@ -0,0 +1,207 @@
+import { describe, expect, it } from 'vitest'
+import type { DiagnosticsEvent } from '@janhq/tauri-plugin-llamacpp-api'
+
+import { diagnosticsSuggestions } from '@/lib/diagnosticsSuggestions'
+import {
+ applyDiagnosticsEvent,
+ type DiagnosticsRun,
+} from '@/hooks/useLlamacppDiagnostics'
+
+const JOB = 'suggest-job'
+
+function build(events: Omit<DiagnosticsEvent, 'job'>[]): DiagnosticsRun {
+ let run: DiagnosticsRun = {
+ job: JOB,
+ status: 'running',
+ preset: 'model',
+ backendModules: [],
+ devices: [],
+ cases: [],
+ casesTruncated: false,
+ totalUnits: 0,
+ finishedUnits: 0,
+ startedAt: 0,
+ }
+ for (const event of events) {
+ run = applyDiagnosticsEvent(run, { ...event, job: JOB } as DiagnosticsEvent)
+ }
+ return run
+}
+
+const device = (name: string) =>
+ ({
+ event: 'device',
+ name,
+ description: `${name} device`,
+ type: name === 'CPU' ? 'cpu' : 'gpu',
+ reg: name.replace(/\d+$/, ''),
+ }) as const
+
+const summary = (
+ name: string,
+ over: Partial<{
+ ok: number
+ failed: number
+ not_supported: number
+ families_crashed: number
+ families_hung: number
+ families_no_cases: number
+ }> = {}
+) =>
+ ({
+ event: 'summary',
+ device: name,
+ ok: 1000,
+ failed: 0,
+ not_supported: 0,
+ families_crashed: 0,
+ families_hung: 0,
+ families_no_cases: 0,
+ ...over,
+ }) as const
+
+const failingCase = (name: string, op: string, params: string) =>
+ ({
+ event: 'case',
+ device: name,
+ family: op,
+ backend: name,
+ op,
+ params,
+ mode: 'test',
+ status: 'fail',
+ }) as const
+
+/**
+ * An unsupported case as the *support probe* reports it. Only probe cases
+ * feed `opSupport`; the test run re-reports the same ops, and counting both
+ * would double every quick-preset family.
+ */
+const fallbackCase = (name: string, op: string) =>
+ ({
+ event: 'case',
+ device: name,
+ family: '*',
+ backend: name,
+ op,
+ params: 'type=f32',
+ mode: 'support',
+ status: 'not_supported',
+ }) as const
+
+const ids = (run: DiagnosticsRun) => diagnosticsSuggestions(run).map((s) => s.id)
+
+describe('diagnosticsSuggestions', () => {
+ it('says nothing about a machine where everything worked', () => {
+ const run = build([device('CUDA0'), summary('CUDA0')])
+ expect(diagnosticsSuggestions(run)).toEqual([])
+ })
+
+ it('offers the healthy device only when there is one to offer', () => {
+ const alone = build([
+ device('CUDA0'),
+ failingCase('CUDA0', 'MUL_MAT', 'type_a=q4_K,m=4096'),
+ summary('CUDA0', { failed: 1 }),
+ ])
+ expect(ids(alone)).not.toContain('tryAnotherDevice')
+
+ const paired = build([
+ device('CUDA0'),
+ device('CPU'),
+ failingCase('CUDA0', 'MUL_MAT', 'type_a=q4_K,m=4096'),
+ summary('CUDA0', { failed: 1 }),
+ summary('CPU'),
+ ])
+ const swap = diagnosticsSuggestions(paired).find(
+ (s) => s.id === 'tryAnotherDevice'
+ )
+ expect(swap?.values).toEqual({ device: 'CUDA0', alternative: 'CPU' })
+ // The evidence is a plain-language group, never a ggml op name.
+ expect(swap?.groups).toEqual(['matrixMath'])
+ })
+
+ it('reads a dead test process as a memory or driver problem', () => {
+ const run = build([
+ device('Vulkan0'),
+ summary('Vulkan0', { families_crashed: 1, families_hung: 1 }),
+ ])
+ const advice = diagnosticsSuggestions(run).find(
+ (s) => s.id === 'reduceGpuLayers'
+ )
+ expect(advice?.values).toEqual({ device: 'Vulkan0', count: 2 })
+ })
+
+ it('offers turning flash attention off when the attention kernels are wrong', () => {
+ const run = build([
+ device('CUDA0'),
+ failingCase('CUDA0', 'FLASH_ATTN_EXT', 'hsk=128,hsv=128,type_K=f16'),
+ summary('CUDA0', { failed: 1 }),
+ ])
+ const advice = diagnosticsSuggestions(run).find(
+ (s) => s.id === 'disableFlashAttention'
+ )
+ expect(advice?.values).toEqual({ device: 'CUDA0', count: 1 })
+ })
+
+ // The advice reads "while the uncompressed ones passed", so it belongs to
+ // the run where *every* failure is a compressed one. When plain kernels
+ // fail too the quantization is not what singles this machine out, and a
+ // differently compressed download will not help.
+ it('blames the compression only when the uncompressed kernels passed', () => {
+ const onlyQuantized = build([
+ device('CUDA0'),
+ failingCase('CUDA0', 'MUL_MAT', 'type_a=q4_K,m=4096'),
+ summary('CUDA0', { failed: 1, ok: 100 }),
+ ])
+ expect(ids(onlyQuantized)).toContain('useAnotherQuantization')
+
+ const mixed = build([
+ device('CUDA0'),
+ failingCase('CUDA0', 'MUL_MAT', 'type_a=q4_K,m=4096'),
+ failingCase('CUDA0', 'MUL_MAT', 'type_a=f16,m=4096'),
+ summary('CUDA0', { failed: 2, ok: 100 }),
+ ])
+ expect(ids(mixed)).not.toContain('useAnotherQuantization')
+
+ // Nothing passed, so nothing supports "the uncompressed ones passed".
+ const nothingPassed = build([
+ device('CUDA0'),
+ failingCase('CUDA0', 'MUL_MAT', 'type_a=q4_K,m=4096'),
+ summary('CUDA0', { failed: 1, ok: 0 }),
+ ])
+ expect(ids(nothingPassed)).not.toContain('useAnotherQuantization')
+ })
+
+ it('offers the offload note for an accelerator, as advice not a fault', () => {
+ const run = build([
+ device('Vulkan0'),
+ fallbackCase('Vulkan0', 'SILU'),
+ fallbackCase('Vulkan0', 'GELU'),
+ summary('Vulkan0', { not_supported: 2 }),
+ ])
+ const advice = diagnosticsSuggestions(run)
+ expect(advice.map((s) => s.id)).toEqual(['expectCpuFallback'])
+ expect(advice[0].values).toEqual({ device: 'Vulkan0', count: 2 })
+ })
+
+ // The whole point of the phase: a narrowed run that covered nothing has to
+ // say so, or the user acts on a result that was never measured.
+ it('always asks for a full run when a family matched no test case', () => {
+ const run = build([
+ device('CUDA0'),
+ summary('CUDA0', { families_no_cases: 3 }),
+ ])
+ const advice = diagnosticsSuggestions(run).find(
+ (s) => s.id === 'rerunWholeCheck'
+ )
+ expect(advice?.values).toEqual({ device: 'CUDA0', count: 3 })
+ })
+
+ it('says nothing from a device still running', () => {
+ const run = build([
+ device('CUDA0'),
+ failingCase('CUDA0', 'MUL_MAT', 'type_a=q4_K,m=4096'),
+ ])
+ expect(diagnosticsSuggestions(run)).toEqual([])
+ })
+})
diff --git a/web-app/src/lib/__tests__/engineError.test.ts b/web-app/src/lib/__tests__/engineError.test.ts
index a9e14d6ec..f8e6c529a 100644
--- a/web-app/src/lib/__tests__/engineError.test.ts
+++ b/web-app/src/lib/__tests__/engineError.test.ts
@@ -14,6 +14,8 @@ import {
parseEngineError,
describeEngineError,
engineFailure,
+ formatLoadDiagnostics,
+ stripLocalPaths,
ENGINE_ERROR_CODES,
} from '../engineError'
@@ -252,3 +254,133 @@ describe('engineFailure', () => {
expect(wrapped.message).toContain('GPU fail')
})
})
+
+describe('formatLoadDiagnostics', () => {
+ const failure = {
+ code: 'MODEL_LOAD_FAILED',
+ details: 'failed to load model; open /home/bob/models/qwen.gguf failed',
+ diagnostics: {
+ model_file: 'qwen.gguf',
+ architecture: 'qwen3',
+ quantization: 'Q4_K_M',
+ request: { ctx_size: '8192', n_gpu_layers: '20', flash_attn: null },
+ gpus: [
+ {
+ name: 'NVIDIA RTX 4090',
+ driver_version: '560.35',
+ total_mib: 24564,
+ free_mib: 20000,
+ },
+ ],
+ backends: ['CUDA (libggml-cuda.so)'],
+ engine: { version: '0.9.0', tag: 'b12110', commit: 'a'.repeat(40) },
+ log: 'load_tensors: loading /home/bob/models/qwen.gguf\nC:\\Users\\bob\\x.dll failed',
+ log_truncated: true,
+ },
+ }
+
+ it('reports the request, devices, engine and log as markdown', () => {
+ const text = formatLoadDiagnostics(failure, {
+ appVersion: '0.9.0',
+ os: 'linux',
+ })!
+
+ expect(text).toContain('- Model file: qwen.gguf')
+ expect(text).toContain('- Architecture: qwen3')
+ expect(text).toContain('- ctx_size: 8192')
+ expect(text).not.toContain('flash_attn')
+ expect(text).toContain(
+ 'NVIDIA RTX 4090 (driver 560.35, 24564 MiB, 20000 MiB free)'
+ )
+ expect(text).toContain('- CUDA (libggml-cuda.so)')
+ expect(text).toContain('- llama.cpp: 0.9.0 (b12110, aaaaaaaaaaaa)')
+ expect(text).toContain('Engine log (older lines dropped)')
+ })
+
+ it('leaves no home directory or user name in the copied text', () => {
+ const text = formatLoadDiagnostics(failure)!
+
+ expect(text).not.toContain('bob')
+ expect(text).toContain('~/models/qwen.gguf')
+ })
+
+ it('has nothing to report for an error without diagnostics', () => {
+ expect(formatLoadDiagnostics({ code: 'MODEL_LOAD_FAILED' })).toBeUndefined()
+ expect(formatLoadDiagnostics(new Error('plain'))).toBeUndefined()
+ })
+
+ it('reads diagnostics from an error that was stringified or wrapped', () => {
+ const wrapped = new Error('outer') as Error & { cause?: unknown }
+ wrapped.cause = failure
+ expect(formatLoadDiagnostics(wrapped)).toContain('Model load failure')
+ expect(formatLoadDiagnostics(new Error(JSON.stringify(failure)))).toContain(
+ 'qwen.gguf'
+ )
+ })
+})
+
+describe('stripLocalPaths', () => {
+ it('replaces home directories on every platform', () => {
+ expect(
+ stripLocalPaths('/home/alice/a /Users/bob/b C:\\Users\\carol\\c')
+ ).toBe('~/a ~/b ~\\c')
+ })
+
+ it('still strips a home directory with nothing after it', () => {
+ expect(stripLocalPaths('cannot open /home/alice')).toBe('cannot open ~')
+ })
+
+ // The shape-guessing fallback stops at whitespace, so it can neither eat
+ // the prose between two paths nor turn an unrelated path into one under
+ // the home directory.
+ it('never reaches across prose into another path', () => {
+ expect(
+ stripLocalPaths('cannot open /home/bob and /usr/lib/libggml.so')
+ ).toBe('cannot open ~ and /usr/lib/libggml.so')
+ expect(stripLocalPaths('cannot open /home/bob and models/x.gguf')).toBe(
+ 'cannot open ~ and models/x.gguf'
+ )
+ expect(
+ stripLocalPaths('C:\\Users\\bob and C:\\Windows\\System32\\x.dll')
+ ).toBe('~ and C:\\Windows\\System32\\x.dll')
+ })
+
+ // Knowing the directory is what makes a name with a space safe: there is no
+ // rule over the text alone that tells `/home/Jo Smith/lib` apart from
+ // `/home/bob and models/x.gguf`.
+ it('takes a spaced or non-ASCII profile name when the home is known', () => {
+ expect(
+ stripLocalPaths(
+ 'C:\\Users\\Jo Smith\\AppData\\jan',
+ 'C:\\Users\\Jo Smith'
+ )
+ ).toBe('~\\AppData\\jan')
+ expect(
+ stripLocalPaths('/Users/Jos\u00e9 Garc\u00eda/Library/jan', '/Users/Jos\u00e9 Garc\u00eda')
+ ).toBe('~/Library/jan')
+ expect(
+ stripLocalPaths("/home/Se\u00e1n O'Brien/models", "/home/Se\u00e1n O'Brien/")
+ ).toBe('~/models')
+ })
+
+ // A bare substring replace turned `/home/bobby` into `~by`, and having
+ // eaten the `/home/` the fallback could no longer recognise what was left.
+ it('does not match a longer name that merely starts with the home', () => {
+ expect(stripLocalPaths('/home/bobby/x.gguf', '/home/bob')).toBe('~/x.gguf')
+ expect(
+ stripLocalPaths('C:\\Users\\bobby\\x.gguf', 'C:\\Users\\bob')
+ ).toBe('~\\x.gguf')
+ })
+
+ it('matches the home directory written with either separator', () => {
+ expect(
+ stripLocalPaths('C:/Users/Jo Smith/jan', 'C:\\Users\\Jo Smith')
+ ).toBe('~/jan')
+ })
+
+ it('leaves the prose alone even when a home is known', () => {
+ expect(
+ stripLocalPaths('cannot open /home/Jo Smith and models/x.gguf', '/home/Jo Smith')
+ ).toBe('cannot open ~ and models/x.gguf')
+ })
+})
diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.ts
index 8fef933f0..e08d4536b 100644
--- a/web-app/src/lib/custom-chat-transport.ts
+++ b/web-app/src/lib/custom-chat-transport.ts
@@ -1414,6 +1414,37 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
useAppState
.getState()
.setCurrentStreamThreadId(threadId, this.streamRoutesToCowork)
+ try {
+ return await this.openStream(options, threadId, myGeneration)
+ } catch (error) {
+ // No stream exists yet, so its onError/onFinish will never release this.
+ this.releaseStream(threadId, myGeneration)
+ throw error
+ }
+ }
+
+ /**
+ * Clears the per-request UI state, unless a newer request (e.g. after
+ * Reload) has since taken it over.
+ */
+ private releaseStream(threadId: string, generation: number) {
+ if (this.streamGeneration !== generation) return
+ const app = useAppState.getState()
+ app.updatePromptProgress(undefined)
+ app.updateThreadPromptProgress(threadId, undefined)
+ this.setLoadingModel(threadId, false)
+ app.updateLiveTokenStats(undefined)
+ app.updateThreadLiveTokenStats(threadId, undefined)
+ if (app.currentStreamThreadId === threadId) {
+ app.setCurrentStreamThreadId(undefined)
+ }
+ }
+
+ private async openStream(
+ options: Parameters<CustomChatTransport['sendMessages']>[0],
+ threadId: string,
+ myGeneration: number
+ ): Promise<ReadableStream<UIMessageChunk>> {
// Capture the effective provider name early so the Anthropic serial
// tool-use repair later uses the same value that was used to create the
// model, even if the user switches provider mid-request.
@@ -1725,18 +1756,7 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
// streaming surface shares (see `lib/stepMetadata`).
messageMetadata: ({ part }) => stepMetadata.onPart(part),
onError: (error) => {
- // A superseded request (e.g. after Reload) must not clear loading/stream
- // state the newer request already owns.
- if (this.streamGeneration === myGeneration) {
- useAppState.getState().updatePromptProgress(undefined)
- useAppState.getState().updateThreadPromptProgress(threadId, undefined)
- this.setLoadingModel(threadId, false)
- useAppState.getState().updateLiveTokenStats(undefined)
- useAppState.getState().updateThreadLiveTokenStats(threadId, undefined)
- if (useAppState.getState().currentStreamThreadId === threadId) {
- useAppState.getState().setCurrentStreamThreadId(undefined)
- }
- }
+ this.releaseStream(threadId, myGeneration)
const unwrapped = unwrapRetryError(error)
const rawMessage = unwrapped == null
? 'Unknown error'
@@ -1754,16 +1774,7 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
return baseMessage
},
onFinish: ({ responseMessage }) => {
- if (this.streamGeneration === myGeneration) {
- useAppState.getState().updatePromptProgress(undefined)
- useAppState.getState().updateThreadPromptProgress(threadId, undefined)
- this.setLoadingModel(threadId, false)
- useAppState.getState().updateLiveTokenStats(undefined)
- useAppState.getState().updateThreadLiveTokenStats(threadId, undefined)
- if (useAppState.getState().currentStreamThreadId === threadId) {
- useAppState.getState().setCurrentStreamThreadId(undefined)
- }
- }
+ this.releaseStream(threadId, myGeneration)
if (responseMessage) {
const metadata = responseMessage.metadata as
| Record<string, unknown>
diff --git a/web-app/src/lib/diagnosticsGroups.ts b/web-app/src/lib/diagnosticsGroups.ts
new file mode 100644
index 000000000..42745f5fd
--- /dev/null
+++ b/web-app/src/lib/diagnosticsGroups.ts
@@ -0,0 +1,274 @@
+import type {
+ DiagnosticsCaseStatus,
+ DiagnosticsDeviceKind,
+ DiagnosticsFamilyStatus,
+} from '@janhq/tauri-plugin-llamacpp-api'
+
+import type { DiagnosticsDeviceRun } from '@/hooks/useLlamacppDiagnostics'
+
+/**
+ * Turning ggml op names into something a person can act on.
+ *
+ * Upstream has 150+ op families keyed on `op_desc`, which is the right unit for
+ * running the test and the wrong one for reading the result: nobody knows what
+ * `MUL_MAT_ID_FUSION` is, and a list of 150 rows answers no question. These
+ * groups are the question a user actually has -- "is the part my model leans on
+ * broken?" -- and the detail table behind them keeps every original name.
+ */
+
+/** Ordered: the first rule that matches an op wins, so specific rules lead. */
+export const DIAGNOSTICS_GROUPS = [
+ 'matrixMath',
+ 'attention',
+ 'normalization',
+ 'positional',
+ 'convolution',
+ 'activation',
+ 'memory',
+ 'basicMath',
+ 'other',
+] as const
+
+export type DiagnosticsGroup = (typeof DIAGNOSTICS_GROUPS)[number]
+
+const ACTIVATIONS = new Set([
+ 'ABS',
+ 'CLAMP',
+ 'COS',
+ 'ELU',
+ 'EXP',
+ 'FLOOR',
+ 'GELU',
+ 'GELU_ERF',
+ 'GELU_QUICK',
+ 'HARDSIGMOID',
+ 'HARDSWISH',
+ 'LEAKY_RELU',
+ 'LOG',
+ 'NEG',
+ 'RELU',
+ 'RELU_SQR',
+ 'ROUND',
+ 'SGN',
+ 'SIGMOID',
+ 'SILU',
+ 'SILU_BACK',
+ 'SIN',
+ 'SOFTCAP',
+ 'SOFT_PLUS',
+ 'SQR',
+ 'SQRT',
+ 'STEP',
+ 'TANH',
+ 'TRUNC',
+ 'XIELU',
+])
+
+const MEMORY_OPS = new Set([
+ 'ACC',
+ 'ARANGE',
+ 'CONCAT',
+ 'CONT',
+ 'CPY',
+ 'DIAG',
+ 'DUP',
+ 'GET_ROWS',
+ 'GET_ROWS_BACK',
+ 'PAD',
+ 'PAD_REFLECT_1D',
+ 'PERMUTE',
+ 'REPEAT',
+ 'REPEAT_BACK',
+ 'RESHAPE',
+ 'ROLL',
+ 'SET',
+ 'SET_ROWS',
+ 'TRANSPOSE',
+ 'TRI',
+ 'VIEW',
+])
+
+const BASIC_MATH = new Set([
+ 'ADD',
+ 'ADD1',
+ 'ADD_ID',
+ 'ARGMAX',
+ 'ARGSORT',
+ 'COUNT_EQUAL',
+ 'CUMSUM',
+ 'DIV',
+ 'MEAN',
+ 'MUL',
+ 'SCALE',
+ 'SUB',
+ 'SUM',
+ 'SUM_ROWS',
+])
+
+/**
+ * Which group an op belongs to. Order matters: a fused op carries several
+ * names (`RMS_NORM_MUL_ROPE`), and the leading rule is the one that describes
+ * what it is for -- it is a normalization kernel, not a rope one.
+ */
+export function groupForOp(op: string): DiagnosticsGroup {
+ const name = op.toUpperCase()
+ if (name.startsWith('MUL_MAT') || name === 'OUT_PROD') return 'matrixMath'
+ if (
+ name.includes('FLASH_ATTN') ||
+ name.includes('SOFT_MAX') ||
+ name.startsWith('DIAG_MASK') ||
+ name.includes('TOP_K') ||
+ name.includes('TOPK') ||
+ name.startsWith('SSM_') ||
+ name.startsWith('RWKV') ||
+ name.includes('DELTA_NET') ||
+ name.includes('LINEAR_ATTN')
+ ) {
+ return 'attention'
+ }
+ if (name.includes('NORM')) return 'normalization'
+ if (name.includes('ROPE')) return 'positional'
+ if (
+ name.startsWith('CONV') ||
+ name.startsWith('IM2COL') ||
+ name.startsWith('POOL')
+ ) {
+ return 'convolution'
+ }
+ if (ACTIVATIONS.has(name) || name.includes('GLU')) return 'activation'
+ if (MEMORY_OPS.has(name)) return 'memory'
+ if (BASIC_MATH.has(name)) return 'basicMath'
+ return 'other'
+}
+
+/**
+ * Whether a case exercises a quantized kernel, which is read off the
+ * parameters rather than the op: quantization is a property of the tensor
+ * types a case runs with, and the same `MUL_MAT` covers both. Worth singling
+ * out because every local model is quantized, so a failure here is one a user
+ * will actually hit.
+ */
+export function isQuantizedCase(params: string): boolean {
+ return /\b(?:type|type_a|type_b)=(?:q\d|iq\d|mxfp|tq\d)/i.test(params)
+}
+
+/** A device's overall verdict. Ordered worst to best; see `deviceVerdict`. */
+export type DeviceVerdict =
+ | 'failed'
+ | 'inconclusive'
+ | 'fallback'
+ | 'passed'
+ | 'unknown'
+
+export interface DeviceTally {
+ ok: number
+ failed: number
+ notSupported: number
+ crashed: number
+ hung: number
+ /**
+ * Families whose shape filter matched no case, so they tested nothing. A
+ * narrowed run that silently covered none of what it named is the one wrong
+ * answer a diagnostic must not give, so it outranks a pass.
+ */
+ noCases: number
+ /**
+ * Families the run never reached, because it was cancelled or passed its
+ * deadline. Like [`noCases`] it outranks a pass: the families that did run
+ * say nothing about the ones that did not.
+ */
+ cancelled: number
+ /** False while families are still running, which makes the verdict partial. */
+ complete: boolean
+ /**
+ * Whether an op this device lacks would be run somewhere else. True for a
+ * GPU or accelerator; false for the CPU, which *is* ggml's fallback. See
+ * [`hasCpuFallback`].
+ */
+ canOffload: boolean
+}
+
+/**
+ * Whether ggml has anywhere to send an op this device does not implement.
+ *
+ * The CPU is the fallback of last resort, so a case it has no kernel for is
+ * not deferred anywhere -- it is simply absent. Calling that "runs on the
+ * processor" on the CPU's own row is circular, and calling it "slower" names
+ * no faster path that exists.
+ */
+export function hasCpuFallback(kind: DiagnosticsDeviceKind): boolean {
+ return kind !== 'cpu'
+}
+
+/**
+ * The one-line answer for a device.
+ *
+ * A crashed or hung family counts as failed: the user's model would have died
+ * the same way. `fallback` is deliberately not a failure -- an accelerator
+ * that lacks an op has it run on the CPU instead, which costs speed and
+ * nothing else, and saying otherwise would send people chasing a non-problem.
+ *
+ * On the CPU itself an unsupported case is not a fallback and not a fault. The
+ * check enumerates type combinations exhaustively, including backward/training
+ * ops (`GET_ROWS_BACK`, `SOFT_MAX_BACK`, most of `OUT_PROD`) that inference
+ * never builds, so every machine reports some. Those ops are also only
+ * *partially* unsupported -- the CPU has a `MUL_MAT` kernel for 2630 of its
+ * 3090 cases -- so naming the op would overstate it too.
+ */
+export function deviceVerdict(tally: DeviceTally): DeviceVerdict {
+ if (tally.failed > 0 || tally.crashed > 0 || tally.hung > 0) return 'failed'
+ // Before the `ok === 0` check below: a narrowed run whose filter matched no
+ // case has no passes behind it either, and "Not checked" would say the run
+ // never happened when in fact it finished and covered nothing it named.
+ if (tally.noCases > 0) return 'inconclusive'
+ // Nothing ran at all -- still going, or stopped before the first case. That
+ // really is "not checked", which is why this sits above the partial test.
+ if (tally.ok === 0) return 'unknown'
+ // A partial device is inconclusive for the same reason: a run cut short by
+ // the user or by its deadline has no evidence about the families it never
+ // reached, and reporting the ones it did reach as a clean bill of health is
+ // the wrong answer this verdict exists to prevent.
+ if (tally.cancelled > 0 || !tally.complete) {
+ return 'inconclusive'
+ }
+ if (tally.notSupported > 0 && tally.canOffload) return 'fallback'
+ return 'passed'
+}
+
+/**
+ * The tally for one device of a run. The single place the verdict inputs are
+ * assembled, so the panel, the report and the suggestions cannot disagree
+ * about what a device's result was.
+ */
+export function tallyOf(device: DiagnosticsDeviceRun): DeviceTally {
+ return {
+ ok: device.ok,
+ failed: device.failed,
+ notSupported: device.notSupported,
+ crashed: device.crashed,
+ hung: device.hung,
+ noCases: device.noCases,
+ cancelled: device.cancelled,
+ complete: device.complete,
+ canOffload: hasCpuFallback(device.device.type),
+ }
+}
+
+/** A family status that means the leaf itself went wrong, not a kernel. */
+export function isProcessFailure(status: DiagnosticsFamilyStatus): boolean {
+ return status === 'crashed' || status === 'hung'
+}
+
+/**
+ * A family that completed having tested nothing. Not a failure and not a
+ * pass: the shapes it was narrowed to do not exist in this llama.cpp, so the
+ * run has no evidence either way.
+ */
+export function isInconclusive(status: DiagnosticsFamilyStatus): boolean {
+ return status === 'no_cases'
+}
+
+/** Whether a case outcome should draw the eye. */
+export function isCaseFailure(status: DiagnosticsCaseStatus): boolean {
+ return status === 'fail'
+}
diff --git a/web-app/src/lib/diagnosticsReport.ts b/web-app/src/lib/diagnosticsReport.ts
new file mode 100644
index 000000000..60b6de5e6
--- /dev/null
+++ b/web-app/src/lib/diagnosticsReport.ts
@@ -0,0 +1,178 @@
+import { stripLocalPaths } from '@/lib/engineError'
+import {
+ deviceVerdict,
+ isQuantizedCase,
+ tallyOf,
+} from '@/lib/diagnosticsGroups'
+
+import {
+ unsupportedOps,
+ type DiagnosticsDeviceRun,
+ type DiagnosticsRun,
+} from '@/hooks/useLlamacppDiagnostics'
+
+/** Ops whose example parameters are quoted; enough to diagnose, not a dump. */
+const REPORTED_OPS = 3
+
+const VERDICT_TEXT: Record<string, string> = {
+ passed: 'all checks passed',
+ fallback: 'all checks passed, some ops run on the CPU',
+ inconclusive: 'INCOMPLETE - some families were not checked',
+ failed: 'FAILED',
+ unknown: 'did not finish',
+}
+
+function memory(device: DiagnosticsDeviceRun): string {
+ const { memory_free_mib: free, memory_total_mib: total } = device.device
+ if (total === undefined) return ''
+ const gib = (mib: number) => `${(mib / 1024).toFixed(1)} GB`
+ return free === undefined
+ ? `, ${gib(total)}`
+ : `, ${gib(free)} free of ${gib(total)}`
+}
+
+function deviceSection(
+ device: DiagnosticsDeviceRun,
+ home?: string | null
+): string[] {
+ const verdict = deviceVerdict(tallyOf(device))
+ const lines = [
+ `### ${device.device.name} - ${VERDICT_TEXT[verdict]}`,
+ '',
+ `- Device: ${device.device.description} (${device.device.reg}${memory(device)})`,
+ `- Cases: ${device.ok} passed, ${device.failed} failed, ${device.notSupported} not supported`,
+ ]
+ if (device.crashed > 0 || device.hung > 0) {
+ lines.push(
+ `- Families that did not complete: ${device.crashed} crashed, ${device.hung} hung`
+ )
+ }
+ // Named explicitly in the report, not just implied by a low case count: a
+ // reader comparing two pastes has no other way to tell a narrowed run that
+ // covered nothing from one that covered everything.
+ if (device.noCases > 0) {
+ lines.push(`- Families that matched no test case: ${device.noCases}`)
+ }
+ // Ratios, not bare op names. An op is usually only partly unsupported, and
+ // "Falls back to CPU: MUL_MAT" reads as "this device cannot multiply
+ // matrices" when 2630 of its 3090 cases ran fine.
+ const unsupported = unsupportedOps(device)
+ if (unsupported.length > 0) {
+ const offloads = tallyOf(device).canOffload
+ const n = `${unsupported.length} op${unsupported.length === 1 ? '' : 's'}`
+ lines.push(
+ '',
+ offloads
+ ? `**Runs on the CPU instead** (${n})`
+ : `**No kernel on this device** (${n})`,
+ ''
+ )
+ for (const op of unsupported) {
+ const total = op.ok + op.notSupported
+ const whole = op.ok === 0 ? ', the whole op' : ''
+ lines.push(`- ${op.op}: ${op.notSupported} of ${total} cases${whole}`)
+ }
+ // The parameters are the answer to "which MUL_MAT?"; a bare op name is
+ // not actionable. Only for partial ops -- for a whole missing op the name
+ // already says it.
+ const partial = unsupported.filter((o) => o.ok > 0).slice(0, REPORTED_OPS)
+ if (partial.length > 0) {
+ lines.push('', 'Examples of the cases with no kernel:', '')
+ for (const op of partial) {
+ for (const params of op.examples) {
+ lines.push(`- \`${op.op} ${params}\``)
+ }
+ }
+ }
+ }
+
+ const broken = device.families.filter((f) => f.status !== 'ok')
+ for (const family of broken) {
+ lines.push('', `**${family.family}: ${family.status}**`)
+ if (family.exit) lines.push(`- Exit: ${family.exit}`)
+ for (const line of family.lastLines) {
+ lines.push(`- \`${stripLocalPaths(line, home)}\``)
+ }
+ }
+ return lines
+}
+
+export interface DiagnosticsReportContext {
+ appVersion?: string
+ os?: string
+ /** The real home directory, so paths are stripped by knowing, not guessing. */
+ home?: string | null
+}
+
+/**
+ * A markdown report of a hardware check, for pasting into an issue.
+ *
+ * Built from the run already in memory and handed to the caller to put on the
+ * clipboard. Nothing is sent anywhere, and `stripLocalPaths` -- the same one
+ * the load-failure report uses -- takes the user's home directory out of
+ * anything llama.cpp printed.
+ */
+export function formatDiagnosticsReport(
+ run: DiagnosticsRun,
+ context: DiagnosticsReportContext = {},
+ options: { allCases?: boolean } = {}
+): string {
+ const lines: string[] = ['## llama.cpp hardware check', '']
+
+ if (context.appVersion) lines.push(`- Jan: ${context.appVersion}`)
+ if (context.os) lines.push(`- OS: ${context.os}`)
+ if (run.engine) {
+ lines.push(
+ `- Engine: llama.cpp ${run.engine.version} (${run.engine.tag}, ${run.engine.commit.slice(0, 8)})`
+ )
+ }
+ lines.push(`- Preset: ${run.preset}`)
+ if (run.model) lines.push(`- Model: ${run.model}`)
+ lines.push(`- Result: ${run.status}`)
+ // Stripped like every other engine-sourced string here: a spawn or exit
+ // failure quotes the worker's path, which is under the user's home.
+ if (run.error) lines.push(`- Stopped: ${stripLocalPaths(run.error, context.home)}`)
+ if (run.backendModules.length > 0) {
+ lines.push(`- Backend modules: ${run.backendModules.join(', ')}`)
+ }
+
+ for (const device of run.devices) {
+ lines.push('', ...deviceSection(device, context.home))
+ }
+
+ const failures = run.cases.filter((c) => c.status === 'fail')
+ const shown = options.allCases ? run.cases : failures
+ if (shown.length > 0) {
+ lines.push(
+ '',
+ options.allCases ? '### All cases' : `### Failing cases (${failures.length})`,
+ '',
+ '| Device | Op | Parameters | Status | Error |',
+ '| --- | --- | --- | --- | --- |'
+ )
+ for (const c of shown) {
+ const error = c.error ?? c.detail ?? ''
+ lines.push(
+ `| ${c.device} | ${c.op} | \`${c.params}\` | ${c.status} | ${stripLocalPaths(error, context.home).replace(/\|/g, '\\|').replace(/\n/g, ' ')} |`
+ )
+ }
+ if (options.allCases && run.casesTruncated) {
+ lines.push(
+ '',
+ `_Passing cases beyond the first ${run.cases.length} were not kept; every failure is listed._`
+ )
+ }
+ }
+
+ const quantized = failures.filter((c) => isQuantizedCase(c.params))
+ if (quantized.length > 0) {
+ lines.push(
+ '',
+ quantized.length === 1
+ ? '1 of the failures is in a quantized kernel, which every local model uses.'
+ : `${quantized.length} of the failures are in quantized kernels, which every local model uses.`
+ )
+ }
+
+ return lines.join('\n')
+}
diff --git a/web-app/src/lib/diagnosticsSuggestions.ts b/web-app/src/lib/diagnosticsSuggestions.ts
new file mode 100644
index 000000000..870a3c7a1
--- /dev/null
+++ b/web-app/src/lib/diagnosticsSuggestions.ts
@@ -0,0 +1,173 @@
+import {
+ deviceVerdict,
+ groupForOp,
+ isQuantizedCase,
+ tallyOf,
+ type DeviceVerdict,
+ type DiagnosticsGroup,
+} from '@/lib/diagnosticsGroups'
+import {
+ unsupportedOps,
+ type DiagnosticsRun,
+} from '@/hooks/useLlamacppDiagnostics'
+
+/**
+ * What to do about a check's result.
+ *
+ * A list of failing kernels is a finding, not an answer: the question the user
+ * actually has is "so what do I change?". Each suggestion here is drawn from a
+ * specific, named observation and carries it, so nothing has to be taken on
+ * trust -- and nothing is offered that the run did not actually observe.
+ *
+ * The evidence is deliberately counts and plain-language groups rather than
+ * ggml op names: the op names live in the technical details table, which is
+ * where someone who wants them is already looking.
+ */
+export type SuggestionId =
+ | 'tryAnotherDevice'
+ | 'reduceGpuLayers'
+ | 'disableFlashAttention'
+ | 'useAnotherQuantization'
+ | 'expectCpuFallback'
+ | 'rerunWholeCheck'
+
+export interface DiagnosticsSuggestion {
+ id: SuggestionId
+ /** The device the suggestion is about. */
+ device: string
+ /** Interpolation values for the localized sentence. */
+ values: Record<string, string | number>
+ /** Groups the evidence came from, worst first; may be empty. */
+ groups: DiagnosticsGroup[]
+}
+
+/** Failing cases on one device, grouped, worst first. */
+function failedGroups(run: DiagnosticsRun, device: string): DiagnosticsGroup[] {
+ const counts = new Map<DiagnosticsGroup, number>()
+ for (const c of run.cases) {
+ if (c.device !== device || c.status !== 'fail') continue
+ const group = groupForOp(c.op)
+ counts.set(group, (counts.get(group) ?? 0) + 1)
+ }
+ return [...counts.entries()]
+ .sort((a, b) => b[1] - a[1])
+ .map(([group]) => group)
+}
+
+function attentionFailures(run: DiagnosticsRun, device: string): number {
+ return run.cases.filter(
+ (c) =>
+ c.device === device &&
+ c.status === 'fail' &&
+ c.op.toUpperCase().includes('FLASH_ATTN')
+ ).length
+}
+
+function quantizedFailures(run: DiagnosticsRun, device: string): number {
+ return run.cases.filter(
+ (c) =>
+ c.device === device && c.status === 'fail' && isQuantizedCase(c.params)
+ ).length
+}
+
+/**
+ * What the run suggests, worst first.
+ *
+ * Every rule is conditioned on a complete device: a suggestion drawn from a
+ * run still in flight would change under the user as the remaining families
+ * land.
+ */
+export function diagnosticsSuggestions(
+ run: DiagnosticsRun
+): DiagnosticsSuggestion[] {
+ const complete = run.devices.filter((d) => d.complete)
+ const verdicts = new Map<string, DeviceVerdict>(
+ complete.map((d) => [d.device.name, deviceVerdict(tallyOf(d))])
+ )
+ const healthy = complete.filter((d) => {
+ const verdict = verdicts.get(d.device.name)
+ return verdict === 'passed' || verdict === 'fallback'
+ })
+
+ const out: DiagnosticsSuggestion[] = []
+ for (const device of complete) {
+ const name = device.device.name
+ const verdict = verdicts.get(name)
+
+ if (verdict === 'failed') {
+ // Only when there is somewhere to go: "use another device" on a machine
+ // with one device is advice the user cannot take.
+ const alternative = healthy.find((d) => d.device.name !== name)
+ if (alternative) {
+ out.push({
+ id: 'tryAnotherDevice',
+ device: name,
+ values: {
+ device: name,
+ alternative: alternative.device.name,
+ },
+ groups: failedGroups(run, name),
+ })
+ }
+
+ // A family that killed its own process is what a GGML_ASSERT or a lost
+ // device looks like, and that is a memory or driver problem rather than
+ // a wrong answer, so it gets its own advice.
+ const died = device.crashed + device.hung
+ if (died > 0) {
+ out.push({
+ id: 'reduceGpuLayers',
+ device: name,
+ values: { device: name, count: died },
+ groups: [],
+ })
+ }
+
+ const attention = attentionFailures(run, name)
+ if (attention > 0) {
+ out.push({
+ id: 'disableFlashAttention',
+ device: name,
+ values: { device: name, count: attention },
+ groups: ['attention'],
+ })
+ }
+
+ // Only when the plain kernels are fine, which is what the advice says:
+ // every failure is a compressed-weight one and something uncompressed
+ // passed. With plain kernels failing too, the quantization is not what
+ // singles this machine out and a different download will not help.
+ const quantized = quantizedFailures(run, name)
+ if (quantized > 0 && quantized === device.failed && device.ok > 0) {
+ out.push({
+ id: 'useAnotherQuantization',
+ device: name,
+ values: { device: name, count: quantized },
+ groups: failedGroups(run, name),
+ })
+ }
+ }
+
+ if (verdict === 'fallback') {
+ out.push({
+ id: 'expectCpuFallback',
+ device: name,
+ values: { device: name, count: unsupportedOps(device).length },
+ groups: [],
+ })
+ }
+
+ // Last, because it is about the check rather than the machine -- but
+ // never omitted: a narrowed run that covered none of what it named must
+ // not be read as a clean bill of health.
+ if (device.noCases > 0) {
+ out.push({
+ id: 'rerunWholeCheck',
+ device: name,
+ values: { device: name, count: device.noCases },
+ groups: [],
+ })
+ }
+ }
+ return out
+}
diff --git a/web-app/src/lib/engineError.ts b/web-app/src/lib/engineError.ts
index fb3255e76..7cc911335 100644
--- a/web-app/src/lib/engineError.ts
+++ b/web-app/src/lib/engineError.ts
@@ -23,16 +23,76 @@ export const ENGINE_ERROR_CODES = [
export type EngineErrorCode = (typeof ENGINE_ERROR_CODES)[number]
+/** Mirrors `LoadDiagnostics` in `tauri-plugin-llamacpp/src/diagnostics.rs`. */
+export interface LoadDiagnostics {
+ modelFile?: string
+ architecture?: string
+ quantization?: string
+ request: Record<string, string | undefined>
+ gpus: {
+ name: string
+ driverVersion: string
+ totalMib: number
+ freeMib?: number
+ }[]
+ backends: string[]
+ engine: { version: string; tag: string; commit: string }
+ log: string
+ logTruncated: boolean
+}
+
export interface EngineError {
code: EngineErrorCode
message?: string
/** Raw engine output. Technical, shown only in a details area. */
details?: string
missingLibraries?: string[]
+ diagnostics?: LoadDiagnostics
}
const KNOWN_CODES: ReadonlySet<string> = new Set(ENGINE_ERROR_CODES)
+type Rec = Record<string, unknown>
+
+const asString = (v: unknown): string | undefined =>
+ typeof v === 'string' ? v : undefined
+
+const asNumber = (v: unknown): number | undefined =>
+ typeof v === 'number' ? v : undefined
+
+const asStrings = (v: unknown): string[] =>
+ Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : []
+
+function readDiagnostics(value: unknown): LoadDiagnostics | undefined {
+ if (typeof value !== 'object' || value === null) return undefined
+ const d = value as Rec
+ const engine = (d.engine ?? {}) as Rec
+ const request: LoadDiagnostics['request'] = {}
+ for (const [key, v] of Object.entries((d.request ?? {}) as Rec)) {
+ request[key] = asString(v)
+ }
+ return {
+ modelFile: asString(d.model_file),
+ architecture: asString(d.architecture),
+ quantization: asString(d.quantization),
+ request,
+ gpus: (Array.isArray(d.gpus) ? (d.gpus as Rec[]) : []).map((g) => ({
+ name: asString(g.name) ?? '',
+ driverVersion: asString(g.driver_version) ?? '',
+ totalMib: asNumber(g.total_mib) ?? 0,
+ freeMib: asNumber(g.free_mib),
+ })),
+ backends: asStrings(d.backends),
+ engine: {
+ version: asString(engine.version) ?? '',
+ tag: asString(engine.tag) ?? '',
+ commit: asString(engine.commit) ?? '',
+ },
+ log: asString(d.log) ?? '',
+ logTruncated: d.log_truncated === true,
+ }
+}
+
function readEngineErrorObject(value: unknown): EngineError | undefined {
if (typeof value !== 'object' || value === null) return undefined
@@ -41,6 +101,7 @@ function readEngineErrorObject(value: unknown): EngineError | undefined {
message?: unknown
details?: unknown
missing_libraries?: unknown
+ diagnostics?: unknown
}
if (typeof record.code !== 'string' || !KNOWN_CODES.has(record.code)) {
return undefined
@@ -57,6 +118,9 @@ function readEngineErrorObject(value: unknown): EngineError | undefined {
...(typeof record.message === 'string' ? { message: record.message } : {}),
...(typeof record.details === 'string' ? { details: record.details } : {}),
...(missingLibraries?.length ? { missingLibraries } : {}),
+ ...(record.diagnostics
+ ? { diagnostics: readDiagnostics(record.diagnostics) }
+ : {}),
}
}
@@ -168,3 +232,109 @@ export function engineFailure(messageKey: string, error: unknown): Error {
wrapped.cause = error
return wrapped
}
+
+/** Escapes a literal for use inside a regular expression. */
+function quoteRegExp(literal: string): string {
+ return literal.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+}
+
+/**
+ * Replaces the user's home directory wherever a path shows up, so a pasted
+ * report does not name them. The engine logs full model and library paths,
+ * which is where these come from.
+ *
+ * `home` is the real directory, from [`localHomeDir`](./localHome), and when
+ * it is known this is an exact replacement with nothing to get wrong. Pass it
+ * wherever it can be had.
+ *
+ * The fallback is a guess at the *shape* of a path, and it deliberately stops
+ * the name at whitespace. A profile folder may well contain a space, but no
+ * rule over the text alone separates `/home/Jo Smith/lib` from
+ * `/home/bob and models/x.gguf`: three attempts at spanning the space each
+ * ended up swallowing the prose between two paths instead. Under-stripping a
+ * surname is the lesser harm only because the exact pass above is what
+ * actually covers the user's own home on the desktop, which is the only place
+ * these reports are produced.
+ */
+export function stripLocalPaths(text: string, home?: string | null): string {
+ let out = text
+ if (home) {
+ const trimmed = home.replace(/[/\\]+$/, '')
+ if (trimmed) {
+ // Both separators: a Windows path reaches the report either way.
+ const variants = [trimmed, trimmed.replace(/\//g, '\\'), trimmed.replace(/\\/g, '/')]
+ for (const variant of new Set(variants)) {
+ // Anchored on a boundary, or home `/home/bob` would rewrite
+ // `/home/bobby/x` to `~by/x` -- and having eaten the `/home/` the
+ // fallback below could no longer recognise what was left.
+ out = out.replace(
+ new RegExp(`${quoteRegExp(variant)}(?![\\p{L}\\p{M}\\p{N}._'-])`, 'giu'),
+ '~'
+ )
+ }
+ }
+ }
+ return out
+ .replace(/\/(?:home|Users)\/[^/\s"'`:;,)]+/g, '~')
+ .replace(/[A-Za-z]:\\Users\\[^\\\s"'`:;,)]+/g, '~')
+}
+
+const FENCE = '```'
+
+const fence = (text: string): string =>
+ `${FENCE}\n${text.split(FENCE).join("'''")}\n${FENCE}`
+
+/**
+ * A markdown report of a failed engine load, for pasting into an issue. Local
+ * only: it is built from the error already in memory and handed to the caller
+ * to put on the clipboard. Undefined when the error carries no diagnostics.
+ */
+export function formatLoadDiagnostics(
+ error: unknown,
+ context: { appVersion?: string; os?: string; home?: string | null } = {}
+): string | undefined {
+ const engineError = parseEngineError(error)
+ const d = engineError?.diagnostics
+ if (!engineError || !d) return undefined
+
+ const rows: [string, string | undefined][] = [
+ ['Error', engineError.code],
+ ['Jan', context.appVersion],
+ ['OS', context.os],
+ [
+ 'llama.cpp',
+ `${d.engine.version} (${d.engine.tag}, ${d.engine.commit.slice(0, 12)})`,
+ ],
+ ['Model file', d.modelFile],
+ ['Architecture', d.architecture],
+ ['Quantization', d.quantization],
+ ...Object.entries(d.request),
+ ]
+ const lines = ['## Model load failure', '']
+ for (const [key, value] of rows) {
+ if (value) lines.push(`- ${key}: ${value}`)
+ }
+ if (d.gpus.length) {
+ lines.push('', '### Devices')
+ for (const g of d.gpus) {
+ const free = g.freeMib === undefined ? '' : `, ${g.freeMib} MiB free`
+ lines.push(
+ `- ${g.name} (driver ${g.driverVersion || 'unknown'}, ${g.totalMib} MiB${free})`
+ )
+ }
+ }
+ if (d.backends.length) {
+ lines.push('', '### Backend modules', ...d.backends.map((b) => `- ${b}`))
+ }
+ if (engineError.details) {
+ lines.push('', '### Engine message', fence(engineError.details))
+ }
+ if (d.log) {
+ lines.push(
+ '',
+ d.logTruncated ? '### Engine log (older lines dropped)' : '### Engine log',
+ fence(d.log)
+ )
+ }
+ return stripLocalPaths(lines.join('\n'), context.home)
+}
diff --git a/web-app/src/lib/loadDiagnosticsReport.ts b/web-app/src/lib/loadDiagnosticsReport.ts
new file mode 100644
index 000000000..243e973f8
--- /dev/null
+++ b/web-app/src/lib/loadDiagnosticsReport.ts
@@ -0,0 +1,22 @@
+import { formatLoadDiagnostics } from '@/lib/engineError'
+import { getCoworkEnvironment } from '@/lib/coworkEnv'
+import { localHomeDir } from '@/lib/localHome'
+
+/**
+ * The paste-ready report for a failed engine load, with this app's version and
+ * OS filled in. Undefined when the error carries no diagnostics, which is the
+ * caller's cue not to offer the action.
+ */
+export async function buildLoadDiagnosticsReport(
+ error: unknown
+): Promise<string | undefined> {
+ const [env, home] = await Promise.all([
+ getCoworkEnvironment(),
+ localHomeDir(),
+ ])
+ return formatLoadDiagnostics(error, {
+ appVersion: env.appVersion ?? undefined,
+ os: [env.os, env.arch].filter(Boolean).join(' ') || undefined,
+ home,
+ })
+}
diff --git a/web-app/src/lib/localHome.ts b/web-app/src/lib/localHome.ts
new file mode 100644
index 000000000..53445ddf5
--- /dev/null
+++ b/web-app/src/lib/localHome.ts
@@ -0,0 +1,35 @@
+import { isPlatformTauri } from '@/lib/platform'
+
+let pending: Promise<string | null> | undefined
+
+/**
+ * The user's home directory, or `null` where there is nothing to ask.
+ *
+ * Exists so a report can take the home directory out of a path by *knowing*
+ * it rather than guessing at its shape. Guessing is what
+ * [`stripLocalPaths`](./engineError) has to do without it, and a profile
+ * folder containing spaces makes that ambiguous against ordinary prose in a
+ * log line -- there is no rule that separates `/home/Jo Smith/lib` from
+ * `/home/bob and models/x.gguf` by looking at the text alone.
+ *
+ * Cached: it cannot change while the app is running.
+ */
+export function localHomeDir(): Promise<string | null> {
+ // The *promise* is cached, not a provisional answer: a second caller during
+ // the lookup would otherwise be handed `null` and fall back to the weaker
+ // heuristic, which is exactly the case this exists to avoid.
+ pending ??= lookUp()
+ return pending
+}
+
+async function lookUp(): Promise<string | null> {
+ if (!isPlatformTauri()) return null
+ try {
+ const { homeDir } = await import('@tauri-apps/api/path')
+ // Trailing separator dropped so it joins the same way on both families.
+ return (await homeDir()).replace(/[/\\]+$/, '') || null
+ } catch {
+ // Web build or a missing plugin: the heuristic is all there is.
+ return null
+ }
+}
diff --git a/web-app/src/locales/en/model-errors.json b/web-app/src/locales/en/model-errors.json
index 514015b02..5a5b7fa2d 100644
--- a/web-app/src/locales/en/model-errors.json
+++ b/web-app/src/locales/en/model-errors.json
@@ -34,5 +34,7 @@
"serverPortOccupiedDescription": "Port {{port}} is already in use. Please try a different port.",
"serverInvalidModelPath": "Invalid or inaccessible model path",
"serverStartModelFailed": "Failed to start model",
- "serverStartFailed": "Failed to start server"
+ "serverStartFailed": "Failed to start server",
+ "copyDiagnostics": "Copy diagnostics",
+ "diagnosticsCopied": "Diagnostics copied. Paste them into your bug report."
}
diff --git a/web-app/src/locales/en/providers.json b/web-app/src/locales/en/providers.json
index 62fd8c04e..8f6724645 100644
--- a/web-app/src/locales/en/providers.json
+++ b/web-app/src/locales/en/providers.json
@@ -125,5 +125,126 @@
"oneKeyHint": "Optional fallback keys are configured in Advanced.",
"addKey": "Add key",
"removeKey": "Remove key"
+ },
+ "diagnostics": {
+ "title": "Hardware check",
+ "description": "Run every llama.cpp operation on your devices and check the results are correct. Useful when a model fails to load or gives bad output.",
+ "run": "Run check",
+ "runOptions": "Check options",
+ "quick": "Quick check",
+ "quickHint": "A few minutes",
+ "full": "Full check",
+ "fullHint": "15 minutes or more per device",
+ "device": "Device",
+ "allDevices": "All devices",
+ "cancel": "Stop check",
+ "runAgain": "Run again",
+ "copyResults": "Copy results",
+ "copied": "Results copied",
+ "copyFailed": "Could not copy the results",
+ "lastRun": "Checked {{when}}",
+ "neverRun": "Not checked yet",
+ "checking": "Checking {{family}} on {{device}}",
+ "preparing": "Starting the check",
+ "progress": "{{done}} of {{total}}",
+ "cancelled": "Check stopped",
+ "stoppedEarly": "The check stopped early: {{reason}}",
+ "startFailed": "The check could not start: {{reason}}",
+ "verdictPassed": "Working correctly",
+ "verdictPassedDetail": "Every operation returned the right answer.",
+ "verdictFallback": "Working correctly",
+ "verdictFallbackDetail_one": "1 operation type is not fully implemented here. If a model uses it, that part of the work runs on the CPU instead. A model that does not use it is unaffected.",
+ "verdictFallbackDetail_other": "{{count}} operation types are not fully implemented here. If a model uses one, that part of the work runs on the CPU instead. A model that does not use them is unaffected.",
+ "verdictFailed": "Problems found",
+ "verdictFailedDetail_one": "1 operation returned the wrong answer. A model using it will produce bad output or fail to load.",
+ "verdictFailedDetail_other": "{{count}} operations returned the wrong answer. A model using them will produce bad output or fail to load.",
+ "verdictCrashed": "Crashed during the check",
+ "verdictCrashedDetail": "The check process died on this device. A model would stop the same way.",
+ "verdictUnknown": "Not checked",
+ "verdictUnknownDetail": "No results for this device yet.",
+ "casesFailed": "{{count}} failed",
+ "casesFallback": "{{count}} of {{total}} variants",
+ "groupMatrixMath": "Matrix multiplication",
+ "groupAttention": "Attention",
+ "groupNormalization": "Normalization",
+ "groupPositional": "Word position",
+ "groupConvolution": "Convolutions",
+ "groupActivation": "Activations",
+ "groupMemory": "Copying and reshaping",
+ "groupBasicMath": "Basic arithmetic",
+ "groupOther": "Other operations",
+ "fullConfirmTitle": "Run the full check?",
+ "fullConfirmBody": "The full check tests every operation. It takes 15 minutes or more per device and uses every CPU core.",
+ "fullConfirmDriver": "On Windows, a long GPU test can reset the display driver, which would interrupt anything you have loaded.",
+ "fullConfirmLoaded_one": "1 model is loaded and will compete for memory.",
+ "fullConfirmLoaded_other": "{{count}} models are loaded and will compete for memory.",
+ "unloadFirst": "Unload them first",
+ "fullConfirmRun": "Run full check",
+ "allCasesTitle": "All cases",
+ "filterAll": "All",
+ "filterFailed": "Failed",
+ "filterFallback": "On CPU",
+ "filterPassed": "Passed",
+ "searchCases": "Filter by operation or parameters",
+ "columnOp": "Operation",
+ "columnParams": "Parameters",
+ "columnStatus": "Result",
+ "noCases": "No cases match this filter.",
+ "casesTruncated": "Only the first {{count}} cases that passed or ran on the CPU were kept. Every failure is listed.",
+ "statusOk": "Passed",
+ "statusFail": "Failed",
+ "statusNotSupported": "Runs on CPU",
+ "statusSkipped": "Skipped",
+ "statusCrashed": "Crashed",
+ "statusHung": "Stopped responding",
+ "statusCancelled": "Stopped",
+ "familyExit": "Exit: {{status}}",
+ "groupMatrixMathDetail": "The core calculation of every model. Most of the work happens here.",
+ "groupAttentionDetail": "How the model decides which earlier words matter for the next one.",
+ "groupNormalizationDetail": "Keeps numbers in a workable range between layers.",
+ "groupPositionalDetail": "How the model tracks the order words came in.",
+ "groupConvolutionDetail": "Used by image and audio models, not by plain chat models.",
+ "groupActivationDetail": "The small shaping step applied after each layer.",
+ "groupMemoryDetail": "Moving numbers around without changing them.",
+ "groupBasicMathDetail": "Adding, multiplying and scaling numbers.",
+ "groupOtherDetail": "Everything that does not fit the groups above.",
+ "quantizedDetail": "Every model you download is compressed, so a failure here affects all of them.",
+ "technicalDetails": "Technical details",
+ "opColumnHint": "llama.cpp operation name",
+ "passedLabel": "Passed",
+ "busyBlocked": "The check is unavailable while a model is loading or replying. Wait for it to finish, then run the check.",
+ "busyDuringRun": "A model started working during this check. Results are still accurate, but the timings are not, and a failure here may be caused by competing for memory.",
+ "checkThisDevice": "Run hardware check",
+ "model": "Check this model",
+ "modelHint": "About a minute",
+ "modelOf": "Checking the operations {{model}} needs",
+ "checkThisModel": "Check why this model failed",
+ "verdictInconclusive": "Not fully checked",
+ "verdictInconclusiveDetail_one": "1 part of the check matched no test on this build of llama.cpp, so it was not checked. Run the full check to cover it.",
+ "verdictInconclusiveDetail_other": "{{count}} parts of the check matched no test on this build of llama.cpp, so they were not checked. Run the full check to cover them.",
+ "verdictPartialDetail": "This check stopped before every part of it had run on this device, so the parts that did pass are not the whole answer. Run it again to finish.",
+ "inconclusiveNotice": "Some parts of this check tested nothing, so it is not a clean result. Run the full check to cover them.",
+ "suggestionsTitle": "What to try",
+ "suggestionEvidence": "Based on: {{groups}}",
+ "suggestionTryAnotherDevice": "Run your models on {{alternative}} instead of {{device}}.",
+ "suggestionTryAnotherDeviceDetail": "{{device}} returned wrong answers, and {{alternative}} passed every check. Set the device in the model's settings.",
+ "suggestionReduceGpuLayers": "Put fewer layers on {{device}}, or run on the processor.",
+ "suggestionReduceGpuLayersDetail_one": "1 part of the check stopped the test process on this device, which is what running out of video memory or losing the driver looks like.",
+ "suggestionReduceGpuLayersDetail_other": "{{count}} parts of the check stopped the test process on this device, which is what running out of video memory or losing the driver looks like.",
+ "suggestionDisableFlashAttention": "Turn flash attention off for models on {{device}}.",
+ "suggestionDisableFlashAttentionDetail_one": "1 attention check returned the wrong answer. Flash attention is optional, and turning it off uses the slower path that passed.",
+ "suggestionDisableFlashAttentionDetail_other": "{{count}} attention checks returned the wrong answer. Flash attention is optional, and turning it off uses the slower path that passed.",
+ "suggestionUseAnotherQuantization": "Try a model with a different compression on {{device}}.",
+ "suggestionUseAnotherQuantizationDetail_one": "1 failure is in a compressed-weight operation while the uncompressed ones passed, so a differently compressed download may work.",
+ "suggestionUseAnotherQuantizationDetail_other": "{{count}} failures are in compressed-weight operations while the uncompressed ones passed, so a differently compressed download may work.",
+ "suggestionExpectCpuFallback": "Some work may run on the CPU instead of {{device}}.",
+ "suggestionExpectCpuFallbackDetail_one": "1 operation type is not fully implemented on {{device}}. Whether this costs you any speed depends on the model: one that never uses it runs at full speed.",
+ "suggestionExpectCpuFallbackDetail_other": "{{count}} operation types are not fully implemented on {{device}}. Whether this costs you any speed depends on the model: one that never uses them runs at full speed.",
+ "suggestionRerunWholeCheck": "Run the full check on {{device}}.",
+ "suggestionRerunWholeCheckDetail_one": "1 part of this check matched no test, so it was not checked at all. The full check does not narrow anything.",
+ "suggestionRerunWholeCheckDetail_other": "{{count}} parts of this check matched no test, so they were not checked at all. The full check does not narrow anything.",
+ "verdictCpuUnsupported": "Working correctly",
+ "verdictCpuUnsupportedDetail": "Every operation your models need returned the right answer. The check also tries combinations no model builds, such as training-only operations, and those have no CPU version; that is normal on every machine.",
+ "statusNotImplemented": "No kernel here"
}
}
diff --git a/web-app/src/routes/settings/__tests__/hardware.test.tsx b/web-app/src/routes/settings/__tests__/hardware.test.tsx
index aad872f4b..3652f0462 100644
--- a/web-app/src/routes/settings/__tests__/hardware.test.tsx
+++ b/web-app/src/routes/settings/__tests__/hardware.test.tsx
@@ -137,7 +137,8 @@ vi.mock('@tauri-apps/api/webviewWindow', () => ({ WebviewWindow: vi.fn() }))
vi.mock('@/constants/routes', () => ({
route: {
settings: {
- hardware: '/settings/hardware'
+ hardware: '/settings/hardware',
+ providers: '/settings/providers/$providerName',
},
systemMonitor: '/monitor'
}
@@ -146,11 +147,25 @@ vi.mock('@/constants/windows', () => ({ windowKey: { systemMonitorWindow: 'monit
vi.mock('@tabler/icons-react', () => ({
IconDeviceDesktopAnalytics: () => <div data-testid="icon" />,
IconRefresh: () => <div data-testid="icon-refresh" />,
+ IconStethoscope: () => <div data-testid="icon-stethoscope" />,
}))
// Mock the route structure properly
vi.mock('@tanstack/react-router', () => ({
createFileRoute: () => (config: any) => config,
+ // Each GPU card links to the hardware check on the llama.cpp provider page.
+ Link: ({ children, to, params, search, ...rest }: any) => (
+ <a
+ href={Object.entries(params ?? {}).reduce(
+ (path: string, [k, v]) => path.replace(`$${k}`, String(v)),
+ to
+ )}
+ data-search={JSON.stringify(search ?? {})}
+ {...rest}
+ >
+ {children}
+ </a>
+ ),
}))
// Mock platform utils to enable hardware monitoring
@@ -226,6 +241,25 @@ describe('Hardware Settings', () => {
})
})
+ // The check itself lives on the provider page; this is a signpost that
+ // carries the device over, not a second place a long run can start from.
+ it('points each GPU at the hardware check, preselecting that device', async () => {
+ llamacpp.devices = [
+ { id: 'CUDA0', name: 'RTX 3090', mem: 24127, free: 1259, activated: true },
+ ]
+ const Component = Route.component as React.ComponentType
+ render(<Component />)
+
+ const link = await screen.findByText(
+ 'providers:diagnostics.checkThisDevice'
+ )
+ const anchor = link.closest('a')
+ expect(anchor).toHaveAttribute('href', '/settings/providers/llamacpp')
+ expect(JSON.parse(anchor?.dataset.search ?? '{}')).toEqual({
+ diagnose: 'CUDA0',
+ })
+ })
+
it('merges multi-backend devices into one card with a backend selector', async () => {
llamacpp.devices = [
{ id: 'Vulkan0', name: 'RTX 3090', mem: 24824, free: 24240, activated: false },
diff --git a/web-app/src/routes/settings/hardware.tsx b/web-app/src/routes/settings/hardware.tsx
index 19e298a7f..7626e4f97 100644
--- a/web-app/src/routes/settings/hardware.tsx
+++ b/web-app/src/routes/settings/hardware.tsx
@@ -1,4 +1,4 @@
-import { createFileRoute } from '@tanstack/react-router'
+import { createFileRoute, Link } from '@tanstack/react-router'
import { route } from '@/constants/routes'
import SettingsMenu from '@/containers/SettingsMenu'
import HeaderPage from '@/containers/HeaderPage'
@@ -10,7 +10,11 @@ import { useHardware, type GPU } from '@/hooks/useHardware'
import { useLlamacppDevices } from '@/hooks/useLlamacppDevices'
import { useEffect, useState } from 'react'
import { toast } from 'sonner'
-import { IconDeviceDesktopAnalytics, IconRefresh } from '@tabler/icons-react'
+import {
+ IconDeviceDesktopAnalytics,
+ IconRefresh,
+ IconStethoscope,
+} from '@tabler/icons-react'
import { useServiceHub } from '@/hooks/useServiceHub'
import type {
DeviceList,
@@ -273,6 +277,18 @@ function GpuGroupCard({
))}
</dl>
)}
+ {/* The check itself lives on the provider page, with the results and
+ the run controls; this carries the device over rather than being a
+ second place a minutes-long run can be started from. */}
+ <Link
+ to={route.settings.providers}
+ params={{ providerName: 'llamacpp' }}
+ search={{ diagnose: device.id }}
+ className="mt-3 inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"
+ >
+ <IconStethoscope size={14} />
+ {t('providers:diagnostics.checkThisDevice')}
+ </Link>
</div>
</div>
)
diff --git a/web-app/src/routes/settings/providers/$providerName.tsx b/web-app/src/routes/settings/providers/$providerName.tsx
index 7c77ba7e6..93a21631a 100644
--- a/web-app/src/routes/settings/providers/$providerName.tsx
+++ b/web-app/src/routes/settings/providers/$providerName.tsx
@@ -14,6 +14,8 @@ import { ImportLlamacppModelDialog } from '@/containers/dialogs/ImportLlamacppMo
import { ImportMlxModelDialog } from '@/containers/dialogs/ImportMlxModelDialog'
import { ModelSetting } from '@/containers/ModelSetting'
import { LlamacppEngineInfo } from '@/containers/LlamacppEngineInfo'
+import { LlamacppDiagnostics } from '@/containers/LlamacppDiagnostics'
+import { isEngineWorkInFlight } from '@/containers/dialogs/llamacppRouterError'
import { DialogDeleteModel } from '@/containers/dialogs/DeleteModel'
import { DialogDeleteAllModels } from '@/containers/dialogs/DeleteAllModels'
import { FavoriteModelAction } from '@/containers/FavoriteModelAction'
@@ -57,10 +59,22 @@ import {
// as route.threadsDetail
export const Route = createFileRoute('/settings/providers/$providerName')({
component: ProviderDetail,
- validateSearch: (search: Record<string, unknown>): { step?: string } => {
+ validateSearch: (
+ search: Record<string, unknown>
+ ): { step?: string; diagnose?: string; diagnoseModel?: string } => {
// validate and parse the search params into a typed state
return {
step: String(search?.step),
+ // The hardware page's per-device entry point; it preselects a device in
+ // the hardware check rather than starting one.
+ diagnose:
+ typeof search?.diagnose === 'string' ? search.diagnose : undefined,
+ // A failed load's entry point, carrying the model whose shapes the check
+ // should be narrowed to. Also only preselects.
+ diagnoseModel:
+ typeof search?.diagnoseModel === 'string'
+ ? search.diagnoseModel
+ : undefined,
}
},
})
@@ -72,6 +86,10 @@ function ProviderDetail() {
const [activeModels, setActiveModels] = useAppState(
useShallow((state) => [state.activeModels, state.setActiveModels])
)
+ // This page is the llama.cpp one when the panel below renders, so engine
+ // work in flight is this engine's work.
+ const engineBusy = useAppState(isEngineWorkInFlight)
+ const { diagnose: diagnoseDevice, diagnoseModel } = Route.useSearch()
const [loadingModels, setLoadingModels] = useState<string[]>([])
const [refreshingModels, setRefreshingModels] = useState(false)
const [importingModel, setImportingModel] = useState<string | null>(null)
@@ -681,6 +699,13 @@ function ProviderDetail() {
)}
{isLlamacpp && <LlamacppEngineInfo />}
+ {isLlamacpp && (
+ <LlamacppDiagnostics
+ busy={engineBusy}
+ deviceHint={diagnoseDevice}
+ modelHint={diagnoseModel}
+ />
+ )}
{provider?.provider === 'mlx' && (
<div className="flex items-start gap-2 rounded-md border border-main-view-fg/10 bg-main-view-fg/5 px-3 py-2 text-xs text-muted-foreground">
diff --git a/web-app/src/routes/settings/providers/__tests__/$providerName.test.tsx b/web-app/src/routes/settings/providers/__tests__/$providerName.test.tsx
index c626532f9..cc6c20cfb 100644
--- a/web-app/src/routes/settings/providers/__tests__/$providerName.test.tsx
+++ b/web-app/src/routes/settings/providers/__tests__/$providerName.test.tsx
@@ -83,6 +83,13 @@ const h = vi.hoisted(() => {
const appState = {
activeModels: [] as string[],
setActiveModels: vi.fn(),
+ // The page selects over these to decide whether the engine is busy, so
+ // the mock has to carry the real store's shape.
+ currentStreamThreadId: undefined as string | undefined,
+ abortControllers: {} as Record<string, unknown>,
+ busyThreads: {} as Record<string, boolean>,
+ loadingModels: {} as Record<string, boolean>,
+ streamingContents: {} as Record<string, unknown>,
}
const useAppStateMock: any = (selector: any) => selector(appState)
useAppStateMock.getState = () => appState
@@ -119,6 +126,7 @@ const h = vi.hoisted(() => {
}
const params: any = { providerName: 'openai' }
+ const search: any = {}
return {
toastSuccess,
@@ -139,6 +147,7 @@ const h = vi.hoisted(() => {
dialogSvc,
modelLoad,
params,
+ search,
}
})
@@ -146,7 +155,12 @@ const h = vi.hoisted(() => {
// Module mocks
// -----------------------------------------------------------------------------
vi.mock('@tanstack/react-router', () => ({
- createFileRoute: () => (cfg: any) => ({ ...cfg, id: '/settings/providers/$providerName' }),
+ createFileRoute: () => (cfg: any) => ({
+ ...cfg,
+ id: '/settings/providers/$providerName',
+ // The page reads ?diagnose to preselect a device in the hardware check.
+ useSearch: () => h.search ?? {},
+ }),
useParams: () => h.params,
Link: ({ children, to, params }: any) => (
<a
@@ -294,6 +308,18 @@ vi.mock('@tabler/icons-react', () => ({
IconEyeOff: () => <span />,
IconCopy: () => <span />,
IconCopyCheck: () => <span />,
+ // Used by the llama.cpp panels this page renders; the diagnostics status
+ // table reads these at module scope, so a missing one fails on import.
+ IconCpu: () => <span />,
+ IconExternalLink: () => <span />,
+ IconStethoscope: () => <span />,
+ IconChevronDown: () => <span />,
+ IconLoader2: () => <span />,
+ IconCheck: () => <span />,
+ IconX: () => <span />,
+ IconCircleDashed: () => <span />,
+ IconHelpCircle: () => <span />,
+ IconAlertTriangle: () => <span />,
}))
vi.mock('@/lib/utils', () => ({
@@ -303,6 +329,7 @@ vi.mock('@/lib/utils', () => ({
getModelDisplayName: (m: any) => m.name ?? m.id,
basenameNoExt: (p: string) => p.split('/').pop() ?? p,
isLocalProvider: (p: string) => p === 'llamacpp' || p === 'mlx',
+ formatMegaBytes: (n: number) => `${n} MB`,
}))
vi.mock('@/constants/providers', () => ({
diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsx
index c8b2a6f72..15d4bb575 100644
--- a/web-app/src/routes/threads/$threadId.tsx
+++ b/web-app/src/routes/threads/$threadId.tsx
@@ -11,6 +11,7 @@ import { MessageItem } from '@/containers/MessageItem'
import { useMessages } from '@/hooks/useMessages'
import { useMessageErrors } from '@/stores/message-errors'
+import { buildLoadDiagnosticsReport } from '@/lib/loadDiagnosticsReport'
import { useServiceHub } from '@/hooks/useServiceHub'
import { useTools } from '@/hooks/useTools'
import { useAppState } from '@/hooks/useAppState'
@@ -2326,6 +2327,29 @@ function ThreadDetail() {
return
}
useMessageErrors.getState().setError(targetId, errMessage)
+ const reportTarget = targetId
+ // The turn's own model, not the one selected by the time anyone reads
+ // this: the check offered from the message has to be about the model
+ // that actually failed.
+ const failedTurn = turnModelOf(threadId)
+ const failedModel =
+ failedTurn.selectedProvider === 'llamacpp'
+ ? failedTurn.selectedModel?.id
+ : undefined
+ void buildLoadDiagnosticsReport(error)
+ .then((report) => {
+ // Only if this is still the error on screen: a second failure on the
+ // same message must not be handed the previous one's report, and one
+ // that resolves after `clearError` must not put it back.
+ if (!report) return
+ if (useMessageErrors.getState().errors[reportTarget] !== errMessage) {
+ return
+ }
+ useMessageErrors.getState().setReport(reportTarget, report, failedModel)
+ })
+ .catch((e) =>
+ console.warn('could not build the load diagnostics report:', e)
+ )
const tm = useMessages.getState().getMessages(threadId).find(
(m) => m.id === targetId
)
diff --git a/web-app/src/stores/__tests__/message-errors.test.ts b/web-app/src/stores/__tests__/message-errors.test.ts
new file mode 100644
index 000000000..b868163eb
--- /dev/null
+++ b/web-app/src/stores/__tests__/message-errors.test.ts
@@ -0,0 +1,50 @@
+import { describe, it, expect, beforeEach } from 'vitest'
+import { useMessageErrors } from '../message-errors'
+
+describe('useMessageErrors reports', () => {
+ beforeEach(() => useMessageErrors.getState().clearAll())
+
+ it('keeps a diagnostics report with its error until the error is cleared', () => {
+ const s = useMessageErrors.getState()
+ s.setError('m1', 'boom')
+ s.setReport('m1', '## Model load failure', 'llama-3-8b')
+ expect(useMessageErrors.getState().reports.m1).toEqual({
+ text: '## Model load failure',
+ model: 'llama-3-8b',
+ })
+
+ useMessageErrors.getState().clearError('m1')
+ expect(useMessageErrors.getState().reports.m1).toBeUndefined()
+ })
+
+ // The model is what the check offered from the message runs on, so a report
+ // recorded without one must not invent the current selection downstream.
+ it('records no model when the failed turn was not a local one', () => {
+ useMessageErrors.getState().setReport('m1', 'r')
+ expect(useMessageErrors.getState().reports.m1.model).toBeUndefined()
+ })
+
+ // The report describes the failure it was built for; a different failure on
+ // the same message may carry no diagnostics at all.
+ it('drops a stale report when the error changes', () => {
+ const s = useMessageErrors.getState()
+ s.setError('m1', 'boom')
+ s.setReport('m1', '## Model load failure', 'llama-3-8b')
+ useMessageErrors.getState().setError('m1', 'a different failure')
+ expect(useMessageErrors.getState().reports.m1).toBeUndefined()
+ })
+
+ it('keeps the report when the same error is set again', () => {
+ const s = useMessageErrors.getState()
+ s.setError('m1', 'boom')
+ s.setReport('m1', 'r')
+ useMessageErrors.getState().setError('m1', 'boom')
+ expect(useMessageErrors.getState().reports.m1).toBeDefined()
+ })
+
+ it('drops reports when errors are hydrated from storage', () => {
+ useMessageErrors.getState().setReport('m1', 'r')
+ useMessageErrors.getState().hydrate({ m2: 'x' })
+ expect(useMessageErrors.getState().reports).toEqual({})
+ })
+})
diff --git a/web-app/src/stores/message-errors.ts b/web-app/src/stores/message-errors.ts
index 27a0ac12e..3a89d0c93 100644
--- a/web-app/src/stores/message-errors.ts
+++ b/web-app/src/stores/message-errors.ts
@@ -1,8 +1,22 @@
import { create } from 'zustand'
+/** Diagnostics for one failed load, and the model that failed. */
+export type LoadReport = {
+ text: string
+ /**
+ * The model of the turn that failed, not whichever is selected now. A
+ * message is read long after the user has moved on, and a check offered
+ * from it has to be a check of the model it is reporting on.
+ */
+ model?: string
+}
+
type MessageErrorsState = {
errors: Record<string, string>
+ /** Paste-ready diagnostics for a failed model load, by message id. */
+ reports: Record<string, LoadReport>
setError: (messageId: string, error: string) => void
+ setReport: (messageId: string, report: string, model?: string) => void
clearError: (messageId: string) => void
clearAll: () => void
hydrate: (entries: Record<string, string>) => void
@@ -10,19 +24,30 @@ type MessageErrorsState = {
export const useMessageErrors = create<MessageErrorsState>()((set) => ({
errors: {},
+ reports: {},
+ setReport: (messageId, report, model) =>
+ set((state) => ({
+ reports: { ...state.reports, [messageId]: { text: report, model } },
+ })),
setError: (messageId, error) =>
- set((state) =>
- state.errors[messageId] === error
- ? state
- : { errors: { ...state.errors, [messageId]: error } }
- ),
+ set((state) => {
+ if (state.errors[messageId] === error) return state
+ // A different error on the same message: the old report describes the
+ // old failure, and the new one may have no diagnostics at all, so it
+ // must not be left behind offering stale advice.
+ const reports = { ...state.reports }
+ delete reports[messageId]
+ return { errors: { ...state.errors, [messageId]: error }, reports }
+ }),
clearError: (messageId) =>
set((state) => {
if (!(messageId in state.errors)) return state
const rest = { ...state.errors }
delete rest[messageId]
- return { errors: rest }
+ const reports = { ...state.reports }
+ delete reports[messageId]
+ return { errors: rest, reports }
}),
- clearAll: () => set({ errors: {} }),
- hydrate: (entries) => set({ errors: entries }),
+ clearAll: () => set({ errors: {}, reports: {} }),
+ hydrate: (entries) => set({ errors: entries, reports: {} }),
}))