Skip to content

Studio: find models already on the device before downloading, and make the first download cancellable - #7379

Merged
danielhanchen merged 71 commits into
mainfrom
studio-autoload-on-device-only
Aug 7, 2026
Merged

danielhanchen merged 71 commits into
mainfrom
studio-autoload-on-device-only

Conversation

@shimmyshimmer

@shimmyshimmer shimmyshimmer commented Jul 23, 2026 •

Copy link
Copy Markdown
Member

Summary

Fixes #7374.

Pressing Send in a new chat with no model loaded reported "No downloaded models found" and started downloading unsloth/Qwen3.5-4B-MTP-GGUF, even when the user had a perfectly loadable model sitting on disk. Two separate causes:

  1. The auto-load cascade only read the two managed HF cache lists (listCachedGguf / listCachedModels). Models in the models dir, LM Studio folders, and custom scan folders were invisible to it, even though the model picker lists them.
  2. Both of those requests were wrapped in .catch(() => []), so a single failed inventory request read as "this user has nothing" and fell straight through to the download.

This branch has been rebuilt on top of current main. The earlier version of this PR was 3,324 added lines across 24 files and had drifted far enough from main to conflict in 10 files, including chat-adapter.ts itself. The replacement is 863 added lines across 5 files, 407 of which are tests.

What changed

Discovery now sees the whole device, and fails closed

studio/frontend/src/features/chat/api/chat-adapter.ts

  • Auto-load now merges the managed cache lists with listLocalModels(), the same backend-indexed inventory the unified picker reads. A GGUF in the models dir, LM Studio, or a custom scan folder is now a first-class candidate.
  • The .catch(() => []) wrappers are gone. A failed inventory lookup stops automatic selection instead of pretending the device is empty.
  • The remembered-model shortcut and the two separate GGUF/safetensors sweeps have collapsed into one ordered cascade over a single AutoLoadSource list: last used first, then GGUF before safetensors, then smallest first, deduplicated by load target. That is a net reduction in the sweep even before the new behaviour is counted.
  • Local rows follow the picker's own policy (complete, chat-capable, not hidden infrastructure), minus two formats that have to stay an explicit user action: adapters resolve their base model, which is a Hub fetch when the base is not cached, and a scan-folder checkpoint is a pickle with no Hub security scan behind it.
  • Chat-only installs will not auto-pick a format they cannot run. GGUF anywhere, MLX on a Mac, matching the picker's chatOnly gate. Read from the boot-detected platform snapshot, so no extra fetch.
  • Skip keys are now keyed by load target rather than display id, so a cached repo and an indexed local row that alias the same files cannot each burn an attempt on the same broken file.

The last used model can actually be a local one

studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
studio/frontend/src/features/chat/utils/last-local-model-load.ts

  • Backend-indexed local picks (picker source local) are now recorded, so auto-load re-picks the model the user actually ran rather than the smallest one it can find. Native file-picker selections stay excluded, since reaching those depends on a signed expiring path lease that a bare remembered path would bypass.
  • The non-empty GGUF variant requirement is now scoped to cached repo ids. A cached repo holds many quants, so a record without one names no file, but a local .gguf path is the file. The storage key and record shape are unchanged, so existing records keep working.

The empty-device download is now visible and cancellable

An empty device still gets a model, but the transfer no longer happens invisibly inside /api/inference/load. It goes through the Hub download manager, so it is a real job:

  • An entry in the download panel in the bottom right corner, with a progress bar and a working Cancel, exactly like any Hub download.
  • Live byte progress in the toast title, plus a Cancel action on the toast itself wired to the same job.
  • The download keeps running if the user navigates away, and stopping the send stops the wait rather than killing the transfer.
  • The load only happens once the bytes are on disk. A cancelled, failed, or conflicted transfer never reaches /load.
  • If the variant is already on disk from an earlier run, there is no download at all.

Cancelling leaves the user somewhere useful rather than at a dead end: "Pick one from the top bar, or download another from the Hub, then send again."

Friendlier copy, and a new default

The old toast read as a warning about the user's machine and named a raw repo id and quant:

Downloading a small model...
No downloaded models found. Fetching Qwen3.5-4B-MTP (UD-Q4_K_XL).

It now explains what is happening and what the user can do about it:

