返回 CodeWhale
session_state.rs
根目录 / crates / tui / src / tui / ui / session_state.rs
1 //! Session durability: snapshot/restore, recovery after a crash or stall,
2 //! and workspace/worktree switching.
3 //!
4 //! Moved verbatim out of `ui.rs`.
5
6 use super::*;
7
8 pub(crate) struct OfflineQueueTransition {
9 lease: Arc<codewhale_engine::session_manager::OfflineQueueLease>,
10 restored: Option<OfflineQueueState>,
11 }
12
13 /// A session load/resume failure must survive past the next footer update.
14 ///
15 /// The status line is replaced almost immediately, which left a failed
16 /// resume looking like a silent new session — the screen even offered to
17 /// resume the id it had just created (#6138). Keep both: the transcript
18 /// error cell is the durable record, the status line the immediate one.
19 pub(crate) fn surface_session_load_failure(app: &mut App, message: String) {
20 app.add_message(crate::tui::history::HistoryCell::Error {
21 message: message.clone(),
22 severity: codewhale_error_taxonomy::ErrorSeverity::Error,
23 code: None,
24 });
25 app.show_command_result(message, StatusToastLevel::Error);
26 }
27
28 /// Complete all fallible queue work before a session switch mutates the App.
29 /// A second editor must fail without touching either composer or queue file.
30 pub(crate) fn prepare_offline_queue_transition(
31 app: &App,
32 session_id: &str,
33 ) -> Result<Option<OfflineQueueTransition>, String> {
34 if app
35 .offline_queue_lease
36 .as_ref()
37 .is_some_and(|lease| lease.session_id() == session_id)
38 {
39 return Ok(None);
40 }
41 let manager = SessionManager::default_location().map_err(|error| error.to_string())?;
42 let lease = manager
43 .acquire_offline_queue_lease(session_id)
44 .map_err(|error| error.to_string())?;
45 let restored = manager
46 .load_offline_queue_state(session_id)
47 .map_err(|error| {
48 format!("Could not restore queued input for session {session_id}: {error}")
49 })?;
50 Ok(Some(OfflineQueueTransition { lease, restored }))
51 }
52
53 pub(crate) fn install_offline_queue_transition(
54 app: &mut App,
55 transition: Option<OfflineQueueTransition>,
56 ) -> bool {
57 let Some(transition) = transition else {
58 return false;
59 };
60 restore_preparing_steers(app);
61 // The request retains the old Arc until the actor finishes its write.
62 // Acquiring the next lease does not release the previous editor early.
63 persist_offline_queue_state(app);
64 if app.queued_draft.take().is_some() {
65 app.clear_input();
66 }
67 app.queued_draft_was_held = false;
68 app.queued_messages.clear();
69 app.held_restored_queue = 0;
70 app.set_current_session_id(Some(transition.lease.session_id().to_string()));
71 app.offline_queue_lease = Some(transition.lease);
72 transition
73 .restored
74 .is_some_and(|state| restore_matching_offline_queue_state(app, state))
75 }
76
77 pub(crate) fn offline_queue_is_empty(app: &App) -> bool {
78 app.preparing_steers.is_empty() && app.queued_messages.is_empty() && app.queued_draft.is_none()
79 }
80
81 /// The editable composer is the durable draft. Keep `queued_draft` itself as
82 /// the original message so Escape can still cancel the edit in this window.
83 pub(crate) fn offline_queue_projection(
84 app: &App,
85 ) -> (VecDeque<QueuedMessage>, Option<QueuedMessage>) {
86 let draft = app.queued_draft.as_ref().map(|original| {
87 let mut edited = original.clone();
88 edited.display.clone_from(&app.input);
89 edited
90 });
91 let (messages, _, unsent_draft) = recovered_steer_queue(app);
92 (messages, draft.or(unsent_draft))
93 }
94
95 #[derive(Clone)]
96 pub(crate) struct SavedWorkProjection {
97 pub(super) owner: Option<String>,
98 pub(super) state: Option<codewhale_engine::session_manager::SessionWorkState>,
99 }
100
101 pub(crate) fn saved_work_projection(app: &App, session: &SavedSession) -> SavedWorkProjection {
102 SavedWorkProjection {
103 owner: app.current_session_id.clone(),
104 state: session.work_state.clone(),
105 }
106 }
107
108 pub(crate) async fn publish_saved_work_projection(
109 app: &mut App,
110 projection: &SavedWorkProjection,
111 ) -> Result<bool, String> {
112 let Some(work) = app.runtime_services.work.clone() else {
113 return Ok(false);
114 };
115 let published = work
116 .publish_pending_matching(
117 projection.owner.as_deref(),
118 projection
119 .state
120 .as_ref()
121 .and_then(|state| state.graph.as_ref()),
122 )
123 .await?;
124 if !published && work.has_pending_publish() {
125 return Err("a newer Work update remains pending".to_string());
126 }
127 Ok(published)
128 }
129
130 #[cfg(test)]
131 pub(crate) async fn publish_pending_work_projection(app: &mut App) -> Result<bool, String> {
132 let Some(work) = app.runtime_services.work.clone() else {
133 return Ok(false);
134 };
135 work.publish_pending().await
136 }
137
138 pub(crate) fn prepare_session_publication(
139 app: &mut App,
140 request: &mut PersistRequest,
141 ) -> Result<(), String> {
142 if app.dispatch_in_flight {
143 return Err("session publication is waiting for native dispatch admission".to_string());
144 }
145 let session = match request {
146 PersistRequest::SaveCheckpoint { session }
147 | PersistRequest::AcknowledgedCheckpoint { session, .. }
148 | PersistRequest::SessionSnapshot(session)
149 | PersistRequest::CompletedCommit { session } => session,
150 _ => return Ok(()),
151 };
152 let owner = app
153 .session_write_owner
154 .clone()
155 .ok_or_else(|| "session publication lacks an admitted native owner".to_string())?;
156 let receipt = session
157 .capture_publication(owner)
158 .map_err(|error| error.to_string())?;
159 if app
160 .current_session_id
161 .as_deref()
162 .is_none_or(|id| id == session.metadata.id)
163 {
164 app.session_write_receipt = Some(receipt);
165 }
166 Ok(())
167 }
168
169 pub(crate) fn try_persist_session(app: &mut App, mut request: PersistRequest) -> bool {
170 if let Err(error) = prepare_session_publication(app, &mut request) {
171 tracing::warn!(%error, "session publication could not capture its native source");
172 let session_id = match &request {
173 PersistRequest::SaveCheckpoint { session }
174 | PersistRequest::AcknowledgedCheckpoint { session, .. }
175 | PersistRequest::SessionSnapshot(session)
176 | PersistRequest::CompletedCommit { session } => Some(session.metadata.id.as_str()),
177 _ => None,
178 };
179 super::event_loop::surface_session_save_failure(app, session_id, &error);
180 return false;
181 }
182 persistence_actor::try_persist(request)
183 }
184
185 pub(crate) fn prepare_fresh_session_write(
186 id: &str,
187 ) -> Result<codewhale_engine::session_manager::SessionWriteReceipt, String> {
188 SessionManager::default_location()
189 .and_then(|manager| manager.expect_absent_session(id))
190 .map_err(|error| error.to_string())
191 }
192
193 pub(crate) fn expect_fresh_session(app: &mut App, id: &str) -> Result<(), String> {
194 app.session_write_receipt = Some(prepare_fresh_session_write(id)?);
195 app.session_write_owner = Some(codewhale_engine::session_manager::SessionWriteOwner::control());
196 Ok(())
197 }
198
199 pub(crate) async fn persist_pending_work_checkpoint(app: &mut App) -> Result<bool, String> {
200 if app.dispatch_in_flight {
201 return Ok(false);
202 }
203 let Some(work) = app.runtime_services.work.clone() else {
204 return Ok(false);
205 };
206 if !work.has_pending_publish() {
207 return Ok(false);
208 }
209 let manager = SessionManager::default_location()
210 .map_err(|err| format!("could not open sessions directory: {err}"))?;
211 let session = build_session_snapshot(app, &manager)?;
212 let projection = saved_work_projection(app, &session);
213 if app.current_session_id.is_none() {
214 app.set_current_session_id(Some(session.metadata.id.clone()));
215 }
216 if !try_persist_session(app, PersistRequest::SaveCheckpoint { session }) {
217 return Err("persistence actor is unavailable".to_string());
218 }
219 publish_saved_work_projection(app, &projection).await
220 }
221
222 pub(crate) fn persist_with_pending_work_boundary(
223 app: &mut App,
224 mut request: PersistRequest,
225 projection: &SavedWorkProjection,
226 ) -> Result<(), String> {
227 prepare_session_publication(app, &mut request)?;
228 let has_pending = app
229 .runtime_services
230 .work
231 .as_ref()
232 .is_some_and(|work| work.has_pending_publish());
233 if !has_pending {
234 return persistence_actor::persist_checked(request);
235 }
236 if !persistence_actor::try_persist(request) {
237 return Err("persistence actor is unavailable".to_string());
238 }
239 app.publish_saved_work_state(projection.owner.as_deref(), projection.state.as_ref())
240 .map(|_| ())
241 }
242
243 pub(crate) fn restore_matching_offline_queue_state(
244 app: &mut App,
245 state: OfflineQueueState,
246 ) -> bool {
247 if state.session_id.as_deref() != app.current_session_id.as_deref()
248 || state.session_id.is_none()
249 {
250 return false;
251 }
252 app.queued_messages = state
253 .messages
254 .into_iter()
255 .map(queued_session_to_ui)
256 .collect();
257 app.held_restored_queue = app.queued_messages.len();
258 if let Some(draft) = state.draft.map(queued_session_to_ui) {
259 app.input.clone_from(&draft.display);
260 app.cursor_position = app.input.chars().count();
261 app.active_skill.clone_from(&draft.skill_instruction);
262 app.active_skill_provenance
263 .clone_from(&draft.skill_provenance);
264 app.queued_draft = Some(draft);
265 app.queued_draft_was_held = true;
266 } else {
267 app.queued_draft = None;
268 app.queued_draft_was_held = false;
269 }
270 app.needs_redraw = true;
271 true
272 }
273
274 /// Running rows that never veto recovery: a prior-session row has no live
275 /// actor in this process, and a current child silent beyond its heartbeat
276 /// bound (at least `TOOL_HANG_WATCHDOG_TIMEOUT`) may have lost its terminal event (#6184).
277 /// Elapsed time alone does not establish that a current child is stalled.
278 pub(crate) fn suspect_running_agents(app: &App, now: Instant) -> Vec<String> {
279 app.subagent_cache
280 .iter()
281 .filter(|agent| matches!(agent.status, SubAgentStatus::Running))
282 .filter(|agent| {
283 agent.from_prior_session
284 || app
285 .agent_progress_meta
286 .get(&agent.agent_id)
287 .and_then(|meta| meta.last_progress_at)
288 .or(agent.started_at)
289 .is_some_and(|at| {
290 now.saturating_duration_since(at)
291 > TOOL_HANG_WATCHDOG_TIMEOUT.max(Duration::from_millis(
292 agent.heartbeat_timeout_ms.unwrap_or(0),
293 ))
294 })
295 })
296 .map(|agent| agent.agent_id.clone())
297 .collect()
298 }
299
300 /// Running sub-agents that still legitimately hold the turn open.
301 pub(crate) fn live_running_agent_count(app: &App, now: Instant) -> usize {
302 let suspects = suspect_running_agents(app, now);
303 let mut ids: std::collections::HashSet<&str> = app
304 .agent_progress
305 .keys()
306 .filter(|id| {
307 app.agent_progress_meta
308 .get(id.as_str())
309 .and_then(|meta| meta.last_progress_at)
310 .is_some_and(|at| now.saturating_duration_since(at) <= TOOL_HANG_WATCHDOG_TIMEOUT)
311 })
312 .map(String::as_str)
313 .collect();
314 for agent in app
315 .subagent_cache
316 .iter()
317 .filter(|agent| matches!(agent.status, SubAgentStatus::Running))
318 {
319 ids.insert(agent.agent_id.as_str());
320 }
321 ids.retain(|id| !suspects.iter().any(|suspect| suspect == id));
322 ids.len()
323 }
324
325 /// Queued follow-ups the stalled turn is holding back, as a sentence suffix.
326 fn held_queue_note(app: &App) -> String {
327 match app.queued_messages.len() {
328 0 => String::new(),
329 1 => " 1 queued message is held until the turn ends.".to_string(),
330 n => format!(" {n} queued messages are held until the turn ends."),
331 }
332 }
333
334 /// Log, record under `crashes/`, and name a stall the UI watchdog saw.
335 fn record_ui_stall(app: &App, phase: &str, since_progress: Duration, bound: Duration) {
336 let suspects = suspect_running_agents(app, Instant::now());
337 let detail = (!suspects.is_empty()).then(|| {
338 format!(
339 "sub-agent(s) from a prior session or with no progress for 10m, treated as suspect: {}",
340 suspects.join(", ")
341 )
342 });
343 codewhale_runtime::stall_report::report_stall(&codewhale_runtime::stall_report::StallReport {
344 source: "ui",
345 phase: phase.to_string(),
346 detail,
347 turn_id: app.runtime_turn_id.clone(),
348 provider_request: app
349 .active_turn
350 .as_ref()
351 .and_then(|turn| turn.route.as_ref())
352 .map(|route| format!("{} / {}", route.provider_identity, route.model)),
353 since_progress,
354 bound: Some(bound),
355 });
356 }
357
358 /// The UI watchdog, supervised by the engine heartbeat (#6184). Suspect
359 /// sub-agents no longer veto recovery, and an engine-reported stall is shown
360 /// with the phase it stalled in.
361 ///
362 /// Recovering a turn that had started is all-or-nothing (#6800): the engine's
363 /// turn is cancelled with the UI's, through the cancellation the cancel key
364 /// issues. Clearing only the UI left the engine owning the turn, so the next
365 /// message was refused and no outcome was ever recorded. The engine's
366 /// terminal event for that turn then arrives as it does after a local cancel.
367 ///
368 /// Known limitation: a turn wedged somewhere that does not observe
369 /// cancellation still holds the engine; this only removes the disagreement.
370 pub(crate) fn reconcile_turn_liveness_supervised(
371 app: &mut App,
372 now: Instant,
373 heartbeat: &codewhale_engine::core::engine::turn_heartbeat::HeartbeatSnapshot,
374 engine: &EngineHandle,
375 ) -> bool {
376 if app.external_agent.is_some() {
377 return false;
378 }
379 let turn_in_progress = matches!(app.runtime_turn_status.as_deref(), Some("in_progress"));
380 if (app.is_loading || matches!(app.runtime_turn_status.as_deref(), Some("in_progress")))
381 && let Some(stall) = heartbeat.stall.as_ref()
382 {
383 // Coalesced by text while visible, so one toast per stall episode.
384 let text = format!("{}{}", stall.status_line(), held_queue_note(app));
385 app.push_status_toast(text, StatusToastLevel::Error, None);
386 }
387 let has_live_agents = live_running_agent_count(app, now) > 0;
388 let recovered = reconcile_turn_liveness_with(app, now, has_live_agents, Some(heartbeat));
389 if recovered && turn_in_progress && app.runtime_turn_status.is_none() {
390 engine.cancel_with_reason(codewhale_engine::core::engine::CancelReason::Stalled);
391 app.suppress_stream_events_until_turn_complete = true;
392 }
393 recovered
394 }
395
396 /// Unsupervised form (no engine heartbeat), kept for focused tests.
397 #[cfg(test)]
398 pub(crate) fn reconcile_turn_liveness(
399 app: &mut App,
400 now: Instant,
401 has_running_agents: bool,
402 ) -> bool {
403 reconcile_turn_liveness_with(app, now, has_running_agents, None)
404 }
405
406 pub(crate) fn reconcile_turn_liveness_with(
407 app: &mut App,
408 now: Instant,
409 has_running_agents: bool,
410 heartbeat: Option<&codewhale_engine::core::engine::turn_heartbeat::HeartbeatSnapshot>,
411 ) -> bool {
412 if app.external_agent.is_some() {
413 return false;
414 }
415 let engine_owns_wait = heartbeat.is_some_and(|snapshot| snapshot.engine_owns_live_wait());
416 // #6872: human decisions can wait indefinitely. Their configured timeout,
417 // answer or withdrawal owns the wait, including buried or hidden cards.
418 let awaiting_human_decision = app.pending_user_input_prompt.is_some()
419 || app.view_stack.contains_kind(ModalKind::Approval)
420 || app.view_stack.contains_kind(ModalKind::Elevation)
421 || app
422 .pending_child_requests
423 .keys()
424 .any(|id| !crate::tui::pending_requests::is_foreign_child_request(app, id));
425 if app.is_loading
426 && app.runtime_turn_status.is_none()
427 && !has_running_agents
428 && !app.is_compacting
429 && !app.is_purging
430 && app.dispatch_started_at.is_some_and(|started| {
431 now.saturating_duration_since(started) > DISPATCH_WATCHDOG_TIMEOUT
432 })
433 {
434 if let Some(started) = app.dispatch_started_at {
435 record_ui_stall(
436 app,
437 "while dispatching the message to the engine",
438 now.saturating_duration_since(started),
439 DISPATCH_WATCHDOG_TIMEOUT,
440 );
441 }
442 // #2739: the user's prompt was already appended to api_messages
443 // before dispatch, but the turn never reached `in_progress`. Persist
444 // it before clearing turn state so `--continue` keeps the prompt
445 // instead of loading the previous save.
446 persist_recovery_snapshot(app);
447 settle_pending_human_requests(app);
448 app.is_loading = false;
449 app.dispatch_started_at = None;
450 app.turn_started_at = None;
451 app.turn_last_activity_at = None;
452 app.pending_turn_route = None;
453 app.pending_auto_route_receipt = None;
454 app.active_turn = None;
455 app.suppress_stream_events_until_turn_complete = false;
456 app.push_status_toast(
457 "Turn dispatch timed out; the engine may have stopped. Please try again.",
458 StatusToastLevel::Error,
459 None,
460 );
461 return true;
462 }
463
464 if app.is_loading
465 && matches!(
466 app.runtime_turn_status.as_deref(),
467 Some("completed" | "interrupted" | "failed")
468 )
469 && !has_running_agents
470 && !app.is_compacting
471 && !app.is_purging
472 {
473 settle_pending_human_requests(app);
474 app.is_loading = false;
475 app.dispatch_started_at = None;
476 app.turn_started_at = None;
477 app.turn_last_activity_at = None;
478 app.pending_turn_route = None;
479 app.pending_auto_route_receipt = None;
480 app.active_turn = None;
481 app.suppress_stream_events_until_turn_complete = false;
482 app.push_status_toast(
483 "Recovered from an inconsistent busy state.",
484 StatusToastLevel::Warning,
485 None,
486 );
487 return true;
488 }
489
490 // Branch 3: turn started but never completed — engine may have
491 // panicked, sub-agent may be stuck, or the completion event was lost.
492 if app.is_loading
493 && matches!(app.runtime_turn_status.as_deref(), Some("in_progress"))
494 && !has_running_agents
495 && !engine_owns_wait
496 && !awaiting_human_decision
497 && !app.is_compacting
498 && !active_turn_has_running_tool(app)
499 && let Some(last_activity) = app.turn_last_activity_at.or(app.turn_started_at)
500 && now.saturating_duration_since(last_activity) > turn_stall_watchdog_timeout(app)
501 {
502 record_ui_stall(
503 app,
504 "waiting for the turn's completion signal",
505 now.saturating_duration_since(last_activity),
506 turn_stall_watchdog_timeout(app),
507 );
508 recover_stalled_runtime_turn(
509 app,
510 "Turn stalled — no completion signal received. Please try again.",
511 StatusToastLevel::Error,
512 );
513 return true;
514 }
515
516 if app.is_loading
517 && matches!(app.runtime_turn_status.as_deref(), Some("in_progress"))
518 && !has_running_agents
519 && !awaiting_human_decision
520 && !app.is_compacting
521 && !app.is_purging
522 && active_turn_has_running_tool(app)
523 && let Some(last_activity) = app.turn_last_activity_at.or(app.turn_started_at)
524 && now.saturating_duration_since(last_activity) > TOOL_HANG_WATCHDOG_TIMEOUT
525 {
526 record_ui_stall(
527 app,
528 "while a tool ran with no progress",
529 now.saturating_duration_since(last_activity),
530 TOOL_HANG_WATCHDOG_TIMEOUT,
531 );
532 recover_stalled_runtime_turn(
533 app,
534 "Tool stalled with no progress for 10m — recovered; the command may still be running in the background. Run /jobs to see it and /jobs cancel <id> to stop it.",
535 StatusToastLevel::Error,
536 );
537 return true;
538 }
539
540 false
541 }
542
543 /// #2739: persist the current in-memory session state before a recovery or
544 /// cancellation path clears turn bookkeeping. Without this snapshot, the
545 /// just-finalised partial turn lives only in `app.api_messages` and is never
546 /// written to disk, so `--continue` loads the *previous* save — effectively
547 /// losing the entire in-progress turn.
548 pub(crate) fn persist_recovery_snapshot(app: &mut App) {
549 if app.dispatch_in_flight {
550 return;
551 }
552 let built = SessionManager::default_location()
553 .map_err(|err| err.to_string())
554 .and_then(|manager| build_session_snapshot(app, &manager));
555 let mut session = match built {
556 Ok(session) => session,
557 Err(err) => {
558 tracing::error!(%err, "recovery snapshot could not be built; in-progress turn not persisted");
559 surface_session_save_failure(app, &err);
560 return;
561 }
562 };
563 if let Some(turn) = app.active_turn.as_ref()
564 && app.runtime_turn_id.as_deref() == Some(turn.turn_id.as_str())
565 && !app.suppress_stream_events_until_turn_complete
566 && app
567 .api_messages
568 .last()
569 .is_some_and(|message| message.role == codewhale_models::Role::User)
570 && let Some(HistoryCell::Assistant {
571 content,
572 streaming: true,
573 }) = app
574 .streaming_message_index
575 .and_then(|index| app.history.get(index))
576 && !content.is_empty()
577 && let Some(journal) = session.journal.as_mut()
578 {
579 session.leaf_id = Some(journal.append_message(Message::interrupted_assistant(content)));
580 session.metadata.message_count += 1;
581 }
582 let projection = saved_work_projection(app, &session);
583 if app.current_session_id.is_none() {
584 app.set_current_session_id(Some(session.metadata.id.clone()));
585 }
586 if let Err(err) = persist_with_pending_work_boundary(
587 app,
588 PersistRequest::SaveCheckpoint { session },
589 &projection,
590 ) {
591 tracing::error!(%err, "recovery snapshot save failed; in-progress turn not durably persisted");
592 surface_session_save_failure(app, &err);
593 }
594 }
595
596 fn surface_session_save_failure(app: &mut App, error: &str) {
597 let id = app
598 .current_session_id
599 .as_deref()
600 .map(codewhale_engine::session_manager::truncate_id)
601 .unwrap_or("—");
602 let message = app
603 .tr(MessageId::SessionSaveFailed)
604 .replace("{id}", id)
605 .replace("{error}", error);
606 app.add_message(HistoryCell::Error {
607 message: message.clone(),
608 severity: codewhale_error_taxonomy::ErrorSeverity::Error,
609 code: None,
610 });
611 let session_id = app.current_session_id.clone();
612 super::event_loop::surface_session_save_failure(app, session_id.as_deref(), error);
613 app.set_sticky_status(message, StatusToastLevel::Error, None);
614 }
615
616 pub(crate) fn persist_full_reset_snapshot(app: &mut App) {
617 let session = SessionManager::default_location()
618 .map_err(|err| err.to_string())
619 .and_then(|manager| build_session_snapshot(app, &manager));
620 let session = match session {
621 Ok(session) => session,
622 Err(err) => {
623 tracing::error!(%err, "reset snapshot could not be built");
624 surface_session_save_failure(app, &err);
625 return;
626 }
627 };
628 let projection = saved_work_projection(app, &session);
629 app.set_current_session_id(Some(session.metadata.id.clone()));
630 if let Err(err) = persist_with_pending_work_boundary(
631 app,
632 PersistRequest::CompletedCommit { session },
633 &projection,
634 ) {
635 tracing::error!(%err, "reset snapshot save failed");
636 surface_session_save_failure(app, &err);
637 }
638 }
639
640 pub(crate) fn maybe_throttled_recovery_snapshot(
641 app: &mut App,
642 now: Instant,
643 last_snapshot_at: &mut Option<Instant>,
644 ) {
645 if app.dispatch_in_flight
646 || (!app.is_loading && !matches!(app.runtime_turn_status.as_deref(), Some("in_progress")))
647 {
648 return;
649 }
650 if last_snapshot_at
651 .is_some_and(|last| now.saturating_duration_since(last) < RECOVERY_SNAPSHOT_INTERVAL)
652 {
653 return;
654 }
655 persist_recovery_snapshot(app);
656 *last_snapshot_at = Some(now);
657 }
658
659 pub(crate) fn recover_stalled_runtime_turn(app: &mut App, message: &str, level: StatusToastLevel) {
660 settle_pending_human_requests(app);
661 // Capture the turn identity before the reset below clears it; the
662 // outbox event must name the turn that stalled.
663 let stalled_turn_id = app.runtime_turn_id.clone();
664 let stalled_session_id = app.hooks.session_id().to_string();
665 // Finalize in-flight thinking / assistant / tool cells so the
666 // transcript doesn't show permanent spinners after recovery.
667 streaming_thinking::finalize_current(app);
668 app.finalize_streaming_assistant_as_interrupted();
669 app.finalize_active_cell_as_interrupted();
670 app.streaming_state.reset();
671 app.streaming_message_index = None;
672 app.streaming_thinking_active_entry = None;
673
674 // #2739: persist the partial turn's api_messages before clearing
675 // turn state. Without this snapshot the stalled/cancelled turn's
676 // messages are held only in memory and --continue sees the
677 // *previous* save, losing the entire in-progress turn.
678 persist_recovery_snapshot(app);
679
680 app.is_loading = false;
681 // #6800: fail an unadmitted dispatch back now instead of after its bound.
682 app.cancel_in_flight_dispatch();
683 app.turn_started_at = None;
684 app.turn_last_activity_at = None;
685 app.runtime_turn_status = None;
686 app.runtime_turn_id = None;
687 app.dispatch_started_at = None;
688 app.pending_turn_route = None;
689 app.pending_auto_route_receipt = None;
690 app.active_turn = None;
691 app.suppress_stream_events_until_turn_complete = false;
692 // Per-turn scroll lock — clear so the next turn auto-scrolls.
693 app.user_scrolled_during_stream = false;
694 // #6184: queued follow-ups drain only on a TurnComplete this recovered
695 // turn will never send. Hand the latest one back to the composer so one
696 // Enter resends it (the rest drain after that turn), and say so.
697 let held = app.queued_messages.len();
698 let message = if held > 0 && app.pop_last_queued_into_draft() {
699 let rest = held - 1;
700 let tail = if rest == 0 {
701 String::new()
702 } else {
703 format!(" {rest} more queued message(s) send after it.")
704 };
705 format!(
706 "{message} Your queued message is back in the composer — press Enter to resend it.{tail}"
707 )
708 } else {
709 format!("{message}{}", held_queue_note(app))
710 };
711 let message = message.as_str();
712 app.push_status_toast(message, level, None);
713 // Lifecycle outbox (`[lifecycle_outbox]`): the first scriptable stall
714 // signal. Until now a wedged turn was only visible as this toast; with
715 // the outbox enabled a supervisor can react to the same moment.
716 // No-op when the feature is disabled.
717 app.lifecycle_outbox.emit(codewhale_hooks::LifecycleEvent {
718 event: "turn_stalled".to_string(),
719 kind: "turn.stalled".to_string(),
720 thread_id: stalled_session_id,
721 turn_id: stalled_turn_id,
722 item_id: None,
723 payload: serde_json::json!({
724 "message": codewhale_hooks::bounded_text(
725 message,
726 codewhale_hooks::OUTBOX_DETAIL_MAX_CHARS,
727 ),
728 "workspace": app.workspace.display().to_string(),
729 }),
730 });
731 }
732
733 pub(crate) fn recover_engine_event_disconnect(app: &mut App) -> bool {
734 restore_preparing_steers(app);
735 let had_live_work = app.is_loading
736 || app.is_compacting
737 || app.manual_compaction_queued
738 || app.is_purging
739 || matches!(app.runtime_turn_status.as_deref(), Some("in_progress"))
740 || app.pending_turn_route.is_some()
741 || app.pending_user_input_prompt.is_some()
742 || app.active_turn.is_some()
743 || app.suppress_stream_events_until_turn_complete
744 || app.streaming_message_index.is_some()
745 || app.streaming_thinking_active_entry.is_some()
746 || app
747 .active_cell
748 .as_ref()
749 .is_some_and(|cell| !cell.is_empty());
750
751 if !had_live_work {
752 return false;
753 }
754
755 settle_pending_human_requests(app);
756
757 streaming_thinking::finalize_current(app);
758 app.finalize_streaming_assistant_as_interrupted();
759 app.finalize_active_cell_as_interrupted();
760 app.streaming_state.reset();
761 app.streaming_message_index = None;
762 app.streaming_thinking_active_entry = None;
763
764 // #2739: persist partial turn before clearing state.
765 persist_recovery_snapshot(app);
766
767 app.is_loading = false;
768 app.is_compacting = false;
769 app.active_compaction = None;
770 app.manual_compaction_queued = false;
771 app.deferred_manual_compaction = None;
772 app.is_purging = false;
773 app.turn_started_at = None;
774 app.turn_last_activity_at = None;
775 app.runtime_turn_status = None;
776 app.runtime_turn_id = None;
777 app.dispatch_started_at = None;
778 app.pending_turn_route = None;
779 app.pending_auto_route_receipt = None;
780 app.active_turn = None;
781 app.suppress_stream_events_until_turn_complete = false;
782 app.user_scrolled_during_stream = false;
783
784 app.add_message(HistoryCell::Error {
785 message: "Engine stopped before completing the turn. Check ~/.codewhale/crashes and retry."
786 .to_string(),
787 severity: codewhale_error_taxonomy::ErrorSeverity::Error,
788 code: None,
789 });
790 app.push_status_toast(
791 "Engine stopped before completing the turn.",
792 StatusToastLevel::Error,
793 None,
794 );
795 true
796 }
797
798 pub(crate) fn capture_turn_started_metadata(app: &mut App, event: &EngineEvent) -> bool {
799 match event {
800 EngineEvent::TurnStarted {
801 previous_source,
802 turn_id,
803 created_at,
804 route,
805 submission_id,
806 } => {
807 let source = codewhale_engine::core::ops::SessionSnapshotSource::turn(
808 turn_id.clone(),
809 submission_id.clone(),
810 );
811 let admitted = match app.session_write_owner.as_ref() {
812 Some(codewhale_engine::session_manager::SessionWriteOwner::Submission(id)) => {
813 submission_id.as_ref() == Some(id)
814 }
815 Some(owner) => {
816 owner.matches_source(&source)
817 || previous_source
818 .as_ref()
819 .is_some_and(|previous| owner.matches_source(previous))
820 }
821 None => true,
822 };
823 if !admitted {
824 return false;
825 }
826 app.session_write_owner =
827 Some(codewhale_engine::session_manager::SessionWriteOwner::Engine(source));
828 app.ocean_completion_started_at = None;
829 let auto_route_receipt = if route.as_ref().is_some_and(|route| route.auto_model) {
830 app.pending_auto_route_receipt.take()
831 } else if route.is_some() {
832 app.pending_auto_route_receipt = None;
833 None
834 } else {
835 None
836 };
837 // Bind the prompt-suggestion authority to the receipt the engine minted
838 // from the client it installed for this turn. Deliberately not read
839 // from `config`: web config events are drained ahead of engine events,
840 // so config here may already describe a different key or endpoint than
841 // the one this turn is actually running on.
842 let suggestion_authority = route
843 .as_ref()
844 .and_then(crate::tui::prompt_suggestion::capture_route_authority);
845 app.active_turn = Some(ActiveTurnMetadata {
846 turn_id: turn_id.clone(),
847 created_at: *created_at,
848 route: route.clone(),
849 auto_route_receipt,
850 suggestion_authority,
851 });
852 app.pending_turn_route = None;
853 }
854 // The dispatch boundary is the billing truth: refresh the active turn's
855 // route with the envelope that was actually put on the wire. Receipts
856 // already taken at `TurnStarted` are preserved — this event narrows the
857 // route, it never re-opens an authority decision.
858 EngineEvent::RouteDispatched { turn_id, route } => {
859 let newer_submission = matches!(
860 app.session_write_owner.as_ref(),
861 Some(codewhale_engine::session_manager::SessionWriteOwner::Submission(_))
862 );
863 if let Some(active) = app
864 .active_turn
865 .as_mut()
866 .filter(|active| active.turn_id == *turn_id)
867 {
868 if !newer_submission && route.auto_model && active.auto_route_receipt.is_none() {
869 active.auto_route_receipt = app.pending_auto_route_receipt.take();
870 } else if !newer_submission && !route.auto_model {
871 app.pending_auto_route_receipt = None;
872 active.auto_route_receipt = None;
873 }
874 if active.suggestion_authority.is_none() {
875 active.suggestion_authority =
876 crate::tui::prompt_suggestion::capture_route_authority(route);
877 }
878 active.route = Some(route.clone());
879 }
880 }
881 EngineEvent::CompactionStarted {
882 id,
883 previous_source,
884 auto: false,
885 ..
886 } => {
887 let source = codewhale_engine::core::ops::SessionSnapshotSource::compaction(id.clone());
888 let admitted = app.session_write_owner.as_ref().is_none_or(|owner| {
889 owner.matches_source(&source)
890 || previous_source
891 .as_ref()
892 .is_some_and(|previous| owner.matches_source(previous))
893 });
894 if !admitted {
895 return false;
896 }
897 app.session_write_owner =
898 Some(codewhale_engine::session_manager::SessionWriteOwner::Engine(source));
899 }
900 _ => {}
901 }
902 true
903 }
904
905 pub(crate) fn record_turn_activity(app: &mut App, event: &EngineEvent, now: Instant) {
906 if matches!(event, EngineEvent::TurnStarted { .. }) {
907 app.turn_last_activity_at = Some(now);
908 return;
909 }
910
911 if app.is_loading || matches!(app.runtime_turn_status.as_deref(), Some("in_progress")) {
912 app.turn_last_activity_at = Some(now);
913 }
914 }
915
916 pub(crate) fn persist_offline_queue_state(app: &App) {
917 let Some(lease) = app
918 .offline_queue_lease
919 .as_ref()
920 .filter(|lease| app.current_session_id.as_deref() == Some(lease.session_id()))
921 else {
922 let lease_owner = app
923 .offline_queue_lease
924 .as_ref()
925 .map(|lease| lease.session_id());
926 if lease_owner.is_some() || !offline_queue_is_empty(app) {
927 tracing::warn!(
928 target: "persistence",
929 what = "offline-queue",
930 session_id = app.current_session_id.as_deref().unwrap_or("none"),
931 lease_owner = lease_owner.unwrap_or("none"),
932 queued = app.queued_messages.len(),
933 draft = app.queued_draft.is_some(),
934 "offline queue not persisted: this window holds no queue lease for the current session",
935 );
936 }
937 return;
938 };
939 if offline_queue_is_empty(app) {
940 persistence_actor::persist(PersistRequest::ClearOfflineQueue {
941 lease: Arc::clone(lease),
942 });
943 return;
944 }
945 let (messages, draft) = offline_queue_projection(app);
946 let converted = messages
947 .iter()
948 .map(queued_ui_to_session)
949 .collect::<Result<Vec<_>>>();
950 let draft = draft.as_ref().map(queued_ui_to_session).transpose();
951 let (messages, draft) = match converted
952 .and_then(|messages| draft.map(|draft| (messages, draft)))
953 {
954 Ok(value) => value,
955 Err(error) => {
956 tracing::error!(target: "persistence", %error, "offline queue serialization refused");
957 return;
958 }
959 };
960 let state = OfflineQueueState {
961 messages,
962 draft,
963 ..OfflineQueueState::default()
964 };
965 persistence_actor::persist(PersistRequest::OfflineQueue {
966 state,
967 lease: Arc::clone(lease),
968 });
969 }
970
971 pub(crate) fn restore_queued_message(
972 app: &mut App,
973 index: Option<usize>,
974 was_held: bool,
975 message: QueuedMessage,
976 ) {
977 if message.extension_command.is_some() {
978 app.restore_unsent_message(message);
979 return;
980 }
981 if let Some(index) = index.or_else(|| was_held.then_some(app.held_restored_queue))
982 && index <= app.queued_messages.len()
983 {
984 if was_held || index < app.held_restored_queue {
985 app.held_restored_queue += 1;
986 }
987 app.queued_messages.insert(index, message);
988 } else {
989 app.queue_message(message);
990 }
991 }
992
993 pub(crate) fn restore_queued_or_draft_message(
994 app: &mut App,
995 recovery: DispatchRecovery,
996 message: QueuedMessage,
997 ) {
998 if message.extension_command.is_some() {
999 app.restore_unsent_message(message);
1000 return;
1001 }
1002 match recovery {
1003 DispatchRecovery::Draft => {
1004 app.stash_typed_draft_before_restore();
1005 app.input.clone_from(&message.display);
1006 app.cursor_position = app.input.chars().count();
1007 app.active_skill = message.skill_instruction.clone();
1008 app.active_skill_provenance = message.skill_provenance.clone();
1009 app.queued_draft = Some(message);
1010 app.queued_draft_was_held = false;
1011 app.needs_redraw = true;
1012 }
1013 DispatchRecovery::Queued {
1014 restore_index,
1015 was_held,
1016 } => {
1017 restore_queued_message(app, restore_index, was_held, message);
1018 }
1019 DispatchRecovery::Immediate | DispatchRecovery::Initial => app.queue_message(message),
1020 }
1021 }
1022
1023 pub(crate) fn recover_unstarted_external_message(
1024 app: &mut App,
1025 message: QueuedMessage,
1026 recovery: DispatchRecovery,
1027 error: &str,
1028 ) {
1029 app.dispatch_in_flight = false;
1030 match recovery {
1031 DispatchRecovery::Immediate | DispatchRecovery::Initial => {
1032 restore_failed_immediate_submit(app, message, &anyhow::Error::msg(error.to_string()));
1033 }
1034 DispatchRecovery::Draft => {
1035 restore_queued_or_draft_message(app, recovery, message);
1036 app.show_command_result(
1037 format!("{error}; queued draft restored"),
1038 StatusToastLevel::Error,
1039 );
1040 }
1041 DispatchRecovery::Queued {
1042 restore_index,
1043 was_held,
1044 } => {
1045 restore_queued_message(app, restore_index, was_held, message);
1046 app.show_command_result(
1047 format!(
1048 "{error}; {} queued follow-up(s) restored",
1049 app.queued_message_count()
1050 ),
1051 StatusToastLevel::Error,
1052 );
1053 }
1054 }
1055 app.needs_redraw = true;
1056 }
1057
1058 pub(crate) fn restore_message_submit_denial(
1059 app: &mut App,
1060 message: QueuedMessage,
1061 recovery: DispatchRecovery,
1062 denial: String,
1063 ) {
1064 app.dispatch_in_flight = false;
1065 match recovery {
1066 DispatchRecovery::Immediate | DispatchRecovery::Initial => {
1067 app.restore_unsent_message(message);
1068 }
1069 DispatchRecovery::Draft => {
1070 restore_queued_or_draft_message(app, recovery, message);
1071 }
1072 DispatchRecovery::Queued {
1073 restore_index,
1074 was_held,
1075 } => {
1076 restore_queued_message(app, restore_index, was_held, message);
1077 }
1078 }
1079 app.push_status_toast(denial, StatusToastLevel::Warning, Some(6_000));
1080 app.needs_redraw = true;
1081 }
1082
1083 /// Resume one recent-work row from the startup card by session id. Mirrors
1084 /// `/resume <id>`: the card dissolves and the saved session loads through
1085 /// the normal `LoadSession` path; a session that vanished behind the card
1086 /// leaves the card up with a status saying why instead of stranding the
1087 /// user on an empty stage.
1088 pub(crate) fn resume_launch_session(app: &mut App, session_id: &str) -> commands::CommandResult {
1089 let failed = |app: &mut App, err: &str| {
1090 app.launch.status = Some(
1091 app.tr(MessageId::LaunchResumeFailed)
1092 .replace("{error}", err),
1093 );
1094 commands::CommandResult::ok()
1095 };
1096 let manager = match codewhale_engine::session_manager::SessionManager::default_location() {
1097 Ok(manager) => manager,
1098 Err(err) => return failed(app, &err.to_string()),
1099 };
1100 let saved = match manager.load_session_snapshot(session_id) {
1101 Ok(saved) => saved,
1102 Err(err) => return failed(app, &err.to_string()),
1103 };
1104 let path = manager
1105 .sessions_dir()
1106 .join(format!("{}.json", saved.metadata.id));
1107 if !path.exists() {
1108 return failed(app, "saved session file is gone");
1109 }
1110 app.launch.dissolve_card(app.ambient_clock_ms);
1111 commands::CommandResult::action(AppAction::LoadSession(path))
1112 }
1113
1114 pub(crate) fn begin_launch_session(
1115 app: &mut App,
1116 workspace: Option<PathBuf>,
1117 ) -> commands::CommandResult {
1118 let session_id = uuid::Uuid::new_v4().to_string();
1119 let transition = match prepare_offline_queue_transition(app, &session_id) {
1120 Ok(transition) => transition,
1121 Err(error) => return commands::CommandResult::error(error),
1122 };
1123 install_offline_queue_transition(app, transition);
1124 if let Some(workspace) = workspace {
1125 app.workspace = workspace;
1126 }
1127 app.set_current_session_id(Some(session_id.clone()));
1128 if let Err(error) = expect_fresh_session(app, &session_id) {
1129 return commands::CommandResult::error(error);
1130 }
1131 app.current_session_metadata = None;
1132 app.window_title = None;
1133 app.composer_color = None;
1134 app.session_title = Some(app.tr(MessageId::SessionsNewSessionTitle).into_owned());
1135 let motion = app.motion_policy().allows_decorative();
1136 app.launch
1137 .leave_for_new_session(app.ambient_clock_ms, motion);
1138 app.launch.status = None;
1139 app.retire_deferred_prompt_notice();
1140 commands::CommandResult::action(AppAction::SyncSession {
1141 session_id: Some(session_id),
1142 messages: Vec::new(),
1143 system_prompt: None,
1144 model: app.model.clone(),
1145 workspace: app.workspace.clone(),
1146 mode: app.mode,
1147 agent_preset: app.agent_preset(),
1148 })
1149 }
1150
1151 /// Point the manager the App currently owns at `workspace`.
1152 ///
1153 /// Reads through the slot rather than a captured handle: a session switch can
1154 /// replace the manager, and a stale handle would update a store this host no
1155 /// longer holds.
1156 pub(crate) async fn sync_runtime_workspace_state(app: &App, workspace: PathBuf) {
1157 if let Some(current) = app.runtime_services.task_manager.as_ref() {
1158 current.set_default_workspace(workspace).await;
1159 }
1160 }
1161
1162 pub(crate) async fn switch_workspace(
1163 app: &mut App,
1164 engine_handle: &mut EngineHandle,
1165 config: &Config,
1166 workspace: PathBuf,
1167 ) {
1168 if app.is_loading {
1169 let busy = app.tr(MessageId::WorkspaceSwitchBusy).into_owned();
1170 app.show_command_result(busy.clone(), StatusToastLevel::Warning);
1171 app.add_message(HistoryCell::System { content: busy });
1172 return;
1173 }
1174
1175 let shown = workspace.display().to_string();
1176 if app.workspace == workspace {
1177 app.show_command_result(
1178 app.tr(MessageId::WorkspaceUnchanged)
1179 .replace("{path}", &shown),
1180 StatusToastLevel::Info,
1181 );
1182 return;
1183 }
1184
1185 apply_workspace_runtime_state(app, config, workspace.clone());
1186 sync_runtime_workspace_state(app, workspace.clone()).await;
1187
1188 replace_tui_engine(app, config, engine_handle).await;
1189 if !app.api_messages.is_empty() {
1190 let _ = engine_handle
1191 .send(Op::SyncSession {
1192 expected: None,
1193 control: app.session_sync_control(),
1194 session_id: app.current_session_id.clone(),
1195 messages: app.api_messages.as_ref().clone(),
1196 system_prompt: app.system_prompt.clone(),
1197 system_prompt_override: false,
1198 model: app.model.clone(),
1199 workspace: workspace.clone(),
1200 mode: app.mode,
1201 agent_preset: app.agent_preset(),
1202 })
1203 .await;
1204 }
1205
1206 let switched = app
1207 .tr(MessageId::WorkspaceSwitched)
1208 .replace("{path}", &shown);
1209 app.add_message(HistoryCell::System { content: switched });
1210 app.show_command_result(
1211 app.tr(MessageId::WorkspaceStatus).replace("{path}", &shown),
1212 StatusToastLevel::Success,
1213 );
1214 }
1215
1216 /// A message submitted with no usable key (#6566). Nothing reached a model:
1217 /// the caller has already rolled back the optimistic echo, so the text goes
1218 /// back into the composer — not lost, and sent once when the person presses
1219 /// Enter after connecting, not doubled. One transcript line says what
1220 /// happened and the provider picker opens.
1221 ///
1222 /// A new user never chose a provider, so the line does not name the built-in
1223 /// default's key or print its help page. A returning user whose saved route
1224 /// lost its key also gets the one command that saves it.
1225 pub(crate) fn keep_unsent_message_for_connect(app: &mut App, message: QueuedMessage, error: &str) {
1226 if message.extension_command.is_some() {
1227 app.restore_unsent_message(message);
1228 app.show_command_result(error.to_string(), StatusToastLevel::Error);
1229 return;
1230 }
1231 tracing::warn!(
1232 error = %error,
1233 "user message not sent: no usable credential; restored to composer"
1234 );
1235 app.restore_unsent_message(message);
1236
1237 let new_user = app.onboarding_had_provider_step;
1238 let mut content = app.tr(MessageId::DispatchNotSentNoModel).into_owned();
1239 if !new_user
1240 && let Some(save) = error
1241 .lines()
1242 .map(str::trim)
1243 .find(|line| line.starts_with("codewhale auth set"))
1244 {
1245 content.push('\n');
1246 content.push_str(
1247 &app.tr(MessageId::DispatchNotSentSaveKey)
1248 .replace("{command}", save),
1249 );
1250 }
1251 app.add_message(HistoryCell::System { content });
1252 app.onboarding_needs_api_key = true;
1253 // From the composer, the saved route is the one missing its key: this is
1254 // missing-key recovery, as after `/logout`, so Esc returns to the
1255 // composer. A first-run launch with an initial prompt is still in
1256 // onboarding and keeps its remaining steps (Esc walks back as before).
1257 if app.onboarding == OnboardingState::None {
1258 app.onboarding_missing_key_recovery = true;
1259 app.onboarding_provider = app.api_provider;
1260 }
1261 app.onboarding = OnboardingState::Provider;
1262 // The footer keeps the provider's full message for a returning user; a
1263 // new user's footer says only that no model is connected.
1264 let reason = if new_user {
1265 app.tr(MessageId::LaunchNoModelConnected).into_owned()
1266 } else {
1267 error.to_string()
1268 };
1269 let status = app
1270 .tr(MessageId::DispatchNotSentStatus)
1271 .replace("{reason}", &reason);
1272 app.set_sticky_status(
1273 status,
1274 StatusToastLevel::Error,
1275 Some(App::STICKY_ERROR_TTL_MS),
1276 );
1277 app.needs_redraw = true;
1278 }
1279
1280 /// The engine reported this turn's message as never sent: a key rejected
1281 /// before any model output (#6566). Take the message back, and its bubble
1282 /// out of the live transcript when nothing has landed after it, so sending it
1283 /// again shows it once. `None` when no dispatched message is on record.
1284 pub(crate) fn take_back_unsent_submission(app: &mut App) -> Option<QueuedMessage> {
1285 let submission = app.unanswered_submission.take()?;
1286 let cell = submission.history_cell;
1287 let bubble_is_last = cell + 1 == app.history.len()
1288 && matches!(
1289 &app.history[cell],
1290 HistoryCell::User { content } if content == &submission.message.display
1291 );
1292 if bubble_is_last {
1293 app.truncate_history_to(cell);
1294 }
1295 Some(submission.message)
1296 }
1297
1298 pub(crate) fn restore_failed_immediate_submit(
1299 app: &mut App,
1300 message: QueuedMessage,
1301 error: &anyhow::Error,
1302 ) {
1303 if message.extension_command.is_some() {
1304 app.restore_unsent_message(message);
1305 app.show_command_result(error.to_string(), StatusToastLevel::Error);
1306 return;
1307 }
1308 tracing::warn!(
1309 error = %error,
1310 "immediate user message dispatch failed; restored composer"
1311 );
1312 app.stash_typed_draft_before_restore();
1313 app.input = message.display;
1314 app.cursor_position = app.input.chars().count();
1315 app.active_skill = message.skill_instruction;
1316 app.active_skill_provenance = message.skill_provenance;
1317 let status = tr(app.ui_locale, MessageId::ComposerDispatchFailedRestored)
1318 .replace("{error}", &error.to_string());
1319 app.set_sticky_status(
1320 status,
1321 StatusToastLevel::Error,
1322 Some(App::STICKY_ERROR_TTL_MS),
1323 );
1324 app.needs_redraw = true;
1325 }
1326
1327 /// Show the default recommended Hotbar slots. Since #3807 an absent `hotbar`
1328 /// key means "hidden", so `/hotbar on` persists the explicit default bindings
1329 /// rather than deleting the key. This is an explicit reset, so any custom
1330 /// bindings are replaced with the recommended set.
1331 pub(crate) fn restore_hotbar_defaults(app: &mut App, config: &mut Config) {
1332 let defaults = codewhale_config::default_hotbar_bindings_toml();
1333 match codewhale_runtime::config_persistence::persist_hotbar_bindings(
1334 app.config_path.as_deref(),
1335 &defaults,
1336 ) {
1337 Ok(path) => {
1338 config.hotbar = Some(defaults);
1339 app.show_owned_command_result(
1340 StatusToastKind::HotbarSettings,
1341 format!(
1342 "Hotbar enabled with the default slots ({}). Customize with `/hotbar`.",
1343 path.display()
1344 ),
1345 StatusToastLevel::Success,
1346 );
1347 }
1348 Err(err) => {
1349 app.show_owned_command_result(
1350 StatusToastKind::HotbarSettings,
1351 format!("Failed to enable the Hotbar: {err}"),
1352 StatusToastLevel::Error,
1353 );
1354 app.add_message(HistoryCell::System {
1355 content: format!("Failed to enable the Hotbar: {err}"),
1356 });
1357 }
1358 }
1359 app.needs_redraw = true;
1360 }
1361
1362 pub(crate) fn persist_rules_from_approval(
1363 app: &mut App,
1364 config: &mut Config,
1365 rules: &[codewhale_config::ToolAskRule],
1366 ) -> bool {
1367 let action = rules.first().map(|rule| rule.action);
1368 match codewhale_config::ConfigStore::load(app.config_path.clone()).and_then(|mut store| {
1369 let added = match action {
1370 Some(codewhale_execpolicy::PermissionAction::Ask) => store.append_ask_rules(rules)?,
1371 Some(codewhale_execpolicy::PermissionAction::Allow) => {
1372 store.append_allow_rules(rules)?
1373 }
1374 Some(codewhale_execpolicy::PermissionAction::Deny) => {
1375 anyhow::bail!("the approval UI cannot persist deny rules")
1376 }
1377 None => 0,
1378 };
1379 let permissions_path = store.permissions_path();
1380 config
1381 .exec_policy_engine
1382 .set_ruleset(store.permissions().ruleset());
1383 Ok((added, permissions_path))
1384 }) {
1385 Ok((added, path)) if added > 0 => {
1386 let action = match action {
1387 Some(codewhale_execpolicy::PermissionAction::Allow) => "allow",
1388 _ => "ask",
1389 };
1390 app.show_owned_command_result(
1391 StatusToastKind::PermissionRule,
1392 format!(
1393 "Saved {added} {action} permission rule(s) to {}",
1394 path.display()
1395 ),
1396 StatusToastLevel::Success,
1397 );
1398 true
1399 }
1400 Ok((_added, path)) => {
1401 let action = match action {
1402 Some(codewhale_execpolicy::PermissionAction::Allow) => "Allow",
1403 _ => "Ask",
1404 };
1405 app.show_owned_command_result(
1406 StatusToastKind::PermissionRule,
1407 format!(
1408 "{action} permission rule already saved in {}",
1409 path.display()
1410 ),
1411 StatusToastLevel::Info,
1412 );
1413 true
1414 }
1415 Err(err) => {
1416 app.show_owned_command_result(
1417 StatusToastKind::PermissionRule,
1418 format!("Failed to save permission rule: {err:#}"),
1419 StatusToastLevel::Error,
1420 );
1421 false
1422 }
1423 }
1424 }
1425
1426 pub(crate) fn mirror_saved_model_in_config(
1427 config: &mut Config,
1428 identity: &ProviderIdentity,
1429 model: String,
1430 ) -> Result<(), String> {
1431 config.verify_provider_identity(identity)?;
1432 if identity.provider == ProviderKind::Deepseek {
1433 config.default_text_model = Some(model);
1434 return Ok(());
1435 }
1436 config
1437 .set_provider_model_override(identity, Some(model))
1438 .map_err(|error| error.to_string())
1439 }
1440
1441 pub(crate) fn mirror_saved_context_window_in_config(
1442 config: &mut Config,
1443 identity: &ProviderIdentity,
1444 context_window: u32,
1445 ) -> Result<(), String> {
1446 config.verify_provider_identity(identity)?;
1447 if identity.provider == ProviderKind::Moonshot {
1448 config
1449 .provider_config_for_mut(identity)
1450 .map_err(|error| error.to_string())?
1451 .context_window = Some(context_window);
1452 }
1453 Ok(())
1454 }
1455
1456 pub(crate) fn mirror_saved_api_key_in_config(
1457 config: &mut Config,
1458 identity: &ProviderIdentity,
1459 api_key: String,
1460 ) -> Result<(), String> {
1461 config.verify_provider_identity(identity)?;
1462 let provider = identity.provider;
1463 // These shared auth leaves are intrinsic released credential contracts;
1464 // presentation names cannot select them.
1465 if provider == ProviderKind::Deepseek {
1466 let auth_owner = config.builtin_provider_identity(ProviderKind::Deepseek)?;
1467 config
1468 .set_provider_api_key_override(&auth_owner, Some(api_key))
1469 .map_err(|error| error.to_string())?;
1470 config.auth_mode = Some("api_key".to_string());
1471 return Ok(());
1472 }
1473 let pin_kimi_code_base_url = provider == ProviderKind::Moonshot
1474 && config.provider_config_for(identity).is_some_and(|entry| {
1475 codewhale_runtime::config::provider_config_uses_kimi_imported_token(entry)
1476 && entry
1477 .base_url
1478 .as_deref()
1479 .is_none_or(|base_url| base_url.trim().is_empty())
1480 });
1481 let auth_owner = if provider == ProviderKind::SiliconflowCN {
1482 config.builtin_provider_identity(ProviderKind::Siliconflow)?
1483 } else {
1484 identity.clone()
1485 };
1486 let entry = config
1487 .provider_config_for_mut(&auth_owner)
1488 .map_err(|error| error.to_string())?;
1489 if pin_kimi_code_base_url {
1490 entry.base_url =
1491 Some(codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL.to_string());
1492 }
1493 entry.auth_mode = Some("api_key".to_string());
1494 entry.api_key = Some(api_key);
1495 entry.external_credentials = None;
1496 if matches!(provider, ProviderKind::Xai | ProviderKind::Anthropic) {
1497 entry.oauth_credential_generation = None;
1498 }
1499 Ok(())
1500 }
1501
1502 pub(crate) fn loaded_session_requires_engine_respawn(
1503 app: &App,
1504 previous_provider: ProviderKind,
1505 previous_provider_identity: &str,
1506 previous_workspace: &Path,
1507 ) -> bool {
1508 app.api_provider != previous_provider
1509 || app.provider_identity_for_persistence() != previous_provider_identity
1510 || app.workspace != previous_workspace
1511 }
1512
1513 pub(crate) fn restore_loaded_session_provider(
1514 app: &mut App,
1515 config: &mut Config,
1516 identity: ProviderIdentity,
1517 ) -> Result<(), String> {
1518 let provider = identity.provider;
1519 config.scope_to_provider_identity(&identity)?;
1520 app.set_provider_identity_record(identity.clone());
1521 app.billing_presentation = codewhale_engine::route_billing::for_route(config, &identity);
1522 app.max_subagents = config
1523 .max_subagents_for_provider(&identity)
1524 .clamp(1, codewhale_runtime::config::MAX_SUBAGENTS);
1525 app.provider_chain = (identity.key.as_str() == provider.as_str()
1526 && provider != ProviderKind::Antigravity)
1527 .then(|| codewhale_config::ProviderChain::new(provider, &config.fallback_providers))
1528 .filter(|chain| chain.providers().len() > 1);
1529 app.last_fallback_reason = None;
1530 app.model_ids_passthrough = config.model_ids_pass_through();
1531 if !app.auto_model {
1532 let requested = app
1533 .reasoning_effort_preference
1534 .unwrap_or(app.reasoning_effort);
1535 app.reasoning_effort = requested.normalize_for_route_identity(
1536 provider,
1537 identity.key.as_str(),
1538 &config.active_route_base_url(),
1539 &app.model,
1540 );
1541 }
1542 app.set_active_context_window_override(config, &identity);
1543 app.active_route_limits = app.context_window_override_limits();
1544 app.active_route_base_url = config.active_route_base_url();
1545 app.active_context_window = app.configured_context_window_for(&app.model);
1546 app.active_context_window_source = app
1547 .configured_context_window_for(&app.model)
1548 .map(|resolution| resolution.source)
1549 .unwrap_or(codewhale_engine::route_runtime::ContextWindowSource::Fallback);
1550 Ok(())
1551 }
1552
1553 pub(crate) fn resolve_loaded_session_route(app: &mut App, config: &Config) {
1554 let identity = match app
1555 .admitted_provider_identity()
1556 .cloned()
1557 .and_then(|identity| {
1558 config.verify_provider_identity(&identity)?;
1559 Ok(identity)
1560 }) {
1561 Ok(identity) => identity,
1562 Err(reason) => {
1563 app.push_status_toast(reason, StatusToastLevel::Error, Some(8_000));
1564 return;
1565 }
1566 };
1567 app.set_active_context_window_override(config, &identity);
1568 if app.auto_model {
1569 app.active_route_limits = app.context_window_override_limits();
1570 app.active_route_base_url = config.active_route_base_url();
1571 app.active_context_window = app.configured_context_window_for(&app.model);
1572 app.active_context_window_source = app
1573 .configured_context_window_for(&app.model)
1574 .map(|resolution| resolution.source)
1575 .unwrap_or(codewhale_engine::route_runtime::ContextWindowSource::Fallback);
1576 return;
1577 }
1578
1579 match codewhale_engine::route_runtime::resolve_runtime_route_for_identity(
1580 config,
1581 &identity,
1582 Some(&app.model),
1583 ) {
1584 Ok(resolution) => {
1585 app.set_active_route_resolution(
1586 resolution.candidate.endpoint().base_url.clone(),
1587 resolution.candidate.limits(),
1588 resolution.context_window,
1589 );
1590 }
1591 Err(_) => {
1592 app.active_route_limits = app.context_window_override_limits();
1593 app.active_route_base_url = config.active_route_base_url();
1594 app.active_context_window = app.configured_context_window_for(&app.model);
1595 app.active_context_window_source = app
1596 .configured_context_window_for(&app.model)
1597 .map(|resolution| resolution.source)
1598 .unwrap_or(codewhale_engine::route_runtime::ContextWindowSource::Fallback);
1599 }
1600 }
1601 }
1602
1603 /// Derive a short display title from the API message list.
1604 ///
1605 /// Tries several strategies in order:
1606 /// 1. If the first user message starts with a known slash command (`/goal`,
1607 /// `/fleet`, `/workflow`, etc.), use the command + first argument.
1608 /// 2. Otherwise, take the first meaningful line and cut it at a natural
1609 /// phrase boundary (period, comma, colon, or word boundary) within
1610 /// `SESSION_TITLE_MAX_CHARS`, never splitting mid-word.
1611 ///
1612 /// Never leaks raw prompt text — the result is always a concise label.
1613 pub(crate) fn derive_session_title(messages: &[Message]) -> Option<String> {
1614 let text = codewhale_engine::session_manager::conversation_title_prompt(messages)?;
1615
1616 let first_line = codewhale_engine::session_manager::sanitize_session_title(
1617 text.lines().next().unwrap_or("").trim(),
1618 );
1619 let first_line = first_line.trim();
1620 if first_line.is_empty() {
1621 return None;
1622 }
1623
1624 // Slash command: extract command name + first reasonable argument.
1625 if let Some(rest) = first_line.strip_prefix('/') {
1626 let parts: Vec<&str> = rest.split_whitespace().collect();
1627 return match parts.as_slice() {
1628 [] => None,
1629 [cmd] => Some(format!("/{cmd}")),
1630 [cmd, arg, ..] => {
1631 let arg_short = short_title_truncate(arg, 24);
1632 Some(format!("/{cmd} {arg_short}"))
1633 }
1634 };
1635 }
1636
1637 Some(short_title_truncate(first_line, SESSION_TITLE_MAX_CHARS))
1638 }
1639
1640 #[cfg(test)]
1641 mod derived_title_tests {
1642 use super::*;
1643 use codewhale_models::Role;
1644
1645 fn user(text: &str) -> Message {
1646 Message {
1647 role: Role::User,
1648 content: vec![ContentBlock::Text {
1649 text: text.to_string(),
1650 cache_control: None,
1651 }],
1652 }
1653 }
1654
1655 #[test]
1656 fn derived_titles_drop_terminal_controls_and_bidi_format_chars() {
1657 // The first user message can carry pasted escape sequences; the
1658 // derived session name must never persist them.
1659 let msgs = [user("Fix \u{1b}]0;PWNED\u{7}the\u{202e} build 会議")];
1660 assert_eq!(
1661 derive_session_title(&msgs).as_deref(),
1662 Some("Fix ]0;PWNEDthe build 会議")
1663 );
1664 // Controls alone leave no title to derive.
1665 assert_eq!(derive_session_title(&[user("\u{1b}\u{7}\u{200b}")]), None);
1666 }
1667
1668 #[test]
1669 fn live_title_uses_the_same_user_prompt_after_runtime_handoffs() {
1670 let handoff = codewhale_engine::runtime_handoff::operate_contract_runtime_message();
1671 assert_eq!(derive_session_title(std::slice::from_ref(&handoff)), None);
1672 let messages = [handoff, user("/goal Fix the diagnostic display")];
1673 assert_eq!(
1674 derive_session_title(&messages).as_deref(),
1675 Some("/goal Fix")
1676 );
1677 assert_eq!(
1678 codewhale_engine::session_manager::conversation_title_prompt(&messages),
1679 Some("/goal Fix the diagnostic display")
1680 );
1681 }
1682 }
1683
1684 #[cfg(test)]
1685 mod stall_outbox_tests {
1686 use super::*;
1687 use crate::tui::app::TuiOptions;
1688
1689 /// `recover_stalled_runtime_turn` must emit a `turn_stalled` lifecycle
1690 /// outbox event naming the wedged turn — the first scriptable stall
1691 /// signal. The outbox is opt-in, so the test enables it through config.
1692 #[tokio::test]
1693 async fn stalled_turn_emits_turn_stalled_outbox_event() {
1694 let _lock = crate::test_support::lock_test_env();
1695 let dir = tempfile::tempdir().expect("tempdir");
1696 let outbox_path = dir.path().join("outbox.jsonl");
1697
1698 let config = {
1699 let __cw_config_init_0_0 = Some(codewhale_config::LifecycleOutboxToml {
1700 path: Some(outbox_path.clone()),
1701 webhook_url: None,
1702 webhook_token: None,
1703 });
1704 let mut __cw_config_init_0_value: Config = Default::default();
1705 __cw_config_init_0_value.lifecycle_outbox = __cw_config_init_0_0;
1706 __cw_config_init_0_value
1707 };
1708 let options = TuiOptions {
1709 start_in_agent_mode: true,
1710 ..crate::tui::test_support::test_tui_options(dir.path())
1711 };
1712 let mut app = App::new(options, &config);
1713 assert!(app.lifecycle_outbox.is_enabled());
1714 let expected_workspace = app.workspace.display().to_string();
1715
1716 app.runtime_turn_id = Some("turn-1".to_string());
1717 app.runtime_turn_status = Some("in_progress".to_string());
1718 app.is_loading = true;
1719 recover_stalled_runtime_turn(
1720 &mut app,
1721 "Turn stalled — no completion signal received",
1722 StatusToastLevel::Error,
1723 );
1724
1725 // The outbox writer task drains asynchronously; wait for the line.
1726 let mut lines = Vec::new();
1727 for _ in 0..200 {
1728 if let Ok(text) = tokio::fs::read_to_string(&outbox_path).await {
1729 lines = text
1730 .lines()
1731 .map(|line| serde_json::from_str::<serde_json::Value>(line).expect("json"))
1732 .collect();
1733 if !lines.is_empty() {
1734 break;
1735 }
1736 }
1737 tokio::time::sleep(std::time::Duration::from_millis(10)).await;
1738 }
1739
1740 assert_eq!(lines.len(), 1, "expected one turn_stalled outbox line");
1741 let line = &lines[0];
1742 assert_eq!(line["event"], "turn_stalled");
1743 assert_eq!(line["kind"], "turn.stalled");
1744 assert_eq!(line["turn_id"], "turn-1");
1745 assert_eq!(line["schema_version"], 1);
1746 assert_eq!(line["seq"], 1);
1747 // Every payload carries the workspace for consumer-side routing.
1748 assert_eq!(
1749 line["payload"]["workspace"],
1750 serde_json::json!(expected_workspace)
1751 );
1752 // The stall message is engine-authored and safe, but still bounded
1753 // and never raw tool/environment content.
1754 let message = line["payload"]["message"].as_str().expect("message");
1755 assert!(message.contains("stalled"));
1756 assert!(
1757 message.chars().count() <= codewhale_hooks::OUTBOX_DETAIL_MAX_CHARS,
1758 "stall message must be bounded"
1759 );
1760 }
1761
1762 /// A disabled outbox (config without a path) must make stall recovery
1763 /// behave exactly as before: the toast still lands, no file is written.
1764 #[tokio::test]
1765 async fn stalled_turn_without_outbox_config_writes_nothing() {
1766 let _lock = crate::test_support::lock_test_env();
1767 let dir = tempfile::tempdir().expect("tempdir");
1768 let options = TuiOptions {
1769 start_in_agent_mode: true,
1770 ..crate::tui::test_support::test_tui_options(dir.path())
1771 };
1772 let mut app = App::new(options, &Config::default());
1773 assert!(!app.lifecycle_outbox.is_enabled());
1774
1775 app.runtime_turn_id = Some("turn-1".to_string());
1776 app.runtime_turn_status = Some("in_progress".to_string());
1777 app.is_loading = true;
1778 recover_stalled_runtime_turn(
1779 &mut app,
1780 "Turn stalled — no completion signal received",
1781 StatusToastLevel::Error,
1782 );
1783
1784 // Recovery still clears the wedged turn state and posts the toast.
1785 assert!(app.runtime_turn_id.is_none());
1786 assert!(!app.is_loading);
1787 assert!(!app.status_toasts.is_empty());
1788 assert!(
1789 !dir.path().join("outbox.jsonl").exists(),
1790 "no outbox file must be created when the feature is off"
1791 );
1792 }
1793 }
1794
1795 #[cfg(test)]
1796 mod launch_resume_tests {
1797 use super::*;
1798
1799 /// A recent-work row that vanished behind the card must leave the card
1800 /// up with a status — never strand the user on an empty stage.
1801 #[test]
1802 fn resume_missing_session_leaves_the_card_up_with_a_status() {
1803 let dir = tempfile::tempdir().unwrap();
1804 let mut app = App::new(
1805 crate::tui::test_support::test_tui_options(dir.path()),
1806 &Config::default(),
1807 );
1808 app.launch.visible = true;
1809 let result = resume_launch_session(&mut app, "no-such-session-000000");
1810 assert!(result.action.is_none(), "nothing to load");
1811 assert!(app.launch.visible, "the card stays up");
1812 let status = app.launch.status.as_deref().expect("a status");
1813 assert!(
1814 status.contains("Resume failed"),
1815 "the status says why: {status}"
1816 );
1817 }
1818
1819 /// U1 / #6566: a keyless first message goes back into the composer, leaves
1820 /// one durable transcript line, opens the provider picker, and a later
1821 /// routine acknowledgement ("Auto-compaction enabled") does not wipe the
1822 /// error from the footer.
1823 #[test]
1824 fn keyless_submit_leaves_a_durable_recovery_that_config_acks_cannot_erase() {
1825 let dir = tempfile::tempdir().unwrap();
1826 let mut app = App::new(
1827 crate::tui::test_support::test_tui_options(dir.path()),
1828 &Config::default(),
1829 );
1830 app.onboarding_had_provider_step = true;
1831 let cells_before = app.history.len();
1832 keep_unsent_message_for_connect(
1833 &mut app,
1834 crate::tui::app::QueuedMessage::new("hello".to_string(), None),
1835 "DeepSeek API key not found",
1836 );
1837 assert_eq!(app.input, "hello", "the unsent message is not lost");
1838 assert_eq!(app.history.len(), cells_before + 1);
1839 let Some(HistoryCell::System { content }) = app.history.last() else {
1840 panic!("keyless submit must leave a transcript line");
1841 };
1842 assert!(content.starts_with("No model is connected"), "{content}");
1843 // A new user never chose DeepSeek; the line must not blame its key.
1844 assert!(!content.contains("DeepSeek"), "{content}");
1845 assert_eq!(app.onboarding, OnboardingState::Provider);
1846 assert!(app.onboarding_needs_api_key);
1847
1848 app.show_command_result(
1849 "Make room automatically: on".to_string(),
1850 StatusToastLevel::Info,
1851 );
1852 let shown = app
1853 .active_status_toast(crate::tui::underwater::ShellPhase::Idle)
1854 .expect("footer notice");
1855 assert_eq!(shown.level, StatusToastLevel::Error);
1856 assert!(shown.text.contains("Message not sent"), "{}", shown.text);
1857 assert!(!shown.text.contains("DeepSeek"), "{}", shown.text);
1858 }
1859
1860 /// A returning user's line names the command that saves the missing key,
1861 /// and Esc from the picker it opens returns to the composer with the
1862 /// message still there, not to the welcome screen.
1863 #[test]
1864 fn keyless_submit_names_the_key_and_esc_returns_to_the_composer() {
1865 let dir = tempfile::tempdir().unwrap();
1866 let mut app = App::new(
1867 crate::tui::test_support::test_tui_options(dir.path()),
1868 &Config::default(),
1869 );
1870 app.onboarding = OnboardingState::None;
1871 app.onboarding_missing_key_recovery = false;
1872 app.onboarding_had_provider_step = false;
1873 keep_unsent_message_for_connect(
1874 &mut app,
1875 crate::tui::app::QueuedMessage::new("hello".to_string(), None),
1876 "DeepSeek API key not found.\n\n 1. Get a key: https://platform.deepseek.com/api_keys\n 2. Save it (works in every folder, no OS prompts):\n codewhale auth set --provider deepseek\n\n Alternatives:\n • export DEEPSEEK_API_KEY=<your-key>. Failed to configure provider route deepseek / deepseek-flash.",
1877 );
1878 let Some(HistoryCell::System { content }) = app.history.last() else {
1879 panic!("keyless submit must leave a transcript line");
1880 };
1881 assert!(
1882 content.contains("codewhale auth set --provider deepseek"),
1883 "{content}"
1884 );
1885 assert!(content.contains("F3"), "{content}");
1886 // The footer keeps the full help page; the transcript keeps two facts.
1887 assert!(!content.contains("Alternatives"), "{content}");
1888 assert!(!content.contains("Failed to configure"), "{content}");
1889 assert!(app.onboarding_missing_key_recovery);
1890 assert!(app.onboarding_recovers_configured_route());
1891
1892 back_from_provider_onboarding(&mut app);
1893 assert_eq!(app.onboarding, OnboardingState::None);
1894 assert!(app.onboarding_needs_api_key);
1895 assert_eq!(app.input, "hello");
1896 }
1897
1898 #[test]
1899 fn new_session_owns_input_and_hits_before_departing_home_ink_settles() {
1900 let area = ratatui::layout::Rect::new(0, 0, 106, 39);
1901 for reduced in [false, true] {
1902 let dir = tempfile::tempdir().unwrap();
1903 let mut app = App::new(
1904 crate::tui::test_support::test_tui_options(dir.path()),
1905 &Config::default(),
1906 );
1907 app.fancy_animations = true;
1908 app.low_motion = reduced;
1909 app.onboarding = crate::tui::app::OnboardingState::None;
1910 app.launch.visible = true;
1911 app.ui_locale = codewhale_localization::Locale::En;
1912 app.ambient_clock_ms = 500;
1913 crate::tui::underwater::refresh_launch_row_hitboxes(&mut app, area);
1914 assert!(!app.launch.row_hitboxes.is_empty());
1915 let result = begin_launch_session(&mut app, None);
1916 assert!(matches!(result.action, Some(AppAction::SyncSession { .. })));
1917 assert!(app.current_session_id.is_some());
1918 assert!(!app.launch.visible);
1919 assert!(app.launch.row_hitboxes.is_empty());
1920 assert!(!app.launch.card_paintable(500, !reduced));
1921 app.insert_str("new draft");
1922 assert_eq!(app.input, "new draft");
1923 let lines = |app: &App| crate::tui::underwater::empty_state_lines(app, area);
1924 let visible = |lines: &[ratatui::text::Line<'_>]| {
1925 lines
1926 .iter()
1927 .any(|line| line.to_string().contains("New session"))
1928 };
1929 let initial = lines(&app);
1930 assert_eq!(visible(&initial), !reduced);
1931 assert_eq!(
1932 crate::tui::underwater::launch_motion_active(&app, false, true),
1933 !reduced
1934 );
1935 app.ambient_clock_ms += 120;
1936 let midpoint = lines(&app);
1937 assert_eq!(visible(&midpoint), !reduced);
1938 if !reduced {
1939 assert_ne!(initial, midpoint);
1940 }
1941 app.add_message(crate::tui::history::HistoryCell::User {
1942 content: "first turn".into(),
1943 });
1944 assert!(!crate::tui::widgets::should_render_empty_state(&app));
1945 assert!(!crate::tui::underwater::launch_motion_active(
1946 &app, false, true
1947 ));
1948 app.ambient_clock_ms += 120;
1949 assert!(!visible(&lines(&app)));
1950 assert!(
1951 !app.launch
1952 .session_handoff_active(app.ambient_clock_ms, !reduced)
1953 );
1954 }
1955 }
1956 }
1957
1958 enum FreshSessionPhase {
1959 Inspecting(tokio::sync::oneshot::Receiver<codewhale_engine::core::ops::SessionSnapshot>),
1960 Syncing(tokio::sync::oneshot::Receiver<codewhale_engine::core::ops::SessionSnapshot>),
1961 Acknowledged,
1962 Uncertain,
1963 }
1964
1965 pub(crate) struct PendingFreshSession {
1966 id: String,
1967 control: codewhale_engine::core::ops::SessionControlId,
1968 previous_id: Option<String>,
1969 ui_id: Option<String>,
1970 previous_source: Option<codewhale_engine::core::ops::SessionSnapshotSource>,
1971 provider_identity: codewhale_runtime::config::ProviderIdentity,
1972 model: String,
1973 workspace: PathBuf,
1974 mode: AppMode,
1975 agent_preset: Option<String>,
1976 queue_transition: Option<OfflineQueueTransition>,
1977 write_receipt: codewhale_engine::session_manager::SessionWriteReceipt,
1978 input: String,
1979 input_cursor: usize,
1980 paste_reference: Option<String>,
1981 oversized_paste: Option<String>,
1982 skill: Option<String>,
1983 skill_provenance: Option<codewhale_skills::SkillProvenance>,
1984 queued: VecDeque<QueuedMessage>,
1985 queued_draft: Option<QueuedMessage>,
1986 pub(crate) draft: Option<String>,
1987 phase: FreshSessionPhase,
1988 started: Instant,
1989 deadline_reported: bool,
1990 }
1991
1992 pub(crate) fn begin_fresh_session(
1993 app: &mut App,
1994 engine: &EngineHandle,
1995 sync: codewhale_command_contract::facets::SessionSyncPayload,
1996 force: bool,
1997 draft: Option<String>,
1998 ) -> Result<(), String> {
1999 if app.session_transition_blocked() || app.remote_control.runtime_chat_blocks_local_dispatch() {
2000 return Err("Cannot start a new session while the current session is busy.".to_string());
2001 }
2002 if !force
2003 && (!app.input.trim().is_empty()
2004 || !app.queued_messages.is_empty()
2005 || app.queued_draft.is_some())
2006 {
2007 return Err(
2008 "Cannot start a new session with pending input. Use /new --force to discard it."
2009 .to_string(),
2010 );
2011 }
2012 let agent_preset = sync.agent_preset.clone();
2013 let id = sync
2014 .session_id
2015 .filter(|id| !id.is_empty())
2016 .ok_or_else(|| "The new session request has no session ID.".to_string())?;
2017 if !sync.messages.is_empty()
2018 || sync.system_prompt.is_some()
2019 || sync.model != app.model
2020 || sync.workspace != app.workspace
2021 || crate::commands::from_command_mode(sync.mode) != app.mode
2022 {
2023 return Err("The new session request no longer matches the active route.".to_string());
2024 }
2025 let provider_identity = app.admitted_provider_identity()?.clone();
2026 let queue_transition = prepare_offline_queue_transition(app, &id)?;
2027 let write_receipt = prepare_fresh_session_write(&id)?;
2028 let (tx, rx) = tokio::sync::oneshot::channel();
2029 engine
2030 .try_send(Op::GetSessionSnapshot {
2031 tx: Arc::new(std::sync::Mutex::new(Some(tx))),
2032 })
2033 .map_err(|error| format!("Could not inspect the Engine session: {error}"))?;
2034 app.pending_fresh_session = Some(PendingFreshSession {
2035 id,
2036 control: codewhale_engine::core::ops::SessionControlId::new(),
2037 previous_id: app.current_session_id.clone(),
2038 ui_id: app.current_session_id.clone(),
2039 previous_source: None,
2040 provider_identity,
2041 model: app.model.clone(),
2042 workspace: app.workspace.clone(),
2043 mode: app.mode,
2044 agent_preset,
2045 queue_transition,
2046 write_receipt,
2047 input: app.input.clone(),
2048 input_cursor: app.cursor_position,
2049 paste_reference: app.pending_paste_reference.clone(),
2050 oversized_paste: app.oversized_paste_full_text.clone(),
2051 skill: app.active_skill.clone(),
2052 skill_provenance: app.active_skill_provenance.clone(),
2053 queued: app.queued_messages.clone(),
2054 queued_draft: app.queued_draft.clone(),
2055 draft,
2056 phase: FreshSessionPhase::Inspecting(rx),
2057 started: Instant::now(),
2058 deadline_reported: false,
2059 });
2060 app.show_command_result(
2061 "Starting a new session; waiting for Engine confirmation.".to_string(),
2062 StatusToastLevel::Info,
2063 );
2064 app.needs_redraw = true;
2065 Ok(())
2066 }
2067
2068 pub(crate) fn poll_fresh_session(app: &mut App, engine: &EngineHandle) -> bool {
2069 let Some(mut pending) = app.pending_fresh_session.take() else {
2070 return false;
2071 };
2072 let result = match &mut pending.phase {
2073 FreshSessionPhase::Inspecting(receiver) | FreshSessionPhase::Syncing(receiver) => {
2074 receiver.try_recv()
2075 }
2076 FreshSessionPhase::Acknowledged => {
2077 return commit_fresh_session(app, pending);
2078 }
2079 FreshSessionPhase::Uncertain => {
2080 app.pending_fresh_session = Some(pending);
2081 return false;
2082 }
2083 };
2084 match result {
2085 Ok(snapshot) if matches!(pending.phase, FreshSessionPhase::Inspecting(_)) => {
2086 if app.current_session_id != pending.ui_id
2087 || app.model != pending.model
2088 || app.workspace != pending.workspace
2089 || app.mode != pending.mode
2090 || pending
2091 .previous_id
2092 .as_deref()
2093 .is_some_and(|id| id != snapshot.session_id)
2094 || app.admitted_provider_identity().ok() != Some(&pending.provider_identity)
2095 || snapshot.model_provider != pending.provider_identity.persisted_kind()
2096 || snapshot.model_provider_id.as_deref() != pending.provider_identity.persisted_id()
2097 || snapshot.model != pending.model
2098 || snapshot.mode != pending.mode.as_setting()
2099 || snapshot.workspace != pending.workspace
2100 || (app.session_write_owner.is_some()
2101 && !app.owns_session_projection(snapshot.source.as_ref()))
2102 {
2103 surface_session_load_failure(
2104 app,
2105 format!(
2106 "New session was not requested: the Engine is running session {} and the current UI is not its acknowledged projection.",
2107 snapshot.session_id
2108 ),
2109 );
2110 return false;
2111 }
2112 pending.previous_id = Some(snapshot.session_id.clone());
2113 pending.previous_source = snapshot.source.clone();
2114 let first = engine.tx_op.clone().try_reserve_owned();
2115 let second = engine.tx_op.clone().try_reserve_owned();
2116 let (Ok(first), Ok(second)) = (first, second) else {
2117 surface_session_load_failure(app, "New session was not requested: the Engine mailbox is unavailable; retry when it is ready.".to_string());
2118 return false;
2119 };
2120 let (tx, rx) = tokio::sync::oneshot::channel();
2121 engine.send_reserved_op(
2122 first,
2123 Op::SyncSession {
2124 expected: Some(Box::new(snapshot)),
2125 control: pending.control.clone(),
2126 session_id: Some(pending.id.clone()),
2127 messages: Vec::new(),
2128 system_prompt: None,
2129 system_prompt_override: false,
2130 model: pending.model.clone(),
2131 workspace: pending.workspace.clone(),
2132 mode: pending.mode,
2133 agent_preset: pending.agent_preset.clone(),
2134 },
2135 );
2136 engine.send_reserved_op(
2137 second,
2138 Op::GetSessionSnapshot {
2139 tx: Arc::new(std::sync::Mutex::new(Some(tx))),
2140 },
2141 );
2142 pending.phase = FreshSessionPhase::Syncing(rx);
2143 }
2144 Ok(snapshot) => {
2145 if fresh_session_ack_matches(
2146 &pending,
2147 &snapshot.session_id,
2148 snapshot.source.as_ref(),
2149 &snapshot.workspace,
2150 &snapshot.model,
2151 ) {
2152 pending.phase = FreshSessionPhase::Acknowledged;
2153 return commit_fresh_session(app, pending);
2154 }
2155 if pending.previous_id.as_deref() == Some(snapshot.session_id.as_str())
2156 && pending.previous_source == snapshot.source
2157 {
2158 surface_session_load_failure(
2159 app,
2160 format!(
2161 "Could not start new session {}: the Engine kept session {}. The current draft and transcript were preserved.",
2162 codewhale_engine::session_manager::truncate_id(&pending.id),
2163 codewhale_engine::session_manager::truncate_id(&snapshot.session_id)
2164 ),
2165 );
2166 return false;
2167 }
2168 pending.phase = FreshSessionPhase::Uncertain;
2169 pending.draft = None;
2170 surface_session_load_failure(app, "New session acknowledgement did not match the requested Engine transition; input is preserved and sending remains blocked.".to_string());
2171 }
2172 Err(tokio::sync::oneshot::error::TryRecvError::Closed) => {
2173 if matches!(pending.phase, FreshSessionPhase::Inspecting(_)) {
2174 surface_session_load_failure(app, "The Engine dropped session inspection; no new session was requested and the current input is preserved.".to_string());
2175 return false;
2176 }
2177 pending.phase = FreshSessionPhase::Uncertain;
2178 pending.draft = None;
2179 surface_session_load_failure(app, "The Engine dropped the new-session acknowledgement; input is preserved and the transition remains unresolved.".to_string());
2180 }
2181 Err(tokio::sync::oneshot::error::TryRecvError::Empty) => {}
2182 }
2183 if !pending.deadline_reported
2184 && pending.started.elapsed() >= super::event_loop::LAUNCH_SESSION_SYNC_WAIT
2185 {
2186 if matches!(pending.phase, FreshSessionPhase::Inspecting(_)) {
2187 surface_session_load_failure(app, "Session inspection timed out; no new session was requested and the current input is preserved.".to_string());
2188 return false;
2189 }
2190 pending.deadline_reported = true;
2191 app.show_command_result("The new session is still awaiting Engine confirmation. The current draft and transcript are preserved; sending is paused.".to_string(), StatusToastLevel::Warning);
2192 app.needs_redraw = true;
2193 }
2194 app.pending_fresh_session = Some(pending);
2195 false
2196 }
2197
2198 fn fresh_session_ack_matches(
2199 pending: &PendingFreshSession,
2200 id: &str,
2201 source: Option<&codewhale_engine::core::ops::SessionSnapshotSource>,
2202 workspace: &Path,
2203 model: &str,
2204 ) -> bool {
2205 matches!(
2206 pending.phase,
2207 FreshSessionPhase::Syncing(_) | FreshSessionPhase::Acknowledged
2208 ) && id == pending.id
2209 && source
2210 == Some(
2211 &codewhale_engine::core::ops::SessionSnapshotSource::control(
2212 pending.control.clone(),
2213 ),
2214 )
2215 && workspace == pending.workspace.as_path()
2216 && model == pending.model.as_str()
2217 }
2218
2219 pub(crate) fn acknowledge_fresh_session(
2220 app: &mut App,
2221 id: &str,
2222 source: Option<&codewhale_engine::core::ops::SessionSnapshotSource>,
2223 workspace: &Path,
2224 model: &str,
2225 ) -> bool {
2226 if app.pending_fresh_session.as_ref().is_some_and(|pending| {
2227 matches!(pending.phase, FreshSessionPhase::Acknowledged)
2228 && !fresh_session_ack_matches(pending, id, source, workspace, model)
2229 }) {
2230 if let Some(pending) = app.pending_fresh_session.as_mut() {
2231 pending.phase = FreshSessionPhase::Uncertain;
2232 pending.draft = None;
2233 }
2234 surface_session_load_failure(app, "Another Engine session update superseded the confirmed transition; input is preserved and sending remains blocked.".to_string());
2235 return false;
2236 }
2237 if app
2238 .pending_fresh_session
2239 .as_ref()
2240 .is_some_and(|pending| fresh_session_ack_matches(pending, id, source, workspace, model))
2241 {
2242 let mut pending = app
2243 .pending_fresh_session
2244 .take()
2245 .expect("matched pending transition");
2246 pending.phase = FreshSessionPhase::Acknowledged;
2247 return commit_fresh_session(app, pending);
2248 }
2249 false
2250 }
2251
2252 fn commit_fresh_session(app: &mut App, mut pending: PendingFreshSession) -> bool {
2253 if app.current_session_id != pending.ui_id
2254 || app.model != pending.model
2255 || app.workspace != pending.workspace
2256 || app.mode != pending.mode
2257 || app.admitted_provider_identity().ok() != Some(&pending.provider_identity)
2258 {
2259 pending.phase = FreshSessionPhase::Uncertain;
2260 pending.draft = None;
2261 surface_session_load_failure(app, "The UI changed while the Engine confirmed a new session; input is preserved and the transition remains unresolved.".to_string());
2262 app.pending_fresh_session = Some(pending);
2263 return false;
2264 }
2265 let preserve_input = app.input != pending.input
2266 || app.cursor_position != pending.input_cursor
2267 || app.pending_paste_reference != pending.paste_reference
2268 || app.oversized_paste_full_text != pending.oversized_paste
2269 || app.active_skill != pending.skill
2270 || app.active_skill_provenance != pending.skill_provenance
2271 || app.paste_burst.is_active();
2272 let preserve_queue =
2273 app.queued_messages != pending.queued || app.queued_draft != pending.queued_draft;
2274 let composer = std::mem::take(&mut app.composer);
2275 let queued = app.queued_messages.clone();
2276 let queued_draft = app.queued_draft.take();
2277 let queued_draft_was_held = std::mem::take(&mut app.queued_draft_was_held);
2278 if !crate::commands::groups::core::reset_conversation_state(app) {
2279 app.composer = composer;
2280 app.queued_draft = queued_draft;
2281 app.queued_draft_was_held = queued_draft_was_held;
2282 app.show_command_result("The Engine confirmed the new session; waiting for Work state before updating the UI. Input is preserved.".to_string(), StatusToastLevel::Info);
2283 app.pending_fresh_session = Some(pending);
2284 return false;
2285 }
2286 install_offline_queue_transition(app, pending.queue_transition.take());
2287 app.composer = composer;
2288 if !preserve_input {
2289 app.clear_input();
2290 }
2291 if preserve_queue {
2292 app.queued_messages = queued;
2293 for message in &mut app.queued_messages {
2294 message.history_echoed = false;
2295 }
2296 app.held_restored_queue = app.queued_messages.len();
2297 app.queued_draft_was_held = queued_draft.is_some();
2298 app.queued_draft = queued_draft;
2299 }
2300 app.session_artifacts.clear();
2301 app.session_context_references.clear();
2302 app.tool_evidence.clear();
2303 app.set_current_session_id(Some(pending.id.clone()));
2304 app.install_conversation_mode(pending.agent_preset.clone(), None);
2305 if let Some(draft) = pending.draft.take().filter(|_| !preserve_input) {
2306 app.input = draft;
2307 app.cursor_position = app.input.chars().count();
2308 app.line_began_with_slash = false;
2309 }
2310 app.session_write_receipt = Some(pending.write_receipt);
2311 app.session_write_owner =
2312 Some(codewhale_engine::session_manager::SessionWriteOwner::Control(pending.control));
2313 app.current_session_metadata = None;
2314 app.session_title = Some(codewhale_engine::session_manager::DEFAULT_SESSION_TITLE.to_string());
2315 app.window_title = None;
2316 app.composer_color = None;
2317 app.scroll_to_bottom();
2318 let message = format!(
2319 "Started new session {} (New Session). Previous sessions remain available via /resume.",
2320 codewhale_engine::session_manager::truncate_id(&pending.id)
2321 );
2322 app.add_message(HistoryCell::System {
2323 content: message.clone(),
2324 });
2325 app.show_command_result(message, StatusToastLevel::Success);
2326 app.refresh_agent_approved_plugins_notice();
2327 app.needs_redraw = true;
2328 true
2329 }
2330
2330 lines RUST