Skip to content

fix: restore interactive sudo input and suppress duplicate bash output#186

Merged
F16shen merged 3 commits into
AI-Shell-Team:rustfrom
F16shen:fix/sudo-bash-interactive-output
May 15, 2026
Merged

fix: restore interactive sudo input and suppress duplicate bash output#186
F16shen merged 3 commits into
AI-Shell-Team:rustfrom
F16shen:fix/sudo-bash-interactive-output

Conversation

@F16shen
Copy link
Copy Markdown
Collaborator

@F16shen F16shen commented May 15, 2026

Background

AI-triggered interactive bash commands had two regressions on the Rust shell path:

  • sudo password prompts could lose stdin ownership while the shell was still polling for AI events
  • interactive bash output could be rendered twice, once from the live PTY stream and again from the tool preview path

Changes

  • route interactive bash commands through the PTY-backed path when stdin takeover is required
  • propagate bash tool arguments through ToolExecutionEnd so the shell UI can recognize interactive bash completions
  • skip duplicate bash preview rendering when output was already shown live in the terminal
  • keep readline aligned with the PTY execution signature used by interactive commands
  • filter auth-interaction noise from captured PTY output before passing tool results back to the model

Validation

  • cargo test -p aish-pty test_clean_pty_output --lib -- --nocapture
  • cargo test -p aish-llm tool_execution_end_event_includes_tool_args --lib -- --nocapture
  • cargo test -p aish-shell collapsing_tests:: --lib -- --nocapture
  • cargo build -p aish-cli

Risk

The main risk is divergence between interactive and non-interactive bash execution behavior, especially around PTY cleanup and tool preview rendering.

Summary by CodeRabbit

  • Bug Fixes

    • Removed authentication and password-related noise from command output
    • Improved handling of interactive bash commands to prevent output interference
    • Tool output displays without multi-line return code blocks for cleaner formatting
  • New Features

    • Tool execution events now include command input arguments for better visibility
    • Commands requiring interactive input are automatically detected and handled appropriately

Review Change Stack

@github-actions
Copy link
Copy Markdown
Contributor

Thanks for the pull request. A maintainer will review it when available.

Please keep the PR focused, explain the why in the description, and make sure local checks pass before requesting review.

Contribution guide: https://github.com/AI-Shell-Team/aish/blob/main/CONTRIBUTING.md

@github-actions
Copy link
Copy Markdown
Contributor

This pull request description looks incomplete. Please update the missing sections below before review.

Missing items:

  • Summary
  • User-visible Changes
  • Compatibility
  • Testing
  • Change Type
  • Scope

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 15, 2026

Warning

Rate limit exceeded

@F16shen has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 24 minutes and 33 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: dada188f-0c36-4eb7-9c09-b3afe72a6bc5

📥 Commits

Reviewing files that changed from the base of the PR and between eaf7835 and 4cb9b38.

📒 Files selected for processing (5)
  • crates/aish-llm/src/session.rs
  • crates/aish-pty/src/persistent.rs
  • crates/aish-shell/src/app.rs
  • crates/aish-shell/src/readline.rs
  • crates/aish-tools/src/bash.rs
📝 Walkthrough

Walkthrough

This PR enhances interactive bash command execution by adding detection, display control, and event enrichment. It exposes interactive-command detection to the shell, adds PTY display control with authentication-noise filtering, enriches tool events with command arguments, and coordinates shell loops with interactive input status to avoid interference during password prompts.

Changes

Interactive Bash Tool Execution

