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, 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}
123
124pub fn host_interaction_from_command(command: &InlineCommand) -> Option<HostInteraction> {
126 let InlineCommand::ShowTransient { request } = command else {
127 return None;
128 };
129
130 match request.as_ref() {
131 TransientRequest::List(request) => {
132 let choices = host_choices(&request.items, 0);
133 let kind = infer_interaction_kind(choices.iter().map(|choice| &choice.selection));
134 let selected_choice_id = request.selected.as_ref().and_then(|selected| {
135 choices
136 .iter()
137 .find(|choice| &choice.selection == selected)
138 .map(|choice| choice.id.clone())
139 });
140 let selected_choice_ids = selected_choice_id.iter().cloned().collect();
141 Some(HostInteraction {
142 kind,
143 wizard: false,
144 title: request.title.clone(),
145 details: request.lines.clone(),
146 steps: vec![HostInteractionStep {
147 title: request.title.clone(),
148 question: request.lines.first().cloned().unwrap_or_default(),
149 choices,
150 selected_choice_id,
151 allow_freeform: false,
152 }],
153 selected_choice_ids,
154 })
155 }
156 TransientRequest::Wizard(request) => {
157 let steps = request
158 .steps
159 .iter()
160 .enumerate()
161 .map(|(index, step)| {
162 let choices = host_choices(&step.items, index);
163 let selected_choice_id = step.answer.as_ref().and_then(|selected| {
164 choices
165 .iter()
166 .find(|choice| &choice.selection == selected)
167 .map(|choice| choice.id.clone())
168 });
169 HostInteractionStep {
170 title: step.title.clone(),
171 question: step.question.clone(),
172 choices,
173 selected_choice_id,
174 allow_freeform: step.allow_freeform,
175 }
176 })
177 .collect::<Vec<_>>();
178 let kind = infer_interaction_kind(steps.iter().flat_map(|step| step.choices.iter().map(|c| &c.selection)));
179 let selected_choice_ids = steps.iter().filter_map(|step| step.selected_choice_id.clone()).collect();
180 Some(HostInteraction {
181 kind,
182 wizard: true,
183 title: request.title.clone(),
184 details: Vec::new(),
185 steps,
186 selected_choice_ids,
187 })
188 }
189 TransientRequest::Modal(request) => Some(HostInteraction {
190 kind: HostInteractionKind::Other,
191 wizard: false,
192 title: request.title.clone(),
193 details: request.lines.clone(),
194 steps: Vec::new(),
195 selected_choice_ids: Vec::new(),
196 }),
197 _ => None,
198 }
199}
200
201pub fn host_interaction_response(
203 interaction: &HostInteraction,
204 choice_ids: &[String],
205 answer_texts: &[Option<String>],
206 cancelled: bool,
207) -> Option<InlineEvent> {
208 if cancelled {
209 return Some(InlineEvent::Transient(TransientEvent::Cancelled));
210 }
211
212 if interaction.steps.is_empty() {
213 return None;
214 }
215
216 let mut selections = Vec::with_capacity(interaction.steps.len());
217 for (step_index, step) in interaction.steps.iter().enumerate() {
218 let choice_id = if choice_ids.len() == interaction.steps.len() {
219 choice_ids.get(step_index)
220 } else if interaction.steps.len() == 1 {
221 choice_ids.first()
222 } else {
223 return None;
224 };
225 let answer = answer_texts.get(step_index).and_then(Option::as_deref);
226 let mut selection = choice_id
227 .and_then(|choice_id| step.choices.iter().find(|choice| &choice.id == choice_id))
228 .map(|choice| choice.selection.clone());
229 if selection.is_none() && answer.is_some() {
230 selection = step.choices.iter().find_map(|choice| {
231 matches!(choice.selection, InlineListSelection::RequestUserInputAnswer { .. })
232 .then(|| choice.selection.clone())
233 });
234 }
235 let mut selection = selection?;
236 if let Some(answer) = answer {
237 apply_freeform_answer(&mut selection, answer);
238 }
239 selections.push(selection);
240 }
241
242 let submission = if interaction.wizard {
243 TransientSubmission::Wizard(selections)
244 } else {
245 TransientSubmission::Selection(selections[0].clone())
246 };
247 Some(InlineEvent::Transient(TransientEvent::Submitted(submission)))
248}
249
250fn host_choices(
251 items: &[crate::tui::core_tui::app::types::InlineListItem],
252 step_index: usize,
253) -> Vec<HostInteractionChoice> {
254 items
255 .iter()
256 .enumerate()
257 .filter_map(|(choice_index, item)| {
258 let selection = item.selection.clone()?;
259 Some(HostInteractionChoice {
260 id: format!("step-{step_index}-choice-{choice_index}"),
261 label: item.title.clone(),
262 description: item.subtitle.clone(),
263 selection,
264 })
265 })
266 .collect()
267}
268
269fn infer_interaction_kind<'a>(selections: impl Iterator<Item = &'a InlineListSelection>) -> HostInteractionKind {
270 let mut kind = HostInteractionKind::Other;
271 for selection in selections {
272 match selection {
273 InlineListSelection::ToolApproval(_)
274 | InlineListSelection::ToolApprovalDenyOnce
275 | InlineListSelection::ToolApprovalSession
276 | InlineListSelection::ToolApprovalPermanent
277 | InlineListSelection::ToolApprovalEnable => return HostInteractionKind::Approval,
278 InlineListSelection::PlanApprovalExecute
279 | InlineListSelection::PlanApprovalFreshContext
280 | InlineListSelection::PlanApprovalEditPlan
281 | InlineListSelection::PlanApprovalDiscuss
282 | InlineListSelection::PlanApprovalAutoAccept
283 | InlineListSelection::PlanApprovalSwitchBuild
284 | InlineListSelection::PlanApprovalSwitchAuto => return HostInteractionKind::PlanApproval,
285 InlineListSelection::RequestUserInputAnswer { .. } | InlineListSelection::AskUserChoice { .. } => {
286 kind = HostInteractionKind::Question;
287 }
288 _ if kind == HostInteractionKind::Other => kind = HostInteractionKind::Choice,
289 _ => {}
290 }
291 }
292 kind
293}
294
295fn apply_freeform_answer(selection: &mut InlineListSelection, answer: &str) {
296 if let InlineListSelection::RequestUserInputAnswer { other, .. } = selection {
297 *other = Some(answer.to_string());
298 }
299}
300
301pub fn new_host_session() -> HostSession {
303 let closed = Arc::new(AtomicBool::new(false));
304 let (command_sender, command_receiver) = sync_channel(HOST_COMMAND_QUEUE_CAPACITY);
305 let (input, events) = tokio::sync::mpsc::unbounded_channel();
306 let handle = InlineHandle::new_bounded_host(command_sender, Arc::clone(&closed));
307 HostSession {
308 session: InlineSession { handle: handle.clone(), events, worker: None },
309 input,
310 commands: HostCommandReceiver { receiver: command_receiver, closed },
311 }
312}
313
314impl Default for SessionOptions {
315 fn default() -> Self {
316 Self {
317 placeholder: None,
318 surface_preference: SessionSurface::default(),
319 inline_rows: crate::tui::config::constants::ui::DEFAULT_INLINE_VIEWPORT_ROWS,
320 event_callback: None,
321 focus_callback: None,
322 active_pty_sessions: None,
323 input_activity_counter: None,
324 keyboard_protocol: KeyboardProtocolSettings::default(),
325 fullscreen: FullscreenInteractionSettings::default(),
326 workspace_root: None,
327 slash_commands: Vec::new(),
328 appearance: None,
329 app_name: "Agent TUI".to_string(),
330 non_interactive_hint: None,
331 key_bindings: HashMap::new(),
332 preview_callback: None,
333 }
334 }
335}
336
337impl SessionOptions {
338 fn from_host(host: &impl crate::tui::host::HostAdapter) -> Self {
340 let defaults = host.session_defaults();
341 Self {
342 surface_preference: defaults.surface_preference,
343 inline_rows: defaults.inline_rows,
344 keyboard_protocol: defaults.keyboard_protocol,
345 fullscreen: defaults.fullscreen,
346 workspace_root: host.workspace_root(),
347 slash_commands: host.slash_commands(),
348 app_name: host.app_name(),
349 non_interactive_hint: host.non_interactive_hint(),
350 ..Self::default()
351 }
352 }
353}
354
355pub fn spawn_session_with_options(theme: InlineTheme, options: SessionOptions) -> anyhow::Result<InlineSession> {
357 use crossterm::tty::IsTty;
358
359 if !std::io::stdin().is_tty() {
361 return Err(anyhow::anyhow!(
362 "cannot run interactive TUI: stdin is not a terminal (must be run in an interactive terminal)"
363 ));
364 }
365
366 let (command_tx, command_rx) = tokio::sync::mpsc::unbounded_channel();
367 let (event_tx, event_rx) = tokio::sync::mpsc::unbounded_channel();
368 let show_logs = log::is_tui_log_capture_enabled();
369 let transient_active = Arc::new(TransientActivitySignal::default());
370 let transient_active_for_session = transient_active.clone();
371
372 let worker = tokio::spawn(async move {
373 if let Err(error) = run_tui(
374 command_rx,
375 event_tx,
376 TuiOptions {
377 surface_preference: UiSurfacePreference::from(options.surface_preference),
378 inline_rows: options.inline_rows,
379 show_logs,
380 log_theme: None,
381 event_callback: options.event_callback,
382 focus_callback: options.focus_callback,
383 active_pty_sessions: options.active_pty_sessions,
384 input_activity_counter: options.input_activity_counter,
385 keyboard_protocol: KeyboardProtocolConfig::from(options.keyboard_protocol),
386 fullscreen: options.fullscreen,
387 workspace_root: options.workspace_root,
388 preview_callback: options.preview_callback.clone(),
389 },
390 move |rows| {
391 let bindings = BindingStore::new(options.key_bindings.clone());
392 let mut session = AppSession::new_with_logs_and_bindings(
393 theme,
394 options.placeholder,
395 rows,
396 show_logs,
397 options.appearance,
398 options.slash_commands,
399 options.app_name,
400 bindings,
401 );
402 session.set_transient_activity_signal(transient_active_for_session.clone());
403 session
404 },
405 )
406 .await
407 {
408 let error_msg = error.to_string();
409 if error_msg.contains("stdin is not a terminal") {
410 vtcode_commons::diagnostics::stderr(format_args!("Error: Interactive TUI requires a proper terminal."));
411 if let Some(hint) = options.non_interactive_hint.as_deref() {
412 eprintln!("{hint}");
413 } else {
414 eprintln!("Use a non-interactive mode in your host app for piped input.");
415 }
416 } else {
417 vtcode_commons::diagnostics::stderr(format_args!("Error: TUI startup failed: {error:#}"));
418 }
419 tracing::error!(%error, "inline session terminated unexpectedly");
420 }
421 });
422
423 Ok(InlineSession {
424 handle: InlineHandle::new_with_transient_signal(InlineCommandSender::Unbounded(command_tx), transient_active),
425 events: event_rx,
426 worker: Some(worker),
427 })
428}
429
430pub fn spawn_session_with_host(
432 theme: InlineTheme,
433 host: &impl crate::tui::host::HostAdapter,
434) -> anyhow::Result<InlineSession> {
435 spawn_session_with_options(theme, SessionOptions::from_host(host))
436}
437
438#[cfg(test)]
439mod tests {
440 use super::*;
441
442 #[tokio::test]
443 async fn host_session_bridges_inputs_and_commands_without_a_tui_worker() {
444 let mut host = new_host_session();
445 assert!(host.session.worker.is_none());
446 host.input
447 .send(InlineEvent::Submit("inspect this file".into()))
448 .expect("send host input");
449 assert!(matches!(
450 host.session.next_event().await,
451 Some(InlineEvent::Submit(input)) if input.text == "inspect this file"
452 ));
453
454 host.session.handle.set_placeholder(Some("ready".to_string()));
455 assert!(matches!(
456 host.commands.recv(),
457 Ok(InlineCommand::SetPlaceholder { hint: Some(hint), .. }) if hint == "ready"
458 ));
459 }
460
461 #[test]
462 fn host_interaction_returns_the_original_approval_choice() {
463 let command = InlineCommand::ShowTransient {
464 request: Box::new(TransientRequest::List(crate::tui::core_tui::app::types::ListOverlayRequest {
465 title: "Approve command".to_string(),
466 lines: vec!["Run the requested command?".to_string()],
467 footer_hint: None,
468 items: vec![crate::tui::core_tui::app::types::InlineListItem::new(
469 "Do not run (Recommended)",
470 Some(InlineListSelection::ToolApproval(false)),
471 )],
472 selected: Some(InlineListSelection::ToolApproval(false)),
473 search: None,
474 hotkeys: Vec::new(),
475 status: None,
476 })),
477 };
478 let interaction = host_interaction_from_command(&command).expect("interaction view");
479 assert_eq!(interaction.kind, HostInteractionKind::Approval);
480 assert!(interaction.steps[0].choices[0].label.contains("Recommended"));
481
482 let event =
483 host_interaction_response(&interaction, &[interaction.steps[0].choices[0].id.clone()], &[None], false)
484 .expect("host response");
485 assert!(matches!(
486 event,
487 InlineEvent::Transient(TransientEvent::Submitted(TransientSubmission::Selection(
488 InlineListSelection::ToolApproval(false)
489 )))
490 ));
491 }
492
493 #[test]
494 fn host_interaction_keeps_single_step_question_wizard_shape_and_freeform_text() {
495 let question = InlineListSelection::RequestUserInputAnswer {
496 question_id: "goal".to_string(),
497 selected: Vec::new(),
498 other: Some(String::new()),
499 };
500 let command = InlineCommand::ShowTransient {
501 request: Box::new(TransientRequest::Wizard(crate::tui::core_tui::app::types::WizardOverlayRequest {
502 title: "Project goal".to_string(),
503 steps: vec![crate::tui::core_tui::app::types::WizardStep {
504 title: "Goal".to_string(),
505 question: "What should this change deliver?".to_string(),
506 items: vec![crate::tui::core_tui::app::types::InlineListItem::new(
507 "Custom answer",
508 Some(question),
509 )],
510 completed: false,
511 answer: None,
512 allow_freeform: true,
513 freeform_label: Some("Custom answer".to_string()),
514 freeform_placeholder: None,
515 freeform_default: None,
516 }],
517 current_step: 0,
518 search: None,
519 mode: crate::tui::core_tui::app::types::WizardModalMode::MultiStep,
520 })),
521 };
522 let interaction = host_interaction_from_command(&command).expect("interaction view");
523 let choice_id = interaction.steps[0].choices[0].id.clone();
524 let event =
525 host_interaction_response(&interaction, &[choice_id], &[Some("Keep the change scoped".to_string())], false)
526 .expect("host response");
527 assert!(interaction.wizard);
528 assert!(matches!(
529 event,
530 InlineEvent::Transient(TransientEvent::Submitted(TransientSubmission::Wizard(selections)))
531 if matches!(selections.as_slice(), [InlineListSelection::RequestUserInputAnswer {
532 question_id,
533 selected,
534 other: Some(answer),
535 }] if question_id == "goal" && selected.is_empty() && answer == "Keep the change scoped")
536 ));
537 }
538
539 struct DemoHost;
540
541 impl crate::tui::host::WorkspaceInfoProvider for DemoHost {
542 fn workspace_name(&self) -> String {
543 "demo".to_string()
544 }
545
546 fn workspace_root(&self) -> Option<PathBuf> {
547 Some(PathBuf::from("/workspace/demo"))
548 }
549 }
550
551 impl crate::tui::host::NotificationProvider for DemoHost {
552 fn set_terminal_focused(&self, _focused: bool) {}
553 }
554
555 impl crate::tui::host::ThemeProvider for DemoHost {
556 fn available_themes(&self) -> Vec<String> {
557 vec!["default".to_string()]
558 }
559
560 fn active_theme_name(&self) -> Option<String> {
561 Some("default".to_string())
562 }
563 }
564
565 impl crate::tui::host::HostAdapter for DemoHost {
566 fn session_defaults(&self) -> crate::tui::host::HostSessionDefaults {
567 crate::tui::host::HostSessionDefaults {
568 surface_preference: SessionSurface::Inline,
569 inline_rows: 24,
570 keyboard_protocol: KeyboardProtocolSettings::default(),
571 fullscreen: FullscreenInteractionSettings::default(),
572 }
573 }
574 }
575
576 #[test]
579 fn session_options_from_host_uses_defaults() {
580 let options = SessionOptions::from_host(&DemoHost);
581
582 assert_eq!(options.surface_preference, SessionSurface::Inline);
583 assert_eq!(options.inline_rows, 24);
584 assert_eq!(options.workspace_root, Some(PathBuf::from("/workspace/demo")));
585 }
586
587 #[test]
588 fn session_options_default_uses_inline_surface() {
589 assert_eq!(SessionOptions::default().surface_preference, SessionSurface::Inline);
590 }
591}