1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
//! ReadConsole callback and prompt handling.
use crate::config::HistoryForgetConfig;
use crate::history::HistoryStore;
use crossterm::{
ExecutableCommand,
style::Stylize,
terminal::{self, ClearType},
};
use reedline::{HistoryItemId, Signal};
use std::io::{self, Write};
use super::history::{finalize_history, save_ipc_history};
use super::state::{PendingHistoryContext, SpongeQueue};
use super::{
MetaAction, REPL_STATE, RPrompt, SessionInfoContext, arf_eprintln, arf_println,
clear_input_lines, execute_shell_command, handle_meta_command_result, meta_command,
process_meta_command, strip_reprex_output,
};
struct ApprovedInteractiveIpcOperation {
reply: tokio::sync::oneshot::Sender<crate::ipc::protocol::IpcResponse>,
wrote_newline: bool,
}
/// Record the outcome for a command that has already been saved by reedline.
///
/// R normally reports this outcome when the next top-level prompt is requested.
/// Formatter failures never reach R, so they use the same persistence and
/// sponge bookkeeping immediately before returning to the input loop.
fn record_command_outcome(
store: Option<HistoryStore>,
history_id: Option<HistoryItemId>,
failed: bool,
forget_config: &HistoryForgetConfig,
sponge_queue: &mut SpongeQueue,
) {
if let (Some(store), Some(history_id)) = (&store, history_id) {
let exit_status = if failed { 1i64 } else { 0i64 };
if let Err(error) = store.set_exit_status(history_id, exit_status) {
log::warn!("Failed to update history exit status: {error}");
}
}
if forget_config.enabled {
let effective_delay = if forget_config.on_exit_only {
usize::MAX
} else {
forget_config.delay
};
if let Some(id_to_delete) = sponge_queue.record_command(failed, history_id, effective_delay)
&& let Some(store) = &store
&& let Err(error) = store.delete(id_to_delete)
{
log::warn!("Failed to remove forgotten history entry {id_to_delete}: {error}");
}
}
}
/// Ask for approval for an operation that executes in the user's interactive
/// session, replying with the standard rejection when it is declined.
fn approve_interactive_ipc_operation(
code: &str,
reply: tokio::sync::oneshot::Sender<crate::ipc::protocol::IpcResponse>,
) -> Option<ApprovedInteractiveIpcOperation> {
crate::ipc::set_r_at_prompt(false);
let approval = crate::ipc::approve_user_input(code, &reply);
if approval.approved {
Some(ApprovedInteractiveIpcOperation {
reply,
wrote_newline: approval.wrote_newline,
})
} else {
crate::ipc::set_r_at_prompt(true);
crate::ipc::reject_user_input_not_approved(reply);
None
}
}
/// ReadConsole callback function.
/// This is called by R when it needs user input.
///
/// With the Validator in place, reedline handles multiline input internally.
/// The callback receives complete expressions (possibly with embedded newlines)
/// from reedline and passes them to R.
pub(super) fn read_console_callback(
r_prompt: &str,
prompt_info: arf_libr::ReadConsolePromptInfo,
) -> Option<String> {
REPL_STATE.with(|state| {
// Use try_borrow_mut to detect re-entrant calls.
// This is a defensive measure in case R unexpectedly calls ReadConsole
// while we're still processing a previous call. This was originally
// needed when RValidator called harp::is_expression_complete (which
// invokes R's parser), but is now less critical since we switched to
// a tree-sitter-r based validator that doesn't call into R.
let mut guard = match state.try_borrow_mut() {
Ok(guard) => guard,
Err(_) => {
// Re-entrant call detected - RefCell already borrowed.
// Return None (EOF) to terminate the nested call.
// This prevents panic from double borrow.
return None;
}
};
let state = guard.as_mut()?;
if state.should_exit {
return None;
}
if should_warn_prompt_ambiguity(
&mut state.r_prompt_options_ambiguous,
prompt_info.options_are_ambiguous,
) {
arf_eprintln!(
r#"Warning: options("prompt") and options("continue") are identical; arf cannot distinguish top-level and continuation prompts."#
);
}
// The low-level ReadConsole callback reads both prompt options once and
// supplies their metadata here. Classify the prompt once so every
// lifecycle, IPC, display, menu, formatter, and history decision shares
// one value.
let prompt_kind = classify_prompt(r_prompt, prompt_info.is_continuation);
// R startup and user profiles can replace options(error) after
// initialize_r returns. Capture and wrap the resulting handler at the
// first real command prompt, before returning any user input to R.
if prompt_kind.is_command() && !state.error_handler_setup_attempted {
state.error_handler_setup_attempted = true;
if !arf_libr::command_outcome_tracking_available() {
log::info!("R library lacks safe error-state inspection; command outcomes are unavailable");
} else {
match arf_harp::eval_string_in_base(arf_libr::global_error_handler_code()) {
Ok(_) => {
log::info!("R error handler initialized after startup");
arf_libr::mark_global_error_handler_initialized();
}
Err(error) => {
log::warn!("Failed to initialize R error handler: {error:?}");
}
}
}
}
// Update exit_status for the previous command when a new prompt is shown.
// This is called when R has finished evaluating and wants new input.
// Continuation prompts identified by the low-level option lookup mean
// we're still in the same expression.
// Non-command prompts (menus, etc.) should also not trigger exit status updates.
// Track prompt state for IPC: true when R is idle at the command
// prompt, false for continuation/menu/selection prompts so IPC
// requests are correctly rejected during non-command prompts.
crate::ipc::set_r_at_prompt(prompt_kind.is_command());
if prompt_kind.is_command() && !state.prompt_config.is_shell_enabled() {
let pending_history_context = std::mem::take(&mut state.pending_history_context);
let outcome = match pending_history_context {
PendingHistoryContext::Command { store, history_id } => {
let outcome = arf_libr::command_outcome();
if let Some(failed) = outcome_failure_projection(outcome) {
record_command_outcome(
store,
history_id,
failed,
&state.forget_config,
&mut state.sponge_queue,
);
}
Some(outcome)
}
PendingHistoryContext::None => None,
};
// Update prompt status indicator for the next prompt
if let Some(outcome) = outcome {
match outcome_failure_projection(outcome) {
Some(failed) => state.prompt_config.set_last_command_failed(failed),
None => state.prompt_config.set_last_command_outcome_unknown(),
}
}
// Calculate duration for the {duration} prompt placeholder
state.prompt_config.set_command_duration();
// Reset error state for the next command
arf_libr::reset_command_error_state();
}
// Prepared help is consumed only at a verified command prompt, after
// the previous command's lifecycle has been finalized and before IPC
// dispatch or reedline starts reading the next command.
if should_process_pending_help_requests(
prompt_kind,
state.prompt_config.is_shell_enabled(),
) {
super::pager_ui::process_pending_help_requests();
}
// Check for pending IPC operations before entering the reedline input loop.
// At this point reedline hasn't started, so there's no editor buffer to
// conflict with — we can always accept.
if prompt_kind.is_command()
&& !state.prompt_config.is_shell_enabled()
&& let Some(op) = crate::ipc::take_pending_ipc_operation()
{
use crate::ipc::{
PendingIpcKind, accept_user_input, run_silent_eval, setup_visible_eval,
};
match op.kind {
PendingIpcKind::SilentEvaluate { reply } => {
// Run silent evaluate directly — no buffer conflict possible.
// Unlike visible eval / user_input, silent eval does not return
// code to R. It runs synchronously here and then falls through
// to the reedline loop below to wait for user input.
run_silent_eval(&op.code, reply);
}
PendingIpcKind::VisibleEvaluate { reply, timeout } => {
if let Some(ApprovedInteractiveIpcOperation { reply, .. }) =
approve_interactive_ipc_operation(&op.code, reply)
{
setup_visible_eval(reply, timeout);
let store = state.r_history.store();
let history_id = save_ipc_history(
state.line_editor.history_mut(),
store,
&op.code,
state.history_session_id,
);
if !op.code.trim().is_empty() {
state.pending_history_context = PendingHistoryContext::Command {
store: state.r_history.store(),
history_id,
};
}
let prompt_str = "agent> ";
println!("{}{}", prompt_str.dark_cyan(), op.code);
if !op.code.is_empty() {
state.prompt_config.set_command_start();
state.prompt_config.start_spinner();
}
crate::ipc::set_r_at_prompt(false);
return Some(op.code);
}
}
PendingIpcKind::UserInput { reply } => {
if let Some(ApprovedInteractiveIpcOperation { reply, .. }) =
approve_interactive_ipc_operation(&op.code, reply)
{
accept_user_input(reply);
let store = state.r_history.store();
let history_id = save_ipc_history(
state.line_editor.history_mut(),
store,
&op.code,
state.history_session_id,
);
if !op.code.trim().is_empty() {
state.pending_history_context = PendingHistoryContext::Command {
store: state.r_history.store(),
history_id,
};
}
let prompt_str = "agent> ";
println!("{}{}", prompt_str.dark_cyan(), op.code);
if !op.code.is_empty() {
state.prompt_config.set_command_start();
state.prompt_config.start_spinner();
}
crate::ipc::set_r_at_prompt(false);
return Some(op.code);
}
}
}
}
loop {
// Build prompt dynamically from config.
// We detect the type of prompt R is asking for:
// - Continuation prompts are identified by PromptKind (multiline input)
// - Command prompts are identified by PromptKind at R's top level
// - Non-standard prompts (menus, etc.) are passed through directly
let prompt = if prompt_kind.is_continuation() {
state.prompt_config.build_cont_prompt(state.reprex.mode)
} else if prompt_kind.is_command() {
state.prompt_config.build_main_prompt(state.reprex.mode)
} else {
// Non-standard prompt from R (menu selection, etc.)
// Pass through R's actual prompt instead of our configured one
RPrompt::new(r_prompt.to_string(), r_prompt.to_string())
};
// Use shell editor when in shell mode (for separate history)
let is_shell_mode = state.prompt_config.is_shell_enabled();
let history_handle = if is_shell_mode {
state.shell_history.clone()
} else {
state.r_history.clone()
};
let editor = if is_shell_mode {
&mut state.shell_line_editor
} else {
&mut state.line_editor
};
// Process R events once before entering the input loop.
// The idle callback will continue processing events at ~30fps while waiting for input,
// keeping graphics windows (plot(), help browser) responsive.
arf_libr::process_r_events();
// Track whether we're in a non-standard prompt mode (menu selection, etc.)
let is_menu_prompt = prompt_kind.is_other();
let read_result = editor.read_line(&prompt);
// Keep startup echo suppression through the raw-mode transition.
// The original cooked mode is restored only after reedline returns,
// so early PTY input cannot pass through an echo window.
if read_result.is_ok()
&& let Err(error) = crate::console_mode::handoff_to_reedline()
{
eprintln!("Error: {}", error);
state.should_exit = true;
return None;
}
match read_result {
Ok(Signal::Success(line)) => {
let save_outcome = history_handle.receipt_outcome();
// For non-standard prompts (menus, etc.), pass input directly to R
// without any processing (meta commands, shell mode, or reprex)
if is_menu_prompt {
// Deliberately leave pending_history_context alone. This
// input was requested by R during an evaluation that is
// already in progress (readline(), menu(), browser()),
// so the outer command still owns the result. Claiming
// the context here would strand the outer entry without
// an exit status, which matters most when that entry
// came from IPC and cannot be recovered from reedline's
// own last-command context.
finalize_history(Some(&history_handle), save_outcome, false);
return Some(line);
}
// Check for meta commands first
if let Some(result) = process_meta_command(
&line,
&mut state.prompt_config,
&mut state.reprex,
&state.r_history,
&state.shell_history,
&state.r_source_status,
&mut state.dir_stack,
state.history_session_id.map(i64::from),
state.r_home.as_deref(),
) {
finalize_history(Some(&history_handle), save_outcome, true);
// Clear duration so the previous R command's time
// does not persist in the prompt after a meta command.
state.prompt_config.clear_command_duration();
let ctx = SessionInfoContext {
prompt_config: &state.prompt_config,
reprex: &state.reprex,
config_file_info: &state.config_file_info,
history_location: &state.history_location,
r_history: &state.r_history,
shell_history: &state.shell_history,
r_source_status: &state.r_source_status,
};
match handle_meta_command_result(result, &ctx) {
MetaAction::Continue => continue,
MetaAction::Exit => {
state.should_exit = true;
return None;
}
}
}
finalize_history(Some(&history_handle), save_outcome, false);
// Shell mode: execute as shell command instead of R
if is_shell_mode {
let trimmed = line.trim();
if !trimmed.is_empty() {
// Check if user wants to exit shell mode.
// We compare commands as strings because Shell mode doesn't run
// a persistent shell process - each command is executed via
// `$SHELL -c "command"`. There's no actual shell session to exit,
// so we intercept "exit" and "logout" to return to R mode instead
// of running them as no-op shell commands.
if trimmed == "exit" || trimmed == "logout" {
state.prompt_config.set_shell(false);
arf_println!("Returned to R mode.");
continue;
}
// Show a hint for cd/pushd/popd since they have no effect
// in a subprocess. The command still runs in the shell.
if let Some(hint) = meta_command::dir_command_hint(trimmed) {
arf_println!("{}", hint);
}
execute_shell_command(trimmed);
}
continue;
}
// In reprex mode, strip lines starting with "#>" (reprex output comments)
// This allows users to paste reprex output directly without duplicate output
// Keep original for line count calculation in clear_input_lines
let (original_line, line) = if state.reprex.is_enabled() {
(line.clone(), strip_reprex_output(&line))
} else {
(line.clone(), line)
};
// Format code when format mode is enabled.
let code = match state.reprex.maybe_format_code(&line) {
Ok(code) => code,
Err(error) => {
arf_println!("{}", error);
// A continuation input still belongs to the outer
// command. It must not finalize that command's
// history or sponge state merely because formatting
// this piece failed.
if formatter_failure_updates_lifecycle(prompt_kind) {
let history_id = match save_outcome {
Some(crate::history::HistorySaveOutcome::Saved(id)) => Some(id),
_ => None,
};
record_command_outcome(
history_handle.store(),
history_id,
true,
&state.forget_config,
&mut state.sponge_queue,
);
state.prompt_config.set_last_command_failed(true);
state.prompt_config.clear_command_duration();
}
continue;
}
};
// In reprex mode, clear the prompt and input lines
// Show the (possibly formatted) code
// Use original_line for line count since that's what was displayed on terminal
if state.reprex.is_enabled() && !code.is_empty() {
clear_input_lines(&original_line, &code);
}
// Record command start time for the {duration} prompt placeholder
// Start the spinner to indicate R is evaluating code
// The spinner will be stopped when R produces output or the next prompt appears
if !code.is_empty() {
state.prompt_config.set_command_start();
state.prompt_config.start_spinner();
}
// Mark R as busy (no longer at prompt) for IPC
crate::ipc::set_r_at_prompt(false);
// Return the (possibly formatted) code to R
// Only a top-level command starts a new Reedline history
// context. Continuation prompts remain part of the outer
// command, so preserve its context until evaluation ends.
if prompt_kind.is_command() && !code.trim().is_empty() {
let history_id = match save_outcome {
Some(crate::history::HistorySaveOutcome::Saved(id)) => Some(id),
_ => None,
};
state.pending_history_context = PendingHistoryContext::Command {
store: history_handle.store(),
history_id,
};
}
return Some(code);
}
Ok(Signal::CtrlC) => {
// Clear any visible completion menu before printing ^C
let _ = io::stdout().execute(terminal::Clear(ClearType::FromCursorDown));
println!("^C");
// In shell mode, Ctrl+C returns to R mode
if state.prompt_config.is_shell_enabled() {
state.prompt_config.set_shell(false);
arf_println!("Returned to R mode.");
continue;
}
return Some(String::new());
}
Ok(Signal::CtrlD) => {
// Clear any visible menu before proceeding
let _ = io::stdout().execute(terminal::Clear(ClearType::FromCursorDown));
// In shell mode, Ctrl+D returns to R mode (consistent with Ctrl+C)
if state.prompt_config.is_shell_enabled() {
state.prompt_config.set_shell(false);
arf_println!("Returned to R mode.");
continue;
}
state.should_exit = true;
return None;
}
Ok(Signal::ExternalBreak(buffer)) => {
// IPC operation triggered a break signal.
// Check the editor buffer for mutual exclusion with console input.
if let Some(op) = crate::ipc::take_pending_ipc_operation() {
use crate::ipc::{
PendingIpcKind, accept_user_input, reject_operation_user_typing,
run_silent_eval, setup_visible_eval,
};
// If the user has typed something, reject the IPC operation.
// We use trim() because reedline may include trailing whitespace
// in the buffer; whitespace-only input is treated as empty.
if !buffer.trim().is_empty() {
reject_operation_user_typing(op, &buffer);
continue;
}
// Helper: clear the current prompt line and show agent prefix
let clear_and_show_agent_prompt = |code: &str| {
let mut out = io::stdout();
let _ = out.execute(crossterm::cursor::MoveToColumn(0));
let _ = out.execute(terminal::Clear(ClearType::CurrentLine));
println!("{}{}", "agent> ".dark_cyan(), code);
};
// Silent evaluate: run in-place and return to reedline
if let PendingIpcKind::SilentEvaluate { reply } = op.kind {
// Show visual indicator, run eval, then return to reedline
{
let mut out = io::stdout();
let _ = out.execute(crossterm::cursor::MoveToColumn(0));
let _ = out.execute(terminal::Clear(ClearType::CurrentLine));
print!("{}", "[evaluating...]".dark_cyan());
let _ = out.flush();
}
run_silent_eval(&op.code, reply);
// Clear the indicator — reedline will repaint the prompt
{
let mut out = io::stdout();
let _ = out.execute(crossterm::cursor::MoveToColumn(0));
let _ = out.execute(terminal::Clear(ClearType::CurrentLine));
}
continue;
}
// Visible evaluate / user input: accept, inject code into REPL.
// Preserve whether approval already emitted its CRLF.
let approval_wrote_newline = match op.kind {
PendingIpcKind::VisibleEvaluate { reply, timeout } => {
let Some(ApprovedInteractiveIpcOperation {
reply,
wrote_newline,
}) = approve_interactive_ipc_operation(&op.code, reply)
else {
continue;
};
setup_visible_eval(reply, timeout);
wrote_newline
}
PendingIpcKind::UserInput { reply } => {
let Some(ApprovedInteractiveIpcOperation {
reply,
wrote_newline,
}) = approve_interactive_ipc_operation(&op.code, reply)
else {
continue;
};
accept_user_input(reply);
wrote_newline
}
PendingIpcKind::SilentEvaluate { .. } => unreachable!(),
};
let history_id = save_ipc_history(
editor.history_mut(),
history_handle.store(),
&op.code,
state.history_session_id,
);
if !op.code.trim().is_empty() {
state.pending_history_context = PendingHistoryContext::Command {
store: history_handle.store(),
history_id,
};
}
clear_and_show_agent_prompt(&op.code);
// ExternalBreak leaves reedline's previous prompt position suspended.
// Its saved row range includes the line after a single-line prompt, so
// leave the cursor one row beyond that range. Otherwise, when R produces
// no output, the next repaint reuses the old prompt origin and clears the
// echoed agent line.
if !approval_wrote_newline {
println!();
}
if !op.code.is_empty() {
state.prompt_config.set_command_start();
state.prompt_config.start_spinner();
}
crate::ipc::set_r_at_prompt(false);
return Some(op.code);
}
// No pending operation (spurious signal), continue waiting
continue;
}
Ok(_) => continue,
Err(err) => {
eprintln!("Error: {}", err);
state.should_exit = true;
return None;
}
}
}
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PromptKind {
Command,
UnverifiedCommand,
Continuation,
Other,
}
impl PromptKind {
fn is_command(self) -> bool {
matches!(self, Self::Command | Self::UnverifiedCommand)
}
fn is_verified_command(self) -> bool {
matches!(self, Self::Command)
}
fn is_continuation(self) -> bool {
matches!(self, Self::Continuation)
}
fn is_other(self) -> bool {
matches!(self, Self::Other)
}
}
/// Classify a ReadConsole prompt once per callback.
///
/// Continuation status comes directly from R's low-level option lookup. For
/// every other prompt, call sys.nframe() once to distinguish a top-level command
/// prompt from input requested by user code (readline(), menu(), browser(), …).
fn classify_prompt(prompt: &str, is_continuation: bool) -> PromptKind {
if is_continuation {
return PromptKind::Continuation;
}
match arf_harp::r_n_frame() {
Ok(0) => PromptKind::Command,
Ok(_) => PromptKind::Other,
Err(_) => {
// Preserve the historical command-prompt fallback for lifecycle
// and IPC behavior, while marking it unverified for operations
// that require a confirmed top-level prompt.
if prompt.ends_with("> ") {
PromptKind::UnverifiedCommand
} else {
PromptKind::Other
}
}
}
}
/// Formatter failures only finalize lifecycle state for top-level commands.
/// Continuation prompts belong to the outer command and retain its context.
fn formatter_failure_updates_lifecycle(prompt_kind: PromptKind) -> bool {
prompt_kind.is_command()
}
fn should_process_pending_help_requests(prompt_kind: PromptKind, shell_enabled: bool) -> bool {
prompt_kind.is_verified_command() && !shell_enabled
}
/// Project a reliable R outcome into the prompt, history, and sponge lifecycle.
/// An unavailable outcome has no reliable boolean projection.
fn outcome_failure_projection(outcome: arf_libr::CommandOutcome) -> Option<bool> {
match outcome {
arf_libr::CommandOutcome::Success => Some(false),
arf_libr::CommandOutcome::Failure => Some(true),
arf_libr::CommandOutcome::Unavailable => None,
}
}
/// Warn once for each transition into an ambiguous prompt-option state.
fn should_warn_prompt_ambiguity(was_ambiguous: &mut bool, is_ambiguous: bool) -> bool {
let should_warn = is_ambiguous && !*was_ambiguous;
*was_ambiguous = is_ambiguous;
should_warn
}
#[cfg(test)]
mod tests {
use super::{
PromptKind, classify_prompt, formatter_failure_updates_lifecycle,
outcome_failure_projection, should_process_pending_help_requests,
should_warn_prompt_ambiguity,
};
#[test]
fn unavailable_outcome_does_not_project_to_lifecycle_consumers() {
assert_eq!(
outcome_failure_projection(arf_libr::CommandOutcome::Unavailable),
None
);
assert_eq!(
outcome_failure_projection(arf_libr::CommandOutcome::Success),
Some(false)
);
assert_eq!(
outcome_failure_projection(arf_libr::CommandOutcome::Failure),
Some(true)
);
}
#[test]
fn continuation_formatter_failure_keeps_outer_lifecycle_context() {
assert!(!formatter_failure_updates_lifecycle(
PromptKind::Continuation
));
}
#[test]
fn prepared_help_is_drained_only_at_a_command_prompt_outside_shell_mode() {
assert!(should_process_pending_help_requests(
PromptKind::Command,
false
));
assert!(!should_process_pending_help_requests(
PromptKind::Command,
true
));
assert!(!should_process_pending_help_requests(
PromptKind::UnverifiedCommand,
false
));
assert!(!should_process_pending_help_requests(
PromptKind::Continuation,
false
));
assert!(!should_process_pending_help_requests(
PromptKind::Other,
false
));
}
#[test]
fn prompt_classification_prioritizes_low_level_continuation_status() {
assert_eq!(classify_prompt("... ", true), PromptKind::Continuation,);
}
#[test]
fn prompt_classification_falls_back_for_uninitialized_r() {
let prompt_kind = classify_prompt("> ", false);
assert_eq!(prompt_kind, PromptKind::UnverifiedCommand);
assert!(prompt_kind.is_command());
assert!(!prompt_kind.is_verified_command());
assert_eq!(classify_prompt("Selection: ", false), PromptKind::Other,);
}
#[test]
fn prompt_ambiguity_warning_is_rearmed_after_distinct_options() {
let mut was_ambiguous = false;
assert!(should_warn_prompt_ambiguity(&mut was_ambiguous, true));
assert!(!should_warn_prompt_ambiguity(&mut was_ambiguous, true));
assert!(!should_warn_prompt_ambiguity(&mut was_ambiguous, false));
assert!(should_warn_prompt_ambiguity(&mut was_ambiguous, true));
}
}