Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

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

Daniel Hana062c04d5171
diff --git a/studio/backend/core/inference/checkpoint.py b/studio/backend/core/inference/checkpoint.py
index 5f6f5a66fab..863f727bde4 100644
--- a/studio/backend/core/inference/checkpoint.py
+++ b/studio/backend/core/inference/checkpoint.py
@@ -491,6 +491,8 @@ def fit_checkpoint_context(
# Signature compatibility with `fit_rolling_context`. A checkpoint reset already drops to the latest turn plus X; an
# extra bite of the window would only shrink the standing-instruction block, which is the half worth keeping.
headroom_ratio: Optional[float] = None,
+ force_reset: bool = False,
+ sticky_manual: bool = False,
) -> tuple[list[dict], Optional[dict[str, Any]]]:
"""Fit a chat by resetting the epoch, keeping the newest turn and a carried-forward X.
@@ -512,7 +514,7 @@ def fit_checkpoint_context(
prompt_target = prompt_budget(context_length, max_tokens)
initial_tokens = count_tokens(list(messages))
- if initial_tokens <= prompt_target and sticky_dropped <= 0:
+ if initial_tokens <= prompt_target and sticky_dropped <= 0 and not force_reset:
return messages, None
budget = min(MAX_TOKENS, max(0, int(prompt_target * MAX_FRACTION)))
@@ -563,7 +565,7 @@ def fit_checkpoint_context(
fitted = list(messages)
dropped = 0
is_new_epoch = False
- if sticky_dropped > 0 and initial_tokens > prompt_target:
+ if sticky_dropped > 0 and (initial_tokens > prompt_target or sticky_manual) and not force_reset:
candidate, replayed = truncate_oldest_messages(
fitted,
1.0,
@@ -583,7 +585,7 @@ def fit_checkpoint_context(
# Phase two: the epoch is full, so start a new one. keep_ratio 0.0 takes every evictable group in one pass; the
# primitive itself protects system, developer, final and newest user groups.
- if current_tokens > prompt_target and _resolved(can_reset):
+ if (current_tokens > prompt_target or force_reset) and _resolved(can_reset):
candidate, reset_dropped = truncate_oldest_messages(
messages,
0.0,
@@ -640,4 +642,6 @@ def fit_checkpoint_context(
"checkpoint": True,
"checkpoint_started": is_new_epoch,
"carried_forward_chars": len(block),
+ # Explicit on a new epoch: the client merges a reply's fits, and a stale True would outlive it.
+ **({"manual": force_reset} if is_new_epoch else {"manual": True} if sticky_manual else {}),
}
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 5688b71a094..c2167046f7a 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -294,6 +294,9 @@ def _fit_context(messages, **kwargs):
requested_policy = kwargs.pop("context_policy", None)
if requested_policy not in ("checkpoint", "rolling"):
requested_policy = None
+ # /compact: only a checkpoint reset can honour it, since only its turns are archived.
+ force_reset = bool(kwargs.pop("force_reset", False))
+ sticky_manual = bool(kwargs.pop("sticky_manual", False))
try:
from core.inference import checkpoint
@@ -313,7 +316,11 @@ def _fit_context(messages, **kwargs):
# header's tool sentence swapped for one that promises no lookup this request
# cannot perform. If the replay cannot fit, fall through to rolling BELOW.
fitted, truncation = checkpoint.fit_checkpoint_context(
- messages, can_reset = False, searchable = False, **kwargs
+ messages,
+ can_reset = False,
+ searchable = False,
+ sticky_manual = sticky_manual,
+ **kwargs,
)
if truncation is not None and truncation.get("fits"):
return fitted, truncation
@@ -354,6 +361,8 @@ def _fit_context(messages, **kwargs):
messages,
can_reset = lambda: not _is_degraded(),
searchable = lambda: recall_offered and not _is_degraded(),
+ force_reset = force_reset,
+ sticky_manual = sticky_manual,
**kwargs,
)
# `can_reset = False` has no phase two, so it refuses once the replayed
@@ -1922,7 +1931,25 @@ def _sticky_compaction_state(
can_reset: bool = True,
compaction_headroom_ratio: Optional[float] = None,
) -> tuple[int, bool]:
- """How many leading messages this thread last compacted away, and who compacted them.
+ """`_sticky_compaction_details` without the manual flag."""
+ return _sticky_compaction_details(
+ thread_id,
+ branch_messages,
+ context_policy = context_policy,
+ can_reset = can_reset,
+ compaction_headroom_ratio = compaction_headroom_ratio,
+ )[:2]
+
+
+def _sticky_compaction_details(
+ thread_id: Optional[str],
+ branch_messages: Optional[list[dict]] = None,
+ context_policy: Optional[str] = None,
+ can_reset: bool = True,
+ compaction_headroom_ratio: Optional[float] = None,
+) -> tuple[int, bool, bool]:
+ """How many leading messages this thread last compacted away, who compacted them, and
+ whether the user asked for it (/compact), which replays even while the prompt fits.
The provenance decides which fitter may consume the count. A rolling boundary handed
to `fit_checkpoint_context` reads as an epoch already in force, so the fit returns
@@ -1941,7 +1968,7 @@ def _sticky_compaction_state(
a non-persisting API client, or a storage error all mean "no boundary".
"""
if not thread_id:
- return 0, False
+ return 0, False, False
requested_ratio = _effective_headroom_ratio(compaction_headroom_ratio)
try:
from storage import studio_db
@@ -1949,24 +1976,25 @@ def _sticky_compaction_state(
stored = list(studio_db.list_chat_messages(thread_id) or [])
states = _compaction_branch_states(stored, branch_messages)
if not states:
- return 0, False
+ return 0, False, False
boundaries = []
origins = []
+ manual = []
branch_wire = _archive_as_wire(branch_messages)
for state in states:
truncation = state.truncation
recorded = state.recorded
if truncation is None:
- return 0, False
+ return 0, False, False
# Only a SUCCEEDED fit describes a boundary, but an explicit failure still rules.
if not truncation.get("fits"):
- return 0, False
+ return 0, False, False
# A provider-generated summary boundary is display metadata, not a local-fit epoch. On a provider/model
# switch the opaque summary is deliberately withheld, so replaying its boundary here would discard the
# original turns without retaining their summary.
if truncation.get("summarized") is True:
- return 0, False
+ return 0, False, False
# A boundary is valid only under the fit that will consume it, and the two
# directions fail differently.
#
@@ -1987,9 +2015,9 @@ def _sticky_compaction_state(
recorded_checkpoint = bool(truncation.get("checkpoint"))
effective_checkpoint = _request_uses_checkpoint(context_policy)
if recorded_checkpoint and not effective_checkpoint:
- return 0, False
+ return 0, False, False
if not recorded_checkpoint and effective_checkpoint and can_reset:
- return 0, False
+ return 0, False, False
# Changing the extra trim has to change something. Phase one of
# `fit_rolling_context` re-applies this count before anything else and stops
# once the result fits, so a boundary cut under a DIFFERENT ratio never reaches
@@ -2005,9 +2033,9 @@ def _sticky_compaction_state(
recorded_ratio is not None
and abs(float(recorded_ratio) - requested_ratio) > 1e-9
):
- return 0, False
+ return 0, False, False
except (TypeError, ValueError):
- return 0, False
+ return 0, False, False
# A count is only valid against the transcript it was counted on. Deleting an
# already-evicted turn shortens the front, and replaying the count then evicts
# that many LIVE messages instead. Re-derive it from the anchor's position on
@@ -2021,11 +2049,29 @@ def _sticky_compaction_state(
break
boundaries.append(recorded)
origins.append(recorded_checkpoint)
+ manual.append(recorded_checkpoint and truncation.get("manual") is True)
if not boundaries:
- return 0, False
- return min(boundaries), all(origins)
+ return 0, False, False
+ return min(boundaries), all(origins), all(manual)
except Exception:
- return 0, False
+ return 0, False, False
+
+
+def _sticky_compaction_manual(
+ thread_id: Optional[str],
+ branch_messages: Optional[list[dict]] = None,
+ context_policy: Optional[str] = None,
+ can_reset: bool = True,
+ compaction_headroom_ratio: Optional[float] = None,
+) -> bool:
+ """Whether the epoch `_sticky_compaction_state` replays was started by /compact."""
+ return _sticky_compaction_details(
+ thread_id,
+ branch_messages,
+ context_policy = context_policy,
+ can_reset = can_reset,
+ compaction_headroom_ratio = compaction_headroom_ratio,
+ )[2]
def _sticky_compaction_boundary(
@@ -37539,6 +37585,7 @@ class LlamaCppBackend:
tools_withheld: bool = False,
thinking_budget_tokens: Optional[int] = None,
_allow_respawn_retry: bool = True,
+ compact_context: bool = False,
) -> Generator[Union[str, dict], None, None]:
"""
Send a chat completion to llama-server and stream tokens back.
@@ -37618,7 +37665,7 @@ class LlamaCppBackend:
_backend_supports_tools(self),
tools_withheld = tools_withheld,
)
- _sticky, _sticky_is_checkpoint = _sticky_compaction_state(
+ _sticky, _sticky_is_checkpoint, _sticky_manual = _sticky_compaction_details(
thread_id,
_before_fit,
context_policy = context_policy,
@@ -37644,6 +37691,8 @@ class LlamaCppBackend:
reserve_tokens = _conversation_recall_reserve(thread_id),
sticky_dropped = _sticky,
sticky_is_checkpoint = _sticky_is_checkpoint,
+ sticky_manual = _sticky_manual,
+ force_reset = compact_context,
keeps_boundary = _keeps_compaction_boundary(thread_id),
can_reset = _can_reset,
recall_offered = False,
@@ -37769,6 +37818,7 @@ class LlamaCppBackend:
# tools as the first attempt was.
tools_withheld = tools_withheld,
thinking_budget_tokens = thinking_budget_tokens,
+ compact_context = compact_context,
_allow_respawn_retry = False,
)
@@ -38000,6 +38050,7 @@ class LlamaCppBackend:
deduplicate_tool_calls: bool = True,
instruction_anchor_ids = None,
sandbox_level: Optional[str] = None,
+ compact_context: bool = False,
) -> Generator[dict, None, None]:
"""
Agentic loop: let the model call tools, execute them, and continue.
@@ -38631,10 +38682,12 @@ class LlamaCppBackend:
_backend_supports_tools(self),
tools_withheld = _memory_tool_withheld(thread_id, tools),
)
- _iteration_sticky, _iteration_sticky_is_checkpoint = (
- (0, True)
+ # The saved boundary and /compact both apply once, to the loop's first fit.
+ _iteration_force_reset = compact_context and not _sticky_boundary_applied
+ _iteration_sticky, _iteration_sticky_is_checkpoint, _iteration_sticky_manual = (
+ (0, True, False)
if _sticky_boundary_applied
- else _sticky_compaction_state(
+ else _sticky_compaction_details(
thread_id,
_request_branch,
context_policy = context_policy,
@@ -38670,6 +38723,8 @@ class LlamaCppBackend:
reserve_tokens = _conversation_recall_reserve(thread_id),
sticky_dropped = _iteration_sticky,
sticky_is_checkpoint = _iteration_sticky_is_checkpoint,
+ sticky_manual = _iteration_sticky_manual,
+ force_reset = _iteration_force_reset,
**_compaction_fit_kwargs(context_policy, compaction_headroom_ratio),
)
# Accounted for in this request now, whatever the fit decided.
diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.py
index 8bf8c85b8be..2b7caf21e3c 100644
--- a/studio/backend/core/inference/orchestrator.py
+++ b/studio/backend/core/inference/orchestrator.py
@@ -2780,6 +2780,7 @@ class InferenceOrchestrator:
recall_done: bool = False,
request_branch: Optional[list] = None,
live_branch: Optional[list] = None,
+ force_reset: bool = False,
) -> dict:
"""Fit one MLX prompt into the served window under the policy GGUF uses.
@@ -2825,6 +2826,7 @@ class InferenceOrchestrator:
_keeps_compaction_boundary,
_memory_tool_withheld,
_records_boundary,
+ _sticky_compaction_manual,
_sticky_compaction_state,
)
@@ -2875,6 +2877,17 @@ class InferenceOrchestrator:
if replay_boundary
else (0, False)
)
+ sticky_manual = (
+ sticky > 0
+ and sticky_is_checkpoint
+ and _sticky_compaction_manual(
+ thread_id,
+ request_branch,
+ context_policy = context_policy,
+ can_reset = can_reset,
+ compaction_headroom_ratio = compaction_headroom_ratio,
+ )
+ )
fitted, truncation = _fit_with_instruction_pins(
conversation,
context_length = context_length,
@@ -2887,6 +2900,8 @@ class InferenceOrchestrator:
reserve_tokens = _conversation_recall_reserve(thread_id),
sticky_dropped = sticky,
sticky_is_checkpoint = sticky_is_checkpoint,
+ sticky_manual = sticky_manual,
+ force_reset = force_reset,
**_compaction_fit_kwargs(context_policy, compaction_headroom_ratio),
)
if not truncation:
@@ -3103,6 +3118,7 @@ class InferenceOrchestrator:
context_overflow: Optional[str] = None,
context_policy: Optional[str] = None,
compaction_headroom_ratio: Optional[float] = None,
+ compact_context: bool = False,
**_unused,
):
"""Run the safetensors agentic tool loop in the parent process, calling the worker for each
@@ -3254,6 +3270,7 @@ class InferenceOrchestrator:
tool_loop = True,
anchor_ids = pinned,
replay_boundary = not _sticky_boundary_applied,
+ force_reset = compact_context and not _sticky_boundary_applied,
recall_done = _conversation_recall_done,
request_branch = _request_branch,
live_branch = live_branch,
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index d170b68bc86..28ea9bc8c18 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -2902,6 +2902,16 @@ class ChatCompletionRequest(BaseModel):
"for checkpoint compaction. Unset keeps the process default."
),
)
+ compact_context: Optional[bool] = Field(
+ None,
+ description = (
+ "[x-unsloth] Compact now (Studio's /compact). A local GGUF or MLX chat starts "
+ "a checkpoint on this request even when it still fits: older turns are "
+ "archived and searchable, and the model keeps the newest turn plus standing "
+ "instructions until the chat outgrows the window again. Needs "
+ "context_overflow=truncate_oldest and a saved thread; otherwise ignored."
+ ),
+ )
studio_tool_history: Optional[bool] = Field(
None,
description = (
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 5ade0daca64..469792ccfda 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -31846,6 +31846,7 @@ async def produce_openai_chat_completions(
context_overflow = _rolling_context_policy(payload),
context_policy = _request_context_policy(payload),
compaction_headroom_ratio = _request_compaction_headroom_ratio(payload),
+ compact_context = getattr(payload, "compact_context", None) is True,
)
_tool_admission_mode = "chat_tool_stream" if payload.stream else "chat_tool_nonstream"
@@ -32691,6 +32692,7 @@ async def produce_openai_chat_completions(
context_overflow = _rolling_context_policy(payload),
context_policy = _request_context_policy(payload),
compaction_headroom_ratio = _request_compaction_headroom_ratio(payload),
+ compact_context = getattr(payload, "compact_context", None) is True,
thread_id = payload.thread_id,
# These requests suppress the tool loop AND are excluded from the checkpoint
# repair above, so search_conversation is offered neither now nor on the
@@ -33975,6 +33977,7 @@ async def produce_openai_chat_completions(
context_overflow = _sf_fit_overflow,
context_policy = _request_context_policy(payload),
compaction_headroom_ratio = _request_compaction_headroom_ratio(payload),
+ compact_context = getattr(payload, "compact_context", None) is True,
)
_sf_tool_sentinel = object()
@@ -34673,6 +34676,7 @@ async def produce_openai_chat_completions(
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,
max_tokens = effective_max_tokens,
thread_id = payload.thread_id,
cancel_event = cancel_event,
diff --git a/studio/backend/tests/test_llama_admission_compat_matrix.py b/studio/backend/tests/test_llama_admission_compat_matrix.py
index 51940885abb..2d01a80527d 100644
--- a/studio/backend/tests/test_llama_admission_compat_matrix.py
+++ b/studio/backend/tests/test_llama_admission_compat_matrix.py
@@ -253,7 +253,8 @@ class TestOldCallers:
names = list(
inspect.signature(LlamaCppBackend.generate_chat_completion_with_tools).parameters
)
- assert names[-1] == "sandbox_level"
+ assert names.index("sandbox_level") == names.index("instruction_anchor_ids") + 1
+ assert names[-1] == "compact_context"
assert names.index("promote_reasoning_only") == names.index("permission_mode") + 1
def test_the_wait_timeout_has_a_sane_default(self):
diff --git a/studio/backend/tests/test_manual_compaction.py b/studio/backend/tests/test_manual_compaction.py
new file mode 100644
index 00000000000..a1952d595d1
--- /dev/null
+++ b/studio/backend/tests/test_manual_compaction.py
@@ -0,0 +1,179 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""/compact: a checkpoint the user asks for, on a chat that still fits."""
+
+from __future__ import annotations
+
+import sys
+import types
+
+from core.inference import checkpoint, llama_cpp
+from core.inference.checkpoint import fit_checkpoint_context
+
+
+def count(messages):
+ return sum(max(1, len(str(m.get("content", ""))) // 4) for m in messages)
+
+
+def _thread(pad = 4, chars = 200):
+ messages = [{"role": "system", "content": "you are helpful"}]
+ for index in range(pad):
+ messages += [
+ {"role": "user", "content": f"Section {index}. " + "x" * chars},
+ {"role": "assistant", "content": f"Section {index} noted."},
+ ]
+ return messages + [{"role": "user", "content": "continue"}]
+
+
+def _fit(messages, **kwargs):
+ kwargs.setdefault("context_length", 100_000)
+ kwargs.setdefault("max_tokens", 512)
+ kwargs.setdefault("count_tokens", count)
+ kwargs.setdefault("can_reset", True)
+ return fit_checkpoint_context(messages, **kwargs)
+
+
+def test_a_chat_that_fits_is_untouched_unless_asked():
+ messages = _thread()
+
+ assert _fit(messages) == (messages, None)
+
+
+def test_compact_now_resets_a_chat_that_fits():
+ fitted, truncation = _fit(_thread(), force_reset = True)
+
+ assert [m["role"] for m in fitted] == ["system", "user"]
+ assert fitted[-1]["content"] == "continue"
+ assert truncation["fits"] is True
+ assert truncation["checkpoint_started"] is True
+ assert truncation["dropped_messages"] == 8
+ assert truncation["manual"] is True
+
+
+def test_compact_now_never_resets_where_the_turns_could_not_be_archived():
+ messages = _thread()
+
+ assert _fit(messages, force_reset = True, can_reset = False) == (messages, None)
+
+
+def test_compact_now_with_nothing_older_is_a_no_op():
+ messages = [{"role": "system", "content": "s"}, {"role": "user", "content": "hi"}]
+
+ assert _fit(messages, force_reset = True) == (messages, None)
+
+
+def test_a_manual_epoch_keeps_replaying_while_the_chat_still_fits():
+ _, first = _fit(_thread(), force_reset = True)
+ later = _thread() + [
+ {"role": "assistant", "content": "Carrying on."},
+ {"role": "user", "content": "and the next part"},
+ ]
+
+ fitted, truncation = _fit(later, sticky_dropped = first["dropped_messages"], sticky_manual = True)
+
+ assert truncation["dropped_messages"] == first["dropped_messages"]
+ assert truncation["checkpoint_started"] is False
+ assert truncation["manual"] is True
+ assert [m["content"] for m in fitted[1:]] == [
+ "continue",
+ "Carrying on.",
+ "and the next part",
+ ]
+ assert _fit(later, sticky_dropped = first["dropped_messages"]) == (later, None)
+
+
+def test_an_overflow_reset_after_a_manual_epoch_is_an_ordinary_one():
+ _, first = _fit(_thread(), force_reset = True)
+ later = _thread(pad = 12, chars = 600)
+
+ _, truncation = _fit(
+ later,
+ context_length = 1200,
+ max_tokens = 200,
+ sticky_dropped = first["dropped_messages"],
+ sticky_manual = True,
+ )
+
+ assert truncation["checkpoint_started"] is True
+ # False rather than absent, so it replaces the reply's earlier manual fit when merged.
+ assert truncation["manual"] is False
+
+
+def test_the_rolling_fit_ignores_compact_now(monkeypatch):
+ monkeypatch.setattr(checkpoint, "CONTEXT_POLICY", "rolling")
+ messages = _thread()
+
+ fitted, truncation = llama_cpp._fit_context(
+ messages,
+ context_length = 100_000,
+ max_tokens = 512,
+ count_tokens = count,
+ can_reset = True,
+ force_reset = True,
+ sticky_manual = True,
+ )
+
+ assert (fitted, truncation) == (messages, None)
+
+
+def test_fit_context_hands_compact_now_to_the_checkpoint_fit(monkeypatch):
+ monkeypatch.setattr(checkpoint, "CONTEXT_POLICY", "checkpoint")
+ monkeypatch.setattr(llama_cpp, "_archive_is_degraded", lambda: False)
+
+ fitted, truncation = llama_cpp._fit_context(
+ _thread(),
+ context_length = 100_000,
+ max_tokens = 512,
+ count_tokens = count,
+ can_reset = True,
+ force_reset = True,
+ )
+
+ assert [m["role"] for m in fitted] == ["system", "user"]
+ assert truncation["manual"] is True
+
+
+def _stub_studio_db(monkeypatch, rows):
+ module = types.SimpleNamespace(list_chat_messages = lambda thread_id: rows)
+ package = types.ModuleType("storage")
+ package.studio_db = module
+ monkeypatch.setitem(sys.modules, "storage", package)
+ monkeypatch.setitem(sys.modules, "storage.studio_db", module)
+
+
+def _rows(**truncation):
+ return [
+ {"id": "u1", "parentId": None, "role": "user", "content": "Do the work."},
+ {
+ "id": "a1",
+ "parentId": "u1",
+ "role": "assistant",
+ "content": "Done.",
+ "metadata": {
+ "custom": {
+ "contextTruncation": {
+ "fits": True,
+ "checkpoint": True,
+ "boundary_messages": 6,
+ **truncation,
+ }
+ }
+ },
+ },
+ ]
+
+
+def test_the_saved_boundary_says_whether_compact_now_started_it(monkeypatch):
+ monkeypatch.setattr(checkpoint, "CONTEXT_POLICY", "checkpoint")
+ branch = [
+ {"role": "user", "content": "Do the work."},
+ {"role": "assistant", "content": "Done."},
+ ]
+
+ _stub_studio_db(monkeypatch, _rows(manual = True))
+ assert llama_cpp._sticky_compaction_state("t1", branch) == (6, True)
+ assert llama_cpp._sticky_compaction_manual("t1", branch) is True
+
+ _stub_studio_db(monkeypatch, _rows())
+ assert llama_cpp._sticky_compaction_manual("t1", branch) is False
diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.ts
index 996da55a5c8..23159e3a567 100644
--- a/studio/frontend/scripts/check-bundle-budget.ts
+++ b/studio/frontend/scripts/check-bundle-budget.ts
@@ -67,8 +67,11 @@ export const BUDGET = {
// growth so main's margin stays where it was.
// Sidebar server paging adds 17.4 KB raw / 5.6 KB transfer to the first screen (6,544.5 -> 6,561.9
// KB raw, 1,967.1 -> 1,972.7 KB transfer against b73110c6f, one machine and build), raised by that.
- transferBytes: 2_021_100,
- rawBytes: 6_728_100,
+ // /compact and the in-loop compaction divider add 3.6 KB raw / 1.4 KB transfer to the eager startup
+ // JS (6,563.4 -> 6,567.0 KB raw, 1,973.0 -> 1,974.4 KB transfer against 280c45695, one machine
+ // and build), raised by that.
+ transferBytes: 2_022_600,
+ rawBytes: 6_731_800,
};
// The chunk count is reported but not budgeted. Splitting a page out of the entry raises it while lowering the
diff --git a/studio/frontend/src/components/assistant-ui/compaction-divider.tsx b/studio/frontend/src/components/assistant-ui/compaction-divider.tsx
index 02e2c7f3607..61c7bf74547 100644
--- a/studio/frontend/src/components/assistant-ui/compaction-divider.tsx
+++ b/studio/frontend/src/components/assistant-ui/compaction-divider.tsx
@@ -10,6 +10,7 @@ import {
TooltipTrigger,
} from "@/components/ui/tooltip";
import { type ContextTruncation, promptWasShortened } from "@/features/chat";
+import { cn } from "@/lib/utils";
const DetailRow: FC<{ label: string; value: ReactNode }> = ({
label,
@@ -21,10 +22,24 @@ const DetailRow: FC<{ label: string; value: ReactNode }> = ({
</div>
);
-/** renders metadata once per compaction above its triggering prompt and survives reloads without entering model context, editable content, or exports. */
-export const CompactionDivider: FC<{ truncation: ContextTruncation }> = ({
- truncation,
-}) => {
+/** renders metadata once per compaction where it cut and survives reloads without entering model context, editable content, or exports. */
+export const CompactionDivider: FC<
+ (
+ | { truncation: ContextTruncation; pending?: false }
+ | { truncation?: undefined; pending: true }
+ ) & { className?: string }
+> = ({ truncation, pending, className }) => {
+ if (pending) {
+ return (
+ <DividerRule className={className}>
+ <p className="max-w-72 text-xs leading-snug">
+ Your next message starts a fresh context. Older messages stay here,
+ and the parts relevant to each question are brought back
+ automatically.
+ </p>
+ </DividerRule>
+ );
+ }
if (!promptWasShortened(truncation)) return null;
const summarized = truncation.summarized === true;
@@ -35,51 +50,63 @@ export const CompactionDivider: FC<{ truncation: ContextTruncation }> = ({
const after = truncation.prompt_tokens_after;
return (
- <div
- data-testid="compaction-divider"
- className="mx-auto mb-6 flex w-full max-w-(--thread-content-max-width) items-center gap-3 text-muted-foreground text-sm"
- >
- <span aria-hidden={true} className="h-px flex-1 bg-border" />
- <Tooltip>
- <TooltipTrigger asChild>
- <button
- type="button"
- data-slot="compaction-divider-label"
- // negative margins keep a large target from moving the rule.
- // positioning stops the reply above from covering the target.
- className="relative -mx-2 -my-2.5 inline-flex shrink-0 cursor-default items-center gap-1.5 whitespace-nowrap rounded-md px-2 py-2.5 leading-none transition-colors hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring"
- >
- <ArchiveIcon className="size-3.5" aria-hidden={true} />
- Context compacted
- </button>
- </TooltipTrigger>
- <TooltipContent side="top" sideOffset={8} variant="rich">
- <div className="grid max-w-72 gap-1.5 text-xs">
- <p className="leading-snug">
- {summarized
- ? "The provider summarized older messages to make room."
- : "Older messages were dropped from the model's context to make room."}{" "}
- {archived
- ? "They are saved and searchable, and the parts relevant to each question are brought back automatically."
- : "The full conversation is still visible and saved here."}
- </p>
- <DetailRow
- label={summarized ? "Messages summarized" : "Messages dropped"}
- value={dropped}
- />
- {recalled > 0 && (
- <DetailRow label="Passages recalled" value={recalled} />
- )}
- {before !== undefined && after !== undefined && (
- <DetailRow
- label="Prompt tokens"
- value={`${before.toLocaleString()} → ${after.toLocaleString()}`}
- />
- )}
- </div>
- </TooltipContent>
- </Tooltip>
- <span aria-hidden={true} className="h-px flex-1 bg-border" />
- </div>
+ <DividerRule className={className}>
+ <div className="grid max-w-72 gap-1.5 text-xs">
+ <p className="leading-snug">
+ {summarized
+ ? "The provider summarized older messages to make room."
+ : "Older messages were dropped from the model's context to make room."}{" "}
+ {archived
+ ? "They are saved and searchable, and the parts relevant to each question are brought back automatically."
+ : "The full conversation is still visible and saved here."}
+ </p>
+ <DetailRow
+ label={summarized ? "Messages summarized" : "Messages dropped"}
+ value={dropped}
+ />
+ {recalled > 0 && (
+ <DetailRow label="Passages recalled" value={recalled} />
+ )}
+ {before !== undefined && after !== undefined && (
+ <DetailRow
+ label="Prompt tokens"
+ value={`${before.toLocaleString()} → ${after.toLocaleString()}`}
+ />
+ )}
+ </div>
+ </DividerRule>
);
};
+
+const DividerRule: FC<{ children: ReactNode; className?: string }> = ({
+ children,
+ className = "mb-6",
+}) => (
+ <div
+ data-testid="compaction-divider"
+ className={cn(
+ "mx-auto flex w-full max-w-(--thread-content-max-width) items-center gap-3 text-muted-foreground text-sm",
+ className,
+ )}
+ >
+ <span aria-hidden={true} className="h-px flex-1 bg-border" />
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ type="button"
+ data-slot="compaction-divider-label"
+ // negative margins keep a large target from moving the rule.
+ // positioning stops the reply above from covering the target.
+ className="relative -mx-2 -my-2.5 inline-flex shrink-0 cursor-default items-center gap-1.5 whitespace-nowrap rounded-md px-2 py-2.5 leading-none transition-colors hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring"
+ >
+ <ArchiveIcon className="size-3.5" aria-hidden={true} />
+ Context compacted
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="top" sideOffset={8} variant="rich">
+ {children}
+ </TooltipContent>
+ </Tooltip>
+ <span aria-hidden={true} className="h-px flex-1 bg-border" />
+ </div>
+);
diff --git a/studio/frontend/src/components/assistant-ui/message-derived.ts b/studio/frontend/src/components/assistant-ui/message-derived.ts
index 57564e292ae..a9990c1e03d 100644
--- a/studio/frontend/src/components/assistant-ui/message-derived.ts
+++ b/studio/frontend/src/components/assistant-ui/message-derived.ts
@@ -7,6 +7,7 @@
import { isRenderableRenderHtmlToolPart } from "../../features/chat/artifacts/html-fences.ts";
import { searchImagesSignature } from "../../features/chat/search-images/search-images.ts";
import {
+ type CompactionMarker,
type ContextTruncation,
compactionBoundary,
shouldShowCompactionNotice,
@@ -128,33 +129,110 @@ export const compactionNoticeMessageIds = memoOnArray(
},
);
-const NO_COMPACTION_DIVIDERS: ReadonlyMap<string, ContextTruncation> =
- new Map();
+type CompactionDividers = {
+ rows: ReadonlyMap<string, ContextTruncation>;
+ /** Keyed by reply: tool call ids are only unique within one. */
+ afterToolCalls: ReadonlyMap<string, CompactionMarker>;
+};
-/** maps each compaction to its triggering prompt row or, if absent, its reply row at the kept-context boundary so visible dividers match the context meter. */
-export const compactionDividerRows = memoOnArray(
- (
- messages: readonly MessageLike[],
- ): ReadonlyMap<string, ContextTruncation> => {
+const NO_COMPACTION_DIVIDERS: CompactionDividers = {
+ rows: new Map(),
+ afterToolCalls: new Map(),
+};
+
+function compactionMarkersOf(
+ message: MessageLike,
+): readonly CompactionMarker[] | null {
+ const markers = (
+ message.metadata as { custom?: { compactionMarkers?: unknown } } | undefined
+ )?.custom?.compactionMarkers;
+ return Array.isArray(markers) && markers.length > 0
+ ? (markers as CompactionMarker[])
+ : null;
+}
+
+function hasToolCall(message: MessageLike, toolCallId: string): boolean {
+ const { parts, content } = message as { parts?: unknown; content?: unknown };
+ const list = Array.isArray(parts) ? parts : content;
+ return (
+ Array.isArray(list) &&
+ list.some(
+ (part) =>
+ (part as { type?: string }).type === "tool-call" &&
+ (part as { toolCallId?: string }).toolCallId === toolCallId,
+ )
+ );
+}
+
+/** Request-start fits go above their prompt, a reply's last in-loop fit after the tool call it followed. */
+const compactionDividers = memoOnArray(
+ (messages: readonly MessageLike[]): CompactionDividers => {
const notices = compactionNoticeMessageIds(messages);
- // streamed tokens create new arrays, so reuse this map until a thread compacts.
+ // streamed tokens create new arrays, so reuse this result until a thread compacts.
if (notices.size === 0) return NO_COMPACTION_DIVIDERS;
const rows = new Map<string, ContextTruncation>();
+ const afterToolCalls = new Map<string, CompactionMarker>();
let previous: MessageLike | undefined;
+ let previousBoundary = 0;
for (const message of messages) {
- if (notices.has(message.id)) {
- const row = previous?.role === "user" ? previous.id : message.id;
- rows.set(
- row,
- (
- message.metadata as {
- custom: { contextTruncation: ContextTruncation };
- }
- ).custom.contextTruncation,
+ const row = previous?.role === "user" ? previous.id : message.id;
+ const markers =
+ message.role === "assistant" ? compactionMarkersOf(message) : null;
+ if (markers) {
+ // Only the last reset matters: everything above it was out of the model's view.
+ let lastInLoop: CompactionMarker | null = null;
+ for (const marker of markers) {
+ if (!shouldShowCompactionNotice(marker.truncation, previousBoundary)) {
+ continue;
+ }
+ previousBoundary = Math.max(
+ previousBoundary,
+ compactionBoundary(marker.truncation),
+ );
+ if (
+ marker.afterToolCallId !== null &&
+ hasToolCall(message, marker.afterToolCallId)
+ ) {
+ lastInLoop = marker;
+ } else if (!rows.has(row)) {
+ rows.set(row, marker.truncation);
+ }
+ }
+ if (lastInLoop?.afterToolCallId) {
+ afterToolCalls.set(message.id, lastInLoop);
+ }
+ } else if (notices.has(message.id)) {
+ const truncation = (
+ message.metadata as {
+ custom: { contextTruncation: ContextTruncation };
+ }
+ ).custom.contextTruncation;
+ rows.set(row, truncation);
+ previousBoundary = Math.max(
+ previousBoundary,
+ compactionBoundary(truncation),
);
}
previous = message;
}
- return rows;
+ return rows.size === 0 && afterToolCalls.size === 0
+ ? NO_COMPACTION_DIVIDERS
+ : { rows, afterToolCalls };
},
);
+
+export const compactionDividerRows = (
+ messages: readonly MessageLike[],
+): ReadonlyMap<string, ContextTruncation> => compactionDividers(messages).rows;
+
+export const compactionToolCallDividers = (
+ messages: readonly MessageLike[],
+): ReadonlyMap<string, CompactionMarker> =>
+ compactionDividers(messages).afterToolCalls;
+
+export const compactionDividerCount = (
+ messages: readonly MessageLike[],
+): number => {
+ const dividers = compactionDividers(messages);
+ return dividers.rows.size + dividers.afterToolCalls.size;
+};
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index 29a3de727ac..6d792fc8261 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -25,6 +25,7 @@ import { AutoReadAloud } from "@/components/assistant-ui/auto-read-aloud";
import { CompactionDivider } from "@/components/assistant-ui/compaction-divider";
import {
compactionDividerRows,
+ compactionToolCallDividers,
memoOnArrayByKey,
} from "@/components/assistant-ui/message-derived";
import { downloadImagePart } from "@/components/assistant-ui/image";
@@ -100,6 +101,10 @@ import {
type ContextTruncation,
attachmentsPastedText,
hasPendingPromptQueueStart,
+ isCompactCommand,
+ isThreadIncognito,
+ requestThreadCompaction,
+ useCompactRequestStore,
isPastedTextFile,
pastedTextQueueKey,
promptQueueActiveItemChanged,
@@ -429,6 +434,7 @@ import {
type FC,
type KeyboardEvent,
type DragEvent as ReactDragEvent,
+ type PropsWithChildren,
type ReactNode,
type RefObject,
Fragment,
@@ -1858,10 +1864,23 @@ const ThreadMessage: FC = () => {
<CompactionRowDivider />
{body}
<ForkContinuationRule />
+ <PendingCompactionRule />
</>
);
};
+const PendingCompactionRule: FC = () => {
+ const threadId = useChatRuntimeStore((s) => s.activeThreadId);
+ const pending = useCompactRequestStore((s) =>
+ threadId === null ? false : s.requested[threadId] === true,
+ );
+ const endsWithReply = useAuiState(
+ ({ message }) => message.isLast && message.role === "assistant",
+ );
+ if (!pending || !endsWithReply) return null;
+ return <CompactionDivider pending={true} className="mt-6" />;
+};
+
// The selector returns the persisted record, which keeps its identity between renders, so a
// row re-renders only when a divider arrives or leaves above it.
const CompactionRowDivider: FC = () => {
@@ -5375,6 +5394,41 @@ const Composer: FC<{
});
return;
}
+ if (
+ !overlay &&
+ !hasAttachments &&
+ !hasPendingAudio &&
+ isCompactCommand(composerText)
+ ) {
+ event.preventDefault();
+ const runtime = useChatRuntimeStore.getState();
+ if (!referenceThreadId || aui.thread().getState().messages.length === 0) {
+ toast.info("Nothing to compact yet");
+ return;
+ }
+ if (runtime.incognito || isThreadIncognito(referenceThreadId)) {
+ toast.info("Temporary chats are not saved, so they cannot be compacted");
+ return;
+ }
+ // The compacted turns stay reachable only through search_conversation, so no tools, no reset.
+ if (
+ !runtime.supportsTools ||
+ !resumesThought({
+ loadedIsGguf: runtime.loadedIsGguf,
+ loadedIsMlx: runtime.loadedIsMlx,
+ activeGgufVariant: runtime.activeGgufVariant,
+ activeNativePathToken: runtime.activeNativePathToken,
+ checkpoint: runtime.params.checkpoint,
+ })
+ ) {
+ toast.info("/compact works with GGUF and MLX models that support tools");
+ return;
+ }
+ requestThreadCompaction(referenceThreadId);
+ clearStoredDraft();
+ aui.composer().setText("");
+ return;
+ }
if (disabled || shouldBlockSend()) {
event.preventDefault();
parkIfWaitingOnAttachments();
@@ -7986,6 +8040,33 @@ const ContinueMessageBarForLastMessage: FC = () => {
);
};
+const ToolGroupThenCompaction = memo<
+ PropsWithChildren<{ startIndex: number; endIndex: number }>
+>(({ startIndex, endIndex, children }) => {
+ const truncation = useAuiState(({ thread, message }) => {
+ const marker = compactionToolCallDividers(thread.messages).get(message.id);
+ if (!marker) return null;
+ for (let index = startIndex; index <= endIndex; index += 1) {
+ const part = message.parts[index];
+ if (part?.type === "tool-call" && part.toolCallId === marker.afterToolCallId) {
+ return marker.truncation;
+ }
+ }
+ return null;
+ });
+ return (
+ <>
+ <ToolGroup startIndex={startIndex} endIndex={endIndex}>
+ {children}
+ </ToolGroup>
+ {truncation && (
+ <CompactionDivider truncation={truncation} className="my-6" />
+ )}
+ </>
+ );
+});
+ToolGroupThenCompaction.displayName = "ToolGroupThenCompaction";
+
const WebSearchToolUIConfirmable = withToolConfirmation(WebSearchToolUI);
const KnowledgeBaseToolUIConfirmable =
withToolConfirmation(KnowledgeBaseToolUI);
@@ -8017,7 +8098,7 @@ const ASSISTANT_PART_COMPONENTS = {
Reasoning: Reasoning,
ReasoningGroup: ReasoningGroup,
Source: Sources,
- ToolGroup: ToolGroup,
+ ToolGroup: ToolGroupThenCompaction,
tools: {
by_name: {
web_search: WebSearchToolUIConfirmable,
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 2bd6a9295c6..3a0719ef8c4 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -287,6 +287,7 @@ import {
} from "../presets/preset-policy";
import { ensureGpuDeviceCache } from "@/hooks/use-gpu-info";
import { useExternalProvidersStore } from "../stores/external-providers-store";
+import { takeThreadCompactionRequest } from "../stores/compact-request-store";
import {
shouldPreserveFullOutput,
toolOutputKey,
@@ -330,6 +331,9 @@ import {
getImageInputUnavailableReason,
} from "../utils/image-input-support";
import {
+ appendCompactionMarker,
+ type CompactionMarker,
+ compactionAnchorToolCallId,
historyCannotHelp,
latestTurnIsTheProblem,
latestTurnOwnTokens,
@@ -5656,6 +5660,10 @@ export function createOpenAIStreamAdapter(
// the local model still resident.
const isMlxForCompaction =
!isExternalModelId(params.checkpoint) && runtime.loadedIsMlx === true;
+ // Taken once, so a retried request still carries it and the next turn does not.
+ const compactNow =
+ takeThreadCompactionRequest(resolvedThreadId) &&
+ (isGgufForCompaction || isMlxForCompaction);
const generationUserMessage = [...survivingMessages]
.reverse()
.find((message) => message.role === "user");
@@ -5915,6 +5923,7 @@ export function createOpenAIStreamAdapter(
};
let codexRoundToolCallIds: string[] = [];
let contextTruncation: OpenAIChatChunk["context_truncated"];
+ let compactionMarkers: CompactionMarker[] | undefined;
let providerCompaction: ProviderCompactionContentPart | undefined =
continuationCompaction ?? undefined;
let providerCompactionAfterToolCalls: number | undefined =
@@ -5946,6 +5955,7 @@ export function createOpenAIStreamAdapter(
openaiCodexReasoning: codexReasoningLedger,
openaiResponsesReasoning: openAIResponsesReasoningLedger,
contextTruncation,
+ compactionMarkers,
providerCompaction,
providerCompactionAfterToolCalls,
providerCompactionProviderType,
@@ -6992,6 +7002,7 @@ export function createOpenAIStreamAdapter(
isGguf: isGgufForCompaction,
isMlx: isMlxForCompaction,
autoCompactEnabled: runtime.autoCompactEnabled,
+ compactNow,
}),
temperature: params.temperature,
top_p: params.topP,
@@ -7311,6 +7322,14 @@ export function createOpenAIStreamAdapter(
contextTruncation,
chunk.context_truncated,
);
+ compactionMarkers = appendCompactionMarker(
+ compactionMarkers,
+ chunk.context_truncated,
+ compactionAnchorToolCallId(
+ toolCallParts,
+ chunk.context_truncated,
+ ),
+ );
const activeThreadId = useChatRuntimeStore.getState().activeThreadId;
// What must stay silent is a fit that returned the ORIGINAL messages: "older turns were
// removed" would be untrue and burns the once-per-thread flag. Not `fits`, which is also
@@ -8836,6 +8855,19 @@ export function createOpenAIStreamAdapter(
}
}
+ if (
+ compactNow &&
+ !compactionMarkers?.some(
+ (marker) =>
+ marker.truncation.manual === true &&
+ marker.truncation.checkpoint_started === true,
+ )
+ ) {
+ toast.info("This chat was not compacted", {
+ description:
+ "Compaction needs the conversation archive and the default checkpoint policy.",
+ });
+ }
const finalTiming = buildTiming(
streamStartTime,
totalChunks,
@@ -8874,6 +8906,7 @@ export function createOpenAIStreamAdapter(
openaiCodexReasoning: codexReasoningLedger,
openaiResponsesReasoning: openAIResponsesReasoningLedger,
contextTruncation,
+ compactionMarkers,
providerCompaction,
providerCompactionAfterToolCalls,
providerCompactionProviderType,
@@ -9053,6 +9086,7 @@ export function createOpenAIStreamAdapter(
custom: {
...reasoningDurationTracker.metadata(),
contextTruncation,
+ compactionMarkers,
providerCompaction,
providerCompactionAfterToolCalls,
providerCompactionProviderType,
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index bbb057bf352..e19e72f7a47 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -162,6 +162,11 @@ export {
rewindTouchesConversation,
rewindTouchesFiles,
} from "./utils/rewind";
+export {
+ isCompactCommand,
+ requestThreadCompaction,
+ useCompactRequestStore,
+} from "./stores/compact-request-store";
export {
folderRingKey,
planKey,
diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsx
index d40b2369108..09ce3103c08 100644
--- a/studio/frontend/src/features/chat/runtime-provider.tsx
+++ b/studio/frontend/src/features/chat/runtime-provider.tsx
@@ -56,7 +56,7 @@ import {
streamChatCompletions,
uploadChatAttachmentOriginal,
} from "./api/chat-api";
-import { compactionNoticeMessageIds } from "@/components/assistant-ui/message-derived";
+import { compactionDividerCount } from "@/components/assistant-ui/message-derived";
import { selectCodeToolNames } from "./api/code-tool-placement";
import { getResearchThreadState } from "./api/research-api";
import {
@@ -183,7 +183,12 @@ import {
} from "./utils/saved-history-reconciliation";
import { createGenerationToolRecovery } from "./utils/generation-tool-recovery";
import { providerCompactionConnectionKey } from "./utils/provider-compaction";
-import { mergeContextTruncation } from "./utils/context-truncation";
+import {
+ appendCompactionMarker,
+ type CompactionMarker,
+ compactionAnchorToolCallId,
+ mergeContextTruncation,
+} from "./utils/context-truncation";
import { registerLiveThreadView } from "./utils/live-thread-head";
import {
cancelReplyFinishedNotification,
@@ -1759,12 +1764,23 @@ function scheduleGenerationRecovery(
firstChunkAt ??= update.event.createdAt;
}
if (chunk.context_truncated) {
+ const toolCalls = carried
+ .map((entry) => entry.part as { type?: unknown } | null)
+ .filter((part) => part?.type === "tool-call") as Array<{
+ toolCallId?: unknown;
+ toolName?: unknown;
+ }>;
currentMetadata = {
...currentMetadata,
contextTruncation: mergeContextTruncation(
currentMetadata.contextTruncation as OpenAIChatChunk["context_truncated"],
chunk.context_truncated,
),
+ compactionMarkers: appendCompactionMarker(
+ currentMetadata.compactionMarkers as CompactionMarker[] | undefined,
+ chunk.context_truncated,
+ compactionAnchorToolCallId(toolCalls, chunk.context_truncated),
+ ),
};
}
if (recoveredProviderCompaction) {
@@ -3819,7 +3835,7 @@ function CompactionCountRegistrar({
}): ReactElement | null {
const threadId = useAuiState(({ threadListItem }) => threadListItem.remoteId);
const count = useAuiState(
- ({ thread }) => compactionNoticeMessageIds(thread.messages).size,
+ ({ thread }) => compactionDividerCount(thread.messages),
);
useEffect(() => {
diff --git a/studio/frontend/src/features/chat/stores/compact-request-store.ts b/studio/frontend/src/features/chat/stores/compact-request-store.ts
new file mode 100644
index 00000000000..aa48be9ee40
--- /dev/null
+++ b/studio/frontend/src/features/chat/stores/compact-request-store.ts
@@ -0,0 +1,44 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { create } from "zustand";
+
+// Session only: the server's compaction record is what persists.
+export interface CompactRequestState {
+ requested: Record<string, true>;
+ request: (threadId: string) => void;
+ clear: (threadId: string) => void;
+}
+
+export const useCompactRequestStore = create<CompactRequestState>()((set) => ({
+ requested: {},
+ request: (threadId) =>
+ set((state) =>
+ state.requested[threadId]
+ ? state
+ : { requested: { ...state.requested, [threadId]: true } },
+ ),
+ clear: (threadId) =>
+ set((state) => {
+ if (!state.requested[threadId]) return state;
+ const requested = { ...state.requested };
+ delete requested[threadId];
+ return { requested };
+ }),
+}));
+
+export function requestThreadCompaction(threadId: string): void {
+ useCompactRequestStore.getState().request(threadId);
+}
+
+export function takeThreadCompactionRequest(threadId: string | undefined): boolean {
+ if (!threadId) return false;
+ const state = useCompactRequestStore.getState();
+ if (!state.requested[threadId]) return false;
+ state.clear(threadId);
+ return true;
+}
+
+export function isCompactCommand(text: string): boolean {
+ return text.trim().toLowerCase() === "/compact";
+}
diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.ts
index 12ea4aba9e3..6ac40557d95 100644
--- a/studio/frontend/src/features/chat/types/api.ts
+++ b/studio/frontend/src/features/chat/types/api.ts
@@ -827,6 +827,8 @@ export interface OpenAIChatChunk {
boundary_messages?: number;
// true when this fit started a checkpoint, including inside the current tool loop
checkpoint_started?: boolean;
+ // true while the checkpoint in force was started by /compact
+ manual?: boolean;
// true when the provider summarized earlier turns instead of Unsloth dropping them
summarized?: boolean;
// boundary text lets the count be re-derived after deleting an already evicted prompt
diff --git a/studio/frontend/src/features/chat/utils/auto-compaction.ts b/studio/frontend/src/features/chat/utils/auto-compaction.ts
index 2fd8184aaef..187c6b14cf4 100644
--- a/studio/frontend/src/features/chat/utils/auto-compaction.ts
+++ b/studio/frontend/src/features/chat/utils/auto-compaction.ts
@@ -14,10 +14,16 @@ export function ggufCompactionRequestFields(options: {
isGguf: boolean;
isMlx?: boolean;
autoCompactEnabled: boolean;
+ // /compact: asked for by the user, so it applies with auto-compaction off too
+ compactNow?: boolean;
}): {
context_overflow?: "error" | "truncate_oldest";
+ compact_context?: true;
} {
if (!options.isGguf && !options.isMlx) return {};
+ if (options.compactNow) {
+ return { context_overflow: "truncate_oldest", compact_context: true };
+ }
if (!options.autoCompactEnabled) {
// explicit error avoids the UNSLOTH_CONTEXT_OVERFLOW fallback, which may compact
return { context_overflow: "error" };
diff --git a/studio/frontend/src/features/chat/utils/context-truncation.ts b/studio/frontend/src/features/chat/utils/context-truncation.ts
index baa241852ec..8c8a92168e7 100644
--- a/studio/frontend/src/features/chat/utils/context-truncation.ts
+++ b/studio/frontend/src/features/chat/utils/context-truncation.ts
@@ -52,6 +52,46 @@ export function shouldShowCompactionNotice(
);
}
+/** afterToolCallId is null when the fit ran before the reply began. */
+export interface CompactionMarker {
+ afterToolCallId: string | null;
+ truncation: ContextTruncation;
+}
+
+/** A fit that recalled already emitted its `search_conversation`, which belongs after the cut. */
+export function compactionAnchorToolCallId(
+ toolCalls: ReadonlyArray<{ toolCallId?: unknown; toolName?: unknown }>,
+ truncation: ContextTruncation,
+): string | null {
+ let end = toolCalls.length;
+ if (
+ (truncation.recalled_chunks ?? 0) > 0 &&
+ toolCalls[end - 1]?.toolName === "search_conversation"
+ ) {
+ end -= 1;
+ }
+ const id = toolCalls[end - 1]?.toolCallId;
+ return typeof id === "string" ? id : null;
+}
+
+/** Skips the cut a tool loop replays every round. */
+export function appendCompactionMarker(
+ markers: CompactionMarker[] | undefined,
+ truncation: ContextTruncation,
+ afterToolCallId: string | null,
+): CompactionMarker[] | undefined {
+ if (!promptWasShortened(truncation)) return markers;
+ const last = markers?.[markers.length - 1];
+ if (
+ last &&
+ truncation.checkpoint_started !== true &&
+ compactionBoundary(truncation) <= compactionBoundary(last.truncation)
+ ) {
+ return markers;
+ }
+ return [...(markers ?? []), { afterToolCallId, truncation }];
+}
+
function nonNegativeInt(value: number | undefined): number {
// A propagated NaN would print "NaN tokens on its own" at the user.
return Number.isFinite(value) ? Math.max(0, Math.trunc(value as number)) : 0;
diff --git a/studio/frontend/tests/chat-barrel-module-scope-reads.test.ts b/studio/frontend/tests/chat-barrel-module-scope-reads.test.ts
index c4f87b19272..04cbda1a423 100644
--- a/studio/frontend/tests/chat-barrel-module-scope-reads.test.ts
+++ b/studio/frontend/tests/chat-barrel-module-scope-reads.test.ts
@@ -1524,7 +1524,6 @@ const KNOWN_DEEP_CYCLE_READS = new Map<string, number>([
["components/assistant-ui/thread.tsx: Sources", 1],
["components/assistant-ui/thread.tsx: TerminalToolUI", 1],
["components/assistant-ui/thread.tsx: ToolFallback", 1],
- ["components/assistant-ui/thread.tsx: ToolGroup", 1],
["components/assistant-ui/thread.tsx: WebSearchToolUI", 1],
["components/ui/sidebar.tsx: SIDEBAR_WIDTH_DEFAULT", 1],
["features/chat/attachment-content.ts: MAX_OPEN_DOCUMENT_ARCHIVE_BYTES", 1],
diff --git a/studio/frontend/tests/manual-compaction.test.ts b/studio/frontend/tests/manual-compaction.test.ts
new file mode 100644
index 00000000000..524cb4e8198
--- /dev/null
+++ b/studio/frontend/tests/manual-compaction.test.ts
@@ -0,0 +1,257 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+import {
+ compactionDividerCount,
+ compactionDividerRows,
+ compactionToolCallDividers,
+} from "../src/components/assistant-ui/message-derived.ts";
+import { ggufCompactionRequestFields } from "../src/features/chat/utils/auto-compaction.ts";
+import {
+ appendCompactionMarker,
+ type CompactionMarker,
+ compactionAnchorToolCallId,
+ type ContextTruncation,
+} from "../src/features/chat/utils/context-truncation.ts";
+import {
+ isCompactCommand,
+ requestThreadCompaction,
+ takeThreadCompactionRequest,
+} from "../src/features/chat/stores/compact-request-store.ts";
+
+import { readSrc } from "./helpers/kit.ts";
+
+const fit = (
+ boundary: number,
+ extra: Partial<ContextTruncation> = {},
+): ContextTruncation => ({
+ dropped_messages: boundary,
+ boundary_messages: boundary,
+ fits: true,
+ ...extra,
+});
+
+test("/compact is the command typed alone, in any case", () => {
+ assert.equal(isCompactCommand("/compact"), true);
+ assert.equal(isCompactCommand(" /COMPACT \n"), true);
+ assert.equal(isCompactCommand("/compact the chat please"), false);
+ assert.equal(isCompactCommand("compact"), false);
+});
+
+test("a compaction request applies to the thread's next request only", () => {
+ requestThreadCompaction("t1");
+ requestThreadCompaction("t1");
+ assert.equal(takeThreadCompactionRequest("t2"), false);
+ assert.equal(takeThreadCompactionRequest(undefined), false);
+ assert.equal(takeThreadCompactionRequest("t1"), true);
+ assert.equal(takeThreadCompactionRequest("t1"), false);
+});
+
+test("compact now asks a GGUF or MLX model to compact, even with auto-compaction off", () => {
+ const asked = { context_overflow: "truncate_oldest", compact_context: true };
+ for (const autoCompactEnabled of [true, false]) {
+ assert.deepEqual(
+ ggufCompactionRequestFields({ isGguf: true, autoCompactEnabled, compactNow: true }),
+ asked,
+ );
+ assert.deepEqual(
+ ggufCompactionRequestFields({
+ isGguf: false,
+ isMlx: true,
+ autoCompactEnabled,
+ compactNow: true,
+ }),
+ asked,
+ );
+ }
+ assert.deepEqual(
+ ggufCompactionRequestFields({ isGguf: false, autoCompactEnabled: true, compactNow: true }),
+ {},
+ );
+});
+
+test("a tool loop's replayed cut is not a new marker, a new reset is", () => {
+ let markers: CompactionMarker[] | undefined;
+ markers = appendCompactionMarker(markers, fit(0, { dropped_messages: 0 }), null);
+ assert.equal(markers, undefined);
+ markers = appendCompactionMarker(markers, fit(4, { checkpoint_started: true }), null);
+ markers = appendCompactionMarker(markers, fit(4), "call-1");
+ markers = appendCompactionMarker(markers, fit(4, { checkpoint_started: true }), "call-2");
+ assert.deepEqual(
+ markers?.map((marker) => marker.afterToolCallId),
+ [null, "call-2"],
+ );
+});
+
+const toolCall = (toolCallId: string) => ({ type: "tool-call", toolCallId });
+
+test("a compaction inside a tool loop is drawn after the call it followed", () => {
+ const midLoop = fit(0, { dropped_messages: 6, checkpoint_started: true });
+ const messages = [
+ { id: "u1", role: "user" },
+ {
+ id: "a1",
+ role: "assistant",
+ parts: [toolCall("call-1"), toolCall("call-2"), toolCall("call-3")],
+ metadata: {
+ custom: {
+ contextTruncation: midLoop,
+ compactionMarkers: [{ afterToolCallId: "call-2", truncation: midLoop }],
+ },
+ },
+ },
+ ];
+
+ assert.equal(compactionDividerRows(messages).size, 0);
+ assert.deepEqual(compactionToolCallDividers(messages).get("a1"), {
+ afterToolCallId: "call-2",
+ truncation: midLoop,
+ });
+ assert.equal(compactionDividerCount(messages), 1);
+});
+
+test("a request that compacted before replying keeps its divider above the prompt", () => {
+ const atStart = fit(4, { checkpoint_started: true, manual: true });
+ const inLoop = fit(4, { dropped_messages: 3, checkpoint_started: true });
+ const messages = [
+ { id: "u1", role: "user" },
+ { id: "a1", role: "assistant" },
+ { id: "u2", role: "user" },
+ {
+ id: "a2",
+ role: "assistant",
+ parts: [toolCall("call-9")],
+ metadata: {
+ custom: {
+ contextTruncation: inLoop,
+ compactionMarkers: [
+ { afterToolCallId: null, truncation: atStart },
+ { afterToolCallId: "call-9", truncation: inLoop },
+ ],
+ },
+ },
+ },
+ ];
+
+ assert.deepEqual([...compactionDividerRows(messages)], [["u2", atStart]]);
+ assert.deepEqual(
+ [...compactionToolCallDividers(messages)].map(([id, m]) => [id, m.afterToolCallId, m.truncation]),
+ [["a2", "call-9", inLoop]],
+ );
+ assert.equal(compactionDividerCount(messages), 2);
+});
+
+test("a marker naming a call the reply no longer shows falls back to the prompt", () => {
+ const midLoop = fit(0, { dropped_messages: 2, checkpoint_started: true });
+ const messages = [
+ { id: "u1", role: "user" },
+ {
+ id: "a1",
+ role: "assistant",
+ parts: [],
+ metadata: {
+ custom: {
+ contextTruncation: midLoop,
+ compactionMarkers: [{ afterToolCallId: "gone", truncation: midLoop }],
+ },
+ },
+ },
+ ];
+
+ assert.deepEqual([...compactionDividerRows(messages)], [["u1", midLoop]]);
+ assert.equal(compactionToolCallDividers(messages).size, 0);
+});
+
+test("the composer reads /compact before any send path, and only for GGUF or MLX", async () => {
+ const thread = await readSrc("components/assistant-ui/thread.tsx");
+ const submit = thread.slice(thread.indexOf("const handleSubmit = useCallback("));
+ const command = submit.indexOf("isCompactCommand(composerText)");
+ assert.ok(command > 0);
+ assert.ok(command < submit.indexOf("if (disabled || shouldBlockSend())"));
+ assert.match(submit, /requestThreadCompaction\(referenceThreadId\)/);
+ assert.match(submit, /resumesThought\(\{/);
+ assert.match(submit, /!runtime\.supportsTools \|\|/);
+ assert.match(submit, /runtime\.incognito \|\| isThreadIncognito\(referenceThreadId\)/);
+ const adapter = await readSrc("features/chat/api/chat-adapter.ts");
+ assert.match(adapter, /takeThreadCompactionRequest\(resolvedThreadId\) &&/);
+ assert.match(adapter, /compactNow,\n\s+\}\),/);
+ // Only a reset started by this request counts; a replayed manual epoch is not one.
+ assert.match(
+ adapter,
+ /marker\.truncation\.manual === true &&\s+marker\.truncation\.checkpoint_started === true/,
+ );
+ assert.match(adapter, /compactNow &&\n\s+!compactionMarkers\?\.some\(/);
+ assert.match(adapter, /"This chat was not compacted"/);
+});
+
+test("a fit that recalled anchors before the recall it already emitted", () => {
+ const recalled = fit(4, { checkpoint_started: true, recalled_chunks: 3 });
+ const search = { toolCallId: "recall", toolName: "search_conversation" };
+ const terminal = { toolCallId: "call-1", toolName: "terminal" };
+ assert.equal(compactionAnchorToolCallId([search], recalled), null);
+ assert.equal(compactionAnchorToolCallId([terminal, search], recalled), "call-1");
+ assert.equal(compactionAnchorToolCallId([terminal, search], fit(4)), "recall");
+ assert.equal(compactionAnchorToolCallId([], fit(4)), null);
+});
+
+test("a reply that reset on many tool rounds draws only its last reset", () => {
+ const reset = (dropped: number) =>
+ fit(0, { dropped_messages: dropped, checkpoint_started: true });
+ const first = reset(4);
+ const last = reset(2);
+ const messages = [
+ { id: "u1", role: "user" },
+ {
+ id: "a1",
+ role: "assistant",
+ parts: [toolCall("c1"), toolCall("c2"), toolCall("c3")],
+ metadata: {
+ custom: {
+ contextTruncation: last,
+ compactionMarkers: [
+ { afterToolCallId: "c1", truncation: first },
+ { afterToolCallId: "c2", truncation: reset(3) },
+ { afterToolCallId: "c3", truncation: last },
+ ],
+ },
+ },
+ },
+ ];
+
+ assert.deepEqual(
+ [...compactionToolCallDividers(messages)].map(([id, m]) => [id, m.afterToolCallId, m.truncation]),
+ [["a1", "c3", last]],
+ );
+ assert.equal(compactionDividerCount(messages), 1);
+});
+
+test("two replies reusing a tool call id keep their own dividers", () => {
+ const reset = (dropped: number) =>
+ fit(0, { dropped_messages: dropped, checkpoint_started: true });
+ const reply = (id: string, truncation: ContextTruncation) => ({
+ id,
+ role: "assistant",
+ parts: [toolCall("tool_call_0")],
+ metadata: {
+ custom: {
+ contextTruncation: truncation,
+ compactionMarkers: [{ afterToolCallId: "tool_call_0", truncation }],
+ },
+ },
+ });
+ const first = reset(4);
+ const second = reset(5);
+ const messages = [
+ { id: "u1", role: "user" },
+ reply("a1", first),
+ { id: "u2", role: "user" },
+ reply("a2", second),
+ ];
+
+ const dividers = compactionToolCallDividers(messages);
+ assert.equal(dividers.get("a1")?.truncation, first);
+ assert.equal(dividers.get("a2")?.truncation, second);
+ assert.equal(compactionDividerCount(messages), 2);
+});
diff --git a/studio/frontend/tests/rolling-context-window.test.ts b/studio/frontend/tests/rolling-context-window.test.ts
index 0e6440e4789..febcf798745 100644
--- a/studio/frontend/tests/rolling-context-window.test.ts
+++ b/studio/frontend/tests/rolling-context-window.test.ts
@@ -219,6 +219,8 @@ test("the compaction notice renders from persisted metadata, not from a message"
// Read off metadata.custom so it can never become part of the conversation.
assert.match(DERIVED, /\.custom\.contextTruncation/);
assert.match(THREAD, /<CompactionDivider truncation=\{truncation\} \/>/);
+ assert.match(THREAD, /compactionToolCallDividers\(thread\.messages\)/);
+ assert.match(THREAD, /ToolGroup: ToolGroupThenCompaction,/);
assert.match(COMPACTION_DIVIDER, /Context compacted/);
});
@@ -268,7 +270,7 @@ test("a boundary that goes BACKWARDS does not re-announce", () => {
test("the context meter counts exactly the compaction notices the thread renders", () => {
assert.match(
RUNTIME_PROVIDER,
- /compactionNoticeMessageIds\(thread\.messages\)\.size/,
+ /compactionDividerCount\(thread\.messages\)/,
);
assert.match(RUNTIME_PROVIDER, /<CompactionCountRegistrar onCountChange=/);
// Project views show the meter for a chat started on the landing page too.