From 46c0973869a3a7886df8b1bd12a670c5d02bc7da Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Mon, 30 Nov 2026 19:48:37 -0600 Subject: [PATCH] program(feat): Preview owned terminal programs why: A tmux command status does not report how a terminal program finished or what it last displayed. what: - Share a dedicated program owner across core and Async. - Retain bounded screen text and observe exit status or signal. - Require tmux 3.7 for the program preview and verify refusal. --- README.md | 7 + capabilities.json | 15 ++ docs/reference/api.md | 32 +++- docs/reference/behavior.md | 64 ++++++++ docs/reference/contracts.json | 21 +++ examples/api/owned_program.rb | 25 +++ examples/manifest.json | 17 ++ gems/libtmux-async/CHANGELOG.md | 3 + gems/libtmux-async/lib/libtmux/async.rb | 10 ++ gems/libtmux-async/sig/libtmux-async.rbs | 4 + gems/libtmux/CHANGELOG.md | 3 + gems/libtmux/lib/libtmux.rb | 1 + gems/libtmux/lib/libtmux/capabilities.rb | 5 + gems/libtmux/lib/libtmux/program.rb | 193 ++++++++++++++++++++++ gems/libtmux/libtmux.gemspec | 2 + gems/libtmux/sig/program.rbs | 25 +++ scripts/types | 2 +- test/integration/program_test.rb | 195 +++++++++++++++++++++++ test/types/consumer.rb | 17 ++ 19 files changed, 639 insertions(+), 2 deletions(-) create mode 100644 examples/api/owned_program.rb create mode 100644 gems/libtmux/lib/libtmux/program.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 704e3d9f..040f2828 100644 --- a/README.md +++ b/README.md @@ -359,6 +359,12 @@ sessions after client close: 1 More: [ownership and errors][doc-ownership]. +## Run a program and read its exit status + +The core and Async preview APIs use tmux 3.7 or newer to run a program on a +dedicated 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: @@ -582,6 +588,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 2416e40c..a2d13b12 100644 --- a/capabilities.json +++ b/capabilities.json @@ -5,6 +5,21 @@ "minimum": "3.3a" }, "capabilities": [ + { + "id": "owned-terminal-program", + "name": "Owned terminal program", + "summary": "Wait for process exit and retain the drained terminal screen on a private daemon.", + "since": "3.7", + "handling": "refuse", + "error": "LibTmux::UnsupportedFeatureError", + "apis": [ + "LibTmux.start_program", + "LibTmux.run_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 84f6eb97..514ca26e 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#L10) | `::LibTmux::Program::Result` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [.start_program](../../gems/libtmux/lib/libtmux/program.rb#L5) | `::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 @@ -637,6 +646,27 @@ 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 | +| --- | --- | --- | +| [#close](../../gems/libtmux/lib/libtmux/program.rb#L171) | `nil` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#inspect](../../gems/libtmux/lib/libtmux/program.rb#L181) | `::String` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#resize](../../gems/libtmux/lib/libtmux/program.rb#L164) | `::LibTmux::CommandResult` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#screen](../../gems/libtmux/lib/libtmux/program.rb#L144) | `::String` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#send_keys](../../gems/libtmux/lib/libtmux/program.rb#L158) | `::LibTmux::CommandResult` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#send_text](../../gems/libtmux/lib/libtmux/program.rb#L152) | `::LibTmux::CommandResult` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#wait](../../gems/libtmux/lib/libtmux/program.rb#L120) | `::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#L19) | `::Integer?` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#inspect](../../gems/libtmux/lib/libtmux/program.rb#L27) | `::String` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#screen](../../gems/libtmux/lib/libtmux/program.rb#L19) | `::String` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#signal](../../gems/libtmux/lib/libtmux/program.rb#L19) | `::Integer?` | [Owned terminal programs](behavior.md#owned-terminal-programs) | + ## LibTmux::ProtocolError | Method | Declared return | Contract | diff --git a/docs/reference/behavior.md b/docs/reference/behavior.md index 2cd98c3c..94301105 100644 --- a/docs/reference/behavior.md +++ b/docs/reference/behavior.md @@ -1021,3 +1021,67 @@ 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` and `LibTmux::Async.start_program` run literal argv +in a terminal on a dedicated server. The preview checks the daemon's tmux 3.7 +floor before launching the application. Each launch accepts a working +directory, environment overrides, and dimensions. Geometry defaults to +80×24 and is limited to 256×100 cells. +The methods return a program owner or yield it to a block and close it +when the block ends. `run_program` launches, waits, and closes, then +returns the completion result. The `timeout:` value applies separately to +daemon startup, terminal setup, and the wait in `run_program`. Each phase can +be cancelled through the supplied `cancel:` token. + +`Program#wait` observes the terminal process and returns a frozen result +with an exit code or a signal number once tmux's process-exit hook runs. +Successful waits share the result. A cancelled or expired waiter leaves the +program and other waiters running. The Async owner uses the current Async task +and bounded scope dispatch. Dedicated daemon startup and retirement use +the core lifecycle. + +The screen joins stdout and stderr as rendered terminal text. It includes +the visible rows and up to 100 history rows. Captures retain the newest +64 KiB of UTF-8 text and omit incomplete or invalid code units. tmux +may wrap lines, overwrite terminal cells, and add an exit banner. +Use `send_text` and `send_keys` to enter input and `resize` to change +dimensions. + +`Program#close` retires the Async scope and dedicated daemon in the +owner process. Block scopes also retire on exceptions. If an explicit close +fails, the same owner can retry it. A forcibly terminated Ruby owner may leave +a live daemon. An application that ignores SIGHUP or detaches can survive +terminal closure. Keep the daemon exclusive to this owner. External respawn +can replace the process observed by the program handle. + +Run a sample migration command and report the failure from its retained +screen. + + +```ruby +require "libtmux" +require "rbconfig" + +command = [RbConfig.ruby, "-e", <<~'RUBY'] + warn "Migration stopped: café table missing" + exit 7 +RUBY + +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 +``` diff --git a/docs/reference/contracts.json b/docs/reference/contracts.json index 4f28e0cf..fa0e1c32 100644 --- a/docs/reference/contracts.json +++ b/docs/reference/contracts.json @@ -1,6 +1,27 @@ { "version": 1, "contracts": [ + { + "id": "owned-terminal-programs", + "title": "Owned terminal programs", + "methods": [ + "LibTmux.start_program", + "LibTmux.run_program", + "LibTmux::Async.start_program", + "LibTmux::Async.run_program", + "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#signal" + ] + }, { "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..944e0ec8 --- /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", <<~'RUBY'] + warn "Migration stopped: café table missing" + exit 7 + RUBY + + 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/manifest.json b/examples/manifest.json index a828a674..32903971 100644 --- a/examples/manifest.json +++ b/examples/manifest.json @@ -1,6 +1,17 @@ { "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": "quickstart", "path": "examples/quickstart.rb", @@ -365,6 +376,12 @@ "gems/libtmux/README.md" ], "snippets": [ + { + "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/CHANGELOG.md b/gems/libtmux-async/CHANGELOG.md index fb0245f3..b8efef65 100644 --- a/gems/libtmux-async/CHANGELOG.md +++ b/gems/libtmux-async/CHANGELOG.md @@ -11,6 +11,9 @@ in the [main changelog](../../CHANGELOG.md). ## 0.1.3 (unreleased) +- Preview `LibTmux::Async.start_program` and `run_program` with + scheduler-aware terminal input, capture, and cancellable waits. + ## 0.1.2 (2026-11-04) No entries for `libtmux-async`. diff --git a/gems/libtmux-async/lib/libtmux/async.rb b/gems/libtmux-async/lib/libtmux/async.rb index e4cd2532..ee56947b 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) } + Program.__send__(:start_with, adapter, argv, **options, &block) + end + + def self.run_program(argv, **options) + start_program(argv, **options) { |program| program.wait(**options.slice(:timeout, :cancel)) } + 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/sig/libtmux-async.rbs b/gems/libtmux-async/sig/libtmux-async.rbs index 81c15b70..96299955 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, ?executable: String, ?cwd: String?, ?environment: Hash[String, String], ?width: Integer, ?height: Integer, ?timeout: Numeric, ?cancel: untyped) -> LibTmux::Program + | [T] (Array[String], ?parent: untyped, ?executable: String, ?cwd: String?, ?environment: Hash[String, String], ?width: Integer, ?height: Integer, ?timeout: Numeric, ?cancel: untyped) { (LibTmux::Program) -> T } -> T + def self.run_program: (Array[String], ?parent: untyped, ?executable: String, ?cwd: String?, ?environment: Hash[String, String], ?width: Integer, ?height: 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/CHANGELOG.md b/gems/libtmux/CHANGELOG.md index 326eee67..631c8f4a 100644 --- a/gems/libtmux/CHANGELOG.md +++ b/gems/libtmux/CHANGELOG.md @@ -11,6 +11,9 @@ in the [main changelog](../../CHANGELOG.md). ## 0.1.3 (unreleased) +- Preview `LibTmux.start_program` and `LibTmux.run_program` for literal argv + in a private tmux terminal with a typed exit and bounded final screen. + ## 0.1.2 (2026-11-04) No entries for `libtmux`. diff --git a/gems/libtmux/lib/libtmux.rb b/gems/libtmux/lib/libtmux.rb index 0ff4ce3a..d4ec88c1 100644 --- a/gems/libtmux/lib/libtmux.rb +++ b/gems/libtmux/lib/libtmux.rb @@ -17,3 +17,4 @@ require "libtmux/group" require "libtmux/owned" require "libtmux/terminal" +require "libtmux/program" diff --git a/gems/libtmux/lib/libtmux/capabilities.rb b/gems/libtmux/lib/libtmux/capabilities.rb index 9fc9729b..028cc512 100644 --- a/gems/libtmux/lib/libtmux/capabilities.rb +++ b/gems/libtmux/lib/libtmux/capabilities.rb @@ -79,6 +79,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: "Wait for process exit and retain the drained terminal screen on a private daemon.", + apis: ["LibTmux.start_program", "LibTmux.run_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/program.rb b/gems/libtmux/lib/libtmux/program.rb new file mode 100644 index 00000000..8242654f --- /dev/null +++ b/gems/libtmux/lib/libtmux/program.rb @@ -0,0 +1,193 @@ +# frozen_string_literal: true + +module LibTmux + # Start literal argv in a terminal on a dedicated private tmux server. + def self.start_program(argv, **options, &block) + Program.__send__(:start_with, nil, argv, **options, &block) + end + + # Start a private program, await completion, and retire the server. + def self.run_program(argv, **options) + start_program(argv, **options) { |program| program.wait(**options.slice(:timeout, :cancel)) } + end + + # A terminal program and the dedicated tmux server that owns its pane. + # Use the block form for automatic cleanup, or explicitly close the owner. + class Program + # A completed process and the retained terminal screen, including history. + class Result + attr_reader :exit_status, :signal, :screen + + def initialize(exit_status, signal, screen) + @exit_status, @signal, @screen = exit_status, signal, screen + freeze + end + private_class_method :new + + 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 + COMPLETION = '#{@libtmux-program-done}:#{pane_dead_status}:#{pane_dead_signal}' + private_constant :HISTORY_LINES, :SCREEN_BYTES, :MAX_WIDTH, :MAX_HEIGHT, :COMPLETION + + def self.start_with(adapter, argv, executable: "tmux", cwd: nil, environment: {}, width: 80, height: 24, + timeout: 5.0, cancel: nil) + validate_size(width, height) + owned = Server.start(executable: executable, timeout: timeout, cancel: cancel) + capability = Internal::Capabilities.capability("owned-terminal-program") + unless capability.available?(owned.__send__(:tmux_release)) + raise UnsupportedFeatureError.new("owned terminal programs require tmux #{capability.since} or newer", + phase: :admission, delivery: :not_sent) + end + + scope = adapter&.call(owned) + server = scope ? scope.server : owned + budget = server.__send__(:operation_budget, timeout, cancel) + + server.options(scope: :window).set("remain-on-exit", true, **budget.options) + server.options(scope: :session).set("history-limit", HISTORY_LINES, **budget.options) + server.hooks.set("pane-died", command: "set-option -p @libtmux-program-done 1", **budget.options) + receipt = server.new_session(name: "program", command: argv, width: width, height: height, + cwd: cwd, environment: environment, receipt: true, **budget.options) + program = new(owned, scope, receipt.pane, receipt.window) + return program unless block_given? + + yield program + rescue Exception => failure + raise + ensure + if owned && (!program || 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, pane, window) + @owned, @scope, @pane, @window = owned, scope, pane, window + @result_lock = Mutex.new + end + private_class_method :new + + # Ordinary exits have an integer exit_status. Signalled exits have a + # signal number. The terminal's final UTF-8 text is limited to 64 KiB. + # Cancelling this call leaves the process and other waiters running. + def wait(timeout: 5.0, cancel: nil) + ensure_open + budget = @pane.server.__send__(:operation_budget, timeout, cancel) + loop do + options = budget.options + result = @result_lock.synchronize { @result } + return result if result + + marker, status, signal = @pane.display(COMPLETION, **options).text.chomp.split(":", -1) + if marker == "1" + status, signal = [status, signal].map { |value| Integer(value, 10) unless value.empty? } + unless status.nil? != signal.nil? + raise ProtocolError.new("tmux did not report an exit status or signal", phase: :decode) + end + + result = Result.__send__(:new, status, signal, screen(**budget.options)) + return @result_lock.synchronize { @result ||= result } + end + + sleep([budget.options.fetch(:timeout), 0.01].min) + end + end + + # Capture screen and bounded scrollback as UTF-8 text. + def screen(timeout: 5.0, cancel: nil) + ensure_open + text = @pane.capture(start: -HISTORY_LINES, timeout: timeout, cancel: cancel).stdout + offset = [text.bytesize - SCREEN_BYTES, 0].max + text.byteslice(offset..).force_encoding(Encoding::UTF_8).scrub("").freeze + end + + # Type literal text into the terminal. + def send_text(text, **options) + ensure_open + @pane.send_text(text, **options) + end + + # Send tmux key names, for example Enter. + def send_keys(*keys, **options) + ensure_open + @pane.send_keys(*keys, **options) + end + + # Resize the terminal in cells. + def resize(width:, height:, **options) + ensure_open + self.class.__send__(:validate_size, width, height) + @window.resize(width: width, height: height, **options) + end + + # Retire the dedicated server and its terminal resources. + def close + return nil if @closed + + # Reject foreign Async callers before attempting daemon retirement. + @scope&.__send__(:ensure_owner) + self.class.__send__(:close_owned, @scope, @owned) + @closed = true + nil + end + + def inspect + "#<#{self.class} #{@closed ? 'closed' : 'open'}>" + end + + private + + def ensure_open + raise ClosedError.new("program is closed", phase: :admission) if @closed + + @pane.server.__send__(:with_bound_endpoint) { nil } + end + end +end diff --git a/gems/libtmux/libtmux.gemspec b/gems/libtmux/libtmux.gemspec index 5785363d..5f71360b 100644 --- a/gems/libtmux/libtmux.gemspec +++ b/gems/libtmux/libtmux.gemspec @@ -44,6 +44,7 @@ Gem::Specification.new do |spec| lib/libtmux/owned.rb lib/libtmux/socket_readiness.rb lib/libtmux/terminal.rb + lib/libtmux/program.rb lib/libtmux/criteria.rb lib/libtmux/process_wait.rb lib/libtmux/native_guard.rb @@ -55,6 +56,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..bfc9362a --- /dev/null +++ b/gems/libtmux/sig/program.rbs @@ -0,0 +1,25 @@ +module LibTmux + def self.start_program: (Array[String], ?executable: String, ?cwd: String?, ?environment: Hash[String, String], ?width: Integer, ?height: Integer, ?timeout: Numeric, ?cancel: untyped) -> Program + | [T] (Array[String], ?executable: String, ?cwd: String?, ?environment: Hash[String, String], ?width: Integer, ?height: Integer, ?timeout: Numeric, ?cancel: untyped) { (Program) -> T } -> T + def self.run_program: (Array[String], ?executable: String, ?cwd: String?, ?environment: Hash[String, String], ?width: Integer, ?height: Integer, ?timeout: Numeric, ?cancel: untyped) -> Program::Result + + class Program + private def self.new: (*untyped, **untyped) -> instance + + class Result + private def self.new: (*untyped, **untyped) -> instance + attr_reader exit_status: Integer? + attr_reader signal: Integer? + attr_reader screen: String + def inspect: () -> String + end + + def wait: (?timeout: Numeric, ?cancel: untyped) -> Result + 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 4b203911..5e9e60e1 100755 --- a/scripts/types +++ b/scripts/types @@ -16,7 +16,7 @@ class PublicAPI @specs = PACKAGES.map { |name| Gem::Specification.find_by_name(name) } @specs.each { |spec| loader.add(path: Pathname(File.join(spec.full_gem_path, "sig"))) } @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..a8904e19 --- /dev/null +++ b/test/integration/program_test.rb @@ -0,0 +1,195 @@ +# frozen_string_literal: true + +require_relative "../test_helper" +require "libtmux/async" +require "rbconfig" +require "open3" + +class ProgramTest < Minitest::Test + def setup + return if %w[test_adapter_is_private_to_the_factories test_older_tmux_refuses_before_launch].include?(name) + + skip "owned terminal programs require tmux 3.7" unless supported? + end + + def test_older_tmux_refuses_before_launch + skip "requires tmux before 3.7" if supported? + + Dir.mktmpdir("libtmux-ruby-program-") do |directory| + marker = File.join(directory, "launched") + argv = [RbConfig.ruby, "-e", 'File.write(ARGV.fetch(0), "started")', marker] + error = assert_raises(LibTmux::UnsupportedFeatureError) do + LibTmux.start_program(argv, executable: executable) { flunk "yielded a program owner" } + end + assert_equal :admission, error.phase + assert_equal :not_sent, error.delivery + + Async do + assert_raises(LibTmux::UnsupportedFeatureError) do + LibTmux::Async.start_program(argv, executable: executable) { flunk "yielded a program owner" } + end + end.wait + refute File.exist?(marker) + end + 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_outer_exception_does_not_hide_cleanup_failure + 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 + 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 + 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| + 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 + app = %q{trap '' HUP; printf 'closed café\n'; exec 0<&- 1>&- 2>&-; /bin/sleep 0.2; exit 7} + result = LibTmux.run_program(["/bin/sh", "-c", app], executable: executable) + assert_equal 7, result.exit_status + assert_includes result.screen, "closed café" + end + + def test_final_screen_is_a_bounded_valid_utf8_tail + 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_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_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_cwd_and_environment_are_passed_to_the_terminal + 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 + assert_raises LibTmux::DeadlineExceeded do + LibTmux.run_program(["/bin/cat"], executable: executable, timeout: 0.8) + end + end + + private + + 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 84164d6c..77352882 100644 --- a/test/types/consumer.rb +++ b/test/types/consumer.rb @@ -68,8 +68,20 @@ def verify_rejects_wrong_return(value = Object.new) consumer = SignatureConsumer.new LibTmux::Server.start(executable: ENV.fetch("LIBTMUX_TEST_TMUX", "tmux")) do |server| + programs = LibTmux::Internal::Capabilities.capability("owned-terminal-program") + supports_programs = programs.available?(LibTmux::Internal::TmuxVersion.parse(server.tmux_version)) case package when "libtmux" + if supports_programs + executable = ENV.fetch("LIBTMUX_TEST_TMUX", "tmux") + consumer.call("singleton(::LibTmux)", LibTmux, :start_program, ["/bin/true"], + executable: executable, expected: ":checked") do |program| + result = consumer.call("::LibTmux::Program", program, :wait, expected: "::LibTmux::Program::Result") + consumer.call("::LibTmux::Program::Result", result, :exit_status, expected: "Integer") + consumer.call("::LibTmux::Program::Result", result, :screen, expected: "String") + :checked + end + 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, @@ -137,6 +149,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, executable: ENV.fetch("LIBTMUX_TEST_TMUX", "tmux"), + expected: "::LibTmux::Program::Result") + end consumer.call("singleton(::LibTmux::Async)", LibTmux::Async, :open, parent: parent, server: server, expected: ":checked") do |scope| facade = consumer.call("::LibTmux::Async::Scope", scope, :server, expected: "::LibTmux::Async::Server") consumer.call("::LibTmux::Async::Scope", scope, :diagnostics, expected: "::LibTmux::Async::scope_diagnostics")