Getting Gemma 4 E2B ready (1.2 GB of 2.4 GB)
Unsloth couldn't find an existing model. Unsloth is now getting Gemma 4 E2B ready for use. You can stop the download or manage models later in the 'Model hub'

The default model is now unsloth/gemma-4-E2B-it-GGUF (UD-Q4_K_XL), held in three constants with a test asserting no raw repo id or quant is left anywhere on the send path.

Testing

tests/studio/test_chat_autoload_failure_gate.py already runs the real sliced autoLoadSmallestModel under node against a mocked backend, so these are behavioural, not source-text assertions. Its stubs are extended to cover the local inventory, the download manager, and the platform snapshot, and 14 scenarios are added:

  • An indexed local GGUF loads instead of downloading the default, including when the managed cache is empty.
  • Cached and local rows compete in one size-ordered cascade, so the smallest on-device model wins across inventories.
  • Each of the three inventory lookups failing is tested separately, and none of them downloads anything.
  • Rows the picker would hide (can_chat false, partial, adapter, checkpoint, ollama) are never auto-loaded.
  • A remembered local model beats a smaller one.
  • The default fetch goes through the download manager, and download.start is ordered before loadModel.
  • Cancelled, failed, busy, and conflicted transfers all load nothing.
  • Chat-only installs skip a local safetensors row, and a Mac chat-only install still picks up a local MLX model.

17 of the 30 scenarios in that file fail against unmodified main, so they genuinely reproduce the reported bug rather than just describing the fix.

  • pytest tests/studio/test_chat_autoload_failure_gate.py: 30 passed
  • pytest tests/studio/test_model_picker_contracts.py: 137 passed, 6 new
  • pytest tests/studio/: 2,634 passed. The 40 failures are the same ones that fail on clean main (ROCm installer, desktop titlebar), verified by stashing.
  • npm run test: 729 passed
  • npm run typecheck and npm run build: clean
  • npx biome check on the three changed frontend files adds no new diagnostic categories

Review feedback addressed

The automated review flagged six things on this branch. I checked each against the source before acting, and each one is reproduced by a test that fails without the fix.

Image and video rows were auto-loadable for chat. /api/hub/local tags every row with a pipeline task, and it only ever sets one for an image or video model (a chat LLM stays null), but can_chat is derived from file format alone. The chat picker lists those rows and routes them to the Images/Video page on click; a background load has no routing step, so it would load a diffusion model and then send the chat turn to it. The cascade now skips rows tagged text-to-image, text-to-video, or image-diffusion-unsupported.

One correction on the review's wording here: it suggested applying the picker's task gate, but that gate does not exclude these rows in the chat context (passesTaskGate with no filter only hides the never-loadable diffusion tag). The defect is real, the suggested mechanism was not the one that fixes it.

Local embedding models could exhaust the attempt budget. A SentenceTransformers or BERT export is config.json plus model.safetensors, which _capabilities_for_format marks chat-capable on format alone. Since embeddings are small and the cascade tries smallest first, three of them could burn MAX_AUTO_LOAD_ATTEMPTS before a real chat model is reached. This is a regression the local-inventory admission introduces, so it is fixed here rather than deferred: _local_transformers_can_chat() classifies from config.json architectures, auto_map, model_type, and the SentenceTransformers modules.json marker. It fails open, so an unfamiliar architecture is never hidden, and it gates chat only, leaving can_train and LoRA support untouched.

A corrupt quant sank the whole repository. The cascade resolved one candidate per source, so if the smallest downloaded quant failed /load, a valid larger quant beside it was never tried. Each failed quant is now marked tried and the source is revisited, still inside the attempt cap.

Cancel was swallowed during the download preflight. requestStart runs transport and status preflights before any job exists, and cancelJob returns immediately for a missing key, so a Cancel clicked in that window did nothing and the download proceeded. The click is now remembered and replayed once the job appears. It also fires exactly once: cancelling patches the job, which wakes the progress subscription, and the first version of this fix recursed until the stack blew. The behavioural harness caught that, which is why the guard is there.

Cached inventory lookups ignored the run signal. listCachedGguf and listCachedModels are raw fetches with no timeout of their own, so a stall held the model-loading lease after the user stopped the send. Both now take options?.abortSignal. The review also asked for the same on the local inventory; that one already has its own 30 second bound, so it cannot hang, and it is left alone.

