rho-coding-agent 3.0.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
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
use crate::tui::DefaultTerminal;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

use super::{
    command_actions::CommandSubmission,
    command_palette::{slash_command_args, CommandPaletteKeyOutcome},
    commands,
    composer_buffer::ComposerEditKey,
    send_confirm::SendSubmission,
    ActivityPhase, App, ChatMedia, ComposerMode, InputSubmissionMode, PasteSegment,
    PendingLoginFinish, QueuedPrompt, TurnPrompt,
};

/// A turn held until MCP servers and OpenAPI sources finish loading.
pub(super) struct HeldTurn {
    pub(super) turn: TurnPrompt,
    pub(super) media: Vec<ChatMedia>,
    /// Kept so `esc` can hand the prompt back exactly as it was typed.
    pub(super) paste_segments: Vec<PasteSegment>,
    pub(super) origin: HeldOrigin,
}

/// Where a held turn came from, which decides how it is sent once its wait
/// is over and what `esc` does with it meanwhile.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum HeldOrigin {
    /// The composer: `esc` hands the prompt back to it.
    Composer,
    /// The composer, for a prompt to a daemon session the person confirmed
    /// for this model before it was held (`send_confirm::daemon`): released,
    /// it is asked about again only if the session's model changed since.
    Confirmed(rho_sdk::model::ModelIdentity),
    /// A command of a daemon session that is no send to confirm, as
    /// `/compact`: `esc` hands it back to the composer.
    Command,
    /// The workflow hub of a daemon session, whose launch is a prompt the
    /// person never typed: `esc` cancels it.
    WorkflowHub,
}

impl App {
    fn take_command_submission(
        &mut self,
        invocation: super::CommandInvocation,
        turn: TurnPrompt,
    ) -> CommandSubmission {
        let media = self
            .input_ui
            .take_ready_media()
            .expect("pending attachments block submission");
        let paste_segments = self.input_ui.paste_segments().to_vec();
        let submission = CommandSubmission::new(invocation, turn, media, paste_segments);
        self.clear_submitted_input();
        submission
    }

    /// Route keys owned by modal/overlay composers. Returns true when handled.
    fn handle_composer_mode_key<'a>(
        &'a mut self,
        key: KeyEvent,
        terminal: &'a mut DefaultTerminal,
    ) -> impl std::future::Future<Output = anyhow::Result<bool>> + 'a {
        // Keep modal futures out of every idle key's poll frame, including
        // ordinary Enter and /exit. Allocate in a synchronous frame so debug
        // construction temporaries are gone before polling the handler.
        Box::pin(self.handle_composer_mode_key_inner(key, terminal))
    }

    async fn handle_composer_mode_key_inner(
        &mut self,
        key: crossterm::event::KeyEvent,
        terminal: &mut DefaultTerminal,
    ) -> anyhow::Result<bool> {
        match self.input_ui.composer() {
            ComposerMode::Input => Ok(false),
            ComposerMode::InteractivePending(pending)
                if matches!(pending.finish, PendingLoginFinish::UserConfirms(_))
                    && key.code == KeyCode::Enter
                    && key.modifiers.is_empty() =>
            {
                self.record_daemon_login(terminal).await?;
                Ok(true)
            }
            ComposerMode::InteractivePending(_) => self.handle_interactive_pending_key(key),
            ComposerMode::InlineChoice(_) => self.handle_inline_choice_key(key, terminal).await,
            ComposerMode::Questionnaire(_) => self.handle_questionnaire_key(key),
            ComposerMode::SecretInput(_) => self.handle_secret_key(key, terminal).await,
            ComposerMode::TextInput(_) => self.handle_text_input_key(key),
            ComposerMode::Picker(_) => self.handle_picker_key(key, terminal).await,
            ComposerMode::Panel(_) => {
                let handled = self.handle_panel_overlay_key(key, terminal);
                self.attach_from_jobs_view(terminal).await;
                Ok(handled)
            }
            ComposerMode::Side => Ok(self.handle_side_chat_key(key, terminal)),
            ComposerMode::TranscriptSearch(_) => Ok(self.handle_transcript_search_key(key)),
            // Approvals are handled on the during-turn path, not idle input.
            ComposerMode::Approval(_) => Ok(false),
        }
    }

    pub(super) async fn handle_key(
        &mut self,
        key: KeyEvent,
        terminal: &mut DefaultTerminal,
    ) -> anyhow::Result<()> {
        if self.handle_paste_burst_key(key) {
            return Ok(());
        }

        if self.handle_pending_input_key(key) {
            return Ok(());
        }

        if self.external_editor_shortcut_matches(key) {
            self.open_composer_in_editor(terminal).await?;
            return Ok(());
        }

        if self.handle_history_key(key, terminal)? {
            return Ok(());
        }

        if self.handle_questionnaire_transcript_key(key, terminal)? {
            return Ok(());
        }

        // Overlay / modal composers own keys first. Dispatch by mode so the
        // shared free-text path below only runs for ComposerMode::Input.
        if self.handle_composer_mode_key(key, terminal).await? {
            return Ok(());
        }

        if self.handle_reasoning_cycle_key(key)? {
            return Ok(());
        }

        if self.handle_favorite_cycle_key(key)? {
            return Ok(());
        }

        match self.handle_command_palette_key(key) {
            CommandPaletteKeyOutcome::Ignored => {}
            CommandPaletteKeyOutcome::Handled => {
                self.input_ui.clear_paste_burst();
                self.ctrl_c_streak = 0;
                return Ok(());
            }
            CommandPaletteKeyOutcome::Submit => {
                self.input_ui.clear_paste_burst();
                self.ctrl_c_streak = 0;
                self.submit(terminal).await?;
                return Ok(());
            }
        }

        if self.handle_file_palette_key(key)? {
            return Ok(());
        }

        if self.handle_vim_key(key) {
            return Ok(());
        }

        if self.handle_configurable_composer_key(key, terminal).await? {
            return Ok(());
        }

        if let Some(edit) = ComposerEditKey::from_key(key) {
            self.apply_input_edit_key(edit);
            self.ctrl_c_streak = 0;
            self.clamp_command_selection();
            self.clamp_file_selection();
            return Ok(());
        }
        match (key.modifiers, key.code) {
            (KeyModifiers::CONTROL, KeyCode::Char('c')) => {
                if self.ctrl_c_streak == 0 {
                    self.clear_submitted_input();
                    self.input_ui
                        .set_submission_mode(InputSubmissionMode::ParseCommands);
                    self.notify_status("input cleared; press ctrl-c again to quit");
                    self.ctrl_c_streak = 1;
                } else {
                    self.should_quit = true;
                }
            }
            (_, KeyCode::Esc) => {
                if !self.cancel_inline_shells() && !self.exit_shell_mode() {
                    self.take_back_held_turn();
                }
                self.ctrl_c_streak = 0;
            }
            (_, KeyCode::Enter) => {
                // Reset first: submit runs the whole turn, and a Ctrl-C streak
                // armed during it (leaving attach or peek) must survive.
                self.ctrl_c_streak = 0;
                self.submit(terminal).await?;
            }
            _ => {
                self.input_ui.clear_paste_burst();
                self.ctrl_c_streak = 0;
            }
        }
        self.clamp_command_selection();
        self.clamp_file_selection();
        Ok(())
    }

    pub(super) fn submit<'a>(
        &'a mut self,
        terminal: &'a mut DefaultTerminal,
    ) -> impl std::future::Future<Output = anyhow::Result<()>> + 'a {
        // Submission can poll an entire turn or command. Its construction
        // frame must not stay on the Windows main stack for that whole call.
        Box::pin(self.submit_inner(terminal))
    }

    async fn submit_inner(&mut self, terminal: &mut DefaultTerminal) -> anyhow::Result<()> {
        if self.input_ui.has_pending_attachments() {
            self.notify_status("wait for document extraction to finish before submitting");
            return Ok(());
        }
        let mut turn = TurnPrompt::standard(
            self.expanded_input().trim().to_string(),
            self.input_ui.text().trim().to_string(),
        );
        if turn.model.is_empty()
            && self.input_ui.attachments().is_empty()
            && self.input_ui.shell_mode().is_none()
        {
            self.clear_submitted_input();
            return Ok(());
        }
        if let Some((mode, command)) = self.shell_submission() {
            if !self.input_ui.paste_segments().is_empty() {
                return self.block_pasted_inline_shell();
            }
            self.clear_submitted_input();
            self.start_inline_shell(mode, command)?;
            return Ok(());
        }

        match self.parse_input_command() {
            Ok(Some(invocation)) => {
                // A command the daemon runs as a prompt needs credentials
                // as any prompt does: held for `/login` the same way.
                if super::daemon_gate::command_route(invocation.id)
                    == super::daemon_gate::CommandRoute::Prompt
                    && self.daemon_offers_built_in(invocation.id)
                    && self.daemon_prompt_needs_login()
                {
                    return self.offer_login_instead_of_turn(turn);
                }
                let submission = self.take_command_submission(invocation, turn);
                self.execute_command(submission, terminal).await?;
                return Ok(());
            }
            Ok(None) => {}
            Err(commands::CommandParseError::Unknown(name)) => {
                // `/skill:<name>` goes as the daemon's `/$<name>`, which
                // loads the skill or says why the session cannot.
                if let Some(skill) = name.strip_prefix("skill:") {
                    if !self.daemon_may_load_skill(skill) {
                        self.clear_submitted_input();
                        self.report_unknown_command(&name);
                        return Ok(());
                    }
                    turn =
                        TurnPrompt::command(turn.model, turn.display).with_skill(skill.to_owned());
                } else if !self.daemon_prompt_command_available(&name) {
                    self.clear_submitted_input();
                    self.daemon_command_unavailable(&name);
                    return Ok(());
                }
                if self.daemon_prompt_needs_login() {
                    // The held text is what Enter sends after login, so a
                    // template is held expanded. The daemon expands one it
                    // is sent as typed.
                    let trailing = slash_command_args(&turn.model).trim().to_string();
                    if let Some(prompt) = self.resolve_prompt_template(&name, &trailing) {
                        turn = TurnPrompt::standard(prompt.clone(), prompt);
                    }
                    return self.offer_login_instead_of_turn(turn);
                }
            }
        }

        // The daemon session runs the turn: it loads the skills the prompt
        // mentions and owns tools and compaction. A prompt it could only
        // refuse for want of credentials offers `/login` first.
        if self.daemon_prompt_needs_login() {
            return self.offer_login_instead_of_turn(turn);
        }
        let media = self
            .input_ui
            .take_ready_media()
            .expect("pending attachments block submission");
        let paste_segments = self.input_ui.paste_segments().to_vec();
        self.clear_submitted_input();
        self.submit_daemon_turn(turn, media, paste_segments, terminal)
            .await
    }

    pub(super) fn hold_turn(
        &mut self,
        turn: TurnPrompt,
        media: Vec<ChatMedia>,
        paste_segments: Vec<PasteSegment>,
    ) {
        self.hold(HeldTurn {
            turn,
            media,
            paste_segments,
            origin: HeldOrigin::Composer,
        });
    }

    /// Holds `held` until the session's tool sources loaded.
    pub(super) fn hold(&mut self, held: HeldTurn) {
        self.held_turns.push_back(held);
        self.turn
            .set_activity_phase(ActivityPhase::LoadingToolSources);
        self.turn.start_loading_if_needed();
        self.set_tool_sources_loading_status();
    }

    /// Hand the most recently held turn back to the composer, so `esc` unwinds
    /// prompts newest first instead of leaving them to run. Does nothing unless
    /// the composer is empty, so it cannot overwrite something the person has
    /// started typing since. A workflow the hub started is cancelled instead,
    /// whatever the composer holds: the composer never held its command.
    fn take_back_held_turn(&mut self) {
        let composer_in_use =
            !self.input_ui.text().is_empty() || !self.input_ui.attachments().is_empty();
        match self.held_turns.back().map(|held| &held.origin) {
            Some(HeldOrigin::Composer | HeldOrigin::Confirmed(_) | HeldOrigin::Command)
                if composer_in_use =>
            {
                return
            }
            Some(
                HeldOrigin::Composer
                | HeldOrigin::Confirmed(_)
                | HeldOrigin::Command
                | HeldOrigin::WorkflowHub,
            )
            | None => {}
        }
        let Some(HeldTurn {
            turn,
            media,
            paste_segments,
            origin,
        }) = self.held_turns.pop_back()
        else {
            return;
        };
        match origin {
            HeldOrigin::Composer | HeldOrigin::Confirmed(_) | HeldOrigin::Command => self
                .restore_pending_prompt(QueuedPrompt {
                    prompt: turn.model,
                    display_prompt: turn.display,
                    paste_segments,
                    media,
                }),
            HeldOrigin::WorkflowHub => {}
        }
        if !self.held_turns.is_empty() {
            // Older holds are still waiting. Leave their status alone: writing
            // any status here would hand `status_source` back to `Other`, and
            // `show_daemon_tool_sources_loaded` would never retire the indicator.
            return;
        }
        self.clear_tool_sources_loading_activity();
        self.set_status_quiet("");
    }

    pub(super) fn clear_tool_sources_loading_activity(&mut self) {
        if matches!(
            self.turn.activity_phase(),
            ActivityPhase::LoadingToolSources
        ) {
            self.turn.set_activity_phase(ActivityPhase::default());
            if !self.turn.is_busy() {
                self.turn.stop_loading();
            }
        }
    }

    pub(super) fn restore_tool_sources_hold_activity_if_needed(&mut self) {
        if self.held_turns.is_empty() || !self.tool_sources_pending() || self.turn.is_busy() {
            return;
        }
        self.turn
            .set_activity_phase(ActivityPhase::LoadingToolSources);
        self.turn.start_loading_if_needed();
    }

    /// Start the next held turn whose wait is over. One per call, so several
    /// held turns run in submission order. Reports whether anything changed so
    /// the caller can redraw.
    pub(super) async fn release_pending_held_turn(
        &mut self,
        terminal: &mut DefaultTerminal,
    ) -> anyhow::Result<bool> {
        // The session may be running a turn another client or a background
        // result started; the held one waits for it to end.
        if self.input_ui.composer().blocks_held_turn_start()
            || self.is_ui_busy()
            || self.tool_sources_pending()
        {
            return Ok(false);
        }
        let Some(HeldTurn {
            turn,
            media,
            paste_segments,
            origin,
        }) = self.held_turns.pop_front()
        else {
            return Ok(false);
        };
        self.set_status_quiet("");
        if self.held_turns.is_empty() {
            self.clear_tool_sources_loading_activity();
        }
        match origin {
            HeldOrigin::WorkflowHub => self.send_daemon_workflow(turn, terminal).await?,
            HeldOrigin::Command => {
                self.send_daemon_command(turn, media, paste_segments, terminal)
                    .await?;
            }
            HeldOrigin::Confirmed(model) => {
                let submission =
                    SendSubmission::turn(turn, media, paste_segments).approve_for(model);
                self.submit_daemon_submission(submission, terminal).await?;
            }
            HeldOrigin::Composer => {
                self.submit_daemon_turn(turn, media, paste_segments, terminal)
                    .await?;
            }
        }
        Ok(true)
    }
}

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