Skip to content

Studio: stop two tabs both auto-continuing the same truncated reply - #9425

Merged
danielhanchen merged 11 commits into
mainfrom
studio-cross-tab-continuation-claim
Aug 23, 2026
Merged

danielhanchen merged 11 commits into
mainfrom
studio-cross-tab-continuation-claim

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Aug 20, 2026 •

Copy link
Copy Markdown
Member

Follow-up to the automatic Max Tokens continuation. The claim that stops a truncated reply being resumed twice is module state, so it only covers one tab.

The scenario

  1. A reply hits Max Tokens and is saved with reason: "length".
  2. The same thread is open in two browser tabs, both with that reply as the last message on the selected branch.
  3. Each tab loads its own copy of continuation.ts, so each has its own empty continued set. claimAutoContinue(messageId) returns true in both.
  4. Both tabs call startContinuation(). Two sibling branches, two provider requests, and the user pays for both.

The effect is not tied to the end of a stream, which is what makes the second tab enough on its own. Its own comment records the earlier version of this: leaving the chat with a truncated branch selected and coming back fired it again. A second tab is that same fresh mount, with a claim set that has never seen the message.

The mechanism

The claim is decided under a Web Lock (navigator.locks) and recorded as a lease in localStorage under unsloth_chat_auto_continue_leases, one record per claimed message id holding a random token and an expiry.

Both halves are needed and neither is enough alone. localStorage is the durable half: it survives the lock being released, the tab being closed, and a reload, which is what a second tab arriving later has to be able to see. The lock is the exclusive half: read, decide and write happen inside one held lock, so no other tab can be between them. localStorage cannot do that part -- its individual operations are atomic, but a read-modify-write across statements is not, and the storage mutex that once serialized such sequences was dropped from the spec. A write-then-read-back narrows that window; it does not close it, because two tabs can both read free, both write, and each verify the token it just wrote.

The read-back is kept anyway, as the only defence left where there is no lock manager.

TTL: 3 minutes, renewed while the run is live

The lease is not a guess at how long a continuation takes. The holder renews it every 30 seconds for as long as the thread is running, and gives it back when the run reaches a terminal state, so the TTL measures one thing only: how long a tab that stopped renewing is still believed to be alive. Without renewal a local model on a large Max Tokens can out-generate any fixed TTL and have its message taken mid-stream.

Three minutes because renewals are timers and a hidden tab is throttled to roughly one timer callback a minute in Chrome, so a backgrounded winner gets about three chances to check in before anyone else may touch its message, while a tab that really died gives the message back inside a pause the user notices anyway. The manual Continue button is never gated on any of this, so the way out is always open.

The keeper lives at thread level rather than on the bar that took the lease: the continuation runs as a sibling and becomes the selected branch, so the truncated message unmounts almost immediately and a timer living there would die with it, mid-stream.

Renewal and release name one message and one thread. The thread is what keeps compare mode's two panes apart, since it mounts a runtime per pane, and it is what keeps one round of a turn apart from the next, because a round that hits Max Tokens again is claimed before the finished one is given back. Anything operating on "every lease this holder owns" settled a round that had only just started.

The lifetime of a lease is the lifetime of its run, and nothing else. It is read from runningByThreadId, which is per thread and indifferent to which chat is on screen: opening another saved chat does not stop a generation, because the chat view is keyed by project and the provider is not remounted, so a lease whose lifetime came from the selected thread's isRunning was released the moment the user looked away. The same store field is what the prompt queue already uses for completion detection, for the same stated reason, that it tracks the actual thread and so survives navigation.

The keeper that holds this lives outside React (auto-continue-run-keeper.ts wires it to the store; the logic itself is in continuation.ts and knows nothing about the app). A hold is one message on one thread; it arms on a run that starts after the hold was taken, renews while that thread generates, and is given back when that thread stops. Selection, mounting and effect ordering are not inputs to any of it. A thread with no remote id yet, the first turn of a New Chat, files its run under a shared placeholder that is not safe to watch, so nothing is held for it and its lease runs out its TTL, which is the same outcome as a tab closing mid-run and is never an early release.

resetAutoContinue() stays wholesale on purpose: a run ending is one run speaking for itself, while a reset is the whole tab being told it holds nothing, and nothing in the run lifecycle calls it. The only other operation that spans messages is pruning lapsed records on write, which removes nothing that was not already free by its own expiry and is what bounds the size of a key every tab shares.

A released lease is cut back to a 30 second settle window rather than deleted. A tab still showing the pre-continuation branch has not seen the sibling that was just written and, handed the message back instantly, would start the duplicate this whole change exists to stop.

What the losing tab shows

autoContinuing is computed from shouldAutoContinueMessage, which is a synchronous read and cannot see a race the lock decides later, so both tabs can render the "Continuing automatically" spinner before either claim resolves. The claim therefore reports which of the two ways it did not start a run: held-elsewhere is another tab, and feeds React state that puts this tab's manual Continue button back; skipped is this tab's own duplicate call, a <StrictMode> replay or a claim already in flight, where the run is coming and nothing on screen should move. A single bare false for both left the loser holding a spinner for a run it never started, with the Continue button hidden behind it.

