Skip to content

Studio: turn the offload planner on by default - #9779

Merged
danielhanchen merged 13 commits into
mainfrom
smart-offload-on-by-default
Aug 26, 2026
Merged

danielhanchen merged 13 commits into
mainfrom
smart-offload-on-by-default

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Makes UNSLOTH_SMART_OFFLOAD opt-out rather than opt-in, so the -ot placement planner from #9675 runs by default.

Kept deliberately separate from #9778, which widens what the planner can place. That one is strictly more capability and can land on its own merits. This one is a policy decision about defaults, and should be argued on its own.

Why now

The planner shipped opt-in with a condition written into the docstring: "until it has run on more than one machine". It has.

  • 118 paired runs across T4, T4 high-RAM, L4, RTX PRO 6000 and A100, with the VRAM budget forced from 4 GiB up to each card's own size in 2 to 4 GiB steps.
  • Faster on generation in 111 of 118.
  • In all 83 runs where the layer-count arm split the KV cache to host RAM, the planner kept 100 percent of the cache on the GPU.
  • The win is largest exactly where it matters. MoE B/A is 3.08 at a 4 GiB budget and 1.52 at 36 GiB.
  • Also run on a B200, and on a real gfx1151 Strix Halo, where the detector reports the unified pool and the planner correctly declines while the same layout spills 51 blocks with the flag forced off.

What this does and does not mean

Being the default does not mean it places every load. It abstains often, and every abstain falls through to --fit on, which is llama.cpp's own fitter and exactly what this arm did before the planner existed. That fallback is not the disabled path, it is the planner declining, and it stays. Emitting a plan where the planner declined is the defect that once put -ngl -1 --fit off on loads it had just said do not fit.

So the accurate statement is: --fit on is gone whenever the planner produces a plan, and remains wherever it declines or is switched off.

One asymmetry worth calling out

An unrecognised value now disables rather than enables. For an opt-out flag the two typos are not symmetric: someone who writes flase meaning off would otherwise get the very thing they were trying to switch off, while someone who fumbles an on-spelling merely keeps the previous behaviour. The escape hatch has to be the reliable direction.

0, off, no, false, disabled and empty all still disable, and there is a test for each.

The risk being accepted

Stating this plainly, since it is the argument against merging.

  • Dense models on very small hosts lose. Median B/A 0.92 on a 2 vCPU host, n=4. Spilled decode runs on the CPU backend, a dense FFN is read in full every token, and with two cores there is nothing to read it with. MoE is where the idea pays, because only around 3B params are active per token.
  • Multi-GPU still abstains in nearly every spilling case, so on those hosts this changes little today.
  • The cost model is optimistic by 3x to 8x on Q2_K. That drives the reported penalty rather than the fit decision, so a wrong number misinforms rather than OOMs, but it is wrong.
  • 25 defects were found during this work and every one was in the optimistic direction, a plan claiming a fit that is not there. The last several came from review rather than measurement, so I would not assume the list is closed.

If the dense small-host case is the blocker, the natural narrowing is to keep declining for dense models below a core-count threshold, which leaves that band on --fit on. Happy to add it here.

Tests

test_the_planner_is_on_by_default now asserts a plan appears with no env set at all, for both a load that fits and one that does not. Added tests for every off-spelling and for the unrecognised-value case. 292 pass across test_offload_planner_seam, test_offload_planner and test_llama_cpp_placement.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

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: e569ab2cd1

ℹ️ 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 +810 to +811
if raw is None:
return 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 Gate default planner on -ot support

When UNSLOTH_SMART_OFFLOAD is unset and a supported custom LLAMA_SERVER_PATH points to a build whose successful --help lacks -ot, a spill decision now reaches _spill_plan_flags_for, which unconditionally emits -ot; that binary rejects the unknown argument and forces a failed startup plus recovery retry. The capability probe already exposes the binary's advertised flags, so the default-on path should decline when neither -ot nor --override-tensor is supported, while retaining fail-open behavior for an inconclusive probe.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Checked this one carefully and I do not think the scenario can occur. The spill flags are -ngl -1 --fit off -ot ..., and Studio emits --fit on every launch path regardless of the planner (the abstain branch sends --fit on, the fits-on-GPU branch --fit off). There is no supports_fit capability: --fit is the assumed floor, and only its sub-flags --fit-ctx and --fit-target are probed.