Layer / File(s) Summary
Interactive command detection and status tracking
crates/aish-tools/src/bash.rs
Exposes command_needs_interactive(command: &str) and interactive_input_active() backed by a global atomic flag. Both persistent PTY and one-shot executor paths compute interactive status from the command and manage the flag around execution.
PTY display control and auth-noise filtering
crates/aish-pty/src/persistent.rs
execute_command gains a display_output: bool parameter to optionally write fresh PTY bytes to stdout. clean_pty_output extends output filtering to strip password/auth-interaction noise for commands likely to prompt for authentication (sudo, su, ssh). Tests verify auth stripping and signature compliance.
Tool execution event enrichment
crates/aish-llm/src/session.rs
ToolExecutionEnd event payload now includes tool_args (the tool's input arguments). A test confirms bash tool command arguments are captured in the event.
Shell loop coordination and tool output handling
crates/aish-shell/src/app.rs, crates/aish-shell/src/readline.rs
Remote follow-up and main event loops pause briefly and retry when interactive_input_active() returns true, avoiding interference during interactive input. Tool preview output is suppressed for interactive bash commands. Completion queries and command syncing pass the display_output parameter. Multi-line return-code XML blocks are stripped from tool output before display.

Sequence Diagram

sequenceDiagram
  participant Shell as ShellApp
  participant Bash as BashTool
  participant PTY as PersistentPty
  participant EventLoop as EventCallback
  Shell->>Bash: execute bash tool command
  Bash->>Bash: detect if command needs interactive
  Bash->>Bash: set INTERACTIVE_INPUT_ACTIVE = true
  Bash->>PTY: execute_command(..., display_output)
  PTY->>PTY: clean output, strip auth noise
  PTY-->>Bash: cleaned output + exit code
  Bash->>Bash: reset INTERACTIVE_INPUT_ACTIVE = false
  Bash-->>Shell: command result
  Shell->>EventLoop: emit ToolExecutionEnd with tool_args
  EventLoop->>EventLoop: suppress preview if interactive
  EventLoop->>Shell: event handled
Loading

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • AI-Shell-Team/aish#132: Extends interactive input and retry behavior for bash execution, aligning with this PR's interactive stdin + loop-pausing fixes.
  • AI-Shell-Team/aish#139: Expands interactive-command detection and PTY handling in the same crates/aish-tools/src/bash.rs area.
  • AI-Shell-Team/aish#135: Addresses sudo/su interactive-auth behavior via PTY with controlling-terminal setup, complementing this PR's Rust-side interactive/auth-noise handling.

Suggested labels

size: M, tests, tools, experienced-contributor

Poem

🐰 A hopping tale of prompts that stay,
Auth noise stripped and loops that pause—
When bash needs input, out of the way,
Events enrich, without a fuss!
Interactive flows now clean and bright,

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately captures the two main fixes: restoring interactive sudo input and suppressing duplicate bash output, which align with the core changes across multiple files in the PR.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🧹 Nitpick comments (2)
crates/aish-pty/src/persistent.rs (1)

3571-3579: ⚡ Quick win

Narrow auth-prompt filtering trigger to command token, not substring.

command_may_prompt_for_auth matches with broad contains(...), so unrelated commands that merely include words like sudo/ssh in arguments can trigger auth-line stripping and lose valid output. Parsing first executable token (same style as interactive detection) would reduce false positives.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/aish-pty/src/persistent.rs` around lines 3571 - 3579, The auth prompt
detector command_may_prompt_for_auth currently uses substring checks and should
instead inspect only the command's first token (executable) to avoid false
positives; change it to split_whitespace() (or the same token parsing used by
the interactive detection) and run checks against that first token (e.g., token
== "sudo" or token.starts_with("su") or token == "ssh") rather than using
contains()/contains(" ssh "), so only the actual invoked program triggers
auth-line stripping.
crates/aish-shell/src/app.rs (1)

1708-1713: ⚡ Quick win

Use lock_pty() here for consistent poison recovery.

This path bypasses the helper introduced earlier in the file, so a poisoned PTY mutex will panic here even though the normal execution paths recover and keep going.

♻️ Suggested change
-        let _ = self.pty.lock().unwrap().execute_command(
+        let _ = self.lock_pty().execute_command(
             command,
             std::time::Duration::from_secs(5),
             None,
             false,
         );
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/aish-shell/src/app.rs` around lines 1708 - 1713, The call uses
self.pty.lock().unwrap().execute_command(...) which will panic on a poisoned
mutex; replace this direct lock with the helper lock_pty() used elsewhere to get
the PTY guard (so poison recovery is applied) and then call execute_command on
that guard with the same arguments; specifically, locate the occurrence of
self.pty.lock().unwrap().execute_command and change it to use lock_pty() to
obtain the guard before calling execute_command.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@crates/aish-llm/src/session.rs`:
- Around line 1463-1467: The new test block has formatting drift around the
let-binding for result at session.execute_tool_external(&tool_call).await and
the seen_event lock/unwrap clone lines; run rustfmt (cargo fmt) to reformat the
file so the let-binding wrapping and subsequent assertions match project style,
or manually adjust the indentation/line-wrapping in the test (around
session.execute_tool_external,
seen_event.lock().unwrap().clone().expect("missing ToolExecutionEnd event"), and
the assert_eq! block) to match rustfmt output.

In `@crates/aish-pty/src/persistent.rs`:
- Around line 292-300: The display_output branch currently calls libc::write and
ignores its return value (involving tmp, n, and libc::STDOUT_FILENO), which can
drop data on short writes; replace that call with a small write-all loop that
retries on EINTR and advances the buffer by the number of bytes written until
all n bytes are written (handling partial writes and returning or breaking on
unrecoverable errors). Implement the loop around libc::write in the same unsafe
block used now, check for negative returns to map errno, treat EINTR as retry,
subtract the bytes_written from the remaining count and advance the pointer (or
index) accordingly, and only exit when total bytes written equals n or an
unrecoverable error occurs.

In `@crates/aish-shell/src/app.rs`:
- Around line 3417-3418: The regex initializer for TOOL_XML_RETURN_CODE_RE
(assigned to re_return_code via get_or_init and calling
regex::Regex::new(r"(?s)<(?:return_code|exit-code)>.*?</(?:return_code|exit-code)>").unwrap())
is not formatted to Rustfmt standards; run rustfmt (or `cargo fmt`) to reformat
this block so the expression, method chaining, and indentation meet `cargo fmt
--check`, then commit the formatted change so CI passes.
- Around line 3416-3419: The current regex TOOL_XML_RETURN_CODE_RE (used to
initialize re_return_code) is applied to the entire preview string (cleaned) and
can remove legitimate <return_code> or <exit-code> fragments from command
stdout; instead, first isolate the tool metadata block (the trailing wrapper
content inside the <stdout> or the metadata section) and apply the regex only to
that substring, or move the replace_all call to after you peel off the <stdout>
wrapper; update the logic around the variable cleaned and the use of
re_return_code so you only strip return-code/exit-code tags within the tool
metadata region rather than the full preview.

In `@crates/aish-tools/src/bash.rs`:
- Line 269: The CI failure is due to formatting at the call site of
pty.execute_command(command, command_timeout, Some(&cancel_token), interactive);
— run rustfmt (or cargo fmt) to reformat crates/aish-tools/src/bash.rs so the
call wraps/aligns per rustfmt rules (or manually adjust the call to a
rustfmt-friendly layout, e.g., place args on separate indented lines) and re-run
cargo fmt --check to ensure the formatting issue is resolved.
- Around line 266-272: Replace the global boolean INTERACTIVE_INPUT_ACTIVE
toggles with an atomic reference count: increment (fetch_add(1)) before calling
pty.execute_command(...) and decrement (fetch_sub(1)) after it (ensuring you
never underflow) so overlapping interactive commands keep the flag active until
the last one finishes; update both occurrences where you currently call
INTERACTIVE_INPUT_ACTIVE.store(true/false, Ordering::SeqCst) around
pty.execute_command (the blocks using interactive, INTERACTIVE_INPUT_ACTIVE,
pty.execute_command, command_timeout and cancel_token) to use the atomic counter
instead and use Ordering::SeqCst for increments/decrements to preserve ordering.

---

Nitpick comments:
In `@crates/aish-pty/src/persistent.rs`:
- Around line 3571-3579: The auth prompt detector command_may_prompt_for_auth
currently uses substring checks and should instead inspect only the command's
first token (executable) to avoid false positives; change it to
split_whitespace() (or the same token parsing used by the interactive detection)
and run checks against that first token (e.g., token == "sudo" or
token.starts_with("su") or token == "ssh") rather than using
contains()/contains(" ssh "), so only the actual invoked program triggers
auth-line stripping.

In `@crates/aish-shell/src/app.rs`:
- Around line 1708-1713: The call uses
self.pty.lock().unwrap().execute_command(...) which will panic on a poisoned
mutex; replace this direct lock with the helper lock_pty() used elsewhere to get
the PTY guard (so poison recovery is applied) and then call execute_command on
that guard with the same arguments; specifically, locate the occurrence of
self.pty.lock().unwrap().execute_command and change it to use lock_pty() to
obtain the guard before calling execute_command.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: e23a3366-5d34-44b5-a1fe-c96018010d2f

📥 Commits

Reviewing files that changed from the base of the PR and between 29ae67e and eaf7835.

📒 Files selected for processing (5)
  • crates/aish-llm/src/session.rs
  • crates/aish-pty/src/persistent.rs
  • crates/aish-shell/src/app.rs
  • crates/aish-shell/src/readline.rs
  • crates/aish-tools/src/bash.rs

Comment thread crates/aish-llm/src/session.rs
Comment thread crates/aish-pty/src/persistent.rs
Comment thread crates/aish-shell/src/app.rs Outdated
Comment thread crates/aish-shell/src/app.rs Outdated
Comment thread crates/aish-tools/src/bash.rs Outdated
Comment thread crates/aish-tools/src/bash.rs Outdated
@F16shen F16shen force-pushed the fix/sudo-bash-interactive-output branch from eaf7835 to a7a16be Compare May 15, 2026 05:57
@github-actions github-actions Bot added size: M and removed size: S labels May 15, 2026
@F16shen F16shen merged commit 352b631 into AI-Shell-Team:rust May 15, 2026
7 checks passed
@F16shen F16shen deleted the fix/sudo-bash-interactive-output branch May 15, 2026 06:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant