返回 CodeWhale
dispatch.rs
根目录 / crates / tui / src / tui / ui / dispatch.rs
1 //! Getting a composed user message into a turn: dispatch, steering, and the
2 //! offline/queued message paths.
3 //!
4 //! Moved verbatim out of `ui.rs`.
5
6 use super::*;
7 use codewhale_engine::core::ops::TurnSpec;
8 use codewhale_models::Role;
9
10 pub(crate) fn dispatch_hotbar_slot(
11 app: &mut App,
12 config: &Config,
13 slot: u8,
14 ) -> Result<Option<HotbarDispatch>> {
15 let known_action_ids = app
16 .hotbar_actions
17 .iter()
18 .map(|action| action.id())
19 .collect::<Vec<_>>();
20 let bindings = config.resolve_hotbar_bindings(&known_action_ids).bindings;
21 let Some(action_id) = bindings
22 .iter()
23 .find(|binding| binding.slot == slot)
24 .map(|binding| binding.action.clone())
25 else {
26 return Ok(None);
27 };
28
29 let Some(action) = app.hotbar_actions.get(&action_id) else {
30 app.show_command_result(
31 format!("Hotbar slot {slot} action is not available: {action_id}"),
32 StatusToastLevel::Warning,
33 );
34 app.needs_redraw = true;
35 return Ok(Some(HotbarDispatch::Handled));
36 };
37
38 if let Some(reason) = action.disabled_reason(app) {
39 app.show_command_result(
40 format!("Hotbar slot {slot} action is not available: {reason}"),
41 StatusToastLevel::Warning,
42 );
43 app.needs_redraw = true;
44 return Ok(Some(HotbarDispatch::Handled));
45 }
46
47 action.dispatch(app, config).map(Some)
48 }
49
50 pub(crate) fn queued_ui_to_session(msg: &QueuedMessage) -> Result<QueuedSessionMessage> {
51 anyhow::ensure!(
52 msg.extension_command.is_none(),
53 "Plugin command prompts cannot be persisted as user input"
54 );
55 Ok(QueuedSessionMessage {
56 display: msg.display.clone(),
57 skill_instruction: msg.skill_instruction.clone(),
58 skill_provenance: msg.skill_provenance.clone(),
59 })
60 }
61
62 pub(crate) fn queued_session_to_ui(msg: QueuedSessionMessage) -> QueuedMessage {
63 QueuedMessage {
64 display: msg.display,
65 skill_instruction: msg.skill_instruction,
66 skill_provenance: msg.skill_provenance,
67 extension_command: None,
68 approved_plan: None,
69 owner_input: false,
70 // Persistence does not carry this flag; restore may re-echo or rely on
71 // pending preview. Live Queue path sets true after painting.
72 history_echoed: false,
73 }
74 }
75
76 /// Echo a freshly submitted turn into the transcript before it waits on the
77 /// queue / offline bucket. Ops contract: every submit paints `HistoryCell::User`
78 /// before the model runs (queued included).
79 pub(crate) fn echo_queued_user_turn(app: &mut App, message: &mut QueuedMessage) {
80 if message.history_echoed {
81 return;
82 }
83 app.add_message(HistoryCell::User {
84 content: message.display.clone(),
85 });
86 message.history_echoed = true;
87 app.needs_redraw = true;
88 app.scroll_to_bottom();
89 }
90
91 /// Paint command input as an attributed receipt and composer input as a user
92 /// turn, reusing its queue-time echo. Return the displayed cell's index.
93 pub(crate) fn paint_user_turn_cell(
94 app: &mut App,
95 message: &QueuedMessage,
96 content: String,
97 ) -> usize {
98 if let Some((command, _)) = message.extension_command.as_ref() {
99 app.add_message(HistoryCell::System {
100 content: format!("{} command input:\n{content}", command.origin),
101 });
102 return app.history.len().saturating_sub(1);
103 }
104 if message.history_echoed
105 && let Some(idx) = echoed_user_turn_cell(app, &message.display)
106 {
107 app.history[idx] = HistoryCell::User { content };
108 app.bump_history_cell(idx);
109 return idx;
110 }
111 app.add_message(HistoryCell::User { content });
112 app.history.len().saturating_sub(1)
113 }
114
115 /// The newest transcript cell that queue-time echo painted for `display`.
116 pub(crate) fn echoed_user_turn_cell(app: &App, display: &str) -> Option<usize> {
117 app.history
118 .iter()
119 .enumerate()
120 .rev()
121 .find_map(|(idx, cell)| match cell {
122 HistoryCell::User { content } if content == display => Some(idx),
123 _ => None,
124 })
125 }
126
127 fn reject_if_queue_full(app: &mut App, message: QueuedMessage) -> Option<QueuedMessage> {
128 if app.follow_up_queue_full() {
129 app.queue_message(message);
130 return None;
131 }
132 Some(message)
133 }
134
135 pub(crate) fn enqueue_offline_message(app: &mut App, message: QueuedMessage) {
136 app.queue_message(message);
137 persist_offline_queue_state(app);
138 }
139
140 pub(crate) fn push_assistant_message(
141 app: &mut App,
142 text: String,
143 thinking: Option<String>,
144 tool_uses: PendingToolUses,
145 ) {
146 let mut blocks = Vec::new();
147 if let Some(thinking) = thinking {
148 blocks.push(ContentBlock::Thinking {
149 thinking,
150 signature: None,
151 state: None,
152 redacted_data: None,
153 });
154 }
155 if !text.is_empty() {
156 blocks.push(ContentBlock::Text {
157 text,
158 cache_control: None,
159 });
160 }
161 blocks.extend(tool_uses);
162
163 let has_sendable_content = blocks.iter().any(|block| {
164 matches!(
165 block,
166 ContentBlock::Text { .. } | ContentBlock::ToolUse { .. }
167 )
168 });
169 if has_sendable_content {
170 app.push_api_message(Message {
171 role: Role::Assistant,
172 content: blocks,
173 });
174 }
175 }
176
177 pub(crate) fn replace_matching_assistant_text(
178 app: &mut App,
179 original_text: &str,
180 translated_text: String,
181 ) -> bool {
182 for message in app.api_messages_mut().iter_mut().rev() {
183 if message.role != "assistant"
184 && message.role != codewhale_models::INTERRUPTED_ASSISTANT_ROLE
185 {
186 continue;
187 }
188 for block in &mut message.content {
189 if let ContentBlock::Text { text, .. } = block
190 && text == original_text
191 {
192 *text = translated_text;
193 return true;
194 }
195 }
196 }
197 false
198 }
199
200 pub(crate) fn build_queued_message(app: &mut App, input: String) -> QueuedMessage {
201 let skill_instruction = app.active_skill.take();
202 let skill_provenance = app.active_skill_provenance.take();
203 QueuedMessage::new(input, skill_instruction).with_skill_provenance(skill_provenance)
204 }
205
206 pub(crate) fn allowed_tools_for_message(
207 configured: Option<Vec<String>>,
208 message: &QueuedMessage,
209 ) -> Option<Vec<String>> {
210 if message.is_workflow_draft() {
211 // `/workflow <objective>` is review-first. The model may draft and ask
212 // for confirmation, but the host makes execution impossible in the
213 // same turn even if the provider ignores that instruction.
214 Some(Vec::new())
215 } else {
216 configured
217 }
218 }
219
220 pub(crate) async fn submit_initial_input_if_ready(
221 app: &mut App,
222 config: &Config,
223 engine_handle: &EngineHandle,
224 ) -> Result<()> {
225 if app.pending_fresh_session.is_some() {
226 return Ok(());
227 }
228 if !app.auto_submit_initial_input || app.input.trim().is_empty() {
229 app.retire_deferred_prompt_notice();
230 if app.input.trim().is_empty()
231 && app.onboarding == OnboardingState::None
232 && !app.redaction_gate
233 {
234 app.auto_submit_initial_input = false;
235 }
236 return Ok(());
237 }
238
239 if app.onboarding != OnboardingState::None || app.redaction_gate {
240 if app
241 .active_status_toast(crate::tui::underwater::ShellPhase::Typing)
242 .is_none()
243 {
244 app.defer_initial_prompt_notice(INITIAL_PROMPT_DEFERRED_STATUS);
245 }
246 return Ok(());
247 }
248
249 app.auto_submit_initial_input = false;
250 app.retire_deferred_prompt_notice();
251 if let Some(input) = app.submit_input() {
252 let queued = build_queued_message(app, input);
253 dispatch_user_message_with_recovery(
254 app,
255 config,
256 engine_handle,
257 queued,
258 DispatchRecovery::Initial,
259 )
260 .await?;
261 }
262 Ok(())
263 }
264
265 pub(crate) fn message_from_submitted_input(
266 app: &mut App,
267 input: String,
268 ) -> (QueuedMessage, DispatchRecovery) {
269 if let Some(mut draft) = app.queued_draft.take() {
270 app.queued_draft_was_held = false;
271 draft.display = input;
272 (draft, DispatchRecovery::Draft)
273 } else {
274 (
275 build_queued_message(app, input),
276 DispatchRecovery::Immediate,
277 )
278 }
279 }
280
281 pub(crate) fn take_next_queued_message(app: &mut App) -> Option<(QueuedMessage, DispatchRecovery)> {
282 if app.input.is_empty() {
283 let was_held = app.held_restored_queue > 0;
284 return app.take_queued_message_for_dispatch(0).map(|message| {
285 (
286 message,
287 DispatchRecovery::Queued {
288 restore_index: Some(0),
289 was_held,
290 },
291 )
292 });
293 }
294 None
295 }
296
297 pub(crate) async fn send_next_queued_message_now(
298 app: &mut App,
299 config: &Config,
300 engine_handle: &EngineHandle,
301 ) -> Result<bool> {
302 let Some((message, recovery)) = take_next_queued_message(app) else {
303 return Ok(false);
304 };
305 send_taken_queued_message_now(app, config, engine_handle, message, recovery).await?;
306 Ok(true)
307 }
308
309 pub(crate) async fn send_queued_message_at_index_now(
310 app: &mut App,
311 config: &Config,
312 engine_handle: &EngineHandle,
313 index: usize,
314 ) -> Result<bool> {
315 let was_held = index < app.held_restored_queue;
316 let Some(message) = app.take_queued_message_for_dispatch(index) else {
317 app.show_command_result(
318 "Queued message not found".to_string(),
319 StatusToastLevel::Warning,
320 );
321 return Ok(true);
322 };
323 send_taken_queued_message_now(
324 app,
325 config,
326 engine_handle,
327 message,
328 DispatchRecovery::Queued {
329 restore_index: Some(index),
330 was_held,
331 },
332 )
333 .await?;
334 Ok(true)
335 }
336
337 pub(crate) async fn send_taken_queued_message_now(
338 app: &mut App,
339 config: &Config,
340 engine_handle: &EngineHandle,
341 message: QueuedMessage,
342 recovery: DispatchRecovery,
343 ) -> Result<()> {
344 if app.offline_mode {
345 restore_queued_or_draft_message(app, recovery, message);
346 app.show_command_result(
347 app.tr(MessageId::ToastOfflineQueuedCount)
348 .replace("{count}", &app.queued_message_count().to_string()),
349 StatusToastLevel::Warning,
350 );
351 return Ok(());
352 }
353
354 if app.dispatch_in_flight {
355 // A spawned dispatch is still resolving route/sending its op (#4605):
356 // there is no turn to steer into yet. Re-queue; the completion/turn
357 // lifecycle will drive the next drain.
358 restore_queued_or_draft_message(app, recovery, message);
359 app.show_command_result(queued_follow_up_toast(app), StatusToastLevel::Info);
360 return Ok(());
361 }
362 if app.is_loading {
363 attempt_steer_with_queue_fallback(app, config, engine_handle, message, recovery);
364 } else {
365 let _ = dispatch_user_message_with_recovery(app, config, engine_handle, message, recovery)
366 .await;
367 }
368 Ok(())
369 }
370
371 pub(crate) fn validate_extension_command_context(app: &App, message: &QueuedMessage) -> Result<()> {
372 let Some((command, session_id)) = message.extension_command.as_ref() else {
373 return Ok(());
374 };
375 anyhow::ensure!(
376 app.current_session_id.as_deref() == Some(session_id.as_str())
377 && app.workspace == command.workspace,
378 "Plugin command belongs to a different session or workspace"
379 );
380 anyhow::ensure!(
381 !app.offline_mode
382 && app.agent_focus.is_none()
383 && !app.paused
384 && app.paused_goal_objective.is_none()
385 && !app.remote_control.runtime_chat_blocks_local_dispatch(),
386 "Plugin command prompts require the active root session online and unpaused"
387 );
388 codewhale_engine::extension_host::command::validate_selected_registration(command, session_id)
389 .map_err(anyhow::Error::msg)
390 }
391
392 #[cfg(test)]
393 pub(crate) fn queued_message_content_for_app(
394 app: &App,
395 message: &QueuedMessage,
396 cwd: Option<PathBuf>,
397 git_cache: &mut crate::tui::git_mention::GitMentionCache,
398 ) -> Result<String> {
399 if message.extension_command.is_some() {
400 validate_extension_command_context(app, message)?;
401 return Ok(message.display.clone());
402 }
403 MentionContext::capture(app, message, cwd).content(message, git_cache)
404 }
405
406 #[derive(Clone, Debug)]
407 pub(super) struct MentionContext {
408 workspace: PathBuf,
409 cwd: Option<PathBuf>,
410 completion_index: Option<std::sync::Arc<[String]>>,
411 plugins: Option<std::sync::Arc<codewhale_plugins::PluginRegistry>>,
412 }
413
414 impl MentionContext {
415 pub(super) fn capture(app: &App, message: &QueuedMessage, cwd: Option<PathBuf>) -> Self {
416 Self {
417 workspace: app.workspace.clone(),
418 cwd,
419 completion_index: app.composer.mention_discovery.fuzzy_candidates(
420 &app.workspace,
421 &app.composer.mention_cwd,
422 app.mention_walk_depth,
423 app.workspace_follow_symlinks,
424 ),
425 plugins: message
426 .skill_provenance
427 .as_ref()
428 .map(|_| app.extension_plugin_view()),
429 }
430 }
431
432 fn resolve(&self, message: &QueuedMessage) -> Result<(String, Vec<ContextReference>)> {
433 let mut git_cache = crate::tui::git_mention::GitMentionCache::default();
434 let references = crate::tui::file_mention::context_references_from_input_cached(
435 &message.display,
436 &self.workspace,
437 self.cwd.clone(),
438 &mut git_cache,
439 self.completion_index.as_deref(),
440 );
441 Ok((self.content(message, &mut git_cache)?, references))
442 }
443
444 pub(super) fn content(
445 &self,
446 message: &QueuedMessage,
447 git_cache: &mut crate::tui::git_mention::GitMentionCache,
448 ) -> Result<String> {
449 if let Some(provenance) = message.skill_provenance.as_ref() {
450 provenance
451 .verify_for(&self.workspace, self.plugins.as_deref())
452 .map_err(anyhow::Error::msg)?;
453 }
454 // Stabilize macOS screencapture temp references before anything else sees
455 // the text: macOS deletes those Temporary Items dirs minutes after capture.
456 let stabilization_dir =
457 crate::tui::file_mention::screenshot_stabilization_dir(&self.workspace);
458 let display = crate::tui::file_mention::stabilize_screenshot_references(
459 &message.display,
460 &stabilization_dir,
461 );
462 let user_request = crate::tui::file_mention::user_request_with_file_mentions_cached(
463 &display,
464 &self.workspace,
465 self.cwd.clone(),
466 git_cache,
467 self.completion_index.as_deref(),
468 );
469 if let Some(skill_instruction) = message.skill_instruction.as_ref() {
470 Ok(format!(
471 "{skill_instruction}\n\n---\n\nUser request: {user_request}"
472 ))
473 } else {
474 Ok(user_request)
475 }
476 }
477 }
478
479 pub(crate) fn dispatch_completion_permit(
480 app: &App,
481 ) -> std::result::Result<
482 tokio::sync::mpsc::OwnedPermit<crate::tui::app::DispatchApplyFn>,
483 &'static str,
484 > {
485 let sender = app
486 .dispatch_completion_tx
487 .clone()
488 .ok_or("dispatch completion mailbox is unavailable")?;
489 sender.try_reserve_owned().map_err(|error| match error {
490 tokio::sync::mpsc::error::TrySendError::Full(_) => "dispatch completion mailbox is full",
491 tokio::sync::mpsc::error::TrySendError::Closed(_) => {
492 "dispatch completion mailbox is closed"
493 }
494 })
495 }
496
497 #[cfg(test)]
498 pub(crate) async fn dispatch_user_message(
499 app: &mut App,
500 config: &Config,
501 engine_handle: &EngineHandle,
502 message: QueuedMessage,
503 ) -> Result<()> {
504 dispatch_user_message_with_recovery(
505 app,
506 config,
507 engine_handle,
508 message,
509 DispatchRecovery::Immediate,
510 )
511 .await
512 }
513
514 pub(crate) async fn dispatch_user_message_with_recovery(
515 app: &mut App,
516 config: &Config,
517 engine_handle: &EngineHandle,
518 mut message: QueuedMessage,
519 recovery: DispatchRecovery,
520 ) -> Result<()> {
521 if app.pending_fresh_session.is_some() {
522 restore_queued_or_draft_message(app, recovery, message);
523 app.show_command_result(
524 "A new session is awaiting Engine confirmation; sending is paused.".to_string(),
525 StatusToastLevel::Warning,
526 );
527 return Ok(());
528 }
529 if message.extension_command.is_some() {
530 let admitted = validate_extension_command_context(app, &message).and_then(|()| {
531 anyhow::ensure!(
532 !app.is_loading
533 && !app.dispatch_in_flight
534 && !app.suppress_stream_events_until_turn_complete,
535 "Plugin command prompts require an idle session"
536 );
537 Ok(())
538 });
539 if let Err(error) = admitted {
540 app.restore_unsent_message(message);
541 app.show_command_result(error.to_string(), StatusToastLevel::Error);
542 return Err(error);
543 }
544 }
545 if app.redaction_gate {
546 recover_unstarted_external_message(app, message, recovery, INITIAL_PROMPT_DEFERRED_STATUS);
547 return Ok(());
548 }
549 let stop_words = config.stop_words();
550 if message.extension_command.is_none() && is_stop_word(&message.display, &stop_words).is_some()
551 {
552 if !crate::tui::external_agent::interrupt_external_turn(app) {
553 engine_handle.cancel();
554 }
555 app.stopped_turn = true;
556 app.show_command_result(
557 "Turn stopped. Tool calls blocked for this turn.".to_string(),
558 StatusToastLevel::Warning,
559 );
560 return Ok(());
561 }
562 app.stopped_turn = false;
563 if app.external_agent.is_some() {
564 if let Err(error) = crate::tui::external_agent::dispatch_external_turn(app, message.clone())
565 {
566 recover_unstarted_external_message(app, message, recovery, &error.to_string());
567 return Err(error);
568 }
569 return Ok(());
570 }
571
572 // #1364: run mutable `message_submit` hooks before dispatch. Hooks see the
573 // user's display text and may replace or block it before file mentions,
574 // skill wrapping, history, and model input are resolved.
575 // Fast-path skip when no hooks configured.
576 if app
577 .hooks
578 .has_hooks_for_event(codewhale_config::hooks::HookEvent::MessageSubmit)
579 {
580 let context = app.base_hook_context().with_message(&message.display);
581 let strict_gates = app.hooks.matched_strict_gate_labels(
582 codewhale_config::hooks::HookEvent::MessageSubmit,
583 &context,
584 );
585 let hooks = app.hooks.clone();
586 let original_text = message.display.clone();
587
588 if app.dispatch_completion_tx.is_some() {
589 // The foreground transform is a gate, but its child wait belongs
590 // on the blocking pool, never on the terminal event loop. Result
591 // delivery reserves bounded mailbox capacity before any work or
592 // state mutation, so the recovery closure cannot be dropped.
593 let completion_permit = match dispatch_completion_permit(app) {
594 Ok(permit) => permit,
595 Err(error) => {
596 recover_unstarted_external_message(app, message, recovery, error);
597 return Err(anyhow::Error::msg(error));
598 }
599 };
600 app.dispatch_in_flight = true;
601 tokio::spawn(async move {
602 let outcome = match tokio::task::spawn_blocking(move || {
603 hooks.execute_message_submit_transform_for_dispatch(&context, &original_text)
604 })
605 .await
606 {
607 Ok(outcome) => outcome,
608 Err(error) => {
609 tracing::error!(target: "hooks", %error, "message_submit executor task was lost");
610 lost_message_submit_outcome(&strict_gates)
611 }
612 };
613 let apply: crate::tui::app::DispatchApplyFn = Box::new(
614 move |app: &mut App,
615 engine_handle: &EngineHandle,
616 config: &Config|
617 -> anyhow::Result<()> {
618 if let Err(denial) =
619 apply_message_submit_outcome(app, &mut message, outcome)
620 {
621 app.dispatch_in_flight = false;
622 restore_message_submit_denial(app, message, recovery, denial);
623 return Ok(());
624 }
625 let _ = start_user_dispatch(app, config, engine_handle, message, recovery);
626 Ok(())
627 },
628 );
629 completion_permit.send(apply);
630 });
631 return Ok(());
632 }
633
634 // Unit tests intentionally omit the event-loop completion channel.
635 // Keep those synchronous from the test's perspective while still
636 // running the blocking child wait off the async runtime worker.
637 let outcome = match tokio::task::spawn_blocking(move || {
638 hooks.execute_message_submit_transform_for_dispatch(&context, &original_text)
639 })
640 .await
641 {
642 Ok(outcome) => outcome,
643 Err(error) => {
644 tracing::error!(target: "hooks", %error, "message_submit executor task was lost");
645 lost_message_submit_outcome(&strict_gates)
646 }
647 };
648 if let Err(denial) = apply_message_submit_outcome(app, &mut message, outcome) {
649 restore_message_submit_denial(app, message, recovery, denial);
650 return Ok(());
651 }
652 }
653
654 if app.dispatch_completion_tx.is_some() {
655 return start_user_dispatch(app, config, engine_handle, message, recovery);
656 }
657
658 let prepare = match prepare_user_dispatch(app, config, message.clone()) {
659 Ok(prepare) => prepare,
660 Err(error) => {
661 recover_unstarted_external_message(app, message, recovery, &error.to_string());
662 return Err(error);
663 }
664 };
665 run_prepared_dispatch(app, config, engine_handle, prepare, recovery).await
666 }
667
668 pub(crate) fn lost_message_submit_outcome(
669 strict_gates: &[String],
670 ) -> codewhale_engine::hooks::MessageSubmitOutcome {
671 if strict_gates.is_empty() {
672 codewhale_engine::hooks::MessageSubmitOutcome::Unchanged {
673 warning: Some(
674 "message_submit hook executor did not run; submission continued because no strict gate matched"
675 .to_string(),
676 ),
677 }
678 } else {
679 codewhale_engine::hooks::MessageSubmitOutcome::Blocked {
680 reason: "message_submit hook executor did not run; a strict gate blocked submission"
681 .to_string(),
682 }
683 }
684 }
685
686 pub(crate) fn prepare_user_dispatch(
687 app: &mut App,
688 config: &Config,
689 message: QueuedMessage,
690 ) -> Result<UserDispatchPrepare> {
691 anyhow::ensure!(!app.redaction_gate, "{INITIAL_PROMPT_DEFERRED_STATUS}");
692 let _ = app.maybe_nudge_plugin_for_prompt(&message.display);
693
694 // Plan paused-command changes without touching App or the engine pause
695 // gate. Route selection can await and client preflight can fail; neither
696 // may resume or discard a paused command unless a turn is ready to send.
697 let extension_command = message.extension_command.is_some();
698 if extension_command {
699 validate_extension_command_context(app, &message)?;
700 anyhow::ensure!(
701 !app.is_loading && !app.suppress_stream_events_until_turn_complete,
702 "Plugin command prompts require an idle session"
703 );
704 }
705 let paused_dispatch = if extension_command {
706 PausedCommandDispatch::None
707 } else {
708 plan_paused_command_message(app, &message.display)
709 };
710
711 let mention_context = (!extension_command)
712 .then(|| MentionContext::capture(app, &message, std::env::current_dir().ok()));
713 let (app_route_identity, route_config) =
714 app_scoped_runtime_config(app, config).map_err(anyhow::Error::msg)?;
715
716 let should_auto_resolve = auto_router::should_resolve_auto_model_selection(app);
717 let auto_router_context = auto_router::recent_auto_router_context(&app.api_messages);
718
719 // Capture the App state before any optimistic mutation so a failure can
720 // roll back cleanly.
721 let snapshot = UserDispatchSnapshot {
722 session_write_owner: app.session_write_owner.clone(),
723 is_loading: app.is_loading,
724 suppress_stream_events_until_turn_complete: app.suppress_stream_events_until_turn_complete,
725 runtime_turn_status: app.runtime_turn_status.clone(),
726 receipt_text: app.receipt_text.clone(),
727 receipt_started_at: app.receipt_started_at,
728 tool_evidence: app.tool_evidence.clone(),
729 history_len: app.history.len(),
730 history_revisions_len: app.history_revisions.len(),
731 last_send_at: app.last_send_at,
732 active_turn_user_index: app.active_turn_user_index,
733 };
734
735 // --- Sync prepare: show the user message and spinner immediately so the
736 // event loop can repaint before network I/O (#4605). The async phase runs
737 // the auto-model route, compaction, and engine send off the render thread.
738 app.is_loading = true;
739 app.runtime_turn_status = None;
740 app.clear_receipt();
741 app.tool_evidence.clear();
742 app.needs_redraw = true;
743
744 // Already painted at Queue time — reuse that cell for reference
745 // recording instead of duplicating the bubble.
746 let history_cell = paint_user_turn_cell(app, &message, message.display.clone());
747 app.active_turn_user_index = (!extension_command).then_some(history_cell);
748 app.scroll_to_bottom();
749 // Anchor the tail-flash to the moment the user message appears, not to
750 // the async dispatch completion (which can lag by a route plan). The
751 // failure path restores the pre-send timestamp from the snapshot.
752 app.last_send_at = Some(Instant::now());
753 let goal_objective = if extension_command {
754 app.goal.objective.clone()
755 } else {
756 paused_dispatch.goal_objective(app)
757 };
758 let allowed_tools = allowed_tools_for_message(app.active_allowed_tools.clone(), &message);
759
760 let accounting_origin = app.session_write_receipt.as_ref().and_then(|source| {
761 match source.usage_origin(codewhale_engine::cost_status::scope_token()) {
762 Ok(origin) => Some(origin),
763 Err(error) => {
764 tracing::warn!(%error, "auto routing session accounting origin unavailable; continuing with unknown cost");
765 None
766 }
767 }
768 });
769 let input_authorship = if extension_command {
770 codewhale_engine::core::ops::TurnInputAuthorship::NotPerson
771 } else if let Some(plan) = message.approved_plan.as_ref() {
772 codewhale_engine::core::ops::TurnInputAuthorship::ApprovedPlan(plan.clone())
773 } else if message.owner_input {
774 codewhale_engine::core::ops::TurnInputAuthorship::Person(message.display.clone())
775 } else {
776 codewhale_engine::core::ops::TurnInputAuthorship::NotPerson
777 };
778 Ok(UserDispatchPrepare {
779 submission_id: uuid::Uuid::new_v4().to_string(),
780 content: message.display.clone(),
781 message,
782 mention_context,
783 references: Vec::new(),
784 paused_dispatch,
785 app_route_identity,
786 route_config,
787 goal_objective,
788 goal_status: app.goal.status,
789 goal_token_budget: app.goal.token_budget,
790 mode: app.mode,
791 api_provider: app.api_provider,
792 app_model: app.model.clone(),
793 auto_model: app.auto_model,
794 reasoning_effort: app.reasoning_effort,
795 allow_shell: app.allow_shell,
796 trust_mode: app.trust_mode,
797 auto_approve: app_auto_approve_enabled(app),
798 approval_mode: app.approval_mode,
799 translation_enabled: app.translation_enabled,
800 allowed_tools,
801 hook_executor: app.runtime_services.hook_executor.clone(),
802 verbosity: app.verbosity.clone(),
803 provenance: if extension_command {
804 UserInputProvenance::Runtime
805 } else {
806 UserInputProvenance::ExternalUser
807 },
808 input_authorship,
809 auto_router_context,
810 should_auto_resolve,
811 auto_compact_user_configured: app.auto_compact_user_configured,
812 auto_compact: app.auto_compact,
813 auto_compact_threshold_percent: app.auto_compact_threshold_percent,
814 snapshot,
815 cost_scope: codewhale_engine::cost_status::scope_token(),
816 accounting_origin,
817 history_cell,
818 })
819 }
820
821 impl UserDispatchPrepare {
822 pub(super) async fn resolve_mentions(&mut self) -> Result<()> {
823 if let Some(context) = self.mention_context.take() {
824 let message = self.message.clone();
825 let (mut content, references) =
826 tokio::task::spawn_blocking(move || context.resolve(&message)).await??;
827 if let Some(note) = self.paused_dispatch.note() {
828 content.push_str(note);
829 }
830 self.content = content;
831 self.references = references;
832 }
833 Ok(())
834 }
835 }
836
837 pub(crate) fn start_user_dispatch(
838 app: &mut App,
839 config: &Config,
840 engine_handle: &EngineHandle,
841 message: QueuedMessage,
842 recovery: DispatchRecovery,
843 ) -> Result<()> {
844 let completion_permit = match dispatch_completion_permit(app) {
845 Ok(permit) => permit,
846 Err(error) => {
847 recover_unstarted_external_message(app, message, recovery, error);
848 return Err(anyhow::Error::msg(error));
849 }
850 };
851 let recovery_message = message.clone();
852 let prepare = match prepare_user_dispatch(app, config, message) {
853 Ok(prepare) => prepare,
854 Err(error) => {
855 recover_unstarted_external_message(app, recovery_message, recovery, &error.to_string());
856 return Err(error);
857 }
858 };
859 app.dispatch_in_flight = true;
860 // #6800: a local cancel (Esc, stall recovery) trips this token so the
861 // dispatch fails back to the composer at once instead of holding
862 // `dispatch_in_flight` — and queueing every new send — for the full
863 // `DISPATCH_TASK_BOUND` while it waits on engine admission.
864 let cancel = tokio_util::sync::CancellationToken::new();
865 app.dispatch_cancel = Some(cancel.clone());
866 // Supervised: `spawned_dispatch_execute` owns the whole dispatch future,
867 // so its completion callback always arrives — on success, on a panic, on
868 // a local cancel, or when the dispatch exceeds its bound (#6184).
869 tokio::spawn(spawned_dispatch_execute(
870 prepare,
871 recovery,
872 engine_handle.clone(),
873 completion_permit,
874 cancel,
875 ));
876 Ok(())
877 }
878
879 /// Longest a dispatch may spend routing and waiting for engine admission
880 /// before it is failed back to the composer (#6184). An engine whose op
881 /// mailbox never frees (a wedged turn) used to hold the dispatch — and the
882 /// user's message — forever.
883 pub(crate) const DISPATCH_TASK_BOUND: std::time::Duration = std::time::Duration::from_secs(60);
884
885 pub(crate) async fn spawned_dispatch_execute(
886 prepare: UserDispatchPrepare,
887 recovery: DispatchRecovery,
888 engine_handle: EngineHandle,
889 completion_permit: tokio::sync::mpsc::OwnedPermit<crate::tui::app::DispatchApplyFn>,
890 cancel: tokio_util::sync::CancellationToken,
891 ) {
892 let apply = supervised_dispatch(
893 prepare,
894 recovery,
895 DISPATCH_TASK_BOUND,
896 cancel,
897 |prepare, recovery| spawned_dispatch_inner(prepare, recovery, engine_handle),
898 )
899 .await;
900 completion_permit.send(apply);
901 }
902
903 /// Run one dispatch future under supervision. A dropped JoinHandle used to
904 /// turn a panic or a hang into a dispatch that never reported back: the
905 /// completion permit was dropped, `dispatch_in_flight` stayed set and the
906 /// message sat in limbo. Every outcome now yields a callback; a panic or an
907 /// overrun also leaves a log line and a `crashes/` record. A tripped `cancel`
908 /// token abandons the dispatch and fails it back through the same error
909 /// closure, so the unsent message returns to the composer exactly as on any
910 /// other dispatch failure (#6800).
911 pub(crate) async fn supervised_dispatch<F, Fut>(
912 prepare: UserDispatchPrepare,
913 recovery: DispatchRecovery,
914 bound: std::time::Duration,
915 cancel: tokio_util::sync::CancellationToken,
916 run: F,
917 ) -> crate::tui::app::DispatchApplyFn
918 where
919 F: FnOnce(UserDispatchPrepare, DispatchRecovery) -> Fut,
920 Fut: std::future::Future<Output = crate::tui::app::DispatchApplyFn>,
921 {
922 use futures_util::FutureExt as _;
923 let fallback = prepare.clone();
924 let started = std::time::Instant::now();
925 let supervised = std::panic::AssertUnwindSafe(run(prepare, recovery)).catch_unwind();
926 let outcome = tokio::select! {
927 biased;
928 () = cancel.cancelled() => {
929 return build_dispatch_error_closure(
930 fallback,
931 recovery,
932 "Message dispatch was cancelled before it reached the engine".to_string(),
933 );
934 }
935 outcome = tokio::time::timeout(bound, supervised) => outcome,
936 };
937 match outcome {
938 Ok(Ok(apply)) => apply,
939 Ok(Err(panic)) => {
940 let detail = codewhale_util::utils::panic_message(&*panic);
941 codewhale_util::utils::record_caught_panic("user-dispatch", &detail);
942 build_dispatch_error_closure(
943 fallback,
944 recovery,
945 format!("Message dispatch hit an internal error: {detail}"),
946 )
947 }
948 Err(_elapsed) => {
949 codewhale_runtime::stall_report::report_stall(
950 &codewhale_runtime::stall_report::StallReport {
951 source: "ui",
952 phase: "while dispatching the message (route planning / engine admission)"
953 .to_string(),
954 detail: Some(format!(
955 "{} / {}",
956 fallback
957 .app_route_identity
958 .compatibility()
959 .map_or(fallback.app_route_identity.key.as_str(), |row| row.label),
960 fallback.app_model
961 )),
962 turn_id: None,
963 provider_request: None,
964 since_progress: started.elapsed(),
965 bound: Some(bound),
966 },
967 );
968 build_dispatch_error_closure(
969 fallback,
970 recovery,
971 format!(
972 "Message dispatch stalled for {}s before the engine accepted it; your message was restored. Press Esc to cancel the running turn, then retry.",
973 bound.as_secs()
974 ),
975 )
976 }
977 }
978 }
979
980 /// Keep classifier receipts owned until the UI admits the operation to Engine.
981 /// Dropping a reserved dispatch (including a closed completion mailbox) must
982 /// settle its already-incurred usage in the original session scope.
983 pub(super) struct UnacceptedDispatchUsage {
984 pub(super) scope: codewhale_engine::cost_status::CostScopeToken,
985 pub(super) batch: Option<codewhale_engine::cost_status::RuntimeUsageBatch>,
986 }
987
988 impl Drop for UnacceptedDispatchUsage {
989 fn drop(&mut self) {
990 if let Some(batch) = self.batch.as_ref() {
991 codewhale_engine::cost_status::record_runtime_usage_batch(self.scope, None, batch);
992 }
993 }
994 }
995
996 pub(crate) async fn spawned_dispatch_inner(
997 mut prepare: UserDispatchPrepare,
998 recovery: DispatchRecovery,
999 engine_handle: EngineHandle,
1000 ) -> crate::tui::app::DispatchApplyFn {
1001 if let Err(error) = prepare.resolve_mentions().await {
1002 return build_dispatch_error_closure(prepare, recovery, error.to_string());
1003 }
1004 if let Some((command, session_id)) = prepare.message.extension_command.as_ref()
1005 && let Err(error) =
1006 codewhale_engine::extension_host::command::validate_reference(command, session_id).await
1007 {
1008 return build_dispatch_error_closure(prepare, recovery, error);
1009 }
1010 if !prepare.auto_model {
1011 codewhale_engine::provider_lake::refresh_unverified_local_context(
1012 &prepare.route_config,
1013 &prepare.app_route_identity,
1014 &prepare.app_model,
1015 )
1016 .await;
1017 }
1018 // Bound in its own statement: the planner borrows `prepare`, and the error
1019 // arm moves it into the failure closure.
1020 let plan_result = plan_turn_route(TurnRoutePlanRequest {
1021 accounting_origin: prepare.accounting_origin.clone(),
1022 route_config: &prepare.route_config,
1023 app_route_identity: &prepare.app_route_identity,
1024 api_provider: prepare.api_provider,
1025 app_model: &prepare.app_model,
1026 auto_model: prepare.auto_model,
1027 reasoning_effort: prepare.reasoning_effort,
1028 mode: prepare.mode,
1029 content: &prepare.content,
1030 auto_router_context: &prepare.auto_router_context,
1031 should_auto_resolve: prepare.should_auto_resolve,
1032 allow_auto_router_response_cache: true,
1033 preflight_required: engine_handle.client_preflight_required(),
1034 auto_compact_user_configured: prepare.auto_compact_user_configured,
1035 auto_compact: prepare.auto_compact,
1036 auto_compact_threshold_percent: prepare.auto_compact_threshold_percent,
1037 })
1038 .await;
1039 let planned = match plan_result {
1040 Ok(planned) => planned,
1041 Err(err) => return build_dispatch_error_closure(prepare, recovery, err),
1042 };
1043
1044 let PlannedTurnRoute {
1045 route: turn_route,
1046 compaction: turn_compaction,
1047 effective_provider,
1048 effective_model,
1049 effective_provider_identity,
1050 effective_provider_label,
1051 selected_reasoning_effort,
1052 effective_reasoning_effort,
1053 auto_controls_reasoning,
1054 auto_selection,
1055 initial_routed_usage,
1056 routing_source: _,
1057 } = planned;
1058 let effective_reasoning_tier = selected_reasoning_effort
1059 .unwrap_or(prepare.reasoning_effort)
1060 .normalize_for_route(
1061 effective_provider,
1062 &turn_route.candidate.endpoint().base_url,
1063 &turn_route.model,
1064 );
1065 let effective_reasoning_receipt = reasoning_effort_receipt_for_route(
1066 effective_reasoning_tier,
1067 effective_provider,
1068 &turn_route.candidate.endpoint().base_url,
1069 &turn_route.model,
1070 );
1071
1072 let mut usage = UnacceptedDispatchUsage {
1073 scope: prepare.cost_scope,
1074 batch: Some(initial_routed_usage.clone()),
1075 };
1076 let route_limits = turn_route.candidate.limits();
1077 let context_window = turn_route.context_window;
1078 let op = Op::SendMessage(TurnSpec {
1079 profile_constitution: None,
1080 max_output_tokens: None,
1081 content: prepare.content.clone(),
1082 images: Vec::new(),
1083 mode: prepare.mode,
1084 route: Box::new(turn_route),
1085 compaction: Box::new(turn_compaction.clone()),
1086 initial_routed_usage: Box::new(initial_routed_usage),
1087 goal_objective: prepare.goal_objective.clone(),
1088 goal_token_budget: prepare.goal_token_budget,
1089 goal_status: prepare.goal_status,
1090 reasoning_effort: effective_reasoning_effort,
1091 reasoning_effort_auto: auto_controls_reasoning,
1092 auto_model: prepare.auto_model,
1093 allow_shell: prepare.allow_shell,
1094 trust_mode: prepare.trust_mode,
1095 auto_approve: prepare.auto_approve,
1096 approval_mode: prepare.approval_mode,
1097 translation_enabled: prepare.translation_enabled,
1098 allowed_tools: prepare.allowed_tools.clone(),
1099 dynamic_tools: Vec::new(),
1100 hook_executor: prepare.hook_executor.clone(),
1101 verbosity: prepare.verbosity.clone(),
1102 provenance: prepare.provenance,
1103 input_authorship: prepare.input_authorship.clone(),
1104 submission_id: Some(prepare.submission_id.clone()),
1105 });
1106 // Reserve capacity off the render thread, but do not let Engine start
1107 // until the completion callback has installed the UI's acceptance state.
1108 // Separate completion/event mailboxes otherwise allow TurnStarted (or
1109 // TurnComplete) to arrive before a callback that resets those newer facts.
1110 let permit = match engine_handle.tx_op.clone().reserve_owned().await {
1111 Ok(permit) => permit,
1112 Err(err) => return build_dispatch_error_closure(prepare, recovery, err.to_string()),
1113 };
1114 let outcome = UserDispatchOutcome {
1115 turn_compaction,
1116 effective_provider,
1117 effective_model,
1118 effective_provider_identity,
1119 effective_provider_label,
1120 effective_reasoning_effort: effective_reasoning_receipt,
1121 auto_selection,
1122 route_limits,
1123 context_window,
1124 };
1125 Box::new(move |app, current_engine, config| {
1126 // Admission stays serialized by this flag until its callback retires,
1127 // even if the user replaced the Engine/session while routing waited.
1128 app.dispatch_in_flight = false;
1129 // This request has no admitted Op and cannot emit TurnComplete. Retire
1130 // its local cancellation even after replacement, but leave a previous
1131 // admitted turn's suppression for that turn's terminal event to retire.
1132 if !prepare.snapshot.suppress_stream_events_until_turn_complete {
1133 app.suppress_stream_events_until_turn_complete = false;
1134 }
1135 if !engine_handle.tx_op.same_channel(&current_engine.tx_op)
1136 || prepare.cost_scope != codewhale_engine::cost_status::scope_token()
1137 {
1138 anyhow::bail!("Message dispatch belongs to a previous engine or session");
1139 }
1140 if !app.is_loading || engine_handle.tx_op.is_closed() {
1141 let error = if engine_handle.tx_op.is_closed() {
1142 "Engine stopped before accepting the message"
1143 } else {
1144 "Message dispatch was cancelled before it reached the engine"
1145 };
1146 return build_dispatch_error_closure(prepare, recovery, error.to_string())(
1147 app,
1148 &engine_handle,
1149 config,
1150 );
1151 }
1152 if let Err(error) = validate_extension_command_context(app, &prepare.message) {
1153 return build_dispatch_error_closure(prepare, recovery, error.to_string())(
1154 app,
1155 &engine_handle,
1156 config,
1157 );
1158 }
1159 build_dispatch_success_closure(prepare, outcome, recovery)(app, &engine_handle, config)?;
1160 // Existing Engine admission binds cancellation controls and the Op in
1161 // one FIFO. No await separates the UI checkpoint from this handoff.
1162 engine_handle.send_reserved_op(permit, op);
1163 drop(usage.batch.take());
1164 Ok(())
1165 })
1166 }
1167
1168 pub(crate) fn build_dispatch_success_closure(
1169 prepare: UserDispatchPrepare,
1170 outcome: UserDispatchOutcome,
1171 recovery: DispatchRecovery,
1172 ) -> crate::tui::app::DispatchApplyFn {
1173 Box::new(
1174 move |app: &mut App, engine_handle: &EngineHandle, config: &Config| -> anyhow::Result<()> {
1175 app.dispatch_in_flight = false;
1176 prepare.paused_dispatch.apply(app, engine_handle);
1177 app.session_write_owner = Some(
1178 codewhale_engine::session_manager::SessionWriteOwner::Submission(
1179 prepare.submission_id.clone(),
1180 ),
1181 );
1182
1183 let dispatch_started_at = Instant::now();
1184 app.is_loading = true;
1185 app.dispatch_started_at = Some(dispatch_started_at);
1186 app.runtime_turn_status = None;
1187 // last_send_at was already anchored in the sync prepare phase so
1188 // the tail-flash starts together with the visible user cell.
1189 app.last_submitted_prompt = prepare
1190 .message
1191 .extension_command
1192 .is_none()
1193 .then(|| prepare.message.display.clone());
1194 app.unanswered_submission = Some(crate::tui::app::UnansweredSubmission {
1195 message: prepare.message.clone(),
1196 history_cell: prepare.history_cell,
1197 });
1198 app.clear_receipt();
1199 app.tool_evidence.clear();
1200
1201 if prepare.auto_model {
1202 app.last_effective_model = Some(outcome.effective_model.clone());
1203 app.last_effective_provider = Some(outcome.effective_provider);
1204 app.last_effective_provider_identity =
1205 Some(outcome.effective_provider_identity.clone());
1206 app.last_effective_budget = Some(crate::tui::app::AutoRouteBudget {
1207 provider: outcome.effective_provider,
1208 provider_identity: outcome.effective_provider_identity.clone(),
1209 model: outcome.effective_model.clone(),
1210 limits: codewhale_engine::route_budget::known_route_limits(
1211 outcome.route_limits,
1212 ),
1213 window: outcome.context_window,
1214 restored: false,
1215 });
1216 } else {
1217 app.set_active_route_limits(outcome.route_limits);
1218 app.active_context_window = Some(outcome.context_window);
1219 app.active_context_window_source = outcome.context_window.source;
1220 }
1221 app.update_model_compaction_budget();
1222
1223 app.system_prompt = Some(build_app_system_prompt_with_goal(
1224 app,
1225 config,
1226 app.goal.objective.as_deref(),
1227 ));
1228 let message_index = app.api_messages.len();
1229 if prepare.message.extension_command.is_none() {
1230 app.push_api_message(Message {
1231 role: Role::User,
1232 content: vec![ContentBlock::Text {
1233 text: prepare.content,
1234 cache_control: None,
1235 }],
1236 });
1237 }
1238 app.record_context_references(prepare.history_cell, message_index, prepare.references);
1239 app.scroll_to_bottom();
1240
1241 app.last_effective_reasoning_effort = Some(outcome.effective_reasoning_effort);
1242 if prepare.auto_model {
1243 if let Some(selection) = outcome.auto_selection.as_ref() {
1244 app.last_auto_route_receipt = selection.receipt.clone();
1245 let status = app
1246 .tr(MessageId::AutoRouteSelectedToast)
1247 .replace("{provider}", &outcome.effective_provider_label)
1248 .replace("{model}", &outcome.effective_model)
1249 .replace("{source}", selection.source.label());
1250 app.push_status_toast(status, StatusToastLevel::Info, Some(6_000));
1251 }
1252 } else {
1253 app.last_effective_model = None;
1254 app.last_effective_provider = None;
1255 app.last_effective_provider_identity = None;
1256 app.last_auto_route_receipt = None;
1257 }
1258 app.pending_auto_route_receipt = outcome
1259 .auto_selection
1260 .as_ref()
1261 .and_then(|selection| selection.receipt.clone());
1262 app.pending_turn_route = Some((
1263 outcome.effective_provider,
1264 outcome.effective_model,
1265 prepare.auto_model,
1266 ));
1267
1268 app.session.last_prompt_tokens = None;
1269 app.session.last_completion_tokens = None;
1270 app.session.last_prompt_cache_hit_tokens = None;
1271 app.session.last_prompt_cache_miss_tokens = None;
1272 app.session.last_reasoning_replay_tokens = None;
1273 maybe_warn_context_pressure_for_config(app, &outcome.turn_compaction);
1274 if let Some(message) = codewhale_plugins::plugin_reload_nudge(
1275 app.plugin_registry.as_ref(),
1276 &mut app.plugin_reload_nudge_stamp,
1277 ) {
1278 app.push_status_toast(message, StatusToastLevel::Warning, Some(8_000));
1279 }
1280
1281 if matches!(
1282 recovery,
1283 DispatchRecovery::Queued { .. } | DispatchRecovery::Draft
1284 ) {
1285 app.show_command_result(
1286 app.tr(MessageId::ToastSentIntoTurn).into_owned(),
1287 StatusToastLevel::Success,
1288 );
1289 }
1290 if let Ok(manager) = SessionManager::default_location()
1291 && let Ok(session) = build_session_snapshot(app, &manager)
1292 {
1293 let projection = saved_work_projection(app, &session);
1294 if app.current_session_id.is_none() {
1295 app.current_session_id = Some(session.metadata.id.clone());
1296 }
1297 if let Err(err) = persist_with_pending_work_boundary(
1298 app,
1299 PersistRequest::SaveCheckpoint { session },
1300 &projection,
1301 ) {
1302 app.show_command_result(
1303 format!("To-do list update pending while saving turn checkpoint ({err})"),
1304 StatusToastLevel::Warning,
1305 );
1306 }
1307 }
1308
1309 Ok(())
1310 },
1311 )
1312 }
1313
1314 /// Missing-credential / auth preflight failures. The message never reached a
1315 /// model, so it returns to the composer with a transcript line saying why
1316 /// (`keep_unsent_message_for_connect`) rather than as an echo that has to be
1317 /// typed again — which lost the text and then showed it twice (#6566).
1318 pub(crate) fn is_missing_credential_dispatch_error(error: &str) -> bool {
1319 let lower = error.to_ascii_lowercase();
1320 lower.contains("api key not found")
1321 || lower.contains("access token")
1322 || (lower.contains("credential")
1323 && (lower.contains("not found")
1324 || lower.contains("missing")
1325 || lower.contains("unavailable")
1326 || lower.contains("unsupported")))
1327 }
1328
1329 pub(crate) fn build_dispatch_error_closure(
1330 prepare: UserDispatchPrepare,
1331 recovery: DispatchRecovery,
1332 error: String,
1333 ) -> crate::tui::app::DispatchApplyFn {
1334 Box::new(
1335 move |app: &mut App,
1336 _engine_handle: &EngineHandle,
1337 _config: &Config|
1338 -> anyhow::Result<()> {
1339 app.dispatch_in_flight = false;
1340 // No operation was admitted, including route/reservation failures:
1341 // retire only cancellation introduced by this dispatch. A previous
1342 // admitted turn may still need to suppress its queued events.
1343 if !prepare.snapshot.suppress_stream_events_until_turn_complete {
1344 app.suppress_stream_events_until_turn_complete = false;
1345 }
1346 if prepare.cost_scope != codewhale_engine::cost_status::scope_token() {
1347 anyhow::bail!("Message dispatch belongs to a previous session");
1348 }
1349 app.remote_control.fail_active_dispatch(&error);
1350 // Roll back the optimistic sync prepare mutations.
1351 app.session_write_owner = prepare.snapshot.session_write_owner.clone();
1352 app.is_loading = prepare.snapshot.is_loading;
1353 app.runtime_turn_status = prepare.snapshot.runtime_turn_status.clone();
1354 app.receipt_text = prepare.snapshot.receipt_text.clone();
1355 app.receipt_started_at = prepare.snapshot.receipt_started_at;
1356 app.tool_evidence = prepare.snapshot.tool_evidence.clone();
1357 let missing_credential = is_missing_credential_dispatch_error(&error);
1358 // Nothing was sent, so the optimistic echo goes too. A message
1359 // that is not in the transcript can be sent again without
1360 // appearing twice (#6566).
1361 app.history.truncate(prepare.snapshot.history_len);
1362 app.prune_transcript_index_state(prepare.snapshot.history_len);
1363 app.history_revisions
1364 .truncate(prepare.snapshot.history_revisions_len);
1365 // Never rewind the version: a cache keyed by (version, len) that
1366 // saw the rolled-back echo would match a different cell that
1367 // later lands at the same version and length.
1368 app.history_version = app.history_version.wrapping_add(1);
1369 app.last_send_at = prepare.snapshot.last_send_at;
1370 app.active_turn_user_index = prepare.snapshot.active_turn_user_index;
1371 app.needs_redraw = true;
1372
1373 match recovery {
1374 DispatchRecovery::Immediate => {
1375 if missing_credential {
1376 keep_unsent_message_for_connect(app, prepare.message, &error);
1377 } else {
1378 restore_failed_immediate_submit(
1379 app,
1380 prepare.message,
1381 &anyhow::Error::msg(error.clone()),
1382 );
1383 }
1384 }
1385 DispatchRecovery::Queued {
1386 restore_index,
1387 was_held,
1388 } => {
1389 restore_queued_message(app, restore_index, was_held, prepare.message);
1390 app.show_command_result(
1391 app.tr(MessageId::DispatchFailedQueued)
1392 .replace("{error}", &error)
1393 .replace("{count}", &app.queued_message_count().to_string()),
1394 StatusToastLevel::Error,
1395 );
1396 }
1397 DispatchRecovery::Draft => {
1398 restore_queued_or_draft_message(app, DispatchRecovery::Draft, prepare.message);
1399 app.show_command_result(
1400 format!("Message dispatch failed ({error}); queued draft restored"),
1401 StatusToastLevel::Error,
1402 );
1403 }
1404 DispatchRecovery::Initial => {
1405 if missing_credential {
1406 keep_unsent_message_for_connect(app, prepare.message, &error);
1407 } else {
1408 let initial_error = app
1409 .tr(MessageId::DispatchFailedInitial)
1410 .replace("{error}", &error);
1411 restore_failed_immediate_submit(
1412 app,
1413 prepare.message,
1414 &anyhow::Error::msg(initial_error),
1415 );
1416 }
1417 }
1418 }
1419
1420 Err(anyhow::Error::msg(error))
1421 },
1422 )
1423 }
1424
1425 pub(crate) fn parse_queue_send_command(input: &str) -> Option<Result<usize, String>> {
1426 let rest = strip_queue_command_prefix(input.trim())?;
1427 let mut parts = rest.split_whitespace();
1428 let action = parts.next()?;
1429 if !action.eq_ignore_ascii_case("send") && !action.eq_ignore_ascii_case("now") {
1430 return None;
1431 }
1432 let Some(raw_index) = parts.next() else {
1433 return Some(Err("Usage: /queue send <n>".to_string()));
1434 };
1435 if parts.next().is_some() {
1436 return Some(Err("Usage: /queue send <n>".to_string()));
1437 }
1438 let Ok(index) = raw_index.parse::<usize>() else {
1439 return Some(Err("Use a positive number".to_string()));
1440 };
1441 if index == 0 {
1442 return Some(Err("Use 1 or more".to_string()));
1443 }
1444 Some(Ok(index - 1))
1445 }
1446
1447 pub(crate) fn strip_queue_command_prefix(input: &str) -> Option<&str> {
1448 for prefix in ["/queue", "/queued"] {
1449 if let Some(rest) = input.strip_prefix(prefix)
1450 && (rest.is_empty() || rest.chars().next().is_some_and(char::is_whitespace))
1451 {
1452 return Some(rest);
1453 }
1454 }
1455 None
1456 }
1457
1458 type SteerPermit = codewhale_engine::core::engine::handle::SteerPermit;
1459 type SteerPreparation = (
1460 codewhale_engine::hooks::MessageSubmitOutcome,
1461 Option<(String, Vec<ContextReference>, SteerPermit)>,
1462 );
1463
1464 pub(crate) struct PreparingSteer {
1465 pub(super) message: QueuedMessage,
1466 recovery: DispatchRecovery,
1467 queue_index: usize,
1468 deadline: tokio::time::Instant,
1469 work: Option<futures_util::future::BoxFuture<'static, Result<SteerPreparation>>>,
1470 }
1471
1472 impl PreparingSteer {
1473 pub(crate) fn forget_queue_position(&mut self, index: usize) -> usize {
1474 if index < self.queue_index {
1475 self.queue_index -= 1;
1476 index
1477 } else if matches!(self.recovery, DispatchRecovery::Queued { .. }) {
1478 index + 1
1479 } else {
1480 index
1481 }
1482 }
1483
1484 pub(crate) fn shift_for_queue_insert(&mut self, index: usize) -> usize {
1485 if index <= self.queue_index {
1486 self.queue_index += 1;
1487 index
1488 } else if !matches!(self.recovery, DispatchRecovery::Draft) {
1489 index + 1
1490 } else {
1491 index
1492 }
1493 }
1494 }
1495
1496 pub(super) fn recovered_steer_queue(
1497 app: &App,
1498 ) -> (VecDeque<QueuedMessage>, usize, Option<QueuedMessage>) {
1499 let mut queue = app.queued_messages.clone();
1500 let mut held = app.held_restored_queue;
1501 let draft_index = if app.input.is_empty() && app.queued_draft.is_none() {
1502 app.preparing_steers
1503 .iter()
1504 .position(|p| matches!(p.recovery, DispatchRecovery::Draft))
1505 } else {
1506 None
1507 };
1508 let mut draft = None;
1509 for (offset, pending) in app.preparing_steers.iter().enumerate().rev() {
1510 if Some(offset) == draft_index {
1511 draft = Some(pending.message.clone());
1512 continue;
1513 }
1514 let was_held = matches!(
1515 pending.recovery,
1516 DispatchRecovery::Queued { was_held: true, .. }
1517 );
1518 let index = pending.queue_index.min(queue.len());
1519 queue.insert(index, pending.message.clone());
1520 if was_held || index < held {
1521 held += 1;
1522 }
1523 }
1524 (queue, held, draft)
1525 }
1526
1527 pub(crate) fn restore_preparing_steers(app: &mut App) {
1528 if app.preparing_steers.is_empty() {
1529 return;
1530 }
1531 app.steer_cancel.cancel();
1532 app.steer_cancel = Default::default();
1533 let (queue, held, draft) = recovered_steer_queue(app);
1534 app.preparing_steers.clear();
1535 app.queued_messages = queue;
1536 app.held_restored_queue = held;
1537 if let Some(draft) = draft {
1538 restore_queued_or_draft_message(app, DispatchRecovery::Draft, draft);
1539 }
1540 }
1541
1542 fn start_next_steer(app: &mut App, engine_handle: &EngineHandle) -> bool {
1543 let Some((deadline, work)) = app
1544 .preparing_steers
1545 .front_mut()
1546 .and_then(|p| Some((p.deadline, p.work.take()?)))
1547 else {
1548 return true;
1549 };
1550 let completion = match dispatch_completion_permit(app) {
1551 Ok(permit) => permit,
1552 Err(err) => {
1553 restore_preparing_steers(app);
1554 app.show_command_result(format!("Could not steer: {err}"), StatusToastLevel::Error);
1555 return false;
1556 }
1557 };
1558 let cancel = app.steer_cancel.clone();
1559 let origin = engine_handle.clone();
1560 let session = app.current_session_id.clone();
1561 let workspace = app.workspace.clone();
1562 let turn = app.turn_counter;
1563 tokio::spawn(async move {
1564 let result = tokio::select! {
1565 biased;
1566 () = cancel.cancelled() => return,
1567 result = tokio::time::timeout_at(deadline, work) => result.map_err(anyhow::Error::from).and_then(|r| r),
1568 };
1569 completion.send(Box::new(move |app, engine, _| {
1570 if cancel.is_cancelled() {
1571 return Ok(());
1572 }
1573 if !origin.tx_op.same_channel(&engine.tx_op) || workspace != app.workspace || session != app.current_session_id {
1574 restore_preparing_steers(app);
1575 app.held_restored_queue = app.queued_messages.len();
1576 if app.queued_draft.is_some() {
1577 app.queued_draft_was_held = true;
1578 }
1579 app.show_command_result("Steering was interrupted by a workspace or session change. Recovered input is held for review.", StatusToastLevel::Warning);
1580 return Ok(());
1581 }
1582 let result = if app.is_loading
1583 && !app.stopped_turn
1584 && !app.suppress_stream_events_until_turn_complete
1585 && turn == app.turn_counter
1586 {
1587 result
1588 } else {
1589 Err(anyhow::anyhow!(
1590 "the original turn ended or was interrupted"
1591 ))
1592 };
1593 let result = if tokio::time::Instant::now() >= deadline {
1594 Err(anyhow::anyhow!("steering timed out before engine admission"))
1595 } else { result };
1596 let result = result.and_then(|(outcome, payload)| {
1597 let Some(pending) = app.preparing_steers.front() else {
1598 anyhow::bail!("steering preparation was retired");
1599 };
1600 let mut message = pending.message.clone();
1601 if let Err(denial) = apply_message_submit_outcome(app, &mut message, outcome) {
1602 return Ok(Some(denial));
1603 }
1604 let (content, references, permit) =
1605 payload.ok_or_else(|| anyhow::anyhow!("missing steering input"))?;
1606 commit_prepared_steer(app, engine, message, content, references, permit);
1607 Ok(None)
1608 });
1609 let failure = match result {
1610 Ok(None) => {
1611 app.preparing_steers.pop_front();
1612 app.push_status_toast(
1613 app.tr(MessageId::ToastSentIntoTurn).into_owned(),
1614 StatusToastLevel::Info,
1615 Some(1_500),
1616 );
1617 start_next_steer(app, engine);
1618 None
1619 }
1620 Err(err) => Some(format!("{} ({err})", app.tr(MessageId::ToastCouldNotSendIntoTurn))),
1621 Ok(Some(reason)) => Some(format!("{}: {reason}", app.tr(MessageId::ToastHookBlockedFollowUp))),
1622 };
1623 if let Some(failure) = failure {
1624 restore_preparing_steers(app);
1625 app.push_status_toast(failure, StatusToastLevel::Warning, Some(4_000));
1626 }
1627 persist_offline_queue_state(app);
1628 Ok(())
1629 }));
1630 });
1631 true
1632 }
1633
1634 pub(crate) fn attempt_steer_with_queue_fallback(
1635 app: &mut App,
1636 config: &Config,
1637 engine_handle: &EngineHandle,
1638 message: QueuedMessage,
1639 recovery: DispatchRecovery,
1640 ) -> bool {
1641 if message.extension_command.is_some()
1642 || is_stop_word(&message.display, &config.stop_words()).is_some()
1643 {
1644 if message.extension_command.is_none() {
1645 engine_handle.cancel();
1646 app.stopped_turn = true;
1647 restore_preparing_steers(app);
1648 app.show_command_result(
1649 "Turn stopped. Tool calls blocked for this turn.",
1650 StatusToastLevel::Warning,
1651 );
1652 }
1653 restore_queued_or_draft_message(app, recovery, message);
1654 return false;
1655 }
1656 let Some(message) = reject_if_queue_full(app, message) else {
1657 return false;
1658 };
1659 let mentions = MentionContext::capture(app, &message, std::env::current_dir().ok());
1660 let hook = app
1661 .hooks
1662 .has_hooks_for_event(codewhale_config::hooks::HookEvent::MessageSubmit)
1663 .then(|| {
1664 (
1665 app.hooks.clone(),
1666 app.base_hook_context().with_message(&message.display),
1667 )
1668 });
1669 let reserve = engine_handle.reserve_current_steer();
1670 let mut input = message.clone();
1671 let work = Box::pin(async move {
1672 use codewhale_engine::hooks::MessageSubmitOutcome;
1673 let (outcome, resolved) = tokio::task::spawn_blocking(move || {
1674 let outcome = match hook {
1675 Some((hooks, context)) => {
1676 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1677 hooks
1678 .execute_message_submit_transform_for_dispatch(&context, &input.display)
1679 }))
1680 .unwrap_or_else(|_| {
1681 let gates = hooks.matched_strict_gate_labels(
1682 codewhale_config::hooks::HookEvent::MessageSubmit,
1683 &context,
1684 );
1685 lost_message_submit_outcome(&gates)
1686 })
1687 }
1688 None => MessageSubmitOutcome::unchanged(),
1689 };
1690 match &outcome {
1691 MessageSubmitOutcome::Blocked { .. } => return Ok((outcome, None)),
1692 MessageSubmitOutcome::Replaced { text, .. } => input.display.clone_from(text),
1693 MessageSubmitOutcome::Unchanged { .. } => {}
1694 }
1695 let resolved = mentions.resolve(&input)?;
1696 Ok::<_, anyhow::Error>((outcome, Some(resolved)))
1697 })
1698 .await??;
1699 let payload = match resolved {
1700 Some((content, references)) => Some((content, references, reserve.await?)),
1701 None => None,
1702 };
1703 Ok((outcome, payload))
1704 });
1705 app.preparing_steers.push_back(PreparingSteer {
1706 message,
1707 recovery,
1708 queue_index: match recovery {
1709 DispatchRecovery::Queued { restore_index, .. } => restore_index.unwrap_or(0),
1710 _ => app.queued_messages.len(),
1711 },
1712 deadline: tokio::time::Instant::now() + DISPATCH_TASK_BOUND,
1713 work: Some(work),
1714 });
1715 if !matches!(
1716 recovery,
1717 DispatchRecovery::Queued {
1718 restore_index: None,
1719 ..
1720 }
1721 ) {
1722 persist_offline_queue_state(app);
1723 }
1724 start_next_steer(app, engine_handle)
1725 }
1726
1727 fn commit_prepared_steer(
1728 app: &mut App,
1729 engine_handle: &EngineHandle,
1730 message: QueuedMessage,
1731 mut content: String,
1732 references: Vec<ContextReference>,
1733 permit: SteerPermit,
1734 ) {
1735 let paused_dispatch = plan_paused_command_message(app, &message.display);
1736 if let Some(note) = paused_dispatch.note() {
1737 content.push_str(note);
1738 }
1739 // Send exactly what the engine will store. `turn_loop` commits a steer as
1740 // `pending.commit().trim()`, so a composer newline or an appended note
1741 // left the held copy differing from the record by whitespace alone --
1742 // `accepted_steer_index` then never matched, the steer was never
1743 // promoted, and the "sending into this turn" card kept showing a message
1744 // the transcript had already delivered. Trimming here keeps that match an
1745 // exact comparison, which is the stronger invariant.
1746 let content = content.trim().to_string();
1747 let message_index = app.api_messages.len();
1748
1749 paused_dispatch.apply(app, engine_handle);
1750
1751 let person_text = if message.extension_command.is_none()
1752 && message.approved_plan.is_none()
1753 && message.owner_input
1754 {
1755 Some(message.display.clone())
1756 } else {
1757 None
1758 };
1759
1760 permit.send_with_person_text(content.clone(), person_text);
1761 app.last_submitted_prompt = Some(message.display.clone());
1762
1763 // #6190: the steer channel accepting the text is not the turn accepting
1764 // it. The engine commits a steer at the next step boundary and discards
1765 // one whose turn has already moved on, so painting a settled cell and
1766 // pushing `api_messages` here produced two defects at once: the cell sat
1767 // above the assistant content the record places before it, and a dropped
1768 // steer left a transcript entry the model never saw. Hold it as in-flight
1769 // instead — it renders in the "sending into turn" preview until the
1770 // engine's own `SessionUpdated` shows it, which is also where it learns
1771 // its real message index.
1772 app.inflight_steers
1773 .push_back(crate::tui::app::InflightSteer {
1774 message,
1775 content,
1776 sent_after_index: message_index,
1777 references,
1778 });
1779 app.needs_redraw = true;
1780
1781 app.show_command_result(
1782 "Steering current turn...".to_string(),
1783 StatusToastLevel::Info,
1784 );
1785 }
1786
1787 /// Promote every in-flight steer the engine's record now contains.
1788 ///
1789 /// Called from `apply_engine_session_projection` after the projection lands,
1790 /// so the transcript cell is appended in the position the record gives it:
1791 /// below the assistant work that preceded the steer, as the newest entry.
1792 /// Matching is on the exact text handed to `EngineHandle::steer`, which the
1793 /// engine stores as the accepted user message's first text block, searched
1794 /// from the index the steer was sent after so an identical earlier message
1795 /// cannot claim it.
1796 pub(crate) fn settle_accepted_steers(app: &mut App) {
1797 if app.inflight_steers.is_empty() {
1798 return;
1799 }
1800 let mut claimed: Vec<usize> = Vec::new();
1801 let mut unsettled = VecDeque::new();
1802 for steer in std::mem::take(&mut app.inflight_steers) {
1803 let Some(index) = accepted_steer_index(app, &steer, &claimed) else {
1804 unsettled.push_back(steer);
1805 continue;
1806 };
1807 claimed.push(index);
1808 // Settle the streaming thinking/tool content that chronologically
1809 // preceded the steer before the steer's own cell is appended.
1810 app.flush_active_cell();
1811 let display = format!("+ {}", steer.message.display);
1812 let history_cell = paint_user_turn_cell(app, &steer.message, display);
1813 app.record_context_references(history_cell, index, steer.references);
1814 app.needs_redraw = true;
1815 }
1816 app.inflight_steers = unsettled;
1817 }
1818
1819 fn accepted_steer_index(
1820 app: &App,
1821 steer: &crate::tui::app::InflightSteer,
1822 claimed: &[usize],
1823 ) -> Option<usize> {
1824 let start = steer.sent_after_index.min(app.api_messages.len());
1825 app.api_messages
1826 .iter()
1827 .enumerate()
1828 .skip(start)
1829 .find(|(index, message)| {
1830 !claimed.contains(index)
1831 && message.role == Role::User
1832 && matches!(
1833 message.content.first(),
1834 Some(ContentBlock::Text { text, .. }) if text == &steer.content
1835 )
1836 })
1837 .map(|(index, _)| index)
1838 }
1839
1840 /// A turn that ended without accepting a steer must not swallow it (#6190,
1841 /// #6297). The message becomes a queued follow-up — the queue is the one path
1842 /// that actually drains into a turn, where the engine's context-pressure gate
1843 /// sees it like any other send — instead of a display-only "rejected" string
1844 /// that nothing ever dispatches.
1845 pub(crate) fn settle_unaccepted_steers_at_turn_end(app: &mut App) {
1846 let preparing = !app.preparing_steers.is_empty();
1847 restore_preparing_steers(app);
1848 if app.inflight_steers.is_empty() {
1849 return;
1850 }
1851 let deferred = std::mem::take(&mut app.inflight_steers);
1852 if preparing {
1853 for steer in deferred.into_iter().rev() {
1854 restore_queued_message(app, Some(0), false, steer.message);
1855 }
1856 } else {
1857 app.queued_messages
1858 .extend(deferred.into_iter().map(|steer| steer.message));
1859 }
1860 app.needs_redraw = true;
1861 }
1862
1863 fn queued_follow_up_toast(app: &App) -> String {
1864 if app.offline_mode {
1865 return app.tr(MessageId::ToastQueuedOffline).into_owned();
1866 }
1867 let count = app.queued_message_count();
1868 if count <= 1 {
1869 app.tr(MessageId::ToastQueuedFollowUp).into_owned()
1870 } else {
1871 app.tr(MessageId::ToastQueuedFollowUpCount)
1872 .replace("{count}", &count.to_string())
1873 }
1874 }
1875
1876 pub(crate) async fn dispatch_composer_message(
1877 app: &mut App,
1878 config: &Config,
1879 engine_handle: &EngineHandle,
1880 message: QueuedMessage,
1881 recovery: DispatchRecovery,
1882 action: ComposerSubmitAction,
1883 ) -> Result<()> {
1884 if app.pending_fresh_session.is_some() {
1885 restore_queued_or_draft_message(app, recovery, message);
1886 app.show_command_result(
1887 "A new session is awaiting Engine confirmation; sending is paused.".to_string(),
1888 StatusToastLevel::Warning,
1889 );
1890 return Ok(());
1891 }
1892 if message.extension_command.is_some() {
1893 return dispatch_user_message_with_recovery(app, config, engine_handle, message, recovery)
1894 .await;
1895 }
1896 // The ordinary web mirror does not block local prompts. Isolated Runtime
1897 // Chat is different: it owns a provider-backed native turn that is not
1898 // reflected by the interactive engine's `is_loading` bit. Preserve the
1899 // local message in the queue until that exact turn and its terminal relay
1900 // receipt have settled, so one attached run never has two inference loops.
1901 if app.remote_control.runtime_chat_blocks_local_dispatch() {
1902 let mut message = message;
1903 echo_queued_user_turn(app, &mut message);
1904 enqueue_offline_message(app, message);
1905 let queued = app
1906 .tr(MessageId::AgentRailQueuedCount)
1907 .replace("{count}", &app.queued_message_count().to_string());
1908 let status = format!(
1909 "Runtime Chat · {} · {queued}",
1910 app.tr(MessageId::PhaseFinishing)
1911 );
1912 app.push_status_toast(status, StatusToastLevel::Info, Some(4_000));
1913 return Ok(());
1914 }
1915
1916 // Agent focus: the composer addresses one child's fork, not the main
1917 // session. The follow-up is real runtime work (Op::FollowUpSubAgent); the
1918 // main transcript keeps a receipt line and the focused view echoes the
1919 // message until the child's own transcript carries it.
1920 if let Some(focus) = app.agent_focus.as_ref() {
1921 let agent_id = focus.agent_id.clone();
1922 let label = focus.label.clone();
1923 let text = message.display.clone();
1924 crate::tui::agent_focus::echo_user_follow_up(app, &text);
1925 let receipt = app
1926 .tr(codewhale_localization::MessageId::AgentFocusFollowUpQueued)
1927 .replace("{agent}", &label);
1928 app.push_history_cell(crate::tui::history::HistoryCell::System { content: receipt });
1929 // #6150: the input path never awaits a full op channel. The follow-up
1930 // is retryable; a rejected send surfaces immediately.
1931 if let Err(err) =
1932 engine_handle.try_send(codewhale_engine::core::ops::Op::FollowUpSubAgent {
1933 agent_id: agent_id.clone(),
1934 text,
1935 })
1936 {
1937 let reason = if err
1938 .downcast_ref::<tokio::sync::mpsc::error::TrySendError<codewhale_engine::core::ops::Op>>()
1939 .is_some_and(|e| matches!(e, tokio::sync::mpsc::error::TrySendError::Full(_)))
1940 {
1941 "engine busy"
1942 } else {
1943 "engine unavailable"
1944 };
1945 let failed = app
1946 .tr(codewhale_localization::MessageId::AgentFocusFollowUpFailed)
1947 .replace("{agent}", &label)
1948 .replace("{reason}", reason);
1949 app.push_status_toast(failed, StatusToastLevel::Warning, Some(5_000));
1950 }
1951 return Ok(());
1952 }
1953 let disposition = match action {
1954 _ if is_stop_word(&message.display, &config.stop_words()).is_some() => {
1955 SubmitDisposition::Immediate
1956 }
1957 ComposerSubmitAction::Submit(disposition) => disposition,
1958 ComposerSubmitAction::SendQueuedNow | ComposerSubmitAction::Noop => {
1959 // The caller extracted a non-empty input, so these can only arise
1960 // if state changed between key resolution and dispatch. Queueing
1961 // is lossless and preserves ordering in that narrow race.
1962 SubmitDisposition::Queue
1963 }
1964 };
1965 match disposition {
1966 SubmitDisposition::Immediate => {
1967 let _ =
1968 dispatch_user_message_with_recovery(app, config, engine_handle, message, recovery)
1969 .await;
1970 Ok(())
1971 }
1972 SubmitDisposition::Queue => {
1973 let Some(mut message) = reject_if_queue_full(app, message) else {
1974 return Ok(());
1975 };
1976 echo_queued_user_turn(app, &mut message);
1977 enqueue_offline_message(app, message);
1978 let toast = queued_follow_up_toast(app);
1979 app.push_status_toast(toast, StatusToastLevel::Info, Some(3_000));
1980 Ok(())
1981 }
1982 SubmitDisposition::Steer => {
1983 attempt_steer_with_queue_fallback(app, config, engine_handle, message, recovery);
1984 Ok(())
1985 }
1986 }
1987 }
1988
1989 #[cfg(test)]
1990 pub(crate) async fn submit_or_steer_message(
1991 app: &mut App,
1992 config: &Config,
1993 engine_handle: &EngineHandle,
1994 message: QueuedMessage,
1995 recovery: DispatchRecovery,
1996 ) -> Result<()> {
1997 let action = ComposerSubmitAction::Submit(app.decide_submit_disposition());
1998 dispatch_composer_message(app, config, engine_handle, message, recovery, action).await
1999 }
2000
2000 lines RUST