rho-coding-agent 2.6.0

A fast Rust agent harness with a small footprint and opinionated defaults
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
//! Config, OAuth, secret, and reasoning-cycle key handlers for the interactive TUI.

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::DefaultTerminal;

use super::{
    config_editor::{ConfigNumberInput, ConfigNumberSave},
    config_picker, App, ComposerMode, Entry, InteractiveRuntime,
};

impl App {
    pub(super) fn handle_interactive_pending_key(&mut self, key: KeyEvent) -> anyhow::Result<bool> {
        if !matches!(
            self.input_ui.composer(),
            ComposerMode::InteractivePending(_)
        ) {
            return Ok(false);
        }

        match (key.modifiers, key.code) {
            (KeyModifiers::CONTROL, KeyCode::Char('c' | 'C')) => return Ok(false),
            (modifiers, KeyCode::Char('c' | 'C'))
                if !modifiers.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) =>
            {
                let url = match self.input_ui.composer() {
                    ComposerMode::InteractivePending(pending) => {
                        pending.prompt.copyable_url().to_string()
                    }
                    _ => return Ok(true),
                };
                self.copy_text(&url, std::time::Instant::now());
            }
            (_, KeyCode::Esc) => {
                if let Some(pending) = self.pending_interactive_login.take() {
                    pending.handle.abort();
                }
                // Cancelling a pending login is not backing out of setup.
                // Setup picker Esc still calls `dismiss_setup_screen()`.
                self.restore_after_cancelled_login();
                self.clear_transient_key_state();
            }
            _ => {}
        }
        Ok(true)
    }

    pub(super) async fn handle_secret_key(
        &mut self,
        key: KeyEvent,
        terminal: &mut DefaultTerminal,
        agent: &mut InteractiveRuntime,
    ) -> anyhow::Result<bool> {
        match self.apply_secret_key(key) {
            SecretKeyResult::NotSecret => Ok(false),
            SecretKeyResult::Handled => {
                self.clear_transient_key_state();
                Ok(true)
            }
            SecretKeyResult::Submit(submission) => {
                self.clear_transient_key_state();
                self.submit_api_key_login(submission, terminal, agent)
                    .await?;
                Ok(true)
            }
        }
    }

    /// Apply a keystroke to API-key secret input.
    fn apply_secret_key(&mut self, key: KeyEvent) -> SecretKeyResult {
        if !matches!(self.input_ui.composer(), ComposerMode::SecretInput(_)) {
            return SecretKeyResult::NotSecret;
        }

        // Restore before borrowing the secret buffer: Esc needs `&mut self`.
        if matches!(key.code, KeyCode::Esc) {
            self.restore_after_cancelled_login();
            return SecretKeyResult::Handled;
        }

        let ComposerMode::SecretInput(secret) = self.input_ui.composer_mut() else {
            return SecretKeyResult::NotSecret;
        };

        match (key.modifiers, key.code) {
            (KeyModifiers::NONE, KeyCode::Enter) => {
                let submission = secret.submission();
                self.input_ui.set_composer(ComposerMode::Input);
                SecretKeyResult::Submit(submission)
            }
            (_, KeyCode::Backspace) => {
                secret.editor.backspace();
                SecretKeyResult::Handled
            }
            (_, KeyCode::Delete) => {
                secret.editor.delete();
                SecretKeyResult::Handled
            }
            (_, KeyCode::Left) => {
                secret.editor.move_cursor_left();
                SecretKeyResult::Handled
            }
            (_, KeyCode::Right) => {
                secret.editor.move_cursor_right();
                SecretKeyResult::Handled
            }
            (_, KeyCode::Home) => {
                secret.editor.move_cursor_home();
                SecretKeyResult::Handled
            }
            (_, KeyCode::End) => {
                secret.editor.move_cursor_end();
                SecretKeyResult::Handled
            }
            (modifiers, KeyCode::Char(ch))
                if !modifiers.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) =>
            {
                secret.editor.insert_char(ch);
                SecretKeyResult::Handled
            }
            _ => SecretKeyResult::Handled,
        }
    }

    pub(super) fn handle_config_number_key(
        &mut self,
        key: KeyEvent,
        terminal: &mut DefaultTerminal,
    ) -> anyhow::Result<bool> {
        if !matches!(self.input_ui.composer(), ComposerMode::ConfigNumberInput(_)) {
            return Ok(false);
        }

        match (key.modifiers, key.code) {
            (KeyModifiers::NONE, KeyCode::Enter) => {
                let ComposerMode::ConfigNumberInput(input) = self.input_ui.composer() else {
                    return Ok(true);
                };
                if input.key.proposes_confirm() {
                    match input.parsed_value() {
                        Ok(value) => self.propose_prompt_history_limit(value)?,
                        Err(err) => {
                            self.insert_entry(&Entry::Error(err.to_string()));
                            self.set_status("config save failed");
                        }
                    }
                    return Ok(true);
                }
                let saved = match input.save(&self.info.services.config_repository) {
                    Ok(saved) => saved,
                    Err(err) => {
                        self.insert_entry(&Entry::Error(err.to_string()));
                        self.set_status("config save failed");
                        return Ok(true);
                    }
                };
                match saved {
                    ConfigNumberSave::MaxOutputBytes(value) => {
                        self.open_main_config_picker_selected(
                            config_picker::MAX_OUTPUT_BYTES_VALUE,
                        )?;
                        self.set_status(format!(
                            "max output bytes set to {value}; applies next session"
                        ));
                    }
                    ConfigNumberSave::MaxToolOutputLines(value) => {
                        self.info.runtime.max_tool_output_lines = value;
                        self.info
                            .services
                            .diagnostics
                            .update_max_tool_output_lines(value);
                        self.open_main_config_picker_selected(
                            config_picker::MAX_TOOL_OUTPUT_LINES_VALUE,
                        )?;
                        self.clamp_history_scroll_for_terminal(terminal)?;
                        self.set_status(format!("max tool output lines set to {value}"));
                    }
                    ConfigNumberSave::CompactThresholdPercent(value) => {
                        self.open_main_config_picker_selected(
                            config_picker::COMPACT_THRESHOLD_PERCENT_VALUE,
                        )?;
                        self.set_status(format!("compact threshold set to {value}%"));
                    }
                    ConfigNumberSave::CompactTargetPercent(value) => {
                        self.open_main_config_picker_selected(
                            config_picker::COMPACT_TARGET_PERCENT_VALUE,
                        )?;
                        self.set_status(format!("compact target set to {value}%"));
                    }
                    ConfigNumberSave::AgentConcurrency(value) => {
                        self.apply_live_agent_concurrency(value);
                        self.open_main_config_picker_selected(
                            config_picker::AGENT_CONCURRENCY_VALUE,
                        )?;
                        self.set_status(format!("concurrent agents set to {value}"));
                    }
                }
                Ok(true)
            }
            (KeyModifiers::NONE, KeyCode::Backspace) => {
                self.with_config_number_mut(|input| input.editor.backspace());
                Ok(true)
            }
            (KeyModifiers::NONE | KeyModifiers::SHIFT, KeyCode::Char(ch)) => {
                self.with_config_number_mut(|input| input.insert_char(ch));
                Ok(true)
            }
            (_, KeyCode::Left) => {
                self.with_config_number_mut(|input| input.editor.move_cursor_left());
                Ok(true)
            }
            (_, KeyCode::Right) => {
                self.with_config_number_mut(|input| input.editor.move_cursor_right());
                Ok(true)
            }
            (_, KeyCode::Home) => {
                self.with_config_number_mut(|input| input.editor.move_cursor_home());
                Ok(true)
            }
            (_, KeyCode::End) => {
                self.with_config_number_mut(|input| input.editor.move_cursor_end());
                Ok(true)
            }
            (_, KeyCode::Esc) => {
                let ComposerMode::ConfigNumberInput(input) = self.input_ui.composer() else {
                    return Ok(true);
                };
                let selected_value = input.key.picker_value();
                let config = self.info.services.config_repository.load()?;
                self.info.runtime.show_reasoning_output = config.show_reasoning_output;
                self.info.runtime.zen_mode = config.zen_mode;
                self.open_main_config_picker_selected(selected_value)?;
                Ok(true)
            }
            _ => Ok(true),
        }
    }

    pub(super) fn handle_text_input_key(&mut self, key: KeyEvent) -> anyhow::Result<bool> {
        if !matches!(self.input_ui.composer(), ComposerMode::TextInput(_)) {
            return Ok(false);
        }

        match (key.modifiers, key.code) {
            (KeyModifiers::NONE, KeyCode::Enter) => self.commit_text_input(),
            (KeyModifiers::NONE, KeyCode::Backspace) => {
                self.with_text_input_mut(|input| input.editor.backspace());
                Ok(true)
            }
            (KeyModifiers::NONE, KeyCode::Delete) => {
                self.with_text_input_mut(|input| input.editor.delete());
                Ok(true)
            }
            (KeyModifiers::NONE | KeyModifiers::SHIFT, KeyCode::Char(ch)) => {
                self.with_text_input_mut(|input| input.editor.insert_char(ch));
                Ok(true)
            }
            (_, KeyCode::Left) => {
                self.with_text_input_mut(|input| input.editor.move_cursor_left());
                Ok(true)
            }
            (_, KeyCode::Right) => {
                self.with_text_input_mut(|input| input.editor.move_cursor_right());
                Ok(true)
            }
            (_, KeyCode::Home) => {
                self.with_text_input_mut(|input| input.editor.move_cursor_home());
                Ok(true)
            }
            (_, KeyCode::End) => {
                self.with_text_input_mut(|input| input.editor.move_cursor_end());
                Ok(true)
            }
            (_, KeyCode::Esc) => self.cancel_text_input(),
            _ => Ok(true),
        }
    }

    fn commit_text_input(&mut self) -> anyhow::Result<bool> {
        let ComposerMode::TextInput(input) = self.input_ui.composer() else {
            return Ok(true);
        };
        let target = input.target.clone();
        let value = input.editor.value.clone();
        match target {
            super::text_input::TextInputTarget::ConfigApiKey(key) => {
                let save_result = save_config_api_key(self.credential_store.as_ref(), key, &value);
                match save_result {
                    Ok(()) => {
                        self.refresh_web_search_config_picker(key.picker_value())?;
                        self.set_status(format!("{} saved", key.label()));
                    }
                    Err(err) => {
                        self.insert_entry(&Entry::Error(format!(
                            "could not save {}: {err}",
                            key.label()
                        )));
                        self.set_status("config save failed");
                    }
                }
            }
            super::text_input::TextInputTarget::AgentField(field) => {
                self.commit_agent_text_input(field, value)?;
            }
            super::text_input::TextInputTarget::CustomHost(step) => {
                self.submit_custom_host_step(step, value)?;
            }
        }
        Ok(true)
    }

    fn cancel_text_input(&mut self) -> anyhow::Result<bool> {
        let ComposerMode::TextInput(input) = self.input_ui.composer() else {
            return Ok(true);
        };
        let target = input.target.clone();
        match target {
            super::text_input::TextInputTarget::ConfigApiKey(key) => {
                self.refresh_web_search_config_picker(key.picker_value())?;
                self.set_status("web search config");
            }
            super::text_input::TextInputTarget::AgentField(field) => {
                self.reopen_agent_field_picker(field.value());
            }
            super::text_input::TextInputTarget::CustomHost(_) => self.cancel_custom_host_step(),
        }
        Ok(true)
    }

    pub(super) async fn handle_reasoning_cycle_key(
        &mut self,
        key: KeyEvent,
        agent: &mut InteractiveRuntime,
    ) -> anyhow::Result<bool> {
        let is_shift_tab = matches!(key.code, KeyCode::BackTab)
            || (matches!(key.code, KeyCode::Tab) && key.modifiers.contains(KeyModifiers::SHIFT));
        if !is_shift_tab {
            return Ok(false);
        }

        self.cycle_reasoning(agent).await?;
        self.clear_transient_key_state();
        Ok(true)
    }

    pub(super) fn execute_config_command(
        &mut self,
        terminal: &mut DefaultTerminal,
    ) -> anyhow::Result<()> {
        let config = self.info.services.config_repository.load()?;
        self.info.runtime.max_tool_output_lines = config.max_tool_output_lines.max(1);
        self.info
            .services
            .diagnostics
            .update_max_tool_output_lines(self.info.runtime.max_tool_output_lines);
        self.info.runtime.show_reasoning_output = config.show_reasoning_output;
        self.info.runtime.zen_mode = config.zen_mode;
        self.input_ui
            .set_composer(ComposerMode::Picker(config_picker::config_picker(
                &self.info.runtime,
                &config,
            )));
        self.set_status("config");
        terminal.draw(|frame| self.draw(frame))?;
        Ok(())
    }

    fn with_config_number_mut(&mut self, f: impl FnOnce(&mut ConfigNumberInput)) {
        if let ComposerMode::ConfigNumberInput(input) = self.input_ui.composer_mut() {
            f(input);
        }
    }

    fn with_text_input_mut(&mut self, f: impl FnOnce(&mut super::text_input::TextInput)) {
        if let ComposerMode::TextInput(input) = self.input_ui.composer_mut() {
            f(input);
        }
    }
}

enum SecretKeyResult {
    NotSecret,
    Handled,
    Submit(super::login::ApiKeySubmission),
}

fn save_config_api_key(
    credential_store: &dyn rho_providers::credentials::CredentialStore,
    key: super::config_editor::ConfigTextKey,
    value: &str,
) -> rho_providers::credentials::CredentialResult<()> {
    use rho_providers::credentials::{delete_web_search_api_key, save_web_search_api_key};
    let value = value.trim();
    let credential = key.web_search_credential();
    if value.is_empty() {
        delete_web_search_api_key(credential_store, credential).map(|_| ())
    } else {
        save_web_search_api_key(credential_store, credential, value)
    }
}

#[cfg(test)]
#[path = "config_input_tests.rs"]
mod tests;