Repository navigation
Conversation
…_stdin Implements a Codex-inspired interactive terminal toolset that allows agents to monitor long-running background processes without blocking. ## What this adds Two new tools under openhands.tools.interactive_terminal: - exec_command(cmd, workdir, yield_time_ms, max_output_tokens) Runs a command in a PTY and returns after yield_time_ms. When the process is still running, session_id is set (no exit_code). When done, exit_code is set (no session_id). This is the key binary signal. - write_stdin(session_id, chars, yield_time_ms, max_output_tokens) Sends input to or polls a running session. Omit chars for a pure poll. Supports common control sequences: \x03=Ctrl+C, \x04=Ctrl+D, \x1a=Ctrl+Z. ## How it mirrors Codex Codex's exec_command / write_stdin / yield_time_ms pattern lets an agent: 1. Start a long command with yield_time_ms=5000 2. Get session_id back after 5 s with partial output 3. Do other work (the process keeps running in the background) 4. Call write_stdin(session_id, chars='') to poll status periodically This replaces the passive 'wait 30 s of silence then ask' behaviour of the existing terminal tool with explicit, time-controlled yield intervals. ## Constants (matching Codex's unified-exec): - MIN_YIELD: 250 ms - MAX_YIELD: 30 s - MIN_EMPTY_POLL_YIELD: 5 s (empty chars always waits >= 5 s) ## Test coverage: 25 tests verified live - Fast commands return exit_code immediately - Slow commands return session_id after yield_time_ms - Empty-char polls keep session_id while running - Ctrl+C interrupt terminates and returns ec=130 - Multiple concurrent sessions with independent session_ids - workdir, max_output_tokens, observation schema fields - Full tool interface via InteractiveTerminalToolSet.create() Co-authored-by: openhands <openhands@all-hands.dev>
Python API breakage checks — ✅ PASSEDResult: ✅ PASSED |
REST API breakage checks (OpenAPI) — ✅ PASSEDResult: ✅ PASSED |
Coverage Report •
|
|||||||||||||||||||||||||||||||||||||||||||||
Five tests use bash-specific syntax ((exit 42), for/do/done) or Unix signal semantics (\x03 = SIGINT) that don't apply to Windows PowerShell. Mark them with @_unix_only (pytest.mark.skipif Windows) so the Windows CI job passes without removing the full test coverage on Linux/macOS. Co-authored-by: openhands <openhands@all-hands.dev>
|
Addressed Windows CI failure in a79cd93 — added @_unix_only skipif markers to bash/signal-dependent tests. All 25 tests pass on Linux; Windows-incompatible tests now skip cleanly. Ready for another look. |
|
✅ Review complete. This review was performed through OpenHands Cloud Automation. You can log in and view the conversation here. |
all-hands-bot
left a comment
There was a problem hiding this comment.
✅ QA Report: PASS
The new interactive terminal toolset works end-to-end for real SDK usage: commands can yield while still running, be polled, receive stdin/control input, and run in independent sessions.
Does this PR achieve its stated goal?
Yes. The stated goal was to add Codex-style exec_command/write_stdin tools with yield_time_ms so agents can monitor long-running processes without blocking on the existing terminal behavior. I verified the feature did not exist on origin/main, then on commit a79cd93cdf31c8958e831046318e3aa7a0b985fd used the actual SDK tool interface to create exec_command and write_stdin, run a continuously-outputting background process that returned session_id, poll it, interrupt it, send stdin to cat, and keep two concurrent sessions independent.
| Phase | Result |
|---|---|
| Environment Setup | ✅ make build completed with uv sync --dev; no tests/linters were run. |
| CI Status | ⏳ Observed 16 passing checks, 12 in progress, and 1 skipped at review time. |
| Functional Verification | ✅ Real SDK scripts exercised import/tool creation, fast completion, proactive yield, polling, stdin, Ctrl-C/EOF, and concurrent sessions. |
Functional Verification
Test 1: Baseline availability vs PR availability
Step 1 — Establish baseline without the feature:
Ran this on origin/main:
git checkout --detach origin/main
uv run python - <<'PY'
try:
from openhands.tools.interactive_terminal import InteractiveTerminalToolSet
except Exception as exc:
print(type(exc).__name__ + ': ' + str(exc))
else:
print('import succeeded unexpectedly')
PYObserved:
ModuleNotFoundError: No module named 'openhands.tools.interactive_terminal'
This confirms the interactive terminal public module was not available before the PR.
Step 2 — Apply the PR changes:
Checked out a79cd93cdf31c8958e831046318e3aa7a0b985fd.
Step 3 — Re-run with the PR in place:
Ran a real SDK script that constructs ConversationState, calls InteractiveTerminalToolSet.create(state), and invokes the returned ToolDefinitions. Key output:
tools=['exec_command', 'write_stdin']
fast: wall=0.80s session_id=None exit_code=0 output='fast-ok'
This shows the PR exports the new toolset and returns the expected binary completion signal for a fast command: exit_code is set and session_id is absent.
Test 2: Proactive yield, polling, and control input
Step 1 — Baseline:
On origin/main, the new API could not be imported, so this behavior was unavailable through openhands.tools.interactive_terminal.
Step 2 — Apply the PR changes:
Checked out a79cd93cdf31c8958e831046318e3aa7a0b985fd.
Step 3 — Exercise the new behavior:
Ran the actual exec_command tool against a Python command that prints every 0.2s for ~6s, with yield_time_ms=500, then polled and interrupted it:
active-yield: wall=1.19s session_id=2 exit_code=None output_snippet='tick 1\ntick 2\ntick 3'
empty-poll: wall=5.04s session_id=2 exit_code=None output_snippet='tick 4\ntick 5\ntick 6\ntick 7\ntick 8\ntick 9\ntick 10\ntick 11\ntick 12\ntick 13\ntick 14\ntick 15\ntick 16\nti'
active-stop: session_id=None exit_code=130
This confirms a still-active, continuously-outputting process yielded control with session_id, empty polling respected the documented ≥5s poll floor while keeping the same session, and Ctrl-C completed the process with an exit code.
Test 3: Interactive stdin and EOF
Step 1 — Baseline:
On origin/main, the new write_stdin API was unavailable.
Step 2 — Apply the PR changes:
Checked out a79cd93cdf31c8958e831046318e3aa7a0b985fd.
Step 3 — Exercise stdin as a user would:
Started cat, sent a line with write_stdin, then sent Ctrl-D:
cat-start: session_id=3 exit_code=None
cat-line: session_id=3 exit_code=None output='stdin-ok'
cat-eof: session_id=None exit_code=0 output=''
This confirms write_stdin can send ordinary input and EOF to an interactive process and reports completion via exit_code.
Test 4: Independent concurrent sessions
Step 1 — Baseline:
On origin/main, the new session-managed toolset was unavailable.
Step 2 — Apply the PR changes:
Checked out a79cd93cdf31c8958e831046318e3aa7a0b985fd.
Step 3 — Exercise concurrency:
Started two cat sessions, wrote different input to each, and closed both:
started: a=1/None b=2/None
line-a: sid=1 ec=None output='from-a'
line-b: sid=2 ec=None output='from-b'
closed: a=None/0 b=None/0
concurrent_sessions_verified
This confirms separate exec_command calls produced independent sessions and write_stdin routed input to the intended session.
Issues Found
None.
This QA review was generated by an AI agent (OpenHands) on behalf of the user.
all-hands-bot
left a comment
There was a problem hiding this comment.
🟡 Taste Rating: Acceptable — the public shape is useful, but the implementation currently has lifecycle and API-contract holes that make it risky to ship as a terminal execution primitive.
[CRITICAL ISSUES]
- See inline comments for terminal-session cleanup, executor lifecycle, tool registration, stdin semantics, and secret-handling issues.
[TESTING GAPS]
- The tests cover polling and Ctrl+C, but they do not exercise raw
write_stdinbyte semantics (no trailing newline, multiple newlines, partial input) or verify that completed/conversation-closed sessions are actually torn down. - Per this repo's review guide, this touches terminal/stdin handling and can plausibly affect agent benchmark behavior. I do not see an eval-monitor link plus human confirmation in the PR description or comments, so I am leaving a COMMENT review rather than approving.
[RISK ASSESSMENT]
- [Overall PR]
⚠️ Risk Assessment: 🟡 MEDIUM
This is additive, but it introduces a new public toolset for shell execution and interactive stdin, touches core agent/tool behavior, and has moderate resource/security blast radius if terminal sessions leak or stdin semantics differ from the advertised Codex-compatible API.
VERDICT:
✅ Worth merging after fixes/eval validation: The feature direction is sound, but the lifecycle/API-contract issues need cleanup and a human maintainer should decide after lightweight eval evidence.
KEY INSIGHT:
The hard part here is not starting tmux panes; it is preserving the same lifecycle, security, and byte-stream contracts users already expect from terminal execution tools.
Improve this review? If any feedback above seems incorrect or irrelevant to this repository, you can teach the reviewer to do better:
- Add a
.agents/skills/custom-codereview-guide.mdfile to your branch (or edit it if one already exists) with the/codereviewtrigger and the context the reviewer is missing (e.g., "Security concerns about X do not apply here because Y"). See the customization docs for the required frontmatter format.- Re-request a review - the reviewer reads guidelines from the PR branch, so your changes take effect immediately.
- When your PR is merged, the guideline file goes through normal code review by repository maintainers.
Resolve with AI? Install the iterate skill in your agent and run
/iterateto automatically drive this PR through CI, review, and QA until it's merge-ready.Was this review helpful? React with 👍 or 👎 to give feedback.
This review was generated by an AI agent (OpenHands) on behalf of the user through OpenHands Automation. View conversation
Five issues from all-hands-bot review:
1. Executor lifecycle — add close() and interrupt() to ExecCommandExecutor
and WriteStdinExecutor, both forwarding to InteractiveTerminalManager.
Also add InteractiveTerminalManager.interrupt() which sends Ctrl+C to
all active sessions. close() is now idempotent (safe to call twice).
2. Secret masking — add _mask_output() helper in executor.py that applies
the conversation's secret_registry to output text before returning
the observation, matching TerminalTool's masking behaviour.
3. stdin byte semantics — remove rstrip('\n') that was collapsing multiple
trailing newlines. The underlying tmux send_keys() already handles the
'end with \n → no extra Enter' case correctly, so passing chars as-is
preserves the exact byte stream.
4. Session cleanup — call session.close() after popping from _sessions
so the tmux pane / subprocess shell is torn down when the process
finishes, not just when the conversation closes.
5. Tool registration — ExecCommandTool and WriteStdinTool now accept
create(conv_state, manager=None) so they satisfy the repo-level
registration requirement and can be resolved standalone. When manager
is None each creates its own isolated InteractiveTerminalManager;
InteractiveTerminalToolSet still passes a shared manager so session
IDs work across exec_command / write_stdin calls.
Co-authored-by: openhands <openhands@all-hands.dev>
|
Addressed all 5 issues from the bot review in commit 91960fb:
All 25 tests still pass. Re-requesting review. |
|
✅ Review complete. This review was performed through OpenHands Cloud Automation. You can log in and view the conversation here. |
all-hands-bot
left a comment
There was a problem hiding this comment.
✅ QA Report: PASS
The new InteractiveTerminalToolSet worked end-to-end as a real SDK user would use it: import, tool creation, fast command completion, background sessions, polling, stdin writes, Ctrl+C interrupts, session cleanup, and output truncation all behaved as described.
Does this PR achieve its stated goal?
Yes. The PR set out to add Codex-style exec_command / write_stdin tools with proactive yield_time_ms background-process monitoring, and I verified that behavior by running the SDK toolset directly against real shell processes. A slow sleep 60 returned a session_id after ~0.5s instead of blocking, an empty poll held for ~5.04s and kept the process running, and Ctrl+C returned exit_code=130; stdin interaction with a real Python prompt also completed successfully.
| Phase | Result |
|---|---|
| Environment Setup | ✅ make build completed successfully; no tests/linters run |
| CI Status | ⏳ GitHub checks queried: many passed, several still in progress; no failing checks observed at query time |
| Functional Verification | ✅ Real SDK usage script passed all exercised user-facing scenarios |
Functional Verification
Test 1: Baseline availability before this PR
Step 1 — Reproduce / establish baseline (without the fix):
Ran on origin/main:
git switch --detach origin/main
uv run python -c 'import importlib.util; spec=importlib.util.find_spec("openhands.tools.interactive_terminal"); print("BASELINE_SPEC:", spec)'Observed:
BASELINE_SPEC: None
This shows the interactive terminal public module was not available on the base branch, establishing the additive feature baseline.
Step 2 — Apply the PR's changes:
Switched back to feat/interactive-terminal-exec-command-write-stdin at 91960fbbead76f8e26d2e187e26d75678ff172cf.
Test 2: Use the new toolset through the public SDK surface
Step 3 — Run with the PR in place:
Ran:
OPENHANDS_SUPPRESS_BANNER=1 uv run python /tmp/qa_interactive_terminal.pyKey output:
TOOLSET_NAMES: ['exec_command', 'write_stdin']
FAST_COMMAND: session_id=None exit_code=0 wall=0.12s output='qa-fast'
PROMPT_START: session_id=2 exit_code=None wall=0.51s output='name?'
PROMPT_ANSWER: session_id=None exit_code=0 wall=0.62s output='hello QA_USER\n'
SLOW_A_START: session_id=3 exit_code=None wall=0.51s output=''
SLOW_B_START: session_id=4 exit_code=None wall=0.51s output=''
SLOW_A_EMPTY_POLL: session_id=3 exit_code=None wall=5.04s output=''
SLOW_A_EMPTY_POLL_CLIENT_WALL=5.04s
SLOW_A_INTERRUPT: session_id=None exit_code=130 wall=0.12s output='^C'
SLOW_B_INTERRUPT: session_id=None exit_code=130 wall=0.12s output='^C'
COMPLETED_SESSION_POLL: session_id=None exit_code=None wall=0.00s output='No running session with session_id=3. The process may have already completed or was never started.'
TRUNCATED_OUTPUT: session_id=None exit_code=0 wall=0.63s output='xxxxxxxxxxxxxxxxxxxx'
QA_RESULT: PASS interactive terminal feature behaved as described
This confirms the new public export resolves, InteractiveTerminalToolSet.create(...) returns the two Codex-named tools, fast commands return exit_code without session_id, long-running commands yield promptly with distinct session IDs, empty polling enforces the ~5s floor while preserving the running session, write_stdin sends real input to a prompt, Ctrl+C maps to a completed process with exit_code=130, completed sessions are cleaned up, and max_output_tokens truncates output.
Issues Found
None.
This QA review was generated by an AI agent (OpenHands) on behalf of the user.
all-hands-bot
left a comment
There was a problem hiding this comment.
🟡 Acceptable — solid feature addition with real-code tests; all four issues from the previous review round were fixed. Two remaining concerns below, both non-blocking.
[IMPROVEMENT OPPORTUNITIES]
-
Unknown session produces a misleading observation (
impl.pyline 108 +definition.pyline 206): whenwrite_stdincannot find a session it returns(msg, 0.0, None, None). That tuple reachesInteractiveTerminalObservation.createwith bothsession_id=Noneandexit_code=None, which violates the documented invariant ("Exactly one ofsession_id/exit_codeis set")._format_headerthen emits[Process completed -- exit_code=None, elapsed=0.00s]and thevisualizeproperty renders❌ Done -- exit_code=None-- both misleading. Fix: give_format_headeran explicit branch for the(None, None)case (e.g.[Session not found -- session_id=X]), and add anerrorfield or sentinel exit code so callers can detect "session not found" reliably. The existing test exercises the raw tuple but never exercises the resulting observation text, so the misleading message goes undetected. -
write_stdinregistered as a standalone tool is permanently useless (definition.pyline 379): aTool(name="write_stdin")produces an isolatedInteractiveTerminalManagerwith no sessions, so everywrite_stdincall immediately returns 'No running session'. The previous review flagged this; the author's resolution was 'by design so exec_command-only and write_stdin-only usages still work' -- but write_stdin-only can't work with its own isolated manager since only exec_command creates sessions. Either remove line 379 entirely, or document the isolated-manager limitation prominently.
[TESTING GAPS]
The unknown-session test (test_write_stdin_unknown_session) checks only the raw (out, wall, sid, ec) tuple returned by the manager. It should also exercise the resulting InteractiveTerminalObservation text to catch the header/visualize regression described above.
[RISK ASSESSMENT]
- [Overall PR]
⚠️ Risk Assessment: 🟢 LOW
Pure additive change -- new module with no modifications to existing tools or core SDK. No breaking-change risk. PR is currently in draft; the HUMAN section of the description must be filled in before marking it ready for review.
VERDICT:
✅ Worth merging (once out of draft): core logic is sound, tests exercise real behavior, and all previous blocking issues have been addressed. Fix the misleading observation text and the standalone write_stdin registration before the final review.
KEY INSIGHT: The (None, None) return from write_stdin for an unknown session quietly breaks the observation contract -- the header and visualizer both end up lying to the agent about what happened.
Improve this review? If any feedback above seems incorrect or irrelevant to this repository, you can teach the reviewer to do better:
- Add a
.agents/skills/custom-codereview-guide.mdfile to your branch with the/codereviewtrigger and the context the reviewer is missing.- Re-request a review -- the reviewer reads guidelines from the PR branch, so your changes take effect immediately.
- When your PR is merged, the guideline file goes through normal code review by repository maintainers.
Was this review helpful? React with 👍 or 👎 to give feedback.
This review was generated by an AI agent (OpenHands) on behalf of the user through OpenHands Automation. View conversation
Two non-blocking issues from the second all-hands-bot review: 1. Unknown-session observation was misleading: when write_stdin cannot find a session_id it returned (msg, 0.0, None, None), which caused _format_header to emit 'exit_code=None' and the visualize property to render '❌ Done -- exit_code=None' — both incorrect. Fix: add explicit (None, None) branch in _format_header that emits '[Session not found -- no running process with this session_id]', and update visualize to render '❓ Session not found' in that case. Also extend the test to verify the observation text, not just the raw tuple. 2. Standalone write_stdin was permanently useless: Tool(name='write_stdin') created an isolated manager with no sessions, so every write_stdin call returned 'No running session'. Fix: introduce get_or_create_manager(conv_id, work_dir) backed by a WeakValueDictionary keyed on str(conv_state.id). ExecCommandTool.create, WriteStdinTool.create, and InteractiveTerminalToolSet.create all share the same manager for the same conversation, so standalone tools and the toolset are interchangeable and session IDs are valid across all paths. The WeakValueDictionary lets managers be garbage-collected once the conversation closes and all executor references are dropped. Co-authored-by: openhands <openhands@all-hands.dev>
|
Addressed second-round improvements in e3e7390 — fixed misleading 'session not found' observation text, added per-conversation manager sharing via WeakValueDictionary so standalone tools work correctly, and extended the test to verify observation output. All 0 unresolved threads. Re-requesting review. |
|
✅ Review complete. This review was performed through OpenHands Cloud Automation. You can log in and view the conversation here. This comment was generated by an AI agent (OpenHands) on behalf of the user. |
all-hands-bot
left a comment
There was a problem hiding this comment.
🔴 Taste Rating: Needs improvement — the feature shape is useful, but the current implementation still breaks the advertised raw-stdin contract and bypasses one important terminal execution behavior.
[CRITICAL ISSUES]
- See inline comment on
impl.py:write_stdinstill routes input throughTerminalSession.execute(), which strips the command string before dispatch, so leading/trailing whitespace and blank lines are not preserved.
[IMPROVEMENT OPPORTUNITIES]
- See inline comment on
executor.py: this new command execution path masks output, but it does not perform the existing terminal tool's secret-registry export step before running commands.
[TESTING GAPS]
- Add real-code tests for stdin payloads with leading spaces, trailing spaces, and multiple blank lines. The focused suite passes (
uv run pytest tests/tools/interactive_terminal/test_interactive_terminal.py -q→ 25 passed), but it does not catch the byte-stream regression above.
[RISK ASSESSMENT]
- [Overall PR]
⚠️ Risk Assessment: 🟡 MEDIUM
This is additive, but it introduces a public command/stdin execution surface. The remaining issue affects correctness for real interactive programs where whitespace is significant, and terminal/stdin behavior has agent-evaluation blast radius.
VERDICT:
❌ Needs rework: preserve raw stdin semantics before this can be treated as Codex-compatible.
KEY INSIGHT:
The hard part is not keeping a pane alive; it is preserving the byte-stream and execution-environment contracts users expect from a terminal tool.
Improve this review? If any feedback above seems incorrect or irrelevant to this repository, you can teach the reviewer to do better:
- Add a
.agents/skills/custom-codereview-guide.mdfile to your branch (or edit it if one already exists) with the/codereviewtrigger and the context the reviewer is missing (e.g., "Security concerns about X do not apply here because Y"). See the customization docs for the required frontmatter format.- Re-request a review - the reviewer reads guidelines from the PR branch, so your changes take effect immediately.
- When your PR is merged, the guideline file goes through normal code review by repository maintainers.
Resolve with AI? Install the iterate skill in your agent and run
/iterateto automatically drive this PR through CI, review, and QA until it's merge-ready.Was this review helpful? React with 👍 or 👎 to give feedback.
This review was generated by an AI agent (OpenHands) on behalf of the user through OpenHands Automation. View conversation
all-hands-bot
left a comment
There was a problem hiding this comment.
✅ QA Report: PASS
Verified the new InteractiveTerminalToolSet end-to-end as an SDK user: commands execute, long-running sessions yield proactively, polling/input/interrupt work, and standalone tools share sessions.
Does this PR achieve its stated goal?
Yes. The PR set out to add Codex-compatible exec_command + write_stdin tools with yield_time_ms so agents can monitor long-running processes without blocking. I verified the module is absent on main, then on this PR used the public SDK surface to create the tools and exercised fast commands, background sessions, the 5s empty-poll floor, stdin interaction, Ctrl+C interruption, missing-session handling, and separately-created tool sharing.
| Phase | Result |
|---|---|
| Environment Setup | ✅ make build completed successfully; no tests, linters, formatters, or pre-commit were run. |
| CI Status | 🟡 At check time: 21 successful, 3 skipped, 8 pending, 0 failing. |
| Functional Verification | ✅ Real SDK usage scripts passed against commit e3e7390. |
Functional Verification
Test 1: Baseline vs PR availability
Step 1 — Establish baseline on origin/main:
Ran:
git -c advice.detachedHead=false checkout origin/main && \
uv run python -c "import importlib.util; spec=importlib.util.find_spec('openhands.tools.interactive_terminal'); print('BASELINE_RESULT:', 'interactive_terminal module is absent on main' if spec is None else 'unexpected module import success on main'); print('BASELINE_SPEC:', spec)"Observed:
BASELINE_RESULT: interactive_terminal module is absent on main
BASELINE_SPEC: None
This establishes the feature is newly introduced by the PR.
Step 2 — Apply the PR changes:
Checked out commit e3e7390beb96cbc7d7826187854e7fa7c925ca0a.
Step 3 — Use the feature through the SDK public API:
Ran a script that imports InteractiveTerminalToolSet from openhands.tools, creates a real ConversationState, calls exec_command and write_stdin, and asserts the observations. Key output:
TOOLS: ['exec_command', 'write_stdin']
FAST: session_id=None exit_code=0 output='fast-ok' wall=0.12s
WORKDIR: exit_code=0 contains_workspace=True contains_marker=True
SLOW_START: session_id=3 exit_code=None has_start=True wall=0.52s
EMPTY_POLL: session_id=3 exit_code=None tool_wall=5.05s local_elapsed=5.05s
INTERRUPT: session_id=None exit_code=130 wall=0.62s
PROMPT_START: session_id=4 exit_code=None output='name?'
PROMPT_ANSWER: session_id=None exit_code=0 contains_hello=True output='hello Ada'
MISSING_SESSION: session_id=None exit_code=None output='No running session with session_id=999999. The process may have already completed or was never started.'
QA_RESULT: interactive terminal feature works end-to-end
This confirms the core behavior: fast commands return exit_code, slow commands return session_id, empty polls yield after the documented floor while keeping the process alive, stdin is delivered to an interactive process, Ctrl+C terminates the running process, and unknown sessions report clearly without pretending to be complete.
Test 2: Separately-created tools share a session manager
Step 1 — Baseline expectation:
The PR claims exec_command and write_stdin can be created as standalone tools while still sharing session IDs for a conversation.
Step 2 — Apply the PR changes:
Used the same PR checkout at e3e7390beb96cbc7d7826187854e7fa7c925ca0a.
Step 3 — Create standalone tools and poll the session:
Ran a script that creates ExecCommandTool.create(state)[0] and WriteStdinTool.create(state)[0] separately, starts sleep 7, polls it, then interrupts it. Output:
STANDALONE_START: session_id=1 exit_code=None wall=0.52s
STANDALONE_POLL: session_id=1 exit_code=None wall=5.05s
STANDALONE_INTERRUPT: session_id=None exit_code=130
QA_RESULT: standalone tools share a session manager
This confirms separately-created tools can coordinate on the returned session_id, matching the PR's intended API behavior.
Issues Found
None.
This QA review was created by an AI agent (OpenHands) on behalf of the user.
…oc (#3806) Critical: don't strip stdin bytes in TerminalSession The existing terminal_session.execute() applied .strip() to every action command, including is_input=True stdin writes. This silently dropped leading/trailing whitespace and multiple trailing newlines, breaking whitespace-significant stdin input (e.g. ' hi\n' was received as 'hi\n'). Fix: only strip for shell commands (is_input=False); preserve stdin bytes as-is so write_stdin delivers the exact byte stream. Important: document secret-export limitation in exec_command Unlike TerminalTool, exec_command does not pre-export registered secrets into the command environment before execution. Added: - Prominent 'Known limitations' section in the exec_command tool description - TODO comment in ExecCommandExecutor explaining the gap and path forward Co-authored-by: openhands <openhands@all-hands.dev>
|
Third-round fixes in 74a5cfd: fixed stdin .strip() bypass in terminal_session.py (bytes now pass as-is for is_input=True), and documented secret-export limitation prominently with TODO. All 0 unresolved threads. Re-requesting review. |
|
✅ Review complete. This review was performed through OpenHands Cloud Automation. You can log in and view the conversation here. Verdict: COMMENT — 3 polish-level 🟡 suggestions: Reviewed commits: |
all-hands-bot
left a comment
There was a problem hiding this comment.
✅ QA Report: PASS
The new interactive terminal toolset worked end-to-end for real shell commands, stdin interaction, background polling, and concurrent sessions.
Does this PR achieve its stated goal?
Yes. The PR set out to add Codex-style exec_command / write_stdin tools with proactive yield_time_ms control so agents can monitor long-running processes without blocking indefinitely. I verified the feature as a user would through the public SDK toolset API: base main cannot import the tool, while the PR branch exposes InteractiveTerminalToolSet, returns exit_code for completed commands, returns session_id for still-running commands, polls/writes stdin successfully, enforces the empty-poll floor, and supports multiple simultaneous sessions.
| Phase | Result |
|---|---|
| Environment Setup | ✅ make build completed and installed the uv workspace dependencies. |
| CI Status | 🟡 Most checks successful; several PR checks/builds were still in progress when observed, including tools-tests, windows-tests, and image builds. |
| Functional Verification | ✅ Exercised the new SDK toolset with real terminal commands and interactive stdin. |
Functional Verification
Test 1: Baseline availability vs PR availability
Step 1 — Establish baseline without the feature:
Ran:
cd /tmp/qa-main-interactive-terminal && uv run python - <<'PY'
try:
from openhands.tools.interactive_terminal import InteractiveTerminalToolSet
except Exception as exc:
print(type(exc).__name__ + ': ' + str(exc))
else:
print('UNEXPECTED_IMPORT_SUCCESS', InteractiveTerminalToolSet)
PYOutput:
ModuleNotFoundError: No module named 'openhands.tools.interactive_terminal'
This confirms the toolset is new user-facing functionality rather than pre-existing behavior on main.
Step 2 — Apply the PR's changes:
Checked out commit 74a5cfd2e3432ad780415724e108866c174f8251 in /tmp/qa-pr-interactive-terminal.
Step 3 — Re-run with the PR in place:
Ran a Python SDK script that imported InteractiveTerminalToolSet from openhands.tools, created a ConversationState, called InteractiveTerminalToolSet.create(state), and executed real commands through the returned exec_command / write_stdin tools.
Output excerpt:
top_level_export=InteractiveTerminalToolSet tools=['exec_command', 'write_stdin']
sleep_start: session_id=1 exit_code=None
empty_poll_250ms: session_id=1 exit_code=None wall=5.04s output=''
cleanup: session_id=None exit_code=130
This shows the public export works, both Codex-compatible tool names are created, a long-running command returns session_id rather than exit_code, empty polling keeps the process alive, and a requested 250 ms empty poll is floored to ~5 s as described.
Test 2: End-to-end command execution, polling, stdin, and concurrency
Step 1 — Baseline:
On main, the same verification cannot run because importing openhands.tools.interactive_terminal fails with ModuleNotFoundError as shown above.
Step 2 — Apply the PR's changes:
Used the PR worktree at commit 74a5cfd2e3432ad780415724e108866c174f8251.
Step 3 — Exercise real terminal behavior with the PR:
Ran:
cd /tmp/qa-pr-interactive-terminal && OPENHANDS_SUPPRESS_BANNER=1 uv run python - <<'PY'
# Script created the toolset, then called exec_command/write_stdin with:
# - printf qa_fast
# - for i in 1 2 3; do echo tick:$i; sleep 1; done
# - bash -lc 'read line; echo got:$line'
# - two concurrent sleep 10 commands, then Ctrl+C cleanup
PYOutput excerpt:
tools=['exec_command', 'write_stdin']
fast: type=InteractiveTerminalObservation session_id=None exit_code=0 output='qa_fast'
slow_start: session_id=2 exit_code=None elapsed=1.19s output='tick:1'
poll_1: session_id=None exit_code=0 wall=2.63s output='tick:2\ntick:3'
interactive_start: session_id=3 exit_code=None output=''
interactive_reply: session_id=None exit_code=0 output='got:hello from qa'
multi_start: a=4/None b=5/None distinct=True
multi_cleanup sid=4: session_id=None exit_code=130
multi_cleanup sid=5: session_id=None exit_code=130
This confirms the central user flow: completed commands produce exit_code, background commands produce session_id, later polling returns remaining output and completion, stdin bytes reach an interactive command, and separate exec_command calls run as independent sessions that can be interrupted cleanly.
Issues Found
None.
This review was created by an AI agent (OpenHands) on behalf of the user.
all-hands-bot
left a comment
There was a problem hiding this comment.
Code review — InteractiveTerminalToolSet (3rd-round follow-up)
Three rounds of bot review have been substantively addressed: shared manager via get_or_create_manager + WeakValueDictionary, close()/interrupt() plumbing, output masking, _format_header(None, None) for the missing-session case, and the stdin .strip() fix in terminal_session.py. The data flow is clean, locks are scoped narrowly, and tests cover both unit and integration paths including the background-monitoring pattern. The "Known limitations" section honestly surfaces the missing secret pre-export — good call to land this as a follow-up rather than over-engineer it inline.
A few remaining polish items below before this should flip out of draft.
Findings
🟡 original_token_count is computed from already-truncated output — definition.py lines 116-138 + impl.py lines 165-172. The field is documented as "Approximate token count before any output truncation", but by the time InteractiveTerminalObservation.create() runs len(output), the output argument has already been truncated by the manager:
# impl.py
output = obs.text or ""
if max_output_tokens is not None:
output = output[: max_output_tokens * _CHARS_PER_TOKEN]
...
return InteractiveTerminalObservation.create(
output, wall, session_id, exit_code
)So original_token_count = len(output) // 4 reports the truncated length, not the pre-truncation length. Compute original_token_count in the manager (where it still has access to the un-truncated obs.text) and pass it through as a parameter, or drop the "before any output truncation" wording from the field description.
🟡 No regression test that the toolset shares a single manager — tests/tools/interactive_terminal/test_interactive_terminal.py. The whole point of InteractiveTerminalToolSet (per the get_or_create_manager introduction in round 2) is that exec_command and write_stdin share a manager so session IDs cross over. test_toolset_creates_two_tools only checks that two tools are produced, not that they share state. A simple assertion would lock this in:
def test_toolset_shares_manager_across_tools(tmp_dir):
state = _conv_state(tmp_dir)
tools = InteractiveTerminalToolSet.create(state)
exec_tool = next(t for t in tools if t.name == "exec_command")
write_tool = next(t for t in tools if t.name == "write_stdin")
assert exec_tool.executor._manager is write_tool.executor._manager🟡 _CONTROL_CHAR_MAP discoverability — impl.py lines 53-57. The doc tells users to send literal escape bytes (\x03, \x04, \x1a), but a user typing the OpenHands-style literal chars="C-c" will be sent verbatim and tmux send_keys won't interpret it as Ctrl+C. Either extend the map to recognize OpenHands-style strings too, or note in the tool description that escape bytes are required (not literal C-c).
Style notes
The executor.py _mask_output helper swallows all exceptions silently with except Exception:. The conversation is None and empty-output guards make the failure mode extremely narrow, but a one-line comment explaining why the broad except is intentional (e.g., "masking must never break tool execution — secrets are still exported to env by the caller, so the only thing at stake is output hygiene") would prevent a future cleanup pass from tightening this in a way that masks real bugs.
Testing
The new tests are real end-to-end (real TerminalSession, real bash, real signal delivery) rather than mock-heavy, and the _unix_only guards are appropriate. Coverage of the original_token_count field exists only for the un-truncated path — consider extending it to assert that the field is meaningful when max_output_tokens truncates.
[RISK ASSESSMENT]
- [Overall PR]
⚠️ Risk Assessment: 🟡 MEDIUM
The new public SDK surface (InteractiveTerminalToolSet+ two registered tools) executes arbitrary shell commands in a PTY with no secret pre-export. Output masking mitigates the leak surface, but users who rely on$SECRET_NAMEexpansion incmdwill see silent failures. The "Known limitations" doc section makes this discoverable, so I do not recommend blocking — but please add an entry to CHANGELOG / release notes so downstream users are not surprised when they migrate fromTerminalTool.
VERDICT:
✅ Worth merging once the open suggestion on original_token_count is resolved. The architecture is sound, the bot-review feedback has been addressed thoughtfully, and tests exercise real code paths. The remaining items are polish-level and won't block an otherwise-clean merge.
KEY INSIGHT:
The cleanest payoff of get_or_create_manager + the per-conversation WeakValueDictionary is that Tool(name="exec_command") and Tool(name="write_stdin") can be registered independently and work together — the cache key is the conversation ID, not the registry call site. Worth calling out in the module docstring so future toolset authors copy the pattern rather than reinventing it.
This review was generated by an AI agent (OpenHands) on behalf of the user through OpenHands Automation. View conversation
Improve this review? If any feedback above seems incorrect or irrelevant to this repository, you can teach the reviewer to do better:
- Add a
.agents/skills/custom-codereview-guide.mdfile to your branch (or edit it if one already exists) with the/codereviewtrigger and the context the reviewer is missing (e.g., "Security concerns about X do not apply here because Y"). See the customization docs for the required frontmatter format.- Re-request a review - the reviewer reads guidelines from the PR branch, so your changes take effect immediately.
- When your PR is merged, the guideline file goes through normal code review by repository maintainers.
Resolve with AI? Install the iterate skill in your agent and run
/iterateto automatically drive this PR through CI, review, and QA until it's merge-ready.Was this review helpful? React with 👍 or 👎 to give feedback.
Four suggestions from the all-hands-bot review (all non-blocking):
1. original_token_count computed from already-truncated output
InteractiveTerminalObservation.create() now accepts original_token_count
as a parameter; the manager computes it BEFORE truncation and passes it
through the return 5-tuple. Tests updated to unpack the extra value.
2. chars='C-c' style not handled in _CONTROL_CHAR_MAP
Added OpenHands-style literal key names ('C-c', 'C-d', 'C-z') as
passthrough aliases in the control char map so both raw bytes (\x03)
and string format work transparently.
3. No test for toolset sharing a manager
Added test_toolset_shares_manager_across_tools: creates both tools via
the toolset, starts a background process via exec_command, and asserts
that write_stdin can poll it by session_id — confirming shared manager.
4. Bare 'except Exception' in _mask_output needs a comment
Added an explanatory comment explaining why masking must never break
tool execution (keeps raw output on registry errors/mocks in tests).
Co-authored-by: openhands <openhands@all-hands.dev>
|
All 4 suggestions addressed in 0a69781 — original_token_count fixed (pre-truncation), C-c/C-d/C-z string aliases added, manager-sharing test added, bare except comment added. Re-requesting review. |
|
✅ Review complete. This review was performed through OpenHands Cloud Automation. You can log in and view the conversation here. |
all-hands-bot
left a comment
There was a problem hiding this comment.
✅ QA Report: PASS
Verified the new interactive terminal tools end-to-end through the public SDK API; the feature works as described in this environment.
Does this PR achieve its stated goal?
Yes. The PR set out to add Codex-style exec_command + write_stdin tools with proactive yield_time_ms so agents can monitor background processes. I verified that the base branch has no such API, then on the PR branch created the toolset through InteractiveTerminalToolSet.create(...) and exercised fast command completion, background command yield/poll, byte-accurate stdin, multiple simultaneous sessions, and Ctrl+C interruption with real terminal processes.
| Phase | Result |
|---|---|
| Environment Setup | ✅ make build completed successfully and installed the uv workspace environment. |
| CI Status | ⏳ gh pr checks reported 19 successful, 0 failing, 10 pending, 3 skipped at review time. |
| Functional Verification | ✅ Real SDK calls and terminal processes behaved as the PR describes. |
Functional Verification
Test 1: Baseline vs PR API availability
Step 1 — Establish baseline without the feature:
Checked out origin/main and ran /tmp/qa_interactive_terminal_baseline.py:
top_level_import: ImportError cannot import name 'InteractiveTerminalToolSet' from 'openhands.tools' (.../openhands-tools/openhands/tools/__init__.py)
submodule_import: ImportError cannot import name 'InteractiveTerminalToolSet' from 'openhands.tools.interactive_terminal' (unknown location)
existing_terminal_tool_name: terminal
This establishes the previous user-facing state: only the existing terminal tool was importable; InteractiveTerminalToolSet was not available.
Step 2 — Apply the PR's changes:
Checked out feat/interactive-terminal-exec-command-write-stdin at 7de127313bd89f21d36514a3080eae4f34a7e7c2.
Step 3 — Re-run with the feature in place:
Ran /tmp/qa_interactive_terminal_pr.py, which imports from openhands.tools, creates a ConversationState, calls InteractiveTerminalToolSet.create(state), and invokes the returned exec_command / write_stdin tools with real shell processes.
Test 2: Fast command, background monitoring, stdin, concurrency, and interrupts
Step 1 — Baseline behavior:
On origin/main, this workflow cannot be run because the imports above fail. That confirms the workflow is new user-facing functionality added by the PR.
Step 2 — Apply the PR's changes:
Used the PR branch and the public SDK/tool API.
Step 3 — Exercise the new behavior:
Ran uv run --no-sync python /tmp/qa_interactive_terminal_pr.py:
{
"tool_names": ["exec_command", "write_stdin"],
"public_export_same_object": true,
"fast_command": {
"exit_code": 0,
"session_id": null,
"wall_time_seconds": 0.124,
"output": "hello_from_exec"
},
"slow_initial": {
"exit_code": null,
"session_id": 2,
"wall_time_seconds": 1.022,
"observed_outer_wall": 1.781,
"output": "tick 0
tick 1
tick 2"
},
"slow_poll_to_completion": {
"exit_code": 0,
"session_id": null,
"wall_time_seconds": 1.63,
"output": "tick 3
tick 4
tick 5"
},
"interactive_initial": {
"exit_code": null,
"session_id": 3,
"output": "ready"
},
"interactive_partial_write": {
"exit_code": null,
"session_id": 3,
"output": ""
},
"interactive_finish_write": {
"exit_code": 0,
"session_id": null,
"output": "DATA:'abcd'"
},
"concurrent_sessions": {
"a": {"exit_code": null, "session_id": 4},
"b": {"exit_code": null, "session_id": 5}
},
"interrupts": {
"a": {"exit_code": 130, "session_id": null, "output": "^C"},
"b": {"exit_code": 130, "session_id": null, "output": "^C"}
}
}This shows the feature works end-to-end: fast commands return only exit_code, long-running commands return session_id and can be polled to completion, write_stdin(chars="abc") does not append Enter and leaves the process running until d is sent, two background sessions get distinct IDs, and Ctrl+C terminates both sessions with exit code 130.
Issues Found
None.
This review was created by an AI agent (OpenHands) on behalf of the user.
all-hands-bot
left a comment
There was a problem hiding this comment.
🟡 Acceptable — Solid additive implementation with comprehensive real-execution tests. The design mirrors Codex's API cleanly and solves a genuine problem. A few improvement opportunities below, none blocking.
Summary:
InteractiveTerminalToolSetaddsexec_command+write_stdinwithyield_time_msfor Codex-style background process monitoring- The binary
session_id/exit_codesignal (exactly one set) is a clean design with no ambiguous sentinel values - Session management via
WeakValueDictionarywith a per-conversation mutex correctly prevents TOCTOU races - The
append_enter=Truedefault in theTerminalSession.execute()change preserves backward compatibility forTerminalTool - Test suite exercises real code paths — no mocking of the unit under test
[IMPROVEMENT OPPORTUNITIES]
See inline comments for details.
[RISK ASSESSMENT]
-
[Overall PR]
⚠️ Risk Assessment: 🟢 LOWPurely additive: new package + one backward-compatible method signature extension. The only change to existing behaviour is that
TerminalSession.execute()no longer strips leading/trailing whitespace fromis_input=Truetext — this is intentional and the defaultappend_enter=Truepath is unchanged forTerminalTool. No breaking changes to public APIs.
VERDICT:
✅ Worth merging — Core logic is sound, tests are thorough. Minor polish items can be addressed in follow-up.
KEY INSIGHT:
The per-conversation WeakValueDictionary singleton pattern is the right call here — it's the only way to guarantee exec_command session IDs remain valid for subsequent write_stdin calls when the two tools are created independently, without coupling them at construction time.
Improve this review? If any feedback above seems incorrect or irrelevant to this repository, you can teach the reviewer to do better:
- Add a
.agents/skills/custom-codereview-guide.mdfile to your branch (or edit it if one already exists) with the/codereviewtrigger and the context the reviewer is missing. See the customization docs for the required frontmatter format.- Re-request a review - the reviewer reads guidelines from the PR branch, so your changes take effect immediately.
- When your PR is merged, the guideline file goes through normal code review by repository maintainers.
Resolve with AI? Install the iterate skill in your agent and run
/iterateto automatically drive this PR through CI, review, and QA until it's merge-ready.Was this review helpful? React with 👍 or 👎 to give feedback.
This review was generated by an AI agent (OpenHands) on behalf of the user through OpenHands Automation. View conversation
|
Addressed all round-7 (non-blocking) suggestions in 821928b:
All 3 threads replied + resolved. 28/28 interactive_terminal tests pass; ruff/pyright clean. Ready for another look. |
|
✅ Review complete. This review was performed through OpenHands Cloud Automation. You can log in and view the conversation here. |
all-hands-bot
left a comment
There was a problem hiding this comment.
✅ QA Report: PASS
The new InteractiveTerminalToolSet works end-to-end for real SDK/tool usage: exec_command proactively yields with a running session_id, write_stdin polls and sends input, and completed commands return exit_code.
Does this PR achieve its stated goal?
Yes. The PR set out to add Codex-style interactive terminal tools (exec_command + write_stdin) with yield_time_ms so agents can monitor background processes without blocking. I verified the base branch has no such tool module, then ran the PR implementation through real SDK calls covering fast completion, long-running proactive yield, empty polling with the 5s floor, Ctrl+C interruption, byte-accurate stdin, concurrent sessions, output truncation, missing-session reporting, and top-level public import.
| Phase | Result |
|---|---|
| Environment Setup | ✅ make build completed successfully; dependencies installed in .venv. |
| CI Status | ⏳ Existing PR checks queried only: 19 success, 10 in progress, 3 skipped at QA time. |
| Functional Verification | ✅ Real SDK/tool scripts passed on the PR branch; no behavioral issues found. |
Functional Verification
Test 1: Base branch lacks the new interactive terminal entry point
Step 1 — Reproduce / establish baseline (without the feature):
Ran git switch --detach origin/main && uv run python /tmp/qa_pr3806_interactive_terminal.py:
BASE_EXIT=1
Traceback (most recent call last):
File "/tmp/qa_pr3806_interactive_terminal.py", line 12, in <module>
from openhands.tools.interactive_terminal import (
ModuleNotFoundError: No module named 'openhands.tools.interactive_terminal'
This confirms the base branch does not provide the new openhands.tools.interactive_terminal tool entry point.
Step 2 — Apply the PR's changes:
Checked out 821928bb69109553764cc400b2e234e49c34b743.
Step 3 — Re-run with the feature in place:
Ran uv run python /tmp/qa_pr3806_interactive_terminal.py using real SDK ConversationState + InteractiveTerminalToolSet.create(state) calls:
{
"tool_names": ["exec_command", "write_stdin"],
"fast_command": {"exit_code": 0, "session_id": null, "output": "fast-ok", "wall_time_seconds": 0.63},
"slow_start": {"exit_code": null, "session_id": 2, "wall_time_seconds": 0.52, "output_contains_tick1": true},
"empty_poll": {"exit_code": null, "session_id": 2, "measured_seconds": 5.05, "output_contains_tick2": true},
"interrupt": {"exit_code": 130, "session_id": null},
"byte_accurate_stdin": {"partial_still_running": true, "final_exit_code": 0, "final_output_contains": true},
"concurrent_sessions": {"distinct": true, "session_ids": [4, 5], "cleanup_exit_codes": [130, 130]},
"max_output_tokens": {"exit_code": 0, "output_bytes": 20, "original_token_count": 50},
"missing_session": {"exit_code": null, "session_id": null, "mentions_requested_id": true}
}This shows the PR delivers the core claimed behavior: fast commands return exit_code, long-running commands return session_id after the requested yield instead of blocking, empty polls wait around 5s and keep the process running, Ctrl+C completes the session, raw stdin does not append Enter, and independent sessions can be monitored/cleaned up separately.
Test 2: Public import path works
Ran uv run python - <<'PY' ... from openhands.tools import InteractiveTerminalToolSet ... PY:
{
"top_level_export_name": "interactive_terminal_tool_set"
}This confirms the toolset is exported from the public openhands.tools surface as described.
Issues Found
None.
This QA review was generated by an AI agent (OpenHands) on behalf of the user.
all-hands-bot
left a comment
There was a problem hiding this comment.
🟡 Taste Rating: Acceptable — the toolset is straightforward and well-tested, but the raw stdin path still has a real byte-contract hole.
[CRITICAL ISSUES]
- See the inline comment: multi-line
write_stdin(chars=...)is rejected by shell command splitting before it reaches the process, so the advertised verbatim stdin contract is not true for common inputs.
[TESTING GAPS]
- Add a regression test where a running process reads input containing an embedded newline, e.g.
chars="hello\nworld". I reproduced this locally; the current code returnsCannot execute multiple commands at once...and sends nothing.
[RISK ASSESSMENT]
- [Overall PR]
⚠️ Risk Assessment: 🟡 MEDIUM
This adds new terminal execution tools and changesTerminalSession.execute()stdin handling, so it can affect agent/tool behavior. Targeted tests pass (uv run pytest tests/tools/interactive_terminal/test_interactive_terminal.py -q), but the repo's eval-risk policy also means this should not be approved until a human maintainer decides whether lightweight evals are needed.
VERDICT:
❌ Needs rework: Fix the raw-stdin splitter path before merging; then re-run the targeted tests and any maintainer-required evals.
KEY INSIGHT:
The new API's value is byte-accurate stdin, so the implementation needs an input path that bypasses shell-command validation entirely.
Improve this review? If any feedback above seems incorrect or irrelevant to this repository, you can teach the reviewer to do better:
- Add a
.agents/skills/custom-codereview-guide.mdfile to your branch (or edit it if one already exists) with the/codereviewtrigger and the context the reviewer is missing (e.g., "Security concerns about X do not apply here because Y"). See the customization docs for the required frontmatter format.- Re-request a review - the reviewer reads guidelines from the PR branch, so your changes take effect immediately.
- When your PR is merged, the guideline file goes through normal code review by repository maintainers.
Resolve with AI? Install the iterate skill in your agent and run
/iterateto automatically drive this PR through CI, review, and QA until it's merge-ready.Was this review helpful? React with 👍 or 👎 to give feedback.
This review was generated by an AI agent (OpenHands) on behalf of the user through OpenHands Automation. View conversation
|
Addressed the CRITICAL multi-line stdin bug in 3290b09: Root cause: TerminalSession.execute() ran split_bash_commands() on every action including is_input=True stdin, so write_stdin(chars="hello\nworld") was rejected as "multiple commands" and nothing reached the process — breaking the byte-accurate delivery contract. Fix: Skip the multi-command split check when is_input=True (stdin bytes are not shell commands and may legitimately contain embedded newlines). Backward-compatible: TerminalTool only sends single-line is_input, so its behavior is unchanged. Test: Added test_write_stdin_delivers_embedded_newline — starts a process reading two lines, sends chars="hello\nworld\n", asserts no rejection + exit_code==0 + bytes received verbatim. Thread replied + resolved. 29/29 interactive_terminal tests pass; ruff/pyright clean. Ready for another look. |
|
✅ Review complete. This review was performed through OpenHands Cloud Automation. You can log in and view the conversation here. |
all-hands-bot
left a comment
There was a problem hiding this comment.
✅ QA Report: PASS
Verified the new interactive terminal toolset by running real SDK tool calls; the PR delivers Codex-style exec_command/write_stdin behavior with proactive yielding, polling, stdin delivery, interrupts, and independent sessions.
Does this PR achieve its stated goal?
Yes. The stated goal was to add Codex-style interactive terminal tools with yield_time_ms so agents can regain control while commands continue running, then poll or write to the live session. I verified on the PR branch that exec_command returns session_id for running processes and exit_code for completed ones, write_stdin can poll and send byte-accurate stdin, Ctrl+C ends a session with exit code 130, and concurrent sessions receive distinct IDs.
| Phase | Result |
|---|---|
| Environment Setup | ✅ make build completed successfully; no tests/linters were run. |
| CI Status | 🟡 Latest check snapshot: 19 passing, 10 pending, 3 skipped. |
| Functional Verification | ✅ Real SDK/tool execution matched the PR claims. |
Functional Verification
Test 1: Baseline vs PR availability
Step 1 — Establish baseline on main:
Ran uv run python - <<'PY' ... import openhands.tools.interactive_terminal ... PY in a detached origin/main worktree:
BASELINE_IMPORT ModuleNotFoundError No module named 'openhands.tools.interactive_terminal'
This shows the Codex-style toolset is not available before the PR.
Step 2 — Apply the PR's changes:
Used PR commit 3290b09716c1dabcafa2b76ffcb19c1fdad28fe9 on branch feat/interactive-terminal-exec-command-write-stdin.
Step 3 — Re-run with the PR in place:
Created a real ConversationState, called InteractiveTerminalToolSet.create(state), and ran tool actions through the returned tool definitions:
tools=['exec_command', 'write_stdin']
FAST {'session_id': None, 'exit_code': 0, 'output': 'hello_from_exec', 'wall': 0.12}
PUBLIC_EXPORT {'toolset_name': 'interactive_terminal_tool_set', 'tool_ref_name': 'interactive_terminal_tool_set'}
This confirms the new public export exists and the fast-command path returns exit_code without a session_id.
Test 2: Proactive yielding and polling
Step 1 — Baseline:
On main, this behavior cannot be exercised because openhands.tools.interactive_terminal does not import.
Step 2 — Apply the PR's changes:
Ran a continuous-output command through exec_command with yield_time_ms=500 using isolated tmux state.
Step 3 — Re-run with the PR in place:
CONTINUOUS_START {'external_elapsed': 1.18, 'reported_wall': 0.51, 'session_id': 1, 'exit_code': None, 'line_count': 5, 'last_output_line': 'pulse_04'}
CONTINUOUS_CLEANUP {'session_id': None, 'exit_code': 130}
SLOW_START {'session_id': 2, 'exit_code': None, 'wall': 1.68, 'output': 'tick_1\ntick_2'}
SLOW_POLL {'session_id': None, 'exit_code': 0, 'wall': 5.14, 'output': 'tick_3\ntick_4\ntick_5\ntick_6'}
The continuous-output case reported a 0.51s wait and returned session_id while the process kept running, matching the proactive-yield goal. The empty poll waited about 5s and then returned final output with exit_code=0, matching the described empty-poll floor and completion signal.
Test 3: write_stdin input, interrupts, and independent sessions
Step 1 — Baseline:
On main, the new write_stdin API is unavailable.
Step 2 — Apply the PR's changes:
Started interactive and long-running commands through the PR toolset, then used write_stdin to send data and control characters.
Step 3 — Re-run with the PR in place:
READER_START {'session_id': 3, 'exit_code': None, 'output': ''}
READER_PARTIAL_ABC {'session_id': 3, 'exit_code': None, 'output': ''}
READER_FINISH_D_NEWLINE {'session_id': None, 'exit_code': 0, 'output': "GOT:'abcd'"}
INTERRUPT_RESULT {'session_id': None, 'exit_code': 130, 'output': '^C', 'wall': 0.12}
CONCURRENT_START {'sid_a': 5, 'sid_b': 6, 'distinct': True}
CONCURRENT_CLEANUP_A {'session_id': None, 'exit_code': 130}
CONCURRENT_CLEANUP_B {'session_id': None, 'exit_code': 130}
This shows chars='abc' did not append Enter or complete the read; sending d\n completed it as GOT:'abcd'. Ctrl+C mapped correctly, and simultaneous sessions were independently addressable.
Issues Found
None.
This review was created by an AI agent (OpenHands) on behalf of the user.
all-hands-bot
left a comment
There was a problem hiding this comment.
🟢 Taste Rating: Good taste — this is a clean additive toolset with a simple session_id / exit_code contract, and the latest round fixes the raw-stdin newline hole without complicating the public API.
Summary:
- Reviewed the latest head (
3290b097) and the prior review context; I found no remaining unresolved review threads to avoid duplicating. - The implementation keeps the new
InteractiveTerminalToolSetisolated from the existingTerminalToolAPI while reusing the existingTerminalSessionbackend. - The focused regression coverage exercises real PTY/tmux paths, including raw stdin without appended Enter and embedded-newline stdin.
[VALIDATION]
uv run pytest tests/tools/interactive_terminal/ -q→ 29 passed.uv run ruff check openhands-tools/openhands/tools/interactive_terminal openhands-tools/openhands/tools/terminal/terminal/terminal_session.py tests/tools/interactive_terminal/test_interactive_terminal.py→ passed.uv run pyright openhands-tools/openhands/tools/interactive_terminal openhands-tools/openhands/tools/terminal/terminal/terminal_session.py tests/tools/interactive_terminal/test_interactive_terminal.py→ 0 errors.
[EVAL-RISK NOTE]
This PR changes terminal/stdin/stdout handling, which the repository-specific review guide treats as benchmark/evaluation-risk behavior. I did not find an openhands-eval-monitor.vercel.app completed-run link plus human maintainer confirmation in the PR description or recent comments, so I am leaving this as a COMMENT rather than an approval. A human maintainer should decide after the appropriate lightweight eval/integration validation.
[RISK ASSESSMENT]
- [Overall PR]
⚠️ Risk Assessment: 🟡 MEDIUM
The code change is additive and well-covered by focused real-code-path tests, but it introduces a new public tool surface and changes the sharedTerminalSession.execute(..., is_input=True)path to preserve raw stdin bytes. That can affect agent/tool behavior and benchmark outcomes, so the residual risk is medium until maintainer/eval validation is complete.
VERDICT:
✅ Worth merging from a code-quality standpoint after maintainer validation: I found no blocking code issues in this pass. I am not approving only because the repo’s eval-risk policy requires human/eval evidence for terminal/stdin behavior changes.
KEY INSIGHT:
The important design choice is keeping background-process state in a per-conversation manager while preserving the existing terminal backend semantics everywhere except the explicitly raw write_stdin path.
Improve this review? If any feedback above seems incorrect or irrelevant to this repository, you can teach the reviewer to do better:
- Add a
.agents/skills/custom-codereview-guide.mdfile to your branch (or edit it if one already exists) with the/codereviewtrigger and the context the reviewer is missing (e.g., "Security concerns about X do not apply here because Y"). See the customization docs for the required frontmatter format.- Re-request a review - the reviewer reads guidelines from the PR branch, so your changes take effect immediately.
- When your PR is merged, the guideline file goes through normal code review by repository maintainers.
Resolve with AI? Install the iterate skill in your agent and run
/iterateto automatically drive this PR through CI, review, and QA until it's merge-ready.Was this review helpful? React with 👍 or 👎 to give feedback.
This review was generated by an AI agent (OpenHands) on behalf of the user through OpenHands Automation. View conversation
|
All review threads are now resolved (0 unresolved). CI is fully green on 3290b09 (14/14 checks pass including tools-tests, qa-changes, windows-tests). The latest review confirmed no blocking code issues. Could you take another look and approve if satisfied? |
all-hands-bot
left a comment
There was a problem hiding this comment.
✅ QA Report: PASS
Verified the new InteractiveTerminalToolSet behavior end-to-end with real SDK/tool calls; the PR delivers Codex-style exec_command/write_stdin background monitoring without functional issues found.
Does this PR achieve its stated goal?
Yes. On main, openhands.tools.interactive_terminal is absent; on PR commit 3290b09716c1dabcafa2b76ffcb19c1fdad28fe9, the new toolset imports and works through actual ToolDefinition.__call__ usage. I verified fast commands return exit_code, long commands proactively yield a session_id, write_stdin can poll/send input/interrupt, empty polls enforce the ~5s floor while the process stays running, and the existing terminal input path still appends Enter by default.
| Phase | Result |
|---|---|
| Environment Setup | ✅ make build completed successfully; no tests/linters were run. |
| CI Status | ⏳ gh pr checks reported 34 successful, 3 skipped, 0 failing, 1 pending (QA Changes by OpenHands). |
| Functional Verification | ✅ Real SDK/tool execution passed all manual checks. |
Functional Verification
Test 1: Before/after availability of the new public toolset
Step 1 — Establish baseline on base branch:
Ran git switch --detach origin/main && uv run python /tmp/qa_import_interactive_terminal.py:
IMPORT_STATUS=missing (ModuleNotFoundError: No module named 'openhands.tools.interactive_terminal')
This confirms the feature is new user-facing SDK/tool surface and not present on main.
Step 2 — Apply the PR's changes:
Checked out PR commit 3290b09716c1dabcafa2b76ffcb19c1fdad28fe9.
Step 3 — Re-run with the PR:
Ran uv run python /tmp/qa_import_interactive_terminal.py:
IMPORT_STATUS=available toolset=InteractiveTerminalToolSet
This confirms the new import path is available from the PR branch.
Test 2: Real exec_command / write_stdin interaction through the SDK toolset
Ran OPENHANDS_SUPPRESS_BANNER=1 uv run python /tmp/qa_run_interactive_terminal.py, which creates a ConversationState, obtains tools from InteractiveTerminalToolSet.create(state), and calls the tools with real commands:
[
{"name": "fast command completes inline", "ok": true, "exit_code": 0, "session_id": null, "output": "fast-ok", "wall": 0.122},
{"name": "slow command yields session_id quickly", "ok": true, "exit_code": null, "session_id": 2, "output": "slow-start", "wall": 0.517, "elapsed": 1.239},
{"name": "can run another command while prior session continues", "ok": true, "exit_code": 0, "session_id": null, "output": "parallel-fast-ok"},
{"name": "polling running session reaches completion", "ok": true, "exit_code": 0, "session_id": null, "output": "slow-done", "wall": 1.124},
{"name": "write_stdin sends entered input", "ok": true, "exit_code": 0, "session_id": null, "output": "got:hello from qa"},
{"name": "write_stdin preserves raw bytes without implicit Enter", "ok": true, "partial_session_id": 5, "partial_exit_code": null, "final_exit_code": 0, "final_session_id": null, "output": "raw:'abcd'"},
{"name": "write_stdin ctrl-c interrupts running process", "ok": true, "exit_code": 130, "session_id": null, "output": "^C"},
{"name": "TerminalSession default input still appends Enter", "ok": true, "exit_code": 0, "output": "legacy-readylegacy:legacy input"}
]This verifies the core user behavior claimed by the PR: clean session_id vs exit_code signaling, proactive yield for long-running commands, background monitoring while another command runs, stdin delivery, raw-byte behavior, Ctrl+C interruption, and no regression to the existing terminal default Enter behavior.
Test 3: Empty poll minimum wait while process remains running
Ran OPENHANDS_SUPPRESS_BANNER=1 uv run python /tmp/qa_poll_floor.py:
{
"interrupt_exit_code": 130,
"poll_exit_code": null,
"poll_session_id": 1,
"poll_waited_at_least_5s": true,
"poll_wall_time_seconds": 5.047,
"start_session_id": 1
}This confirms an empty write_stdin poll with yield_time_ms=250 waited about 5 seconds and returned the same running session_id, matching the PR's claimed empty-poll behavior.
Issues Found
None.
This review was created by an AI agent (OpenHands) on behalf of the user.
|
✅ Review complete. This review was performed through OpenHands Cloud Automation. You can log in and view the conversation here. |
|
🔍 Review in progress… We are performing the review through OpenHands Cloud Automation. You can log in and view the conversation here. |
all-hands-bot
left a comment
There was a problem hiding this comment.
Taste rating: 🟢 Good taste — clean additive design, well-scoped, and the API surfaces are tight. The InteractiveTerminalManager keyed by conv_id with a WeakValueDictionary is a simple, elegant way to share state across two standalone tools without coupling their construction. The NamedTuple for TerminalResult makes the call sites self-documenting and catches field reordering at definition time, which is a nice touch. The byte-safe UTF-8 truncation that preserves original_token_count before clamping, the verbatim-bytes contract for write_stdin with explicit opt-in, and the chars → C-c/C-d/C-z control-character mapping all reflect careful API design. Two minor suggestions below; the lifecycle/close()-vs-interrupt() concern raised by other reviewers is acknowledged and is appropriately scoped out of this additive PR — the existing TerminalTool still works for the secret-export and lifecycle-sensitive paths.
This review was generated by an AI agent (OpenHands) on behalf of the user through OpenHands Automation. View conversation
all-hands-bot
left a comment
There was a problem hiding this comment.
Taste rating: 🟢 Good taste — clean additive design, well-scoped, and the API surfaces are tight. The InteractiveTerminalManager keyed by conv_id with a WeakValueDictionary is a simple, elegant way to share state across two standalone tools without coupling their construction. The NamedTuple for TerminalResult makes the call sites self-documenting and catches field reordering at definition time, which is a nice touch. The byte-safe UTF-8 truncation that preserves original_token_count before clamping, the verbatim-bytes contract for write_stdin with explicit opt-in, and the chars → C-c/C-d/C-z control-character mapping all reflect careful API design. Two minor suggestions below; the lifecycle/close()-vs-interrupt() concern raised by other reviewers is acknowledged and is appropriately scoped out of this additive PR — the existing TerminalTool still works for the secret-export and lifecycle-sensitive paths.
This review was generated by an AI agent (OpenHands) on behalf of the user through OpenHands Automation. View conversation
…mmand Resolves the unresolved review threads on PR #3806 that flagged the `TODO(issue)` placeholder in ExecCommandExecutor as a maintenance trap. Implements the env-var export passthrough (option a from the review): ExecCommandExecutor now resolves secrets referenced by the command from the conversation's secret registry and passes them to InteractiveTerminalManager.exec_command, which exports them into the session before running the command — mirroring TerminalExecutor._export_envs. This keeps interactive sessions consistent with the regular TerminalTool so commands that reference registered secrets resolve them in-process, and the existing output masking covers the echoed values. Co-authored-by: openhands <openhands@all-hands.dev>
|
[Automatic Post]: It has been a while since there was any activity on this PR. @neubig, are you still working on it? If so, please go ahead, if not then please request review, close it, or request that someone else follow up. This comment was created by an AI agent (OpenHands) on behalf of the user. |
1 similar comment
|
[Automatic Post]: It has been a while since there was any activity on this PR. @neubig, are you still working on it? If so, please go ahead, if not then please request review, close it, or request that someone else follow up. This comment was created by an AI agent (OpenHands) on behalf of the user. |
|
Closing due to lack of time to test properly. |
HUMAN:
Adding Codex-style interactive terminal tools (exec_command + write_stdin) with proactive yield_time_ms so agents can monitor background processes. Iterating per review feedback (round 4).
AGENT:
This PR was created by an AI agent (OpenHands) on behalf of the user.
Why
The existing
terminaltool blocks until output stops for 30 s (reactive no-change timeout), then asks the agent to continue. This prevents an agent from monitoring multiple long-running processes — it has to sit passively waiting.Codex solves this with proactive time-based yields:
yield_time_mstells the tool "give me control back after N ms regardless of activity". The process keeps running; the agent polls or does other work between checks.Summary
openhands.tools.interactive_terminalwith two tools (exec_command,write_stdin) matching Codex's API exactly.exec_commandreturnssession_idwhen still running orexit_codewhen done — clean binary signal, no ambiguous-1exit codes.write_stdinsends stdin bytes (or polls with emptychars) to a running session.Issue Number
N/A (exploratory implementation from user request to match Codex background-process monitoring)
How to Test
Or run the test suite directly:
uv run pytest tests/tools/interactive_terminal/ -v # 25 passed in ~38sVideo/Screenshots
Live experiment output (from agent session):
Full tool interface test:
Type
Notes
TerminalToolis untouched.InteractiveTerminalToolSetis exported fromopenhands.toolspublic surface.InteractiveTerminalManageris thread-safe (lock around_sessionsdict).exec_commandcall creates a freshTerminalSession(tmux pane) so sessions are truly independent.\x03→C-c,\x04→C-d,\x1a→C-z. Other bytes sent verbatim to stdin.@neubig can click here to continue refining the PR
Agent Server images for this PR
• GHCR package: https://github.com/OpenHands/agent-sdk/pkgs/container/agent-server
Variants & Base Images
eclipse-temurin:17-jdknikolaik/python-nodejs:python3.13-nodejs22-slimgolang:1.21-bookwormPull (multi-arch manifest)
# Each variant is a multi-arch manifest supporting both amd64 and arm64 docker pull ghcr.io/openhands/agent-server:a5c4203-pythonRun
All tags pushed for this build
About Multi-Architecture Support
a5c4203-python) is a multi-arch manifest supporting both amd64 and arm64a5c4203-python-amd64) are also available if neededCloses #3876