Skip to content

feat(chat): admit media turns to durable runs; refusal is a toggle now - #10406

Closed
CelesteHeartsong wants to merge 41 commits into
unslothai:mainfrom
CelesteHeartsong:feat/durable-media-turns
Closed

CelesteHeartsong wants to merge 41 commits into
unslothai:mainfrom
CelesteHeartsong:feat/durable-media-turns

Conversation

@CelesteHeartsong

@CelesteHeartsong CelesteHeartsong commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

TL;DR

Media turns ride durable runs by default; the refusal is a toggle now, not a rule. Stacked on #10365 — this branch is that branch's tip plus ONE commit (studio: admit media turns to durable runs; refusal is a toggle now, not a rule); everything above it belongs there. It retargets onto main by rebasing --onto main once #10365 lands.

What

The media turn stops being forced onto the subscriber-owned (cancel-on-disconnect) stream: it rides the durable path like text, and the attachment still travels scoped to THIS turn's message only. The refusal survives as UNSLOTH_STUDIO_DURABLE_MEDIA_TURNS=0, and with the toggle off the backend 400 degrades silently through isLegacyFallbackChatGenerationAdmissionError exactly like a refused tool turn — the frontend gate no longer keys on media at all.

Why the default flipped

Replay fidelity killed the old "no replayable transcript" argument: #10365's parts accumulator replays persisted frames faithfully, so once generation starts the client contributes nothing, screenshot included. The residual cost is only the blob — it rides along verbatim in request_json beside the thread's own copy of the message. That trade is a toggle now so review can settle the default without a revert.

Tests

Accept-by-default / toggle-off-rejects pairs: the media refusal test became an accept/reject pair (durable-gate.test.ts, test_chat_generation_runs.py), green on the rebased branch alongside the full frontend suite.

@danielhanchen

Copy link
Copy Markdown
Member

Repo tests (CPU) is failing on test_base64_media_turns_stay_on_the_legacy_stream, and the test is the thing that is wrong here, not the change. But two details are worth having before you fix it.

The test encodes an obsolete invariant

I traced the payload rather than taking the description on trust, and a base64 media turn is functionally intact on the durable path:

  • buildRequestPayload is called once (chat-adapter.ts:6185) and the same object goes to the durable creator (:6228) and the legacy stream (:6316). The media fields at :6062-6071 are identical on both.
  • All three fields are declared model fields (models/inference.py:2065,2068,2083), so they survive _sanitize_request's unknown-key check and model_dump. Base64 is ASCII, so json.dumps -> SQLite TEXT -> json.loads is byte-exact.
  • The worker replays them into the same function the HTTP route calls: chat_generation_runs.py:693-702 does ChatCompletionRequest.model_validate(run["requestPayload"]) -> produce_openai_chat_completions(...) (routes/inference.py:20344 vs :20352).
  • The user bubble survives reconnect for the reason you give: the recovery follower only writes the assistant message (runtime-provider.tsx:912-919), and the user turn is rebuilt from thread history via toThreadMessage (:770-785), never from request_json.

So there is no durable-vs-legacy asymmetry for media, and nothing drops or corrupts the payload.

The failure comes from #10365, not from this PR

#10365 changed the gate from !imageBase64 to !currentTurnCarriesMedia. I ran the same test at pr10365's head: same assertion, same failure. This PR only removes the line that was already failing. If #10365 lands first its CI is red on the identical test, so the test update belongs there.

Suggested replacement

Rather than deleting the assertion, this keeps the routing intent and re-points it, and additionally pins the two things that actually make removing the gate safe -- the turn-scoped attachment channel (the mis-attribution #10365 fixed, where a stale blob made the backend 400 every later turn) and the toggle-off fallback:

def test_base64_media_turns_are_durable_and_their_attachments_stay_turn_scoped():
    candidate = _between(CHAT_ADAPTER, "const generationCandidate = Boolean(", ");")
    for token in ("imageBase64", "audioBase64", "videoBase64", "currentTurnCarriesMedia"):
        assert token not in candidate, (
            f"the durability gate reads {token} again, so a media turn is back on the "
            "subscriber-owned stream and closing the tab kills it mid-generation. "
            "If it must be refused again, do it behind UNSLOTH_STUDIO_DURABLE_MEDIA_TURNS "
            "in studio/backend/routes/chat_generation_runs.py, not in the frontend gate"
        )

    assert "const currentTurnMessages = [generationUserMessage]" in CHAT_ADAPTER
    for field, argument in (
        ("image_base64", "findLatestUserImageBase64(currentTurnMessages)"),
        ("video_base64", "findLatestUserVideoBase64(currentTurnMessages)"),
    ):
        assert f"{field}: {argument}" in CHAT_ADAPTER, (
            f"{field} must be scanned out of currentTurnMessages, not thread history: a "
            "stale blob from an earlier turn makes the backend refuse every later turn"
        )
    assert '"Media chat runs use the legacy streaming path"' in CHAT_GENERATION_API
    assert "isLegacyFallbackChatGenerationAdmissionError" in CHAT_ADAPTER

Full patch (with the docstring and the audio case, which wraps): I mutation-tested it rather than just checking that it passes. All four regressions are caught with a legible message: gate back to !imageBase64 (main's state), gate back to !currentTurnCarriesMedia (#10365's state), attachment channel back to survivingMessages, and the fallback string removed. pytest tests/studio -q is 7527 passed, 195 skipped with it applied.

Three things found while tracing, none of which block this

  1. "Replay is faithful" is overstated. chat-generation-replay.ts:238-252 copies event.result verbatim, while the live consumer (chat-adapter.ts:6672-6778) structures __IMAGES__: / __MCP_IMAGES__: / image_b64 into an object. A recovered python turn that plotted a chart renders the literal string __IMAGES__:["plot_0.png"]. source parts are never rebuilt, and parked tool-approval state (awaiting_confirmation / approval_id) is lost, so a reconnected tab sees a card with no Approve/Deny. These are tool-turn gaps inherited from feat(chat): make agentic turns survive tab-close #10365, not media ones.

  2. delete_chat_attachment no longer removes every copy. studio_db.py:4318-4400 scrubs the message copy but not request_json, and request_json now holds the blob twice (data URI inside messages, plus the top-level echo the backend documents at routes/inference.py:1975-1976). That residue could not exist before this change.

  3. test_durable_cancel_still_denies asserts nothing. studio/backend/tests/test_tool_approvals.py:285-286 is docstring-only after commit 62f5c2421; its former body is sitting as dead duplicate code at the tail of the test below it.

On the test style

Worth saying, since this PR moved the pattern rather than escaping it: studio/frontend/tests/durable-gate.test.ts:52-64 readFileSyncs chat-adapter.ts and regexes it, so it passes even if media turns are broken at runtime. durable-gate.ts already exists as a pure module, but only turnRequiresLegacyStream(enabled_tools) moved into it. Every input to generationCandidate is a plain value, so extracting isDurableRunCandidate(input): boolean is mechanical, and then durable-gate.test.ts can be a real truth table (media in/out, continuation, incognito, diffusion, audio model, external) and the Python contract test shrinks to one honest assertion that the adapter delegates. That would be a much better home for this invariant than either grep.

@danielhanchen

Copy link
Copy Markdown
Member

Admitting media turns by default means each turn's base64 blob is now stored verbatim in the run's request_json next to the thread's own copy, so could you say what that does to database size for an image-heavy thread; also, rather than dropping the base64 media assertion here, could you re-point it in #10365 where it first goes red, and keep this branch to the toggle alone?

CelesteHeartsong and others added 21 commits September 9, 2026 10:49
…rrupted

Case A: only browser-executed tools force the legacy (cancel-on-disconnect) stream.
Server-executed tool loops (enable_tools) now go durable like plain text, so an
auto/bypass loop runs to completion while you are away and a confirm-mode call parks.
Case B: wait_tool_decision parks instead of auto-denying at 3600s when the run's
cancel_event is tagged durable; chat_generation_runs tags its run cancel_event durable.
Case C: a legacy run cut by closing the tab now persists as 'interrupted' (partial kept,
Resume affordance) instead of an ambiguous blank/'cancelled'; an explicit Stop still reads cancelled.
… the live stream tags them

Three coupled pieces of follow-up to the durable-agentic-turn work, all verified end-to-end
against a live local GGUF with tools ON (six browser-closed turns replayed clean).

GATE. The conjunction upstream of the PR's gate keyed on THREAD-scoped media: one past
screenshot made every later text-only turn legacy, and those stale fields went out as
top-level payload fields, so the backend 400'd "Media chat runs use the legacy streaming
path" on turns that never carried media. The gate now keys on this turn's attachments and
on enabled_tools (extracted to durable-gate.ts as turnRequiresLegacyStream; keyed on
enabled_tools, never tools, which on the passthrough path is the caller's schema catalog).
A media policy 400 now degrades silently through isLegacyFallbackChatGenerationAdmissionError
like every other policy rejection instead of rethrowing as "An error occurred". The
post-admission claim line a prior edit dropped is restored, and its comment no longer lies.

REPLAY. The producer persists EVERY decoded SSE data frame as a chunk event and
_SSEDecoder drops the SSE event field, so persisted tool frames (tool_status,
tool_start/end/output/args, diffusion_frame) arrive at replay indistinguishable from OpenAI
chunks. normalizeChatGenerationChunkPayload now re-tags them exactly as the legacy stream
does before yielding, so a resumed run renders tool activity identically to a live one.

BACKEND. The tool-turn refusal is now env-gated and defaults ON (default "1";
UNSLOTH_STUDIO_DURABLE_TOOL_TURNS=0 restores the refusal) so a restart alone activates
durable tool turns; marked TEMPORARY DIAGNOSTIC until review settles whether it ships ON.

Tests: +5 (4 gate, 1 replay re-tag); full frontend suite 6886/6886, tsc -b clean.
…tool cards

The recovery follower folded every stored chunk into ONE string and re-parsed it on each
publish. A tool-heavy reply has no string form (its calls are parts, not characters), so a
reopened agentic reply lost its pills and their output -- and the per-publish full re-parse is
what made long replies fill in gradually from the replay cursor.

The follower now folds frames through createRecoveryReplay: text/reasoning runs extend in place
and a tool frame lands on the card its id names, at the offset the call ran at (the same parts
the live adapter builds, keyed by mintStreamedToolCallId's deterministic ids). Publish is gated
on applyChunk's changed-flag instead of firing per event regardless. The output-preference rules
moved to a dependency-free util so the replay module imports clean under node --test;
tool-output-scope re-exports them unchanged for its React consumers.
The review question was what frees the inference reservation when nobody ever answers a
parked gate. Nothing new does: parking does not renew the progress lease, so the lease
sweeper settles the aged run as interrupted, supervisor.cancel() sets the cancel_event
wait_tool_decision already polls, the waiter denies and pops its own slot, and the producer
unwinding balances the reservation — one lease window (default 1200s) of holdage, exactly
what a non-durable run already costs. The marker comment now says so, and a test pins the
whole chain: an elapsed ceiling releases nothing; only the settle's cancel does.
A follower attaches to a run already under way, so most of what it reads was written before
it existed. The follow loop published every update it folded, so coming back from a browser
close replayed the whole answer one awaited storage write per frame -- minutes of "streaming
in" for text that had finished while the tab was shut.

createRecoveryCatchUpGate arms on the first update, whose lastEventSeq is the live edge as
this tab saw it on arrival: frames at or under it fold silently into the accumulator, and
the first update past it publishes the caught-up reply in one write. From there every frame
is genuinely live and shows as it arrives. A run that had already settled has nothing above
the watermark, so `settled` overrides the fold and its whole history shows once.

Both publish paths (the reasoning-summary early-continue and the frame path) now ask the gate
instead of comparing status inline, so the rule lives in one module; a reconnect handing the
loop a fresher lastEventSeq must not drag the edge backwards over live frames, and a test
pins that along with the single catch-up write.
… wrote it

Reopening mid-reply could put a literal `< /think>` where the answer's first word should be,
doubled on every reopen. The live stream cannot hit this: chat-adapter closes an open thought
before it records a call (closeReasoningContent) and appends its tags into the same string it
parses, so the close lands at the end of the thought run. A replay seeded from stored parts has
to re-create those tags, and createRecoveryReplay tracked the block with a flag carried across
the WHOLE reply -- so after a call started a new run outside the block the run before it ended
inside, the next text chunk still got a close tag, and it landed in the new run as text.

grow now asks the run it is actually writing (ParsedRun.insideThink, exposed on the segmented
accumulator) which tag the next chunk owes, and a part landing at a boundary closes an open
thought first, exactly where the live stream closed it. seededReplayState re-creates that close
when it rebuilds the reply from stored parts, so reseeding from a mid-thought partial is
byte-identical to the string the live stream was parsing; what it no longer returns is the flag
it used to hand up, since the run answers that question better than a carried boolean can.

Pinned by two tests: a call landing mid-thought closes where the live stream closed it, and
reopening at any point of a thought-call-answer run yields exactly what the same frames produce
when nothing was interrupted.
A replay had no clock. The live stream times a thought against Date.now() between two chunks; every
frame a follower folds arrived before this tab existed, so timing them against now collapsed every
group to "Thought for 0 seconds" -- 742f43a brought the contents back and the duration was left
behind, because the only writer of reasoningDurations on this path was the server-summary helper, and
a local model emits no summary frame at all.

createRecoveryReplay now runs the SAME tracker chat-adapter runs, on the frames' own createdAt, and
counts groups on the same parts array the renderer indexes reasoningDurations by -- which is what
keeps index N of one the same thought as index N of the other. A call landing on the reply closes the
thought before it, exactly as closeReasoningContent does on the wire, so the clock stops where the
block closed instead of running on into the answer.

What the closing tab already measured rides along as the seed: the frames below this follower's cursor
were never folded here, so its numbers are all anyone will ever know about those groups, and a group
this reader DID watch takes the next slot instead of overwriting one it inherited. A server summary
now overwrites the group it describes instead of appending and shifting every later group along by
one -- which was quietly mislabelling the group after the summary even when a summary did arrive.

The append-only helper is gone: seeding plus per-group overwrite is what the array actually means.
…s own text

A model that carries its own  tags inside delta.content classifies its own
thought: the live stream appends such a delta verbatim (appendCumulative) and only
closes a block it opened itself (reasoningContentOpen, set solely for a
reasoning_content/reasoning_details frame). createRecoveryReplay closed whatever block
the run being written sat inside regardless of who opened it, so the first answer delta
of a tagged run closed the thought mid-sentence and the model's own close tag survived
as literal text in the answer part -- the mirror of the previous bug, and the reason a
reopened tab shows the thought leaking into the response.

grow now closes a block only when this replay opened it: seededReplayState hands up
whether what storage holds ends inside a thought it re-created a tag for (a stored
reasoning part carries no tag of its own), and a frame carrying tags of its own is
appended verbatim, exactly as the live stream appends it, so its own tag does the
classifying. closeThought is gated on the same flag, so a boundary inside a block the
model opened stays the model's business.

Pinned by two tests: a tagged run replays as parseAssistantContent of the same frames
reads it, and reopening at any point of it yields the same parts as a stream that never
left. Both fail without the flag.
extractDeltaText wraps a structured `thinking` part in a full pair of tags, so such a frame arrives
already carrying an OPEN one. grow() now appends it verbatim -- its own tag does the classifying -- but
that left the replay's own open tag standing inside the block a reasoning_content frame had opened, and
an open tag inside an open block is not a no-op for the parser: it survives as literal text in the middle
of the thought, which is what a reopened tab showed as the thought leaking into the response.

Only a chunk carrying an OPEN tag gets closed out from under first. A chunk carrying only a CLOSE does
not: that tag ends whichever block is open either way, which is exactly what the model's own close does
to a block the seed re-created -- the case the previous commit pinned.

Pinned by a test: a thinking part with its own tags landing in a replay-opened thought replays as
parseAssistantContent of the same frames reads it, literal tag and all. It fails without the guard.
…ed as a truth table

`test_durable_cancel_still_denies` had been docstring-only since 62f5c24, its body sitting as dead duplicate code at the tail of the sweeper test below it; it now carries its own assertions again.

The durability gate moved out of the adapter into `isDurableRunCandidate` (api/durable-gate.ts) over plain resolved values, so it is tested case by case in tests/durable-gate.test.ts instead of by grepping the adapter for a token that happens to spell the rule, and the media contract test asserts that the adapter delegates and that the gate only ever sees THIS turn's attachment scan.
…pin it

The adapter's conjunction moved to isDurableRunCandidate over the values it already had in hand - external provider, audio model, diffusion, THIS turn's media, continuation, thread/incognito, message present - so each term gets its own case and its own failure message instead of a regex hoping a token keeps its spelling.
…rote

The live stream shaped a tool frame into the object the card renders - sandbox files sliced off __FILES__, an MCP image envelope unwrapped, __IMAGES__ split into images + the session that ran, web-search images, an inline base64 image kept off `result`. A reopened tab replayed the frames and copied event.result VERBATIM, so a python turn that plotted a chart rendered the literal string __IMAGES__:["plot_0.png"]. The shaping moved out of the adapter into utils/tool-result-shape.ts and both readers call it, so faithfulness is one code path instead of a per-shape coincidence; replay now also carries the run's session id through to what it folds.
…le still refuses

These five pinned the refusal this PR made conditional: durable tool turns ship ON by default (UNSLOTH_STUDIO_DURABLE_TOOL_TURNS=0 restores the refusal), so an enabled-tools payload no longer raises. They now pin BOTH halves - admitted by default, refused under the toggle - instead of an invariant that only holds with the env off.
…he block they explain has

Nothing tsc can see rode through green from the shaping commit: a doc comment starting at column 0 under a
two-space block, a while condition broken mid-expression so the operand it tests is hard to read, and the
same rule ("a longer captured stream beats the model-visible result") stated twice two lines apart.
…that reopened it

A follower builds its accumulator when it attaches and only learns WHICH sandbox session the run ran in once
the stored run comes back, so the option is read at the frame that shapes a result rather than at construction,
and both accumulators are handed ONE holder: a fresh literal at the mid-follow rebuild would hand the new one
back an option it has been folding frames under all along. Without it a python turn that plotted a chart comes
back as a path from whoever's scope this tab happens to be on instead of an image from the run that made it.
Pinned by the shape of the card a replayed python frame leaves, and by both call sites handing over the holder.
The contract test sliced chat-adapter.ts at the inline block this branch moved into
utils/tool-result-shape.ts, so it died on .index() before it ever asserted. Pin the
gate/extraction/image-slice ordering in the one shaper both readers share, and pin that
neither reader grew a private copy of the rule back.
…eiling moves with the measurement that moved it

Same build both sides: merge base 191b69c at 1,582.0 KB transfer / 5,295.8 KB raw against the branch at 1,583.9 KB / 5,301.0 KB. The replay/gate code sits inside the chat chunk, which is entry-static, so nothing here can be deferred to import(); the gate IS the chat path. transferBytes 1_620_000 -> 1_622_000.
Live derives Sources from web_search/web_fetch results at its final yield and appends them, then the citation parts; the replay assembled text and calls and stopped there, so a follower's message had pills with no panel. The shapers moved to tool-result-shape for the same reason as every other shape here: the replay cannot import the adapter (react under node --test), and both readers must agree on an id shape down to the byte.
@danielhanchen

Copy link
Copy Markdown
Member

Thanks for the measurement and for cutting this back to the toggle alone; the 3x per media turn comes from the run keeping its own verbatim copy of the blob with nothing sweeping those rows. Before the default flips, could you say whether storing the content-part-sha256- id and rehydrating at replay in chat_generation_runs.py is in scope here or a follow-up?

@CelesteHeartsong

Copy link
Copy Markdown
Contributor Author

could you say whether storing the content-part-sha256- id and rehydrating at replay in chat_generation_runs.py is in scope here or a follow-up?

Follow-up. The rehydration path needs a stable content-part id scheme (hash of what, scoped to which message), changes in both the payload builder and the replay reader in chat_generation_runs.py, and a fallback for the edge case where the thread message was edited or deleted after the run was created. That's a self-contained optimization that's easier to review on its own once the feature is proven.

For now the toggle covers it: UNSLOTH_STUDIO_DURABLE_MEDIA_TURNS=0 restores the legacy path for anyone who hits the size ceiling.

@danielhanchen

Copy link
Copy Markdown
Member

Thanks for the measurements, the 3x per media turn with no TTL on those rows is the part I want settled before the default flips; could you confirm whether the top-level image_base64 echo can be dropped from request_json, or the content-part id stored and rehydrated at replay, so an image-heavy thread does not grow three copies?

The base64 blob already rides in messages[].content as a data URI.
Storing it again at the top level (image_base64/audio_base64/
video_base64) tripled the per-turn cost for image-heavy threads with
nothing sweeping those rows.

_strip: _sanitize_request now pops the media fields from the stored
payload after validation. The live request still carries them for the
inference path; only the persisted copy loses the duplicate.

_rehydrate: at replay time, _rehydrate_media_fields extracts the
base64 back from the content array before model_validate, so the
inference code sees the same shape as a live request.

3x -> 2x per media turn (thread copy + request_json messages), with
no new machinery and no TTL needed.
@CelesteHeartsong

Copy link
Copy Markdown
Contributor Author

could you confirm whether the top-level image_base64 echo can be dropped from request_json, or the content-part id stored and rehydrated at replay, so an image-heavy thread does not grow three copies?

Yes — the top-level echo is redundant with the data URI already in messages[].content[]. Dropped and rehydrated in fbeed49d:

  • Store: _sanitize_request pops the media fields from the persisted payload after validation. The live request still carries them for the inference path; only the stored copy loses the duplicate.
  • Replay: _rehydrate_media_fields extracts the data URI back from the content array before model_validate, so downstream sees the same shape as a live request. No changes needed in the inference code.

Result: 3x → 2x per media turn. The blob lives in the thread's message + request_json.messages[].content, but no longer as a separate top-level field. No TTL, no id scheme. The content-part-id rehydration (2x → 1x) stays as the longer-term optimization.

danielhanchen added a commit that referenced this pull request Sep 22, 2026
* studio: make agentic turns survive tab-close; label walk-away as interrupted

Case A: only browser-executed tools force the legacy (cancel-on-disconnect) stream.
Server-executed tool loops (enable_tools) now go durable like plain text, so an
auto/bypass loop runs to completion while you are away and a confirm-mode call parks.
Case B: wait_tool_decision parks instead of auto-denying at 3600s when the run's
cancel_event is tagged durable; chat_generation_runs tags its run cancel_event durable.
Case C: a legacy run cut by closing the tab now persists as 'interrupted' (partial kept,
Resume affordance) instead of an ambiguous blank/'cancelled'; an explicit Stop still reads cancelled.

* test: cover durable-run approval parking (waits past timeout; explicit Stop still denies)

* studio: gate durability on THIS turn only; replay persisted frames as the live stream tags them

Three coupled pieces of follow-up to the durable-agentic-turn work, all verified end-to-end
against a live local GGUF with tools ON (six browser-closed turns replayed clean).

GATE. The conjunction upstream of the PR's gate keyed on THREAD-scoped media: one past
screenshot made every later text-only turn legacy, and those stale fields went out as
top-level payload fields, so the backend 400'd "Media chat runs use the legacy streaming
path" on turns that never carried media. The gate now keys on this turn's attachments and
on enabled_tools (extracted to durable-gate.ts as turnRequiresLegacyStream; keyed on
enabled_tools, never tools, which on the passthrough path is the caller's schema catalog).
A media policy 400 now degrades silently through isLegacyFallbackChatGenerationAdmissionError
like every other policy rejection instead of rethrowing as "An error occurred". The
post-admission claim line a prior edit dropped is restored, and its comment no longer lies.

REPLAY. The producer persists EVERY decoded SSE data frame as a chunk event and
_SSEDecoder drops the SSE event field, so persisted tool frames (tool_status,
tool_start/end/output/args, diffusion_frame) arrive at replay indistinguishable from OpenAI
chunks. normalizeChatGenerationChunkPayload now re-tags them exactly as the legacy stream
does before yielding, so a resumed run renders tool activity identically to a live one.

BACKEND. The tool-turn refusal is now env-gated and defaults ON (default "1";
UNSLOTH_STUDIO_DURABLE_TOOL_TURNS=0 restores the refusal) so a restart alone activates
durable tool turns; marked TEMPORARY DIAGNOSTIC until review settles whether it ships ON.

Tests: +5 (4 gate, 1 replay re-tag); full frontend suite 6886/6886, tsc -b clean.

* studio: name what releases an unanswered parked approval, and pin it

The review question was what frees the inference reservation when nobody ever answers a
parked gate. Nothing new does: parking does not renew the progress lease, so the lease
sweeper settles the aged run as interrupted, supervisor.cancel() sets the cancel_event
wait_tool_decision already polls, the waiter denies and pops its own slot, and the producer
unwinding balances the reservation — one lease window (default 1200s) of holdage, exactly
what a non-durable run already costs. The marker comment now says so, and a test pins the
whole chain: an elapsed ceiling releases nothing; only the settle's cancel does.

* test: the explicit-Stop deny test asserts again, and the gate is pinned as a truth table

`test_durable_cancel_still_denies` had been docstring-only since 62f5c24, its body sitting as dead duplicate code at the tail of the sweeper test below it; it now carries its own assertions again.

The durability gate moved out of the adapter into `isDurableRunCandidate` (api/durable-gate.ts) over plain resolved values, so it is tested case by case in tests/durable-gate.test.ts instead of by grepping the adapter for a token that happens to spell the rule, and the media contract test asserts that the adapter delegates and that the gate only ever sees THIS turn's attachment scan.

* studio: the durability gate reads plain values, so a truth table can pin it

The adapter's conjunction moved to isDurableRunCandidate over the values it already had in hand - external provider, audio model, diffusion, THIS turn's media, continuation, thread/incognito, message present - so each term gets its own case and its own failure message instead of a regex hoping a token keeps its spelling.

* test: what a tool-enabled turn is admitted for now, and what the toggle still refuses

These five pinned the refusal this PR made conditional: durable tool turns ship ON by default (UNSLOTH_STUDIO_DURABLE_TOOL_TURNS=0 restores the refusal), so an enabled-tools payload no longer raises. They now pin BOTH halves - admitted by default, refused under the toggle - instead of an invariant that only holds with the env off.

* studio: an explicit Stop on a legacy turn persists cancelled, not the walk-away label it aborted under

* fix(test): update auto-compaction test for durable-gate image_base64 derivation

The chat adapter now derives image_base64 from THIS turn's messages only
(findLatestUserImageBase64(currentTurnMessages)) rather than a hoisted
variable, so a media turn cannot lose compaction fields and a stale
screenshot from an earlier turn doesn't make the backend see a non-empty
media field on later text-only turns.

This updates the source-shape assertion to match the new pattern.

* studio: tool turns ride the durable path as shipped behavior, not a diagnostic

The flip was landed as TEMPORARY DIAGNOSTIC so a restart alone activated it while replay-as-parts was still
being built out. Replay now re-tags persisted frames exactly as the live stream yields them, so default-ON is
the shipped behavior and UNSLOTH_STUDIO_DURABLE_TOOL_TURNS is an escape hatch that restores the old refusal -
the comment says that instead of promising a revert that isn't coming. Flag block wording kept byte-identical
to the media PR's flip wording, so restacking that commit onto this tip applies clean.

* studio: deny a durable park at the approval timeout, not the lease window

An unanswered approval previously held its inference slot for the full
lease window (~20 min) because the durable flag suppressed the 3600s
ceiling and only the sweeper could release it. For agentic work where
the user has left, that stalls the loop unnecessarily.

Add UNSLOTH_STUDIO_TOOL_APPROVAL_TIMEOUT_S (default 300s) as the
park-specific ceiling. wait_tool_decision now denies at that timeout
instead of waiting indefinitely, so the model receives
TOOL_REJECTED_MESSAGE and adapts. Set to 0 for fully autonomous mode.
The sweeper remains a backstop for producers wedged before they reach
the gate.

* fix: remove duplicate closing brace from conflict resolution in chat-adapter.ts

* studio: drop the redundant top-level media echo from stored runs

The base64 blob already rides in messages[].content as a data URI.
Storing it again at the top level (image_base64/audio_base64/
video_base64) tripled the per-turn cost for image-heavy threads with
nothing sweeping those rows.

_strip: _sanitize_request now pops the media fields from the stored
payload after validation. The live request still carries them for the
inference path; only the persisted copy loses the duplicate.

_rehydrate: at replay time, _rehydrate_media_fields extracts the
base64 back from the content array before model_validate, so the
inference code sees the same shape as a live request.

3x -> 2x per media turn (thread copy + request_json messages), with
no new machinery and no TTL needed.

* Revert "studio: drop the redundant top-level media echo from stored runs"

This reverts commit fbeed49.

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

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

* studio: persist a failed turn as interrupted even when it produced no text

The error-path partial yield was wrapped in 'if (partialContent.length > 0)', so a turn that errored before any text never persisted its incomplete reason at all. That contradicts chat-continuation.test.ts ('a turn that fails before any text is still saved as interrupted') and the invariant pinned elsewhere that publishing the reason must not depend on renderable content. Drop the guard so the yield always runs; the body is unchanged.

* studio: route the durability gate through isDurableRunCandidate

chat-adapter built generationCandidate as an inline Boolean(...) conjunction, while durable-gate.ts already extracted the same rule as isDurableRunCandidate({...}) and its tests pinned that call - so test_multi_chat_prompt_queue_contract.py asserted a marker that was never in the adapter. Call the shared gate with the resolved values; each term maps 1:1 to the old conjunction, so behavior is unchanged. The two object-literal adjustments (incognito guarded on threadId, hasUserMessage coerced) only keep the types honest - truthiness is identical.

* tests: gate the stopping-criteria device test on has_real_cuda, not the spoofable probe

The accelerator skip-guard (test_no_skip_guard_reads_a_spoofable_accelerator_probe) flags any test that gates hardware on torch.cuda.is_available(), which tests/_zoo_aggressive_cuda_spoof.py patches True process-wide. test_stopping_criteria_device.py still used it, so 'Repo tests (CPU, python)' failed 10/10 on this branch while passing on main. Adopt main's fix: use has_real_cuda() and bring in the matching real_accelerator helper that defines it.

* studio: a reopened tab can answer the approval its tool call is parked on

A durable tool turn parks the backend on a human decision and keeps waiting for the returning
session, which is the whole point of the park. The reopened tab rebuilt the card but had no way
to answer it: createGenerationToolRecovery never read awaiting_confirmation and never registered
with the confirmation store, whose only call site was the live adapter, and
ToolConfirmationControls renders Approve/Deny only for a card the store knows about. So the tab
came back to a spinner over a call nobody could allow, and the run sat parked until the ceiling
denied it for the user.

Recovery now arms the card both ways a parked call can reach a reopened tab. A call that parks
after the tab reattaches arms itself as its tool_start folds. A call that parked BEFORE the tab
closed has its tool_start at or below the cursor, so no frame ever re-folds it and the seed is
the only place it still exists: armSeededApprovals re-raises those once the follower learns the
run's session, which is what the decision resolves against. Both paths key the card by its own
toolCallId and scope it exactly as the live stream does, so arming the same call twice is one
card, and a recovery only ever resolves a card it armed itself.

The hooks are passed in rather than imported, so the util stays a util and the caller keeps the
store. The recovery test harness gains the two store methods the real store has always had.

* studio: a park ceiling nobody can parse falls back instead of taking the backend down

UNSLOTH_STUDIO_TOOL_APPROVAL_TIMEOUT_S was read as a bare float() at module scope, so
UNSLOTH_STUDIO_TOOL_APPROVAL_TIMEOUT_S=5m raised ValueError while state.tool_approvals was being
imported. That module is on the chat path, so a typo in an environment variable stopped the
backend from starting at all. It now warns and uses the default, as do a negative, NaN or
infinite value, which would otherwise disable the ceiling silently. A parsed value still applies
exactly as before, and the read stays at import so one run cannot move the ceiling mid-flight.

The marker comment on the durable cancel_event still described the behaviour that shipped before
the park ceiling existed: it promised the lease sweeper was the only thing that released an
unanswered approval, at roughly 1200s. The ceiling releases it first, at 300s by default, and a
user who returns after that finds the call already declined rather than still waiting. The
comment now names both releases and which comes first.

Also pinned: the ceiling reads every shape of env value without raising, an unset one is the
documented default, a zero ceiling denies at the first poll rather than instantly so a decision
inside that first 500ms still wins, and a session returning past the ceiling can no longer
resolve its own approval.

* tests: name the media contract test after what this branch actually does

test_base64_media_turns_are_durable_and_their_attachments_stay_turn_scoped said a media turn is
durable now. It is not, on this branch: the gate still sends a turn carrying its own attachment
to the legacy stream, and _sanitize_request still refuses a populated media payload. What
changed is that such a turn stops refusing its text-only FOLLOW-UPS, which is what the
assertions check. Admitting the media turn itself is a separate change in #10406.

Assertions are untouched; the name, the docstring and two failure messages now describe them.

* studio: say what the park ceiling actually bounds, which is one wait and not the run

The comment added a commit ago claimed the reservation is held "for at most the park ceiling".
It is not. The ceiling ends one approval WAIT: the gate denies, the loop appends the denial as a
tool message and keeps generating, and the InferenceActivityReservation is released by the
producer unwinding and by nothing else. A turn that parks on several calls in a row holds the
reservation across several ceilings, and the progress between them renews the lease, so the
sweeper only bounds a producer that stops making progress at all.

Found by reading the denial path in llama_cpp.py against the release in this file rather than
trusting the sentence, which is the sort of claim a comment gets believed for.

* studio: arm a seeded approval only while its run can still answer

A call that parked before the tab closed is re-raised from the saved message by
armSeededApprovals, which restores the Approve/Deny the reopened tab had no other
way to show. That call was unconditional, so a run which settled while it was
parked re-armed the card too: a backend restart terminalises surviving rows, the
in-memory pending slot is gone, and no tool_end is coming to disarm the card. The
reopened tab then offered buttons whose confirm could only return 404.

Gate on the run still being answerable, using the isTerminalChatGenerationRun this
file already imports, so the terminal set stays defined in one place.

The follow loop has no behavioural test that does not need a live EventSource, so
the call site is pinned instead: tests/seeded-approval-terminal-run.test.ts asserts
the guard, that the check is imported rather than reinvented, and that the call site
exists at all, so the assertion cannot pass by finding nothing.

* studio: take recovered approval cards down when the run ends, not only when a call ends

The per-call disarm runs on tool_end. A run that terminates without one, because
the backend failed or restarted while the call was parked, never reaches it, so
the card outlived its own run: buttons still on screen, the tool group still open,
and a decision that could only 404 since the pending slot went with the restart.

The terminal check added at the call site covers a run that was ALREADY terminal
when recovery attached. It does not cover one that gets there afterwards, which is
the case a watching tab actually sees. Add a run-level sweep and call it where the
follow loop already recognises a terminal snapshot.

Scoped and idempotent for the same reason the per-call disarm is: a recovery shares
the confirmation store with whatever else is on screen, so it resolves only cards it
armed itself, and the follow loop can see more than one terminal snapshot.

* studio: keep an inline base64 image off the durable path, wherever it sits

The media guard was field-shaped plus nested audio and video. It had no nested
image check, and it did not need one while a thread holding a screenshot was
pushed onto the legacy stream wholesale. Turn-scoping removed that: a text-only
follow-up no longer sets top-level image_base64, yet the thread's earlier
screenshot still rides along inside messages[].content, so the follow-up was
admitted to the durable path.

A durable run persists its request verbatim, so that blob was written into
request_json again on every follow-up turn for the life of the thread, which is
the exact cost the guard's own comment says it exists to prevent.

_messages_have_embedded_image matches an inline data URL only. A remote image_url
is a short string that costs nothing to persist and has no business giving up
durability, so it stays admitted; the narrow match is pinned by a test, as is the
plain-text case, because a guard that over-matched would push every turn back onto
the legacy stream and the feature would stop working silently.

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

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

* studio: ask whether a parked approval is still waiting before restoring its buttons

Recovery inferred 'still parked' from the shape of the saved card: no result, and
an approval id. A call the user already answered looks exactly the same, because
the result only arrives with tool_end. So closing the tab between the click and
the tool finishing, then reopening, put Approve/Deny back over a call that was
already executing, and every press returned 404 until it finished.

The card cannot answer this and neither could anything else that was persisted:
awaiting_confirmation rides only on tool_start, no event marks a decision, and the
run snapshot carries no approval state. So the state is asked for. tool-approval-status
takes the approval id in the body and answers pending or not, scoped to the session
like resolve_tool_decision and keyed on an id the caller already holds, so it cannot
be used to enumerate anyone else's approvals. A set event counts as decided, which
closes the window between the decision and the waiter popping its own slot.

Failure leans the safe way at both ends: an older backend answering 404 or 405, or
a check that throws, falls back to arming. Losing the buttons on a call that really
is parked is the worse outcome, and it is the one this whole path exists to prevent.

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

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

* Scope the tool approval park ceiling to unattended runs for PR #10365

The 300s park ceiling was keyed on cancel_event.durable alone, and the supervisor
sets that marker on every run it owns. Durable means cancel_on_disconnect is off,
not that the tab is gone, so with tool turns durable by default the ceiling applied
to a user sitting in front of an open Approve/Deny card: a decision that had 3600s
before this branch now expired after five minutes, with no countdown or warning
anywhere in the UI because the timeout is never serialized into any frame.

Three changes:

1. The ceiling now measures time with nobody watching rather than time since the
   call parked. The run's SSE follower stamps a presence heartbeat (new
   state/run_subscribers.py, keyed by run id, entries aged out after three
   keep-alive periods) and wait_tool_decision re-arms its deadline while a follower
   is attached, falling back to the module's own _DECISION_TIMEOUT as the absolute
   backstop so an attended run keeps exactly the hour a browser-owned run always
   had. An abandoned approval still releases at the park ceiling, so an unattended
   agentic loop is unaffected. A heartbeat rather than a reference count, because a
   leaked increment would park an abandoned approval forever.

2. An expiry is no longer reported as the user's decision. wait_tool_decision
   collapsed user-deny, run-cancelled and ceiling-expired into one bare "deny", so
   all three emitted TOOL_REJECTED_MESSAGE, "The user declined to run this tool
   call." That reached both the model and the reopened card as the only account of
   the call, and it is false for an expiry. wait_tool_decision_detail returns
   (verdict, reason) and the three tool loops pick TOOL_APPROVAL_EXPIRED_MESSAGE
   for an expiry. wait_tool_decision keeps its old signature and return, so every
   other caller is untouched and TOOL_REJECTED_MESSAGE is byte-identical for a real
   denial.

3. Pressing Allow on an approval that is already gone said "Could not send your
   decision. Try again." next to re-enabled buttons: the slot is popped, so every
   retry 404s until tool_end clears the card. The 404 now carries its own type,
   the card says the request is no longer waiting and disables the buttons, and
   Always allow records its session grant only after the backend takes the
   decision instead of on the click, where a visibly failed press still
   auto-approved the tool for the rest of the session.

Also pins the durable marker itself. Deleting cancel_event.durable = True left the
entire backend suite green, since every approval test sets the attribute by hand,
so the whole park feature could be disabled without a single test noticing.

Backend 46 + 62 pass, frontend 7858 pass, tsc -b clean, ruff clean. The existing
park, cancel and sweeper-settle tests pass unchanged.

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

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

* Keep wait_tool_decision as the single patchable waiter for PR #10365

The previous commit split the waiter into wait_tool_decision_detail to return
(verdict, reason) and pointed the three tool loops at it. That broke the loops'
patch target: tests/test_llama_cpp_tool_loop.py, test_safetensors_tool_loop.py
and test_studio_tool_loop.py monkeypatch core.inference.<loop>.wait_tool_decision
by name, and tests/test_refactor_guard.py resolves every string patch target, so
15 tests failed on the attribute no longer being there.

The reason now rides on the slot instead. wait_tool_decision keeps its name,
signature and bare "allow"/"deny" return, records why in slot["reason"], and the
loops read it back with decision_reason(slot) before dropping the slot in their
deny branch. A stubbed waiter that returns a bare string and never touches the
slot leaves the reason None, which falls back to TOOL_REJECTED_MESSAGE: exactly
the behaviour those tests expect.

Caught by staging CI on Datta0/unsloth-staging-3, which runs the tool-loop suites
this box cannot. Backend Windows, macOS, GGUF, API, Tauri, Wheel, studiobench and
Lint were already green on the same head.

tests/test_llama_cpp_tool_loop.py, test_safetensors_tool_loop.py,
test_studio_tool_loop.py, test_refactor_guard.py, test_tool_approvals.py and
test_chat_generation_runs.py: 686 passed. Frontend tool-approval-gone 6 passed,
tsc -b clean, ruff clean over studio/backend.

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

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

* Track approval attendance per follower, not per run, for PR #10365

One run can have several followers: two tabs on the same thread, or a reconnect
whose replacement stream attaches before the old one finishes unwinding. With a
single stamp per run, either follower's cleanup deleted the heartbeat the other
had just written, and the survivor does not stamp again until its event wait
turns over, which is up to 15s.

That is reachable. UNSLOTH_STUDIO_TOOL_APPROVAL_TIMEOUT_S below 15s is a
supported configuration, 0 included and already covered by a test, so a parked
approval could be denied while a second tab was actively watching it. That is the
exact failure the presence heartbeat was added to prevent.

_SEEN is now run_id -> {follower token: last heartbeat}. The SSE route mints one
token per stream, mark_subscriber_seen and subscriber_departed take it, and a
departure removes only that follower's entry, dropping the run key when the last
one goes. is_attended expires stale tokens as it reads them.

Reproduced first: two stamps then one departure left is_attended False. Pinned by
three tests, all red without the fix (test_one_tab_closing_leaves_another_tabs_
attendance_intact, test_an_attended_park_survives_a_second_tab_closing, and
test_a_follower_only_clears_its_own_stamp_not_the_run). test_tool_approvals 49
passed, formatter fixed point 11 passed, ruff clean.

* Do not hold the event stream closed while checking seeded approvals for PR #10365

followChatGenerationRun yields its snapshot before opening /events: the
`yield { run, source: "snapshot" }` in chat-generation-api.ts precedes the
streamChatGenerationEvents loop, so the generator sits suspended at that yield
while the consumer works. Awaiting armSeededApprovals there therefore serialises
the "is this approval still pending?" request AHEAD of the stream, and /events is
the only thing that marks the run attended server-side.

So a tab returning close to UNSLOTH_STUDIO_TOOL_APPROVAL_TIMEOUT_S could have its
approval expire during the very request asking whether it was still pending, and
be handed restored Allow / Deny buttons that can only 404. The window is the
duration of that round trip, which is wide enough to matter on a shortened
ceiling or a loaded server.

The call is no longer awaited at the call site. The promise is kept and joined
before disarmAll, so an arm that resolves late still cannot raise buttons on a
run that has already ended, and armSeededApprovals already treats an unanswerable
check as "still parked" so nothing is lost by letting it settle later.

Pinned by two AST tests alongside the existing terminal-run guard, in the same
file and for the same reason: the follow loop needs a live EventSource, so no
behavioural test in this suite reaches it. Re-adding the await turns the first
red. Frontend suite 7860 passed, tsc -b and tsc -p tsconfig.test.json clean.

* Renew the run lease while an approval is attended, for PR #10365

Re-arming the approval's own counter was not enough. Parking makes no progress,
so the run's lease still aged out: ChatGenerationLeaseSweeper settles it at
_LEASE_TIMEOUT_SECONDS (1200s by default) and supervisor.cancel() sets the same
cancel_event the waiter polls, which returns deny with DECISION_CANCELLED.

So an attended deliberation was capped at roughly 20 minutes and ended as a
cancel, while the docstring I added promised the full _DECISION_TIMEOUT. The
claim was wrong, not just the behaviour.

The supervisor now hands the waiter cancel_event.renew_lease, in the same
attribute idiom as durable and durable_run_id, and an attended park calls it
alongside re-arming its counter. Throttled to one call per _LEASE_RENEW_EVERY_S
(30s): the poll runs twice a second and this is a database write. A renewal that
raises is swallowed, because a lease we could not renew is the sweeper's problem
to discover rather than a reason to drop the decision. An UNATTENDED park never
renews, so the sweeper stays the backstop for an abandoned run, which is the one
thing it exists for.

Docstring corrected to say that reaching _DECISION_TIMEOUT depends on this.

Four tests, two of them red without the change: renewal happens when attended,
does not when unattended, is throttled to one call per window, and a cancel_event
carrying no renew_lease still parks correctly. test_tool_approvals 53 passed,
formatter fixed point green, ruff clean over studio/backend. The 14 failures in
test_chat_generation_run_lease.py when that file is run standalone are identical
with and without this change.

* Recheck a seeded approval after its status request, for PR #10365

Removing the await at the call site (50280e9) was right, but it opened this:
the replay now runs concurrently with the pending check, so tool_end can fold a
card while its status request is still in flight. disarmApproval is a no-op then,
because this recovery has not armed anything yet, and arming afterwards registers
an already-finished call.

Nothing renders buttons over it, since a part with a result is not `awaiting`.
The cost is the leaked store entry: it survives until disarmAll at the end of the
run, and `soleRequest` in tool-confirmation-controls counts entries, so a LATER
approval reads as non-sole and silently loses its Enter and Escape chords.

armSeededApprovals now re-reads entry.part after the await and skips a card that
gained a result meanwhile. The recheck rather than an unconditional disarm,
because disarmApproval is deliberately scoped to cards this recovery raised
itself: it shares the store with whatever else is on screen.

Two tests, the first red without the change: a card finished while its request
was in flight is not armed, and a card still unresolved when the request returns
is armed exactly as before. Frontend suite 7862 passed, tsc -b clean.

* Scope approval attendance by account, and disarm on every recovery exit, for PR #10365

Two findings from the same review round.

Attendance was keyed on the bare run id. studio.db is per-account
(utils.paths.storage_roots.studio_db_path resolves through account_path) and the
run id comes from the client (CreateChatGenerationRun.runId is a free-form string
the caller picks), so two accounts on one managed install can hold the same id.
A process-global map keyed on that id alone let one tenant's follower report
another tenant's run as attended: it would hold a stranger's approval open past
its ceiling and keep renewing that run's lease, pinning an inference slot the
other account never asked to hold.

_SEEN is now keyed on (account_id, run_id). The supervisor stamps
cancel_event.durable_account_id from the same current_account_id() that
ActiveGeneration captures beside it, the SSE route passes its own, and a missing
account is its own scope rather than a wildcard, so a caller that cannot name its
account never matches one that can.

Second, disarmAll ran only after a terminal snapshot. A permanent follower error
(another tab deletes the thread, the run row cascades, the next request 404s)
throws past that branch and is swallowed by the outer catch, so a card armed from
the seed stayed in the global toolConfirmations store for the rest of the
session. Nothing renders buttons over a finished part, but soleRequest counts
entries, so a later real approval read as non-sole and silently lost its Enter
and Escape chords. The disarm moved into the recovery's finally, which every exit
reaches, with the seed joined first as before; the terminal-path copy is gone so
the two cannot disagree about ordering.

Six tests, all red against their own mutation: three for the account key, two
pinning the disarm into the finally, one that the join still precedes it.
Backend 129 passed across approvals, generation runs and the formatter fixed
point. Frontend 7863 passed, tsc -b clean, ruff clean over studio/backend.

* Trim the comments added for PR #10365 to the facts that change behaviour

---------

Co-authored-by: CelesteHeartsong <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
Conflict Test and others added 4 commits September 22, 2026 11:48
…ai#10365 conflicts)

unslothai#10365 landed on main after this branch forked from the shared dev base, so its
reviewed durable-turns code collided with the copy carried here. Resolved per file:

- backend state/tool_approvals.py, tests/test_tool_approvals.py and
  tests/studio/test_desktop_reliability_frontend_contract.py: take main's reviewed
  version (this PR has no unique work in them).
- core/inference/chat_generation_runs.py: take main's reviewed park/lease logic.
- routes/chat_generation_runs.py, durable-gate.ts, durable-gate.test.ts and
  test_multi_chat_prompt_queue_contract.py: keep THIS PR's media-turns work -
  UNSLOTH_STUDIO_DURABLE_MEDIA_TURNS toggle (default on), media removed from the
  frontend gate, and the matching "media turns are durable" assertions.
- chat-adapter.ts: keep shapeToolResult shaper + media-durable gate args; take main
  for import formatting and the partial-yield block (unslothai#10811 removed that guard); drop
  the duplicate local isMcpImageToolResult (imported from utils/tool-result-shape).
- runtime-provider.tsx: keep this PR's self-consistent recovery impl.
- generation-tool-recovery.test.ts: union the mock store stubs.

REVIEW NOTE: main's media-refusal branch also detects input-audio / embedded-image /
video inside messages[] (added after this branch forked); this branch's toggle-off
refusal only checks top-level _MEDIA_FIELDS. Decide whether to fold those in.

Follow-ups before landing: tsc -b + npm test; backend test_chat_generation_runs +
test_tool_approvals; reconcile the shared replay files with unslothai#10910 (keep unslothai#10910's).
Merging main left main's code referencing the McpImageToolResult type in local scope
(~line 1768), but this branch only re-exports it and its local import omitted the type,
so tsc failed with "Cannot find name 'McpImageToolResult'". Add the type to the local
import from utils/tool-result-shape. No duplicate: there is no local definition of it.
…ngine

unslothai#10910 replaced createGenerationToolRecovery's arm/disarm lifecycle and the
client-side parseThinkTags flag with createRecoveryReplay (frame-type reasoning
split + toolConfirmations register/resolve). Update literal-think-when-thinking-off
and seeded-approval-terminal-run to pin that new wiring instead of the removed call sites.
@CelesteHeartsong

Copy link
Copy Markdown
Contributor Author

I believe the progress of the separate PRs has put this PR behind #10910. Once that completes/merges then we can rebase this PR on main and drive it to completion.

shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
* studio: make agentic turns survive tab-close; label walk-away as interrupted

Case A: only browser-executed tools force the legacy (cancel-on-disconnect) stream.
Server-executed tool loops (enable_tools) now go durable like plain text, so an
auto/bypass loop runs to completion while you are away and a confirm-mode call parks.
Case B: wait_tool_decision parks instead of auto-denying at 3600s when the run's
cancel_event is tagged durable; chat_generation_runs tags its run cancel_event durable.
Case C: a legacy run cut by closing the tab now persists as 'interrupted' (partial kept,
Resume affordance) instead of an ambiguous blank/'cancelled'; an explicit Stop still reads cancelled.

* test: cover durable-run approval parking (waits past timeout; explicit Stop still denies)

* studio: gate durability on THIS turn only; replay persisted frames as the live stream tags them

Three coupled pieces of follow-up to the durable-agentic-turn work, all verified end-to-end
against a live local GGUF with tools ON (six browser-closed turns replayed clean).

GATE. The conjunction upstream of the PR's gate keyed on THREAD-scoped media: one past
screenshot made every later text-only turn legacy, and those stale fields went out as
top-level payload fields, so the backend 400'd "Media chat runs use the legacy streaming
path" on turns that never carried media. The gate now keys on this turn's attachments and
on enabled_tools (extracted to durable-gate.ts as turnRequiresLegacyStream; keyed on
enabled_tools, never tools, which on the passthrough path is the caller's schema catalog).
A media policy 400 now degrades silently through isLegacyFallbackChatGenerationAdmissionError
like every other policy rejection instead of rethrowing as "An error occurred". The
post-admission claim line a prior edit dropped is restored, and its comment no longer lies.

REPLAY. The producer persists EVERY decoded SSE data frame as a chunk event and
_SSEDecoder drops the SSE event field, so persisted tool frames (tool_status,
tool_start/end/output/args, diffusion_frame) arrive at replay indistinguishable from OpenAI
chunks. normalizeChatGenerationChunkPayload now re-tags them exactly as the legacy stream
does before yielding, so a resumed run renders tool activity identically to a live one.

BACKEND. The tool-turn refusal is now env-gated and defaults ON (default "1";
UNSLOTH_STUDIO_DURABLE_TOOL_TURNS=0 restores the refusal) so a restart alone activates
durable tool turns; marked TEMPORARY DIAGNOSTIC until review settles whether it ships ON.

Tests: +5 (4 gate, 1 replay re-tag); full frontend suite 6886/6886, tsc -b clean.

* studio: name what releases an unanswered parked approval, and pin it

The review question was what frees the inference reservation when nobody ever answers a
parked gate. Nothing new does: parking does not renew the progress lease, so the lease
sweeper settles the aged run as interrupted, supervisor.cancel() sets the cancel_event
wait_tool_decision already polls, the waiter denies and pops its own slot, and the producer
unwinding balances the reservation — one lease window (default 1200s) of holdage, exactly
what a non-durable run already costs. The marker comment now says so, and a test pins the
whole chain: an elapsed ceiling releases nothing; only the settle's cancel does.

* test: the explicit-Stop deny test asserts again, and the gate is pinned as a truth table

`test_durable_cancel_still_denies` had been docstring-only since 62f5c24, its body sitting as dead duplicate code at the tail of the sweeper test below it; it now carries its own assertions again.

The durability gate moved out of the adapter into `isDurableRunCandidate` (api/durable-gate.ts) over plain resolved values, so it is tested case by case in tests/durable-gate.test.ts instead of by grepping the adapter for a token that happens to spell the rule, and the media contract test asserts that the adapter delegates and that the gate only ever sees THIS turn's attachment scan.

* studio: the durability gate reads plain values, so a truth table can pin it

The adapter's conjunction moved to isDurableRunCandidate over the values it already had in hand - external provider, audio model, diffusion, THIS turn's media, continuation, thread/incognito, message present - so each term gets its own case and its own failure message instead of a regex hoping a token keeps its spelling.

* test: what a tool-enabled turn is admitted for now, and what the toggle still refuses

These five pinned the refusal this PR made conditional: durable tool turns ship ON by default (UNSLOTH_STUDIO_DURABLE_TOOL_TURNS=0 restores the refusal), so an enabled-tools payload no longer raises. They now pin BOTH halves - admitted by default, refused under the toggle - instead of an invariant that only holds with the env off.

* studio: an explicit Stop on a legacy turn persists cancelled, not the walk-away label it aborted under

* fix(test): update auto-compaction test for durable-gate image_base64 derivation

The chat adapter now derives image_base64 from THIS turn's messages only
(findLatestUserImageBase64(currentTurnMessages)) rather than a hoisted
variable, so a media turn cannot lose compaction fields and a stale
screenshot from an earlier turn doesn't make the backend see a non-empty
media field on later text-only turns.

This updates the source-shape assertion to match the new pattern.

* studio: tool turns ride the durable path as shipped behavior, not a diagnostic

The flip was landed as TEMPORARY DIAGNOSTIC so a restart alone activated it while replay-as-parts was still
being built out. Replay now re-tags persisted frames exactly as the live stream yields them, so default-ON is
the shipped behavior and UNSLOTH_STUDIO_DURABLE_TOOL_TURNS is an escape hatch that restores the old refusal -
the comment says that instead of promising a revert that isn't coming. Flag block wording kept byte-identical
to the media PR's flip wording, so restacking that commit onto this tip applies clean.

* studio: deny a durable park at the approval timeout, not the lease window

An unanswered approval previously held its inference slot for the full
lease window (~20 min) because the durable flag suppressed the 3600s
ceiling and only the sweeper could release it. For agentic work where
the user has left, that stalls the loop unnecessarily.

Add UNSLOTH_STUDIO_TOOL_APPROVAL_TIMEOUT_S (default 300s) as the
park-specific ceiling. wait_tool_decision now denies at that timeout
instead of waiting indefinitely, so the model receives
TOOL_REJECTED_MESSAGE and adapts. Set to 0 for fully autonomous mode.
The sweeper remains a backstop for producers wedged before they reach
the gate.

* fix: remove duplicate closing brace from conflict resolution in chat-adapter.ts

* studio: drop the redundant top-level media echo from stored runs

The base64 blob already rides in messages[].content as a data URI.
Storing it again at the top level (image_base64/audio_base64/
video_base64) tripled the per-turn cost for image-heavy threads with
nothing sweeping those rows.

_strip: _sanitize_request now pops the media fields from the stored
payload after validation. The live request still carries them for the
inference path; only the persisted copy loses the duplicate.

_rehydrate: at replay time, _rehydrate_media_fields extracts the
base64 back from the content array before model_validate, so the
inference code sees the same shape as a live request.

3x -> 2x per media turn (thread copy + request_json messages), with
no new machinery and no TTL needed.

* Revert "studio: drop the redundant top-level media echo from stored runs"

This reverts commit fbeed49.

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

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

* studio: persist a failed turn as interrupted even when it produced no text

The error-path partial yield was wrapped in 'if (partialContent.length > 0)', so a turn that errored before any text never persisted its incomplete reason at all. That contradicts chat-continuation.test.ts ('a turn that fails before any text is still saved as interrupted') and the invariant pinned elsewhere that publishing the reason must not depend on renderable content. Drop the guard so the yield always runs; the body is unchanged.

* studio: route the durability gate through isDurableRunCandidate

chat-adapter built generationCandidate as an inline Boolean(...) conjunction, while durable-gate.ts already extracted the same rule as isDurableRunCandidate({...}) and its tests pinned that call - so test_multi_chat_prompt_queue_contract.py asserted a marker that was never in the adapter. Call the shared gate with the resolved values; each term maps 1:1 to the old conjunction, so behavior is unchanged. The two object-literal adjustments (incognito guarded on threadId, hasUserMessage coerced) only keep the types honest - truthiness is identical.

* tests: gate the stopping-criteria device test on has_real_cuda, not the spoofable probe

The accelerator skip-guard (test_no_skip_guard_reads_a_spoofable_accelerator_probe) flags any test that gates hardware on torch.cuda.is_available(), which tests/_zoo_aggressive_cuda_spoof.py patches True process-wide. test_stopping_criteria_device.py still used it, so 'Repo tests (CPU, python)' failed 10/10 on this branch while passing on main. Adopt main's fix: use has_real_cuda() and bring in the matching real_accelerator helper that defines it.

* studio: a reopened tab can answer the approval its tool call is parked on

A durable tool turn parks the backend on a human decision and keeps waiting for the returning
session, which is the whole point of the park. The reopened tab rebuilt the card but had no way
to answer it: createGenerationToolRecovery never read awaiting_confirmation and never registered
with the confirmation store, whose only call site was the live adapter, and
ToolConfirmationControls renders Approve/Deny only for a card the store knows about. So the tab
came back to a spinner over a call nobody could allow, and the run sat parked until the ceiling
denied it for the user.

Recovery now arms the card both ways a parked call can reach a reopened tab. A call that parks
after the tab reattaches arms itself as its tool_start folds. A call that parked BEFORE the tab
closed has its tool_start at or below the cursor, so no frame ever re-folds it and the seed is
the only place it still exists: armSeededApprovals re-raises those once the follower learns the
run's session, which is what the decision resolves against. Both paths key the card by its own
toolCallId and scope it exactly as the live stream does, so arming the same call twice is one
card, and a recovery only ever resolves a card it armed itself.

The hooks are passed in rather than imported, so the util stays a util and the caller keeps the
store. The recovery test harness gains the two store methods the real store has always had.

* studio: a park ceiling nobody can parse falls back instead of taking the backend down

UNSLOTH_STUDIO_TOOL_APPROVAL_TIMEOUT_S was read as a bare float() at module scope, so
UNSLOTH_STUDIO_TOOL_APPROVAL_TIMEOUT_S=5m raised ValueError while state.tool_approvals was being
imported. That module is on the chat path, so a typo in an environment variable stopped the
backend from starting at all. It now warns and uses the default, as do a negative, NaN or
infinite value, which would otherwise disable the ceiling silently. A parsed value still applies
exactly as before, and the read stays at import so one run cannot move the ceiling mid-flight.

The marker comment on the durable cancel_event still described the behaviour that shipped before
the park ceiling existed: it promised the lease sweeper was the only thing that released an
unanswered approval, at roughly 1200s. The ceiling releases it first, at 300s by default, and a
user who returns after that finds the call already declined rather than still waiting. The
comment now names both releases and which comes first.

Also pinned: the ceiling reads every shape of env value without raising, an unset one is the
documented default, a zero ceiling denies at the first poll rather than instantly so a decision
inside that first 500ms still wins, and a session returning past the ceiling can no longer
resolve its own approval.

* tests: name the media contract test after what this branch actually does

test_base64_media_turns_are_durable_and_their_attachments_stay_turn_scoped said a media turn is
durable now. It is not, on this branch: the gate still sends a turn carrying its own attachment
to the legacy stream, and _sanitize_request still refuses a populated media payload. What
changed is that such a turn stops refusing its text-only FOLLOW-UPS, which is what the
assertions check. Admitting the media turn itself is a separate change in unslothai#10406.

Assertions are untouched; the name, the docstring and two failure messages now describe them.

* studio: say what the park ceiling actually bounds, which is one wait and not the run

The comment added a commit ago claimed the reservation is held "for at most the park ceiling".
It is not. The ceiling ends one approval WAIT: the gate denies, the loop appends the denial as a
tool message and keeps generating, and the InferenceActivityReservation is released by the
producer unwinding and by nothing else. A turn that parks on several calls in a row holds the
reservation across several ceilings, and the progress between them renews the lease, so the
sweeper only bounds a producer that stops making progress at all.

Found by reading the denial path in llama_cpp.py against the release in this file rather than
trusting the sentence, which is the sort of claim a comment gets believed for.

* studio: arm a seeded approval only while its run can still answer

A call that parked before the tab closed is re-raised from the saved message by
armSeededApprovals, which restores the Approve/Deny the reopened tab had no other
way to show. That call was unconditional, so a run which settled while it was
parked re-armed the card too: a backend restart terminalises surviving rows, the
in-memory pending slot is gone, and no tool_end is coming to disarm the card. The
reopened tab then offered buttons whose confirm could only return 404.

Gate on the run still being answerable, using the isTerminalChatGenerationRun this
file already imports, so the terminal set stays defined in one place.

The follow loop has no behavioural test that does not need a live EventSource, so
the call site is pinned instead: tests/seeded-approval-terminal-run.test.ts asserts
the guard, that the check is imported rather than reinvented, and that the call site
exists at all, so the assertion cannot pass by finding nothing.

* studio: take recovered approval cards down when the run ends, not only when a call ends

The per-call disarm runs on tool_end. A run that terminates without one, because
the backend failed or restarted while the call was parked, never reaches it, so
the card outlived its own run: buttons still on screen, the tool group still open,
and a decision that could only 404 since the pending slot went with the restart.

The terminal check added at the call site covers a run that was ALREADY terminal
when recovery attached. It does not cover one that gets there afterwards, which is
the case a watching tab actually sees. Add a run-level sweep and call it where the
follow loop already recognises a terminal snapshot.

Scoped and idempotent for the same reason the per-call disarm is: a recovery shares
the confirmation store with whatever else is on screen, so it resolves only cards it
armed itself, and the follow loop can see more than one terminal snapshot.

* studio: keep an inline base64 image off the durable path, wherever it sits

The media guard was field-shaped plus nested audio and video. It had no nested
image check, and it did not need one while a thread holding a screenshot was
pushed onto the legacy stream wholesale. Turn-scoping removed that: a text-only
follow-up no longer sets top-level image_base64, yet the thread's earlier
screenshot still rides along inside messages[].content, so the follow-up was
admitted to the durable path.

A durable run persists its request verbatim, so that blob was written into
request_json again on every follow-up turn for the life of the thread, which is
the exact cost the guard's own comment says it exists to prevent.

_messages_have_embedded_image matches an inline data URL only. A remote image_url
is a short string that costs nothing to persist and has no business giving up
durability, so it stays admitted; the narrow match is pinned by a test, as is the
plain-text case, because a guard that over-matched would push every turn back onto
the legacy stream and the feature would stop working silently.

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

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

* studio: ask whether a parked approval is still waiting before restoring its buttons

Recovery inferred 'still parked' from the shape of the saved card: no result, and
an approval id. A call the user already answered looks exactly the same, because
the result only arrives with tool_end. So closing the tab between the click and
the tool finishing, then reopening, put Approve/Deny back over a call that was
already executing, and every press returned 404 until it finished.

The card cannot answer this and neither could anything else that was persisted:
awaiting_confirmation rides only on tool_start, no event marks a decision, and the
run snapshot carries no approval state. So the state is asked for. tool-approval-status
takes the approval id in the body and answers pending or not, scoped to the session
like resolve_tool_decision and keyed on an id the caller already holds, so it cannot
be used to enumerate anyone else's approvals. A set event counts as decided, which
closes the window between the decision and the waiter popping its own slot.

Failure leans the safe way at both ends: an older backend answering 404 or 405, or
a check that throws, falls back to arming. Losing the buttons on a call that really
is parked is the worse outcome, and it is the one this whole path exists to prevent.

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

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

* Scope the tool approval park ceiling to unattended runs for PR unslothai#10365

The 300s park ceiling was keyed on cancel_event.durable alone, and the supervisor
sets that marker on every run it owns. Durable means cancel_on_disconnect is off,
not that the tab is gone, so with tool turns durable by default the ceiling applied
to a user sitting in front of an open Approve/Deny card: a decision that had 3600s
before this branch now expired after five minutes, with no countdown or warning
anywhere in the UI because the timeout is never serialized into any frame.

Three changes:

1. The ceiling now measures time with nobody watching rather than time since the
   call parked. The run's SSE follower stamps a presence heartbeat (new
   state/run_subscribers.py, keyed by run id, entries aged out after three
   keep-alive periods) and wait_tool_decision re-arms its deadline while a follower
   is attached, falling back to the module's own _DECISION_TIMEOUT as the absolute
   backstop so an attended run keeps exactly the hour a browser-owned run always
   had. An abandoned approval still releases at the park ceiling, so an unattended
   agentic loop is unaffected. A heartbeat rather than a reference count, because a
   leaked increment would park an abandoned approval forever.

2. An expiry is no longer reported as the user's decision. wait_tool_decision
   collapsed user-deny, run-cancelled and ceiling-expired into one bare "deny", so
   all three emitted TOOL_REJECTED_MESSAGE, "The user declined to run this tool
   call." That reached both the model and the reopened card as the only account of
   the call, and it is false for an expiry. wait_tool_decision_detail returns
   (verdict, reason) and the three tool loops pick TOOL_APPROVAL_EXPIRED_MESSAGE
   for an expiry. wait_tool_decision keeps its old signature and return, so every
   other caller is untouched and TOOL_REJECTED_MESSAGE is byte-identical for a real
   denial.

3. Pressing Allow on an approval that is already gone said "Could not send your
   decision. Try again." next to re-enabled buttons: the slot is popped, so every
   retry 404s until tool_end clears the card. The 404 now carries its own type,
   the card says the request is no longer waiting and disables the buttons, and
   Always allow records its session grant only after the backend takes the
   decision instead of on the click, where a visibly failed press still
   auto-approved the tool for the rest of the session.

Also pins the durable marker itself. Deleting cancel_event.durable = True left the
entire backend suite green, since every approval test sets the attribute by hand,
so the whole park feature could be disabled without a single test noticing.

Backend 46 + 62 pass, frontend 7858 pass, tsc -b clean, ruff clean. The existing
park, cancel and sweeper-settle tests pass unchanged.

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

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

* Keep wait_tool_decision as the single patchable waiter for PR unslothai#10365

The previous commit split the waiter into wait_tool_decision_detail to return
(verdict, reason) and pointed the three tool loops at it. That broke the loops'
patch target: tests/test_llama_cpp_tool_loop.py, test_safetensors_tool_loop.py
and test_studio_tool_loop.py monkeypatch core.inference.<loop>.wait_tool_decision
by name, and tests/test_refactor_guard.py resolves every string patch target, so
15 tests failed on the attribute no longer being there.

The reason now rides on the slot instead. wait_tool_decision keeps its name,
signature and bare "allow"/"deny" return, records why in slot["reason"], and the
loops read it back with decision_reason(slot) before dropping the slot in their
deny branch. A stubbed waiter that returns a bare string and never touches the
slot leaves the reason None, which falls back to TOOL_REJECTED_MESSAGE: exactly
the behaviour those tests expect.

Caught by staging CI on Datta0/unsloth-staging-3, which runs the tool-loop suites
this box cannot. Backend Windows, macOS, GGUF, API, Tauri, Wheel, studiobench and
Lint were already green on the same head.

tests/test_llama_cpp_tool_loop.py, test_safetensors_tool_loop.py,
test_studio_tool_loop.py, test_refactor_guard.py, test_tool_approvals.py and
test_chat_generation_runs.py: 686 passed. Frontend tool-approval-gone 6 passed,
tsc -b clean, ruff clean over studio/backend.

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

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

* Track approval attendance per follower, not per run, for PR unslothai#10365

One run can have several followers: two tabs on the same thread, or a reconnect
whose replacement stream attaches before the old one finishes unwinding. With a
single stamp per run, either follower's cleanup deleted the heartbeat the other
had just written, and the survivor does not stamp again until its event wait
turns over, which is up to 15s.

That is reachable. UNSLOTH_STUDIO_TOOL_APPROVAL_TIMEOUT_S below 15s is a
supported configuration, 0 included and already covered by a test, so a parked
approval could be denied while a second tab was actively watching it. That is the
exact failure the presence heartbeat was added to prevent.

_SEEN is now run_id -> {follower token: last heartbeat}. The SSE route mints one
token per stream, mark_subscriber_seen and subscriber_departed take it, and a
departure removes only that follower's entry, dropping the run key when the last
one goes. is_attended expires stale tokens as it reads them.

Reproduced first: two stamps then one departure left is_attended False. Pinned by
three tests, all red without the fix (test_one_tab_closing_leaves_another_tabs_
attendance_intact, test_an_attended_park_survives_a_second_tab_closing, and
test_a_follower_only_clears_its_own_stamp_not_the_run). test_tool_approvals 49
passed, formatter fixed point 11 passed, ruff clean.

* Do not hold the event stream closed while checking seeded approvals for PR unslothai#10365

followChatGenerationRun yields its snapshot before opening /events: the
`yield { run, source: "snapshot" }` in chat-generation-api.ts precedes the
streamChatGenerationEvents loop, so the generator sits suspended at that yield
while the consumer works. Awaiting armSeededApprovals there therefore serialises
the "is this approval still pending?" request AHEAD of the stream, and /events is
the only thing that marks the run attended server-side.

So a tab returning close to UNSLOTH_STUDIO_TOOL_APPROVAL_TIMEOUT_S could have its
approval expire during the very request asking whether it was still pending, and
be handed restored Allow / Deny buttons that can only 404. The window is the
duration of that round trip, which is wide enough to matter on a shortened
ceiling or a loaded server.

The call is no longer awaited at the call site. The promise is kept and joined
before disarmAll, so an arm that resolves late still cannot raise buttons on a
run that has already ended, and armSeededApprovals already treats an unanswerable
check as "still parked" so nothing is lost by letting it settle later.

Pinned by two AST tests alongside the existing terminal-run guard, in the same
file and for the same reason: the follow loop needs a live EventSource, so no
behavioural test in this suite reaches it. Re-adding the await turns the first
red. Frontend suite 7860 passed, tsc -b and tsc -p tsconfig.test.json clean.

* Renew the run lease while an approval is attended, for PR unslothai#10365

Re-arming the approval's own counter was not enough. Parking makes no progress,
so the run's lease still aged out: ChatGenerationLeaseSweeper settles it at
_LEASE_TIMEOUT_SECONDS (1200s by default) and supervisor.cancel() sets the same
cancel_event the waiter polls, which returns deny with DECISION_CANCELLED.

So an attended deliberation was capped at roughly 20 minutes and ended as a
cancel, while the docstring I added promised the full _DECISION_TIMEOUT. The
claim was wrong, not just the behaviour.

The supervisor now hands the waiter cancel_event.renew_lease, in the same
attribute idiom as durable and durable_run_id, and an attended park calls it
alongside re-arming its counter. Throttled to one call per _LEASE_RENEW_EVERY_S
(30s): the poll runs twice a second and this is a database write. A renewal that
raises is swallowed, because a lease we could not renew is the sweeper's problem
to discover rather than a reason to drop the decision. An UNATTENDED park never
renews, so the sweeper stays the backstop for an abandoned run, which is the one
thing it exists for.

Docstring corrected to say that reaching _DECISION_TIMEOUT depends on this.

Four tests, two of them red without the change: renewal happens when attended,
does not when unattended, is throttled to one call per window, and a cancel_event
carrying no renew_lease still parks correctly. test_tool_approvals 53 passed,
formatter fixed point green, ruff clean over studio/backend. The 14 failures in
test_chat_generation_run_lease.py when that file is run standalone are identical
with and without this change.

* Recheck a seeded approval after its status request, for PR unslothai#10365

Removing the await at the call site (50280e9) was right, but it opened this:
the replay now runs concurrently with the pending check, so tool_end can fold a
card while its status request is still in flight. disarmApproval is a no-op then,
because this recovery has not armed anything yet, and arming afterwards registers
an already-finished call.

Nothing renders buttons over it, since a part with a result is not `awaiting`.
The cost is the leaked store entry: it survives until disarmAll at the end of the
run, and `soleRequest` in tool-confirmation-controls counts entries, so a LATER
approval reads as non-sole and silently loses its Enter and Escape chords.

armSeededApprovals now re-reads entry.part after the await and skips a card that
gained a result meanwhile. The recheck rather than an unconditional disarm,
because disarmApproval is deliberately scoped to cards this recovery raised
itself: it shares the store with whatever else is on screen.

Two tests, the first red without the change: a card finished while its request
was in flight is not armed, and a card still unresolved when the request returns
is armed exactly as before. Frontend suite 7862 passed, tsc -b clean.

* Scope approval attendance by account, and disarm on every recovery exit, for PR unslothai#10365

Two findings from the same review round.

Attendance was keyed on the bare run id. studio.db is per-account
(utils.paths.storage_roots.studio_db_path resolves through account_path) and the
run id comes from the client (CreateChatGenerationRun.runId is a free-form string
the caller picks), so two accounts on one managed install can hold the same id.
A process-global map keyed on that id alone let one tenant's follower report
another tenant's run as attended: it would hold a stranger's approval open past
its ceiling and keep renewing that run's lease, pinning an inference slot the
other account never asked to hold.

_SEEN is now keyed on (account_id, run_id). The supervisor stamps
cancel_event.durable_account_id from the same current_account_id() that
ActiveGeneration captures beside it, the SSE route passes its own, and a missing
account is its own scope rather than a wildcard, so a caller that cannot name its
account never matches one that can.

Second, disarmAll ran only after a terminal snapshot. A permanent follower error
(another tab deletes the thread, the run row cascades, the next request 404s)
throws past that branch and is swallowed by the outer catch, so a card armed from
the seed stayed in the global toolConfirmations store for the rest of the
session. Nothing renders buttons over a finished part, but soleRequest counts
entries, so a later real approval read as non-sole and silently lost its Enter
and Escape chords. The disarm moved into the recovery's finally, which every exit
reaches, with the seed joined first as before; the terminal-path copy is gone so
the two cannot disagree about ordering.

Six tests, all red against their own mutation: three for the account key, two
pinning the disarm into the finally, one that the join still precedes it.
Backend 129 passed across approvals, generation runs and the formatter fixed
point. Frontend 7863 passed, tsc -b clean, ruff clean over studio/backend.

* Trim the comments added for PR unslothai#10365 to the facts that change behaviour

---------

Co-authored-by: CelesteHeartsong <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
@danielhanchen danielhanchen self-assigned this Oct 5, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Thanks for all the work on this, and for cutting the top-level echo when asked. I am closing this one for now rather than taking it over, for three reasons, all measured on the current head 6dc4512cd against main a1ff98b84.

1. The blob is persisted once per turn of the thread, not 2x. Every follow-up in an image thread carries the earlier image inside messages[].content, and with the embedded-image refusal removed each of those follow-ups now goes durable and stores it again in request_json, which nothing ever sweeps. Calling _sanitize_request with one 1 MB image and five text-only follow-ups:

turn main this PR (default) this PR, UNSLOTH_STUDIO_DURABLE_MEDIA_TURNS=0
0 (image attached) refused, legacy stream durable, 1.33 MB refused
1..5 (text follow-ups) refused, legacy stream durable, 1.33 MB each durable, 1.33 MB each
stored after 6 turns 0 MB 8.01 MB 6.67 MB

So growth is linear in the number of turns per image, and the toggle does not restore the original refusal either: with it off, only the turn that sets the top-level field is refused, which undoes the turn-scoping fix main carries for exactly this case.

2. The branch would revert work that landed on main after it forked. Against main the diff drops the timezone headers (#11852), the API monitor origin (#12305), extra_audio_base64 (#12267) and mcp_image (#10871) from _MEDIA_FIELDS and the durable producer, the tool-heartbeat / prefill-progress lease renewal and quote_cut, and it also carries the whole replay engine from #10910 (chat-generation-replay.ts, tool-result-shape.ts and their tests), which is still open. With extra_audio_base64 gone, a durable multi-audio turn would silently lose every file after the first.

3. The premise is not on main yet. The case for flipping the default rests on faithful replay, which is #10910, not #10365.

The capability itself is worth having, so the path I would suggest is a fresh PR on main once #10910 lands, containing only the gate change plus content-addressed storage for attachments (store each blob once, keyed by hash, and rehydrate at replay), so an image thread costs one copy regardless of how many turns follow it. Happy to review that when it is up.

@CelesteHeartsong
CelesteHeartsong deleted the feat/durable-media-turns branch October 7, 2026 23:25
danielhanchen pushed a commit that referenced this pull request Nov 4, 2026
Once a chat held an image, every later text message in it lost its
background run. The reply was tied to the open tab, so closing or
reloading the tab stopped it and the reopened chat showed an empty
reply. Text-only chats keep generating in the same situation.

Text follow-ups in those chats now run in the background like any other
message, and the model still sees the earlier image. The image is kept
out of the saved run, so a long image chat adds no extra copies to the
database: the run stores a hash and the image stays in memory only until
generation starts. A message that carries its own attachment still uses
the live stream, as before.

The review on #10406 objected to a stored copy of the image per turn and
suggested content-addressed storage with rehydration at replay. This
goes further on storage: nothing is stored, because the worker reads the
request once and a restart fails the run anyway.
test_a_text_only_follow_up_carrying_an_earlier_inline_image_stays_legacy
pinned the old refusal and is replaced. Earlier video or audio
attachments still use the live stream.

| | Before | After |
|---|---|---|
| Reopened image chat after closing the tab during a text follow-up |
![before](https://raw.githubusercontent.com/NilayYadav/unsloth-staging/pr-media/pr/16491/main-5819e6c-image-followup-after-tab-close-7289777f51c4.png)
|
![after](https://raw.githubusercontent.com/NilayYadav/unsloth-staging/pr-media/pr/16491/branch-5819e6c+fix-image-followup-after-tab-close-1f80ded1ec8e.png)
|

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants