Skip to content

Reuse PTY startup handshake during shell startup#128

Merged
F16shen merged 3 commits into
AI-Shell-Team:mainfrom
F16shen:fix/startup-handshake-reuse
Apr 23, 2026
Merged

Reuse PTY startup handshake during shell startup#128
F16shen merged 3 commits into
AI-Shell-Team:mainfrom
F16shen:fix/startup-handshake-reuse

Conversation

@F16shen
Copy link
Copy Markdown
Collaborator

@F16shen F16shen commented Apr 23, 2026

Summary

  • expose PTY startup handshake state and startup cwd from PTYManager
  • reuse that startup-ready state in PTYAIShell._setup_pty() instead of waiting for a second backend-ready timeout
  • keep the old sleep only as a fallback when startup handshake is unavailable
  • add regression tests for manager startup state exposure and shell-side startup handshake reuse

Validation

  • pytest tests/terminal/pty/test_pty_control_protocol.py tests/shell/runtime/test_shell_pty_core.py
  • repeated startup timing check dropped first-prompt latency from about 3.1s to about 0.89s in local measurement

Summary by CodeRabbit

  • New Features

    • Improved shell startup: backend session readiness is detected during initialization, the backend working directory is synchronized when available, and the shell moves to editing mode immediately when ready.
  • Bug Fixes

    • Removed an unnecessary startup delay so initialization proceeds promptly when readiness is confirmed.
  • Tests

    • Added tests validating the startup handshake, readiness indicators, and immediate post-start state.

@github-actions github-actions Bot added the tests label Apr 23, 2026
@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:

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

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 23, 2026

📝 Walkthrough

Walkthrough

After PTY startup drain, PTYManager records startup readiness and initial CWD via new properties; PTYAIShell._setup_pty now consults these flags to optionally sync the backend CWD, mark the backend session ready, and transition the shell from "booting" to "editing" (removing the prior unconditional sleep).

Changes

Cohort / File(s) Summary
PTY startup state
src/aish/terminal/pty/manager.py
Added startup_session_ready, startup_prompt_ready, startup_ready, and startup_cwd properties. Drain logic now decodes control events directly, accumulates protocol issues, updates continuation prompt and startup_cwd from session_ready, and captures observed readiness into startup flags.
Shell startup integration
src/aish/shell/runtime/app.py
_setup_pty now checks startup_ready/startup_cwd: when ready, it synchronizes backend working directory, marks backend session ready, and sets shell phase to "editing"; removed unconditional 0.2s sleep.
Tests / expectations
tests/shell/runtime/test_shell_pty_core.py, tests/terminal/pty/test_pty_control_protocol.py
Added/updated tests to assert PTYManager startup readiness indicators and startup_cwd are observed by the shell; extended fake PTY manager with startup_ready/startup_cwd; added immediate post-start assertions and protocol-issues checks.

Sequence Diagram

sequenceDiagram
    participant Shell as PTYAIShell
    participant Manager as PTYManager
    participant Backend as Backend/PTY

    rect rgba(100,150,255,0.5)
    note over Backend,Manager: PTY emits control events during boot
    Backend->>Manager: control events (session_ready, prompt_ready, ...)
    activate Manager
    Manager->>Manager: decode control events
    Manager->>Manager: record startup_cwd, continuation prompt
    Manager->>Manager: set startup_session_ready / startup_prompt_ready
    Manager->>Manager: set startup_ready
    deactivate Manager
    end

    rect rgba(100,200,100,0.5)
    note over Shell,Manager: Shell setup uses startup handshake
    Shell->>Manager: call _setup_pty()
    Shell->>Manager: check startup_ready, read startup_cwd
    activate Manager
    Manager-->>Shell: startup_ready=true, startup_cwd
    deactivate Manager
    Shell->>Backend: sync working directory to startup_cwd
    Shell->>Shell: mark backend session ready
    Shell->>Shell: set _backend_session_ready and _shell_phase="editing"
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I listened to bytes in the dim little shed,
A handshake arrived and the cwd was said.
Flags hopped to ready, the shell gave a grin,
Paths all aligned — now editing begins! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 45.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Reuse PTY startup handshake during shell startup' clearly and concisely describes the main change: reusing the PTY startup handshake to improve shell startup performance.
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

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: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/aish/terminal/pty/manager.py`:
- Around line 238-239: The startup handshake flags are left from previous runs;
before starting a new process in PTYManager (the method where saw_session_ready
= self._startup_session_ready and saw_startup_prompt_ready =
self._startup_prompt_ready are set) explicitly reset self._startup_session_ready
= False and self._startup_prompt_ready = False so each start begins with a fresh
handshake state, then read those flags into saw_session_ready and
saw_startup_prompt_ready; make the same change for the other occurrence around
lines 276-277 so both start paths clear the prior-state flags before use.

In `@tests/shell/runtime/test_shell_pty_core.py`:
- Around line 267-297: The test uses hardcoded "/tmp/..." paths which trip Ruff
S108; change the test to accept a tmp_path (or tmpdir) fixture and replace all
"/tmp/frontend" and "/tmp/backend" literals with str(tmp_path / "frontend") and
str(tmp_path / "backend") respectively (update the _StartedPTYManager.__init__
assertions, its startup_cwd value, the monkeypatched os.chdir lambda,
shell._current_cwd initial value, and the final asserts) so paths are generated
from the temporary fixture rather than hardcoded.
🪄 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: 08d27af6-763f-4113-96fb-0603163c2192

📥 Commits

Reviewing files that changed from the base of the PR and between f37dde0 and df1416c.

📒 Files selected for processing (4)
  • src/aish/shell/runtime/app.py
  • src/aish/terminal/pty/manager.py
  • tests/shell/runtime/test_shell_pty_core.py
  • tests/terminal/pty/test_pty_control_protocol.py

Comment thread src/aish/terminal/pty/manager.py
Comment thread tests/shell/runtime/test_shell_pty_core.py Outdated
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: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@tests/shell/runtime/test_shell_pty_core.py`:
- Around line 288-303: The test should ensure the patched time.sleep is not
invoked during PTYAIShell._setup_pty; replace the no-op patch with a spy or a
stub that records calls (or raises if called) and add an assertion after
PTYAIShell._setup_pty that verifies the spy was never called (i.e., startup
fallback wait was not used). Reference the patched symbol
"aish.shell.runtime.app.time.sleep" and the function under test
"PTYAIShell._setup_pty" so the check directly ties the sleep call absence to the
startup handshake path.
🪄 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: 16c88dff-4d42-4a11-b6a5-8a50962c543f

📥 Commits

Reviewing files that changed from the base of the PR and between df1416c and 26f45dc.

📒 Files selected for processing (2)
  • src/aish/terminal/pty/manager.py
  • tests/shell/runtime/test_shell_pty_core.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/aish/terminal/pty/manager.py

Comment thread tests/shell/runtime/test_shell_pty_core.py Outdated
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.

🧹 Nitpick comments (1)
tests/shell/runtime/test_shell_pty_core.py (1)

291-305: Consider asserting os.chdir is called to harden cwd-sync coverage.

Right now Line 291 patches os.chdir to a no-op lambda. Switching to a mock and asserting the call would better catch regressions where cwd assignment happens without full sync behavior.

Proposed test hardening
-    monkeypatch.setattr("aish.shell.runtime.app.os.chdir", lambda _cwd: None)
+    chdir_mock = Mock()
+    monkeypatch.setattr("aish.shell.runtime.app.os.chdir", chdir_mock)
@@
     assert shell._backend_session_ready is True
     assert shell._shell_phase == "editing"
     sleep_mock.assert_not_called()
+    chdir_mock.assert_called_once_with(backend_cwd)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/shell/runtime/test_shell_pty_core.py` around lines 291 - 305, Replace
the no-op patch of os.chdir with a mock so the test asserts the call: instead of
monkeypatch.setattr("aish.shell.runtime.app.os.chdir", lambda _cwd: None) use a
mock (e.g., MagicMock) and after calling PTYAIShell._setup_pty(shell) assert
that the mock was called with backend_cwd; keep existing assertions for
shell._current_cwd, current_env_info, _backend_session_ready and _shell_phase
and ensure sleep_mock.assert_not_called() remains. This targets
PTYAIShell._setup_pty and the shell._current_cwd synchronization behavior so
regressions where os.chdir is not invoked will be caught.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@tests/shell/runtime/test_shell_pty_core.py`:
- Around line 291-305: Replace the no-op patch of os.chdir with a mock so the
test asserts the call: instead of
monkeypatch.setattr("aish.shell.runtime.app.os.chdir", lambda _cwd: None) use a
mock (e.g., MagicMock) and after calling PTYAIShell._setup_pty(shell) assert
that the mock was called with backend_cwd; keep existing assertions for
shell._current_cwd, current_env_info, _backend_session_ready and _shell_phase
and ensure sleep_mock.assert_not_called() remains. This targets
PTYAIShell._setup_pty and the shell._current_cwd synchronization behavior so
regressions where os.chdir is not invoked will be caught.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 80ac08e4-328b-40a6-80dc-b23a5fb2e8d7

📥 Commits

Reviewing files that changed from the base of the PR and between 26f45dc and 7dcefa4.

📒 Files selected for processing (1)
  • tests/shell/runtime/test_shell_pty_core.py

@F16shen F16shen merged commit e53da97 into AI-Shell-Team:main Apr 23, 2026
11 checks passed
@F16shen F16shen deleted the fix/startup-handshake-reuse branch April 23, 2026 06:27
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