Residual race

With navigator.locks the read-decide-write is exclusive across same-origin tabs in one profile, so two tabs cannot both come out of it as winners. What is left:

  • Browsers with no lock manager, or one that rejects the request, fall back to write-then-read-back. That is strictly better than a bare check-then-act and strictly worse than a lock: the interleaving where both tabs read free, both write and each verifies before the other's write can still produce two winners. Web Locks is in current Chromium, Firefox and Safari, so this is the old-webview case.
  • Two different browsers, two profiles, a private window beside a normal one, or two devices share neither storage nor locks, so nothing can coordinate them at all.
  • A tab killed between taking the lease and starting the run blocks its own message until the lease lapses. That is a delay of at most one TTL, not a duplicate.
  • The free check before the lock is an optimisation that can only ever refuse; a stale "free" reading of it is re-checked inside the lock.

Degradation

No window, no localStorage, a localStorage property access that throws (Safari private mode), a quota-exceeded write, an unparseable value, no navigator.locks, or a lock request that rejects: every path falls back to the module-only claim that shipped before. The fallback is never a refusal, so a single tab with no working storage still continues exactly as it does today.

Single-tab reload

What stops a reload double-firing today is branch selection, not the claim: the continuation runs as a sibling and becomes the selected branch, so the truncated reply is no longer last and the effect never asks. That is untouched. The lease only adds refusals on top of it, and a reload that does land back on a truncated reply within the window is now refused instead of firing a second run.

BroadcastChannel, and why not

A channel carries no state. It does not replay, so the second tab, which by construction opens after the first has already claimed, hears nothing and would need a request/response handshake with a timeout, guessing how long to wait for silence to mean "nobody is running this". It also dies with its tab, so it cannot express "someone is running this, and here is when to stop believing that", and it is not exclusive: two tabs that broadcast at the same instant both hear the other only after they have already decided. The lock decides, the lease remembers, and the codebase already has the replay note in rag-api.ts for the same reason.

Tests

Appended to studio/frontend/tests/chat-continuation.test.ts, in the same node:test style as the rest of the file. The tab is now constructible (createAutoContinueTab), because a second instance over one shared store and one shared lock manager is exactly what a second browser tab is, and it is the only way to write the case down. The storage fake can interleave another tab in the middle of a read-modify-write, at the read as well as at the write.

Covered: two tabs claiming at once, a tab claiming in full between another tab's read and its write, the loser being told it lost rather than just failing, renewal outliving the TTL, release and its settle window, two compare panes in one tab where the one that finishes first must leave the other's lease live and renewable, two sequential rounds of one turn where the next is claimed before the last is released (with and without a lock manager), a run left generating on a background thread while the user reads another chat, no lock manager, a lock request that rejects, no storage, storage that throws, lease expiry, pruning, a reload not double-firing, and reset releasing this tab's lease and nobody else's.

$ node --experimental-strip-types --test tests/chat-continuation.test.ts
ℹ tests 63
ℹ pass 63
ℹ fail 0

Full frontend suite (npm test): 4251 tests, 4251 pass, 0 fail. npm run typecheck clean.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

Confirmed the gap in studio/frontend/src/features/chat/utils/continuation.ts, where the claim set is module scope so a second tab starts its own continuation for the same truncated reply, and the lock plus lease covers it with the module-only path kept as fallback. Will get this reviewed.

The same saved thread open in two tabs, last reply cut for length: the claim
set lives in module scope, so each tab has its own empty one and both start a
continuation. Two sibling branches, two paid requests.

Back the per-message claim with a short localStorage lease, written with a
random token and read back, so exactly one tab starts the run. No storage, or
storage that throws, falls back to the module-only claim that shipped before.
… renewed

Write-then-read-back narrowed the race without closing it: two tabs can both
read the slot free, both write, and both verify their own token. Take the
read-decide-write under a Web Lock, which is the only primitive that is
actually exclusive, and keep the localStorage lease as the durable record the
lock cannot be.

The claim now says WHY it did not start a run, so the tab that loses drops its
spinner and puts the manual Continue button back instead of waiting on a run it
never owned.

The lease is renewed for as long as the run is live and given back when it
ends, so its TTL means one thing: the holder stopped answering.
…hat took it

Compare mode mounts a Thread runtime per pane, so one tab runs two lease
keepers. Renewing and releasing every lease the tab owned meant the pane that
finished first ended the hold on the pane still generating: its renewals found
nothing held, and a settle window later another tab could claim its message and
start a second paid run.

