Commit graph

23 commits

Author SHA1 Message Date
oobabooga
495ba21ebd
Studio: add MiniMax H3 video generation (#7989)
* Add MiniMax H3 video generation

* Improve MiniMax H3 memory routing

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Address MiniMax H3 review feedback

* Keep H3's VAE off the CPU path, so low_vram stops aborting

low_vram maps to the `model` policy, and offload_flags emits --vae-on-cpu for it
unconditionally. On H3 that kills the process:

    ggml/src/ggml-cpu/ops.cpp:6321: GGML_ASSERT(src0->type == GGML_TYPE_F16) failed

deterministically, SIGABRT, exit 134. Bisected on the flags: --vae-on-cpu with
--audio-vae aborts, the same command without --audio-vae renders in 95.87s, and an
fp16-converted audio VAE aborts too. So the trigger is the audio VAE, not the video
one, and the F32 type is imposed inside stable-diffusion.cpp rather than by the
file: ggml_conv_1d hardcodes an F16 im2col destination (ggml/src/ggml.c),
ggml_compute_forward_im2col_f16 then asserts the KERNEL is F16, and
audio_conv_weight_type (src/model/vae/ltx_audio_vae.hpp) maps only BF16 to F16 and
lets F32 through. It cannot be fixed by shipping a different checkpoint.

low_vram is the one mode a small-card user reaches for, so this drops the flag
rather than the mode. offload_flags takes vae_on_cpu, defaulting True so no other
family changes, and the H3 native path passes False. --offload-to-cpu and
--clip-on-cpu still apply, which is where the saving actually is: the denoiser
dominates, and with --offload-to-cpu the whole model peaks at 13.14 GiB.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Point the H3 GGUF pick at the unsloth mirror

Main added test_curated_gguf_repos_are_unsloth_mirrors, which requires
every curated video gguf_repo to live under unsloth/ so a one-click pick
cannot 404 when a community repack is renamed or taken down. H3 was the
one family still on a community repo.

This was meant to be part of the merge commit but was left in the
worktree, so CI on that commit still saw the old value.

unsloth/MiniMax-H3-GGUF is still private and has to be made public
before this merges, or the pick will 401. No CI check reads it.

* Pin H3's native cfg-scale under test

H3 is distilled and CFG-free: its empty unconditional prompt encodes to
zero tokens, and the transposed tensor that produces trips
GGML_ASSERT(!ggml_is_transposed(a)) in ggml.c. SIGABRT, exit 134.
Measured: cfg 1.0 renders, cfg 1.5 and cfg 4.0 both abort. sd.cpp
defaults cfg-scale to 7.0, so this is a crash a plausible refactor
reintroduces by forwarding guidance the way every other family does.

The native path already hardcodes 1.0 and the family sets
supports_cfg = False, but nothing held either in place. supports_cfg
only gates the diffusers path; the native path builds its own params.

Checked the test fails when cfg_scale is changed to forward guidance,
so it is not passing vacuously.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Pin diffusers by source archive instead of git, so macOS installs work

The macos-15-intel leg fails deterministically, not flakily:

  process didn't exit successfully: `/usr/bin/git init` (exit status: 1)
  --- stderr
  xcode-select: note: No developer tools were found, requesting install.

That runner has no Xcode, so /usr/bin/git is the developer-tools shim and
exits 1 for everything. uv needs a working git to resolve a git+https
dependency, so the diffusers pin this branch added cannot install there
at all. Main is unaffected because it depends on plain diffusers.

GitHub serves the same commit as a source archive, which uv installs with
no git involved. Verified by stubbing git to fail exactly the way the
macOS shim does: the git+ form reproduces the CI error, the archive form
installs diffusers 0.40.0.dev0 from the same SHA with
MiniMaxH3Transformer3DModel present and exported.

Also drops a full clone of diffusers from every install.

* Allow the diffusers source build on the clean-machine legs

With the archive pin the macOS leg gets past `git init` and installs, but
then trips the nobuild guard:

  built from source: diffusers -- these must resolve to wheels on a clean machine

There is no wheel to resolve to. MiniMax-H3 support is not in any
diffusers release, so this branch has to pin a commit, and neither a git
URL nor a source archive can produce a wheel from an index.

Added to the same allowlist that already carries triton-kernels for the
same reason. Checked against the bar the comment there sets: diffusers
builds with plain setuptools, declares no ext_modules, and its tree has
zero .c/.cpp/.pyx/.rs/.cu files and no shipped binaries, so the PEP 517
build is a pure-Python copy step and needs no toolchain. The separate
compiler-invocation check in both scripts is untouched and still fires if
one is ever needed.

Verified the allowlist logic still rejects a non-allowlisted source build
(a log building both diffusers and numpy reports only numpy).

Remove this entry once a diffusers release carries H3 and the requirement
goes back to a version specifier. Noted in both scripts.

* Baseline the hf-hub retry loop reopened by the 1.x upgrade

`pip scan-packages :: hf-stack` fails on this branch with 1 unbaselined
CRITICAL:

  C2 polling/beaconing loop detected
  Package: huggingface-hub
  File:    huggingface_hub/utils/_http.py
  L461:    while True:

This is on us, not upstream drift. Main pins huggingface-hub==0.36.2;
this branch needs >=1.23.0,<2.0 because diffusers at the pinned commit
requires it, so the resolved version moves 0.36.2 -> 1.27.0.

The baseline already carries this exact file and check at L462 and L298,
from earlier versions. It did not carry over because the key hashes the
matched code, not the line number, and the surrounding code changed
across the major version. That is the guard behaving correctly: changed
code in a baselined file reopens for review rather than staying
suppressed.

Reviewed it rather than just re-suppressing. L461 is the retry loop in
`http_backoff`: bounded by `nb_tries > max_retries`, the URL comes from
the caller, there is no hardcoded endpoint and nothing is exfiltrated.
Same benign construct as the entries it replaces.

Entry generated with the scanner's own _evidence_hash rather than
hand-written, and inserted beside its siblings so the diff stays 8 lines.
Verified: with the baseline the scan is exit 0 with 4 suppressed, without
it exit 1, so the guard still bites.

* Lift the macOS-arm huggingface-hub cap that this branch made unsatisfiable

`mac macos-15 / trace / file` fails on this branch and passes on main. uv
reports:

  No solution found when resolving dependencies:
  Because you require huggingface-hub>=0.34.0,<1.0 and
  huggingface-hub>=1.23.0,<2.0, your requirements are unsatisfiable.

This branch moved base.txt, no-torch-runtime.txt, studio.txt and
constraints.txt to hub >=1.23.0,<2.0, because diffusers at the pinned
commit requires it, but left the flat <1.0 cap in
overrides-darwin-arm64.txt. That file is macOS-arm only, which is why
only the mac legs see it and Linux and Windows stayed green.

The failure then presents as something else entirely: uv gives up, the
installer falls back to pip, and the clean-machine trace fails on
"installer invoked toolchain: rustc" rather than on the resolution.

The cap's own comment explains it exists so the resolver can never pair
hub 1.x with a pinned transformers 4.57.6 / hub 0.36.2 stack. That is
still true below python 3.10 and still capped there. At 3.10 and above
this branch is on transformers 5.5.0 and hub 1.x, so the premise is gone,
and mlx-audio's own >=1.0 floor is satisfied by the 1.x window anyway.

Checked by collecting every hub specifier that applies per Python version
across all five files: py3.9 resolves to 0.36.2 as intended, py3.13 to
1.23.0/1.27.0. Before this change py3.13 resolved to nothing.

* Make H3's native download use the repo the family advertises

The curated-mirror test main added only inspects VideoFamily.gguf_repo.
H3's native path does not read that field: video_minimax_h3.py has its
own H3_GGUF_REPO constant, used for both the transformer and the Qwen3-VL
encoder. So pointing the family at the unsloth mirror in the previous
commit satisfied that test while the actual one-click download still came
from a community repack, which is the exact failure the test exists to
prevent.

Pointed the constant at the same mirror and added
test_the_h3_native_repo_matches_the_family_gguf_repo to pin the pair, so
the two cannot drift apart again. Verified it fails when the constant is
put back to leejet, so it is not passing vacuously.

The mirror now carries the Qwen3-VL encoder quants alongside the
denoisers, byte-identical in size to the community ones, so this repo
alone satisfies both of h3_native_hub_files' hub entries. The encoder is
part of MiniMaxAI/MiniMax-H3 itself (FL2VA/text_encoder) which we already
mirror publicly at unsloth/MiniMax-H3 under the same licence, so shipping
a quantization of it beside the denoisers is the same act.

Also checked the encoder-tier routing survives the dynamic rung names:
-UD-Q2_K_XL selects the Q2_K_M encoder and -UD-Q3_K_XL the Q4_K_M one,
asserted in the new test.

Updated the download-plan test, which hardcoded the old repo id.

NOTE: unsloth/MiniMax-H3-GGUF is private. Unlike before, that now really
does gate this: the native path downloads from it. It has to be public
before this merges.

* Pin H3's companion-checkpoint guard under test

validate_h3_transformer_filename had no test. That mattered less when the
denoisers lived alone; the mirror now ships the Qwen3-VL encoder quants in
the same repo, so the picker lists both and a user can name either. Loading
a 12-17 GB encoder as the transformer would fail deep inside sd-cli instead
of at the boundary.

The accept cases include the dynamic rung names on purpose. The guard is a
prefix/suffix check and `-UD-Q2_K_XL` is a shape it had never seen when it
was written; it happens to pass, and now that is asserted rather than
assumed.

Checked the test fails when the prefix check is dropped, so it is not
vacuous.

* Record why H3 drops --vae-on-cpu, now that the abort is fixed

The comment justified the drop entirely by an sd.cpp abort. That abort is fixed
in the Unsloth fork, which would have made this look like a stale workaround to
revert once the fix reaches the pinned prebuilt.

Measured on a build carrying the fix, 640x384, 25 frames, 4 steps, q4_K, with
--offload-to-cpu --clip-on-cpu already applied: adding --vae-on-cpu moved peak
VRAM 12.42 -> 12.42 GiB and wall time 20.9s -> 100.4s. Under --offload-to-cpu
the peak is set by the streamed denoiser, so the flag saves nothing and costs
4.8x. It stays off on its own merits.

* Pin the sd.cpp prebuilt that actually renders MiniMax-H3

The pin was master-812-ea7f0c8, a stock upstream build, and on a stock build H3
does not work: it aborts on the default --cfg-scale, aborts again on
--vae-on-cpu, and its 1-D norms are quantized into an output uncorrelated with
its own bf16 reference (LPIPS 0.981). The Studio side worked around the first by
pinning cfg to 1.0 and the second by dropping the flag; the third had no
workaround on the consumer side at all.

All three are fixed in unslothai/stable-diffusion.cpp and open upstream as
leejet/stable-diffusion.cpp#1861, #1862 and #1863. The mirror's prebuilt
pipeline now applies them on top of the aged upstream tag it already builds, and
marks such a build with a -u<id> suffix naming the patch set, so
master-813-bfbef5b-u0665242 is upstream master-813-bfbef5b plus those three
patches and nothing else. The patches are deleted once upstream releases them,
at which point this pin goes back to a plain tag.

Verified on the published Linux x86_64 asset, not on a local build: both new
error strings are in the shipped sd-cli, and running it on a q4_K H3 denoiser
without --mode vid_gen now exits 1 with the instruction instead of core dumping
on a ggml assert.

test_video_backend's fake engine returned the old tag as its version string,
which read like a second pin; it only needs a non-None value, so it now says so.

* Close two gaps the H3 mirror switch opened

Both are consequences of the two preceding commits, found in review.

The prebuilt pin is now mirror-only (master-813-bfbef5b-u0665242), and
_resolve_with_fallback still asked leejet for it. That request is a guaranteed
404 by construction, since the -u<id> suffix marks a build only the mirror
makes, so it was a wasted round trip on every install. Worse, when the mirror
genuinely cannot serve a host the fallback lands on leejet's latest, which has
none of the H3 fixes. For every other model that is the right trade, better a
stock native engine than none. For H3 it is not visible: it aborts on the
default cfg-scale, aborts on --vae-on-cpu, and a blanket --type renders a broken
video rather than failing. A user who saw only the generic 'falling back to
leejet' line had nothing connecting that to the output. It now says so.

Second, hub/utils/gguf.py filtered H3 companion GGUFs by the old community repo
id only. The mirror the family and catalog now advertise carries the Qwen3-VL
encoder quants beside the denoisers, so a 12 GB text encoder was being
aggregated as if it were a selectable transformer quant. Both bundle repos are
now recognised, case-insensitively, and the cache-dir match follows.

Tests are mutation-verified rather than assumed: restoring the upstream 404
attempt fails the ordering test, removing the H3 warning fails the fallback
test, and dropping the mirror from the bundle set fails three. The ordering test
deliberately makes the mirror serve nothing, because with the mirror serving the
first attempt succeeds and the upstream attempts are never reached, which made
an earlier version of it pass under its own mutation.

A third test pins the native loader's H3_GGUF_REPO to the bundle set, since
those live in different files and a future repo move that updated only the
loader would silently reintroduce the same aggregation bug.

* Exclude MiniMax-H3's small-M projections from int8

_INT8_FAMILY_EXCLUDE_NAME_TOKENS has entries for qwen-image and hunyuanvideo-1.5
but none for minimax-h3, and H3 needs one for the same reason they do.

H3's adaLN projection is named adaln_proj, which no token in the generic list
matches: 'norm' is the closest and does not appear in the name. On the dense
checkpoint that projection is Linear(2688 -> 96768), so it clears
min_features = 512, gets quantized, and then runs at M = 1. Inductor lowers int8
matmul to _int_mm, which requires M > 16, so it raises 'self.size(0) needs to be
greater than 16, but got 1' at the first denoise. The offline prequant builder
bakes it in happily, which is exactly the drift the exclude list exists to
prevent for Flux and Qwen.

The pruned-modulation form hides this rather than fixing it: there adaln_proj is
Linear(8 -> 96768) and falls under min_features anyway. So this exclusion is what
makes the DENSE path correct and is a no-op on the pruned one.

context_embedder and token_refiner are added for the same reason hunyuanvideo-1.5
excludes its text stream. Measured at M = 10 text tokens against the video
stream's thousands, they are 3.47% of GEMM time even in the slow eager int8 path,
so leaving them bf16 costs nothing measurable.

This is what made an earlier measurement conclude int8 does not work on H3. It
does: on the pruned form int8 compiles and is 4.24% +-0.54% faster than fp8 at
identical memory, paired over 12 renders.

* Say which H3 component could not be downloaded, and why

H3 pulls four files from two repos, and the Hub returns the same
'Repository Not Found ... make sure you are authenticated' for a repo that does
not exist, one that is private, and one your token does not cover. A user
reading that has no way to tell which of the four failed, and the wording points
away from the real cause whenever the repo exists but is not public.

That is the state the GGUF mirror is in today: it is unpublished, so picking H3
fails with a message suggesting the user fix their token, which will not help.
This replaces it with the repo, the component, and the actual remedy, and says
the other components are unaffected so the failure is not read as total.

Gated repos get different wording, since accepting a licence is a different
action from waiting for a repo to be published.

Anything that is not a recognised access error is passed back unchanged rather
than reworded, so a timeout or a full disk still reads as itself. The helper
returns the exception instead of raising, so the caller keeps raise-from and the
original traceback survives.

Mutation-verified three ways: rewording every error (timeouts included), fixing
the component name to 'denoiser', and giving gated repos the private wording
each fail the test.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Stop MiniMax-H3 holding two copies of its video VAE

Two thirds of an H3 render's peak is not activations. Measured at
640x384 across 124 frames, a 20.25 GB int8 denoiser peaks at 36.96 GB,
and the gap is almost all weights: the video VAE alone is 10.42 GB
because diffusers pins it to float32, and a further 4.91 GB is
autocast's own float16 copy of those same weights. A memory snapshot
puts 92.9% of the transient in 437 blocks allocated from nn.Linear,
largest 67.1 MB, which is the decoder's [2048, 16384] SwiGLU projection
in float16.

MiniMaxH3VideoDecodeStep wraps vae.decode in torch.autocast(float16),
and autocast caches every weight it casts for the lifetime of the
region, so the float32 original and its float16 twin are both resident
through the whole decode. Storing those weights as float16 up front
makes the cast a no-op and removes both. This is not an approximation:
x.to(float16).to(float16) is x.to(float16), and the four regression
tests check that on a real matmul rather than on the reasoning. The
audio VAE decode is not under autocast, so it keeps float32.

t2va starts from noise and never encodes, so vae.encoder and
vae.quant_conv go too. That part is gated on the workflow name rather
than dropped unconditionally, because an image-conditioned workflow
needs them.

Measured 36.96 -> 28.37 GB peak with the encoder drop and the pre-cast,
28.27 with expandable_segments as well, over 5 prompts x 2 seeds. Speed
is unchanged (-0.05% +-0.86% eager, -0.34% +-2.23% compiled), and every
arm hashes identically to its control on latents, audio_latents, frames
and audio.

The estimator's base still reads 68.5 GB. That figure was measured on
the bfloat16 modular components, not the int8 arm above, so it stays put
until it is re-measured in the same configuration rather than adjusted
by arithmetic.

* Pad MiniMax-H3's small-M int8 linears instead of leaving them dense

torch._int_mm asserts self.size(0) > 16. torchao's eager path never trips
it (safe_int_mm falls back to a widened matmul), but inductor lowers the
same quantized linear straight to _int_mm, so any quantized Linear invoked
at a small activation row count crashes under torch.compile. Until now the
fix was to leave those linears dense bf16, which on H3 meant excluding
context_embedder and both token_refiner blocks: 13 linears, 798M
parameters, 0.80 GB of weights the int8 checkpoint was not allowed to
touch.

Pad instead. diffusion_quant_pad.PadToMinM pads the flattened row count up
to 32, runs the GEMM and slices the result back, so the module compiles
with no change to the quantization config and the caller's rows come back
bitwise unchanged. Verified bitwise on all 65 (module, M) cases across
H3's 13 linears at M = 10, 13, 14, 17, 19, on real torchao-quantized
weights; compiling those same modules unpadded raises the _int_mm assert
at M = 10, 13 and 14.

Two properties carry that exactness and both are asserted rather than
assumed. The pad rows replicate row 0, not zeros: an all-zero row has amax
0, so the activation quantizer divides by zero. And the activation scale
must be per row, so each kept row's scale comes from that row alone; a
quantized Linear whose granularity cannot be proven per row raises instead
of being quietly skipped, because a half-padded transformer compiles on
the wrapped modules and crashes on the rest.

Everything below pad_to normalises to pad_to rather than only what is
below the floor, so one inductor graph covers every prompt length in the
range. H3's seven eval prompts run at M = 10..19, which straddles the
floor, and padding only to 17 would leave three shapes behind.

The wrapper reparents the Linear, so it runs after quantize_ on the
runtime path and after load_state_dict on the prequant one. The offline
builder drives quantize_ directly and saves the state dict, so it never
sees a wrapper; PadToMinM is also state-dict transparent as a second line
of defence, saving and loading under its own prefix so a wrapped
transformer still writes context_embedder.weight.

Scoped to minimax-h3. qwen-image, qwen-image-edit and hunyuanvideo-1.5
have the same small-M shape but published int8 prequant checkpoints whose
metadata bakes the current exclusion set, and _validate_checkpoint
compares that set against exclude_tokens_for_scheme, so they move only
together with a rebuild. adaln_proj stays excluded for a different reason:
on the dense checkpoint it is Linear(2688 -> 96768) and runs at M = 1,
while on the pruned form it is Linear(8 -> 96768) and falls under
min_features anyway (verified: the filter rejects all 51 for min_features).

Measured on B200, 640x384 x 124 frames, 4 steps, 7 prompts x 2 seeds, the
two arms alternated within each cell so drift on a shared box cancels:

  checkpoint      21.052 -> 20.254 GB  (-0.798, -3.8%)
  transformer     21.051 -> 20.253 GB  (-0.798)
  load peak       21.137 -> 20.336 GB  (-0.801)
  render peak     37.766 -> 36.966 GB  (-0.800, -2.1%)
  step time       +0.0597 s +-0.0057 eager, +0.0533 s +-0.0086 compiled

The time is torchao's un-fused eager activation quantization on 13 modules
that run ONCE per render, so it is a fixed cost rather than a per-step
one, and it does not scale with steps or resolution. Compiling those
modules alongside the blocks removes it: +0.0034 s +-0.0040, no detectable
difference. Quality is unchanged as far as n = 14 can resolve: against the
same bf16 twin the padded arm sits +0.0070 +-0.0151 LPIPS from the
excluded one, which rules out a degradation larger than 0.022.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Classify the MiniMax-H3 GGUF bundle as video in the cached inventory

The H3 GGUFs are stable-diffusion.cpp conversions and carry no metadata
keys at all (kv_count 0), so general.architecture is absent where the
LTX-2 and Wan video GGUFs declare ltxv/wan. _arch_to_task therefore left
the downloaded repo with no task, which drops it from the Video picker's
On Device list and hands it to chat as a plain GGUF. Key the two bundle
repo ids before the arch is consulted.

* Release the VIDEO GPU claim when H3 native falls back to the CPU build

On a CUDA/ROCm host /video/load acquires the VIDEO arbiter owner because the
resolved device target is not CPU. _run_load_h3_native then asks for an
accelerator-matched sd-cli, and the pinned prebuilt release publishes no Linux
CUDA/ROCm archive, so ensure_sd_cpp_binary returns None and the load commits the
CPU build with native_device = cpu. Nothing dropped the VIDEO claim, so the next
chat or image acquire evicted and unloaded an H3 runtime that holds no VRAM.

Release the claim once the CPU fallback is committed, through release_if so the
token check is atomic against a newer load that already took ownership. Mirrors
the CPU-only native release /images/load already does.

* Video: protect the native H3 companion repos, cancel the modular denoise, forward the hub token

- VideoBackend.loaded_repo_ids() publishes the repos the committed native H3 runtime
  re-reads every generation (Qwen encoder + both VAEs), and the delete-cached guard
  consults it, so deleting a companion under a loaded model is refused.
- The H3 modular workflow no longer falls back to a null progress context: the denoise
  loop drives pipe.scheduler.step once per step, so the existing wrapper gives it the
  same per-step progress and cancellation the other callback-less pipeline gets.
- load_components() gets the Settings token, so gated/private component loads are not
  issued anonymously.

* Reject stable-diffusion.cpp builds that predate MiniMax-H3 support

ensure_sd_cpp_binary hands back whatever find_sd_cpp_binary locates and only
probes that it runs, so an install upgraded from an older Studio kept serving
its pre-H3 managed sd-cli. The H3 load's only gate is SdCppEngine.version(),
which that binary passes, so the load reported ready and the failure surfaced
on the first generation, after the whole bundle had downloaded.

Gate the H3 path alone on the capability instead of a version string: upstream
added --ref-video and the other H3-only options in the same commit that added
MiniMax-H3 (leejet/stable-diffusion.cpp#1854, master-812-ea7f0c8), and the
release prebuilts report 'version unknown, commit unknown' because they are
built without a .git directory, so --help is the only usable signal. Image
generation keeps accepting any user-supplied build.

A stale copy under the installer-owned root is removed so the pinned prebuilt
reinstalls; a build the user supplied is left in place and the load fails
naming it, the same ownership split _usable_or_discard_managed makes. A --help
that cannot be read means 'cannot tell', never 'no H3'.

* Distinguish a reused CPU sd-cli from an accelerator build on an H3 load

On a Linux CUDA host the first H3 load installs the CPU prebuilt through the
fallback and correctly commits native_device = cpu, because the pinned tag
publishes no Linux CUDA, ROCm or Vulkan asset. Every later load then calls
ensure_sd_cpp_binary(accelerator = cuda), which finds that same CPU binary and
returns it without looking at what it was built for, so the fallback was
skipped, native_device stayed cuda, and Studio applied GPU offload policy and
retained the VIDEO gpu_arbiter claim while sd-cli ran wholly on the CPU. A
later chat or image acquire then evicted an unrelated GPU model.

Fall back on what the binary offers rather than on whether one was returned:
sd-cli --list-devices prints one name/description line per available ggml
backend device, so a CPU-only build answers with CPU alone. The second load now
reaches the same cpu conclusion as the first, which is what lets the existing
release_if drop the stale claim. Unreadable output, or an older build that
rejects the flag, keeps the GPU: neither says the accelerator is missing.

* Guard the H3 companion repos while a native video load is downloading

_run_load_h3_native downloads from repo_id, the H3 GGUF companion and the H3
component repo, but the in-flight state only carried repo_id and base_repo. The
cached-model delete guard reads loading_repo_ids(), so it allowed deleting
Comfy-Org/MiniMax-H3, and the GGUF companion when the load comes from another
mirror or a local file, while those files were still downloading, which fails
the load.

Carry the companions on the loading state, the way the image backend's
_SdLoading already does, and publish them from loading_repo_ids(). This is the
in-flight twin of loaded_repo_ids() and covers the same repos.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Keep curated Recommended rows searchable and give them their metadata

Two things went wrong with the curated video models the Recommended list
paints from the catalog rather than from a live Hub listing.

Search dropped them. The Recommended search matched the query against
`recommendedIds`, which filters out every id already on disk because a
downloaded model gets its own On Device row. The unfiltered Recommended
list does not filter that way: it renders the curated seeds and badges the
downloaded ones. So a curated model was visible in the list and unfindable
by typing its name the moment it was downloaded, and only a live listing
row could bring it back, which a repo the listing does not return never
gets. `searchableRecommendedIds` unions the seed ids with the listing ids,
seeds first, deduped case insensitively (the HF cache lowercases repo ids),
so both lists agree on what exists.

Rows rendered bare. Everything past the id came from the listing alone, so
a curated row the listing never returns showed no parameter chip and no
capability glyph while its neighbours showed both. The catalog now carries
the two facts nothing else can supply: `totalParams` per artifact and
`capabilities` per group, read through `curatedTotalParamsFor` and
`curatedCapabilitiesFor`. Both are fallbacks only. A listing row wins
wherever there is one, because real tags and a Hub-reported total outrank
anything hand written here.

The parameter counts are measured, not guessed. The MiniMax-H3 figure is
the sum of the tensor shapes in the BF16 GGUF of the FL2VA denoiser that
repo publishes; the LTX-2.3 figure is what the Hub reports for its repo,
carried so the row looks the same offline or rate limited.

One more inconsistency fell out of the same place: `searchRowFits` hides
anything it cannot size (`requireKnown`), and it could not size a curated
repo with no listing row and no "<n>B" token in its id, so turning on
"Fits on device" hid from search a row the unfiltered list still showed.
It now falls back to the curated total the same way it already fell back
to the curated size.

Covered by studio/frontend/tests/recommended-curated-row-metadata.test.ts:
15 assertions over the search pool, the two catalog lookups, the fit check,
and the four picker call sites that read them.

* Load MiniMax-H3 from a hosted pre-quantized denoiser

Video families had no way to reach a hosted pre-quantized DENOISER. VideoFamily
carried gguf_repo and te_prequant_repos (the text encoder) only, and nothing in
video.py consulted a denoiser table, so a MiniMax-H3 load either pulled the full
66.3 GB bfloat16 DiT or nothing at all. The image side already solves this with
DiffusionFamily.prequant_repos plus family_prequant_repo(), so this follows that
shape rather than inventing a second one.

Four parts.

VideoFamily gains prequant_repos, prequant_variant_repos and prequant_subfolder,
resolved by video_family_prequant_repo() / video_family_prequant_schemes(),
mirroring the image resolver. The registries stay separate, as the module header
requires, so the base-id normaliser is local rather than imported.

The shared resolver learns an optional subfolder. The hosted video checkpoints
nest theirs one level down instead of keeping it at the repo root, and the prefix
has to reach BOTH candidate names or the primary 404 is followed by a second one
and the load silently falls back to the dense download. Always a literal forward
slash: these are Hub repo paths, and a Windows join would miss the cache. The
cache and download plumbing already handled a nested name, so only the filename
builder changed, and every existing call site is byte-identical.

The modular workflow builds its denoiser through its own component loader, so
there is no dense module to quantise in place. A hosted checkpoint is therefore
the only way to run that transformer quantized, and pre-seeding it with
update_components() before load_components() is also what stops the dense
download: load_components(names=None) skips a component whose attribute is
already set. Passing names= instead would have forfeited the workflow's own block
pruning, which is what already avoids the 61.7 GB Ref2VA transformer.

Those checkpoints carry the pruned adaLN, where the modulation is a rank-8 affine
factorization of the time-embedding curve plus a shared table, and roughly 40% of
the released model's parameters go. Against the base repo's dense config the
model is four keys short, one over and fifty-one shapes wrong, so the strict load
fails and the checkpoint is unloadable by every route. video_minimax_h3_adaln.py
reshapes the model between from_config and load_state_dict: table lookup with
interpolation instead of the timestep MLP, no SiLU (the table already holds the
activation's own output projected onto the basis), and the modulation cast to the
block stack's dtype, without which the first quantized matmul dies on mismatched
dtypes. Bound per instance, so a dense load in the same process is untouched.

Finally the refusal becomes honest. A single-file pick on a modular family used
to reach the loader only after ~98.7 GB had downloaded AND after the resident
pipeline had been evicted to make room for it, because download-plan returned 200
and validation passed. Both refusals now run in validate_load_request, ahead of
the diffusers availability probe so they still fire where diffusers cannot be
imported, and each names what to pick instead. download-plan forwards
transformer_quant to validation and to the plan, without which the quant-keyed
refusal never fires on the route that stages the download and the plan stages
shards the load never opens.

* Point both MiniMax-H3 schemes at one hosted pre-quantized repo

The two hosted pre-quantized denoisers were split across two repos with the
checkpoint nested one level down, so reaching them needed a mechanism the image
side has never had: a VideoFamily.prequant_subfolder field, a
prequant_subfolder_prefix() normaliser, and a subfolder keyword threaded through
both resolve_prequant_source() and usable_prequant_source().

Both schemes now live in ONE hosted repo, at the root, named <Model>-<SCHEME>.pt.
That is the layout every image-side prequant repo already uses, and it is exactly
what prequant_repo_filename() builds unaided, so the whole mechanism goes. Match
an existing convention and the code should shrink, not grow: -22 lines in
diffusion_prequant.py, -6 in video_families.py, -6 in video.py, with no new
concept to carry.

Landing on the primary name also fixes a memory-planning under-credit.
cached_checkpoint_path() deliberately credits only the PRIMARY filename, so that
a cached legacy artifact cannot pin a stale name once a repo ships the real one.
While these checkpoints were published as transformer_<scheme>.pt the primary
never existed: every hit came through fallback_filename, and planning therefore
read an already-cached checkpoint as "this would have to download" and handed the
pick to GGUF. The primary is now the published name, so the probe hits it.

fallback_filename stays. It still covers repos that have not been renamed, and
dropping it is a separate decision from this one.

Tests: the subfolder-prefix cases are replaced by the naming they now guard --
both schemes resolving to one repo, the primary resolving to a root-level
<Model>-<SCHEME>.pt with no directory component on any platform, the cache probe
being asked for that primary name, and the repo's own scheme suffix being
stripped and replaced rather than carried through. Five mutations run, each
caught by the named test and reverted: two repos again (M1), the primary nested
under prequant/ again (M2), the suffix strip removed (M3), the cache probe keyed
on the fallback (M4), the fallback name dropped (M5).

* Add MiniMax-H3 image and reference video conditioning

* Improve H3 finalization progress

* Report real sd.cpp progress on the Video page instead of a frozen 0 of 30

A native (GGUF) video generation reported phase "denoise", step 0/30 for its
entire run and then flipped straight to "completed". Two separate things were
wrong, and the progress endpoint could not move until both were fixed.

The parser looked for r"(?:step|sampling)\D+(\d+)/(\d+)". sd-cli's sampling
bar contains neither word. It prints

    |=========>          | 7/30 - 21.50s/it

so nothing ever matched. Anchor the pattern on the bar and on the trailing
speed unit instead. A bare "n/m" is deliberately not enough: an unrelated
ratio in some other log line must not drive the progress bar.

The reader also delivered every redraw one step late. sd-cli redraws in
place, and its carriage return LEADS the record while the newline only
arrives on the final step, so a reader keyed on CR/LF cannot produce step 1
until step 2 has been flushed. Treat the erase-to-end-of-line that closes
each redraw as a terminator too, and read the pipe with buffer.read1 so a
record that carries no newline is not stuck behind a blocking readline.
Escapes are stripped before a record reaches on_log or the error tail.
Streams without a raw .buffer keep the old line iteration.

The same bar shape is printed by three different things, so the parser now
tells them apart rather than reporting whichever came last. Weight load
prints it with a byte rate, and tiled VAE decode prints an identical s/it bar
counting TILES: without a guard a run finished sampling at 30/30 and then
jumped backwards to "step 1/16". Load and decode are real work with no
sampling step, so they report their own phase and a null step rather than a
fake 0 of 30. ETA is measured from the first step, not from job start, so the
one-off weight load is not charged to every remaining step.

Verified end to end against a real CUDA sd-cli MiniMax-H3 generation: the
step advances 1..6 over 6.2s..9.7s of wall clock, load and decode are
reported as themselves, and the ETA tracks.

* Read sd-cli's in-place progress redraws so the Video bar moves during sampling

The native H3 progress bar had two independent causes and fixing either alone
changed nothing observable. The bar pattern is now correct, but the reader still
was not.

sd-cli redraws its sampling bar in place: one printf per step shaped
"\r<bar> <n>/<total> - <speed>\033[K", with a newline only on the final step of a
phase. The drain loop did `for raw in proc.stdout`, which terminates on LF only,
so every redraw sat in the buffer until the next one's carriage return arrived
and the last one until sampling was already over. The Video page saw nothing.

Split the raw pipe into records on CR, LF, or the trailing erase-to-end-of-line,
reading through buffer.read1 with an incremental UTF-8 decoder so a multi-byte
character straddling two reads survives, and strip the CSI escapes before the
record reaches on_log or the error tail. Streams without a raw .buffer (test
doubles, non-pipes) fall back to line iteration.

The new backend test drives the real byte stream through both halves, one flush
per read, and asserts each step is visible on the read that carried it rather
than one redraw later.

* Give MiniMax-H3 first and last frame conditioning in the video backend

MiniMax-H3's released transformer is the FL2VA one: text-to-video is the same
checkpoint run with no keyframes. Studio only ever ran it text-only, so the
Video generate request had nowhere to attach a reference frame.

The load used to prune the block graph to t2va. That argument prunes STATICALLY,
so an fl2va-pruned pipeline runs the keyframe blocks on every request and cannot
serve a text-only one at all: it raises packing an empty conditioning list.
The load now keeps the whole auto graph, which selects per request, and bounds
load_components to the keyframe workflow's component set instead, so the 61.7 GB
Ref2VA partition is no more loaded than before. Measured against the released
checkpoint: a text-only request through this pipeline is bit-identical, video
and audio, to the same request through a t2va-pruned one.

A keyframe is a geometry anchor, not just conditioning, so the canvas comes from
its aspect ratio through the released arithmetic (768 short edge, area capped at
768x1344, both axes rounded to 32) rather than from whatever resolution preset
was selected. An arbitrary size produces a garbled clip rather than an error.

sd.cpp already implements the same conditioning, so that side is the existing
--init-img / --end-img flags with the frames staged as PNGs.

Only MiniMax-H3 declares the capability, and status reports it, so Wan and LTX
do not grow a control that does nothing.

* Cover the MiniMax-H3 keyframe path with tests

Registry (which families declare it, and the canvas a keyframe resolves to),
the load wiring (whole block graph, component set still bounded, VAE encoder
kept), request handling (decode, refusal, canvas override, what reaches the
pipeline call) and the sd-cli argv.

* Add the reference-frame controls to the Video page

First and last frame pickers, shown only for a family whose status declares
keyframe conditioning, so Wan and LTX are unchanged. The Images page's source
picker moves to a shared component rather than the Video page growing a second
upload path; both send the same data URL to the same backend decoder.

While a frame is attached the Resolution preset is disabled and says why: the
frame's aspect ratio resolves the clip's size, the way the model itself does.
The gallery recipe records which ends were pinned.

* Check the keyframe canvas against the pipeline's own resolver

The canvas rule is a checkpoint contract, so pin it to the released
implementation rather than only to hand-written expectations. Skipped where
diffusers does not ship MiniMax-H3, which is most runners.

* Revert the standalone H3 keyframe implementation

oobabooga/unsloth#121 covers first frame, last frame, first-and-last, Ref2VA and
the canvas rule, and it reached the same load construction independently. Two
implementations of the same feature on one branch is worse than either, so this
takes mine back out and leaves the branch ready for that work to land whole.

The one finding worth keeping from it is already reflected there: passing
workflow= to ModularPipeline.from_pretrained prunes the block graph statically,
so the pipeline must be built unpruned and only load_components bounded.

* Keep the pre-quantized MiniMax-H3 denoiser resident so a generation can run

Loading H3 with a hosted pre-quantized denoiser worked, but every generation died
on its first denoise step:

  Attempted to set the storage of a tensor on device "cuda:0" to a storage on
  different device "cpu". This is no longer allowed; the devices must match.

ComponentsManager.enable_auto_cpu_offload parks every component on the CPU and
moves each one onto the accelerator inside its own pre_forward, that is from
within the block that is already executing. The text encoder and the VAEs survive
that; a torchao-quantized denoiser does not, because the device change reaches
return_and_correct_aliasing, which tries to alias a CPU storage to an accelerator
tensor. Moving the same module at load time, outside any executing block, works.

So place it once at load and take it out of the offload rotation: drop its hook,
unlist it from the other components' eviction candidates, and move it. Everything
else is unchanged, and the encoder and VAEs still offload around it. Keeping it
resident is what asking for a quantized denoiser buys in the first place: the
hosted checkpoint is about 20 GB against 66.3 GB dense.

Verified end to end on a B200: MiniMaxAI/MiniMax-H3 loaded with the hosted fp8
denoiser, then a 1280x768, 124-frame clip generated from a start frame in 167s.
The clip's first frame matches the supplied image and the motion is coherent.

* Apply the pinned Diffusers revision on a fresh install, not just an update

MiniMax-H3 needs a Diffusers revision newer than any published release, and
Studio refuses to load it otherwise. The pin was in
studio/backend/requirements/base.txt, and a clean install.sh run still ended up
on diffusers 0.39.0 from PyPI, every time, with nothing in the log to say so.

base.txt is never installed by install.sh. install.sh installs unsloth itself,
whose own metadata pulls a diffusers release in transitively, and then runs
install_python_stack.py with SKIP_STUDIO_BASE=1, where the base-packages step is
a bare `pass`. So the pin applied on `unsloth studio update` and on the no-torch
path (install.sh installs no-torch-runtime.txt directly) and was dead on exactly
the path a new user takes. Reproduced on a clean install into a throwaway prefix
before and after: 0.39.0, then 0.40.0.dev0 with MiniMaxH3Transformer3DModel
present.

The revision now lives in its own diffusers-pin.txt, installed by a step that
sits outside every skip_base / NO_TORCH branch and after every other
requirements file, so nothing left in the run can re-resolve diffusers back to a
release behind it. No forced reinstall is needed: a direct URL requirement is not
satisfied by a resident registry install, so the step is a no-op once the
environment is already on the pin.

tests/studio/install/test_diffusers_pin.py holds the shape in place: exactly one
requirements file may name diffusers, the pin must be a full commit sha rather
than a moving ref, the install step must sit at function top level rather than
under a conditional, and it must come after every other requirements install.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: let the Video and Images pickers see a local diffusers pipeline

A model already on disk never reached the pickers' On Device list unless it
happened to keep a weight file beside a root config.json. Every image and video
model downloaded as a pipeline keeps its weights in component subdirs under a
root model_index.json instead, so the hub inventory scan behind /api/hub/local
rejected it. Pointing Custom Folders at one was worse than empty: the LM Studio
publisher walk descended into the pipeline and offered vae, transformer,
text_encoder and audio_vae as four separate models, none of them loadable.

Teach the hub scanner the same pipeline-root test routes/models.py already
applies, in the three places that only accepted a root config plus loose
weights, and keep a pipeline row through the custom-folder format filter: the
layout has no loose weight to classify, so the row is "unknown" by construction
rather than by fault.

* Cover the local diffusers pipeline scan with tests

* Pin what the pipeline exemption must not let through

Three gaps in the cover added with the scan change, each found by mutating the fix and
watching the suite stay green.

The custom-folder format filter now waves a row through on its shape, and nothing said
what it still has to reject: replacing the whole predicate with True passed. A folder
holding a config.json and no weights, which an aborted download leaves behind, reports
the same "unknown" format and no loader can start it, so it pins the boundary.

The predicate is applied to every row the filter did not already accept, and a row's
path can be a GGUF file rather than a directory. A missing path, a file, and a
directory whose model_index.json is itself a directory must answer False rather than
raise, because an exception there fails the scan and empties the picker.

The publisher walk was only covered one level up. Adding the model folder itself as a
scan folder is the obvious thing to do and used to publish vae, transformer and
text_encoder as three models.

* Drop the unused H3_TASK_KEYFRAMES import from the video backend

video.py only branches on H3_TASK_REFERENCES; the keyframe constant is read
from video_minimax_h3 directly by the tests that need it. The hoisted-import
safety net in Source lint flags the unused name as a blocker.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Stage the hosted pre-quantized H3 denoiser in the video download plan

The plan already drops the dense transformer shards whenever a hosted
pre-quantized checkpoint covers them, but nothing put that checkpoint back:
an int8 or fp8 H3 stage skipped 66.3 GB of base shards and added none of the
20.25 GB artifact the load actually opens. The byte total under-reported the
stage by the size of the checkpoint, the disk preflight cleared a volume that
could not hold it, and an offline stage completed without the one file the
load needs.

_denoiser_prequant_hub_files mirrors the pre-cast encoder helper: it resolves
the family's hosted checkpoint, confirms the file really exists on the Hub,
and prefers the repo-root name over the legacy scheme name in the same order
the load tries them. An unreachable repo is logged and yields no files, so a
gated or renamed artifact keeps the dense shards instead of sinking the plan.

The progress-bar estimate is deliberately left alone: it counts cached bytes
for the checkpoint and base repos only, so adding a third repo there would
leave the bar permanently short of 100 percent.

* List both H3 denoiser partitions in the picker, not only FL2VA

The bundle-repo filter accepted only minimax_h3_fl2va*, so every published
minimax_h3_ref2va* quant was hidden from the variant listing. The loader
disagrees: validate_h3_transformer_filename accepts either partition, on the
grounds that which one is picked IS the task, and h3_transformer_task routes
Ref2VA to the reference-video workflow this PR adds. The community bundle repo
publishes three Ref2VA quants today, so the reference path was unreachable from
the remote catalog.

Accept both prefixes from one shared tuple and keep excluding the Qwen3-VL
encoder and VAE companions, which are never picks for either partition. The
filter test asserted the old behaviour and is updated with it.

* Bound H3 reference-audio decoding to the trained window

The reference-video decoder already selects, resizes and refuses incrementally
because the encoded size says nothing about the decoded size. The audio decoder
did not: it appended every resampled block to a list and then allocated a second
full buffer in np.concatenate, with no duration or sample cap.

The route accepts 32 MiB of encoded audio, which is over half an hour of
compressed stereo. That lands as roughly 1.9 GB of float32 and doubles again in
the concatenate, and up to three references are accepted per request, so an
ordinary long music or podcast file picked by mistake could exhaust the host
before the background job even started.

H3's reference window is 15 seconds, so anything past it is unusable rather than
merely large. Refuse it while decoding, with the same shape of message the video
guard uses, instead of decoding it first.

* Refuse a quantized H3 reference load instead of seeding the keyframe denoiser

The hosted pre-quantized checkpoints are FL2VA (keyframe) denoisers. Ref2VA
shares their module shapes and the same base model, so resolve_prequant_source
handed one back for a reference load, it passed every metadata check, and
seeding it made load_components skip the real Ref2VA transformer. The request
then generated from the wrong partition rather than failing, which is the worst
of the three outcomes.

The route accepts h3_task, so this was reachable from the public API even though
the picker does not expose the choice yet. validate_load_request now refuses the
pairing with a message naming the workable alternatives, in the same place it
already refuses a scheme with no hosted checkpoint, and the modular loader drops
to the released components if a direct call reaches it. Nothing changes for
keyframe loads, which are what the checkpoints are.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Skip modular-workflow families in the dense text-encoder plan assertion

The plan-unchanged sweep from main walks every family and asserts the dense
budget plan_diffusion_memory received. MiniMax-H3 is the first modular-workflow
family to reach that list, and load_pipeline dispatches to the workflow's own
loader before the planner runs: each component is built by its own
from_pretrained, so there is no single dense pipeline to budget and no plan call
to assert on. Skip it the way the sweep already skips wan2.2-t2v-a14b.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Scope the paired-axes canvas rule to keyframe requests

A half-specified width/height is long-standing, documented API behaviour: the backend
resolves the missing axis from the family's default preset, in both
validate_video_request_shape and _resolve_keyframes. Applying the new paired-axes rule
as an unconditional request validator rejected those calls with a 422 before family
validation ever ran, breaking existing LTX, Wan, Hunyuan and prompt-only H3 clients.

The rule still holds where it means something: with a keyframe present the canvas is
matched to the source aspect whenever either axis is missing, so the axis the caller
sent would be silently discarded.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Keep the CUDA sd-cli pin and translate a mirror-only tag upstream

The merge with main brings in the accelerator-aware installer, whose fallback
translates a mirror-only -u<id> pin back to the upstream release it was built
from instead of skipping the upstream attempt. That is strictly better: skipping
kept the round trip cheap but dropped the pin entirely on every host the mirror
does not build, leaving them on upstream latest.

test_a_mirror_only_pin_is_never_requested_upstream asserted the old shape, that
the fallback settled for upstream latest. It now pins the new one: never the
literal -u<id> string, the translated release instead, and no latest attempt at
all because the translated pin succeeds.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Han <danielhanchen@gmail.com>
2026-08-09 10:05:58 -07:00
Michael Han
b3705f44b9
Studio: add a loaded models indicator with per-model eject (#8082)
* Studio: add a loaded models indicator with per-model eject

A loaded model is only visible on the page that loaded it. Leave Chat for the
Hub or Train and nothing on screen says a model is still holding memory, so the
only way to check or release it is to navigate back.

Adds a compact card in the bottom-right listing everything resident, with an
eject button per row. Chat, images, video and dictation each own a runtime and
their own /status, so all four are read and merged. A TTS load is split out from
a chat load by audio_type: same picker, but it does not answer prompts.

It joins the existing bottom-right stack in provider.tsx alongside the update
banners and the download panel, so nothing overlaps. Collapses to a pill, and
that choice persists. On by default, with a toggle in Settings, General,
Notifications.

Reads fail soft per runtime, so a chat-only host missing /video keeps its other
rows. Ejecting the active chat model reuses the API monitor's read, unload,
re-read sequence, since an API auto-switch can replace the model mid-eject.

* Studio: address review on the loaded models indicator

Eject the row's own model, not whatever is active. An API auto-switch can land
between the poll and the click, and re-reading unconditionally would free a
model nobody asked to free while reporting the clicked one as ejected. The
sequence moves to eject-chat-model.ts, taking its I/O as deps like
api-monitor/unload-resident.ts, so the scoping is under test.

Fall back to the top-level STT fields. Servers predating the per-engine split
report the resident Transformers model only there, so those installs showed no
dictation row and had no eject for it.

Bound each status read. authFetch has no timeout, so a runtime that accepts the
connection and never answers left the Promise.all pending forever, and with it
the in-flight guard that gates every later refresh.

Re-sync Images and Video after an eject. Both hold their own status and re-read
it on tab activation, not on a timer, so ejecting from the indicator left their
controls offering to generate on a freed runtime.

Add both preference keys to "Reset all local preferences", which otherwise left
the indicator hidden or collapsed after a reset.

* Studio: verify the row before the identity-less unloads

/images/unload, /video/unload and the STT unload carry no model id and release
whatever their runtime holds, so acting on a row up to one poll old could free a
model nobody clicked while reporting the clicked one as ejected. The image and
video races need a load landing in that window; dictation loads on demand and
releases when idle, so its engine can change with no user action at all.

Each now re-reads its runtime and only unloads when the resident model still
matches the row. This narrows the window to the round trip rather than closing
it, which would take a backend that accepts the model id.

Ejecting reports an outcome instead of a bare string, so a stale row says the
model is already gone and names what took its place, rather than claiming a
success it did not perform. An unreadable dictation status is now an error
rather than a false success.

* Studio: stop dictation rows printing their engine twice

The llama.cpp and whisper.cpp STT sidecars report their engine name as the
device (stt_mtmd_sidecar.device is "llama.cpp", stt_ggml_sidecar.device is
"whisper.cpp"), so a row read "Dictation - llama.cpp - llama.cpp". Only the
Transformers sidecar reports a real device.

joinDetail now drops repeated parts, so the engine is named once and a genuine
device still shows beside it.

* Studio: make the loaded models card movable and keep it off the Live monitor

The card and the Live monitor both anchor to the bottom-right, so opening the
monitor buried the card underneath it. The monitor is draggable and resizable,
so a fixed offset would only hold until it moved.

The monitor now publishes its box. The corner stack lifts above it, but only
while it is in the stack's column and low enough to be in the way, so a monitor
dragged elsewhere leaves the corner alone. This clears the update banners and
the download panel too, which had the same overlap.

The card also gets a drag handle: anchored to its corner until moved, then kept
where it was left, clamped back into view if the window shrinks. Its position
persists and joins the reset list.

* Studio: use the AI brain icon and lead the Notifications section

The loaded models card and the Train wizard's Model step both take
AiBrain01Icon, and the indicator toggle moves above the llama.cpp one so the
Notifications section leads with it.

* Studio: let the collapsed indicator be dragged too

The drag handle only existed in the expanded header, so the pill could not be
moved. The pill is now its own handle: a press becomes a drag past a few
pixels, below that it stays the click that expands the card, and reading the
flag clears it so a keyboard activation is not swallowed.

Re-clamping now also runs on a ResizeObserver, so expanding a pill dragged to
the bottom edge pulls the taller card back into view instead of growing off
screen.

* Studio: address review on the loaded models indicator

Keep the Chat picker selection when an eject leaves the model resident, so a
reload during the run no longer empties the picker while the model still runs.

Republish the Live monitor's frame from a layout effect. ResizeObserver does
not fire for a position-only change, so dragging the monitor left the overlay
stack dodging its old corner.

Cap the overlay stack's height to the space above its own bottom inset. Lifting
it over the monitor without shortening it pushed the top of a long download
list off screen.

Measure the stack column from the update banners (448px), not the download
panel (400px), so a monitor beside a banner is still dodged.

Name the precision an image or video pipeline loaded at, so a quantised build
is distinguishable from bf16 in the row.

* Studio: make the loaded models card resizable

The card is anchored bottom-right, where a native CSS resize grip has nowhere
to grow, so it resizes from a grip at the leading corner instead: the anchored
corner is held still and the box opens up and to the left. The grip shares the
title icon's slot rather than adding another control to a small header, and
double-clicking it returns the card to its default size and corner.

The size persists next to the position, is clamped to a floor and to the room
available, and is cleared by Reset all local preferences.

* Studio: open a loaded model's page from its row

Clicking a row now goes to where that model is used: chat models to Chat,
image and video pipelines to their tabs, dictation to the Voice settings tab
that drives the sidecars. The target follows the runtime holding the weights,
not the kind, so a Whisper checkpoint in the chat slot goes to Chat rather
than to dictation.

Navigation carries no search params, so it only changes page: it does not
start a new thread or reload anything. Dictation moves to the Audio page once
that lands.

* Studio: revert the resizable loaded models card

Back to the fixed-size card. Reverts 96749d1f.

Also read /api/inference/status directly instead of through the chat barrel,
matching the dictation read alongside it. The server logs show the indicator's
chat read never reaching the backend: across every session the status count
sits at roughly half the images/video/dictation count, matching the chat
page's own 10s poll rather than the indicator's 5s one, which is why a loaded
text model showed no row while an image model did.

* Studio: keep the loaded models card reachable, and stop the ejects that report work they did not do

Two of these break the feature outright, the rest report success for an eject
that never happened.

The card can become permanently unreachable. use-drag-position captured
panelRef.current once, in an effect keyed [position, reclamp]. The indicator
returns null until the first poll produces a row, so that effect always ran
while the ref was still null: no ResizeObserver was ever constructed, and the
resize listener closed over null. Neither dependency changes when the node
finally mounts, so it never re-ran, and nothing in production ever called
clampToViewport except an active drag. Dragging the card on a 2560x1440 screen
and reopening at 1440x900 left it at x=2502, off screen, taking its own drag
handle and collapse button with it; resizing did not help. The only way back
was devtools or Reset all local preferences. The node now arrives through
state so the effect re-subscribes, and the stored position is clamped as it is
read so it cannot paint off screen even for one frame.

Locale parity fails. CI's first gate is i18n:check:strict and the two new keys
were added to en.ts only, so all 11 overlays were short. Added everywhere.

The chat eject reported ejects it never performed. When nothing matching was
resident it POSTed /unload anyway and returned stillResident: null without
re-reading. The backend answers 200 "unloaded" for a model it never held, so
the user got a success toast for a no-op and their picker selection was
cleared off the back of it. Reachable by an ordinary sequence: loading B
evicts A, and the card shows A for up to one poll. It now reports the same
replaced / already-gone outcomes the runtime rows use, and only names a model
directly for a cached row, which is the one case a status read cannot see.

The dictation eject could release another engine's model. /audio/stt/unload
silently serves gguf from the transformers engine when whisper-server is
absent, and the unload response body is a fixed {loaded_model: null}, so a 200
was not evidence this engine let go. It now re-reads and reports what the
engine actually holds.

No timeout on the eject path. READ_TIMEOUT_MS guarded only readLoadedModels; a
runtime that accepted the connection and never answered left the row disabled
with a spinner until reload. Same bound, raised rather than swallowed.

An audio-input VLM was filed under Speech. The split was audio_type !==
"whisper", but the backend's own is_audio_input_type names two input types,
whisper and audio_vlm. A model that listens was labelled as one that speaks,
which is the confusion this card exists to remove.

A stale poll could restore an ejected row, and the trailing refresh could not
repair it because the in-flight guard was still held by that same read. A
generation counter retires reads issued before an eject, and a pending flag
keeps the trailing refresh.

The drag now captures the pointer, as the Live monitor's does. Without it a
release over another window is never delivered and the card follows the cursor.

Backend: the card polls four runtimes every 5s for as long as the app is open,
and only /api/inference/status was in _QUIET_POLL_PATHS. Its three siblings
are now too, or every desktop tauri.log carries three lines every five seconds.

Tests

tests/loaded-models-platform-matrix.test.ts walks the payloads
[Windows, Linux, WSL, macOS] x [NVIDIA, AMD ROCm, Intel XPU, CPU-only, Apple]
actually produce. None of it is visible from a CUDA box: ROCm reports itself
as cuda, Apple reports mps, XPU reports xpu for images but cpu for dictation
because the STT device probe never checks torch.xpu, and the sd.cpp engine
omits model_kind and puts "gguf" in dtype.

tests/loaded-models-backcompat.test.ts covers the desktop app running against
an older wheel, which is a supported configuration: it ships its own frontend
bundle and adopts a separately installed backend. /video/status and the STT
mtmd block are both days old, so a 404 route, a missing engine block, the
pre-split top-level fields and absent optional fields all have to degrade
rather than blank the rows a working runtime returned. Also pins that fields
a future backend adds are ignored.

tests/loaded-models-drag-restore.test.ts guards the restore geometry and, by
reading the source, the wiring it depends on. Four of its cases fail against
the code before this commit.

tests/studio/playwright_loaded_models_indicator.py runs 28 checks in Chromium,
Firefox and WebKit, covering Chrome, Edge and the WebView2, WKWebView and
WebKitGTK the desktop app embeds. It stubs the four status endpoints with
page.route, so it needs no model, no GPU and no llama.cpp build, and can
therefore replay the AMD, Apple and CPU-only payloads on any runner. The
position restore is here rather than in the node suite because it needs a real
layout and a real ResizeObserver. Wired into the Linux, macOS and Windows UI
workflows alongside the existing permission runs. Against the code before this
commit it reports 25/28, failing exactly on the off-screen card and the
mislabelled audio-input model.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: read the indicator's rows in one call, so the eject checks stop racing them

Staging CI on macos-14 caught this: every check up to the eject passed, then
the run died on a 60s locator timeout.

rows() read count() and then indexed nth(i). The eject checks poll it while
the row is disappearing, which is the whole point of them, so the row could go
between the two calls and nth(1) would block for the full locator timeout
rather than reporting a shorter list. evaluate_all takes the snapshot in a
single evaluation, so there is no window.

card_text had the same count()-then-read shape; it is now bounded and returns
empty rather than blocking when the card is mid-change.

Test-only. Confirmed 28/28 in Chromium, Firefox and WebKit after the change.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: finish the second review round on the indicator

Run the media pages' full unload cleanup on an indicator eject, not just a
status refresh. Images and Video kept lastLoad and canReapply, so Reapply
still offered to reload the model that was just ejected, and the stale
quantisation stayed on screen. Both now share that cleanup with their own
Unload rather than duplicating half of it.

Cap the overlay stack under a monitor parked high in its column. Avoidance was
skipped entirely whenever the monitor's bottom sat above the midpoint, on the
grounds that the corner was free, but the stack grows upwards from the bottom
and a full download list plus the card reaches well past halfway. It is capped
to the gap below such a monitor instead, since lifting over it would be wrong.

stackBottomInset and stackMaxHeight now come from one stackGeometry call, so
the two cannot disagree about where the monitor is.

* Studio: stop the chat header claiming an evicted model is loaded

Loading an image or video model evicts the chat model: the GPU arbiter allows
one owner and logs 'evicting chat for diffusion'. Nothing on the chat page
said so. modelLoaded was '!!checkpoint && !modelLoading', which reads the
picker selection rather than what the backend holds, and the status poll's
null-active_model branch reset three capability flags but left the checkpoint
alone. So the header kept its green tick for a model that was gone and the
next prompt came back as a bare 'Request failed (400)'.

The store now tracks residentCheckpoint from /api/inference/status, published
in applyActiveModelStatusToStore so the poll and the readopt path share it,
and the header derives loaded from that. undefined until the first read, so
startup does not flash 'not loaded'; an external model is unaffected, having
nothing resident.

An eviction also raises a toast naming the model, since it is otherwise silent
and the card in the corner was the only thing reporting it.

* Studio: fix the header tick for a model that was evicted

The previous commit added residency tracking but changed the wrong
modelLoaded: that one gates image attachments. The tick in the header comes
from the model selector's own isLoaded, which was 'selected !== ""', so it
still lit up for a chat model an image load had already evicted.

The selector now takes an optional loaded prop, defaulting to the old rule so
the Images and Video pickers are untouched, and the chat header passes
residency through it. A test reads both the selector rule and the header call
site out of the source, since the failure mode here was wiring, not logic.

* Studio: show a loading model in the indicator, with the toast

The load toast appeared at once and the card up to five seconds later, so a
slow load looked like nothing was happening anywhere but the toast.

The four load calls now announce themselves. model-eject-events becomes
model-lifecycle-events, and withModelLoadNotice wraps loadModel,
loadDiffusionModel, loadVideoModel and loadSttModel, so every caller is
covered without each page remembering to and the announcement cannot drift
from the request. The indicator adds a row on the start event and re-reads on
the settle one, rather than waiting for its next tick.

Loads are also read from the polls that already carry them: /status reports
loading[] and the dictation status reports loading per engine. That covers a
load started in another tab or before the page opened, which no event can.

A loading row shows a spinner where the eject button goes, since there is
nothing resident to release yet, and a status row for the same runtime always
replaces the announced one.

* Studio: let an audio VLM stay a chat row, and keep an exiting monitor from clearing the live frame

Two review items from the latest round.

An audio VLM is a chat model. is_audio means TTS in this codebase -- both
ModelConfig constructors build it as `audio_type is not None and audio_type !=
"audio_vlm"`, llama.cpp keeps _is_audio False for csm/whisper/audio_vlm, and
mlx_inference says so outright: "audio_vlm (omni audio input; is_audio stays
False -- it means TTS and redirects in the chat route)". The frontend already
agrees elsewhere: isMultimodalResponse counts audio_vlm as multimodal chat
capability, which is what lets a user attach audio to a chat message.

So the audio types split three ways, not two: whisper is the ASR sidecar,
audio_vlm answers prompts and happens to listen, and the remaining four speak.
The previous rule sorted every audio type as speaks-or-listens and filed
Gemma 3n under Dictation. Nothing was user-visibly wrong, because is_audio is
never true for audio_vlm and the row already fell through to Chat -- but the
rule encoded a false invariant and the test pinned it as the contract, which is
the part worth fixing.

Reopening the Live monitor during its exit animation blanked the frame.
AnimatePresence defaults to sync mode, so the replacement panel mounts while
the old one is still animating out, and the old one unmounts last. Its cleanup
called setFrame(null) unconditionally, wiping the frame the replacement had
just published. Nothing republishes afterwards: the reconcile effect is
ResizeObserver-driven and the republish effect keys on layout, so a monitor
left sitting still never writes again. The overlay stack then dropped back to
the bottom-right corner and covered the open monitor, including its close
button.

The store now records which panel published the frame, and clearFrame is a
no-op unless that panel still owns it.

tests/monitor-frame-ownership.test.ts covers the reopen-during-exit case, a
lone close still clearing, the replacement clearing its own frame afterwards,
and that no-op writes still do not notify (the overlay stack re-renders on
every notification). Six of its seven cases fail without the change.

* Studio: keep the images and video loading rows up for the whole background load

Both loads only start the work: begin_load hands off to a daemon thread and the
POST returns at once, while /images/status and /video/status keep reporting
loaded: false until it finishes. withModelLoadNotice settled on the POST, so the
indicator row appeared and vanished within one round trip while the page toast
went on saying "loading" for minutes, which is the exact gap the notice exists
to close.

withBackgroundLoadNotice settles from the same load-progress endpoint the toast
watches instead. The poll belongs to the load call rather than to a page, so the
row still settles when the user navigates away mid-load; a load that never
started settles from the POST, so exactly one of the two paths ends the notice.
An unreadable progress read is not treated as terminal, since a restarting
backend would otherwise drop a live row, and an hour-long deadline covers a
backend that never answers again.

* Studio: say what the eject read bound does and does not cover

* Studio: bound each background progress read, and drop pending loads on disable

Two follow-ups on the loading rows.

The hour-long deadline only bounded the settle loop if every turn of it ended.
A load-progress request that accepted the connection and never answered parked
the await forever, so the deadline was never tested again and the row stayed
loading for the life of the tab. Each read now runs under its own AbortController
timer, and both progress endpoints take a signal so the request is really
dropped, not just ignored. A plain controller rather than AbortSignal.timeout,
which the older WebKitGTK builds Tauri embeds do not have.

Nothing listens for the terminal event while the indicator is disabled, so a
load in flight when the pref went off left a pending entry that came back on
re-enable as a row no poll could retire: withPendingLoads only yields to a
status row for the same runtime, and a failed or since-unloaded load has none.
The pending map is now emptied on the disable transition, adjusted during render
rather than from an effect so the stale rows never reach the DOM.

* Studio: re-read the chat status when another runtime loads

The header kept its tick on an evicted model because nothing ever told the
chat page the model had gone. syncInferenceStatusToStore, the only thing that
updates residency, runs on mount and from refreshModelLists when the model
lists change. It is not on a timer. So an image load evicting the chat model
was never observed here: residentCheckpoint stayed undefined, which reads as
loaded, and the previous two commits could not take effect.

Confirmed against the running server rather than by reading: /api/inference/status
reports active_model null while the header still showed the model ticked, and
/api/models/list, which only that sync calls, was absent from the log for the
whole period after the eviction.

The chat runtime now re-reads whenever another runtime finishes a load, using
the lifecycle event added for the indicator. Loras are skipped: only residency
is in question.

* Studio: settle a cancelled load, and show a replacement next to what it replaces

Two faults in the loading rows, both in the window where a load is in flight.

A cancelled or evicted load leaves load-progress reporting null: all three
engines return that only for "nothing loading and nothing loaded", and unload
bumps the load token and drops the loading marker, so the phase never changes
again. Treating null as non-terminal was wrong -- begin_load records its loading
state before the POST answers, so a read before the first byte moves already
says downloading, and null after that means the load ended with nothing to show.
Ejecting a model whose replacement was still downloading therefore replaced the
row with a spinner that had no eject on it and stood for the full hour deadline.
The Images page's own poll has always treated null as terminal, "else this loop
spins forever". An unreadable read stays distinct from it, as undefined.

The other half is why that eject was offered at all. Images and video keep the
old pipeline resident while the replacement downloads, freeing it only at the
commit, so status reports the old model for the whole pull. Suppressing the
announcement on the runtime alone hid the incoming model for minutes, showing
only the one being replaced. A status row now wins only when it describes the
same load; a row that is itself loading still wins, which is what keeps chat and
dictation from announcing a load twice when the backend spells the name
differently.

* Studio: retire a settled load row only once a read replaces it

The row vanished at random. On the settle event the optimistic row was dropped
immediately and a read was asked for, but that read is a round trip away and
can be queued behind one already in flight. For that gap the card had one row
fewer, and nothing at all when it was the only one, so it blinked out and came
back a moment later.

The row is now retired by the read that supersedes it rather than ahead of it,
so the card hands over from the announced row to the status row with no gap
either way. A read that fails still retires it, from the same finally, so a
row cannot be left spinning.

* Studio: initialise the loaded models preference before the indicator

There is a real cycle here: the barrel evaluates the indicator, the indicator
imports the settings barrel, that eagerly evaluates SettingsDialog and so
general-tab, and general-tab's reset list dereferences
LOADED_MODELS_PREFERENCE_KEYS back through the barrel it is still inside.

It happens to work today only because app.tsx reaches the settings barrel first,
which finishes the preference module before general-tab's body runs. Entering
the loaded models barrel first is enough to break it: under Vite dev, which
serves native ESM and so has no bundler to reorder the graph, that throws
"Cannot access 'LOADED_MODELS_PREFERENCE_KEYS' before initialization" and the
app never starts.

Exporting the preference module first evaluates the constant before the
indicator is touched, so either entry order is safe. Pinned by a test, since a
bundler can hide this.

* Studio: gate the picker and hub "Loaded" marks on residency too

The header tick was one of three places claiming a model was loaded, and
all three read the picker selection. An image or video load evicts the
chat model, which leaves the selection alone, so the dropdown's green
"Loaded" badge and the Model hub cards went on marking a model the
backend had already released.

Both now use the same rule as the header: resident, not merely picked.
An unread status stays as it was, so nothing flashes on startup, and an
external selection is untouched since it holds no local weights.

* Studio: drag both floating panels without a render per frame

Dragging the loaded models card or the Live monitor was heavy. Three
things, all per pointermove: each move set React state, so a trackpad
reporting faster than the display refreshed rendered frames nobody saw;
the move was written to left/top, which is the layout path, and both
panels are expensive to lay out again (a wide blurred shadow on one, a
backdrop filter on the other); and the card's reclamp effect was keyed
on the position it was updating, so every frame disconnected its
ResizeObserver and built a new one, each rebuild forcing a synchronous
layout.

A drag now records the offset, asks for one animation frame, and moves
the node with a translate3d, so it costs no render at all. Release hands
the offset back to left/top, written to the node as well as to state so
it cannot flash at the spot it started from, and folds in a frame still
owed rather than landing behind a flick.

The monitor also published its box to the shared frame store on every
frame, re-rendering each overlay subscribed to it. That now settles on
release, so the stack moves aside once instead of chasing the drag.

* Studio: drop the chat pick when the server evicts the model

Loading an image model evicts the chat one, and the picker went on
naming it. The last few rounds only dimmed the marks that said "loaded",
which was the wrong end of it: the name on its own reads as "this is my
model", and sending to it comes back a bare 400.

An eviction now clears the pick, so the picker drops to "Select model",
which is already what a server-side unload does. Guarded on the model
having been known resident and on no load being in flight, since a load
also reports no active model while it runs and must not wipe the pick
the user just made.

* Studio: time the load row's giving-up from the last healthy read, not the start

An absolute hour deadline retired the row on a download that was still visibly
progressing: a large video checkpoint on a slow link legitimately runs longer
than that, and every progress read still said downloading. The window now
measures a stall, restarting on each healthy read, so only a sustained run of
unreadable polls gives up and a load that keeps reporting progress is never
abandoned.

Also drop the drag sentinel when the handle that started the drag has no click
to consume it. The expanded card's grip is not a button, so after dragging by it
the flag stayed set, and the collapsed pill's next click read a drag that was
not its own and refused to expand. Cleared on both end paths: pointerup and the
buttons === 0 bail for a release the window never saw.

* Studio: let the loaded models card be closed, and reopen it on the next load

Adds an X beside the collapse chevron, and swaps the card's brain badge
for the sparkle.

Closing is its own flag, not the Settings toggle. They read as the same
thing but are not: closing means "not now", so the next model load
brings the card back, while the toggle means "stop showing me this" and
no load may override it. Reopening happens on the start of a load, so
the card is up for the same stretch as the toast, and setting the flag
to what it already holds is inert, since every load start writes it.

Kept in storage rather than in memory, like the collapsed state, so a
reload does not undo a close.

* Studio: eject with the eject glyph, and badge the card with the single sparkle

A row's X released the model's weights while the header's X only closed
the card, so one glyph stood for two unrelated acts. The row now uses
Remove circle, which is already the model picker's own eject shortcut,
and the header keeps the X the Live monitor closes with.

The badge was Sparkles, which is the two-star glyph. Sparkle is a
separate icon and the free set shipped in 4.1.1 predates it, so it is
defined in lib/ beside the chevrons rather than moving every other glyph
in the app to a newer icon set for one shape. The path is the published
stroke-rounded outline with its fixed stroke swapped for currentColor.

* Studio: drop the drag sentinel option, which guarded a state that cannot happen

I added this on a review note and the note was wrong. Every drag handle wires
onPointerDown to startDrag, and startDrag zeroes movedRef; pointerdown fires
before click, so the pill always clears the sentinel before its own click reads
it. A drag by the expanded grip cannot leave a stale flag for the pill to trip
over, and the clickFollows option was guarding a state the code cannot reach.

Checked rather than reasoned: with the option removed, dragging by the grip,
collapsing, and clicking the pill once reopens the card, on all three engines.
That sequence is now a browser check, and it asserts the collapse really
happened first so it cannot pass vacuously. The unit tests assert the invariant
that actually holds the line, which is that every handle goes through startDrag.

* Studio: keep recording loads while the card is closed, so one can reopen it

Closing the card is meant to mean "not now", with the next load bringing it
back. The dismissal was cleared correctly, from the indicator's own
subscription, but the rows come from useLoadedModels and that subscription
early-returned while the card was hidden. So the loading: true event was never
recorded, and the card reopened onto nothing.

Chat and dictation limped: the 5s poll synthesises their loading rows from
status.loading and the per-engine flag. Images and video have no such fallback,
so with nothing else resident the card did not come back at all until the load
finished, which on a large download is minutes. Reproduced in a real browser
before fixing, and the reopened card now reads "Image . Loading" for the model
that reopened it.

Recording is now separate from showing: only the Settings toggle stops it, since
that is the one that means "stop telling me", while a closed card or a route
that hides the card keeps listening. The pending map is still emptied when
recording stops, so a load missed while the preference was off cannot come back
as a row no poll can retire.

* Studio: do not read an unreadable dictation status as an empty one

The dictation unload answers {loaded_model: null} whatever it did, and the
backend serves gguf from the transformers engine when whisper-server is absent,
so the eject re-reads the status to find out what actually happened. But
readSttStatus returns null on any non-2xx as well as for an empty runtime, and
the re-read treated the two the same: a transient 404 or 500 on the confirming
read toasted "Ejected" and dropped a row whose model was still holding memory.
That is the exact case the re-read exists to catch.

An unconfirmed unload is now its own outcome rather than being collapsed into
success or failure, since neither is true, and it warns instead of claiming the
memory was freed. Images and video already raise here, since their unload
responses go through parseJson; only dictation swallowed it.

* Studio: re-read chat residency when a media load takes the GPU, not when it ends

The arbiter evicts chat inside the image or video load POST, before the
background download starts, but the chat runtime only re-read its status when
that load settled. Since the settle waits for the whole download, the picker and
the header went on naming the evicted model for its entire duration.

Measured against a live backend rather than inferred: with Qwen3-0.6B-GGUF
resident, /api/inference/status reported active_model null 1.8s after the image
load POST returned, and a send to the model the picker still offered answered
400 "No model loaded. Call POST /inference/load first."

The load is now announced a second time once the POST returns, which is the
instant the eviction has committed; announcing only before it would have had
listeners re-read a status that was still correct. Dictation is excluded, since
it is a sidecar and takes no GPU ownership.

Also settle the media page's own busy state when an eject cancels its load. The
indicator shows the resident row next to the incoming one during a replacement,
so that eject is reachable; the page's listener then stops the load-progress
poll, which is the only thing that clears busy. Left set it locked the page --
the picker ignores every choice, and Unload is not rendered once the status read
comes back empty -- and both pages stay mounted for the session, so only a
reload recovered.

* Studio: stop the indicator reporting ejects it did not perform

Three of the four eject paths could report a success with no unload behind
it, and the card could overwrite a saved position it was only adapting to
the current window. Found by driving the branch against a real backend in
Chromium, Firefox and WebKit with the four /status endpoints stubbed.

A stale row over an idle runtime said "Ejected X". ejectRuntimeRow folded
verifyResident's "gone" verdict into "ejected", so a row up to one poll old
whose runtime had already released everything reported an unload that never
ran. Images, video and dictation all reach this without anyone doing
anything: the dictation sidecars release themselves when idle. It is now a
distinct alreadyFree outcome, and the toast says the model was no longer
loaded. The row still goes, since its memory is free either way. That also
retires the `&& resident` guard, which could not be false: verifyResident
only answers "replaced" when resident is set.

A cached chat row was unloaded without confirmation. It is the one path with
no scoped re-read, because a cached row is never the active model and so can
never match one, and /unload answers 200 for a name the backend no longer
holds. So the success was the call itself rather than evidence of a release,
and the picker was cleared on it. ejectChatModel now takes an optional
readCached and checks the row against what the runtime still holds, the way
every other path checks its own.

The card overwrote a position saved on a larger screen. The persist ran from
an effect on `position`, and a reclamp changes `position` too, so opening the
app on a laptop wrote the laptop's clamp back to localStorage and going back
to the large monitor left the card where the laptop had put it. Only a landed
drag is stored now; the read path clamps, so nothing needs the clamp kept.

Arabic said the card is in the bottom-left. Nothing sets document.dir and the
stack is anchored with a physical `right-4`, so it is bottom-right there too.

Covered by three cases in the node suite for the cached row, one for the
persist rule, and one in the Playwright suite for the stale row, which runs
on all three engines. Full suite 896 pass, typecheck, i18n parity and build
clean, and the same on a tree merged with current main (1126 pass).

* Studio: keep a row whose runtime could not answer, rather than reading it as gone

A read that fails or times out comes back as null and the describe helpers map
null to no rows, so one bad poll took a loaded model off the card. Against a
remote Studio all four reads can fail on the same blip, and the whole card went
while every runtime stayed resident.

An unreadable source now keeps what it last showed. A readable one is still
replaced outright, including by an empty answer, so an unload clears the row as
before -- that is the distinction that matters, and both halves are checked in
the browser suite: a sustained 503 on the chat status keeps the row, and a
readable empty status still retires it. Reverting the change fails the first and
leaves the second passing.

* Studio: sequence the chat refreshes, and reopen a closed card for a silent load

Announcing a media load twice put two chat refreshes in flight inside the load
POST's own duration, measured at 1.8s against a live backend. They read the
status either side of the eviction and answer in whatever order the network
gives, so the older one could land last and re-pin the model the newer had just
seen released, leaving chat claiming a model that 400s on send until the load
settled. Every refresh now takes a generation and the newest wins; a superseded
one writes nothing back and reports no failure either, since its answer
describes a moment that has passed.

Separately, the close tooltip promises "Back on the next model load", and that
did not hold for a load started outside the frontend: the OpenAI-compatible API
and auto-switch raise no lifecycle event, and dismissing the card had also
stopped the poll, so nothing was left to notice. The poll now runs while the
card is closed, and a row appearing that was not there on the previous poll
reopens it. The first poll after closing is the baseline rather than a reopen,
or -- since a dismissal survives a reload -- whatever was already resident would
make the card impossible to close at all.

* Studio: keep a settled load's row when the read that should replace it failed

An optimistic row is retired once a status read has replaced it with a real one.
But readLoadedModels is handed the polled rows only, and an optimistic row lives
in the pending map, so a read that could not see that source has nothing to
preserve: retiring anyway took the row for a model that had just finished
loading off the card, on the strength of a request that failed.

The read now reports which sources it could say nothing about. Those stay
settled, so the next readable poll retires them instead, and a read that failed
outright is treated as evidence about none of them. A source that did answer is
retired exactly as before, including when it answers empty, or the row would
never go at all.

* Studio: stop writing off an eject target that was only demoted to the cache

Eject an active row that was replaced inside the card's five-second poll window
and nothing was released. The standard backend does not evict on a switch:
load_model only moves active_model_name and leaves the previous model in
backend.models (core/inference/inference.py:620), which /status still reports
under `loaded` (routes/inference.py:8112). So a switch from another tab, the
OpenAI-compatible API or the CLI demotes A to a cached entry that is still
holding its weights, the scoped read cannot match it, and the click reported
"A is no longer loaded. B took its place and was left alone" having unloaded
nothing. With the replacement since gone it read as alreadyFree and dropped the
row as well.

The branch now asks what the runtime is really holding before writing the row
off, reusing the readCached the confirming read already had, so the demoted
model is unloaded by name and confirmed like any other. A target that is
genuinely gone still reports replaced and unloads nothing, and with readCached
omitted the behaviour is unchanged. GGUF is unaffected: that branch reports
loaded as the single active id.

Three cases in the node suite: a row replaced while still cached, a row
replaced and really gone, and an idle runtime still holding the row. The first
and third fail with the source reverted.

* Studio: keep the indicator off the login page, and surface what a GGUF load left behind

Two from the latest round, both real.

Recording polled four protected endpoints on /login. Widening the recording
flag past `enabled` was right for dismissal, so a closed card still hears the
load that reopens it, but it went one step too far: `canShowIndicator` also
carries the auth gate, and gating recording on the Settings toggle alone left
the poll running before there was a session. Each tick then sent four requests
that 401 and drove authFetch's refresh-then-redirect ladder, every five
seconds, for as long as the login page was open. Reachability is now hoisted
and shared, so tracking survives a dismissal but not a route with no session.

A model cached behind a GGUF was invisible and could not be released. The GGUF
load unloads only the ACTIVE Unsloth model (routes/inference.py:6603-6610), so
a Transformers model cached behind it keeps its weights, but the GGUF status
branch reported `loaded` as the single active id. So after loading A, then B,
then a GGUF, A held VRAM that nothing surfaced and no client could free. That
branch now also reports what the registry still holds, deduped against the
GGUF's own id and peeking rather than constructing the orchestrator. The unload
route already reaches a cached model by name through
_resident_standard_model_name, so the rows this adds are ejectable as they
stand.

Three backend cases and one frontend case, each failing with its source
reverted. 919 node tests and 31 backend tests pass; typecheck, i18n parity and
build clean.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: lift the corner stack above the chat composer, which the card was covering

The loaded models card is the first overlay in the bottom-right stack that is
persistent rather than transient, and the chat composer docks to the bottom of
that same column once a thread has turns. The card landed on top of the Send
button and swallowed the click: Playwright resolved the button, found it
visible, enabled and stable, then retried for 60s while
"unsloth/gemma-3-270m-it-GGUF ... subtree intercepts pointer events". Caught by
the chat UI suite on both ubuntu-latest and macos-14.

The stack already knows how to keep clear of something: the Live monitor
publishes its box and stackGeometry lifts the stack above it. That store held
one box, from one publisher, so the composer had nowhere to say where it is.
It now keeps a box per publisher and dodges their union, which is also the
right answer while the monitor is mid-exit and two panels are briefly
published at once.

The composer publishes through a small usePublishedFrame hook, re-measuring on
resize and through a ResizeObserver because it grows with its input and moves
from centred to docked without a resize event. A hidden composer measures 0x0
and is withdrawn rather than published, which would otherwise pull the union
to the top-left and pin the stack there.

Verified against a live backend at 1280x900, 1280x720 and 1440x900 with the
composer docked: the element under the Send button's centre is the composer,
and reverting the publish alone puts the overlay stack back there at all
three. 1289 node tests pass, typecheck, i18n parity and build clean.

* Studio: fold the stack's obstacles one at a time, not as their bounding box

Follow-up to the composer fix. Publishing a second box made the store hold two,
and reading their union as one obstacle was wrong: a tall monitor and the wide
docked composer share almost no area, so the rectangle around the pair covers
most of the viewport. stackBottomInset then lifted the stack to its clamp near
the top of the screen and put it back over the monitor it was dodging. The chat
UI suite caught it on Windows and macOS as the card swallowing the monitor's
Close button, at the step that drags the monitor up the column first, which is
exactly when the union is most unlike its parts.

stackGeometry now folds per box: each asks for the lift it needs, the stack
takes the largest, and the height is the shortest any of them allows. The
single-box maths is untouched, so its existing cases still pin it. The store
keeps the union as a summary only, and says so.

Three cases added: the fold against a monitor parked high, which is the case
that diverges, plus an empty list and a single box matching the old calls.
1295 node tests pass, typecheck and build clean, and the docked-composer probe
still finds the composer under the Send button at three viewports.

* Studio: let only the newest status read write on the media pages

The Images and Video pages hold their own status and re-read it on tab
activation and on their own actions, never on a timer. Two reads are therefore
in flight across an eject: the activation read that saw the pipeline loaded,
and the post-eject read that saw it gone. Responses have no order, so the older
one could land last and put the loaded status back, leaving the page offering
to generate against a runtime that was already free, with no poll coming to
correct it. Both pages had it, identically.

Every read now takes a ticket before it awaits, and only the newest may write.
All three writers on each page go through the same gate, not just the refresh:
the load-progress read and the unload response could overwrite a newer answer
just as easily.

Also drops the merged rectangle the frame store still exposed. Nothing read it
after the fold landed, but it was the shape the review picked up on, and it
merged obstacles that do not touch: the rectangle around a left-hand monitor
and a bottom-right composer spans the empty space between them. The store keeps
the boxes apart and says why; stackGeometry already folds them one at a time.

Four cases pin the sequencing, all four failing with the pages reverted. 1299
node tests pass, typecheck, i18n parity and build clean.

---------

Co-authored-by: shimmyshimmer <danielhanchen@gmail.com>
Co-authored-by: danielhanchen <moonshotaisubstack@gmail.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2026-08-08 08:27:45 -07:00
Daniel Han
7103733d7b
Studio: hold the Mac capability verdict while an MLX repair can still overturn it (#8152)
* Studio: keep the Mac capability verdict provisional while MLX repair runs

* Studio: bound the MLX repair hold so a scheduler that never runs cannot spin the tabs

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: gate the Mac capability verdict on a real Apple Silicon host

The hold that keeps /api/health from publishing a chat-only verdict an MLX
self-heal is about to overturn was covered only by unit tests, which drive it
with a fake clock and a stand-in repair worker. Nothing ran it where `import
mlx.core` succeeds or fails for real.

tests/studio/mac_capability_verdict_smoke.py boots the real `unsloth studio`
through .github/scripts/boot-studio-api-only.sh and polls /api/health from the
first reply the socket gives, judging the whole sequence rather than the last
answer, since the reported bug was a verdict that was wrong for a while and
right afterwards. Three boots, one per scenario, because the self-heal is once
per process:

- real-mlx: the verdict must settle chat_only=false with /api/system reporting
  device_backend "mlx", and no reply on the way there may publish chat_only
  true.
- no-mlx-settles: MLX made unimportable and UNSLOTH_DISABLE_MLX_AUTOREPAIR=1.
  The verdict must still settle promptly to mlx_unavailable, or a Mac with no
  repair coming spins Train and Video for the session.
- no-mlx-repair: MLX made unimportable, self-heal on. No reply may publish the
  verdict while the installer runs, including well past the pre-start grace so
  the hold is provably the live worker, and it must settle once the install
  fails.

MLX is made unimportable the way tests/studio/test_hardware_dispatch_matrix.py
does it, through the import system, but from a sitecustomize on PYTHONPATH
since there is a server to boot. It hides mlx from PathFinder rather than
raising, so the find_spec in unsloth/__init__.py answers None instead of
crashing. The installer in the third scenario is a stub uv first on PATH that
records its argv and takes its time; utils.mlx_repair is untouched and runs its
real thread, real command and real subprocess against it. The recorded argv is
asserted, so a run where the self-heal never reached the installer fails rather
than passing quietly.

mlx-ci.yml gains the three steps plus a venv at $STUDIO_HOME/unsloth_studio,
which is what `unsloth studio` re-execs into and refuses to start without.
Building it over the job's own site-packages gets the real launch path without
the ten minutes install.sh costs. Path filters pick up main.py, mlx_repair.py
and the two boot scripts; timeout goes to 40 minutes for the in-flight boot,
which waits out the torch warm before the self-heal is even scheduled.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* CI: let boot-studio-api-only.sh actually boot API-only

The script exports UNSLOTH_API_ONLY=1 and its banner says --api-only, but nothing
in unsloth_cli reads that variable. Whether the web UI is served is decided by the
CLI flag alone; the backend only reads the variable back out in main.py to pick a
CORS profile, after run.py has set it from the flag. Every caller has therefore
been booting a server that serves the frontend, which is what the Playwright UI
smokes need, so the flag is opt-in and no existing caller changes.

The capability-verdict boots in mlx-ci.yml are the first caller without a built
studio/frontend/dist (it is gitignored, and that job installs with pip rather than
install.sh). Without the flag the server printed "Unsloth frontend build not found"
and exited before binding, which is how this surfaced.

Also in the smoke driver: give up a wait as soon as the server process is gone
rather than spending the full budget, and flush the boot banner when it is written
so it does not surface minutes later next to the timeout it preceded.

* Studio: drop the verdict cache and bound both halves of the MLX repair hold

Remove the localStorage hardware-verdict cache. It did not buy what it
claimed: the store deliberately kept `fetched` false, so
`capabilitiesUnknown()` is still true on a returning user's first paint
and the rows spin exactly as they do without it. Its only demonstrated
effect was unbreaking a `/settings` deep link, and it introduced a real
regression in exchange. model-selector.tsx, pickers.tsx,
model-inspector.tsx and app-sidebar.tsx read `chatOnly` with no
`capabilitiesUnknown()` gate, so a cached `chatOnly=false` during a
repair window offers MLX-only models that cannot load - worse than the
conservative `navigator.platform` guess it replaced. env.ts and both
frontend test files are back to what main has, and nothing under
studio/frontend changes in this PR.

Start the pre-start handoff grace on the first reading that sees the
warm stopped rather than the last reading that saw it running. The
warm's final stages are C-extension imports that hold the GIL for
seconds at a time, so health requests queue behind them and the next one
served can be the first in a minute. Measured from the last observed
poll the grace could already be spent by the time anyone could ask,
publishing the mlx_unavailable verdict during the very handoff the hold
exists to cover. A stopped reading between two running ones is a lull,
not the end, so it reopens.

Bound a live repair worker with _WORKER_BUDGET_S, the subprocess timeout
plus 300s. attempt_mlx_repair times the uv call but not the
mlx_stack_available() imports that verify the install nor the
detect_hardware() pass after it, and those import mlx.core, mlx_lm and
mlx_vlm on a stack this module already assumes can park indefinitely. An
alive thread was an unbounded answer, so a parked worker held the
verdict provisional for the whole session. Fix _superseded_by_mlx_repair
and mlx_repair_in_flight docstrings, which claimed a cap that did not
exist.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2026-08-08 06:47:11 -07:00
Daniel Han
95d9f23a64
Normalize the /api/health wait and extract it into one script (#8060) 2026-08-06 22:32:49 -07:00
Daniel Han
7e47cc03c1
Extract the API-only Studio boot into one script (#8029)
Twenty-one steps across eight workflows ran the same five-line body, varying
only in port, log filename and the name of the environment variable the pid
lands in. .github/scripts/boot-studio-api-only.sh takes those three as flags.

Three parts of that body are easy to get subtly wrong, which is the argument
for one definition rather than twenty-one:

  rm -rf, not `reset-password`. The boot only re-seeds a fresh
  .bootstrap_password when the auth directory is absent, so a caller that
  resets keeps the old password and the test authenticates against stale state.

  The pid has to reach $GITHUB_ENV, because the step that stops the server is a
  different step with a different shell.

  Both streams go to the log. The server writes startup diagnostics to stderr,
  so a redirect without 2>&1 leaves an empty log on exactly the failure someone
  needs it for.

Not folded into serve-unsloth-run.sh, despite the plan saying so. That script
boots `unsloth run --disable-tools` and its body is banner-key parsing and
/v1/models resolution; these boot `unsloth studio --api-only` with auth wiped
and no banner. The two share the word boot and nothing else, and each header
now says which is which.

Deliberately does not wait for health: the callers' waits differ, some polling
/api/health and stopping while others go on to rotate the password and load a
model in the same step.

Left alone: three boots inside Playwright retry loops, which re-boot mid-loop
and reassign the pid in the running shell, and three boot-briefly-and-kill
steps that keep the pid in a local variable rather than $GITHUB_ENV.

Each caller's paths filter gains the script, so an edit to it re-runs the
workflows that call it -- the trap #8015 hit when the install body moved out
from under those filters.
2026-08-06 07:40:28 -07:00
Daniel Han
607b928adf
CI: run the three mac inference smokes as phases of one job (#7978)
* CI: run the three mac inference smokes as phases of one job

The three jobs in this workflow differed only in model, port and test body.
Their checkout, setup-node, setup-python, install.sh --local --no-torch and
assert-llama-loads.sh preamble was byte-identical, so every triggering PR ran
the same install on three macos-14 runners at once. Concurrent macOS jobs are
capped at 5 per account and that pool is shared with unslothai/unsloth-zoo, so
this one workflow took 3 of the 5 slots to derive the same install three times.

They are now three sequential phases sharing a single install. Each phase keeps
its own model cache, port, server log and uploaded artifact, so a failure still
names one phase and the earlier phases' logs survive it.

Collisions the merge had to resolve, none of which were visible from the job
list alone:

  - cache-gguf and download-gguf were defined in both the tool-calling and
    json-images jobs. Duplicate step ids inside one job are a hard error, so
    they are suffixed -tools and -vision.
  - both jobs cached to the same gguf-cache directory with different models.
    Merged, the vision phase could have restored tool-phase bytes. Split into
    gguf-cache-tools and gguf-cache-vision.
  - all three boots wrote logs/studio.log, so merged, each phase would have
    truncated the previous phase's diagnostics. Split per phase.

Phase-specific values are set only through , never at job level.
Whether a later  write beats a job-level env: key of the same name
is not something the Actions docs pin down, and a phase quietly talking to the
previous phase's port is a bad way to discover the answer. Everything inside
${{ }} is a literal for the same reason: a cache key that silently resolved to
the wrong model would still pass, just against the wrong bytes. The literals
resolve to the same strings as before, so existing caches still hit.

Verified: one job, 37 steps, no duplicate ids or artifact names, no dangling
steps.* references, exactly one install, three distinct ports and logs, and the
extracted test-command set is identical to before once the cache-directory
rename is normalised.

macOS jobs in this repo: 29 -> 27 on top of #7975 (31 -> 29 on main alone).

* CI: bump the renamed GGUF cache keys so the merged phases can cache at all

Caught by an A/B on staging CI, not by inspection.

Splitting gguf-cache into gguf-cache-tools and gguf-cache-vision kept the cache
keys byte-identical, which looked safe. It is not. actions/cache identifies an
entry by key AND a version hash derived from the path input, while key
uniqueness is global per ref. So the pre-existing gguf-cache entries still hold
the old keys: a restore into the new directory misses on version, and the
matching save is then refused with "Unable to reserve cache with key ...,
another job may be creating this cache".

The result is not a one-time repopulation. It is permanent: two consecutive
staging runs of the merged workflow both logged "Cache not found for input
keys" and both failed to save, so both re-downloaded the tool model (~890MB)
and the vision model (~2.4GB + 986MB). That is roughly 3.3GB per run, forever,
on a macOS runner from a pool capped at 5 concurrent jobs.

Bumping the key suffixes (tools v1 -> v2, vision v2 -> v3) gives the new paths a
free key so the entries actually populate.

The rule this encodes: changing an actions/cache path requires changing the key
too, even though the key alone looks like it fully identifies the entry.

* CI: keep per-phase timeouts and phase independence in the merged mac smoke job

Merging the three mac inference jobs into one job lost two properties the
separate jobs had.

A step with no explicit `if:` gets an implicit `success()`, and that check is
job-wide, not per-step. So one failed step in phase 1 skipped every remaining
step of phases 2 and 3, and a tool-calling or vision regression went unreported
until phase 1 was fixed and the job re-run. Phases 2 and 3 now run under
`!cancelled() && steps.assert-llama.outcome == 'success'`: a failure inside a
phase no longer skips the phases after it, while a failure in the SHARED
preamble (checkout, install, llama.cpp load check) still skips them, since
assert-llama is itself skipped in that case. The job still ends red, because the
failed step already set the job status.

The three jobs were also capped at 25 / 25 / 30 minutes each; the merged job had
only the aggregate 90. hf-download-with-retry.sh retries forever and names the
enclosing timeout as its bound, so one stalled download could hold a macOS slot
for the full 90 minutes and leave nothing for the phases behind it. Every step
that can block now carries its own timeout-minutes, with 90 kept as the outer
guard.

Also drops the two leftover job divider comments that still announced jobs 2 and
3 in the middle of the step list.

* CI: keep the shared preamble out of phase 1's failure chain

The previous round gated phases 2 and 3 on steps.assert-llama.outcome, so a
failure inside one phase no longer suppresses the others. It left the two shared
preamble steps on the implicit success() check, which reopens the same hole one
level up.

Install Unsloth and Assert llama.cpp both had no if:, so GitHub applied
success(), which is true only when every previous step succeeded. Phase 1's
Prime HF_HOME sits above them and carries a 15-minute timeout, and a step
timeout marks the step failed rather than cancelled. So a stalled or failing
phase-1 model download skips Install, skips Assert, leaves
steps.assert-llama.outcome == 'skipped', and silently takes phases 2 and 3 with
it. Before the consolidation those were independent jobs and still ran.

Install now runs under !cancelled(), and Assert gates on the install step
explicitly instead of on the job-wide implicit check. A phase-1 GGUF problem is
a phase-1 resource problem: the install probe that install.sh itself needs is
fetched live by hf_hub_download when the cache is cold, so the bootstrap can
still succeed and tool-calling and vision still get exercised. A genuinely
broken bootstrap still fails Install, which still skips Assert and correctly
holds both later phases out.

Ordering is unchanged, so no cache key or path moves.

Behaviour, verified against the step table: all green -> phases run; prime-hf
fails or times out -> phases run; checkout, setup-python or install fails ->
phases skipped; assert fails -> phases skipped; run cancelled -> all skipped.

* Bound the phase-1 cache actions in the mac inference smoke job

Phases 2 and 3 got timeout-minutes on their cache restore/save pairs in
the previous follow-up, but phase 1's pair was left unbounded. Before
consolidation that phase was a separate job with its own 25-minute
timeout, so a stalled cache action was bounded by it; after the merge
the only bound is the job's 90 minutes, and a stall there would hold a
macOS slot and starve phases 2 and 3.

15 minutes matches the sibling Prime HF_HOME step and phase 2's pair.
2026-08-06 01:52:18 -07:00
Daniel Han
1301e16004
Keep the file-edit turn 2 prompt to one instruction, and stop waiving its cap (#7846)
* Keep the file-edit turn 2 prompt to one instruction, and stop waiving its cap

* Tighten the turn 2 comments
2026-08-04 23:47:42 -07:00
Daniel Han
cf4acbcce5
Make the Colab oracle tripwire able to fire, and stop blaming start.py for a hung agent CLI (#7838)
* Make the Colab oracle tripwire able to fire, and stop blaming start.py for a hung agent CLI

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Keep a connection-mode cap fatal, and do not read 137 as a timeout

* Note that the opencode non-exit is intermittent

* Close three gaps the waiver opened: turn-2 side effect, attribution-ab, and the guard tests

* Bound a TERM-resistant CLI again, and judge a capped turn 2 on an artifact

* Gate both timeout statuses on the clock, keep the cron lint reachable, and make refresh --all atomic

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2026-08-04 07:42:42 -07:00
Daniel Han
3c6343b455
Sign the NSIS plugin DLLs, and fail the release on any unsigned file (#7819)
* Sign the NSIS plugin DLLs, and fail the release on any unsigned file

Both 0.1.51-beta and 0.1.512-beta ship four unsigned DLLs: NSISdl.dll,
System.dll, StartMenu.dll and nsDialogs.dll. Only nsis_tauri_utils.dll carries
the Unsloth AI Inc. signature.

tauri-bundler is doing the work already. When a signing identity is configured
it copies Plugins/x86-unicode aside, signs all five files listed in
NSIS_PLUGIN_FILES, and exports the copy as the NSISPLUGINS environment
variable. Nothing consumes it: no NSIS template references $%NSISPLUGINS%, and
the only plugin directory added is ADDITIONALPLUGINSPATH, which points at the
copy's additional subdirectory and holds exactly one file. So one DLL resolves
from the signed copy and the other four fall back to the default unsigned one.

Add the directory in our template, guarded so unsigned local builds still
compile, and add a check that unpacks each bundle and fails listing every
unsigned executable rather than stopping at the first.

* Fail the signing gate when a bundle cannot be unpacked

7-Zip leaves a partial tree behind on error and can fall back to its PE
handler, which yields sections rather than the payload. Both cases passed
the gate having verified nothing. Move !addplugindir above the includes so
the signed copy is registered before any plugin is packed.

* Tighten comments on the bundle signing gate

* Sign the bundled install script and gate on it

install.ps1 ships as a bundle resource and is the first thing the app runs
after install, but the bundler never signs it and the gate did not look at
scripts. Sign it before the build packs it in, and add .ps1/.psm1 to the
checked set. Verified on a Windows runner that signtool attaches a valid
signature to a .ps1; trusted-signing-cli lists ps1 as supported and does
not filter by extension.

* Tighten comments on the bundle signing gate

* Reduce the Windows false positive surface

Three changes, none of which alter behaviour:

install.rs no longer passes -WindowStyle Hidden -ExecutionPolicy Bypass to
powershell.exe. CREATE_NO_WINDOW already suppresses the console and the
NSIS-extracted script carries no mark-of-the-web, so RemoteSigned loads it.
That flag pair is the command line Microsoft ships as a detection test.

install.ps1 installs uv from a pinned, SHA-256 verified release archive
instead of evaluating a downloaded script in-process.

installer.nsi fills in CompanyName and InternalName, which upstream's
template leaves empty.

* Match astral's installer on unmanaged installs, mirrors, and the PATH probe

UV_UNMANAGED_INSTALL forces no-modify-path in astral's installer, so it must
here too, and honour UV_INSTALLER_GHE_BASE_URL / UV_INSTALLER_GITHUB_BASE_URL
so a mirrored environment still works. Every mirror serves the same asset, so
the pinned hash is unchanged; UV_DOWNLOAD_URL stays unhonoured because it
points at an arbitrary version the pin would then reject.

Record where uv actually landed. Refresh-SessionPath rebuilds PATH machine
first and drops the in-process prepend, and the recovery probe never checked
the XDG_DATA_HOME or unmanaged destinations, so a good install could still
report failure. Required by the change above, which leaves that prepend as
the only thing putting uv on PATH.

* Tighten comments on the false positive reduction changes

---------

Co-authored-by: danielhanchen <danielhanchen@users.noreply.github.com>
2026-08-04 04:12:15 -07:00
Daniel Han
b35bdcbea3
CI: prove an interrupted install can never masquerade as a healthy one (#7552)
* CI: prove an interrupted install can never masquerade as a healthy one

Nothing in CI had ever interrupted an install, which is how the reported failure
shipped: quit the desktop app mid-install, the app SIGTERMs the installer process
group, and if that lands during 'studio deps' the venv loses structlog. Preflight
then probes 'unsloth -h' and 'studio desktop-capabilities', both of which succeed
because the CLI's own deps are core, so the app reported ManagedReady with
can_auto_repair=false while the backend died on import. A permanent dead end.

This kills the installer at each interesting phase and asserts the result is
either genuinely healthy or explicitly repairable, never silently ready. 13 legs
across macos-14, ubuntu-latest and windows: each of the dependency-pass steps
plus the coarse phases (venv, torch, unsloth, setup).

The kill targets the process GROUP, matching install.rs. Killing only the leader
leaves uv and python children to finish the dependency pass, and the test would
quietly prove nothing. Windows has no process groups, so that leg walks the CIM
parent links instead, which is the same reason the app carries windows_job.rs.

One shared probe for all platforms. The Windows check used to be bespoke inline
PowerShell that only ran -h and desktop-capabilities, so it could not observe
studio_install_ok, verify-install or desktop-runtime-check: it would have
reported FALSE_READY for the very PRs that add them, no matter how well they
worked. The probe boots the backend as ground truth and owns the whole process
tree, since terminating only the parent leaves children holding the port.

install.sh runs with --local, which is load-bearing rather than a convenience:
without it the installer resolves unsloth from PyPI and the venv gets the
PUBLISHED CLI, so no branch-side change is present and every deeper probe reports
'absent' regardless of what the branch does.

Verified: against a tree without the detection, windows kill@studio-deps reports
FALSE_READY, reproducing the user report exactly. With #7492 merged the same leg
reports REPAIRABLE, and all 13 legs pass.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Make the POSIX legs actually run the installer, and fail if they do not

install.sh --tauri rejects a custom UNSLOTH_STUDIO_HOME outright (the desktop app
still uses the legacy ~/.unsloth/studio root), and this workflow set one at
workflow level for every job. So all 11 macOS and Linux legs exited about a second
in with

    ERROR: UNSLOTH_STUDIO_HOME is not supported with --tauri.

produced no CLI, took the probe's NO_CLI 'safe' branch and reported success. They
were vacuously green. Only the two Windows legs were real, because install.ps1 has
no equivalent guard.

The override now applies to the Windows job only, and the POSIX legs read the
legacy root, which is where --tauri installs. The runner is ephemeral so the real
home is as disposable as the override.

Also adds the check that makes this class of mistake loud: a leg asserts its kill
actually landed on the marker it was aimed at, using the interrupt_reason the
driver already records. A leg that never reached its kill point proves nothing,
and NO_CLI made that indistinguishable from a pass.

* Make the interrupted-install legs able to fail

The probe treated a present .desktop-install-in-progress marker as proof of a
repairable state, but the drivers seed it unconditionally and never clear it, so
REPAIRABLE was unconditional and FALSE_READY unreachable. The Windows leg had no
kill-landed guard, blanket continue-on-error, and no repair re-run; -SkipTorch
was silently dropped, since install.ps1 parses only --no-torch.

Judge the re-run by whether the backend boots, on both platforms. The log grep
matched the frontend build printing "up to date" and failed a leg whose venv
was fine.

* Drop the interrupt cell that could never be interrupted

install.sh --local sets skip_base, so install_python_stack returns before any
"base packages" label is printed. The kill had nothing to land on and the
installer ran to completion, reaching [TAURI:DONE] in 62s.

* Fail the leg when the installer finished instead of being killed

The driver set reason=marker-hit before the post-marker sleep and never
rechecked, so a step whose work was already cached could run to completion
inside that beat and still be recorded as an interruption. The landing assertion
tests reason != marker-hit, so a fully completed install passed green having
interrupted nothing. Reproduced with a stub that exits during the delay:
reported marker-hit / killed=true / exit=0 next to "install finished fully".
Set the reason after the sleep, on both drivers.

Also trigger on _studio_deps.py and install_manifest.py, where the two decisions
the probe asserts on are actually implemented.

* Kill the group, and stop the probe blocking on a full pipe

The escalation was gated on the leader still being alive, so a leader that exits
promptly on SIGTERM while a uv or python descendant ignores it skipped the
SIGKILL entirely, and wait reaped only the leader. Proven with a descendant that
traps TERM: pre-fix its heartbeat keeps ticking while the probe would be running,
post-fix it stops. Signal the group unconditionally and drain it after the reap,
since an unreaped leader is still a member of its own group.

The probe started the backend on stdout=PIPE and read nothing until after the
poll loop, so a backend logging more than the pipe buffer during import blocked
before binding. Measured 65536 bytes here; a child emitting 200 KB never reaches
its bind line, which would make backend_ok false for a healthy install. Write
straight to the artefact file.

Also trigger on studio/backend/requirements/**, where structlog is declared.

* Make the NO_CLI legs assert repair, and fix the Windows straggler sweep

Two of the interrupted-install legs were passing without testing anything.

The re-run assertion skipped verdict=NO_CLI, but a kill at "venv" or "torch"
lands before install.sh ever prints "Installing Unsloth" (:2125, :3667, :3961),
so those legs can only ever produce NO_CLI. Three non-gating-exempt cells
(macos-14 kill@venv, macos-14 kill@torch, ubuntu-latest kill@torch) therefore
asserted nothing beyond a marker appearing in a log. NO_CLI is now included:
a re-run must produce a booting backend regardless of how little the first run
managed to install. Each re-run step grows an existence check first, because
the probe exits without writing verdict.json when the binary is absent and the
json.load would crash rather than report.

The Windows straggler sweep matched nothing at all. UNSLOTH_STUDIO_HOME arrives
as D:\a\r\r/.studio-home, since the workflow joins ${{ github.workspace }} with
a forward slash, while Process.Path is all backslashes, so the literal -like
missed even the venv's own python.exe. uv is never under the studio home in any
case: install.ps1 takes it from winget or astral.sh. Normalise the separators,
match uv by name (the runner is ephemeral and runs no other uv), and skip the
home comparison entirely when the variable is empty, which would otherwise turn
the pattern into "**" and kill every python on the runner.

* Run the Windows legs as the desktop does, and judge repair by what preflight reads

The Windows matrix set a workspace-scoped UNSLOTH_STUDIO_HOME, which forces
install.ps1 down the shell-install path: install.ps1:189-215 rejects a custom
root under --tauri, so those legs ran with UNSLOTH_TAURI_MODE=0, the frontend
build on and no bundled-file overlay, while the desktop always spawns the
installer as --tauri with the variable scrubbed (install.rs:202 and :356). The
torch leg could not even reach its marker: "Installing PyTorch" is printed only
by Write-TauriLog (install.ps1:2440), so it was killed at the deadline. Both
legs now run --tauri --local at the default root, and the probe and re-run
resolve the CLI under %USERPROFILE%\.unsloth\studio.

The probe counted `studio verify-install` and `studio desktop-runtime-check`
failures as proof the app can repair, but preflight/managed.rs runs only `-h`
and `studio desktop-capabilities --json` (:357) and reads studio_install_ok from
that payload (:445); neither deeper command is invoked anywhere under
studio/src-tauri. A leg where capabilities regressed to ready while only those
standalone commands saw the damage would have passed green with the app stuck on
ManagedReady, which is the exact false negative this workflow exists to catch.
They are still run and recorded in verdict.json, just no longer repair evidence.

An interrupted install can leave the console script in place while its venv
interpreter is gone. The probes go through run(), which catches OSError, but the
backend spawn did not, so the probe aborted before writing verdict.json and both
workflows died on the json.load instead of reporting. That state is now recorded
as backend_spawn_error and lands on REPAIRABLE, which is what `-h` failing
already implies.

On win32 the CLI re-spawns the server as a child and waits on it
(unsloth_cli/commands/studio.py:1543), and CREATE_NEW_PROCESS_GROUP does not
make terminate() reach descendants, so the reap left a server holding the venv
open while the repair step reinstalled into files Windows had locked. Use
taskkill /F /T for the tree. The straggler sweep now falls back to the default
studio root, since under --tauri there is no UNSLOTH_STUDIO_HOME to match on.

* Judge the install the way preflight does, and reap the whole probe group

Read desktop-capabilities the way the desktop reads it. preflight/managed.rs
pipes stdout and sends stderr to /dev/null (managed.rs:358), then hands the
whole stdout buffer to serde_json (managed.rs:414). The probe concatenated both
streams and scanned to the first brace, so a single diagnostic line on stderr
made json.loads raise on the trailing text, studio_install_ok stayed "absent",
and a broken backend was reported FALSE_READY over an install the real app
parses, sees as incomplete, and offers to repair. That fails a valid recovery
change for a reason that exists only in the probe. stdout and stderr are now
captured separately and stdout is parsed strictly; a payload that does not parse
counts as repair evidence, matching the Stale the desktop reports when the
capability probe returns nothing (managed.rs:521).

A booting backend alone is not a finished install. The manifest is written last
(install_python_stack.py:3255), so a kill after "studio deps" but before it, the
data-designer leg, leaves a venv whose backend boots while desktop-capabilities
still reports studio_install_ok=false and preflight reports Stale
(managed.rs:445). Calling that HEALTHY skipped the re-run step, so the leg
asserted nothing beyond a marker appearing and never exercised the version fast
path that is supposed to clear an incomplete install, which is the half of the
bug that strands the user. HEALTHY now requires both.

Escalate to the process group after reaping the probe's backend. reap() returned
as soon as proc.wait() succeeded, and the leader exits promptly on SIGTERM while
a uvicorn worker does not, so the SIGKILL iteration was skipped and that worker
kept the port and the venv open while the repair step reinstalled underneath it.
It also read os.getpgid(proc.pid) after the reap, which raises. The pgid is now
captured up front and SIGKILL always goes to the group, the same escalation
interrupt-install.sh:94 makes. A heartbeat experiment left the group alive with
the old sequence and empty with the new one.

Trigger the workflow on pyproject.toml. Every leg installs the checkout with
--local, so that file decides the unsloth console script and the core
dependencies the probe leans on: -h and desktop-capabilities only survive a torn
install because typer/click/rich are declared there. No other install workflow
interrupts the installer, so such a change would otherwise merge without a
single leg running.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Judge an absent capability field and a dead -h the way preflight does

The probe left studio_install_ok=absent undecided and judged those installs on
whether the backend booted. preflight/managed.rs:445 tests studio_install_ok
!= Some(true), so an absent field is Stale exactly like a false one; a CLI too
old to carry it is already rejected one check earlier on
desktop_manageability_version. The gap mattered in both directions: a payload
that stopped carrying the field reported HEALTHY on every booting leg and
skipped the re-run assertion this workflow exists to make, and a torn venv with
a working -h was failed as FALSE_READY even though the app would have offered
repair. unsloth_cli/commands/studio.py is in this workflow's path filter
precisely to catch that class of change, so it must not be the thing that
silences it.

The verdict also consulted cli_h_ok only in the repairable arm, so a CLI that
cannot print help was called HEALTHY whenever the backend happened to boot.
probe_managed_bin runs -h first and returns Stale cli_unusable before it ever
reaches the capability probe (managed.rs:465-478), so that install goes to
repair in the real app and the leg must assert it here.

* Judge the probes on the desktop's deadline, and interrupt the host it uses

Preflight gives each managed probe ten seconds and nothing more: managed.rs:337
wraps `unsloth -h` and managed.rs:390 wraps `studio desktop-capabilities --json`
in a tokio timeout, kills the child on expiry, and returns Stale as
"cli_unusable" or "desktop_capability_probe_failed". The probe allowed three
minutes, so a venv torn badly enough that its CLI only answers after half a
minute of retries was recorded HEALTHY here while the real app shows it as
repairable. That skips the re-run assertion the leg exists to make, which is the
same false-HEALTHY hole the studio_install_ok and -h gating already closed. Both
calls now use the desktop's ten seconds, and the elapsed time is recorded so a
leg that flips for timing reasons says so in the artefact.

On Windows the installer child now runs where the desktop runs it. install.rs
325-339 spawns the bundled install.ps1 as powershell.exe with -NoLogo -NoProfile
-NonInteractive -WindowStyle Hidden -ExecutionPolicy Bypass -File, so Windows
PowerShell 5.1 is the only host a real desktop install ever uses. The interrupted
run and the repair re-run both used pwsh 7, and every other Windows job in
.github runs install.ps1 under pwsh too, so the installer's behaviour on 5.1 was
covered by nothing: .NET Framework instead of .NET, OEM console encoding instead
of UTF-8, and different native-command and OSArchitecture reporting are all real
sources of divergence. A workflow whose point is to reproduce what the app does
cannot run a different interpreter than the app does. The driver itself stays
under pwsh; only the installer child and the repair invocation change.

* Tighten the interrupted-install comments

* Tighten the probe docstrings

* Fail the leg when the installer completed inside the kill window

* Land the kill in the marked step, and reject non-boolean capabilities

Two holes found from the staging run's own logs.

The venv leg never interrupted the venv step. Creating the venv takes ~0.1s, so
by the time the 1s poll noticed its line the installer was already in
"Installing PyTorch", and the flat 3s beat sent the signal there: staging run
30419729244 shows both step lines in the tail and a kill 4s in. That made the
leg a duplicate of the torch leg while its label claimed otherwise. Both
drivers now poll in half-second slices, cut the beat short the moment a later
[TAURI:STEP] line appears, and print the step the signal actually landed in,
warning when it is not the marked one. Sub-step markers such as "studio deps"
print no step line, so they keep the whole beat and never warn.

studio_install_ok is Option<bool> (managed.rs:43), so serde rejects a
non-boolean and the whole payload fails to deserialize, which the desktop
reports as Stale. bool() read a JSON string "false" as True, so the probe
called a torn install ready. Only a literal JSON true counts now.

* Tighten the interrupt driver comments

* Fail the leg when the signal landed after the marked step

The cut-short added last round only helps when the marked step is still the
last [TAURI:STEP] line at the moment the poll notices it. Creating the venv
takes ~0.1s (staging run 30419729244: 03:31:07.371 -> 07.478), less than the
0.5s poll, so the next step's line is usually already in the log when the
marker matches, the step count never changes during the beat, and the full 3s
elapses inside "Installing PyTorch". Reproduced with a stub installer against
the driver at head: kill at 4.11s, step at kill "Installing PyTorch". The leg
then duplicates the torch leg while its matrix label claims the venv step, and
passed green on nothing but a :⚠️:.

Both drivers now skip the beat entirely when the marked step is already over,
so the kill goes out at once instead of deeper into the next step, and both
record interrupt_step_mismatch in interrupt.env. The landing assertion fails on
it: a warning that cannot fail the leg proves nothing. Sub-step markers
("studio deps", "pip bootstrap") print no step line of their own and stay
exempt, as before.

The venv leg becomes experimental. Its step is shorter than any log poll can
resolve, so it must not block the PR on a race it cannot win, and it still
probes the earliest torn state whenever it does land.

* Tighten the interrupted-install workflow and driver comments

* Land the kill in the phase each leg is named for

Splitting the log on \r shows that 5 of the 12 legs of staging run 30419729244
interrupted a later phase than their label claims, and the run was fully green.
The venv leg's install.log is byte-identical to the torch leg's. So is
pip-bootstrap's to unsloth-extras'. Worse, both "studio deps" legs, the cells
that reproduce the reported bug, were killed at "7/10 data designer deps" and
"12/14 local plugin": their own probe artefacts report backend_ok=true, so
structlog was installed and the flagship cell was passing on the manifest gate
alone.

Two causes. The dependency pass rewrites ONE physical line with \r
(install_python_stack.py:2499), so its sub-steps are CR-separated segments and
a line-based check could not see one end; the drivers exempted them and warned
about nothing. And the flat 3s beat between the marker and the signal is longer
than several phases, while every phase label prints BEFORE its work starts, so
the beat pushed the signal past the phase instead of into it.

Both drivers now split on \r, track the running phase at both levels, and judge
a sub-step marker against the running sub-step and a step marker against the
running step, so a step is not "over" because the sub-steps beneath it
advanced. The beat defaults to 0 and is set per leg, 3s only for torch,
unsloth and setup, which run for minutes. The mismatch is recorded in
interrupt.env and the landing assertion fails on it, in both languages.

Both detectors were replayed against the 12 real logs from 30419729244 and
agree with the artefacts on every leg. venv and pip-bootstrap become
experimental: their phases are shorter than any log poll can resolve.

* Fail the Windows leg when the installer never exited

The driver writes installer_exit=running when the installer outlived Stop-Tree
and WaitForExit, and 'running' is not '0', so the landing assertion accepted it.
A live installer writing into the venv while the probe reads it is not an
interrupted install. Only a real integer exit code counts now, checked against
0, 143, 137, -1, running and the empty string.

* Drop the legs that cannot land, and prove the kill was delivered

Two cells never interrupted the phase they were named for. "Creating virtual
environment" runs 0.107s (staging 30419729244, 03:31:07.371 -> 07.478) and
"1/10 pip bootstrap" is over just as fast, both shorter than any poll that
watches the log, so in 30423181897 and 30424366953 the signal landed in
"Installing PyTorch" and "2/10 unsloth extras" every time. Each was another
leg wearing a false label, so they are gone rather than allowed to fail, and
continue-on-error goes with them: a leg permitted to fail asserts nothing.
The only coverage lost is a venv caught half-written, which interruption
cannot reach at this resolution; the torch leg's signal lands ~3s into a
multi-minute download, so it already leaves a complete venv with nothing
installed into it.

The landing check also accepted an installer that failed on its own. A
dependency error between the driver's last liveness check and the signal
exits non-zero, which the exit != 0 guard let through as a kill. POSIX now
requires 143 or 137, the only statuses a signal produces here and what all
ten POSIX legs of 30424366953 reported. Recording whether kill(2) returned 0
would not separate them, since the unreaped leader keeps its group alive.
Windows has no such status, so the driver records whether Stop-Process
actually terminated the installer: it throws on a process already gone, so
the flag is false exactly when there was nothing left to interrupt.

* Signal at the marker, with no beat to overshoot the phase

Staging run 30426111484 failed the macOS torch leg on the landing check: the
3s beat carried the signal from "Installing PyTorch" into "Installing
Unsloth", because the PyTorch step, which this workflow called minutes long,
finished in under three seconds. The beat only ever existed to land
mid-work, and it cannot do that safely: every label prints before its work
starts, so detection is already inside the phase, and any wait is a bet on
how long that phase runs. It lost in 30419729244 and again here.

So the beat is gone rather than retuned, and with it the matrix knob and the
driver parameter on both platforms. The landing check stays and can still
fail, since a phase shorter than one poll is seen only after it ends.

The Windows driver also polled every 500ms while its own comment claimed a
fifth of a second. That is 2.5 slices of overshoot the POSIX side does not
carry, and it is now 200ms like the POSIX loop.

* Kill the installer before its children, not after

The depth-first walk killed the child install.ps1 was waiting on and only
then the root, which races the leader's own reaction to that death. It is
not a theoretical race: in staging run 30424366953 install.ps1 had already
printed "unsloth studio setup failed (exit code -1)" by the time
Stop-Process reached it. A leader that wins the race makes Stop-Process
throw, and the new root-kill assertion would then fail a leg whose
interruption the driver really did deliver.

The tree is now snapshotted first, since a dead parent leaves nothing to
walk, then the root goes down ahead of its descendants. A dead leader cannot
react to a child and cannot respawn one either, which is what the
depth-first order was for.

* CI: give the probe the desktop's startup grace and fail a nonzero repair

The probe allowed the backend 120s to answer /api/health while the desktop
waits 5 minutes (BACKEND_STARTUP_GRACE_PERIOD, commands.rs:9), so a slow but
healthy install could be reported FALSE_READY. A broken backend exits at once
and the poll breaks on it, so the longer deadline only bounds a live backend.

The re-run step also accepted a HEALTHY probe over an installer that exited
nonzero. setup.sh does fallible sidecar and GPU setup after the manifest is
written, and the desktop returns the repair error without starting the backend
(commands.rs:615-630). The Windows leg ignored powershell.exe's status entirely.

* Tighten the interrupted-install comments

Comments only: shorter wording for the same rationale, no code touched.

* CI: raise the interrupted-install job timeout above its own deadlines

A leg configures up to 25 minutes to the marker plus two probe passes of up to
17 minutes each around a repair install, so the 60 minute limit could cancel a
slow runner mid-assertion. Legs land in 6 to 10 minutes in practice.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <unslothai@gmail.com>
2026-07-29 06:27:33 -07:00
Daniel Han
b6781a8bfe
CI: prove the installer works on a machine with no developer toolchain (#7551)
* CI: prove the installer works on a machine with no developer toolchain

No job has ever run the installer on a machine without one.
studio-mac-install-matrix.yml is the only macOS installer job and it runs
'bash install.sh --local --no-torch' on runners that already have the Xcode CLT
selected and setup-python preinstalled, so the CLT gate never fires there, and
--local is precisely the mode that legitimately needs git. Repo-wide there was
zero coverage of xcode-select or CommandLineTools outside install.sh itself.

clean-machine-install-ci.yml runs the installer on a genuinely stripped machine.
macOS legs move /var/db/xcode_select_link, /Library/Developer/CommandLineTools,
/Applications/Xcode*.app and Homebrew aside, so xcode-select -p, git, cc and
clang really do fail, and restore unconditionally afterwards. Removing the
select-link alone is not enough: xcode-select falls through to a full Xcode.app
and re-arms /usr/bin/git. Linux legs use containers, which are genuinely clean.
Windows legs cover winget visible and masked, plus windows-11-arm. A WSL leg
covers the 126 lines of WSL-specific install.sh logic that had no runtime test.

Each macOS leg runs four deliveries: pipe (the advertised command, and the shape
that turns an early exit into curl (56)), file (separates installer logic from
pipe delivery), no-torch, and tauri (stdin closed, no tty, as the desktop app
invokes it). One leg records every toolchain invocation and asserts the trace,
which is the real deliverable: proof the installer never reached for a compiler
rather than proof it happened to succeed.

The asserts test that tools do NOT WORK rather than that they are absent from
PATH. On a real virgin Mac /usr/bin/git and /usr/bin/cc exist as CLT stubs, so
'command -v git' succeeds and only running it tells the truth.

desktop-app-clean-machine-ci.yml installs and launches the SHIPPED desktop app
release on a stripped machine, covering Gatekeeper and quarantine on macOS, NSIS
silent install on Windows, and Xvfb with WebKit2GTK on Linux.

Known limit, stated plainly: hosted macOS runners are developer machines. Masking
reproduces this bug and proves the installer does not invoke a toolchain, but it
cannot prove no hidden dependency exists on a truly virgin Mac. An ephemeral-VM
lane is the follow-up.

* Point the llama assert at the right root, and name the Intel limitation

The tauri leg installs to the legacy root because --tauri refuses a custom
UNSLOTH_STUDIO_HOME. Its install succeeds end to end, but llama.cpp lives at
<root>/llama.cpp while the venv is at <root>/studio, so the assert was pointed one
level too deep.

On macos-15-intel /usr/bin/git keeps working once the CLT are gone, so it is not
CLT-provided there and no masking can remove it, while cc and clang do become
stubs. Calling that 'masking failed' was wrong. That leg allowlists git
explicitly and says why, so the assert stays strict everywhere else.

* Make the clean-machine legs able to fail

The toolchain strip never ran on the automatic triggers: inputs exists only for
workflow_dispatch, and GitHub coerces '' and false alike to 0, so
`inputs.strip_toolchain != false` was false. Confirmed on a pull_request run
where the strip step reports skipped. Gate on the event instead.

Also: scrub the Machine and User registry PATH, since install.ps1 rebuilds
$env:Path from them mid-install and the toolchain came back; stop dropping
WindowsApps unconditionally, which removed winget on the winget=visible leg too;
fail rather than annotate when a bundle ships no installer or no CLI; run the
bundled installer, which a headless launch never reaches; resolve the newest
desktop-v* release instead of a pinned immutable tag; and give the two macOS
matrix rows distinct artifact names.

* Make the Windows and Linux clean-machine legs honest

The Windows scrub only touched PATH, so the legs were green while not clean: run
30365014702 logged "python ABSENT" and then "Python 3.13 already installed"
with uv resolving C:\hostedtoolcache\windows\Python\3.13.14\arm64\python.exe.
py.exe lives in C:\Windows and uv discovers interpreters itself, so take the
toolcache off disk and fail when tooling survives, instead of only printing it.

The Linux desktop legs never stripped anything, and the tauri.log step was all
|| true so it could not fail. Run the bundled installer the way install.rs does,
with --tauri alone, and assert torch: passing --no-torch skipped the slowest
half of first launch and let the venv check pass over it.

Pin the WSL rootfs to a dated build; current/ is a rolling alias and the digest
next to it is fixed.

* Give the Linux and WSL legs an assertion that can fail

The Linux rows' only post-install gate was nobuild, a log grep, so an installer
exiting 0 having produced nothing kept a required leg green. The WSL job and the
Windows job both already check the install runs; the Linux job now does too.

The WSL detection half only printed its Select-String, and the alternation also
matches "platform linux", so a regression that skipped every WSL-specific
branch would still pass as a plain-Linux install. Assert the exact marker,
stripping ANSI first since step writes the label in reverse video. Probed against
three fixtures: real wsl log passes, platform linux fails, missing log fails.

* Tighten the clean-machine comments

Compress the comment blocks across the clean-machine workflows and
scripts. The explanations of why each check is written the way it is
stay; the padding, restatement and duplication go.

No code or workflow logic changes.

* Point the nightly at the repo that publishes, and let its checks fail

REL_REPO defaulted to unsloth-test/unsloth-test, which holds one release frozen
at 2026-07-27, while release-desktop.yml publishes into github.repository. The
schedule was re-testing the same fixture forever and could never see a broken
production bundle.

The windows job carried a blanket continue-on-error, so its NSIS assertions
could not gate. lipo -archs prints and exits 0 for a thin binary and `|| true`
swallowed even that, so the architecture was never checked; fall back to file,
which survives the CLT mask. And require the preflight disposition line rather
than the mere existence of tauri.log, which setup_logging creates at process
start regardless.

* Stop four clean-machine checks from passing over a real failure

Re-run `absent` after the install on the masked macOS legs. It only ran
before, so an installer that quietly selected the Xcode CLT or installed a
compiler left the leg green while every later source build could succeed,
which is the one thing clean-machine-assert.sh says `absent` guards the whole
run against.

Fail the Windows simulation when py.exe can still start an interpreter. The
launcher binary itself may stay, but Find-CompatiblePython probes `py` first
(install.ps1:1130-1153), so an interpreter registered outside the two renamed
toolcache directories gets reused and Python bootstrap is never exercised.
Exempting `py` without ever running it left that unchecked.

Propagate the WSL installer exit code. It was printed and discarded, and the
CLI check does not compensate: install.sh links the `unsloth` shim (4174-4182)
before it reports a failing studio/setup.sh (4219-4230), so a late setup
failure leaves a shim whose --version succeeds.

Run the bundled installer in the Linux desktop jobs. The launch step only
proves the process stayed alive, and on a fresh home preflight reports
not_installed and the app waits on the install screen, so both required rows
passed after 90 seconds without ever touching the shipped install.sh. Locate
the resource in the deb payload or the extracted AppImage, run it the way
install.rs does, and require a managed venv that can import torch.

* Prove the trace wrapper records before trusting an empty trace

The `notools` check reads an absence: it passes when the trace file contains no
compiler, git or brew invocation. A shim directory that never reached PATH
produces exactly the same empty file as an installer that touched nothing, so
the single leg carrying that assertion would stay green no matter what the
installer did. "Verify the simulation actually took effect" only ran for mask
mode, which left the trace leg with nothing checking its own instrumentation.

Call git explicitly after sourcing the environment and require it to appear in
the trace, then truncate the file so the self-test entry does not count against
the install. The call has to be explicit because macOS reaches _has_working_git
only under STUDIO_LOCAL_INSTALL (install.sh:2026), so no consumer leg on that
platform probes git on its own.

* Stop the Windows clean-machine check failing on its own probe exit code

All three Windows legs failed "Verify the simulation took effect" with no
::error:: printed at all. The check itself was right: the mask step logged
"masked toolcache python: C:\hostedtoolcache\windows\Python", python/git/cmake/cl
were ABSENT, no `py -3.x` probe started an interpreter, and the winget assertions
were satisfied. The step still exited 1.

The cause is $LASTEXITCODE leaking out of the step. The last external command is
the `py -3.13` probe, which is SUPPOSED to fail; Get-Command and Write-Host are
cmdlets and never reset $LASTEXITCODE, and the runner appends
`if ((Test-Path -LiteralPath variable:\LASTEXITCODE)) { exit $LASTEXITCODE }`
to every pwsh step (actions/runner#351). So a clean machine reported failure,
and because this step runs before Install, no Windows leg has ever reached the
installer. Clear $LASTEXITCODE after the probe loop and end with an explicit
exit 0. The leak detection is untouched: a surviving python/git/cmake/cl, or a
`py -3.x` that actually starts, still exits 1.

Also print each probe's exit code and output, so the next failure here explains
itself instead of being silent, and label `py -0p` as what it is. The launcher
reads the registry, which the on-disk toolcache rename cannot rewrite, so -0p
keeps naming paths that no longer exist. Unlabelled it reads like a leak.

Accept the Fedora leg's real outcome instead of a message that can be absent

The fedora assertion only accepted the unsupported-package-manager hard exit.
That is still what this ref's install.sh does, but the pending installer change
replaces it with a warning that lets the install continue, at which point the
old grep matches nothing and the step fails for the wrong reason.

Handle both, strictly. If the log shows the newer "using prebuilt llama.cpp
(missing:" warning, the Linux gate demonstrably did not hard-stop, and the only
tolerated failure past that point is release lag: install.sh comes from this ref
while unsloth comes from PyPI, and the released studio/install_python_stack.py
has no "skip triton kernels when git is missing" guard, so it still fetches the
git+https triton_kernels requirement on a machine with no git. Anything else
after that warning fails the step. Otherwise the old hard-exit message is still
required. A missing log, a bootstrap outage or any unrecognised failure all
remain errors, and the step retires to a plain success assertion once a release
ships the no-git skip.

* Make the AppImage Linux row actually extract, and hold Linux to the macOS preflight bar

The appimage row invoked the extractor by bare filename, and a command word
with no slash is resolved through PATH rather than the working directory, so
the extraction exited 127 and the bundled-installer assertion below it never
ran. Prefix it with ./ so the row exercises what it claims to.

The Linux log step also asserted nothing: it skipped a missing log with
continue and discarded the grep with || true. The launch step only proves the
process stayed alive for 90 seconds, and the bundled-installer checks do not
exercise the Rust preflight path, so an app that hung before preflight
completed passed both required Linux rows. Require the same
desktop_preflight completed disposition= record the macOS rows already do.

* Put the branch's own Python under test on the clean-machine legs

install.sh and install.ps1 come from the ref under test, but they install
unsloth from PyPI, which is the consumer path and has to stay that way. That
left everything Python-side coming out of the released wheel: studio/setup.sh,
studio/setup.ps1, studio/install_python_stack.py, and every requirements and
constraints file those resolve through Path(__file__). A branch that changes
constraints.txt or setup.ps1 therefore got a green run that proved nothing
about the change, and some legs proved less than they looked. The Fedora
assertion was already carrying a hand-written workaround for exactly this,
tolerating a triton/git failure on the grounds that the released package lags
the ref.

Legs marked overlay: true now re-point the venv at the ref just before studio
setup runs, through UNSLOTH_CI_SOURCE_OVERLAY: a --no-deps editable install of
the checkout. That makes import studio resolve to the working tree, so the
existing setup-script lookup finds the ref's setup.sh / setup.ps1 and
install_python_stack reads the ref's constraints, with no other change to
either installer.

Not --local: --local additionally installs unsloth-zoo from a git+https URL,
which genuinely needs git, and git absence is the whole point of the masked
legs. The overlay resolves no dependencies and clones nothing, so it holds up
with git, cmake and the compilers all gone. It is not a consumer knob either:
no flag, no usage entry, ignored unless the variable names a directory with a
pyproject.toml in it.

Four legs stay on the released package deliberately, each for its own reason,
recorded in the header: the mac pipe legs keep an end-to-end signal on what a
user actually runs; the trace leg would otherwise answer its own question,
since the editable build calls git through setuptools-scm's file finder; the
non-root Linux leg dies before a venv exists; and WSL only ever receives
install.sh, not a source tree.

Two supporting fixes the overlay depends on or exposes:

install_python_stack.py discarded uv's output whenever a step succeeded, so
the nobuild assertion, which reads the install log, could not see a source
build in the dependency phase at all. That is the phase that installs
studio.txt, where an sdist-only dependency actually turns up, and it reported
"built: none" regardless. It now echoes successful output under
UNSLOTH_VERBOSE, matching what install.sh's run_install_cmd already does.

nobuild now ignores "Building <name> @ file://" lines. A local-path build is
something the caller pointed at, never a dependency resolution chose, and
index dependencies always print <name>==<version>, so a real sdist from PyPI
is still caught, including one named unsloth.

Each overlaid leg also asserts it really was overlaid, so an unset variable
cannot quietly put the whole matrix back on the released wheel.

* Allowlist the triton-kernels pure-Python sdist, and record why Windows on ARM is red

The two ubuntu2404 root legs went red at "Assert no source build" reporting
triton-kernels. That is not a regression in what the installer does. Those
builds have always happened; they only became visible now that pip_install
stopped discarding uv's output on success, which is what finally let the
nobuild check read the dependency phase at all.

So the question was whether each build actually needs a compiler. Checked
against the real artifacts rather than assumed:

  openai-whisper 20250625, randomname 0.2.1, argbind 0.3.9 -- no version of
  any of the three has ever published a wheel; antlr4-python3-runtime is
  pinned at 4.9.3, below the first release that ships one. All four sdists
  use setuptools.build_meta, declare no ext_modules, and contain no
  .c/.cpp/.pyx/.rs file. Already allowlisted, correctly.

  triton-kernels is the same category and was the only name failing. It is
  pinned to the triton repo's python/triton_kernels subdirectory; that tree
  is 75 files of Python, a four-line pyproject.toml, no setup.py and no
  native source at all. The kernels are Triton DSL compiled at runtime, not
  at install time. It is also a direct URL the installer names itself rather
  than something resolution picked, and only Linux reaches it. It belongs in
  the allowlist, so add it with that reasoning written down.

The allowlist match is now lowercased and underscore-folded on both sides.
The requirement spells the package triton_kernels while uv prints
triton-kernels, and an allowlist that matched only one spelling would pass
by luck rather than by intent. A plain pyarrow sdist is still caught.

The two data-designer @ file:// plugin builds needed nothing: they are
in-tree local paths, already dropped by the same rule that exempts the
source overlay's own build.

Separately, the windows-11-arm leg fails for a real reason and should keep
failing. The ARM handling itself works, the log shows torchaudio being
skipped and torch plus torchvision installing from wheels. What stops it is
that pyarrow and hf-transfer publish no win_arm64 wheel at all, so uv falls
back to their sdists and they fail on CMake configure and on openssl-sys
wanting perl. That is a product gap on the platform, not a gap in the
simulation, so the leg stays experimental and keeps reporting it. Record
that above the matrix entry so the next reader does not re-diagnose it.

* Exercise the bundled Windows installer, and stop mislabelling installer sources

Four things that let a leg go green while proving nothing.

The desktop Windows job installed the bundle and launched it, and that was all.
On a fresh profile preflight reports not_installed and the app sits on the
install screen waiting for a click, so the process happily stays alive for 90
seconds without the bundled install.ps1 ever running. A bundle that shipped no
install.ps1 resource, or a broken one, passed this job -- which is the packaged
app failure the workflow exists to catch. macOS and Linux already invoke their
bundled script directly; Windows now does the same, via the resource NSIS laid
down next to the exe, invoked the way install.rs invokes it, then asserts the
managed venv exists and can import torch. Its timeout goes to 60 minutes
because a full torch install on a Windows runner is the slowest of the three.

A manual run that selects installer_source: published only redirected the macOS
and Linux jobs. WSL kept copying the checked-out install.sh and Windows kept
running the checked-out install.ps1, so a run asking whether the script on
unsloth.ai works reported on this ref under the published label. Both now honor
the selection; install.ps1 advertises its own unsloth.ai URL, so published has a
meaning on Windows too. Both branches stay empty on pull_request and push, so
automatic runs are unchanged.

The push-to-main filter listed only install.sh, install.ps1 and this workflow,
while the PR filter also covers setup.sh, setup.ps1, install_python_stack.py and
the clean-machine helpers. A direct push touching those skipped the workflow
entirely, so the post-merge backstop never ran for the files the source overlay
was added to cover. The two lists now match.

Neither filter covered studio/backend/requirements, even though the overlay
exists precisely so a constraints change is resolved on a machine with no
compiler and no cached wheels. The update-smoke workflows cannot stand in: they
start from a preinstalled Python and full developer tooling.

* Make the Linux and Windows desktop legs clean, and honour published on every macOS delivery

The desktop workflow claims all three platforms are stripped, but only macOS
and Windows had a strip step and the Windows one scrubbed the process PATH
only. Both gaps let a bundle that needs a developer toolchain pass the one
workflow whose premise is that it must not.

Linux: the job ignored strip_toolchain entirely and ran the bundled install.sh
with the runner's git, gcc, cmake and make in /usr/bin. clean-machine-env.sh
now has a Linux --remove branch that moves the resolved tool binaries aside,
recorded in restore.sh, and the job calls it plus `assert absent` after the apt
step (the .deb install needs dpkg) and before the bundled installer, with a
restore step to match macOS. The loop repeats per tool so a name present in
both /usr/bin and /usr/local/bin is fully masked rather than half masked.

Windows: rewriting $env:PATH does not survive the bundled install.ps1, which
calls Refresh-SessionPath (318-337) and rebuilds $env:Path from the Machine and
User registry values, and py.exe in C:\Windows reaches the toolcache whatever
PATH says. Ported the on-disk toolcache rename, the Machine/User registry scrub
and the py -3.11/-3.12/-3.13 start probe from clean-machine-install-ci.yml, so
the strip is proven rather than assumed.

Windows preflight: the log step was Test-Path, Get-Content and Select-String,
none of which can fail, so an app that hangs before preflight passed on the
90 second liveness check alone. It now asserts a tauri.log exists and carries a
`desktop_preflight completed disposition=` line, the same unconstrained check
macOS and Linux already make. The disposition VALUE is deliberately not
constrained: ManagedReady over an unbootable venv is the reported bug.

installer_source on macOS: only the pipe delivery branched on it, so a
`published` dispatch ran the checked-out script on six of the eight macOS rows
while the run was labelled published. The script is now resolved once at the
top of the Install step and used by the file and tauri deliveries; pipe still
re-fetches through the live transport, because that is half of what it tests.
Linux, WSL and Windows already honoured the input.

Also shortened the comments across the changed files, keeping the reasoning
that says why each check exists.

* Run the Windows installer under PowerShell 5.1, the only shell a clean machine has

The Windows Install step ran `& $script` inside a `shell: pwsh` step, so
install.ps1 was executing under PowerShell 7. A genuinely clean Windows box
does not have PowerShell 7: Windows ships powershell.exe (Windows PowerShell
5.1) and pwsh is a separate install that the hosted runner image happens to
preinstall. So the one workflow whose premise is a machine that has never seen
a developer toolchain was testing the installer under a shell that machine
would not have, and no other Windows job anywhere in .github exercises
install.ps1 under 5.1.

Invoke it the way the desktop does (install.rs:325-339, and the bundled
installer step in desktop-app-clean-machine-ci.yml): powershell.exe with
-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -File. The pwsh
step wrapper stays, since it is only the installer that has to be under 5.1.
Calling powershell.exe with `&` keeps the output in the pipeline, so
Tee-Object still fills logs/install.log, and $LASTEXITCODE after the pipeline
is the child's real exit code, so $rc and `exit $rc` are unchanged.

install.ps1 and studio/setup.ps1 hold no PowerShell 7-only constructs: no
`#Requires` above 5.1, no `&&`/`||` chain operators, no ternary, no
null-coalescing, no ForEach-Object -Parallel, no $IsWindows/$PSStyle, and no
6+ cmdlets or parameters. setup.ps1 declares `#Requires -Version 5.1`, and its
three $PSVersionTable branches gate a 7-only preference on the 7 side with a
5.1 fallback. Every Invoke-WebRequest already passes -UseBasicParsing, which
5.1 needs because it otherwise reaches for the IE engine.

* Assert the Windows desktop strip actually took effect

The desktop job's Windows masking renamed the toolcache Python, scrubbed the
Machine and User registry PATH, and probed `py`, but nothing checked that
`python`, `git`, `cmake` or `cl` were gone. The drop list is heuristic path
fragment matching, so a runner image that moves any of those outside those
fragments leaves the bundled install.ps1 reusing hosted developer tooling while
the job still reports a clean machine. PATH written to $GITHUB_ENV only applies
to later steps, so the check has to live in a step of its own; it carries the
same event gate as the strip, exempts `py` (it lives in C:\Windows and stays,
which is why the start probe is the real evidence), and resets $LASTEXITCODE
before exiting 0 so an intentionally failing probe cannot fail a clean machine.

Also correct the no-winget matrix note: that leg is not failing for an unfixed
product reason. It stops at the unconditional git gate in setup.ps1 only on this
ref, and with that gate relaxed it passes along with every other leg, so the row
is a merge order dependency and stays required.

* Resolve the desktop release including drafts, the convention this repo ships

All three desktop legs died at the download step with an empty REL_TAG. The
resolver passed --exclude-drafts while REL_REPO now defaults to
github.repository, and every desktop-v* release in unslothai/unsloth is a draft:
desktop-v0.1.50-beta and desktop-v0.1.471-beta are both drafts carrying the .dmg,
.deb, .AppImage and setup.exe, while only the non-desktop tags like v0.1.501-beta
are published. Excluding drafts therefore matched nothing and no leg could ever
run against a production bundle.

Drop --exclude-drafts so the newest desktop-v* release is found. A draft has no
tag ref, so releases/tags/<tag> 404s for one, but gh resolves drafts over GraphQL
and gh release download <tag> fetches their assets normally, so the download call
is unchanged. Listing drafts requires push access, which for GITHUB_TOKEN means
contents: write, so the workflow permission is raised from read and annotated.

When nothing resolves the leg still fails hard rather than skipping: with no
bundle to install there is nothing to prove, so a green run would be a lie. The
error now names both causes, no release cut yet or a token that cannot see drafts.

Also stop the restore step swallowing its own failure. `bash
.clean-machine/restore.sh || true` printed "No such file or directory" whenever an
earlier step failed before the toolchain was stripped, and hid a genuinely broken
restore just the same. Skip explicitly when the file is absent and let a real
restore failure surface. Same fix in clean-machine-install-ci.yml, which had the
identical line.

* Skip the desktop jobs on fork PRs instead of failing them

Every desktop-v* release in this repo is a draft, and GitHub lists drafts only
to a token with push access, which is why resolving one needs contents: write.
A pull request from a fork receives a read-only token no matter what the
workflow declares, so on those runs the resolver cannot see any release and the
job died on "no desktop-v* release visible", accusing the repo of having no
bundle when the real cause is the trigger.

This workflow runs on pull_request for changes to itself and the stripping
scripts, so an outside contributor editing either would have hit that. Guard the
three jobs on the head repo not being a fork. A skipped job is honest here: it
does not claim to have tested a bundle it was never able to download, and it is
not reported as a pass.

* Close the free headroom in the clean-machine simulation

Assert arch and signature on every downloaded Mach-O. This is the one genuine
gap the simulation had: Rosetta 2 is preinstalled on hosted runners and absent
from a factory-fresh Mac, so an x86_64-only llama.cpp, whisper.cpp, Node or uv
payload runs green here and dies with "bad CPU type in executable" for the
user. llama-server launching under `assert-llama-loads.sh` does not rule that
out, because Rosetta makes it launch. The new `macho` check reads `file -b`
(`lipo` is an xcrun shim and is gone after masking, as the desktop lane already
notes) and keys the expected arch off `uname -m`, so macos-15-intel expects
x86_64. It also requires at least an ad-hoc signature on arm64, which closes
the AMFI "Killed: 9" class that uv has already been bitten by; the check is
skipped on x86_64, where unsigned code loads fine and so is not the same
defect. It fails when the scan finds nothing, since an empty scan reads exactly
like a clean one.

Make absence real rather than PATH-hidden. uv probes well-known interpreter
locations and the framework loader ignores PATH entirely, so hiding the
toolcache only hid it from `command -v`. Empty /usr/local (it EXISTS on a
factory-fresh Mac as a SIP-exempt firmlink, and is empty; it is /usr/local/bin
that is absent, so the directory itself stays), move the hosted toolcache and
/Library/Frameworks/Python.framework aside, and clear the developer dotdirs and
caches. A populated uv or pip cache can also satisfy a resolution that would
fail on a user's machine. Every removal goes through --remove and is recorded
in the generated restore.sh, guarded so a path the install recreated is not
buried inside its own restore.

Unset CI, GITHUB_* and RUNNER_* for the installer process only. An installer
branching on CI=true is a hidden dependency no consumer exercises. Scoped to
the child so the step's own $GITHUB_OUTPUT still resolves.

Record spctl --status and csrutil status. Neither is documented for these
images and both change what a binary is allowed to do.

* Pin the two failures no change here can fix, and add the virgin Windows container lane

Three red checks, two of which test something this branch does not own.

desktop linux deb / appimage run the SHIPPED bundle's own install.sh, and
desktop-v0.1.50-beta was cut on 2026-07-21, before #7547 merged on 07-29. That
bundle still carries the old optional-dependency gate, so on a stripped runner it
exits 2 at [TAURI:NEED_SUDO] cmake git build-essential libcurl4-openssl-dev and
never creates a venv. Current main's _check_linux_deps runs the same set through
_SMART_APT_OPTIONAL, which suppresses every escalation path, so only a new release
can change this. The step now pins that exact outcome: the exit code must be 2 and
the log must carry exactly that package list, anything else still fails, and
finding _SMART_APT_OPTIONAL in the extracted install.sh (the guard #7547 added)
turns into a hard error saying to delete the pin. The venv and torch assertions
stay and still run whenever the installer succeeds.

win windows-11-arm gets a native ARM64 CPython, and torchaudio publishes no
win_arm64 wheel at any version, so the PyTorch step cannot resolve. The fix is in
install.ps1 on #7549, still open. Same treatment: the Install step is
continue-on-error and a new step requires all three of the PyTorch step, the
torchaudio resolution error and the missing win_arm64 platform tag, so any other
failure is red. The row leaves experimental so the job is required, and the pin
errors out as soon as the venv interpreter reports anything but win-arm64, which
is what #7549 landing looks like.

Adds the virgin Windows container lane as two jobs here rather than a sibling
workflow: same premise as the win legs, same path filters, and masked-versus-real
reads better side by side. The hosted Windows legs cannot test the VC++
2015-2022 runtime (it ships in the runner image's System32) or a Windows with no
Microsoft Store, and a servercore:ltsc2022 container on windows-2022 answers both.
The probe asserts no python, py, git, cmake, cl, winget or uv on PATH, on disk or
in the registry, and now also asserts vcruntime140.dll, vcruntime140_1.dll and
msvcp140.dll are absent, which is the one thing the hosted runner cannot un-ship.

Both container install rows stop at studio/setup.ps1's winget-only git gate on
this branch, since #7549 is what relaxes it, so both are pinned the same way. The
overlay row additionally requires the UNSLOTH_CI_SOURCE_OVERLAY hook to have
fired, unconditionally: without that it would be indistinguishable from the
released-wheel row, and the hook is this branch's own feature.

Container notes carried over from the spike: never docker pull when the image is
cached, since MCR has shipped an image ahead of the runner host before; wait for
the Docker daemon, because one leg died in 21s on npipe:////./pipe/docker_engine
and that flake misreads as "Windows containers unavailable"; drive docker from a
run: step, because the job-level container: key is Linux-only. The root CA store
is seeded after the virginity assertion, restoring what a real Windows already
has, because studio/install_node_prebuilt.py downloads Node with bare
urllib.request.urlopen and hits CERTIFICATE_VERIFY_FAILED against the empty
container ROOT store. That product bug is left alone here.

* Check signatures on Mach-O main executables only

The macho check asserted a valid signature for every Mach-O under the studio
home, and failed the macos-15 mask/pipe leg on 29 files: lxml, charset_normalizer,
cygrpc, _upb, fontTools, caio, brotli and a bundled libportaudio.dylib. Those are
MH_BUNDLE and MH_DYLIB images dlopen'd into a process without library validation,
they ship unsigned in the wheels, and the same run had already installed and
imported them with the installer exiting 0.

Key the signature half off the Mach-O filetype and run it only on main
executables. Report an absent seal separately from one that fails to verify, and
capture codesign output instead of piping it into grep, which returned the
unsigned exit status through pipefail and called every unsigned binary broken.

The architecture half is unchanged and still a hard failure: it is what closes
the Rosetta 2 gap. The zero-Mach-O guard is unchanged. The .venv_t5_* sidecars
stay in scope; setup.sh creates them during a normal install and
transformers_version.py puts them on sys.path, so they are payload.

* Make the WSL job gate, assert Windows installed no toolchain, strip before the .deb

* Assert the root Linux legs did not compile llama.cpp with the apt-installed toolchain

* Pin the macOS desktop legs on the same pre-7547 release lag

The Linux rows already pin the shipped bundle's own install.sh exiting 2 at the
NEED_SUDO handshake. macos-15 and macos-26 fail the same way for the same reason:
desktop-v0.1.50-beta predates #7547, so the bundled installer still hard-exits on
the Xcode CLT gate that #7547 turned into a warning.

Accept exit 1 plus that exact gate line, and nothing else. _check_macos_deps is
the function #7547 added, so its presence in the bundle means the release caught
up and the block errors out asking for the pin to be deleted.

* Pin the WSL pipe truncation and the masked-winget git gate

The WSL leg dies at install.sh:2082 with an unterminated quoted string.
Nothing is wrong with that line: piping the script into sh is not atomic.
dash reads it from the pipe in 8192-byte blocks and runs each command as
it parses, and install.sh:2007 calls _maybe_reroute_strixhalo_to_2404,
which on WSL alone shells out to Windows interop; interop relays the
stdin it inherited and drains the pipe. dash has 11 blocks buffered at
that point, ending at byte 90112, which falls inside
"$STUDIO_LOCAL_INSTALL" on line 2082. Truncating install.sh at 90112
and parsing it reproduces the message verbatim, and running the whole
file under a stdin-draining interop stub reproduces the exit code too.
#7548 wraps the body in _unsloth_main so sh parses everything before
running anything, and the same reproduction against its head is clean.

The eight green staging runs cited when this job's continue-on-error came
off were all on trees that already carried #7548, so that evidence never
covered this branch. Pin the exact signature instead: exit 2 plus the
shell's own unterminated-quoted-string error, with the _unsloth_main
marker read back out of the distro as the flip condition.

Pin winget=masked the same way. studio/setup.ps1:1655-1669 gates on git
unconditionally and can only fetch it through winget, so masking winget
leaves no way to satisfy it. #7549 relaxes the gate, and its wording
appearing in the tree retires the pin.

* Retire the WSL pipe pin now that #7548 is in main

The pin flipped exactly as designed: it looks for _unsloth_main in the installer
it actually ran, and #7548 put it there. Delete the pin and the CLI waiver, and
assert the opposite instead.

WSL is the only platform whose install shells out to Windows interop mid-script,
and interop relays the stdin it inherited, so this job is the one that can catch
the pipe being drained again. A truncation here is now a hard failure.

* Gate the no-elevation Linux install and split off the no-transport case

* Assert no source build on the hosted Windows legs and keep winget for the desktop lane

* Retry the container root CA seeding instead of failing on one Windows Update timeout

* Run the clean-machine workflow for the prebuilt installer helpers it overlays

* Narrow the container pin to its own gates and scan uv and the venv interpreter for arch

* Tighten the clean-machine comments

* Re-assert toolchain absence after the desktop .deb pulls its dependencies

* Retire the #7549 pins and add a wget-only Linux leg

#7549 is in main, so the three known-outcome pins that were waiting on it are
stale and would now hard-error by design. Each is replaced by the assertion it
was standing in for rather than deleted:

win windows-11-arm now gates. The x64-on-ARM64 resolver is asserted as an
outcome: the venv interpreter reports win-amd64 from its own sysconfig, and
torchaudio (no win_arm64 wheel at any version) is installed. Measured on the
integration branch before #7549 merged: "only a native ARM64 Python 3.13 was
found" -> "installing x64 Python" -> torchaudio 2.10.0+cpu, install green.

win windows-latest / winget=masked now gates. The relaxed git gate is asserted
from both sides: the old unconditional message must be absent, the no-git
branch must have been reached (so the row cannot pass because git leaked back
onto PATH), and setup.ps1 must report git as absent-but-not-required.

Both Windows rows, and the visible one, gained the usability check the Linux
legs have had and Windows never did: a managed interpreter, an unsloth CLI on
disk, and that CLI actually running. nobuild and the toolchain check only read
the log, so an installer that exited 0 having produced nothing satisfied them.
The torch assert also loses its fallback to whatever `python` resolves to.

The virgin container overlay row gates, and asserts what only that lane can:
it is the one environment whose System32 does not already ship the VC++
2015-2022 runtime, so it is the only place Ensure-VCRedist's direct aka.ms
download can be proved to run rather than be short-circuited. The overlay=false
row keeps a pin, with a new reason: it installs unsloth from PyPI on purpose,
and setup.ps1 inside 2026.7.5 (uploaded the 23rd) predates #7549, so it still
stops at the old gate. That is release lag, it flips on the next release, and
the pinned signature is now the old wording rather than "#7549 has not landed".

Also adds linux ubuntu2404-nonroot-wget. install.sh's download() takes curl or
wget and _transport_missing is true only when both are gone, so a wget-only box
is supported on paper, but the gating nonroot leg provisions ca-certificates
AND curl, so curl won every probe and the wget branch had never run. Same image,
same no-sudo user, same asserts, wget instead of curl, and curl proved absent on
disk for root and for tester before AND after the install, so the claim is that
every download went through wget rather than that curl happened to be unused.

* Tighten the clean-machine CI comments

Comments only, no assertion logic, pins or leg definitions touched.

Reflowed every rationale block to denser wording and removed the
duplication that had built up across repeated steps: the desktop
workflow repeated the fork-PR skip, the desktop-v* tag resolution and
the restore-runner note once per platform, and the installer workflow
repeated its path-filter rationale in both the pull_request and push
blocks. Those now point at the first copy.

Every WHY is kept: why the masked legs avoid install.sh --local, what
UNSLOTH_CI_SOURCE_OVERLAY is for, why `absent` tests "must not work"
rather than command -v, why the .venv_t5_* sidecars are in the macho
scan scope, why the signature check is main-executables-only, why each
nobuild allowlist entry is a pure-Python sdist, why the WSL job gates
and what the pipe truncation was, and why the virgin container's
overlay=false row is still pinned.

Proved comments-only three ways: both workflow revisions parsed with
yaml.safe_load_all and every leaf walked (only `run:` scalars differ);
every changed bash body and .sh compared byte-for-byte after
`bash --pretty-print -n`; every changed pwsh body and .ps1 compared as
a token stream with Comment and NewLine tokens dropped. A negative
control injecting one non-comment line into each layer makes all of
them fail.

* Clean machine CI: strip Strawberry, make the Fedora pin gating, run the Linux CLI

desktop windows failed the strip verification because windows-latest ships a MinGW
toolchain under C:\Strawberry\c\bin, which matches none of the drop fragments; the
installer workflow already scrubs it.

Fedora sat behind job-level continue-on-error, so its outcome pin could not fail the
run. Tolerate the install step instead, as the no-transport row does.

The Linux usable-install check only tested the executable bit; Windows and WSL already
execute the CLI. The macho scan now fails when no venv interpreter was scanned, rather
than letting uv alone satisfy the outside-root guard.

* Clean machine CI: tighten the comments

Round 12 comment reduction: compress wording, keep every reason. Comments only,
verified with a YAML leaf walk (differences only inside run: scalars, only on # lines),
bash --pretty-print -n byte comparison, a PowerShell token-stream diff and a Python AST
comparison.

* Clean machine CI: dereference the venv interpreter, pin the deb deps and the Windows disposition

file did not follow the <venv>/bin/python symlink find -L printed, so it answered
'symbolic link to ...' and the Mach-O test dropped the one interpreter the Rosetta scan
exists to check. Read with file -Lb and count what was classified, not what was found.

apt treats a toolchain package the strip only renamed as already installed, so a .deb
that started declaring git or cmake would never restore it and the absent re-check would
still pass. Assert the declared Depends instead.

The Windows lane accepted any preflight disposition although the bundled installer was
already required to build a working venv; NotInstalled or ManagedStale there means the
app cannot boot what it just installed.

* Clean machine CI: assert every masked tool, and re-select the developer dir last

clean-machine-env.sh moves ten tools aside and only warns when a move fails, but absent
checked four of them, so a surviving gcc -- which install.sh probes for build-essential
-- went unnoticed.

restore.sh ran xcode-select --switch before the line that moved CommandLineTools back,
so it named a still-masked directory, failed into || true and left the selection link
unrestored. Capture the original selection and re-apply it after both directory
restores.

---------

Co-authored-by: danielhanchen <unslothai@gmail.com>
2026-07-29 06:21:40 -07:00
Nilay
52609fb890
Studio: reset-password rotates the credential in place instead of deleting auth.db (#7573)
* reset-password: rotate the admin credential in place instead of deleting auth.db

* reset-password: fix the CI callers and error handling for the in-place rotation

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* reset-password: narrow the CI change to the jobs that read .bootstrap_password

* reset-password: stop over-claiming what the reset revokes and when it takes effect

* auth: bind token issuance to the credential version that was verified

* auth: bind credential-creating writes to the version the request authenticated with

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* auth: bind the change-password and workflow-key writes to their own credential version

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* auth: read the credential version inside the transaction that validated it

* data-recipe: answer 401 when a reset revokes the credential mid job start

* Fix lint blocker and Windows path assertion for PR #7573

Drop the now-unused validate_api_key import from studio/backend/auth/authentication.py.
Every call site moved to validate_api_key_with_credential, so the Source lint job's
import-hoist gate flagged it as a blocker. The wrapper itself stays in storage.py;
test_api_key_expiry.py still exercises it.

Make test_run_reexec_forwards_resolved_frontend_on_public_launch compare against
str(Path(...)) instead of a POSIX literal. _find_frontend_dist returns a Path, so on
Windows the forwarded value is \fake\studio\frontend\dist and the assertion could
never pass there. Pre-existing, surfaced by running unsloth_cli/tests on Windows.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Han <danielhanchen@gmail.com>
2026-07-29 01:40:12 -07:00
Michael Han
2916e84499
Studio: clarify tool permission controls (#7181) 2026-07-20 09:55:39 -03:00
Daniel Han
03590f696e
Give opencode real timeout headroom in Local Agent Guides CI (#7235)
* Raise the opencode invoke timeout in Local Agent Guides CI

The connection (opencode) cell flakes with a 600s timeout reported as guide drift, but it is not a hang: in a passing run the same opencode run finishes in ~482s (08:12:31 to 08:20:33), right against the shared AGENT_INVOKE_TIMEOUT of 600s, so about one run in six drifts past the cap.

opencode is the slow outlier. The print-mode agents (claude -p, codex exec) run one turn against a minimal injected system prompt, while opencode run runs its own full turn with opencode's large system prompt plus a separate small_model call to name the session (start.py pins small_model to the same 4B the server hosts). On a CPU-served gemma-4-E4B that is about 8 minutes, leaving no margin under 600s.

Double opencode's per-invoke timeout in agent-guides-drive.sh and keep the tight 600s cap for the fast agents, so a genuine headless-TTY hang still fails quickly. 1200s stays well under the 40-minute job budget.

* Normalize the agent invoke timeout before doubling it for opencode

Strip an optional trailing 's' from AGENT_INVOKE_TIMEOUT so the opencode
arithmetic, and the "${TIMEOUT}s" timeout message, stay valid if a
timeout(1)-style suffix is ever configured.

* Only double the opencode timeout for a bare-integer seconds value

Guard the arithmetic so a GNU timeout(1) duration suffix (s/m/h/d, including
floats like 0.5s) is passed through unchanged instead of breaking the
expansion; timeout(1) parses those directly. Bare seconds still double.

---------

Co-authored-by: danielhanchen <unslothai@gmail.com>
2026-07-19 06:08:54 -07:00
Michael Han
6d8c18cd1a
Replace standalone Studio wording with Unsloth (#7221)
* Replace standalone Studio wording with Unsloth

Replace the single word Studio with Unsloth wherever it is used as
shorthand for Unsloth Studio in docs, CLI output, UI strings, i18n
locales, workflow display names, comments and docstrings.

Kept unchanged: the full name Unsloth Studio, third party product
names (LM Studio, Visual Studio, Mac Studio), feature names
(Recipe Studio, Fine-tuning Studio and its translations), and all
identifiers such as env vars, commands, paths and filenames.

* Address review feedback on the Studio wording rename

Use "an" before Unsloth where the rename left the article as "a".
Restore the split brand where Unsloth and Studio render as two halves
of the full product name: the onboarding sidebar subtitle and the
IPv6 localhost warning. Scope two messages to the full name Unsloth
Studio where plain Unsloth was misleading: the AMD README bullet and
the CLI studio setup error.
2026-07-19 00:47:04 -07:00
Daniel Han
c1e06e9ddf
unsloth start: add --persist to keep and reopen agent sessions (#7014)
* unsloth start: add --resume to persist and reopen agent sessions

`unsloth start <agent>` launches a coding agent whose home is a throwaway
temp dir wiped on exit, so codex/openclaw/hermes/pi (which relocate their
whole home there) cannot resume a conversation after you quit. opencode and
claude keep their session data in a fixed user dir, so they already resume.

Add an opt-in --resume/--no-resume flag: it routes the launch to the stable
Unsloth agents dir (the same one --no-launch already uses) so the session
survives the exit, never touching the user's own ~/.<agent>. A bare --resume
also reopens the last conversation via the agent's native flag (codex
`resume --last`, opencode/claude/pi `--continue`). The default is unchanged:
a plain launch still uses a temp dir and persists nothing.

Add a dispatch-only `resume` job to the Local Agent Guides CI that drives the
real launch path and asserts the split: codex/pi are wiped without --resume
and persist with it, while opencode/claude persist either way.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* unsloth start: rename --resume to --persist

The session flag collided with agents' own resume flags. `unsloth start
claude --resume <id>` used to forward `--resume <id>` straight to Claude
(which keeps its history in ~/.claude regardless), so a boolean --resume on
unsloth start would have swallowed the session id and turned it into a stray
prompt. Name the persistence flag --persist instead, so every agent's native
resume flag (claude --resume <id>, codex resume, opencode --continue, ...)
still passes through untouched. Behavior is otherwise identical: --persist
keeps a launched agent's session under the Unsloth agents dir, and a bare
--persist reopens the last conversation.

Add a regression test that `--resume <id>` passes through verbatim, and in the
CI resume experiment skip the redundant second pass for opencode/claude (they
persist either way, and a second CPU turn only risks a timeout).

* unsloth start: correct --persist help and drop the buggy auto-resume

Reword the --persist help to be accurate: claude and opencode keep sessions in
the user's own stores and resume regardless, so --persist only stabilizes the
otherwise-ephemeral relocated home of codex/openclaw/hermes/pi. Drop the
bare-launch auto-append of native resume tokens: it errored on a first launch
with no prior session, and was inconsistent between launch and no-launch.
--persist now only keeps the session dir; resume via the agent's own command
(e.g. `unsloth start codex --persist resume`), which now finds it.

In the CI resume experiment, fail the pass when the launched turn exits
non-zero, so a write-then-error is not misread as PERSISTED.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2026-07-09 11:47:59 +02:00
Lee Jackson
6ef0936180
Fix OpenClaw start default to local TUI (#6937)
* fix: launch OpenClaw local TUI by default

* Fix/adjust OpenClaw launch paths for PR #6937

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Default OpenClaw to the local TUI only on a bare invocation

The first-arg startswith('-') branch rewrote passthrough globals into a broken
command: OpenClaw's grammar is openclaw [--dev] [--profile <name>] <command>, so
'unsloth start openclaw --profile test' became 'openclaw tui --local --profile
test', but tui does not accept --profile (or --dev), so the invocation failed.

A leading '--flag value' is ambiguous between a global (--profile test) and a tui
option (--message hi), so it cannot be reinterpreted safely. Default to the local
TUI only when no passthrough args are given, and forward everything else verbatim
so OpenClaw parses it under its own grammar. The bare-launch default (the point
of this change) is preserved; explicit subcommands and global flags pass through.

---------

Co-authored-by: wasimysaid <112766706+wasimysaid@users.noreply.github.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <danielhanchen@gmail.com>
Co-authored-by: Wasim Yousef Said <wasimysdev@gmail.com>
2026-07-08 04:25:42 -07:00
Daniel Han
69f8e0b228
Clear stale yolo approval state on no-launch reruns (#6868)
* Clear stale yolo approval state on no-launch reruns

The no-launch session config dir is deliberately reused across runs, but
the config writers only ever added the --yolo auto-approval settings and
never removed them. After one --yolo --no-launch run, every later run
without --yolo kept OpenClaw's tools.exec security=full/ask=off policy
plus exec-approvals.json, and OpenCode's permission allow block, so tool
execution stayed silently pre-approved.

Non-yolo runs now reset that state: OpenClaw drops the exec policy keys
and the yolo defaults in exec-approvals.json (approvals OpenClaw itself
recorded are kept; the file is removed when only the yolo payload is
left), and OpenCode drops the permission block. Launch mode is untouched
since it already uses an ephemeral temp dir.

* Strip only yolo-written values on non-yolo cleanup

Match each field against the exact value the yolo path writes before
removing it, so a stricter exec policy, approvals defaults set by the
user or the OpenClaw UI, and deny/ask OpenCode permission entries all
survive a plain no-launch rerun. An unparseable exec-approvals.json is
left in place, matching how an unparseable config is handled.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Write a prompting policy on non-yolo instead of deleting to a permissive default

OpenClaw and OpenCode both treat an omitted policy as permissive: OpenClaw's
effective exec policy for an unset tools.exec is security=full/ask=off on the
gateway host, and OpenCode defaults an unset permission to allow. So clearing
the yolo values on a non-yolo run did not restore prompting, it fell back to
those permissive defaults and left tool execution auto-approved.

A non-yolo run now writes an explicit prompting policy: OpenClaw gets
security=allowlist/ask=on-miss (verified to prompt even with the approvals file
removed, since the stricter of config and approvals wins), and OpenCode gets
edit/bash/webfetch=ask. Only a permissive/yolo value is tightened; a stricter
deny (or an ask the user set) is preserved, and the yolo approvals defaults are
still stripped. The file-edit CI path opts opencode/openclaw into --yolo, since
those agents now prompt by default and the headless test needs auto-approval.

* Respect existing exec mode, sandbox/node host, and global permission rules on non-yolo reset

The non-yolo reset for openclaw/opencode assumed an omitted policy was the
permissive yolo default and rewrote it, which corrupted or weakened stricter
setups it should have preserved:

- OpenClaw tools.exec.mode is the normalized policy knob and cannot be combined
  with explicit security/ask (OpenClaw rejects the whole config), so writing
  security+ask alongside a mode:deny/ask policy both broke the config and
  relaxed it. Leave a mode-based policy untouched.
- host=sandbox defaults to security=deny and host=node routes to a paired node;
  neither is written by --yolo (which only writes host=gateway). Treating the
  missing security as full and popping host broadened those into gateway/auto
  exec. Only rewrite a gateway-routed permissive policy, and never pop a
  non-gateway host.
- OpenCode permission can be a string ("deny") or a {"*": ...} catch-all.
  The old code dropped a string form and overrode a catch-all by writing
  per-tool ask, weakening a stricter user rule. Now a string is left in place,
  a catch-all governs absent tools, and only an effective allow is tightened.
- The non-yolo ask policy only lived in OPENCODE_CONFIG, which loads below
  project opencode.json, so a project config allowing edit/bash/webfetch still
  auto-approved. Carry the ask policy in OPENCODE_CONFIG_CONTENT (above project
  config) too, symmetric to how yolo carries its allow.

Also harden the openclaw path against a malformed non-dict tools value.

Adds tests for mode/sandbox/node hosts, string and catch-all permissions, and
the inline ask policy over a project config.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Scope non-yolo resets to the exact yolo fingerprint and preserve granular denies

OpenClaw: reset only the exact host=gateway/security=full/ask=off policy --yolo
writes, so an omitted or host=auto/sandbox/node policy (which can resolve to a
sandbox security=deny default) is no longer broadened to allowlist/on-miss, and a
deliberate tools.exec.mode is left alone (OpenClaw never migrates our security/ask
write into a mode).

OpenCode: carry a granular object or a deny inline verbatim so a per-tool user rule
is not collapsed to a blanket ask, but floor any object that grants allow anywhere to
the string ask (which fully replaces a project object) so no inline allow pattern can
leak through into a silent auto-approve on a non-yolo session.

* Stop overriding project config on non-yolo; require full approvals fingerprint

The non-yolo OpenCode reset carried a session permission in
OPENCODE_CONFIG_CONTENT, which outranks the project opencode.json we
cannot read. That inline override could not correctly reflect the project:
it weakened a project deny to a prompt, mishandled global string rules,
leaked through a granular object's permissive default when no catch-all
was present, collapsed an object with an allow (losing its deny), and
missed per-agent permissions. All of these stem from forcing a value over
an unknown project config.

A non-yolo run now only undoes what --yolo wrote: it flips our own
explicit per-tool allow back to ask in our config file and carries no
permission inline, so the project's own permissions are honored as
written. Clearing our persisted yolo state is the actual fix; --yolo still
carries its allow inline so it works over a project config.

OpenClaw approvals cleanup now strips the yolo defaults only when the full
fingerprint (security=full, ask=off, askFallback=full) is present, so a
mixed user policy that merely shares askFallback=full (whose omitted
default is deny) is kept intact.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2026-07-07 00:06:48 -07:00
Nilay
b8400f40df
CLI: Rename unsloth connect to unsloth start (#6613)
* replaced connect with start

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* fix

* Studio: build the coding-agent command from the selected server

The API keys panel showed a hardcoded `unsloth start claude`. `unsloth start`
defaults to 127.0.0.1:8888 and only mints a key for a loopback server, so a
non-default port or a tunnel/remote base would target the wrong server or fail
to mint. Build the command from the panel base/key (and emit a key for
non-loopback), matching the other snippets in the panel.

* CLI: keep `unsloth connect` as a hidden alias for `unsloth start`

Avoids breaking existing scripts and docs that still call `unsloth connect`.

* Tests: stub _unstarted_cleanup in same-task disconnect test

The test builds _SameTaskStreamingResponse via __new__, so set the attribute
that __call__ now reads.

* Match coding-agent command loopback check to the CLI 127.0.0.0/8 rule (#6613)

* Keep unsloth_cli.commands.connect importable as a deprecated shim (#6613)

* Format the new coding-agents panel strings and import per biome (#6613)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Drop the unsloth connect alias and shim; unsloth start is the only command (#6613)

* Route unsloth connect to unsloth start as a hidden backward-compatible alias (#6613)

* Forward unsloth run model-load flags to unsloth start (gguf-variant, context-length, load-in-4bit, tensor-parallel) (#6613)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Session-scope coding agent config in unsloth start

Configure each agent for the current session instead of writing the Studio endpoint, key, and default model into the user's own config. Codex, OpenCode, OpenClaw, and Hermes get a private config relocated through their config-path env vars (CODEX_HOME, OPENCODE_CONFIG overlay, OPENCLAW_CONFIG_PATH plus OPENCLAW_STATE_DIR, HERMES_HOME). Claude Code suppresses the attribution header for the session via the CLAUDE_CODE_ATTRIBUTION_HEADER env var plus a --settings overlay, with no ~/.claude write. --launch uses an ephemeral temp dir removed after the agent exits; --no-launch uses a stable Unsloth-owned dir and prints the matching export lines.

* Read relocated agent session config in Local Agent Guides CI

The contract crosscheck and the openclaw/hermes patch helpers now read each agent's config from the relocated path printed by unsloth start --no-launch (CODEX_HOME, OPENCODE_CONFIG, OPENCLAW_CONFIG_PATH, HERMES_HOME) instead of fixed home paths. The Claude attribution A/B toggles the header for the session only (shipped-config HIT vs vanilla MISS) instead of editing ~/.claude/settings.json.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Skip the POSIX-only --no-launch parser test on Windows

test_no_launch_output_is_parseable mirrors the #6547 bash CI parser, which greps export/unset lines and only runs on Linux/macOS runners. On Windows --no-launch prints PowerShell ($env: / Remove-Item), so the export-line assertion does not apply there. Cross-OS staging CI surfaced this.

* Size Claude Code's auto-compact window to the loaded model's context

Claude Code auto-compacts against its native (~600k token) window, so against a smaller local model it overflows the server's context (silent truncation) long before it compacts. Set CLAUDE_CODE_AUTO_COMPACT_WINDOW to the loaded model's real context length (the value codex/openclaw already get via model_context_window / contextWindow). Omitted when the model reports no context length.

* Pin OpenCode/Hermes context window and set 90% compaction across agents

Feed every agent the server-determined sequence length (the value /v1/models reports from runtime_context_length) and a ~90% compaction threshold. OpenCode: a custom-provider model with no limit defaults to context 0, which silently disables auto-compaction, so set limit.context/output and scale the compaction buffer to 10% of the window. Hermes: pin model.context_length (it otherwise falls back to a 256k default when the server's /v1/models omits the field) and set compression.threshold 0.9. Claude: add CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=90 alongside the window. Codex (model_context_window) and OpenClaw (contextWindow) already carried the window and auto-manage off it.

* Add `unsloth start pi` recipe

Pi was the only agent without a built-in recipe, so the agent-guides CI
hand-wrote ~/.pi/agent/models.json. Add a first-class `pi` command mirroring
the others:

- write_pi_config writes the session-scoped OpenAI-compatible provider config
  (key in the config, like openclaw/opencode).
- pi() launches `pi --provider unsloth --model <id>` (Pi defaults to the google
  provider, so the provider/model are pinned on the command line) with HOME
  relocated for the session. Pi has no config-dir env var and resolves ~/.pi off
  $HOME, so HOME-scoping keeps the user's ~/.pi untouched.

Migrate the agent-guides CI off the hand-written config onto the
`unsloth start pi --no-launch` path (connection + file-edit), with a crosscheck
for the provider api, so the documented recipe is exercised.

* Harden unsloth start for Windows and WSL agent launches

Address the Codex review on PR 6613:
- write_pi_config now pins the loaded contextWindow and a sane maxTokens so Pi
  compacts instead of overflowing a small Studio context (it otherwise assumes
  its 128000 default), matching the other agents.
- pi() sets USERPROFILE (and HOMEDRIVE/HOMEPATH when present) alongside HOME on
  native Windows, where Node resolves ~/.pi via USERPROFILE rather than HOME, so
  the session no longer reads or writes the user's real ~/.pi.
- The WSLENV bridge flags path-valued vars with /p so a Windows npm shim under
  /mnt receives translated paths, while scalar vars (the numeric context window)
  pass through untranslated. WSLENV is deduped on the bare name.
- _print_env prints the launch command with PowerShell-safe quoting so the inline
  --settings JSON survives copy-paste on native Windows --no-launch.

Add tests for the WSLENV path flagging, PowerShell quoting, the Pi context
window, and the Pi USERPROFILE relocation.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Set CLAUDE_CODE_NO_FLICKER for the Claude session

A local server streams in bursts, so Claude Code's full-screen TUI redraw
flickers between tokens. Disable it for the session via CLAUDE_CODE_NO_FLICKER,
alongside the other CLAUDE_CODE_* session env knobs.

* Add a normalized --yolo flag routed to each agent's auto-approve mode

It is easy to forget which agent spells "run tools without prompting" which way,
so `unsloth start` now accepts all three spellings as one option (--yolo,
--dangerously-skip-permissions, --dangerously-bypass-approvals-and-sandbox) and
routes to the agent's own mechanism:

- claude:   --dangerously-skip-permissions
- codex:    --dangerously-bypass-approvals-and-sandbox
- hermes:   --yolo
- pi:       --approve (Pi's only approval gate is project trust)
- opencode: a permission allow block in opencode.json (no CLI flag exists)
- openclaw: tools.exec security=full / ask=off / host=gateway (no CLI flag exists)

Because the option is parsed by `unsloth start`, the "wrong" spelling for an
agent still routes correctly instead of leaking through to the agent and erroring.
IS_SANDBOX is deliberately left unset for Claude so its root/sandbox safety gate
still applies. Adds routing, cross-routing, and per-config tests.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fix review findings: IPv6 loopback command, pi USERPROFILE under WSL, yolo guard

From a 10-reviewer pass over the PR:

- studio/frontend agent-command.ts: normalize bracketed IPv6 hosts. URL.hostname
  returns "[::1]" for http://[::1]:8888, which never matched the "::1" loopback
  checks, so the copied command embedded the placeholder API key for a local IPv6
  server instead of the bare auto-minting command. Now [::1] is treated as loopback
  like the CLI's is_loopback_url, so the command matches the CLI contract.

- pi(): also relocate USERPROFILE (and HOMEDRIVE/HOMEPATH) when running under WSL
  against a /mnt Windows shim, not just on native Windows. Windows Node resolves
  ~/.pi via USERPROFILE, and the WSLENV bridge translates the path, so pi no longer
  falls back to the user's real ~/.pi in that case.

- _yolo_command_flags: use .get so a config-based agent (or a typo) yields no flag
  instead of a latent KeyError.

Adds tests for the WSL pi USERPROFILE relocation, the yolo unmapped-agent guard,
and that opencode/openclaw --yolo stays config-only (no argv flag).

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fix round-2 review findings: WSLENV /p upgrade, agent help text

- _merge_wslenv now upgrades a user's pre-existing unflagged WSLENV entry (e.g. a
  bare HOME or USERPROFILE) to the path-translated form (HOME/p) instead of leaving
  it as-is, so a Windows agent shim under WSL receives the translated session path
  rather than the raw Linux path.
- Generalize the `unsloth start` registration help to list all six agents (was only
  "Claude Code, Codex").

Adds a test for the WSLENV unflagged-entry upgrade.

* Fix round-3 review findings: complete openclaw --yolo, refresh stale copy

- openclaw --yolo now also writes the host approvals file (exec-approvals.json with
  defaults security=full / ask=off / askFallback=full) alongside the tools.exec
  config. OpenClaw gates tool execution on both layers (the stricter wins), so the
  config alone could still leave it prompting or denying. Mirrors `openclaw
  exec-policy preset yolo`. ask=off means nothing is ever prompted, so the runtime
  socket block is unnecessary.
- Studio API panel copy: clarify that a local server auto-mints the key while a
  remote one embeds it in the command, and add pi to the swap hint.
- Local Agent Guides CI: drop the stale "pi has no start.py recipe" note now that
  all six agents are driven via `unsloth start <agent> --no-launch`.

Adds the openclaw approvals-file assertions and a no-yolo openclaw test.

* start: parse claude --version with a regex so a format change does not drop optimization flags

* start: offer to install a missing agent (prompt then run its install command)

* start: auto-start a Studio server for --model when none is running, and stop it on exit

* inference: surface an actionable message when llama-server cannot compile a tool grammar

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fix review findings: kill the auto-started server tree on Windows; apply the tool-grammar message to the OpenAI passthrough too

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* start: split --model org/repo:variant so a running session is not evicted

`unsloth start <agent> --model org/repo:QUANT` failed against an already-running
Studio server and, worse, killed whatever model another session had loaded.

/v1/models lists a loaded GGUF under its bare repo id (e.g. unsloth/Qwen3-1.7B-GGUF),
so _resolve_model never matched the `:QUANT`-suffixed request. It then POSTed
/api/inference/load with model_path=org/repo:QUANT, which (a) Hugging Face rejects
("Repo id must use alphanumeric chars, '-', '_' or '.'") and (b) evicts the model the
other session was using, so a second 'unsloth start' in a new tmux/terminal tore down
the first. Re-running the command then attached to the now-empty server, which is why
it 'worked the second time'.

Mirror the org/repo:QUANT -> org/repo + --gguf-variant QUANT shorthand that
'unsloth run' and llama.cpp already accept, splitting it in _connect before we match or
serve. Matching now resolves against the loaded bare repo id (no spurious reload, no
eviction), and any real load uses a valid repo id plus gguf_variant. An explicit
--gguf-variant still wins; local paths and Windows drive letters pass through untouched.
The auto-serve path likewise spawns 'unsloth run --model org/repo --gguf-variant QUANT'.

* start: harden auth-key handling, codex teardown, and CI transcript redaction

Three review findings:

1. CI could leak a live key. agent-guides-drive.sh printed the raw
   'unsloth start --no-launch' transcript (which carries export UNSLOTH_API_KEY /
   ANTHROPIC_AUTH_TOKEN lines) to the Actions log on both the failure path and the
   success path before redact() ran. Add cat_redacted() and use it for those two
   prints, so the key is scrubbed on the way to the log while the on-disk file stays
   intact for the env parsing that follows.

2. Outages masqueraded as bad keys. _key_accepted caught a broad Exception and
   returned False, so a 5xx or timeout while checking a cached key looked like a
   rejection: it discarded a good key and minted extra ones (local) or reported 'no
   saved key' (remote). Only treat HTTP 401/403 as a rejection; let other errors
   propagate so a real outage surfaces.

3. Codex preflight could leave the auto-started server up. _require_gguf_for_codex
   runs after _connect may have auto-started Studio but before _run installs its
   teardown finally, so a preflight rejection (e.g. a transformers-backend model) left
   the server holding the port/GPU until the atexit backstop. Tear it down explicitly
   at the point of failure.

Tests: a 5xx on a saved key surfaces without minting; a non-GGUF codex preflight
tears down the auto-served server.

* start: fix IPv6/portless studio URLs, Pi config-dir isolation, and Pi install recipe

Four review findings:

1. Pi ignored the session config when PI_CODING_AGENT_DIR was already set. Pi's
   getAgentDir() reads process.env.PI_CODING_AGENT_DIR before falling back to
   $HOME/.pi/agent, so a value inherited from the user's shell sent Pi to their real
   config and skipped our provider/key (the HOME relocation alone was not enough). Pin
   PI_CODING_AGENT_DIR at the session's .pi/agent dir; it is path-valued so the WSL
   bridge translates it automatically.

2. Pi install hint dropped Pi's documented --ignore-scripts. Pi's README installs with
   'npm install -g --ignore-scripts @earendil-works/pi-coding-agent' and notes it needs
   no install scripts, so accepting the prompt now follows that safe recipe.

3. Auto-start ignored a portless UNSLOTH_STUDIO_URL. unsloth run binds to
   'parsed.port or 8888', so http://127.0.0.1 launched the child on 8888 but the health
   poll (and the returned base) still used port 80, stalling until the startup timeout.
   Normalize the base to host:8888 (IPv6-safe) before starting and polling.

4. API-panel command mistook IPv6 loopback for the bare default. The bare 'unsloth
   start' only probes 127.0.0.1:8888 on the IPv4 stack, so http://[::1]:8888 must carry
   an explicit UNSLOTH_STUDIO_URL. Drop ::1 from the bare-default host set while keeping
   it a loopback host (URL emitted, no key needed).

Tests: PI_CODING_AGENT_DIR is set to the session dir; _effective_base normalizes
portless/IPv6 bases; a portless UNSLOTH_STUDIO_URL auto-serves on :8888.

* start: apply fresh-review findings across CLI, CI, and the API-panel command

From a fresh multi-reviewer pass over the merged head plus the latest Codex bot review:

1. Load knobs now always consult the server. _resolve_model matched on model id alone,
   so --gguf-variant / --context-length / --no-load-in-4bit / --tensor-parallel were
   silently ignored whenever the id was already loaded (asking for UD-Q4_K_XL kept a
   Q8_0 serving). With any explicit knob the CLI defers to /api/inference/load, whose
   already-loaded dedup answers without reloading when variant and settings match, so a
   second session running the same command still attaches without evicting the first.

2. OpenCode --yolo and the session model pin now ride in OPENCODE_CONFIG_CONTENT. A
   project's own opencode.json outranks OPENCODE_CONFIG, so a repo config could silently
   override the session model and the --yolo permission block; OPENCODE_CONFIG_CONTENT
   outranks project config. The API key stays in the private file, never in printed env.

3. The --no-launch recipe's last line is a self-contained one-liner (inline VAR=value
   assignments before the command, conflicting vars blanked). People copy just the last
   line, and a bare codex/claude there ran against the user's real ~/.codex or Anthropic
   credentials with zero isolation, e.g. inheriting a pre-existing damaged ~/.codex
   state DB and blaming the recipe. The CI drive script scrubs the key from the one
   'invoking:' echo this adds.

4. The auto-serve log is 0600 and the parent handle is closed. It sat world-readable in
   the shared tempdir under a predictable name while carrying the minted sk-unsloth-
   key from the unsloth run banner.

5. _key_accepted fails with a clean message on outages. Non-auth errors (5xx, network,
   timeout) surfaced as a raw traceback; 401/403 still mean a rejected key.

6. _effective_base strips URL paths, and https loopback targets never auto-serve.
   http://127.0.0.1:8888/studio polled /studio/api/health (404) and https://127.0.0.1
   polled the wrong scheme, both spinning until the 15-minute startup timeout.

7. API-panel command: only literal 127.0.0.1:8888 earns the bare command. localhost can
   resolve to ::1, which the bare CLI never probes, so it keeps UNSLOTH_STUDIO_URL.

8. CI artifact sweep covers redacted-configs/ and agent-workdir/, not just logs/.

Tests: 125 CLI tests pass (new coverage for each fix), 156 backend tests pass, ruff
clean. Adds an unsloth connect alias regression test.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* start: hand Pi a clean screen at launch

Pi paints inline from wherever the cursor sits: its first render assumes a
clean screen instead of clearing or entering the alternate screen itself
(current Pi never emits a clear at startup). Launched under unsloth start,
that left the session starting mid-scroll beneath the connection output.
Clear the screen (click.clear, cross-platform, no-op without a TTY) right
before the Studio banner so Pi opens exactly one line down on a clean
viewport. Launch path only: --no-launch recipes and piped output are never
wiped, and alternate-screen agents are left alone.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* start: auto-override hermes' 64K context floor for small model windows

Hermes refuses to initialize when the served model's context window is
under 64,000 tokens, and a second copy of the same check rejects the
compression model mid-session. write_hermes_config previously pinned the
real window, so any small local model (e.g. 40,960) failed at startup
with manual config.yaml instructions.

For windows below the floor the recipe now claims 65,536 in
model.context_length, scales compression.threshold so compaction still
fires at 90% of the real window, and sets
auxiliary.compression.context_length to cover the mid-session check.
Windows at or above the floor keep the exact previous behavior.

* ci: install pi with --ignore-scripts, matching the start.py hint

The pi cell predates the pi recipe in start.py and still installed the
package with lifecycle scripts enabled, so CI stopped exercising the
exact command users are prompted to run. npm_retry now passes extra
flags through, the pi branch mirrors the install hint verbatim, and the
stale no-recipe comment is refreshed.

* ci: fail loudly when a relocation var is missing from connect output

The empty-string guards ran after appending /config.toml or /config.yaml,
so they could never fire: crosscheck_contract silently skipped its
contract checks and patch_hermes_tools died on the root path with a bare
traceback. Check the raw variable first and guide_fail with the real
cause.

* staging: 6613 round 6 (https elision, no-launch home reuse, auto-start key fallback)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: shimmyshimmer <107991372+shimmyshimmer@users.noreply.github.com>
Co-authored-by: Daniel Han <danielhanchen@gmail.com>
Co-authored-by: Lee Jackson <130007945+Imagineer99@users.noreply.github.com>
Co-authored-by: Wasim Yousef Said <wasimysdev@gmail.com>
2026-07-03 08:17:27 -07:00
Daniel Han
264f1a04f8
Add Local Agent Guides CI (#6547)
Boot `unsloth run --disable-tools` against a small GGUF and drive each
supported coding agent (claude, codex, hermes, openclaw, opencode, pi)
through its documented `unsloth connect <agent> --no-launch` recipe, so
the connect flow in unsloth_cli/commands/connect.py stays exercised end
to end and regressions surface as a failing check.

Per-agent matrix, three jobs:
- connection: assert a non-empty, error-free reply to a trivial prompt
- file-edit: a two-turn create-and-run hello.py test (dispatch/schedule
  only, skipped on pull_request)
- prompt-cache: verify llama.cpp prefix-cache reuse across requests

The GitHub-hosted runners are CPU-only, so each request is trimmed to
the smallest prompt that still drives the recipe: claude with --tools to
drop unused tool schemas (--allowedTools only gates permission, it does
not shrink the prompt), hermes with an empty platform_toolsets.cli, and
openclaw with a minimal agent definition. hermes and openclaw run a
multi-turn tool loop in file-edit that a CPU runner cannot finish in
time, so those two cells are best-effort; their endpoint wiring is still
hard-gated by the connection job.

A preflight step HTTP-checks each agent's API dialect before install so a
server-side contract regression is reported separately from agent or
guide drift.
2026-06-22 04:21:48 -07:00
Daniel Han
e83d4ae072
Windows installer: fix DiskPart UAC mid-install, drive-root cache, and spurious unsloth.exe rename warning (#6296)
* Windows installer: fix DiskPart UAC, drive-root cache, spurious rename warning, CPU-base messaging

amd-smi gate (DiskPart UAC mid-install): the AMD torch wheel ships hipInfo.exe
inside the venv, and the bitsandbytes fix prepends that venv Scripts dir to PATH.
shutil.which("hipinfo") then found it and flipped _amd_smi_allowed() to True, so
the post-install AMD probe fell through to `amd-smi list` (the venv hipInfo failed
to report gcnArchName, which is why the arch came from the GPU-name table) and
amd-smi elevated, popping the DiskPart UAC. Fix: a hipinfo resolved inside the
active venv (sys.prefix) is the torch-wheel binary, not a HIP SDK, and must not
open the gate. Mirrored in install_python_stack.py, install_llama_prebuilt.py, and
backend utils/hardware/amd.py (the runtime VRAM poller had the same latent prompt).

TORCHINDUCTOR_CACHE_DIR: move from C:\tc to <StudioHome>\TORCHINDUCTOR_CACHE_DIR so
the inductor/Triton cache lives under the user's Studio home, not the system drive
root. Long paths are already enabled above so deep inductor paths still fit.

unsloth.exe rename: skip the rename (and its "pip may fail with WinError 32"
warning) when SKIP_STUDIO_BASE=1. In the install.ps1 flow base packages are not
reinstalled, so unsloth.exe is never rewritten; the self-rename only failed because
setup runs via unsloth.exe (the running launcher holds its own file). The
'studio update' flow still attempts it.

CPU PyTorch messaging: clarify that the CPU base is temporary and setup replaces it
with GPU ROCm wheels, and print an explicit "GPU ROCm PyTorch installed" line after
the AMD wheels land, so the log makes clear the final install is GPU-accelerated.

Adds two regression tests covering the venv-internal vs external hipInfo gate.

Verified end-to-end on a Strix Halo box (Radeon 8060S / gfx1151): install.ps1
--local from this branch completed exit 0 with no DiskPart prompt, no rename
warning, the cache under the Studio home, and "GPU ROCm PyTorch installed
(gfx1151)"; Studio then booted and detected "ROCm (HIP 7.13.99004) -- AMD Radeon
8060S Graphics".

* Windows installer: drop the unreliable unsloth.exe rename and its WinError 32 warning

setup.ps1 used to rename the running unsloth.exe out of the way before the
base-package upgrade so pip could replace it. That rename never actually
worked: setup runs *via* unsloth.exe, so renaming our own running
uv-trampoline launcher failed with a sharing violation (WinError 32) and only
printed a scary 'could not rename unsloth.exe; pip may fail with WinError 32'
warning on every Windows install and update.

It also was not needed. pip tolerates a running/locked console-script .exe: it
moves the old one aside and writes the new one. The base upgrade routes through
pip on Windows, so the upgrade succeeds (or, in the install.ps1 flow with
SKIP_STUDIO_BASE=1, the base is not touched at all) and unsloth.exe is left
intact either way.

Removing the rename block and its failed-install restore block removes the
false warning for all Windows devices in both the install and update flows.

* Windows installer: gate venv-internal hipInfo.exe in PowerShell amd-smi probe; harden venv path checks

Follow-up to PR #6296.

- install.ps1 and setup.ps1: ignore the AMD torch wheel hipInfo.exe that lives
  inside the Studio venv when probing for a HIP SDK, so amd-smi no longer reopens
  the DiskPart UAC during install/update. Mirrors _path_inside_venv in the Python
  installers, which already do this.
- amd.py, install_llama_prebuilt.py, install_python_stack.py: normcase the venv
  containment check (Windows paths are case-insensitive) and run the
  HIP_PATH/ROCM_PATH candidate through it too.
- setup.ps1: fall back to a short TORCHINDUCTOR cache dir when long paths are
  unavailable, and create the dir wildcard-safely.
- tests: isolate sys.prefix in the gate helper, add HIP_PATH/ROCM_PATH cases, and
  assert the PowerShell venv exclusion.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Windows installer: install ROCm PyTorch directly for a known AMD arch

When the GPU arch is known (name-inferred from the GPU-name table) but ROCm
could not be probe-verified (no HIP SDK, no amd-smi), the bootstrap installed
a CPU PyTorch base that setup.ps1 then force-reinstalled as ROCm. The
repo.amd.com wheels bundle their own runtime (no HIP SDK required), which
setup.ps1 already relies on, so the CPU base was a pure wasted download/install.

- Gate the ROCm index on a known arch, not only on probe-verified ROCm, so a
  mapped arch installs ROCm torch directly. Unmapped arches and no-GPU hosts
  still get CPU (unchanged).
- Fall back to a CPU base if the ROCm-index install fails, so a transient
  repo.amd.com outage does not abort the install (setup.ps1 retries ROCm).
- Correct the stale comment that claimed ROCm wheels need a confirmed HIP SDK.
- Add a regression test for the arch-based gate.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Windows installer: correct the unsloth.exe rename-removal comment

The comment claimed the base upgrade 'routes through pip on Windows' and that
pip 'moves the old unsloth.exe aside, then writes the new one'. That is not what
the code does. install_python_stack tries uv first; on a locked launcher uv
aborts and falls back to pip, but the pip fallback strips --upgrade-package and
base.txt lists only bare unsloth/unsloth-zoo, so pip finds them already
satisfied and no-ops. The running unsloth.exe is left intact at its current
version either way. Reword the comment to describe the real uv-first /
pip-fallback-no-op behavior. No functional change.

* Windows installer: close two gaps in the venv-internal hipinfo exclusion

Review follow-up. The amd-smi/DiskPart gate could still reopen in two cases:

- setup.ps1 ran the HIP probe long before $VenvDir is assigned, so without
  VIRTUAL_ENV (the `unsloth studio update` path) $venvRoots was empty and the
  venv-internal hipInfo.exe was not recognized. Seed the venv root from
  UNSLOTH_SETUP_PYTHON and the default Studio home too (both installers).
- The HIP_PATH/ROCM_PATH candidate was accepted without the venv filter, so an
  env var pointing into the venv (AMD wheel) still set $HipSdkInstalled. Run
  Test-HipinfoIsVenvInternal on the candidate as well (both installers).

Extend the PS gate test to assert both. Both .ps1 parse clean; install tests
pass (the venv-internal / HIP probe coverage at 359 passed).

* Windows installer: correct the CPU-base message for arches with no ROCm wheels

After gating the ROCm index on a known arch, a mapped arch sets $ROCmIndexUrl
and installs ROCm directly, so it no longer reaches the "temporary CPU base"
branch. That branch is now reached only by a name-inferred arch with no ROCm
wheels (e.g. RDNA2 gfx103X), where setup.ps1 does NOT install ROCm. The old
text ("setup replaces it with GPU ROCm wheels ... the final install IS
GPU-accelerated") was therefore always wrong there. Say plainly that PyTorch
stays on CPU for this GPU.

* Windows installer: seed the venv-internal hipInfo check from a custom Studio home

Test-HipinfoIsVenvInternal seeded the venv root from VIRTUAL_ENV, VenvDir, the
setup python, and the default %USERPROFILE% path only. A standalone
`unsloth studio update` with a custom UNSLOTH_STUDIO_HOME (or STUDIO_HOME alias)
and none of those set would not recognize the venv hipInfo on PATH, reopening the
amd-smi/DiskPart gate. Seed the custom home too, in both installers, and assert
it in the gate test.

* Studio installer: resolve venv aliases and expand ~ in the hipInfo venv filter

Two review points on the amd-smi/DiskPart UAC gate:

1. _path_inside_venv compared os.path.abspath of sys.prefix and the hipInfo
   path, which does not resolve symlinks, junctions, or 8.3 short names. A venv
   reached through an aliased path then fails the check, so its bundled
   hipInfo.exe is mistaken for an external HIP SDK and amd-smi runs (the
   DiskPart prompt this fix exists to suppress). Switch to os.path.realpath in
   all three copies (amd.py, install_llama_prebuilt.py, install_python_stack.py).

2. setup.ps1's early venv-internal hipInfo probe seeded the venv root from a
   custom Studio home (UNSLOTH_STUDIO_HOME / STUDIO_HOME) without expanding a
   leading ~, while the canonical resolver does. With a tilde form,
   [IO.Path]::GetFullPath kept the literal ~ relative to cwd, so the custom-home
   hipInfo escaped the filter and reopened the gate. Expand ~ in the probe the
   same way as the resolver.

tests/studio/install/test_pr5940_followups.py: 30 passed (adds a symlink
realpath case and a setup.ps1 tilde-expansion guard).

* Studio installer: mirror the hipInfo venv filter and ROCm wheel pins into install.ps1

Follow-up review on the same install.ps1 paths:

1. install.ps1's venv-internal hipInfo probe (Test-HipinfoIsVenvInternal)
   seeded the venv root from a custom Studio home without expanding a leading
   ~, unlike the canonical resolver and setup.ps1. A tilde form left
   [IO.Path]::GetFullPath with the literal ~ (relative to cwd), so the
   custom-home hipInfo escaped the filter and reopened the amd-smi/DiskPart
   gate. Expand ~ in the probe, matching the setup.ps1 fix.

2. The AMD ROCm path installed torchvision/torchaudio bare while pinning torch
   to below 2.12. AMD's per-arch index publishes the companions independently
   and may ship torchvision 0.27 (for torch 2.12) before removing 0.26, so a
   bare resolve can pick an ABI-incompatible set and fall back to CPU. Add
   torchvision/torchaudio floor maps and pass the pinned specs, mirroring
   setup.ps1 and install_python_stack.py.

3. The ROCm-to-CPU fallback torch install used Invoke-InstallCommand (no
   retry), the only torch step in the file without it. Switch to
   Invoke-InstallCommandRetry so the recovery path survives a transient index
   failure.

tests/studio/install/test_pr5940_followups.py: 33 passed (parametrized tilde
check over both installers, a torch/companion floor-map parity test, and a
CPU-fallback retry guard).

* Studio installer: scan all PATH hipinfo so the venv copy can't shadow a real HIP SDK

The amd-smi HIP-SDK probe used shutil.which("hipinfo") / Get-Command hipinfo,
which return only the first hit on PATH. The AMD torch wheel ships hipInfo.exe
inside the venv and the bnb fix (plus the Studio backend) prepend the venv
Scripts dir to PATH, so that venv-internal copy lands first. When a real HIP SDK
hipinfo sits later on PATH with HIP_PATH/ROCM_PATH unset, the first-hit probe
stopped at the venv copy, treated it as "not a HIP SDK", and closed the amd-smi
gate -- AMD users in that PATH-only SDK setup lost amd-smi telemetry and could
fall back to CPU. Scan every PATH entry and keep the first hipinfo that is not
venv-internal; only the venv copy is ignored, so the UAC/DiskPart suppression is
unchanged.

Applied to all three Python copies (install_llama_prebuilt.py,
install_python_stack.py, backend/utils/hardware/amd.py) via a new
_external_hipinfo_on_path helper, and both PowerShell callers (install.ps1,
setup.ps1) now use Get-Command hipinfo -All filtered by Test-HipinfoIsVenvInternal.

tests/studio/install/test_pr5940_followups.py: 36 passed (real-PATH scan tests, a
shadow-regression test for the exact venv-first ordering, and a parity check that
every Python copy uses the scanning helper).

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio uninstallers: fix leftovers (false "removed", shared icon, llama lock)

Auditing a dual native+WSL uninstall on a real device surfaced three leftovers:

1. uninstall.ps1 removed the data dir (which holds unsloth.ico) before the
   shortcuts that reference that icon, so Explorer's icon cache briefly held it
   open. Remove-Item -Recurse reported success yet left the locked file, and the
   dir was never re-attempted, so it orphaned with a false "removed" log.
   _RemovePath now verifies the path is actually gone (retrying transient locks)
   and reports honestly, and the data dir is re-swept after the shortcuts go.

2. install.sh writes a shared unsloth.ico to %LOCALAPPDATA%\Unsloth Studio for
   the WSL shortcut, but uninstall.sh never removed it, orphaning the icon (and
   dir) after a WSL uninstall. uninstall.sh now drops that icon and the dir when
   empty, in both the powershell.exe and drvfs-fallback paths.

3. ~/.unsloth/.llama.cpp.install.lock was never removed, so the rmdir of
   ~/.unsloth failed and the dir lingered. Both uninstallers now remove the lock.

Verified by running both uninstallers on a real dual install: device fully clean
(no install dirs, shortcuts, PATH/registry entries, shared icon, or lock left).

* install.sh: auto-route Strix Halo WSL to an existing Ubuntu 24.04

ROCm-on-WSL is the GPU runtime for Strix Halo and only targets Ubuntu
24.04. When the installer runs in a newer default distro (e.g. 26.04) it
cannot enable the GPU and silently falls back to CPU. If a 24.04 distro
already exists, re-run the install there and stop in the current one so the
GPU path is taken without the user having to know about the distro
requirement.

Runs before venv creation so the wrong distro is left untouched, guards
against re-route loops via UNSLOTH_WSL_REROUTED, leaves a working ROCm
distro alone (librocdxg present), and skips the GGUF-only / opt-out /
non-Strix cases. When no 24.04 distro exists we keep today's behaviour:
continue to CPU and print the `wsl --install Ubuntu-24.04` guidance, never
auto-downloading a distro.

Adds tests/sh/test_strixhalo_wsl_reroute.sh (hermetic: extracts the
function, rewrites its paths to fixtures, mocks wsl.exe) covering the full
decision matrix, wired into tests/run_all.sh.

* uninstall.ps1: keep shared unsloth.ico for a surviving WSL shortcut

A dual native+WSL install shares %LOCALAPPDATA%\Unsloth Studio\unsloth.ico:
install.sh points the WSL shortcut's icon there while the native install owns the
dir. The native uninstaller removed the whole dir unconditionally, so uninstalling
native while keeping WSL left the WSL shortcut with a blank icon. The old code only
avoided this when Explorer happened to hold the icon open, which is unreliable; on a
real dual install the dir was deleted and the WSL shortcut went blank.

_RemoveDataDirKeepingWslIcon now scans the Start Menu + Desktop for a surviving
"Unsloth Studio (WSL ...).lnk" and, if found, removes everything in the data dir
except unsloth.ico (keeping the dir) instead of deleting it; with no WSL shortcut it
removes the dir as before. uninstall.sh still drops the icon and the empty dir when
WSL itself is uninstalled, so every uninstall order ends clean.

Adds tests/studio/test_uninstall_dual_install_icon.ps1 (AST-extracts the helper and
runs it against a temp dir with controlled shortcut dirs) covering the dual,
native-only, empty, and missing-dir cases, wired into the windows-inference smoke
workflow. Verified on a real dual install: native uninstall now keeps unsloth.ico
and the WSL shortcut's icon stays intact.

* installer: condense AMD/ROCm code comments (no behavior change)

Tighten the comments added for the Strix Halo native+WSL installer work so
they are shorter and clearer without losing intent: the venv-internal hipInfo
amd-smi gate, the ROCm torch/companion floor maps, the WSL 24.04 reroute, and
the dual-install uninstall icon handling. Comment-only; code paths unchanged.
107 insertions, 166 deletions across 11 files.

* install.sh: run the Strix Halo WSL reroute before any STUDIO_HOME write

The reroute fired after mkdir -p "$STUDIO_HOME" and the legacy-venv migration,
so rerouting 26.04 -> 24.04 left an empty ~/.unsloth/studio stub in the origin
distro (and ran venv migration in the distro about to be abandoned). Move the
reroute ahead of the venv section so the origin distro is left untouched, matching
the function's own comment. Behavior is identical on every non-reroute path.

* installer: fix ROCm CPU-fallback, hipinfo gate edge cases, uninstall icon, WSL 22.04

- install.ps1: clear $ROCmIndexUrl/$ROCmTorchFloor after the CPU fallback so the
  flavor-repair block does not retry the failed ROCm index and abort the install;
  pin the ROCm companion specs ($visionSpec/$audioSpec) in the repair path too.
- install.ps1 + setup.ps1: skip a bare drive root in Test-HipinfoIsVenvInternal so a
  non-venv UNSLOTH_SETUP_PYTHON does not match the whole drive; iterate
  HIP_PATH/HIP_PATH_57/ROCM_PATH and take the first non-venv hipinfo.
- amd.py, install_llama_prebuilt.py, install_python_stack.py: strip surrounding
  quotes from PATH entries before probing for hipinfo.
- install.sh: pipefail the WSL reroute curl|sh; do not reroute supported Ubuntu 22.04.
- uninstall.sh: keep the shared unsloth.ico while any Unsloth shortcut (native or
  another WSL distro) still references it, in both the powershell and drvfs paths.
- tests: regression coverage for all of the above.

* installer: forward reroute options, guard ROCm bootstrap, harden hipinfo gate

- install.sh: forward the caller's --package/--python/--verbose/--tauri and a custom
  UNSLOTH_STUDIO_HOME into the WSL reroute (was a bare default install); bail on
  --local; run the reroute BEFORE dependency/uv install so the origin distro is left
  untouched; set UNSLOTH_SKIP_ROCM_WSL_SETUP after a failed reroute so the later
  ROCm-on-WSL bootstrap does not install into the unsupported origin distro.
- install.ps1 + setup.ps1: Get-Command hipinfo -CommandType Application so only real
  executables match (not an alias/function named hipinfo).
- uninstall.ps1: guard $env:APPDATA when building the default shortcut search dirs.
- tests: cover option forwarding, --local bail, the bootstrap guard, and the gate change.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* installer: guard origin ROCm bootstrap on every CPU-only fallback; harden ~ expansion

WSL reroute: the no-wsl.exe, no-24.04-target and --local fallbacks all tell the
user the install continues CPU-only, but only the failed-reroute branch set
UNSLOTH_SKIP_ROCM_WSL_SETUP=1. The later _maybe_bootstrap_rocm_wsl gate keys off
that flag, so the other three branches could still install ROCm into the
unsupported origin distro (e.g. 26.04). Set the skip guard on all of them.

Forward UNSLOTH_ROCM_WSL_AUTO into the reroute so a Tauri/consented GPU bootstrap
carries through to the rerouted 24.04 child instead of dropping to the prompt path.

install.ps1/setup.ps1: guard the venv-probe ~ expansion on a non-empty
$env:USERPROFILE so Join-Path does not throw on a profile-less service account.

Tests: add no-wsl.exe and UNSLOTH_ROCM_WSL_AUTO reroute cases, the USERPROFILE
guard assertion, and route shell-test fixtures through a single trap-cleaned root.

* installer: pin + soften Windows ROCm Python repair, reroute to 22.04, harden gates

install_python_stack.py: the Windows AMD ROCm repair in _ensure_rocm_torch()
installed bare torch/torchvision/torchaudio via the fatal pip_install -- the same
asymmetry already fixed on the PowerShell side. A transient repo.amd.com failure
could abort the whole install even after install.ps1/setup.ps1 fell back to CPU.
Pin companions per-arch (gfx120X/Strix -> the rocm7.2 trio, mirroring the PS floor
maps) and make the retry nonfatal: keep the existing build and let the user re-run
update to retry ROCm, so the chain install.ps1 -> setup.ps1 -> stack stays CPU-safe.

install.sh: reroute now targets an installed Ubuntu 24.04 OR 22.04 (24.04 preferred);
both are AMD-supported for ROCm-on-WSL, matching the leave-alone set, so a box with
only 22.04 reaches the GPU instead of staying CPU-only.

install.ps1/setup.ps1: a bare ~ for UNSLOTH_STUDIO_HOME left an empty Join-Path child
(PS 5.1 throws); fall back to USERPROFILE directly and only join a real remainder.

_path_inside_venv (amd.py + both installers): guard a root-dir sys.prefix so commonpath
can't classify every path on the drive as venv-internal (defensive; venv never at root).

uninstall.sh: guard an empty LOCALAPPDATA in the PS-interop icon cleanup (mirror APPDATA).

Tests: add 22.04-target reroute cases, Windows ROCm pin+nonfatal coverage (text +
behavioral), root-dir guard coverage, and bare-~/LOCALAPPDATA guard assertions.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* install.sh: match WSL reroute target by exact distro name, not substring

The 24.04/22.04 reroute target was chosen with grep -F (substring), so a custom
distro such as 'Ubuntu-24.04-test' (with no exact Ubuntu-24.04) was picked as the
target; the later 'wsl -d Ubuntu-24.04' then fails and the Strix Halo install stays
CPU-only. Match whole lines (grep -ixF) and reuse the matched name so only a real
Ubuntu-24.04/22.04 is targeted. Adds substring-rejection + exact-vs-custom tests.

* install.sh: keep the WSL reroute target to Ubuntu 24.04 (helper-supported only)

The ROCm-on-WSL bootstrap (scripts/install_rocm_wsl_strixhalo.sh) dies on any
VERSION_ID other than 24.04 and pins the noble repo, so treating 22.04 as
GPU-supported let the parent report a successful reroute while the child fell
back to CPU. Drop 22.04 from the supported set and the reroute target list;
24.04 stays the sole target (keeping the exact whole-line distro match). An
already-working ROCm on any other version is still left alone by the librocdxg
check above.

tests: reroute 22.04 cases updated to the 24.04-only behavior; make the
"no wsl.exe" case hermetic so a real host wsl.exe can't leak in on dev boxes;
stop the tauri exit-order check from mis-flagging the reroute helper's
[ "$TAURI_MODE" = true ] && ... --tauri one-liner.

* installer: tighten comment wording across the Strix Halo install/uninstall paths

Condense the verbose multi-line comment blocks (amd-smi hipinfo gate, ROCm
torch install + CPU fallback, WSL reroute, uninstall icon-keep) into fewer,
clearer lines. Comments and a few docstrings only; no code, logic, or
behavior change. Verified with bash -n, the PowerShell parser, and ast.parse,
and the installer test suite still passes.

* add AGPL-3.0 SPDX headers to the .sh/.ps1 scripts missing them

Every shell and PowerShell script under the Studio/installer surface now
carries the standard SPDX-License-Identifier: AGPL-3.0-only + copyright
header (after the shebang where present): the installer (install.sh,
install.ps1), build.sh, the .github and src-tauri scripts, the installer
test suite, and the moe kernel test. Header-only, line endings preserved;
bash -n, the PowerShell parser, and the installer tests all pass.

* installer: drop the duplicate AGPL header from install.sh and install.ps1

Both already carry an SPDX-License-Identifier: AGPL-3.0-only header below
their usage comment block; the prior header pass added a second one at the
top because it only scanned the first few lines. Remove the duplicate so each
file keeps a single original header.

* installer: force-reinstall CPU fallback torch; propagate Tauri NEED_SUDO from reroute

install.ps1/setup.ps1: when the AMD ROCm wheel install fails and we fall back to a
CPU base, force-reinstall the torch/vision/audio triplet. A failed ROCm install can
leave an unpinned ROCm torch (e.g. 2.10.0+rocm on gfx110X/gfx90a) that still
satisfies the CPU torch>=2.4,<2.11.0 range, so without --force-reinstall uv keeps the
ROCm build and only swaps the companions -- a mismatched venv the flavor-repair block
won't fix. setup.ps1 scopes the forced reinstall to the ROCm-fallback path
() so the genuine CPU-only install stays fast.

install.sh: the Strix Halo WSL reroute treated every nonzero child exit as a reroute
failure and fell back to CPU. In --tauri mode the child uses exit 2 ([TAURI:NEED_SUDO])
to ask the desktop app to elevate for the target distro; capture the child's exit code
and propagate exit 2 in Tauri mode (the child already printed the NEED_SUDO line)
instead of masking it. CLI mode still falls back to CPU on a generic failure.

Tests: reroute Tauri exit-2 propagation (and non-Tauri CPU-fallback) cases;
run_func now preserves the child exit code; force-reinstall assertions for both
PowerShell installers.

Note: codex's _rr_q apostrophe finding is a false positive -- the helper already
emits POSIX-correct 'O'\''Brien' and round-trips under both sh and bash.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* setup.ps1: fix $cpuForce array collapse in the ROCm->CPU torch fallback

An if-expression assignment ($cpuForce = if ($ROCmCpuFallback) { @("--force-reinstall") })
collapses the single-element array to a scalar string, so @cpuForce splatting enumerated
it character-by-character into broken single-letter args (- - f o r c e ...), which made
uv/pip reject the install and aborted the whole Studio setup on the AMD ROCm->CPU fallback
path. Build $cpuForce as a real array assigned outside the if-expression so the splat passes
a single --force-reinstall arg. Genuine CPU-only installs stay fast (empty array, no flag).
Test now asserts the array-build form and rejects the if-expression form.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* uninstall: remove the isolated Node.js runtime (~/.unsloth/node)

The isolated Node.js runtime (install_node_prebuilt.py, added with the managed-Node
change) installs to ~/.unsloth/node in default mode -- a sibling of studio, so deleting
<studio> leaves it behind (~200MB orphaned after uninstall). Both uninstallers already
remove the other default-mode siblings (llama.cpp/.cache/.staging); add node alongside
them. uninstall.ps1 also adds it to the handle-lock sweep so a held node.exe can't block
the delete. Env/custom mode nests node under the custom root, removed with that root.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2026-06-22 03:09:08 -07:00
Daniel Han
366937de44
studio: pick a macOS llama.cpp prebuilt that loads on the host OS (#5883)
Make macOS llama.cpp prebuilt selection host-OS-version aware: skip a prebuilt whose minimum-OS exceeds the host and walk back to the newest release that loads (macOS 26 keeps latest; 14/15 land on a compatible older release). Source-build fallback pins CMAKE_OSX_DEPLOYMENT_TARGET=13.3. CI: binary-load assertion plus a macos-14/15/26 install matrix. No change to Linux/Windows or CUDA selection.
2026-05-31 00:59:25 -07:00
Daniel Han
54a86c3514
ci: route every hf download through xet-tuned stall-retry wrapper (#5476)
Some checks are pending
Security audit / npm scan-packages (Studio frontend tarballs) (push) Waiting to run
Security audit / workflow-trigger lint (pull_request_target / cache-poisoning) (push) Waiting to run
Security audit / pytest tests/security (push) Waiting to run
Security audit / npm provenance + new install-script diff (push) Waiting to run
Studio API CI / Studio API & Auth Tests (push) Waiting to run
Backend CI / (Python 3.10) (push) Waiting to run
Backend CI / (Python 3.11) (push) Waiting to run
Backend CI / (Python 3.12) (push) Waiting to run
Backend CI / (Python 3.13) (push) Waiting to run
Backend CI / Repo tests (CPU) (push) Waiting to run
Frontend CI / Frontend build + bundle sanity (push) Waiting to run
Studio GGUF CI / OpenAI, Anthropic API tests (push) Waiting to run
Studio GGUF CI / Tool calling Tests (push) Waiting to run
Studio GGUF CI / JSON, images (push) Waiting to run
Mac Studio API CI / Studio API & Auth Tests (push) Waiting to run
Mac Studio GGUF CI / OpenAI, Anthropic API tests (push) Waiting to run
Mac Studio GGUF CI / Tool calling Tests (push) Waiting to run
Mac Studio GGUF CI / JSON, images (push) Waiting to run
Mac Studio UI CI / Chat UI Tests (push) Waiting to run
Mac Studio Update CI / Studio Updating Tests (push) Waiting to run
Studio Tauri CI / Tauri Linux debug build (no codesign) (push) Waiting to run
Studio UI CI / Chat UI Tests (push) Waiting to run
Studio Update CI / Studio Updating Tests (push) Waiting to run
Windows Studio API CI / Studio API & Auth Tests (push) Waiting to run
Windows Studio GGUF CI / OpenAI, Anthropic API tests (push) Waiting to run
Windows Studio GGUF CI / Tool calling Tests (push) Waiting to run
Windows Studio GGUF CI / JSON, images (push) Waiting to run
Windows Studio UI CI / Chat UI Tests (push) Waiting to run
Windows Studio Update CI / Studio Updating Tests (push) Waiting to run
Wheel CI / Wheel build + content sanity + import smoke (push) Waiting to run
Root cause of the Mac json-images 30 min timeout (run 25950714888 /
PR #5430): huggingface_hub>=1.15 deprecated `hf_transfer` and routes
every transfer through `hf-xet`. The CI step's unpinned
`pip install --upgrade huggingface_hub hf_transfer` jumped to 1.15.0
+ hf-xet 1.5.0, the 940 MB mmproj finished in ~21s, then the 3 GB
gemma-4 GGUF made it to ~46% and went completely silent for the
remaining 29 minutes -- no progress bytes, no error, no exit -- until
the job timeout fired.

This wraps every CI `hf download` in a new
`.github/scripts/hf-download-with-retry.sh`:

  * Drops the no-op `HF_HUB_ENABLE_HF_TRANSFER=1` prefix and the
    `hf_transfer` install (both are deprecated on 1.15+ and only
    emit a FutureWarning now).
  * Exports the hf-xet high-performance knobs Daniel asked for:
        HF_XET_HIGH_PERFORMANCE=1
        HF_XET_CHUNK_CACHE_SIZE_BYTES=0
        HF_XET_NUM_CONCURRENT_RANGE_GETS=64
        HF_XET_RECONSTRUCT_WRITE_SEQUENTIALLY=0
        HF_XET_CLIENT_READ_TIMEOUT=500
  * Watchdogs each attempt: if `hf download` has not exited after
    HF_DOWNLOAD_STALL_SECONDS (default 180s = 3 min), SIGTERM,
    sleep 2, SIGKILL, then loop. Retries are unbounded; the
    enclosing job's `timeout-minutes` is the real cap.
  * Optional 3rd positional `LOCAL_DIR` -- omitted lets `hf` use
    the default HF_HUB_CACHE, which is what the HF_HOME-priming
    jobs need.

19 call sites migrated across mlx-ci.yml + 9 studio-*-smoke.yml
workflows. The inline `python -c "from huggingface_hub import
hf_hub_download; ..."` block in mlx-ci.yml is also routed through
the wrapper so every hf transfer in CI gets the same treatment.

Also reverts the json-images timeout 45 -> 30 from #5475: the bump
was masking this hang, not fixing it.
2026-05-15 21:11:56 -07:00