Repository navigation
Studio: find models already on the device before downloading, and make the first download cancellable - #7379
Conversation
…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.
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.
…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.
|
CI triage for the failures seen on the previous run: all five are pre-existing on main and unrelated to this change.
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). |
… 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.
There was a problem hiding this comment.
💡 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), |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
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.
|
@codex review |
There was a problem hiding this comment.
💡 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".
| localCandidate = | ||
| (await resolveLocalRowCandidate(row, null, isSkippedAutoLoadCandidate)) | ||
| ?.candidate ?? null; |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
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:
|
There was a problem hiding this comment.
💡 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".
| ...ggufRepos.map((repo) => ({ | ||
| type: "cached-gguf" as const, | ||
| repo, | ||
| sizeBytes: sizeOrUnknownBytes(repo.size_bytes), |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
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.
…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.
|
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. |
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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".
| function normalizeTarget(value: string): string { | ||
| const target = value.trim().normalize("NFC"); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
# Conflicts: # studio/backend/hub/tests/test_model_services.py
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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"); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
There was a problem hiding this comment.
💡 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; |
There was a problem hiding this comment.
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 👍 / 👎.
| if (abortSignal) { | ||
| const onAbort = () => finish("cancelled"); | ||
| abortSignal.addEventListener("abort", onAbort, { once: true }); |
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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 👍 / 👎.
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: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..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.tsitself. 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.tslistLocalModels(), 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..catch(() => [])wrappers are gone. A failed inventory lookup stops automatic selection instead of pretending the device is empty.AutoLoadSourcelist: 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.chatOnlygate. Read from the boot-detected platform snapshot, so no extra fetch.The last used model can actually be a local one
studio/frontend/src/features/chat/hooks/use-chat-model-runtime.tsstudio/frontend/src/features/chat/utils/last-local-model-load.tslocal) 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..ggufpath 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:/load.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:
It now explains what is happening and what the user can do about it:
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.pyalready runs the real slicedautoLoadSmallestModelunder 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:download.startis ordered beforeloadModel.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 passedpytest tests/studio/test_model_picker_contracts.py: 137 passed, 6 newpytest 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 passednpm run typecheckandnpm run build: cleannpx biome checkon the three changed frontend files adds no new diagnostic categoriesReview 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/localtags every row with a pipeline task, and it only ever sets one for an image or video model (a chat LLM stays null), butcan_chatis 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 taggedtext-to-image,text-to-video, orimage-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 (
passesTaskGatewith 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.jsonplusmodel.safetensors, which_capabilities_for_formatmarks chat-capable on format alone. Since embeddings are small and the cascade tries smallest first, three of them could burnMAX_AUTO_LOAD_ATTEMPTSbefore 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 fromconfig.jsonarchitectures,auto_map,model_type, and the SentenceTransformersmodules.jsonmarker. It fails open, so an unfamiliar architecture is never hidden, and it gates chat only, leavingcan_trainand 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.
requestStartruns transport and status preflights before any job exists, andcancelJobreturns 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.
listCachedGgufandlistCachedModelsare raw fetches with no timeout of their own, so a stall held the model-loading lease after the user stopped the send. Both now takeoptions?.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.
isRememberedSourcelowercased 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 samenormalizeTarget.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_fieldsis the sole producer of a cached row's capabilities and it derivedcan_chatfrom 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 onsnapshot_pathbeing present so a row with nothing to inspect keeps its format capability.A mixed cached repository was attempted twice (correct).
ModelConfig.from_identifier()callsdetect_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:
listGgufVariantsruns throughrunBoundedVariantsRequest, which appliesGGUF_VARIANTS_TIMEOUT_MSwhether 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
isRememberedSourceandautoLoadSourceKeybut leftautoLoadCandidateKeylowercasing its load target, and that key is what marks a candidate tried. On Linux a failed/models/Foo/model.gguftherefore marked a distinct/models/foo/model.ggufas already attempted, which can end the cascade with nothing loaded. All three comparisons now sharenormalizeTarget, with a contract test asserting none of them reintroduces a baretoLowerCase.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
ensureDefaultModelDownloadedpending and the model-loading lease held for the remainder of that window. The lookup now takes the signal. Worth noting the surroundingcatchswallows the abort rejection, so thethrowIfAbortedimmediately 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.
cancelJobcan fail its request, probe the transfer as still running, andpatchJob(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,applyCancelResultcan finalize a cancel attempt ascomplete, 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
CachedGgufRepoandCachedModelRepoboth carrytask, and cached diffusion repos reportcan_chattrue on file format alone.isChattableCachedReponow applies the same exclusion.Two corrections to the review's reasoning here, neither of which changes the outcome. The suggested value
image-to-videois never emitted; the vocabulary istext-to-image,text-to-video, andimage-diffusion-unsupported. And a chat GGUF is taggedtext-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 cachedtext-generationrow still loads.The default download sent an unprepared token.
startJobreads the stored token straight from the shared store and sends it, with none of the anonymous-fallback recoveryvalidateModelandloadModelget. 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.prepareHfTokenForUsenow 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_fieldsclassified onsnapshot_path, but the non-GGUF producer,_scan_cached_models(), passes onlyidentity=identityand leavessnapshot_pathasNone. So the override was alwaysNoneand cached BERT, CLIP, and SentenceTransformers repos stayed chat candidates. The classification now readsidentity.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_pathexplicitly, so it exercised a call shape production never uses and passed against a gate that never ran. The tests now build the same_LoadIdentitythe scanner does, and fail against the previous commit.Whisper was auto-loadable for chat.
WhisperForConditionalGenerationmatches 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.
runsOnThisPlatformappliedchatOnlywithout checkingplatform.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/loadcould 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
ViTModelconfig has no task suffix on its class name, so it missed the non-generative suffix list, andvitwas absent from the encoder model types, leaving the classifier atNoneand 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 (
visibleCachedModelRowsinmodel-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
normalizeTargetfix (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_onlywork 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.