Skip to content

Engine(feat): Add raw-byte libtmux.engine seam and capabilities - #739

Open
tony wants to merge 22 commits into
masterfrom
engine-seam-minimal
Open

tony wants to merge 22 commits into
masterfrom
engine-seam-minimal

Conversation

@tony

@tony tony commented Aug 13, 2026 •

Copy link
Copy Markdown
Member

Note

Rebase alignment with v0.70.0 (0.74.0 milestone, #907): libtmux._internal.support.capabilities (#887, 0.65.0), Server(..., kill_on_exit=True) (#728, 0.69.0), structured logging and symmetric environment masking (#748, 0.70.0), exc.TmuxCommandTimeout with pipe-safe child reaping (#807, 0.70.0), and ty + Ruff ANN (#682, 0.70.0) are now on master. Rebase aligns _run_popen_request and ControlModeEngine timeout non-replay with #807 and unifies public capability reporting (#871, #925).

Summary

  • Route every tmux command in libtmux through a pluggable raw-byte libtmux.engine seam (TmuxEngine, AsyncTmuxEngine, TmuxRequest, TmuxResult, DaemonGuard, SubprocessEngine, ControlModeEngine, ExecEngine) while keeping Server.cmd() (tmux_cmd) and the Server → Session → Window → Pane hierarchy unchanged under the default transport.
  • Add ExecEngine.docker(), ExecEngine.ssh(), ExecEngine.kubectl(), and ExecEngine.sandbox() with shell=True remote shell quoting and cached remote tmux -V probing.
  • Add libtmux.capabilities (Capability, ServerCapabilities, Workaround) and Server.capabilities(), backed by the shared capability table in libtmux._internal.support.capabilities and published in capabilities.json (just build-capabilities).
  • Add FakeEngine and RecordingEngine in libtmux.test for offline and pass-through command verification without patching subprocess.

Closes #841.

Changes

Engine seam (libtmux.engine & libtmux._internal)

  • TmuxRequest carries native argv or structured command tuples, client flags, stdin, deadlines, and environment overrides. A subprocess result exposes separate exact byte streams. The classic stdout and stderr lists recognize CRLF and lone CR as line breaks.
  • Transports:
    • SubprocessEngine: Default binary-mode CLI transport with bounded timeouts and spawn_client() handles.
    • ExecEngine: Prepends wrapper prefixes (docker exec, ssh, kubectl exec, sandbox wrappers) with shell=True remote shell quoting on ssh, remote tmux -V probing (tmux_version()), and distinct endpoint identity reflected in Server.__eq__.
    • ControlModeEngine pipelines eligible commands on tmux 3.7 and newer. It can choose a subprocess before dispatch. An interruption after dispatch retires the client and propagates to the caller. A control frame has one payload and a success or error status. Use the subprocess engine for independent stdout and stderr.
  • Wire & lifecycle guards:
    • Check packed size and argument count before launch. Server.cmd() preserves native argv. Structured requests preserve literal data.
    • Check named socket limits using the request environment. The default new_session() starts its client with a cleaned environment. ControlModeEngine.for_server() binds a persistent client to an explicit endpoint and gives the caller its cleanup handle.

Capabilities (libtmux.capabilities & capabilities.json)

  • Unify version-gated flags (Server.run_shell, Server.list_keys, Pane.capture_pane, Pane.paste_buffer, Pane.new_pane, ControlModeEngine), retired tmux 3.9 popup window options (#878), and Pane.break_pane's 3.7 repair workaround in libtmux._internal.support.capabilities, matching #887's just build-capabilities manifest workflow.
  • Probe connected daemons in Server.capabilities() via -u -N run-shell -C so neither a stopped server is started nor any after-* hook fires.

Test plan

  • Real control client checked for replay and stale replies after an interruption. Pipe and PTY runs covered carriage returns, empty output, invalid UTF-8, and command failures.
  • ExecEngine shim tests cover docker exec, ssh (shell=True vs shell=False awkward quoting), kubectl exec, and sandbox wrappers, binary stdin transfers, and remote tmux -V probing.
  • Ruff format, Ruff lint, and ty (3.11 and 3.15)
  • Full pytest suite across supported tmux releases
  • Sphinx documentation build passes cleanly (just build-docs)

The subprocess result covers the raw output portion of #881.

@tony
tony force-pushed the engine-seam-minimal branch from ed7206c to 18e3d72 Compare August 15, 2026 10:36
@codecov

codecov Bot commented Aug 15, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 55.75648% with 734 lines in your changes missing coverage. Please review.
✅ Project coverage is 59.96%. Comparing base (db4e314) to head (0269c6c).

Files with missing lines Patch % Lines
src/libtmux/engine.py 58.14% 175 Missing and 33 partials ⚠️
src/libtmux/_internal/control_mode.py 45.18% 62 Missing and 12 partials ⚠️
src/libtmux/_internal/connection.py 58.59% 58 Missing and 7 partials ⚠️
src/libtmux/_internal/support/capabilities.py 51.28% 48 Missing and 9 partials ⚠️
src/libtmux/test/fake_engine.py 39.36% 50 Missing and 7 partials ⚠️
src/libtmux/_internal/protocols.py 30.37% 51 Missing and 4 partials ⚠️
src/libtmux/capabilities.py 15.62% 53 Missing and 1 partial ⚠️
src/libtmux/server.py 72.98% 35 Missing and 12 partials ⚠️
src/libtmux/_internal/invocation.py 64.22% 37 Missing and 7 partials ⚠️
src/libtmux/_internal/instrumentation.py 62.36% 32 Missing and 3 partials ⚠️
... and 5 more
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #739      +/-   ##
==========================================
- Coverage   61.99%   59.96%   -2.03%     
==========================================
  Files          29       37       +8     
  Lines        5091     6582    +1491     
  Branches     1082     1318     +236     
==========================================
+ Hits         3156     3947     +791     
- Misses       1595     2199     +604     
- Partials      340      436      +96     

☔ 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
tony force-pushed the engine-seam-minimal branch 2 times, most recently from b9deeb2 to 947eaa4 Compare August 15, 2026 12:32
@tony
tony force-pushed the engine-seam-minimal branch from 0bcf5b9 to 740526e Compare August 23, 2026 00:16
@tony
tony force-pushed the engine-seam-minimal branch from 3de1062 to 7cfa475 Compare November 7, 2026 02:17
@tony
tony force-pushed the engine-seam-minimal branch from 7cfa475 to cc024dd Compare November 20, 2026 23:10
@tony
tony force-pushed the engine-seam-minimal branch from cc024dd to 48ba47c Compare November 21, 2026 16:30
@tony tony changed the title Make tmux command execution pluggable, default path unchanged Engine(feat): Add raw-byte libtmux.engine seam and capabilities Nov 21, 2026
@tony
tony force-pushed the engine-seam-minimal branch from 48ba47c to 08fd87a Compare November 21, 2026 17:11
@tony tony mentioned this pull request Nov 21, 2026
44 of 77 tasks
@tony
tony force-pushed the engine-seam-minimal branch 4 times, most recently from 909b8de to 240da60 Compare November 22, 2026 20:12
@tony tony added the area: engines Engine layer, deadlines, async, control mode, transports label Nov 24, 2026
tony added 22 commits December 5, 2026 10:46
why: Raw-byte engines need shared imsg ceiling checks, trailing
semicolon escaping, generation fences, and control-mode guard parsing.

what:
- Add transport, timeout, command-length, restart, and mismatch errors
  to libtmux.exc
- Add invocation packing, trailing semicolon escaping, and command-chain
  splitting in libtmux._internal.invocation
- Add if-shell -F generation fences in libtmux._internal.daemon_guard
- Add ServerConnection, structural capability protocols, and flags-aware
  ControlModeParser
why: Exposing a minimal raw-byte TmuxEngine protocol allows swapping
transports, streaming binary stdin/stdout, and testing without tmux.

what:
- Add libtmux.engine with TmuxEngine, AsyncTmuxEngine, TmuxRequest,
  TmuxResult, DaemonGuard, SubprocessEngine, ControlModeEngine, and
  ExecEngine
- Add batch-delegating InstrumentedEngine and CountingSink in
  libtmux._internal.instrumentation
- Add FakeEngine and RecordingEngine in libtmux.test
why: Gated tmux features and connected daemon identity checks should
read one declarative table and publish capabilities.json.

what:
- Add libtmux._internal.support.capabilities with shared port capability
  and workaround entries, release ordering, and hook-free daemon probing
- Add public libtmux.capabilities (Capability, ServerCapabilities,
  Workaround)
- Generate capabilities.json via just build-capabilities
why: Classic Server, Session, Window, Pane, neo, and tmux_cmd callers
should execute over any TmuxEngine without losing raw bytes or UTF-8
format separators under C locales.

what:
- Route tmux_cmd through TmuxEngine, exposing raw_stdout and raw_stderr
  alongside decoded stdout and stderr lines
- Add Server(..., engine=...), Server.capabilities(), Server.kill(wait=)
  and endpoint-aware Server.__eq__
- Route version gates through capability_since(), drop sub-floor hook
  gates, strip $TMUX per invocation, and gate retired 3.9 popup options
why: Later transport changes need a baseline benchmark that separates
request count from inline tmux command count on an isolated server.

what:
- Add scripts/bench/primitives.py and scripts/bench/current_api.py over
  libtmux.engine and CountingSink
- Cover PEP 723 script source pins, scratch reaper safety, and benchmark
  accounting under tests/scripts/
why: Engine behavior and public examples need coverage through the same
entry points used by custom engines and classic Server callers.

what:
- Exercise engine dispatch, capability rules, and session environments.
- Document engine selection, daemon capabilities, and the public API.
why: Reconcile the engine seam with v0.70.0 timeout reaping, single-owner
command logging, and strict ty plus Ruff ANN static type checking.

what:
- Slice communicate waits and close pipes without draining on timeout or
  BaseException in SubprocessEngine and ClientProcess
- Propagate TmuxCommandTimeout from ControlModeEngine without fallback
  replay and preserve OS launch diagnostics in TmuxCommandNotFound
- Keep tmux_cmd as the sole command-log producer and avoid duplicating
  os.environ when probing named sockets
- Type ServerConnectionTarget, Sink[_StateT], InstrumentedEngine,
  RecordingEngine, guard_sync_call, and benchmark reports without Any or
  type-ignore comments
why: Moving command execution to a byte transport exposed carriage
returns in the classic stdout and stderr lists.

what:
- Normalize CRLF and lone CR in the decoded view of each stream.
- Keep the exact bytes available to callers that parse native replies.
- Exercise both command entry points and custom result objects.
why: A lost control reply leaves delivery uncertain. Retrying submitted
commands can apply a state change twice.

what:
- Keep subprocess fallback inside the connection setup phase.
- Propagate a transport failure while sending or collecting replies.
- Count real single and batched mutations after a simulated reply loss.
why: Session creation removes TMUX from the child environment. Applying
that complete snapshot as an overlay reintroduced the parent value.

what:
- Pass the cleaned environment as the entire subprocess environment.
- Verify the new daemon retains unrelated variables and excludes TMUX.
why: A classic command may use native tmux syntax. Repacking its
arguments as structured values changed what tmux received.

what:
- Keep native argument vectors alongside structured command inspection.
- Use the same command rendering and size checks for CLI transports.
- Route unsupported control-mode requests before dispatch.
why: An interrupted reply can stay unread on a persistent client.
Reusing it can return the previous command's output to the next caller.

what:
- Detach the client under the dispatch lock on an interrupted exchange.
- Reap the abandoned process and propagate the original exception.
- Check distinct replies after single-command and batch interruptions.
why: A named socket resolves under the client environment. Checking it
under the parent environment could reject a valid requested address.

what:
- Resolve socket limits with the same environment supplied to tmux.
- Keep connection construction separate from per-call validation.
- Check both directions of named-socket environment replacement.
why: A structured request supplies data separately from command
boundaries. A quoting character in a data value must reach tmux.

what:
- Encode each structured argument once at the invocation boundary.
- Keep native argument vectors and format markers intact.
- Document which output the tmux control protocol provides.
why: Cloning a persistent transport during server configuration left its
control client attached after the caller closed the original engine.

what:
- Require callers to bind a persistent connection before injecting it.
- Preserve that lifetime rule when a recording engine wraps the client.
- Compare effective injected socket selectors when comparing servers.
why: A fixture may select its isolated daemon by socket path or label. Native comparisons must query the same daemon as the public session.

what:
- Forward the fixture connection's client flags and executable to tmux_cmd.
why: A request can override an engine's socket or the process environment. Checking the server defaults before rendering can reject a reachable daemon or let an oversized address through.

what:
- Resolve native client selectors with the same environment and working directory used to launch tmux.
- Validate classic calls at their local transport boundary and retain native status for low-level requests.
- Apply the same address rules when opening a control client and exercise overridden selectors with a private daemon.
why: An injected subprocess engine can own the only socket selector. Building a persistent client from the server's constructor flags then addresses the ambient daemon.

what:
- Preserve the selected local engine connection in the control client factory.
- Exercise the native socket, attached control client count, and cleanup through public entry points.
why: Deadlines and interrupts must reap the actual tmux client and close
its pipes. A test double that copies subprocess options rejects valid
launches when the runner supplies its socket environment.

what:
- Observe real processes and preserve their launch environment in the
  readiness handshake.
- Use real server and session objects to exercise log escaping.
- Retain the PID, signal, closed pipe and surviving server assertions.
why: Version detection and the standalone control client have their own
launch paths. Callers choosing a test engine need to know which
operations it can intercept.

what:
- Describe engine dispatch at Server.cmd and its object-method callers.
…elpers

why: Callers running tmux inside containers, pods, remote SSH hosts, or
sandboxes need ready-made transport prefixes, remote shell quoting for
space-joining transports like ssh, and remote tmux -V probing (#841).

what:
- Add ExecEngine.docker(), ExecEngine.ssh(shell=True),
  ExecEngine.kubectl(), ExecEngine.sandbox(), shell= shlex.join quoting,
  and cached tmux_version() probing
- Exercise docker, ssh, kubectl, and sandbox shims with awkward quoting
  and binary stdin payloads
why: Callers selecting a command transport need its byte, process,
delivery, and remote wrapper contracts recorded in the changelog.

what:
- Describe decoded lines, native bytes, binary subprocess pipes, and
  ExecEngine transport wrappers
- Document connection fallback and uncertain completion after dispatch
@tony
tony force-pushed the engine-seam-minimal branch from ebde4a6 to 0269c6c Compare December 5, 2026 16:52

This branch has not been deployed

No deployments
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

Status: In Progress

Development

Successfully merging this pull request may close these issues.

Run tmux commands through a caller-supplied transport (docker exec, ssh, sandbox exec)

1 participant