Skip to content

Studio: detect local MTP subdirectory drafters - #7385

Merged
danielhanchen merged 17 commits into
mainfrom
agent/fix-local-mtp-drafter-discovery
Jul 29, 2026
Merged

danielhanchen merged 17 commits into
mainfrom
agent/fix-local-mtp-drafter-discovery

Conversation

@shimmyshimmer

@shimmyshimmer shimmyshimmer commented Jul 24, 2026 •

Copy link
Copy Markdown
Member

Summary

  • detect compatible Gemma 4 MTP drafters stored under a local model's MTP/ directory
  • allow native-path MTP drafters in that direct child directory after secure path validation
  • reuse the repository companion root for quant-subdirectory native loads and reload deduplication
  • resolve selected quant directories and direct GGUF files to the same companion root
  • require a model-name boundary so similarly prefixed models cannot cross-pair
  • keep root-level drafter precedence, and fall back to the MTP/ copy when the root drafter is out of bounds for a native grant
  • pair on the module's full quant vocabulary so K, IQ, UD and MXFP drafters match, including sharded files
  • choose the smallest compatible subdirectory copy by real file size, with precision as a tie break
  • require a published drafter name inside MTP/ so a weight copy cannot launch as --model-draft
  • report local model source metadata so direct-file, custom-folder, bare-relative-folder, and native-picker GGUF loads show local placement guidance
  • use the scalable 11px-equivalent UI token for existing settings helper text

Root cause

Direct local GGUF loads only searched for root-level mtp-*.gguf siblings. Valid precision copies in the repository's MTP/ directory were excluded, even though cached offline loads can reuse them.

There was also a second gate for native file selections. It required every GGUF companion to have exactly the same parent as the selected model, so an MTP drafter detected in MTP/ was discarded before launch. Local-path loads do not attempt a companion download, which made the existing download-failure warning misleading.

Quant-subdirectory loads had three related edge cases: native validation rejected a valid repository-root MTP/ directory, reload deduplication originally searched only beside the GGUF, and selecting a quant directory resolved a different companion root than selecting its GGUF file. Filename matching also treated a model name as a raw prefix, which could attach mtp-foo.gguf to foo2-*.gguf.

The frontend could identify syntactically obvious filesystem paths, but it could not safely distinguish a bare relative folder such as outputs/gemma from a repository identifier. The backend already makes that distinction using filesystem existence, so load and status responses now carry the authoritative source classification.

Follow-up fixes

Filename pairing stripped only q<d>_<d>, bf16 and f16, so drafters published as K, IQ, UD or MXFP quants never matched and MTP silently stayed off. Pairing now reuses _GGUF_KNOWN_QUANT_RE and strips the shard suffix first, since it sits outside the quant token.

Subdirectory selection ranked candidates against a fixed precision list that placed unrecognised quants behind BF16, so a small K-quant lost to a much larger BF16 copy. Ordering is now by real file size, with precision breaking ties.

A weight in a quant subdirectory with both a root drafter and an MTP/ copy ended up with no drafter at all: detection preferred the root drafter and native validation then rejected it. The native path now retries the MTP/ copy before dropping MTP.

_is_mtp_drafter accepts everything under MTP/ by design, which keeps those files out of the variant menus but is too broad as an inclusion test, so a weight copy placed there was handed to llama-server as --model-draft. Inclusion now requires mtp-<model> or <model>-MTP.

The status poll cleared activeModelIsLocal while specFallbackReason survived, flipping a local model's warning back to the download-failure text. That branch now leaves the flag alone.

Compatibility and safety

  • root-level drafters still win, with the MTP/ copy used only when the root drafter cannot be reached
  • Hugging Face repository download behavior is unchanged
  • only the model directory or its immediate repository root may own the added MTP/ directory
  • arbitrary nesting and symlink escapes remain rejected
  • vision companion validation keeps its existing same-directory rule
  • existing root-level, remote repository, and baked-in MTP paths are unchanged
  • the new response field is additive and defaults to remote for older or missing metadata

Known limitation

Reload deduplication computes its companion root from the GGUF path while load time computes it from the user's selection. For a weight in a subdirectory whose name does not match the quant pattern, such as DeepSeek-V3-UD-Q2_K_XL, the two disagree and a duplicate /load reloads instead of deduplicating. This predates this branch, which improves the quant directory shape only. Fixing it properly needs the original selection path and is left for a separate change.

Tests

  • focused discovery, native route, path-security, reload-deduplication, frontend source, and font-scale tests
  • 185 passing across the MTP drafter, native companion, model picker, mmproj, GGUF routing, reload inheritance, and native context length suites
  • frontend source contract for local file, folder, bare-relative-folder, and native-picker warning classification
  • scalable-font source contract, frontend typecheck, and production build
  • related MTP, GGUF cache, reload, native-path, vision, GPU-memory, and tensor-parallel tests
  • production UI warning matrix in Chromium, Chrome, Edge, Firefox, and Safari/WebKit
  • repository pre-commit hooks for every changed file

@shimmyshimmer
shimmyshimmer marked this pull request as ready for review July 24, 2026 10:32
@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: 38e3b41c64

ℹ️ 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 +375 to +376
const isDirectLocalGguf =
currentCheckpoint?.toLowerCase().endsWith(".gguf") ?? false;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3 Badge Classify local folder GGUFs as local for warnings

When a local Gemma GGUF is loaded from a directory/custom folder (or from a native picker label that does not end in .gguf), isDirectLocalGguf remains false even though the backend did only local drafter detection. If specFallbackReason === "drafter_not_found", the settings panel then shows the Hugging Face download/network-access warning instead of the new local placement guidance, leaving these local-path users with the wrong recovery action. Consider deriving this from a broader local-GGUF signal rather than only the checkpoint suffix.

Useful? React with 👍 / 👎.

Comment on lines +1523 to +1524
if f.is_file():
subdir_candidates.append(f)

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 MTP subdir drafters for native loads

For native desktop loads (drag/drop or file picker), returning a drafter from MTP/ is still dropped later: routes/inference.py:_validate_native_gguf_companion requires the companion's resolved parent to equal the selected GGUF's parent, and the caller catches that failure by clearing config.gguf_mtp_file. As a result, native users with exactly the new MTP/ layout continue to load without MTP despite this detection succeeding; the native companion validation needs to allow the MTP subdirectory before these paths can be used.

Useful? React with 👍 / 👎.

@shimmyshimmer
shimmyshimmer force-pushed the agent/fix-local-mtp-drafter-discovery branch from 38e3b41 to 8ef7c9c Compare July 24, 2026 11:59

@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: 8ef7c9c345

ℹ️ 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".

if weight_name is None:
return True
stem = _pairing_stem(candidate.name)
return bool(stem) and weight_name.startswith(stem)

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 Require a boundary when matching MTP stems

When a candidate's precision suffix is stripped, this bare prefix check also accepts sibling models whose names merely start with the stripped stem. For example, in a local multi-model directory containing foo2-Q4_0.gguf and only MTP/mtp-foo-Q4_0.gguf, _pairing_stem() returns foo, so the foo drafter is passed as --model-draft for foo2; llama-server can then start with an incompatible drafter or fail instead of falling back to no MTP. Please require a separator/end boundary before treating the drafter as compatible.

Useful? React with 👍 / 👎.

except OSError:
continue
logger.info(f"Detected MTP subdirectory drafter: {resolved}")
return str(resolved)

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 Reuse the companion search root during reload dedup

When this fallback returns a drafter found via search_root (common when the selected GGUF is inside a quant subdirectory and MTP/ is at the repo root), the next identical /load never dedupes: _request_matches_loaded_settings() later calls detect_mtp_file(llama_backend.gguf_path) without that companion root, rediscovers None, and treats the stored MTP path as a mismatch. In that layout every settings apply/reload restarts llama-server even though nothing changed; derive the same search root for the loaded path before comparing.

Useful? React with 👍 / 👎.

