Skip to main content

trusty_code_tui/app/
reduce.rs

1//! [`apply`] — the `ReplApp` half of [`crate::run::event_loop`]'s
2//! `apply: FnMut(&mut M, ReplEvent)` contract.
3//!
4//! Why: Slice 4 (already on main) needed *some* `apply` closure so the
5//! widgets could be demonstrated against real key input before DOC-50 §5
6//! Slice 5 ("Event dispatch and line editing") landed as its own slice — it
7//! shipped the generic core: character insertion/deletion, cursor movement,
8//! history recall, and scroll. Slice 5 (this revision) completes the keymap
9//! to full parity with tagent's actual `crates/trusty-agents/src/repl/tui/keys.rs`
10//! (not its doc comments, which in at least one case — Up-arrow —
11//! misattribute production behavior to a dead-code helper) and wires
12//! [`ReplApp::pending_submit`]/[`ReplApp::pending_cancel`] through to
13//! `TuiEngine::handle_input`/`cancel_session` in [`crate::run::run`]. See
14//! [`crate::app`]'s module doc comment for the full disclosed-differences
15//! list. Tagent-specific extras (pickers, slash-completion, cost/token
16//! tracking) stay behind per the generalization mandate; line-editing
17//! features tagent's own `keys.rs` never had either (Ctrl-w word-delete, a
18//! kill-ring, word-motion) are deliberately NOT invented here — full parity
19//! means matching tagent, not exceeding it.
20//!
21//! What: `apply` cannot reach the event channel or the engine — it only has
22//! `&mut ReplApp` — so anything that would normally need to call
23//! `TuiEngine::handle_input`/`cancel_session` instead stages a signal on
24//! `ReplApp` ([`ReplApp::pending_submit`], [`ReplApp::pending_cancel`]) for
25//! the caller to drain after `apply` returns, mirroring tagent's own
26//! `pending_picker_selection`/`pending_cancel` precedent
27//! (`crates/trusty-agents/src/repl/tui/types.rs`). [`crate::run::run`]'s
28//! dispatch step is the actual drain point — see that module for the
29//! `engine.handle_input`/`engine.cancel_session` wiring and the
30//! `ReplEvent::Quit` round-trip an engine's `Ok(false)` needs to reach
31//! `ReplApp::quit`, since a spawned task can't reach `&mut ReplApp` directly.
32//!
33//! # Spec References
34//! - [`SPEC-TTUI-05~draft`](docs/specs/DOC-50-tcode-tui-claude-code-clone.md#SPEC-TTUI-05~draft) — Slice 5 deliverable (§5, Slice 5): line-editor keymap + Ctrl-C daemon cancel.
35
36use super::{CANCELLED_STATUS, ChatLine, ChatRole, Delegation, ReplApp, ToolCard};
37use crate::event::{DelegationOutcome, KeyCode, KeyInput, ReplEvent};
38use crate::model::{CancelReply, PendingPermission, PermissionAnswer};
39use crate::text::{strip_interior_blank_lines, trim_surrounding_blank_lines};
40// #8237: the scrollback permission row folds a multi-line subject through the
41// same helper the boxed prompt uses, rather than a second copy that can drift.
42use crate::widgets::permission_prompt::fold_to_one_line;
43
44/// How many lines a Page-Up/Page-Down key press scrolls.
45const PAGE_SCROLL: isize = 10;
46
47/// Apply one [`ReplEvent`] to `app`, mutating it in place.
48///
49/// Why: a free function (rather than an `ReplApp` method) so it matches
50/// `crate::run::event_loop`'s `apply: impl FnMut(&mut M, ReplEvent)` shape
51/// exactly — a caller passes `trusty_code_tui::app::apply` directly as that
52/// argument.
53/// What: dispatches on every [`ReplEvent`] variant (see the module doc
54/// comment for what's out of scope). `Key` events are further dispatched by
55/// [`apply_key`].
56/// Test: `tests` below cover every variant this function actually changes
57/// state for.
58pub fn apply(app: &mut ReplApp, ev: ReplEvent) {
59    match ev {
60        ReplEvent::Key(key) => apply_key(app, key),
61        ReplEvent::Resize(_, _) => {
62            // No-op: ratatui reads the real terminal size on every `draw`;
63            // nothing in `ReplApp` caches a stale width/height to refresh.
64        }
65        ReplEvent::Scroll(delta) => app.scroll(delta),
66        ReplEvent::Submit(line) => app.submit_line(line),
67        ReplEvent::Cancel => app.pending_cancel = true,
68        // #8207: the cancel's reply, not the request, is what ends the turn.
69        ReplEvent::CancelSettled(reply) => apply_cancel_settled(app, reply),
70        ReplEvent::Quit => app.quit = true,
71        // `crate::run::dispatch_pending`'s completion safety net (see
72        // `ReplEvent::TurnFinished`'s doc comment for the stuck-`busy`
73        // deadlock this closes). Applied ONLY if `generation` still matches
74        // `app.current_generation` — a stale signal from a turn that was
75        // since cancelled/superseded is a no-op, by construction (this
76        // compare runs serially in the reducer, never as a spawned task's
77        // load-then-branch against the shared counter — see that variant's
78        // doc comment for the TOCTOU race this closes). When applied, it
79        // touches ONLY these two fields, never `chat`, so it can never push
80        // a stray blank entry.
81        ReplEvent::TurnFinished { generation } => {
82            if generation == app.current_generation {
83                app.busy = false;
84                app.streaming_idx = None;
85            }
86        }
87        ReplEvent::AssistantOutput {
88            chunk,
89            done,
90            is_error,
91        } => apply_assistant_output(app, chunk, done, is_error),
92        ReplEvent::ToolInvocation {
93            id,
94            agent_id,
95            tool_name,
96            args,
97            result,
98            failed,
99        } => {
100            let card = ToolCard {
101                id,
102                tool_name,
103                args,
104                result,
105                failed,
106                // #4596: `apply_tool_invocation` decides the real default
107                // once it knows whether the call completed and how.
108                collapsed: false,
109            };
110            apply_tool_invocation(app, card, &agent_id);
111        }
112        ReplEvent::AgentOutput {
113            agent_id,
114            turn_id,
115            chunk,
116            done,
117        } => apply_agent_output(app, agent_id, turn_id, chunk, done),
118        ReplEvent::DelegationStarted {
119            agent_id,
120            agent,
121            task,
122        } => apply_delegation_started(app, agent_id, agent, task),
123        ReplEvent::DelegationFinished {
124            agent_id,
125            agent,
126            outcome,
127        } => apply_delegation_finished(app, agent_id, agent, outcome),
128        ReplEvent::PermissionRequested {
129            request_id,
130            agent,
131            agent_id,
132            tool,
133            subject,
134            rule,
135        } => apply_permission_requested(
136            app,
137            PendingPermission {
138                request_id,
139                agent,
140                agent_id,
141                tool,
142                subject,
143                rule,
144            },
145        ),
146        ReplEvent::PermissionResolved {
147            request_id,
148            agent,
149            decision,
150            source,
151            ..
152        } => apply_permission_resolved(app, &request_id, &agent, &decision, &source),
153        ReplEvent::PermissionAnswerFailed { pending, error } => {
154            apply_permission_answer_failed(app, pending, &error)
155        }
156        ReplEvent::StatusMessage(msg) => app.push_status(msg),
157        ReplEvent::ClearScrollback => app.clear_scrollback(),
158        // #8164: the splash replaces the banner's identity row — see
159        // `ReplEvent::SplashUpdated`. Stored verbatim; nothing is parsed.
160        ReplEvent::SplashUpdated(lines) => app.splash = lines,
161        ReplEvent::StatuslineUpdate(segments) => app.statusline = segments,
162        ReplEvent::WorkstreamUpdated(ws) => app.active_workstream = Some(ws),
163        ReplEvent::WorkstreamActivationChanged { new_active_id, .. } => {
164            if new_active_id.is_none() {
165                // The workstream was deactivated with no replacement active
166                // (DOC-48 §4.2/§4.3, a real daemon-published state — see this
167                // variant's own doc comment). `WorkstreamUpdated`'s payload
168                // is a concrete `WorkstreamSummary`, so it structurally
169                // CANNOT represent "no active workstream" — there is no
170                // follow-up `WorkstreamUpdated` to wait for here, unlike the
171                // `Some(new_id)` case below. This is the only place the
172                // indicator gets cleared; skipping it (as a prior revision
173                // did, treating this whole variant as an unconditional
174                // no-op) left the status line showing a stale workstream
175                // name forever after a deactivation.
176                app.active_workstream = None;
177            }
178            // A `Some(new_id)` activation: per
179            // `TuiEngine::subscribe_workstream_events`'s contract, the
180            // engine follows this with a `WorkstreamUpdated` carrying the
181            // full re-fetched summary — that event, not this one, is what
182            // sets the displayed name (this event alone names an id with no
183            // display name to show yet).
184        }
185        ReplEvent::ConnectionLost { reason } => {
186            app.push_status(format!("Connection lost: {reason}"))
187        }
188    }
189}
190
191/// Apply the backend's answer to a dispatched cancel (#8207).
192///
193/// Why: this is the only place the TUI is entitled to say a run stopped, and
194/// the three arms differ in exactly that. `Stopped` ends the turn and reopens
195/// input. `StillCancelling` keeps both [`ReplApp::busy`] and
196/// [`ReplApp::cancelling`] set, because the run has not stopped — reopening
197/// input there is #8207's original bug, and the operator's next Ctrl-C simply
198/// asks again. `Failed` leaves the cancelling state (so the pane cannot sit on
199/// "cancelling…" forever behind a dead transport) but NOT `busy`: the cancel
200/// never landed, so the turn is still presumed in flight and Ctrl-C retries it.
201/// No arm prints a protocol code — each payload string is the plain sentence
202/// [`CancelReply`] requires of its producer.
203/// What: a reply arriving with no cancel outstanding is ignored, so a straggler
204/// from an already-settled cancel (a second Ctrl-C's reply, say) cannot clear
205/// `busy` for a turn the user has since started.
206/// Test: [`tests::apply_cancel_settled_stopped_reopens_input`],
207/// [`tests::apply_cancel_settled_still_cancelling_keeps_input_closed`],
208/// [`tests::apply_cancel_settled_failed_leaves_the_cancelling_state_without_claiming_a_stop`],
209/// [`tests::apply_cancel_settled_is_ignored_when_no_cancel_is_outstanding`],
210/// [`tests::no_cancel_settled_arm_renders_a_protocol_code`].
211fn apply_cancel_settled(app: &mut ReplApp, reply: CancelReply) {
212    if !app.cancelling {
213        return;
214    }
215    match reply {
216        CancelReply::Stopped => {
217            app.cancelling = false;
218            app.busy = false;
219            app.streaming_idx = None;
220            app.push_status(CANCELLED_STATUS);
221        }
222        CancelReply::StillCancelling { detail } => {
223            app.push_status(format!(
224                "still cancelling — the run has not stopped yet: {detail}. Ctrl-C asks again."
225            ));
226        }
227        CancelReply::Failed { error } => {
228            app.cancelling = false;
229            app.push_status(format!(
230                "cancel failed: {error}. The turn is still assumed to be running — Ctrl-C retries the cancel."
231            ));
232        }
233    }
234}
235
236/// Accumulate one streamed assistant-output chunk into the in-progress chat
237/// entry, finalizing (trim + role) it on `done`.
238///
239/// Why: split out of [`apply`] so the streaming state machine — "append to
240/// the open entry, or open a new one" — reads as its own unit.
241/// What: mirrors [`ReplApp::push_assistant`]'s trim/collapse pass, but only
242/// on the *finished* text (trimming mid-stream would strip a blank line the
243/// next chunk was about to fill back in). Also refreshes
244/// [`ReplApp::last_bash_block`] on finalize, same as `push_assistant`
245/// (Ctrl-E's paste buffer must not go stale just because a response arrived
246/// via streaming instead of a single push).
247/// Test: [`tests::apply_assistant_output_streams_into_one_entry`],
248/// [`tests::apply_assistant_output_finalizes_as_error_role`],
249/// [`tests::apply_assistant_output_refreshes_last_bash_block_on_finalize`].
250fn apply_assistant_output(app: &mut ReplApp, chunk: String, done: bool, is_error: bool) {
251    match app.streaming_idx {
252        Some(idx) => {
253            if let Some(entry) = app.chat.get_mut(idx) {
254                entry.text.push_str(&chunk);
255            }
256        }
257        None => {
258            app.chat.push(ChatLine {
259                role: ChatRole::Assistant,
260                text: chunk,
261                tool: None,
262            });
263            app.streaming_idx = Some(app.chat.len() - 1);
264        }
265    }
266    app.busy = !done;
267    app.scroll_offset = 0;
268
269    if done
270        && let Some(idx) = app.streaming_idx.take()
271        && let Some(entry) = app.chat.get_mut(idx)
272    {
273        let trimmed = trim_surrounding_blank_lines(&entry.text);
274        entry.text = strip_interior_blank_lines(&trimmed);
275        if is_error {
276            entry.role = ChatRole::Error;
277        }
278        app.update_last_bash_block();
279    }
280}
281
282/// Whether `agent_id` names a delegation whose block is currently open
283/// (#7940).
284///
285/// Why: an empty `agent_id` means "no attribution", which must never match
286/// an open block — otherwise an unattributed event would be filed under
287/// whichever delegation happened to be running.
288fn is_delegated(app: &ReplApp, agent_id: &str) -> bool {
289    !agent_id.is_empty() && app.delegations.iter().any(|d| d.agent_id == agent_id)
290}
291
292/// Push one line into the scrollback with `role`, pinning the view to the
293/// newest content (#7940).
294fn push_delegated(app: &mut ReplApp, role: ChatRole, text: String) {
295    app.chat.push(ChatLine {
296        role,
297        text,
298        tool: None,
299    });
300    app.scroll_offset = 0;
301}
302
303/// File one half of a tool call — its start or its completion — into that
304/// call's card (#4596).
305///
306/// Why: a call and its result arrive as two `ToolInvocation` events sharing
307/// `id`. Pushing each as its own line split one call across two scrollback
308/// entries.
309/// What: a completion whose `id` names an open card fills that card's
310/// `result` in place and releases the key; a repeated start for an open card
311/// is a no-op. Anything else opens a new card, keyed by `id` while it runs.
312/// Placement is decided once, when the card opens: [`ChatRole::Delegated`]
313/// inside an open delegation block (#7940), [`ChatRole::Status`] otherwise.
314/// An empty `id` never correlates. The completion's own `args` are dropped,
315/// since producers send `Null` there.
316/// A completed call also picks its default render state (#4596): collapsed
317/// on success, expanded on failure ([`ToolCard::is_error`]) so the error
318/// text is never hidden behind a keystroke. A still-running card stays
319/// expanded — its body is the single `running…` row.
320/// Test: [`tests::tool_invocation_result_merges_into_its_call_card`],
321/// [`tests::tool_invocation_result_without_a_start_opens_its_own_card`],
322/// [`tests::tool_invocation_attributed_to_a_delegation_is_delegated_role`],
323/// [`tests::tool_card_is_error_reads_the_event_failure_flag`].
324fn apply_tool_invocation(app: &mut ReplApp, mut card: ToolCard, agent_id: &str) {
325    app.scroll_offset = 0;
326    if !card.id.is_empty()
327        && let Some(&idx) = app.tool_cards.get(&card.id)
328        && let Some(open) = app.chat.get_mut(idx).and_then(|e| e.tool.as_mut())
329        && open.id == card.id
330    {
331        if card.result.is_some() {
332            open.result = card.result;
333            // #4596: the completion carries the verdict; the start event
334            // never could.
335            open.failed = card.failed;
336            open.collapsed = !open.is_error();
337            app.tool_cards.remove(&card.id);
338        }
339        return;
340    }
341    card.collapsed = card.result.is_some() && !card.is_error();
342    if card.id.is_empty() || card.result.is_some() {
343        app.tool_cards.remove(&card.id);
344    } else {
345        app.tool_cards.insert(card.id.clone(), app.chat.len());
346    }
347    let role = if is_delegated(app, agent_id) {
348        ChatRole::Delegated
349    } else {
350        ChatRole::Status
351    };
352    app.chat.push(ChatLine {
353        role,
354        text: String::new(),
355        tool: Some(card),
356    });
357}
358
359/// Accumulate one attributed output chunk into the bubble for its
360/// `(agent_id, turn_id)` stream (#7940).
361///
362/// Why: [`apply_assistant_output`] accumulates into ONE unkeyed slot
363/// (`ReplApp::streaming_idx`), so a primary agent and a delegated sub-agent
364/// streaming inside the same human turn appended into a single chat entry —
365/// their words physically interleaved. Keying the in-progress entry by the
366/// producer's own `(agent_id, turn_id)` pair makes that impossible by
367/// construction rather than by luck of arrival order.
368/// What: find-or-open the entry for the key, append, and on `done` trim it
369/// and drop the key. The entry's role is decided ONCE, when it is opened:
370/// `Delegated` when the id names an open delegation block, `Assistant`
371/// otherwise. `busy` is deliberately untouched — one agent's turn ending is
372/// not the human turn ending, which only `AssistantOutput { done: true }`
373/// reports.
374/// Test: [`tests::agent_output_keys_concurrent_streams_separately`],
375/// [`tests::agent_output_finalizes_and_drops_its_key`],
376/// [`tests::agent_output_inside_a_delegation_is_delegated_role`].
377fn apply_agent_output(
378    app: &mut ReplApp,
379    agent_id: String,
380    turn_id: String,
381    chunk: String,
382    done: bool,
383) {
384    let key = (agent_id, turn_id);
385    let idx = match app.agent_streams.get(&key) {
386        Some(&idx) => idx,
387        None => {
388            // A terminal delta carries no text of its own (see
389            // `ReplEvent::AgentOutput`), so opening a bubble for one whose
390            // stream we never saw would push a permanently blank entry.
391            if done && chunk.is_empty() {
392                return;
393            }
394            let role = if is_delegated(app, &key.0) {
395                ChatRole::Delegated
396            } else {
397                ChatRole::Assistant
398            };
399            app.chat.push(ChatLine {
400                role,
401                text: String::new(),
402                tool: None,
403            });
404            let idx = app.chat.len() - 1;
405            app.agent_streams.insert(key.clone(), idx);
406            idx
407        }
408    };
409    if let Some(entry) = app.chat.get_mut(idx) {
410        entry.text.push_str(&chunk);
411    }
412    app.scroll_offset = 0;
413
414    if done {
415        app.agent_streams.remove(&key);
416        if let Some(entry) = app.chat.get_mut(idx) {
417            let trimmed = trim_surrounding_blank_lines(&entry.text);
418            entry.text = strip_interior_blank_lines(&trimmed);
419        }
420        app.update_last_bash_block();
421    }
422}
423
424/// Open a delegated sub-agent's scrollback block (#7940).
425///
426/// Why: this is what makes delegation visible at all — without a header the
427/// sub-agent's output and tool calls arrive indistinguishable from the
428/// primary agent's.
429/// What: pushes a [`ChatRole::Delegation`] header and registers the
430/// delegation so later attributed events file under it. A second
431/// `DelegationStarted` for the same agent ADOPTS the open block instead of
432/// opening a duplicate — a producer that announces its intent to delegate
433/// before the sub-agent exists (no `agent_id` yet) and then reports the real
434/// spawn emits two events for one delegation.
435/// Test: [`tests::delegation_started_pushes_header_and_sets_active_agent`],
436/// [`tests::delegation_started_with_id_adopts_an_announced_block`],
437/// [`tests::delegation_started_twice_for_distinct_ids_opens_two_blocks`].
438fn apply_delegation_started(app: &mut ReplApp, agent_id: String, agent: String, task: String) {
439    if let Some(open) = app
440        .delegations
441        .iter_mut()
442        .find(|d| d.agent == agent && (d.agent_id.is_empty() || d.agent_id == agent_id))
443    {
444        if open.agent_id.is_empty() {
445            open.agent_id = agent_id;
446        }
447        return;
448    }
449    app.delegations.push(Delegation {
450        agent_id,
451        agent: agent.clone(),
452    });
453    let text = if task.trim().is_empty() {
454        format!("▶ {agent}")
455    } else {
456        format!("▶ {agent} — {task}")
457    };
458    push_delegated(app, ChatRole::Delegation, text);
459}
460
461/// Close a delegated sub-agent's scrollback block with its outcome (#7940).
462///
463/// Why: a block with no footer reads as still-running forever, and "finished"
464/// vs. "blew up" is the single fact an operator watching a delegation most
465/// needs.
466/// What: pushes a [`ChatRole::Delegation`] footer naming the outcome, drops
467/// the delegation (so [`ReplApp::active_agent`] reverts), and drops any
468/// still-open stream key for that agent — a failed loop aborts mid-turn and
469/// never sends its terminal chunk, which would otherwise leak a map entry
470/// for the life of the session. The footer renders even for an id this
471/// client never saw start (a TUI that attached mid-delegation), rather than
472/// dropping the only report of how the run ended.
473/// Test: [`tests::delegation_finished_pushes_footer_and_clears_active_agent`],
474/// [`tests::delegation_finished_failed_footer_carries_the_error`],
475/// [`tests::delegation_finished_drops_an_unterminated_stream_key`].
476fn apply_delegation_finished(
477    app: &mut ReplApp,
478    agent_id: String,
479    agent: String,
480    outcome: DelegationOutcome,
481) {
482    app.delegations
483        .retain(|d| !(d.agent_id == agent_id && d.agent == agent));
484    app.agent_streams.retain(|(aid, _), _| aid != &agent_id);
485    let text = match outcome {
486        DelegationOutcome::Finished(status) if status.trim().is_empty() => format!("└ {agent}"),
487        DelegationOutcome::Finished(status) => format!("└ {agent} — {status}"),
488        DelegationOutcome::Failed(error) => format!("└ {agent} — failed: {error}"),
489    };
490    push_delegated(app, ChatRole::Delegation, text);
491}
492
493/// Open the modal permission prompt and record the request in the
494/// scrollback (#3422).
495///
496/// Why: the request has to survive in the transcript even after the prompt
497/// closes — an operator reading back needs to see what was asked, not only
498/// what was answered. The prompt itself is separate state because it is
499/// re-rendered every frame and addressed by `request_id`.
500/// What: pushes one [`ChatRole::Status`] line naming the tool, the
501/// already-redacted subject and the matched rule, then stores the request.
502/// The subject goes through the SAME
503/// [`fold_to_one_line`](crate::widgets::permission_prompt::fold_to_one_line)
504/// the boxed widget uses, so a multi-statement command reads the same in
505/// both places. A second request arriving while one is open REPLACES it: the
506/// backend suspends one call per agent loop, so an overlap means the first is
507/// already resolved (its `PermissionResolved` may simply not have landed
508/// yet) and stacking prompts would block on a request nobody can answer.
509/// Test: [`tests::permission_requested_opens_a_prompt_and_records_it`],
510/// [`tests::permission_requested_twice_keeps_only_the_newest_prompt`],
511/// [`tests::permission_requested_folds_a_multi_line_subject_in_scrollback`].
512fn apply_permission_requested(app: &mut ReplApp, pending: PendingPermission) {
513    let mut text = format!("permission: {} wants {}", pending.agent, pending.tool);
514    if !pending.subject.trim().is_empty() {
515        // #8237: the scrollback row is one `Span`, and a raw `\n` inside a
516        // `Span` renders as nothing — folding is what keeps `echo one` and
517        // `echo two` from appearing as `echo oneecho two`.
518        text.push_str(&format!(" — {}", fold_to_one_line(&pending.subject)));
519    }
520    text.push_str(&format!(" (rule: {})", pending.rule));
521    app.push_status(text);
522    // #3422: a fresh request carries no failed answer — never inherit the
523    // retry line from the prompt this one replaces.
524    app.permission_error = None;
525    app.pending_permission = Some(pending);
526}
527
528/// Record a permission decision and close the prompt it answers (#3422).
529///
530/// Why: the backend is the only authority on how a request resolved — it may
531/// have timed out, been answered by another client, or been covered by a
532/// grant this client never saw. Recording ITS word (rather than the local key
533/// press) is what keeps the scrollback honest.
534/// What: pushes one [`ChatRole::Status`] line carrying the producer's own
535/// `decision`/`source` words verbatim, and clears
536/// [`ReplApp::pending_permission`] only when the ids match — a resolution for
537/// some other request must not unblock the prompt the user is looking at.
538/// Test: [`tests::permission_resolved_clears_the_prompt_and_records_the_decision`],
539/// [`tests::permission_resolved_for_another_request_leaves_the_prompt_pending`].
540fn apply_permission_resolved(
541    app: &mut ReplApp,
542    request_id: &str,
543    agent: &str,
544    decision: &str,
545    source: &str,
546) {
547    app.push_status(format!("permission: {agent} — {decision} (by {source})"));
548    if app
549        .pending_permission
550        .as_ref()
551        .is_some_and(|p| p.request_id == request_id)
552    {
553        app.pending_permission = None;
554        app.permission_error = None;
555    }
556}
557
558/// Reopen the prompt whose answer never reached the backend (#3422).
559///
560/// Why: [`ReplApp::answer_permission`] clears the prompt the instant a key is
561/// pressed, ahead of the RPC, so a slow backend can never freeze the
562/// keyboard. A failed relay makes that optimism wrong: the call is still
563/// suspended on the backend, and with the modal gone the operator has no way
564/// to answer it again. This restores the question.
565/// What: records the engine's own error text in the scrollback and, unless
566/// some OTHER prompt is already open, puts the request back with
567/// [`ReplApp::permission_error`] set so the prompt draws its retry line. A
568/// newer prompt wins: the backend suspends one call per agent loop, so an
569/// open prompt means this request is already moot.
570/// Test: [`tests::permission_answer_failed_reopens_the_prompt_with_a_retry_line`],
571/// [`tests::permission_answer_failed_never_clobbers_a_newer_prompt`],
572/// `crate::run::tests::dispatch_pending_permission_answer_failure_reopens_the_prompt`.
573fn apply_permission_answer_failed(app: &mut ReplApp, pending: PendingPermission, error: &str) {
574    app.push_status(format!(
575        "permission answer failed: {error} — {} is still waiting; answer again",
576        pending.tool
577    ));
578    if app.pending_permission.is_some() {
579        return;
580    }
581    app.permission_error = Some(format!("answer failed ({error}) — retry"));
582    app.pending_permission = Some(pending);
583}
584
585/// The answer bound to `key` while a permission prompt is open (#3422), or
586/// `None` for a key that is not one of the three bindings.
587///
588/// Why: kept pure so the whole keymap is testable without driving a frame,
589/// and so "which keys answer" is one readable list rather than arms scattered
590/// through [`apply_key`]. The bindings extend #3422's original y/n proposal
591/// with the third answer #7948's wire protocol added — a prompt offering only
592/// allow-once and deny would nag on every repeat of the same call.
593/// What: `y`/`Y` allow once, `a`/`A` allow for the session, `n`/`N`/Esc deny
594/// — exactly the keys [`crate::widgets::permission_prompt`]'s footer
595/// advertises, and nothing else. Enter is deliberately UNBOUND; see the
596/// inline note on the match below. `AllowForSession` carries `pattern: None`
597/// deliberately: choosing a grant width is policy, and policy is the
598/// backend's (ADR-0063).
599/// Test: [`tests::permission_key_y_answers_allow_once`],
600/// [`tests::permission_key_a_answers_allow_for_session`],
601/// [`tests::permission_key_n_answers_deny`],
602/// [`tests::permission_key_escape_answers_deny`],
603/// [`tests::permission_unbound_key_leaves_the_prompt_pending`],
604/// [`tests::enter_while_a_permission_prompt_is_pending_does_not_submit`].
605fn permission_answer_for_key(key: KeyInput) -> Option<PermissionAnswer> {
606    if key.modifiers.ctrl || key.modifiers.alt {
607        return None;
608    }
609    // #3422: no `KeyCode::Enter` arm. A prior revision mapped Enter to
610    // `AllowOnce`, a grant the footer never advertises — an operator pressing
611    // Enter to send the line they were typing would silently approve the
612    // suspended call. An unadvertised key must never answer; Enter falls
613    // through to `_ => None` with every other key.
614    match key.code {
615        KeyCode::Char('y') | KeyCode::Char('Y') => Some(PermissionAnswer::AllowOnce),
616        KeyCode::Char('a') | KeyCode::Char('A') => {
617            Some(PermissionAnswer::AllowForSession { pattern: None })
618        }
619        KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => Some(PermissionAnswer::Deny),
620        _ => None,
621    }
622}
623
624/// Dispatch one translated key press to the appropriate `ReplApp` mutator.
625///
626/// Why: split out of [`apply`] so the (long, mechanical) key-by-key match
627/// reads as its own unit, matching tagent's `keys.rs::handle_key` precedent
628/// in spirit (though deliberately smaller — see the module doc comment for
629/// what's deferred to Slice 5).
630/// What: printable chars insert; Backspace/Left/Right/Home/End edit/move;
631/// PageUp/PageDown scroll a page; Enter submits, or — while
632/// [`ReplApp::busy`] — inserts the newline it stands for so queued
633/// type-ahead keeps its line breaks (#8240); Ctrl-a/u/c/d match the
634/// readline bindings DOC-50 §5 Slice 5 specifies; Ctrl-O expands/collapses
635/// the newest tool-call card (#4596). Up, Down, and Ctrl-E are
636/// direct ports of tagent's real `keys.rs` bindings rather than a Slice-5
637/// invention — see [`apply_up`] and [`apply_ctrl_e`] for why they're pulled
638/// into their own functions. Any other key (Tab, Esc, Delete,
639/// `KeyCode::Other`) is a no-op — those are slash-completion/picker-
640/// navigation concerns this slice doesn't own.
641/// Test: [`tests`] below, one per binding.
642fn apply_key(app: &mut ReplApp, key: KeyInput) {
643    // #3422: the prompt is modal. While a tool call is suspended on the
644    // backend, every key either answers it or does nothing — routing a
645    // keystroke to the line editor would let the user compose a turn the
646    // backend cannot start, and Enter would look like a submit that silently
647    // vanished. Deny is always one key away (`n` or Esc), so this can never
648    // trap the keyboard.
649    if app.pending_permission.is_some() {
650        if let Some(answer) = permission_answer_for_key(key) {
651            app.answer_permission(answer);
652        }
653        return;
654    }
655    let ctrl = key.modifiers.ctrl;
656    match key.code {
657        KeyCode::Char(c) if ctrl => match c {
658            'a' => app.cursor_pos = 0,
659            'e' => apply_ctrl_e(app),
660            'u' => {
661                app.input_buf.clear();
662                app.cursor_pos = 0;
663            }
664            'c' => app.pending_cancel = true,
665            // #4596: expand/collapse the newest tool-call card. `o` for
666            // "output"; the free ctrl bindings were o/b/f/k/w/y and this is
667            // the one Claude Code's own TUI uses for the same gesture.
668            'o' => {
669                app.toggle_last_tool_card();
670            }
671            // Direct port of tagent's real `KeyCode::Char('d')` arm
672            // (`crates/trusty-agents/src/repl/tui/keys.rs`): Ctrl-D only
673            // quits on an EMPTY input buffer (the readline EOF convention);
674            // with text still in the buffer it's a no-op in tagent too (no
675            // forward-delete fallback), so this stays a plain guard rather
676            // than growing new behavior tagent doesn't have.
677            'd' if app.input_buf.is_empty() => app.quit = true,
678            _ => {}
679        },
680        KeyCode::Char(c) => app.insert_char(c),
681        KeyCode::Backspace => app.backspace(),
682        KeyCode::Left => app.cursor_left(),
683        KeyCode::Right => app.cursor_right(),
684        KeyCode::Home => app.cursor_pos = 0,
685        KeyCode::End => app.cursor_pos = app.input_buf.len(),
686        KeyCode::Up => apply_up(app),
687        // #8181: live since `apply_up` walks `history` rather than recalling
688        // the single-level `last_prompt`. Down steps forward through the
689        // same list and restores the in-progress draft at the newest end.
690        KeyCode::Down => app.history_next(),
691        KeyCode::PageUp => app.scroll(-PAGE_SCROLL),
692        KeyCode::PageDown => app.scroll(PAGE_SCROLL),
693        // Gated on `ReplApp::accepts_submit` BEFORE `take_input()` runs (not
694        // just inside `submit_line`, which also guards): while a turn is in
695        // flight, the typed line stays in `input_buf` untouched rather than
696        // being taken out and then silently dropped by `submit_line`'s own
697        // guard — DOC-50 §5 Slice 5's "blocks user input until cancel
698        // completes", made literal so a second turn genuinely cannot start (see
699        // `ReplApp::submit_line`'s doc comment for the corruption bug this
700        // closes). #8207 widened the gate from `busy` alone to that predicate,
701        // so the unconfirmed-cancel window queues exactly like a live turn.
702        KeyCode::Enter => {
703            // #8240: printable keys ALREADY queue into `input_buf` while a
704            // turn runs, so a busy Enter that did nothing at all welded the
705            // next typed line onto the previous one (`echo twoecho three`).
706            // Record the separator the operator actually typed instead; the
707            // whole buffer submits verbatim, newlines included, on the first
708            // Enter after the turn ends. An empty buffer still gets nothing —
709            // a bare Enter must not open the queue with a blank line.
710            if !app.accepts_submit() {
711                if !app.input_buf.is_empty() {
712                    app.insert_char('\n');
713                }
714            } else if let Some(line) = app.take_input() {
715                app.submit_line(line);
716            }
717        }
718        KeyCode::Delete | KeyCode::Tab | KeyCode::Esc | KeyCode::Other => {}
719    }
720}
721
722/// Up-arrow: walk one step back through [`ReplApp::history`], and — while
723/// [`ReplApp::busy`] — ALSO signal [`ReplApp::pending_cancel`].
724///
725/// Why: #8181. This used to recall [`ReplApp::last_prompt`], a single
726/// snapshot overwritten on every submit, so a second press repeated the
727/// first and `KeyCode::Down` (which calls [`ReplApp::history_next`]) never
728/// had an index to walk forward from. Walking [`ReplApp::history`] is the
729/// readline behavior the owner asked for and is what makes the already-wired
730/// Down arm live. The busy-cancel half is unchanged tagent parity
731/// (`crates/trusty-agents/src/repl/tui/keys.rs`): it fires independent of
732/// whether anything is recallable, and the composer's `↑ to cancel` hint
733/// depends on it.
734/// What: the composer is a single ROW — [`crate::widgets::input_composer`]
735/// renders `input_buf` on one line, showing a queued newline as a `⏎` glyph
736/// (#8240) rather than wrapping — so readline's "history only when the
737/// cursor is on the first/last line" rule is satisfied unconditionally here
738/// and Up is always history.
739/// [`ReplApp::history_prev`] saves the in-progress draft on the first step
740/// (so Down can restore it), clamps at the oldest entry, and no-ops on an
741/// empty history.
742/// Test: [`tests::apply_up_walks_back_through_submitted_prompts`],
743/// [`tests::apply_down_walks_forward_and_restores_the_draft`],
744/// [`tests::apply_up_clamps_at_the_oldest_entry`],
745/// [`tests::apply_down_is_noop_when_not_navigating_history`],
746/// [`tests::apply_up_signals_cancel_and_recalls_when_busy`],
747/// [`tests::apply_up_signals_cancel_even_with_no_history`],
748/// [`tests::apply_up_is_noop_when_idle_and_history_is_empty`].
749fn apply_up(app: &mut ReplApp) {
750    if app.busy {
751        app.pending_cancel = true;
752    }
753    // #8181: was a single-level `last_prompt` recall; `history_prev` walks
754    // the whole session's submissions and is what gives Down an index.
755    app.history_prev();
756}
757
758/// Ctrl-E: with an empty input buffer and a cached
759/// [`ReplApp::last_bash_block`], paste that block's first non-blank line;
760/// otherwise (non-empty buffer, or no cached block) move the cursor to the
761/// end of the line.
762///
763/// Why: direct port of tagent's real `KeyCode::Char('e')` arm
764/// (`crates/trusty-agents/src/repl/tui/keys.rs`) — only the first line
765/// pastes because the REPL input is single-line; pasting a multi-line block
766/// verbatim would silently truncate at the first `\n` on submit.
767/// Test: [`tests::apply_ctrl_e_pastes_last_bash_block_when_input_empty`],
768/// [`tests::apply_ctrl_e_falls_back_to_end_of_line_when_input_nonempty`],
769/// [`tests::apply_ctrl_e_noop_when_no_block_and_input_empty`].
770fn apply_ctrl_e(app: &mut ReplApp) {
771    if app.input_buf.is_empty()
772        && let Some(block) = &app.last_bash_block
773    {
774        let first_line = block
775            .lines()
776            .find(|l| !l.trim().is_empty())
777            .unwrap_or("")
778            .to_string();
779        if !first_line.is_empty() {
780            app.input_buf = first_line;
781            app.cursor_pos = app.input_buf.len();
782            return;
783        }
784    }
785    app.cursor_pos = app.input_buf.len();
786}
787
788#[cfg(test)]
789mod tests;