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