Repository navigation
feat(chat): make agentic turns survive tab-close - #10365
Conversation
|
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. |
|
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. |
|
Going to work on splitting into the two separate tasks
|
110678c to
6697c66
Compare
|
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 |
|
Follow-up PR for making media turns durable after this is completed: #10406 |
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. |
|
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: And we're now leaking between thought/response in the opposite direction. (Thoughts leaking into response instead of response leaking into thoughts) |
Fixed in b354208 Seconds for thought cards are now fetched in a re-opened session. |
|
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 1491f227 - the mirror case. Pinned by tests: both shapes now replay exactly as |
|
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:
Separately: several of the other red checks here (the three |
1491f22 to
d84f8f7
Compare
…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.
…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.
|
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
park = bool(getattr(cancel_event, "durable", False))
effective_timeout = _PARK_TIMEOUT_S if park else timeoutDurable means Three things made it worse than a number being too small:
Reproduced rather than argued: removing the attendance re-arm from my fix turns Before and after
What I pushed
Two mistakes of mine in that sequence, both caught by staging and fixed: the first version split the waiter into Gate A, executableReverting each hunk one at a time, the named tests go red:
VerificationLocal: 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:
The branch merges onto current main with no conflicts, and every symbol it depends on still resolves. What I could not prove
Good branch. The replay work is better than my Sep 7 note claimed: |
…#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




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; nevertools, which is the passthrough caller's schema catalog), andBROWSER_EXECUTED_TOOLSships 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_eventcarries the durable flag;wait_tool_decisionwaits for the returning session instead of silently denying at a fixed ceiling — it is now bounded byUNSLOTH_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 asinterruptedand 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 latchescancelled. (The legacy-stream Stop labelling is a known open item from review — see danielhanchen's Sep 20 note.)Split out (not in this diff)
createRecoveryReplay/ parts accumulator, catch-up watermark, thought-tag and duration preservation, and tool-result shaping so a reopened tab renders cards exactly as a watched one did. This branch persists the frames those replay features read; feat(chat): faithful replay of durable runs — parts accumulator, catch-up watermark, card fidelity #10910 adds the replay layer on top.Caveats
_pendingslot is in-memory). Intentional — a session isn't expected to outlive the app.interruptedreason for walk-away; a distinct label (e.g.detached) is a one-enum change if preferred. B's sweeper settle lands oninterruptedtoo, by design.UNSLOTH_STUDIO_DURABLE_TOOL_TURNS=0restores 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
npm test0 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.)test_tool_approvalsgreen — the park ceiling bounds the wait, explicit Stop denies, and the sweeper-settle release chain is pinned end to end;test_chat_generation_runsgreen 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 base448bf6b05and 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_searchunder "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.
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.
Measured alongside the pictures, since a screenshot cannot be diffed:
448bf6b05The 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
448bf6b05a 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
terminalcall 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, soPOST /api/inference/tool-confirmanswers 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.
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_endclears the card. AFTER says the request is no longer waiting and disables the buttons.Measured alongside the pictures, since a screenshot cannot be diffed:
c0c40bc1b021273cd2The 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.