1use std::path::PathBuf;
2use std::sync::mpsc::{Receiver, RecvError, SyncSender, sync_channel};
3use std::sync::{Arc, atomic::AtomicBool};
4
5use crate::tui::config::KeyboardProtocolConfig;
6use crate::tui::config::UiSurfacePreference;
7use hashbrown::HashMap;
8
9use crate::tui::core_tui::app::session::AppSession;
10use crate::tui::core_tui::app::types::{
11 FocusChangeCallback, InlineCommand, InlineCommandSender, InlineEvent, InlineEventCallback, InlineHandle,
12 InlineListSelection, InlineSession, InlineTheme, PreviewCallback, SlashCommandItem, TransientActivitySignal,
13 TransientEvent, TransientHotkeyAction, TransientRequest, TransientSubmission,
14};
15use crate::tui::core_tui::log;
16use crate::tui::core_tui::runner::{TuiOptions, run_tui};
17use crate::tui::core_tui::session::action::BindingStore;
18use crate::tui::core_tui::session::config::AppearanceConfig;
19use crate::tui::options::{FullscreenInteractionSettings, KeyboardProtocolSettings, SessionSurface};
20
21const HOST_COMMAND_QUEUE_CAPACITY: usize = 128;
22
23#[derive(Clone)]
25pub struct SessionOptions {
26 pub placeholder: Option<String>,
27 pub surface_preference: SessionSurface,
28 pub inline_rows: u16,
29 pub event_callback: Option<InlineEventCallback>,
30 pub focus_callback: Option<FocusChangeCallback>,
31 pub active_pty_sessions: Option<Arc<std::sync::atomic::AtomicUsize>>,
32 pub input_activity_counter: Option<Arc<std::sync::atomic::AtomicU64>>,
33 pub keyboard_protocol: KeyboardProtocolSettings,
34 pub fullscreen: FullscreenInteractionSettings,
35 pub workspace_root: Option<PathBuf>,
36 pub slash_commands: Vec<SlashCommandItem>,
37 pub appearance: Option<AppearanceConfig>,
38 pub app_name: String,
39 pub non_interactive_hint: Option<String>,
40 pub key_bindings: HashMap<String, Vec<String>>,
43 pub preview_callback: Option<PreviewCallback>,
44}
45
46pub struct HostSession {
51 pub session: InlineSession,
53 pub input: tokio::sync::mpsc::UnboundedSender<InlineEvent>,
56 pub commands: HostCommandReceiver,
59}
60
61pub struct HostCommandReceiver {
63 receiver: Receiver<InlineCommand>,
64 closed: Arc<AtomicBool>,
65}
66
67impl HostCommandReceiver {
68 pub fn recv(&self) -> Result<InlineCommand, RecvError> {
70 self.receiver.recv()
71 }
72}
73
74impl Drop for HostCommandReceiver {
75 fn drop(&mut self) {
76 self.closed.store(true, std::sync::atomic::Ordering::Release);
77 }
78}
79
80#[derive(Clone, Copy, Debug, PartialEq, Eq)]
82pub enum HostInteractionKind {
83 Approval,
84 PlanApproval,
85 Question,
86 Choice,
87 Other,
88}
89
90#[derive(Clone, Debug)]
92pub struct HostInteractionChoice {
93 pub id: String,
95 pub label: String,
97 pub description: Option<String>,
99 pub selection: InlineListSelection,
101}
102
103#[derive(Clone, Debug)]
105pub struct HostInteractionStep {
106 pub title: String,
107 pub question: String,
108 pub choices: Vec<HostInteractionChoice>,
109 pub selected_choice_id: Option<String>,
110 pub allow_freeform: bool,
111}
112
113#[derive(Clone, Debug)]
115pub struct HostInteraction {
116 pub kind: HostInteractionKind,
117 pub wizard: bool,
118 pub title: String,
119 pub details: Vec<String>,
120 pub steps: Vec<HostInteractionStep>,
121 pub selected_choice_ids: Vec<String>,
122 pub plan_markdown: Option<String>,
124}
125
126pub fn host_interaction_from_command(command: &InlineCommand) -> Option<HostInteraction> {
128 let InlineCommand::ShowTransient { request } = command else {
129 return None;
130 };
131
132 match request.as_ref() {
133 TransientRequest::List(request) => {
134 let choices = host_choices(&request.items, 0);
135 let kind = infer_interaction_kind(choices.iter().map(|choice| &choice.selection));
136 let selected_choice_id = request.selected.as_ref().and_then(|selected| {
137 choices
138 .iter()
139 .find(|choice| &choice.selection == selected)
140 .map(|choice| choice.id.clone())
141 });
142 let selected_choice_ids = selected_choice_id.iter().cloned().collect();
143 Some(HostInteraction {
144 kind,
145 wizard: false,
146 title: request.title.clone(),
147 details: request.lines.clone(),
148 steps: vec![HostInteractionStep {
149 title: request.title.clone(),
150 question: request.lines.first().cloned().unwrap_or_default(),
151 choices,
152 selected_choice_id,
153 allow_freeform: false,
154 }],
155 selected_choice_ids,
156 plan_markdown: request.plan_markdown.clone(),
157 })
158 }
159 TransientRequest::Wizard(request) => {
160 let steps = request
161 .steps
162 .iter()
163 .enumerate()
164 .map(|(index, step)| {
165 let choices = host_choices(&step.items, index);
166 let selected_choice_id = step.answer.as_ref().and_then(|selected| {
167 choices
168 .iter()
169 .find(|choice| &choice.selection == selected)
170 .map(|choice| choice.id.clone())
171 });
172 HostInteractionStep {
173 title: step.title.clone(),
174 question: step.question.clone(),
175 choices,
176 selected_choice_id,
177 allow_freeform: step.allow_freeform,
178 }
179 })
180 .collect::<Vec<_>>();
181 let kind = infer_interaction_kind(steps.iter().flat_map(|step| step.choices.iter().map(|c| &c.selection)));
182 let selected_choice_ids = steps.iter().filter_map(|step| step.selected_choice_id.clone()).collect();
183 Some(HostInteraction {
184 kind,
185 wizard: true,
186 title: request.title.clone(),
187 details: Vec::new(),
188 steps,
189 selected_choice_ids,
190 plan_markdown: None,
191 })
192 }
193 TransientRequest::Modal(request) => Some(HostInteraction {
194 kind: HostInteractionKind::Other,
195 wizard: false,
196 title: request.title.clone(),
197 details: request.lines.clone(),
198 steps: Vec::new(),
199 selected_choice_ids: Vec::new(),
200 plan_markdown: None,
201 }),
202 _ => None,
203 }
204}
205
206pub fn host_interaction_response(
208 interaction: &HostInteraction,
209 choice_ids: &[String],
210 answer_texts: &[Option<String>],
211 cancelled: bool,
212) -> Option<InlineEvent> {
213 if cancelled {
214 return Some(InlineEvent::Transient(TransientEvent::Cancelled));
215 }
216
217 if interaction.steps.is_empty() {
218 return None;
219 }
220
221 let mut selections = Vec::with_capacity(interaction.steps.len());
222 for (step_index, step) in interaction.steps.iter().enumerate() {
223 let choice_id = if choice_ids.len() == interaction.steps.len() {
224 choice_ids.get(step_index)
225 } else if interaction.steps.len() == 1 {
226 choice_ids.first()
227 } else {
228 return None;
229 };
230 let answer = answer_texts.get(step_index).and_then(Option::as_deref);
231 let mut selection = choice_id
232 .and_then(|choice_id| step.choices.iter().find(|choice| &choice.id == choice_id))
233 .map(|choice| choice.selection.clone());
234 if selection.is_none() && answer.is_some() {
235 selection = step.choices.iter().find_map(|choice| {
236 matches!(choice.selection, InlineListSelection::RequestUserInputAnswer { .. })
237 .then(|| choice.selection.clone())
238 });
239 }
240 let mut selection = selection?;
241 if let Some(answer) = answer {
242 apply_freeform_answer(&mut selection, answer);
243 }
244 selections.push(selection);
245 }
246
247 let submission = if interaction.wizard {
248 TransientSubmission::Wizard(selections)
249 } else {
250 TransientSubmission::Selection(selections[0].clone())
251 };
252 Some(InlineEvent::Transient(TransientEvent::Submitted(submission)))
253}
254
255pub fn host_interaction_hotkey_response(
260 interaction: &HostInteraction,
261 action: TransientHotkeyAction,
262) -> Option<InlineEvent> {
263 if interaction.kind != HostInteractionKind::PlanApproval || !matches!(action, TransientHotkeyAction::LaunchEditor) {
264 return None;
265 }
266 Some(InlineEvent::Transient(TransientEvent::Submitted(TransientSubmission::Hotkey(action))))
267}
268
269fn host_choices(
270 items: &[crate::tui::core_tui::app::types::InlineListItem],
271 step_index: usize,
272) -> Vec<HostInteractionChoice> {
273 items
274 .iter()
275 .enumerate()
276 .filter_map(|(choice_index, item)| {
277 let selection = item.selection.clone()?;
278 Some(HostInteractionChoice {
279 id: format!("step-{step_index}-choice-{choice_index}"),
280 label: item.title.clone(),
281 description: item.subtitle.clone(),
282 selection,
283 })
284 })
285 .collect()
286}
287
288fn infer_interaction_kind<'a>(selections: impl Iterator<Item = &'a InlineListSelection>) -> HostInteractionKind {
289 let mut kind = HostInteractionKind::Other;
290 for selection in selections {
291 match selection {
292 InlineListSelection::ToolApproval(_)
293 | InlineListSelection::ToolApprovalDenyOnce
294 | InlineListSelection::ToolApprovalSession
295 | InlineListSelection::ToolApprovalPermanent
296 | InlineListSelection::ToolApprovalEnable => return HostInteractionKind::Approval,
297 InlineListSelection::PlanApprovalExecute
298 | InlineListSelection::PlanApprovalFreshContext
299 | InlineListSelection::PlanApprovalEditPlan
300 | InlineListSelection::PlanApprovalDiscuss
301 | InlineListSelection::PlanApprovalAutoAccept
302 | InlineListSelection::PlanApprovalSwitchBuild
303 | InlineListSelection::PlanApprovalSwitchAuto => return HostInteractionKind::PlanApproval,
304 InlineListSelection::RequestUserInputAnswer { .. } | InlineListSelection::AskUserChoice { .. } => {
305 kind = HostInteractionKind::Question;
306 }
307 _ if kind == HostInteractionKind::Other => kind = HostInteractionKind::Choice,
308 _ => {}
309 }
310 }
311 kind
312}
313
314fn apply_freeform_answer(selection: &mut InlineListSelection, answer: &str) {
315 if let InlineListSelection::RequestUserInputAnswer { other, .. } = selection {
316 *other = Some(answer.to_string());
317 }
318}
319
320pub fn new_host_session() -> HostSession {
322 let closed = Arc::new(AtomicBool::new(false));
323 let (command_sender, command_receiver) = sync_channel(HOST_COMMAND_QUEUE_CAPACITY);
324 let (input, events) = tokio::sync::mpsc::unbounded_channel();
325 let handle = InlineHandle::new_bounded_host(command_sender, Arc::clone(&closed));
326 HostSession {
327 session: InlineSession { handle: handle.clone(), events, worker: None },
328 input,
329 commands: HostCommandReceiver { receiver: command_receiver, closed },
330 }
331}
332
333impl Default for SessionOptions {
334 fn default() -> Self {
335 Self {
336 placeholder: None,
337 surface_preference: SessionSurface::default(),
338 inline_rows: crate::tui::config::constants::ui::DEFAULT_INLINE_VIEWPORT_ROWS,
339 event_callback: None,
340 focus_callback: None,
341 active_pty_sessions: None,
342 input_activity_counter: None,
343 keyboard_protocol: KeyboardProtocolSettings::default(),
344 fullscreen: FullscreenInteractionSettings::default(),
345 workspace_root: None,
346 slash_commands: Vec::new(),
347 appearance: None,
348 app_name: "Agent TUI".to_string(),
349 non_interactive_hint: None,
350 key_bindings: HashMap::new(),
351 preview_callback: None,
352 }
353 }
354}
355
356impl SessionOptions {
357 fn from_host(host: &impl crate::tui::host::HostAdapter) -> Self {
359 let defaults = host.session_defaults();
360 Self {
361 surface_preference: defaults.surface_preference,
362 inline_rows: defaults.inline_rows,
363 keyboard_protocol: defaults.keyboard_protocol,
364 fullscreen: defaults.fullscreen,
365 workspace_root: host.workspace_root(),
366 slash_commands: host.slash_commands(),
367 app_name: host.app_name(),
368 non_interactive_hint: host.non_interactive_hint(),
369 ..Self::default()
370 }
371 }
372}
373
374pub fn spawn_session_with_options(theme: InlineTheme, options: SessionOptions) -> anyhow::Result<InlineSession> {
376 use crossterm::tty::IsTty;
377
378 if !std::io::stdin().is_tty() {
380 return Err(anyhow::anyhow!(
381 "cannot run interactive TUI: stdin is not a terminal (must be run in an interactive terminal)"
382 ));
383 }
384
385 let (command_tx, command_rx) = tokio::sync::mpsc::unbounded_channel();
386 let (event_tx, event_rx) = tokio::sync::mpsc::unbounded_channel();
387 let show_logs = log::is_tui_log_capture_enabled();
388 let transient_active = Arc::new(TransientActivitySignal::default());
389 let transient_active_for_session = transient_active.clone();
390
391 let worker = tokio::spawn(async move {
392 if let Err(error) = run_tui(
393 command_rx,
394 event_tx,
395 TuiOptions {
396 surface_preference: UiSurfacePreference::from(options.surface_preference),
397 inline_rows: options.inline_rows,
398 show_logs,
399 log_theme: None,
400 event_callback: options.event_callback,
401 focus_callback: options.focus_callback,
402 active_pty_sessions: options.active_pty_sessions,
403 input_activity_counter: options.input_activity_counter,
404 keyboard_protocol: KeyboardProtocolConfig::from(options.keyboard_protocol),
405 fullscreen: options.fullscreen,
406 workspace_root: options.workspace_root,
407 preview_callback: options.preview_callback.clone(),
408 },
409 move |rows| {
410 let bindings = BindingStore::new(options.key_bindings.clone());
411 let mut session = AppSession::new_with_logs_and_bindings(
412 theme,
413 options.placeholder,
414 rows,
415 show_logs,
416 options.appearance,
417 options.slash_commands,
418 options.app_name,
419 bindings,
420 );
421 session.set_transient_activity_signal(transient_active_for_session.clone());
422 session
423 },
424 )
425 .await
426 {
427 let error_msg = error.to_string();
428 if error_msg.contains("stdin is not a terminal") {
429 vtcode_commons::diagnostics::stderr(format_args!("Error: Interactive TUI requires a proper terminal."));
430 if let Some(hint) = options.non_interactive_hint.as_deref() {
431 eprintln!("{hint}");
432 } else {
433 eprintln!("Use a non-interactive mode in your host app for piped input.");
434 }
435 } else {
436 vtcode_commons::diagnostics::stderr(format_args!("Error: TUI startup failed: {error:#}"));
437 }
438 tracing::error!(%error, "inline session terminated unexpectedly");
439 }
440 });
441
442 Ok(InlineSession {
443 handle: InlineHandle::new_with_transient_signal(InlineCommandSender::Unbounded(command_tx), transient_active),
444 events: event_rx,
445 worker: Some(worker),
446 })
447}
448
449pub fn spawn_session_with_host(
451 theme: InlineTheme,
452 host: &impl crate::tui::host::HostAdapter,
453) -> anyhow::Result<InlineSession> {
454 spawn_session_with_options(theme, SessionOptions::from_host(host))
455}
456
457#[cfg(test)]
458mod tests {
459 use super::*;
460
461 #[tokio::test]
462 async fn host_session_bridges_inputs_and_commands_without_a_tui_worker() {
463 let mut host = new_host_session();
464 assert!(host.session.worker.is_none());
465 host.input
466 .send(InlineEvent::Submit("inspect this file".into()))
467 .expect("send host input");
468 assert!(matches!(
469 host.session.next_event().await,
470 Some(InlineEvent::Submit(input)) if input.text == "inspect this file"
471 ));
472
473 host.session.handle.set_placeholder(Some("ready".to_string()));
474 assert!(matches!(
475 host.commands.recv(),
476 Ok(InlineCommand::SetPlaceholder { hint: Some(hint), .. }) if hint == "ready"
477 ));
478 }
479
480 #[test]
481 fn host_interaction_returns_the_original_approval_choice() {
482 let command = InlineCommand::ShowTransient {
483 request: Box::new(TransientRequest::List(crate::tui::core_tui::app::types::ListOverlayRequest {
484 title: "Approve command".to_string(),
485 lines: vec!["Run the requested command?".to_string()],
486 footer_hint: None,
487 items: vec![crate::tui::core_tui::app::types::InlineListItem::new(
488 "Do not run (Recommended)",
489 Some(InlineListSelection::ToolApproval(false)),
490 )],
491 selected: Some(InlineListSelection::ToolApproval(false)),
492 search: None,
493 hotkeys: Vec::new(),
494 status: None,
495 plan_markdown: None,
496 })),
497 };
498 let interaction = host_interaction_from_command(&command).expect("interaction view");
499 assert_eq!(interaction.kind, HostInteractionKind::Approval);
500 assert!(interaction.steps[0].choices[0].label.contains("Recommended"));
501
502 let event =
503 host_interaction_response(&interaction, &[interaction.steps[0].choices[0].id.clone()], &[None], false)
504 .expect("host response");
505 assert!(matches!(
506 event,
507 InlineEvent::Transient(TransientEvent::Submitted(TransientSubmission::Selection(
508 InlineListSelection::ToolApproval(false)
509 )))
510 ));
511 }
512
513 #[test]
514 fn host_interaction_carries_plan_markdown_from_list_requests() {
515 let command = InlineCommand::ShowTransient {
516 request: Box::new(TransientRequest::List(crate::tui::core_tui::app::types::ListOverlayRequest {
517 title: "Ready to code?".to_string(),
518 lines: vec!["A plan is ready to execute.".to_string()],
519 footer_hint: None,
520 items: Vec::new(),
521 selected: None,
522 search: None,
523 hotkeys: Vec::new(),
524 status: None,
525 plan_markdown: Some("# Plan\n\nDo the thing.".to_string()),
526 })),
527 };
528 let interaction = host_interaction_from_command(&command).expect("interaction view");
529 assert_eq!(interaction.plan_markdown.as_deref(), Some("# Plan\n\nDo the thing."));
530 }
531
532 #[test]
533 fn host_interaction_hotkey_only_maps_launch_editor_for_plan_approvals() {
534 fn plan_command(
535 title: &str,
536 item: &str,
537 selection: InlineListSelection,
538 plan_markdown: Option<String>,
539 ) -> InlineCommand {
540 InlineCommand::ShowTransient {
541 request: Box::new(TransientRequest::List(crate::tui::core_tui::app::types::ListOverlayRequest {
542 title: title.to_string(),
543 lines: vec!["A plan is ready to execute.".to_string()],
544 footer_hint: None,
545 items: vec![crate::tui::core_tui::app::types::InlineListItem::new(
546 item,
547 Some(selection.clone()),
548 )],
549 selected: Some(selection),
550 search: None,
551 hotkeys: Vec::new(),
552 status: None,
553 plan_markdown,
554 })),
555 }
556 }
557
558 let plan = host_interaction_from_command(&plan_command(
559 "Ready to code?",
560 "Edit plan",
561 InlineListSelection::PlanApprovalEditPlan,
562 Some("# Plan\n\nDo the thing.".to_string()),
563 ))
564 .expect("interaction view");
565 assert_eq!(plan.kind, HostInteractionKind::PlanApproval);
566
567 let event =
568 host_interaction_hotkey_response(&plan, TransientHotkeyAction::LaunchEditor).expect("plan hotkey maps");
569 assert!(matches!(
570 event,
571 InlineEvent::Transient(TransientEvent::Submitted(TransientSubmission::Hotkey(
572 TransientHotkeyAction::LaunchEditor
573 )))
574 ));
575 assert!(
576 host_interaction_hotkey_response(&plan, TransientHotkeyAction::OpenSourceThread).is_none(),
577 "non-editor actions fail closed"
578 );
579
580 let approval = host_interaction_from_command(&plan_command(
581 "Approve command",
582 "Do not run (Recommended)",
583 InlineListSelection::ToolApproval(false),
584 None,
585 ))
586 .expect("interaction view");
587 assert_eq!(approval.kind, HostInteractionKind::Approval);
588 assert!(
589 host_interaction_hotkey_response(&approval, TransientHotkeyAction::LaunchEditor).is_none(),
590 "hotkeys outside plan approvals fail closed"
591 );
592 }
593
594 #[test]
595 fn host_interaction_keeps_single_step_question_wizard_shape_and_freeform_text() {
596 let question = InlineListSelection::RequestUserInputAnswer {
597 question_id: "goal".to_string(),
598 selected: Vec::new(),
599 other: Some(String::new()),
600 };
601 let command = InlineCommand::ShowTransient {
602 request: Box::new(TransientRequest::Wizard(crate::tui::core_tui::app::types::WizardOverlayRequest {
603 title: "Project goal".to_string(),
604 steps: vec![crate::tui::core_tui::app::types::WizardStep {
605 title: "Goal".to_string(),
606 question: "What should this change deliver?".to_string(),
607 items: vec![crate::tui::core_tui::app::types::InlineListItem::new(
608 "Custom answer",
609 Some(question),
610 )],
611 completed: false,
612 answer: None,
613 allow_freeform: true,
614 freeform_label: Some("Custom answer".to_string()),
615 freeform_placeholder: None,
616 freeform_default: None,
617 }],
618 current_step: 0,
619 search: None,
620 mode: crate::tui::core_tui::app::types::WizardModalMode::MultiStep,
621 })),
622 };
623 let interaction = host_interaction_from_command(&command).expect("interaction view");
624 let choice_id = interaction.steps[0].choices[0].id.clone();
625 let event =
626 host_interaction_response(&interaction, &[choice_id], &[Some("Keep the change scoped".to_string())], false)
627 .expect("host response");
628 assert!(interaction.wizard);
629 assert!(matches!(
630 event,
631 InlineEvent::Transient(TransientEvent::Submitted(TransientSubmission::Wizard(selections)))
632 if matches!(selections.as_slice(), [InlineListSelection::RequestUserInputAnswer {
633 question_id,
634 selected,
635 other: Some(answer),
636 }] if question_id == "goal" && selected.is_empty() && answer == "Keep the change scoped")
637 ));
638 }
639
640 struct DemoHost;
641
642 impl crate::tui::host::WorkspaceInfoProvider for DemoHost {
643 fn workspace_name(&self) -> String {
644 "demo".to_string()
645 }
646
647 fn workspace_root(&self) -> Option<PathBuf> {
648 Some(PathBuf::from("/workspace/demo"))
649 }
650 }
651
652 impl crate::tui::host::NotificationProvider for DemoHost {
653 fn set_terminal_focused(&self, _focused: bool) {}
654 }
655
656 impl crate::tui::host::ThemeProvider for DemoHost {
657 fn available_themes(&self) -> Vec<String> {
658 vec!["default".to_string()]
659 }
660
661 fn active_theme_name(&self) -> Option<String> {
662 Some("default".to_string())
663 }
664 }
665
666 impl crate::tui::host::HostAdapter for DemoHost {
667 fn session_defaults(&self) -> crate::tui::host::HostSessionDefaults {
668 crate::tui::host::HostSessionDefaults {
669 surface_preference: SessionSurface::Inline,
670 inline_rows: 24,
671 keyboard_protocol: KeyboardProtocolSettings::default(),
672 fullscreen: FullscreenInteractionSettings::default(),
673 }
674 }
675 }
676
677 #[test]
680 fn session_options_from_host_uses_defaults() {
681 let options = SessionOptions::from_host(&DemoHost);
682
683 assert_eq!(options.surface_preference, SessionSurface::Inline);
684 assert_eq!(options.inline_rows, 24);
685 assert_eq!(options.workspace_root, Some(PathBuf::from("/workspace/demo")));
686 }
687
688 #[test]
689 fn session_options_default_uses_inline_surface() {
690 assert_eq!(SessionOptions::default().surface_preference, SessionSurface::Inline);
691 }
692}