From 90a0dcf988cf4c3c7a368247084727f42148eddb Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 5 Dec 2026 04:45:26 -0600 Subject: [PATCH 1/2] Program(feat): Own terminal programs why: Callers need one owner for application completion, terminal output, input, and cleanup. what: Share the supervised program owner across Core and Async. Document the bound daemon capability and verify terminal use. Share daemon-loss classification with pane text waits. Pass the sample migration diagnostic as literal data. --- README.md | 7 + capabilities.json | 16 + docs/reference/api.md | 124 ++- docs/reference/behavior.md | 137 ++++ docs/reference/contracts.json | 28 + examples/api/owned_program.rb | 25 + examples/api/owned_program_input.rb | 23 + examples/manifest.json | 34 + gems/libtmux-async/lib/libtmux/async.rb | 10 + .../lib/libtmux/async/process.rb | 20 +- gems/libtmux-async/lib/libtmux/async/scope.rb | 4 +- .../libtmux-async/lib/libtmux/async/server.rb | 5 +- gems/libtmux-async/sig/libtmux-async.rbs | 4 + gems/libtmux/lib/libtmux.rb | 1 + gems/libtmux/lib/libtmux/capabilities.rb | 5 + gems/libtmux/lib/libtmux/owned.rb | 11 + gems/libtmux/lib/libtmux/process.rb | 51 +- gems/libtmux/lib/libtmux/program.rb | 478 ++++++++++++ gems/libtmux/lib/libtmux/server.rb | 27 +- gems/libtmux/lib/libtmux/text_wait.rb | 2 +- gems/libtmux/lib/libtmux/tmux_version.rb | 12 +- gems/libtmux/libexec/program_child.rb | 60 ++ gems/libtmux/libtmux.gemspec | 3 + gems/libtmux/sig/program.rbs | 47 ++ scripts/types | 2 +- test/integration/program_test.rb | 722 ++++++++++++++++++ test/types/consumer.rb | 23 + test/unit/tmux_version_test.rb | 12 +- 28 files changed, 1824 insertions(+), 69 deletions(-) create mode 100644 examples/api/owned_program.rb create mode 100644 examples/api/owned_program_input.rb create mode 100644 gems/libtmux/lib/libtmux/program.rb create mode 100644 gems/libtmux/libexec/program_child.rb create mode 100644 gems/libtmux/sig/program.rbs create mode 100644 test/integration/program_test.rb diff --git a/README.md b/README.md index ba039511..aaec5a72 100644 --- a/README.md +++ b/README.md @@ -458,6 +458,12 @@ sessions after client close: 1 More: [ownership and errors][doc-ownership]. +## Run a program and read its exit status + +On tmux 3.7 or newer, core and Async can run a program on a new or existing +server and return its exit status and bounded final screen. See how +to [report a failed terminal command][owned-terminal-programs]. + ## Packages Start with `libtmux`. Add the companion for your caller: @@ -687,6 +693,7 @@ Part of the [libtmux.org](https://libtmux.org/) family alongside Python [mcp-application]: https://libtmux.org/en/ruby/latest/mcp/reference/libtmux-mcp-application/ [multiplematcheserror]: https://libtmux.org/en/ruby/latest/reference/libtmux-multiplematcheserror/ [nomatcherror]: https://libtmux.org/en/ruby/latest/reference/libtmux-nomatcherror/ +[owned-terminal-programs]: docs/reference/behavior.md#owned-terminal-programs [pane]: https://libtmux.org/en/ruby/latest/reference/libtmux-pane-14z6/ [pane-capture]: https://libtmux.org/en/ruby/latest/reference/libtmux-pane-capture/ [pane-resize]: https://libtmux.org/en/ruby/latest/reference/libtmux-pane-resize/ diff --git a/capabilities.json b/capabilities.json index ee7bf5f1..83c8a4bc 100644 --- a/capabilities.json +++ b/capabilities.json @@ -5,6 +5,22 @@ "minimum": "3.3a" }, "capabilities": [ + { + "id": "owned-terminal-program", + "name": "Owned terminal program", + "summary": "Run literal argv in an owned terminal and retain its final screen on the bound daemon.", + "since": "3.7", + "handling": "refuse", + "error": "LibTmux::UnsupportedFeatureError", + "apis": [ + "LibTmux.start_program", + "LibTmux.run_program", + "LibTmux::Server#start_program", + "LibTmux::Async.start_program", + "LibTmux::Async.run_program" + ], + "commands": [] + }, { "id": "control-mode", "name": "Control mode", diff --git a/docs/reference/api.md b/docs/reference/api.md index 1107f918..9557a663 100644 --- a/docs/reference/api.md +++ b/docs/reference/api.md @@ -16,11 +16,20 @@ This inventory checks declaration presence and visibility. The installed signature consumers check exercised calls; neither is whole-program static type checking. See [signature proof](behavior.md#signature-proof). +## LibTmux + +| Method | Declared return | Contract | +| --- | --- | --- | +| [.run_program](../../gems/libtmux/lib/libtmux/program.rb#L16) | `::LibTmux::Program::Result` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [.start_program](../../gems/libtmux/lib/libtmux/program.rb#L11) | `::LibTmux::Program` / `T` | [Owned terminal programs](behavior.md#owned-terminal-programs) | + ## LibTmux::Async | Method | Declared return | Contract | | --- | --- | --- | -| [.open](../../gems/libtmux-async/lib/libtmux/async.rb#L31) | `T` | [Async scope](behavior.md#async-scope) | +| [.open](../../gems/libtmux-async/lib/libtmux/async.rb#L41) | `T` | [Async scope](behavior.md#async-scope) | +| [.run_program](../../gems/libtmux-async/lib/libtmux/async.rb#L37) | `::LibTmux::Program::Result` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [.start_program](../../gems/libtmux-async/lib/libtmux/async.rb#L32) | `::LibTmux::Program` / `T` | [Owned terminal programs](behavior.md#owned-terminal-programs) | ## LibTmux::Async::ControlConnection @@ -68,41 +77,43 @@ type checking. See [signature proof](behavior.md#signature-proof). | Method | Declared return | Contract | | --- | --- | --- | | [#attach](../../gems/libtmux-async/lib/libtmux/async/server.rb#L53) | `bot` | [Async unsupported operations](behavior.md#async-unsupported-operations) | -| [#capabilities](../../gems/libtmux/lib/libtmux/server.rb#L240) | `::LibTmux::Capabilities` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#capabilities](../../gems/libtmux/lib/libtmux/server.rb#L242) | `::LibTmux::Capabilities` | [Daemon capabilities](behavior.md#daemon-capabilities) | | [#close](../../gems/libtmux-async/lib/libtmux/async/server.rb#L19) | `nil` | [Async scope](behavior.md#async-scope) | | [#delete_buffer](../../gems/libtmux/lib/libtmux/operations.rb#L69) | `::LibTmux::CommandResult` | [Buffers](behavior.md#buffers) | | [#diagnostics](../../gems/libtmux-async/lib/libtmux/async/server.rb#L24) | `::LibTmux::Async::scope_diagnostics` | [Diagnostics](behavior.md#diagnostics) | | [#display](../../gems/libtmux/lib/libtmux/operations.rb#L18) | `::LibTmux::CommandResult` | [Formats](behavior.md#formats) | | [#endpoint](../../gems/libtmux/lib/libtmux/server.rb#L149) | `::LibTmux::Endpoint` | [Borrowed bindings](behavior.md#borrowed-bindings) | | [#environment](../../gems/libtmux/lib/libtmux/operations.rb#L92) | `::String?` | [Environment](behavior.md#environment) | -| [#explain_panes](../../gems/libtmux/lib/libtmux/server.rb#L407) | `::Hash[::Symbol, untyped]` | [Source query plans](behavior.md#source-query-plans) | +| [#explain_panes](../../gems/libtmux/lib/libtmux/server.rb#L409) | `::Hash[::Symbol, untyped]` | [Source query plans](behavior.md#source-query-plans) | | [#hooks](../../gems/libtmux/lib/libtmux/operations.rb#L11) | `::LibTmux::Hooks` | [Options and hooks](behavior.md#options-and-hooks) | -| [#kill](../../gems/libtmux/lib/libtmux/server.rb#L300) | `::LibTmux::CommandResult` | [Killing daemons](behavior.md#killing-daemons) | +| [#kill](../../gems/libtmux/lib/libtmux/server.rb#L302) | `::LibTmux::CommandResult` | [Killing daemons](behavior.md#killing-daemons) | | [#list_buffers](../../gems/libtmux/lib/libtmux/operations.rb#L73) | `::Array[{ name: ::String, size: ::Integer }]` | [Buffers](behavior.md#buffers) | | [#list_clients](../../gems/libtmux/lib/libtmux/operations.rb#L100) | `::Array[{ name: ::String, pid: ::Integer, created: ::Integer, tty: ::String?, session_id: ::String?, control: bool }]` | [Live acquisition](behavior.md#live-acquisition) | -| [#list_panes](../../gems/libtmux/lib/libtmux/server.rb#L334) | `::Array[::LibTmux::Pane]` | [Live acquisition](behavior.md#live-acquisition) | -| [#list_sessions](../../gems/libtmux/lib/libtmux/server.rb#L326) | `::Array[::LibTmux::Session]` | [Live acquisition](behavior.md#live-acquisition) | +| [#list_panes](../../gems/libtmux/lib/libtmux/server.rb#L336) | `::Array[::LibTmux::Pane]` | [Live acquisition](behavior.md#live-acquisition) | +| [#list_sessions](../../gems/libtmux/lib/libtmux/server.rb#L328) | `::Array[::LibTmux::Session]` | [Live acquisition](behavior.md#live-acquisition) | | [#list_window_links](../../gems/libtmux/lib/libtmux/operations.rb#L80) | `::Array[::LibTmux::WindowLink]` | [Live acquisition](behavior.md#live-acquisition) | -| [#list_windows](../../gems/libtmux/lib/libtmux/server.rb#L330) | `::Array[::LibTmux::Window]` | [Live acquisition](behavior.md#live-acquisition) | -| [#new_session](../../gems/libtmux/lib/libtmux/server.rb#L311) | `::LibTmux::CreationReceipt` / `::LibTmux::Session` | [Creation](behavior.md#creation) | +| [#list_windows](../../gems/libtmux/lib/libtmux/server.rb#L332) | `::Array[::LibTmux::Window]` | [Live acquisition](behavior.md#live-acquisition) | +| [#new_session](../../gems/libtmux/lib/libtmux/server.rb#L313) | `::LibTmux::CreationReceipt` / `::LibTmux::Session` | [Creation](behavior.md#creation) | | [#open_control](../../gems/libtmux-async/lib/libtmux/async/server.rb#L28) | `T` / `::LibTmux::Async::ControlConnection` | [Control connections](behavior.md#control-connections) | | [#options](../../gems/libtmux/lib/libtmux/operations.rb#L7) | `::LibTmux::Options` | [Options and hooks](behavior.md#options-and-hooks) | | [#owned?](../../gems/libtmux/lib/libtmux/owned.rb#L16) | `bool` | [Borrowed bindings](behavior.md#borrowed-bindings) | -| [#pane](../../gems/libtmux/lib/libtmux/server.rb#L346) | `::LibTmux::Pane` | [Live handles](behavior.md#live-handles) | +| [#pane](../../gems/libtmux/lib/libtmux/server.rb#L348) | `::LibTmux::Pane` | [Live handles](behavior.md#live-handles) | +| [#program_support](../../gems/libtmux/lib/libtmux/program.rb#L458) | `{ binding_key: ::String, pid: ::Integer, start_time: ::Integer, version: ::String, since: ::String, supported: bool }` | [Owned terminal programs](behavior.md#owned-terminal-programs) | | [#read_buffer](../../gems/libtmux/lib/libtmux/operations.rb#L65) | `::LibTmux::CommandResult` | [Buffers](behavior.md#buffers) | | [#run](../../gems/libtmux-async/lib/libtmux/async/server.rb#L15) | `::LibTmux::CommandResult` | [Raw commands](behavior.md#raw-commands) | | [#run_group](../../gems/libtmux/lib/libtmux/group.rb#L32) | `::LibTmux::GroupResult` | [Command groups](behavior.md#command-groups) | -| [#search_panes](../../gems/libtmux/lib/libtmux/server.rb#L403) | `::LibTmux::Selection[::LibTmux::PaneSnapshot]` | [Source query execution](behavior.md#source-query-execution) | -| [#session](../../gems/libtmux/lib/libtmux/server.rb#L338) | `::LibTmux::Session` | [Live handles](behavior.md#live-handles) | +| [#search_panes](../../gems/libtmux/lib/libtmux/server.rb#L405) | `::LibTmux::Selection[::LibTmux::PaneSnapshot]` | [Source query execution](behavior.md#source-query-execution) | +| [#session](../../gems/libtmux/lib/libtmux/server.rb#L340) | `::LibTmux::Session` | [Live handles](behavior.md#live-handles) | | [#set_environment](../../gems/libtmux/lib/libtmux/operations.rb#L88) | `::LibTmux::CommandResult` | [Environment](behavior.md#environment) | -| [#snapshot](../../gems/libtmux/lib/libtmux/server.rb#L397) | `::LibTmux::Snapshot` | [Snapshot acquisition](behavior.md#snapshot-acquisition) | +| [#snapshot](../../gems/libtmux/lib/libtmux/server.rb#L399) | `::LibTmux::Snapshot` | [Snapshot acquisition](behavior.md#snapshot-acquisition) | | [#source_file](../../gems/libtmux/lib/libtmux/operations.rb#L42) | `::LibTmux::CommandResult` | [Source files](behavior.md#source-files) | -| [#supports_control?](../../gems/libtmux/lib/libtmux/server.rb#L232) | `bool` | [Borrowed bindings](behavior.md#borrowed-bindings) | +| [#start_program](../../gems/libtmux/lib/libtmux/program.rb#L464) | `::LibTmux::Program` / `T` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#supports_control?](../../gems/libtmux/lib/libtmux/server.rb#L234) | `bool` | [Borrowed bindings](behavior.md#borrowed-bindings) | | [#switch_client](../../gems/libtmux/lib/libtmux/terminal.rb#L39) | `::LibTmux::CommandResult` | [Client switching](behavior.md#client-switching) | -| [#tmux_version](../../gems/libtmux/lib/libtmux/server.rb#L227) | `::String` | [Borrowed bindings](behavior.md#borrowed-bindings) | +| [#tmux_version](../../gems/libtmux/lib/libtmux/server.rb#L229) | `::String` | [Borrowed bindings](behavior.md#borrowed-bindings) | | [#unset_environment](../../gems/libtmux/lib/libtmux/operations.rb#L96) | `::LibTmux::CommandResult` | [Environment](behavior.md#environment) | | [#wait_for](../../gems/libtmux/lib/libtmux/operations.rb#L47) | `::LibTmux::CommandResult` | [Wait channels](behavior.md#wait-channels) | -| [#window](../../gems/libtmux/lib/libtmux/server.rb#L342) | `::LibTmux::Window` | [Live handles](behavior.md#live-handles) | +| [#window](../../gems/libtmux/lib/libtmux/server.rb#L344) | `::LibTmux::Window` | [Live handles](behavior.md#live-handles) | | [#window_link](../../gems/libtmux/lib/libtmux/operations.rb#L84) | `::LibTmux::WindowLink` | [Live handles](behavior.md#live-handles) | | [#write_buffer](../../gems/libtmux/lib/libtmux/operations.rb#L57) | `::LibTmux::CommandResult` | [Buffers](behavior.md#buffers) | | [.open](../../gems/libtmux-async/lib/libtmux/async/server.rb#L61) | `bot` | [Async unsupported operations](behavior.md#async-unsupported-operations) | @@ -722,6 +733,51 @@ type checking. See [signature proof](behavior.md#signature-proof). | --- | --- | --- | | [.build](../../gems/libtmux/lib/libtmux/criteria.rb#L405) | `::LibTmux::FilterExpr` | [Criteria](behavior.md#criteria) | +## LibTmux::Program + +| Method | Declared return | Contract | +| --- | --- | --- | +| [#capture_screen](../../gems/libtmux/lib/libtmux/program.rb#L188) | `::LibTmux::Program::Screen` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#close](../../gems/libtmux/lib/libtmux/program.rb#L215) | `nil` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#inspect](../../gems/libtmux/lib/libtmux/program.rb#L243) | `::String` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#resize](../../gems/libtmux/lib/libtmux/program.rb#L208) | `::LibTmux::CommandResult` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#screen](../../gems/libtmux/lib/libtmux/program.rb#L183) | `::String` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#send_keys](../../gems/libtmux/lib/libtmux/program.rb#L202) | `::LibTmux::CommandResult` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#send_text](../../gems/libtmux/lib/libtmux/program.rb#L196) | `::LibTmux::CommandResult` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#wait](../../gems/libtmux/lib/libtmux/program.rb#L159) | `::LibTmux::Program::Result` | [Owned terminal programs](behavior.md#owned-terminal-programs) | + +## LibTmux::Program::Result + +| Method | Declared return | Contract | +| --- | --- | --- | +| [#exit_status](../../gems/libtmux/lib/libtmux/program.rb#L47) | `::Integer?` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#inspect](../../gems/libtmux/lib/libtmux/program.rb#L60) | `::String` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#screen](../../gems/libtmux/lib/libtmux/program.rb#L47) | `::String` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#screen_truncated?](../../gems/libtmux/lib/libtmux/program.rb#L56) | `bool` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#signal](../../gems/libtmux/lib/libtmux/program.rb#L47) | `::Integer?` | [Owned terminal programs](behavior.md#owned-terminal-programs) | + +## LibTmux::Program::Screen + +| Method | Declared return | Contract | +| --- | --- | --- | +| [#inspect](../../gems/libtmux/lib/libtmux/program.rb#L40) | `::String` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#text](../../gems/libtmux/lib/libtmux/program.rb#L28) | `::String` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#truncated?](../../gems/libtmux/lib/libtmux/program.rb#L36) | `bool` | [Owned terminal programs](behavior.md#owned-terminal-programs) | + +## LibTmux::Program::ScreenGeometryError + +| Method | Declared return | Contract | +| --- | --- | --- | +| [#cleanup_errors](../../gems/libtmux/lib/libtmux/errors.rb#L5) | `::Array[::String]` | [Errors](behavior.md#errors) | +| [#delivery](../../gems/libtmux/lib/libtmux/errors.rb#L5) | `::Symbol` | [Errors](behavior.md#errors) | +| [#entity](../../gems/libtmux/lib/libtmux/errors.rb#L5) | `::Symbol?` | [Errors](behavior.md#errors) | +| [#expected](../../gems/libtmux/lib/libtmux/errors.rb#L5) | `::String?` | [Errors](behavior.md#errors) | +| [#path](../../gems/libtmux/lib/libtmux/errors.rb#L5) | `::String?` | [Errors](behavior.md#errors) | +| [#phase](../../gems/libtmux/lib/libtmux/errors.rb#L5) | `::Symbol?` | [Errors](behavior.md#errors) | +| [#pid](../../gems/libtmux/lib/libtmux/errors.rb#L5) | `::Integer?` | [Errors](behavior.md#errors) | +| [#text](../../gems/libtmux/lib/libtmux/errors.rb#L5) | `::String?` | [Errors](behavior.md#errors) | +| [.new](../../gems/libtmux/lib/libtmux/errors.rb#L7) | `::LibTmux::Program::ScreenGeometryError` | [Errors](behavior.md#errors) | + ## LibTmux::ProtocolError | Method | Declared return | Contract | @@ -760,41 +816,43 @@ type checking. See [signature proof](behavior.md#signature-proof). | Method | Declared return | Contract | | --- | --- | --- | | [#attach](../../gems/libtmux/lib/libtmux/terminal.rb#L52) | `::LibTmux::TerminalResult` | [Terminal attachment](behavior.md#terminal-attachment) | -| [#capabilities](../../gems/libtmux/lib/libtmux/server.rb#L240) | `::LibTmux::Capabilities` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [#close](../../gems/libtmux/lib/libtmux/server.rb#L251) | `nil` | [Closing bindings](behavior.md#closing-bindings) | +| [#capabilities](../../gems/libtmux/lib/libtmux/server.rb#L242) | `::LibTmux::Capabilities` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#close](../../gems/libtmux/lib/libtmux/server.rb#L253) | `nil` | [Closing bindings](behavior.md#closing-bindings) | | [#delete_buffer](../../gems/libtmux/lib/libtmux/operations.rb#L69) | `::LibTmux::CommandResult` | [Buffers](behavior.md#buffers) | -| [#diagnostics](../../gems/libtmux/lib/libtmux/server.rb#L290) | `{ admitted_requests: ::Integer, reserved_process_slots: ::Integer, control_connections: ::Integer, closed: bool, limits: { max_requests: ::Integer, max_controls: ::Integer, close_timeout: ::Numeric } }` | [Diagnostics](behavior.md#diagnostics) | +| [#diagnostics](../../gems/libtmux/lib/libtmux/server.rb#L292) | `{ admitted_requests: ::Integer, reserved_process_slots: ::Integer, control_connections: ::Integer, closed: bool, limits: { max_requests: ::Integer, max_controls: ::Integer, close_timeout: ::Numeric } }` | [Diagnostics](behavior.md#diagnostics) | | [#display](../../gems/libtmux/lib/libtmux/operations.rb#L18) | `::LibTmux::CommandResult` | [Formats](behavior.md#formats) | | [#endpoint](../../gems/libtmux/lib/libtmux/server.rb#L149) | `::LibTmux::Endpoint` | [Borrowed bindings](behavior.md#borrowed-bindings) | | [#environment](../../gems/libtmux/lib/libtmux/operations.rb#L92) | `::String?` | [Environment](behavior.md#environment) | -| [#explain_panes](../../gems/libtmux/lib/libtmux/server.rb#L407) | `::Hash[::Symbol, untyped]` | [Source query plans](behavior.md#source-query-plans) | +| [#explain_panes](../../gems/libtmux/lib/libtmux/server.rb#L409) | `::Hash[::Symbol, untyped]` | [Source query plans](behavior.md#source-query-plans) | | [#hooks](../../gems/libtmux/lib/libtmux/operations.rb#L11) | `::LibTmux::Hooks` | [Options and hooks](behavior.md#options-and-hooks) | -| [#kill](../../gems/libtmux/lib/libtmux/server.rb#L300) | `::LibTmux::CommandResult` | [Killing daemons](behavior.md#killing-daemons) | +| [#kill](../../gems/libtmux/lib/libtmux/server.rb#L302) | `::LibTmux::CommandResult` | [Killing daemons](behavior.md#killing-daemons) | | [#list_buffers](../../gems/libtmux/lib/libtmux/operations.rb#L73) | `::Array[{ name: ::String, size: ::Integer }]` | [Buffers](behavior.md#buffers) | | [#list_clients](../../gems/libtmux/lib/libtmux/operations.rb#L100) | `::Array[{ name: ::String, pid: ::Integer, created: ::Integer, tty: ::String?, session_id: ::String?, control: bool }]` | [Live acquisition](behavior.md#live-acquisition) | -| [#list_panes](../../gems/libtmux/lib/libtmux/server.rb#L334) | `::Array[::LibTmux::Pane]` | [Live acquisition](behavior.md#live-acquisition) | -| [#list_sessions](../../gems/libtmux/lib/libtmux/server.rb#L326) | `::Array[::LibTmux::Session]` | [Live acquisition](behavior.md#live-acquisition) | +| [#list_panes](../../gems/libtmux/lib/libtmux/server.rb#L336) | `::Array[::LibTmux::Pane]` | [Live acquisition](behavior.md#live-acquisition) | +| [#list_sessions](../../gems/libtmux/lib/libtmux/server.rb#L328) | `::Array[::LibTmux::Session]` | [Live acquisition](behavior.md#live-acquisition) | | [#list_window_links](../../gems/libtmux/lib/libtmux/operations.rb#L80) | `::Array[::LibTmux::WindowLink]` | [Live acquisition](behavior.md#live-acquisition) | -| [#list_windows](../../gems/libtmux/lib/libtmux/server.rb#L330) | `::Array[::LibTmux::Window]` | [Live acquisition](behavior.md#live-acquisition) | -| [#new_session](../../gems/libtmux/lib/libtmux/server.rb#L311) | `::LibTmux::CreationReceipt` / `::LibTmux::Session` | [Creation](behavior.md#creation) | -| [#open_control](../../gems/libtmux/lib/libtmux/server.rb#L350) | `T` / `::LibTmux::ControlConnection` | [Control connections](behavior.md#control-connections) | +| [#list_windows](../../gems/libtmux/lib/libtmux/server.rb#L332) | `::Array[::LibTmux::Window]` | [Live acquisition](behavior.md#live-acquisition) | +| [#new_session](../../gems/libtmux/lib/libtmux/server.rb#L313) | `::LibTmux::CreationReceipt` / `::LibTmux::Session` | [Creation](behavior.md#creation) | +| [#open_control](../../gems/libtmux/lib/libtmux/server.rb#L352) | `T` / `::LibTmux::ControlConnection` | [Control connections](behavior.md#control-connections) | | [#options](../../gems/libtmux/lib/libtmux/operations.rb#L7) | `::LibTmux::Options` | [Options and hooks](behavior.md#options-and-hooks) | | [#owned?](../../gems/libtmux/lib/libtmux/owned.rb#L16) | `bool` | [Borrowed bindings](behavior.md#borrowed-bindings) | -| [#pane](../../gems/libtmux/lib/libtmux/server.rb#L346) | `::LibTmux::Pane` | [Live handles](behavior.md#live-handles) | +| [#pane](../../gems/libtmux/lib/libtmux/server.rb#L348) | `::LibTmux::Pane` | [Live handles](behavior.md#live-handles) | +| [#program_support](../../gems/libtmux/lib/libtmux/program.rb#L458) | `{ binding_key: ::String, pid: ::Integer, start_time: ::Integer, version: ::String, since: ::String, supported: bool }` | [Owned terminal programs](behavior.md#owned-terminal-programs) | | [#read_buffer](../../gems/libtmux/lib/libtmux/operations.rb#L65) | `::LibTmux::CommandResult` | [Buffers](behavior.md#buffers) | -| [#run](../../gems/libtmux/lib/libtmux/server.rb#L247) | `::LibTmux::CommandResult` | [Raw commands](behavior.md#raw-commands) | +| [#run](../../gems/libtmux/lib/libtmux/server.rb#L249) | `::LibTmux::CommandResult` | [Raw commands](behavior.md#raw-commands) | | [#run_group](../../gems/libtmux/lib/libtmux/group.rb#L32) | `::LibTmux::GroupResult` | [Command groups](behavior.md#command-groups) | -| [#search_panes](../../gems/libtmux/lib/libtmux/server.rb#L403) | `::LibTmux::Selection[::LibTmux::PaneSnapshot]` | [Source query execution](behavior.md#source-query-execution) | -| [#session](../../gems/libtmux/lib/libtmux/server.rb#L338) | `::LibTmux::Session` | [Live handles](behavior.md#live-handles) | +| [#search_panes](../../gems/libtmux/lib/libtmux/server.rb#L405) | `::LibTmux::Selection[::LibTmux::PaneSnapshot]` | [Source query execution](behavior.md#source-query-execution) | +| [#session](../../gems/libtmux/lib/libtmux/server.rb#L340) | `::LibTmux::Session` | [Live handles](behavior.md#live-handles) | | [#set_environment](../../gems/libtmux/lib/libtmux/operations.rb#L88) | `::LibTmux::CommandResult` | [Environment](behavior.md#environment) | -| [#snapshot](../../gems/libtmux/lib/libtmux/server.rb#L397) | `::LibTmux::Snapshot` | [Snapshot acquisition](behavior.md#snapshot-acquisition) | +| [#snapshot](../../gems/libtmux/lib/libtmux/server.rb#L399) | `::LibTmux::Snapshot` | [Snapshot acquisition](behavior.md#snapshot-acquisition) | | [#source_file](../../gems/libtmux/lib/libtmux/operations.rb#L42) | `::LibTmux::CommandResult` | [Source files](behavior.md#source-files) | -| [#supports_control?](../../gems/libtmux/lib/libtmux/server.rb#L232) | `bool` | [Borrowed bindings](behavior.md#borrowed-bindings) | +| [#start_program](../../gems/libtmux/lib/libtmux/program.rb#L464) | `::LibTmux::Program` / `T` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#supports_control?](../../gems/libtmux/lib/libtmux/server.rb#L234) | `bool` | [Borrowed bindings](behavior.md#borrowed-bindings) | | [#switch_client](../../gems/libtmux/lib/libtmux/terminal.rb#L39) | `::LibTmux::CommandResult` | [Client switching](behavior.md#client-switching) | -| [#tmux_version](../../gems/libtmux/lib/libtmux/server.rb#L227) | `::String` | [Borrowed bindings](behavior.md#borrowed-bindings) | +| [#tmux_version](../../gems/libtmux/lib/libtmux/server.rb#L229) | `::String` | [Borrowed bindings](behavior.md#borrowed-bindings) | | [#unset_environment](../../gems/libtmux/lib/libtmux/operations.rb#L96) | `::LibTmux::CommandResult` | [Environment](behavior.md#environment) | | [#wait_for](../../gems/libtmux/lib/libtmux/operations.rb#L47) | `::LibTmux::CommandResult` | [Wait channels](behavior.md#wait-channels) | -| [#window](../../gems/libtmux/lib/libtmux/server.rb#L342) | `::LibTmux::Window` | [Live handles](behavior.md#live-handles) | +| [#window](../../gems/libtmux/lib/libtmux/server.rb#L344) | `::LibTmux::Window` | [Live handles](behavior.md#live-handles) | | [#window_link](../../gems/libtmux/lib/libtmux/operations.rb#L84) | `::LibTmux::WindowLink` | [Live handles](behavior.md#live-handles) | | [#write_buffer](../../gems/libtmux/lib/libtmux/operations.rb#L57) | `::LibTmux::CommandResult` | [Buffers](behavior.md#buffers) | | [.new](../../gems/libtmux/lib/libtmux/server.rb#L183) | `::LibTmux::Server` | [Borrowed bindings](behavior.md#borrowed-bindings) | diff --git a/docs/reference/behavior.md b/docs/reference/behavior.md index d5626c58..afcca543 100644 --- a/docs/reference/behavior.md +++ b/docs/reference/behavior.md @@ -1135,3 +1135,140 @@ Checker-only dependencies are installed after each artifact's minimal runtime import and executable recipes, so they cannot hide runtime dependency omissions. Behavioral tests, real-tmux fixtures and the platform matrix remain separate evidence. + +## Owned terminal programs + +`LibTmux.start_program(argv)` creates a private daemon. Pass `server:` or +call `server.start_program(argv)` to borrow an existing binding. Each program +owns one terminal in a new private session. Existing sessions and their +options keep their settings. The capability `owned-terminal-program` requires +tmux 3.7. The library checks the bound daemon before it creates a pane or +starts the application. The helper and Ruby installation must be accessible +to the daemon on the same machine. + +`server.program_support` returns the bound daemon's identity, minimum +release and support decision in a frozen hash. It queries the binding +without running display hooks or acquiring a pane listing. + +Pass an argv array of up to 256 KiB. Empty arguments and shell metacharacters +reach the executable literally. Set `cwd:`, `environment:`, `width:` or +`height:` when launching. Geometry defaults to 80×24 and accepts 1–256 +columns and 1–100 rows. `history_lines:` accepts 0–100 and defaults to 100. + +The factory retires the temporary pane used to set retention before it +returns or yields the program handle. + +Use the block form for automatic cleanup. `run_program` returns the +completion result after closing its program. Startup, setup and completion +share the caller's timeout and cancellation token. Cancellation of an +owning run retires its resources. Each explicit `Program#wait` has a +separate deadline. Cancelling one waiter leaves the program and its other +waiters running. Async uses the supplied scope or creates a scoped adapter +for a core binding. It shares the same program owner and releases its own +adapter at close. + +The supervisor observes the application's exit code or signal and sends +it over a one-shot local socket. After the application exits, the supervisor +writes a private terminal title. tmux processes that title after the +preceding output. Once both observations arrive, `wait` captures the screen +and returns a frozen result. Successful waiters share that result. +`screen` captures the current terminal on demand. The capture combines +rendered stdout and stderr, wraps at terminal width and retains up to 64 KiB +of valid UTF-8 from the visible rows and configured history. +`program.capture_screen` returns a frozen capture with `text` and +`truncated?`. The flag records bytes omitted by the 64 KiB cap. A completed +result exposes the same evidence through `screen_truncated?`. Terminal edits, +alternate screens and scrollback eviction can remove earlier text. +Polling screens provides snapshots and has no lossless stream or replay. +`send_text`, `send_keys` and `resize` operate on the live generation. + +Each capture, input, resize and borrowed-pane retirement checks the +supervisor PID and launch token in the daemon command queue. Resize also +requires that the pane still belongs to its original window. A pane respawn +or daemon replacement invalidates the live handle. If the daemon is gone +before the native client connects, the operation raises a +`TargetNotFoundError` with `delivery: :not_sent`. If a connected native +client loses the daemon before a reply, the error has `delivery: :possibly_sent`. +A failed explicit close can be retried on the same handle. Block exit also runs +cleanup. Use the owner in the process that launched it. After a Ruby fork, +call `close` on the inherited handle in the forked child to release its copies +of the sockets. A child that +keeps those descriptors open can delay detection of owner death. + +An external tmux move or resize can grow a pane beyond the program's +256-column or 100-row limit. Capture checks the geometry in the daemon +queue and raises `Program::ScreenGeometryError` before reading the screen. +Input and retirement remain available. Restore the pane size in tmux to +retry a capture or retrieve the observed completion with `wait`. + +Closing the program releases its private socket. If the owner process dies, +the supervisor observes EOF and kills its foreground process group, including +children that ignore hangup. A process that creates a new group or session can +outlive this cleanup. The application runs with the daemon user's filesystem, +network and process privileges. The helper consumes and removes its private +launch files before running argv. Once setup completes a dedicated daemon +exits when its last session closes. A forced owner exit can leave its private +directory and socket pathname on disk after the daemon exits. + +For recovery records, start the server explicitly and pass it to +`start_program`. Record `server.endpoint.socket_path` and the result of +`server.display('#{pid} #{start_time}').text` while the program runs. +After an interrupted launch, query that socket with +`tmux -N -S "$socket" display-message -p '#{pid} #{start_time}'` and +compare the identity before retiring a surviving dedicated daemon. +Once the recorded daemon has exited, remove its private directory. +On a shared daemon, check the specific program session and pane. + +Run a sample migration command and report the failure from its retained +screen. + + +```ruby +require "libtmux" +require "rbconfig" + +command = [ + RbConfig.ruby, "-e", "warn ARGV.fetch(0); exit 7", + "Migration stopped: café table missing" +] + +result = LibTmux.run_program(command) +diagnostic = result.screen.lines(chomp: true).find do |line| + line.start_with?("Migration stopped:") +end +raise "Expected a migration failure with a diagnostic" unless + result.exit_status == 7 && diagnostic + +puts "Exit #{result.exit_status}. #{diagnostic}" +``` + + +It prints: + +```text +Exit 7. Migration stopped: café table missing +``` + + +Send a line to an application on an existing server and check its own reply. + + +```ruby +require "libtmux" +require "rbconfig" + +command = [RbConfig.ruby, "-e", 'puts "Received: " + STDIN.readline.chomp'] +LibTmux::Server.start do |server| + server.start_program(command) do |program| + program.send_text("café") + program.send_keys("Enter") + result = program.wait + reply = result.screen.lines(chomp: true).find { |line| line == "Received: café" } + raise "Missing confirmation from the program" unless reply && result.exit_status == 0 + puts reply + end +end +``` + + +The program prints `Received: café`. diff --git a/docs/reference/contracts.json b/docs/reference/contracts.json index d9865435..15e508fd 100644 --- a/docs/reference/contracts.json +++ b/docs/reference/contracts.json @@ -1,6 +1,34 @@ { "version": 1, "contracts": [ + { + "id": "owned-terminal-programs", + "title": "Owned terminal programs", + "methods": [ + "LibTmux.start_program", + "LibTmux.run_program", + "LibTmux::Server#program_support", + "LibTmux::Server#start_program", + "LibTmux::Async.start_program", + "LibTmux::Async.run_program", + "LibTmux::Program#capture_screen", + "LibTmux::Program#close", + "LibTmux::Program#inspect", + "LibTmux::Program#resize", + "LibTmux::Program#screen", + "LibTmux::Program#send_keys", + "LibTmux::Program#send_text", + "LibTmux::Program#wait", + "LibTmux::Program::Result#exit_status", + "LibTmux::Program::Result#inspect", + "LibTmux::Program::Result#screen", + "LibTmux::Program::Result#screen_truncated?", + "LibTmux::Program::Result#signal", + "LibTmux::Program::Screen#inspect", + "LibTmux::Program::Screen#text", + "LibTmux::Program::Screen#truncated?" + ] + }, { "id": "async-map", "title": "Async map", diff --git a/examples/api/owned_program.rb b/examples/api/owned_program.rb new file mode 100644 index 00000000..c3cf5500 --- /dev/null +++ b/examples/api/owned_program.rb @@ -0,0 +1,25 @@ +# frozen_string_literal: true + +begin + # docs:begin main + require "libtmux" + require "rbconfig" + + command = [ + RbConfig.ruby, "-e", "warn ARGV.fetch(0); exit 7", + "Migration stopped: café table missing" + ] + + result = LibTmux.run_program(command) + diagnostic = result.screen.lines(chomp: true).find do |line| + line.start_with?("Migration stopped:") + end + raise "Expected a migration failure with a diagnostic" unless + result.exit_status == 7 && diagnostic + + puts "Exit #{result.exit_status}. #{diagnostic}" + # docs:end main +rescue StandardError => error + warn "#{error.class}: #{error.message}" + exit 1 +end diff --git a/examples/api/owned_program_input.rb b/examples/api/owned_program_input.rb new file mode 100644 index 00000000..58d2ee4f --- /dev/null +++ b/examples/api/owned_program_input.rb @@ -0,0 +1,23 @@ +# frozen_string_literal: true + +begin + # docs:begin main + require "libtmux" + require "rbconfig" + + command = [RbConfig.ruby, "-e", 'puts "Received: " + STDIN.readline.chomp'] + LibTmux::Server.start do |server| + server.start_program(command) do |program| + program.send_text("café") + program.send_keys("Enter") + result = program.wait + reply = result.screen.lines(chomp: true).find { |line| line == "Received: café" } + raise "Missing confirmation from the program" unless reply && result.exit_status == 0 + puts reply + end + end + # docs:end main +rescue LibTmux::UnsupportedFeatureError => error + warn "#{error.class}: #{error.message}" + exit 1 +end diff --git a/examples/manifest.json b/examples/manifest.json index 8a134627..5abaccda 100644 --- a/examples/manifest.json +++ b/examples/manifest.json @@ -1,6 +1,28 @@ { "version": 2, "programs": [ + { + "id": "owned_program", + "path": "examples/api/owned_program.rb", + "gem": "libtmux", + "api": { + "symbols": ["LibTmux.run_program"], + "capabilities": ["owned-terminal-program"], + "description": "Report a terminal program failure with the exit status and the final diagnostic.", + "output": "Exit 7. Migration stopped: café table missing\n" + } + }, + { + "id": "owned_program_input", + "path": "examples/api/owned_program_input.rb", + "gem": "libtmux", + "api": { + "symbols": ["LibTmux::Server#start_program", "LibTmux::Program#send_text", "LibTmux::Program#send_keys", "LibTmux::Program#wait"], + "capabilities": ["owned-terminal-program"], + "description": "Send literal input on an existing server and verify the program's reply and exit status.", + "output": "Received: café\n" + } + }, { "id": "quickstart", "path": "examples/quickstart.rb", @@ -454,6 +476,18 @@ "gems/libtmux/README.md" ], "snippets": [ + { + "id": "owned_program_input/main", + "source": "examples/api/owned_program_input.rb", + "region": "main", + "language": "ruby" + }, + { + "id": "owned_program/main", + "source": "examples/api/owned_program.rb", + "region": "main", + "language": "ruby" + }, { "id": "quickstart/main", "source": "examples/quickstart.rb", diff --git a/gems/libtmux-async/lib/libtmux/async.rb b/gems/libtmux-async/lib/libtmux/async.rb index e4cd2532..8dd1feb1 100644 --- a/gems/libtmux-async/lib/libtmux/async.rb +++ b/gems/libtmux-async/lib/libtmux/async.rb @@ -28,6 +28,16 @@ def self.attach_cleanup(error, details) end private_class_method :attach_cleanup + # Own a private terminal program with scheduler-aware tmux requests. + def self.start_program(argv, parent: ::Async::Task.current, **options, &block) + adapter = ->(server) { Scope.new(parent: parent, server: server) unless server.is_a?(Server) } + Program.__send__(:start_with, adapter, argv, **options, &block) + end + + def self.run_program(argv, **options) + Program.__send__(:run_with, self, argv, **options) + end + def self.open(server:, parent: ::Async::Task.current, **options) raise ArgumentError, "Async scope requires a block" unless block_given? diff --git a/gems/libtmux-async/lib/libtmux/async/process.rb b/gems/libtmux-async/lib/libtmux/async/process.rb index 6417d4fa..7f563992 100644 --- a/gems/libtmux-async/lib/libtmux/async/process.rb +++ b/gems/libtmux-async/lib/libtmux/async/process.rb @@ -11,17 +11,21 @@ class ProcessDriver attr_reader :pid, :result - def initialize(scope, ticket, argv, input, deadline, cancel, limits) + def initialize(scope, ticket, argv, input, deadline, cancel, limits, stdout_tail: nil) @scope, @ticket, @argv, @input = scope, ticket, argv, input @deadline, @cancel, @limits = deadline, cancel, limits @started = clock @changed = ::Async::Notification.new @tasks, @streams = [], [] - @buffers = {stdout: +"".b, stderr: +"".b} + @stdout_tail = stdout_tail @finished_reads = 0 end def call + @buffers = { + stdout: Internal::CommandOutput.new(@limits.fetch(:stdout), tail: @stdout_tail), + stderr: Internal::CommandOutput.new(@limits.fetch(:stderr)) + } failure = nil begin watch_cancellation @@ -219,16 +223,13 @@ def start_io def read_stream(io, stream) buffer = @buffers.fetch(stream) loop do - remaining = @limits.fetch(stream) - buffer.bytesize - bytes = io.read_nonblock([CHUNK, remaining + 1].min, exception: false) + bytes = io.read_nonblock(buffer.read_size(CHUNK), exception: false) case bytes when nil then break when :wait_readable then Fiber.scheduler.io_wait(io, IO::READABLE) when String - raise CapacityError.new("command #{stream} exceeded its byte limit", **details(:read)) if bytes.bytesize > remaining - - @scope.__send__(:retain_output, @ticket, bytes.bytesize) - buffer << bytes + appended = buffer.append(bytes) { |retained| @scope.__send__(:retain_output, @ticket, retained) } + raise CapacityError.new("command #{stream} exceeded its byte limit", **details(:read)) unless appended end end @finished_reads += 1 @@ -273,7 +274,8 @@ def drive raise @failure if @failure if @status && @finished_reads == 2 check_budget(:publish) - @result = CommandResult.new(**@buffers, status: @status, pid: @pid, argv: @argv, elapsed_seconds: clock - @started) + @result = CommandResult.new(**@buffers.transform_values(&:bytes), status: @status, + pid: @pid, argv: @argv, elapsed_seconds: clock - @started) return end phase = observed? ? :drain : :read diff --git a/gems/libtmux-async/lib/libtmux/async/scope.rb b/gems/libtmux-async/lib/libtmux/async/scope.rb index 70d2b9ab..22105514 100644 --- a/gems/libtmux-async/lib/libtmux/async/scope.rb +++ b/gems/libtmux-async/lib/libtmux/async/scope.rb @@ -279,7 +279,7 @@ def ensure_open raise ClosedError.new("Async scope is closed", phase: :admission) if @closed || @parent.finished? end - def execute(argv, input: "".b, timeout: 5.0, cancel: nil) + def execute(argv, input: "".b, timeout: 5.0, cancel: nil, stdout_tail: nil) ensure_open deadline = clock + timeout if timeout.is_a?(Numeric) && timeout.finite? raise ArgumentError, "timeout must be finite" unless deadline @@ -304,7 +304,7 @@ def execute(argv, input: "".b, timeout: 5.0, cancel: nil) @waiting << ticket @queued_bytes += bytes ticket.execution = ProcessDriver.new(self, ticket, argv.map { |arg| arg.dup.freeze }.freeze, - input.b.freeze, deadline, cancel, @limits) + input.b.freeze, deadline, cancel, @limits, stdout_tail: stdout_tail) ticket.task = ::Async::Task.new(@parent) do begin ticket.result = ticket.execution.call diff --git a/gems/libtmux-async/lib/libtmux/async/server.rb b/gems/libtmux-async/lib/libtmux/async/server.rb index be03a634..82d822cf 100644 --- a/gems/libtmux-async/lib/libtmux/async/server.rb +++ b/gems/libtmux-async/lib/libtmux/async/server.rb @@ -66,7 +66,7 @@ def self.open(**) private - def dispatch(argv, input: "".b, timeout: 5.0, cancel: nil, repaired_break: false) + def dispatch(argv, input: "".b, timeout: 5.0, cancel: nil, repaired_break: false, stdout_tail: nil) ensure_owner ensure_open validate_argv(argv) @@ -74,7 +74,8 @@ def dispatch(argv, input: "".b, timeout: 5.0, cancel: nil, repaired_break: false Internal::NativeGuard.check(argv, @release, repaired_break: repaired_break) fence, marker = Internal::TmuxVersion.fence(@release) - result = @scope.__send__(:execute, @pin.command_prefix + fence + argv, input: input, timeout: timeout, cancel: cancel) + result = @scope.__send__(:execute, @pin.command_prefix + fence + argv, + input: input, timeout: timeout, cancel: cancel, stdout_tail: stdout_tail) Internal::TmuxVersion.check_fence(result, marker, @release) end diff --git a/gems/libtmux-async/sig/libtmux-async.rbs b/gems/libtmux-async/sig/libtmux-async.rbs index 24e34d31..f9c1a949 100644 --- a/gems/libtmux-async/sig/libtmux-async.rbs +++ b/gems/libtmux-async/sig/libtmux-async.rbs @@ -4,6 +4,10 @@ module LibTmux def self.open: [T] (server: LibTmux::Server, ?parent: untyped, **untyped) { (Scope) -> T } -> T + def self.start_program: (Array[String], ?parent: untyped, ?server: LibTmux::Server?, ?executable: String, ?cwd: String?, ?environment: Hash[String, String], ?width: Integer, ?height: Integer, ?history_lines: Integer, ?timeout: Numeric, ?cancel: untyped) -> LibTmux::Program + | [T] (Array[String], ?parent: untyped, ?server: LibTmux::Server?, ?executable: String, ?cwd: String?, ?environment: Hash[String, String], ?width: Integer, ?height: Integer, ?history_lines: Integer, ?timeout: Numeric, ?cancel: untyped) { (LibTmux::Program) -> T } -> T + def self.run_program: (Array[String], ?parent: untyped, ?server: LibTmux::Server?, ?executable: String, ?cwd: String?, ?environment: Hash[String, String], ?width: Integer, ?height: Integer, ?history_lines: Integer, ?timeout: Numeric, ?cancel: untyped) -> LibTmux::Program::Result + type scope_diagnostics = { transport: :async_process, closed: bool, admitted_requests: Integer, reserved_process_slots: Integer, diff --git a/gems/libtmux/lib/libtmux.rb b/gems/libtmux/lib/libtmux.rb index f908a157..8f287f99 100644 --- a/gems/libtmux/lib/libtmux.rb +++ b/gems/libtmux/lib/libtmux.rb @@ -18,3 +18,4 @@ require "libtmux/owned" require "libtmux/terminal" require "libtmux/text_wait" +require "libtmux/program" diff --git a/gems/libtmux/lib/libtmux/capabilities.rb b/gems/libtmux/lib/libtmux/capabilities.rb index c9572d07..f6090a83 100644 --- a/gems/libtmux/lib/libtmux/capabilities.rb +++ b/gems/libtmux/lib/libtmux/capabilities.rb @@ -159,6 +159,11 @@ def to_h CONTROL_CHANNELS = %w[LibTmux::ControlConnection#exchange LibTmux::Async::ControlConnection#exchange].freeze CAPABILITIES = [ + Capability.new(id: "owned-terminal-program", name: "Owned terminal program", since: "3.7", + handling: :refuse, error: ERROR, + summary: "Run literal argv in an owned terminal and retain its final screen on the bound daemon.", + apis: ["LibTmux.start_program", "LibTmux.run_program", "LibTmux::Server#start_program", "LibTmux::Async.start_program", "LibTmux::Async.run_program"], + commands: []), Capability.new(id: "control-mode", name: "Control mode", since: "3.7", handling: :refuse, error: ERROR, summary: "Attach a library-managed control client and stream events.", apis: ["LibTmux::Server#open_control", "LibTmux::Async::Server#open_control"], diff --git a/gems/libtmux/lib/libtmux/owned.rb b/gems/libtmux/lib/libtmux/owned.rb index 93843ae2..15619583 100644 --- a/gems/libtmux/lib/libtmux/owned.rb +++ b/gems/libtmux/lib/libtmux/owned.rb @@ -206,9 +206,11 @@ class OwnedServer < Server def initialize(executable: "tmux", config: nil, timeout: 5.0, cancel: nil, **options) begin Thread.handle_interrupt(Exception => :never) do + @startup_budget = operation_budget(timeout, cancel) @daemon = OwnedDaemon.new(executable: executable, config: config, timeout: timeout, cancel: cancel) super(endpoint: @daemon.endpoint, **options) @binding_ready = true + @startup_budget.options Thread.handle_interrupt(Exception => :immediate) { nil } end rescue Exception => failure @@ -218,6 +220,8 @@ def initialize(executable: "tmux", config: nil, timeout: 5.0, cancel: nil, **opt failure.__send__(:attach_cleanup_errors, ["owned daemon close failed (#{cleanup.class})"]) if failure.is_a?(Error) end raise failure + ensure + @startup_budget = nil end end @@ -249,6 +253,13 @@ def close nil end + + private + + def version_probe_options(timeout) + remaining = @startup_budget.options + remaining.merge(timeout: [timeout, remaining.fetch(:timeout)].min) + end end private_constant :SocketReadiness, :OwnedDaemon, :OwnedServer end diff --git a/gems/libtmux/lib/libtmux/process.rb b/gems/libtmux/lib/libtmux/process.rb index c11df3f6..1de5af17 100644 --- a/gems/libtmux/lib/libtmux/process.rb +++ b/gems/libtmux/lib/libtmux/process.rb @@ -91,6 +91,35 @@ def ensure_owner module Internal Cancellation = LibTmux::Cancellation + class CommandOutput + attr_reader :bytes + + def initialize(limit, tail: nil) + @bytes = +"".b + @limit = @retained_limit = limit + if tail && tail.fetch(:retain) <= limit + @limit = tail.fetch(:read) + @retained_limit = tail.fetch(:retain) + end + @read = 0 + end + + def read_size(chunk_size) + [chunk_size, @limit - @read + 1].min + end + + def append(chunk) + @read += chunk.bytesize + return false if @read > @limit + + discard = [@bytes.bytesize + chunk.bytesize - @retained_limit, 0].max + yield chunk.bytesize - discard if block_given? + @bytes << chunk + @bytes.slice!(0, discard) if discard.positive? + true + end + end + class ProcessExecutor def initialize(stdout_limit: 1 << 20, stderr_limit: 1 << 18, input_limit: 1 << 20, argv_limit: 1 << 18, cleanup_timeout: 0.5, drain_timeout: 0.5) [stdout_limit, stderr_limit, input_limit, argv_limit].each do |limit| @@ -107,14 +136,15 @@ def initialize(stdout_limit: 1 << 20, stderr_limit: 1 << 18, input_limit: 1 << 2 # +discard_stdout+ gives the child the null device for stdout, so the # result reports no stdout and the call does not wait for a descriptor # that a daemon older than tmux 3.2 keeps open after its client exits. - def run(argv, input: "".b, env: {}, timeout: 5.0, cancel: nil, discard_stdout: false) - Execution.new(argv, input, env, timeout, cancel, @limits, @cleanup_timeout, @drain_timeout, discard_stdout).call + def run(argv, input: "".b, env: {}, timeout: 5.0, cancel: nil, discard_stdout: false, stdout_tail: nil) + Execution.new(argv, input, env, timeout, cancel, @limits, @cleanup_timeout, @drain_timeout, + discard_stdout, stdout_tail).call end class Execution CHUNK_BYTES = 16_384 - def initialize(argv, input, env, timeout, cancel, limits, cleanup_timeout, drain_timeout, discard_stdout) + def initialize(argv, input, env, timeout, cancel, limits, cleanup_timeout, drain_timeout, discard_stdout, stdout_tail) @started = monotonic unless argv.is_a?(Array) && !argv.empty? && argv.all? { |argument| argument.is_a?(String) && !argument.include?("\0") } raise ArgumentError, "argv must contain strings without NUL" @@ -136,7 +166,8 @@ def initialize(argv, input, env, timeout, cancel, limits, cleanup_timeout, drain @discard_stdout = discard_stdout @process_wait = ProcessWait.new @owned = [] - @buffers = {stdout: +"".b, stderr: +"".b} + @buffers = {stdout: CommandOutput.new(limits.fetch(:stdout), tail: stdout_tail), + stderr: CommandOutput.new(limits.fetch(:stderr))} @offset = 0 end @@ -249,15 +280,12 @@ def communicate def read_output(io, reading) stream = reading.fetch(io) buffer = @buffers.fetch(stream) - available = @limits.fetch(stream) - buffer.bytesize - bytes = io.read_nonblock([CHUNK_BYTES, available + 1].min, exception: false) + bytes = io.read_nonblock(buffer.read_size(CHUNK_BYTES), exception: false) if bytes.nil? reading.delete(io) io.close - elsif bytes.is_a?(String) - raise CapacityError.new("command #{stream} exceeded its byte limit", **details(:read)) if bytes.bytesize > available - - buffer << bytes + elsif bytes.is_a?(String) && !buffer.append(bytes) + raise CapacityError.new("command #{stream} exceeded its byte limit", **details(:read)) end end @@ -286,7 +314,8 @@ def details(phase) end def result - CommandResult.new(**@buffers, status: @status, elapsed_seconds: monotonic - @started, pid: @pid, argv: @argv) + CommandResult.new(**@buffers.transform_values(&:bytes), status: @status, + elapsed_seconds: monotonic - @started, pid: @pid, argv: @argv) end def retire diff --git a/gems/libtmux/lib/libtmux/program.rb b/gems/libtmux/lib/libtmux/program.rb new file mode 100644 index 00000000..0034de04 --- /dev/null +++ b/gems/libtmux/lib/libtmux/program.rb @@ -0,0 +1,478 @@ +# frozen_string_literal: true + +require "fileutils" +require "io/wait" +require "socket" +require "tmpdir" +require "rbconfig" + +module LibTmux + # Start literal argv in a terminal on a new private server or a supplied server. + def self.start_program(argv, **options, &block) + Program.__send__(:start_with, nil, argv, **options, &block) + end + + # Start a private program, await completion, and close the program. + def self.run_program(argv, **options) + Program.__send__(:run_with, self, argv, **options) + end + + # A terminal program tied to one process generation on a bound daemon. + # Use the block form for automatic cleanup, or explicitly close the owner. + class Program + # The pane's current geometry exceeds the owned screen limits. + class ScreenGeometryError < CapacityError; end + + # A UTF-8 capture of the retained rows. Truncation records the byte cap. + class Screen + attr_reader :text + + def initialize(text, truncated) + @text, @truncated = text.freeze, truncated + freeze + end + private_class_method :new + + def truncated? + @truncated + end + + def inspect + "#<#{self.class} bytes=#{text.bytesize} truncated=#{truncated?}>" + end + end + + # A completed process and the retained terminal screen, including history. + class Result + attr_reader :exit_status, :signal, :screen + + def initialize(exit_status, signal, capture) + @exit_status, @signal, @screen = exit_status, signal, capture.text + @screen_truncated = capture.truncated? + freeze + end + private_class_method :new + + def screen_truncated? + @screen_truncated + end + + def inspect + "#<#{self.class} exit_status=#{exit_status.inspect} signal=#{signal.inspect} screen_bytes=#{screen.bytesize}>" + end + end + + HISTORY_LINES = 100 + SCREEN_BYTES = 65_536 + MAX_WIDTH = 256 + MAX_HEIGHT = 100 + # A tmux grid cell holds up to 32 UTF-8 bytes, including combining marks. + SCREEN_TAIL = {retain: SCREEN_BYTES + 1, read: (MAX_HEIGHT + HISTORY_LINES) * (MAX_WIDTH * 32 + 1)}.freeze + CHILD = File.expand_path("../../libexec/program_child.rb", __dir__) + private_constant :HISTORY_LINES, :SCREEN_TAIL, :CHILD + + def self.run_with(factory, argv, timeout: 5.0, cancel: nil, **options) + budget = Server.__send__(:operation_budget, timeout, cancel) + factory.start_program(argv, **options, **budget.options) { |program| program.wait(**budget.options) } + end + private_class_method :run_with + + def self.start_with(adapter, argv, server: nil, executable: "tmux", cwd: nil, environment: {}, width: 80, height: 24, + timeout: 5.0, cancel: nil, history_lines: HISTORY_LINES) + validate_size(width, height) + raise ArgumentError, "server must be a LibTmux::Server" unless server.nil? || server.is_a?(Server) + unless history_lines.is_a?(Integer) && (0..HISTORY_LINES).cover?(history_lines) + raise ArgumentError, "history_lines must be between 0 and #{HISTORY_LINES}" + end + budget = Server.__send__(:operation_budget, timeout, cancel) + owned = Server.start(executable: executable, **budget.options) unless server + source = server || owned + scope = adapter&.call(source) + source = scope.server if scope + source.__send__(:require_program_support, **budget.options) + + program = new(owned, scope, source, history_lines) + program.__send__(:launch, argv, cwd, environment, width, height, budget) + return program unless block_given? + + yield program + rescue Exception => failure + raise + ensure + if (program || owned || scope) && (failure || block_given?) + begin + program ? program.close : close_owned(scope, owned) + rescue Exception => cleanup + raise unless failure + + attach_cleanup(failure, cleanup) + end + end + end + private_class_method :start_with + + def self.validate_size(width, height) + unless [width, height].zip([MAX_WIDTH, MAX_HEIGHT]).all? { |value, limit| value.is_a?(Integer) && (1..limit).cover?(value) } + raise ArgumentError, "geometry must fit #{MAX_WIDTH} columns by #{MAX_HEIGHT} rows" + end + end + private_class_method :validate_size + + def self.close_owned(scope, owned) + failure = nil + begin + scope&.close + rescue Exception => error + failure = error + ensure + begin + owned&.close + rescue Exception => cleanup + attach_cleanup(failure, cleanup) + failure ||= cleanup + end + end + raise failure if failure + end + private_class_method :close_owned + + def self.attach_cleanup(failure, cleanup) + return unless failure.is_a?(Error) + + details = ["program cleanup failed (#{cleanup.class})"] + details.concat(cleanup.cleanup_errors) if cleanup.is_a?(Error) + failure.__send__(:attach_cleanup_errors, details) + end + private_class_method :attach_cleanup + + def initialize(owned, scope, server, history_lines) + @history_lines = history_lines + @close_lock = Mutex.new + @owned, @scope, @server = owned, scope, server + @result_lock = Mutex.new + @status_bytes = +"".b + @creator = Process.pid + end + private_class_method :new + + # Each wait has its own deadline. All successful waits return the same result. + def wait(timeout: 5.0, cancel: nil) + ensure_open + budget = @server.__send__(:operation_budget, timeout, cancel) + loop do + options = budget.options + result = @result_lock.synchronize { @result } + return result if result + + # Also check identity while the worker is running, so a respawn has + # a definite outcome even if its predecessor never reported an exit. + title = guarded("display-message", ["-p", "-t", @pane.id, "\#{pane_title}"], **options).text.chomp + status = read_status + if title == @final_title && status + result = Result.__send__(:new, *status, capture_screen(**budget.options)) + budget.options + return @result_lock.synchronize { @result ||= result } + end + remaining = budget.options.fetch(:timeout) + pause = [remaining, 0.02].min + cancel ? cancel.reader.wait_readable(pause) : sleep(pause) + end + end + + # Capture screen and bounded scrollback as UTF-8 text. + def screen(timeout: 5.0, cancel: nil) + capture_screen(timeout: timeout, cancel: cancel).text + end + + # Capture the current screen and whether the 64 KiB limit dropped bytes. + def capture_screen(timeout: 5.0, cancel: nil) + ensure_open + text = capture_within_geometry(timeout: timeout, cancel: cancel) + offset = [text.bytesize - SCREEN_BYTES, 0].max + tail = text.byteslice(offset..).force_encoding(Encoding::UTF_8).scrub("") + Screen.__send__(:new, tail, offset.positive?) + end + + def send_text(text, timeout: 5.0, cancel: nil) + ensure_open + raise ArgumentError, "text must be a String" unless text.is_a?(String) + guarded("send-keys", ["-l", "-t", @pane.id, "--", text], timeout: timeout, cancel: cancel) + end + + def send_keys(*keys, timeout: 5.0, cancel: nil) + ensure_open + raise ArgumentError, "provide at least one key name" if keys.empty? + guarded("send-keys", ["-t", @pane.id, "--", *keys], timeout: timeout, cancel: cancel) + end + + def resize(width:, height:, timeout: 5.0, cancel: nil) + ensure_open + self.class.__send__(:validate_size, width, height) + guarded("resize-window", ["-t", @window.id, "-x", width.to_s, "-y", height.to_s], + window: @window.id, timeout: timeout, cancel: cancel) + end + + def close + if @creator != Process.pid + # Only release descriptor copies inherited by this fork. + close_sockets + @closed = true + return nil + end + @close_lock.synchronize do + return nil if @closed + @scope&.__send__(:ensure_owner) + @server.__send__(:ensure_owner) + @result_lock.synchronize { @closing = true } + begin + retire_borrowed_panes unless @owned + ensure + close_sockets + begin + FileUtils.remove_entry_secure(@directory) if @directory + rescue Errno::ENOENT + # The supervisor removes its one-shot directory before launching. + end + end + self.class.__send__(:close_owned, @scope, @owned) + @closed = true + end + nil + end + + def inspect + "#<#{self.class} #{@closed ? "closed" : "open"}>" + end + + private + + def capture_within_geometry(timeout:, cancel:) + native = @server.method(:tmux_command) + marker = "libtmux-screen-geometry-#{SecureRandom.hex(12)}" + fits = "\#{&&:\#{e|<=:\#{pane_width},#{MAX_WIDTH}},\#{e|<=:\#{pane_height},#{MAX_HEIGHT}}}" + capture = native.call([@names.fetch("capture-pane"), "-p", "-S", (-@history_lines).to_s, "-t", @pane.id]) + refuse = native.call([@names.fetch("display-message"), "-p", "--", marker]) + result = guarded("if-shell", ["-F", "-t", @pane.id, fits, capture, refuse], + timeout: timeout, cancel: cancel, stdout_tail: SCREEN_TAIL) + return result.stdout unless result.stdout == "#{marker}\n" + + raise ScreenGeometryError.new("Terminal program screen requires at most #{MAX_WIDTH} columns and #{MAX_HEIGHT} rows. " \ + "Restore the pane geometry in tmux and retry.", phase: :admission) + end + + def retire_pane + if @pending_listener + cleanup = @server.__send__(:operation_budget, 0.5, nil) + claim_pending(cleanup) + retire_guarded_pane(@pending_target, pid: @pending_pid, **cleanup.options) + elsif @pid + retire_guarded_pane(@pane.id) + end + end + + def retire_preparation(**options) + return unless @prepare_pane + + retire_guarded_pane(@prepare_pane, pid: @prepare_pid, **options) + @prepare_pane = nil + end + + def retire_guarded_pane(pane, **options) + guarded("kill-pane", ["-t", pane], pane: pane, **options) + rescue TargetNotFoundError => error + raise if error.delivery == :possibly_sent + end + + def retire_borrowed_panes + failure = nil + begin + retire_preparation(timeout: 0.5) + rescue Exception => error + failure = error + ensure + begin + retire_pane unless @pane_retired + @pane_retired = true + rescue Exception => cleanup + raise unless failure + + self.class.__send__(:attach_cleanup, failure, cleanup) + end + end + raise failure if failure + end + + def close_sockets + @pending_peer&.close + @pending_listener&.close + @prepare_peer&.close + @peer&.close + end + + def launch(argv, cwd, environment, width, height, budget) + @server.__send__(:pane_command, argv) + @server.__send__(:creation_options, cwd: cwd, environment: environment) + if argv.sum { |argument| argument.bytesize + 1 } > 262_144 + raise ArgumentError, "program argv exceeds 256 KiB" + end + @nonce = SecureRandom.hex(12).upcase + @final_title = "LIBTMUX-FINISHED-#{@nonce}" + temporary_root = (Dir.tmpdir.bytesize <= 40) ? Dir.tmpdir : "/tmp" + @directory = Dir.mktmpdir("libtmux-ruby-program-", temporary_root) + File.open(File.join(@directory, "argv"), "wb", 0o600) { |io| io.write(argv.map(&:b).join("\0".b)) } + @names = @server.__send__(:builtin_spellings, "if-shell", "display-message", "set-option", "kill-pane", + "capture-pane", "send-keys", "resize-window", budget: budget) + helper = [RbConfig.ruby, "--disable=rubyopt,gems", CHILD, @directory] + session_name = "program-#{@nonce}" + # A grid created with zero history stays disabled even if the session's + # history-limit increases. Set the limit before creating the real pane. + setup, @prepare_peer, @prepare_pid = open_candidate("prepare", "=#{session_name}:", budget) do + @server.new_session(name: session_name, command: [*helper, "prepare", @nonce], + width: width, height: height, receipt: true, **budget.options) + end + @prepare_pane = setup.pane.id + setup.entity.options.set("history-limit", @history_lines, **budget.options) + receipt, @peer, @pid = open_candidate("owner", "=#{session_name}:=program", budget) do + setup.entity.new_window(name: "program", command: [*helper, @final_title], + cwd: cwd, environment: environment, focus: true, receipt: true, **budget.options) + end + @pane, @window = receipt.pane, receipt.window + retire_preparation(**budget.options) + @prepare_peer.close + guarded("set-option", ["-p", "-t", @pane.id, "allow-set-title", "on"], **budget.options) + @server.options.set("exit-empty", true, **budget.options) if @owned + guarded("display-message", ["-p", "-t", @pane.id, "\#{pane_id}"], **budget.options) + @peer.write("G") + wait_readable(@peer, budget) + unless @peer.read_nonblock(1) == "A" + raise ProtocolError.new("program supervisor did not acknowledge launch", phase: :spawn, delivery: :possibly_sent) + end + rescue EOFError, Errno::ECONNRESET, Errno::EPIPE + raise OutcomeUnknown.new("program supervisor disconnected during launch", phase: :spawn, delivery: :possibly_sent) + end + + def open_candidate(name, target, budget) + path = File.join(@directory, "#{name}.sock") + @pending_target, @pending_listener = target, UNIXServer.new(path) + @pending_peer = @pending_pid = nil + @handshake = +"".b + begin + receipt = yield + rescue Error => failure + if failure.delivery == :not_sent + @pending_listener.close + @pending_listener = nil + end + raise + end + @pending_target = receipt.pane.id + claim_pending(budget) + guarded("set-option", ["-p", "-t", @pending_target, "remain-on-exit", "off"], + pane: @pending_target, pid: @pending_pid, **budget.options) + @pending_listener.close + File.unlink(path) + @pending_listener = nil + [receipt, @pending_peer, @pending_pid] + end + + def claim_pending(budget) + unless @pending_peer + wait_readable(@pending_listener, budget) + @pending_peer = @pending_listener.accept_nonblock + end + until @handshake.end_with?("\n") + wait_readable(@pending_peer, budget) + @handshake << @pending_peer.read_nonblock(32) + raise ProtocolError.new("invalid program helper identity", phase: :admission) if @handshake.bytesize > 24 + end + unless @handshake.match?(/\A[1-9]\d*\n\z/) + raise ProtocolError.new("invalid program helper PID", phase: :admission) + end + @pending_pid = Integer(@handshake, 10) + end + + def wait_readable(io, budget) + loop do + options = budget.options + timeout = options.fetch(:timeout) + timeout = [timeout, 0.02].min if options[:cancel] + if io.wait_readable(timeout) + budget.options + return + end + end + end + + def read_status + @result_lock.synchronize do + raise ClosedError.new("program is closing", phase: :retire) if @closing + raise @spawn_error if @spawn_error + return @exit if @exit + part = @peer.read_nonblock(48, exception: false) + return if part == :wait_readable + raise OutcomeUnknown.new("program supervisor closed before reporting exit", phase: :command, delivery: :possibly_sent) unless part + @status_bytes << part + raise ProtocolError.new("program supervisor sent an oversized result", phase: :decode) if @status_bytes.bytesize > 48 + return unless @status_bytes.end_with?("\n") + match = /\A(exit|signal|spawn) (\d+)\n\z/.match(@status_bytes) + raise ProtocolError.new("invalid program supervisor result", phase: :decode) unless match + value = Integer(match[2], 10) + if match[1] == "spawn" + @spawn_error = TransportError.new("terminal program could not start (errno #{value})", phase: :spawn, delivery: :not_sent) + raise @spawn_error + end + @exit = (match[1] == "exit") ? [value, nil] : [nil, value] + end + end + + def guarded(command, arguments, pane: @pane.id, pid: @pid, window: nil, **options) + # New sessions run a supervisor whose startup command includes a fresh + # directory. That directory accepts one peer and one launch only. + native = @server.method(:tmux_command) + nonce = "\#{m:*#{@nonce}*,\#{pane_start_command}}" + guard = "\#{&&:\#{==:\#{pane_pid},#{pid}},#{nonce}}" + guard = "\#{&&:#{guard},\#{==:\#{window_id},#{window}}}" if window + marker = "libtmux-replaced-#{SecureRandom.hex(12)}" + yes = native.call([@names.fetch(command), *arguments]) + no = native.call([@names.fetch("display-message"), "-p", "--", marker]) + result = @server.__send__(:execute_typed, [@names.fetch("if-shell"), "-F", "-t", pane, guard, yes, no], **options) + return result unless result.stdout == "#{marker}\n" + + raise TargetNotFoundError.new("terminal program target changed", phase: :command, delivery: :observed) + rescue CommandError => error + if (delivery = Internal::TmuxVersion.daemon_loss_delivery(error.result)) + raise TargetNotFoundError.new("the terminal program's tmux daemon stopped", phase: :command, delivery: delivery) + end + raise unless error.result.stderr.match?(/\A(?:can't find pane|no current target)/) + raise TargetNotFoundError.new("terminal program pane is gone", phase: :command, delivery: :observed) + end + + def ensure_open + raise ClosedError.new("program is closed", phase: :admission) if @closing || @closed || @creator != Process.pid + @server.__send__(:with_bound_endpoint) { nil } + end + end + + class Server + # Read the owned-program requirement and support decision from the bound daemon. + def program_support(timeout: 5.0, cancel: nil) + identity = bound_daemon_identity(timeout: timeout, cancel: cancel) + capability = Internal::Capabilities.capability("owned-terminal-program") + identity.merge(binding_key: @pin.key, since: capability.since, supported: capability.available?(@release)).freeze + end + + def start_program(argv, **options, &block) + LibTmux.start_program(argv, **options, server: self, &block) + end + + private + + def require_program_support(**options) + support = program_support(**options) + return if support.fetch(:supported) + + raise UnsupportedFeatureError.new("owned terminal programs require tmux #{support.fetch(:since)} or newer", + phase: :admission, delivery: :not_sent, expected: "owned-terminal-program") + end + end +end diff --git a/gems/libtmux/lib/libtmux/server.rb b/gems/libtmux/lib/libtmux/server.rb index cacd5f05..4b841978 100644 --- a/gems/libtmux/lib/libtmux/server.rb +++ b/gems/libtmux/lib/libtmux/server.rb @@ -213,10 +213,12 @@ def initialize(endpoint: nil, socket_path: nil, socket_name: nil, executable: "t @executor = Internal::ProcessExecutor.new @pin = Internal::SocketIdentity.new(@endpoint) begin - @release = Internal::TmuxVersion.connected(@pin.command_prefix) { |argv| @executor.run(argv, timeout: version_timeout, discard_stdout: true) } + @release = Internal::TmuxVersion.connected(@pin.command_prefix) do |argv| + @executor.run(argv, **version_probe_options(version_timeout), discard_stdout: true) + end @pin.record_release(@release) argv, marker = Internal::TmuxVersion.fence_check_argv - Internal::TmuxVersion.verify_fence(@executor.run(@pin.command_prefix + argv, timeout: version_timeout), marker) + Internal::TmuxVersion.verify_fence(@executor.run(@pin.command_prefix + argv, **version_probe_options(version_timeout)), marker) rescue Exception @pin.close raise @@ -410,6 +412,10 @@ def explain_panes(where: {}, pushdown: :auto) private + def version_probe_options(timeout) + {timeout: timeout} + end + class OperationBudget def initialize(timeout, cancel, clock) raise ArgumentError, "timeout must be finite" unless timeout.is_a?(Numeric) && timeout.finite? @@ -435,6 +441,11 @@ def options end private_constant :OperationBudget + def self.operation_budget(timeout, cancel) + OperationBudget.new(timeout, cancel, -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) }) + end + private_class_method :operation_budget + def operation_budget(timeout, cancel) OperationBudget.new(timeout, cancel, method(:monotonic)) end @@ -578,7 +589,7 @@ def bound_daemon_identity(timeout:, cancel:) end # Library operations that repair exact tmux 3.7's break-pane say so here. - def dispatch(argv, input: "".b, timeout: 5.0, cancel: nil, repaired_break: false) + def dispatch(argv, input: "".b, timeout: 5.0, cancel: nil, repaired_break: false, stdout_tail: nil) ensure_owner started = monotonic validate_argv(argv) @@ -588,14 +599,18 @@ def dispatch(argv, input: "".b, timeout: 5.0, cancel: nil, repaired_break: false perform_request(cancel: cancel) do |view| fence, marker = Internal::TmuxVersion.fence(@release) result = @executor.run(@pin.command_prefix + fence + argv, input: input, - timeout: timeout - (monotonic - started), cancel: view) + timeout: timeout - (monotonic - started), cancel: view, stdout_tail: stdout_tail) Internal::TmuxVersion.check_fence(result, marker, @release) end end - def execute_typed(arguments, repaired_break: false, **options) + def execute_typed(arguments, repaired_break: false, stdout_tail: nil, **options) arguments = encode_arguments(arguments) - result = repaired_break ? dispatch(arguments, repaired_break: true, **options) : run(arguments, **options) + result = if repaired_break || stdout_tail + dispatch(arguments, repaired_break: repaired_break, stdout_tail: stdout_tail, **options) + else + run(arguments, **options) + end unless result.success? message = "tmux #{arguments.first} failed" line = result.stderr.byteslice(0, 240).partition(/[\r\n]/).first diff --git a/gems/libtmux/lib/libtmux/text_wait.rb b/gems/libtmux/lib/libtmux/text_wait.rb index 48e58657..6991e2ad 100644 --- a/gems/libtmux/lib/libtmux/text_wait.rb +++ b/gems/libtmux/lib/libtmux/text_wait.rb @@ -77,7 +77,7 @@ def text_wait_frame(result, marker, pane_id) end # A failed capture can print hook output without reading the screen. - if stderr.match?(/\A(?:server exited unexpectedly\n|#{Internal::TmuxVersion::ABSENT})/) + if Internal::TmuxVersion.daemon_loss_delivery(result) return [nil, :server_gone] end if stderr.start_with?("no current target\n") || diff --git a/gems/libtmux/lib/libtmux/tmux_version.rb b/gems/libtmux/lib/libtmux/tmux_version.rb index fb63314f..03c64921 100644 --- a/gems/libtmux/lib/libtmux/tmux_version.rb +++ b/gems/libtmux/lib/libtmux/tmux_version.rb @@ -28,7 +28,8 @@ module TmuxVersion # sharing it, refuses the server instead of silently disabling the fence. FENCE_COMMAND = "if-shel" PROBE_COMMAND = "run-shel" - ABSENT = /no server running|error connecting to .*\((?:No such file or directory|Connection refused)\)/ + ABSENT = /\A(?:no server running(?: on [^\n]+)?|error connecting to [^\n]+ \((?:No such file or directory|Connection refused)\))\n?\z/n + private_constant :ABSENT # What a daemon older than 3.2 answers to the probe. run-shell gained -C # in 3.2, so 3.1 reports its usage line; a 3.0 daemon speaks a protocol # the client refuses before any command runs. @@ -117,7 +118,7 @@ def connected(prefix) raise UnsupportedFeatureError.new("tmux #{MINIMUM} or newer is required (the connected daemon is older than 3.2); #{REMEDY}", phase: :admission, expected: EXPECTED) end - if ABSENT.match?(stderr) + if daemon_loss_delivery(result) raise TargetNotFoundError.new("no tmux server is running at the selected endpoint", phase: :admission) end @@ -126,6 +127,13 @@ def connected(prefix) raise not_sent(error), cause: nil end + def daemon_loss_delivery(result) + return if result.success? + return :not_sent if result.stdout.empty? && ABSENT.match?(result.stderr.b) + + :possibly_sent if result.stderr == "server exited unexpectedly\n" + end + # Reads the executable that would start a new daemon. tmux 3.3a prints # its own file name where later releases print "tmux". def executable(path) diff --git a/gems/libtmux/libexec/program_child.rb b/gems/libtmux/libexec/program_child.rb new file mode 100644 index 00000000..5799bc33 --- /dev/null +++ b/gems/libtmux/libexec/program_child.rb @@ -0,0 +1,60 @@ +# frozen_string_literal: true + +# tmux starts this supervisor as the foreground process-group leader. Only the +# original socket peer can release the one-shot argv or keep the program alive. +require "socket" + +directory, title = ARGV +if title == "prepare" + begin + UNIXSocket.open(File.join(directory, "prepare.sock")) do |socket| + socket.puts(Process.pid) + socket.read(1) + end + rescue Errno::ENOENT, Errno::ECONNREFUSED, Errno::ECONNRESET + # The launching owner has already unwound. + end + exit +end +exit 1 unless Process.getpgrp == Process.pid +begin + owner = UNIXSocket.new(File.join(directory, "owner.sock")) +rescue Errno::ENOENT, Errno::ECONNREFUSED + exit 1 +end +owner.close_on_exec = true +# Terminal-generated signals also reach the supervisor. Caught dispositions +# revert to their defaults when the worker execs. +%w[HUP INT QUIT TSTP].each { |signal| Signal.trap(signal) {} } +begin + owner.puts(Process.pid) + exit unless owner.read(1) == "G" + command_file = File.join(directory, "argv") + argv = File.binread(command_file).split("\0".b, -1) + File.unlink(command_file) + Dir.rmdir(directory) + owner.write("A") + begin + child = Process.spawn([argv.first, argv.first], *argv.drop(1), close_others: true) + rescue SystemCallError => error + owner.puts("spawn #{error.errno}") + else + loop do + if (observed = Process.waitpid2(child, Process::WNOHANG)) + status = observed.last + # CAN ends any unfinished escape. tmux parses the uppercase title after + # preceding output, and the title survives PTY uppercase conversion. + STDOUT.syswrite("\x18\e]2;#{title}\a") + owner.puts(status.signaled? ? "signal #{status.termsig}" : "exit #{status.exitstatus}") + break + end + exit if IO.select([owner], nil, nil, 0.01) + end + end + owner.read(1) # Keep the process generation live until close or owner death. +rescue Errno::EPIPE, Errno::ECONNRESET, Errno::EIO + # The owner or terminal disappeared. +ensure + owner.close + Process.kill("KILL", 0) # Our live process still pins this process group. +end diff --git a/gems/libtmux/libtmux.gemspec b/gems/libtmux/libtmux.gemspec index 2c9d68c6..8edab0c4 100644 --- a/gems/libtmux/libtmux.gemspec +++ b/gems/libtmux/libtmux.gemspec @@ -45,6 +45,8 @@ Gem::Specification.new do |spec| lib/libtmux/socket_readiness.rb lib/libtmux/terminal.rb lib/libtmux/text_wait.rb + lib/libtmux/program.rb + libexec/program_child.rb lib/libtmux/criteria.rb lib/libtmux/process_wait.rb lib/libtmux/native_guard.rb @@ -56,6 +58,7 @@ Gem::Specification.new do |spec| sig/group.rbs sig/owned.rbs sig/terminal.rbs + sig/program.rbs sig/fields.rbs schema/where-v1.json ] diff --git a/gems/libtmux/sig/program.rbs b/gems/libtmux/sig/program.rbs new file mode 100644 index 00000000..5e76248f --- /dev/null +++ b/gems/libtmux/sig/program.rbs @@ -0,0 +1,47 @@ +module LibTmux + def self.start_program: (Array[String], ?server: Server?, ?executable: String, ?cwd: String?, ?environment: Hash[String, String], ?width: Integer, ?height: Integer, ?history_lines: Integer, ?timeout: Numeric, ?cancel: untyped) -> Program + | [T] (Array[String], ?server: Server?, ?executable: String, ?cwd: String?, ?environment: Hash[String, String], ?width: Integer, ?height: Integer, ?history_lines: Integer, ?timeout: Numeric, ?cancel: untyped) { (Program) -> T } -> T + def self.run_program: (Array[String], ?server: Server?, ?executable: String, ?cwd: String?, ?environment: Hash[String, String], ?width: Integer, ?height: Integer, ?history_lines: Integer, ?timeout: Numeric, ?cancel: untyped) -> Program::Result + + class Server + def program_support: (?timeout: Numeric, ?cancel: untyped) -> {binding_key: String, pid: Integer, start_time: Integer, version: String, since: String, supported: bool} + def start_program: (Array[String], ?cwd: String?, ?environment: Hash[String, String], ?width: Integer, ?height: Integer, ?history_lines: Integer, ?timeout: Numeric, ?cancel: untyped) -> Program + | [T] (Array[String], ?cwd: String?, ?environment: Hash[String, String], ?width: Integer, ?height: Integer, ?history_lines: Integer, ?timeout: Numeric, ?cancel: untyped) { (Program) -> T } -> T + end + + class Program + private def self.new: (*untyped, **untyped) -> instance + + SCREEN_BYTES: Integer + MAX_WIDTH: Integer + MAX_HEIGHT: Integer + + class ScreenGeometryError < CapacityError + end + + class Screen + private def self.new: (*untyped) -> instance + attr_reader text: String + def truncated?: () -> bool + def inspect: () -> String + end + + class Result + private def self.new: (*untyped, **untyped) -> instance + attr_reader exit_status: Integer? + attr_reader signal: Integer? + attr_reader screen: String + def screen_truncated?: () -> bool + def inspect: () -> String + end + + def wait: (?timeout: Numeric, ?cancel: untyped) -> Result + def capture_screen: (?timeout: Numeric, ?cancel: untyped) -> Screen + def screen: (?timeout: Numeric, ?cancel: untyped) -> String + def send_text: (String, ?timeout: Numeric, ?cancel: untyped) -> CommandResult + def send_keys: (*String, ?timeout: Numeric, ?cancel: untyped) -> CommandResult + def resize: (width: Integer, height: Integer, ?timeout: Numeric, ?cancel: untyped) -> CommandResult + def close: () -> nil + def inspect: () -> String + end +end diff --git a/scripts/types b/scripts/types index 0b461bef..1433dd26 100755 --- a/scripts/types +++ b/scripts/types @@ -19,7 +19,7 @@ class PublicAPI @specs.each { |spec| loader.add(path: Pathname(File.join(spec.full_gem_path, "sig"))) } signatures.each { |path| loader.add(path: Pathname(path)) } @builder = RBS::DefinitionBuilder.new(env: RBS::Environment.from_loader(loader).resolve_type_names) - @exports = [] + @exports = [LibTmux] collect(LibTmux) end diff --git a/test/integration/program_test.rb b/test/integration/program_test.rb new file mode 100644 index 00000000..ee5f2d10 --- /dev/null +++ b/test/integration/program_test.rb @@ -0,0 +1,722 @@ +# frozen_string_literal: true + +require_relative "../test_helper" +require_relative "../support/stub_executable" +require "libtmux/async" +require "rbconfig" +require "open3" +require "socket" + +class ProgramTest < Minitest::Test + def test_program_admission_precedes_launch + assert_program_admission(LibTmux.method(:start_program)) + Async { assert_program_admission(LibTmux::Async.method(:start_program)) }.wait + end + + def test_adapter_is_private_to_the_factories + assert_raises ArgumentError do + LibTmux.start_program(["/bin/true"], adapter: nil, executable: executable) { nil } + end + + Async do + assert_raises ArgumentError do + LibTmux::Async.start_program(["/bin/true"], adapter: nil, executable: executable) { nil } + end + end.wait + end + + def test_borrowed_daemon_keeps_its_other_sessions_and_configuration + LibTmux::Server.start(executable: executable) do |server| + next unless require_program_support(LibTmux.method(:run_program), server: server) + + neighbor = server.new_session(name: "neighbor", command: ["/bin/cat"]) + original = server.options(scope: :window).get("remain-on-exit").raw + result = LibTmux.run_program([RbConfig.ruby, "-e", 'puts "final café"; exit 7'], server: server) + assert_equal 7, result.exit_status + refute_predicate result, :screen_truncated? + assert_includes result.screen, "final café" + assert_equal [neighbor.id], server.list_sessions.map(&:id) + assert_equal original, server.options(scope: :window).get("remain-on-exit").raw + end + end + + def test_borrowed_handoff_retires_the_preparation_pane_before_publication + LibTmux::Server.start(executable: executable) do |server| + next unless require_program_support(server.method(:start_program)) + + neighbor = server.new_session(name: "neighbor", command: ["/bin/cat"]).list_panes.first + hold_preparation_peer do |held| + server.start_program(["/bin/cat"]) do |program| + assert_equal 2, server.list_panes.length, "public handoff left the preparation pane" + prepare_peer = held.call + assert prepare_peer.wait_readable(1), "preparation helper still owns the peer" + assert_nil prepare_peer.read_nonblock(1, exception: false) + assert_nil program.close + assert_equal [neighbor.id], server.list_panes.map(&:id) + end + end + end + end + + def test_borrowed_cancellation_retires_admitted_preparation + LibTmux::Server.start(executable: executable) do |server| + next unless require_program_support(server.method(:start_program)) + + neighbor = server.new_session(name: "neighbor", command: ["/bin/cat"]) + token = LibTmux::Cancellation.new + native = server.method(:create_window) + server.define_singleton_method(:create_window) do |reference, **options| + token.cancel + native.call(reference, **options) + end + hold_preparation_peer do |held| + failure = assert_raises(LibTmux::Cancelled) { server.start_program(["/bin/true"], cancel: token) } + assert_equal :not_sent, failure.delivery + assert_empty failure.cleanup_errors + assert_equal [neighbor.id], server.list_sessions.map(&:id) + prepare_peer = held.call + assert prepare_peer.wait_readable(1), "cancelled launch left the preparation peer open" + assert_nil prepare_peer.read_nonblock(1, exception: false) + end + ensure + token&.close + end + end + + def test_private_session_retains_history_when_borrowed_daemon_defaults_to_zero + LibTmux::Server.start(executable: executable) do |server| + next unless require_program_support(LibTmux.method(:run_program), server: server) + + server.options(scope: :session).set("history-limit", 0) + neighbor = server.new_session(name: "neighbor", command: ["/bin/cat"]) + app = 'puts "retained café"; 55.times { puts "next line" }; exit 7' + result = LibTmux.run_program([RbConfig.ruby, "-e", app], server: server, height: 8) + assert_equal 7, result.exit_status + assert_includes result.screen, "retained café" + assert_equal "0", neighbor.display("\#{history_limit}").text.chomp + assert_equal "0", server.options(scope: :session).get("history-limit").raw + end + end + + def test_custom_retention_captures_only_the_requested_history + argv = [RbConfig.ruby, "-e", 'puts "first marker"; 40.times { puts "row" }; puts "last marker"'] + assert_raises(ArgumentError) { LibTmux.start_program(argv, executable: executable, history_lines: 101) } + return unless require_program_support(LibTmux.method(:run_program)) + + result = LibTmux.run_program(argv, executable: executable, height: 4, history_lines: 0) + refute_includes result.screen, "first marker" + assert_includes result.screen, "last marker" + end + + def test_cancellation_after_creation_removes_a_pane_that_would_be_retained + LibTmux::Server.start(executable: executable) do |server| + next unless require_program_support(server.method(:start_program)) + + neighbor = server.new_session(name: "neighbor", command: ["/bin/cat"]) + server.options(scope: :window).set("remain-on-exit", true) + token = LibTmux::Cancellation.new + native = server.method(:new_session) + server.define_singleton_method(:new_session) do |**args| + native.call(**args).tap { token.cancel } + end + assert_raises(LibTmux::Cancelled) { server.start_program(["/bin/true"], cancel: token) } + assert_equal [neighbor.id], server.list_sessions.map(&:id) + assert_equal "on", server.options(scope: :window).get("remain-on-exit").raw + ensure + token&.close + end + end + + def test_a_respawned_pane_cannot_receive_input_or_be_destroyed_by_the_old_owner + LibTmux::Server.start(executable: executable) do |server| + next unless require_program_support(LibTmux.method(:start_program), server: server) + + program = LibTmux.start_program(["/bin/cat"], server: server) + pane = server.list_panes.fetch(0) + pane.respawn(command: ["/bin/cat"], kill: true) + assert_raises(LibTmux::TargetNotFoundError) { program.send_text("belongs to the old program") } + assert_raises(LibTmux::TargetNotFoundError) { program.wait } + program.close + assert_equal [pane.id], server.list_panes.map(&:id) + refute_includes pane.capture.text, "belongs to the old program" + ensure + program&.close + end + end + + def test_an_active_program_loses_its_daemon_without_touching_a_replacement + LibTmux::Server.start(executable: executable) do |replacement| + next unless require_program_support(replacement.method(:start_program)) + + witness = replacement.new_session(name: "witness", command: ["/bin/cat"]).list_panes.first + socket = daemon_pid = source = program = nil + LibTmux::Server.start(executable: executable) do |original| + socket = original.endpoint.socket_path + daemon_pid = original.program_support.fetch(:pid) + source = LibTmux::Server.open(socket_path: socket, executable: executable) + program = source.start_program(["/bin/cat"]) + end + assert_raises(Errno::ECHILD) { Process.waitpid(daemon_pid, Process::WNOHANG) } + recreated = Dir.mkdir(File.dirname(socket), 0o700) + File.link(replacement.endpoint.socket_path, socket) + + failure = assert_raises(LibTmux::TargetNotFoundError) { program.wait } + assert_equal :not_sent, failure.delivery + assert_raises(LibTmux::TargetNotFoundError) { program.send_text("do not dispatch") } + assert_nil program.close + assert_nil program.close + assert File.identical?(replacement.endpoint.socket_path, socket) + assert_equal [witness.id], replacement.list_panes.map(&:id) + refute_includes witness.capture.text, "do not dispatch" + ensure + begin + program&.close + ensure + source&.close + if recreated + File.unlink(socket) if File.socket?(socket) + Dir.rmdir(File.dirname(socket)) + end + end + end + end + + def test_daemon_disconnect_leaves_in_flight_input_and_retirement_uncertain + [ + ["after-send-keys", ->(program) { program.send_text("input before daemon exit") }], + ["after-kill-pane", ->(program) { program.close }] + ].each do |hook, dispatch| + LibTmux::Server.start(executable: executable) do |source| + next unless require_program_support(source.method(:start_program)) + + source.new_session(name: "witness", command: ["/bin/cat"]) + daemon_pid = source.program_support.fetch(:pid) + source.start_program(["/bin/cat"]) do |program| + source.hooks.set(hook, command: "wait-for -S program-dispatched ; wait-for program-client-held") + request = Thread.new do + dispatch.call(program) + rescue LibTmux::Error => error + error + end + source.wait_for("program-dispatched") + assert request.alive?, "native client completed while the #{hook} hook was held" + Process.kill("KILL", daemon_pid) + assert request.join(2), "client did not observe daemon disconnect" + failure = request.value + assert_instance_of LibTmux::TargetNotFoundError, failure + assert_equal :possibly_sent, failure.delivery + assert_equal :command, failure.phase + assert_nil program.close + ensure + request&.join + end + end + end + end + + def test_same_start_command_respawn_cannot_reuse_a_completed_generation + LibTmux::Server.start(executable: executable) do |server| + next unless require_program_support(server.method(:start_program)) + + program = server.start_program(["/bin/cat"]) + pane = server.list_panes.fetch(0) + pane.options.set("remain-on-exit", true) + server.run(["respawn-pane", "-k", "-t", pane.id]) + deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 2 + until pane.display("\#{pane_dead}").text.chomp == "1" + flunk "replacement did not exit" if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline + sleep 0.01 + end + assert_raises(LibTmux::TargetNotFoundError) { program.screen } + program.close + assert_equal [pane.id], server.list_panes.map(&:id) + ensure + program&.close + end + end + + def test_resize_refuses_when_the_pane_leaves_its_owned_window + LibTmux::Server.start(executable: executable) do |server| + next unless require_program_support(server.method(:start_program)) + + neighbor = server.new_session(name: "neighbor", command: ["/bin/cat"]).list_panes.first + server.start_program(["/bin/cat"]) do |program| + pane = server.list_panes.find { |candidate| candidate.id != neighbor.id } + original_window = pane.display('#{window_id}').text + assert server.run(["split-window", "-d", "-t", pane.id, "/bin/cat"]).success? + sizes = -> { server.run(["list-windows", "-a", "-F", '#{window_id}:#{window_width}x#{window_height}']).text } + pane.move(neighbor.ref, direction: :vertical) + assert_equal neighbor.display('#{window_id}').text, pane.display('#{window_id}').text + refute_equal original_window, pane.display('#{window_id}').text + before = sizes.call + + assert_raises(LibTmux::TargetNotFoundError) { program.resize(width: 99, height: 31) } + assert_raises(ArgumentError) { program.resize(width: 99, height: 31, window: nil) } + assert_equal before, sizes.call + end + end + end + + def test_screen_and_wait_preserve_completion_across_external_geometry_refusal + LibTmux::Server.start(executable: executable) do |server| + next unless require_program_support(server.method(:start_program)) + + neighbor = server.new_session(name: "wide", command: ["/bin/cat"], width: 1025, height: 300).list_panes.first + script = 'STDIN.readline; puts "final marker"; exit 7' + server.start_program([RbConfig.ruby, "-e", script]) do |program| + pane = server.list_panes.find { |candidate| candidate.id != neighbor.id } + pane.move(neighbor.ref, direction: :horizontal) + width, height = pane.display('#{pane_width} #{pane_height}').text.split.map(&:to_i) + assert_operator width, :>, 256 + assert_operator height, :>, 100 + server.hooks.set("after-capture-pane", command: "set-option -gq @program-capture-ran yes") + + failure = assert_raises(LibTmux::CapacityError) { program.capture_screen } + assert_instance_of LibTmux::Program::ScreenGeometryError, failure + assert_equal :admission, failure.phase + assert_equal :not_sent, failure.delivery + assert_match(/256 columns.*100 rows/, failure.message) + program.send_keys("Enter") + assert_raises(LibTmux::CapacityError) { program.wait } + assert_empty server.run(["show-options", "-gqv", "@program-capture-ran"]).text + + destination = pane.display('#{window_id}').text.strip + assert server.run(["resize-window", "-t", destination, "-x", "192", "-y", "99"]).success? + result = program.wait + assert_equal 7, result.exit_status + assert_includes result.screen, "final marker" + assert_equal "yes\n", server.run(["show-options", "-gqv", "@program-capture-ran"]).text + end + assert_equal [neighbor.id], server.list_panes.map(&:id) + end + end + + def test_closing_retires_a_descendant_that_ignores_hangup + return unless require_program_support + + Dir.mktmpdir("libtmux-ruby-program-") do |directory| + ready = File.join(directory, "ready") + escaped = File.join(directory, "escaped") + source = <<~RUBY + fork do + Signal.trap("HUP", "IGNORE") + Signal.trap("TERM", "IGNORE") + File.write(ARGV[0], "ready") + sleep 0.8 + File.write(ARGV[1], "survived close") + end + sleep 2 + RUBY + LibTmux.start_program([RbConfig.ruby, "-e", source, ready, escaped], executable: executable) do + deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 3 + until File.exist?(ready) + flunk "descendant did not start" if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline + sleep 0.01 + end + end + sleep 0.9 + refute_path_exists escaped + end + end + + def test_outer_exception_does_not_hide_cleanup_failure + return unless require_program_support + + cleanup_failure = LibTmux::TransportError.new("retirement failed") + begin + raise "outer failure" + rescue RuntimeError + actual = assert_raises(LibTmux::TransportError) do + LibTmux.start_program(["/bin/true"], executable: executable) do |program| + original = program.method(:close) + program.define_singleton_method(:close) do + original.call + raise cleanup_failure + end + :block_succeeded + end + end + assert_same cleanup_failure, actual + end + end + + def test_fast_exit_keeps_literal_argv_and_final_utf8 + return unless require_program_support + + argv = [RbConfig.ruby, "-e", 'puts ARGV.map(&:inspect); puts "fin café"; exit 7', "", "a; $HOME"] + program = LibTmux.start_program(argv, executable: executable) + result = program.wait + assert_equal 7, result.exit_status + assert_nil result.signal + assert_includes result.screen, '""' + assert_includes result.screen, '"a; $HOME"' + assert_includes result.screen, "fin café" + assert_equal Encoding::UTF_8, result.screen.encoding + assert result.frozen? + refute_includes result.inspect, "café" + assert_includes result.inspect, "screen_bytes=" + ensure + program&.close + end + + def test_signal_has_no_numeric_exit + return unless require_program_support(LibTmux.method(:run_program)) + + result = LibTmux.run_program( + [RbConfig.ruby, "-e", 'Process.kill("TERM", Process.pid)'], executable: executable + ) + assert_nil result.exit_status + assert_equal Signal.list.fetch("TERM"), result.signal + end + + def test_async_wait_cancellation_leaves_input_and_other_waiters_available + Async do |task| + next unless require_program_support(LibTmux::Async.method(:start_program)) + + app = <<~'APP' + require "io/console" + $stdout.sync = true + puts "Name?" + name = STDIN.gets.chomp + puts "Hello, #{name}! #{IO.console.winsize.join("x")}" + APP + + captured = nil + LibTmux::Async.start_program([RbConfig.ruby, "-e", app], executable: executable) do |program| + captured = program + ready = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 0.9 + until program.screen.lines(chomp: true).include?("Name?") + flunk "program did not show its prompt" if Process.clock_gettime(Process::CLOCK_MONOTONIC) > ready + end + + cancel = LibTmux::Cancellation.new + begin + first = task.async { assert_raises(LibTmux::Cancelled) { program.wait(cancel: cancel) } } + second = task.async { program.wait } + cancel.close + first.wait + refute second.finished? + + program.resize(width: 50, height: 18) + program.send_text("Ada") + program.send_keys("Enter") + result = second.wait + assert_equal 0, result.exit_status + assert_includes result.screen, "Hello, Ada! 18x50" + assert_same result, program.wait + ensure + cancel.close + end + end + + assert_raises(LibTmux::ClosedError) { captured.screen } + end.wait + end + + def test_terminal_eof_does_not_complete_a_live_process + return unless require_program_support(LibTmux.method(:run_program)) + + app = <<~'RUBY' + Signal.trap("HUP", "IGNORE") + puts "closed café" + [STDIN, STDOUT, STDERR].each(&:close) + sleep 0.2 + exit 7 + RUBY + result = LibTmux.run_program([RbConfig.ruby, "-e", app], executable: executable) + assert_equal 7, result.exit_status + assert_includes result.screen, "closed café" + end + + def test_completion_drains_output_with_linux_uppercase_postprocessing + skip "requires Linux PTY output case conversion" unless RUBY_PLATFORM.include?("linux") + + script = 'exit 20 unless system("stty", "opost", "olcuc"); puts "final marker"; exit 7' + argv = [RbConfig.ruby, "-e", script] + if require_program_support(LibTmux.method(:run_program)) + result = LibTmux.run_program(argv, executable: executable, timeout: 2) + assert_equal 7, result.exit_status + assert_includes result.screen, "FINAL MARKER" + end + Async do + next unless require_program_support(LibTmux::Async.method(:run_program)) + + result = LibTmux::Async.run_program(argv, executable: executable, timeout: 2) + assert_equal 7, result.exit_status + assert_includes result.screen, "FINAL MARKER" + end.wait + end + + def test_final_screen_is_a_bounded_valid_utf8_tail + return unless require_program_support(LibTmux.method(:run_program)) + + app = '280.times { puts "é" * 240 }; puts "fin café"' + result = LibTmux.run_program( + [RbConfig.ruby, "-e", app], executable: executable, width: 256, height: 100 + ) + assert_equal 0, result.exit_status + assert_predicate result, :screen_truncated? + assert_includes 65_535..65_536, result.screen.bytesize + assert_predicate result.screen, :valid_encoding? + assert_includes result.screen, "fin café" + assert result.screen.frozen? + end + + def test_dense_combining_cells_keep_the_same_final_tail_as_native_capture + # tmux 3.7 takes several seconds to compose these cells. + script = '160.times { puts ("x" + "\u{1D167}" * 7) * 256 }; puts "fin café"; exit 7' + LibTmux::Server.start(executable: executable) do |server| + next unless require_program_support(server.method(:start_program)) + + server.start_program([RbConfig.ruby, "-e", script], width: 256, height: 100) do |program| + result = program.wait(timeout: 20) + capture = ["capture-pane", "-p", "-S", "-100", "-t", server.list_panes.fetch(0).id] + assert_raises(LibTmux::CapacityError) { server.run(capture) } + native, status = Open3.capture2(executable, "-N", "-S", server.endpoint.socket_path, *capture, binmode: true) + + assert status.success? + assert_operator native.bytesize, :>, 1 << 20 + assert_equal 7, result.exit_status + assert_predicate result, :screen_truncated? + tail = native.byteslice(-65_536, 65_536).force_encoding(Encoding::UTF_8) + refute_predicate tail, :valid_encoding? + assert_predicate result.screen, :valid_encoding? + assert_equal tail.scrub(""), result.screen + assert_includes result.screen, "fin café" + end + end + end + + def test_cancelled_setup_does_not_yield_an_owner + cancel = LibTmux::Cancellation.new + cancel.cancel + assert_raises LibTmux::Cancelled do + LibTmux.start_program(["/bin/true"], executable: executable, cancel: cancel) do + flunk "cancelled launch yielded an owner" + end + end + ensure + cancel&.close + end + + def test_async_close_retries_when_scope_reports_incomplete_retirement + LibTmux::Server.start(executable: executable) do |server| + Async do + next unless require_program_support(LibTmux::Async.method(:start_program), server: server) + + neighbor = server.new_session(name: "neighbor", command: ["/bin/cat"]) + program = LibTmux::Async.start_program(["/bin/cat"], server: server) + scope = program.instance_variable_get(:@scope) + original = scope.method(:close) + failed = false + scope.define_singleton_method(:close) do + original.call + unless failed + failed = true + raise LibTmux::TransportError.new("scope retirement incomplete", phase: :retire, + cleanup_errors: ["test request owner still pending"]) + end + end + failure = assert_raises(LibTmux::TransportError) { program.close } + assert_equal ["test request owner still pending"], failure.cleanup_errors + assert_nil program.close + assert_nil program.close + assert_equal [neighbor.id], server.list_sessions.map(&:id) + end.wait + end + end + + def test_wait_racing_close_reports_a_typed_lifecycle_error + LibTmux::Server.start(executable: executable) do |server| + next unless require_program_support(server.method(:start_program)) + + program = server.start_program(["/bin/cat"]) + read_started = Queue.new + resume_wait = Queue.new + original = program.method(:read_status) + program.define_singleton_method(:read_status) do + read_started << true + resume_wait.pop(timeout: 2) || raise("the test did not release the status read") + original.call + end + waiter = Thread.new do + program.wait(timeout: 2) + rescue => error + error + end + assert read_started.pop(timeout: 1), "waiter did not reach status read" + assert_nil program.close + resume_wait << true + assert waiter.join(2) + assert_instance_of LibTmux::ClosedError, waiter.value + ensure + resume_wait << true if resume_wait + waiter&.join(2) + program&.close + end + end + + def test_terminal_interrupt_is_reported_as_the_program_signal + return unless require_program_support + + app = 'STDOUT.sync = true; puts "ready"; exec "/bin/cat"' + LibTmux.start_program([RbConfig.ruby, "-e", app], executable: executable) do |program| + deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 2 + until program.screen.include?("ready") + flunk "program did not reach input" if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline + end + program.send_keys("C-c") + result = program.wait + assert_nil result.exit_status + assert_equal Signal.list.fetch("INT"), result.signal + end + end + + def test_forked_child_closes_its_descriptor_copy_without_retiring_the_program + return unless require_program_support + + LibTmux.start_program(["/bin/cat"], executable: executable) do |program| + pid = fork do + begin + program.close + program.screen + rescue LibTmux::ClosedError + exit! 0 + end + exit! 1 + end + assert_predicate Process.waitpid2(pid).last, :success? + program.send_text("owner still has its terminal") + capture = program.capture_screen + assert_instance_of LibTmux::Program::Screen, capture + refute_predicate capture, :truncated? + assert_predicate capture.text, :frozen? + refute_includes capture.inspect, "owner still has its terminal" + end + end + + def test_cwd_and_environment_are_passed_to_the_terminal + return unless require_program_support(LibTmux.method(:run_program)) + + Dir.mktmpdir("libtmux-ruby-program-") do |directory| + app = 'puts Dir.pwd; puts ENV.fetch("CHOICE")' + result = LibTmux.run_program([RbConfig.ruby, "-e", app], + executable: executable, cwd: directory, environment: {"CHOICE" => "green; $HOME"}) + assert_equal 0, result.exit_status + assert_includes result.screen, File.realpath(directory) + assert_includes result.screen, "green; $HOME" + end + end + + def test_owning_run_retires_when_the_wait_times_out + return unless require_program_support(LibTmux.method(:run_program)) + + assert_raises LibTmux::DeadlineExceeded do + LibTmux.run_program(["/bin/cat"], executable: executable, timeout: 0.8) + end + end + + def test_startup_deadline_retires_the_delayed_version_probe + with_delayed_binding("libtmux-version-") do |wrapper, notice, completed| + assert_raises(LibTmux::DeadlineExceeded) do + LibTmux.run_program(["/bin/true"], executable: wrapper, timeout: 0.6) + end + assert notice.wait_readable(0), "the owned daemon did not reach its binding probe" + notice.accept.close + refute_path_exists completed + end + end + + def test_async_startup_cancellation_retires_the_delayed_fence_probe + with_delayed_binding("libtmux-fence-") do |wrapper, notice, completed| + token = LibTmux::Cancellation.new + Async do |parent| + canceller = parent.async do + raise "the owned daemon did not reach its fence probe" unless notice.wait_readable(4) + notice.accept.close + token.cancel + end + assert_raises(LibTmux::Cancelled) do + LibTmux::Async.run_program(["/bin/true"], executable: wrapper, timeout: 4, cancel: token) + end + canceller.wait + refute_path_exists completed + ensure + canceller&.stop + end.wait + ensure + token&.close + end + end + + private + + def assert_program_admission(launch) + Dir.mktmpdir("libtmux-ruby-program-") do |directory| + marker = File.join(directory, "launched") + argv = [RbConfig.ruby, "-e", 'File.write(ARGV.fetch(0), "started")', marker] + if require_program_support(launch, argv: argv) + launch.call(argv, executable: executable) { |program| assert_equal 0, program.wait.exit_status } + assert_equal "started", File.read(marker) + else + refute_path_exists marker + end + end + end + + # Below the minimum, exercise admission through the same public factory. + def require_program_support(launch = LibTmux.method(:start_program), argv: ["/bin/true"], **options) + return true if supported? + + error = assert_raises(LibTmux::UnsupportedFeatureError) do + launch.call(argv, executable: executable, **options) { flunk "yielded a program owner" } + end + assert_equal [:admission, :not_sent], [error.phase, error.delivery] + assert_match(/owned terminal programs require tmux 3\.7 or newer/, error.message) + false + end + + def hold_preparation_peer + peer = nil + # A descriptor copy keeps the helper's read pending after the owner closes. + trace = TracePoint.new(:return) do |event| + next unless event.defined_class == LibTmux::Program && event.method_id == :open_candidate + next unless event.binding.local_variable_get(:name) == "prepare" + + peer = event.return_value.fetch(1).dup + end + trace.enable { yield -> { peer } } + ensure + peer&.close + end + + def with_delayed_binding(marker) + Dir.mktmpdir("libtmux-ruby-bind-") do |directory| + completed = File.join(directory, "completed") + UNIXServer.open(File.join(directory, "ready")) do |notice| + probe = {TMUX_EXE: executable, MARKER: marker, NOTICE: notice.path, COMPLETED: completed} + wrapper = LibTmuxTest::StubExecutable.write(File.join(directory, "tmux"), <<~RUBY, **probe) + require "socket" + if ARGV.any? { |arg| arg.include?(MARKER) } + UNIXSocket.open(NOTICE).close + sleep 1.5 + File.write(COMPLETED, "probe finished") + end + exec(TMUX_EXE, *ARGV) + RUBY + yield wrapper, notice, completed + end + end + end + + def supported? + banner, status = Open3.capture2(executable, "-V") + assert status.success? + LibTmux::Internal::TmuxVersion.parse(banner.delete_prefix("tmux ").strip) >= + LibTmux::Internal::TmuxVersion.parse("3.7") + end + + def executable + ENV.fetch("LIBTMUX_TEST_TMUX", "tmux") + end +end diff --git a/test/types/consumer.rb b/test/types/consumer.rb index 1c63059f..4854f51c 100644 --- a/test/types/consumer.rb +++ b/test/types/consumer.rb @@ -68,14 +68,32 @@ def verify_rejects_wrong_return(value = Object.new) consumer = SignatureConsumer.new LibTmux::Server.start(executable: ENV.fetch("LIBTMUX_TEST_TMUX", "tmux")) do |server| + programs = consumer.call("::LibTmux::Server", server, :program_support, + expected: "{binding_key: String, pid: Integer, start_time: Integer, version: String, since: String, supported: bool}") + supports_programs = programs.fetch(:supported) case package when "libtmux" + if supports_programs + consumer.call("::LibTmux::Server", server, :start_program, ["/bin/true"], expected: ":checked") do |program| + result = consumer.call("::LibTmux::Program", program, :wait, expected: "::LibTmux::Program::Result") + capture = consumer.call("::LibTmux::Program", program, :capture_screen, expected: "::LibTmux::Program::Screen") + consumer.call("::LibTmux::Program::Screen", capture, :text, expected: "String") + consumer.call("::LibTmux::Program::Screen", capture, :truncated?, expected: "bool") + consumer.call("::LibTmux::Program::Result", result, :screen_truncated?, expected: "bool") + consumer.call("::LibTmux::Program::Result", result, :exit_status, expected: "Integer") + consumer.call("::LibTmux::Program::Result", result, :screen, expected: "String") + :checked + end + end capabilities = consumer.call("::LibTmux::Server", server, :capabilities, expected: "::LibTmux::Capabilities") consumer.verify_rejects_wrong_return feature = consumer.call("::LibTmux::Capabilities", capabilities, :feature, "layout-json", expected: "::LibTmux::Capabilities::Feature") consumer.call("::LibTmux::Capabilities::Feature", feature, :supported?, expected: "bool") consumer.call("::LibTmux::Capabilities", capabilities, :supports?, "control-mode", expected: "bool") + unless capabilities.feature("owned-terminal-program").supported? == supports_programs + raise "owned program discovery disagrees with admission" + end consumer.call("::LibTmux::Server", server, :diagnostics, expected: "{admitted_requests: Integer, reserved_process_slots: Integer, control_connections: Integer, closed: bool, limits: Hash[Symbol, Numeric]}") receipt = consumer.call("::LibTmux::Server", server, :new_session, name: "types", command: ["/bin/cat"], receipt: true, @@ -147,6 +165,11 @@ def verify_rejects_wrong_return(value = Object.new) session = server.new_session(name: "async-types", command: ["/bin/cat"]) control_daemon = server.supports_control? Async do |parent| + if supports_programs + consumer.call("singleton(::LibTmux::Async)", LibTmux::Async, :run_program, + ["/bin/true"], parent: parent, server: server, + expected: "::LibTmux::Program::Result") + end consumer.call("singleton(::LibTmux::Async)", LibTmux::Async, :open, parent: parent, server: server, expected: ":checked") do |scope| consumer.call("::LibTmux::Async::Server", scope.server, :capabilities, expected: "::LibTmux::Capabilities") facade = consumer.call("::LibTmux::Async::Scope", scope, :server, expected: "::LibTmux::Async::Server") diff --git a/test/unit/tmux_version_test.rb b/test/unit/tmux_version_test.rb index 928f440d..03fe7c15 100644 --- a/test/unit/tmux_version_test.rb +++ b/test/unit/tmux_version_test.rb @@ -263,14 +263,15 @@ def test_the_json_layout_floor_is_tmux_3_8_and_the_refusal_names_it def test_connected_probe_separates_an_absent_server_from_other_failures ["no server running on /tmp/route\n", "error connecting to /tmp/route (No such file or directory)\n", - "error connecting to /tmp/route (Connection refused)\n"].each do |stderr| + "error connecting to /tmp/route (Connection refused)\n", "server exited unexpectedly\n"].each do |stderr| error = assert_raises(LibTmux::TargetNotFoundError, stderr) do version.connected(["tmux"]) { Report.new(stdout: "", stderr: stderr, ok: false) } end assert_equal :not_sent, error.delivery end [["", "error connecting to /tmp/route (Permission denied)\n", false], ["3.3a\n", "", true], - ["", "unknown command: other3.3a\n", false], ["", "", true]].each do |stdout, stderr, ok| + ["", "unknown command: other3.3a\n", false], ["", "unknown command: no server running\n", false], + ["", "", true]].each do |stdout, stderr, ok| error = assert_raises(LibTmux::CommandError, stderr) do version.connected(["tmux"]) { Report.new(stdout: stdout, stderr: stderr, ok: ok) } end @@ -279,6 +280,13 @@ def test_connected_probe_separates_an_absent_server_from_other_failures end end + def test_daemon_disconnect_can_follow_partial_output + disconnected = Report.new(stdout: "partial\n", stderr: "server exited unexpectedly\n", ok: false) + unrelated = Report.new(stdout: "", stderr: "unknown command: server exited unexpectedly\n", ok: false) + assert_equal :possibly_sent, version.daemon_loss_delivery(disconnected) + assert_nil version.daemon_loss_delivery(unrelated) + end + def test_probe_failures_keep_their_class_and_phase_but_report_no_dispatch [[LibTmux::DeadlineExceeded, :read], [LibTmux::TransportError, :spawn], [LibTmux::TransportError, :transport]].each do |kind, phase| error = assert_raises(kind, phase.to_s) do From ac7e40d25f967fce02a5ebee4fed2b616bbf0f63 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 5 Dec 2026 05:08:44 -0600 Subject: [PATCH 2/2] Changelog(docs): Note owned terminal programs why: Readers need to know which tmux release supports the new Core and Async program owner. what: Record launch, input, and completion in the unreleased changelog. --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b781e153..0f00f95f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -78,6 +78,9 @@ at one version, so a release has a section in each changelog. - Core and Async can query the features and workarounds of the bound tmux daemon. MCP exposes the same support decisions alongside the tools the server permits. (#128) +- Core and Async can run a terminal program on a private or existing tmux + server, send input, and read its exit status and bounded screen. Program + management requires tmux 3.7 or newer. (#166) - The unit tests load tmuxp's example catalog, with its license, through `LibTmux::Workspace.load`. The files the loader reads show on the docs site as workspace presets; each file it refuses fails with the message the test