Skip to content

Studio: keep typing and streaming fast in long chats - #13059

Merged
oobabooga merged 12 commits into
mainfrom
studio-long-thread-lag
Oct 8, 2026
Merged

oobabooga merged 12 commits into
mainfrom
studio-long-thread-lag

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 8, 2026 •

Copy link
Copy Markdown
Member

Fixes #12552.

Problem

Long chats get slower and slower in Unsloth Studio and Desktop, and long agent sessions with Rolling Context are hit the hardest. Typing in the composer stalls for hundreds of milliseconds per character (seconds on slower machines), streaming falls behind, and the slowdown persists after reopening the saved chat with no model loaded.

assistant-ui has a single notification manager per client tree. Every store write, which includes every composer keystroke and every streamed delta, re-runs every useAuiState selector in every mounted message row, and ProgressiveMessages keeps the whole thread mounted. On top of that fan-out, several selectors did work proportional to the whole message or the whole thread on every write:

Selector Where Cost per store write
showsNotice (compaction notice) thread.tsx, per assistant message Walked thread.messages up to itself, so O(messages^2)
messageTextKey, precedingText, searchImagesKey markdown-text.tsx, per text part JSON.stringify / join of every text part of the message, so O(parts x text) and lots of garbage
reasoning fold, duration, documents and copy text reasoning.tsx, per reasoning group slice / filter / join over the message's parts
group open / running / live output checks tool-group.tsx, per tool group 4 to 6 parts.slice(...).some(...)
hasText tool-ui-*.tsx, per tool card message.content.some(...), so O(parts^2) per agent turn

Changes

  1. Selector values are computed once per revision (message-derived.ts, use-message-memo.ts). assistant-ui rebuilds message.parts, message.content and thread.messages whenever anything in them changes and returns the same arrays otherwise, so derived values are cached on the array (WeakMap), and per-group selectors are memoized on the message state object. The compaction notice is one pass over the thread producing a Set of message ids. The reasoning Copy text is read when the button is clicked instead of being subscribed. Preceding text for every part is a slice of one joined string, so the cache holds one copy of the message text.
  2. Each message row only hears the notifications that can change it (row-notification-gate.ts, progressive-messages.tsx). Every row subscribes through its own client that inherits everything from the parent except subscribe:
    • Only the thread composer's text changed (a keystroke): no row is notified. Inside a row, composer is that message's edit composer, and nothing under a row reads the thread composer.
    • Only thread.messages changed, at the same length: rows from one before the first changed message onwards are notified. Row selectors read their own message, earlier messages, or the reply right after them (research ownership, the MessageRoot last pair check), so a streamed delta reaches the last two rows instead of every row.
    • The same visible messages in a new array: every row if the runtime's message repository changed (a write on a branch the view is not showing, which the research reply ownership check needs to hear), no row if only the store rebuilt the array (it does on the first keystroke after a run).
    • Anything else (another scope, another thread field, a message added or removed, branch switches): every row, as before.
    • If the state cannot be read, the notification is delivered to every row.
  3. Smoke harness (smoke-thread-weight-main.tsx): agent shaped replies (reasoning, a tool call with its result and a short answer, repeated), compaction metadata every Nth reply, ?remote=1 to wrap the local runtime in the remote thread list like the app does, and ?stream=N to stream a reply of N chunks, so this can be measured without a backend.

Results

Production build of the smoke page, ?remote=1, headless Chromium, 4 repetitions per arm with the arm order flipped on odd repetitions. The base arm was run twice per repetition as a null control (base vs base); its median delta was between 0% and 28% across the metrics below, and every change reported here is well outside that. Medians:

Keystroke into the composer (49 keys)

Thread Base p50 This PR p50 Base script time This PR script time
200 agent messages 27.1 ms 8.6 ms 1.30 s 0.20 s
800 agent messages 104.6 ms 11.7 ms 4.74 s 0.22 s
2,000 agent messages 210.6 ms 16.8 ms 10.14 s 0.23 s
1 reply with 1,500 parts 132.9 ms 7.7 ms 6.56 s 0.17 s
800 plain messages 47.6 ms 15.7 ms 1.97 s 0.22 s

Streaming a 200 chunk reply (20 ms apart, so 4 s is ideal)

Thread Base wall time This PR wall time Base frames over 50 ms This PR frames over 50 ms
800 agent messages 24.6 s 8.1 s 202 6
2,000 agent messages 66.6 s 24.5 s 296 188
1 reply with 1,500 parts 24.9 s 4.5 s 201 2

The remaining streaming cost at 2,000 messages is mostly inside assistant-ui itself (its thread client rebuilds a client per message on every update), which this PR does not touch.

Testing

  • npm test: 11,033 passed, 0 failed. New tests: message-derived.test.ts (cached values equal the uncached ones, including a randomized preceding text check and a check that the compaction notice set matches the old per-message walk) and row-notification-gate.test.ts (keystrokes reach no row, a streamed delta reaches the last two rows, added or removed messages and other scope changes reach every row, a rebuilt messages array with the same messages reaches every row only after a repository write, the gate fails open).
  • tsc -b and tsc -p tsconfig.test.json are clean, npm run build passes, and ESLint / Biome report no new errors on the changed files.
  • Rendered output is identical to main on a 120 message agent thread with compaction every 4 replies, in both the local and remote runtime modes: thread text hash and HTML length, compaction notice positions, composer typing, editing a user message (the edit composer Send button still enables and disables), streaming a reply to completion, expanding and collapsing reasoning and tool groups, and the reasoning Copy clipboard text.
  • These Playwright harnesses pass on both main and this branch: playwright_thread_weight, playwright_tool_activity, playwright_collapse_layout, playwright_prompt_queue_actions, playwright_composer_settings, playwright_find_in_page, playwright_thread_fast_copy, playwright_research_review, playwright_keyboard_shortcuts.

Not covered here: WebView2 on Windows, WebKitGTK and WKWebView were not measured directly (Chromium, Firefox and Playwright WebKit were), and the IME, dictation, queue and steer paths were not exercised end to end against a backend. The composer code itself is unchanged.

Real app

Local Studio (backend plus the built frontend from main and from this branch), a saved agent chat seeded through the chat API, opened with no model loaded, typing 43 characters into the composer:

Browser, thread Main: input handling p50 This PR: input handling p50 Main: key to next frame p50 This PR: key to next frame p50
Chromium, 800 messages 89.9 ms 3.2 ms 103.4 ms 13.5 ms
Chromium, 2,000 messages 200.6 ms 3.6 ms 218.6 ms 21.1 ms
Firefox, 800 messages 131 ms 6 to 8 ms

WebKit on this branch handled keystrokes in 7 to 16 ms on the 800 message chat; WebKit on main crashed the headless tab before the measurement finished, so there is no main number for it.

Screenshots

Same 800 message chat in the real app, Chromium with the CPU throttled 4x, typing the same text at the same speed. Main is still catching up after the keys have all been sent; this branch keeps up:

Typing into an 800 message chat, main vs this PR

The page looks the same once typing settles (the two screenshots are pixel identical):

Final state, main vs this PR

…er part per store write (#12552)

Every store write (a composer keystroke, a streamed delta) re-runs every useAuiState
selector in the mounted tree. Several selectors scanned or joined the whole message
(per text part, per reasoning or tool group, per tool card) or walked the whole thread
(the compaction notice, per assistant message), so one keystroke cost O(parts^2) in a
long agent turn and O(messages^2) in a long Rolling Context chat.

message.parts, message.content and thread.messages are rebuilt by assistant-ui whenever
anything in them changes and kept otherwise, so derived values are cached on the array
(WeakMap), and per-group selectors are memoized on the message state object. The
reasoning Copy text is read at click time instead of subscribed.
…ctors (#12552)

The message rows subscribe through a client that skips notifications in which only the thread
composer's text changed. At 2,000 agent-shaped messages a keystroke drops from ~170 ms to ~13 ms
(script time per 49 keys 8.1 s -> 0.36 s) on the production smoke build.
Each message row now subscribes through its own gated client. A keystroke still reaches no row;
a change confined to thread.messages at the same length reaches the rows from one before the first
changed message onwards, so a streamed token reaches the last two rows instead of every row.
…text (#12552)

Caching a preceding-text string per part index held a quadratic amount of text for a long agent
turn while its parts array lived (about 120 MB at 1,500 parts). Each index now slices one joined
string, so the cache holds one copy. Also closes the smoke page's title stream, gives each runtime
its own harness component, and keeps the fixture's compaction counts positive.
@danielhanchen danielhanchen self-assigned this Oct 8, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-08T14:36:15.753981Z c6a4d3c New commits
🔒 Security Review ⚠️ Failed 2026-10-08T12:28:58.310529Z 29fa9d4 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 8, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 8, 2026

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ec88621315

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

return Math.max(0, index - 1);
}
}
return "none";

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve notifications for message-array revision changes

When a repository mutation affects only an unselected branch, assistant-ui can rebuild thread.messages while retaining the same visible message objects; this path therefore returns "none" and every gated row misses the update. useOwnsResearchMessage in thread.tsx deliberately keys researchReplyOwners on the array identity and exports the whole repository to detect research replies on hidden branches, so its cached ownership can remain stale and leave Edit/Delete controls incorrectly enabled or disabled until an unrelated update occurs. Treat a distinct array with identical entries as a revision change for these subscribers rather than suppressing it entirely.

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.

Fixed in 7b1ab37. The gate now also fingerprints the runtime's message array, which the repository rebuilds on every write including hidden branches. Same visible messages in a new store array now reach every row when that array changed, and still reach none when only the store rebuilt it (the first keystroke after a run does this, so typing stays cheap). Checked against the real runtime: updating a message on a hidden branch now notifies every row, adding one notifies from the first row, and keystrokes still notify none.

…12552)