Remembered POSIX paths were matched case-insensitively. isRememberedSource lowercased both sides while the dedupe key preserved POSIX case, so on Linux two models differing only by casing both ranked as remembered and the wrong one could win. Both now use the same normalizeTarget.

Six of the eight new scenarios fail against the previous head of this branch, and the classifier tests fail without the backend change.

Second pass over the older open comments

Re-checking the comments left against earlier commits, three still described the current code and two did not.

Cached encoder-only repos were chat-capable (correct). _cache_inventory_fields is the sole producer of a cached row's capabilities and it derived can_chat from file format, so a cached BERT, CLIP, or SentenceTransformers repo was a chat candidate. The classifier above now runs on the cached snapshot as well, gated on snapshot_path being present so a row with nothing to inspect keeps its format capability.

A mixed cached repository was attempted twice (correct). ModelConfig.from_identifier() calls detect_gguf_model_remote() before building a Transformers config, so a repo id whose repo holds any GGUF resolves to GGUF whatever the caller intended. A repo holding both formats produces a row in each cached list, so the safetensors row spent a second attempt on the same files and recorded the wrong kind. Sources now dedupe on the load target alone, and dedupe runs after ordering so the row kept is the one the cascade would have reached first, which is the GGUF row the backend will actually resolve.

Variant scans now take the run signal. They are already bounded by their own timeout, so this is not a hang fix, but a stopped send should not sit through one.

Two did not apply. The unbounded-variant-scan comment is already resolved on main: listGgufVariants runs through runBoundedVariantsRequest, which applies GGUF_VARIANTS_TIMEOUT_MS whether or not a caller signal is passed. The GGUF scan-gate comment described the worker-pool scheduling in the earlier version of this branch, which no longer exists; the cascade resolves one source at a time.

Third pass

Two more comments landed on the previous head. Both were correct.

Tried-candidate keys still folded POSIX case. The remembered-path fix normalized isRememberedSource and autoLoadSourceKey but left autoLoadCandidateKey lowercasing its load target, and that key is what marks a candidate tried. On Linux a failed /models/Foo/model.gguf therefore marked a distinct /models/foo/model.gguf as already attempted, which can end the cascade with nothing loaded. All three comparisons now share normalizeTarget, with a contract test asserting none of them reintroduces a bare toLowerCase.

The default variant lookup ignored the run signal. It is bounded by its own 30 second timeout, so this was never a hang, but stopping Send before the download started left ensureDefaultModelDownloaded pending and the model-loading lease held for the remainder of that window. The lookup now takes the signal. Worth noting the surrounding catch swallows the abort rejection, so the throwIfAborted immediately after it is what actually prevents a download from starting after a stop; there is a test pinning that ordering.

Fourth pass

Three more comments. All three were correct, though one carried a wrong example value.

Cancel was permanently latched off after a failed cancellation. cancelJob can fail its request, probe the transfer as still running, and patchJob(key, {state: "running"}). The sticky flag added in the previous pass then made every later Cancel a no-op. The latch is now in-flight only, cleared when the request settles, and the deferred pending-start attempt fires once rather than on every store tick, so retries come from clicks instead of spinning. Separately, applyCancelResult can finalize a cancel attempt as complete, so a cancelled download could still be handed to a load; the completion listener now resolves cancelled when the user asked to stop, whatever the manager reports.

Cached image and video repos were auto-loadable for chat. The task gate from the previous pass only covered scan-folder rows, but CachedGgufRepo and CachedModelRepo both carry task, and cached diffusion repos report can_chat true on file format alone. isChattableCachedRepo now applies the same exclusion.

Two corrections to the review's reasoning here, neither of which changes the outcome. The suggested value image-to-video is never emitted; the vocabulary is text-to-image, text-to-video, and image-diffusion-unsupported. And a chat GGUF is tagged text-generation, not left null, so the gate has to be a list of image and video tasks rather than "has a task". The earlier comment in the source claiming chat rows stay null was wrong and has been corrected, with a test asserting a cached text-generation row still loads.

The default download sent an unprepared token. startJob reads the stored token straight from the shared store and sends it, with none of the anonymous-fallback recovery validateModel and loadModel get. An empty-device Send could therefore discover the public default anonymously in the variant lookup and then fail its actual download on an expired token. prepareHfTokenForUse now runs before the managed start, and because choosing anonymous clears that same shared store, the download proceeds without the bad token. It runs after the on-disk check, so a default that is already present never prompts, and declining starts no download.