gguf_parent = Path(gguf_path).resolve(strict = True).parent
return companion_parent == gguf_parent or bool(
allow_mtp_subdir
and companion_parent.parent == gguf_parent

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 Allow repo-root MTP for native quant-subdir loads

When a native GGUF is selected from a quant subdirectory, from_identifier() can now detect the drafter via search_root in the repository root's MTP/ folder, but this validation only allows MTP/ directly under the selected GGUF's own parent. Fresh evidence is that the new detector documents and returns repository-root MTP/ drafters for quant-subdir weights, so native loads in that supported layout still drop config.gguf_mtp_file and run without MTP.

Useful? React with 👍 / 👎.

@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: af4464a0e0

ℹ️ 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 +3346 to +3349
companion_root = _local_gguf_companion_search_root(
llama_backend.gguf_path, llama_backend.gguf_path
)
detected = detect_mtp_file(llama_backend.gguf_path, search_root = companion_root)

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 the selected companion root during deduplication

When the original model_path is a directory named like a quant (for example /repo/Q4_0), ModelConfig.from_identifier() searches only that selected directory, so /repo/MTP/... is not loaded. This deduplication path instead treats the backend's resolved GGUF file as a direct-file selection, promotes the search root to /repo, and detects that drafter. Every otherwise identical /load is therefore considered different and reloads the model, but the reload again omits the drafter, creating a persistent reload loop. Store/reuse the companion root derived from the original selection, or apply identical root resolution during initial loading and deduplication.

Useful? React with 👍 / 👎.

Comment on lines +398 to +400
(activeNativePathToken != null ||
isLocalModelPath(currentCheckpoint ?? "") ||
(currentCheckpoint?.toLowerCase().endsWith(".gguf") ?? false));

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 Classify existing relative model folders as local

For a GGUF loaded from an existing bare relative directory such as outputs/gemma (which the backend's is_local_path() explicitly accepts), the checkpoint has neither a .gguf suffix nor one of the prefixes recognized by the frontend's isLocalModelPath(). With no native token, isLocalGguf is therefore false and a local drafter_not_found fallback incorrectly tells the user to check Hugging Face access rather than place the companion locally. The classification needs to cover these backend-supported relative folder identifiers or use source metadata from the load response.

Useful? React with 👍 / 👎.

@shimmyshimmer

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 83d496ea48

ℹ️ 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".

Follow-up fixes to the local MTP subdirectory discovery in this PR.

- pair drafters using the module's full quant vocabulary instead of a
  local q<d>_<d>/bf16/f16 subset, so K, IQ, UD and MXFP copies match
- strip the shard suffix before the anchored quant strip, so sharded
  drafters pair instead of falling through
- order subdirectory candidates by real file size, with precision as a
  tie break; the previous fixed list ranked unknown quants behind BF16,
  so a small K-quant lost to a much larger BF16 copy
- fall back to the MTP/ copy on native loads when the preferred root
  drafter sits outside the granted directory, instead of dropping the
  drafter and losing speculative decoding entirely
- require a published drafter name inside MTP/ (mtp-<model> or
  <model>-MTP). _is_mtp_drafter accepts everything in that directory by
  design for variant-menu exclusion, which is too broad to include on: a
  weight copy placed there was launching as --model-draft
- stop clearing activeModelIsLocal when the status poll reports no active
  model. specFallbackReason survives that branch, so clearing local-ness
  alone flipped a local model's warning back to the download-failed text
@shimmyshimmer

Copy link
Copy Markdown
Member Author

Pushed a follow-up commit fixing issues found while reviewing this branch.

Pairing missed most real drafter names

_pairing_stem stripped only q<d>_<d>, bf16 and f16. Subdirectory matching depends entirely on that strip, so any drafter published as a K, IQ, UD or MXFP quant never paired and MTP silently stayed off:

weight  gemma-4-12b-it-Q4_0.gguf
drafter MTP/mtp-gemma-4-12b-it-Q4_K_M.gguf  ->  None

It now reuses _GGUF_KNOWN_QUANT_RE, the vocabulary this module already owns, rather than a hand maintained subset. The shard suffix is stripped first, since it sits outside the quant token and otherwise blocks the anchored strip (mtp-<model>-Q4_0-00001-of-00002.gguf).

"Smallest compatible copy" did not look at size

_precision_rank was a fixed list that ranked every unrecognised quant behind BF16, so a small K-quant lost to a much larger BF16 copy. Candidates are now ordered by real file size, with precision only breaking size ties and the name keeping the pick stable. This preserves the existing Q4_0 over BF16 expectation in test_detect_mtp_file_falls_back_to_new_scheme_subdir, where both stubs are one byte.

Native loads could end up with no drafter at all

With a weight in a quant subdirectory and both a root drafter and an MTP/ copy present, detection returned the root drafter, native validation rejected it as out of bounds, and the drafter was dropped with no fallback. The result was worse than either layout on its own. detect_mtp_file takes a skip_root flag and the native path now retries the MTP/ copy before giving up.

MTP/ contents were trusted wholesale

_is_mtp_drafter returns true for anything under MTP/, which is correct for its real job of keeping those files out of the variant menus, but too broad as an inclusion test. A plain weight copy dropped in MTP/ was being handed to llama-server as --model-draft. Inclusion now requires a published drafter name, mtp-<model> or <model>-MTP, so both schemes still work. _is_mtp_drafter itself is unchanged.

Warning could still flip back to the misleading text

syncInferenceStatusToStore cleared activeModelIsLocal when the status poll reports no active model, but specFallbackReason and the checkpoint deliberately survive that branch. Clearing local-ness on its own flipped the warning back to "could not be downloaded, check your network connection" for a bare relative path model that never touched the network, which is the case this field was added for. Every load path and clearCheckpoint already set the flag, so the branch now leaves it alone.

Deliberately not changed

  • Resolving a quant named directory to its parent is the intended behaviour of this PR, not a regression. A folder named BF16 containing gemma-4-12b-it-BF16.gguf is structurally the same as a repository with a BF16 quant directory, and the drafter it picks up name matches correctly.
  • Allowing <parent>/MTP for a weight in a quant subdirectory widens what one native grant covers, but a repository root and any other parent directory cannot be told apart from the path alone. That is the cost of supporting this layout.
  • The name boundary stays a prefix plus non alphanumeric check. Tightening it would break the shipping case it exists for, where mtp-gemma-4-12B-it.gguf must pair with gemma-4-12B-it-qat-Q4_0.gguf.

Known, left for a separate change

Reload deduplication computes its companion root from the GGUF path while load time computes it from the user's selection. For a weight in a subdirectory whose name does not match the quant pattern, for example DeepSeek-V3-UD-Q2_K_XL, the two disagree and every duplicate /load fully reloads. This predates the branch, which improves the quant directory shape only, and fixing it properly needs the original selection path.

Tests

185 passing across the MTP, native companion, model picker, mmproj, GGUF routing, reload inheritance and native context length suites, plus a clean frontend typecheck and pre-commit on every changed file.

@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: 6690d1b009

ℹ️ 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".

companion_root = _local_gguf_companion_search_root(
llama_backend.gguf_path, llama_backend.gguf_path
)
detected = detect_mtp_file(llama_backend.gguf_path, search_root = companion_root)

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 Apply native fallback when redetecting the drafter

For a native GGUF selected from a quant subdirectory when both a repository-root mtp-*.gguf and a compatible MTP/ copy exist, the initial load rejects the root drafter as outside the lease and deliberately launches the subdirectory fallback. This root-first deduplication scan instead redetects the rejected root drafter, so it never equals the stored subdirectory path and every identical /load unnecessarily restarts llama-server. Fresh evidence in this revision is the new native fallback in _load_model_impl, which changes config.gguf_mtp_file after ordinary detection; mirror that admissibility/fallback choice here.

Useful? React with 👍 / 👎.

Comment on lines +1572 to +1574
for candidate in sorted(subdir_candidates, key = _smallest_first):
try:
resolved = candidate.resolve()

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 Normalize sharded MTP candidates to the first shard

When an MTP/ drafter is split across multiple GGUF shards, this size-based ordering usually selects the smaller final remainder shard rather than 00001-of-N. The new _pairing_stem() explicitly recognizes shard suffixes, but llama-server expects the first shard as its model path (the main-model path already enforces this through _local_gguf_load_path), so an otherwise compatible sharded drafter can fail to load or be treated as incomplete. Group each precision copy's shards and return its first shard before applying the size/precision preference.

Useful? React with 👍 / 👎.

Addresses the two review points that apply to the current revision.

- collapse a split MTP/ drafter to its first shard before ranking, so
  size ordering cannot select a smaller trailing shard. llama-server
  takes shard 1 as the model path, matching _local_gguf_load_path
- align the shard suffix pattern with _GGUF_SPLIT_FILE_RE
- accept the MTP/ fallback during reload deduplication. A native load
  whose root drafter is out of bounds launches the subdir copy, so
  root-first detection never equalled the stored path and that layout
  restarted llama-server on every apply. A deleted drafter still forces
  a reload

The two review points about the companion root during deduplication do
not apply: for a quant named directory the load-time and dedup roots
both resolve to the repository root. The divergence is limited to
subdirectories whose names do not match the quant pattern, which
predates this branch and is noted in the description.
@shimmyshimmer

Copy link
Copy Markdown
Member Author

Went through the review findings and checked each one against the current branch rather than taking them at face value. Two applied and are now fixed, two did not, and the rest were already handled by later commits.

Fixed: sharded MTP copies resolved to the wrong shard

Correct, and this one was introduced by the previous commit. Once shard suffixes were stripped for pairing, a split MTP/ copy produced one candidate per shard, and size ordering then picked the smallest, which is usually the trailing remainder:

MTP/mtp-model-Q4_0-00001-of-00002.gguf   9 MB
MTP/mtp-model-Q4_0-00002-of-00002.gguf   1 MB
picked -> 00002-of-00002

Candidates are now collapsed to their first shard with _local_gguf_load_path before ranking, which is the same helper the main model path uses, then deduplicated. A smaller unsplit copy still wins over a split one, and an incomplete shard set behaves as _local_gguf_load_path already does. The shard pattern also now matches _GGUF_SPLIT_FILE_RE instead of accepting any digit count.

Fixed: native fallback defeated reload deduplication

Also correct, and also a consequence of the previous commit. When a native load rejects the out-of-bounds root drafter and launches the MTP/ copy instead, deduplication re-ran root-first detection, got the root drafter back, and never matched the stored path, so that layout restarted llama-server on every apply.

Deduplication now also accepts the skip_root result as current. A drafter deleted underneath a running server still forces a reload, which is covered by a test.

Does not apply: companion root during deduplication

Both comments on this assume the load-time and deduplication roots disagree for a weight in a quant subdirectory. They do not:

select /repo/Q4_0        -> /repo
gguf   /repo/Q4_0/w.gguf -> /repo

_local_gguf_companion_search_root resolves a quant named directory and a direct file to the same root, which is what this PR changed it to do. The premise that /repo/MTP/... is not loaded for a /repo/Q4_0 selection is not the current behaviour.

There is a real divergence, but only for subdirectories whose names do not match the quant pattern, such as DeepSeek-V3-UD-Q2_K_XL. That predates this branch, needs the original selection path to fix properly, and is already noted in the description.

Already handled by later commits

These were raised against earlier revisions and are fixed on the current head. Verified rather than assumed:

  • boundary when matching MTP stems: foo2-Q4_0.gguf with only MTP/mtp-foo-Q4_0.gguf returns None
  • repo-root MTP/ for native quant-subdir loads: allowed, True
  • MTP subdir drafters preserved for native loads: same-parent and repo-root MTP/ both accepted
  • local folder and bare relative folder GGUFs classified as local: driven by the backend is_local_model flag rather than the checkpoint suffix

CI

The two failures were both from main, not this branch, which was 31 commits behind and touches none of the affected files. test_no_raw_pixel_text_utilities was failing on agents-tab.tsx, fixed upstream by #7462 and #7468, the ROCm gfx* setup errors and the font-scale Playwright flake by #7469, and the bitsandbytes import by #7471. Merged main to pick those up.

Tests

422 passing locally across the MTP drafter, native companion, model picker, UI font scale contract, mmproj, GGUF routing, reload inheritance, and llama.cpp MTP detection suites, plus a clean frontend typecheck and pre-commit on every changed file. Six new tests cover first-shard selection, skip_root, the weight-copy rejection, K-quant pairing, and both deduplication directions. The deduplication test was confirmed to fail without the fix.

@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: bb8ab88f6e

ℹ️ 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 thread studio/backend/routes/inference.py Outdated
Comment on lines +3372 to +3374
fallback = detect_mtp_file(
llama_backend.gguf_path, search_root = companion_root, skip_root = 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 Reload when a preferred root drafter appears

When an ordinary local load initially starts with an MTP/ drafter and a matching root mtp-*.gguf is added later, detected correctly changes to the root file, but this fallback comparison still accepts the stored subdirectory path and deduplicates the request. Consequently the root-first selection that ModelConfig.from_identifier() would make is never applied; restrict this exception to native loads where the detected root candidate is actually outside the lease.

Useful? React with 👍 / 👎.


for candidate in sorted(dict.fromkeys(subdir_candidates), key = _smallest_first):
try:
resolved = candidate.resolve()

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 snapshot symlinks for sharded MTP drafters

For a sharded drafter stored as Hugging Face snapshot symlinks, _local_gguf_load_path() deliberately returns the first shard through its snapshot path so llama-server can find the colocated remaining shards, but resolving it here converts that path to the standalone blob target. The resulting --model-draft path no longer has sibling shard names and the drafter cannot load. Fresh evidence in this revision is that shard 1 is now selected before this subsequent resolve() undoes the helper's symlink-preservation behavior.

Useful? React with 👍 / 👎.

Both review points on the previous revision were correct.

- stop resolving a split MTP/ drafter to its blob target. Snapshot
  symlinks are how HF stores shards, and the blob has no sibling shard
  names, so --model-draft could not load. _local_gguf_load_path already
  preserves the snapshot path; the later resolve() was undoing it.
  Single file drafters still resolve as before
- restrict the reload deduplication fallback to native loads. An
  ordinary local load can reach a root drafter added after the fact and
  must reload to pick it up; only a native load, whose root candidate is
  outside the lease, keeps running the MTP/ copy

Tests cover the snapshot shard path and both deduplication routes.
@shimmyshimmer

Copy link
Copy Markdown
Member Author

Both new review points were correct and are now fixed. Verified each against the running code before changing anything.

Sharded drafters lost their snapshot path

Right, and this was a real break introduced by the first-shard change. _local_gguf_load_path deliberately returns shard 1 on its snapshot path, but the resolve() immediately after it converted that to the blob target:

helper alone    -> snapshots/abc/MTP/mtp-model-Q4_0-00001-of-00002.gguf
detect_mtp_file -> blobs/sha_0
siblings found  -> False

A blob has no sibling shard names, so llama-server could not have loaded the drafter at all. A split copy now keeps the path the helper produced; single file drafters still resolve exactly as before, so the blob comparison in reload deduplication is unaffected.

Deduplication swallowed a newly added root drafter

Also right. Accepting the MTP/ fallback unconditionally meant an ordinary local load that started on the subdir copy would keep it even after a matching root mtp-*.gguf appeared, so the root-first choice was never applied.

The exception is now restricted to native loads. native_grant_backed is already computed at the deduplication call site, so it is passed straight through rather than inferred. Path logic alone cannot separate the two cases: for a weight in a quant subdirectory the root drafter is out of bounds under the native rule either way, so the distinction has to come from the caller.

Behaviour now:

root drafter present native load ordinary load
yes, added after load dedupe, root is out of lease reload, root is usable
no dedupe dedupe

A drafter deleted from underneath a running server still forces a reload on both routes.

Tests

650 passing across the MTP drafter, native companion, model picker, UI font scale contract, mmproj, GGUF routing, reload inheritance, llama.cpp MTP detection, MTP VRAM budget, and GPU memory mode suites. Both new tests were confirmed to fail without their fix. The existing native fallback test now passes the native flag explicitly, since that is the case it describes.

CI

Green on the previous head, 48 passing and 2 skipped. The earlier failures were entirely from main and cleared once it was merged in.

@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: fc90affb29

ℹ️ 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 +1528 to +1530
try:
if f.is_file():
return str(f.resolve())

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 the snapshot path for root-level MTP shards

When a root-level drafter is sharded and represented by Hugging Face snapshot symlinks, this resolves the first shard to its standalone blob path, where llama-server cannot discover the sibling shard names. Fresh evidence in this revision is that _pairing_stem() now makes root-level shard filenames match, while only the later MTP/ branch preserves the snapshot path via _local_gguf_load_path; apply the same shard handling before returning a root candidate.

Useful? React with 👍 / 👎.

Comment thread studio/backend/routes/inference.py Outdated
Comment on lines +3384 to +3385
if stored_resolved is None or fallback_resolved != stored_resolved:
return False

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 Deduplicate native loads after rejecting an inaccessible drafter

For a native GGUF selected inside a quant directory when the repository root contains a matching mtp-*.gguf but no compatible MTP/ copy, the initial load rejects the root drafter as outside the grant and stores no drafter. Every identical /load then reaches this condition with stored_resolved is None and returns false, restarting llama-server even though the reload will reject the same drafter again; compare against the effective admissible native candidate, which is None in this layout.

Useful? React with 👍 / 👎.

lower = f.name.lower()
if not lower.endswith(".gguf"):
continue
if not (lower.startswith("mtp-") or Path(lower).stem.endswith("-mtp")):

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 Recognize sharded old-scheme MTP filenames

When an old-scheme drafter in MTP/ is sharded, its files are named like model-Q8_0-MTP-00001-of-00002.gguf, so the stem does not end in -mtp at this check and every shard is discarded. _pairing_stem() already strips the shard suffix before handling -MTP, but it is never reached for these candidates, causing an otherwise supported sharded drafter to be silently omitted.

Useful? React with 👍 / 👎.

const isLocalGguf =
isGguf &&
(activeModelIsLocal ||
activeNativePathToken != 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 Ignore stale native tokens when classifying a remote GGUF

When another tab or client replaces a native GGUF with a remote Hugging Face GGUF, status reconciliation updates the checkpoint and sets activeModelIsLocal to false, but applyActiveModelStatusToStore() intentionally retains activeNativePathToken for every GGUF status because status responses cannot carry a replacement token. This stale token therefore makes the newly active remote model local here, so a remote drafter_not_found response displays filesystem-placement guidance instead of the download/access recovery text; only use the token when it still belongs to the active checkpoint, or rely on the authoritative backend field after status reconciliation.

Useful? React with 👍 / 👎.

…ison

All four review points on the previous revision were correct.

- share one launch-path helper between the root and MTP/ branches. The
  root branch still resolved to the blob, so a sharded snapshot drafter
  lost its sibling shard names. It began matching once _pairing_stem
  learned shard suffixes, so the two branches had drifted
- strip the shard suffix before the -mtp name check. An old-scheme split
  copy is <model>-Q8_0-MTP-00001-of-00002.gguf, whose stem does not end
  in -mtp, so every shard was discarded
- mirror the load path's admissibility choice during reload dedup for
  native loads instead of special casing a stored None. With a root
  drafter outside the grant and no MTP/ copy the load stores no drafter,
  and dedup compared that None against the root file and reloaded every
  time
- drop activeNativePathToken from the local GGUF classification. Status
  reconciliation keeps the token across a switch to a remote GGUF
  because no replacement token exists, so a stale token labelled that
  remote model local and showed placement guidance instead of the
  download recovery text. activeModelIsLocal is the backend's own
  classification and already covers native picks

The model picker contract now asserts the token is absent rather than
present, since it pinned the stale-token behaviour.
@shimmyshimmer

Copy link
Copy Markdown
Member Author

All four points on the previous revision were correct. Reproduced each against the running code first, then fixed, and each fix has a test that fails without it.

Root branch lost the snapshot path for sharded drafters

Correct, and it was a drift I introduced: the MTP/ branch got shard handling while the root branch kept a plain resolve(). Once _pairing_stem learned shard suffixes, root-level sharded drafters started matching and went straight to the blob:

before  blobs/sha0                                    siblings: False
after   snapshots/abc/mtp-model-Q4_0-00001-of-00002.gguf   siblings: True

Both branches now go through one _drafter_launch_path helper, so they cannot drift again. Single-file drafters still resolve as before.

Old-scheme sharded names were discarded

Also correct. The name check ran on the raw stem, and an old-scheme split copy is model-Q8_0-MTP-00001-of-00002.gguf, whose stem ends in the shard suffix rather than -mtp, so every shard was dropped. The shard suffix now comes off before that check, matching what _pairing_stem already did. Confirmed the whole set was previously returning None.

Native dedup compared against a drafter that never launched

Correct, and it was caused by the stored_resolved is None guard added in the last commit. With a root drafter outside the grant and no MTP/ copy, the load stores no drafter, and dedup then compared None against the root file and restarted llama-server on every apply.

Rather than special casing None, dedup now mirrors the load path: for native loads it walks the same root, then MTP/, then nothing sequence, reusing the real validator through a small predicate so the two cannot disagree on symlink or regular-file rules. Ordinary loads are untouched and still reload when a root drafter appears.

layout, native load stored dedup
root out of grant, MTP/ copy present subdir copy dedupe
root out of grant, no MTP/ copy none dedupe
drafter deleted underneath stale reload

Stale native token classified a remote GGUF as local

Correct. applyActiveModelStatusToStore keeps activeNativePathToken for every GGUF status, since a status response cannot carry a replacement token, so after a switch to a remote Hugging Face GGUF the old token was still present and forced the local branch.

The token is gone from that classification. activeModelIsLocal is the backend's own field and already covers native picks: /status derives it as _native_grant_backed or is_local_path(...), and the load responses use config.is_local, so nothing is lost. The model picker contract asserted the token was present, which pinned exactly this bug, and now asserts it is absent.

Tests

692 passing across the MTP drafter, native companion, model picker, UI font scale, llama.cpp MTP detection, GPU memory mode, MTP VRAM budget, mmproj, GGUF routing, reload inheritance, and native context length suites. Frontend typecheck clean, pre-commit clean on every changed file.

CI

Green on bb8ab88f6, 48 passing and 2 skipped, which cleared the earlier main-side failures. The runs for the two commits since then are still sitting queued on the runners, so I have not seen them go green yet.

@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: e9784fd212

ℹ️ 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 +3122 to +3123
allow_mtp_subdir = allow_mtp_subdir,
mtp_search_root = mtp_search_root,

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 Validate every split-drafter shard under native leases

When a native load discovers a sharded MTP drafter, detect_mtp_file returns shard 1 and llama-server automatically opens its sibling shards, but this validation only checks that launch path. A later shard can therefore be a symlink or otherwise resolve outside the permitted MTP directory without undergoing the regular-file or parent checks, bypassing the native-path boundary this function is intended to enforce; enumerate and validate every expected shard before accepting a split drafter.

Useful? React with 👍 / 👎.

Comment on lines +1580 to +1582
if f.is_file():
# Collapse a split copy to shard 1 before ranking.
subdir_candidates.append(_local_gguf_load_path(f))

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 Reject incomplete split drafter candidates

When an MTP/ download contains shard 1 but is missing any later shard, _local_gguf_load_path still returns shard 1 even though _colocated_first_split_shard reported the set incomplete, and this code adds it as a usable candidate. It can then outrank a complete alternative and make llama-server fail its draft-model startup, causing MTP to be disabled despite a valid drafter being available; only add split candidates after confirming that all declared shards are present.

Useful? React with 👍 / 👎.

# larger BF16. Precision breaks size ties, name keeps it stable.
name = candidate.name.lower()
try:
size = candidate.stat().st_size

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 Rank split drafters by their total shard size

When both split and single-file MTP copies are present, candidates have already been collapsed to shard 1, so this stat() ranks a split model using only its first shard. For example, a two-shard 90+90 byte drafter beats a 100-byte single-file drafter even though it is 180 bytes overall, selecting a larger draft that consumes more memory and can trigger the runtime MTP fallback; sum all shards belonging to a complete split candidate for this ordering.

Useful? React with 👍 / 👎.

if stem.endswith("-mtp"):
stem = stem[: -len("-mtp")]
# Full quant vocabulary, not a subset: K/IQ/UD/MXFP drafters pair too.
return re.sub(rf"-(?:{_GGUF_KNOWN_QUANT_RE.pattern})$", "", stem, flags = re.IGNORECASE)

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 Strip bpw modifiers when pairing MTP copies

When an MTP copy uses a supported bits-per-weight-qualified quant name such as mtp-model-IQ4_XS-3.53bpw.gguf while the main weights use another quant, this anchored substitution cannot remove the quant because -3.53bpw remains at the end. _matches_weight then compares model-iq4_xs-3.53bpw against the main model name and rejects the valid drafter, even though _extract_quant_label explicitly supports these repository filenames; strip the optional bpw modifier together with the quant token.

Useful? React with 👍 / 👎.

Comment thread studio/backend/routes/inference.py Outdated
model_identifier = None if _native_grant_backed else _model_id,
is_vision = llama_backend.is_vision,
is_gguf = True,
is_local_model = _native_grant_backed or bool(_model_id and is_local_path(_model_id)),

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 Persist local provenance instead of rechecking existence

When a model was loaded from a bare relative directory such as outputs/gemma and that directory is later deleted or temporarily unmounted, llama-server can remain active from its open mmap while is_local_path now classifies the identifier as an HF-style org/model because it no longer exists. The next status poll therefore changes is_local_model to false and shows the remote download-failure guidance for a model that was definitively loaded locally; persist the load-time config.is_local value on the backend rather than re-deriving provenance from current filesystem state.

Useful? React with 👍 / 👎.

All five review points on the previous revision were correct.

- pair bpw-qualified drafters such as mtp-model-IQ4_XS-3.53bpw.gguf. The
  anchored quant strip left the modifier behind, so the name never
  matched even though _extract_quant_label supports these filenames
- skip an incomplete split candidate instead of launching shard 1 of a
  set that llama-server cannot start, which also let it outrank a
  complete copy and disable MTP outright
- rank a split copy by its total shard size. Candidates collapse to
  shard 1, so a 90+90 split was beating a 100 byte single file
- validate every shard of a split drafter under a native lease. Sibling
  shards are opened implicitly by llama-server, so checking only the
  launch path let a later shard be a symlink out of the permitted
  directory
- record provenance at load time and report that from status. Deleting
  or unmounting a bare relative model directory underneath a running
  server made is_local_path read the identifier as an org/model repo id
  and flipped a local model to remote

colocated_split_shards is the one place that enumerates a shard set, so
detection, ranking and native validation cannot disagree about it. The
model picker contract now pins the provenance helper rather than the
inline status expression it replaced.
@shimmyshimmer

Copy link
Copy Markdown
Member Author

All five points were correct. Reproduced each before changing anything, and every fix has a test that fails without it.

Pairing dropped bpw-qualified drafters

Confirmed. _extract_quant_label("mtp-model-IQ4_XS-3.53bpw.gguf") returns IQ4_XS-3.53bpw, but the anchored strip in _pairing_stem left -3.53bpw behind, so the name never matched and the drafter was rejected. The strip now takes the optional bpw modifier with the quant token, using the same pattern _extract_quant_label does.

Incomplete split sets were launched

Confirmed, and worse than described: the incomplete set also outranked a complete copy.

MTP/mtp-model-Q4_0-00001-of-00002.gguf   50B, declares 2 shards, ships 1
MTP/mtp-model-BF16.gguf                  100B, complete
picked -> the incomplete Q4_0

llama-server would fail its draft startup there and MTP would be off entirely, despite a usable copy sitting beside it. Incomplete candidates are now skipped in both branches.

Split copies ranked on shard 1 alone

Confirmed. A 90+90 split beat a 100 byte single file, since candidates collapse to shard 1 before ranking. Ranking now sums the whole set.

Native leases validated only the launch path

Confirmed, and this is the one with a real boundary consequence. A symlinked shard 2 beside a regular shard 1 passed validation, and llama-server opens siblings implicitly, so it would have been read. Validation now walks every shard, and the dedup predicate calls the same helper so the two cannot disagree.

Provenance was re-derived per status poll

Confirmed. With the directory gone, is_local_path("outputs/gemma") falls through to the org/model shape check and returns false, so a definitively local model started showing the download-failure guidance mid-session.

Provenance is now recorded at load time next to the existing _native_grant_backed flag and read back from status, with the filesystem check kept as a fallback for a server started before the flag existed.

One thing worth noting

These five all touched shard handling from different angles, and the duplication is what let them drift apart. Enumeration now lives in a single colocated_split_shards, used by detection, ranking and native validation alike.

The model picker contract asserted the old inline status expression, so it was pinning the behaviour being fixed. It now pins the provenance helper instead. The same thing happened last round with activeNativePathToken, so these source-text contracts are worth a look: they lock in the implementation rather than the behaviour.

Tests

737 passing across the MTP drafter, native companion, model picker, UI font scale, llama.cpp MTP detection, GPU memory mode, MTP VRAM budget, mmproj, GGUF routing, reload inheritance, native context length, and TP vision suites. Frontend typecheck and pre-commit clean.

CI

Green on e9784fd21, 48 passing and 2 skipped.

@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: 2d1e2cc180

ℹ️ 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 thread studio/backend/routes/inference.py Outdated
Comment on lines +4512 to +4513
is_local_model = native_grant_backed
or is_local_path(llama_backend.model_identifier),

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 Reuse persisted provenance in already-loaded response

When a GGUF loaded from a bare relative directory such as outputs/gemma has a variant and that directory is later deleted or temporarily unmounted while llama-server remains active, an identical /load can deduplicate here but is_local_path() now interprets the missing path as an HF identifier. The response consequently resets activeModelIsLocal to false and shows the remote download/access recovery text. Fresh evidence beyond the prior status-poll issue is that this revision persists _is_local_model and uses _loaded_is_local_model() in get_status, while this newly changed already_loaded response still bypasses that persisted provenance.

Useful? React with 👍 / 👎.

isGguf &&
(activeModelIsLocal ||
isLocalModelPath(currentCheckpoint ?? "") ||
(currentCheckpoint?.toLowerCase().endsWith(".gguf") ?? false));

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 Do not classify repository IDs by .gguf suffix

For a remote Hugging Face repository whose identifier ends in .gguf, such as org/name.gguf, this suffix check overrides activeModelIsLocal: false and classifies the model as local. The backend explicitly treats a one-slash org/name.gguf as a repository rather than a direct GGUF file (utils/security/consent.py:108-112), so if that repository loads a GGUF variant and reports drafter_not_found, the UI incorrectly recommends placing a filesystem companion instead of checking download or repository access; use the backend provenance for this ambiguous identifier shape.

Useful? React with 👍 / 👎.

Both review points on the previous revision were correct.

- the already_loaded GGUF response still derived provenance from the
  filesystem, so a deduplicated /load flipped a local model to remote
  once its directory went away, the same flip already fixed for the
  status poll. It now reads the persisted value
- drop the .gguf suffix from the local classification in the settings
  sheet. A one-slash org/name.gguf is a repository id, not a file, as
  _is_direct_gguf_file_ref documents, so that suffix overrode the
  backend saying remote and offered filesystem placement guidance for a
  model that downloads

The contract now pins both GGUF responses using the provenance helper,
and pins the suffix out of the classification.
@shimmyshimmer

Copy link
Copy Markdown
Member Author

Both points were correct and are fixed.

The dedup reply bypassed the persisted provenance

Right, and it is the same flip as the status poll, just on the other response. The already_loaded GGUF path still called is_local_path(llama_backend.model_identifier), so once a bare relative directory went away underneath a running server, a deduplicated /load reported the model as remote and the sheet offered download recovery for something that never downloaded. It now reads the value recorded at load time.

The non-GGUF already_loaded reply is deliberately left alone: the flag is recorded on the llama.cpp backend during a GGUF load, and that path holds a different backend object, so it keeps the existing derivation.

The .gguf suffix classified repository ids as local

Also right. _is_direct_gguf_file_ref documents that a one-slash org/name.gguf is a repository id that can still ship safetensors, and the shape confirms it:

org/name.gguf           direct_file=False  is_local_path=False
org/repo/sub/file.gguf  direct_file=True   is_local_path=False

So the suffix check was overriding a backend that had correctly said remote. The term is gone. It was a leftover from before the backend field existed, and everything it covered is now covered properly: a direct local file reports config.is_local, and path-shaped identifiers still go through isLocalModelPath. The classification is down to backend provenance plus a syntactic path check.

On the contract tests

That is the third revision running where a source-text contract had to be edited alongside a real fix, having pinned the exact expression being corrected. This time the assertions were written the other way around, stating what must not decide the classification rather than what must appear, and both were confirmed to fail against the previous code. They are still greps over source text, so they cannot catch a behavioural regression that keeps the same spelling. Worth considering whether this file earns its keep in its current form.

Tests

737 passing across the MTP drafter, native companion, model picker, UI font scale, llama.cpp MTP detection, GPU memory mode, MTP VRAM budget, mmproj, GGUF routing, reload inheritance, native context length, and TP vision suites. Frontend typecheck and pre-commit clean.

CI

Green on e9784fd21, 48 passing and 2 skipped. The run for 2d1e2cc18 was still queued when this went up, with nothing failing in what had started.

@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: 1f7adc6c5f

ℹ️ 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".

search_dir = gguf_path.parent if selected.suffix.lower() == ".gguf" else selected
if not search_dir.name:
return str(search_dir)
if re.fullmatch(quant_dir_re, search_dir.name, re.IGNORECASE):

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 Recognize bpw-qualified quant directories

When the selected GGUF is under a quant directory such as IQ4_XS-3.53bpw, this fullmatch rejects the directory name because quant_dir_re lacks the optional bpw modifier already supported by _extract_quant_label and MTP stem pairing. The search root therefore remains inside the quant directory, so the new repository-root MTP/ discovery, native fallback, and reload deduplication never see /repo/MTP; accept the bpw suffix when promoting quant directories to their parent.

Useful? React with 👍 / 👎.

The review point was correct. _local_gguf_companion_search_root carried
its own copy of the quant pattern, which never gained the bpw modifier,
so a directory such as IQ4_XS-3.53bpw was not recognised as a quant dir.
The search root stayed inside it and the repository-root MTP/ copy was
out of scope for discovery, the native fallback and reload dedup alike.

It now builds on _GGUF_KNOWN_QUANT_RE plus the optional bpw suffix, so
there is a single vocabulary rather than a duplicate that can fall
behind again. Promotion is unchanged for every previously matching name
and still rejects DeepSeek-V3-UD-Q2_K_XL, Q4_0-extra and Q4_0bpw.
@shimmyshimmer

Copy link
Copy Markdown
Member Author

Correct, and it is the same gap as the pairing fix in the previous revision, one layer down.

_local_gguf_companion_search_root carried its own copy of the quant pattern. When bpw support was added to _pairing_stem, that copy never got it, so the directory was not recognised as a quant dir at all:

IQ4_XS-3.53bpw  ->  root stayed inside the quant dir
drafter         ->  None, with /repo/MTP/mtp-model.gguf sitting right there

Discovery, the native fallback and reload deduplication all take their root from that function, so none of them could see the repository-root MTP/ copy.

Rather than adding the modifier to the duplicate, the function now builds on _GGUF_KNOWN_QUANT_RE plus the optional bpw suffix. The duplicate vocabulary is what allowed the drift, and this was the second time it bit: _pairing_stem had the same hand-maintained subset problem earlier in this branch.

Promotion is unchanged for everything that matched before, verified across Q4_0, Q4_K_M, UD-Q4_K_XL, IQ4_XS, MXFP4, TQ1_0, BF16, F16, F32 and lowercase spellings, and still correctly declines DeepSeek-V3-UD-Q2_K_XL, Q4_0-extra, Q4_0bpw and gemma-BF16. Both directions are now pinned by tests, and the promotion test was confirmed to fail without the change.

Tests

743 passing across the MTP drafter, native companion, model picker, UI font scale, llama.cpp MTP detection, GPU memory mode, MTP VRAM budget, mmproj, GGUF routing, reload inheritance, native context length, TP vision, and quant resolution suites. Pre-commit clean.

CI

No failures on any revision. e9784fd21 completed green at 48 passing and 2 skipped; the runs for the revisions since have been superseded or are still queued on the runners.

@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: 05932db5ec

ℹ️ 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 +401 to +402
const isLocalGguf =
isGguf && (activeModelIsLocal || isLocalModelPath(currentCheckpoint ?? ""));

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 Reset local provenance when selecting another checkpoint

When a local GGUF with drafter_not_found is followed by selecting a remote GGUF, setCheckpoint() changes the checkpoint but does not clear activeModelIsLocal, and the no-active-model reconciliation branch explicitly preserves both this flag and specFallbackReason. If the remote load fails, this expression therefore continues classifying the selected remote model as local indefinitely and shows filesystem-placement guidance instead of the download/access recovery text. Clear or associate the provenance flag with the checkpoint when the selection changes.

Useful? React with 👍 / 👎.

Comment thread studio/backend/routes/inference.py Outdated
Comment on lines +4782 to +4787
fallback = detect_mtp_file(
config.gguf_file,
search_root = mtp_search_root,
skip_root = True,
)
except HTTPException as exc:
logger.warning("Dropping MTP drafter for native load: %s", exc.detail)
config.gguf_mtp_file = None
if fallback and _mtp_allowed(fallback):

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 Continue past rejected MTP subdirectory candidates

When MTP/ contains multiple compatible copies and the size-preferred one resolves outside the native grant (for example, a small snapshot symlink plus a larger regular local copy), detect_mtp_file(..., skip_root=True) returns only that first candidate. After _mtp_allowed() rejects it here, the valid remaining candidate is never considered and MTP is disabled; the same selection also causes repeated reload mismatches during deduplication. Iterate candidates until one passes native validation rather than treating rejection of the first result as exhaustion.

Useful? React with 👍 / 👎.

Both review points were correct.

- detect_mtp_file takes an optional accept callback, so a caller with
  extra rules keeps scanning its candidates in preference order. A
  native load whose size-preferred MTP/ copy resolved out of the grant
  was treating that rejection as exhaustion and disabling MTP, even with
  a valid copy beside it. Both the load path and reload dedup now pass
  their admissibility check straight in, which also removes the manual
  two-step retry
- clear activeModelIsLocal and specFallbackReason in setCheckpoint when
  the checkpoint really changes. Both describe the model being replaced,
  so a selection change was classifying the newly chosen model by the
  previous one's provenance. They are cleared together: dropping one
  alone pairs a stale reason with the wrong recovery text, which is the
  flip fixed earlier for the no-active-model branch. The load or status
  response reseeds both.
@shimmyshimmer

Copy link
Copy Markdown
Member Author

Both points were correct and are fixed.

First rejection was treated as exhaustion

Confirmed with a repository holding two compatible copies, the smaller one a symlink pointing out of the tree:

MTP/mtp-model-Q4_0.gguf   symlink -> ../outside/blob.gguf   preferred by size, rejected
MTP/mtp-model-Q8_0.gguf   5000B regular file                valid, never considered
result: MTP disabled

detect_mtp_file now takes an optional accept callback and applies it to candidates in preference order, in both the root and MTP/ branches. The load path and reload deduplication pass their existing admissibility check straight in, which also removes the manual two-step retry each of them was carrying. Same layout now selects the Q8_0 copy, and still returns nothing when no candidate passes.

Provenance outlived the model it described

Also correct. setCheckpoint tracked checkpointChanged for contextUsage but left activeModelIsLocal and specFallbackReason alone, so selecting a remote GGUF after a local one with drafter_not_found kept classifying the new selection by the old model's provenance.

Both are cleared together on a real change. Clearing only the flag would pair a stale reason with the wrong recovery text, which is exactly the flip fixed earlier in the no-active-model branch, and that branch is deliberately left as is: the checkpoint is unchanged there, so both fields still describe the current model. The load or status response reseeds them either way.

Note on the callback

This replaces the pattern where a caller ran detection, checked the result, then re-ran detection with skip_root and checked again. That shape is what made the single-candidate assumption invisible, since neither call site could see how many candidates existed. Preference order now lives in one place and callers only supply the rule.

Tests

745 passing across the MTP drafter, native companion, model picker, UI font scale, llama.cpp MTP detection, GPU memory mode, MTP VRAM budget, mmproj, GGUF routing, reload inheritance, native context length, TP vision, and quant resolution suites. Frontend typecheck and pre-commit clean. All three new tests were confirmed to fail against the previous revision.

CI

No failures on any revision. e9784fd21 completed green at 48 passing and 2 skipped; the runs since have been superseded by the next push or are still queued.

…rafter-discovery

# Conflicts:
#	studio/frontend/src/features/chat/stores/chat-runtime-store.ts
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@shimmyshimmer

Copy link
Copy Markdown
Member Author

No new review points this round. Two CI failures appeared on 05932db5e, so here is what they were.

Source lint: not this branch's code

The blocker was HOISTED-IMPORT-UNUSED 'get_vulkan_inference_gpu_info' in studio/backend/utils/hardware/__init__.py. Every file this branch touches was reported CLEAN, including model_config.py and native_path_leases.py.

That file is not in the diff, and the commit that added the import, #7476, was not even an ancestor of the branch head. It arrived through the merge ref while the branch sat 22 commits behind main, so the verifier compared main's newer code against the older merge base and attributed main's own re-export to this PR. The workflow comment at lint-ci.yml describes exactly this time-reversed comparison as the thing the merge-base diff is meant to avoid, so the remaining gap is the merge ref rather than the two-dot diff.

Merging main fixes the attribution. Against the new merge base the changed-file list is only this branch's own files:

studio/backend/{models,routes}/inference.py
studio/backend/utils/models/model_config.py
studio/backend/utils/native_path_leases.py
studio/backend/tests/test_mtp_drafter_companion.py
tests/studio/test_model_picker_contracts.py
studio/frontend/src/features/chat/*

I also ran the verifier locally the way CI does, comparing each changed Python file against the merge base: OVERALL: PASS (no blockers), and --self-test all pass.

connection (opencode): third party, not the diff

connection (opencode) failed after roughly 23 minutes against a 600 second agent invoke timeout. The five sibling connectors on the same run, claude, codex, hermes, openclaw and pi, all passed. This branch changes MTP drafter discovery and local provenance reporting, nothing in the agent connector path, and there is no plausible mechanism by which it would break one connector while five others succeed. That job only runs on pull requests, so there is no main baseline to compare against. The fresh run should re-test it.

Merge conflict

Main and this branch both edited the setCheckpoint return. Main added the Deep Research reset for external providers, this branch added the provenance reset on a real checkpoint change. They are independent, so both are kept.

Tests

752 passing across the MTP drafter, native companion, model picker, UI font scale, llama.cpp MTP detection, GPU memory mode, MTP VRAM budget, mmproj, GGUF routing, reload inheritance, native context length, TP vision, and quant resolution suites, after the merge. Frontend typecheck and pre-commit clean.

@shimmyshimmer

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 2698f09eb5

ℹ️ 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".

Two conflicts, both additive on the same lines:

- routes/inference.py: main added requested_parallel_slots to
  _request_matches_loaded_settings, this branch added
  native_grant_backed. Keep both on the signature and at the single
  call site.
- chat-runtime-store.ts: main added contextUsageByThreadId to the
  setCheckpoint reset, this branch added activeModelIsLocal and
  specFallbackReason. Union the reset.
@danielhanchen
danielhanchen merged commit bc702f7 into main Jul 29, 2026
52 of 53 checks passed
@danielhanchen
danielhanchen deleted the agent/fix-local-mtp-drafter-discovery branch July 29, 2026 15:14
danielhanchen added a commit that referenced this pull request Jul 30, 2026
* Read the backend source as utf-8 in the model-picker contract test

_read_backend landed in #7385 without an encoding, so it falls back to the
platform default and breaks on Windows the moment a backend file it reads gains
a non-ASCII byte. tests/test_source_read_encoding.py guards exactly this and is
currently failing on main, which turns Repo tests (CPU) red on every open PR
whose CI runs the merge commit.

The sibling _read helper directly above already passes encoding = "utf-8".

* Strip colour from the unsloth_cli CLI test output

Three test_start.py cases assert on plain substrings of result.output, e.g.
"Invalid value for '--gpu-memory-mode'". Typer renders parameter errors through
Rich, which emits ANSI escapes as soon as FORCE_COLOR is set, so the substring is
split across escape sequences and the assertion fails even though the message is
present. They pass locally and fail in CI purely because the runner exports
FORCE_COLOR; click, typer and rich are the same versions in both.

Setting NO_COLOR alone does not help, FORCE_COLOR still wins, so the autouse
fixture removes FORCE_COLOR and CLICOLOR_FORCE as well.

#7598 only recently started running unsloth_cli/tests in Backend CI, which is why
this surfaced now. Verified: the whole suite is 748 passed with and without
FORCE_COLOR=1.
danielhanchen added a commit that referenced this pull request Aug 3, 2026
* fix(studio): refresh token count after model load and thread switch (#7450)

Add a chat count_tokens API and call it from the frontend when a local
GGUF model finishes loading or when a thread is opened, so the context
usage bar reflects the current conversation without waiting for another
message.

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

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

* fix(studio): address Codex review on token count refresh (#7450)

Defer post-load recount until modelLoading clears, restore saved usage
while recount runs, walk the active parentId branch, read incognito
messages from the live thread, guard on activeThreadId, and include
local tool/RAG options in count_tokens so the bar matches chat sends.

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

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

* Add Playwright E2E for token bar after model switch (#7450)

- Add @playwright/test harness with auth injection and model-picker helpers
- Cover token bar visibility on load and after unload/reload without resending
- Fix isInferenceLoaded to treat empty loaded[] as unloaded (Boolean([]) bug)
- Restore saved context usage before background recount in refreshContextUsage
- Add data-testid hooks on context bar and model selector

* fix(ci): pin fsevents override and refresh fastapi scan baseline

- Override fsevents to 2.3.3 so @playwright/test does not introduce a new
  install-script dependency ([email protected]) blocked by security-audit CI
- Update scan_packages_baseline for fastapi routing.py line shift in resolved
  studio deps (C2 polling false positive)

* fix(ci): unblock Repo tests after main merge

Replace raw px text utilities in agents-tab with scaled text-ui tokens
so test_ui_font_scale_contract passes. Stub bitsandbytes in the ROCm
routing test child process so unsloth_zoo can import under the HIP
torch spoof on CPU-only CI.

* Fix branch selection in the context-usage recount for PR #7453

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

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

* Recount the displayed branch and make the E2E unload real for PR #7453

Post-model-load recounts now follow the branch the runtime is showing, so
stepping back to an earlier retry sibling and switching models no longer
counts the newest stored sibling instead. The history adapter's own recount
still mirrors the import head reset.

The E2E unload helper sent an empty body, which UnloadRequest rejects with a
422, so no model was ever unloaded and the model-switch spec never exercised
a switch. It now resolves the loaded model from /api/inference/status and
asserts the unload succeeded. ensureLocalModelLoaded also stopped waiting out
the 180s count_tokens response timeout on a brand-new chat, which never
issues that request.

* Refuse token recounts for image threads in PR #7453

llama-server's /apply-template replaces every image_url part with a short
media marker and discards the decoded bytes, so tokenizing the rendered prompt
misses the whole image embedding and the context bar would claim an
image-heavy conversation still fits. Refuse the recount for those payloads
instead, which leaves the caller on the usage it already had, and refuse
before the auto-switch so a count never moves the loaded model.

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

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

* Keep recounts off the model-switch path and fix the E2E token gate for PR #7453

The recount has no abort signal, so a count still naming the model that was
loaded when it started could reach the backend after the user picked another
one and, with OpenAI auto-switch on, drag the loaded model back. Drop the
auto-switch from /chat/count_tokens: model there is informational and the
active model is what gets counted.

Scope the saved-usage fallback to the branch being counted, so a thread with a
regeneration no longer leaves a sibling branch's usage on the bar when the
recount does not land.

issue-tokens.py minted a plain token, but ensure_default_admin seeds the
account with must_change_password and every protected route answers 403 for a
token without the desktop claim, so the Playwright suite could not reach the
backend at all on a fresh install.

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

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

* Count the Canvas instruction and close the recount usage-snapshot window for PR #7453

Canvas appends a system instruction to the real request, and the recount
already declares the matching render_html tool, so it has to count that
instruction too or every Canvas conversation reads short after a model load.
The instruction text and the system-message folding now live in one helper the
generation path and the recount share.

The stale-recount guard sampled contextUsage after the outbound payload and
tool-extras builds, both of which await storage and the project/RAG lookups. A
completion landing in that window was captured by the snapshot itself, so the
equality check passed and the stale count overwrote its exact usage. Sample as
soon as the message list is fixed instead.

* Decline recounts for audio turns and fix the second E2E token minter for PR #7453

toOpenAIMessages has no audio branch, so a stored user turn whose attachment
the real request replays as audio_base64 would be counted as a text-only
prompt and overwrite the bar with an undercount. Decline the recount there,
matching what the endpoint already does for images.

e2e_count_tokens_api.py minted a plain access token like the Playwright issuer
did, so on a fresh database the bootstrap password gate answered 403 for every
protected call the script makes.

* Count the configured prompt in a brand-new chat for PR #7453

A chat with no persisted thread short-circuited to zero, but a configured
system prompt, project instructions or enabled tools are already part of the
next request, so the bar read 0 / context until the first completion. Build and
count that payload instead, keeping the immediate zero as the placeholder so a
failed count still leaves a number on the bar, and fall back to zero only when
the payload really is empty.

The completion guard now compares the captured thread against activeThreadId
even when it is null, so a count started on an unsaved chat cannot land on a
thread the user opened while it was in flight.

* Count tool-only prompts for empty chats in PR #7453

An empty transcript with Search, Code, Canvas, Docs or MCP enabled skipped the
count endpoint on the empty message list and wrote zero, even though the tool
schemas and the backend's tool/RAG nudge are prompt tokens the next request
pays for. Count whenever the tool extras contribute; buildLocalTokenCountExtras
returns an empty object when nothing is enabled, which is the only genuinely
zero case.

* Clean tool history before counting and scope the runtime getter for PR #7453

The GGUF and Anthropic tool paths strip stale tool-call markup out of replayed
assistant turns before rendering the prompt; the count path did not, so it
priced text the next completion removes. Apply the same gated strip there.

The runtime message getter is one module-level slot that every provider writes,
so in compare mode an unmounting pane cleared the survivor's registration.
Registration now hands back an owner-scoped disposer, and the incognito read
only trusts the slot for the active thread.

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

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

* Match the completion prompt shape in token recounts for PR #7453

Four alignments between the recount and the request it is predicting:

Auto-Heal off leaves leaked tool markup in the real prompt, so the count now
takes auto_heal_tool_calls from the client instead of forcing the strip on.

System and developer turns are collapsed into one leading system message, the
same normalization the completion path applies, so a runtime system turn plus
the configured prompt renders identically.

The endpoint is called even for an otherwise empty payload: the template has
tokens of its own, and a process-level policy (unsloth run --enable-tools) can
inject tool schemas the client cannot see.

The runtime message getter is a stack rather than a slot, so unmounting one
compare pane uncovers the provider underneath instead of leaving none.

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

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

* Guard the token recount against retrieval and tokenizer drift for PR #7453

Decline the recount for a pending turn that the next generation would
answer with retrieved documents: with search_knowledge_base selected and
a thread ending in an unanswered user turn (or a tool result an
interrupted loop never answered), the tool loop splices in whatever
build_rag_autoinject retrieves before the first render, which the count
never sees. build_rag_autoinject's entry gate moves into
rag_autoinject_permitted so the decline cannot drift from the retrieval
it stands in for.

Return the tokenizer identity with the count. The endpoint counts
against whatever is loaded now, so another API client's auto-switch is
invisible to a caller that only checks its own captured checkpoint.
_llama_status_model_ids now derives the (active_model, model_identifier)
pair once for both /status and this endpoint, the count reports the same
string the client holds as params.checkpoint, and a switch landing
mid-count returns 503 rather than a total belonging to neither model.

Recount when the initial status refresh first discovers a loaded local
GGUF: thread history can load before that refresh has a checkpoint or a
window, and nothing reloaded history afterwards, so the bar stayed blank
until the thread was reopened.

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

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

* Search every mounted runtime for the counted thread in PR #7453

The post-load recount asked only the topmost entry of the runtime getter
stack. Compare mode keeps both panes mounted, so when the pane showing the
counted thread is not the newest mount, the tail id check fails against that
thread's records and the count falls back to the branch rebuilt from storage.
After the user steps back through a retry that is the sibling nobody is
looking at, so the bar shows a count for the wrong branch of the right thread.

Walk the stack newest first and take the first getter whose tail is one of
these records. Message ids are unique, so that getter is the pane displaying
them; a stack with no match still falls back to storage exactly as before. A
getter that throws while its provider tears down is now skipped instead of
aborting the whole recount.

* Scope recount cancellation to one thread in PR #7453

The generation counter that supersedes an in-flight recount was module wide,
but every mounted provider recounts its own thread when its history loads.
In compare mode a hidden pane's load therefore cancelled the visible thread's
recount, and the pane's own result was then dropped by the activeThreadId
guard, so the context bar stayed blank.

Key the counter by thread id. Two calls for the same thread still supersede
each other, which is what the counter is for; calls for different threads no
longer see each other. A call that finishes after the user has switched away
is still dropped by the unchanged activeThreadId guard.

* Tighten the token-count comments for PR #7453

* Compress the token-count docstrings for PR #7453

* Decline strict token counts when the chat template will not render for PR #7453

* Compress the strict token-count comments for PR #7453

* Tighten the token-count comments for PR #7453

* Count the request the completion actually sends for PR #7453

Decide the route before applying the tool policy. With `unsloth run
--enable-tools` set and a completed tool call still in history, the counter
selected every built-in tool schema and appended the tool nudge, while the
completion sent the same request to llama-server verbatim and sent neither:
the policy turns on `_effective_enable_tools`, but the passthrough turns on
an explicit per-request `enable_tools` or `mcp_enabled`, which that shape
does not carry. The bar therefore priced a prompt larger than the one being
generated from.

The rule now lives in one helper that both the counter and the completion
call, so the two cannot drift apart silently. It reads `tool_choice` and
`response_format` defensively because the count endpoint takes a different
request model that carries neither.

Decline a runtime message getter whose owner is unknown. Registration
records no thread, and compare mode keeps several providers mounted, so the
newest getter can belong to a sibling pane while the caller's guard only
checks the thread it asked for. Use it when it is the only one mounted,
which is the single-pane case, and otherwise price the template alone
rather than report another pane's total as this thread's.

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

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

* Route the recount before merging user turns for PR #7453

The counter coalesced adjacent user turns unconditionally, but
_openai_messages_for_passthrough does not merge them: it only drops the empty
assistant sentinel. So on the passthrough route the count rendered a prompt
the request never sends, and could come back clean where the real strict
template rejects the unmerged history. Two user turns around an empty
sentinel is the shape a thread has after a response is stopped before its
first token.

Coalescing is a normal-GGUF-path step, so it now happens only once the route
is known, using the same helper the completion asks. The test pins the
passthrough builder as the reference and asserts the route is decided before
the merge.

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

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

* Tighten the comments added while reviewing

Comments only, no code change, verified with comment_tools check. The
call-site note in the count endpoint now points at _takes_tool_passthrough
rather than restating its docstring, and the getter, tool-result and
partial-scan notes lose a line each without losing the reason they exist.

* Studio: stop pricing a withdrawn tool catalog in the token count

tool_choice "none" with no tool history takes the request off the
passthrough, and the GGUF path it lands on calls
generate_chat_completion, which has no tools argument. The counter still
handed payload.tools to /apply-template, and llama-server puts whatever
tools reach that endpoint straight into the Jinja context regardless of
tool_choice, so the bar reported schemas the completion never sends.

Move the rule _build_openai_passthrough_body already applied into
_passthrough_client_tools and read it from both, so the count and the
body cannot drift, and clear the catalog outright on every route that
renders tools from the selection instead.

* Tests: stop shadowing the real structlog in the load-freeze suite

sys.modules.setdefault("structlog", ModuleType("structlog")) ran before
anything imported the package, so the empty placeholder won and stayed
for the whole session. Any later file importing a studio module that
calls structlog.get_logger at module scope then hit AttributeError, and
only when this file was collected first - the new token-count parity
tests passed alone and failed under pytest tests/studio, and the MLX
hardware-dispatch cases failed the same way through utils.mlx_repair.

Only stub when structlog is genuinely missing, and give that stub the
get_logger those callers use.

* Revert the scan-packages baseline edit

The hunk rewrote the fastapi 0.139.2 entry into a byte-for-byte copy of
the 0.140.0 entry sitting next to it, so it dropped a reviewed allowlist
row and left a duplicate key. It also does not silence anything: CI
resolves fastapi 0.140.6, whose evidence digest is neither of those. The
three scan-packages shards fail on main for the same three findings and
are not this branch's to fix.

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

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

* Retract the seeded token count when the recount declines

refreshContextUsage seeds zeroed usage so a chat with no persisted thread has
something to show, then several paths return without counting: staged audio,
a checkpoint that moved under it, and any failure of the count itself. The seed
stayed on screen, so a recount that never landed rendered a confident
"0 / <window>" where the bar previously just stayed hidden.

Hold the seed by identity and clear it on those exits, but only while it is
still the value on screen: anything else means a later count or a completion
already owns the bar, and clearing there would roll back real usage.

The load-without-sending e2e assertion had no minUsed, so the placeholder
satisfied it on its own and a recount that never landed looked like a pass.

* Recount the empty prompt when a New Chat opens against a resident model

ThreadNewChatSwitch blanks the bar with setActiveThreadId(null), and the
/chat?new=<uuid> view reaches none of the other recount triggers: no persisted
thread for the history loader, and ActiveThreadSync is off while a nonce is
present. Loading a model on that view showed a bar, arriving on it with the same
model already loaded showed nothing until the first completion.

Ask for the count after the switch. The template and system prompt are already
in the request, and a fresh chat in a project resolves through the
activeProjectId branch, so its instructions are priced too.

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

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

* Count with the selected reasoning template settings for PR #7453

llama-server merges the load-time --chat-template-kwargs under whatever a
request omits, so /apply-template called with only messages and tools
rendered the mode the model was LAUNCHED in while the completion rendered
the user's. A Preserve Thinking pill flipped on keeps every past turn's
think block in the real prompt but not in the count, so the context bar
under-reported the prompt it was about to send.

The count now forwards enable_thinking / reasoning_effort /
preserve_thinking and reuses _request_reasoning_kwargs, the same helper
the completion paths build their kwargs with.

* Probe structlog with find_spec instead of a bare import

The availability check imported the module purely for its side effect, so
the import-hoist verifier flagged it as an added-but-unused import and
failed Source lint. find_spec answers the same question without binding a
name.

* Recount a reloaded New Chat once inference status hydrates for PR #7453

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

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

* Leave an existing structlog entry alone in the availability probe

find_spec raises ValueError on a module already in sys.modules whose
__spec__ is None, which is what a bare types.ModuleType stub is. Check
sys.modules first so anything already present, real or stubbed, is left
untouched and only a genuinely absent package gets stubbed.

* Consolidate the token-count tests without changing behaviour for PR #7453

The three node-harness files each rebuilt the same mkdtemp plumbing, so it
now lives in tests/studio/_node_harness.py. The reload-hydration cases move
into test_new_chat_context_recount.py beside the New Chat cases they share a
component with, and the reasoning-mode cases collapse into a parametrize.

No behaviour changes. Each merged case was re-checked against the source
revert that motivated it: the hydration retry still reddens at 0 == 1, the
original recount at 0 == 1, the backend kwargs at 28 == 48 and 28 == 29, and
the client payload at None is False.

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

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

* Unload only once the chats stop generating, and honour the E2E backend port for PR #7453

* Trim the token recount backend to what the usage bar needs for PR #7453

* Trim the frontend recount to the branch it counts for PR #7453

* Fold the New Chat recount cases into the branch each one pins for PR #7453

* Compact the count endpoint tests and drop the fixtures they no longer read

* Fold the reload-hydration case into the New Chat pricing test for PR #7453

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

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

* Recount the context bar when a pick adopts the already-resident GGUF for PR #7453

* Price the Canvas prompt instruction in the token recount for PR #7453

* Fold the Canvas recount cases into one parametrised test for PR #7453

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

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

* Price the branch the mounted runtime shows in the token recount for PR #7453

* Reprice a thread that becomes active with a blank context bar for PR #7453

* Count the prompt in the reasoning mode the next completion asks for in PR #7453

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

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

* Price a New Chat as its own empty prompt, not the conversation it was opened from, for PR #7453

ThreadNewChatSwitch voids switchToNewThread() and writes setActiveThreadId(null)
in the same effect, and the recount effect beside it runs in the same flush. The
outgoing conversation is deliberately left running, so its runtime is still
mounted and the live branch reader still returns its messages; the captured
thread and the store's active thread were then both null, so the equality check
matched and the empty chat was priced as the conversation being left behind.

Require a non-null captured thread before reading the live branch. A recount
with no thread id is an unpersisted New Chat, whose prompt is the bare template,
and the stored-records fallback already yields that. Threads that need the live
reader all carry an id: ActiveThreadSync writes assistant-ui's mainThreadId for
incognito threads too, so the branch this reader was added for is unaffected.

* Decline a token recount whose generation would retrieve documents for PR #7453

A thread left on a pending turn -- an unanswered user message, or a tool
result an interrupted loop never answered -- is the one shape where the next
generation runs on exactly the messages the recount sends, and the tool loop
opens that turn by splicing in whatever build_rag_autoinject returns: top-K
passages, or a whole thread document under the context budget. The count never
saw any of it, so the refreshed bar could report that the pending turn fits
when the generation it stands in for would overflow.

Decline that shape exactly as the image case above already does, leaving the
usage already on the bar rather than under-reporting it. Threads ending on an
assistant turn are unaffected: their retrieval runs against a user message that
does not exist yet, which no count could predict. A count payload never carries
an autoinject override, so a scope arriving here is one the default-on gate
retrieves for, and declining a scope it would have skipped only keeps the
previous total.

* Name the tokenizer that produced a token count for PR #7453

This endpoint deliberately never auto-switches: it counts with whatever is
resident and treats the requested model as informational. So a load from
another tab or API client, landing after this client's last status refresh but
before its recount reaches the backend, returns a total from a tokenizer whose
context window the bar is not showing. The frontend's guards compare only its
own captured checkpoint, thread and usage object, none of which moved, so it
published model B's count against model A's window.

Report the identity with the count, in the same shape /api/inference/status
publishes it (model_identifier ?? active_model), and drop the result client
side when it is not the checkpoint the count was started for. The pair is now
derived once in _llama_status_model_ids and used by both the status handler and
this endpoint, so the string a client compares cannot drift from the one it was
given. A load landing mid-count is refused outright, since that total belongs
to neither model. A reply without the field is still accepted, so an older
backend keeps working.

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

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

* Price the route the completion takes in token recounts for PR #7453

The token count has to describe the request the completion actually sends.
The counter applied the process tool policy without first asking which route
the request takes: with `unsloth run --enable-tools` set and a completed tool
call still in history, it selected every built-in tool schema and appended the
tool nudge, while the completion forwarded the same request to llama-server
verbatim and sent neither.

Restore the two rules the completion path already follows and have both routes
read them from one helper each, so a count can never describe a route the
completion does not take:

- `_takes_tool_passthrough` decides the route before the process tool policy
  applies, and before adjacent user turns are coalesced (the passthrough does
  not merge them, so merging prices a prompt that route never sends).
- `_passthrough_client_tools` decides which client tools reach the wire, so a
  caller's own catalog is priced on the passthrough and a `tool_choice: "none"`
  withdrawal is not.

`ChatCountTokensRequest` carries `tools` again, since that catalog is what the
passthrough renders.

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

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

* Bind _native_grant_backed in the loaded-GGUF status branch again

Merging main into this branch left GET /api/inference/status raising NameError
whenever a GGUF is loaded. The two edits do not touch the same lines, so git
merges cleanly and neither side is wrong on its own:

  - this branch moved the native-path identity logic out of get_status into
    _llama_status_model_ids, and with it the local _native_grant_backed read;
  - main (#7385) added is_local_model = _loaded_is_local_model(llama_backend,
    _native_grant_backed, _model_id) inside that same branch.

Read the flag in get_status again. Keeping the helper at its two-value contract:
it reports identities, is_local_model wants provenance, and the helper is also
consumed by _llama_status_checkpoint_id and the token count route.

Also refuse an audio prompt in /chat/count_tokens, for the reason the image guard
already exists. ChatCountTokensRequest allows extra fields, so audio_base64 was
accepted, dropped, and answered with a total short by the whole clip. Studio
declines client side, but the router is mounted at /v1 too, so a direct caller
on /v1/chat/count_tokens could be handed that number.

Tests: test_inference_status_loaded_gguf.py calls the handler with a loaded
stub, which nothing did before, so neither suite could have caught this; it
reddens on the NameError itself with the fix reverted. Two cases on
test_openai_auto_switch.py for the audio refusal and its negative control.

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

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

* Tighten the comments added for PR #7453

Comment and docstring only. AST of routes/inference.py and
test_openai_auto_switch.py is byte identical to the previous commit; the new
test module differs in docstrings alone, with an identical code AST.

* Do not put a non-finite token count on the context bar

The count endpoint's response type is a compile-time assertion; parseJsonOrThrow
returns the body unvalidated. Anything other than a matched backend answering 200
on that path (a reverse proxy, a version-skewed fork, an SPA fallback serving
JSON) therefore publishes undefined as promptTokens and totalTokens.

ContextUsageBar does not absorb that. Its "nothing to show" guard is
'used <= 0', and 'undefined <= 0' is false, so it renders 'undefined / 8.2k'
with a NaN width, and formatTokenCountFull calls toLocaleString on it, which
throws inside the tooltip render as soon as the bar is hovered.

Leave the bar as it was instead, which is what every other failure of the
recount already does.

Six cases on test_new_chat_context_recount.py: a reply that omits input_tokens,
and null, a numeric string, NaN, Infinity and an object in its place. All six
publish to the bar with the guard reverted.

* Close three prompt-parity gaps in the token recount

All three were re-raised by review after ab2cc58 ("Trim the token recount
backend to what the usage bar needs") rewound this area; most of what that trim
dropped was restored afterwards, these three were not.

Strict counting no longer accepts the text-only fallback. count_chat_tokens
refused it only when the prompt had non-text parts, so a text-only history whose
/apply-template call timed out, 500'd or was rejected by a strict-alternation
template still returned a number: message text plus serialized tools, with no
role markers or special tokens, measured earlier at roughly 30 percent under a
six-turn two-tool prompt. Both public count endpoints pass strict = True, so
/v1/messages/count_tokens is corrected the same way; the three streaming
message_start.usage callers are non-strict and keep the best-effort behaviour.
The docstring already promised this.

The counter now runs the same stale tool-call XML strip over replayed assistant
turns that the GGUF tool path runs before rendering, gated on the same enabled
tool names so a documented inactive foo[ARGS]{...} survives in both. Without it
the count priced markup the completion deletes, which reads as a tool-enabled
chat sitting closer to its window than it is. auto_heal_tool_calls is forwarded
so the Auto-Heal-off cohort, whose real prompt keeps that markup, is not
undercounted instead.

A turn sent while a count is in flight now drops the count. The existing guard
compares contextUsage by identity, which only catches a completion that wrote
usage; a run stopped or failed before emitting any leaves it untouched, so the
pre-message total published for a branch that had gained a turn and stayed there,
since no dependency moves to retry. Compare the counted branch instead.

Declined two other items. A bounded retry after a transient 503 would also
re-poll the four deliberate declines (image, audio, no model, pending RAG turn),
which are permanent per payload and carry no Retry-After, and its failure mode is
publishing a wrong total rather than the blank bar it would fix. Forwarding
autoinject and whole_doc for a Docs-enabled chat with auto-injection off changes
nothing on its own, since the decline keys on rag_scope alone and the nudge never
reads autoinject: there is no wrong number in that configuration, only a blank
bar, and closing it needs the retrieval gate back plus a frontend mirror of
resolveAutoInject that must stay in lockstep forever.

Tests: three cases with negative controls. Reverting only the source reddens 5 of
them on values, and the auto_heal_off and branch_unchanged rows stay green, so
neither new guard overreaches.

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

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

* Tighten the comments this PR added

Comment, docstring and whitespace only, across the 11 files with PR-added
comments: 509 comment lines down to 445. Heaviest cut in routes/inference.py
(95 to 69), where a 14-line rationale for the pending-RAG-turn decline became 7
without losing the causal chain.

Rules applied: delete where the code already says it, compress where the comment
records a non-obvious reason, and keep every workaround or ordering note. So the
"Route FIRST" ordering constraint in chat_count_tokens, the captured-null New
Chat race note, the llama-server chat_template_kwargs layering quirk and the
_native_grant_backed refactor history all survive, shorter.

Two things constrained the pass. The python harness tests slice shipped TS
between literal comment markers, so those markers are byte-identical and the
CANVAS_* constant names stay unmentioned (one test asserts a count of 3). And a
python docstring is an AST node, so three helper docstrings were shortened to one
line rather than removed.

Verified comment-only two ways: comment_tools.py check --strip-docstrings is
11/11, and prepush_gate --comment-only --allow-docstring-edits is 11/11, the
latter isolating the docstring rewrites from the code. 269 tests pass, ruff
clean, tsc clean, node --test 57 pass.

* Drop a recount taken while its thread is still running

The branch signature added in 961971e catches a turn appended during a count,
but a run streaming into a turn that already exists grows that message's content
without moving the branch length or its last id, so the signature compares equal
and the partial response is what gets published. Nothing recounts again, and if
the run is then stopped or fails before writing usage the undercount stays.

Reachable because the recount effect gates only on contextUsage being null and on
its model/thread dependencies, with no running-state check, so returning to a
thread with a background run and a blank usage cache starts a count mid-stream.

Decline at publish time when the thread is running, rather than folding content
into the signature: a live run writes its own usage when it lands and leaves the
bar untouched if it is stopped, so nothing is lost by not publishing, and there is
no hash of a whole branch on the main thread.

Two cases, and reverting the guard reddens the streaming one while the idle
control still publishes.

* Make the recount's branch validation whole instead of patching it again

Three rounds have each found another way past this guard, which is the signal
that comparing a weak signature at publish time was the wrong shape rather than
three separate bugs. Closing all three at the root.

Text length joins the signature. A run streaming into a turn that already exists
grows that message's content without moving the branch length or its last id, so
neither the previous signature nor the running check saw it once the run had
stopped: runningByThreadId is already false by then and the usage snapshot is
still equal, so the partial published.

An empty current branch now counts as a mismatch. The old current.length > 0
condition skipped the comparison entirely, so deleting the sole exchange
mid-count left the old conversation's total on the emptied thread.

The running check keys on "__default" when there is no thread id. A New Chat count
captures a null id and has no branch to compare, and the active-thread check stays
null until initialize() assigns one, so a first turn sent mid-count previously left
the bare-template total on a chat that already had the turn. A first turn files its
run under that key, which is the only witness available before the id exists.

Six cases, three of them new. Reverting only this file reddens exactly the three
new ones and leaves every control row green.

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

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

* Identify a counted branch by its content, not its size, for PR #7453

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

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

* Price the RAG tool on a new chat and validate attachments for PR #7453

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

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

* Validate stored-history recounts and repoint the status contract test for PR #7453

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

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

* Leave the context bar blank for output-only audio models for PR #7453

* Tighten the comments added by PR #7453

* Render a template for an empty chat so a new chat still counts for PR #7453

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

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

* Revert the empty-chat template shim for PR #7453; minja renders an empty list

* Keep the token recount off the inference path for PR #7453

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

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

* Refuse a token count server side while any generation is in flight

The client gate added in 9bdb0f8 only covers Studio's own tab. A second tab, a
script against /api or a count already queued could still land a recount next to
a decode, so chat_count_tokens now declines with 503 when active_generations
reports anything running. Checked twice: on entry, before the handler does any of
the count's work, and again immediately before the llama-server round trip, since
everything in between awaits and a run can begin in the gap.

The refusal is deliberately coarse. _TrackedCancel registers external-provider
runs too, and those never reach llama-server, so a count that was safe gets
declined. Narrowing it would mean trusting a kind field to decide whether to do
work beside a decode, and being wrong that way costs inference time while being
wrong this way costs a later redraw.

That coarseness exposed a gap on the client, which gated on localRunByThreadId
alone. During an external-provider run it would issue a count, take the 503, and
never retry, because only what the recount effect depends on can re-fire it and
that run was not in the dependency array. The gate and the dependency are both
runningByThreadId now, so the client refuses exactly what the server refuses.

The client swallows the 503 and keeps the value already on the bar, so the cost
is a number that arrives when the run ends rather than during it.

test_a_count_taken_while_the_thread_is_running_is_dropped seeded a live run and
asserted the publish guard dropped the total. The entry gate makes that state
unreachable, so the case now starts idle and flips mid count, which is the only
way a count can still be in flight when a run begins.

* Price cached MCP schemas, and retry a New Chat recount after a background run

Two review findings, both real.

The count forced mcp_allowed False to keep discovery off the background path, so
MCP schemas went unpriced while the completion rendered every one of them. That
is an undercount, which is the dangerous direction: it tells the user room exists
that the next request will not find. cached_mcp_tools() now reads the schemas the
completion path already cached, with no probe, no spawn and no cool-off write,
and the count declines with 503 when an enabled server has nothing cached and
would have been probed. A server in its post-failure cool-off contributes nothing
to the completion either, so skipping that one is exact rather than short.

The tool branch also only opened on _tools_on, while MCP alone turns tools on for
the completion, so a request with built-in tools off and MCP on was short by the
whole catalog. It now opens on either.

Separately, ThreadNewChatSwitch's recount did not observe run activity. New Chat
during a background generation is a supported flow, so refreshContextUsage
declined, and ThreadContextUsageRecount could not pick it up afterwards because
an unpersisted New Chat has no activeThreadId to key on. The empty chat's bar
stayed blank for good rather than until the run landed. The effect now takes
runActive as a guard and a dependency, the same shape as the other recount.

Merged current main, which had moved far enough to break the recount harness:
the load path it slices verbatim gained a useChatRuntimeStore.setState call, and
the harness's fake store had no such door. This was green locally and red in CI
for exactly that reason. The fake now merges on setState, as the real one does.

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

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

* Tighten the comments added by the token-count work

Shorten the explanatory comments in the count endpoint, the recount helper and
the runtime effects to the fewest lines that still carry the reasoning. No code
changes: the minja empty-message note, the coarse generation refusal, the
duplicated generation check, the _mcp_allowed rationale, the MCP cool-off note
and the runningByThreadId dependency note all keep the fact they state.

* Keep saved usage through history hydration, and stand a count down mid flight

Two review findings.

The history loader restores the last completion's own usage when it is for the
current model and inside the window, then called refreshContextUsage
unconditionally. That helper only stands down for a value that CHANGED while it
was counting, not for one that was already there, so it overwrote exact totals
with an estimate whose completionTokens is 0. It now runs only when nothing was
restored, which is still every case it was added for: a thread opened after a
model switch fails the model check and is priced as before. Kept as the narrowed
value rather than a boolean flag, since the writes below it need that narrowing.

The count's generation guards admit only while nothing is decoding, but admission
and the work are separate steps, so a run registering in between was not
prevented. Making them mutually exclusive would mean generation startup waiting
on a lock held for the length of a count, up to tens of milliseconds on a long
thread, which is the cost these guards exist to avoid. Instead count_chat_tokens
takes an optional should_abort, polled between /apply-template and /tokenize, so
a count admitted while idle drops its second round trip once a run appears. The
comment claiming no overlap now describes what the code does rather than what it
would like to be true.

CountAborted has to escape the template except-block: swallowed, it would set
apply_template_failed and the text fallback would tokenize anyway, which is the
work being declined. Covered by a test against the real count_chat_tokens, not a
stub, because a stub cannot see that.

Adding the kwarg broke six existing count tests whose shared stub did not accept
it, which the targeted runs did not show. Backend suite: 13877 passed, 14 failed,
the same 14 as before these changes and a subset of clean main's 15. tests/studio
2350 passed with 3 failures that reproduce on clean main. Frontend 300 passed,
tsc, build, eslint and ruff clean.

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

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

* Tighten the token-count comments added since the last pass

* Stop the recount doing work it can never use

Four review findings, all confirmed against the code.

Deep Research routes the next send to a server-side research run instead of
posting this history, and the research reply carries no usage, so a total counted
here describes a request that is never made and nothing later corrects it. The
recount now declines while it is on.

/chat/count_tokens always refuses images, because /apply-template swaps each one
for a short marker. The client was finding that out by hashing the base64 into
the branch signature, serialising it into a request body that can run to
megabytes, and posting it, all on the UI thread, to be told 503. It now declines
before the hash, which is why the signature moved below the guards.

The history loader recounted for every pane. A compare pane deliberately never
writes activeThreadId, so refreshContextUsage drops its total at publish: opening
two panes rebuilt two branches from storage and paid for /apply-template and
/tokenize twice to display neither. Gated on the same modelType/pairId condition
ThreadContextUsageRecount and ActiveBranchRegistrar already use.

A model load fires two triggers milliseconds apart, the explicit post-load call
and the effect watching modelLoading, which resetLoadingUi clears just before it.
The generation map discarded one result but neither request. Counts are now
deduped per thread while one is on the wire; the publish-time branch check still
drops a total the branch outgrew, so nothing is lost by skipping the second.

Not fixed: making count admission atomic with generation startup. The check is
still check-then-act and that is deliberate. Mutual exclusion means generation
startup waiting on a lock a count holds, up to tens of milliseconds on a long
thread, which is the cost these guards exist to avoid.

tests/studio 2365 passed, the 3 failures in test_chat_autoload_failure_gate.py
also fail on clean main. Frontend 300 passed, tsc and build clean. The one eslint
error is a restricted import from #6205 and is present at the base.

* Defer a skipped recount instead of dropping it

The dedupe added in the previous commit turned one lost-retry bug into another.
A run that starts and is stopped before it emits usage flips runActive back and
fires the retry the recount effect depends on. If that retry arrives while a
count is still in flight it was discarded, the in-flight count then rejected its
now-stale branch, and nothing changed again, so the bar stayed blank for good.

A skipped trigger is now recorded with its options and replayed once the
in-flight count settles, but only if that count published nothing. That keeps
the model-load case at a single count, since there the first trigger publishes
and the queued one has nothing left to do, while the stopped-run case gets its
retry against the branch as it stands rather than the one the first count read.

The dedupe test could not tell the two apart: it awaited both calls but the
replay is scheduled off the first count's finally, so a stray one landed after
the assertions. It now settles first, and replaying unconditionally reddens it.

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

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

* Tighten the comments added by the last two fixes

Collapse the multi-line explanations on the in-flight dedupe, the deferred
retry, the Deep Research decline, the image decline, the compare-pane gate
and the messagesContainImage predicate, keeping the reasoning each records.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Han <[email protected]>
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.

2 participants