arf-console 0.4.5

A cross-platform R console written in Rust
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
//! ReadConsole callback and prompt handling.

use crossterm::{
    ExecutableCommand,
    style::Stylize,
    terminal::{self, ClearType},
};
use reedline::Signal;
use std::io::{self, Write};

use super::history::save_ipc_history;
use super::state::PendingHistoryContext;
use super::{
    MetaAction, REPL_STATE, RPrompt, SessionInfoContext, arf_println, clear_input_lines,
    execute_shell_command, handle_meta_command_result, meta_command, process_meta_command,
    strip_reprex_output,
};

/// 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) -> 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;
        }

        // 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 (starting with '+') 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(is_r_command_prompt(r_prompt));

        if is_r_command_prompt(r_prompt) && !state.prompt_config.is_shell_enabled() {
            let pending_history_context = std::mem::take(&mut state.pending_history_context);
            let had_error = match pending_history_context {
                PendingHistoryContext::Reedline => {
                    if state.line_editor.has_last_command_context() {
                        let had_error = arf_libr::command_had_error();
                        let exit_status = if had_error { 1i64 } else { 0i64 };

                        // Use Cell to capture the history item ID through the immutable closure
                        let captured_id: std::cell::Cell<Option<reedline::HistoryItemId>> =
                            std::cell::Cell::new(None);
                        let _ = state.line_editor.update_last_command_context(&|mut item| {
                            item.exit_status = Some(exit_status);
                            captured_id.set(item.id);
                            item
                        });

                        // Sponge feature: track all commands and purge old failed ones.
                        // See SpongeQueue for the algorithm details.
                        if state.forget_config.enabled {
                            // Determine effective delay: use configured delay normally,
                            // or usize::MAX for on_exit_only (defer all deletions until exit)
                            let effective_delay = if state.forget_config.on_exit_only {
                                usize::MAX
                            } else {
                                state.forget_config.delay
                            };

                            if let Some(id_to_delete) = state.sponge_queue.record_command(
                                had_error,
                                captured_id.get(),
                                effective_delay,
                            ) {
                                let _ = state.line_editor.history_mut().delete(id_to_delete);
                            }
                        }
                        had_error
                    } else {
                        false
                    }
                }
                PendingHistoryContext::Ipc { history_id } => {
                    // IPC history is saved before evaluation. Reedline's
                    // History::update API accepts that saved ID, so update the
                    // IPC entry directly instead of touching the previous
                    // interactive entry. This also preserves the error status
                    // for IPC commands in the history database.
                    let had_error = arf_libr::command_had_error();
                    if let Some(history_id) = history_id {
                        let exit_status = if had_error { 1i64 } else { 0i64 };
                        let _ = state
                            .line_editor
                            .history_mut()
                            .update(history_id, &|mut item| {
                                item.exit_status = Some(exit_status);
                                item
                            });
                    }
                    had_error
                }
                PendingHistoryContext::None => false,
            };

            // Update prompt status indicator for the next prompt
            state.prompt_config.set_last_command_failed(had_error);

            // 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();
        }

        // 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 is_r_command_prompt(r_prompt)
            && !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 } => {
                    setup_visible_eval(reply, timeout);
                    let history_id = save_ipc_history(
                        &mut state.line_editor,
                        &op.code,
                        state.history_session_id,
                    );
                    if !op.code.trim().is_empty() {
                        state.pending_history_context = PendingHistoryContext::Ipc { 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 } => {
                    accept_user_input(reply);
                    let history_id = save_ipc_history(
                        &mut state.line_editor,
                        &op.code,
                        state.history_session_id,
                    );
                    if !op.code.trim().is_empty() {
                        state.pending_history_context = PendingHistoryContext::Ipc { 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 start with '+' (multiline input)
            // - Command prompts typically end with "> " (R's default prompt)
            // - Non-standard prompts (menus, etc.) are passed through directly
            let prompt = if r_prompt.starts_with('+') {
                state.prompt_config.build_cont_prompt()
            } else if is_r_command_prompt(r_prompt) {
                state.prompt_config.build_main_prompt()
            } 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 editor = if state.prompt_config.is_shell_enabled() {
                &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 = !is_r_command_prompt(r_prompt) && !r_prompt.starts_with('+');

            match editor.read_line(&prompt) {
                Ok(Signal::Success(line)) => {
                    // For non-standard prompts (menus, etc.), pass input directly to R
                    // without any processing (meta commands, shell mode, reprex, autoformat)
                    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.
                        return Some(line);
                    }

                    // Check for meta commands first
                    if let Some(result) = process_meta_command(
                        &line,
                        &mut state.prompt_config,
                        &state.r_history_path,
                        &state.shell_history_path,
                        &state.r_source_status,
                        &mut state.dir_stack,
                        state.history_session_id.map(i64::from),
                        state.r_home.as_deref(),
                    ) {
                        // 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,
                            config_path: &state.config_path,
                            config_status: state.config_status,
                            r_history_path: &state.r_history_path,
                            shell_history_path: &state.shell_history_path,
                            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;
                            }
                        }
                    }

                    // Shell mode: execute as shell command instead of R
                    if state.prompt_config.is_shell_enabled() {
                        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.prompt_config.is_reprex_enabled() {
                        (line.clone(), strip_reprex_output(&line))
                    } else {
                        (line.clone(), line)
                    };

                    // Format code if autoformat is enabled
                    let code = state.prompt_config.maybe_format_code(&line);

                    // 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.prompt_config.is_reprex_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 is_r_command_prompt(r_prompt) && !code.trim().is_empty() {
                        state.pending_history_context = PendingHistoryContext::Reedline;
                    }
                    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
                        match op.kind {
                            PendingIpcKind::VisibleEvaluate { reply, timeout } => {
                                setup_visible_eval(reply, timeout);
                            }
                            PendingIpcKind::UserInput { reply } => {
                                accept_user_input(reply);
                            }
                            PendingIpcKind::SilentEvaluate { .. } => unreachable!(),
                        }

                        let history_id =
                            save_ipc_history(editor, &op.code, state.history_session_id);
                        if !op.code.trim().is_empty() {
                            state.pending_history_context =
                                PendingHistoryContext::Ipc { 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.
                        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;
                }
            }
        }
    })
}

/// Check if the prompt is R's standard command prompt (top-level).
///
/// Uses R's call stack depth (sys.nframe()) to determine if we're at the top-level
/// or if user code is requesting input (e.g., via readline() or menu()).
///
/// This approach is more robust than heuristics like checking prompt endings,
/// because it detects the actual R evaluation context.
///
/// Returns true if:
/// - We're at the top-level (n_frame == 0) AND not a continuation prompt
///
/// Returns false if:
/// - This is a continuation prompt (starts with '+')
/// - User code is requesting input (n_frame > 0), e.g., readline(), menu()
///
/// Reference: This approach is used by ark (Positron's R kernel).
fn is_r_command_prompt(prompt: &str) -> bool {
    // Continuation prompts (starting with '+') are NOT command prompts
    //
    // TODO: R lets users change this prefix with options(continue = "..."),
    // and a custom value is then misread as a command prompt. Compare against
    // R's configured continuation string instead. Every caller of this
    // function is affected, including IPC request admission.
    if prompt.starts_with('+') {
        return false;
    }

    // Use R's call stack depth to detect if we're at top-level
    // n_frame == 0 means top-level prompt
    // n_frame > 0 means user code is requesting input (readline, menu, etc.)
    match arf_harp::r_n_frame() {
        Ok(n_frame) => n_frame == 0,
        Err(_) => {
            // If we can't get n_frame, fall back to heuristic
            // R's default prompt ends with "> ", menu prompts end with ": "
            prompt.ends_with("> ")
        }
    }
}