Skip to content

feat(chat): make agentic turns survive tab-close - #10365

Merged
danielhanchen merged 41 commits into
unslothai:mainfrom
CelesteHeartsong:feat/durable-agentic-turns
Sep 22, 2026
Merged

danielhanchen merged 41 commits into
unslothai:mainfrom
CelesteHeartsong:feat/durable-agentic-turns

Conversation

@CelesteHeartsong

@CelesteHeartsong CelesteHeartsong commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

TL;DR

Agentic/tool-using chat turns survive a browser close. Server-executed tool loops run to completion on the durable stream instead of dying when the tab closes, and an approval that parks while you're away stays parked — it re-opens in a fresh tab with its Allow / Always allow / Deny buttons still live, so it can be answered and the tool then runs. A walk-away reads interrupted (partial kept + Resume) rather than blank/cancelled.

Two related pieces are split out to their own stacked PRs and are not in this diff: the default-on media toggle (#10406) and faithful replay fidelity — parts accumulator, catch-up watermark, thought-tag/duration preservation, tool-result shaping (#10910). This branch is the base both build on.

What

  • A — server-executed tool turns go durable. The gate keys on THIS turn's attachments and enabled_tools (durable-gate.ts; never tools, which is the passthrough caller's schema catalog), and BROWSER_EXECUTED_TOOLS ships empty — the set exists to name the exception, not to re-list the server's own tools. An auto/bypass loop runs to completion while you're away; a media-bearing turn no longer gets 400'd out of the durable path by a stale blob from an earlier turn (the payload's attachment channel is now turn-scoped too), and a media-policy 400 degrades silently like every other policy rejection.

  • B — parked approvals don't auto-deny, and they reopen parked. The run's cancel_event carries the durable flag; wait_tool_decision waits for the returning session instead of silently denying at a fixed ceiling — it is now bounded by UNSLOTH_STUDIO_TOOL_APPROVAL_TIMEOUT_S (default 300s) so an unanswered approval can't hold its inference slot indefinitely, and an explicit Stop still denies. A call that is still parked when the tab closed is re-raised in a fresh tab: recovery arms the confirmation card (armSeededApprovals → setToolConfirmation) keyed by tool-call id and scope exactly as the live stream does, so Approve/Deny render here and clicking Allow runs the tool. (The fuller replay-based version of this lives in feat(chat): faithful replay of durable runs — parts accumulator, catch-up watermark, card fidelity #10910; this is the minimum that works on this branch.) What releases an approval nobody answers: parking does not renew the progress lease, so the sweeper settles the aged run as interrupted and its settle-cancel sets the same event — the waiter denies, pops its own slot, and the producer unwinding balances the reservation.

  • C — a tab-close reads interrupted, not blank/cancelled. A walk-away keeps the partial output and offers Resume; on durable turns an explicit Stop still latches cancelled. (The legacy-stream Stop labelling is a known open item from review — see danielhanchen's Sep 20 note.)

Split out (not in this diff)

Caveats

  • B is memory-only: a park survives a browser close, not an Unsloth restart (the _pending slot is in-memory). Intentional — a session isn't expected to outlive the app.
  • C reuses the existing interrupted reason for walk-away; a distinct label (e.g. detached) is a one-enum change if preferred. B's sweeper settle lands on interrupted too, by design.
  • The tool-turn refusal toggle (UNSLOTH_STUDIO_DURABLE_TOOL_TURNS=0 restores the refusal) ships ON as a shipped default, not a diagnostic; both halves — admitted by default, refused under the toggle — are pinned by paired tests.

Tests

  • Frontend suite green on this head (verified in the Sep 20 review: npm test 0 failing; tsc -b, build, and ruff clean). New here: turn-scoped durable-gate pairs, generation-tool-recovery approval arming/disarming, seeded-approval-on-terminal-run, and reconnect coverage. (The parts-accumulator / replay-durations / replay re-tagging suites ship with feat(chat): faithful replay of durable runs — parts accumulator, catch-up watermark, card fidelity #10910.)
  • Backend: test_tool_approvals green — the park ceiling bounds the wait, explicit Stop denies, and the sweeper-settle release chain is pinned end to end; test_chat_generation_runs green including accept-by-default/toggle-off pairs.

Depends on

Nothing else needs to merge first — this branch is the base that #10406 (media turns durable) and #10910 (faithful replay) stack on, and both rebase onto main once this lands.


Browser evidence, merge base vs head

Added by danielhanchen while reviewing. Two isolated installs built from the trees themselves (install.sh --local), BEFORE from the merge base 448bf6b05 and AFTER from a reviewed head, same model and quant (Qwen3-1.7B-GGUF UD-Q4_K_XL), same prompt, same composer state.

The turn parks on web_search under "Ask for approval", the tab is closed while the call is still waiting, and a brand new tab is opened on the same thread.

Control, while the tab is still open. Both halves park identically, so the two installs are comparable and the reopen is the only variable.

live approval, before and after

The claim, after closing the tab and reopening. BEFORE keeps the prompt and an empty assistant turn with only the action icons: the legacy stream died with the tab, so there is nothing left to approve. AFTER still shows the call pending, with Allow / Always allow / Deny, a live spinner on the thread entry and a stop button in the composer.

reopened approval, before and after

Measured alongside the pictures, since a screenshot cannot be diffed:

fact BEFORE 448bf6b05 AFTER (reviewed head)
parked while the tab was open true true
approval controls, tab open 2 2
approval controls after reopening 0 2
approval usable after reopening false true
the tool actually ran once approved n/a true

The last row is the one that matters beyond the picture: the restored card is pressed, and the search runs. A card that renders but cannot act would not be a fix.


Browser evidence for the review fixes, PR head vs PR head plus fixes

Added by danielhanchen. Two isolated installs built from the trees themselves (install.sh --local).

These refs are deliberately not the PR's merge base. At 448bf6b05 a tool turn cannot reach the durable path at all, so an approval never expires and the surface below does not exist. BEFORE is therefore the PR head as submitted, c0c40bc1b, and AFTER is that head plus the review fixes, 021273cd2.

The turn parks on a terminal call under "Ask for approval". The approval id it carries is one the backend never minted, which is exactly the state an expired approval leaves behind, so POST /api/inference/tool-confirm answers a real 404 on both sides rather than a stubbed one.

Control, before anything is pressed. Both halves park identically, so the two installs are comparable and the press is the only variable.

parked approval, before and after

The claim, after pressing Allow on an approval the backend is no longer holding. BEFORE says the decision could not be sent and invites a retry, with all three buttons still live; every retry 404s the same way until tool_end clears the card. AFTER says the request is no longer waiting and disables the buttons.

pressed approval, before and after

Measured alongside the pictures, since a screenshot cannot be diffed:

fact BEFORE c0c40bc1b AFTER 021273cd2
approval controls while parked Allow, Always allow, Deny Allow, Always allow, Deny
all three enabled while parked true true
tool-confirm response 404 404
line shown after pressing Allow Could not send your decision. Try again. This request is no longer waiting for an answer.
all three buttons disabled after pressing false true

The control row is the one that makes the rest readable: both halves park the same way, so the second shot is a difference in what the card does with the 404 and not a difference in what was on screen to begin with.

@CelesteHeartsong

Copy link
Copy Markdown
Contributor Author

Live test didn't run successfully, continuing troubleshooting. Cutting off a response mid-generation does give a "Continue" option, but if the run isn't web-browser required, then it should just keep going in the background and show up in other browsers.

@danielhanchen

Copy link
Copy Markdown
Member

With the durable flag set on every run in core/inference/chat_generation_runs.py, wait_tool_decision no longer has any ceiling, so an approval nobody answers looks like it holds its inference reservation forever; could you confirm what releases that slot, and split the default-on media toggle out from the tool-turn work so each lands on its own?

@CelesteHeartsong

Copy link
Copy Markdown
Contributor Author

With the durable flag set on every run in core/inference/chat_generation_runs.py, wait_tool_decision no longer has any ceiling, so an approval nobody answers looks like it holds its inference reservation forever; could you confirm what releases that slot, and split the default-on media toggle out from the tool-turn work so each lands on its own?

The goal with with tool decisions is to queue/pause on them, display them once the user returns to the session. After the last commit we have queueing of the stream happening successfully, but it's resulting in undesired behavior where the entire stream queues up, causing long assistant responses to gradually fill in, sometimes across 5+ minutes on a long agentic tool response.

Keeping this in draft for now as I work through the initial pains before I have codex review the solution.

What spawned this effort was that when I was using the Unsloth WebUI via my phone, I could constantly accidentally kill the running generation whenever my phone would go into standby after like 30 seconds of inactivity.

@CelesteHeartsong

Copy link
Copy Markdown
Contributor Author

Going to work on splitting into the two separate tasks

  • Default-on media toggle
  • Tool-turn work

@CelesteHeartsong
CelesteHeartsong force-pushed the feat/durable-agentic-turns branch from 110678c to 6697c66 Compare September 6, 2026 23:34
@CelesteHeartsong

Copy link
Copy Markdown
Contributor Author

On the reservation: it's not forever because parking doesn't renew the lease (keep-alives don't stamp progress), so the sweeper settles the run at lease expiry, cancels it, wait_tool_decision returns deny and pops its own slot, and the reservation is released. So an unanswered approval holds keepwarm ~20 min, same as a non-durable run would; the durable flag only removed the 3600s auto-deny, not the sweeper.

Split's done too, this PR is tool-turns only now, media toggle is its own stacked branch

@CelesteHeartsong

Copy link
Copy Markdown
Contributor Author

Follow-up PR for making media turns durable after this is completed: #10406

@CelesteHeartsong

Copy link
Copy Markdown
Contributor Author

Tool calls are no longer disappearing when the session is closed and re-opened during generation. Opened and closed my browser while generating this response like half a dozen times. Still not happy with how the stream starts from the beginning when the user returns to the session, causing sometimes a minutes long delay where you're waiting for the response to "stream in" while the assistant is already finished:

{D77F9E3A-57D8-4517-A8F3-4E7A6FC5DF08}

@CelesteHeartsong

CelesteHeartsong commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor Author

Also, it seems recovery is mangling the split between response and thought:

{E89D3317-0DE5-4253-840C-4C7FAADDA2ED}

@CelesteHeartsong

Copy link
Copy Markdown
Contributor Author

Tool calls are no longer disappearing when the session is closed and re-opened during generation. Opened and closed my browser while generating this response like half a dozen times. Still not happy with how the stream starts from the beginning when the user returns to the session, causing sometimes a minutes long delay where you're waiting for the response to "stream in" while the assistant is already finished:

Fixed in 10b70fb

Now if a thread/session is resumed it won't start at the beginning of the stream, it pops up to the current state of the stream and resumes streaming output from there.

@CelesteHeartsong

Copy link
Copy Markdown
Contributor Author

Thought cards are now retained during session resume in 742f43a

Some cleanup, we do still seem to lose the duration of thought even thought we keep the cards now:
{EF01A8F5-6AD9-4007-BAA9-1DE77FA1AE85}

And we're now leaking between thought/response in the opposite direction. (Thoughts leaking into response instead of response leaking into thoughts)
{3092B763-99B2-43A4-82C8-D81B7D98D87E}

@CelesteHeartsong

Copy link
Copy Markdown
Contributor Author

Some cleanup, we do still seem to lose the duration of thought even thought we keep the cards now

Fixed in b354208

Seconds for thought cards are now fetched in a re-opened session.

@CelesteHeartsong

Copy link
Copy Markdown
Contributor Author

Both halves of the thought/response leak are fixed now.

705e3dfd - a replayed thought keeps its own tags, so the answer keeps its own text. A model that carries its own <think>/</think> tags inside delta.content classifies its own thought: the live stream appends such a delta verbatim and closes a block only when it opened one (reasoningContentOpen, set solely for a reasoning_content/reasoning_details frame). The replay closed whatever block the run sat in regardless of who opened it, so the first answer delta of a tagged run cut the thought mid-sentence and the model's own close tag survived as literal text in the answer part.

1491f227 - the mirror case. extractDeltaText wraps a structured thinking part in a full pair of tags, so such a frame arrives carrying an open tag of its own; appended verbatim into a block the replay had opened, that second open tag survived as literal text inside the thought. Only a chunk carrying an OPEN tag gets closed out from under first - a chunk carrying only a CLOSE does not, since that tag ends whichever block is open either way, which is what the model's own close does to a block the seed re-created.

Pinned by tests: both shapes now replay exactly as parseAssistantContent of the same frames reads them, and reopening at any point of a tagged run yields the same parts as a stream that never left. Both fail without their commit. Frontend suite 6962 pass / 0 fail, tsc -b clean.

@danielhanchen

Copy link
Copy Markdown
Member

Repo tests (CPU) here fails on tests/studio/test_multi_chat_prompt_queue_contract.py::test_base64_media_turns_stay_on_the_legacy_stream, and this PR is where it starts: changing the gate from !imageBase64 to !currentTurnCarriesMedia breaks the assertion, which still spells the old token. I confirmed by running the test at this branch's head and at #10406's, and it fails identically on both. #10406 only removes the line that was already failing, so the test update belongs here, in the PR that changes the gate.

I have written up the replacement test and the reasoning on #10406: #10406 (comment) - it keeps the routing intent instead of deleting the assertion, and additionally pins the turn-scoped attachment channel this PR introduces (the mis-attribution where a stale blob made the backend 400 every later turn), which nothing currently guards. Mutation-tested against four regressions including reverting the gate to this PR's exact state.

Two findings from that trace that belong to this PR rather than to #10406:

  1. Replay is not faithful for tool turns. 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 or Deny. This is on by default here.

  2. test_durable_cancel_still_denies asserts nothing. studio/backend/tests/test_tool_approvals.py:285-286 is docstring-only as of 62f5c2421, and its former body is sitting as dead duplicate code at the tail of the test below it. Worth restoring before this lands, given what it was covering.

Separately: several of the other red checks here (the three Core jobs, Chat UI, API, Update and GGUF inference) are stale rather than yours. They predate unsloth-zoo #1175 and unsloth #10420, both of which landed on main this morning. A rebase or a rerun should clear them; #10406 went green on all three Core jobs after a rerun.

@CelesteHeartsong
CelesteHeartsong force-pushed the feat/durable-agentic-turns branch from 1491f22 to d84f8f7 Compare September 8, 2026 03:25
…hai#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 Bot and others added 2 commits September 21, 2026 07:25
…ai#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.
@danielhanchen

Copy link
Copy Markdown
Member

issue: REAL | PR as submitted: DEFECTIVE, 1 fixed by me | merge: YES

Closing a tab really did kill a tool turn, this branch really does fix it, and the browser evidence above holds up. One thing it got wrong: the new 300s approval ceiling was keyed on a flag that says nothing about whether anyone is watching, so it applied to a user sitting in front of an open Approve / Deny card, where the decision used to have an hour. I pushed a fix for that rather than sending it back, plus a test for a hunk nothing was pinning.

The defect

core/inference/chat_generation_runs.py:513 set cancel_event.durable = True unconditionally, when the reservation is created, and nothing ever cleared it. state/tool_approvals.py:90-91 then keyed the ceiling off that marker alone:

park = bool(getattr(cancel_event, "durable", False))
effective_timeout = _PARK_TIMEOUT_S if park else timeout

Durable means cancel_on_disconnect is off, not that the tab is gone, and wait_tool_decision never consulted whether a subscriber was attached. Since BROWSER_EXECUTED_TOOLS ships empty and the backend default is ON, every local tool turn took this path, so the ceiling written for an unattended agent became the ceiling for everyone.

Three things made it worse than a number being too small:

  1. The three loops collapse user-deny, run-cancelled and ceiling-expired into one bare "deny", so an expiry emitted TOOL_REJECTED_MESSAGE, "The user declined to run this tool call." That reached both the model and the card as the only account of the call, and it is false.
  2. Pressing Allow at 301s 404s, because the slot is popped in wait_tool_decision's finally. The frontend's parseJsonOrThrow throws into a bare catch {}, so the card rendered "Could not send your decision. Try again." next to re-enabled buttons. Retrying can never succeed.
  3. There is no countdown or expiry hint anywhere, and there could not be: the timeout is never serialized into any frame, and the store entry carries no timestamp. The only time-related text is the static "Waiting for approval..." spinner, which reads as an unbounded wait.

Reproduced rather than argued: removing the attendance re-arm from my fix turns test_an_attended_park_does_not_expire_at_the_park_ceiling red, and that mutation is this branch as submitted.

Before and after

behaviour this branch as submitted with the fix
tool turn survives a tab close yes yes, unchanged
parked approval reopens answerable yes yes, unchanged
approval with the tab OPEN, 5 min auto-denied still waiting, up to _DECISION_TIMEOUT as before
approval with nobody watching, 5 min auto-denied auto-denied, unchanged
what the model and the card are told on expiry "The user declined to run this tool call." "This tool call was not run: nobody answered the approval request in time."
pressing Allow after expiry "Could not send your decision. Try again.", buttons live "This request is no longer waiting for an answer.", buttons disabled
Always allow on a press that fails session grant recorded anyway recorded only after the backend takes the decision

What I pushed

  • state/run_subscribers.py (new). The run's SSE follower stamps a presence heartbeat keyed by run id; entries age out after three keep-alive periods. wait_tool_decision re-arms its deadline while a follower is attached, with _DECISION_TIMEOUT as the absolute backstop, so the ceiling measures time with nobody watching rather than time since the call parked. A heartbeat rather than a reference count on purpose: a leaked increment would park an abandoned approval forever, and the stamp expiring on its own fails the safe way.
  • A reason on the slot. wait_tool_decision keeps its name, signature and bare "allow"/"deny" return and records why in slot["reason"]; the loops read it with decision_reason(slot). Deliberate: the loops are monkeypatched by name in test_llama_cpp_tool_loop.py and friends, and test_refactor_guard.py resolves every string patch target. I learned that the hard way, see below. A stubbed waiter leaves the reason None, which falls back to TOOL_REJECTED_MESSAGE exactly as before.
  • The 404 made legible, plus moving allowToolAlways after a successful resolve.
  • A test for cancel_event.durable = True. Deleting that line left the entire backend suite green, because every approval test sets the attribute by hand. The park feature could have been disabled without a single test noticing. test_the_producers_cancel_event_carries_the_durable_marker_and_its_run_id now reads it off the producer.

Two mistakes of mine in that sequence, both caught by staging and fixed: the first version split the waiter into wait_tool_decision_detail and broke 15 tests that patch the old name, and tool_approvals.py landed one blank line off the repo formatter's fixed point. The formatter test skips itself on a ruff version mismatch, which is why a local run looked clean.

Gate A, executable

Reverting each hunk one at a time, the named tests go red:

reverted hunk result
not _durable_tools and guard RED, 4 admission tests
guard regrouped to bind only raw["tools"] RED, same 4
_messages_have_embedded_image dropped RED
url.startswith("data:") widened RED, 2 tests
park ceiling range guard RED, the -1 / nan / inf cases
turnCarriesMedia back to thread-scoped RED, gate + contract
cancel_event.durable = True GREEN, unpinned (now fixed)

Verification

Local: test_tool_approvals 46, test_chat_generation_runs 62, test_chat_generation_supervisor marker test, test_llama_cpp_tool_loop + test_safetensors_tool_loop + test_studio_tool_loop + test_refactor_guard 686 combined, contract 16, formatter fixed point 11. Frontend 7858 pass / 0 fail, tsc -b and tsc -p tsconfig.test.json clean, ruff clean over studio/backend. Every pre-existing park, cancel and sweeper-settle test passes unchanged.

Staging CI on an owned repo, fresh main plus this head, against a control arm built from the same main plus the head without my commits. Both arms: 17 workflows green including Windows UI, Windows API, Windows GGUF, Apple Silicon macOS, Tauri, Core, studiobench and Lint. Both arms fail the same three, and all three are inherited:

  • Repo tests (CPU, studio): 3 contract tests that fail on main alone, verified locally at 175c07050.
  • Repo tests (CPU, rest): test_source_read_encoding[5], whose offender is studio/backend/tests/test_reset_password_command.py:165, an unencoded read_text() that arrived on main in Studio auth and bootstrap gates: throttle desktop-login, narrow the tunnel CORS origin, identify Colab's proxy #11398. Fails on the fix arm only because main moved between the two stagings.
  • Frontend build + bundle sanity and Composer (ubuntu, browsers): fail on the control too. The frontend one is Tooltip must be used within TooltipProvider in the ANSI smoke, nothing this branch touches.

The branch merges onto current main with no conflicts, and every symbol it depends on still resolves.

What I could not prove

  • No real browser walk-through of the fix. The heartbeat is covered by unit tests and the staging Playwright legs, not by closing an actual tab and coming back.
  • The 45s presence window is three keep-alive periods by construction, not a number measured against real follower behaviour on a slow link.
  • Nothing about an Unsloth restart mid-park, which you already scope out.
  • tool_output (streaming stdout) is still dropped by the recovery consumer, so a reopened tab on a running python card shows a spinner until tool_end. feat(chat): faithful replay of durable runs — parts accumulator, catch-up watermark, card fidelity #10910 covers it, and before this branch the tab showed nothing at all, so it is a rough edge on a newly working path rather than a regression. No test guards it either way.
  • Minor, pre-existing, not for this PR: tool_decision_is_pending(approval_id, session_id=None) skips its scope check, so any authenticated caller can probe any approval id. Bounded by secrets.token_urlsafe(16), and resolve_tool_decision has the identical bypass already.

Good branch. The replay work is better than my Sep 7 note claimed: recoveredToolResult does shape __IMAGES__ / __MCP_IMAGES__ / image_b64 and withSources does rebuild Sources, so that finding was already addressed and I was reading stale code.

…#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.
…or 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.
…0365

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.
…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.
…it, 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.
# Conflicts:
#	studio/frontend/src/features/chat/runtime-provider.tsx
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

affects UI# important# new-feature# security# Moves a security boundary: sandbox, allowlist, permission or network guard

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants