Skip to content

Experiment: Control mode - #605

Closed
tony wants to merge 84 commits into
masterfrom
control-mode
Closed

tony wants to merge 84 commits into
masterfrom
control-mode

Conversation

@tony

@tony tony commented Nov 22, 2025 •

Copy link
Copy Markdown
Member

Summary

  • Introduce a control-mode–first engine stack (protocol FSM, ControlModeEngine, subprocess shim) while keeping public cmd APIs compatible via CommandResult -> tmux_cmd bridging.
  • Strengthen control-mode correctness: notification queueing, pending-command tracking, capture-pane normalization, control-client filtering, and robust timeout/connection error types.
  • Improve environment propagation and capture stability with control-aware waits, version guards for tmux <3.2, and expanded regression coverage across new/split windows.
  • Document the new engine architecture and pytest plugin usage; add helpers (wait_for_line, control sandbox) plus extensive control-mode regression suites.

Highlights

  • Protocol layer: New ControlProtocol parses %begin/%end/%error, maintains pending contexts, bounded notification queue, and exposes timing/flags metadata for diagnostics.
  • Engines: ControlModeEngine manages bootstrap sessions, retries on broken pipes, surfaces notifications; SubprocessEngine now emits CommandResult internally but keeps existing tmux_cmd surface.
  • Behavioral fixes: Hide internal control clients from session listings, trim capture-pane output to match subprocess semantics, and add targeted waits so env/prompt output is captured before assertions.
  • Tooling & docs: Added control-mode doc page, quickstart/pytest-plugin notes, and control sandbox tests to exercise real tmux control streams.

Testing

  • uv run ruff check . --fix --show-fixes
  • uv run ruff format .
  • uv run mypy
  • uv run py.test
  • uv run py.test --engine control --reruns 0 -vv

@codecov

codecov Bot commented Nov 22, 2025 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 78.34101% with 188 lines in your changes missing coverage. Please review.
✅ Project coverage is 56.58%. Comparing base (d8b7127) to head (32cc6cc).

Files with missing lines Patch % Lines
src/libtmux/_internal/engines/control_mode.py 74.70% 39 Missing and 25 partials ⚠️
src/libtmux/_internal/engines/control_protocol.py 81.73% 26 Missing and 16 partials ⚠️
src/libtmux/server.py 71.76% 19 Missing and 5 partials ⚠️
src/libtmux/pytest_plugin.py 77.45% 20 Missing and 3 partials ⚠️
src/libtmux/pane.py 47.61% 9 Missing and 2 partials ⚠️
src/libtmux/_internal/engines/subprocess_engine.py 71.42% 9 Missing and 1 partial ⚠️
src/libtmux/exc.py 0.00% 4 Missing ⚠️
src/libtmux/session.py 62.50% 2 Missing and 1 partial ⚠️
tests/helpers.py 70.00% 1 Missing and 2 partials ⚠️
src/libtmux/_internal/engines/base.py 97.95% 1 Missing and 1 partial ⚠️
... and 2 more
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #605      +/-   ##
==========================================
+ Coverage   52.44%   56.58%   +4.14%     
==========================================
  Files          26       31       +5     
  Lines        3726     4533     +807     
  Branches      747      876     +129     
==========================================
+ Hits         1954     2565     +611     
- Misses       1468     1605     +137     
- Partials      304      363      +59     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

tony added a commit that referenced this pull request Nov 22, 2025
@tony
tony force-pushed the control-mode branch 2 times, most recently from 5b241d7 to c046d1b Compare November 22, 2025 20:17
tony added a commit that referenced this pull request Nov 23, 2025
Phase 1: Automatic Internal Session Filtering
- Filter control mode's internal session from Server.sessions property
- Update has_session() to exclude internal sessions
- Add Server._sessions_all() for advanced debugging
- Add Server._get_internal_session_names() to query engine for internal sessions

Phase 2: Engine Configurability
- Add session_name parameter to ControlModeEngine for custom internal session names
- Add attach_to parameter to attach to existing sessions (advanced opt-in)
- Update _start_process() to handle both new-session and attach-session modes
- Dynamic filtering based on engine configuration

Tests:
- test_sessions_excludes_internal_control_mode: verify filtering works
- test_has_session_excludes_control_mode: verify has_session consistency
- test_session_count_engine_agnostic: verify engine transparency
- test_control_mode_custom_session_name: verify custom naming
- test_control_mode_attach_to_existing: verify attach mode

Documentation:
- Update control_mode.md with filtering behavior and advanced options
- Add warnings about attach_to notification spam
- Update CHANGES with features and compatibility notes

This makes control mode engine truly transparent - users see the same
session behavior regardless of which engine they choose. Internal sessions
are used for connection management but hidden from user-facing APIs.

Related: #605
tony added a commit that referenced this pull request Nov 23, 2025
Problem:
- Control mode created internal "libtmux_control_mode" session
- This affected tmux's session numbering (unnamed sessions got incremented IDs)
- Doctests expected specific session numbers (e.g., "2") but got "3"
- Led to 100s of doctest failures with control mode

Solution - Bootstrap Approach:
- Server fixture creates "tmuxp" session BEFORE starting control mode
- Control mode attaches to existing "tmuxp" instead of creating internal session
- Session numbering now consistent between engines:
  - subprocess: $1=tmuxp, $2=test_session
  - control: $1=tmuxp, $2=test_session (same!)

Changes:
- pytest_plugin.py: Bootstrap "tmuxp" session for control mode in server fixture
- pytest_plugin.py: _build_engine() accepts attach_to parameter
- tests/test_server.py: Update control mode tests for new behavior
- common.py: Make session number doctest engine-agnostic
- pane.py: Convert some interactive doctests to code blocks
- server.py: Add ellipsis to session ID doctests

Benefits:
- ✅ Engine-transparent session numbering
- ✅ All server tests pass with both engines (36/36)
- ✅ Control mode engine tests pass (4/4)
- ✅ Major doctests now pass with control mode

Known Issues:
- Some pane.split() doctests fail with control mode (protocol issue)
- Needs investigation into control mode split-window behavior

Related: #605
tony added a commit that referenced this pull request Nov 23, 2025
Root Cause:
- tmux pane IDs use format %N (like %0, %1, %2, %3)
- When split-window -P -F#{pane_id} outputs "%3", it's sent INSIDE
  the %begin/%end command block
- But because it starts with %, the protocol parser treated it as
  a control message/notification, NOT as stdout content
- Result: pane_cmd.stdout was empty, causing IndexError

The Fix:
- Modified _handle_percent_line() to check parser state
- When IN_COMMAND state, lines starting with % that aren't known
  control messages (%begin, %end, %error) are now treated as stdout
- This correctly captures pane/window/session IDs from -P flag

Impact:
- Fixed 62 of 82 test failures (76% reduction)
- Before: 82 failed, 512 passed
- After: 20 failed, 574 passed
- All split/resize/pane operations now work correctly

Remaining Issues:
- capture-pane -p still has issues (different root cause)
- Environment variable passing needs investigation
- Session name validation edge cases
- Some doctests need updates

Verification:
Confirmed with debug logging that %3␞ was being sent inside command
block but incorrectly routed to notification handler instead of stdout.

Related: #605
@tony
tony force-pushed the control-mode branch 2 times, most recently from e9fbbb7 to 8b851d2 Compare November 22, 2026 03:57
tony added 26 commits November 22, 2026 14:03
why: ensure control-mode helpers behave against real tmux clients.
what:
- add live control-mode tests for set_client_flags, set_pane_flow, and subscribe
- run control engine inside sandbox sessions to verify client flags and pane flow usability
- drop redundant stub-based cases from unit suite
why: Control-mode capture-pane can return only the echoed command before output
lands, causing flaky confirmation of capture output.
what:
- detect prompt+command-only captures for control mode
- retry briefly while preserving prompt-only captures as valid
why: Ruff flags redundant branching in the control-mode capture retry logic.
what:
- return the retry condition directly from _needs_retry
why: Non-daemon control-mode threads can hang pytest shutdown when the engine
process isn't closed.
what:
- close the engine in Server.kill cleanup
- ensure pytest fixtures close engines on teardown
- update control-mode engine tests to assert process termination
…miter

why: Session names may include spaces, and split() truncates them.

what:

- use tab-delimited list-clients format and parsing

- add coverage for session names containing spaces
why: connect() cleared TMUX but only restored it on success.

what:

- restore TMUX in a finally block

- add test covering failure path
why: control_client_logs created a stdout log but never wrote to it.

what:

- redirect control client stdout to the log file

- read stdout from the log in tests
why: connect() calls has_session, which inspects cmd.returncode.

what:

- set returncode on dummy cmd to keep the test isolated
why: wall-clock jumps and dummy process cleanup caused flaky failures/warnings.
what:
- switch retry timing assertions to monotonic()
- add stub terminate/kill/wait for dummy control process
- annotate dummy cmd instance attributes for typing
why: Prevent hanging pytest shutdown and unraisable BrokenPipe errors when control-mode pipes stay open.
what:
- Close stdin/stdout/stderr after terminating the control-mode subprocess
- Close tmux -C fixture stdin during teardown
- Add dummy process stream attrs for close compatibility
why: Prevent false 'no current client' errors when non-control clients report empty flags.
what:
- Parse list-clients output with a tab delimiter to preserve empty flags
- Add a unit test for empty client_flags handling
why: Avoid hangs when control-mode subprocesses or fixtures refuse to exit.
what:
- Add a configurable shutdown timeout and warnings in ControlModeEngine.close
- Handle TimeoutExpired when waiting on tmux -C test clients
- Cover timeout shutdown behavior in tests
why: Align control-mode docs with the UUID-based internal session name and runnable examples.
what:
- Update CHANGES and control-mode docs to use libtmux_ctrl_XXXXXXXX naming
- Fix the attach-session example to define a bootstrap Server
why: Ensure downstream users can select tmux engines and markers without relying on repo-only conftest hooks.
what:
- Move engine CLI option, marker registration, and parametrization into libtmux.pytest_plugin
- Leave doctest filtering in repo conftest and harden tmux -C teardown
why: Ensure doctest filtering works for downstream users via the pytest plugin entry point.
what:
- Move control-engine doctest filtering hook into libtmux.pytest_plugin
- Add pytester coverage that doctests are filtered under --engine=control
- Drop redundant hook from repo conftest
why: Avoid ValueError if --engine is not registered in dynamic plugin scenarios.
what:
- Fall back to subprocess when pytest option lookup fails
why: Make doctest filtering visible and avoid silent collection surprises.
what:
- Call pytest_deselected when dropping doctest items under control engine
why: Ensure doctest filtering is visible and validated under --engine=control.
what:
- Require deselection output in pytester control-engine doctest test
why: satisfy ruff SIM103 without changing behavior.
what:
- inline capture_pane retry condition for ControlModeEngine
why: allow switch_client to see real clients before control mode starts.
what:
- ensure control process starts before list-clients in can_switch_client
why: keep raise_if_dead raising TmuxCommandNotFound when tmux is absent.
what:
- return None when tmux is missing so Server handles the error path
why: prevent control-mode threads from blocking interpreter exit if cleanup stalls.
what:
- Close control pipes before joining reader/stderr threads
- Run IO threads as daemon and update shutdown comment
why: keep control-mode test helpers available when libtmux is used as a plugin dependency.
what:
- Relocate control_sandbox/control_client_logs fixtures into pytest_plugin
- Drop duplicate fixtures from top-level conftest
why: The rebase onto current master left an orphaned pre-engine code
block and stale variable names in Server.raise_if_dead, plus an unused
formats import.

what:
- Use the resolved tmux binary in the CalledProcessError command
- Drop the unreachable subprocess.check_call block orphaned inside
  _build_server_args
- Remove the unused libtmux.formats import
why: Trunk's Ruff configuration checks rules this branch predates.

what:
- Catch ImportError, not Exception, around the doctest item import
- Pass check=False to the has-session probe, which reads returncode
- Drop explicit return None where it is the only return value
- Apply ruff format
why: Trunk now builds every -S/-L flag through Server._socket_args(),
which raises SocketPathTooLong for a socket tmux could not bind. The
engine's ServerContext rendered those flags itself, so its spawns
skipped the check. A socket_name is measured when the flags are
rendered, since tmux reads $TMUX_TMPDIR when it runs, so the server is
still built without side effects.

what:
- Give ServerContext an optional socket_args callable, used by
  to_args() in place of its own -L/-S rendering
- Pass Server._socket_args when binding the engine
- Test that a context bound to a server with an unbindable socket
  raises SocketPathTooLong from to_args()
@tony tony added the area: engines Engine layer, deadlines, async, control mode, transports label Nov 24, 2026
@tony

tony commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

Superseded by the ControlClient design and version gate in #884 and the engine seam in #739. Closing this early control-mode spike; branch control-mode (93c697b53) stays on origin.

@tony tony closed this Nov 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: engines Engine layer, deadlines, async, control mode, transports

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant