Skip to content

Studio: add /compact and draw compactions where they happened - #13562

Merged
danielhanchen merged 15 commits into
mainfrom
studio-compact-command
Oct 13, 2026
Merged

danielhanchen merged 15 commits into
mainfrom
studio-compact-command

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 13, 2026 •

Copy link
Copy Markdown
Member

Fixes #13453

Two changes to how Studio compacts long chats:

  1. /compact compacts a chat on demand. Type /compact in the composer and press Enter.
  2. "Context compacted" is drawn where the compaction happened. Studio: mark where a chat was compacted with an inline divider #13502 put every compaction's divider above the prompt that started the request. With a small window, though, most compactions happen inside a tool loop, partway through a reply. Those dividers ended up above the prompt, which for the first prompt of a chat is the very top of the thread, where the header fade hides the label.

/compact

  • How to use it. Type /compact on its own and press Enter. Nothing is sent to the model, and a "Context compacted" divider appears under the last reply right away.
  • When it takes effect. The next message starts a new checkpoint, even if the chat still fits. It is the same reset automatic compaction does: older turns go to the conversation archive, the passages relevant to the new question are recalled, and standing instructions are carried forward. Once the reply arrives, its divider replaces the pending one at the same spot.
  • It sticks. A manual epoch keeps replaying on later turns while the chat fits. Without this, an epoch only replays once the prompt overflows, so the chat would un-compact on the very next turn. When the chat later outgrows the window, the usual automatic reset takes over.
  • Auto-compact off. /compact still works: the user asked for it.
  • When it is refused:
    • A new or empty chat shows "Nothing to compact yet".
    • Temporary chats say they cannot be compacted, because they are never saved.
    • API models, safetensors models and models whose template has no tool support show "/compact works with GGUF and MLX models that support tools". The compacted turns are only reachable through search_conversation.
    • /compact with text after it is sent as an ordinary message.
  • The request applies once. It is taken by the next send whatever model handles it, so switching to an API model clears it.
  • Backend:
    • New compact_context request field. It reaches the GGUF fit (plain and tool-loop paths) and the MLX fit as force_reset, and only on the request's first fit, so later tool rounds compact as usual.
    • fit_checkpoint_context(force_reset=...) starts the epoch even when the prompt fits. The record it saves carries manual: true.
    • _sticky_compaction_manual reads that flag back, so a manual epoch replays while the chat fits.
    • Rolling policy and requests that cannot archive ignore the flag.

Where the divider goes

  • Recording. While a reply streams, every compaction fit that cut something new is saved in metadata.custom.compactionMarkers, together with the tool call it followed. The live stream and the reconnect path both record it.
  • The automatic recall. A reset that recalls passages emits its search_conversation exchange before the compaction record, so the marker anchors to the call before that recall. At the start of a reply there is none, which puts the divider above the prompt and the recall below it.
  • Rendering:
    • A compaction before the reply started stays above its prompt, as before. Under checkpoint, that is exactly where the kept context begins.
    • A compaction inside the tool loop is drawn right after the tool call it followed, outside any folded group, so it stays visible.
    • A 4K window resets on nearly every tool round, so only the last in-loop reset of a reply gets a divider. Everything above it was out of the model's view when it answered.
    • Replies saved before this change keep the Studio: mark where a chat was compacted with an inline divider #13502 placement.
  • Context meter. The compaction count is now the number of dividers on screen.
  • What reaches the model. Nothing new: the markers live in display metadata, like contextTruncation.

Live run

unsloth/Qwen3.8-27B-GGUF UD-Q4_K_XL, context forced to 4,096, Thinking Medium, Tools on, Run automatically. The prompt was "Create a Flappy Bird game in HTML then Python then Rust and fix bugs in it", then "Show me the HTML file inline", /compact, and "Now make the bird yellow in the HTML version". Both sides ran on the same GPU. Before is the merge base; network installs were denied on both sides.

On main the first reply compacts inside its tool loop, and the divider is drawn above the very first prompt, where the header fade hides it. On this branch it sits right after the tool call the compaction followed:

Divider placement before and after

/compact shows the divider under the last reply at once. The next message's reset is saved with manual: true (68 messages archived), and its divider lands in the same spot, above that prompt and the automatic recall:

/compact pending and applied

Reopening the saved thread draws the same five dividers in the same places.

Tests

  • Backend. tests/test_manual_compaction.py (9) covers:

    • a forced reset on a chat that fits;
    • no reset when the turns cannot be archived;
    • a no-op with nothing older to drop;
    • a manual epoch replaying while it fits, and an overflow-driven one not doing so;
    • an overflow reset clearing the manual flag;
    • rolling ignoring the flag;
    • the saved flag being read back;
    • an automatic epoch recording manual: false.

    The test differential against the merge base is DISCRIMINATING: 7 FIXED, 1 NEW_API, 1 UNCHANGED (the "fits, so untouched" control). The 931 other compaction, checkpoint and archive tests pass. The one failure, test_build_prequant_checkpoint.py::test_the_recorded_base_must_be_the_canonical_id_not_just_the_same_tail, also fails on main.

  • Frontend. tests/manual-compaction.test.ts covers command parsing, the one-shot request flag, the request fields with auto-compact on and off, marker dedupe across tool-loop replays, divider placement (in-loop, request-start, fallback) and the meter count. message-derived, rolling-context-window and auto-compaction-settings pass. The full suite runs 11,827 tests with no failure the merge base lacks; the one ratchet it tripped reflected progress, and its ToolGroup allowance was lowered. tsc -b is clean, and eslint reports nothing new on the changed files.

  • Studio regression switchboard. NO_REGRESSION. The two parallel visual diffs are the tiny chat model writing a one-line answer on one side and a bulleted list on the other. compaction/ui_compacted fails on base too.

@danielhanchen danielhanchen self-assigned this Oct 13, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 13, 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-13T13:31:41.212362Z 47058fe New commits
ℹ️ 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.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 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 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

const merged = {
...current,
...incoming,

P2 Badge Replace stale manual provenance when a later reset wins

Ensure manual describes the latest boundary rather than inheriting it through ...current. If /compact performs the first reset and a small-window tool loop later performs an automatic reset in the same reply, the later event omits manual, so this merge leaves the earlier manual: true attached to the later boundary. The backend subsequently reads that saved value via _sticky_compaction_manual() and keeps replaying the automatic epoch even after the full transcript fits again, such as after increasing the context window.

ℹ️ 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 +1872 to +1875
const threadId = useChatRuntimeStore((s) => s.activeThreadId);
const pending = useCompactRequestStore((s) =>
threadId === null ? false : s.requested[threadId] === 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 Resolve pending compaction against the rendered thread

Read the thread ID from the local assistant-ui runtime instead of the global active thread. Compare panes render their own Thread instances while activeThreadId remains the primary chat, so after /compact is requested in the primary chat every compared thread whose last row is an assistant also satisfies this selector and displays the same pending-compaction divider, even though no request was registered for those threads.

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.

Compare view only, and display only: same activeThreadId pattern the fork rule uses. Not changing it here.

Comment on lines +200 to +202
lastInLoop = marker;
} else if (!rows.has(row)) {
rows.set(row, marker.truncation);

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 Replace earlier dividers when the latest marker loses its call

Let a later qualifying marker supersede the selections already made for this reply. If an earlier reset still names a visible tool call but the final reset names a call that is no longer present after recovery or pruning, this branch adds the final reset as a row fallback without clearing lastInLoop; it also refuses to replace an existing row. The result displays an obsolete earlier in-loop divider, can display two dividers for one reply, and may show the first fallback's truncation instead of the final reset that actually bounded the answer.

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.

Needs a recorded tool call to vanish from a saved reply, which the normal save path does not do. Leaving as is.

context_overflow = _sf_fit_overflow,
context_policy = _request_context_policy(payload),
compaction_headroom_ratio = _request_compaction_headroom_ratio(payload),
force_reset = getattr(payload, "compact_context", None) is 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 Preserve /compact across an MLX continuation request

Do not treat force_reset as applied when this call is a continuation. The frontend consumes the pending /compact intent for Resume requests too, but compact_chat_context() returns unchanged whenever continue_final_message targets a trailing assistant turn, before it examines force_reset. Consequently, entering /compact and then resuming an incomplete MLX answer silently clears the pending divider without compacting, and the subsequent user message no longer carries the request.

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.

MLX Resume immediately after /compact is a narrow sequence; the user can type /compact again. Out of scope.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@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: 7b623bd561

ℹ️ 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 +24 to +25
if (options.compactNow) {
return { context_overflow: "truncate_oldest", compact_context: 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 Keep manual epochs active when auto-compaction is disabled

When auto-compaction is off, /compact sends truncate_oldest only for the immediate request; the following turn returns context_overflow: "error", so neither GGUF nor MLX runs the fitter or reads the saved manual boundary. The full transcript is therefore restored on the very next message—or the request fails if it is already too large—despite the manual epoch being documented as sticky. Track that the thread has a manual epoch and continue requesting truncate_oldest until an ordinary reset supersedes it.

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.

Auto-compact off is opt-in; there /compact applies to the next message, which is what it promises. Not adding a second sticky mode.

Comment on lines +5664 to +5666
const compactNow =
takeThreadCompactionRequest(resolvedThreadId) &&
(isGgufForCompaction || isMlxForCompaction);

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 the request when an MLX media turn cannot compact

If the user enters /compact and then sends an image or video as the next MLX message, this consumes the one-shot intent before request construction. The MLX route deliberately skips compact_chat_context whenever image, images, or video is present, and the orchestrator also leaves unpriced media conversations unchanged, so no reset occurs and the pending divider silently disappears. Keep the intent armed for a request the MLX fitter can process, or reject the media send with an explicit explanation.

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.

An MLX image or video turn right after /compact is a narrow sequence; the user can run /compact again. Out of scope.

danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 13, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 13, 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 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: 4f2afeacad

ℹ️ 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 +5664 to +5666
const compactNow =
takeThreadCompactionRequest(resolvedThreadId) &&
(isGgufForCompaction || isMlxForCompaction);

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 Snapshot the compaction intent before preflight awaits

When /compact is entered while the current run is still in pre-stream setup, this late read lets that already-submitted run consume the newly armed intent. The adapter performs multiple potentially long waits before reaching this line—including thread pairing, model readiness, project/source resolution, and chat-instruction loading—while the command handler deliberately accepts /compact ahead of the running/queue gates. As a result, the current message can be compacted instead of the next message promised by the pending divider; capture the request state when the run begins so commands entered afterward cannot alter it.

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.

Needs /compact typed during the few seconds of a run's preflight. Narrow race; leaving it.

Comment on lines +8054 to +8058
<ToolGroup startIndex={startIndex} endIndex={endIndex}>
{children}
</ToolGroup>
{truncation && (
<CompactionDivider truncation={truncation} className="my-6" />

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 Place the divider at the matching call within a tool group

When several tool calls are consecutive, assistant-ui supplies them as one ToolGroup spanning startIndex..endIndex. Although the selector can find a compaction anchored to an earlier call in that range, the divider is always rendered after the entire group. For example, if calls c1, c2, and c3 are grouped and the last reset occurred after c2, the UI incorrectly places the boundary after c3; split the group or render the divider at the matched part boundary so later calls remain visibly below the compaction.

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.

Consecutive calls form one group when they come from one round, and no fit runs between calls of one round. Rounds are separated by reasoning or text parts.

};
let codexRoundToolCallIds: string[] = [];
let contextTruncation: OpenAIChatChunk["context_truncated"];
let compactionMarkers: CompactionMarker[] | undefined;

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 Carry compaction markers into continuation siblings

When an incomplete reply is resumed after it already compacted, the continuation starts a sibling assistant message but initializes this marker list from scratch. If the continuation performs no further fit, the completed sibling loses the original divider entirely; if it does emit another truncation event, only the continuation's marker survives and the original in-loop location can move to the prompt. Seed the continuation request and this accumulator from the resumed message's compactionMarkers so the combined logical reply retains compactions from its first segment.

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.

Same as contextTruncation on main, which a continuation also starts fresh. Out of scope here.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 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: 38f560814e

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

@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. Delightful!

Reviewed commit: 62f87f117f

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

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.

[Feature] allow manual compact conversation

1 participant