Leases now carry the holder that took them, a Thread hands its own id down to
the bar that claims, and renewal and release touch only that holder's leases.
resetAutoContinue stays wholesale on purpose: a run ending is one runtime
speaking for itself, a reset is the whole tab being told it holds nothing.
Rounds of one turn share a holder, and React runs the bar's effect before the
thread's, so the next round is claimed before the keeper sees the finished one
end. Anything that renewed or released every lease a holder owns therefore cut
the round that had just started down to the settle window and dropped its
renewal token, and half a minute later another tab could take it.

Leases are now renewed and released one message at a time, with the holder as
the identity that says whose it is. The keeper keeps a claim in a pending list
until a run of its own thread starts, promotes it then, and releases only what
that run was resuming, so the effect ordering stops mattering either way.
… is on screen

The keeper read thread.isRunning, which is the SELECTED thread. Opening another
saved chat does not stop a generation -- the chat view is keyed by project, so
the provider is not remounted and the run keeps streaming on the thread the
user left -- but it does flip that selector, and the lease was released as if
the run had ended. One settle window later another tab could claim a message
still being written and pay for it twice.

The lifetime now comes from runningByThreadId, which is per thread and survives
navigation, and the keeper lives outside React entirely: a hold is one message
on one thread, it arms on a run that starts after it was taken, it renews while
that thread generates, and it is given back when that thread stops. Selection,
mount and effect ordering are no longer inputs.
@danielhanchen
danielhanchen force-pushed the studio-cross-tab-continuation-claim branch from 6da3137 to 198f8e4 Compare August 23, 2026 01:03
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Two ways a second tab still reached the same continuation.

A finished run cut its record to a 30 second settle window, which assumed the
other tab would pick up the saved thread in that time. Nothing does: the history
event is same-window, no chat key has a storage listener, and persisted messages
are re-read only when a thread is opened. So the stale tab took the message back
on its next remount. The record now carries an explicit done flag and outlives
the sitting, which is the question a lease cannot answer.