-ot (ggml-org/llama.cpp#11397) predates --fit and common/fit.cpp by a long way. So a build whose --help succeeds but lacks -ot necessarily also lacks --fit, and already fails to start today, before the planner is consulted. The -ot token is strictly less demanding than what Studio already ships. A capability probe there would guard a door that is already shut.

Happy to revisit if you have a concrete build where --help lists --fit but not -ot.

@danielhanchen

Copy link
Copy Markdown
Member Author

Merge-order note for whoever lands these.

#9778 fixes an env-twin asymmetry that also exists here: --main-gpu / -mg is declined through _DEVICE_FLAGS, but that set is argv-only, so LLAMA_ARG_MAIN_GPU walks through the placement gate. I fixed it there rather than duplicating it here, to avoid a conflict between the two branches.

The consequence is an ordering preference rather than a blocker: if this PR lands first, there is a window where the planner is on by default without that guard. Landing #9778 first, or rebasing this on it, closes the window. Either way the second one to land needs no extra change.

Structural remark while it is fresh: every guard in that block reads placement env vars by name, one at a time, and there are now eight. Nothing makes a NEW placement env fail closed, so the next LLAMA_ARG_* that upstream adds will be silently unguarded again. Not a defect today, but it is the shape that produced both this item and the RPC one.

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 2670036aa1

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

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 26, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 26, 2026
@danielhanchen

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: f9c9234427

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

# (common/fit.cpp:282-288). Emitting --fit off skips
# common_params_fit_impl and drops the margin silently, while this
# planner spends it. Decline, like any other explicit --fit.
or fit_target_margin_in(extra_args, source_env) is not None

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 explicit fit-context controls

When the caller supplies --fit-ctx/-fitc—or, on an auto-context launch, LLAMA_ARG_FIT_CTX—without an explicit --fit, llama.cpp's default-on fitter uses it as the minimum context it may shrink to (common/arg.cpp:2876-2882). This guard declines --fit-target but not that other fit control, while PlanOptions.context_policy remains NEVER_REDUCE; a successful spill plan then appends --fit off and silently discards the requested context-fitting policy, potentially spilling many GiB of weights where the caller explicitly allowed a smaller resident context. Decline for explicit fit-context controls or translate them into the planner's context policy and minimum.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I think this one inverts what -fitc means. common/arg.cpp:2896 describes fit_params_min_ctx as the MINIMUM ctx size that can be set by --fit, defaulting to 4096 (common/common.h:470), and -c 0 sets it to UINT32_MAX precisely to DISABLE context reduction. It is a floor restricting how far the fitter may shrink, not a permission to shrink.

So context_policy = NEVER_REDUCE is strictly more protective of the caller than any -fitc value they could pass, and nothing they asked for is discarded. The analogy to --fit-target does not carry either: that flag reserves bytes this planner would otherwise spend, which is what made it a decline. -fitc reserves nothing.

Declining here would drop these loads back to --fit on, which is whole-layer offload with the KV cache following it, the regression this change exists to remove. Preference rather than correctness, so leaving it.

return str(raw).strip().lower() in ("1", "true", "yes", "on", "enabled")
raw = (os.environ if env is None else env).get("UNSLOTH_SMART_OFFLOAD")
if raw is None:
return 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.

P1 Badge Include checkpoint snapshots in the spill budget

When a load enables --ctx-checkpoints/--swa-checkpoints, the placement calculations call _kv_bytes(..., _effective_ctx_checkpoints) because each checkpoint adds another per-slot SWA snapshot, but the snapshot handed to the spill planner is reset to _kv_bytes(effective_ctx) with the default checkpoint count of zero. LLAMA_ARG_CTX_CHECKPOINTS is also inherited by llama.cpp but is absent from _effective_ctx_checkpoints, so that form is unpriced everywhere in this snapshot. If the base footprint already requires a spill, the default-on planner can therefore move too few tensors and emit --fit off, leaving the checkpoint allocation to OOM; pass the effective checkpoint-sized KV value into kv_cache_bytes, including the environment twin, or abstain when it cannot be resolved.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This is the VRAM version of a point I answered on #9778 (comment 3860962782), and the answer is the same. The change asked for is kv_cache_bytes -> kv_bytes_floor in plan_placement, which is purely a GPU cache term feeding _per_device_shortfall and _usable_vram, but checkpoints are host heap: common_prompt_checkpoint holds std::vector<uint8_t> buffers (common/common.h:1137-1185), and n_ctx_checkpoints appears only in common/arg.cpp, common/common.h and tools/server/server-context.cpp, never under src/ or ggml/, so it never reaches KV-cache sizing. There is no VRAM allocation here to protect against.

It is not a load-time host shortfall either: the snapshot is update_tgt serialising a seq state into that vector during serving (server-context.cpp:2224-2249), well after placement.

So kv_cache_bytes = _kv_bytes(effective_ctx) is the physically correct resident number, and the checkpoint-inflated form is deliberately confined to _fit_derived_load_mode, which is a footprint-versus-RAM question rather than a placement one. Inflating the VRAM floor would spill layers to make room for bytes that never land on the card.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 26, 2026

@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: 608c09cb63

ℹ️ 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 +19055 to +19058
_spill_inputs["env_mmproj_bytes"] = (
0
if _fit_env_mmproj_on_host
else _fit_env_mmproj_bytes

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Include CPU-pinned projectors in the host budget

When an inherited LLAMA_ARG_MMPROJ is resolved with --no-mmproj-offload or a false LLAMA_ARG_MMPROJ_OFFLOAD, this branch records zero bytes, so _planned_tensor_spill accounts for the projector in neither VRAM nor host RAM. A successful spill plan can consequently have _finish select --load-mode none using only the spilled base tensors as host_bytes; on a host where those tensors fit but those tensors plus the resident CPU projector do not, the launch can be OOM-killed instead of retaining the pageable load mode. Carry the host-pinned projector size into the plan's host budget, or abstain from planning this case.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Your premise is right and I checked it upstream: --no-mmproj-offload and -mmdev none both clear mmproj_use_gpu (common/arg.cpp:2590-2616), the server passes it through as mparams.use_gpu (server-context.cpp:1000), and clip.cpp then allocates the weights from the CPU backend and reads the file straight into them (tools/mtmd/clip.cpp:188-207, :3560-3584). No mmap, at load time. So a CPU-pinned projector really is anonymous host RAM present at startup.

Where it does not follow is the consequence. In the plan, host_ram_bytes has exactly one consumer: load_mode_none = host_bytes <= host_ram_bytes - headroom (offload_planner.py:749-752). It gates no spill decision, and it never becomes argv: _spill_plan_flags_for returns -ngl -1 --fit off plus the -ot tokens and deliberately no --load-mode. Grepping the repo for load_mode_none outside the planner turns up a single test assertion. So the described outcome, selecting --load-mode none and being OOM-killed instead of staying pageable, cannot occur on this path.

The --load-mode Studio actually emits is _fit_derived_load_mode, and that already carries this exact term: the pinned projector goes into host_only_bytes (llama_cpp.py:9257-9259), the term free VRAM is explicitly not allowed to pay for, and the round-three change feeds the inherited on-host projector into it at :19065-19066. The env_mmproj_bytes = 0 you flagged is the GPU budget, where 0 is the correct charge for a projector that is not on the GPU.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@danielhanchen

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: 66a89653c2

ℹ️ 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 inputs.get("env_mmproj_unsized"):
logger.debug("Tensor spill: declined, an inherited projector could not be sized")
return None
extra_gpu_bytes += int(inputs.get("env_mmproj_bytes") or 0)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Account for auto-discovered projectors before spilling

When an automatic launch includes the allowed --mmproj-auto extra and llama.cpp finds an adjacent projector, launch_mmproj_path remains unset and these inherited-projector fields are both zero, even though the child loads the projector onto the GPU. On a load requiring a spill, the planner can consequently move too few tensors and emit --fit off, leaving the unbudgeted projector to trigger a startup OOM. Resolve and size the auto-discovered projector, or abstain whenever --mmproj-auto is effective.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I checked this one rather than taking it, and the premise does not hold in llama.cpp.

--mmproj-auto is not an enabling flag. Its setter is params.no_mmproj = !value (common/arg.cpp:2581-2588) and no_mmproj already defaults to false (common/common.h:586), so the flag only ever undoes an earlier --no-mmproj. If the vector existed it would fire on every launch, flag or not, which makes the gating premise self-defeating.

There is also no adjacent-file discovery. no_mmproj gates exactly one thing, opts.download_mmproj (common/arg.cpp:397-398), and that option is consumed only inside the plan built under if (!params.model.hf_repo.empty()) (:400-402). The lookup is find_best_mmproj over the Hugging Face repository listing (common/download.cpp:781, :632), not a scan of the directory next to -m. Nothing in the tree sets a projector path except that download callback, --mmproj and --mmproj-url.

And Studio cannot reach it regardless: -hf, -hfr, --hf-repo and -hff are hard-denied pass-through groups, and LLAMA_ARG_HF_REPO / LLAMA_ARG_HF_FILE are scrubbed from the child env before launch. With a local -m, hf_repo is always empty, so the download plan never runs and there is no auto projector to charge. The two inherited vectors that ARE reachable are the ones already covered.

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 26, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: fbc918fe46

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

@danielhanchen
danielhanchen merged commit 60d2a63 into main Aug 26, 2026
5 of 6 checks passed
@danielhanchen
danielhanchen deleted the smart-offload-on-by-default branch August 26, 2026 13:13
danielhanchen added a commit that referenced this pull request Aug 27, 2026
* Studio: fix the AttributeError that 500s every planned GGUF load

_planned_tensor_spill read the host-RAM headroom as

    host_ram_headroom_bytes = self._HOST_RAM_HEADROOM_MIB * 1024 * 1024

copying the shape of _PIPELINE_PER_DEVICE_OVERHEAD_MIB on the line directly
above it. That one is a class attribute (llama_cpp.py:9597). The headroom is
module-level (llama_cpp.py:4721), so it is not reachable through self, and every
load that got as far as the planning call raised

    'LlamaCppBackend' object has no attribute '_HOST_RAM_HEADROOM_MIB'

and came back to the client as a 500. Since #9779 the planner is default-on, so
this is on the path of every GGUF load, not an opt-in one.

Observed loading unsloth/Qwen3.8-Flash-Next-GGUF UD-IQ1_S on a Colab T4 high-RAM
VM: llama-server never spawned and the load returned 500.

The seam suite stayed green through all of it because the _Stub double declared
_HOST_RAM_HEADROOM_MIB = 2048 itself, so the lookup found it on the double and
never on the class under test. Dropping that line from the double is most of the
fix here: with it gone and the source left unpatched, 66 of the 127 seam tests
fail. A named test also asserts the double declares no attribute the real class
lacks, and that the seam source no longer reaches for this one through self.

* Tighten the comments on the host RAM headroom fix
danielhanchen added a commit that referenced this pull request Aug 27, 2026
* Studio: fix the AttributeError that 500s every planned GGUF load

_planned_tensor_spill read the host-RAM headroom as

    host_ram_headroom_bytes = self._HOST_RAM_HEADROOM_MIB * 1024 * 1024

copying the shape of _PIPELINE_PER_DEVICE_OVERHEAD_MIB on the line directly
above it. That one is a class attribute (llama_cpp.py:9597). The headroom is
module-level (llama_cpp.py:4721), so it is not reachable through self, and every
load that got as far as the planning call raised

    'LlamaCppBackend' object has no attribute '_HOST_RAM_HEADROOM_MIB'

and came back to the client as a 500. Since #9779 the planner is default-on, so
this is on the path of every GGUF load, not an opt-in one.

Observed loading unsloth/Qwen3.8-Flash-Next-GGUF UD-IQ1_S on a Colab T4 high-RAM
VM: llama-server never spawned and the load returned 500.

The seam suite stayed green through all of it because the _Stub double declared
_HOST_RAM_HEADROOM_MIB = 2048 itself, so the lookup found it on the double and
never on the class under test. Dropping that line from the double is most of the
fix here: with it gone and the source left unpatched, 66 of the 127 seam tests
fail. A named test also asserts the double declares no attribute the real class
lacks, and that the seam source no longer reaches for this one through self.

* Tighten the comments on the host RAM headroom fix
danielhanchen added a commit that referenced this pull request Aug 27, 2026
…hing (#9768)

* Studio: stop a small context window ending a tool-using turn with nothing

A chat at a 4096 context died with "request (4237 tokens) exceeds the
available context size (4096 tokens)" after edit_file had already written
the file. Measured through the model's own template and tokenizer, the
overflow was not the tool result: it was the assistant's own edit_file
arguments, which the template only renders once a tool message answers
the call.

Five defects came out of that one thread:

1. Completed tool-call arguments were replayed verbatim forever, so a
   whole-file write kept costing its full size on every later turn.
   They are now compacted in the replayed conversation only, leaving the
   stored thread and what the tool received byte-identical.

2. The fit was discovered after execution, so an unservable turn had
   already spent its side effect. The check is hoisted above the call,
   and a turn that cannot be rescued is refused before it writes.

3. edit_file took one old_string/new_string pair, so building a file
   meant one call per hunk and the model spent whole turns chunking.
   It now takes a batched edits[] array, matched against the original
   text with overlap detection and applied all-or-nothing.

4. A tool call whose JSON was cut off mid-stream was healed by filling
   the first single-string argument with the raw fragment, so a
   truncated python call became a program that was literally its own
   broken JSON. Truncated calls are now told apart from merely
   malformed ones and are never healed.

5. A turn could spend the entire window reasoning and stop on
   finish_reason length with no answer and no tool call. Because a
   truncated thought is correctly not promoted as an answer, that
   rendered as an empty message. It now continues with thinking off,
   and says which lever to pull if that still produces nothing.

Verified against the live llama-server that produced the original 400.

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

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

* Studio: stop a starved tool result turning into a read loop

Asked to show a 2401-byte file inline at a 4096 window, a turn spent
eighteen tool calls getting nowhere. The log says why:

    tool result: name=terminal budget_tokens=0 chars=109

Six of the last eight calls were priced at zero, so each returned only
the notice saying it had been cut. The model read that as a fresh
failure and tried again with a different line range every time.

Three changes, cheapest first:

- A result budget below a useful floor now triggers compaction and a
  re-price before the call runs. Room is exactly what compaction
  reclaims, and spending it here is what lets the call succeed rather
  than return a notice.

- A call the window has already priced at nothing says so on the FIRST
  result. The pricing is known before the tool runs, so waiting for a
  repeat guard to rediscover it spends calls learning something already
  computed.

- A tool that returns byte-identical results several times in a row now
  tells the model the answer will not change. Keyed on the RESULT and
  not the arguments, because the arguments differed on every one of the
  eighteen calls; an argument-keyed guard would have watched it happen.
  It never fires while results are still changing, so polling is
  untouched, and it tells the model rather than aborting the run.

edit_file's description also now says a successful call means the file
on disk holds what was sent, so there is no need to read it back. That
is what started the spiral.

The result-keyed guard and the never-fire-while-changing rule follow
OpenClaw's tool-loop detection. hermes-agent's repetition guard was
measured against this turn first and would not have fired: two repeats
of a 75-char line in 9935 chars is far below its thresholds.

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

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

* Studio: finish an answer the window cut in half, and stop leaking the
unparsed-arguments sentinel

Two things from live threads on the previous build.

1. A turn streaming a 2401-byte file inline at a 4096 window stopped
mid-token, at `ctx.arc(6, -5, 5, 0` with a <!DOCTYPE and no closing tag.
The earlier fixes had already done their part: the same turn made one
tool call where the build before it made eighteen. What remained is
arithmetic, and the room that ran out belongs to the reply rather than
the prompt, so compaction cannot help and the answer has to span two
turns.

The existing continuation only covered a turn that showed NOTHING. It
now also resumes a truncated answer, handing the partial back with
continue_final_message so the model extends it mid-token instead of
restarting and apologising. Thinking stays on, because thinking was
never the problem here.

hermes-agent's repetition guard is ported alongside it, and this is the
path it was written for: their continuation nudge once stitched a
repeated fragment into a 60,698-char response. A fragment that is mostly
an echo of itself is kept as-is rather than extended. It was measured
against the earlier read-loop first and correctly ruled out there.

2. `__unsloth_unparsed_arguments__` was reaching both places a caller
looks. The tool card showed it to the user verbatim, and the replayed
assistant turn showed it to the MODEL, teaching it a key that no tool
declares. Both boundaries now go through one accessor: the card shows
the fragment under `raw`, and the replay sends it verbatim as the
arguments string, which is what that field is in this format.

test_a_turn_that_answers_is_never_continued is retargeted rather than
removed. It encoded the old rule that any turn with content was left
alone, which the first change deliberately reverses; what still holds,
and is what it now asserts, is that an answer resumes with thinking on
and extends the partial rather than being treated as a stalled thought.

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

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

* Studio: keep replayed tool-call arguments parseable

The previous commit stopped `__unsloth_unparsed_arguments__` reaching the
model by replaying the truncated fragment verbatim as the call's
`arguments`, on the reasoning that the field is a string in this format
so the fragment was the honest value.

The field is a string the SERVER PARSES while rendering the chat
template, which that reasoning missed. A fragment is unparseable by
definition, that being why it is there at all, so every request carrying
one failed outright:

    llama-server returned 500: Failed to parse tool call arguments as
    JSON: parse error at line 1, column 7201: missing closing quote

That surfaced in the UI as "An internal error occurred", which is a
worse outcome than the cosmetic leak it was fixing.

The replay is now a short valid object naming the failure. The detail
the model needs is already in the tool result, and the fragment is not
worth resending: it is the content that overflowed the window.

Five parametrised cases pin the invariant that was missing, that
replayed arguments always parse, plus one that the replay stays small.
Checked against the broken version: all seven fail there.

The test that asserted verbatim replay is corrected rather than removed.
Its comment stated the same wrong premise, so both now record what the
assertion failed to consider.

* Studio: shorten the guidance, and give it one consistent rule

Reading every model-facing string in this branch side by side turned up
a contradiction it had shipped: the compacted-arguments placeholder
ended "read the file back if you need the content", while the edit_file
description says not to read back what you just wrote and both
no-progress notices say reading again will not help. Three lines
discouraging a re-read and one inviting it, and the re-read is the loop
that cost eighteen calls in a single turn.

Every one of them now says the same thing: continue from what you have,
in parts if it will not fit at once, and finish the task. Each is also
shorter, since they are spent out of the same window they are describing
(roughly 68 -> 32 tokens for the repeated-result notice, 68 -> 47 for
the starved one, 41 -> 27 for the placeholder).

The larger saving is not in those. Tool schemas go into EVERY prompt and
came to about 1351 tokens, a third of a 4096-token window before any
conversation at all. edit_file's description was 277 of it and is now
170, with every rule kept: batch into edits, match against the original
text, no overlaps, exactly one match unless replace_all, all-or-nothing,
do not read back. That is about 108 tokens returned on every turn.

Also fixed: thinking_exhausted_message read "spent its whole reply of
the 4096-token window on reasoning", from formatting a pre-spaced
fragment.

Four tests asserted the exact old phrasing. The meaning survives the
rewrite in each, so the assertions moved rather than the messages.

* Studio: continue a truncated answer in the final generation too

A live run spent 25 tool calls and 22387 tokens, hit the tool-iteration
ceiling, and then stopped on finish_reason length inside drawBird() with
the game half-written and nothing to recover it.

The continuation added earlier covers the generation INSIDE the tool
loop. At the iteration ceiling the loop breaks, appends the
budget-exhausted nudge, and runs a separate final generation after it,
which had no continuation at all. A turn that spends its whole tool
budget produces its answer there, so the one path most likely to be cut
off was the one path with no way back.

That generation is now wrapped in the same continuation, under the same
rules: the partial goes back through continue_final_message to be
extended rather than responded to, thinking is left as the caller set it
because thinking is not what ran out, an answer that is mostly an echo
of itself is left alone, and the whole thing is capped.

Four tests drive the final path directly, with max_tool_iterations = 0
so the tool loop cannot take the request first. Checked against a
disabled build: the two that assert the continuation fail there, and the
two that assert it stays out (clean stop, echo) still pass.

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

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

* Studio: address review findings on the small-window tool turn fixes

Backend:
- Rebind the assistant message after run-then-compact rebuilds the
  conversation, so a second call in the same batch is still visible to
  the model when its result arrives.
- Compact only the last call carrying an id. Parsers number from call_0
  on every turn, so rewriting every match relabelled an earlier call
  with a later one's outcome.
- Keep the arguments of a call that never ran. A tool reply proves an
  answer, not an execution, and the completed receipt claimed a write
  the user had declined.
- Word the receipt per tool. python, terminal and MCP calls write no
  file, so they no longer read as already written to disk.
- Build the malformed-arguments receipt from the same phrase, so a
  refused call is not replayed as having run.
- Continue a reasoning-only length stop in the final pass, which the
  in-loop continuation cannot reach, and say so when it never converges.
- Drop an explicit reasoning effort for a thinking-off continuation.
  For that style the effort wins, so the retry re-ran the failing turn.
- Give continuations their own loop credits instead of charging them to
  the caller's tool budget.
- Count the final continuation prompt before reopening the stream, and
  keep the partial rather than send a request that cannot be served.
- Replay only the new suffix on a final continuation, and fold each
  attempt's usage in before the next overwrites it.
- Replay the truncated answer unstripped so the continuation builds on
  the whitespace it was cut on.
- Price the result budget against the compacted prompt when the gate
  ran the call because compaction will make room.
- Use the conservative estimate at the admission gate so dense ASCII
  cannot skip the exact check.
- Key the no-progress guard on the arguments too, unless the result is
  a notice the window itself produced.
- Count repeated windows without overlap, so one long rule no longer
  reads as an echo.
- Detect a value cut mid-literal as truncation, and a complete document
  with trailing junk as not.
- Derive healing keys from the request's schemas as well, restoring
  auto-healing for single-string MCP tools.
- Offer a lever the refused tool actually has.

Frontend:
- Tell the Max Tokens wall from the context wall using the prompt count,
  so a cap the prompt left no room for is not blamed.

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

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

* Studio: keep a continuation inside the caller's budget and stop guessing disk state

- Respect an explicit max_tokens when continuing a truncated answer. A
  caller cap and the context wall both report finish_reason length, so a
  100-token request was continued twice into roughly 300. The retry now
  gets the remainder of the caller's budget, and an attempt that ended
  on length is charged its whole allowance when the server reported no
  usage. max_tokens unset, or equal to the window, is still the context
  wall the continuation exists for.
- Build the continuation as a candidate and commit it only once another
  stream is certain to run. The replay and the usage fold happened
  first, so a refused continuation reported roughly double the tokens
  it cost: the same usage went into the accumulator and then into the
  metadata event.
- Pair a tool reply with its own call site. Ids restart at call_0 every
  turn, so a conversation-wide set of answered ids let an earlier
  success vouch for a later declined call, which was then replayed as
  already written.
- Earn the file wording from the reply rather than the tool name. An
  edit_file that ran and returned an error is not a write, and a python
  or terminal call may well have created files, so both directions of
  the guess are wrong. Anything the reply does not settle gets a receipt
  that claims nothing about the disk.
- Require evidence a result was actually cut before saying so. The
  budget is what the window allowed, not what the tool returned, and a
  short complete result was being reported as nothing usable.
- Cap the edits array. Each entry rescans a file that may be 16 MiB, so
  an unbounded batch turns one call into gigabytes of scanning.

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

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

* Studio: re-baseline the refactor guard and drop an unused import

The guard pins the tool-call parsing stack by AST, runtime surface and a
digest of every guarded function's output. This PR adds six symbols to
tool_call_parser, so the inventories needed the snapshot the module's own
docstring prescribes. Two of the new notices take a result alongside the
tool name, which had no argument fixture, so the driver reported them as
undrivable rather than pinning them.

Audited rather than taken on trust: no existing digest changed, nothing
was removed from any inventory, and the only additions are the three new
guarded functions. The apparent deletions are entries re-ordered and
re-added with identical digests.

Also removes an import of re that this branch added to
tool_loop_controller and never used. Ruff does not reach it; the lint
job's import-hoist check does, and only for files a change touches.

* Studio: carry the continuation guards into the tool loop and compact on aggregate size

The previous round guarded the final generation pass. A request with
tools enabled takes the in-loop path instead, which had neither guard:

- Count the in-loop continuation prompt before retrying, and keep the
  partial when the retry would not be served. With a single user turn
  there is no older history to evict, so the retry was window-sized.
- Spend the caller's output budget across the whole reply rather than
  per attempt. The in-loop payload rebuilds max_tokens from the caller's
  value every iteration, so a request capped at 100 tokens ran two more
  100-token generations.

Also:

- Compact arguments on their aggregate size, not per string. A batched
  refactor of fifty 800-character edits is tens of thousands of
  characters with no single string over the floor, so nothing was
  reclaimed and the call stayed in the prompt for good. The final check
  that the receipt is smaller than what it replaces still applies.
- Word an elided old_string neutrally. Only new_string is on disk after
  a replacement; the completed phrase sent the model after content the
  edit had just removed.
- Reset in_thinking once a truncated reasoning block is closed. The
  thinking-off retry closed it a second time on its first content
  token, and the route showed the stray tag as answer text.
- Apply a lone replace_all without enumerating its matches. There is
  nothing to overlap with, so str.replace does it in linear space where
  spans cost a tuple per match. Entries inside a batch still need spans
  for overlap detection and are bounded instead.

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

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

* Studio: guard the reasoning retry too, and stop blaming a file for every tool call

The previous round guarded the in-loop partial-answer continuation. The
reasoning-only continuation beside it mutated the conversation directly
and checked neither thing:

- Count its candidate prompt before committing, and keep the thought
  when the retry would not be served.
- Spend the caller's cap across the whole reply here as well, and stop
  when it is gone.

Also:

- Compact the arguments of a call the user denied. The denial is itself
  the tool message that makes the template render the call it refused,
  so declining an oversized write cost the prompt the very arguments it
  declined to afford, and the bulk pass skips denials by design.
- Size a result against a prompt carrying the current call's stand-in
  reply. Templates that render a tool call only once a reply follows it
  were pricing the result without the arguments it sits beside.
- Keep the destination path out of the elision. It is the one field
  that says which file was changed, and the lower aggregate floor had
  started spending it.
- Repeat the path inside a receipt only when it is short. Every elided
  leaf embeds it, so a long path cost more than the content removed and
  the size check rejected the whole compaction.
- Blame a file only when a file is involved. An oversized python,
  terminal or MCP call was answered with advice to ask for a smaller
  file, which names the wrong cause and cannot be acted on.
- Treat a cap reached together with the context wall as context-bound.
  At equality raising Max Tokens creates no room, so the advice to do
  so is the one thing that cannot help.

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

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

* Studio: rebind to the current turn, neutralize the replay, and name the right wall

Three of these are defects in the fixes from the previous rounds:

- Scan backward when rebinding the assistant message after a compaction.
  Generated ids restart at call_0 every turn, so a forward scan bound the
  oldest turn carrying the id and the rest of the batch was appended to
  history instead of the live exchange.
- Rebind after compacting a denied call too. The denial path was added
  last round with the same detached-handle defect the executed path had
  already been fixed for.
- Neutralize a continuation candidate before counting and sending it.
  The first payload neutralizes every message; the replay put raw model
  output back, so a template delimiter inside printed code was read as
  chat structure, and the admission count described a different string
  from the one actually sent.

And three from elsewhere:

- Resolve the forced choice when a call is refused by the context gate,
  as a user denial already does. Left pending, the next iteration
  advertised the same tool as required and the model was pushed into
  the same call and the same refusal.
- Say so when a reasoning turn was stopped by the caller's own Max
  Tokens rather than by the window. The two have opposite levers, only
  one attempt ran, and this text reaches the client as ordinary content
  where the frontend's cap-aware error cannot correct it.
- Pass the local context length only for local requests. The resident
  GGUF window stays populated while an external model is selected, so
  an external request with a 16K cap was measured against an unrelated
  4096-token window.

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

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

* Studio: price both counts alike, bound the repetition scan, name the right lever

Six review items, four of them defects in earlier commits on this branch.

Argument compaction chose aggregate mode from the largest leaf, so one 1100-char
edit beside fifty 800-char ones stayed in per-leaf mode and compacted only the
first, replaying about 40 KB. Chosen from the total now, which is the shape a
batched refactor actually produces.

The result-budget rescue re-counted the prompt without the empty tool stand-in
the initial sizing uses. On templates that render a call only once a reply
follows, that dropped the pending call's own arguments from the count and handed
the room they occupy to the result.

The final-pass retry runs with thinking off but was admitted under the
thinking-on kwargs, pricing a prompt nobody sends. The kwargs are computed once
now and used for both admission and the request.

Final-pass exhaustion always blamed the context window. When a caller-set Max
Tokens is what was spent, it now says so, matching the fork the in-loop give-up
already made.

The repetition scan kept one 60-char slice per starting offset, so a very long
fragment held a large multiple of itself alive to decide one continuation. Keyed
by hash with a collision check and a ceiling on distinct windows; both directions
of the bound fail open.

The GenerationLengthError toast hardcoded the Max Tokens advice, overriding the
remedy the error had already chosen from the cap and the prompt size. It repeats
the message now.

Each fix has a regression test confirmed to fail without it. Affected backend
modules 457 passed, frontend 5647 passed, tsc and ruff clean.

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

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

* Studio: judge a continuation on its own attempt, and make room before giving up

Five review items.

A tool reply was paired with the OLDEST pending announcement of its id. Textual
parsers number from call_0 every turn, so an interrupted call leaves a stale site
under the same id: the reply marked the abandoned call executed and left the call
that actually ran replaying its arguments in full.

The in-loop retry was admitted under the previous attempt's thinking-on kwargs
even though it goes out with thinking off, which prices a request nobody sends.
The final pass already computed its own; this path now does too.

A continuation that did not fit ended the turn, so the next iteration's ordinary
preflight never got its chance to drop an older exchange. Under truncate_oldest
the candidate is now fitted once before being abandoned, to the room the
continuation itself needs rather than to the caller's cap: with a small
max_tokens the preflight target is larger than the window minus the reply floor,
so fitting to the caller's figure would evict and still leave it unservable.
Applied at all three continuation sites.

has_content_tokens and _last_emitted are cumulative across attempts by design, so
a continuation that produced nothing but reasoning was classified as another
truncated visible answer: it replayed an empty suffix with thinking still on
instead of taking the reasoning-off recovery. Each attempt is now judged on what
it put on screen itself. Because content events are cumulative, the give-up no
longer sends its explanation on its own once an earlier attempt has written an
answer, which would have replaced the answer with a message about not having one.

Reaching either give-up by exhausting the retry limit left the cap
classification at its default, so a turn whose last permitted attempt finished
off an explicit Max Tokens was told to raise the Context Length. Both sites
re-read the remaining cap.

Each fix has a regression test confirmed to fail without it, except the one
guarding the answer against being overwritten, which guards behaviour the
per-attempt change made reachable. Affected backend modules 590 passed, ruff
clean.

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

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

* Studio: price a continuation as one, and give the safety tests their guards back

Three review items.

The in-loop answer continuation is sent with continue_final_message, which
renders without a generation prompt and with the partial as the turn being
extended, but the admission counted it as an ordinary prompt. The flag is
threaded through _loop_continuation_fits now, and the eviction retry added
alongside it uses the same flag.

Two edit_file safety tests still called execute_tool directly with the top-level
old_string and new_string shape. That shape is refused outright now, and the
refusal starts with "Error:" like the failures they were asserting, so
test_full_access_does_not_replace_a_device_node and
test_a_failed_create_removes_the_partial_file passed without reaching the
device-node guard or the simulated ENOSPC cleanup. Both now send edits, and both
assert the message their own guard produces rather than any error, so neither can
go green again on a malformed call.

Cap attribution passed a null context length for a local safetensors or MLX
request on the legacy stream path, where neither GGUF field is set. A null window
reads as infinite, so every context-length stop was reported as a Max Tokens stop
and the user was told to raise a value already at the model's maximum.
params.maxSeqLength is added last and coerced from zero, the same order the RAG
context_length beside it already uses.

Each fix has a regression test confirmed to fail without it. Affected backend
modules 591 passed, frontend 5648 passed, tsc and ruff clean.

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

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

* Studio: fix the AttributeError that 500s every planned GGUF load (#9821)

* Studio: fix the AttributeError that 500s every planned GGUF load

_planned_tensor_spill read the host-RAM headroom as

    host_ram_headroom_bytes = self._HOST_RAM_HEADROOM_MIB * 1024 * 1024

copying the shape of _PIPELINE_PER_DEVICE_OVERHEAD_MIB on the line directly
above it. That one is a class attribute (llama_cpp.py:9597). The headroom is
module-level (llama_cpp.py:4721), so it is not reachable through self, and every
load that got as far as the planning call raised

    'LlamaCppBackend' object has no attribute '_HOST_RAM_HEADROOM_MIB'

and came back to the client as a 500. Since #9779 the planner is default-on, so
this is on the path of every GGUF load, not an opt-in one.

Observed loading unsloth/Qwen3.8-Flash-Next-GGUF UD-IQ1_S on a Colab T4 high-RAM
VM: llama-server never spawned and the load returned 500.

The seam suite stayed green through all of it because the _Stub double declared
_HOST_RAM_HEADROOM_MIB = 2048 itself, so the lookup found it on the double and
never on the class under test. Dropping that line from the double is most of the
fix here: with it gone and the source left unpatched, 66 of the 127 seam tests
fail. A named test also asserts the double declares no attribute the real class
lacks, and that the seam source no longer reaches for this one through self.

* Tighten the comments on the host RAM headroom fix

* Tighten the comments this PR added (#9825)

Post-convergence comment pass over the 3,346 comment lines this branch
adds across 27 files. 810 lines out, 609 back: every block keeps the fact
that made it worth writing and drops the paragraph restating it.

What stays, deliberately. The measured figures (2296 MiB reserved against
1008 MiB allocated; 1039 -> 2105 MiB at 4k), the upstream citations
(fit.cpp:463, llama_init_from_model(model_tgt), server-context.cpp gating
on a non-empty mmproj.path, common_prompt_checkpoint on the host heap),
and the "what this looked like when it was wrong" clause on each. Those
are the parts a reader cannot reconstruct from the code.

What does not change. The estimate-memory path operation's docstring is
untouched: FastAPI renders it as the route's OpenAPI description, so
editing it is an API change rather than a comment change. The class
docstrings in test_memory_estimate.py are untouched too -- each carries a
distinct account of the defect its tests exist for, and at that density
the next cut removes a fact.

AST-gated throughout: comment_tools.py check 17/17 with
--strip-docstrings, and prepush_gate.py --comment-only against the
pre-pass head. Backend 909 passed, frontend 5331 passed, typecheck clean.

* Fix the studio PEP 604 union ratchet and name what breaches it (#9826)

* Fix the studio PEP 604 union ratchet and name what breaches it

main is red on Core and Python 3.13:

  AssertionError: 37 studio files now evaluate PEP 604 unions on the floor,
  up from 35.

#7880 added studio/backend/tests/test_kv_cache_estimate_compat.py and
test_kv_cache_estimate_route.py, which annotate with Path | None, str | None
and int | None but carry no `from __future__ import annotations`. requires-python
is still 3.9, where those evaluate to a TypeError at import.

The ratchet is right and the new files are the thing to fix. The debt it tracks
is FastAPI routers and pydantic models, where the future import has real failure
modes around class dependencies; these two are plain test modules with no such
constraint, so they take the import and the count returns to 35. Raising the
ratchet instead would bank the debt for no reason.

Also make the next breach diagnosable. The check stored a bare count, so the
failure said only that 37 exceeded 35 and then printed all 37 truncated at 2000
characters. Finding the two additions meant re-running the scan against an older
checkout and diffing by hand. It now stores the SET and reports the difference:

  37 studio files now evaluate PEP 604 unions on the floor, up from 35. Add
  `from __future__ import annotations` to these, do not raise the ratchet:
    studio/backend/tests/test_kv_cache_estimate_compat.py
    studio/backend/tests/test_kv_cache_estimate_route.py

The count still governs the assertion, so one file fixed and another added
cannot pass on set membership alone, and a file that stops offending is named
too so the list can shrink.

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

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

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Studio: keep the memory row readable on a narrow panel (#9824)

* Studio: keep the memory row readable on a narrow panel

The model config panel is w-[min(468px,calc(100vw-1rem))], so once the window
is under about 460px it shrinks with the viewport. The Estimated Memory Usage
header is the only row carrying a title and two figures at once, and the
figures do not shrink, so the title absorbed the entire shortfall: measured on
the current build it went from 150px at 460px wide to 91px at 400, 51px at 360
and 11px at 320, where it rendered as "E...".

Let that header wrap. The figures drop to a line of their own only at the
widths where they would not have fitted beside the title anyway, and ml-auto
keeps them under the right edge they already had, since justify-between has
nothing to push against on a line holding one item. At 460px and above the
layout is unchanged.

The breakdown captions had a smaller version of the same problem: "f16 .
262,144 tokens . 4 slots" broke at whatever space fitted, which left the word
"slots" alone on a line under "... tokens . 4". Gluing each item together with
U+00A0 leaves one break opportunity per bullet, and gluing the bullet to the
item that follows it puts the break before the bullet rather than orphaning it
at the end of the previous line. Measured in the real 183px caption column,
the final line goes from a 22px fragment to the whole 38px item.

* Leave an unseparated breakdown note breakable

Only the KV caption is a list. The Weights and Draft cache notes are ordinary
prose ("256 of 257 layers on GPU", "2.14 GB on GPU"), and passing those through
glueNoteItems replaced every space with U+00A0, leaving them zero break
opportunities. On a narrow panel, or at an enlarged browser font, that made
them a single unbreakable run that overflows the caption column instead of
wrapping inside it, which is worse than the orphaned word the function exists
to prevent.

Return a note with no separator untouched. There are no items to keep apart, so
gluing bought nothing and cost every break the note had.

---------

Co-authored-by: danielhanchen <[email protected]>

* route thinking controls to ollama

* Studio: expose Thinking for Ollama and forward reasoning_effort

Ollama connections had no reasoning capability, so Studio hid Thinking
and never sent reasoning_effort. A reasoning model then kept its default
thinking with no way to turn it off (#9649).

Flag the connection as a reasoning model to show Thinking, then map
off/on onto Ollama's OpenAI-compat reasoning_effort field.

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

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

* Studio: pin Ollama thinking per model and keep research Thinking off

Ollama connections can serve mixed catalogs, so the reasoning-model toggle
now stores which model ids support thinking. Unmarked models no longer
advertise Thinking or send reasoning_effort. Deep Research serializes
reasoningEffort "none" when Thinking is off so Ollama does not fall back
to the model's default.

* preserve ollama max reasoning effort

* fail closed on malformed reasoning pins

* prune stale ollama reasoning pins

* name ollama reasoning model controls

* isolate ollama reasoning request tests

* align reasoning regression test style

* keep ollama gpt-oss reasoning enabled

* gate research reasoning on model support

* match ollama reasoning pins case insensitively

* reset reasoning state on provider changes

* remove ollama reasoning ui

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Maheswar Kumar <[email protected]>

* Read the memory row's captions past their line-breaking glue (#9831)

The breakdown captions now join their items with U+00A0 so a narrow panel breaks
between "262,144 tokens" and "4 slots" rather than inside either. The scene
asserts on the caption with a plain `"6,144 tokens" in text`, which stopped
matching: the figure was correct on screen and in the response, but the space
between it and "tokens" is no longer a space.

Normalise the glue back to ordinary spaces in the two inner_text readers, so
every assertion reads the caption the way it looks rather than the way it is
encoded. Verified against the exact strings CI reported.

Co-authored-by: danielhanchen <[email protected]>

* Studio: persist model disclaimer across instances (#9835)

* Studio: persist model disclaimer across instances

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

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

* Studio: invalidate queued preference reads

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Studio: consolidate the two memory-estimate stacks (#9830)

* Studio: freeze both memory-estimate route contracts before consolidating

/api/inference/estimate-memory and /api/models/kv-cache-estimate already share
the _gguf_memory_breakdown planner, so their arithmetic cannot drift, but their
response contracts are still separate and are about to be consolidated onto one
implementation.

The hazard is not shape drift, which a typechecker catches. weights_bytes exists
on both routes, is an int on both, and means different things: every resident
file on the inference route (weights plus projector plus drafter), the quant
file alone on the models route, where the planner aggregate travels separately
as gpu_bytes / total_bytes / gpu_floor_bytes. Unifying the key changes the
number under whichever caller loses, with no JSON change for a client to notice.

These tests pin both envelopes and that collision, so the consolidation cannot
silently resolve it. The models route has no response_model at all, so nothing
else enforces its shape.

Verified by mutation rather than by passing: adding a key, removing a key,
repointing weights_bytes at the planner aggregate and disabling the delegation
each fail the suite. The first draft did not catch the aggregate swap, because
the planner delegation is gated on _cached_estimate_config resolving the repo to
this disk and is skipped for a synthetic repo id, leaving every planner field
present and null. A freeze written over that fixture asserts nothing. Pinning
the config so the planner returns real figures is what makes these bite.

* Studio: give both memory-estimate routes one canonical contract

The two routes already share the _gguf_memory_breakdown planner, so their
arithmetic agrees. Their vocabulary did not, and the sharp edge is weights_bytes:
it exists on both, is an int on both, and means every resident file on
/inference/estimate-memory but the quant file alone on /models/kv-cache-estimate.
Nothing in the type system separates those, so a caller reading the wrong one is
simply wrong, quietly.

Adds models.inference.MemoryEstimate as the shared contract. It deliberately has
no weights_bytes at all: the name is replaced by quant_file_bytes and
resident_files_bytes, which each say which they are, and it is absent rather
than redefined so no new reader can pick it up and guess.

core/inference/memory_contract.py holds the projections back onto each route's
existing wire shape. Both legacy mappings now sit side by side in one file,
which is the only place either is written down, instead of being implied by two
handlers that never referenced each other.

/kv-cache-estimate is rewired onto the projection and its JSON is unchanged,
which the contract-freeze suite from the previous commit verifies rather than
assumes. Two subtleties it caught while this was being written:

- gpu_bytes must keep 0 distinct from None. Zero is a real answer, an inherited
  LLAMA_ARG_DEVICE=none launch that touches no card; None means the planner
  never ran. The first draft applied `or None` uniformly and reintroduced a bug
  this route had already fixed. MemoryEstimate.gpu_bytes is Optional for that
  reason.
- the quant figure is not clamped against the resident total, though a quant
  file cannot really exceed the files containing it. The two come from different
  resolvers, and clamping truncated a 4.1 GB quant to a 373 byte synthetic
  header rather than catching anything.

kv_bytes is passed into the projection rather than read off the estimate: this
route prices the target cache itself and the planner's figure is not
interchangeable with it.

* Studio: route the Load Model estimate through the shared contract too

/inference/estimate-memory now builds the same canonical MemoryEstimate that
/models/kv-cache-estimate builds, and projects back to EstimateMemoryResponse.
Both routes go through one vocabulary; neither wire shape changes.

weights_bytes keeps its aggregate meaning here through
project_estimate_memory_response, which is the counterpart of the quant-file
mapping the sibling route uses. The two sit next to each other in
core/inference/memory_contract.py so the difference is impossible to read past.

quant_file_bytes is 0 on this route rather than a stand-in. This handler is
given a resolved config and prices what the launch would hold, so nothing in it
measured the single file the user picked; the legacy response does not carry the
field, and inventing a value would be a wrong number for the sake of a non-null.

* Studio: one presentation core for both memory surfaces

The Load Model panel and the Hub memory bar were fed byte-identical figures by
one backend planner and still disagreed about how to present them, in every
category that decides what a user reads: unit labels, rounding, fit thresholds,
the fraction of a card a load may claim, and the verdict vocabulary itself. Each
difference was defensible alone. Together they meant one model could read as
fitting on one screen and not on the other.

src/lib/memory/ now holds the shared core:

- format.ts. There were two exported functions called formatMemoryGb, one per
  surface, both (number) => string, one taking bytes and one taking gibibytes,
  printing different labels. Importing the wrong one was off by 1024^3 and
  typechecked cleanly. They are replaced by formatGiB and formatBytesGiB, whose
  names carry the unit, plus formatKvRate.
- thresholds.ts. The fit ratio and the pressure ramp measure different things
  and keep different values, but they now differ in one file rather than per
  surface.
- verdict.ts. A superset vocabulary, not a winner: the panel's tight band and
  the bar's why-it-exceeds cause both survive, so neither surface loses a
  distinction it used to make.

memory-fit.ts and model-memory.ts stay as each surface's entry point and become
thin re-exporters, so no call site moves. memory-fit.ts keeps relative imports
with explicit extensions rather than the @/ alias: three tests load it directly
under node --experimental-strip-types without a bundler resolver, and an alias
there breaks all three. Its docstring said "no imports" and meant no ALIAS
imports; that is now written down.

Two user-visible labels change, both mislabels rather than preferences:

- the panel printed GiB values labelled GB across seven figures, the defect
  #9570 fixed elsewhere. vram-total-gib-suffix.test.ts could not see it, since
  its regex only matches interpolations naming a *TotalGb and neither module
  was in its list. That guard now reads the shared module, covers all three
  formatters including the panel's, and separately asserts neither surface has
  redefined one locally.
- formatKvRate divided by 1024 and labelled the result KB/MB.

Existing assertions were updated to the new expectations rather than relaxed,
and two fixtures were retuned rather than left passing: at the wider budget the
speculative-reserve case no longer tipped over, so it would have gone green
while measuring nothing.

* Studio: decide unified memory from the hardware, not from the platform

The Load Model panel asked usePlatformStore(s => s.appleSilicon) whether the GPU
and the rest of the system share one memory pool, and passed that answer to
resolveMemoryCapacityGb. On a ROCm APU the answer was false, so the panel
charged one pool as discrete VRAM PLUS host RAM: the same bytes counted twice,
and a ceiling high enough to report a fit for a load that cannot open.

The correct signal already existed. use-gpu-info.ts derives unifiedMemory from
the backend's per-device unified_memory flag, which the ROCm probe sets, and the
Hub memory bar already abstains on exactly that flag. Only the panel was reading
the platform instead of the hardware.

The two uses are now separate rather than renamed wholesale, because they are
genuinely different questions:

- isAppleUnifiedMemory still drives the WORDING. "Unified" is what Apple calls
  its pool; an AMD APU's is a "Shared" one, and the panel already prints both.
- hasUnifiedMemory drives the CAPACITY, and falls back to the Apple check while
  the device probe is in flight, so it is never a weaker answer than before.

A discrete card is unaffected: its devices do not report unified_memory, so
nothing about an ordinary NVIDIA host moves.

Covered by tests on resolveMemoryCapacityGb for the APU pool and for a discrete
card, plus a source assertion that the panel hands the capacity call the general
signal. That last one is not decoration: the behavioural tests pin what the
resolver does with each flag, not which flag it is given, and they both pass on
the unfixed panel. Verified by reverting the fix and watching only the source
assertion fail.

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

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

* Studio: harden the memory contract and pin it across the platform matrix

Adversarial pass over this PR's own changes. Three real defects, two of them
mine, plus a simulation matrix that would have caught all three.

Fixed, introduced by this PR:

- routes/models.py assigned gpu_bytes, compute_bytes, total_bytes and n_ctx onto
  a MemoryEstimate AFTER building it. Pydantic does not validate assignment by
  default, so a post-construction write puts whatever it is handed straight onto
  the wire. Measured rather than assumed: on pydantic 2.13
  m.gpu_bytes = "not an int" succeeds, and a declared int field accepts None the
  same way. Those four are now parameters of build_memory_estimate, so the model
  is built once and validated once. gpu_bytes needs a sentinel rather than a None
  default because it has three states: a number, a real None meaning the planner
  never ran, and "use the breakdown's".

Fixed, pre-existing but in scope because it made the two surfaces disagree:

- computeModelMemory turned a non-finite weightsBytes into "model-exceeds": a
  full destructive bar reading "Larger than VRAM" beside a weights figure of
  "0 GiB", because the formatter clamps what the verdict did not. JSON.parse
  turns 1e999 into Infinity, so a malformed response reaches it without trying.
  classifyMemoryFit on the panel already answered "unknown" for the same input,
  which is the divergence this PR exists to remove. Null and undefined are
  untouched: those mean "has not arrived", an ordinary state.

New simulation coverage:

- memory-cross-surface-matrix.test.ts: [linux, wsl, win32, darwin] x nine device
  inventories (NVIDIA single and dual, ROCm discrete, ROCm APU, AMD Vulkan iGPU,
  Intel iGPU, Apple unified, mixed dGPU+iGPU, CPU only) x four footprints, minus
  the physically impossible cells, checked against six properties: no false fit,
  no bar/panel contradiction, one label per byte count, no pool counted twice,
  CPU-only draws nothing, and no NaN or Infinity reaching a label. 128 cells.
  The Infinity defect above is what P-hostile found.
- test_memory_contract_platforms.py: the same four platform keys x six
  placements, pinning that both wire shapes are byte-identical everywhere and
  that weights_bytes keeps its own meaning per route in every cell.
- Old-backend degradation: a backend that never sends unified_memory leaves
  hasUnifiedMemory exactly equal to the appleSilicon check it replaced, in both
  directions.

Verified in a clean uv venv holding only pytest, pydantic, fastapi, structlog,
huggingface_hub, psutil, pyjwt, passlib, bcrypt and cryptography: 710 passed. The
only two failures there need the real transformers package and pass with it.

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

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

* Studio: scope unified memory to the pin, and share one budget with the fit badge

Two P2 review items, both reproduced before agreeing.

1. The unified-memory flag was host-wide. inferenceGpu.unifiedMemory is
   devices.some(...) over the whole inventory, so an APU beside a discrete card
   made it true, and a pin naming ONLY the discrete card then told
   resolveMemoryCapacityGb the two are one pool. Measured on a 16 GiB pin with an
   APU present and 128 GiB of RAM: totalCapacityGb collapsed from 143.52 to 15.52
   GiB, so the panel warned "more than this machine holds" for a load that fits
   comfortably. That is a regression this branch introduced; on main the flag was
   the Apple check and read false there.

   hasUnifiedMemory now narrows to the pinned devices before asking, falling back
   to the whole inventory when nothing is pinned. The Apple check stays host-wide
   and unconditional: there every device really is the one pool, and it also
   covers the window before the per-device probe lands. SystemGpuDevice carries
   unifiedMemory per device for this, alongside sharedMemory, which is per device
   for the same reason.

2. The Hub fit badge and the memory bar render on the same row and judged against
   different budgets: gguf-fit.ts held 0.90 while the bar used the loader's own
   0.97. gguf-fit now re-exports the shared constant.

   Worth being exact about what that buys, because the review item claims it
   removes the contradiction and it does not. Measured over 15-24 GiB on a 24 GiB
   card, badge-vs-bar disagreements go from 11/19 sizes to 8/19. The residual 8
   are the ESTIMATOR difference: gguf-fit scores size * 1.15 + 1 GB while the bar
   uses the planner's real figures, so no constant can reconcile them. Rewiring
   the badge onto the planner is a separate change with its own blast radius,
   since it also drives a filter.

Frontend: 5677 passed, typecheck and build clean.

* Do not treat a mixed GPU selection as unified memory

Scoping the unified-memory flag to the pinned devices fixed the
discrete-only pin, but the quantifier was still `.some()`, so a set
holding one APU and one discrete card read as a single pool. That is
every unpinned load on such a host, and any pin naming both.

Measured on a 48 GiB APU beside a 16 GiB discrete card with 128 GiB of
system RAM:

  unpinned, .some()   gpu 62.08  total  62.08  singlePool true
  unpinned, .every()  gpu 62.08  total 128.00  singlePool true
  pin both, .some()   gpu 62.08  total  62.08  singlePool true
  pin both, .every()  gpu 62.08  total 143.52  singlePool false

One device with its own memory means there is real VRAM beside system
RAM, so the two are not one pool and the RAM must not be discarded.

`[].every()` is true, so a host with no probed devices would read as a
unified-memory machine; guarded explicitly rather than relying on the
caller never passing an empty set.

use-gpu-info.ts deliberately keeps `.some()`. It answers a different
question, whether the host has any unified-memory device at all, and is
noted as such so the two are not "fixed" into agreement later.

* Correct the memory-estimate scene's unit mirror to GiB

The Playwright scene builds its expected strings with a Python mirror of
the panel's formatter, and that mirror printed "GB" because the panel
did. Both divided by 1024**3 and both called the result a decimal
gigabyte, so the test agreed with the app about the wrong label and the
agreement was what made it invisible.

Staging CI caught it on this branch:

  row header text: 'GPU 4.75 GiB  Total 5.50 GiB'
  FAIL: the row does not show the returned total '5.50 GB'

Every figure is byte for byte what it was. Only the unit moved, which is
the change this branch makes to the panel, so the mirror moves with it.

* Separate the unified pool's size from the fact that it is one pool

`unified_memory` on the wire is ROCm-only: hardware.py sets it from
`_rocm_known_unified` and nothing produces it for Apple. So the panel's
general signal is Apple-or-ROCm, and it was feeding a resolver branch
whose comment reads "Apple reports the one pool as the GPU budget
already". True for Apple, where memory_total_gb is the machine's unified
memory. False for a BIOS-carved window onto system RAM.

Measured on a 96 GiB machine carving a 48 GiB window, budget 0.97:

                      gpu     total    singlePool
  Windows  unified=F  46.56    96.00   true
  Windows  unified=T  46.56    46.56   true
  Linux    unified=F  46.56   142.56   false
  Linux    unified=T  46.56    46.56   true

Both are wrong on Linux and in opposite directions. Before this branch
the ceiling double counted the window that already sits inside the RAM;
after it, the ceiling discarded 49.44 GiB the load can really use, and
the panel warned that a 60 GiB load exceeds a machine holding 96.

The backend has said which figure is real all along, in
llama_cpp.py::_available_system_memory_mib: "On a unified-memory APU
this, not the ROCm-reported VRAM, is the real ceiling: the weights load
into shared system RAM."

`unifiedMemory` still classifies the pool. A new
`unifiedPoolReportedAsGpuMemory` says whether the GPU figure is that
pool's size. The ROCm case falls into the existing
`Math.max(gpuCapacityGb, systemRamTotalGb)` branch the Vulkan iGPU
already used for this exact reason rather than into new arithmetic.

The flag defaults to true, so callers written before the ROCm case keep
their answer untouched. Apple is deliberately not routed through the RAM
branch: max(93.12, 96) would return the raw 96 and drop the VRAM Budget.
Both are pinned as tests, and both new tests were confirmed to fail
against the unfixed resolver.

Score the Hub fit badge against the saved VRAM Budget

Sharing one default constant fixed the loading and old-backend case. It
did not reach the case where the user has actually saved a fraction: the
badge kept applying 0.97 while the memory bar on the SAME ROW consumed
the live value from use-model-memory.ts.

On a 24 GiB card with a saved 0.90 the loader admits at 21.6 GiB while
the badge scored against 23.28 GiB:

  size    required   badge      [email protected]
  18.0    21.70      fits       OVER
  18.5    22.27      fits       OVER
  19.0    22.85      fits       OVER

`GgufFitInput` takes an optional `budgetFraction`, and the Hub card
reads the live value through a new `useVramBudgetFraction`. It is
threaded into all three fit-scoring calls on the row, not only the
badge: the sort and the menu use the same classifier and would otherwise
rank rows against a line the badge no longer applies.

Absent means "use the shared default", not "the whole card": scoring an
unloaded fraction against 1.0 admits loads the loader refuses, which is
the same error in the other direction. Zero, negative, above-one and
non-finite values fall back too, since this arrives from a settings
route; 1.0 is honoured, being a legitimate saved value.

The hook is the fifth caller of subscribeVramBudgetSettings plus
loadVramBudgetSettings and the first not to roll the pattern by hand. It
subscribes before loading, so a save committed while the GET is in
flight is not lost.

Frontend suite 5685 pass, 0 fail; typecheck and build clean.

* Do not count a Linux APU's window as VRAM beside system RAM

Third face of one reporting split, exposed by the previous two fixes.
hardware.py sets shared_memory only on Windows, so the same APU arrives
as shared_memory true there and unified_memory true / shared_memory
false on Linux. Making a mixed set non-unified correctly routed the
ceiling to `dedicatedCapacityGb + systemRamTotalGb`, and `dedicated` was
computed from sharedMemory alone.

A 48 GiB APU beside a 16 GiB discrete card on a 128 GiB host at 0.97:

  before  total = 190.08 GiB
  after   total = 143.52 GiB   (16 * 0.97 + 128)

46.56 GiB of capacity that does not exist, in the direction that admits
a load.

The two flags are folded where they are read rather than the capacity
path learning about a second one: they answer the same question, and the
split is a platform reporting detail, not a distinction the arithmetic
should carry. SystemGpuDevice already grew unifiedMemory earlier in this
branch and satisfies MemoryCapacityDevice structurally, so the panel
carries it through with no call-site change.

A test asserts Windows and Linux now price the same APU identically,
which is the property that matters: if those diverge again, one platform
charges differently for the same silicon.

Credit the VRAM budget, not the raw card, once layers spill

vram_budget_settings.py describes the reserve as "a slice of every card
that the model and KV cache may not use", so the GPU's contribution to a
partly offloaded load is the budget. Adding the raw card to the RAM
allowance invented capacity the loader will not give.

At the legal minimum 0.80 on a 24 GiB card with 16 GiB of RAM:

  budget 19.20   combined raw 32.00   combined@budget 27.20

  size  required   before     after
  23    27.45      partial    oom
  24    28.60      partial    oom
  25    29.75      partial    oom
  26    30.90      partial    oom

Four quant sizes the badge and the fit sort recommended for a card that
cannot load them.

`marginal` deliberately keeps the raw card. `fits` returns for
everything at or under the budget, so scoring this band against the
budget too would make it unreachable; it names the gap between the
budget and the card, which is a warning rather than a claim of
admission. A test pins that it stays reachable.

Frontend suite 5689 pass, 0 fail; typecheck and build clean. Both fixes
were confirmed to fail their new tests when reverted.

* Carry the saved budget and the unified pool to every surface

Three consequences of the previous two rounds, each on a surface the
earlier fix did not reach.

Local On Device card ranked against the default budget. The live
fraction went to the Hub download card's three fit-scoring calls and not
to sortLocalGgufVariants, so that card rendered a memory bar using the
saved fraction directly above a quant menu ranked against 0.97.

Free capacity answered a whole-load question with a carved window.
resolveMemoryFit sends the WHOLE load to freeGpuCapacityGb as soon as
the pool is single, and marking a ROCm APU single-pool is what this
branch did, so a 60 GiB load on a 96 GiB machine with 60+ GiB free was
warned as not fitting a 48 GiB window. A non-Apple unified pool now
takes the host view, the same discriminator the capacity side uses, so
the two cannot answer differently. FreeVramDevice also folds
unifiedMemory the way MemoryCapacityDevice does; measured, that changes
nothing for an APU beside a discrete card (52.08 either way, since a
fully shared device already contributes its free once) and matters when
a SECOND view of the same pool appears, an APU beside a Vulkan iGPU:
77.12 -> 38.56.

One GET per mounted card. loadVramBudgetSettings has no read-through
cache by design and clears its shared promise once each request settles,
so it coalesces only overlapping callers; a catalog mounting cards
through scrolling and filtering issued a settings GET per card, and a
404 per card on an older backend. The FRACTION is now cached module-wide
and kept live by the change event every reader already subscribes to,
while the loader keeps its always-refetch behaviour for the callers that
need reloadRequired.

usableSystemRamGb was computed inline in JSX and is now hoisted, because
the free-capacity memo needs the same figure and two copies of the same
headroom subtraction is how they drift.

Frontend suite 5694 pass, 0 fail; typecheck and build clean. Each fix
was confirmed to fail its own test when reverted; one first-draft test
asserted a double count that does not occur and was replaced with the
case that does.

---------

Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* fix(prompt storage): rework prompt storage into a master-detail layout (#8692)

* Studio: rework prompt storage into a master-detail layout

Cards rendered the full prompt body with no truncation, so a few dozen
saved prompts became a long scroll of uneven cards. Editing happened
inline in a four-row textarea, so long prompts were edited through a
peephole while the list shifted underneath.

Replace the flat list with a master-detail layout: a compact rail of
name plus one-line preview on the left, and a detail pane on the right
that owns its height. Unsaved edits are held per entry so switching
rows no longer discards them, with a dirty marker in the rail and
Save/Revert in the footer.

List items now auto-size to their content and reorder by dragging the
grips, animated with FLIP. The drag listener lives on window rather
than using setPointerCapture: reordering makes React move the row's DOM
node, and detaching implicitly releases pointer capture, which ended
the drag after one row. Hit-testing uses offsetTop/offsetHeight since a
client rect reports the pre-animation position while FLIP is in flight.

Add a Preview toggle on both tabs backed by the existing
MarkdownPreview, and allow bookmarking prompt lists into the + menu
next to bookmarked prompts. Rows there carry a Prompt / List pill,
since selecting a prompt fills the composer while selecting a list
queues and sends every prompt in it.

Presentation only: no schema migration, no API change, no change to the
export formats or import parser, and onUse/onRunList signatures are
unchanged.

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

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

* Studio: address review feedback on prompt storage

Select a newly created prompt or list only after the refresh resolves.
The keep-a-row-selected effect runs against whatever list is in state,
so selecting the new id while the old list was still in state made the
effect bounce the selection to the first existing entry, and the new
entry was never shown.

Let the body shrink and stack on small viewports. The fixed 420px floor
plus the header could exceed the dialog's 94dvh on a short window and
clip the detail pane's actions behind overflow-hidden, and a fixed
248px rail left the detail pane unusably narrow below ~600px. The floor
is now capped against the viewport, the rail narrows at sm and stacks
below it, and the action rows wrap.

Report when a list cannot be queued. startQueue refuses synchronously
when queueing is unavailable and does not run the onAborted callback,
so running a list from the project new-chat composer silently did
nothing from both the Run button and the bookmarked-list menu items.

* Studio: auto-scroll the prompt list while dragging

A list taller than the detail pane could only be reordered within the
visible region: the pointer handler hit-tested coordinates but never
scrolled the overflow-y-auto ancestor, and pointerdown suppresses the
browser's own drag gesture, so there was nothing to pull the list along.

Holding a grip near the top or bottom edge now scrolls the pane and
re-runs the hit-test each frame, so a drag can reach any row. The step
ramps with depth into the edge band and is capped per frame.

The step calculation lives in its own module with unit tests covering
the dead zone, both directions, the ramp, the cap, and panes too short
to hold two edge bands.

* Studio: clear the search when selecting a newly created prompt or list

Awaiting the refresh was not enough on its own. With a search active
that the new entry does not match, the refreshed rail still excludes it,
so the keep-a-row-selected effect bounced the selection to the first
row that did match and the form closed on someone else's prompt.

Clear the search alongside the selection so the new entry is eligible
for the filtered rail. Applies to both create forms.

* Studio: remeasure auto-grown textareas on resize, and end a drag released off-window

The auto-sizing textarea only remeasured when its value changed, so any
width change that rewrapped the text left the old height in place. With
overflowY set to hidden that clipped the newly wrapped lines until the
next keystroke. It now remeasures on window resize, and on a
ResizeObserver width change for the cases where the column moves without
the window doing so.

The grip deliberately does not capture the pointer, so releasing the
mouse outside the window delivered neither pointerup nor pointercancel
and the drag stayed live, still autoscrolling and reordering. A move
reporting no buttons held is now treated as the release that was missed,
and window blur ends the drag for a release that happens entirely off
the page.

* Studio: export the visible draft, and ignore non-primary presses on grips

Export passed the saved entry while the pane could be showing unsaved
edits, so the downloaded file silently disagreed with what was on
screen. It now exports the draft when there is one, normalised the way
saving would normalise it, for both prompts and lists.

A right- or middle-press on a reorder grip started a drag, and the
zero-buttons recovery could not end it because buttons reads 2 or 4, so
opening a context menu over a grip could reorder the list. Reordering
now starts only on a primary press; touch and pen contacts report button
0 so they still drag, and isPrimary keeps a second finger from starting
a competing drag.

* Studio: run the visible list draft, scope drags to one pointer, keep new-entry drafts

Run queued entry.items while the editor could be showing something else.
Worst case, deleting every draft item left the button enabled off the
stored length and silently ran the whole old list. Run now fires the
visible non-blank items and disables on those.

The window-level drag listeners saw every pointer on the device, so a
second finger's movement reordered using its own clientY and its release
ended the firs…
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.

1 participant