Fifth pass

Three more comments, all correct. The first one caught a fix from the previous pass that did not work at all.

The cached-encoder gate was a no-op in production. _cache_inventory_fields classified on snapshot_path, but the non-GGUF producer, _scan_cached_models(), passes only identity=identity and leaves snapshot_path as None. So the override was always None and cached BERT, CLIP, and SentenceTransformers repos stayed chat candidates. The classification now reads identity.load_snapshot, which is the directory the row actually loads from.

The reason this shipped is worth stating plainly: the test I wrote passed snapshot_path explicitly, so it exercised a call shape production never uses and passed against a gate that never ran. The tests now build the same _LoadIdentity the scanner does, and fail against the previous commit.

Whisper was auto-loadable for chat. WhisperForConditionalGeneration matches the generative suffix list, so the classifier called it chat-capable. The managed cache already hides Whisper snapshots via _is_whisper_model_config, but scan-folder rows had no equivalent, and a Whisper checkpoint is usually smaller than a local chat LLM, so the cascade could load one and stop, leaving the queued text turn to fail on a route that requires audio. A short list of non-chat conditional-generation model types and architectures is now checked before the suffix rule. It covers Whisper, Speech2Text, speech and vision encoder-decoders, and MusicGen, and there are tests asserting T5, BART, and Gemma multimodal are unaffected.

Format gates ran against a browser platform guess. runsOnThisPlatform applied chatOnly without checking platform.fetched. The store's initial state is browser-derived (deviceType="mac", chatOnly=true, fetched=false), so a Mac browser driving a remote Linux Studio would filter out every indexed local safetensors model and fall through to the default download whenever the health probe was slow or failed. The gate now applies only once the platform is server-reported; before that, candidates flow through and an ineligible one is refused at validation without consuming a load attempt.

Sixth pass

Three more comments, all correct.

The default was downloaded before it was validated. Moving the transfer into the download manager put canAutoLoad() after it, so a device that is empty but cannot run the default (active training, or the GPU-memory and placement guard) pulled several gigabytes and only then discovered the refusal. The original flow preflighted before /load could fetch anything. The preflight is back in front of the transfer, and the GPU snapshot is taken once and reused by the load so it sends exactly what was cleared.

Bare vision and audio backbones were chat-capable. A ViTModel config has no task suffix on its class name, so it missed the non-generative suffix list, and vit was absent from the encoder model types, leaving the classifier at None and the format capability intact. Standard vision and audio backbones (ViT, DINOv2, Swin, ConvNeXt, ResNet, Wav2Vec2, WavLM and similar) are now listed, with tests confirming causal and conditional-generation chat models are unaffected.

Cached non-GGUF rows escaped the chat-only gate. The platform gate was applied only to indexed local rows, but the picker hides cached non-GGUF rows outright in chat-only mode (visibleCachedModelRows in model-selector/pickers.tsx). A chat-only device with only a cached safetensors model therefore auto-selected a format the UI treats as unrunnable. Cached model rows now take the same authoritative-platform gate; cached GGUF rows stay ungated since GGUF runs everywhere.

This pass also picks up danielhanchen's normalizeTarget fix (Windows separator spellings keying apart, \\wsl$\ folding case it should keep, and NFC for macOS decomposed names). This branch is rebased on it and its six-case test file passes alongside the rest.

Deliberately left out

The backend local_files_only work from the earlier version of this branch (offline guard, local snapshot resolution, roughly 1,400 lines) is not here. Worth noting that Imagineer99 A/B verified that work on Windows and confirmed it fixed cached offline loading, so it should not be dropped, only moved. It closes a real but different leak, a cached repo whose load fetches missing auxiliaries, and it is worth doing on its own. Folding it into this PR is a large part of what made the previous version hard to review.

…ard-coded default

Fixes #7374. Pressing Send with no model loaded could miss local models
(models dir, LM Studio, custom scan folders, inactive HF caches) and then
download unsloth/Qwen3.5-4B-MTP-GGUF from Hugging Face without consent.

- autoLoadSmallestModel is now autoLoadOnDeviceModel: adopts the server
  active model, then the remembered on-device model, then the smallest
  complete chat-capable on-device model (GGUF first), across managed HF
  caches and the unified backend local inventory.