A hold that had not yet seen its run was dropped on a fixed 60 second timer, and
its renewals stopped with it. Preflight has no bound, since the adapter awaits
settings pairing and then polls for model readiness while a local model loads,
so the lease lapsed under a run that had since begun streaming. Pending holds
are now renewed too. A tab that dies still hands the message back at the TTL.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 12c084279a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +6770 to +6771
if (claim === "held-elsewhere" && mounted) {
setClaimHeldElsewhere(true);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Re-arm the loser after the winning lease lapses

When this tab loses the asynchronous claim and the winning tab then crashes before starting or completing its run, this state remains true for the lifetime of the mounted message. Even after the winner's three-minute lease expires, !claimHeldElsewhere keeps autoContinuing false, and there is no timer or storage subscription that clears the state and retries the claim. The truncated reply therefore never resumes automatically unless the user manually continues it or forces this component to remount.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The mechanics are right and the consequence is not. Confirmed the state is a dead end once set: grep -rn claimHeldElsewhere src/ returns exactly three lines, the useState at thread.tsx:6721, the read at 6730 and the single setClaimHeldElsewhere(true) at 6771. No timer, and no storage subscription: of the 14 addEventListener("storage") in src none is for AUTO_CONTINUE_LEASE_KEY, whose only references are the five in continuation.ts. A losing tab also starts no interval at all, since setInterval(tick, ...) in auto-continue-run-keeper.ts runs only from holdAutoContinueRun, which the effect calls only on claim === "started".

Rejecting on three grounds.

The remount is the ordinary case, not a workaround. The state lives on ContinueMessageBarForLastMessage, which the wrapper at 6608-6612 mounts only while message.isLast, so a thread switch, project switch, branch switch, reload, or the user sending anything destroys it. The comment at 6749 records this as the behaviour that forced the module claim in the first place: leaving the chat with a truncated branch selected and returning fired the effect again.

The user is not stuck. With claimHeldElsewhere true, resumable is still true and autoContinuing is false, so control falls past the spinner to the manual bar. Hiding that button behind a spinner for a run this tab never started is the reason the state exists (6712-6720).

And the module layer already resolves the crashed-winner case: after AUTO_CONTINUE_LEASE_TTL_MS the loser's claimed is false and its claim returns "started". Only the React flag holds it, and only until unmount.

The direction matters here. The failure is a MISSED auto-continuation with the way out on screen, no wrong call and nothing paid for. A re-arm timer would fire an unattended provider request in a background tab minutes after another tab crashed, and if the crashed winner had already streamed part of a sibling into the saved thread it would continue from a stale branch and produce a third. On a PR whose purpose is preventing duplicate paid requests, that is the wrong trade.

* Long enough to outlive the sitting the continuation happened in, not permanent: the ids
* are pruned like any other record, so the key cannot grow without bound.
*/
export const AUTO_CONTINUE_CONTINUED_TTL_MS = 86_400_000;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve completion until stale tabs synchronize

The fresh evidence after the prior durable-claim finding is that completed records now expire after a fixed 24 hours even though no cross-tab history refresh was added. A tab that keeps the old truncated branch loaded for longer than a day will treat the expired done record as free on a later rerender or branch remount, claim it, and issue the same paid continuation again. Completion should remain authoritative until stale tabs have refreshed the thread, rather than expiring solely by elapsed time.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Rejecting, and the clearest reason is that this item and 3837499699 cannot both be true. The 'later rerender' path here needs a losing tab to re-claim, and the other item's own finding is that claimHeldElsewhere is sticky for the whole mount, so no rerender re-claims however long it waits. That leaves only a genuine remount, which in practice means leaving the chat and returning, and that is the same navigation that re-runs history.load and refreshes the branch. Fixing that item as proposed is what would make this one reachable.

The remaining tail needs a tab never reloaded for over 24 hours, still holding the pre-continuation branch, and a remount after the mark that somehow skips the history read.

Against that, removing the timer removes the only bound on the key. prune (continuation.ts:630) keeps records on lease.expires > now and runs only opportunistically inside takeLease and restamp, so the expiry IS the bound. Measured, 200 done records is 17,291 bytes and one claim after the TTL prunes it back to 77. An unbounded set grows monotonically for the life of the profile and is JSON.parse'd and stringify'd whole on every renewal, which is every 30s per live hold, on the main thread. The endgame is self-defeating: takeLease swallows a write failure and returns "started" (continuation.ts:698-700), so once the key cannot be written both tabs start, which is exactly the duplicate this PR exists to prevent, made permanent.

I did evaluate keying completion on the sibling existing in the saved thread, which is the right idea and is not available at the claim site: the only synchronous view there is aui.thread().getState().messages, which by construction is the stale branch, and the persisted copy is reachable only through the async load() at runtime-provider.tsx:1304, i.e. an IndexedDB read plus HTTP inside exclusively(...), holding the cross-tab lock across a network call with no safe default on failure.

What this item actually describes is a cross-tab chat-history sync so stale tabs refresh, which would make the TTL moot rather than needing it removed. Nothing in the codebase has one today. That is a feature, not a correction to this PR.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Regression from the previous commit. Removing the arming timeout made an
unarmed hold renew forever, which is right for a run still in preflight and
wrong for one that will never exist. aui.thread() follows the selection rather
than the thread the continue bar belongs to, so switching chat or branch while
the Web Lock claim is pending leaves startContinuation searching a different
message list, finding nothing and issuing no run, after the hold has been taken.
The lease behind it is then renewed for the life of the tab and every other tab
reads it as live, so one message is stuck cross-tab until the tab closes.

The message is checked before anything is held, off the same store
startContinuation reads a line later in the same tick, so a run that has been
issued and is merely slow to start is unaffected. On the declined path nothing
is held and nothing is recorded, and the lease runs out its own TTL exactly as a
tab closed mid-claim would.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…tle a failed hold

Three ways the claim path outlived the thing it was deciding about.

Rows are mounted by index, so selecting a different truncated branch at the
same index re-renders the continue bar rather than remounting it, and a boolean
losing answer suppressed automatic continuation for a message no other tab had
claimed. It is now remembered as the message it was decided for.

The guard added in the previous commit declined the hold but left the claim in
the tab's own continued set, which is what makes a later claim answer skipped.
A message nothing was issued for has not been continued, so the claim is handed
back. Only inside the tab: the storage lease stays and lapses on its own, so no
second tab may start while this one is still deciding.

A preflight that fails never reaches the running signal, so its hold never
armed and was renewed for the life of the tab. The adapter already reports that
failure per thread, so unarmed holds for that thread are discarded on the event
rather than on any deadline. A slow preflight emits nothing and keeps its hold.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

A continuation carrying an image the loaded model cannot read is refused before
any request is made, and the gate flips the per-thread running flag on and off
so compare mode's waitForRunEnd resolves. A hold waiting for its own run read
that pair as the run starting and finishing: it armed on the first flag and was
released on the second, writing the done marker that tells every other tab for a
day that the message has been continued. The failure that follows could not undo
it, since a released hold is already gone.

The pulse now carries a named owner and the keeper's running signal ignores a
thread whose only owner is that gate, so the hold never arms and the failure
discards it like any other run that died before starting. Only when the gate is
all that holds the flag: a real run sharing the key still answers yes.

Tagging the pulse rather than letting the failure undo the marker, because a
real run that streamed and then died emits the same two flags, and its own
cleanup clears the flag before the wrapper reports the failure. Undoing on
failure would unmark genuinely continued messages and hand another tab a
duplicate request.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 945b01bb1d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

…the job

The Chat UI Tests job on this branch ran 55 minutes and was recorded as
cancelled, which `gh pr checks` renders as a failure. It was the 45 minute job
cap plus GitHub's force-kill drain. Nothing before the lanes was slow: the
prologue took 6m44s, and every step through Playwright install passed.

Not this branch's doing. The lane step has a median of 411s over 521 successful
runs and has never exceeded 508s while passing; the five timeouts it shares a
shape with sat in that same step for 48 to 50 minutes. That is a bimodal cliff,
not a budget creeping toward its cap, so 45 minutes is a hang detector and
raising it would only buy a longer waste. Six timeouts in 1070 executed jobs
across six unrelated branches and six runners, none on main, and this branch
passed the same job at 13.05 to 15.92 minutes on six earlier commits. The
suites do not touch what this branch changes: the continuation, cross-tab claim
and image-gate paths are covered by the vitest suite, and the four Linux lanes
and the macOS suite ran these same Playwright scripts against this same commit
and passed.

What made it a 55 minute silence rather than a failure is that nothing in the
path had a deadline shorter than the job's own.

  * Neither the step nor the lanes were bounded. Every wait inside the suites is
    per-operation: 60s default, 540s a turn, 1080s for the rapid-submit
    predicate. Five turns against a stalled model reach the cap before any one
    of them fires. Each lane now runs under coreutils timeout at 1500s, 3.6x the
    measured lane wall, with the step capped at 28m beneath the job's 45m.
    Resolved by absolute path and proven with --version, because System32 has
    its own timeout.exe with unrelated semantics and this job prepends a shim to
    GITHUB_PATH.

  * The step printed nothing while it stalled. The lane files are only cat'ed
    after both waits return, so there was no live signal at all; the always()
    artifact upload never runs when the runner kills the job at its cap; and
    Python block-buffers into a file, so what the suites did print died with
    them. Added a heartbeat, PYTHONUNBUFFERED, and a tail of the server log
    beside the lane log, since a lane killed mid-turn is usually explained by
    the llama-server it was driving. A step timeout is a step failure rather
    than a cancellation, so the upload runs now.

  * Two suites had no wall watchdog. playwright_loaded_models_indicator.py and
    playwright_update_banner_layout.py never armed one, though their siblings
    have since a page.evaluate, which takes no timeout at all, hung a job for 27
    minutes in #5387. They hold ten raw page.evaluate calls between them, and
    they are the last thing the chat lane runs and the middle of the extra lane.
    Same 720s default and env knob as the siblings.

  * The health polls were not bounded either. `curl -fs` sets no maximum
    transfer time and --connect-timeout stops helping once the handshake lands,
    so a server that binds its port and then wedges parked the first iteration
    forever and the 180 iteration count was never a deadline. Added --max-time,
    and made the loop track elapsed time, since once a probe can cost --max-time
    an iteration count means up to 18 minutes rather than the 180s it reads as.

Checked against a lane that never returns: unbounded, the step is still silent
past every deadline it claims; bounded, it fails in seconds, names the lane,
and the SIGINT leaves a traceback on the wait that was stuck. The watchdog
hard-exits 2 with the label and the deadline. The health probe against a socket
that accepts and never answers used to outlive its own deadline and now reports
at it, with a healthy server still passing immediately.
@danielhanchen
danielhanchen merged commit 5869a66 into main Aug 23, 2026
4 of 5 checks passed
@danielhanchen
danielhanchen deleted the studio-cross-tab-continuation-claim branch August 23, 2026 06:44

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9d490d8069

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

* Hold `messageId`'s lease for as long as `threadId`'s own run is generating.
*
* Called by the continuation bar at the moment it starts a run, because that is the last
* point at which anything knows both ids: the bar unmounts as soon as the continuation's

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Stop renewing leases after preflight cancellation

When an automatic continuation is cancelled before runningByThreadId ever becomes true—for example while waitForModelReady is pending—this handler is never called because the adapter wrapper dispatches PROMPT_QUEUE_RUN_FAILED_EVENT only when !args.abortSignal.aborted (chat-adapter.ts:6982-6985). The hold therefore remains unarmed, and the interval keeps renewing its cross-tab lease for the lifetime of the tab even though the run is over, continuously writing storage and making other tabs treat the message as claimed. Ensure aborted pre-stream runs also discard the matching hold.

Useful? React with 👍 / 👎.

danielhanchen added a commit to oobabooga/unsloth that referenced this pull request Aug 23, 2026
Resolves the chat-adapter.ts import conflict: main added createImageGateRunOwner
(unslothai#9425) while this branch added promptWasShortened. Both are used, so the
resolution keeps both imports.
rhsCZ pushed a commit to rhsCZ/unsloth that referenced this pull request Sep 21, 2026
…nswer

The settled check sits ahead of the arming check on purpose, but moving it
below the arming check failed no test: the case claimed for it read a hold
whose own run ended while the thread was idle, where the two positions agree.

They only disagree in one pass: the hold owns an idle key, its own run ended
without streaming, and the key already reads busy by the time the keeper looks,
because the notification for the run that replaced this one has not been
delivered and the settle callback observes on its own. Below the arming check
that pass arms the hold on somebody else's run, and the end of that run
releases it, writing a done marker for a message that produced not one token.

Also corrects the ownsTheKey comment, which said such a hold can never arm. It
cannot arm off its own run, which is what the guard is about, but it can still
arm off a run that starts after the key has been seen idle. That is the
thread-wide mis-arm unslothai#9425 declined to close and this change does not move it.

npm test 7086 passing, npm run typecheck clean on both projects.
danielhanchen added a commit that referenced this pull request Sep 22, 2026
…light (#9560)

* Studio: give back the continuation lease when the user stops the preflight

A tab that starts an automatic continuation takes a hold on that message's
cross-tab lease and renews it for as long as its own run is alive. A hold that
has not started streaming yet is renewed rather than timed out on purpose:
preflight has no upper bound, and an arming deadline dropped holds in the middle
of a model load, lapsing leases under continuations that were about to stream.

That leaves one way out, and it does not cover Stop. The adapter wrapper skips
its per-thread failure notice when the run's signal is already aborted, because
the abort is what was asked for rather than a fault to report, and the stream
flag never moved in either direction because no token was ever on its way. So a
preflight the user stopped left a hold with nothing to arm on and nothing to
settle on: it renewed the lease for the life of the tab, and every other tab
read that lease as live and refused the message for just as long.

Hand the keeper the runtime's own view of the run, counted off the runStart and
runEnd events assistant-ui emits around startRun. The pair spans the whole call,
settings pairing and model load included, and closes however the run ends,
cancellation among them, so "this side watched a run start here and then watched
it end, and the stream never began" is a fact rather than an elapsed time. A
preflight that is merely long raises neither event and keeps its hold and its
renewals, which is what the absence of an arming deadline is for.

Not read off the runtime's running flag, which looks like the answer and is a
trap: that flag is the status of the message at the head of the current branch,
so clicking the branch picker back to the truncated partial mid-preflight reads
as the run having ended and drops a hold whose continuation goes on to stream.

An unreadable runtime is reported as unknown rather than as idle. getById throws
for any id the thread list cannot resolve to a mounted runtime -- an alias
hydration retired, or an ordinary background thread the user has navigated away
from -- so both spellings of the thread are tried, and a hold is only ever
discarded on an answer this side actually got. Discarded, never released: the
lease lapses on its own TTL and no done marker claims a message that produced
not one token.

* Studio: settle the hold on the run's own promise, not on a per-thread signal

The first cut read whether a run was outstanding off the thread, first from
assistant-ui's running flag and then by counting its runStart and runEnd events.
Both are per-thread, and per-thread cannot say WHICH run ended.

That matters because the next round is claimed while the previous one is still
winding down. The adapter clears runningByThreadId from its own finally, strictly
before the runtime announces that run ending, so the successor's hold is taken,
its run is issued, and only then does the predecessor report itself over. Counted
per thread, the predecessor's ending settles the successor's hold in the middle
of its preflight, the renewals stop, and the lease lapses under a continuation
that is still coming. Reproduced against a real LocalThreadRuntimeCore with the
claim on a microtask off the predecessor's last chunk: held 1 during preflight,
0 once the predecessor ended.

startRun hands back the roundtrip's promise. It is pending for the whole
preflight however long that takes, it settles when THAT run ends however it ends,
and it is the only handle here identified with one run rather than with a thread.
So the bar passes what startRun returned to the keeper, and an unarmed hold whose
own run has settled is discarded exactly as a failed preflight is: forgotten,
never released, its lease left to lapse on its own TTL.

Nothing reads a clock, and a preflight that is merely long leaves the promise
pending, which settles nothing.

The type says startRun returns void while every hop from the store proxy down to
LocalThreadRuntimeCore delegates with return, and that core is async. The value
is therefore passed through untyped and its shape checked once: anything that is
not thenable is assistant-ui no longer handing the run back, and the honest answer
is no signal at all, leaving the hold kept and renewed as before rather than
released early.

This also drops the thread-id lookups the previous approach needed. There is no
getById here any more, so no retired alias to fall back past and no listener to
unsubscribe.

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

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

* Discard a continuation hold the run on its thread cannot own

* Keep an armed hold when a second owner holds the thread key

* Trim the continuation hold comments

* Drop a test counter nothing asserts

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

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

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

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

* Keep a hold whose key was already busy when it was taken

* Cover the one pass where the settled check being first is the whole answer

The settled check sits ahead of the arming check on purpose, but moving it
below the arming check failed no test: the case claimed for it read a hold
whose own run ended while the thread was idle, where the two positions agree.

They only disagree in one pass: the hold owns an idle key, its own run ended
without streaming, and the key already reads busy by the time the keeper looks,
because the notification for the run that replaced this one has not been
delivered and the settle callback observes on its own. Below the arming check
that pass arms the hold on somebody else's run, and the end of that run
releases it, writing a done marker for a message that produced not one token.

Also corrects the ownsTheKey comment, which said such a hold can never arm. It
cannot arm off its own run, which is what the guard is about, but it can still
arm off a run that starts after the key has been seen idle. That is the
thread-wide mis-arm #9425 declined to close and this change does not move it.

npm test 7086 passing, npm run typecheck clean on both projects.

* Say plainly that the ordering case is an invariant, not a reachable sequence

The signal the keeper is wired to notifies synchronously on every store write,
so the app never reaches the pass the previous commit covers: the key turning
busy is always observed, and observed while the hold is still unsettled, which
arms it. That is the superseded-run case this change does not close.

The keeper takes its signal as a parameter and promises nothing about delivery,
so the ordering is still worth pinning. Claiming a user hits it was not.

* Cut this change's comments roughly in half

185 comment lines added to studio/frontend, down to 98 against 718 added
non-blank lines. Step narration in the tests goes entirely, since the assertion
messages already say what each line does, and the paragraphs collapse to the one
fact each carries: why the settled check is first, why an armed hold is exempt,
why ownsTheKey leaves the busy-key case alone, why the callback captures the
hold rather than looking it up again.

Comments, docstrings and whitespace only, AST-verified against d1f1ab2.
npm test 97 passing in this file, npm run typecheck clean.

* Cover the wire from the bar to the keeper, and every timer rather than one spelling

Two gaps found by reverting each new guard in turn and re-running the case meant to
catch it. Both are test-only; no behaviour changes.

Emptying watchAutoContinueRun's body, leaving its call site and the issuedRunFrom
shape check in place so both source-text matches still hold, kept all 97 cases green.
The keeper's own decisions are covered against a keeper built with fakes, and the call
site is pinned as text, but nothing executed the one function joining them, which is
the only thing that ends a hold whose preflight the user stopped.

So it is exercised against the real module-scope keeper, in its own file because that
module reads runningByThreadId off the chat runtime store and needs the store stub
resolver. The observable is the renewal timer: holdAutoContinueRun starts it and the
keeper's tick clears it as soon as nothing is held, so "the timer stopped" is "the
hold was given up" with no clock to advance. The timer is replaced outright rather
than mocked, because the keeper captured Date.now as a default argument at import and
mocking Date desynchronises its clock from the lease's, at which point renewals stop
landing and the test passes for the wrong reason.

The second gap is the arming deadline this change exists to avoid. The assertion read
doesNotMatch(/setTimeout\(/), so a deadline counting its own elapsed time under
setInterval passed unnoticed. It now compares the full list of timers either file
schedules against an allowlist, and names the renewal interval rather than counting
it, so a second setInterval cannot pose as it.

npm test 7087 passing, npm run typecheck clean.

* Cut the comments the follow-up added back to where the first sweep left them

---------

Co-authored-by: oobabooga <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…light (unslothai#9560)

* Studio: give back the continuation lease when the user stops the preflight

A tab that starts an automatic continuation takes a hold on that message's
cross-tab lease and renews it for as long as its own run is alive. A hold that
has not started streaming yet is renewed rather than timed out on purpose:
preflight has no upper bound, and an arming deadline dropped holds in the middle
of a model load, lapsing leases under continuations that were about to stream.

That leaves one way out, and it does not cover Stop. The adapter wrapper skips
its per-thread failure notice when the run's signal is already aborted, because
the abort is what was asked for rather than a fault to report, and the stream
flag never moved in either direction because no token was ever on its way. So a
preflight the user stopped left a hold with nothing to arm on and nothing to
settle on: it renewed the lease for the life of the tab, and every other tab
read that lease as live and refused the message for just as long.

Hand the keeper the runtime's own view of the run, counted off the runStart and
runEnd events assistant-ui emits around startRun. The pair spans the whole call,
settings pairing and model load included, and closes however the run ends,
cancellation among them, so "this side watched a run start here and then watched
it end, and the stream never began" is a fact rather than an elapsed time. A
preflight that is merely long raises neither event and keeps its hold and its
renewals, which is what the absence of an arming deadline is for.

Not read off the runtime's running flag, which looks like the answer and is a
trap: that flag is the status of the message at the head of the current branch,
so clicking the branch picker back to the truncated partial mid-preflight reads
as the run having ended and drops a hold whose continuation goes on to stream.

An unreadable runtime is reported as unknown rather than as idle. getById throws
for any id the thread list cannot resolve to a mounted runtime -- an alias
hydration retired, or an ordinary background thread the user has navigated away
from -- so both spellings of the thread are tried, and a hold is only ever
discarded on an answer this side actually got. Discarded, never released: the
lease lapses on its own TTL and no done marker claims a message that produced
not one token.

* Studio: settle the hold on the run's own promise, not on a per-thread signal

The first cut read whether a run was outstanding off the thread, first from
assistant-ui's running flag and then by counting its runStart and runEnd events.
Both are per-thread, and per-thread cannot say WHICH run ended.

That matters because the next round is claimed while the previous one is still
winding down. The adapter clears runningByThreadId from its own finally, strictly
before the runtime announces that run ending, so the successor's hold is taken,
its run is issued, and only then does the predecessor report itself over. Counted
per thread, the predecessor's ending settles the successor's hold in the middle
of its preflight, the renewals stop, and the lease lapses under a continuation
that is still coming. Reproduced against a real LocalThreadRuntimeCore with the
claim on a microtask off the predecessor's last chunk: held 1 during preflight,
0 once the predecessor ended.

startRun hands back the roundtrip's promise. It is pending for the whole
preflight however long that takes, it settles when THAT run ends however it ends,
and it is the only handle here identified with one run rather than with a thread.
So the bar passes what startRun returned to the keeper, and an unarmed hold whose
own run has settled is discarded exactly as a failed preflight is: forgotten,
never released, its lease left to lapse on its own TTL.

Nothing reads a clock, and a preflight that is merely long leaves the promise
pending, which settles nothing.

The type says startRun returns void while every hop from the store proxy down to
LocalThreadRuntimeCore delegates with return, and that core is async. The value
is therefore passed through untyped and its shape checked once: anything that is
not thenable is assistant-ui no longer handing the run back, and the honest answer
is no signal at all, leaving the hold kept and renewed as before rather than
released early.

This also drops the thread-id lookups the previous approach needed. There is no
getById here any more, so no retired alias to fall back past and no listener to
unsubscribe.

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

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

* Discard a continuation hold the run on its thread cannot own

* Keep an armed hold when a second owner holds the thread key

* Trim the continuation hold comments

* Drop a test counter nothing asserts

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

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

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

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

* Keep a hold whose key was already busy when it was taken

* Cover the one pass where the settled check being first is the whole answer

The settled check sits ahead of the arming check on purpose, but moving it
below the arming check failed no test: the case claimed for it read a hold
whose own run ended while the thread was idle, where the two positions agree.

They only disagree in one pass: the hold owns an idle key, its own run ended
without streaming, and the key already reads busy by the time the keeper looks,
because the notification for the run that replaced this one has not been
delivered and the settle callback observes on its own. Below the arming check
that pass arms the hold on somebody else's run, and the end of that run
releases it, writing a done marker for a message that produced not one token.

Also corrects the ownsTheKey comment, which said such a hold can never arm. It
cannot arm off its own run, which is what the guard is about, but it can still
arm off a run that starts after the key has been seen idle. That is the
thread-wide mis-arm unslothai#9425 declined to close and this change does not move it.

npm test 7086 passing, npm run typecheck clean on both projects.

* Say plainly that the ordering case is an invariant, not a reachable sequence

The signal the keeper is wired to notifies synchronously on every store write,
so the app never reaches the pass the previous commit covers: the key turning
busy is always observed, and observed while the hold is still unsettled, which
arms it. That is the superseded-run case this change does not close.

The keeper takes its signal as a parameter and promises nothing about delivery,
so the ordering is still worth pinning. Claiming a user hits it was not.

* Cut this change's comments roughly in half

185 comment lines added to studio/frontend, down to 98 against 718 added
non-blank lines. Step narration in the tests goes entirely, since the assertion
messages already say what each line does, and the paragraphs collapse to the one
fact each carries: why the settled check is first, why an armed hold is exempt,
why ownsTheKey leaves the busy-key case alone, why the callback captures the
hold rather than looking it up again.

Comments, docstrings and whitespace only, AST-verified against d1f1ab2.
npm test 97 passing in this file, npm run typecheck clean.

* Cover the wire from the bar to the keeper, and every timer rather than one spelling

Two gaps found by reverting each new guard in turn and re-running the case meant to
catch it. Both are test-only; no behaviour changes.

Emptying watchAutoContinueRun's body, leaving its call site and the issuedRunFrom
shape check in place so both source-text matches still hold, kept all 97 cases green.
The keeper's own decisions are covered against a keeper built with fakes, and the call
site is pinned as text, but nothing executed the one function joining them, which is
the only thing that ends a hold whose preflight the user stopped.

So it is exercised against the real module-scope keeper, in its own file because that
module reads runningByThreadId off the chat runtime store and needs the store stub
resolver. The observable is the renewal timer: holdAutoContinueRun starts it and the
keeper's tick clears it as soon as nothing is held, so "the timer stopped" is "the
hold was given up" with no clock to advance. The timer is replaced outright rather
than mocked, because the keeper captured Date.now as a default argument at import and
mocking Date desynchronises its clock from the lease's, at which point renewals stop
landing and the test passes for the wrong reason.

The second gap is the arming deadline this change exists to avoid. The assertion read
doesNotMatch(/setTimeout\(/), so a deadline counting its own elapsed time under
setInterval passed unnoticed. It now compares the full list of timers either file
schedules against an allowlist, and names the renewal interval rather than counting
it, so a second setInterval cannot pose as it.

npm test 7087 passing, npm run typecheck clean.

* Cut the comments the follow-up added back to where the first sweep left them

---------

Co-authored-by: oobabooga <[email protected]>
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.

1 participant