返回 CodeWhale
compaction_flow.rs
根目录 / crates / tui / src / tui / ui / compaction_flow.rs
1 //! Compaction UI state: manual/automatic compaction queueing, settlement,
2 //! receipts, and cancel behavior (docs/architecture/TUI_MODULARIZATION.md slice 7). The engine
3 //! owns the actual summarization; this module projects its lifecycle into the
4 //! UI and never awaits the bounded engine mailbox from the event loop.
5
6 use super::*;
7
8 /// Queue a live compaction update without waiting on the engine mailbox.
9 ///
10 /// Config edits are valid while a turn is streaming, but awaiting a bounded
11 /// engine mailbox from the UI event loop can make the whole TUI appear frozen
12 /// when the turn is busy. A dropped refresh is safe: the next turn rebuilds
13 /// its compaction config from `App`, and the status message tells the user
14 /// whether the update was queued or deferred.
15 ///
16 /// The model and its compaction budget are one route update: both mailbox
17 /// slots are reserved before either op is sent, so a full mailbox defers the
18 /// whole update instead of applying the model without its budget (U03-05).
19 pub(crate) fn try_apply_model_and_compaction_update(
20 engine_handle: &EngineHandle,
21 compaction: codewhale_engine::compaction::CompactionConfig,
22 mode: AppMode,
23 route_limits: Option<codewhale_config::route::RouteLimits>,
24 ) -> bool {
25 let Ok(model_permit) = engine_handle.tx_op.clone().try_reserve_owned() else {
26 return false;
27 };
28 let Ok(compaction_permit) = engine_handle.tx_op.clone().try_reserve_owned() else {
29 return false;
30 };
31 engine_handle.send_reserved_op(
32 model_permit,
33 Op::SetModel {
34 model: compaction.model.clone(),
35 mode,
36 route_limits,
37 },
38 );
39 engine_handle.send_reserved_op(compaction_permit, Op::SetCompaction { config: compaction });
40 true
41 }
42
43 pub(crate) fn set_explicit_compaction_status(
44 app: &mut App,
45 text: String,
46 level: StatusToastLevel,
47 sticky: bool,
48 ) {
49 if sticky {
50 app.set_sticky_status(text, level, Some(App::STICKY_ERROR_TTL_MS));
51 } else {
52 app.push_status_toast(text, level, Some(5_000));
53 }
54 }
55
56 /// Queue manual compaction without ever awaiting the bounded engine mailbox
57 /// from the terminal event loop.
58 ///
59 /// During an active turn, a successful send is intentionally deferred until
60 /// the engine returns to its outer operation loop. Full and closed mailboxes
61 /// are rejected immediately with an actionable receipt, so `/compact` cannot
62 /// freeze keyboard input or rendering.
63 pub(crate) fn try_queue_manual_compaction(
64 app: &mut App,
65 config: &Config,
66 engine_handle: &EngineHandle,
67 focus: Option<String>,
68 ) {
69 if app.is_compacting || app.manual_compaction_queued {
70 let text = app
71 .tr(MessageId::ContextCompactionAlreadyRunning)
72 .into_owned();
73 add_compaction_receipt(app, &text);
74 set_explicit_compaction_status(app, text, StatusToastLevel::Warning, false);
75 return;
76 }
77
78 let route = match validated_app_runtime_route(app, config) {
79 Ok(route) => route,
80 Err(error) => {
81 let text = app
82 .tr(MessageId::ContextCompactionRouteInvalid)
83 .replace("{error}", &error.to_string());
84 add_compaction_receipt(app, &text);
85 set_explicit_compaction_status(app, text, StatusToastLevel::Error, true);
86 return;
87 }
88 };
89 let mut compaction = compaction_for_validated_route(app, &route);
90 compaction.focus = focus.clone();
91 let request_id = format!("compact_{}", &uuid::Uuid::new_v4().to_string()[..8]);
92 let op = Op::CompactContext {
93 id: request_id.clone(),
94 route: Box::new(route.into_resolved()),
95 compaction: Box::new(compaction),
96 };
97
98 match engine_handle.try_send(op) {
99 Ok(()) => {
100 app.manual_compaction_queued = true;
101 app.manual_compaction_id = Some(request_id);
102 let id = if app.is_loading {
103 MessageId::ContextCompactionQueued
104 } else {
105 MessageId::ContextManualCompacting
106 };
107 let text = app.tr(id).into_owned();
108 // Queued-behind-a-turn is a state the user must be able to find
109 // again after the 5s toast: leave it in the transcript too.
110 if app.is_loading {
111 add_compaction_receipt(app, &text);
112 }
113 set_explicit_compaction_status(app, text, StatusToastLevel::Info, false);
114 }
115 Err(error) => {
116 let full = error
117 .downcast_ref::<tokio::sync::mpsc::error::TrySendError<Op>>()
118 .is_some_and(|send_error| {
119 matches!(send_error, tokio::sync::mpsc::error::TrySendError::Full(_))
120 });
121 if full {
122 // A saturated mailbox is a timing accident of the active turn,
123 // not a user error. Queue client-side and let the event loop
124 // retry once the engine drains a slot; the user sees the same
125 // queued receipt as the ordinary behind-a-turn path.
126 app.manual_compaction_queued = true;
127 app.manual_compaction_id = Some(request_id);
128 app.deferred_manual_compaction = Some(focus);
129 let text = app.tr(MessageId::ContextCompactionQueued).into_owned();
130 add_compaction_receipt(app, &text);
131 set_explicit_compaction_status(app, text, StatusToastLevel::Info, false);
132 } else {
133 let text = app.tr(MessageId::ContextCompactionQueueClosed).into_owned();
134 add_compaction_receipt(app, &text);
135 set_explicit_compaction_status(app, text, StatusToastLevel::Error, true);
136 }
137 }
138 }
139 }
140
141 /// Retry a manual compaction that was deferred by a full engine mailbox.
142 ///
143 /// Called once per event-loop iteration. Silent by design: the queued receipt
144 /// was already written when the request was deferred, a still-full mailbox
145 /// just waits for the next iteration, and a compaction that started or
146 /// settled in the meantime supersedes the request entirely (handled by
147 /// `apply_compaction_started`/`settle_compaction`).
148 pub(crate) fn flush_deferred_manual_compaction(
149 app: &mut App,
150 config: &Config,
151 engine_handle: &EngineHandle,
152 ) {
153 if app.deferred_manual_compaction.is_none() || app.is_compacting {
154 return;
155 }
156 let route = match validated_app_runtime_route(app, config) {
157 Ok(route) => route,
158 Err(error) => {
159 app.deferred_manual_compaction = None;
160 app.manual_compaction_queued = false;
161 app.manual_compaction_id = None;
162 let text = app
163 .tr(MessageId::ContextCompactionRouteInvalid)
164 .replace("{error}", &error.to_string());
165 add_compaction_receipt(app, &text);
166 set_explicit_compaction_status(app, text, StatusToastLevel::Error, true);
167 return;
168 }
169 };
170 let focus = app.deferred_manual_compaction.clone().unwrap_or_default();
171 let Some(request_id) = app.manual_compaction_id.clone() else {
172 app.deferred_manual_compaction = None;
173 app.manual_compaction_queued = false;
174 return;
175 };
176 let mut compaction = compaction_for_validated_route(app, &route);
177 compaction.focus = focus;
178 let op = Op::CompactContext {
179 id: request_id,
180 route: Box::new(route.into_resolved()),
181 compaction: Box::new(compaction),
182 };
183 match engine_handle.try_send(op) {
184 Ok(()) => {
185 app.deferred_manual_compaction = None;
186 }
187 Err(error) => {
188 let full = error
189 .downcast_ref::<tokio::sync::mpsc::error::TrySendError<Op>>()
190 .is_some_and(|send_error| {
191 matches!(send_error, tokio::sync::mpsc::error::TrySendError::Full(_))
192 });
193 if !full {
194 app.deferred_manual_compaction = None;
195 app.manual_compaction_queued = false;
196 app.manual_compaction_id = None;
197 let text = app.tr(MessageId::ContextCompactionQueueClosed).into_owned();
198 add_compaction_receipt(app, &text);
199 set_explicit_compaction_status(app, text, StatusToastLevel::Error, true);
200 }
201 }
202 }
203 }
204
205 pub(crate) fn apply_compaction_started(app: &mut App, id: String, auto: bool) {
206 app.clear_context_pressure_sticky_status();
207 if !auto {
208 app.manual_compaction_queued = false;
209 if app.manual_compaction_id.as_deref() == Some(id.as_str()) {
210 app.manual_compaction_id = None;
211 }
212 }
213 // A compaction is running; a deferred manual request is now redundant.
214 // Dropping it must also release the queued flag when the running pass is
215 // automatic, or `/compact` would report "already in progress" forever.
216 if app.deferred_manual_compaction.take().is_some() && auto {
217 app.manual_compaction_queued = false;
218 app.manual_compaction_id = None;
219 }
220 app.active_compaction = Some(ActiveCompaction { id, auto });
221 app.is_compacting = true;
222 if !auto {
223 let text = app.tr(MessageId::ContextManualCompacting).into_owned();
224 set_explicit_compaction_status(app, text, StatusToastLevel::Info, false);
225 }
226 let trigger = if auto { "auto" } else { "manual" };
227 if let Err(error) = super::observer_hooks::execute_pre_compact_observer_hook(
228 app,
229 trigger,
230 app.api_messages.len(),
231 app.session.total_conversation_tokens,
232 ) {
233 tracing::warn!("pre_compact hook submission failed: {error}");
234 }
235 }
236
237 /// Clear the compaction-in-flight state for a terminal lifecycle event.
238 ///
239 /// An exact id match clears normally. A terminal event with NO tracked
240 /// compaction is still authoritative (the started event can be lost to a
241 /// dropped drain or session switch): without this, `is_compacting`/
242 /// `manual_compaction_queued` stayed latched and every later `/compact` was
243 /// silently rejected as "already in progress". A stale event while a NEWER
244 /// compaction is live must not clear it (or report anything) — that live
245 /// pass gets its own terminal event. Returns whether the event settled.
246 pub(crate) fn settle_compaction(app: &mut App, id: &str, auto: bool) -> bool {
247 if app
248 .active_compaction
249 .as_ref()
250 .is_some_and(|active| active.id != id || active.auto != auto)
251 {
252 return false;
253 }
254 app.active_compaction = None;
255 app.is_compacting = false;
256 if !auto {
257 app.manual_compaction_queued = false;
258 app.manual_compaction_id = None;
259 }
260 // A settled pass makes a still-deferred manual request redundant (the
261 // context was just compacted). Dropping it releases the queued flag so a
262 // later `/compact` is not rejected as "already in progress".
263 if app.deferred_manual_compaction.take().is_some() {
264 app.manual_compaction_queued = false;
265 app.manual_compaction_id = None;
266 }
267 true
268 }
269
270 /// Durable transcript receipt for a compaction outcome.
271 ///
272 /// Outcome feedback used to be toast-only, and the engine emits
273 /// `TurnComplete` immediately after the compaction event — both land in the
274 /// same UI drain batch, so the turn's "done" status replaced the completion
275 /// toast before a single frame was drawn. `/compact` looked like a no-op
276 /// even when the summary committed (the v0.9.6 release blocker).
277 pub(crate) fn add_compaction_receipt(app: &mut App, message: &str) {
278 app.add_message(HistoryCell::System {
279 content: message.to_string(),
280 });
281 }
282
283 pub(crate) fn apply_compaction_completed(
284 app: &mut App,
285 id: &str,
286 auto: bool,
287 message: String,
288 messages_before: Option<usize>,
289 messages_after: Option<usize>,
290 summary_prompt: Option<String>,
291 ) {
292 if settle_compaction(app, id, auto) {
293 // The billed prompt receipt described the pre-compaction context;
294 // after the rewrite the local estimate is the honest signal until
295 // the next model call bills the new, smaller prompt (#5577).
296 app.last_billed_input_tokens = None;
297 let keep = codewhale_engine::compaction::inspect_compaction_keep(&app.api_messages);
298 let path = if summary_prompt
299 .as_deref()
300 .is_some_and(|text| !text.trim().is_empty())
301 {
302 codewhale_engine::compaction::CompactionPath::Summary
303 } else {
304 codewhale_engine::compaction::CompactionPath::PruneOnly
305 };
306 let after = messages_after.unwrap_or(app.api_messages.len());
307 let before = messages_before.unwrap_or(after);
308 app.last_compaction = Some(codewhale_engine::compaction::LastCompactionSnapshot {
309 auto,
310 coverage: codewhale_engine::compaction::CompactionCoverage {
311 path,
312 last_round_messages: keep.last_round_messages,
313 last_round_tool_results: keep.last_round_tool_results,
314 last_round_assistant: keep.last_round_assistant,
315 dropped_messages: before.saturating_sub(after),
316 anchors_chars: codewhale_engine::compaction::pinned_anchors_text(Some(
317 &app.workspace,
318 ))
319 .map(|text| text.chars().count())
320 .unwrap_or(0),
321 // Only the summary path builds a replacement history, so only
322 // it spent a verbatim budget (#5956).
323 retained_user_message_tokens: match path {
324 codewhale_engine::compaction::CompactionPath::Summary => {
325 app.compaction_retained_user_message_tokens
326 }
327 codewhale_engine::compaction::CompactionPath::PruneOnly => 0,
328 },
329 operator_instructions_applied: matches!(
330 path,
331 codewhale_engine::compaction::CompactionPath::Summary
332 ) && app.compaction_summary_instructions.is_some(),
333 },
334 messages_before: before,
335 messages_after: after,
336 });
337 // Automatic maintenance stays in the context inspector and event
338 // receipts; it does not insert a ceremony into the user's task.
339 if !auto {
340 add_compaction_receipt(app, &message);
341 set_explicit_compaction_status(app, message, StatusToastLevel::Success, false);
342 }
343 }
344 }
345
346 pub(crate) fn apply_compaction_failed(app: &mut App, id: &str, auto: bool, message: String) {
347 if settle_compaction(app, id, auto) {
348 add_compaction_receipt(app, &message);
349 // A pass the user asked for keeps its sticky footer error. An
350 // automatic pass is the engine's own recovery: the transcript receipt
351 // records it, and when the turn then fails its error line is the
352 // headline. Echoing the same failure in the footer made one failure
353 // read as three (experience mark 2).
354 if !auto {
355 set_explicit_compaction_status(app, message, StatusToastLevel::Error, true);
356 }
357 }
358 }
359
360 pub(crate) fn apply_compaction_cancelled(app: &mut App, id: &str, auto: bool, message: String) {
361 if settle_compaction(app, id, auto) {
362 add_compaction_receipt(app, &message);
363 set_explicit_compaction_status(app, message, StatusToastLevel::Info, false);
364 }
365 }
366
367 /// Esc/Ctrl+C during a compact that is serving an in-flight turn must stop
368 /// the turn. Compact-only (manual `/compact` with no model request) still
369 /// cancels just the pass.
370 #[must_use]
371 pub(crate) fn compact_interrupt_should_stop_turn(app: &App) -> bool {
372 (app.is_compacting || app.manual_compaction_queued)
373 && (app.is_loading || matches!(app.runtime_turn_status.as_deref(), Some("in_progress")))
374 }
375
376 /// Cancel the exact queued or running pass without cancelling an unrelated
377 /// model turn. A locally deferred request has never entered the engine, so it
378 /// can settle synchronously with no provider call; all dispatched requests
379 /// wait for the authoritative typed terminal event.
380 pub(crate) fn try_cancel_compaction(app: &mut App, engine_handle: &EngineHandle) -> bool {
381 if !app.is_compacting && !app.manual_compaction_queued {
382 return false;
383 }
384
385 if !app.is_compacting && app.deferred_manual_compaction.take().is_some() {
386 app.manual_compaction_queued = false;
387 app.manual_compaction_id = None;
388 let message = "Making room stopped before it started".to_string();
389 add_compaction_receipt(app, &message);
390 set_explicit_compaction_status(app, message, StatusToastLevel::Info, false);
391 return true;
392 }
393
394 let id = app
395 .active_compaction
396 .as_ref()
397 .map(|active| active.id.clone())
398 .or_else(|| app.manual_compaction_id.clone());
399 let Some(id) = id else {
400 return false;
401 };
402
403 match engine_handle.cancel_compaction(id) {
404 Ok(()) => {
405 set_explicit_compaction_status(
406 app,
407 "Stopping making room…".to_string(),
408 StatusToastLevel::Info,
409 false,
410 );
411 }
412 Err(error) => {
413 let message = format!("Could not stop making room: {error}");
414 add_compaction_receipt(app, &message);
415 set_explicit_compaction_status(app, message, StatusToastLevel::Error, true);
416 }
417 }
418 true
419 }
420
421 pub(crate) fn maybe_warn_context_pressure(app: &mut App) {
422 let config = app.compaction_config();
423 maybe_warn_context_pressure_for_config(app, &config);
424 }
425
426 pub(crate) fn maybe_warn_context_pressure_for_config(
427 app: &mut App,
428 config: &codewhale_engine::compaction::CompactionConfig,
429 ) {
430 if config.enabled {
431 app.clear_context_pressure_sticky_status();
432 return;
433 }
434 let max = config
435 .effective_context_window
436 .unwrap_or_else(|| app.effective_context_window());
437 let Some((used, max, percent)) = context_usage_snapshot_for_window(app, max) else {
438 app.clear_context_pressure_sticky_status();
439 return;
440 };
441
442 let configured_threshold = app.auto_compact_threshold_percent.clamp(10.0, 100.0);
443 let warning_threshold = CONTEXT_SUGGEST_COMPACT_THRESHOLD_PERCENT.min(configured_threshold);
444 if percent < warning_threshold {
445 app.clear_context_pressure_sticky_status();
446 return;
447 }
448 let pressure_level = if percent >= CONTEXT_CRITICAL_THRESHOLD_PERCENT {
449 codewhale_runtime::context_budget::PressureLevel::Critical
450 } else if percent >= CONTEXT_WARNING_THRESHOLD_PERCENT {
451 codewhale_runtime::context_budget::PressureLevel::High
452 } else {
453 codewhale_runtime::context_budget::PressureLevel::Medium
454 };
455 if app
456 .context_pressure_warning_dismissed
457 .is_some_and(|dismissed| pressure_level <= dismissed)
458 {
459 return;
460 }
461
462 // #5239: the meter drives real budgets off this window, so an unverified
463 // one must say so next to the numbers that depend on it.
464 let window_note = if app.effective_context_window_source().is_verified() {
465 ""
466 } else {
467 ", unverified window"
468 };
469
470 let recommendation = "Making room automatically is off. Turn on auto_compact or use /compact.";
471
472 if percent >= CONTEXT_CRITICAL_THRESHOLD_PERCENT {
473 set_context_pressure_status(
474 app,
475 format!(
476 "Context critical: {percent:.0}% ({used}/{max} tokens{window_note}). {recommendation}"
477 ),
478 pressure_level,
479 );
480 return;
481 }
482
483 let status_prefix = if percent >= CONTEXT_WARNING_THRESHOLD_PERCENT {
484 "Context high"
485 } else {
486 "Context building"
487 };
488 set_context_pressure_status(
489 app,
490 format!(
491 "{status_prefix}: {percent:.0}% ({used}/{max} tokens{window_note}). {recommendation}"
492 ),
493 pressure_level,
494 );
495 }
496
497 fn set_context_pressure_status(
498 app: &mut App,
499 text: String,
500 pressure_level: codewhale_runtime::context_budget::PressureLevel,
501 ) {
502 let can_replace = app.sticky_status.as_ref().is_none_or(|status| {
503 matches!(
504 status.kind,
505 crate::tui::app::StatusToastKind::ContextPressure(_)
506 )
507 });
508 if !can_replace {
509 return;
510 }
511 // No TTL: this warning stays visible until compaction or explicit Esc
512 // dismissal instead of being pushed out by later transcript activity.
513 app.sticky_status = Some(crate::tui::app::StatusToast::context_pressure(
514 text,
515 pressure_level,
516 ));
517 app.needs_redraw = true;
518 }
519
520 #[cfg(test)]
521 mod config_update_tests {
522 use super::*;
523 use codewhale_engine::core::engine::mock_engine_handle;
524 use codewhale_engine::core::ops::Op;
525
526 #[tokio::test]
527 async fn live_compaction_update_queues_without_waiting_on_engine() {
528 let mut mock = mock_engine_handle();
529 let compaction = codewhale_engine::compaction::CompactionConfig {
530 enabled: false,
531 token_threshold: 123,
532 model: "deepseek-v4-flash".to_string(),
533 effective_context_window: Some(128_000),
534 cache_summary: true,
535 focus: None,
536 runtime_cost_owner: None,
537 workspace: None,
538 image_input: codewhale_engine::model_profile::SupportState::Unknown,
539 summary_instructions: None,
540 retained_user_message_tokens:
541 codewhale_runtime::config::DEFAULT_COMPACTION_RETAINED_USER_MESSAGE_TOKENS,
542 };
543
544 assert!(try_apply_model_and_compaction_update(
545 &mock.handle,
546 compaction.clone(),
547 AppMode::Agent,
548 None,
549 ));
550
551 assert!(matches!(
552 mock.rx_op.recv().await,
553 Some(Op::SetModel {
554 model,
555 mode: AppMode::Agent,
556 route_limits: None,
557 }) if model == compaction.model
558 ));
559 assert!(matches!(
560 mock.rx_op.recv().await,
561 Some(Op::SetCompaction { config }) if config == compaction
562 ));
563 }
564
565 /// U03-05: with room for only one op, neither half of the route update
566 /// is queued; a model without its compaction budget is a half-applied
567 /// route with nothing to roll it back.
568 #[tokio::test]
569 async fn live_compaction_update_is_all_or_nothing_when_one_slot_is_free() {
570 let mut mock = mock_engine_handle();
571 let mut fillers = 0;
572 while mock.handle.tx_op.capacity() > 1 {
573 mock.handle
574 .try_send(Op::ListSubAgents)
575 .expect("filler op fits");
576 fillers += 1;
577 }
578 let compaction = codewhale_engine::compaction::CompactionConfig {
579 model: "deepseek-v4-flash".to_string(),
580 ..codewhale_engine::compaction::CompactionConfig::default()
581 };
582
583 assert!(!try_apply_model_and_compaction_update(
584 &mock.handle,
585 compaction,
586 AppMode::Agent,
587 None,
588 ));
589
590 for _ in 0..fillers {
591 assert!(matches!(mock.rx_op.try_recv(), Ok(Op::ListSubAgents)));
592 }
593 assert!(
594 mock.rx_op.try_recv().is_err(),
595 "no half of the route update may be queued"
596 );
597 }
598
599 #[cfg(unix)]
600 #[test]
601 fn compaction_started_submits_pre_compact_observer_hook() {
602 use codewhale_config::hooks::{Hook, HookEvent, HooksConfig};
603 use codewhale_engine::hooks::HookExecutor;
604 use std::time::{Duration, Instant};
605
606 let _env_lock = crate::test_support::lock_test_env();
607 let dir = tempfile::tempdir().expect("tempdir");
608 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", dir.path());
609 let marker = dir.path().join("pre_compact.json");
610 let cmd = format!("cat > '{}'", marker.display());
611
612 let mut app = App::new(
613 crate::tui::test_support::test_tui_options(dir.path()),
614 &codewhale_runtime::config::Config::default(),
615 );
616 app.session.total_conversation_tokens = 2048;
617 app.hooks = HookExecutor::new(
618 HooksConfig {
619 enabled: true,
620 hooks: vec![Hook::new(HookEvent::PreCompact, &cmd)],
621 ..HooksConfig::default()
622 },
623 dir.path().to_path_buf(),
624 );
625
626 apply_compaction_started(&mut app, "cmp_1".to_string(), true);
627
628 let deadline = Instant::now() + Duration::from_secs(3);
629 let raw = loop {
630 if let Ok(content) = std::fs::read_to_string(&marker)
631 && !content.is_empty()
632 {
633 break content;
634 }
635 assert!(
636 Instant::now() < deadline,
637 "pre_compact hook did not write payload"
638 );
639 std::thread::sleep(Duration::from_millis(10));
640 };
641 let payload: serde_json::Value = serde_json::from_str(&raw).expect("valid json payload");
642 assert_eq!(payload["event"], "pre_compact");
643 assert_eq!(payload["trigger"], "auto");
644 assert_eq!(payload["token_count"], 2048);
645 }
646 }
647
647 lines RUST