- Inventory failures fail closed instead of reading as an empty cache.
- The remote Qwen fallback is removed from the send path; with no valid
  candidate the user is asked to select or explicitly download a model.
- last-local-model-load records loadId/inventoryId/source with backward
  compatible v1 parsing; indexed local loads are remembered while native
  path lease picks stay excluded.
- New source-contract tests in tests/studio/test_model_picker_contracts.py.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

shimmyshimmer and others added 3 commits July 23, 2026 16:46
Allows behavioral simulations to drive the real auto-load implementation
directly instead of asserting on source text only. No runtime change.
…ip adapters

Review follow-ups, all verified against the backend inventory services:

- Directory-based local GGUFs (LM Studio, models dir, custom folders) are
  flagged requires_variant by the backend, so the fallback now resolves the
  smallest complete quant through the same variants API the picker card
  uses instead of dropping every directory row.
- A folder holding both GGUF and safetensors weights yields two rows with
  the same load target; remembered-model matching now requires the row
  format to agree with the remembered kind.
- Adapter rows are chat-capable but load by resolving their base model,
  which for a Hub-id base would start an implicit remote fetch; adapters
  are excluded from background auto-load.

Contract tests extended to pin all three behaviors.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…apters

Second round of review follow-ups, verified against the backend services:

- A failed remembered local quant now excludes only that exact candidate
  key instead of marking the whole row seen, so another complete quant in
  the same folder can still load (mirrors the managed-cache remembered
  path).
- Quant resolution for a local GGUF folder scans the folder itself via a
  local-path repo id; the cache-first prefer_local_cache flow could return
  a cache quant missing from the folder when the row also has a Hub
  model_id.
- Cached adapter repos are chat-capable in the cached inventory and
  resolve a base model on load, so they are excluded from background
  auto-load like local adapter rows.

Contract tests extended for all three.
@shimmyshimmer

Copy link
Copy Markdown
Member Author

CI triage for the failures seen on the previous run: all five are pre-existing on main and unrelated to this change.

  • Repo tests (CPU): tests/studio/test_ui_font_scale_contract.py fails on text-[9px] and text-[10px] in features/settings/tabs/voice-tab.tsx, which this PR does not touch; the utilities are already present at the merge base and main's Backend CI is red for the same reason.
  • Chat UI Tests (Mac Studio UI CI): identical failure on main, byte for byte, including the Compare bubble warnings and the TargetClosedError at playwright_extra_ui.py line 548 in the Voice model picker step.
  • Core (all three variants): tests/test_mlx_torch_shim_smoke.py::test_module_children_preserves_direct_child_tree fails identically on main's latest Core run; this PR contains no Python library changes.

Everything exercised by this PR passes: Frontend build + bundle sanity, Source lint, pre-commit.ci, both other Chat UI shards, and the studio contract tests (48 passing, including the new autoload guards).

chatgpt-codex-connector[bot]

This comment was marked as resolved.

… target only

Third round of review follow-ups:

- Quant resolution for a local GGUF folder now returns the smallest quant
  that is not already in the skipped set, so one corrupt or blocked file
  cannot sink a folder that still has other complete quants.
- The cached/local dedupe keys on actual load targets and on-disk paths
  only. A local copy that merely shares a repo model_id is a distinct set
  of files and stays available when the cached copy fails or has no
  usable quant.

Contract tests updated and extended for both.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5aa0183706

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