A write to a branch the view is not showing rebuilds thread.messages with the
same visible messages, which the row gate treated as nothing to deliver, so
selectors keyed on the array (research reply owners) went stale. Deliver it to
every row when the runtime's message array changed too; a store-only rebuild
(the first keystroke after a run) still reaches no row.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 7b1ab3793a

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

@oobabooga oobabooga left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Approving. No regressions found, and typing and streaming in long threads are faster on every engine tested (keystrokes up to 5.7x, streams up to 2.7x at 2,000 messages).

Tested 7b1ab3793a against main bc915c0563. c6a4d3c793 only changes comments, so the results apply to it. Production build of smoke-thread-weight.html?remote=1, median of 2 reps with arm order alternated. A keystroke is timed to the second frame after it, so about 32 ms is the floor.

Engine Messages Keystroke p50, main → PR 200-chunk stream, main → PR
Chromium 139, ubuntu-latest 800 97.9 → 31.8 ms 21.5 → 9.9 s
2,000 182.0 → 31.9 ms 49.0 → 21.5 s
Edge 153, windows-latest 800 97.8 → 32.0 ms 18.0 → 7.1 s
2,000 182.7 → 31.9 ms 49.0 → 18.3 s
WebKit 26.0, ubuntu-latest 800 208.0 → 127.0 ms 33.3 → 12.3 s
2,000 506.0 → 272.0 ms 93.3 → 42.0 s
WebKit 26.0, macos-latest 800 205.5 → 122.5 ms 37.1 → 28.1 s
2,000 702.5 → 278.5 ms 155.3 → 108.3 s
Script time per keystroke (Chromium, CDP) 0 msgs 50 200 800
main 1.34 ms 2.98 8.30 29.78
PR 1.52 ms 1.52 1.55 1.94

Rendering is identical to main on Chromium, Edge, and WebKit on Linux and macOS (row text hashes after each step) on a 120-message thread:

  • composer typing;
  • hover and edit of an early row, with Send toggling;
  • streaming to completion;
  • a same-length branch switch.

A build where the gate skips the changed row fails this check.

CI job Status
Cross-engine: Chromium, ubuntu pass
Cross-engine: Edge, windows pass
Cross-engine: WebKit, ubuntu pass
Cross-engine: WebKit, macOS, timing timing above; its parity step hit the harness's 15 s page-load timeout in both arms
Cross-engine: WebKit, macOS, parity rerun pass (page-load timeout raised to 120 s)
Full CI mirror 40 pass, 3 fail (below), none from this PR; Composer (ubuntu) passes on rerun
Frontend build + bundle sanity fail: i18n:check:strict, missing keys from #13009; fails on main
Python 3.13, a-k fail: test_hub_token_caller_identity.py; same 7 fail on main
Composer (ubuntu) fail: apt install timed out before tests (macOS and Windows Composer pass)
Composer (ubuntu), rerun pass

Cross-engine workflow.

Locally: npm test 11,033/11,033 and typecheck clean.

@oobabooga
oobabooga deleted the studio-long-thread-lag branch October 8, 2026 20:16
Etherll added a commit that referenced this pull request Oct 11, 2026
Resolve the reasoning.tsx import conflict with #13059: keep main's import list
(isRenderableRenderHtmlToolPart moved to message-derived) and add reasoningTailCapped.
@Sneakr Sneakr mentioned this pull request Oct 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] The long-context chat has started to lag.

2 participants