.map((row) => ({
type: "local" as const,
row,
sizeBytes: sizeOrUnknown(row.size_bytes),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Sort local GGUF folders by resolved quant size

When the fallback contains directory-based GGUF rows, this sorts them by row.size_bytes, but the backend fills that field with the sum of all GGUF files in the folder. For a folder containing a 2GB quant plus an 8GB quant and another folder containing a single 4GB quant, pressing Send auto-loads the 4GB model before the truly smallest 2GB on-device quant, and can even fail VRAM validation on a larger choice while a smaller quant is available. Resolve or carry the smallest complete variant size for requires_variant GGUF rows before ordering the cascade.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed: the backend fills a GGUF folder row's size_bytes with the sum of every quant in the folder, so ordering on it preferred a larger single-quant model over a folder holding a smaller quant. Local candidates are now resolved before the groups are sorted and multi-quant folders order by the resolved quant's own size. Simulated: a folder with 2 GB plus 8 GB quants now wins over a 4 GB single-quant folder and loads the 2 GB quant. Fixed in a928900.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ordering heuristic rather than a correctness bug: no candidate is dropped and every source stays in the cascade. Resolving per-quant size first would mean listing variants for every source, which is exactly what the lazy design avoids.

…dupe keys

Fourth round of review follow-ups:

- Local candidates are now resolved before the fallback groups are sorted,
  and multi-quant GGUF folders order by the resolved quant's own size. The
  backend row size sums every quant in a folder, so a folder holding a
  2 GB and an 8 GB quant previously sorted after a 4 GB single-quant model
  even though its 2 GB quant was the smallest loadable artifact.
- The cached/local dedupe keys now carry the model kind. A folder emitting
  both GGUF and safetensors rows shares one path while holding two
  different models, so a failing GGUF row no longer shadows its loadable
  safetensors sibling.

Contract tests updated and extended for both.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

shimmyshimmer and others added 2 commits July 23, 2026 22:03
Fifth round of review follow-ups. A resolved quant that passed validation
could still fail /api/inference/load (corrupt file, llama.cpp startup
error); the cascade then abandoned the whole row because only validation
blocks recorded a skip key. The fallback now marks the failed quant
skipped and resolves the folder's next complete quant before moving on,
bounded by the existing attempt cap. Single-candidate rows resolve to
null once skipped, so the retry loop terminates.

Contract test and simulation added for the failure-then-retry path.
@shimmyshimmer

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 69c614e2e8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +2298 to +2300
localCandidate =
(await resolveLocalRowCandidate(row, null, isSkippedAutoLoadCandidate))
?.candidate ?? null;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reinsert retry variants into the global size order

When the smallest quant in a local folder fails during /load, this loop immediately resolves and tries every remaining quant from that same folder before returning to the globally sorted candidate list. For example, a folder with failed 1 GB, 100 GB, and 200 GB quants can consume all three load attempts while a valid 2 GB model in another folder is never tried, defeating the smallest-first fallback and producing a false no-model error. The next quant should re-enter the global queue according to its resolved size.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct: the inline retry could burn the whole attempt cap on one folder's large quants while a smaller model elsewhere went untried. A failed quant's folder now resolves its next complete quant and reinserts it into the shared fallback queue at its resolved size, still ahead of the safetensors group, so ordering stays globally smallest-first. Validation blocks get no requeue since those gates are model-scoped, which also avoids per-quant validate spam. Simulated: a folder with failing 1 GB, 100 GB, and 200 GB quants yields exactly two loads, the 1 GB failure and then the 2 GB model from the other folder. Fixed in bc9a5f7.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deliberate and commented: keeping a failed repo's next quant ahead of a smaller different repo is what stops one corrupt file costing the whole repo. Both stay reachable inside the attempt budget.

… scans

Sixth round of review follow-ups:

- Identifier keys (seen set, skip keys, remembered matching) now use
  path-shape-aware case semantics: POSIX paths keep their case since Linux
  distinguishes /models/Foo from /models/foo, while Windows-style paths and
  Hub repo ids stay case-insensitive. Inventory ids compare exactly.
- A quant that fails /load re-enters the shared fallback queue at its
  resolved size (still ahead of the safetensors group) instead of retrying
  the same folder inline, so a folder of failing quants cannot exhaust the
  attempt cap while a smaller model in another folder goes untried.
- Local variant pre-resolution runs with bounded concurrency (4) so a large
  indexed inventory does not fan out a recursive directory scan per folder
  all at once.

Contract tests and simulations updated and extended for all three.
@shimmyshimmer

Copy link
Copy Markdown
Member Author

Updated CI triage after the run on 69c614e completed: 13 of 15 workflows are green, including Core, Frontend CI, Lint, and the full Python suite (2726 passed; the studio contract tests for this PR all pass, and the earlier voice-tab font-scale failure is resolved). Two failures remain, both unrelated to this change:

  • Mac Studio UI CI: the known playwright_extra_ui.py line 548 TargetClosedError that reproduces identically on main.
  • Backend CI, Repo tests (CPU): the tests/sh/test_get_torch_index_url.sh ROCm cases. This PR touches no install or torch-resolution code; the script and install.sh are unchanged since the merge base, and running the harness locally on this branch and on the unmodified merge base commit produces byte-identical results. It was previously masked in CI because the job used to stop at the font-scale pytest failure before reaching the shell harness step. Main's own latest Repo tests run is also red (12 pytest errors), so the branch is currently cleaner than main on this job.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: bc9a5f7f86

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +2225 to +2228
...ggufRepos.map((repo) => ({
type: "cached-gguf" as const,
repo,
sizeBytes: sizeOrUnknownBytes(repo.size_bytes),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Order cached GGUFs by the selected quant's size

When cached and indexed-local GGUFs coexist, this assigns cached repos their row-level size_bytes, which the backend computes across all GGUF variants, while local folders use the resolved quant's individual size. For example, a cached repo containing 2 GB and 100 GB quants sorts behind several 4–6 GB local models; those models can exhaust the three-attempt cap before the loadable 2 GB quant is reached. Resolve cached variants before building the merged queue and order them by the quant that will actually be loaded.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed against the backend: cached-gguf rows compute size_bytes in _repo_gguf_size_bytes as the sum of every downloaded quant blob, so a repo holding a 2 GB and a 100 GB quant sorted as 102 GB and lost to mid-size local models even though only the 2 GB quant would load. Fixed in 4791969: cached GGUF repos now resolve their smallest complete, auto-loadable, not-yet-skipped quant through the same bounded worker pool local rows use and enter the fallback order with that quant's own size. The all-variant row sum now only orders non-GGUF cached repos, whose snapshot loads whole. Covered by the updated resolved-quant-size contract test and a simulation where a 2 GB cached quant beats a 6 GB local file despite the repo's 102 GB row sum.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same ordering trade-off as the local side, and the branch already accepts it for GGUF repos. A real change here needs a backend field for the selected quant size.

Unsloth and others added 4 commits July 26, 2026 00:10
Resolves the chat-api import conflict: keep GenerationLengthError from
main and keep the branch's move of listCachedGguf and listCachedModels
to the unified inventory API.
…incremental resolution

Cached GGUF repos now order by the quant that will actually load instead
of the row size_bytes, which sums every downloaded quant and pushed a
repo holding one small quant behind larger models. Cached entries apply
the same seen gate local rows use and skip keys are scoped to the
backend load target, so a cached repo and an indexed local row aliasing
the same files no longer spend two attempt slots on one failure. The
fallback resolves candidates through the bounded worker pool and
consumes them incrementally from a size-ordered pool after a short
settle grace, so one slow folder scan no longer stalls the send path
behind the transport timeout.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…fetensors on pending GGUF scans

Local rows that resolve without a backend folder scan seed the pool
before the workers start, so they cannot queue behind slow cached scans.
Cached and local folder scans interleave across the bounded workers so a
run of slow scans from one source cannot monopolize them. The consumer
holds model-kind candidates while scan jobs are pending, since every
pending scan can still yield a GGUF that outranks safetensors in the
documented order; resolved GGUF entries keep flowing immediately.
@shimmyshimmer

Copy link
Copy Markdown
Member Author

CI triage for 4791969: the single red job, Repo tests (CPU), fails on tests/studio/test_ui_font_scale_contract.py::test_no_raw_pixel_text_utilities flagging text-[11px] and text-[10px] in features/settings/tabs/agents-tab.tsx. That file landed on main in 0220104 (#7303) after this branch's merge point and the same job fails identically on main's own head d819029, so it is an upstream regression, not something this branch introduced. The 12 test_rocm_rdna_routing setup errors in the same job also reproduce on main. Everything else is green.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 7, 2026
@unslothai unslothai deleted a comment from shimmyshimmer Aug 7, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 325b6f811e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1977 to +1978
function normalizeTarget(value: string): string {
const target = value.trim().normalize("NFC");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve Unicode-distinct POSIX model paths

On Linux and other normalization-sensitive POSIX filesystems, NFC and NFD spellings are distinct filenames, but normalizing every target to NFC makes paths such as /models/café.gguf and /models/café.gguf share one key. orderAutoLoadSources then removes one model before any attempt, and the tried-candidate set can also let a failure of one suppress the other, potentially causing a usable on-device model to be skipped in favor of the default download. Apply Unicode normalization only where the filesystem guarantees those spellings are aliases, or deduplicate using a backend-provided canonical file identity.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The trade-off is deliberate and the current direction is the safer one. NFC is there because macOS returns a decomposed spelling for the same file, so a remembered NFC path would otherwise stop matching the scanned NFD one, which is a guaranteed case rather than a rare one. The Linux case needs two model files in one scan whose names differ only by normalization form, which is not something a real setup produces. Neither proposed remedy is available here either: the frontend cannot tell which filesystem backs a given path, since a Linux backend can mount APFS, NTFS or SMB and a Mac can mount a case-sensitive volume, and a backend-provided canonical identity such as device plus inode is a backend change well outside this PR.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4628feb912

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

// Transformers source, which sends the safetensors context length to /load and
// remembers the wrong kind.
function isGgufLocalRow(row: LocalModelInfo): boolean {
return row.model_format === "gguf" || row.path.toLowerCase().endsWith(".gguf");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Detect legacy GGUF directories before building sources

When an older backend omits model_format for a GGUF directory, its path does not end in .gguf, so this classifies it as a Transformers source even when its ID or display name identifies a GGUF (the picker checks those fields). The backend still auto-detects and successfully loads a GGUF from such a directory, after which loadAutoLoadCandidate takes the non-GGUF state branch, stores the safetensors context length, and remembers the model with kind model; fresh evidence after the earlier direct-file fix is that directory rows remain uncovered. Mirror the picker's ID/display-name fallbacks here.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rejecting this one. The stated basis does not hold: the picker splits local and cached rows on row.modelFormat === "gguf" alone, in use-chat-picker-inventory.ts, with no id or display-name fallback. isGgufId lives in recommended-fit.ts and drives the Recommended list and fit estimation, not row classification, so there is no picker behaviour here to mirror. Adopting the -GGUF name regex would also cut the other way: a safetensors directory named after a GGUF repo would be typed gguf, sent a context length of 0 and given GGUF runtime state, which is the same wrong-kind bug in reverse. Separately, the allowlist in 9396387 now excludes an unclassified non-GGUF directory from a background pick altogether, so a legacy GGUF directory is no longer silently loaded as a Transformers source.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: 93963879bf

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 97169ef71a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

for (const source of sources) {
if (autoLoadCancelled || loadAttempts >= MAX_AUTO_LOAD_ATTEMPTS) break;
const sourceKey = autoLoadSourceKey(source);
if (candidateResolvedFor.has(sourceKey)) continue;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep GGUF and safetensors candidates distinct

When one repository or local directory contains both GGUF and safetensors weights, both sources have the same loadId but are different load requests because only the GGUF candidate supplies gguf_variant. Since GGUF sources sort first and this set is marked as soon as a candidate resolves, a corrupt or validation-rejected GGUF causes the usable safetensors source to be skipped here; the send then reports the GGUF failure instead of trying the on-device Transformers model. Include the format/kind in this deduplication key, while still deduplicating true aliases within a format.

Useful? React with 👍 / 👎.

Comment on lines +2284 to +2286
if (abortSignal) {
const onAbort = () => finish("cancelled");
abortSignal.addEventListener("abort", onAbort, { once: true });

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Dismiss the autoload toast when aborting the wait

When the user presses Stop while the initial managed download is running, this calls finish("cancelled"), which removes the job and store listeners while intentionally leaving the transfer active. The subsequent throwIfAborted() rethrows before either catch reaches toast.dismiss(toastId), so the infinite-duration “Getting … ready” toast remains at stale progress and cannot react when the background transfer completes or is cancelled from the Hub panel. Dismiss this private toast on abort, or retain a terminal listener that settles it.

Useful? React with 👍 / 👎.

// A repo can hold several downloaded quants: each failure marks that
// quant tried and comes back for the next, so one corrupt file does not
// cost the whole repo. The attempt cap bounds the loop.
while (!autoLoadCancelled && loadAttempts < MAX_AUTO_LOAD_ATTEMPTS) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Bound quant retries that fail validation

When a GGUF repo has many downloaded quants and candidates fail before /load—for example because the validation/training-memory preflight rejects them—loadAttempts is never incremented, so this loop ignores MAX_AUTO_LOAD_ATTEMPTS and walks every quant. Each pass also calls resolveAutoLoadCandidate, which reissues the variant lookup before repeating validation; a repo with many quants can therefore hold Send through an unbounded series of metadata and validation requests even though the comment says the attempt cap bounds the loop. Count resolved/preflighted candidates toward a separate cap or stop retrying after a repo-wide refusal.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] No Model Detected Error after Hitting Send

3 participants